Typescript
使用 Web3.js 的 SPL 代币

使用 Web3.js 的 SPL 代币

批准和撤销指令

批准允许代理人代表账户所有者转移特定数量的代币。这使得程序化的代币转移成为可能,而无需授予完整的账户控制权。

我们设置一个“批准”的金额,代理人只能转移不超过该金额的代币

撤销会移除当前代理人对账户的权限,将完整的控制权返回给账户所有者。

立即取消任何现有的代理权限,且只有账户所有者可以撤销代理(代理人本身无法撤销)

在我们可以代理或撤销任何代币账户之前,我们需要已经完成以下操作:

  • 初始化一个 Mint 账户
  • 初始化一个 Token 账户或 Associated Token 账户,我们将对其进行控制

我们铸造的代币数量是根据小数位数“标准化”的。这意味着如果我们想铸造一个有 6 位小数的 1 个代币,我们实际上需要将金额设置为 1e6

Raw Instruction

仅使用“原始”指令而不进行任何抽象时,批准代币的操作如下:

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

仅使用“原始”指令而不进行任何抽象时,撤销代币的操作如下:

// Revoke the delegate of an ATA 
const revokeInstruction = createRevokeInstruction(
    tokenAccount // account
    keypair.publickey // owner
);
 
const transaction = new Transaction().add(revokeInstruction);
 
const signature = await sendAndConfirmTransaction(connection, transaction, [keypair]);
 
console.log(`Token account delegate revoked! Check out your TX here: https://explorer.solana.com/tx/${signature}?cluster=devnet`);

Abstracted Instruction

以下是通过 approve() 指令抽象后的操作:

const tokenAccount = Keypair.generate();
 
const ata = await getOrCreateAssociatedTokenAccount(
    connection,
    keypair,
    mint,
    tokenAccount.publicKey
);
 
console.log(`This is your ATA: ${ata.address}!`)
  
let tx = await approve(
    connection,
    keypair,
    ata.address, // token Account
    delegate-publicKey, // delegate
    keypair.publicKey, // owner
    1e6, // amount
);
 
console.log(`Succesfully Delegated!. Transaction Here: https://explorer.solana.com/tx/${tx}?cluster=devnet`)

以下是通过 revoke() 指令抽象后的操作:

let tx = await revoke(
    connection,
    keypair,
    ata.address, // token Account
    keypair.publicKey, // owner
);
 
console.log(`Succesfully Revoked Delegate!. Transaction Here: https://explorer.solana.com/tx/${tx}?cluster=devnet`)
Blueshift © 2025Commit: fd080b2