Jacky Gu

Solana开发笔记: Token2022 - 转账代币

01 Jan 2025 Share to

Token2022 - 转账代币

与旧版Token一样,转账不需要使用Anchor程序,只需要在前端调用系统转账指令即可。

创建转移代币指令

tests/token2022.ts中添加以下测试代码,完成转账,将100个代币从user1转给user2

  it("transfer tokens from user1 to user2", async () => {
    // Get the source and destination token accounts
    const sourceAta = await getAssociatedTokenAddress(mintAccount, user1Account.publicKey, false, TOKEN_2022_PROGRAM_ID);
    const destinationAta = await getAssociatedTokenAddress(mintAccount, user2Account.publicKey, false, TOKEN_2022_PROGRAM_ID);

    // Create destination ATA if it doesn't exist
    const tx = new anchor.web3.Transaction();
    try {
      await provider.connection.getTokenAccountBalance(destinationAta);
    } catch {
      // if token accont the destination doesn't exist, create it
      const ix = createAssociatedTokenAccountInstruction(
        user1Account.publicKey,
        destinationAta,
        user2Account.publicKey,
        mintAccount,
        TOKEN_2022_PROGRAM_ID,
      );
      tx.add(ix);
      // await provider.sendAndConfirm(tx, [user1Account]);
      console.log("Created destination ATA:", destinationAta.toBase58());
    }

    // Transfer amount: 100 tokens (considering 9 decimals)
    const amount = 100 * Math.pow(10, 9);

    // Create transfer instruction
    const transferIx = createTransferInstruction(
      sourceAta,
      destinationAta,
      user1Account.publicKey,
      amount,
      undefined,
      TOKEN_2022_PROGRAM_ID,
    );

    // Send transaction
    tx.add(transferIx);
    const signature = await provider.sendAndConfirm(tx, [user1Account]);
    console.log("Transfer transaction signature:", signature);

    // Log balances
    const sourceBalance = await provider.connection.getTokenAccountBalance(sourceAta);
    const destBalance = await provider.connection.getTokenAccountBalance(destinationAta);
    console.log("Source balance after transfer:", sourceBalance.value.uiAmount);
    console.log("Destination balance after transfer:", destBalance.value.uiAmount);
  })

上述代码中,先创建一个tx = new anchor.web3.Transaction();,然后往tx里添加必要的指令。

首先,检查目标账户的token account是否存在,如果不存在,则在tx中添加一个由createAssociatedTokenAccountInstruction生成的指令(instruction),用于创建目标账户的Token account。

然后,在tx中添加一个由createTransferInstruction生成的代币转移指令。

最后,使用await provider.sendAndConfirm(tx, [user1Account]);完成交易指令的发送。

执行后,查看交易hash,如下图所示: