如何通过 '@solana/web3.js' 转移自定义代币。

20

我想使用Solana Web3.js发送已部署令牌而不是Sol,但我不知道如何操作。我已经花了很长时间寻找官方文档,但是找不到。如果您有任何相关信息,能否请告诉我?谢谢

3个回答

29

现有答案的问题在于它们只向您展示了如何首先创建一个新的自定义代币,然后执行从一个钱包到另一个钱包的转账。这里我将展示如何使用现有的自定义代币完成此操作。

import { Token, TOKEN_PROGRAM_ID } from "@solana/spl-token";
import { web3, Wallet } from "@project-serum/anchor";

async function transfer(tokenMintAddress: string, wallet: Wallet, to: string, connection: web3.Connection, amount: number) {
  const mintPublicKey = new web3.PublicKey(tokenMintAddress);    
  const mintToken = new Token(
    connection,
    mintPublicKey,
    TOKEN_PROGRAM_ID,
    wallet.payer // the wallet owner will pay to transfer and to create recipients associated token account if it does not yet exist.
  );
        
  const fromTokenAccount = await mintToken.getOrCreateAssociatedAccountInfo(
    wallet.publicKey
  );

  const destPublicKey = new web3.PublicKey(to);

  // Get the derived address of the destination wallet which will hold the custom token
  const associatedDestinationTokenAddr = await Token.getAssociatedTokenAddress(
    mintToken.associatedProgramId,
    mintToken.programId,
    mintPublicKey,
    destPublicKey
  );

  const receiverAccount = await connection.getAccountInfo(associatedDestinationTokenAddr);
        
  const instructions: web3.TransactionInstruction[] = [];  

  if (receiverAccount === null) {

    instructions.push(
      Token.createAssociatedTokenAccountInstruction(
        mintToken.associatedProgramId,
        mintToken.programId,
        mintPublicKey,
        associatedDestinationTokenAddr,
        destPublicKey,
        wallet.publicKey
      )
    )

  }
  
  instructions.push(
    Token.createTransferInstruction(
      TOKEN_PROGRAM_ID,
      fromTokenAccount.address,
      associatedDestinationTokenAddr,
      wallet.publicKey,
      [],
      amount
    )
  );

  const transaction = new web3.Transaction().add(...instructions);
  transaction.feePayer = wallet.publicKey;
  transaction.recentBlockhash = (await connection.getRecentBlockhash()).blockhash;
  
  const transactionSignature = await connection.sendRawTransaction(
    transaction.serialize(),
    { skipPreflight: true }
  );

  await connection.confirmTransaction(transactionSignature);
}

请注意,如果收件人没有自定义代币账户,我们会添加一条创建该账户的指令。


2
这段代码使用了:import { web3, Wallet } from "@project-serum/anchor"; 而不是 官方的Solana JS绑定 import * as web3 from "@solana/web3.js"; - MiKK
3
@solana/spl-token中不存在该令牌。 - Juan Enrique García Sancho
1
@JuanEnriqueGarcíaSancho 没错,我已经在下面的答案中进行了更新。 - Sanjay

18

从下面的导入中可以看出,您需要确保安装了Token程序的npm绑定。

import * as web3 from "@solana/web3.js";
import * as splToken from "@solana/spl-token";

// Address: 9vpsmXhZYMpvhCKiVoX5U8b1iKpfwJaFpPEEXF7hRm9N
const DEMO_WALLET_SECRET_KEY = new Uint8Array([
  37, 21, 197, 185, 105, 201, 212, 148, 164, 108, 251, 159, 174, 252, 43, 246,
  225, 156, 38, 203, 99, 42, 244, 73, 252, 143, 34, 239, 15, 222, 217, 91, 132,
  167, 105, 60, 17, 211, 120, 243, 197, 99, 113, 34, 76, 127, 190, 18, 91, 246,
  121, 93, 189, 55, 165, 129, 196, 104, 25, 157, 209, 168, 165, 149,
]);
(async () => {
  // Connect to cluster
  var connection = new web3.Connection(web3.clusterApiUrl("devnet"));
  // Construct wallet keypairs
  var fromWallet = web3.Keypair.fromSecretKey(DEMO_WALLET_SECRET_KEY);
  var toWallet = web3.Keypair.generate();
  // Construct my token class
  var myMint = new web3.PublicKey("My Mint Public Address");
  var myToken = new splToken.Token(
    connection,
    myMint,
    splToken.TOKEN_PROGRAM_ID,
    fromWallet
  );
  // Create associated token accounts for my token if they don't exist yet
  var fromTokenAccount = await myToken.getOrCreateAssociatedAccountInfo(
    fromWallet.publicKey
  )
  var toTokenAccount = await myToken.getOrCreateAssociatedAccountInfo(
    toWallet.publicKey
  )
  // Add token transfer instructions to transaction
  var transaction = new web3.Transaction()
    .add(
      splToken.Token.createTransferInstruction(
        splToken.TOKEN_PROGRAM_ID,
        fromTokenAccount.address,
        toTokenAccount.address,
        fromWallet.publicKey,
        [],
        0
      )
    );
  // Sign transaction, broadcast, and confirm
  var signature = await web3.sendAndConfirmTransaction(
    connection,
    transaction,
    [fromWallet]
  );
  console.log("SIGNATURE", signature);
  console.log("SUCCESS");
})();


8
似乎假设我们在代码中可以访问秘密密钥是一个错误的假设。 - Ozymandias
这段代码使用了:import * as web3 from "@solana/web3.js"; 这是官方Solana JS绑定 - MiKK
1
同意 @Ozymandias 的观点。我们如何通过使用Phantom钱包来转移Spl Token,而不是在代码中使用Keypair? - rainbowemoji
对于所有关心硬编码敏感数据的人 - 您可以将其保存到 .env 文件中,并通过 JS 的 env 变量功能进行访问...否则您是否计划复制粘贴片段并硬编码自己的秘钥? - MiKK
publicKey没有令牌地址时,此解决方案在await myToken.getOrCreateAssociatedAccountInfo(toWallet.publicKey)上失败。(如果已由Solana修复,请标记。) - MiKK
模块“@solana/spl-token”没有导出成员“Token”。 - Gervasius Twinklewinkleson

12

关于@Ozymandias答案的一个小更新,spl-token库中似乎有一些更改。

首先,Token不再存在。而一些函数,如Token.getAssociatedTokenAddress也被删除了。以下是更新后的代码:



import * as splToken from "@solana/spl-token";
import { web3, Wallet } from "@project-serum/anchor";

async function transfer(tokenMintAddress: string, wallet: Wallet, to: string, connection: web3.Connection, amount: number) {

  const mintPublicKey = new web3.PublicKey(tokenMintAddress);  
  const {TOKEN_PROGRAM_ID} = splToken

  const fromTokenAccount = await splToken.getOrCreateAssociatedTokenAccount(
    connection,
    wallet.payer,
    mintPublicKey,
    wallet.publicKey
  );

  const destPublicKey = new web3.PublicKey(to);

  // Get the derived address of the destination wallet which will hold the custom token
  const associatedDestinationTokenAddr = await splToken.getOrCreateAssociatedTokenAccount(
    connection,
    wallet.payer,
    mintPublicKey,
    destPublicKey
  );
  

  const receiverAccount = await connection.getAccountInfo(associatedDestinationTokenAddr.address);
        
  const instructions: web3.TransactionInstruction[] = [];  

  
  instructions.push(
    splToken.createTransferInstruction(
      fromTokenAccount.address,
      associatedDestinationTokenAddr.address,
      wallet.publicKey,
      amount,
      [],
      TOKEN_PROGRAM_ID
    )
  );

  const transaction = new web3.Transaction().add(...instructions);
  transaction.feePayer = wallet.publicKey;
  transaction.recentBlockhash = (await connection.getRecentBlockhash()).blockhash;
  
  const transactionSignature = await connection.sendRawTransaction(
    transaction.serialize(),
    { skipPreflight: true }
  );

  await connection.confirmTransaction(transactionSignature);
}

2
请查看官方Solana文档此处链接 - MiKK
1
TOKEN_PROGRAM_ID 的含义是什么?你如何使用 splToken 库来分配它?难道你不需要手动设置吗? - Suat Karabacak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接