3

I have a smart contract with a payable bet() function. When someone sends 1 ether to the bet function, the contract is executed.

I'd like the contract to run the same code when someone sends ether to the address explicitely (as if you're sending ether to someone else), without having to use the function bet().

How do I do this?

Thanks

7

you need to use the Fallback function like in the code below. this function is executed when someone send Ethers to the contract without providing any data or calling a function :

pragma solidity ^0.4.0;
contract bet{

    uint256 public bet;

    event received(string msg);

    function () payable{

        bet=msg.value;
        received("bet received");

    }


}

this function don't accept any parameters, you need when using this fallback to check your security model to avoid any problems.

  • Thanks. what's the received() function you put there? is that like a message the sender gets as a confirmation or something? – Anto Jun 8 '17 at 9:50
  • it's an event which will log the reception of the bet – Badr Bellaj Jun 8 '17 at 9:54
1

you can use the fallback function - an unnamed function that is invoked when no other function matches the call that was received, or if no data was passed (as in the case of a simple eth transfer). Make sure that you have enough gas to perform what you need to do though, as simple eth transfers will carry very little gas.

source: solidity docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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