NFT Transfer Using Private Key with Web3.js or Ethers.js

I’m working on an app where I need to send NFTs from my wallet to users. I used to do this with Moralis but now I want to switch to Web3.js or Ethers.js.

Here’s what I’m trying to achieve with a new approach:

async function sendTokenToRecipient(contractAddr, tokenNumber) {
  const recipientAddr = await getCurrentUserAddress();
  
  // Setup web3 connection with my private key
  const provider = new ethers.providers.JsonRpcProvider();
  const myWallet = new ethers.Wallet("my-private-key-here", provider);
  
  const nftContract = new ethers.Contract(
    contractAddr, 
    abi, 
    myWallet
  );
  
  const tx = await nftContract.transferFrom(
    myWallet.address,
    recipientAddr, 
    tokenNumber
  );
  
  return await tx.wait();
}

Is this the right way to transfer ERC721 tokens using my own private key? I want to make sure the transaction comes from my account and goes to the logged-in user’s address. Any examples or better methods would be helpful.

Oh interesting! I’ve been thinking about ditching Moralis too. Quick question - how are you handling private key storage in production? Hardcoding seems sketchy for a live app. Environment variables or some key management service?

Also curious about your getCurrentUserAddress() function - does that pull from MetaMask or do you store user addresses in your database? Trying to understand the user flow. Do they still connect their wallet for the recipient address or are you doing something different?

One more thing - what about error handling when transfers fail? Like non-existent tokens or insufficient gas? Would love to see how you’re tackling those edge cases.

looks good but ur missing the RPC provider URL! ur new ethers.providers.JsonRpcProvider() is empty - throw in an Infura or Alchemy endpoint. also make sure ur ABI actually has transferFrom or you’ll hit method errors.

Your approach looks solid, but there are a few things to watch out for. First, check if you need to call approve or setApprovalForAll first - some NFT contracts require explicit approval even when transferring from your own wallet. Additionally, consider adding gas estimation to avoid failed transactions during network congestion. I usually use await nftContract.estimateGas.transferFrom(myWallet.address, recipientAddr, tokenNumber) before the actual transaction to catch any issues early. Lastly, use safeTransferFrom instead of transferFrom if the recipient might be a contract, as it includes extra safety checks. Overall, your code structure looks good for programmatic NFT transfers.