Solidity – How Contract Methods Work in Changing State Variables

contract-deploymenterc-721openzeppelin-contractssolidity

So, I'm trying to implement openzeppelin ERC721Enumerable contract. I want to override _beforeTokenTransfer method. Because it was a Hook, I have to call super method like this

function _beforeTokenTransfer(
    address from,
    address to,
    uint256 tokenId
)
    internal
    virtual
    override
{
    super._beforeTokenTransfer(from, to, tokenId);

    // some requirement
    require(someRequirement(_msgSender()), 'MyERC721: Sender has not met the requirement to proceed')

   // some stuff
}

The problem is, inside _beforeTokenTransfer of ERC721Enumerable, there are some changing state variables. I am worried that when my method reverted, the state variables there are changed before are not going back to their previous state. Usually, something like this will happened

>>> class SomeClass:
...     def __init__(self):
...         self.state = 0
...     def change_state(self, x):
...         self.state += x
...         raise Exception('method reverted')
>>> an_instance = SomeClass()
>>> an_instance.state
0
>>> an_instance.change_state(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in change_state
Exception: method reverted
>>> an_instance.state
10

The state variable inside SomeClass is changed because the exception is raised after the state changed. Does this also valid for SmartContract? How does SmartContract handle changing state before exception is raised?

Best Answer

In this context it doesn't make much difference when the exception is raised. Transactions are atomic: either they succeed fully or they are fully reverted back.

So if there is a revert anywhere in the execution path, the whole transaction is reverted back, and all changes made by it are reverted. (This is not 100% correct: external contracts' revertions can be for example caught by try-catch blocks.)

So you don't really need to worry about some residual state changes.

Related Topic