Typescript
SPL Token với Web3.js

SPL Token với Web3.js

Instruction đúc token

Đúc một lượng token mới và gửi chúng vào một account được chỉ định. Chỉ mint authority mới có thể thực hiện thao tác này.

Trước khi chúng ta có thể đúc bất kỳ token nào, chúng ta sẽ cần phải có:

  • Account Mint đã khởi tạo mà chúng ta giữ mintAuthority
  • Account Token hoặc account Associated Token đã khởi tạo, nơi chúng ta sẽ đúc token đến

Số lượng token chúng ta đúc được "chuẩn hóa" với decimal. Điều này có nghĩa là nếu chúng ta muốn đúc 1 token có decimal là 6, chúng ta sẽ cần thực sự đặt 1e6 làm amount

Instruction thô

Bằng cách chỉ sử dụng instruction "thô" mà không có bất kỳ abstraction nào, đây là cách đúc token sẽ trông như thế nào:

const destination = Keypair.generate();
 
const tokenAccount = await getAssociatedTokenAddress(
    mint.publicKey,
    destination.publicKey,
);
 
// Create ATA creation instruction
const createAtaInstruction = createAssociatedTokenAccountIdempotentInstruction(
    keypair.publicKey, // payer
    tokenAccount, // associated token account address
    destination.publicKey, // owner
    mint.publicKey, // mint
);
 
// Mint tokens to ATA 
const mintToInstruction = createMintToInstruction(
    mint.publicKey, // mint
    tokenAccount, // destination
    keypair.publicKey, // mint authority
    1_000e6, // amount of tokens
);
 
const transaction = new Transaction().add(
    createAtaInstruction,
    mintToInstruction,
);
 
const signature = await sendAndConfirmTransaction(connection, transaction, [keypair]);
 
console.log(`Token accounts created and tokens minted! Check out your TX here: https://explorer.solana.com/tx/${signature}?cluster=devnet`);

Instruction được trừu tượng hóa

Đây là cách các instruction tương tự sẽ trông như thế nào được trừu tượng hóa với instruction mintTo():

const destination = Keypair.generate();
 
const ata = await getOrCreateAssociatedTokenAccount(
    connection,
    keypair,
    mint,
    destination.publicKey
);
 
console.log(`This is your ATA: ${ata.address}!`)
  
let tx = await mintTo(
    connection,
    keypair,
    mint,
    ata.address,
    keypair.publicKey,
    1e6,
);
 
console.log(`Succesfully Minted!. Transaction Here: https://explorer.solana.com/tx/${tx}?cluster=devnet`)
Nội dung
Xem mã nguồn
Blueshift © 2025Commit: f7a03c2