How can I transfer an NFT using the built-in methods of @hashgraph/sdk for Hedera?

I’m struggling to transfer an NFT using the @hashgraph/sdk package for Hedera. The NFT is already linked to the seller’s account and shows up in the HashPack NFT section. But when I try to use the TransferTransaction method from @hashgraph/sdk@2.17.1, I get an error.

Here’s a simplified version of what I’m trying:

const moveNFT = async (nftId, from, to) => {
  const hederaClient = await setupClient();
  const tokenId = TokenId.fromString(nftId);
  const senderKey = PrivateKey.fromString(await fetchKey(from));
  const receiverKey = PrivateKey.fromString(await fetchKey(to));

  try {
    const transfer = await new TransferTransaction()
      .addNftTransfer(tokenId, 1, from, to)
      .addHbarTransfer(from, new Hbar(1))
      .addHbarTransfer(to, new Hbar(-1))
      .freezeWith(hederaClient)
      .sign(senderKey);

    const signedTransfer = await transfer.sign(receiverKey);
    const result = await signedTransfer.execute(hederaClient);
    const receipt = await result.getReceipt(hederaClient);
    
    console.log(`NFT transfer status: ${receipt.status}`);
    return receipt.status;
  } catch (err) {
    console.error('NFT transfer failed:', err);
  }
};

But I keep getting a ‘TOKEN_NOT_ASSOCIATED_TO_ACCOUNT’ error. Any ideas on what I’m doing wrong or how to fix this?

The error suggests that the receiving account has not been associated with the NFT’s token. To fix this, you should use the TokenAssociateTransaction to link the token to the recipient’s account and wait until the association is fully processed before attempting the transfer. It might help to remove the Hbar transfers if they are unnecessary for your use case. Finally, double-check that both the sender and receiver account IDs are correct and that you have the appropriate permissions and correct token ID in your transaction.

hey there! the issue might be that the receiver’s account isn’t associated with the NFT token yet. try running a TokenAssociateTransaction first to link the token to the recipient’s account. wait for it to process before attempting the transfer. also, double-check ur account IDs and permissions. good luck!