How to transfer Metaplex's pNFT on Solana using JS
If you are a Solana dev, it could save you a lot of time :)
Hey, it’s Mike again.
I want to share my latest knowledge about working with pNFT on Solana. I migrated Danger Valley Ducks and Birds Aren’t Real collections to pNFT a few days ago, and I had to update ArtRaffle and Quackpot to work with pNFT so we can airdrop NFT prizes automatically.
I thought it should work out of the box, but no. We have to use not the SPL Token Solana program but the Metaplex Token Metadata program. And it has a bit different interface.
As there are no docs yet, that was a glass chewing to find a way to transfer Programmable NFT from one wallet to another using JavaScript. I tried to write low-level code using the needed program. But it turned out to be much easier than I expected. Hopefully, I can save some of your time if you need to transfer Programmable NFT from one Solana wallet to another.
So, all you need is the Metaplex JS library.
static async sendNft(mintPubKey: PublicKey, fromPubKey: PublicKey, toPubKey: PublicKey, feePayerPubKey: PublicKey): Promise<Transaction | undefined>{
const feePayer: Signer = {
publicKey: fromPubKey,
signTransaction: async (tx) => tx,
signMessage: async (msg) => msg,
signAllTransactions: async (txs) => txs,
};
const web3Conn = newConnection();
const metaplex = new Metaplex(web3Conn);
metaplex.use(walletAdapterIdentity({
publicKey: feePayerPubKey,
signTransaction: async (tx) => tx,
}));
const nft = await metaplex.nfts().findByMint({mintAddress: mintPubKey});
const txBuilder = metaplex.nfts().builders().transfer({
nftOrSft: nft,
fromOwner: fromPubKey,
toOwner: toPubKey,
amount: token(1),
authority: feePayer,
});
const blockhash = await web3Conn.getLatestBlockhash();
return txBuilder.toTransaction(blockhash);
}
And that’s all! You only need to sign the tx and send it.
This code works both for NFT and pNFT, so you don’t need to detect if it’s programmable NFT or not.
If you need, you can only get instructions from this tx and paste them into your system.
Make sure you have the latest version of the Metaplex JS SDK. My current version is:
"@metaplex-foundation/js": "^0.18.3",
Huge thanks to Metaplex and their Discord community!
Enjoy!