0

我想使用 web3.js 和 spl-token 从一个钱包向另一个钱包发送一个令牌。要发送它,我必须创建一个名为 Token 的对象,Token() 的构造函数的参数之一是 payer:web3.Signer。

    const mintPublicKey = new web3.PublicKey(this.props.nft.data.mint);  
    const mintToken = new Token(
      this.props.connection,
      mintPublicKey,
      TOKEN_PROGRAM_ID,
      //payer: web3.Signer,
    );

我使用@solana/wallet-adapter-wallets 从用户的钱包中获取信息。我知道 web3.Signer 是从私钥创建的,出于安全目的,无法从钱包中获取该私钥。

我实际上不知道如何处理钱包以完成交易。

非常感谢您的帮助,这是我的完整代码:

import * as web3 from "@solana/web3.js";
import { getPhantomWallet } from "@solana/wallet-adapter-wallets";
import { Token, TOKEN_PROGRAM_ID } from "@solana/spl-token";


async sendNFT() {
  const wallet = getPhantomWallet();
  const adapter = wallet.adapter();

  await adapter.connect();
  if (adapter.connected && adapter.publicKey != null)
  {
    const mintPublicKey = new web3.PublicKey(this.props.nft.data.mint);  
    const mintToken = new Token(
      this.props.connection,
      mintPublicKey,
      TOKEN_PROGRAM_ID,
      //payer: web3.Signer
    );
          
    const fromTokenAccount = await mintToken.getOrCreateAssociatedAccountInfo(
      adapter.publicKey
    );

    const destPublicKey = new web3.PublicKey("example");

    const associatedDestinationTokenAddr = await Token.getAssociatedTokenAddress(
      mintToken.associatedProgramId,
      mintToken.programId,
      mintPublicKey,
      destPublicKey
    );

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

    if (receiverAccount === null) {

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

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

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

    await this.props.connection.confirmTransaction(transactionSignature);
  }
}
4

0 回答 0