如何将spl-token 0.2.x的代币转账代码适配到0.1.8版本?
问题描述
我有一段基于spl-token 0.2.x的代币转账代码,希望将其适配到0.1.8版本。据我查阅文档了解,两个版本间无破坏性变更,但0.1.8使用Token类,我不清楚如何通过它调用getOrCreateAssociatedTokenAccount和transfer函数。
原代码如下:
async function transferToken(endpoint: string, fromWallet: Keypair, address_to: string, token_id: string) { const connection = new Connection(endpoint); const toWalletPublicKey = new PublicKey(address_to); const mint_key = new PublicKey(token_id); // From const from = [connection, fromWallet, mint_key, fromWallet.publicKey]; const fromTokenAccount = await getOrCreateAssociatedTokenAccount(...from); // To const to = [connection, fromWallet, mint_key, toWalletPublicKey]; const toTokenAccount = await getOrCreateAssociatedTokenAccount(...to); // Transfer const transferParams = [connection, fromWallet, fromTokenAccount.address, toTokenAccount.address, fromWallet.publicKey, 1, []]; return await transfer(...transferParams); }
此外,我通过以下方式从十六进制字符串加载fromWallet Keypair:
const fromWallet = Keypair.fromSecretKey(Uint8Array.from(Buffer.from(private_key, 'hex')));
适配到spl-token 0.1.8的代码实现
spl-token 0.1.8版本中,getOrCreateAssociatedTokenAccount和transfer并非独立导出的函数,需要通过Token类实例调用。以下是修改后的完整适配代码:
import { Connection, Keypair, PublicKey } from '@solana/web3.js'; import { Token } from '@solana/spl-token'; async function transferToken(endpoint: string, fromWallet: Keypair, address_to: string, token_id: string) { const connection = new Connection(endpoint); const toWalletPublicKey = new PublicKey(address_to); const mintKey = new PublicKey(token_id); // 初始化Token类实例 const token = new Token(connection, mintKey, Token.defaultProgramId, fromWallet); // 获取或创建转出方的关联代币账户 const fromTokenAccount = await token.getOrCreateAssociatedAccountInfo(fromWallet.publicKey); // 获取或创建转入方的关联代币账户(由转出方支付创建费用) const toTokenAccount = await token.getOrCreateAssociatedAccountInfo(toWalletPublicKey); // 执行代币转账,注意参数顺序与0.2.x的差异 const signature = await token.transfer( fromTokenAccount.address, toTokenAccount.address, fromWallet.publicKey, [], 1 // 转账数量,需为代币最小单位(根据代币decimals调整) ); return signature; }
关键差异说明
- Token类实例化:0.1.8需先创建
Token实例,传入连接对象、代币mint地址、默认代币程序ID(Token.defaultProgramId)以及签名者钱包。 - 关联账户方法:0.1.8中对应方法为
getOrCreateAssociatedAccountInfo,只需传入目标钱包地址即可,无需重复传入连接和mint信息。 - 转账方法参数:
transfer方法参数顺序为:转出账户地址、转入账户地址、签名者公钥、多签签名数组(无则传空数组)、转账数量。 - Keypair加载:你原有的加载代码可直接沿用,无需修改:
const fromWallet = Keypair.fromSecretKey(Uint8Array.from(Buffer.from(private_key, 'hex')));
内容的提问来源于stack exchange,提问作者Berry Blue
相关产品推荐
相关产品推荐

