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?

Adam Chua
  • 21
  • 1
  • 4
  • 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! – goodvibration Oct 30 '18 at 09:50
  • is there a safer way to transfer ethers to an address? – Adam Chua Oct 30 '18 at 09: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. – goodvibration Oct 30 '18 at 11:14

2 Answers2

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.

}

0xSanson
  • 3,114
  • 2
  • 11
  • 23
Jonathan
  • 11
  • 2
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.

  • 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 Oct 30 '18 at 09:49
  • Yes exactly. You should try it out first on a local testnet so you get a good grasp of the dynamics involved. – Thomas Vanderstraeten Oct 30 '18 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 Oct 31 '18 at 02:08