3

I have a problem with sending ether to my contract address via metamask. I found that the function has to be with 'payable' modifier, but it doesn't help. I send transaction, spend ethers from my account, but the contract's address still has 0 value. For example the contract looks like:

contract Mycontract
{
  function Mycontract() payable{}
}
4

The problem is that the constructor Mycontract() gets called only once.

After that you need to be calling a particular function. Without specifying a particular function, the invocation defaults to the default function which is not present in your example. Every smart contract has a default function that does nothing and is not payable. Because of this, your contract simply refuses to accept the ether.

If you want your contract to do absolutely nothing but accept ether (which would be a silly because you could never get the ether back), you can do this:

contract C {
    function C() {}
    function () payable {}
}

This will accept ether, but it will be stuck there forever. The second function is the syntax for a default function.

| improve this answer | |
3

Here's a little hint that might help.

contract Mycontract {

  // This is the constructor. It's payable so you can initialize the contract with funds during deploy.
  function Mycontract() payable {}

  // This function is available after deploy. You can send funds to this function. 
  function pay() payable {}
}
| improve this answer | |
1

function Mycontract() payable{} is the contract constructor. It is only executed when the contract is deployed. Marking it as payable means you can attach a certain amount when you create the contract.

If you want to to allow anyone to send Ether to your contract, you need to make your contract's fallback method payable.

You define it like this:

contract Mycontract {
    fallback() external payable { }
}

You can find more details about the fallback function in Solidity's official documentation.

| improve this answer | |

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.