How to implement onERC721Received function

Viewed 2070

I am trying to send an NFT to a smart contract to hold in escrow but am having a tough time implementing the overriding function onERC721Received as I get an error about unused variables - this is the error im getting ?

Warning: Unused function parameter. Remove or comment out the variable name to silence this warning.
--> contracts/NftEscrow.sol:11:79:
|
11 | function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes memory _data) public override returns(bytes4) {
| ^^^^^^^^^^^^^^^^^^

This is the smart contract

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

    
    contract nftescrow is IERC721Receiver {
        
        enum ProjectState {newEscrow, nftDeposited, cancelNFT, ethDeposited, canceledBeforeDelivery, deliveryInitiated, delivered}
        
        address payable public sellerAddress;
        address payable public buyerAddress;
        address public nftAddress;
        uint256 tokenID;
        bool buyerCancel = false;
        bool sellerCancel = false;
        ProjectState public projectState;
    
        constructor()
        {
            sellerAddress = payable(msg.sender);
            projectState = ProjectState.newEscrow;
        }
        
        function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) public override returns (bytes4) {
            return this.onERC721Received.selector;
        }
        
        function depositNFT(address _NFTAddress, uint256 _TokenID)
            public
            inProjectState(ProjectState.newEscrow)
            onlySeller
        {
            nftAddress = _NFTAddress;
            tokenID = _TokenID;
            ERC721(nftAddress).safeTransferFrom(msg.sender, address(this), tokenID);
            projectState = ProjectState.nftDeposited;
        }
    } 
    
    }

Does anyone have any idea how to fix this?

2 Answers

You can make the warning disappear like this :

    function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
        return IERC721Receiver.onERC721Received.selector;
    }

It's "just" a warning - not an error - so the contract will compile even with the warning.

The compiler tells you that you're defining parameters operator, tokenId, from, and data, but you're not not using them. However the ERC721 standard requires the onERC721Received() function to accept all these parameters, even though you might not use them, because the function selector is determined from them.

So you can safely ignore this warning.

Related