Search code examples
ethereumsolidity

Transfering ETH from Account 1 to 2


I'm trying to transfer ether from an Account 1 to an Account 2. This is the code:

function pay(address _from, uint256 _tokenId) external payable noReentrant {
    uint256 balance = msg.sender.balance;
    require(balance > 0.011 ether, "There is not enough eth");        

    payable(__ADDRESS2__).transfer(0.001 ether);
}

receive() external payable {
}

fallback() external payable {
}

So here the msg.sender is Account 1 and this account wants to transfer eth to Account 2. Both accounts have ethers but it's throwing this error:

Error: Transaction reverted: function call failed to execute

I'm using hardhat to test this function. So I have a couple of doubts:

  1. Is this the correct way to transfer tokens from Account 1 to 2? And here I'm not talking about transfering eth from Account 1 to address of the contract.
  2. If it is, then, what's wrong with it?

Solution

  • First of all, the code you presented trasnfers ether from the contract to ADDRESS2, so the transaction probably reverts because the contract doesn't have enough ether. You should've checked that the caller sends you enough ether to transfer, i.e require(msg.value >= 0.001 ether).

    Concerning the last two questions:

    1. No, this code illustrates ether transfers. If you want to transfer ERC20 tokens, the OZ library would be a good start.
    2. The reason it reverts is explained above. Sending ether is very different from sending ERC20 (or any other) tokens, consider checking the OpenZeppelin library.