8

Thanks to @islami00 for the question (not verbatim):

I have done all error checking as instructed here.
Am I now save to expect all future Results even after modifying storage?

When is it permissible to use expect?
What happens when it fails?

3 Answers 3

17

Short answer: never use expect, unwrap or other panickers in runtime code.

Long answer: only if you can prove that it will never panic, and you are confident that your code is so simple and maintainable that nobody could ever make a change which would result in that proof becoming broken and a panic possible.

In general, it's better to just not include anything which can panic since it will open you up to DoS attacks, or, if the panic happens during one of the runtime hooks (on_initialize &c.) then your chain will halt.

1
  • if one can store panic transaction in some kind of dispatch scheduler he would trigger panic in pallet hooks. if on_finalize panic as bad as on_initialize, chain could halt too Commented Jun 2, 2023 at 4:44
11

When is it permissible to use expect?

When you can prove that it can not panic. Aka you have done all required checks, like that the data exists or that some kind of arithmetic operation will succeed.

What happens when it fails?

The block producer will throw away the transaction and any modifications to the state that have been done. The problem with this is that you can DoS the block producers for free. You can just send the same tx over and over again, you will not need to pay (because we revert all the state, this includes fee deduction if a tx panics), but the block producer will try to include it.

9

You use expect where you want to communicate that unwrapping this result should never fail. You can use unwrap or unwrap_or where you aren't sure, but for infallible calls, you should use expect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.