Search code examples
javascriptethereumsoliditysmartcontracts

Error when I call transfer function in ERC20 contract from other contract, But, can use mint/burn


I write 2 contracts

  • ERC20
  • ERC721 with additional function for buy it.

when call "marketBuy" function it can transfer NFT to buyer and can call burn from ERC20 contract. But when I change "burn" function to "transfer / transferFrom" then appear error like this

transact to NFT2.marketBuy pending ... transact to NFT2.marketBuy errored: VM error: revert.

revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.

This is the code

    ...

    function marketBuy(uint _tokenId) public returns (bool) {
        address _buyer = msg.sender;
        uint _price = marketItem[_tokenId].price;

        IERC20(ERC20Token).approve(marketItem[_tokenId].seller, _price);
        IERC20(ERC20Token).transferFrom(_buyer, marketItem[_tokenId].seller, _price);
        transferFrom(marketItem[_tokenId].seller, _buyer, _tokenId);
        
        marketItem[_tokenId].seller = _buyer;
        marketItem[_tokenId].isSold = true;

        return true;
    }
    
    ....

I don't know how to solve this.


Solution

  • For this line

    IERC20(ERC20Token).approve(marketItem[_tokenId].seller, _price);
    

    the caller is the contract itself, it isn't the buyer.

    So the buyer needs to call the transfer function manually on the ERC-20 contract