0

I am working through Mastering Ethereum and have been building their first example Faucet Contract. I recognize that a lot of their syntax is out of date, and written in ^0.4.19. I've been writing it in ^0.8.7 and updating the code to modern standards through google, ect.

Their code reads as:

contract Faucet {

   function withdraw(uint withdraw_amount) public {

      require(withdraw_amount <= 100000000000000000);

      msg.sender.transfer(withdraw_amount);
    }

   function () public payable {}
}

My updated code reads as:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract myFirstFaucet {
    function withdraw(uint withdrawAmount) view public {
        require(withdrawAmount <= 100000000000000000);

        payable(msg.sender);
    }
    
    fallback () external payable {}
    receive () external payable {}
}

I know the fallback function works, although I'm still a bit confused on the reasoning behind the fallback -> receive split.

However, whenever I call the withdraw function it doesn't send out the ether. I know the contract balance on Ropsten is 5 ETH:

https://ropsten.etherscan.io/address/0x73a3c2810ce8819321ff5e5629377a422350bee9

I assume this is because I need to specify somewhere in the payable(msg.sender) line that they get the withdrawAmount but I am struggling to find correct syntax for that. Can anyone help? Thank you.

1 Answer 1

0

The payable keyword is used to convert an address into an address than can receive ETH. You did it in your example, but you forgot to transfer the funds, you could slightly modify the code to have this:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract myFirstFaucet {
    function withdraw(uint withdrawAmount) view public {
        require(withdrawAmount <= 100000000000000000);

payable(msg.sender).transfer(withdrawAmount);
    }

    fallback () external payable {}
    receive () external payable {}
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.