What's the best way to programmatically transfer an NFT using JavaScript libraries?

I’m working on a project where I need to send an NFT from my account to a user’s account automatically. I tried using Moralis before, but it didn’t work out. The error message was confusing and mentioned something about contract signers.

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

async function sendNFT(recipientAddress, tokenId) {
  const myPrivateKey = 'abcdefghijklmnop123456789';
  const nftContractAddress = '0x1234567890abcdef';
  
  // Set up connection to blockchain
  // Create transaction to transfer NFT
  // Sign and send the transaction
  
  return transactionResult;
}

Can anyone help me figure out how to do this using Web3.js or ethers.js? I’m not sure how to set up the connection and create the right kind of transaction. Thanks!

hey there! i’ve used ethers.js for this before. you’ll need to connect to the network, create a contract instance, and call the transferFrom function. here’s a rough idea:

const provider = new ethers.providers.JsonRpcProvider('YOUR_RPC_URL');
const signer = new ethers.Wallet(myPrivateKey, provider);
const nftContract = new ethers.Contract(nftContractAddress, ABI, signer);
await nftContract.transferFrom(myAddress, recipientAddress, tokenId);

hope this helps! let me know if u need more details

I have implemented NFT transfers using Web3.js in a recent project. In my experience, you first need to install Web3.js and establish a connection to your Ethereum node. Next, load the NFT contract ABI along with its address and create an instance of the contract. Once this is set up, calling the safeTransferFrom method will initiate the transfer. It is essential to ensure you have the correct ABI and that your account has ample gas and the necessary permissions. Additionally, always handle transaction receipts and errors appropriately. If problems arise, check your contract’s ownership and approval settings, as you might need to authorize the transfer before proceeding.

hey owen! i’ve been messing around with nft transfers lately too. have you tried using ethers.js? it’s pretty straightforward once you get the hang of it.

one thing to keep in mind - make sure you’ve got the right ABI for your contract. that tripped me up at first. also, double check that you’re approved to transfer the nft. sometimes that’s the sneaky issue.

quick question - are you using a testnet for development? might be worth trying on rinkeby or goerli first to iron out any kinks.

let me know how it goes! always happy to bounce ideas around if you hit any more roadblocks.