pallet_domain_id/
lib.rs

1// Copyright (C) 2023 Subspace Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// 	http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Pallet Domain Id
17
18#![cfg_attr(not(feature = "std"), no_std)]
19
20#[cfg(test)]
21mod tests;
22
23pub use pallet::*;
24
25#[frame_support::pallet]
26mod pallet {
27    use frame_support::pallet_prelude::*;
28    use sp_domains::DomainId;
29
30    #[pallet::config]
31    pub trait Config: frame_system::Config {}
32
33    #[pallet::storage]
34    pub(super) type SelfDomainId<T> = StorageValue<_, DomainId, OptionQuery>;
35
36    /// Pallet domain-id to store self domain id.
37    #[pallet::pallet]
38    #[pallet::without_storage_info]
39    pub struct Pallet<T>(_);
40
41    // TODO: Remove default once https://github.com/paritytech/polkadot-sdk/pull/1221 is in our fork
42    #[derive(frame_support::DefaultNoBound)]
43    #[pallet::genesis_config]
44    pub struct GenesisConfig<T> {
45        pub domain_id: Option<DomainId>,
46        #[serde(skip)]
47        pub phantom: PhantomData<T>,
48    }
49
50    #[pallet::genesis_build]
51    impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
52        fn build(&self) {
53            // NOTE: the domain id of a domain instance is allocated during instantiation and can not
54            // be known ahead of time, thus the value in the `RuntimeGenesisConfig` of chain spec can
55            // be arbitrary and is ignored, it will be reset to the correct id during domain instantiation.
56            SelfDomainId::<T>::set(self.domain_id);
57        }
58    }
59
60    impl<T: Config> Pallet<T> {
61        #[cfg(not(feature = "runtime-benchmarks"))]
62        pub fn self_domain_id() -> DomainId {
63            SelfDomainId::<T>::get().expect("Domain ID must be set during domain instantiation")
64        }
65
66        #[cfg(feature = "runtime-benchmarks")]
67        pub fn self_domain_id() -> DomainId {
68            SelfDomainId::<T>::get().unwrap_or(0.into())
69        }
70    }
71}