1

After deploying and using the transferFrom function, it is giving the following error: "false Transaction mined but execution failed". This is the code:

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract TransferToken {
    function transferFrom(IERC20 token, address from, address to, uint amount) public{
        token.transferFrom(from, to, amount);
    }
}

How can I transfer my ERC20 token from wallet 1 to wallet 2? Without asking for authorization? Because this will be a form of withdrawal from an NFT game. Wallet 1 will be mine, and wallet 2 will be the player's.

1 Answers1

0

The approval mechanism prevents stealing tokens from users who don't want you to spend their tokens.

So the easiest way is to execute the approve() function on the token contract, from the wallet 1 (sender), passing the TransferToken address in the first argument and total amount of tokens that you want to allow for spending.

This will effectively allow the TransferToken contract to spend the wallet 1's tokens.


If you have control over the token code, you could also implement a separate function (to the token contract) that would allow the transfer without any previous approvals:

pragma solidity ^0.8;

contract MyToken {
    mapping (address => uint256) balanceOf;
    address gameContractAddress;
    
    function transferForGame(address _receiver, uint256 _amount) external {
        require(msg.sender == gameContractAddress, 'Only the game can perform this transfer');
        balanceOf[gameContractAddress] -= _amount;
        balanceOf[_receiver] += _amount;
    }
}
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100