Typescript
使用Web3.js的SPL代幣

使用Web3.js的SPL代幣

Mint To 指令

創建新代幣並將其存入指定帳戶。只有鑄幣權限持有人才能執行此操作。

在我們鑄造任何代幣之前,我們需要已經擁有:

  • 已初始化的Mint帳戶,並且我們持有mintAuthority

  • 已初始化的Token帳戶或Associated Token帳戶,我們將把代幣鑄造到這些帳戶中

我們鑄造的代幣數量是根據小數位數進行「標準化」的。這意味著,如果我們想鑄造一個有 6 位小數的代幣,我們實際上需要輸入1e6作為數量

原始指令

僅使用「原始」指令而不進行任何抽象,這是鑄造代幣的方式:

ts
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`);

抽象指令

這是使用mintTo()指令進行抽象後的相同指令的樣子:

ts
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`)
Blueshift © 2025Commit: e573eab