如何使用web3.js实现Solana钱包向任意地址的NFT转账?
Solana NFT Transfer with web3.js (Step-by-Step Guide)
Hey, since you already have experience transferring standard SPL tokens on Solana with web3.js, you're halfway there! NFTs on Solana are just a specific type of SPL token with a supply of exactly 1 and 0 decimals. The core workflow is similar, but there are a few key details to nail down. Let's walk through how to implement this.
Prerequisites
First, make sure you have the necessary dependencies installed (you probably already have these for token transfers, but just in case):
npm install @solana/web3.js @solana/spl-token
Step-by-Step Code Implementation
Here's a complete, annotated example that covers everything from setup to sending the transaction:
const { Connection, Keypair, PublicKey, Transaction } = require('@solana/web3.js'); const { getOrCreateAssociatedTokenAccount, transferChecked } = require('@solana/spl-token'); async function transferNFT() { // 1. Connect to the Solana cluster (use devnet/testnet for testing!) const connection = new Connection('https://api.devnet.solana.com'); // 2. Initialize your sender wallet (NEVER hardcode private keys in production!) // For production, use a wallet adapter like Phantom instead of Keypair.fromSecretKey const senderWallet = Keypair.fromSecretKey(Uint8Array.from([/* Your private key array here */])); // 3. Define recipient and NFT mint details const recipientPublicKey = new PublicKey('RECIPIENT_WALLET_ADDRESS'); const nftMintAddress = new PublicKey('YOUR_NFT_MINT_ADDRESS'); // Unique to your NFT try { // 4. Get or create associated token accounts for the NFT // Sender's token account (they must already hold the NFT here) const senderTokenAccount = await getOrCreateAssociatedTokenAccount( connection, senderWallet, nftMintAddress, senderWallet.publicKey ); // Recipient's token account (creates it if they don't already have one for this NFT) const recipientTokenAccount = await getOrCreateAssociatedTokenAccount( connection, senderWallet, // Sender pays the fee to create the recipient's account nftMintAddress, recipientPublicKey ); // 5. Build the transfer instruction // NFTs have 0 decimals, so we transfer exactly 1 token const transferIx = transferChecked( connection, senderWallet, senderTokenAccount.address, nftMintAddress, recipientTokenAccount.address, senderWallet.publicKey, 1, // Amount: always 1 for NFTs 0 // Decimals: NFTs use 0 decimals ); // 6. Assemble and send the transaction const transaction = new Transaction().add(transferIx); // Set recent blockhash to prevent transaction expiration const latestBlockhash = await connection.getLatestBlockhash(); transaction.recentBlockhash = latestBlockhash.blockhash; transaction.feePayer = senderWallet.publicKey; // Sign the transaction with the sender's wallet transaction.sign(senderWallet); // Send and confirm the transaction const signature = await connection.sendRawTransaction(transaction.serialize()); await connection.confirmTransaction({ signature, blockhash: latestBlockhash.blockhash, lastValidBlockHeight: latestBlockhash.lastValidBlockHeight }); console.log(`NFT transferred successfully! Transaction signature: ${signature}`); } catch (error) { console.error('Error transferring NFT:', error); } } // Run the function transferNFT();
Key Notes to Remember
- NFT Mint Address: This is the unique identifier for your NFT—you can find this on platforms like Magic Eden, Solscan, or in your NFT's metadata.
transferCheckedvstransfer: We usetransferCheckedhere because it validates the token's mint and decimal count, which is critical for ensuring you're transferring the correct NFT (instead of a random token).- Associated Token Accounts: Each wallet can have one associated token account per mint. If the recipient doesn't have one for your NFT,
getOrCreateAssociatedTokenAccountwill create it automatically, with the sender covering the small SOL fee. - Wallet Security: Never hardcode private keys in production. For frontend apps, use a wallet adapter (like Phantom) to handle signing transactions securely.
Troubleshooting Tips
- If you get an "Insufficient funds" error: Make sure the sender has enough SOL to cover transaction fees and the cost of creating the recipient's token account (if needed).
- If the transaction fails with "Invalid token account": Double-check that the sender's token account actually holds the NFT (you can verify this on Solscan).
- For testnet: Use devnet SOL (you can get some from the Solana faucet) and make sure your NFT is minted on devnet.
内容的提问来源于stack exchange,提问作者VovaProg
相关产品推荐
相关产品推荐

