如何使用spl令牌0.1.8传输令牌



我有这样的代码,它使用spl令牌0.2.x传输令牌。

如何在0.1.8中使用相同的代码?根据我对文档的理解,两者之间没有突破性的变化,但旧版本使用了Token类,但我不确定如何为getOrCreateAssociatedTokenAccounttransfer函数调用它。

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);  
}

这就是我如何传递从十六进制字符串加载的fromWalletKeyPair

const fromWallet = Keypair.fromSecretKey(Uint8Array.from(Buffer.from(private_key, 'hex')));

实际上,版本2确实有中断更改(因此是版本的主要变化(,在这种情况下,它删除了Token类,以支持您在示例中看到的那些函数。

这些文件很。。。糟糕,但如果你在一年前查看Github项目,你可以看到这个函数是如何一点一点地迁移的。

getOrCreateAssociatedTokenAccounttransfer需要以下一种方式使用类Token:


const token = new Token(connection, toWalletPublicKey, mint_key, fromWallet.publicKey) // Not sure about the last argument as it is the Signer
/**
* Retrieve the associated account or create one if not found.
*
* This account may then be used as a `transfer()` or `approve()` destination
*
* @param owner User account that will own the new account
* @return The new associated account
*/
const fromTokenAccount = token.getOrCreateAssociatedAccountInfo(fromWallet.publicKey)
const toTokenAccount = token.getOrCreateAssociatedAccountInfo(toWalletPublicKey)
/**
* Transfer parameters
* @param source Source account
* @param destination Destination account
* @param owner Owner of the source account
* @param multiSigners Signing accounts if `owner` is a multiSig
* @param amount Number of tokens to transfer
*/
token.transfer(fromTokenAccount, toTokenAccount, fromWallet, [], 1)

也部分回答了这一点

最新更新