As we know transactions on Ethereum are atomic. If something throws, everything rolls back. Do we have something similar in Substrate? Or all changes I should manually revert?
2 Answers
At the time of this post, Substrate does not have a "revert" behavior by default.
That is, any change made to storage will be committed to the chain at the end of the block.
We are in the process of changing this and introducing a storage layer by default for each transaction to the chain. That will be such that all changes caused by a transaction could be reverted automatically if the extrinsic return an error.
Until then, we recommend updating the logic of your code to only write to storage when you know everything will be committed, or use the #[transactional]
tag mentioned above.
But it is coming soon!
-
As of now, transactional is default in Substrate, so revert is the default behavior in Substrate.– Shawn Tabrizi ♦Jul 25 at 18:37
I believe you're referring to rolling back storage modifications, right?
In that case, you may use the #[transactional]
macro to achieve that purpose.
That or you may use the "Verify first, write last" pattern. Although, the transactional
macro is pretty inexpensive.
-
Thanks for quick reply. I mean Changes in Storage. Is it still apply? What my function should throw to rollback? Apr 2, 2022 at 19:29
-
1AFAIK, if a function is annotated with
#[transactional]
and returns anErr
of any type (your signature should returnResult<OkType, ErrorType>
), then storage changes should be reverted– AngeloApr 5, 2022 at 14:05 -