Search code examples
solidity

How to use ERC20 token to transfer eth in solidity?


I'm writing a defi project to transfer between an ERC20 token and eth. I want to develop a function that accept the ERC20 token from an address then send eth to that address.

What I deal with that ERC20 token was to generate the token in the smart contract and send the token to the user. The problem is that, if user A send some ERC20 token to user B, what should I do to allow user B use the token to ask for eth in my smart contract?

Another simple question is that, how to ask the user to use their wallet (e.g. metamask) to transfer ERC20 token to my smart contract?


Solution

  • Using the payable you would be able to transfer the native token (eth) from your contract into any user's wallet:

        function transferEth(address payable _to, uint _amount) public {
            (bool success, ) = _to.call{value: _amount}("");
            require(success, "Failed to send Ether");
        }
    

    Notice that this function above is not safe as any one can call the transfer to your contract, please consider to use the modifier to prevent it.


    In your case I can think of a function like:

    function claimEth() public {
        if (balanceOf(msg.sender) > 100) {
            balances[msg.sender] = balances[msg.sender[.sub(100);
            transferEth(msg.sender, 5);
        }
    }