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?

bbusdriver
  • 1,144
  • 2
  • 18
  • 33

1 Answers1

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.

AnAllergyToAnalogy
  • 3,553
  • 11
  • 23
  • so whenever I want to send ether to a contract I must have a fallback function? – bbusdriver May 18 '18 at 09: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 09:31