批准和撤销指令
批准允许代理人代表账户所有者转移特定数量的代币。这使得程序化的代币转移成为可能,而无需授予完整的账户控制权。
撤销会移除当前代理人对账户的权限,将完整的控制权返回给账户所有者。
在我们可以代理或撤销任何代币账户之前,我们需要已经完成以下操作:
- 初始化一个
Mint
账户 - 初始化一个
Token
账户或Associated Token
账户,我们将对其进行控制
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`)