Module frame_support::dispatch_context
source · Expand description
Provides functions to interact with the dispatch context.
A Dispatch context is created by calling run_in_context
and then the given closure will be
executed in this dispatch context. Everyting run in this closure
will have access to the same
dispatch context. This also applies to nested calls of run_in_context
. The dispatch context
can be used to store and retrieve information locally in this context. The dispatch context can
be accessed by using with_context
. This function will execute the given closure and give it
access to the value stored in the dispatch context.
FRAME integration
The FRAME macros implement UnfilteredDispatchable
for
each pallet Call
enum. Part of this implementation is the call to run_in_context
, so that
each call to
UnfilteredDispatchable::dispatch_bypass_filter
or Dispatchable::dispatch
will run in a dispatch
context.
Example
use frame_support::dispatch_context::{with_context, run_in_context};
// Not executed in a dispatch context, so it should return `None`.
assert!(with_context::<(), _>(|_| println!("Hello")).is_none());
// Run it in a dispatch context and `with_context` returns `Some(_)`.
run_in_context(|| {
assert!(with_context::<(), _>(|_| println!("Hello")).is_some());
});
#[derive(Default)]
struct CustomContext(i32);
run_in_context(|| {
with_context::<CustomContext, _>(|v| {
// Intitialize the value to the default value.
assert_eq!(0, v.or_default().0);
v.or_default().0 = 10;
});
with_context::<CustomContext, _>(|v| {
// We are still in the same context and can still access the set value.
assert_eq!(10, v.or_default().0);
});
run_in_context(|| {
with_context::<CustomContext, _>(|v| {
// A nested call of `run_in_context` stays in the same dispatch context
assert_eq!(10, v.or_default().0);
})
})
});
run_in_context(|| {
with_context::<CustomContext, _>(|v| {
// We left the other context and created a new one, so we should be back
// to our default value.
assert_eq!(0, v.or_default().0);
});
});
In your pallet you will only have to use with_context
, because as described above
run_in_context
will be handled by FRAME for you.
Structs
- Abstraction over some optional value
T
that is stored in the dispatch context.
Functions
- Run the given closure
run
in a dispatch context. - Runs the given
callback
in the dispatch context and gives access to some user defined value.