0

I have a payable function that transfers ether to contract.

function test(...) public payable returns (bool) {  
    ...                                                                                               
    address(this).transfer(msg.value); 

    return true;
}

I found that above method fails without having a fallback function in the contract.

function () payable public {}

Can anyone explain this please?

3

Because the line address(this).transfer(msg.value); is transferring msg.value worth of Ether from the contract to itself.

And if you send Ether to a contract without a payable fallback function it will fail.

  • so whenever I want to send ether to a contract I must have a fallback function? – bbusdriver May 18 '18 at 9:27
  • Im not sure what version of solidity it started in, but by default if you dont have a payable fallback function you can't just send ETH to that contract. (This doesn't include other payable functions). But the line address(this).transfer(msg.value); is redundant anyway, the entire msg.value automatically goes to the contract, you don't have to manually set it. – AnAllergyToAnalogy May 18 '18 at 9:31

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.