Search code examples
blockchainsoliditysmartcontractserc20erc721

I want to mint and transfer 1 erc20(custom) to the minter itself, just to track erc20 transaction


This is the code used, I am using polygon testnet for testing, the approve function is working fine but transferFrom is not working(error: -32000)

// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;

import "@0xcert/ethereum-erc721/src/contracts/tokens/nf-token-metadata.sol";
import "@0xcert/ethereum-erc721/src/contracts/ownership/ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract newNFT is NFTokenMetadata, Ownable {
    ERC20 KOOLToken;

    constructor() {
        KOOLToken=ERC20(0xxxxxxxxxxxxxxxxxxxxxxxxxxx);
        nftName = "Test NFT 123";
        nftSymbol = "TNFT321";
    }

    function approve() public onlyOwner {
      KOOLToken.approve(address(msg.sender), 1);
    }

function transferFrom() public onlyOwner{
  KOOLToken.transferFrom(msg.sender,msg.sender, 1);
}

function mint(address _to, uint256 _tokenId, string calldata _uri) public onlyOwner {
  super._mint(_to, _tokenId);
  super._setTokenUri(_tokenId, _uri);
}
}

Solution

  • Your -32000 error is caused by a revert in the ERC20 contract, because msg.sender does't have enough allowance to spend.

    According to EIP20, transferFrom provides:

    The transferFrom method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf. This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in sub-currencies. The function SHOULD throw unless the _from account has deliberately authorized the sender of the message via some mechanism.

    Which means,even though the msg.sender is the owner here, it is not a valid source address for transferFrom unless you call approve on it before.

    You can approve the msg.sender, or simply use transfer function.