Sending an ERC721 token from a smart contract to a user address

Hey everyone,

I’m working on a smart contract that holds NFTs and I want to create a function that lets me, as the owner, send these NFTs to other addresses. I’ve got most of the code written, but I’m running into a problem.

Here’s what I’ve got so far:

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";

contract NFTHolder {
    function sendNFT(
        address nftContract,
        uint256 tokenId,
        address recipient
    ) external onlyOwner {
        IERC721(nftContract).safeTransferFrom(
            address(this),
            recipient,
            tokenId
        );
    }
}

The issue is that when I try to compile this, I get an error saying it can’t find the safeTransferFrom function in IERC721. Am I missing something obvious here? How can I fix this so I can transfer the NFT from my contract to a user’s address?

Any help would be appreciated!

hey kai29! that’s a pretty cool project you’ve got going there. i’m not an expert, but i’ve dabbled with nfts a bit and might have a suggestion.

have you tried using the regular transferFrom function instead of safeTransferFrom? i remember running into a similar issue and switching to transferFrom fixed it for me. it might look something like this:

IERC721(nftContract).transferFrom(address(this), recipient, tokenId);

just a thought! if that doesn’t work, maybe double-check your openzeppelin imports? sometimes those can be tricky.

btw, what kind of nfts are you working with? sounds like an interesting project!

The problem likely stems from using an outdated IERC721 interface. To resolve this, you should import the IERC721 interface from OpenZeppelin’s latest contracts. Replace your current import with:

import '@openzeppelin/contracts/token/ERC721/IERC721.sol';

This updated interface includes the safeTransferFrom function. Additionally, ensure you’re using a recent version of OpenZeppelin contracts in your project’s dependencies.

If the issue persists, you might need to explicitly approve the transfer first:

IERC721(nftContract).approve(recipient, tokenId);
IERC721(nftContract).safeTransferFrom(address(this), recipient, tokenId);

This approach should allow your contract to successfully transfer NFTs to user addresses.

yo kai29, i’ve dealt w/ this before. the issue is probably ur IERC721 interface. u need to import IERC721 from ‘@openzeppelin/contracts/token/ERC721/IERC721.sol’ instead. that should have the safeTransferFrom function. if ur still stuck, lemme kno and i can try to help more!