Search code examples
ethereumsoliditytransfersmartcontractsether

How to withdraw PART of the Smart Contract's balance into an account?


I have looked through many similar questions but they only address transferring the entirety of the smart contract's balance to the personal account, and it is done like this:

msg.sender.transfer(address(this).balance);

What I am trying (and failing) to figure out is how to transfer part of the balance. Eg. If the contract contains 3 ether, I only want to transfer 1. And I want to be able to specify the amount to be transferred every time I use the function. I am not posting my code because nothing I have tried works and it is pretty much guesswork.

Thank you for any help.


Solution

  • function withdraw(uint amount) public {
        msg.sender.transfer(amount);
    }
    

    Withdraws the amount specified with amount variable. No need to check the total balance of the contract because if you try to withdraw more than total balance it will revert.