Search code examples
ethereumsolidity

How do I send my custom token to another account?


so this is the custom token i made

    address public deployer; //to save adress of the deployer
    
    constructor() ERC20('tokenA', 'TA') { //called by the deployer (once)
        _mint(msg.sender, 1000000000000 * 10 ** 10); //mint/create tokens - we have created 100000000000*10^18 tokens
        deployer = msg.sender;  //set the deployer
    }

    //total supply is fixed no more can be created ever

    function burn (uint amount) external {  //remove tokens by sending then to a zero address
        _burn(msg.sender, amount);
    }
}

User1 is the owner of the contract and has tons of tokens, User2 has 3 tokens in his wallet. I have to write a function which when clicked transfers 1 token to the owner that is User1.


    function transferOneToken () public payable {
        address token = //address of token contract;
        ERC20 paymentToken = ERC20(token);

        require(paymentToken.transferFrom(msg.sender, owner, 1), "transfer Failed"); //owner is set in constructor
        
    }

This is what I came up with, User 2 has 3 tokens and only has to transfer 1 but still gas estimation failed error pops up saying insufficient allowance

how do I solve this?


Solution

  • The token holder (User 2) needs to approve() the spender (the contract implementing the transferOneToken() function) to spend their tokens before the transferFrom() function is invoked.

    The approve() function of the token contract takes 2 arguments:

    1. The spender address
    2. The max amount they're allowed to spend

    Without the approval mechanism, any contract could pull their users' tokens, which would be an unsafe situation for users who can't/don't read the contract code.