0

I am reading this page and trying to understand how these 2 pieces of code will behave:

With require()

function transfer(address _newOwner) public {
    require(msg.sender == owner)
    // Do the actual transfer
}

With return in an if():

function transfer(address _newOwner) public {
    if (msg.sender != owner) return;
    // Do the actual transfer
}

I understand that require() will revert all changes and refund me any unused gas, but what exactly does the second code will behave? The function will stop executing, but does it refund unused gas?

Thanks

  • The second code will refund unused gas but it will not throw an exception unlike the first one. – Elliot Solskjaer Apr 5 at 10:59
0

The second function returns execution to the previous function. So for example if you have something like this:

pragma solidity 0.6.0;

contract Example {

    address owner;
    event SomeEvent();
    event OtherEvent();

    function doSomething(address _someowner) public {
        transfer2(_someowner);
        emit SomeEvent();
        transfer1(_someowner);
        emit OtherEvent();
    }

    function transfer1(address _newOwner) public {
        require(msg.sender == owner);
        // Do the actual transfer
    }

    function transfer2(address _newOwner) public {
        if (msg.sender != owner) return;
        // Do the actual transfer
    }
}

So what happens if you call doSomething with:

1) _someowner equals to owner:

  • transfer2 performs the transfer
  • event SomeEvent is emitted
  • transfer1 performs the transfer
  • event OtherEvent is emitted

2) _someowner does not equal to owner:

  • transfer2 does not perform the transfer but returns execution to previous function (doSomething)
  • event SomeEvent is emitted
  • transfer1 does not perform the transfer and halts the transaction execution with an error
  • event OtherEvent is not emitted as the execution never reaches this far
| improve this answer | |
  • Thanks, so in other words return from an if() doesn't do any extra stuff (refund gas, halt transaction) other than return the execution flow – november Apr 5 at 13:53
  • the if if not so relevant here - return always returns the execution flow if the statement is executed – Lauri Peltonen Apr 5 at 18:42
0

I found this to be helpful.

The answer also has a link to the official docs.

| 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.