我想使用 web3.js 和 spl-token 将代币从一个钱包发送到另一个钱包。 要发送它,我必须创建一个名为 Token 的对象,Token() 构造函数的参数之一是付款人:web3。签名。
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-wallet 从用户的钱包中获取信息。 我知道 web3。签名者是从私钥创建的,出于安全目的,私钥无法从钱包中获取。
我实际上不知道如何处理钱包来完成交易。
非常感谢您的帮助,这是我的完整代码:
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);
}
}
我认为最简单的方法是创建一个提供程序并从那里获取签名者。
provider = new anchor.Provider(connection, wallet, anchor.Provider.defaultOptions());
然后您可以通过调用provider.send(tx)
发送交易,如果需要签名,它也将使用您的钱包签名。