![](/img/trans.png)
[英]How to transfer NFT spl-token using phantom wallet and solana web3js
[英]How to transfer token using spl-token 0.1.8
我有这段代码使用 spl-token 0.2.x 传输令牌。
如何在 0.1.8 中使用相同的代码? 根据我对文档的理解,两者之间没有重大变化,但旧版本使用令牌 class,但我不知道如何为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);
}
实际上,版本 2 确实有重大更改(因此是版本的主要改进),在这种情况下,它删除了Token
class 以支持您在示例中看到的那些功能。
文档非常……糟糕,但是如果您在一年前查看 Github 项目,那么您可以看到 function 是如何一点一点迁移的。
getOrCreateAssociatedTokenAccount
和transfer
需要使用 class 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)
这也部分回答在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.