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// TODO: Remove once FRAME macros stop generating `.clone()` calls on `Copy` types with user spans
20#![expect(clippy::clone_on_copy, reason = "Comes from Substrate")]
21
22#[cfg(test)]
23mod tests;
24
25pub use pallet::*;
26
27#[frame_support::pallet]
28mod pallet {
29 use frame_support::pallet_prelude::*;
30 use sp_domains::DomainId;
31
32 #[pallet::config]
33 pub trait Config: frame_system::Config {}
34
35 #[pallet::storage]
36 pub(super) type SelfDomainId<T> = StorageValue<_, DomainId, OptionQuery>;
37
38 /// Pallet domain-id to store self domain id.
39 #[pallet::pallet]
40 #[pallet::without_storage_info]
41 pub struct Pallet<T>(_);
42
43 // TODO: Remove default once https://github.com/paritytech/polkadot-sdk/pull/1221 is in our fork
44 #[derive(frame_support::DefaultNoBound)]
45 #[pallet::genesis_config]
46 pub struct GenesisConfig<T> {
47 pub domain_id: Option<DomainId>,
48 #[serde(skip)]
49 pub phantom: PhantomData<T>,
50 }
51
52 #[pallet::genesis_build]
53 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
54 fn build(&self) {
55 // NOTE: the domain id of a domain instance is allocated during instantiation and can not
56 // be known ahead of time, thus the value in the `RuntimeGenesisConfig` of chain spec can
57 // be arbitrary and is ignored, it will be reset to the correct id during domain instantiation.
58 SelfDomainId::<T>::set(self.domain_id);
59 }
60 }
61
62 impl<T: Config> Pallet<T> {
63 #[cfg(not(feature = "runtime-benchmarks"))]
64 pub fn self_domain_id() -> DomainId {
65 SelfDomainId::<T>::get().expect("Domain ID must be set during domain instantiation")
66 }
67
68 #[cfg(feature = "runtime-benchmarks")]
69 pub fn self_domain_id() -> DomainId {
70 SelfDomainId::<T>::get().unwrap_or(0.into())
71 }
72 }
73}