,
26 | /// Transaction pool instance.
27 | pub pool: Arc,
28 | /// Whether to deny unsafe calls
29 | pub deny_unsafe: DenyUnsafe,
30 | }
31 |
32 | /// Instantiate all RPC extensions.
33 | pub fn create_full(
34 | deps: FullDeps,
35 | ) -> Result>
36 | where
37 | C: ProvideRuntimeApi
38 | + HeaderBackend
39 | + HeaderMetadata
40 | + Send
41 | + Sync
42 | + 'static,
43 | C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi,
44 | C::Api: substrate_frame_rpc_system::AccountNonceApi,
45 | C::Api: BlockBuilder,
46 | P: TransactionPool + Sync + Send + 'static,
47 | {
48 | use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
49 | use substrate_frame_rpc_system::{System, SystemApiServer};
50 |
51 | let mut module = RpcExtension::new(());
52 | let FullDeps {
53 | client,
54 | pool,
55 | deny_unsafe,
56 | } = deps;
57 |
58 | module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?;
59 | module.merge(TransactionPayment::new(client).into_rpc())?;
60 | Ok(module)
61 | }
62 |
--------------------------------------------------------------------------------
/invarch/runtime/build.rs:
--------------------------------------------------------------------------------
1 | use substrate_wasm_builder::WasmBuilder;
2 |
3 | #[cfg(all(not(feature = "metadata-hash"), feature = "std"))]
4 | fn main() {
5 | WasmBuilder::new()
6 | .with_current_project()
7 | .export_heap_base()
8 | .import_memory()
9 | .build()
10 | }
11 |
12 | #[cfg(all(feature = "metadata-hash", feature = "std"))]
13 | fn main() {
14 | WasmBuilder::new()
15 | .with_current_project()
16 | .export_heap_base()
17 | .import_memory()
18 | .enable_metadata_hash("VARCH", 12)
19 | .build()
20 | }
21 |
22 | /// The wasm builder is deactivated when compiling
23 | /// this crate for wasm to speed up the compilation.
24 | #[cfg(not(feature = "std"))]
25 | fn main() {}
26 |
--------------------------------------------------------------------------------
/invarch/runtime/src/assets.rs:
--------------------------------------------------------------------------------
1 | use crate::{
2 | balances,
3 | common_types::AssetId,
4 | staking::MaxNameLength,
5 | xcm_config::{
6 | AccountIdToMultiLocation, BaseXcmWeight, CurrencyIdConvert, MaxInstructions,
7 | ParachainMinFee, SelfLocation, UniversalLocation, XcmConfig,
8 | },
9 | AccountId, Amount, Balance, Balances, BlockNumber, Runtime, RuntimeCall, RuntimeEvent, Tokens,
10 | };
11 | use codec::{Decode, Encode, MaxEncodedLen};
12 | use frame_support::{parameter_types, traits::Everything};
13 | use frame_system::EnsureRoot;
14 | use orml_currencies::BasicCurrencyAdapter;
15 | use orml_traits2::{location::AbsoluteReserveProvider, parameter_type_with_key};
16 | use scale_info::TypeInfo;
17 |
18 | use xcm_builder::FixedWeightBounds;
19 |
20 | pub const VARCH_ASSET_ID: AssetId = 0;
21 |
22 | parameter_types! {
23 | pub const NativeAssetId: AssetId = VARCH_ASSET_ID;
24 | }
25 |
26 | #[derive(TypeInfo, Encode, Decode, Clone, Eq, PartialEq, Debug, MaxEncodedLen)]
27 | pub struct CustomMetadata {
28 | pub fee_per_second: u128,
29 | }
30 |
31 | impl orml_asset_registry::Config for Runtime {
32 | type RuntimeEvent = RuntimeEvent;
33 | type AuthorityOrigin = EnsureRoot;
34 | type AssetId = AssetId;
35 | type Balance = Balance;
36 | type AssetProcessor = orml_asset_registry::SequentialId;
37 | type StringLimit = MaxNameLength;
38 | type CustomMetadata = CustomMetadata;
39 | type WeightInfo = ();
40 | }
41 |
42 | impl orml_currencies::Config for Runtime {
43 | type MultiCurrency = Tokens;
44 | type NativeCurrency = BasicCurrencyAdapter;
45 | type GetNativeCurrencyId = NativeAssetId;
46 | type WeightInfo = ();
47 | }
48 |
49 | parameter_type_with_key! {
50 | pub Eds: |currency_id: AssetId| -> Balance {
51 | if let Some(metadata) = orml_asset_registry::Pallet::::metadata::(*currency_id) {
52 | metadata.existential_deposit
53 | } else {
54 | // Asset does not exist - not supported
55 | Balance::MAX
56 | }
57 | };
58 | }
59 |
60 | impl orml_tokens2::Config for Runtime {
61 | type RuntimeEvent = RuntimeEvent;
62 | type Balance = Balance;
63 | type Amount = Amount;
64 | type CurrencyId = AssetId;
65 | // Ideally we would use AssetRegistry but having multiple instances of orml pallets is causing
66 | // issues related to traits.
67 | type ExistentialDeposits = Eds;
68 | type MaxLocks = balances::MaxFreezes;
69 | type DustRemovalWhitelist = ();
70 | type MaxReserves = balances::MaxReserves;
71 | type ReserveIdentifier = [u8; 8];
72 | type CurrencyHooks = ();
73 | type WeightInfo = ();
74 | }
75 |
76 | parameter_types! {
77 | pub const MaxAssetsForTransfer: usize = 50;
78 | }
79 |
80 | impl orml_xtokens::Config for Runtime {
81 | type RuntimeEvent = RuntimeEvent;
82 | type Balance = Balance;
83 | type CurrencyId = AssetId;
84 | type CurrencyIdConvert = CurrencyIdConvert;
85 | type SelfLocation = SelfLocation;
86 | type XcmExecutor = xcm_executor::XcmExecutor;
87 | type Weigher = FixedWeightBounds;
88 | type BaseXcmWeight = BaseXcmWeight;
89 | type MaxAssetsForTransfer = MaxAssetsForTransfer;
90 | type MinXcmFee = ParachainMinFee;
91 | type ReserveProvider = AbsoluteReserveProvider;
92 | type UniversalLocation = UniversalLocation;
93 | type AccountIdToLocation = AccountIdToMultiLocation;
94 | type LocationsFilter = Everything;
95 | type RateLimiter = ();
96 | type RateLimiterId = ();
97 | }
98 |
--------------------------------------------------------------------------------
/invarch/runtime/src/common_types.rs:
--------------------------------------------------------------------------------
1 | pub type CommonId = u32;
2 |
3 | pub type AssetId = u32;
4 |
--------------------------------------------------------------------------------
/invarch/runtime/src/inflation.rs:
--------------------------------------------------------------------------------
1 | use crate::{
2 | balances::NegativeImbalance, Balance, Balances, BlockNumber, OcifStaking, Runtime,
3 | RuntimeEvent, DAYS,
4 | };
5 | use frame_support::{parameter_types, traits::OnUnbalanced};
6 | use sp_runtime::Perbill;
7 |
8 | pub const TEN_PERCENT_PER_YEAR: pallet_checked_inflation::InflationMethod =
9 | pallet_checked_inflation::InflationMethod::Rate(Perbill::from_percent(10));
10 |
11 | const YEAR: u32 = 365;
12 |
13 | parameter_types! {
14 | pub const BlocksPerEra: BlockNumber = DAYS;
15 | pub const ErasPerYear: u32 = YEAR;
16 | pub const Inflation: pallet_checked_inflation::InflationMethod = TEN_PERCENT_PER_YEAR;
17 | }
18 |
19 | pub struct DealWithInflation;
20 | impl OnUnbalanced for DealWithInflation {
21 | fn on_unbalanced(amount: NegativeImbalance) {
22 | OcifStaking::rewards(amount);
23 | }
24 | }
25 |
26 | impl pallet_checked_inflation::Config for Runtime {
27 | type BlocksPerEra = BlocksPerEra;
28 | type Currency = Balances;
29 | type RuntimeEvent = RuntimeEvent;
30 | type ErasPerYear = ErasPerYear;
31 | type Inflation = Inflation;
32 | type DealWithInflation = DealWithInflation;
33 | type WeightInfo = pallet_checked_inflation::weights::SubstrateWeight;
34 | }
35 |
--------------------------------------------------------------------------------
/invarch/runtime/src/staking.rs:
--------------------------------------------------------------------------------
1 | use crate::{
2 | Balance, Balances, BlockNumber, ExistentialDeposit, MessageQueue, Runtime, RuntimeEvent,
3 | RuntimeHoldReason, DAYS, UNIT,
4 | };
5 | use cumulus_primitives_core::AggregateMessageOrigin;
6 | use frame_support::{parameter_types, PalletId};
7 | use pallet_dao_staking::primitives::CustomAggregateMessageOrigin;
8 | parameter_types! {
9 | pub const BlocksPerEra: BlockNumber = DAYS;
10 | pub const RegisterDeposit: Balance = 5000 * UNIT;
11 | pub const MaxStakersPerDao: u32 = 10000;
12 | // Temporarily dropping down from 50 to 5.
13 | pub const MinimumStakingAmount: Balance = 5 * UNIT;
14 | pub const MaxEraStakeValues: u32 = 5;
15 | pub const MaxUnlockingChunks: u32 = 5;
16 | pub const UnbondingPeriod: u32 = 28;
17 | pub const OcifStakingPot: PalletId = PalletId(*b"inv/stak");
18 | pub const RewardRatio: (u32, u32) = (60, 40);
19 | pub const StakeThresholdForActiveDao: Balance = 250_000 * UNIT;
20 | pub const MaxNameLength: u32 = 20;
21 | pub const MaxDescriptionLength: u32 = 300;
22 | pub const MaxImageUrlLength: u32 = 100;
23 | pub const UnregisterOrigin: CustomAggregateMessageOrigin = CustomAggregateMessageOrigin::UnregisterMessageOrigin;
24 | }
25 |
26 | impl pallet_dao_staking::Config for Runtime {
27 | type OldCurrency = Balances;
28 | type Currency = Balances;
29 | type BlocksPerEra = BlocksPerEra;
30 | type RegisterDeposit = RegisterDeposit;
31 | type RuntimeEvent = RuntimeEvent;
32 | type MaxStakersPerDao = MaxStakersPerDao;
33 | type ExistentialDeposit = ExistentialDeposit;
34 | type PotId = OcifStakingPot;
35 | type MaxUnlocking = MaxUnlockingChunks;
36 | type UnbondingPeriod = UnbondingPeriod;
37 | type MinimumStakingAmount = MinimumStakingAmount;
38 | type MaxEraStakeValues = MaxEraStakeValues;
39 | type RewardRatio = RewardRatio;
40 | type StakeThresholdForActiveDao = StakeThresholdForActiveDao;
41 | type MaxNameLength = MaxNameLength;
42 | type MaxDescriptionLength = MaxDescriptionLength;
43 | type MaxImageUrlLength = MaxImageUrlLength;
44 | type WeightInfo = pallet_dao_staking::weights::SubstrateWeight;
45 | type StakingMessage = frame_support::traits::EnqueueWithOrigin;
46 | type WeightToFee = crate::WeightToFee;
47 | type OnUnbalanced = crate::DealWithFees;
48 | type RuntimeHoldReason = RuntimeHoldReason;
49 | }
50 |
--------------------------------------------------------------------------------
/invarch/runtime/src/weights/block_weights.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) 2022 Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License.
17 |
18 | pub mod constants {
19 | use frame_support::{
20 | parameter_types,
21 | weights::{constants, Weight},
22 | };
23 |
24 | parameter_types! {
25 | /// Importing a block with 0 Extrinsics.
26 | pub const BlockExecutionWeight: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0);
27 | }
28 |
29 | #[cfg(test)]
30 | mod test_weights {
31 | use frame_support::weights::constants;
32 |
33 | /// Checks that the weight exists and is sane.
34 | // NOTE: If this test fails but you are sure that the generated values are fine,
35 | // you can delete it.
36 | #[test]
37 | fn sane() {
38 | let w = super::constants::BlockExecutionWeight::get();
39 |
40 | // At least 100 µs.
41 | assert!(
42 | w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS,
43 | "Weight should be at least 100 µs."
44 | );
45 | // At most 50 ms.
46 | assert!(
47 | w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS,
48 | "Weight should be at most 50 ms."
49 | );
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/invarch/runtime/src/weights/extrinsic_weights.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) 2022 Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License.
17 |
18 | pub mod constants {
19 | use frame_support::{
20 | parameter_types,
21 | weights::{constants, Weight},
22 | };
23 |
24 | parameter_types! {
25 | /// Executing a NO-OP `System::remarks` Extrinsic.
26 | pub const ExtrinsicBaseWeight: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0);
27 | }
28 |
29 | #[cfg(test)]
30 | mod test_weights {
31 | use frame_support::weights::constants;
32 |
33 | /// Checks that the weight exists and is sane.
34 | // NOTE: If this test fails but you are sure that the generated values are fine,
35 | // you can delete it.
36 | #[test]
37 | fn sane() {
38 | let w = super::constants::ExtrinsicBaseWeight::get();
39 |
40 | // At least 10 µs.
41 | assert!(
42 | w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS,
43 | "Weight should be at least 10 µs."
44 | );
45 | // At most 1 ms.
46 | assert!(
47 | w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
48 | "Weight should be at most 1 ms."
49 | );
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/invarch/runtime/src/weights/mod.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) 2022 Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License.
17 |
18 | //! Expose the auto generated weight files.
19 |
20 | pub mod block_weights;
21 | pub mod extrinsic_weights;
22 | pub mod paritydb_weights;
23 | pub mod rocksdb_weights;
24 |
25 | pub use block_weights::constants::BlockExecutionWeight;
26 | pub use extrinsic_weights::constants::ExtrinsicBaseWeight;
27 | #[allow(unused_imports)]
28 | pub use paritydb_weights::constants::ParityDbWeight;
29 | pub use rocksdb_weights::constants::RocksDbWeight;
30 |
--------------------------------------------------------------------------------
/invarch/runtime/src/weights/paritydb_weights.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) 2022 Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License.
17 |
18 | pub mod constants {
19 | use frame_support::{
20 | parameter_types,
21 | weights::{constants, RuntimeDbWeight},
22 | };
23 |
24 | parameter_types! {
25 | /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights
26 | /// are available for brave runtime engineers who may want to try this out as default.
27 | pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight {
28 | read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
29 | write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
30 | };
31 | }
32 |
33 | #[cfg(test)]
34 | mod test_db_weights {
35 | use super::constants::ParityDbWeight as W;
36 | use frame_support::weights::constants;
37 |
38 | /// Checks that all weights exist and have sane values.
39 | // NOTE: If this test fails but you are sure that the generated values are fine,
40 | // you can delete it.
41 | #[test]
42 | fn sane() {
43 | // At least 1 µs.
44 | assert!(
45 | W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS,
46 | "Read weight should be at least 1 µs."
47 | );
48 | assert!(
49 | W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS,
50 | "Write weight should be at least 1 µs."
51 | );
52 | // At most 1 ms.
53 | assert!(
54 | W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
55 | "Read weight should be at most 1 ms."
56 | );
57 | assert!(
58 | W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
59 | "Write weight should be at most 1 ms."
60 | );
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/invarch/runtime/src/weights/rocksdb_weights.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) 2022 Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License.
17 |
18 | pub mod constants {
19 | use frame_support::{
20 | parameter_types,
21 | weights::{constants, RuntimeDbWeight},
22 | };
23 |
24 | parameter_types! {
25 | /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout
26 | /// the runtime.
27 | pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight {
28 | read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
29 | write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS,
30 | };
31 | }
32 |
33 | #[cfg(test)]
34 | mod test_db_weights {
35 | use super::constants::RocksDbWeight as W;
36 | use frame_support::weights::constants;
37 |
38 | /// Checks that all weights exist and have sane values.
39 | // NOTE: If this test fails but you are sure that the generated values are fine,
40 | // you can delete it.
41 | #[test]
42 | fn sane() {
43 | // At least 1 µs.
44 | assert!(
45 | W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS,
46 | "Read weight should be at least 1 µs."
47 | );
48 | assert!(
49 | W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS,
50 | "Write weight should be at least 1 µs."
51 | );
52 | // At most 1 ms.
53 | assert!(
54 | W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
55 | "Read weight should be at most 1 ms."
56 | );
57 | assert!(
58 | W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS,
59 | "Write weight should be at most 1 ms."
60 | );
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/invarch/rust-toolchain.toml:
--------------------------------------------------------------------------------
1 | [toolchain]
2 | channel = "nightly-2024-10-01"
3 | targets = ["wasm32-unknown-unknown"]
4 | components = [ "rustfmt", "rustc", "rust-std", "cargo", "clippy", "llvm-tools-preview", "rust-src"]
--------------------------------------------------------------------------------
/invarch/rustfmt.toml:
--------------------------------------------------------------------------------
1 | edition = "2021"
2 |
3 | imports_granularity = "Crate"
--------------------------------------------------------------------------------
/new-modified-construct-runtime/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "new-modified-construct-runtime"
3 | version = "4.0.0-dev"
4 | authors = ["Parity Technologies "]
5 | edition = "2021"
6 | license = "Apache-2.0"
7 | homepage = "https://substrate.io"
8 | repository = "https://github.com/paritytech/substrate/"
9 | description = "Proc macro of Support code for the runtime."
10 |
11 | [package.metadata.docs.rs]
12 | targets = ["x86_64-unknown-linux-gnu"]
13 |
14 | [lib]
15 | proc-macro = true
16 |
17 | [dependencies]
18 | derive-syn-parse = "0.2.0"
19 | Inflector = "0.11.4"
20 | cfg-expr = "0.15.5"
21 | itertools = "0.11.0"
22 | proc-macro2 = "1.0.64"
23 | quote = "1.0.33"
24 | syn = { version = "2.0.53", features = ["full", "parsing", "visit-mut"] }
25 | frame-support-procedural-tools = { path = "./tools" }
26 | macro_magic = { version = "0.5.1", features = ["proc_support"] }
27 | proc-macro-warning = { version = "1.0.0", default-features = false }
28 | expander = "2.0.0"
29 | sp-crypto-hashing = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407" }
30 |
31 | [dev-dependencies]
32 | regex = "1.10.2"
33 |
34 |
35 | [features]
36 | default = ["std"]
37 | std = ["sp-crypto-hashing/std"]
38 | no-metadata-docs = []
39 | # Generate impl-trait for tuples with the given number of tuples. Will be needed as the number of
40 | # pallets in a runtime grows. Does increase the compile time!
41 | tuples-96 = []
42 | tuples-128 = []
43 |
--------------------------------------------------------------------------------
/new-modified-construct-runtime/src/construct_runtime/expand/composite_helper.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License
17 |
18 | use crate::construct_runtime::parse::PalletPath;
19 | use proc_macro2::{Ident, TokenStream};
20 | use quote::quote;
21 |
22 | pub(crate) fn expand_conversion_fn(
23 | composite_name: &str,
24 | path: &PalletPath,
25 | instance: Option<&Ident>,
26 | variant_name: &Ident,
27 | ) -> TokenStream {
28 | let composite_name = quote::format_ident!("{}", composite_name);
29 | let runtime_composite_name = quote::format_ident!("Runtime{}", composite_name);
30 |
31 | if let Some(inst) = instance {
32 | quote! {
33 | impl From<#path::#composite_name<#path::#inst>> for #runtime_composite_name {
34 | fn from(hr: #path::#composite_name<#path::#inst>) -> Self {
35 | #runtime_composite_name::#variant_name(hr)
36 | }
37 | }
38 | }
39 | } else {
40 | quote! {
41 | impl From<#path::#composite_name> for #runtime_composite_name {
42 | fn from(hr: #path::#composite_name) -> Self {
43 | #runtime_composite_name::#variant_name(hr)
44 | }
45 | }
46 | }
47 | }
48 | }
49 |
50 | pub(crate) fn expand_variant(
51 | composite_name: &str,
52 | index: u8,
53 | path: &PalletPath,
54 | instance: Option<&Ident>,
55 | variant_name: &Ident,
56 | ) -> TokenStream {
57 | let composite_name = quote::format_ident!("{}", composite_name);
58 |
59 | if let Some(inst) = instance {
60 | quote! {
61 | #[codec(index = #index)]
62 | #variant_name(#path::#composite_name<#path::#inst>),
63 | }
64 | } else {
65 | quote! {
66 | #[codec(index = #index)]
67 | #variant_name(#path::#composite_name),
68 | }
69 | }
70 | }
71 |
72 | pub(crate) fn expand_variant_count(
73 | composite_name: &str,
74 | path: &PalletPath,
75 | instance: Option<&Ident>,
76 | ) -> TokenStream {
77 | let composite_name = quote::format_ident!("{}", composite_name);
78 |
79 | if let Some(inst) = instance {
80 | quote! {
81 | #path::#composite_name::<#path::#inst>::VARIANT_COUNT
82 | }
83 | } else {
84 | // Wrapped `<`..`>` means: use default type parameter for enum.
85 | //
86 | // This is used for pallets without instance support or pallets with instance support when
87 | // we don't specify instance:
88 | //
89 | // ```
90 | // pub struct Pallet{..}
91 | //
92 | // #[pallet::composite_enum]
93 | // pub enum HoldReason {..}
94 | //
95 | // Pallet1: pallet_x, // <- default type parameter
96 | // ```
97 | quote! {
98 | <#path::#composite_name>::VARIANT_COUNT
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/new-modified-construct-runtime/src/construct_runtime/expand/freeze_reason.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License
17 |
18 | use super::composite_helper;
19 | use crate::construct_runtime::Pallet;
20 | use proc_macro2::TokenStream;
21 | use quote::quote;
22 |
23 | pub fn expand_outer_freeze_reason(pallet_decls: &[Pallet], scrate: &TokenStream) -> TokenStream {
24 | let mut conversion_fns = Vec::new();
25 | let mut freeze_reason_variants = Vec::new();
26 | let mut freeze_reason_variants_count = Vec::new();
27 | for decl in pallet_decls {
28 | if let Some(_) = decl.find_part("FreezeReason") {
29 | let variant_name = &decl.name;
30 | let path = &decl.path;
31 | let index = decl.index;
32 | let instance = decl.instance.as_ref();
33 |
34 | conversion_fns.push(composite_helper::expand_conversion_fn(
35 | "FreezeReason",
36 | path,
37 | instance,
38 | variant_name,
39 | ));
40 |
41 | freeze_reason_variants.push(composite_helper::expand_variant(
42 | "FreezeReason",
43 | index,
44 | path,
45 | instance,
46 | variant_name,
47 | ));
48 |
49 | freeze_reason_variants_count.push(composite_helper::expand_variant_count(
50 | "FreezeReason",
51 | path,
52 | instance,
53 | ));
54 | }
55 | }
56 |
57 | quote! {
58 | /// A reason for placing a freeze on funds.
59 | #[derive(
60 | Copy, Clone, Eq, PartialEq,
61 | #scrate::__private::codec::Encode, #scrate::__private::codec::Decode, #scrate::__private::codec::MaxEncodedLen,
62 | #scrate::__private::scale_info::TypeInfo,
63 | #scrate::__private::RuntimeDebug,
64 | )]
65 | pub enum RuntimeFreezeReason {
66 | #( #freeze_reason_variants )*
67 | }
68 |
69 | impl #scrate::traits::VariantCount for RuntimeFreezeReason {
70 | const VARIANT_COUNT: u32 = 0 #( + #freeze_reason_variants_count )*;
71 | }
72 |
73 | #( #conversion_fns )*
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/new-modified-construct-runtime/src/construct_runtime/expand/hold_reason.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License
17 |
18 | use super::composite_helper;
19 | use crate::construct_runtime::Pallet;
20 | use proc_macro2::TokenStream;
21 | use quote::quote;
22 |
23 | pub fn expand_outer_hold_reason(pallet_decls: &[Pallet], scrate: &TokenStream) -> TokenStream {
24 | let mut conversion_fns = Vec::new();
25 | let mut hold_reason_variants = Vec::new();
26 | let mut hold_reason_variants_count = Vec::new();
27 | for decl in pallet_decls {
28 | if let Some(_) = decl.find_part("HoldReason") {
29 | let variant_name = &decl.name;
30 | let path = &decl.path;
31 | let index = decl.index;
32 | let instance = decl.instance.as_ref();
33 |
34 | conversion_fns.push(composite_helper::expand_conversion_fn(
35 | "HoldReason",
36 | path,
37 | instance,
38 | variant_name,
39 | ));
40 |
41 | hold_reason_variants.push(composite_helper::expand_variant(
42 | "HoldReason",
43 | index,
44 | path,
45 | instance,
46 | variant_name,
47 | ));
48 |
49 | hold_reason_variants_count.push(composite_helper::expand_variant_count(
50 | "HoldReason",
51 | path,
52 | instance,
53 | ));
54 | }
55 | }
56 |
57 | quote! {
58 | /// A reason for placing a hold on funds.
59 | #[derive(
60 | Copy, Clone, Eq, PartialEq,
61 | #scrate::__private::codec::Encode, #scrate::__private::codec::Decode, #scrate::__private::codec::MaxEncodedLen,
62 | #scrate::__private::scale_info::TypeInfo,
63 | #scrate::__private::RuntimeDebug,
64 | )]
65 | pub enum RuntimeHoldReason {
66 | #( #hold_reason_variants )*
67 | }
68 |
69 | impl #scrate::traits::VariantCount for RuntimeHoldReason {
70 | const VARIANT_COUNT: u32 = 0 #( + #hold_reason_variants_count )*;
71 | }
72 |
73 | #( #conversion_fns )*
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/new-modified-construct-runtime/src/construct_runtime/expand/lock_id.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License
17 |
18 | use super::composite_helper;
19 | use crate::construct_runtime::Pallet;
20 | use proc_macro2::TokenStream;
21 | use quote::quote;
22 |
23 | pub fn expand_outer_lock_id(pallet_decls: &[Pallet], scrate: &TokenStream) -> TokenStream {
24 | let mut conversion_fns = Vec::new();
25 | let mut lock_id_variants = Vec::new();
26 | for decl in pallet_decls {
27 | if let Some(_) = decl.find_part("LockId") {
28 | let variant_name = &decl.name;
29 | let path = &decl.path;
30 | let index = decl.index;
31 | let instance = decl.instance.as_ref();
32 |
33 | conversion_fns.push(composite_helper::expand_conversion_fn(
34 | "LockId",
35 | path,
36 | instance,
37 | variant_name,
38 | ));
39 |
40 | lock_id_variants.push(composite_helper::expand_variant(
41 | "LockId",
42 | index,
43 | path,
44 | instance,
45 | variant_name,
46 | ));
47 | }
48 | }
49 |
50 | quote! {
51 | /// An identifier for each lock placed on funds.
52 | #[derive(
53 | Copy, Clone, Eq, PartialEq,
54 | #scrate::__private::codec::Encode, #scrate::__private::codec::Decode, #scrate::__private::codec::MaxEncodedLen,
55 | #scrate::__private::scale_info::TypeInfo,
56 | #scrate::__private::RuntimeDebug,
57 | )]
58 | pub enum RuntimeLockId {
59 | #( #lock_id_variants )*
60 | }
61 |
62 | #( #conversion_fns )*
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/new-modified-construct-runtime/src/construct_runtime/expand/mod.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License
17 |
18 | mod call;
19 | pub mod composite_helper;
20 | mod config;
21 | mod freeze_reason;
22 | mod hold_reason;
23 | mod inherent;
24 | mod lock_id;
25 | mod metadata;
26 | mod origin;
27 | mod outer_enums;
28 | mod slash_reason;
29 | mod task;
30 | mod unsigned;
31 |
32 | pub use call::expand_outer_dispatch;
33 | pub use config::expand_outer_config;
34 | pub use freeze_reason::expand_outer_freeze_reason;
35 | pub use hold_reason::expand_outer_hold_reason;
36 | pub use inherent::expand_outer_inherent;
37 | pub use lock_id::expand_outer_lock_id;
38 | pub use metadata::expand_runtime_metadata;
39 | pub use origin::expand_outer_origin;
40 | pub use outer_enums::{expand_outer_enum, OuterEnumType};
41 | pub use slash_reason::expand_outer_slash_reason;
42 | pub use task::expand_outer_task;
43 | pub use unsigned::expand_outer_validate_unsigned;
44 |
--------------------------------------------------------------------------------
/new-modified-construct-runtime/src/construct_runtime/expand/slash_reason.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License
17 |
18 | use super::composite_helper;
19 | use crate::construct_runtime::Pallet;
20 | use proc_macro2::TokenStream;
21 | use quote::quote;
22 |
23 | pub fn expand_outer_slash_reason(pallet_decls: &[Pallet], scrate: &TokenStream) -> TokenStream {
24 | let mut conversion_fns = Vec::new();
25 | let mut slash_reason_variants = Vec::new();
26 | for decl in pallet_decls {
27 | if let Some(_) = decl.find_part("SlashReason") {
28 | let variant_name = &decl.name;
29 | let path = &decl.path;
30 | let index = decl.index;
31 | let instance = decl.instance.as_ref();
32 |
33 | conversion_fns.push(composite_helper::expand_conversion_fn(
34 | "SlashReason",
35 | path,
36 | instance,
37 | variant_name,
38 | ));
39 |
40 | slash_reason_variants.push(composite_helper::expand_variant(
41 | "SlashReason",
42 | index,
43 | path,
44 | instance,
45 | variant_name,
46 | ));
47 | }
48 | }
49 |
50 | quote! {
51 | /// A reason for slashing funds.
52 | #[derive(
53 | Copy, Clone, Eq, PartialEq,
54 | #scrate::__private::codec::Encode, #scrate::__private::codec::Decode, #scrate::__private::codec::MaxEncodedLen,
55 | #scrate::__private::scale_info::TypeInfo,
56 | #scrate::__private::RuntimeDebug,
57 | )]
58 | pub enum RuntimeSlashReason {
59 | #( #slash_reason_variants )*
60 | }
61 |
62 | #( #conversion_fns )*
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/new-modified-construct-runtime/src/construct_runtime/expand/task.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License
17 |
18 | use crate::construct_runtime::Pallet;
19 | use proc_macro2::{Ident, TokenStream as TokenStream2};
20 | use quote::quote;
21 |
22 | /// Expands aggregate `RuntimeTask` enum.
23 | pub fn expand_outer_task(
24 | runtime_name: &Ident,
25 | pallet_decls: &[Pallet],
26 | scrate: &TokenStream2,
27 | ) -> TokenStream2 {
28 | let mut from_impls = Vec::new();
29 | let mut task_variants = Vec::new();
30 | let mut variant_names = Vec::new();
31 | let mut task_paths = Vec::new();
32 | for decl in pallet_decls {
33 | if decl.find_part("Task").is_none() {
34 | continue;
35 | }
36 |
37 | let variant_name = &decl.name;
38 | let path = &decl.path;
39 | let index = decl.index;
40 |
41 | from_impls.push(quote! {
42 | impl From<#path::Task<#runtime_name>> for RuntimeTask {
43 | fn from(hr: #path::Task<#runtime_name>) -> Self {
44 | RuntimeTask::#variant_name(hr)
45 | }
46 | }
47 |
48 | impl TryInto<#path::Task<#runtime_name>> for RuntimeTask {
49 | type Error = ();
50 |
51 | fn try_into(self) -> Result<#path::Task<#runtime_name>, Self::Error> {
52 | match self {
53 | RuntimeTask::#variant_name(hr) => Ok(hr),
54 | _ => Err(()),
55 | }
56 | }
57 | }
58 | });
59 |
60 | task_variants.push(quote! {
61 | #[codec(index = #index)]
62 | #variant_name(#path::Task<#runtime_name>),
63 | });
64 |
65 | variant_names.push(quote!(#variant_name));
66 |
67 | task_paths.push(quote!(#path::Task));
68 | }
69 |
70 | let prelude = quote!(#scrate::traits::tasks::__private);
71 |
72 | const INCOMPLETE_MATCH_QED: &'static str =
73 | "cannot have an instantiated RuntimeTask without some Task variant in the runtime. QED";
74 |
75 | let output = quote! {
76 | /// An aggregation of all `Task` enums across all pallets included in the current runtime.
77 | #[derive(
78 | Clone, Eq, PartialEq,
79 | #scrate::__private::codec::Encode,
80 | #scrate::__private::codec::Decode,
81 | #scrate::__private::scale_info::TypeInfo,
82 | #scrate::__private::RuntimeDebug,
83 | )]
84 | pub enum RuntimeTask {
85 | #( #task_variants )*
86 | }
87 |
88 | #[automatically_derived]
89 | impl #scrate::traits::Task for RuntimeTask {
90 | type Enumeration = #prelude::IntoIter;
91 |
92 | fn is_valid(&self) -> bool {
93 | match self {
94 | #(RuntimeTask::#variant_names(val) => val.is_valid(),)*
95 | _ => unreachable!(#INCOMPLETE_MATCH_QED),
96 | }
97 | }
98 |
99 | fn run(&self) -> Result<(), #scrate::traits::tasks::__private::DispatchError> {
100 | match self {
101 | #(RuntimeTask::#variant_names(val) => val.run(),)*
102 | _ => unreachable!(#INCOMPLETE_MATCH_QED),
103 | }
104 | }
105 |
106 | fn weight(&self) -> #scrate::pallet_prelude::Weight {
107 | match self {
108 | #(RuntimeTask::#variant_names(val) => val.weight(),)*
109 | _ => unreachable!(#INCOMPLETE_MATCH_QED),
110 | }
111 | }
112 |
113 | fn task_index(&self) -> u32 {
114 | match self {
115 | #(RuntimeTask::#variant_names(val) => val.task_index(),)*
116 | _ => unreachable!(#INCOMPLETE_MATCH_QED),
117 | }
118 | }
119 |
120 | fn iter() -> Self::Enumeration {
121 | let mut all_tasks = Vec::new();
122 | #(all_tasks.extend(#task_paths::iter().map(RuntimeTask::from).collect::>());)*
123 | all_tasks.into_iter()
124 | }
125 | }
126 |
127 | #( #from_impls )*
128 | };
129 |
130 | output
131 | }
132 |
--------------------------------------------------------------------------------
/new-modified-construct-runtime/src/construct_runtime/expand/unsigned.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License
17 |
18 | use crate::construct_runtime::Pallet;
19 | use proc_macro2::TokenStream;
20 | use quote::quote;
21 | use std::str::FromStr;
22 | use syn::Ident;
23 |
24 | pub fn expand_outer_validate_unsigned(
25 | runtime: &Ident,
26 | pallet_decls: &[Pallet],
27 | scrate: &TokenStream,
28 | ) -> TokenStream {
29 | let mut pallet_names = Vec::new();
30 | let mut pallet_attrs = Vec::new();
31 | let mut query_validate_unsigned_part_macros = Vec::new();
32 |
33 | for pallet_decl in pallet_decls {
34 | if pallet_decl.exists_part("ValidateUnsigned") {
35 | let name = &pallet_decl.name;
36 | let path = &pallet_decl.path;
37 | let attr = pallet_decl
38 | .cfg_pattern
39 | .iter()
40 | .fold(TokenStream::new(), |acc, pattern| {
41 | let attr = TokenStream::from_str(&format!("#[cfg({})]", pattern.original()))
42 | .expect("was successfully parsed before; qed");
43 | quote! {
44 | #acc
45 | #attr
46 | }
47 | });
48 |
49 | pallet_names.push(name);
50 | pallet_attrs.push(attr);
51 | query_validate_unsigned_part_macros.push(quote! {
52 | #path::__substrate_validate_unsigned_check::is_validate_unsigned_part_defined!(#name);
53 | });
54 | }
55 | }
56 |
57 | quote! {
58 | #( #query_validate_unsigned_part_macros )*
59 |
60 | impl #scrate::unsigned::ValidateUnsigned for #runtime {
61 | type Call = RuntimeCall;
62 |
63 | fn pre_dispatch(call: &Self::Call) -> Result<(), #scrate::unsigned::TransactionValidityError> {
64 | #[allow(unreachable_patterns)]
65 | match call {
66 | #(
67 | #pallet_attrs
68 | RuntimeCall::#pallet_names(inner_call) => #pallet_names::pre_dispatch(inner_call),
69 | )*
70 | // pre-dispatch should not stop inherent extrinsics, validation should prevent
71 | // including arbitrary (non-inherent) extrinsics to blocks.
72 | _ => Ok(()),
73 | }
74 | }
75 |
76 | fn validate_unsigned(
77 | #[allow(unused_variables)]
78 | source: #scrate::unsigned::TransactionSource,
79 | call: &Self::Call,
80 | ) -> #scrate::unsigned::TransactionValidity {
81 | #[allow(unreachable_patterns)]
82 | match call {
83 | #(
84 | #pallet_attrs
85 | RuntimeCall::#pallet_names(inner_call) => #pallet_names::validate_unsigned(source, inner_call),
86 | )*
87 | _ => #scrate::unsigned::UnknownTransaction::NoUnsignedValidator.into(),
88 | }
89 | }
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/new-modified-construct-runtime/src/lib.rs:
--------------------------------------------------------------------------------
1 | // This file is part of Substrate.
2 |
3 | // Copyright (C) Parity Technologies (UK) Ltd.
4 | // SPDX-License-Identifier: Apache-2.0
5 |
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License.
17 |
18 | //! Proc macro of Support code for the runtime.
19 |
20 | #![recursion_limit = "512"]
21 | mod construct_runtime;
22 |
23 | use proc_macro::TokenStream;
24 |
25 | #[proc_macro]
26 | pub fn construct_runtime_modified(input: TokenStream) -> TokenStream {
27 | construct_runtime::construct_runtime_modified(input)
28 | }
29 |
--------------------------------------------------------------------------------
/new-modified-construct-runtime/tools/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "frame-support-procedural-tools"
3 | version = "4.0.0-dev"
4 | authors = ["Parity Technologies "]
5 | edition = "2021"
6 | license = "Apache-2.0"
7 | homepage = "https://substrate.io"
8 | repository = "https://github.com/paritytech/substrate/"
9 | description = "Proc macro helpers for procedural macros"
10 |
11 | [package.metadata.docs.rs]
12 | targets = ["x86_64-unknown-linux-gnu"]
13 |
14 | [dependencies]
15 | proc-macro-crate = "3.0.0"
16 | proc-macro2 = "1.0.64"
17 | quote = "1.0.33"
18 | syn = { version = "2.0.53", features = ["full", "visit", "extra-traits"] }
19 | frame-support-procedural-tools-derive = { version = "3.0.0", path = "./derive" }
20 |
--------------------------------------------------------------------------------
/new-modified-construct-runtime/tools/derive/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "frame-support-procedural-tools-derive"
3 | version = "3.0.0"
4 | authors = ["Parity Technologies "]
5 | edition = "2021"
6 | license = "Apache-2.0"
7 | homepage = "https://substrate.io"
8 | repository = "https://github.com/paritytech/polkadot-sdk.git/"
9 | description = "Use to derive parsing for parsing struct."
10 |
11 | [package.metadata.docs.rs]
12 | targets = ["x86_64-unknown-linux-gnu"]
13 |
14 | [lib]
15 | proc-macro = true
16 |
17 | [dependencies]
18 | proc-macro2 = "1.0.64"
19 | quote = { version = "1.0.33", features = ["proc-macro"] }
20 | syn = { version = "2.0.53", features = ["extra-traits", "full", "parsing", "proc-macro"] }
21 |
--------------------------------------------------------------------------------
/pallets/.gitignore:
--------------------------------------------------------------------------------
1 | # Generated by Cargo
2 | # will have compiled files and executables
3 | **/target/
4 |
5 | #local dependencies
6 | **/Cargo.lock
7 | .idea/vcs.xml
8 | .idea/workspace.xml
9 |
--------------------------------------------------------------------------------
/pallets/Cargo.toml:
--------------------------------------------------------------------------------
1 | [workspace]
2 | resolver = "2"
3 | members = [
4 | "pallet-checked-inflation",
5 | "pallet-dao-manager",
6 | "pallet-dao-staking",
7 | "primitives",
8 | # "pallet-rings",
9 | ]
10 |
11 | [workspace.package]
12 | authors = ["Abstracted Labs "]
13 | edition = "2021"
14 | homepage = "https://invarch.network"
15 | license = "GPL-3.0"
16 | repository = "https://github.com/Abstracted-Labs/InvArch/"
17 | version = '0.1.0-dev'
18 |
19 | [workspace.dependencies]
20 |
21 | pallet-checked-inflation = { path = "./pallet-checked-inflation", default-features = false }
22 | pallet-dao-manager = { path = "./pallet-dao-manager", default-features = false }
23 | pallet-dao-staking = { path = "./pallet-dao-staking", default-features = false }
24 | primitives = { path = "./primitives", package = "invarch-primitives", default-features = false }
25 |
26 | # crates.io dependencies
27 | codec = { package = "parity-scale-codec", version = "3.6.12", features = [
28 | "derive",
29 | ], default-features = false }
30 | log = { version = "0.4.20", default-features = false }
31 | num-traits = { version = "0.2", default-features = false }
32 | scale-info = { version = "2.10.0", default-features = false, features = [
33 | "derive",
34 | ] }
35 | serde = { version = "1.0.189", features = ["derive"] }
36 | smallvec = { version = "1.6.1" }
37 |
38 | # polkadot-sdk dependencies
39 | cumulus-primitives-core = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
40 | frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
41 | frame-support = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
42 | frame-system = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
43 | pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
44 | pallet-message-queue = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
45 | pallet-session = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
46 | pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
47 | pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
48 | sp-api = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
49 | sp-arithmetic = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
50 | sp-core = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
51 | sp-io = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
52 | sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
53 | sp-staking = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
54 | sp-std = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "stable2407", default-features = false }
55 | xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "stable2407" }
56 | xcm-builder = { package = "staging-xcm-builder", git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "stable2407" }
57 | xcm-executor = { package = "staging-xcm-executor", git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "stable2407" }
58 |
59 | # orml dev dependencies
60 | orml-asset-registry = { git = "https://github.com/Abstracted-Labs/open-runtime-module-library.git", default-features = false, branch = "stable2407" }
61 | orml-tokens = { package = "orml-tokens", git = "https://github.com/Abstracted-Labs/open-runtime-module-library.git", default-features = false, branch = "stable2407" }
62 | orml-tokens2 = { package = "orml-tokens", git = "https://github.com/Anny0nn/open-runtime-module-library.git", default-features = false, branch = "stable2407" }
63 | orml-traits = { package = "orml-traits", git = "https://github.com/Abstracted-Labs/open-runtime-module-library.git", default-features = false, branch = "stable2407" }
64 | orml-traits2 = { package = "orml-traits", git = "https://github.com/Anny0nn/open-runtime-module-library.git", default-features = false, branch = "stable2407" }
65 |
--------------------------------------------------------------------------------
/pallets/README.md:
--------------------------------------------------------------------------------
1 |
2 |

3 |
4 |
5 |
6 |
InvArch FRAME Pallet Library
7 |
8 |
9 | [](https://twitter.com/InvArchNetwork)
10 | [](https://discord.gg/invarch)
11 | [](https://t.me/InvArch)
12 | [](https://abstracted.notion.site/Knowledge-Hub-eec0071f36364d6aa8138f0004ac8d85)
13 |
14 | [](https://github.com/paritytech/polkadot-sdk/releases/tag/polkadot-v1.6.0)
15 | [](https://invarch.medium.com/)
16 | [](https://github.com/Abstracted-Labs/InvArch/blob/main/LICENSE)
17 | [](https://abstracted-labs.github.io/InvArch/)
18 |
19 |
20 |
21 | ---
22 |
23 | ## Intro
24 |
25 | This repository should contain the Polkadot SDK FRAME Pallets used in the InvArch blockchain, and reviews their relationships and functions. At the current stage, the goal of creating this document and repository is centered around getting feedback while we continue to write the code and develop InvArch. This is a WIP.
26 |
27 | Check out the [Knowledge Hub](https://abstracted.notion.site/Knowledge-Hub-eec0071f36364d6aa8138f0004ac8d85), it is the perfect place to dive into all things InvArch
28 |
29 | ## Overview
30 |
31 | InvArch is a blockchain network & cross-consensus operating system for DAOs. InvArch revolves around on multi-party ownership & computation with a focus on non-custodial asset management, intellectual property rights facilitation, & DAO operations.
32 |
33 | Currently, InvArch features a multichain multisignature solution & DAO staking protocol.
34 |
35 | ---
36 |
37 | # Pallet Library
38 |
39 | ## [DAO Manager](./pallet-dao-manager/)
40 | - The DAO Manager pallet is designed to manage advanced virtual multisigs (DAOs), OLD: internally referred to as cores.
41 | - [`Docs.rs`](https://abstracted-labs.github.io/InvArch/pallet_dao_manager/index.html)
42 | - Articles:
43 | - [`The SDK. (Old)`](https://invarch.medium.com/the-saturn-sdk-c46b4e40f46e)
44 | - [`The DAO Manager Protocol: The Core of the Creator Economy. (Old)`](https://invarch.medium.com/the-inv4-protocol-the-core-of-the-creator-economy-1af59fdbc943)
45 | - [`The Future of Multi-Party Ownership. (Old)`](https://invarch.medium.com/saturn-the-future-of-multi-party-ownership-ac7190f86a7b)
46 |
47 | ## [DAO Staking](./pallet-dao-staking)
48 | - Previously known as OCIF Staking.
49 | - The DAO Staking Staking Pallet is a pallet designed to facilitate staking towards DAOs within a blockchain network.
50 | - [`Docs.rs`](https://abstracted-labs.github.io/InvArch/pallet_dao_staking/index.html)
51 | - Articles:
52 | - [`The DAO Staking Protocol: Permissionless Funding for DAOs & Creators.`](https://invarch.medium.com/the-ocif-protocol-permissionless-funding-for-daos-creators-505aa18098f1)
53 | - DAO Staking is live on [InvArch](https://portal.invarch.network/staking) and [Tinkernet](https://www.tinker.network/staking).
54 |
55 | ## [Rings](./pallet-rings)
56 | - The Rings pallet provides a cross-consensus message (XCM) abstraction layer for DAO Manager.
57 | - [`Docs.rs`](https://abstracted-labs.github.io/InvArch/pallet_rings/index.html)
58 |
59 | ## [Checked Inflation](./pallet-checked-inflation)
60 | - The Checked Inflation pallet is designed to facilitate the inflationary aspect of a blockchain's economy.
61 | - [`Docs.rs`](https://abstracted-labs.github.io/InvArch/pallet_checked_inflation/index.html)
62 |
63 | ---
64 |
65 | ## How to contribute
66 |
67 | We need volunteer developers to help this idea become a reality!
68 |
69 | If you haven't already, come find us on the [#InvArch Discord](https://discord.gg/invarch). We want you working on things you're excited about!
70 |
71 | ### Submitting changes
72 |
73 | Please send a [GitHub Pull Request to InvArch](https://github.com/Abstracted-Labs/InvArch/pull/new) with a clear list of what you've done (read more about [pull requests](http://help.github.com/pull-requests/)). Please make sure all of your commits are atomic (one feature per commit).
74 |
75 | Always write a clear log message for your commits. One-line messages are fine for small changes, but bigger changes should look like this:
76 |
77 | $ git commit -m "A brief summary of the commit
78 | >
79 | > A paragraph describing what changed and its impact."
80 |
81 | Please make sure to update tests as appropriate.
82 |
83 |
84 | ### License
85 |
86 | [GPLv3.0](https://github.com/Abstracted-Labs/InvArch/blob/main/LICENSE)
87 |
--------------------------------------------------------------------------------
/pallets/pallet-checked-inflation/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = 'pallet-checked-inflation'
3 | description = 'FRAME pallet to IP staking'
4 | authors.workspace = true
5 | edition.workspace = true
6 | homepage.workspace = true
7 | license.workspace = true
8 | repository.workspace = true
9 | version.workspace = true
10 |
11 | [package.metadata.docs.rs]
12 | targets = ["x86_64-unknown-linux-gnu"]
13 |
14 | [dependencies]
15 | codec = { workspace = true }
16 | scale-info = { workspace = true }
17 | serde = { workspace = true, optional = true }
18 |
19 | frame-benchmarking = { workspace = true, optional = true }
20 | frame-support = { workspace = true }
21 | frame-system = { workspace = true }
22 | num-traits = { workspace = true }
23 | pallet-session = { workspace = true }
24 | sp-arithmetic = { workspace = true }
25 | sp-core = { workspace = true }
26 | sp-io = { workspace = true }
27 | sp-runtime = { workspace = true }
28 | sp-staking = { workspace = true }
29 | sp-std = { workspace = true }
30 |
31 | [dev-dependencies]
32 | pallet-balances = { workspace = true }
33 |
34 | [features]
35 | default = ["std"]
36 | std = [
37 | "codec/std",
38 | "frame-benchmarking?/std",
39 | "frame-support/std",
40 | "frame-system/std",
41 | "num-traits/std",
42 | "pallet-session/std",
43 | "scale-info/std",
44 | "serde",
45 | "sp-arithmetic/std",
46 | "sp-core/std",
47 | "sp-io/std",
48 | "sp-runtime/std",
49 | "sp-staking/std",
50 | "sp-std/std",
51 | "pallet-balances/std",
52 | ]
53 | runtime-benchmarks = [
54 | "frame-benchmarking/runtime-benchmarks",
55 | "frame-system/runtime-benchmarks",
56 | "sp-runtime/runtime-benchmarks",
57 | "frame-support/runtime-benchmarks",
58 | "sp-staking/runtime-benchmarks",
59 | ]
60 | try-runtime = ["frame-support/try-runtime", "sp-runtime/try-runtime"]
61 |
--------------------------------------------------------------------------------
/pallets/pallet-checked-inflation/README.md:
--------------------------------------------------------------------------------
1 | # Checked Inflation Pallet
2 |
3 | ## Overview
4 |
5 | The Checked Inflation Pallet is designed to facilitate the inflationary aspect of a blockchain's economy.
6 | It automatically mints new tokens at the start of every era, with the amount determined by a configurable inflation method.
7 | This functionality is crucial for maintaining a controlled expansion of the token supply, aligning with economic models or rewarding network participants.
8 |
9 | ### Key Features
10 |
11 | - **Configurable Inflation**: The amount and method of inflation can be tailored to suit the blockchain's economic model.
12 | - **Automatic Token Minting**: New tokens are minted automatically at the beginning of each era.
13 | - **Yearly and Era-Based Inflation**: Supports fixed yearly, fixed per era, or rate-based inflation calculations.
14 |
15 | ## Functionality
16 |
17 | The pallet's core functionality revolves around the `on_initialize` hook, which triggers at the beginning of each block.
18 | If conditions align (start of a new era or year), the pallet calculates the amount to mint based on the configured inflation method and mints the tokens.
19 |
20 | ## Inflation Methods
21 |
22 | Inflation can be configured in one of three ways, as defined in the `InflationMethod` enum:
23 |
24 | - **Rate**: A percentage of the current supply.
25 | - **FixedYearly**: A fixed amount distributed evenly across all eras in a year.
26 | - **FixedPerEra**: A fixed amount minted at the start of each era.
27 |
28 | The choice of method allows for flexibility in how the token supply expands over time, catering to different economic strategies.
29 |
30 | ## Dispatchable Functions
31 |
32 | ### `set_first_year_supply`
33 |
34 | Configures the initial token supply at the year's start, preparing the system for accurate inflation calculation.
35 |
36 | - **Access Control**: Root
37 |
38 | ### `halt_unhalt_pallet`
39 |
40 | Toggles the inflation process, allowing it to be halted or resumed based on network needs.
41 |
42 | - **Parameters**:
43 | - `halt`: A boolean indicating whether to halt (`true`) or resume (`false`) the inflation process.
44 | - **Access Control**: Root
45 |
46 |
47 | ## Events
48 |
49 | - **NewYear**: Marks the beginning of a new year, resetting era counts and updating the starting issuance for inflation calculations.
50 | - **NewEra**: Signifies the start of a new era, triggering token minting according to the configured inflation rate.
51 | - **InflationMinted**: Indicates that tokens have been minted due to inflation, detailing the amounts involved.
52 | - **OverInflationDetected**: Warns of excess token minting beyond expected amounts, prompting corrective measures.
53 | - **HaltChanged**: Reports changes in the inflation process's halt status.
54 |
55 | ## Errors
56 |
57 | - **NoHaltChange**: Triggered when attempting to change the halt status to its current value, indicating no action is needed.
58 |
59 | ## Conclusion
60 |
61 | The Checked Inflation Pallet offers a flexible and automated way to manage token supply expansion through inflation.
62 | By configuring the inflation method to match your blockchain's economic model, you can ensure a controlled and predictable increase in token supply,
63 | this pallet is an essential tool for managing network growth and stability through controlled inflation in response to evolving economic conditions,
64 | ensuring long-term sustainability.
65 |
66 |
--------------------------------------------------------------------------------
/pallets/pallet-checked-inflation/src/benchmarking.rs:
--------------------------------------------------------------------------------
1 | #![cfg(feature = "runtime-benchmarks")]
2 |
3 | use super::*;
4 | use frame_benchmarking::benchmarks;
5 | use frame_system::RawOrigin as SystemOrigin;
6 |
7 | fn assert_last_event(generic_event: ::RuntimeEvent) {
8 | frame_system::Pallet::::assert_last_event(generic_event.into());
9 | }
10 |
11 | benchmarks! {
12 | set_first_year_supply {
13 | }: _(SystemOrigin::Root)
14 |
15 | halt_unhalt_pallet {
16 | }: _(SystemOrigin::Root, true)
17 | verify {
18 | assert_last_event::(Event::::HaltChanged {
19 | is_halted: true
20 | }.into());
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/pallets/pallet-checked-inflation/src/inflation.rs:
--------------------------------------------------------------------------------
1 | //! Available inflation methods and resulting inflation amount generated per era.
2 | //!
3 | //! ## Overview
4 | //!
5 | //! This module contains the available inflation methods and the resulting inflation amount generated per era.
6 |
7 | use crate::{BalanceOf, Config};
8 | use codec::{Decode, Encode};
9 | use scale_info::TypeInfo;
10 | use sp_arithmetic::per_things::Perbill;
11 |
12 | /// Inflation methods.
13 | ///
14 | /// The inflation methods are used to determine the amount of inflation generated per era.
15 | #[derive(TypeInfo, Encode, Decode)]
16 | pub enum InflationMethod {
17 | /// The inflation is calculated as a percentage (`Perbill`) of the current supply.
18 | Rate(Perbill),
19 | /// The inflation is a fixed amount per year.
20 | FixedYearly(Balance),
21 | /// The inflation is a fixed amount per era.
22 | FixedPerEra(Balance),
23 | }
24 |
25 | /// Getter trait for the inflation amount to be minted in each era.
26 | pub trait GetInflation {
27 | /// Returns the inflation amount to be minted per era.
28 | fn get_inflation_args(&self, eras_per_year: u32, current_supply: BalanceOf) -> BalanceOf;
29 | }
30 |
31 | impl GetInflation for InflationMethod>
32 | where
33 | u32: Into>,
34 | {
35 | /// Returns the inflation amount to be minted per era based on the inflation method.
36 | fn get_inflation_args(&self, eras_per_year: u32, current_supply: BalanceOf) -> BalanceOf {
37 | match self {
38 | Self::Rate(rate) => (*rate * current_supply) / eras_per_year.into(),
39 | Self::FixedYearly(amount) => *amount / eras_per_year.into(),
40 | Self::FixedPerEra(amount) => *amount,
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/pallets/pallet-checked-inflation/src/mock.rs:
--------------------------------------------------------------------------------
1 | use super::*;
2 | use crate::inflation::InflationMethod;
3 | use core::convert::TryFrom;
4 | use frame_support::{
5 | derive_impl, parameter_types,
6 | traits::{fungible, ConstU128, ConstU32, ConstU64, Hooks, OnUnbalanced},
7 | };
8 | use pallet_balances::AccountData;
9 | use sp_core::H256;
10 | use sp_runtime::{traits::IdentityLookup, BuildStorage, Perbill};
11 |
12 | type Block = frame_system::mocking::MockBlock;
13 | type Balance = u128;
14 |
15 | type AccountId = u32;
16 | pub type NegativeImbalance =
17 | frame_support::traits::fungible::Credit<::AccountId, Balances>;
18 |
19 | pub const EXISTENTIAL_DEPOSIT: Balance = 1_000_000_000;
20 |
21 | pub const INFLATION_RECEIVER: AccountId = 0;
22 | pub const ALICE: AccountId = 1;
23 |
24 | frame_support::construct_runtime!(
25 | pub enum Test
26 | {
27 | System: frame_system,
28 | Balances: pallet_balances,
29 | CheckedInflation: pallet,
30 | }
31 | );
32 |
33 | #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
34 | impl frame_system::Config for Test {
35 | type RuntimeOrigin = RuntimeOrigin;
36 | type Nonce = u64;
37 | type Block = Block;
38 | type RuntimeCall = RuntimeCall;
39 | type Hash = H256;
40 | type Hashing = ::sp_runtime::traits::BlakeTwo256;
41 | type AccountId = AccountId;
42 | type Lookup = IdentityLookup;
43 | type RuntimeEvent = RuntimeEvent;
44 | type BlockHashCount = ConstU64<250>;
45 | type PalletInfo = PalletInfo;
46 | type AccountData = AccountData;
47 | type MaxConsumers = ConstU32<16>;
48 | }
49 |
50 | #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)]
51 | impl pallet_balances::Config for Test {
52 | type MaxLocks = ConstU32<50>;
53 | type Balance = Balance;
54 | type RuntimeEvent = RuntimeEvent;
55 | type ExistentialDeposit = ConstU128;
56 | type AccountStore = System;
57 | type MaxReserves = ConstU32<50>;
58 | type ReserveIdentifier = [u8; 8];
59 | }
60 |
61 | parameter_types! {
62 | pub const Inflation: InflationMethod> = InflationMethod::Rate(Perbill::from_percent(10));
63 | }
64 |
65 | pub struct DealWithInflation;
66 | impl OnUnbalanced for DealWithInflation {
67 | fn on_unbalanced(amount: NegativeImbalance) {
68 | >::resolve(&INFLATION_RECEIVER, amount)
69 | .expect("should work");
70 | }
71 | }
72 |
73 | pub const BLOCKS_PER_ERA: u64 = 4;
74 | pub const ERAS_PER_YEAR: u32 = 365;
75 |
76 | impl pallet::Config for Test {
77 | type BlocksPerEra = ConstU64;
78 | type Currency = Balances;
79 | type RuntimeEvent = RuntimeEvent;
80 | type ErasPerYear = ConstU32;
81 | type Inflation = Inflation;
82 | type DealWithInflation = DealWithInflation;
83 | type WeightInfo = weights::SubstrateWeight;
84 | }
85 |
86 | pub struct ExtBuilder;
87 |
88 | impl Default for ExtBuilder {
89 | fn default() -> Self {
90 | ExtBuilder
91 | }
92 | }
93 |
94 | pub const GENESIS_ISSUANCE: u128 = 11700000000000000000;
95 |
96 | impl ExtBuilder {
97 | pub fn build(self) -> sp_io::TestExternalities {
98 | let mut t = frame_system::GenesisConfig::::default()
99 | .build_storage()
100 | .unwrap();
101 |
102 | pallet_balances::GenesisConfig:: {
103 | balances: vec![(INFLATION_RECEIVER, GENESIS_ISSUANCE)],
104 | }
105 | .assimilate_storage(&mut t)
106 | .unwrap();
107 |
108 | let mut ext = sp_io::TestExternalities::new(t);
109 | ext.execute_with(|| System::set_block_number(0));
110 |
111 | // ext.execute_with(|| YearStartIssuance::::put(Balances::total_issuance()));
112 |
113 | // ext.execute_with(|| run_to_block(1));
114 |
115 | ext
116 | }
117 | }
118 |
119 | pub fn run_to_block(n: u64) {
120 | while System::block_number() < n {
121 | if System::block_number() > 1 {
122 | System::on_finalize(System::block_number());
123 | }
124 | System::set_block_number(System::block_number() + 1);
125 | System::on_initialize(System::block_number());
126 | CheckedInflation::on_initialize(System::block_number());
127 | }
128 | }
129 |
130 | pub fn run_to_next_era() {
131 | run_to_block(CheckedInflation::next_era_starting_block())
132 | }
133 |
134 | pub fn run_to_next_year() {
135 | // run_to_next_era();
136 |
137 | let current_era = CheckedInflation::current_era();
138 |
139 | run_to_block(System::block_number() + ((ERAS_PER_YEAR - current_era) as u64 * BLOCKS_PER_ERA));
140 |
141 | run_to_next_era();
142 | }
143 |
144 | pub fn run_to_half_year() {
145 | run_to_next_era();
146 |
147 | let current_era = CheckedInflation::current_era();
148 |
149 | run_to_block(
150 | System::block_number() + (((ERAS_PER_YEAR / 2) - current_era) as u64 * BLOCKS_PER_ERA),
151 | );
152 | }
153 |
--------------------------------------------------------------------------------
/pallets/pallet-checked-inflation/src/weights.rs:
--------------------------------------------------------------------------------
1 |
2 | //! Autogenerated weights for `pallet_checked_inflation`
3 | //!
4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 42.0.0
5 | //! DATE: 2024-10-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
6 | //! WORST CASE MAP SIZE: `1000000`
7 | //! HOSTNAME: `franciscos-mbp.lan`, CPU: ``
8 | //! WASM-EXECUTION: `Compiled`, CHAIN: `None`, DB CACHE: `1024`
9 |
10 | // Executed Command:
11 | // ./target/release/invarch-collator
12 | // benchmark
13 | // pallet
14 | // --runtime
15 | // ./target/release/wbuild/invarch-runtime/invarch_runtime.compact.compressed.wasm
16 | // --wasm-execution=compiled
17 | // --pallet=pallet_checked_inflation
18 | // --extrinsic=
19 | // --steps
20 | // 50
21 | // --repeat
22 | // 20
23 | // --output=../pallets/pallet-checked-inflation/src/weights.rs
24 | // --template=../weights-template.hbs
25 |
26 | #![cfg_attr(rustfmt, rustfmt_skip)]
27 | #![allow(unused_parens)]
28 | #![allow(unused_imports)]
29 | #![allow(missing_docs)]
30 |
31 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
32 | use core::marker::PhantomData;
33 |
34 | /// Weight functions needed for `pallet_checked_inflation`.
35 | pub trait WeightInfo {
36 | fn set_first_year_supply() -> Weight;
37 | fn halt_unhalt_pallet() -> Weight;
38 | }
39 |
40 | /// Weights for `pallet_checked_inflation` using the Substrate node and recommended hardware.
41 | pub struct SubstrateWeight(PhantomData);
42 | impl WeightInfo for SubstrateWeight {
43 | /// Storage: `CheckedInflation::YearStartIssuance` (r:0 w:1)
44 | /// Proof: `CheckedInflation::YearStartIssuance` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`)
45 | fn set_first_year_supply() -> Weight {
46 | // Proof Size summary in bytes:
47 | // Measured: `0`
48 | // Estimated: `0`
49 | // Minimum execution time: 1_000_000 picoseconds.
50 | Weight::from_parts(2_000_000, 0)
51 | .saturating_add(T::DbWeight::get().writes(1_u64))
52 | }
53 | /// Storage: `CheckedInflation::Halted` (r:1 w:1)
54 | /// Proof: `CheckedInflation::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`)
55 | fn halt_unhalt_pallet() -> Weight {
56 | // Proof Size summary in bytes:
57 | // Measured: `0`
58 | // Estimated: `1486`
59 | // Minimum execution time: 3_000_000 picoseconds.
60 | Weight::from_parts(4_000_000, 1486)
61 | .saturating_add(T::DbWeight::get().reads(1_u64))
62 | .saturating_add(T::DbWeight::get().writes(1_u64))
63 | }
64 | }
65 |
66 | // For backwards compatibility and tests.
67 | impl WeightInfo for () {
68 | /// Storage: `CheckedInflation::YearStartIssuance` (r:0 w:1)
69 | /// Proof: `CheckedInflation::YearStartIssuance` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`)
70 | fn set_first_year_supply() -> Weight {
71 | // Proof Size summary in bytes:
72 | // Measured: `0`
73 | // Estimated: `0`
74 | // Minimum execution time: 1_000_000 picoseconds.
75 | Weight::from_parts(2_000_000, 0)
76 | .saturating_add(RocksDbWeight::get().writes(1_u64))
77 | }
78 | /// Storage: `CheckedInflation::Halted` (r:1 w:1)
79 | /// Proof: `CheckedInflation::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`)
80 | fn halt_unhalt_pallet() -> Weight {
81 | // Proof Size summary in bytes:
82 | // Measured: `0`
83 | // Estimated: `1486`
84 | // Minimum execution time: 3_000_000 picoseconds.
85 | Weight::from_parts(4_000_000, 1486)
86 | .saturating_add(RocksDbWeight::get().reads(1_u64))
87 | .saturating_add(RocksDbWeight::get().writes(1_u64))
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/pallets/pallet-dao-manager/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = 'pallet-dao-manager'
3 | description = ''
4 | authors.workspace = true
5 | edition.workspace = true
6 | homepage.workspace = true
7 | license.workspace = true
8 | repository.workspace = true
9 | version.workspace = true
10 |
11 | [dependencies]
12 | codec = { workspace = true, default-features = false, features = [
13 | "derive",
14 | "max-encoded-len",
15 | ] }
16 | frame-support = { workspace = true }
17 | log = { workspace = true }
18 | scale-info = { workspace = true }
19 | serde = { workspace = true, optional = true }
20 | smallvec = { workspace = true }
21 | sp-arithmetic = { workspace = true }
22 | sp-runtime = { workspace = true }
23 | sp-std = { workspace = true }
24 |
25 | # InvArch dependencies
26 | primitives = { workspace = true }
27 |
28 | frame-benchmarking = { workspace = true, optional = true }
29 | frame-system = { workspace = true } # frame-benchmarking requires system
30 | pallet-balances = { workspace = true }
31 | sp-api = { workspace = true }
32 | sp-core = { workspace = true }
33 | sp-io = { workspace = true }
34 |
35 |
36 | orml-tokens2 = { workspace = true }
37 | xcm = { workspace = true }
38 |
39 | [dev-dependencies]
40 |
41 | orml-asset-registry = { workspace = true }
42 | orml-tokens = { workspace = true }
43 | orml-traits = { workspace = true }
44 | orml-traits2 = { workspace = true }
45 |
46 |
47 | [features]
48 | default = ["std"]
49 | std = [
50 | "codec/std",
51 | "frame-benchmarking?/std",
52 | "frame-support/std",
53 | "frame-system/std",
54 | "orml-asset-registry/std",
55 | "orml-tokens/std",
56 | "orml-tokens2/std",
57 | "orml-traits/std",
58 | "orml-traits2/std",
59 | "pallet-balances/std",
60 | "primitives/std",
61 | "scale-info/std",
62 | "serde",
63 | "sp-api/std",
64 | "sp-arithmetic/std",
65 | "sp-core/std",
66 | "sp-io/std",
67 | "sp-runtime/std",
68 | "sp-std/std",
69 | "xcm/std",
70 | "log/std",
71 | ]
72 | runtime-benchmarks = [
73 | "frame-benchmarking/runtime-benchmarks",
74 | "frame-support/runtime-benchmarks",
75 | "frame-system/runtime-benchmarks",
76 | "sp-runtime/runtime-benchmarks",
77 | ]
78 | try-runtime = ["frame-support/try-runtime", "sp-runtime/try-runtime"]
79 |
--------------------------------------------------------------------------------
/pallets/pallet-dao-manager/README.md:
--------------------------------------------------------------------------------
1 | # DAO Manager Pallet
2 |
3 | ## Introduction
4 |
5 | The DAO Manager pallet is designed to manage advanced virtual multisigs, internally referred to as DAOs. It provides the functionality to create DAOs, mint and burn the DAO's voting tokens, and manage multisig proposals. This pallet is a comprehensive solution for decentralized decision-making processes, allowing for flexible and secure management of multisig operations.
6 |
7 | ## Features
8 |
9 | - **DAO Creation**: Establish new DAOs with customizable parameters, including metadata, voting thresholds, and token freeze state.
10 | - **Token Management**: Mint and burn the DAO's voting tokens to manage the voting power within the DAO.
11 | - **Multisig Proposals**: Create, vote on, and cancel multisig proposals. Proposals automatically execute if they meet the execution threshold requirements.
12 | - **Vote Management**: Members can vote on proposals, withdraw their votes, and influence the outcome of decisions.
13 | - **Parameter Adjustment**: DAO parameters, such as voting thresholds and token freeze state, can be dynamically adjusted by DAO origins.
14 |
15 | ## Functionality Overview
16 |
17 | ### DAO Management
18 |
19 | - `create_dao`: Initialize a new DAO with specific parameters and distribute initial voting tokens to the creator.
20 | - `set_parameters`: Modify DAO parameters, including voting thresholds, metadata, and token freeze state.
21 |
22 | ### Token Operations
23 |
24 | - `token_mint`: Mint the DAO's voting tokens to a specified target, increasing their voting power within the DAO.
25 | - `token_burn`: Burn the DAO's voting tokens from a specified target, decreasing their voting power.
26 |
27 | ### Multisig Operations
28 |
29 | - `operate_multisig`: Submit a new multisig proposal. If the proposal meets execution thresholds, it is automatically executed.
30 | - `vote_multisig`: Cast a vote on an existing multisig proposal. Proposals execute automatically if they meet threshold requirements after the vote.
31 | - `withdraw_vote_multisig`: Withdraw a previously cast vote from a multisig proposal.
32 | - `cancel_multisig_proposal`: Cancel an existing multisig proposal. This action can only be performed by a DAO origin.
33 |
34 | ### Utility Functions
35 |
36 | - `DaoAccountDerivation`: Derive consistent DAO AccountIds across parachains for seamless interaction.
37 | - `DaoLookup`: Custom account lookup implementation for converting DaoIds to AccountIds.
38 | - `FeeAsset`: Define the asset used by the multisig for paying transaction fees.
39 | - `MultisigFeeHandler`: Manage fee payments for multisig operations, supporting both native and non-native assets.
40 |
41 | ## Usage
42 |
43 | To utilize the DAO Manager pallet, users must first create a DAO and receive initial voting tokens. DAOs can propose actions, vote on proposals, and execute decisions based on the collective voting power of their members. The pallet's flexible design supports a wide range of multisig use cases, from simple governance decisions to complex, conditional executions.
--------------------------------------------------------------------------------
/pallets/pallet-dao-manager/src/account_derivation.rs:
--------------------------------------------------------------------------------
1 | //! Dao Account Derivation.
2 | //!
3 | //! ## Overview
4 | //!
5 | //! This module defines a method for generating account addresses, and how it's implemented within this
6 | //! pallet. We use a custom derivation scheme to ensure that when a multisig is created, its AccountId
7 | //! remains consistent across different parachains, promoting seamless interaction.
8 | //!
9 | //! ### The module contains:
10 | //! - `DaoAccountDerivation` trait: The interface for our derivation method.
11 | //! - Pallet implementation: The specific logic used to derive AccountIds.
12 |
13 | use crate::{Config, Pallet};
14 | use codec::{Compact, Encode};
15 | use frame_support::traits::Get;
16 | use sp_io::hashing::blake2_256;
17 | use xcm::v4::{BodyId, BodyPart, Junction, Junctions};
18 | /// Trait providing the XCM location and the derived account of a dao.
19 | pub trait DaoAccountDerivation {
20 | /// Derives the dao's AccountId.
21 | fn derive_dao_account(dao_id: T::DaoId) -> T::AccountId;
22 | /// Specifies a dao's location.
23 | fn dao_location(dao_id: T::DaoId) -> Junctions;
24 | }
25 |
26 | impl DaoAccountDerivation for Pallet
27 | where
28 | T::AccountId: From<[u8; 32]>,
29 | {
30 | /// HashedDescription of the dao location from the perspective of a sibling chain.
31 | /// This derivation allows the local account address to match the account address in other parachains.
32 | /// Reference: https://github.com/paritytech/polkadot-sdk/blob/master/polkadot/xcm/xcm-builder/src/location_conversion.rs
33 | fn derive_dao_account(dao_id: T::DaoId) -> T::AccountId {
34 | blake2_256(
35 | &(
36 | b"SiblingChain",
37 | Compact::::from(T::ParaId::get()),
38 | (b"Body", BodyId::Index(dao_id.into()), BodyPart::Voice).encode(),
39 | )
40 | .encode(),
41 | )
42 | .into()
43 | }
44 | /// DAO location is defined as a plurality within the parachain.
45 | fn dao_location(dao_id: T::DaoId) -> Junctions {
46 | Junctions::X2(
47 | [
48 | Junction::Parachain(T::ParaId::get()),
49 | Junction::Plurality {
50 | id: BodyId::Index(dao_id.into()),
51 | part: BodyPart::Voice,
52 | },
53 | ]
54 | .into(),
55 | )
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/pallets/pallet-dao-manager/src/dispatch.rs:
--------------------------------------------------------------------------------
1 | //! Dispatches calls internally, charging fees to the multisig account.
2 | //!
3 | //! ## Overview
4 | //!
5 | //! This module employs a custom `MultisigInternalOrigin` to ensure calls originate
6 | //! from the multisig account itself, automating fee payments. The `dispatch_call` function
7 | //! includes pre and post dispatch handling for streamlined fee management within the multisig context.
8 |
9 | use crate::{
10 | fee_handling::{FeeAsset, MultisigFeeHandler},
11 | origin::{DaoOrigin, MultisigInternalOrigin},
12 | Config, Error,
13 | };
14 | use frame_support::{dispatch::GetDispatchInfo, pallet_prelude::*};
15 |
16 | use sp_runtime::traits::Dispatchable;
17 |
18 | /// Dispatch a call executing pre/post dispatch for proper fee handling.
19 | pub fn dispatch_call(
20 | dao_id: ::DaoId,
21 | fee_asset: &FeeAsset,
22 | call: ::RuntimeCall,
23 | ) -> DispatchResultWithPostInfo
24 | where
25 | T::AccountId: From<[u8; 32]>,
26 | {
27 | // Create new custom origin as the multisig.
28 | let internal_origin = MultisigInternalOrigin::new(dao_id);
29 | let multisig_account = internal_origin.to_account_id();
30 | let origin = DaoOrigin::Multisig(internal_origin).into();
31 |
32 | let info = call.get_dispatch_info();
33 | let len = call.encode().len();
34 |
35 | // Execute pre dispatch using the multisig account instead of the extrinsic caller.
36 | let pre = >::pre_dispatch(
37 | fee_asset,
38 | &multisig_account,
39 | &call,
40 | &info,
41 | len,
42 | )
43 | .map_err(|_| Error::::CallFeePaymentFailed)?;
44 |
45 | let dispatch_result = call.dispatch(origin);
46 |
47 | let post = match dispatch_result {
48 | Ok(p) => p,
49 | Err(e) => e.post_info,
50 | };
51 |
52 | >::post_dispatch(
53 | fee_asset,
54 | Some(pre),
55 | &info,
56 | &post,
57 | len,
58 | &dispatch_result.map(|_| ()).map_err(|e| e.error),
59 | )
60 | .map_err(|_| Error::::CallFeePaymentFailed)?;
61 |
62 | dispatch_result
63 | }
64 |
--------------------------------------------------------------------------------
/pallets/pallet-dao-manager/src/fee_handling.rs:
--------------------------------------------------------------------------------
1 | //! MultisigFeeHandler trait.
2 | //!
3 | //! ## Overview
4 | //!
5 | //! Defines how transaction fees are charged to the multisig account.
6 | //! This trait requires proper runtime implementation to allow the usage of native or non-native assets.
7 |
8 | use crate::Config;
9 | use codec::{Decode, Encode, MaxEncodedLen};
10 | use frame_support::{
11 | traits::{fungible::Credit, fungibles::Credit as Credits},
12 | unsigned::TransactionValidityError,
13 | };
14 | use scale_info::TypeInfo;
15 | use sp_runtime::{
16 | traits::{DispatchInfoOf, PostDispatchInfoOf},
17 | DispatchResult,
18 | };
19 |
20 | /// Represents the asset to be used by the multisig for paying transaction fees.
21 | ///
22 | /// This enum defines the assets that can be used to pay for transaction fees.
23 | #[derive(Clone, TypeInfo, Encode, Decode, MaxEncodedLen, Debug, PartialEq, Eq)]
24 | pub enum FeeAsset {
25 | Native,
26 | Relay,
27 | }
28 |
29 | /// Represents a potential negative asset balance incurred during fee payment operations
30 | /// within a multisig context.
31 | ///
32 | /// This enum handles imbalances in either the native token or
33 | /// a relay chain asset used for fees.
34 | ///
35 | /// - `Native(NativeNegativeImbalance)`: Indicates a deficit balance in the chain's native asset.
36 | /// - `Relay(RelayNegativeImbalance)`: Indicates a deficit balance in an asset originating on the relay chain.
37 | ///
38 | /// This enum plays a role in resolving deficit balances in the `MultisigFeeHandler` trait.
39 | pub enum FeeAssetNegativeImbalance {
40 | Native(NativeNegativeImbalance),
41 | Relay(RelayNegativeImbalance),
42 | }
43 |
44 | /// Fee handler trait.
45 | ///
46 | /// This should be implemented properly in the runtime to account for native and non-native assets.
47 | pub trait MultisigFeeHandler {
48 | /// Type returned by `pre_dispatch` - implementation dependent.
49 | type Pre;
50 |
51 | /// Checks if the fee can be paid using the selected asset.
52 | fn pre_dispatch(
53 | asset: &FeeAsset,
54 | who: &T::AccountId,
55 | call: &::RuntimeCall,
56 | info: &DispatchInfoOf<::RuntimeCall>,
57 | len: usize,
58 | ) -> Result;
59 |
60 | /// Charges the call dispatching fee from the multisig directly.
61 | fn post_dispatch(
62 | asset: &FeeAsset,
63 | pre: Option,
64 | info: &DispatchInfoOf<::RuntimeCall>,
65 | post_info: &PostDispatchInfoOf<::RuntimeCall>,
66 | len: usize,
67 | result: &DispatchResult,
68 | ) -> Result<(), TransactionValidityError>;
69 |
70 | /// Charges the fee for creating the dao (multisig).
71 | fn handle_creation_fee(
72 | imbalance: FeeAssetNegativeImbalance<
73 | Credit,
74 | Credits,
75 | >,
76 | );
77 | }
78 |
--------------------------------------------------------------------------------
/pallets/pallet-dao-manager/src/lookup.rs:
--------------------------------------------------------------------------------
1 | //! Custom account lookup implementation.
2 | //!
3 | //! ## Overview
4 | //!
5 | //!
6 | //! This module implements the [`StaticLookup`] trait allowing for convenient lookup of a DAO's
7 | //! AccountId from its DaoId.
8 | //! This implementation abstracts on top of two lower level functions:
9 | //! - `lookup_dao`: Used for accessing the storage and retrieving a DAO's AccountId.
10 | //! - `lookup_address`: Used for converting from a `MultiAddress::Index` that contains a DaoId to this DAO's AccountId.
11 |
12 | use crate::{Config, CoreByAccount, CoreStorage, Pallet};
13 | use core::marker::PhantomData;
14 | use frame_support::error::LookupError;
15 | use sp_runtime::{traits::StaticLookup, MultiAddress};
16 |
17 | impl Pallet {
18 | /// Queries `CoreStorage` to retrieve the AccountId of a DAO.
19 | pub fn lookup_dao(dao_id: T::DaoId) -> Option {
20 | CoreStorage::::get(dao_id).map(|dao| dao.account)
21 | }
22 |
23 | /// Matches `MultiAddress` to allow for a `MultiAddress::Index` containing a DaoId to be converted
24 | /// to it's derived AccountId.
25 | pub fn lookup_address(a: MultiAddress) -> Option {
26 | match a {
27 | MultiAddress::Id(i) => Some(i),
28 | MultiAddress::Index(i) => Self::lookup_dao(i),
29 | _ => None,
30 | }
31 | }
32 | }
33 |
34 | /// StaticLookup implementor using MultiAddress::Index for looking up DAOs by id.
35 | pub struct DaoLookup(PhantomData);
36 |
37 | impl StaticLookup for DaoLookup {
38 | type Source = MultiAddress;
39 | type Target = T::AccountId;
40 |
41 | fn lookup(a: Self::Source) -> Result {
42 | Pallet::::lookup_address(a).ok_or(LookupError)
43 | }
44 |
45 | fn unlookup(a: Self::Target) -> Self::Source {
46 | match CoreByAccount::::get(&a) {
47 | Some(dao_id) => MultiAddress::Index(dao_id),
48 | None => MultiAddress::Id(a),
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/pallets/pallet-dao-manager/src/migrations.rs:
--------------------------------------------------------------------------------
1 | use super::*;
2 | use frame_support::{
3 | dispatch::GetStorageVersion,
4 | traits::{Get, OnRuntimeUpgrade},
5 | weights::Weight,
6 | };
7 | use log::{info, warn};
8 |
9 | pub mod v1 {
10 |
11 | use super::*;
12 |
13 | pub fn clear_storages() {
14 | let _ = frame_support::migration::clear_storage_prefix(b"INV4", b"", b"", None, None);
15 | }
16 |
17 | pub struct MigrateToV1(sp_std::marker::PhantomData);
18 | impl OnRuntimeUpgrade for MigrateToV1 {
19 | #[cfg(feature = "try-runtime")]
20 | fn pre_upgrade() -> Result, &'static str> {
21 | frame_support::ensure!(
22 | Pallet::::current_storage_version() == 0,
23 | "Required v0 before upgrading to v1"
24 | );
25 |
26 | Ok(Default::default())
27 | }
28 |
29 | fn on_runtime_upgrade() -> Weight {
30 | let current = Pallet::::current_storage_version();
31 |
32 | if current == 1 {
33 | clear_storages::();
34 |
35 | current.put::>();
36 |
37 | info!("v1 applied successfully");
38 | T::DbWeight::get().reads_writes(0, 1)
39 | } else {
40 | warn!("Skipping v1, should be removed");
41 | T::DbWeight::get().reads(1)
42 | }
43 | }
44 |
45 | #[cfg(feature = "try-runtime")]
46 | fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), &'static str> {
47 | frame_support::ensure!(
48 | Pallet::::on_chain_storage_version() == 1,
49 | "v1 not applied"
50 | );
51 |
52 | Ok(())
53 | }
54 | }
55 | }
56 |
57 | pub mod v2 {
58 | use super::*;
59 | use codec::{Decode, Encode};
60 | use frame_support::{
61 | pallet_prelude::ValueQuery, storage_alias, Blake2_128Concat, Twox64Concat,
62 | };
63 |
64 | #[derive(Default, Encode, Decode)]
65 | pub struct AccountData {
66 | pub free: Balance,
67 | pub reserved: Balance,
68 | pub frozen: Balance,
69 | }
70 |
71 | #[storage_alias]
72 | pub type Accounts =
73 | StorageDoubleMap<
74 | orml_tokens2::Pallet,
75 | Blake2_128Concat,
76 | ::AccountId,
77 | Twox64Concat,
78 | ::DaoId,
79 | AccountData,
80 | ValueQuery,
81 | >;
82 |
83 | pub fn fill_dao_owners() {
84 | Accounts::::iter_keys()
85 | .for_each(|(member, dao_id)| CoreMembers::::insert(dao_id, member, ()));
86 | }
87 |
88 | pub struct MigrateToV2(sp_std::marker::PhantomData);
89 | impl OnRuntimeUpgrade for MigrateToV2 {
90 | #[cfg(feature = "try-runtime")]
91 | fn pre_upgrade() -> Result, &'static str> {
92 | frame_support::ensure!(
93 | Pallet::::current_storage_version() == 1,
94 | "Required v1 before upgrading to v2"
95 | );
96 |
97 | Ok(Default::default())
98 | }
99 |
100 | fn on_runtime_upgrade() -> Weight {
101 | let current = Pallet::::current_storage_version();
102 |
103 | if current == 2 {
104 | fill_dao_owners::();
105 |
106 | current.put::>();
107 |
108 | info!("v2 applied successfully");
109 | T::DbWeight::get().reads_writes(0, 1)
110 | } else {
111 | warn!("Skipping v1, should be removed");
112 | T::DbWeight::get().reads(1)
113 | }
114 | }
115 |
116 | #[cfg(feature = "try-runtime")]
117 | fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), &'static str> {
118 | frame_support::ensure!(
119 | Pallet::::on_chain_storage_version() == 2,
120 | "v2 not applied"
121 | );
122 |
123 | Ok(())
124 | }
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/pallets/pallet-dao-manager/src/origin.rs:
--------------------------------------------------------------------------------
1 | //! Custom Multisig Origin (`DaoOrigin`).
2 | //!
3 | //! ## Overview
4 | //!
5 | //! This module introduces a custom origin [`DaoOrigin`], enabling self-management for DAOs and
6 | //! includes the [`ensure_multisig`] function to guarantee calls genuinely come from the multisig account.
7 | //! This is an efficient approach considering that converting from DaoId to AccountId is a one-way operation,
8 | //! so the origin brings the DaoId to dispatchable calls.
9 | //! Converting to a `RawOrigin::Signed` origin for other calls is handled in the runtime.
10 |
11 | use crate::{
12 | account_derivation::DaoAccountDerivation,
13 | pallet::{self, Origin, Pallet},
14 | Config,
15 | };
16 | use codec::{Decode, Encode, MaxEncodedLen};
17 | use frame_support::{error::BadOrigin, pallet_prelude::RuntimeDebug};
18 | use scale_info::TypeInfo;
19 |
20 | /// Origin representing a dao by its id.
21 | #[derive(PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, Clone, RuntimeDebug)]
22 | pub enum DaoOrigin {
23 | Multisig(MultisigInternalOrigin),
24 | }
25 |
26 | /// Internal origin for identifying the multisig DaoId.
27 | #[derive(PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, Clone, RuntimeDebug)]
28 | pub struct MultisigInternalOrigin {
29 | pub id: T::DaoId,
30 | }
31 |
32 | impl MultisigInternalOrigin
33 | where
34 | T::AccountId: From<[u8; 32]>,
35 | {
36 | pub fn new(id: T::DaoId) -> Self {
37 | Self { id }
38 | }
39 |
40 | pub fn to_account_id(&self) -> T::AccountId {
41 | Pallet::::derive_dao_account(self.id)
42 | }
43 | }
44 |
45 | /// Ensures the passed origin is a multisig, returning [`MultisigInternalOrigin`].
46 | pub fn ensure_multisig(
47 | o: OuterOrigin,
48 | ) -> Result, BadOrigin>
49 | where
50 | OuterOrigin: Into, OuterOrigin>>,
51 | {
52 | match o.into() {
53 | Ok(Origin::::Multisig(internal)) => Ok(internal),
54 | _ => Err(BadOrigin),
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/pallets/pallet-dao-staking/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = 'pallet-dao-staking'
3 | description = 'FRAME pallet for DAO staking'
4 | authors.workspace = true
5 | edition.workspace = true
6 | homepage.workspace = true
7 | license.workspace = true
8 | repository.workspace = true
9 | version.workspace = true
10 |
11 | [package.metadata.docs.rs]
12 | targets = ["x86_64-unknown-linux-gnu"]
13 |
14 | [dependencies]
15 | codec = { workspace = true }
16 | log = { workspace = true }
17 | scale-info = { workspace = true }
18 | serde = { workspace = true, optional = true }
19 |
20 | frame-support = { workspace = true }
21 | frame-system = { workspace = true }
22 | num-traits = { workspace = true }
23 | pallet-balances = { workspace = true, optional = true }
24 | pallet-message-queue = { workspace = true }
25 | pallet-session = { workspace = true }
26 | pallet-timestamp = { workspace = true, optional = true }
27 | sp-arithmetic = { workspace = true }
28 | sp-core = { workspace = true }
29 | sp-io = { workspace = true }
30 | sp-runtime = { workspace = true }
31 | sp-staking = { workspace = true }
32 | sp-std = { workspace = true }
33 |
34 | pallet-dao-manager = { workspace = true }
35 |
36 | cumulus-primitives-core = { workspace = true }
37 | frame-benchmarking = { workspace = true, optional = true }
38 |
39 | [dev-dependencies]
40 | orml-tokens = { workspace = true }
41 | orml-traits = { workspace = true }
42 | xcm = { workspace = true }
43 |
44 | [features]
45 | default = ["std"]
46 | std = [
47 | "codec/std",
48 | "cumulus-primitives-core/std",
49 | "frame-benchmarking?/std",
50 | "frame-support/std",
51 | "frame-system/std",
52 | "num-traits/std",
53 | "orml-tokens/std",
54 | "orml-traits/std",
55 | "pallet-balances/std",
56 | "pallet-dao-manager/std",
57 | "pallet-message-queue/std",
58 | "pallet-session/std",
59 | "pallet-timestamp/std",
60 | "scale-info/std",
61 | "serde",
62 | "sp-arithmetic/std",
63 | "sp-core/std",
64 | "sp-io/std",
65 | "sp-runtime/std",
66 | "sp-staking/std",
67 | "sp-std/std",
68 | "xcm/std",
69 | "log/std",
70 | ]
71 | runtime-benchmarks = [
72 | "frame-benchmarking/runtime-benchmarks",
73 | "frame-system/runtime-benchmarks",
74 | "pallet-dao-manager/runtime-benchmarks",
75 | "pallet-message-queue/runtime-benchmarks",
76 | "sp-runtime/runtime-benchmarks",
77 | "frame-support/runtime-benchmarks",
78 | "sp-staking/runtime-benchmarks",
79 | ]
80 | try-runtime = ["frame-support/try-runtime", "pallet-dao-manager/try-runtime", "sp-runtime/try-runtime"]
81 |
--------------------------------------------------------------------------------
/pallets/pallet-dao-staking/README.md:
--------------------------------------------------------------------------------
1 | # DAO Staking Pallet
2 |
3 | ## Overview
4 |
5 | The DAO Staking Pallet is a pallet designed to facilitate staking towards DAOs within a blockchain network. This pallet introduces a staking mechanism that allows two distinct sets of entities, namely DAOs and Stakers, to participate in the distribution of tokens from a predefined pot. The allocation of rewards is determined based on the amount staked by each entity and the total stake towards each DAO.
6 |
7 | ### DAOs
8 |
9 | DAOs represent virtual accounts identified by unique IDs, which are responsible for registering themselves within the staking ecosystem. The primary role of DAOs is to attract Stakers to lock tokens in their favor. The rewards allocated to DAOs are proportional to the total amount staked towards them by Stakers. However, for a DAO to be eligible for rewards, it must have a total stake above a predefined threshold, thereby becoming `active`.
10 |
11 | ### Stakers
12 |
13 | Stakers are individual accounts that engage in locking tokens in favor of a DAO. Unlike DAOs, Stakers receive a fraction of the rewards based on their own stake.
14 |
15 | ## Runtime Configuration Parameters
16 |
17 | - `BlocksPerEra`: Defines the duration of an era in terms of block numbers.
18 | - `RegisterDeposit`: Specifies the deposit amount required for DAO registration.
19 | - `MaxStakersPerDao`: Limits the maximum number of Stakers that can simultaneously stake towards a single DAO.
20 | - `MinimumStakingAmount`: Sets the minimum amount required for a Staker to participate in staking.
21 | - `UnbondingPeriod`: Determines the period, in eras, required for unbonding staked tokens.
22 | - `RewardRatio`: Establishes the distribution ratio of rewards between DAOs and Stakers.
23 | - `StakeThresholdForActiveDao`: Sets the stake threshold required for a DAO to become `active`.
24 |
25 | ## Dispatchable Functions
26 |
27 | - `register_dao`: Allows DAOs to register themselves in the system.
28 | - `unregister_dao`: Enables DAOs to unregister from the system, initiating the unbonding period for Stakers.
29 | - `change_dao_metadata`: Changes the metadata associated to a DAO.
30 | - `stake`: Allows Stakers to lock tokens in favor of a DAO.
31 | - `unstake`: Unstakes tokens previously staked to a DAO, starting the unbonding period.
32 | - `withdraw_unstaked`: Allows Stakers to withdraw tokens that have completed the unbonding period.
33 | - `staker_claim_rewards`: Allows Stakers to claim available rewards.
34 | - `dao_claim_rewards`: Allows rewards to be claimed for DAOs.
35 | - `halt_unhalt_pallet`: Allows Root to trigger a halt of the system, eras will stop counting and rewards won't be distributed.
36 |
37 | ## Events
38 |
39 | The pallet emits events such as `Staked`, `Unstaked`, `DaoRegistered`, `DaoUnregistered`, and others to signal various operations and state changes within the staking ecosystem.
40 |
41 | ## Errors
42 |
43 | Errors such as `StakingNothing`, `InsufficientBalance`, `MaxStakersReached`, and others are defined to handle exceptional scenarios encountered during pallet operations.
44 |
45 | ## Example Runtime Implementation
46 |
47 | For an example runtime implementation that integrates this pallet, refer to [src/testing/mock.rs](./src/testing/mock.rs).
--------------------------------------------------------------------------------
/pallets/pallet-dao-staking/src/migrations.rs:
--------------------------------------------------------------------------------
1 | use super::*;
2 | use frame_support::{
3 | pallet_prelude::GetStorageVersion,
4 | traits::{Get, OnRuntimeUpgrade},
5 | weights::Weight,
6 | };
7 | use log::{info, warn};
8 |
9 | pub mod v1 {
10 |
11 | use super::*;
12 |
13 | /// This will check all the info on the ledger and remove the old lock while reapplying the new lock based on the
14 | /// value of the ledger, so the wrogly locked tokens will be unlocked.
15 | pub fn migrate_locks_to_freeze() -> Weight {
16 | let mut weight = Weight::zero();
17 | let mut count: u32 = 0;
18 |
19 | Ledger::::iter().for_each(|(account, ledger)| {
20 | if ledger.locked > Zero::zero() {
21 | ::OldCurrency::remove_lock(LOCK_ID, &account);
22 |
23 | let set_freeze_result =
24 | ::Currency::set_freeze(&LOCK_ID, &account, ledger.locked);
25 |
26 | if set_freeze_result.is_err() {
27 | warn!("set_freeze_result {:?}", set_freeze_result);
28 | }
29 |
30 | weight.saturating_accrue(T::DbWeight::get().reads_writes(3, 2));
31 | count += 1;
32 | }
33 | });
34 |
35 | info!("Migrated {} locks", count);
36 | weight
37 | }
38 |
39 | /// This will just remove all the holds on the enabling staking on a dao to apply the new one.
40 | pub fn migrate_holds() -> Weight {
41 | let mut count: u32 = 0;
42 | let mut weight = Weight::zero();
43 |
44 | RegisteredCore::::iter().for_each(|(_dao_id, dao_info)| {
45 | let dao_account = dao_info.account;
46 | let dao_reserved = ::OldCurrency::reserved_balance(&dao_account);
47 |
48 | ::OldCurrency::unreserve(&dao_account, dao_reserved);
49 |
50 | let set_on_hold_result = ::Currency::set_on_hold(
51 | &HoldReason::DaoStaking.into(),
52 | &dao_account,
53 | dao_reserved,
54 | );
55 |
56 | if set_on_hold_result.is_err() {
57 | warn!("set_on_hold_result {:?}", set_on_hold_result);
58 | }
59 |
60 | count += 1;
61 | weight.saturating_accrue(T::DbWeight::get().reads_writes(3, 2));
62 | });
63 |
64 | info!("Migrated {} daos", count);
65 | weight
66 | }
67 |
68 | pub struct MigrateToV1(sp_std::marker::PhantomData);
69 | impl OnRuntimeUpgrade for MigrateToV1 {
70 | #[cfg(feature = "try-runtime")]
71 | fn pre_upgrade() -> Result, sp_runtime::DispatchError> {
72 | frame_support::ensure!(
73 | Pallet::::on_chain_storage_version() <= Pallet::::in_code_storage_version(),
74 | "Required v0 before upgrading to v1"
75 | );
76 |
77 | Ok(Default::default())
78 | }
79 |
80 | fn on_runtime_upgrade() -> Weight {
81 | let mut weight = Weight::zero();
82 | let current = Pallet::::in_code_storage_version();
83 |
84 | let chain_version = Pallet::::on_chain_storage_version();
85 |
86 | weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 0));
87 |
88 | if current > chain_version {
89 | weight.saturating_accrue(migrate_locks_to_freeze::());
90 |
91 | weight.saturating_accrue(migrate_holds::());
92 |
93 | current.put::>();
94 |
95 | info!("v1 applied successfully");
96 | T::DbWeight::get().reads_writes(0, 1)
97 | } else {
98 | warn!("Skipping v1, should be removed");
99 | T::DbWeight::get().reads(1)
100 | }
101 | }
102 |
103 | #[cfg(feature = "try-runtime")]
104 | fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), sp_runtime::DispatchError> {
105 | frame_support::ensure!(
106 | Pallet::::on_chain_storage_version() == 1,
107 | "v1 not applied"
108 | );
109 |
110 | Ok(())
111 | }
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/pallets/pallet-rings/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = 'pallet-rings'
3 | description = ''
4 | authors.workspace = true
5 | edition.workspace = true
6 | homepage.workspace = true
7 | license.workspace = true
8 | repository.workspace = true
9 | version.workspace = true
10 |
11 | [package.metadata.docs.rs]
12 | targets = ["x86_64-unknown-linux-gnu"]
13 |
14 | [dependencies]
15 | log = { workspace = true }
16 | codec = { workspace = true }
17 | scale-info = { workspace = true }
18 | serde = { workspace = true, optional = true }
19 |
20 | frame-support = { workspace = true }
21 | frame-system = { workspace = true }
22 | num-traits = { workspace = true }
23 | pallet-balances = { workspace = true }
24 | pallet-session = { workspace = true }
25 | pallet-timestamp = { workspace = true, optional = true }
26 | sp-arithmetic = { workspace = true }
27 | sp-core = { workspace = true }
28 | sp-io = { workspace = true }
29 | sp-runtime = {workspace = true}
30 | sp-staking = {workspace = true}
31 | sp-std = {workspace = true}
32 |
33 | pallet-dao-manager = { workspace = true }
34 |
35 | pallet-xcm = { workspace = true }
36 | xcm = { workspace = true }
37 | xcm-executor = { workspace = true }
38 |
39 | frame-benchmarking = { workspace = true, optional = true }
40 |
41 | [dev-dependencies]
42 | orml-traits = { workspace = true }
43 | orml-traits2 = { workspace = true }
44 | orml-tokens = { workspace = true }
45 | orml-tokens2 = { workspace = true }
46 | orml-asset-registry = { workspace = true }
47 | xcm-builder = { workspace = true }
48 |
49 |
50 | [features]
51 | default = ["std"]
52 | std = [
53 | "serde",
54 | "codec/std",
55 | "scale-info/std",
56 | "num-traits/std",
57 | "sp-core/std",
58 | "sp-runtime/std",
59 | "sp-arithmetic/std",
60 | "sp-io/std",
61 | "sp-std/std",
62 | "frame-support/std",
63 | "frame-system/std",
64 | "pallet-balances/std",
65 | "pallet-session/std",
66 | "pallet-timestamp/std",
67 | "sp-staking/std",
68 | "pallet-dao-manager/std",
69 | "pallet-xcm/std",
70 | "xcm/std",
71 | "orml-traits2/std",
72 | "orml-traits/std",
73 | "orml-tokens/std",
74 | "orml-tokens2/std",
75 | "orml-asset-registry/std",
76 | "xcm-builder/std",
77 | "frame-benchmarking?/std",
78 | ]
79 | runtime-benchmarks = [
80 | "frame-benchmarking/runtime-benchmarks",
81 | "sp-runtime/runtime-benchmarks",
82 | "frame-system/runtime-benchmarks",
83 | "pallet-dao-manager/runtime-benchmarks",
84 | "pallet-xcm/runtime-benchmarks",
85 | "xcm-builder/runtime-benchmarks",
86 | ]
87 | try-runtime = ["frame-support/try-runtime"]
88 |
--------------------------------------------------------------------------------
/pallets/pallet-rings/README.md:
--------------------------------------------------------------------------------
1 | # Rings Pallet
2 |
3 | ## Overview
4 |
5 | The Rings pallet provides a cross-consensus message (XCM) abstraction layer for DAO Management, enabling them to manage assets effortlessly across multiple chains. It abstracts XCM complexities, facilitating easier handling of cross-chain transactions.
6 |
7 | ## Key Features
8 |
9 | - **Maintenance Mode**: Chains can be put under maintenance, restricting certain operations to ensure system integrity during upgrades or when issues are detected.
10 | - **Cross-chain Calls**: Enables sending XCM calls to other chains, allowing for a wide range of interactions.
11 | - **Asset Transfers**: Supports transferring fungible assets between accounts across different chains.
12 | - **Asset Bridging**: Facilitates the bridging of assets between chains, enhancing liquidity and asset interoperability.
13 |
14 | ## Traits Overview
15 |
16 | The pallet utilizes traits to abstract chain and asset locations:
17 |
18 | - [`ChainList`]: Provides an interface for referencing chains and retrieving their [`MultiLocation`] or main asset.
19 | - [`ChainAssetsList`]: Offers an interface for referencing chain assets and obtaining their [`MultiLocation`] or parent chain.
20 |
21 | ## Dispatchable Functions
22 |
23 | ### `set_maintenance_status`
24 |
25 | Sets the maintenance status of a chain. Requires `MaintenanceOrigin` authorization.
26 |
27 | - `chain`: The chain to modify.
28 | - `under_maintenance`: The desired maintenance status.
29 |
30 | ### `send_call`
31 |
32 | Allows sending a XCM call to another chain. Can be initiated by a DAO.
33 |
34 | - `destination`: The target chain.
35 | - `weight`: The call's weight.
36 | - `fee_asset`: The asset used for fee payment.
37 | - `fee`: The fee amount.
38 | - `call`: The call data.
39 |
40 | ### `transfer_assets`
41 |
42 | Allows transfers of fungible assets to another account in the destination chain.
43 | **Requires asset and fee_asset to be located in the same chain**.
44 |
45 | - `asset`: The asset to transfer.
46 | - `amount`: The amount to transfer.
47 | - `to`: The recipient account.
48 | - `fee_asset`: The asset used for fee payment.
49 | - `fee`: The fee amount.
50 |
51 | ### `bridge_assets`
52 |
53 | Allows bridging of assets to another chain, with either the DAO account or a third-party account as the beneficiary.
54 |
55 | - `asset`: The asset to bridge and its origin chain.
56 | - `destination`: The destination chain.
57 | - `fee`: The bridging fee.
58 | - `amount`: The amount to bridge.
59 | - `to`: Optional beneficiary account on the destination chain. (Defaults to the DAO account)
60 |
61 | ## Events
62 |
63 | - `CallSent`: Emitted when a XCM call is sent to another chain.
64 | - `AssetsTransferred`: Emitted when assets are transferred to another account on a different chain.
65 | - `AssetsBridged`: Emitted when assets are bridged to another chain.
66 | - `ChainMaintenanceStatusChanged`: Indicates a change in a chain's maintenance status.
67 |
68 | ## Errors
69 |
70 | - `SendingFailed`: Emitted when sending a XCM message fails.
71 | - `WeightTooHigh`: Emitted when the call's weight exceeds the maximum allowed.
72 | - `FailedToCalculateXcmFee`: Emitted when calculating the XCM fee fails.
73 | - `FailedToReanchorAsset`, `FailedToInvertLocation`: Errors related to asset reanchoring or location inversion.
74 | - `DifferentChains`, `ChainUnderMaintenance`: Indicate issues with the target chain or maintenance status.
75 |
76 | This pallet serves as a foundational component for building cross-chain solutions within the InvArch ecosystem, streamlining asset management and interoperability across diverse blockchain environments.
--------------------------------------------------------------------------------
/pallets/pallet-rings/src/benchmarking.rs:
--------------------------------------------------------------------------------
1 | #![cfg(feature = "runtime-benchmarks")]
2 |
3 | use super::*;
4 | use frame_benchmarking::{benchmarks, whitelisted_caller};
5 | use frame_support::{pallet_prelude::Weight, traits::Get, BoundedVec};
6 | use frame_system::RawOrigin as SystemOrigin;
7 | use pallet_dao_manager::origin::{DaoOrigin, MultisigInternalOrigin};
8 | use sp_std::{ops::Div, prelude::*, vec};
9 |
10 | fn assert_last_event(generic_event: ::RuntimeEvent) {
11 | frame_system::Pallet::::assert_last_event(generic_event.into());
12 | }
13 |
14 | benchmarks! {
15 | where_clause {
16 | where
17 | Result<
18 | DaoOrigin,
19 | ::RuntimeOrigin,
20 | >: From<::RuntimeOrigin>,
21 | ::RuntimeOrigin: From>,
22 |
23 | ::DaoId: Into,
24 |
25 | [u8; 32]: From<::AccountId>,
26 |
27 | T::AccountId: From<[u8; 32]>,
28 | }
29 |
30 | set_maintenance_status {
31 | let chain = T::Chains::benchmark_mock();
32 |
33 | }: _(SystemOrigin::Root, chain.clone(), true)
34 | verify {
35 | assert_last_event::(Event::ChainMaintenanceStatusChanged {
36 | chain,
37 | under_maintenance: true
38 | }.into());
39 | }
40 |
41 | send_call {
42 | let c in 0 .. T::MaxXCMCallLength::get();
43 |
44 | let call: BoundedVec = vec![u8::MAX; c as usize].try_into().unwrap();
45 | let destination = T::Chains::benchmark_mock();
46 | let weight = Weight::from_parts(100_000_000u64, 10_000u64);
47 | let fee_asset: <::Chains as ChainList>::ChainAssets = T::Chains::benchmark_mock().get_main_asset();
48 | let fee: u128 = u128::MAX.div(4u128);
49 |
50 | }: _(DaoOrigin::Multisig(MultisigInternalOrigin::new(0u32.into())), destination.clone(), weight, fee_asset, fee, call.clone())
51 | verify {
52 | assert_last_event::(Event::CallSent {
53 | sender: 0u32.into(),
54 | destination,
55 | call: call.to_vec(),
56 | }.into());
57 | }
58 |
59 | transfer_assets {
60 | let asset: <::Chains as ChainList>::ChainAssets = T::Chains::benchmark_mock().get_main_asset();
61 | let amount: u128 = u128::MAX.div(4u128);
62 | let to: T::AccountId = whitelisted_caller();
63 |
64 | }: _(DaoOrigin::Multisig(MultisigInternalOrigin::new(0u32.into())), asset.clone(), amount, to.clone(), asset.clone(), amount)
65 | verify {
66 | assert_last_event::(Event::AssetsTransferred {
67 | chain: asset.clone().get_chain(),
68 | asset,
69 | amount,
70 | from: 0u32.into(),
71 | to,
72 | }.into());
73 | }
74 |
75 | bridge_assets {
76 | let asset: <::Chains as ChainList>::ChainAssets = T::Chains::benchmark_mock().get_main_asset();
77 | let amount: u128 = u128::MAX.div(4u128);
78 | let fee: u128 = amount.div(5u128);
79 | let to: Option = Some(whitelisted_caller());
80 |
81 | }: _(DaoOrigin::Multisig(MultisigInternalOrigin::new(0u32.into())), asset.clone(), asset.clone().get_chain(), fee, amount, to)
82 | verify {
83 | assert_last_event::(Event::AssetsBridged {
84 | origin_chain_asset: asset,
85 | amount,
86 | from: 0u32.into(),
87 | to: whitelisted_caller(),
88 | }.into());
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/pallets/pallet-rings/src/traits.rs:
--------------------------------------------------------------------------------
1 | //! Provides supporting traits for the rings pallet.
2 | //!
3 | //! ## Overview
4 | //!
5 | //! This module contains the traits responsible for creating an abstraction layer on top of XCM [`MultiLocation`] and allows
6 | //! easier handling of cross-chain transactions through XCM.
7 | //!
8 | //! The traits contained in this pallet require an appropriate runtime implementation.
9 | //!
10 | //! ## Traits overview:
11 | //!
12 | //! - [`ChainList`] - Trait used to opaquely refer to a chain, provides an interface to get the chain `MultiLocation` or the chain's main asset as `ChainAssetsList`.
13 | //! - [`ChainAssetsList`] - Trait used to opaquely refer to a chain's asset, provides an interface to get the chain asset `MultiLocation` or the chain as `ChainList`.
14 |
15 | use codec::MaxEncodedLen;
16 | use frame_support::Parameter;
17 | use xcm::opaque::v4::Location;
18 |
19 | /// A chain [`MultiLocation`] abstraction trait.
20 | ///
21 | /// It provides an interface for easily getting a chain's [`MultiLocation`] and to go back and forth between the chain and its assets.
22 | ///
23 | /// This should be implemented properly in the runtime.
24 | pub trait ChainList: Parameter + MaxEncodedLen {
25 | type Balance: Into;
26 | type ChainAssets: ChainAssetsList;
27 |
28 | /// Returns the chain's [`MultiLocation`].
29 | fn get_location(&self) -> MultiLocation;
30 |
31 | /// Returns the chain's main asset as `ChainAssetsList`.
32 | fn get_main_asset(&self) -> Self::ChainAssets;
33 |
34 | #[cfg(feature = "runtime-benchmarks")]
35 | fn benchmark_mock() -> Self;
36 | }
37 |
38 | /// A chain asset [`MultiLocation`] abstraction trait.
39 | ///
40 | /// It provides an interface for easily getting a chain's asset [`MultiLocation`] and to go back and forth between the asset and its parent chain.
41 | ///
42 | /// This should be implemented properly in the runtime.
43 | pub trait ChainAssetsList: Parameter + MaxEncodedLen {
44 | type Chains: ChainList;
45 |
46 | /// Returns the asset's parent chain.
47 | fn get_chain(&self) -> Self::Chains;
48 |
49 | /// Returns the asset's [`MultiLocation`].
50 | fn get_asset_location(&self) -> MultiLocation;
51 | }
52 |
--------------------------------------------------------------------------------
/pallets/primitives/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = 'invarch-primitives'
3 | description = 'InvArch primitives for InvArchh Pallet Library'
4 | authors.workspace = true
5 | edition.workspace = true
6 | homepage.workspace = true
7 | license.workspace = true
8 | repository.workspace = true
9 | version.workspace = true
10 |
11 | [dependencies]
12 | codec = { workspace = true }
13 | scale-info = { workspace = true }
14 | serde = { workspace = true, optional = true }
15 |
16 | frame-system = { workspace = true }
17 | sp-core = { workspace = true }
18 | sp-io = { workspace = true }
19 | sp-runtime = { workspace = true }
20 | sp-std = { workspace = true }
21 |
22 | [features]
23 | default = ["std"]
24 | std = [
25 | "codec/std",
26 | "frame-system/std",
27 | "scale-info/std",
28 | "serde",
29 | "sp-core/std",
30 | "sp-io/std",
31 | "sp-runtime/std",
32 | "sp-std/std",
33 | ]
34 |
--------------------------------------------------------------------------------
/pallets/primitives/src/lib.rs:
--------------------------------------------------------------------------------
1 | #![cfg_attr(not(feature = "std"), no_std)]
2 |
3 | use codec::{Decode, Encode, MaxEncodedLen};
4 | use scale_info::TypeInfo;
5 | use sp_runtime::{Perbill, Percent};
6 |
7 | /// Voting weight of an IPT
8 | #[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)]
9 | pub enum OneOrPercent {
10 | /// Represents 100%
11 | One,
12 | /// Represents 0% - 99% inclusive
13 | ZeroPoint(Percent),
14 | }
15 |
16 | /// Entity is parent or child?
17 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)]
18 | pub enum Parentage {
19 | /// Parent IP (Account Id of itself)
20 | Parent(AccountId),
21 | /// Child IP (Id of the immediate parent, Account Id of the topmost parent)
22 | Child(IpsId, AccountId),
23 | }
24 |
25 | /// Normal or replica IPS
26 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)]
27 | pub enum IpsType {
28 | /// Normal IPS (original)
29 | Normal,
30 | /// IP Replica (Id of the original IP)
31 | Replica(IpsId),
32 | }
33 |
34 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)]
35 | pub enum BoolOrWasm {
36 | Bool(bool),
37 | Wasm(Wasm),
38 | }
39 |
40 | /// DAO IP Set struct
41 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)]
42 | pub struct DaoInfo {
43 | /// IPS parentage
44 | pub account: AccountId,
45 | /// IPS metadata
46 | pub metadata: DaoMetadataOf,
47 |
48 | /// Aye vote percentage required to execute a multisig call.
49 | ///
50 | /// Invariant: If set to `One`, 100% of tokens that have non-zero voting weight must approve
51 | pub minimum_support: Perbill,
52 | pub required_approval: Perbill,
53 |
54 | pub frozen_tokens: bool,
55 | }
56 |
57 | /// IPF Info
58 | #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)]
59 | pub struct IpfInfo {
60 | /// IPF owner
61 | pub owner: AccountId,
62 | /// Original IPF author
63 | pub author: AccountId,
64 | /// IPF metadata
65 | pub metadata: IpfMetadataOf,
66 | /// IPF data
67 | pub data: Data,
68 | }
69 |
70 | // This is a struct in preparation for having more fields in the future.
71 | #[derive(Debug, Clone, Encode, Decode, Eq, PartialEq, MaxEncodedLen, TypeInfo)]
72 | pub struct SubTokenInfo {
73 | pub id: IptId,
74 | pub metadata: SubAssetMetadata,
75 | }
76 |
77 | #[derive(Debug, Clone, Encode, Decode, Eq, PartialEq, MaxEncodedLen, TypeInfo)]
78 | pub struct CallInfo {
79 | pub pallet: Data,
80 | pub function: Data,
81 | }
82 |
83 | pub type Balance = u128;
84 |
--------------------------------------------------------------------------------
/pallets/rust-toolchain.toml:
--------------------------------------------------------------------------------
1 | [toolchain]
2 | channel = "nightly-2024-07-15"
3 | targets = ["wasm32-unknown-unknown"]
4 | components = [ "rustfmt", "rustc", "rust-std", "cargo", "clippy", "llvm-tools-preview"]
5 |
--------------------------------------------------------------------------------
/pallets/rustfmt.toml:
--------------------------------------------------------------------------------
1 | imports_granularity = "Crate"
2 |
--------------------------------------------------------------------------------
/res/invarch/invarch-genesis-state:
--------------------------------------------------------------------------------
1 | 0x00000000000000000000000000000000000000000000000000000000000000000064d77bb0ea342ea5b053fba4fd29248b1c3a5b20a8a9ef0cfc14cf45b0c5a4fb03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400
--------------------------------------------------------------------------------
/res/rococo/genesis-state:
--------------------------------------------------------------------------------
1 | 0x000000000000000000000000000000000000000000000000000000000000000000ce33b242a6720e66c121d20a9ea3d1971024de922f7ad9e9662f99e972dd56d003170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400
--------------------------------------------------------------------------------
/res/rococo/genesis-state-2:
--------------------------------------------------------------------------------
1 | 0x000000000000000000000000000000000000000000000000000000000000000000576f49a7a4fad0a130204494a616ccf31a3c1e16eca0630a60745ccee1a95f5103170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400
--------------------------------------------------------------------------------
/res/rococo/genesis-state-3:
--------------------------------------------------------------------------------
1 | 0x0000000000000000000000000000000000000000000000000000000000000000005b664ece67e12f9c36a6480a11e7a59bd5209cb7aab7bc23182539fa45dfd3f703170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400
--------------------------------------------------------------------------------
/res/tinker/genesis-state:
--------------------------------------------------------------------------------
1 | 0x000000000000000000000000000000000000000000000000000000000000000000f61fa99c7255c9fbd90dc4a55837cf79b621e99a265ebfd8712c647af1b7fdf603170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400
--------------------------------------------------------------------------------
/testall.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Initialize result variables
4 | pallets_result=""
5 | invarch_result=""
6 | tinkernet_result=""
7 |
8 | # Function to build and test a given directory
9 | build_and_test() {
10 | local dir=$1
11 | local result_var=$2
12 |
13 | cd ./$dir
14 |
15 | echo "$dir: 1/3 Checking format..."
16 | if RUSTFLAGS=-Awarnings cargo fmt --all -- --check > /dev/null 2>&1; then
17 | echo "$dir: 1/3 Format Check Ok"
18 | else
19 | echo "$dir: 1/3 Format Check Failed"
20 | echo "$dir: 1/3 Running cargo fmt to fix format..."
21 | if cargo fmt --all > /dev/null 2>&1; then
22 | echo "$dir: 1/3 Format Fixed"
23 | else
24 | echo "$dir: 1/3 Format Fix Failed"
25 | eval "$result_var=\"$dir: Format Failed\""
26 | cd ..
27 | return
28 | fi
29 | fi
30 |
31 | echo "$dir: 2/3 Building..."
32 | if RUSTFLAGS=-Awarnings cargo build --quiet > /dev/null; then
33 | echo "$dir: 2/3 Build Ok"
34 | else
35 | echo "$dir: 2/3 Build Failed"
36 | eval "$result_var=\"$dir: Build Failed\""
37 | cd ..
38 | return
39 | fi
40 |
41 | echo "$dir: 3/3 Testing..."
42 | if RUSTFLAGS=-Awarnings cargo test --quiet > /dev/null; then
43 | echo "$dir: 3/3 Test Ok"
44 | eval "$result_var=\"$dir: Ok\""
45 | else
46 | echo "$dir: 3/3 Test Failed"
47 | eval "$result_var=\"$dir: Test Failed\""
48 | fi
49 |
50 | cd ..
51 | }
52 |
53 | # Build and test each project
54 | build_and_test "pallets" "pallets_result"
55 | build_and_test "invarch" "invarch_result"
56 | build_and_test "tinkernet" "tinkernet_result"
57 |
58 | # Print results
59 | echo -e "\nResults:"
60 | echo $pallets_result
61 | echo $invarch_result
62 | echo $tinkernet_result
--------------------------------------------------------------------------------
/tinkernet/node/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tinkernet-node"
3 | version.workspace = true
4 | authors.workspace = true
5 | license.workspace = true
6 | homepage.workspace = true
7 | publish = false
8 | repository.workspace = true
9 | edition.workspace = true
10 |
11 | build = "build.rs"
12 |
13 | [[bin]]
14 | name = "tinkernet-collator"
15 | path = "src/main.rs"
16 |
17 | [dependencies]
18 | async-trait = { workspace = true }
19 | clap = { workspace = true }
20 | codec = { workspace = true }
21 | derive_more = { workspace = true }
22 | hex-literal = { workspace = true }
23 | log = { workspace = true }
24 | scale-info = { workspace = true }
25 | serde = { workspace = true, features = ["derive"] }
26 | serde_json = { workspace = true }
27 | # RPC related Dependencies
28 |
29 |
30 | ## RPC related Dependencies
31 | jsonrpsee = { workspace = true }
32 | futures = { workspace = true }
33 |
34 | ## Local Dependencies
35 | tinkernet-runtime = { path = "../runtime" }
36 |
37 | ## Substrate Dependencies
38 | frame-benchmarking = { workspace = true, features = ["std"] }
39 | frame-benchmarking-cli = { workspace = true }
40 | pallet-transaction-payment-rpc = { workspace = true }
41 |
42 | ## Substrate Client Dependencies
43 | sc-basic-authorship = { workspace = true }
44 | sc-chain-spec = { workspace = true }
45 | sc-cli = { workspace = true }
46 | sc-client-api = { workspace = true }
47 | sc-consensus = { workspace = true }
48 | sc-consensus-aura = { workspace = true }
49 | sc-consensus-manual-seal = { workspace = true }
50 | sc-executor = { workspace = true }
51 | sc-keystore = { workspace = true }
52 | sc-network = { workspace = true }
53 | sc-network-sync = { workspace = true }
54 | sc-rpc = { workspace = true }
55 | sc-rpc-api = { workspace = true }
56 | sc-service = { workspace = true }
57 | sc-sysinfo = { workspace = true }
58 | sc-telemetry = { workspace = true }
59 | sc-tracing = { workspace = true }
60 | sc-transaction-pool = { workspace = true }
61 | sc-transaction-pool-api = { workspace = true }
62 |
63 | ## Substrate Primitive
64 | sp-api = { workspace = true, features = ["std"] }
65 | sp-io = { workspace = true, features = ["std"] }
66 | sp-block-builder = { workspace = true, features = ["std"] }
67 | sp-blockchain = { workspace = true }
68 | sp-consensus = { workspace = true }
69 | sp-consensus-aura = { workspace = true, features = ["std"] }
70 | sp-core = { workspace = true, features = ["std"] }
71 | sp-inherents = { workspace = true, features = ["std"] }
72 | sp-keystore = { workspace = true }
73 | sp-offchain = { workspace = true, features = ["std"] }
74 | sp-runtime = { workspace = true, features = ["std"] }
75 | sp-session = { workspace = true, features = ["std"] }
76 | sp-timestamp = { workspace = true }
77 | sp-transaction-pool = { workspace = true, features = ["std"] }
78 |
79 | substrate-frame-rpc-system = { workspace = true }
80 | substrate-prometheus-endpoint = { workspace = true }
81 | try-runtime-cli = { workspace = true, optional = true }
82 |
83 | ## Polkadot dependencies Dependencies
84 | polkadot-cli = { workspace = true, features = ["rococo-native"] }
85 | polkadot-parachain = { workspace = true }
86 | polkadot-primitives = { workspace = true }
87 | polkadot-service = { workspace = true }
88 | xcm = { workspace = true }
89 |
90 | ## Cumulus dependencies Dependencies
91 | cumulus-client-cli = { workspace = true }
92 | cumulus-client-collator = { workspace = true }
93 | cumulus-client-consensus-aura = { workspace = true }
94 | cumulus-client-consensus-common = { workspace = true }
95 | cumulus-client-consensus-proposer = { workspace = true }
96 | cumulus-client-network = { workspace = true }
97 | cumulus-client-service = { workspace = true }
98 | cumulus-primitives-core = { workspace = true, features = ["std"] }
99 | cumulus-primitives-parachain-inherent = { workspace = true }
100 | cumulus-relay-chain-inprocess-interface = { workspace = true }
101 | cumulus-relay-chain-minimal-node = { workspace = true }
102 | cumulus-relay-chain-interface = { workspace = true }
103 | cumulus-relay-chain-rpc-interface = { workspace = true }
104 | cumulus-client-parachain-inherent = { workspace = true }
105 |
106 | [build-dependencies]
107 | substrate-build-script-utils = { workspace = true }
108 |
109 | [features]
110 | runtime-benchmarks = [
111 | "tinkernet-runtime/runtime-benchmarks",
112 | "polkadot-cli/runtime-benchmarks",
113 | ]
114 |
115 | try-runtime = ["tinkernet-runtime/try-runtime", "try-runtime-cli/try-runtime"]
116 |
--------------------------------------------------------------------------------
/tinkernet/node/build.rs:
--------------------------------------------------------------------------------
1 | use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
2 |
3 | fn main() {
4 | generate_cargo_keys();
5 |
6 | rerun_if_git_head_changed();
7 | }
8 |
--------------------------------------------------------------------------------
/tinkernet/node/res/.gitignore:
--------------------------------------------------------------------------------
1 | # temporary disabled for collaboration
2 | # !/*.json
3 |
--------------------------------------------------------------------------------
/tinkernet/node/res/local-tinker-para-2000-genesis:
--------------------------------------------------------------------------------
1 | 0x000000000000000000000000000000000000000000000000000000000000000000b910308fc34fe87c1acd65200b97c9211314a4befea38b080b1d1eabf4b6d93603170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400
--------------------------------------------------------------------------------
/tinkernet/node/src/cli.rs:
--------------------------------------------------------------------------------
1 | use crate::chain_spec;
2 | use clap::Parser;
3 | use std::path::PathBuf;
4 |
5 | /// Sub-commands supported by the collator.
6 | #[allow(clippy::large_enum_variant)]
7 | #[derive(Debug, clap::Subcommand)]
8 | pub enum Subcommand {
9 | /// Key management cli utilities
10 | #[clap(subcommand)]
11 | Key(sc_cli::KeySubcommand),
12 |
13 | /// Export the genesis state of the parachain.
14 | #[command(alias = "export-genesis-state")]
15 | ExportGenesisHead(cumulus_client_cli::ExportGenesisHeadCommand),
16 |
17 | /// Export the genesis wasm of the parachain.
18 | #[clap(name = "export-genesis-wasm")]
19 | ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand),
20 |
21 | /// Build a chain specification.
22 | BuildSpec(sc_cli::BuildSpecCmd),
23 |
24 | /// Validate blocks.
25 | CheckBlock(sc_cli::CheckBlockCmd),
26 |
27 | /// Export blocks.
28 | ExportBlocks(sc_cli::ExportBlocksCmd),
29 |
30 | /// Export the state of a given block into a chain spec.
31 | ExportState(sc_cli::ExportStateCmd),
32 |
33 | /// Import blocks.
34 | ImportBlocks(sc_cli::ImportBlocksCmd),
35 |
36 | /// Remove the whole chain.
37 | PurgeChain(cumulus_client_cli::PurgeChainCmd),
38 |
39 | /// Revert the chain to a previous state.
40 | Revert(sc_cli::RevertCmd),
41 |
42 | /// Sub-commands concerned with benchmarking.
43 | /// The pallet benchmarking moved to the `pallet` sub-command.
44 | #[clap(subcommand)]
45 | Benchmark(frame_benchmarking_cli::BenchmarkCmd),
46 |
47 | /// Try some testing command against a specified runtime state.
48 | #[cfg(feature = "try-runtime")]
49 | TryRuntime(try_runtime_cli::TryRuntimeCmd),
50 |
51 | /// Errors since the binary was not build with `--features try-runtime`.
52 | #[cfg(not(feature = "try-runtime"))]
53 | TryRuntime,
54 | }
55 |
56 | #[derive(Debug, Parser)]
57 | #[clap(
58 | propagate_version = true,
59 | args_conflicts_with_subcommands = true,
60 | subcommand_negates_reqs = true
61 | )]
62 | pub struct Cli {
63 | #[clap(subcommand)]
64 | pub subcommand: Option,
65 |
66 | #[clap(flatten)]
67 | pub run: cumulus_client_cli::RunCmd,
68 |
69 | /// Disable automatic hardware benchmarks.
70 | ///
71 | /// By default these benchmarks are automatically ran at startup and measure
72 | /// the CPU speed, the memory bandwidth and the disk speed.
73 | ///
74 | /// The results are then printed out in the logs, and also sent as part of
75 | /// telemetry, if telemetry is enabled.
76 | #[clap(long)]
77 | pub no_hardware_benchmarks: bool,
78 |
79 | /// Relay chain arguments
80 | #[clap(raw = true)]
81 | pub relay_chain_args: Vec,
82 | }
83 |
84 | #[derive(Debug)]
85 | pub struct RelayChainCli {
86 | /// The actual relay chain cli object.
87 | pub base: polkadot_cli::RunCmd,
88 |
89 | /// Optional chain id that should be passed to the relay chain.
90 | pub chain_id: Option,
91 |
92 | /// The base path that should be used by the relay chain.
93 | pub base_path: Option,
94 | }
95 |
96 | impl RelayChainCli {
97 | /// Parse the relay chain CLI parameters using the para chain `Configuration`.
98 | pub fn new<'a>(
99 | para_config: &sc_service::Configuration,
100 | relay_chain_args: impl Iterator- ,
101 | ) -> Self {
102 | let extension = chain_spec::Extensions::try_get(&*para_config.chain_spec);
103 | let chain_id = extension.map(|e| e.relay_chain.clone());
104 | let base_path = para_config.base_path.path().join("polkadot");
105 | Self {
106 | base_path: Some(base_path),
107 | chain_id,
108 | base: polkadot_cli::RunCmd::parse_from(relay_chain_args),
109 | }
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/tinkernet/node/src/lib.rs:
--------------------------------------------------------------------------------
1 | pub mod chain_spec;
2 | pub mod rpc;
3 | pub mod service;
4 |
--------------------------------------------------------------------------------
/tinkernet/node/src/main.rs:
--------------------------------------------------------------------------------
1 | //! InvArch Parachain Node CLI.
2 |
3 | #![warn(missing_docs)]
4 |
5 | mod chain_spec;
6 | #[macro_use]
7 | mod service;
8 | mod cli;
9 | mod command;
10 | mod rpc;
11 |
12 | fn main() -> sc_cli::Result<()> {
13 | command::run()
14 | }
15 |
--------------------------------------------------------------------------------
/tinkernet/node/src/rpc.rs:
--------------------------------------------------------------------------------
1 | //! A collection of node-specific RPC methods.
2 | //! Substrate provides the `sc-rpc` crate, which defines the dao RPC layer
3 | //! used by Substrate nodes. This file extends those RPC definitions with
4 | //! capabilities that are specific to this project's runtime configuration.
5 |
6 | #![warn(missing_docs)]
7 |
8 | use tinkernet_runtime::{opaque::Block, AccountId, Balance, Hash, Nonce};
9 |
10 | use sc_client_api::AuxStore;
11 | pub use sc_rpc::DenyUnsafe;
12 | use sc_transaction_pool_api::TransactionPool;
13 | use sp_api::ProvideRuntimeApi;
14 | use sp_block_builder::BlockBuilder;
15 | use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
16 | use std::sync::Arc;
17 |
18 | use sc_consensus_manual_seal::rpc::EngineCommand;
19 |
20 | /// A type representing all RPC extensions.
21 | pub type RpcExtension = jsonrpsee::RpcModule<()>;
22 |
23 | /// Full client dependencies
24 | pub struct FullDeps {
25 | /// The client instance to use.
26 | pub client: Arc,
27 | /// Transaction pool instance.
28 | pub pool: Arc
,
29 | /// Whether to deny unsafe calls
30 | pub deny_unsafe: DenyUnsafe,
31 | /// Command sink used for solo-dev mode
32 | pub command_sink: Option>>,
33 | }
34 |
35 | /// Instantiate all RPC extensions.
36 | pub fn create_full(
37 | deps: FullDeps,
38 | ) -> Result>
39 | where
40 | C: ProvideRuntimeApi
41 | + HeaderBackend
42 | + AuxStore
43 | + HeaderMetadata
44 | + Send
45 | + Sync
46 | + 'static,
47 | C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi,
48 | C::Api: substrate_frame_rpc_system::AccountNonceApi,
49 | C::Api: BlockBuilder,
50 | P: TransactionPool + Sync + Send + 'static,
51 | {
52 | use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
53 | use substrate_frame_rpc_system::{System, SystemApiServer};
54 |
55 | let mut module = RpcExtension::new(());
56 | let FullDeps {
57 | client,
58 | pool,
59 | deny_unsafe,
60 | command_sink: _,
61 | } = deps;
62 |
63 | module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?;
64 | module.merge(TransactionPayment::new(client).into_rpc())?;
65 | Ok(module)
66 | }
67 |
--------------------------------------------------------------------------------
/tinkernet/runtime/build.rs:
--------------------------------------------------------------------------------
1 | // This file is part of InvArch.
2 |
3 | // Copyright (C) 2021 InvArch.io
4 | // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5 |
6 | // This program is free software: you can redistribute it and/or modify
7 | // it under the terms of the GNU General Public License as published by
8 | // the Free Software Foundation, either version 3 of the License, or
9 | // (at your option) any later version.
10 |
11 | // This program is distributed in the hope that it will be useful,
12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | // GNU General Public License for more details.
15 |
16 | // You should have received a copy of the GNU General Public License
17 | // along with this program. If not, see .
18 |
19 | #[cfg(all(not(feature = "metadata-hash"), feature = "std"))]
20 | fn main() {
21 | substrate_wasm_builder::WasmBuilder::new()
22 | .with_current_project()
23 | .export_heap_base()
24 | .import_memory()
25 | .build()
26 | }
27 |
28 | #[cfg(all(feature = "metadata-hash", feature = "std"))]
29 | fn main() {
30 | substrate_wasm_builder::WasmBuilder::new()
31 | .with_current_project()
32 | .export_heap_base()
33 | .import_memory()
34 | .enable_metadata_hash("TNKR", 12)
35 | .build()
36 | }
37 |
38 | /// The wasm builder is deactivated when compiling
39 | /// this crate for wasm to speed up the compilation.
40 | #[cfg(not(feature = "std"))]
41 | fn main() {}
42 |
--------------------------------------------------------------------------------
/tinkernet/runtime/src/assets.rs:
--------------------------------------------------------------------------------
1 | use crate::{
2 | common_types::AssetId, constants::TreasuryAccount, AccountId, Balance, Balances, BlockNumber,
3 | ExistentialDeposit, MaxLocks, MaxReserves, Runtime, RuntimeEvent, RuntimeOrigin, Tokens,
4 | };
5 | use codec::{Decode, Encode, MaxEncodedLen};
6 | use frame_support::{
7 | parameter_types,
8 | traits::{Contains, EnsureOrigin, EnsureOriginWithArg},
9 | };
10 | use frame_system::EnsureRoot;
11 | use orml_asset_registry::ExistentialDeposits as AssetRegistryExistentialDeposits;
12 | use orml_currencies::BasicCurrencyAdapter;
13 | use orml_traits::parameter_type_with_key;
14 | use scale_info::TypeInfo;
15 |
16 | pub const CORE_ASSET_ID: AssetId = 0;
17 | pub const KSM_ASSET_ID: AssetId = 1;
18 |
19 | parameter_types! {
20 | pub const NativeAssetId: AssetId = CORE_ASSET_ID;
21 | pub const RelayAssetId: AssetId = KSM_ASSET_ID;
22 | pub const StringLimit: u32 = 255;
23 | }
24 |
25 | pub struct AssetAuthority;
26 | impl EnsureOriginWithArg> for AssetAuthority {
27 | type Success = ();
28 |
29 | fn try_origin(
30 | origin: RuntimeOrigin,
31 | _asset_id: &Option,
32 | ) -> Result {
33 | as EnsureOrigin>::try_origin(origin)
34 | }
35 |
36 | #[cfg(feature = "runtime-benchmarks")]
37 | fn try_successful_origin(_asset_id: &Option) -> Result {
38 | unimplemented!()
39 | }
40 | }
41 |
42 | #[derive(Debug, TypeInfo, Encode, Decode, PartialEq, Eq, Clone, MaxEncodedLen)]
43 | pub struct CustomAssetMetadata {
44 | pub fee_per_second: Option,
45 | }
46 |
47 | impl orml_asset_registry::Config for Runtime {
48 | type RuntimeEvent = RuntimeEvent;
49 | type AuthorityOrigin = AssetAuthority;
50 | type AssetId = AssetId;
51 | type Balance = Balance;
52 | type AssetProcessor = orml_asset_registry::SequentialId;
53 | type CustomMetadata = CustomAssetMetadata;
54 | type WeightInfo = ();
55 | type StringLimit = StringLimit;
56 | }
57 |
58 | pub struct DustRemovalWhitelist;
59 | impl Contains for DustRemovalWhitelist {
60 | fn contains(a: &AccountId) -> bool {
61 | // Always whitelists treasury account
62 | *a == TreasuryAccount::get()
63 | }
64 | }
65 |
66 | pub type Amount = i128;
67 |
68 | parameter_type_with_key! {
69 | pub ExistentialDeposits: |currency_id: AssetId| -> Balance {
70 | if currency_id == &CORE_ASSET_ID {
71 | ExistentialDeposit::get()
72 | } else {
73 | AssetRegistryExistentialDeposits::::get(currency_id)
74 | }
75 | };
76 | }
77 |
78 | impl orml_tokens::Config for Runtime {
79 | type RuntimeEvent = RuntimeEvent;
80 | type Balance = Balance;
81 | type Amount = Amount;
82 | type CurrencyId = AssetId;
83 | type WeightInfo = ();
84 | type ExistentialDeposits = ExistentialDeposits;
85 | type MaxLocks = MaxLocks;
86 | type DustRemovalWhitelist = DustRemovalWhitelist;
87 | type MaxReserves = MaxReserves;
88 | type ReserveIdentifier = [u8; 8];
89 | type CurrencyHooks = ();
90 | }
91 |
92 | impl orml_currencies::Config for Runtime {
93 | type MultiCurrency = Tokens;
94 | type NativeCurrency = BasicCurrencyAdapter;
95 | type GetNativeCurrencyId = NativeAssetId;
96 | type WeightInfo = ();
97 | }
98 |
--------------------------------------------------------------------------------
/tinkernet/runtime/src/common_types.rs:
--------------------------------------------------------------------------------
1 | /// The IpId
2 | pub type CommonId = u32;
3 |
4 | pub type AssetId = u32;
5 |
--------------------------------------------------------------------------------
/tinkernet/runtime/src/constants.rs:
--------------------------------------------------------------------------------
1 | use crate::{AccountId, PotId, TreasuryPalletId};
2 | use frame_support::parameter_types;
3 | use sp_runtime::traits::AccountIdConversion;
4 |
5 | pub mod currency {
6 | use crate::Balance;
7 |
8 | pub const UNIT: Balance = 1_000_000_000_000;
9 | pub const MILLIUNIT: Balance = 1_000_000_000;
10 | pub const MICROUNIT: Balance = 1_000_000;
11 |
12 | pub const CENTS: Balance = UNIT / 10_000;
13 | pub const MILLICENTS: Balance = CENTS / 1_000;
14 |
15 | // Almost same as Kusama
16 | pub const fn deposit(items: u32, bytes: u32) -> Balance {
17 | items as Balance * 2_000 * CENTS + (bytes as Balance) * 100 * MILLICENTS
18 | }
19 | }
20 |
21 | parameter_types! {
22 | pub TreasuryAccount: AccountId = TreasuryPalletId::get().into_account_truncating();
23 | pub StakingPotAccount: AccountId = PotId::get().into_account_truncating();
24 | }
25 |
--------------------------------------------------------------------------------
/tinkernet/runtime/src/fee_handling.rs:
--------------------------------------------------------------------------------
1 | use crate::{
2 | assets::RelayAssetId,
3 | common_types::AssetId,
4 | constants::{StakingPotAccount, TreasuryAccount},
5 | AccountId, Balance, Runtime, RuntimeCall, RuntimeEvent, Tokens,
6 | };
7 | use codec::{Decode, Encode};
8 | use frame_support::traits::{
9 | fungible::Inspect as FungibleInspect,
10 | fungibles::{Balanced, Credit},
11 | tokens::{Fortitude, Precision, Preservation, WithdrawConsequence},
12 | Contains, OnUnbalanced,
13 | };
14 | use orml_tokens::CurrencyAdapter;
15 | use pallet_asset_tx_payment::OnChargeAssetTransaction;
16 | use scale_info::TypeInfo;
17 | use sp_runtime::{
18 | traits::{DispatchInfoOf, One, PostDispatchInfoOf, Zero},
19 | transaction_validity::{InvalidTransaction, TransactionValidityError},
20 | };
21 |
22 | pub struct KSMEnabledPallets;
23 | impl Contains for KSMEnabledPallets {
24 | fn contains(t: &RuntimeCall) -> bool {
25 | matches!(
26 | t,
27 | // We want users and DAOs to be able to operate multisigs using KSM.
28 | RuntimeCall::INV4(_)
29 | // We want DAOs to be able to operate XCMultisigs using KSM.
30 | | RuntimeCall::Rings(_)
31 | // These next 3 are needed to manage the KSM itself using KSM as the fee token.
32 | | RuntimeCall::Tokens(_)
33 | | RuntimeCall::XTokens(_)
34 | | RuntimeCall::Currencies(_)
35 | )
36 | }
37 | }
38 |
39 | impl pallet_asset_tx_payment::Config for Runtime {
40 | type RuntimeEvent = RuntimeEvent;
41 | type Fungibles = Tokens;
42 | type OnChargeAssetTransaction = FilteredTransactionCharger;
43 | }
44 |
45 | pub struct TnkrToKsm;
46 | impl TnkrToKsm {
47 | pub fn to_asset_balance(balance: Balance) -> Balance {
48 | balance.saturating_div(20u128)
49 | }
50 | }
51 |
52 | pub struct FilteredTransactionCharger;
53 | impl OnChargeAssetTransaction for FilteredTransactionCharger {
54 | type AssetId = AssetId;
55 | type Balance = Balance;
56 | type LiquidityInfo = Credit;
57 |
58 | fn withdraw_fee(
59 | who: &AccountId,
60 | call: &RuntimeCall,
61 | _dispatch_info: &sp_runtime::traits::DispatchInfoOf,
62 | asset_id: AssetId,
63 | fee: Balance,
64 | _tip: Balance,
65 | ) -> Result, frame_support::unsigned::TransactionValidityError> {
66 | if KSMEnabledPallets::contains(call) && asset_id == 1u32 {
67 | let min_converted_fee = if fee.is_zero() {
68 | Zero::zero()
69 | } else {
70 | One::one()
71 | };
72 |
73 | let fee = TnkrToKsm::to_asset_balance(fee).max(min_converted_fee);
74 |
75 | let can_withdraw = CurrencyAdapter::::can_withdraw(who, fee);
76 |
77 | if !matches!(can_withdraw, WithdrawConsequence::Success) {
78 | return Err(InvalidTransaction::Payment.into());
79 | }
80 |
81 | >::withdraw(
82 | asset_id,
83 | who,
84 | fee,
85 | Precision::Exact,
86 | Preservation::Expendable,
87 | Fortitude::Force,
88 | )
89 | .map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment))
90 | } else {
91 | Err(TransactionValidityError::from(InvalidTransaction::Payment))
92 | }
93 | }
94 |
95 | fn correct_and_deposit_fee(
96 | who: &AccountId,
97 | _dispatch_info: &DispatchInfoOf,
98 | _post_info: &PostDispatchInfoOf,
99 | corrected_fee: Balance,
100 | _tip: Balance,
101 | paid: Credit,
102 | ) -> Result<(u128, u128), TransactionValidityError> {
103 | let min_converted_fee = if corrected_fee.is_zero() {
104 | Zero::zero()
105 | } else {
106 | One::one()
107 | };
108 |
109 | let corrected_fee = TnkrToKsm::to_asset_balance(corrected_fee).max(min_converted_fee);
110 |
111 | let (final_fee, refund) = paid.split(corrected_fee);
112 |
113 | let _ = >::resolve(who, refund);
114 |
115 | DealWithKSMFees::on_unbalanced(final_fee);
116 |
117 | Ok((Zero::zero(), Zero::zero()))
118 | }
119 | }
120 |
121 | pub struct DealWithKSMFees;
122 | impl OnUnbalanced> for DealWithKSMFees {
123 | fn on_unbalanceds(mut fees_then_tips: impl Iterator- >) {
124 | if let Some(mut fees) = fees_then_tips.next() {
125 | if let Some(tips) = fees_then_tips.next() {
126 | // Merge with fee, for now we send everything to the treasury
127 | let _ = fees.subsume(tips);
128 | }
129 |
130 | Self::on_unbalanced(fees);
131 | }
132 | }
133 |
134 | fn on_unbalanced(amount: Credit) {
135 | let total: u128 = 100u128;
136 | let amount1 = amount.peek().saturating_mul(50u128) / total;
137 | let (to_collators, to_treasury) = amount.split(amount1);
138 |
139 | let _ = >::resolve(&TreasuryAccount::get(), to_treasury);
140 |
141 | let _ = >::resolve(&StakingPotAccount::get(), to_collators);
142 | }
143 | }
144 |
145 | #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)]
146 | pub struct ChargerExtra {
147 | #[codec(compact)]
148 | pub tip: Balance,
149 | pub asset_id: Option,
150 | }
151 |
--------------------------------------------------------------------------------
/tinkernet/runtime/src/inflation.rs:
--------------------------------------------------------------------------------
1 | use crate::{
2 | Balance, Balances, BlockNumber, NegativeImbalance, OcifStaking, Runtime, RuntimeEvent, DAYS,
3 | };
4 | use frame_support::{parameter_types, traits::OnUnbalanced};
5 | use sp_runtime::Perbill;
6 |
7 | pub const TEN_PERCENT_PER_YEAR: pallet_checked_inflation::InflationMethod =
8 | pallet_checked_inflation::InflationMethod::Rate(Perbill::from_percent(10));
9 |
10 | const YEAR: u32 = 365;
11 |
12 | parameter_types! {
13 | pub const BlocksPerEra: BlockNumber = DAYS;
14 | pub const ErasPerYear: u32 = YEAR;
15 | pub const Inflation: pallet_checked_inflation::InflationMethod = TEN_PERCENT_PER_YEAR;
16 | }
17 |
18 | pub struct DealWithInflation;
19 | impl OnUnbalanced for DealWithInflation {
20 | fn on_unbalanced(amount: NegativeImbalance) {
21 | OcifStaking::rewards(amount);
22 | }
23 | }
24 |
25 | impl pallet_checked_inflation::Config for Runtime {
26 | type BlocksPerEra = BlocksPerEra;
27 | type Currency = Balances;
28 | type RuntimeEvent = RuntimeEvent;
29 | type ErasPerYear = ErasPerYear;
30 | type Inflation = Inflation;
31 | type DealWithInflation = DealWithInflation;
32 | type WeightInfo = pallet_checked_inflation::weights::SubstrateWeight;
33 | }
34 |
--------------------------------------------------------------------------------
/tinkernet/runtime/src/nft.rs:
--------------------------------------------------------------------------------
1 | use crate::{
2 | common_types::CommonId,
3 | constants::currency::{MILLIUNIT, UNIT},
4 | AccountId, Balance, Balances, Runtime, RuntimeEvent,
5 | };
6 | use frame_support::{parameter_types, traits::AsEnsureOriginWithArg};
7 |
8 | use frame_system::{EnsureRoot, EnsureSigned};
9 |
10 | parameter_types! {
11 | pub const CollectionDeposit: Balance = UNIT;
12 | pub const ItemDeposit: Balance = UNIT / 100;
13 | pub const KeyLimit: u32 = 32;
14 | pub const ValueLimit: u32 = 256;
15 | pub const UniquesMetadataDepositBase: Balance = 10 * MILLIUNIT;
16 | pub const AttributeDepositBase: Balance = 10 * MILLIUNIT;
17 | pub const DepositPerByte: Balance = MILLIUNIT;
18 | pub const UniquesStringLimit: u32 = 128;
19 | }
20 |
21 | impl pallet_uniques::Config for Runtime {
22 | type RuntimeEvent = RuntimeEvent;
23 | type CollectionId = CommonId;
24 | type ItemId = CommonId;
25 | type Currency = Balances;
26 | type ForceOrigin = EnsureRoot;
27 | type CreateOrigin = AsEnsureOriginWithArg