0

lets say i have a donation smart contract that accepts donations, the code should be the following :

contract Donation{
   address payable owner;
   construct()
   {
     owner = msg.sender;
   }
   function Donate() public payable()
   { }

}

my questions are:

  1. as far as i understand ether would be transferred to the smart contract address but not the address of the owner of the smart contract, so how do i transfer that ether to the owner?
  2. if i wanted to restrict the withdraw of that ether from the owner until a certain condition like for example a deadline or some evidence that the work intended of that donation has happened, how i would make that condition?

1 Answer 1

0

You are correct, any ETH sent to the smart contract function marked as payable will belong to the smart contract unless explicitly sent elsewhere.

You can transfer ETH to the owner like this :

owner.transfer(msg.value);

msg.value holds the amount of ETH sent.

So for your first question, the donate method would look something like that :

function donate() hasEther public payable
{
   owner.transfer(msg.value);
}

On a side note, since solidity 0.6.x a special function receive() is used to receive ETH from a transaction that doesn't send data, just ETH.

Consider using it to replace / complement your donate() function :

receive() external payable 
{
   owner.transfer(msg.value);
}

Any ether send to your contract address will be handled by the receive function. ( no need to invoke the function directly, it's easier for the users )

For your second question, you wouldn't send the ether directly in the donate function. Instead, you should add a withdrawal function :

function withdraw() onlyOwner onlyOnConditionTrue public
{
   owner.transfer(address(this).balance);
}

Where onlyOnConditionTrue is a modifier checking that your condition is true. The definition of the condition and the rules under which it can be set is entirely up to you.

1
  • thank you so much man, you are awesome
    – ezio
    Commented Oct 28, 2021 at 12:29

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.