1

I have a function with modifier 'payable' in the contract. My understading is, msg.value gets added to the contract's balance and then further code is executed. First question, is this a correct understading ? Second question, how do i send back msg.value to caller if there is a error, i could think of doing this,

if(<check for error case>){
  msg.sender.send(msg.value)
}

or is there a way to use 'require'?

1

The correct way to signal an error and return a user's funcds is to use the revert, assert, or require operations. All of these will return any funds sent in the transaction. For example, your code may look like

assert(!error);

or

require(conditions, "Error message");

or

if(error)
    revert("Error message");

Note that require and revert return any unused gas to the sender, while assert consumes all unused gas. It is usually preferable to use require.

For more documentation see http://solidity.readthedocs.io/en/v0.4.24/control-structures.html?highlight=revert#error-handling-assert-require-revert-and-exceptions

0

First question, is this a correct understading ?

Yes

Second question, how do i send back msg.value to caller if there is a error

If you use send, you will need to use it inside a require since it doesn't throw an error if the transfer of eth fails. You can use transfer instead of send then, which checks for you if it successfully transfered the eth.

Example :

if (error) {
    msg.sender.transfer(msg.value);
}

is there a way to use 'require'?

Yes, it depends on your code. I consider it a preferable way than your first solution.

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.