I'm trying to implement a functionality in my smart contract in which a token owner (ERC721) transfers that token to a buyer. The buyer is the one that makes the call, after paying the requested amount. There is no marketplace involved. So I can't implement this solution. After a user from any account wants to buy the token, I get this error:
revert ERC721: caller is not token owner or approved.
Here is the code:
function buyShirtNFT(uint256 _tokenId) public payable
{
require(tokenIdToShirtInfo[_tokenId].price > 0, "The NFT should be up for sale");
uint256 cost = tokenIdToShirtInfo[_tokenId].price;
address ownerAddress = ownerOf(_tokenId);
require(msg.value > cost, "You need to have enough Ether");
transferFrom(ownerAddress, msg.sender, _tokenId);
address payable ownerAddressPayable = _make_payable(ownerAddress); // We need to make this conversion to be able to use transfer() function to transfer ethers
ownerAddressPayable.transfer(cost);
if(msg.value > cost)
{
payable(msg.sender).transfer(msg.value - cost);
}
}
Is there any way to solve this, or how can I implement my solution?. Thanks!
The error message
ERC721: caller is not token owner or approvedis displayed in your situation because the buyer (the person who calls thebuyShirtNFTfunction) is neither the owner nor an authorized operator.You can read more about the
ERC721standard here:https://docs.openzeppelin.com/contracts/3.x/erc721#:~:text=ERC721%20is%20a%20standard%20for,across%20a%20number%20of%20contracts.