Search code examples
substrate

How can I define a variable which can be shared between functions defined in decl_module?


I want to implement the process below:

During the processing of a block:
before executing any extrinsics (on_initialize): 
  initialize MyVariable

When MyFunction is called:
  update MyVariable

end of executing all extrinsics (on_finalize):
  update a variable defined in decl_storage with MyVariable

So I defined three functions in decl_module: on_initialize, MyFunction , and on_finalize. But how can I define MyVariable, which will be initialized in on_initialize, and then updated in MyFunction , and finally in on_finalize it will be used to update a variable defined in decl_storage?


Solution

  • You will need to create a decl_storage storage item for that variable, or simply update the existing storage during each step since you will push the value in on_finalize anyway.

    You can see the use of transient storage items in pallets like Timestamp:

    https://github.com/paritytech/substrate/blob/master/frame/timestamp/src/lib.rs#L191

    Where DidUpdate is set somewhere earlier in the block, and removed during the on_finalize.