1

Beginner in solidity and i'm trying to send ether from an address to a contract. I've tried transferring ether using the Remix compiler test accounts.

pragma solidity 0.4.25;

contract sendether{

     function receiveEther() payable public{
     }

     function sendEther(address _address) payable public{
         uint value = 5 ether;

         _address.transfer(value);
     }

}

I made a simple code to accept ether from an address and send ether to an address.

What i'm not sure is, if i made a Dapp, can i just send ether from my wallet and not execute the receiveEther() function. If no, how can i accept the ether from an address?

3
  • Note that the sendEther function doesn't look like it needs to be declared payable, but it does look like it needs some sort of access-restriction, because the way things stand as of now, anyone can call it and get 5 ether out of your contract! Commented Oct 30, 2018 at 9:50
  • is there a safer way to transfer ethers to an address?
    – Adam Chua
    Commented Oct 30, 2018 at 9:54
  • Add a state variable address owner, a function constructor() public {owner = msg.sender;}, and a statement require(msg.sender == owner); at the beginning of the sendEther function. Thus, only the account used for deploying the contract will be able to invoke this function. Commented Oct 30, 2018 at 11:14

2 Answers 2

1

First, the function should be payable.

Also, you don't need to have transfer or any other function to receive ETH. Just check msg.value.

For example:

function receiveETH() payable public{
     uint value = 5 ether;

    require(msg.value >= value, "Insufficient ETH";
    // do whatever you want.
}
0

To accet ETH regardless of the function called you need a so-called nameless fallback function:

function () public payable {
}

Then whenever you send ETH to the contract this function will get called.

3
  • that means if i send ether from my wallet to the contract address, the contract will receive the ether? there's no need to add anything else on my DApp besides the fallback function?
    – Adam Chua
    Commented Oct 30, 2018 at 9:49
  • Yes exactly. You should try it out first on a local testnet so you get a good grasp of the dynamics involved. Commented Oct 30, 2018 at 10:17
  • @ThomasVanderstraeten If you want explicitely call a function and send ether, then that function has to be payable. If function is invoked and the function exists the fallback function will be skipped entirely. You can invoke a function from a contract and pass ether with myContrac.myFunction.value(1 ether)(myParam1, myParam2, ...).
    – Ismael
    Commented Oct 31, 2018 at 2:08

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.