From b6c6f4dc9af7173514b4d7965821191068125545 Mon Sep 17 00:00:00 2001 From: Gabriel Facco de Arruda Date: Wed, 17 Jan 2024 19:44:43 +0800 Subject: [PATCH 1/7] refactor: New core account derivation --- tinkernet/Cargo.lock | 15 +-- tinkernet/Cargo.toml | 5 +- tinkernet/node/src/rpc.rs | 2 +- tinkernet/runtime/Cargo.toml | 8 +- tinkernet/runtime/src/inv4.rs | 17 ++- tinkernet/runtime/src/lib.rs | 4 +- tinkernet/runtime/src/migrations.rs | 155 +++++++++++++++++++++++++++ tinkernet/runtime/src/rings/mod.rs | 8 +- tinkernet/runtime/src/staking.rs | 3 +- tinkernet/runtime/src/weights/mod.rs | 5 - tinkernet/rust-toolchain.toml | 4 +- 11 files changed, 186 insertions(+), 40 deletions(-) create mode 100644 tinkernet/runtime/src/migrations.rs diff --git a/tinkernet/Cargo.lock b/tinkernet/Cargo.lock index d2cbe73d..2ea026de 100644 --- a/tinkernet/Cargo.lock +++ b/tinkernet/Cargo.lock @@ -3845,7 +3845,7 @@ dependencies = [ [[package]] name = "invarch-primitives" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?rev=2830b0abc6e29e1b3412480f2e95265fafd73cb5#2830b0abc6e29e1b3412480f2e95265fafd73cb5" +source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#d83e95692d178982cc2bd4279f31f3eba31d9c97" dependencies = [ "frame-system", "parity-scale-codec", @@ -6020,7 +6020,7 @@ dependencies = [ [[package]] name = "pallet-checked-inflation" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?rev=2830b0abc6e29e1b3412480f2e95265fafd73cb5#2830b0abc6e29e1b3412480f2e95265fafd73cb5" +source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#d83e95692d178982cc2bd4279f31f3eba31d9c97" dependencies = [ "frame-benchmarking", "frame-support", @@ -6279,7 +6279,7 @@ dependencies = [ [[package]] name = "pallet-inv4" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?rev=2830b0abc6e29e1b3412480f2e95265fafd73cb5#2830b0abc6e29e1b3412480f2e95265fafd73cb5" +source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#d83e95692d178982cc2bd4279f31f3eba31d9c97" dependencies = [ "frame-benchmarking", "frame-support", @@ -6297,6 +6297,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-std", + "xcm", ] [[package]] @@ -6451,7 +6452,7 @@ dependencies = [ [[package]] name = "pallet-ocif-staking" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?rev=2830b0abc6e29e1b3412480f2e95265fafd73cb5#2830b0abc6e29e1b3412480f2e95265fafd73cb5" +source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#d83e95692d178982cc2bd4279f31f3eba31d9c97" dependencies = [ "frame-benchmarking", "frame-support", @@ -6600,7 +6601,7 @@ dependencies = [ [[package]] name = "pallet-rings" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?rev=2830b0abc6e29e1b3412480f2e95265fafd73cb5#2830b0abc6e29e1b3412480f2e95265fafd73cb5" +source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#d83e95692d178982cc2bd4279f31f3eba31d9c97" dependencies = [ "frame-benchmarking", "frame-support", @@ -12333,7 +12334,7 @@ dependencies = [ [[package]] name = "tinkernet-node" -version = "1.5.1" +version = "1.6.0" dependencies = [ "async-trait", "clap", @@ -12407,7 +12408,7 @@ dependencies = [ [[package]] name = "tinkernet-runtime" -version = "1.5.1" +version = "1.6.0" dependencies = [ "cumulus-pallet-aura-ext", "cumulus-pallet-dmp-queue", diff --git a/tinkernet/Cargo.toml b/tinkernet/Cargo.toml index 1a5083c5..40b792a4 100644 --- a/tinkernet/Cargo.toml +++ b/tinkernet/Cargo.toml @@ -1,4 +1,5 @@ [workspace] +resolver = "2" members = [ 'node', 'runtime', @@ -7,7 +8,7 @@ members = [ ] [workspace.package] -version = "1.5.1" +version = "1.6.0" edition = "2021" license = "GPL-3.0" @@ -31,4 +32,4 @@ orml-xtokens = { git = "https://github.com/open-web3-stack//open-runtime-module- orml-xcm-support = { git = "https://github.com/open-web3-stack//open-runtime-module-library", rev = "7ecebeab7e3dbc2226ed58d32ee159271a8176ae" } orml-unknown-tokens = { git = "https://github.com/open-web3-stack//open-runtime-module-library", rev = "7ecebeab7e3dbc2226ed58d32ee159271a8176ae" } orml-currencies = { git = "https://github.com/open-web3-stack//open-runtime-module-library", rev = "7ecebeab7e3dbc2226ed58d32ee159271a8176ae" } -orml-tokens = { git = "https://github.com/open-web3-stack//open-runtime-module-library", rev = "7ecebeab7e3dbc2226ed58d32ee159271a8176ae" } \ No newline at end of file +orml-tokens = { git = "https://github.com/open-web3-stack//open-runtime-module-library", rev = "7ecebeab7e3dbc2226ed58d32ee159271a8176ae" } diff --git a/tinkernet/node/src/rpc.rs b/tinkernet/node/src/rpc.rs index ff82db40..79b7c3ed 100644 --- a/tinkernet/node/src/rpc.rs +++ b/tinkernet/node/src/rpc.rs @@ -12,7 +12,7 @@ use tinkernet_runtime::{opaque::Block, AccountId, Balance, Hash, Index as Nonce} //use brainstorm_runtime::{opaque::Block, AccountId, Balance, Hash, Index as Nonce}; use sc_client_api::AuxStore; -pub use sc_rpc::{DenyUnsafe, SubscriptionTaskExecutor}; +pub use sc_rpc::DenyUnsafe; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder; diff --git a/tinkernet/runtime/Cargo.toml b/tinkernet/runtime/Cargo.toml index a3247ec0..df7b88ee 100644 --- a/tinkernet/runtime/Cargo.toml +++ b/tinkernet/runtime/Cargo.toml @@ -24,10 +24,10 @@ smallvec = "1.6.1" getrandom = { version = "0.2.4", default-features = false, features = ["js"] } # InvArch Pallets -pallet-inv4 = { git = "https://github.com/InvArch/InvArch-Frames", rev = "2830b0abc6e29e1b3412480f2e95265fafd73cb5", default-features = false } -pallet-ocif-staking = { git = "https://github.com/InvArch/InvArch-Frames", rev = "2830b0abc6e29e1b3412480f2e95265fafd73cb5", default-features = false } -pallet-checked-inflation = { git = "https://github.com/InvArch/InvArch-Frames", rev = "2830b0abc6e29e1b3412480f2e95265fafd73cb5", default-features = false } -pallet-rings = { git = "https://github.com/InvArch/InvArch-Frames", rev = "2830b0abc6e29e1b3412480f2e95265fafd73cb5", default-features = false } +pallet-inv4 = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } +pallet-ocif-staking = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } +pallet-checked-inflation = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } +pallet-rings = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } #pallet-inv4 = { path = "../../../InvArch-Frames/INV4/pallet-inv4", default-features = false } #pallet-ocif-staking = { path = "../../../InvArch-Frames/OCIF/staking", default-features = false } diff --git a/tinkernet/runtime/src/inv4.rs b/tinkernet/runtime/src/inv4.rs index 17f02b7c..f057b95c 100644 --- a/tinkernet/runtime/src/inv4.rs +++ b/tinkernet/runtime/src/inv4.rs @@ -3,8 +3,8 @@ use crate::{ common_types::{AssetId, CommonId}, constants::currency::UNIT, fee_handling::DealWithKSMFees, - AccountId, Balance, Balances, CoreAssets, DealWithFees, Runtime, RuntimeCall, RuntimeEvent, - RuntimeOrigin, Tokens, + AccountId, Balance, Balances, CoreAssets, DealWithFees, ParachainInfo, Runtime, RuntimeCall, + RuntimeEvent, RuntimeOrigin, Tokens, }; use codec::{Decode, Encode}; use frame_support::{ @@ -14,7 +14,7 @@ use frame_support::{ use pallet_asset_tx_payment::ChargeAssetTxPayment; use pallet_inv4::fee_handling::{FeeAsset, FeeAssetNegativeImbalance, MultisigFeeHandler}; use scale_info::TypeInfo; -use sp_core::{ConstU32, H256}; +use sp_core::ConstU32; use sp_runtime::traits::{One, SignedExtension, Zero}; parameter_types! { @@ -22,13 +22,11 @@ parameter_types! { pub const MaxCallers: u32 = 10000; pub const CoreSeedBalance: Balance = 1000000u128; pub const CoreCreationFee: Balance = UNIT * 100; - pub const GenesisHash: ::Hash = H256([ - 212, 46, 150, 6, 169, 149, 223, 228, 51, 220, 121, 85, 220, 42, 112, 244, 149, 243, 80, - 243, 115, 218, 162, 0, 9, 138, 232, 68, 55, 129, 106, 210, - ]); pub const KSMCoreCreationFee: Balance = UNIT; pub const MaxCallSize: u32 = 50 * 1024; + + pub ParaId: u32 = ParachainInfo::parachain_id().into(); } impl pallet_inv4::Config for Runtime { @@ -38,14 +36,11 @@ impl pallet_inv4::Config for Runtime { type Currency = Balances; type RuntimeCall = RuntimeCall; type MaxCallers = MaxCallers; - type MaxSubAssets = MaxCallers; type CoreSeedBalance = CoreSeedBalance; type AssetsProvider = CoreAssets; type RuntimeOrigin = RuntimeOrigin; - // type AssetFreezer = AssetFreezer; type CoreCreationFee = CoreCreationFee; type FeeCharger = FeeCharger; - type GenesisHash = GenesisHash; type WeightInfo = pallet_inv4::weights::SubstrateWeight; type Tokens = Tokens; @@ -53,6 +48,8 @@ impl pallet_inv4::Config for Runtime { type KSMCoreCreationFee = KSMCoreCreationFee; type MaxCallSize = MaxCallSize; + + type ParaId = ParaId; } #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo, Debug)] diff --git a/tinkernet/runtime/src/lib.rs b/tinkernet/runtime/src/lib.rs index 2c066c1d..9837ed5a 100644 --- a/tinkernet/runtime/src/lib.rs +++ b/tinkernet/runtime/src/lib.rs @@ -96,6 +96,7 @@ mod fee_handling; use fee_handling::TnkrToKsm; mod inflation; mod inv4; +mod migrations; mod nft; mod rings; mod staking; @@ -158,6 +159,7 @@ pub type Executive = frame_executive::Executive< frame_system::ChainContext, Runtime, AllPalletsWithSystem, + migrations::new_core_account_derivation::MigrateToNewDerivation, >; /// Opaque types. These are used by the CLI to instantiate machinery that don't need to know @@ -188,7 +190,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("tinkernet_node"), impl_name: create_runtime_str!("tinkernet_node"), authoring_version: 1, - spec_version: 20, + spec_version: 21, impl_version: 1, apis: RUNTIME_API_VERSIONS, transaction_version: 1, diff --git a/tinkernet/runtime/src/migrations.rs b/tinkernet/runtime/src/migrations.rs new file mode 100644 index 00000000..dea96ba4 --- /dev/null +++ b/tinkernet/runtime/src/migrations.rs @@ -0,0 +1,155 @@ +use frame_support::{dispatch::GetStorageVersion, traits::OnRuntimeUpgrade, weights::Weight}; +use log::{info, warn}; + +pub mod new_core_account_derivation { + use super::*; + use crate::{common_types::CommonId, AccountId, Identity, Runtime, RuntimeOrigin, Vec, INV4}; + use pallet_inv4::{ + account_derivation::CoreAccountDerivation, CoreInfoOf, Pallet as INV4Pallet, + }; + use sp_runtime::MultiAddress; + use sp_std::boxed::Box; + + fn get_old_accounts() -> Vec<(AccountId, CommonId)> { + pallet_inv4::CoreByAccount::::iter().collect() + } + + fn migrate_inv4_storages(old_accounts: Vec<(AccountId, CommonId)>) { + // let _ = pallet_inv4::CoreByAccount::::clear(1000, None); + + old_accounts.iter().for_each(|(old_acc, core_id)| { + let new_account = + as CoreAccountDerivation>::derive_core_account( + *core_id, + ); + + // pallet_inv4::CoreByAccount::::insert(new_account, core_id); + + pallet_inv4::CoreByAccount::::swap(old_acc, new_account); + }); + + pallet_inv4::CoreStorage::::translate( + |core_id, core_data: CoreInfoOf| { + let mut new_core = core_data; + + new_core.account = + as CoreAccountDerivation>::derive_core_account( + core_id, + ); + + Some(new_core) + }, + ); + } + + fn migrate_staking_storages(old_accounts: Vec<(AccountId, CommonId)>) { + old_accounts.iter().for_each(|(old_acc, this_core_id)| { + let new_account = + as CoreAccountDerivation>::derive_core_account( + *this_core_id, + ); + + // let ledger = pallet_ocif_staking::pallet::Ledger::::take(old_acc); + // pallet_ocif_staking::pallet::Ledger::::insert(new_account.clone(), ledger); + + pallet_ocif_staking::pallet::Ledger::::swap(old_acc, new_account.clone()); + + pallet_inv4::CoreStorage::::iter_keys().for_each(|staking_core_id| { + // let info = pallet_ocif_staking::pallet::GeneralStakerInfo::::take( + // staking_core_id, + // old_acc, + // ); + + // pallet_ocif_staking::pallet::GeneralStakerInfo::::insert( + // staking_core_id, + // new_account.clone(), + // info, + // ); + + pallet_ocif_staking::pallet::GeneralStakerInfo::::swap( + staking_core_id, + old_acc, + staking_core_id, + new_account.clone(), + ); + }); + }); + } + + fn migrate_balances_storages(old_accounts: Vec<(AccountId, CommonId)>) { + old_accounts.iter().for_each(|(old_acc, this_core_id)| { + let new_account = + as CoreAccountDerivation>::derive_core_account( + *this_core_id, + ); + + pallet_balances::Account::::swap(old_acc, new_account.clone()); + pallet_balances::Freezes::::swap(old_acc, new_account.clone()); + pallet_balances::Holds::::swap(old_acc, new_account.clone()); + pallet_balances::Locks::::swap(old_acc, new_account.clone()); + pallet_balances::Reserves::::swap(old_acc, new_account.clone()); + + frame_system::Account::::swap(old_acc, new_account); + }); + } + + fn migrate_identity_storages(old_accounts: Vec<(AccountId, CommonId)>) { + old_accounts.iter().for_each(|(old_acc, this_core_id)| { + let new_account = + as CoreAccountDerivation>::derive_core_account( + *this_core_id, + ); + + let maybe_identity = Identity::identity(old_acc); + + if let Some(identity) = maybe_identity { + let _ = Identity::kill_identity( + RuntimeOrigin::root(), + MultiAddress::Id(old_acc.clone()), + ); + let _ = Identity::set_identity( + RuntimeOrigin::signed(new_account), + Box::new(identity.info), + ); + } + }); + } + + pub struct MigrateToNewDerivation; + impl OnRuntimeUpgrade for MigrateToNewDerivation { + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, sp_runtime::DispatchError> { + frame_support::ensure!( + INV4::current_storage_version() == 2, + "Required v2 before migrating core accounts" + ); + + Ok(Default::default()) + } + + fn on_runtime_upgrade() -> Weight { + let current = INV4::current_storage_version(); + + let old_accounts = get_old_accounts(); + + if current == 2 { + migrate_inv4_storages(old_accounts.clone()); + migrate_staking_storages(old_accounts.clone()); + migrate_balances_storages(old_accounts.clone()); + migrate_identity_storages(old_accounts.clone()); + + info!("applied successfully"); + + ::DbWeight::get().reads_writes(0, 1) + } else { + warn!("Skipping, should be removed"); + ::DbWeight::get().reads(1) + } + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), sp_runtime::DispatchError> { + Ok(()) + } + } +} diff --git a/tinkernet/runtime/src/rings/mod.rs b/tinkernet/runtime/src/rings/mod.rs index af1cc8b8..51c02254 100644 --- a/tinkernet/runtime/src/rings/mod.rs +++ b/tinkernet/runtime/src/rings/mod.rs @@ -1,6 +1,6 @@ -use crate::{AccountId, Balance, ParachainInfo, Runtime, RuntimeEvent}; +use crate::{AccountId, Balance, Runtime, RuntimeEvent}; use codec::{Decode, Encode, MaxEncodedLen}; -use frame_support::{parameter_types, traits::Get}; +use frame_support::parameter_types; use frame_system::EnsureRoot; use pallet_rings::{ChainAssetsList, ChainList}; use scale_info::TypeInfo; @@ -12,16 +12,12 @@ mod picasso; use picasso::Picasso; parameter_types! { - pub ParaId: u32 = ParachainInfo::get().into(); - pub INV4PalletIndex: u8 = 71u8; pub MaxXCMCallLength: u32 = 100_000; } impl pallet_rings::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type ParaId = ParaId; type Chains = Chains; - type INV4PalletIndex = INV4PalletIndex; type MaxXCMCallLength = MaxXCMCallLength; type MaintenanceOrigin = EnsureRoot; type WeightInfo = pallet_rings::weights::SubstrateWeight; diff --git a/tinkernet/runtime/src/staking.rs b/tinkernet/runtime/src/staking.rs index c8f9c8e2..fcc90ae8 100644 --- a/tinkernet/runtime/src/staking.rs +++ b/tinkernet/runtime/src/staking.rs @@ -1,5 +1,5 @@ use crate::{ - Balance, Balances, BlockNumber, CommonId, ExistentialDeposit, Runtime, RuntimeEvent, DAYS, UNIT, + Balance, Balances, BlockNumber, ExistentialDeposit, Runtime, RuntimeEvent, DAYS, UNIT, }; use frame_support::{parameter_types, PalletId}; @@ -22,7 +22,6 @@ parameter_types! { impl pallet_ocif_staking::Config for Runtime { type Currency = Balances; type BlocksPerEra = BlocksPerEra; - type CoreId = CommonId; type RegisterDeposit = RegisterDeposit; type RuntimeEvent = RuntimeEvent; type MaxStakersPerCore = MaxStakersPerCore; diff --git a/tinkernet/runtime/src/weights/mod.rs b/tinkernet/runtime/src/weights/mod.rs index 9fc55883..4e9f8dfa 100644 --- a/tinkernet/runtime/src/weights/mod.rs +++ b/tinkernet/runtime/src/weights/mod.rs @@ -2,8 +2,3 @@ pub mod block_weights; pub mod extrinsic_weights; pub mod paritydb_weights; pub mod rocksdb_weights; - -pub use block_weights::constants::BlockExecutionWeight; -pub use extrinsic_weights::constants::ExtrinsicBaseWeight; -pub use paritydb_weights::constants::ParityDbWeight; -pub use rocksdb_weights::constants::RocksDbWeight; diff --git a/tinkernet/rust-toolchain.toml b/tinkernet/rust-toolchain.toml index 124289af..fba59145 100644 --- a/tinkernet/rust-toolchain.toml +++ b/tinkernet/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "nightly-2023-05-22" +channel = "nightly-2023-12-01" targets = ["wasm32-unknown-unknown"] -components = [ "rustfmt", "rustc", "rust-std", "cargo", "clippy", "llvm-tools-preview"] \ No newline at end of file +components = [ "rustfmt", "rustc", "rust-std", "cargo", "clippy", "llvm-tools-preview"] From 02c261379a42deab303331aa835d76751da06085 Mon Sep 17 00:00:00 2001 From: Gabriel Facco de Arruda Date: Mon, 29 Jan 2024 13:15:38 +0800 Subject: [PATCH 2/7] feat: INV4 + Staking for InvArch --- invarch/Cargo.lock | 221 +++++++++++++++++++++- invarch/node/src/chain_spec.rs | 1 + invarch/runtime/Cargo.toml | 27 ++- invarch/runtime/src/assets.rs | 8 + invarch/runtime/src/balances.rs | 2 +- invarch/runtime/src/common_types.rs | 3 + invarch/runtime/src/inflation.rs | 34 ++++ invarch/runtime/src/inv4.rs | 277 ++++++++++++++++++++++++++++ invarch/runtime/src/lib.rs | 29 ++- invarch/runtime/src/staking.rs | 41 ++++ 10 files changed, 632 insertions(+), 11 deletions(-) create mode 100644 invarch/runtime/src/assets.rs create mode 100644 invarch/runtime/src/common_types.rs create mode 100644 invarch/runtime/src/inflation.rs create mode 100644 invarch/runtime/src/inv4.rs create mode 100644 invarch/runtime/src/staking.rs diff --git a/invarch/Cargo.lock b/invarch/Cargo.lock index 80a20406..f83213fa 100644 --- a/invarch/Cargo.lock +++ b/invarch/Cargo.lock @@ -3006,7 +3006,7 @@ dependencies = [ "Inflector", "cfg-expr", "derive-syn-parse", - "frame-support-procedural-tools", + "frame-support-procedural-tools 4.0.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.43)", "itertools 0.10.5", "proc-macro-warning", "proc-macro2", @@ -3014,18 +3014,38 @@ dependencies = [ "syn 2.0.39", ] +[[package]] +name = "frame-support-procedural-tools" +version = "4.0.0-dev" +dependencies = [ + "frame-support-procedural-tools-derive 3.0.0", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.39", +] + [[package]] name = "frame-support-procedural-tools" version = "4.0.0-dev" source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.43#5e49f6e44820affccaf517fd22af564f4b495d40" dependencies = [ - "frame-support-procedural-tools-derive", + "frame-support-procedural-tools-derive 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.43)", "proc-macro-crate", "proc-macro2", "quote", "syn 2.0.39", ] +[[package]] +name = "frame-support-procedural-tools-derive" +version = "3.0.0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] + [[package]] name = "frame-support-procedural-tools-derive" version = "3.0.0" @@ -3933,6 +3953,20 @@ dependencies = [ "xcm", ] +[[package]] +name = "invarch-primitives" +version = "0.1.0-dev" +source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#bf425e26fc062940452b53056ae1a1edba460f39" +dependencies = [ + "frame-system", + "parity-scale-codec", + "scale-info", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", +] + [[package]] name = "invarch-runtime" version = "1.0.0" @@ -3955,13 +3989,19 @@ dependencies = [ "frame-try-runtime", "hex-literal 0.3.4", "log", + "modified-construct-runtime", + "orml-tokens 0.4.1-dev (git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.43)", + "orml-traits 0.4.1-dev (git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.43)", "orml-vesting", "orml-xcm", "pallet-aura", "pallet-authorship", "pallet-balances", + "pallet-checked-inflation", "pallet-collator-selection", "pallet-identity", + "pallet-inv4", + "pallet-ocif-staking", "pallet-session", "pallet-sudo", "pallet-timestamp", @@ -5294,6 +5334,21 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "modified-construct-runtime" +version = "4.0.0-dev" +dependencies = [ + "Inflector", + "cfg-expr", + "derive-syn-parse", + "frame-support-procedural-tools 4.0.0-dev", + "itertools 0.10.5", + "proc-macro-warning", + "proc-macro2", + "quote", + "syn 2.0.39", +] + [[package]] name = "multiaddr" version = "0.17.1" @@ -5711,6 +5766,101 @@ dependencies = [ "num-traits", ] +[[package]] +name = "orml-tokens" +version = "0.4.1-dev" +source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.43#28a2e6f0df9540d91db4018c7ecebb8bfc217a2a" +dependencies = [ + "frame-support", + "frame-system", + "orml-traits 0.4.1-dev (git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.43)", + "parity-scale-codec", + "scale-info", + "serde", + "sp-arithmetic", + "sp-runtime", + "sp-std", +] + +[[package]] +name = "orml-tokens" +version = "0.4.1-dev" +source = "git+https://github.com/arrudagates/open-runtime-module-library?rev=7ecebeab7e3dbc2226ed58d32ee159271a8176ae#7ecebeab7e3dbc2226ed58d32ee159271a8176ae" +dependencies = [ + "frame-support", + "frame-system", + "orml-traits 0.4.1-dev (git+https://github.com/arrudagates/open-runtime-module-library?rev=7ecebeab7e3dbc2226ed58d32ee159271a8176ae)", + "parity-scale-codec", + "scale-info", + "sp-arithmetic", + "sp-runtime", + "sp-std", +] + +[[package]] +name = "orml-traits" +version = "0.4.1-dev" +source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.43#28a2e6f0df9540d91db4018c7ecebb8bfc217a2a" +dependencies = [ + "frame-support", + "impl-trait-for-tuples", + "num-traits", + "orml-utilities 0.4.1-dev (git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.43)", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "xcm", +] + +[[package]] +name = "orml-traits" +version = "0.4.1-dev" +source = "git+https://github.com/arrudagates/open-runtime-module-library?rev=7ecebeab7e3dbc2226ed58d32ee159271a8176ae#7ecebeab7e3dbc2226ed58d32ee159271a8176ae" +dependencies = [ + "frame-support", + "impl-trait-for-tuples", + "num-traits", + "orml-utilities 0.4.1-dev (git+https://github.com/arrudagates/open-runtime-module-library?rev=7ecebeab7e3dbc2226ed58d32ee159271a8176ae)", + "parity-scale-codec", + "scale-info", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "xcm", +] + +[[package]] +name = "orml-utilities" +version = "0.4.1-dev" +source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.43#28a2e6f0df9540d91db4018c7ecebb8bfc217a2a" +dependencies = [ + "frame-support", + "parity-scale-codec", + "scale-info", + "serde", + "sp-io", + "sp-runtime", + "sp-std", +] + +[[package]] +name = "orml-utilities" +version = "0.4.1-dev" +source = "git+https://github.com/arrudagates/open-runtime-module-library?rev=7ecebeab7e3dbc2226ed58d32ee159271a8176ae#7ecebeab7e3dbc2226ed58d32ee159271a8176ae" +dependencies = [ + "frame-support", + "parity-scale-codec", + "scale-info", + "sp-io", + "sp-runtime", + "sp-std", +] + [[package]] name = "orml-vesting" version = "0.4.1-dev" @@ -5928,6 +6078,26 @@ dependencies = [ "sp-std", ] +[[package]] +name = "pallet-checked-inflation" +version = "0.1.0-dev" +source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#bf425e26fc062940452b53056ae1a1edba460f39" +dependencies = [ + "frame-support", + "frame-system", + "num-traits", + "pallet-session", + "parity-scale-codec", + "scale-info", + "serde", + "sp-arithmetic", + "sp-core", + "sp-io", + "sp-runtime", + "sp-staking", + "sp-std", +] + [[package]] name = "pallet-child-bounties" version = "4.0.0-dev" @@ -6166,6 +6336,30 @@ dependencies = [ "sp-std", ] +[[package]] +name = "pallet-inv4" +version = "0.1.0-dev" +source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#bf425e26fc062940452b53056ae1a1edba460f39" +dependencies = [ + "frame-benchmarking", + "frame-support", + "frame-system", + "invarch-primitives", + "log", + "orml-tokens 0.4.1-dev (git+https://github.com/arrudagates/open-runtime-module-library?rev=7ecebeab7e3dbc2226ed58d32ee159271a8176ae)", + "pallet-balances", + "parity-scale-codec", + "scale-info", + "serde", + "smallvec", + "sp-arithmetic", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "xcm", +] + [[package]] name = "pallet-membership" version = "4.0.0-dev" @@ -6299,6 +6493,29 @@ dependencies = [ "sp-std", ] +[[package]] +name = "pallet-ocif-staking" +version = "0.1.0-dev" +source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#bf425e26fc062940452b53056ae1a1edba460f39" +dependencies = [ + "frame-support", + "frame-system", + "num-traits", + "pallet-balances", + "pallet-inv4", + "pallet-session", + "pallet-timestamp", + "parity-scale-codec", + "scale-info", + "serde", + "sp-arithmetic", + "sp-core", + "sp-io", + "sp-runtime", + "sp-staking", + "sp-std", +] + [[package]] name = "pallet-offences" version = "4.0.0-dev" diff --git a/invarch/node/src/chain_spec.rs b/invarch/node/src/chain_spec.rs index 70236fbb..90d8b4f8 100644 --- a/invarch/node/src/chain_spec.rs +++ b/invarch/node/src/chain_spec.rs @@ -328,5 +328,6 @@ fn testnet_genesis( // Assign network admin rights. key: Some(root_key), }, + core_assets: Default::default(), } } diff --git a/invarch/runtime/Cargo.toml b/invarch/runtime/Cargo.toml index 322c0b42..5943a0af 100644 --- a/invarch/runtime/Cargo.toml +++ b/invarch/runtime/Cargo.toml @@ -20,6 +20,12 @@ log = { version = "0.4.17", default-features = false } scale-info = { version = "2.3.1", default-features = false, features = ["derive"] } smallvec = "1.10.0" +modified-construct-runtime = { path = "../../modified-construct-runtime", default-features = false } + +# InvArch +pallet-inv4 = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } +pallet-ocif-staking = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } +pallet-checked-inflation = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } # Substrate frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true, branch = "polkadot-v0.9.43" } @@ -58,6 +64,8 @@ pallet-tx-pause = { path = "../pallet-tx-pause", default-features = false } # ORML orml-xcm = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } orml-vesting = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } +orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } +orml-tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.43" } # Polkadot pallet-xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } @@ -100,21 +108,22 @@ std = [ "frame-support/std", "frame-system-rpc-runtime-api/std", "frame-system/std", - "orml-vesting/std", - "orml-xcm/std", + "orml-tokens/std", + "orml-vesting/std", + "orml-xcm/std", "pallet-aura/std", "pallet-authorship/std", "pallet-balances/std", "pallet-collator-selection/std", - "pallet-identity/std", + "pallet-identity/std", "pallet-session/std", "pallet-sudo/std", "pallet-timestamp/std", "pallet-transaction-payment-rpc-runtime-api/std", "pallet-transaction-payment/std", - "pallet-treasury/std", - "pallet-tx-pause/std", - "pallet-utility/std", + "pallet-treasury/std", + "pallet-tx-pause/std", + "pallet-utility/std", "pallet-xcm/std", "parachain-info/std", "polkadot-parachain/std", @@ -133,6 +142,12 @@ std = [ "xcm-builder/std", "xcm-executor/std", "xcm/std", + + "modified-construct-runtime/std", + + "pallet-inv4/std", + "pallet-checked-inflation/std", + "pallet-ocif-staking/std" ] runtime-benchmarks = [ diff --git a/invarch/runtime/src/assets.rs b/invarch/runtime/src/assets.rs new file mode 100644 index 00000000..50edc2ba --- /dev/null +++ b/invarch/runtime/src/assets.rs @@ -0,0 +1,8 @@ +use crate::common_types::AssetId; +use frame_support::parameter_types; + +pub const VARCH_ASSET_ID: AssetId = 0; + +parameter_types! { + pub const NativeAssetId: AssetId = VARCH_ASSET_ID; +} diff --git a/invarch/runtime/src/balances.rs b/invarch/runtime/src/balances.rs index 16b3dbeb..e9d1aa96 100644 --- a/invarch/runtime/src/balances.rs +++ b/invarch/runtime/src/balances.rs @@ -60,7 +60,7 @@ impl WeightToFeePolynomial for WeightToFee { } } -type NegativeImbalance = >::NegativeImbalance; +pub type NegativeImbalance = >::NegativeImbalance; pub struct ToCollatorPot; impl OnUnbalanced for ToCollatorPot { diff --git a/invarch/runtime/src/common_types.rs b/invarch/runtime/src/common_types.rs new file mode 100644 index 00000000..ebac5b55 --- /dev/null +++ b/invarch/runtime/src/common_types.rs @@ -0,0 +1,3 @@ +pub type CommonId = u32; + +pub type AssetId = u32; diff --git a/invarch/runtime/src/inflation.rs b/invarch/runtime/src/inflation.rs new file mode 100644 index 00000000..f189a5ec --- /dev/null +++ b/invarch/runtime/src/inflation.rs @@ -0,0 +1,34 @@ +use crate::{ + balances::NegativeImbalance, Balance, Balances, BlockNumber, OcifStaking, Runtime, + RuntimeEvent, DAYS, +}; +use frame_support::{parameter_types, traits::OnUnbalanced}; +use sp_runtime::Perbill; + +pub const TEN_PERCENT_PER_YEAR: pallet_checked_inflation::InflationMethod = + pallet_checked_inflation::InflationMethod::Rate(Perbill::from_percent(10)); + +const YEAR: u32 = 365; + +parameter_types! { + pub const BlocksPerEra: BlockNumber = DAYS; + pub const ErasPerYear: u32 = YEAR; + pub const Inflation: pallet_checked_inflation::InflationMethod = TEN_PERCENT_PER_YEAR; +} + +pub struct DealWithInflation; +impl OnUnbalanced for DealWithInflation { + fn on_unbalanced(amount: NegativeImbalance) { + OcifStaking::rewards(amount); + } +} + +impl pallet_checked_inflation::Config for Runtime { + type BlocksPerEra = BlocksPerEra; + type Currency = Balances; + type RuntimeEvent = RuntimeEvent; + type ErasPerYear = ErasPerYear; + type Inflation = Inflation; + type DealWithInflation = DealWithInflation; + type WeightInfo = pallet_checked_inflation::weights::SubstrateWeight; +} diff --git a/invarch/runtime/src/inv4.rs b/invarch/runtime/src/inv4.rs new file mode 100644 index 00000000..4955cb84 --- /dev/null +++ b/invarch/runtime/src/inv4.rs @@ -0,0 +1,277 @@ +use crate::{ + balances::DealWithFees, common_types::CommonId, AccountId, Balance, Balances, CoreAssets, + ParachainInfo, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, UNIT, +}; +use codec::{Decode, Encode}; +use frame_support::{ + parameter_types, + traits::{ + fungibles::{Balanced, Credit, Inspect, Unbalanced}, + Contains, Currency, OnUnbalanced, + }, +}; +use pallet_inv4::fee_handling::{FeeAsset, FeeAssetNegativeImbalance, MultisigFeeHandler}; +use pallet_transaction_payment::ChargeTransactionPayment; +use scale_info::TypeInfo; +use sp_core::ConstU32; +use sp_runtime::traits::{One, SignedExtension, Zero}; + +parameter_types! { + pub const MaxMetadata: u32 = 10000; + pub const MaxCallers: u32 = 10000; + pub const CoreSeedBalance: Balance = 1000000u128; + pub const CoreCreationFee: Balance = UNIT * 100; + + pub const RelayCoreCreationFee: Balance = UNIT; + pub const MaxCallSize: u32 = 50 * 1024; + + pub ParaId: u32 = ParachainInfo::parachain_id().into(); + + pub const NoId: () = (); +} + +impl pallet_inv4::Config for Runtime { + type MaxMetadata = MaxMetadata; + type CoreId = CommonId; + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type RuntimeCall = RuntimeCall; + type MaxCallers = MaxCallers; + type CoreSeedBalance = CoreSeedBalance; + type AssetsProvider = CoreAssets; + type RuntimeOrigin = RuntimeOrigin; + type CoreCreationFee = CoreCreationFee; + type FeeCharger = FeeCharger; + type WeightInfo = pallet_inv4::weights::SubstrateWeight; + + type Tokens = NoTokens; + type RelayAssetId = NoId; + type RelayCoreCreationFee = RelayCoreCreationFee; + + type MaxCallSize = MaxCallSize; + + type ParaId = ParaId; +} + +pub struct NoTokens; + +impl Inspect for NoTokens { + type AssetId = (); + type Balance = u128; + + fn total_issuance(_asset: Self::AssetId) -> Self::Balance { + Zero::zero() + } + + fn minimum_balance(_asset: Self::AssetId) -> Self::Balance { + Zero::zero() + } + + fn total_balance(_asset: Self::AssetId, _who: &AccountId) -> Self::Balance { + Zero::zero() + } + + fn balance(_asset: Self::AssetId, _who: &AccountId) -> Self::Balance { + Zero::zero() + } + + fn reducible_balance( + _asset: Self::AssetId, + _who: &AccountId, + _preservation: frame_support::traits::tokens::Preservation, + _force: frame_support::traits::tokens::Fortitude, + ) -> Self::Balance { + Zero::zero() + } + + fn can_deposit( + _asset: Self::AssetId, + _who: &AccountId, + _amount: Self::Balance, + _provenance: frame_support::traits::tokens::Provenance, + ) -> frame_support::traits::tokens::DepositConsequence { + frame_support::traits::tokens::DepositConsequence::UnknownAsset + } + + fn can_withdraw( + _asset: Self::AssetId, + _who: &AccountId, + _amount: Self::Balance, + ) -> frame_support::traits::tokens::WithdrawConsequence { + frame_support::traits::tokens::WithdrawConsequence::UnknownAsset + } + + fn asset_exists(_asset: Self::AssetId) -> bool { + false + } + + fn active_issuance(_asset: Self::AssetId) -> Self::Balance { + Zero::zero() + } +} + +impl Unbalanced for NoTokens { + fn handle_dust(_dust: frame_support::traits::fungibles::Dust) {} + + fn write_balance( + _asset: Self::AssetId, + _who: &AccountId, + _amount: Self::Balance, + ) -> Result, sp_runtime::DispatchError> { + Err(sp_runtime::DispatchError::Token( + sp_runtime::TokenError::UnknownAsset, + )) + } + + fn set_total_issuance(_asset: Self::AssetId, _amount: Self::Balance) {} +} + +pub struct NoHandle; +impl frame_support::traits::tokens::fungibles::HandleImbalanceDrop<(), u128> for NoHandle { + fn handle(_asset: (), _amount: u128) {} +} + +impl Balanced for NoTokens { + type OnDropCredit = NoHandle; + type OnDropDebt = NoHandle; +} + +#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo, Debug)] +pub struct FeeCharger; + +impl MultisigFeeHandler for FeeCharger { + type Pre = + as SignedExtension>::Pre; + + fn pre_dispatch( + fee_asset: &FeeAsset, + who: &AccountId, + call: &RuntimeCall, + info: &sp_runtime::traits::DispatchInfoOf, + len: usize, + ) -> Result { + match fee_asset { + FeeAsset::Native => ChargeTransactionPayment::::from(Zero::zero()) + .pre_dispatch(who, call, info, len), + + FeeAsset::Relay => Err(frame_support::unsigned::TransactionValidityError::Invalid( + sp_runtime::transaction_validity::InvalidTransaction::Payment, + )), + } + } + + fn post_dispatch( + fee_asset: &FeeAsset, + pre: Option, + info: &sp_runtime::traits::DispatchInfoOf, + post_info: &sp_runtime::traits::PostDispatchInfoOf, + len: usize, + result: &sp_runtime::DispatchResult, + ) -> Result<(), frame_support::unsigned::TransactionValidityError> { + match fee_asset { + FeeAsset::Native => ChargeTransactionPayment::::post_dispatch( + pre, info, post_info, len, result, + ), + + FeeAsset::Relay => Err(frame_support::unsigned::TransactionValidityError::Invalid( + sp_runtime::transaction_validity::InvalidTransaction::Payment, + )), + } + } + + fn handle_creation_fee( + imbalance: FeeAssetNegativeImbalance< + >::NegativeImbalance, + Credit, + >, + ) { + match imbalance { + FeeAssetNegativeImbalance::Native(imb) => DealWithFees::on_unbalanced(imb), + + FeeAssetNegativeImbalance::Relay(_) => {} + } + } +} + +orml_traits::parameter_type_with_key! { + pub CoreExistentialDeposits: |_currency_id: ::CoreId| -> Balance { + Balance::one() + }; +} + +pub struct CoreDustRemovalWhitelist; +impl Contains for CoreDustRemovalWhitelist { + fn contains(_: &AccountId) -> bool { + true + } +} + +pub struct DisallowIfFrozen; +impl orml_traits::currency::OnTransfer::CoreId, Balance> + for DisallowIfFrozen +{ + fn on_transfer( + currency_id: ::CoreId, + _from: &AccountId, + _to: &AccountId, + _amount: Balance, + ) -> sp_runtime::DispatchResult { + if let Some(true) = crate::INV4::is_asset_frozen(currency_id) { + Err(sp_runtime::DispatchError::Token( + sp_runtime::TokenError::Frozen, + )) + } else { + Ok(()) + } + } +} + +pub struct HandleNewMembers; +impl orml_traits::Happened<(AccountId, ::CoreId)> + for HandleNewMembers +{ + fn happened((member, core_id): &(AccountId, ::CoreId)) { + crate::INV4::add_member(core_id, member) + } +} + +pub struct HandleRemovedMembers; +impl orml_traits::Happened<(AccountId, ::CoreId)> + for HandleRemovedMembers +{ + fn happened((member, core_id): &(AccountId, ::CoreId)) { + crate::INV4::remove_member(core_id, member) + } +} + +pub struct INV4TokenHooks; +impl + orml_traits::currency::MutationHooks< + AccountId, + ::CoreId, + Balance, + > for INV4TokenHooks +{ + type PreTransfer = DisallowIfFrozen; + type OnDust = (); + type OnSlash = (); + type PreDeposit = (); + type PostDeposit = (); + type PostTransfer = (); + type OnNewTokenAccount = HandleNewMembers; + type OnKilledTokenAccount = HandleRemovedMembers; +} + +impl orml_tokens::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type Amount = i128; + type CurrencyId = ::CoreId; + type WeightInfo = (); + type ExistentialDeposits = CoreExistentialDeposits; + type MaxLocks = ConstU32<0u32>; + type MaxReserves = ConstU32<0u32>; + type DustRemovalWhitelist = CoreDustRemovalWhitelist; + type ReserveIdentifier = [u8; 8]; + type CurrencyHooks = INV4TokenHooks; +} diff --git a/invarch/runtime/src/lib.rs b/invarch/runtime/src/lib.rs index 2adb9381..c4227713 100644 --- a/invarch/runtime/src/lib.rs +++ b/invarch/runtime/src/lib.rs @@ -8,7 +8,6 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use frame_support::{ - construct_runtime, dispatch::DispatchClass, parameter_types, traits::{ConstU32, ConstU64, Contains, Everything, InsideBoth}, @@ -38,7 +37,12 @@ use sp_version::RuntimeVersion; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; +mod assets; pub mod balances; +mod common_types; +mod inflation; +mod inv4; +mod staking; mod weights; pub mod xcm_config; @@ -415,8 +419,22 @@ impl pallet_tx_pause::Config for Runtime { type WhitelistedCalls = TxPauseWhitelistedCalls; } +use modified_construct_runtime::construct_runtime_modified; + +impl From for Result, RuntimeOrigin> { + fn from(val: RuntimeOrigin) -> Self { + match val.caller { + OriginCaller::system(l) => Ok(l), + OriginCaller::INV4(pallet_inv4::origin::INV4Origin::Multisig(l)) => { + Ok(frame_system::RawOrigin::Signed(l.to_account_id())) + } + _ => Err(val), + } + } +} + // Create the runtime by composing the FRAME pallets that were previously configured. -construct_runtime!( +construct_runtime_modified!( pub enum Runtime where Block = Block, NodeBlock = opaque::Block, @@ -456,6 +474,13 @@ construct_runtime!( // Extra Identity: pallet_identity::{Pallet, Call, Storage, Event} = 40, + CheckedInflation: pallet_checked_inflation::{Pallet, Storage, Event, Call} = 50, + OcifStaking: pallet_ocif_staking::{Pallet, Call, Storage, Event} = 51, + + INV4: pallet_inv4::{Pallet, Call, Storage, Event, Origin} = 71, + CoreAssets: orml_tokens::{Pallet, Storage, Call, Event, Config} = 72, + // 73 reserved for pallet-rings + } ); diff --git a/invarch/runtime/src/staking.rs b/invarch/runtime/src/staking.rs new file mode 100644 index 00000000..88e95073 --- /dev/null +++ b/invarch/runtime/src/staking.rs @@ -0,0 +1,41 @@ +use crate::{ + Balance, Balances, BlockNumber, ExistentialDeposit, Runtime, RuntimeEvent, DAYS, UNIT, +}; +use frame_support::{parameter_types, PalletId}; + +parameter_types! { + pub const BlocksPerEra: BlockNumber = DAYS; + pub const RegisterDeposit: Balance = 500 * UNIT; + pub const MaxStakersPerCore: u32 = 10000; + pub const MinimumStakingAmount: Balance = 10 * UNIT; + pub const MaxEraStakeValues: u32 = 5; + pub const MaxUnlockingChunks: u32 = 5; + pub const UnbondingPeriod: u32 = 7; + pub const OcifStakingPot: PalletId = PalletId(*b"inv/stak"); + pub const RewardRatio: (u32, u32) = (60, 40); + pub const StakeThresholdForActiveCore: Balance = 25000 * UNIT; + pub const MaxNameLength: u32 = 20; + pub const MaxDescriptionLength: u32 = 300; + pub const MaxImageUrlLength: u32 = 100; +} + +impl pallet_ocif_staking::Config for Runtime { + type Currency = Balances; + type BlocksPerEra = BlocksPerEra; + type RegisterDeposit = RegisterDeposit; + type RuntimeEvent = RuntimeEvent; + type MaxStakersPerCore = MaxStakersPerCore; + type ExistentialDeposit = ExistentialDeposit; + type PotId = OcifStakingPot; + type MaxUnlocking = MaxUnlockingChunks; + type UnbondingPeriod = UnbondingPeriod; + type MinimumStakingAmount = MinimumStakingAmount; + type MaxEraStakeValues = MaxEraStakeValues; + type RewardRatio = RewardRatio; + type StakeThresholdForActiveCore = StakeThresholdForActiveCore; + type MaxNameLength = MaxNameLength; + type MaxDescriptionLength = MaxDescriptionLength; + type MaxImageUrlLength = MaxImageUrlLength; + + type WeightInfo = pallet_ocif_staking::weights::SubstrateWeight; +} From 0e7119eaaf49ad2b5b5759e1112bf2e7623f318b Mon Sep 17 00:00:00 2001 From: Gabriel Facco de Arruda Date: Mon, 29 Jan 2024 13:16:49 +0800 Subject: [PATCH 3/7] chore: Bump InvArch spec version --- invarch/runtime/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/invarch/runtime/src/lib.rs b/invarch/runtime/src/lib.rs index c4227713..1118be01 100644 --- a/invarch/runtime/src/lib.rs +++ b/invarch/runtime/src/lib.rs @@ -139,7 +139,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("invarch"), impl_name: create_runtime_str!("invarch"), authoring_version: 1, - spec_version: 4, + spec_version: 5, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, From a46e83f4cd9d7016ec581f6ab598283949629b2b Mon Sep 17 00:00:00 2001 From: Gabriel Facco de Arruda Date: Mon, 29 Jan 2024 16:01:35 +0800 Subject: [PATCH 4/7] refactor: Change tinkernet migrations and set commit hashes on deps --- invarch/Cargo.lock | 8 +- invarch/runtime/Cargo.toml | 6 +- tinkernet/Cargo.lock | 32 +++- tinkernet/runtime/Cargo.toml | 14 +- tinkernet/runtime/src/inv4.rs | 16 +- tinkernet/runtime/src/lib.rs | 3 + tinkernet/runtime/src/migrations.rs | 143 +++++++++++++----- .../src/rings/{statemine.rs => asset_hub.rs} | 20 +-- tinkernet/runtime/src/rings/mod.rs | 8 + 9 files changed, 170 insertions(+), 80 deletions(-) rename tinkernet/runtime/src/rings/{statemine.rs => asset_hub.rs} (61%) diff --git a/invarch/Cargo.lock b/invarch/Cargo.lock index f83213fa..12777c29 100644 --- a/invarch/Cargo.lock +++ b/invarch/Cargo.lock @@ -3956,7 +3956,7 @@ dependencies = [ [[package]] name = "invarch-primitives" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#bf425e26fc062940452b53056ae1a1edba460f39" +source = "git+https://github.com/InvArch/InvArch-Frames?rev=ce1c1421550019472c622b7896e3fbd7f03d2ec5#ce1c1421550019472c622b7896e3fbd7f03d2ec5" dependencies = [ "frame-system", "parity-scale-codec", @@ -6081,7 +6081,7 @@ dependencies = [ [[package]] name = "pallet-checked-inflation" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#bf425e26fc062940452b53056ae1a1edba460f39" +source = "git+https://github.com/InvArch/InvArch-Frames?rev=ce1c1421550019472c622b7896e3fbd7f03d2ec5#ce1c1421550019472c622b7896e3fbd7f03d2ec5" dependencies = [ "frame-support", "frame-system", @@ -6339,7 +6339,7 @@ dependencies = [ [[package]] name = "pallet-inv4" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#bf425e26fc062940452b53056ae1a1edba460f39" +source = "git+https://github.com/InvArch/InvArch-Frames?rev=ce1c1421550019472c622b7896e3fbd7f03d2ec5#ce1c1421550019472c622b7896e3fbd7f03d2ec5" dependencies = [ "frame-benchmarking", "frame-support", @@ -6496,7 +6496,7 @@ dependencies = [ [[package]] name = "pallet-ocif-staking" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#bf425e26fc062940452b53056ae1a1edba460f39" +source = "git+https://github.com/InvArch/InvArch-Frames?rev=ce1c1421550019472c622b7896e3fbd7f03d2ec5#ce1c1421550019472c622b7896e3fbd7f03d2ec5" dependencies = [ "frame-support", "frame-system", diff --git a/invarch/runtime/Cargo.toml b/invarch/runtime/Cargo.toml index 5943a0af..c9056366 100644 --- a/invarch/runtime/Cargo.toml +++ b/invarch/runtime/Cargo.toml @@ -23,9 +23,9 @@ smallvec = "1.10.0" modified-construct-runtime = { path = "../../modified-construct-runtime", default-features = false } # InvArch -pallet-inv4 = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } -pallet-ocif-staking = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } -pallet-checked-inflation = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } +pallet-inv4 = { git = "https://github.com/InvArch/InvArch-Frames", rev = "ce1c1421550019472c622b7896e3fbd7f03d2ec5", default-features = false } +pallet-ocif-staking = { git = "https://github.com/InvArch/InvArch-Frames", rev = "ce1c1421550019472c622b7896e3fbd7f03d2ec5", default-features = false } +pallet-checked-inflation = { git = "https://github.com/InvArch/InvArch-Frames", rev = "ce1c1421550019472c622b7896e3fbd7f03d2ec5", default-features = false } # Substrate frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true, branch = "polkadot-v0.9.43" } diff --git a/tinkernet/Cargo.lock b/tinkernet/Cargo.lock index 2ea026de..7009a215 100644 --- a/tinkernet/Cargo.lock +++ b/tinkernet/Cargo.lock @@ -3845,7 +3845,7 @@ dependencies = [ [[package]] name = "invarch-primitives" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#d83e95692d178982cc2bd4279f31f3eba31d9c97" +source = "git+https://github.com/InvArch/InvArch-Frames?rev=ce1c1421550019472c622b7896e3fbd7f03d2ec5#ce1c1421550019472c622b7896e3fbd7f03d2ec5" dependencies = [ "frame-system", "parity-scale-codec", @@ -6020,7 +6020,7 @@ dependencies = [ [[package]] name = "pallet-checked-inflation" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#d83e95692d178982cc2bd4279f31f3eba31d9c97" +source = "git+https://github.com/InvArch/InvArch-Frames?rev=ce1c1421550019472c622b7896e3fbd7f03d2ec5#ce1c1421550019472c622b7896e3fbd7f03d2ec5" dependencies = [ "frame-benchmarking", "frame-support", @@ -6279,7 +6279,7 @@ dependencies = [ [[package]] name = "pallet-inv4" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#d83e95692d178982cc2bd4279f31f3eba31d9c97" +source = "git+https://github.com/InvArch/InvArch-Frames?rev=ce1c1421550019472c622b7896e3fbd7f03d2ec5#ce1c1421550019472c622b7896e3fbd7f03d2ec5" dependencies = [ "frame-benchmarking", "frame-support", @@ -6452,7 +6452,7 @@ dependencies = [ [[package]] name = "pallet-ocif-staking" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#d83e95692d178982cc2bd4279f31f3eba31d9c97" +source = "git+https://github.com/InvArch/InvArch-Frames?rev=ce1c1421550019472c622b7896e3fbd7f03d2ec5#ce1c1421550019472c622b7896e3fbd7f03d2ec5" dependencies = [ "frame-benchmarking", "frame-support", @@ -6601,7 +6601,7 @@ dependencies = [ [[package]] name = "pallet-rings" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=gabriel-new_derivation#d83e95692d178982cc2bd4279f31f3eba31d9c97" +source = "git+https://github.com/InvArch/InvArch-Frames?rev=ce1c1421550019472c622b7896e3fbd7f03d2ec5#ce1c1421550019472c622b7896e3fbd7f03d2ec5" dependencies = [ "frame-benchmarking", "frame-support", @@ -12451,6 +12451,7 @@ dependencies = [ "pallet-identity", "pallet-inv4", "pallet-maintenance-mode", + "pallet-message-queue", "pallet-multisig", "pallet-ocif-staking", "pallet-preimage", @@ -12467,8 +12468,10 @@ dependencies = [ "pallet-xcm", "parachain-info", "parity-scale-codec", + "polkadot-core-primitives", "polkadot-parachain", "polkadot-runtime-common", + "polkadot-runtime-parachains", "scale-info", "serde", "smallvec", @@ -12488,6 +12491,7 @@ dependencies = [ "xcm", "xcm-builder", "xcm-executor", + "xcm-simulator", ] [[package]] @@ -14283,6 +14287,24 @@ dependencies = [ "syn 2.0.28", ] +[[package]] +name = "xcm-simulator" +version = "0.9.43" +source = "git+https://github.com/paritytech/polkadot?branch=release-v0.9.43#ba42b9ce51d25bdaf52d2c61e0763a6e3da50d25" +dependencies = [ + "frame-support", + "parity-scale-codec", + "paste", + "polkadot-core-primitives", + "polkadot-parachain", + "polkadot-runtime-parachains", + "sp-io", + "sp-std", + "xcm", + "xcm-builder", + "xcm-executor", +] + [[package]] name = "yamux" version = "0.10.2" diff --git a/tinkernet/runtime/Cargo.toml b/tinkernet/runtime/Cargo.toml index df7b88ee..ef3eaad9 100644 --- a/tinkernet/runtime/Cargo.toml +++ b/tinkernet/runtime/Cargo.toml @@ -24,10 +24,10 @@ smallvec = "1.6.1" getrandom = { version = "0.2.4", default-features = false, features = ["js"] } # InvArch Pallets -pallet-inv4 = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } -pallet-ocif-staking = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } -pallet-checked-inflation = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } -pallet-rings = { git = "https://github.com/InvArch/InvArch-Frames", branch = "gabriel-new_derivation", default-features = false } +pallet-inv4 = { git = "https://github.com/InvArch/InvArch-Frames", rev = "ce1c1421550019472c622b7896e3fbd7f03d2ec5", default-features = false } +pallet-ocif-staking = { git = "https://github.com/InvArch/InvArch-Frames", rev = "ce1c1421550019472c622b7896e3fbd7f03d2ec5", default-features = false } +pallet-checked-inflation = { git = "https://github.com/InvArch/InvArch-Frames", rev = "ce1c1421550019472c622b7896e3fbd7f03d2ec5", default-features = false } +pallet-rings = { git = "https://github.com/InvArch/InvArch-Frames", rev = "ce1c1421550019472c622b7896e3fbd7f03d2ec5", default-features = false } #pallet-inv4 = { path = "../../../InvArch-Frames/INV4/pallet-inv4", default-features = false } #pallet-ocif-staking = { path = "../../../InvArch-Frames/OCIF/staking", default-features = false } @@ -118,6 +118,12 @@ cumulus-primitives-utility = { git = "https://github.com/paritytech/cumulus", de pallet-collator-selection = { git = "https://github.com/paritytech/cumulus", default-features = false, branch = "polkadot-v0.9.43" } parachain-info = { git = "https://github.com/paritytech/cumulus", default-features = false, branch = "polkadot-v0.9.43" } +[dev-dependencies] +xcm-simulator = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } +polkadot-core-primitives = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } +polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.43" } +pallet-message-queue = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" } + [features] aura = [] diff --git a/tinkernet/runtime/src/inv4.rs b/tinkernet/runtime/src/inv4.rs index f057b95c..1f791e7c 100644 --- a/tinkernet/runtime/src/inv4.rs +++ b/tinkernet/runtime/src/inv4.rs @@ -44,8 +44,8 @@ impl pallet_inv4::Config for Runtime { type WeightInfo = pallet_inv4::weights::SubstrateWeight; type Tokens = Tokens; - type KSMAssetId = RelayAssetId; - type KSMCoreCreationFee = KSMCoreCreationFee; + type RelayAssetId = RelayAssetId; + type RelayCoreCreationFee = KSMCoreCreationFee; type MaxCallSize = MaxCallSize; @@ -75,10 +75,10 @@ impl MultisigFeeHandler for FeeCharger { len: usize, ) -> Result { match fee_asset { - FeeAsset::TNKR => ChargeAssetTxPayment::::from(Zero::zero(), None) + FeeAsset::Native => ChargeAssetTxPayment::::from(Zero::zero(), None) .pre_dispatch(who, call, info, len), - FeeAsset::KSM => { + FeeAsset::Relay => { ChargeAssetTxPayment::::from(Zero::zero(), Some(KSM_ASSET_ID)) .pre_dispatch(who, call, info, len) } @@ -94,11 +94,11 @@ impl MultisigFeeHandler for FeeCharger { result: &sp_runtime::DispatchResult, ) -> Result<(), frame_support::unsigned::TransactionValidityError> { match fee_asset { - FeeAsset::TNKR => { + FeeAsset::Native => { ChargeAssetTxPayment::::post_dispatch(pre, info, post_info, len, result) } - FeeAsset::KSM => { + FeeAsset::Relay => { ChargeAssetTxPayment::::post_dispatch(pre, info, post_info, len, result) } } @@ -111,9 +111,9 @@ impl MultisigFeeHandler for FeeCharger { >, ) { match imbalance { - FeeAssetNegativeImbalance::TNKR(imb) => DealWithFees::on_unbalanced(imb), + FeeAssetNegativeImbalance::Native(imb) => DealWithFees::on_unbalanced(imb), - FeeAssetNegativeImbalance::KSM(imb) => DealWithKSMFees::on_unbalanced(imb), + FeeAssetNegativeImbalance::Relay(imb) => DealWithKSMFees::on_unbalanced(imb), } } } diff --git a/tinkernet/runtime/src/lib.rs b/tinkernet/runtime/src/lib.rs index 9837ed5a..02afdf0d 100644 --- a/tinkernet/runtime/src/lib.rs +++ b/tinkernet/runtime/src/lib.rs @@ -103,6 +103,9 @@ mod staking; mod weights; pub mod xcm_config; +#[cfg(test)] +mod xcm_simulator; + /// Alias to 512-bit hash when used in the context of a transaction signature on the chain. pub type Signature = MultiSignature; diff --git a/tinkernet/runtime/src/migrations.rs b/tinkernet/runtime/src/migrations.rs index dea96ba4..b18b580b 100644 --- a/tinkernet/runtime/src/migrations.rs +++ b/tinkernet/runtime/src/migrations.rs @@ -4,10 +4,11 @@ use log::{info, warn}; pub mod new_core_account_derivation { use super::*; use crate::{common_types::CommonId, AccountId, Identity, Runtime, RuntimeOrigin, Vec, INV4}; + use frame_support::dispatch::GetDispatchInfo; + use pallet_identity::IdentityInfo; use pallet_inv4::{ account_derivation::CoreAccountDerivation, CoreInfoOf, Pallet as INV4Pallet, }; - use sp_runtime::MultiAddress; use sp_std::boxed::Box; fn get_old_accounts() -> Vec<(AccountId, CommonId)> { @@ -15,16 +16,12 @@ pub mod new_core_account_derivation { } fn migrate_inv4_storages(old_accounts: Vec<(AccountId, CommonId)>) { - // let _ = pallet_inv4::CoreByAccount::::clear(1000, None); - old_accounts.iter().for_each(|(old_acc, core_id)| { let new_account = as CoreAccountDerivation>::derive_core_account( *core_id, ); - // pallet_inv4::CoreByAccount::::insert(new_account, core_id); - pallet_inv4::CoreByAccount::::swap(old_acc, new_account); }); @@ -49,23 +46,9 @@ pub mod new_core_account_derivation { *this_core_id, ); - // let ledger = pallet_ocif_staking::pallet::Ledger::::take(old_acc); - // pallet_ocif_staking::pallet::Ledger::::insert(new_account.clone(), ledger); - pallet_ocif_staking::pallet::Ledger::::swap(old_acc, new_account.clone()); pallet_inv4::CoreStorage::::iter_keys().for_each(|staking_core_id| { - // let info = pallet_ocif_staking::pallet::GeneralStakerInfo::::take( - // staking_core_id, - // old_acc, - // ); - - // pallet_ocif_staking::pallet::GeneralStakerInfo::::insert( - // staking_core_id, - // new_account.clone(), - // info, - // ); - pallet_ocif_staking::pallet::GeneralStakerInfo::::swap( staking_core_id, old_acc, @@ -93,26 +76,68 @@ pub mod new_core_account_derivation { }); } - fn migrate_identity_storages(old_accounts: Vec<(AccountId, CommonId)>) { - old_accounts.iter().for_each(|(old_acc, this_core_id)| { - let new_account = - as CoreAccountDerivation>::derive_core_account( - *this_core_id, - ); + fn clear_identities( + old_accounts: Vec<(AccountId, CommonId)>, + ) -> Vec<( + AccountId, + Option< + pallet_identity::Registration< + crate::Balance, + crate::MaxRegistrars, + crate::MaxAdditionalFields, + >, + >, + )> { + old_accounts + .iter() + .map(|(old_acc, this_core_id)| { + let new_account = + as CoreAccountDerivation>::derive_core_account( + *this_core_id, + ); - let maybe_identity = Identity::identity(old_acc); + let maybe_identity = Identity::identity(old_acc); + + if maybe_identity.is_some() { + let _ = Identity::clear_identity(RuntimeOrigin::signed(old_acc.clone())); + } + + (new_account, maybe_identity) + }) + .collect::, + >, + )>>() + } - if let Some(identity) = maybe_identity { - let _ = Identity::kill_identity( - RuntimeOrigin::root(), - MultiAddress::Id(old_acc.clone()), - ); - let _ = Identity::set_identity( - RuntimeOrigin::signed(new_account), - Box::new(identity.info), - ); - } - }); + fn set_new_identities( + new_identities: Vec<( + AccountId, + Option< + pallet_identity::Registration< + crate::Balance, + crate::MaxRegistrars, + crate::MaxAdditionalFields, + >, + >, + )>, + ) { + new_identities + .into_iter() + .for_each(|(new_account, maybe_identity)| { + if let Some(identity) = maybe_identity { + let _ = Identity::set_identity( + RuntimeOrigin::signed(new_account.clone()), + Box::new(identity.info), + ); + } + }) } pub struct MigrateToNewDerivation; @@ -128,19 +153,53 @@ pub mod new_core_account_derivation { } fn on_runtime_upgrade() -> Weight { - let current = INV4::current_storage_version(); + let spec = crate::System::runtime_version().spec_version; - let old_accounts = get_old_accounts(); + if spec == 21 { + let old_accounts = get_old_accounts(); + let old_accounts_len = old_accounts.len() as u64; - if current == 2 { migrate_inv4_storages(old_accounts.clone()); migrate_staking_storages(old_accounts.clone()); + let new_identities = clear_identities(old_accounts.clone()); migrate_balances_storages(old_accounts.clone()); - migrate_identity_storages(old_accounts.clone()); + set_new_identities(new_identities.clone()); info!("applied successfully"); - ::DbWeight::get().reads_writes(0, 1) + let clear_identities_weight = ::DbWeight::get() + .reads(old_accounts_len) + + (pallet_identity::Call::::clear_identity {} + .get_dispatch_info() + .weight + * old_accounts_len); + + let set_new_identities_weight = pallet_identity::Call::::set_identity { + info: Box::new(IdentityInfo { + additional: Default::default(), + display: Default::default(), + legal: Default::default(), + riot: Default::default(), + web: Default::default(), + twitter: Default::default(), + email: Default::default(), + pgp_fingerprint: Default::default(), + image: Default::default(), + }), + } + .get_dispatch_info() + .weight + * (new_identities.clone().len() as u64); + + clear_identities_weight + + set_new_identities_weight + + ::DbWeight::get().reads(2) + + ::DbWeight::get() + .reads_writes(old_accounts_len, old_accounts_len * 2) + + ::DbWeight::get() + .reads_writes(old_accounts_len, old_accounts_len * 2) + + ::DbWeight::get() + .writes(old_accounts_len * 6) } else { warn!("Skipping, should be removed"); ::DbWeight::get().reads(1) diff --git a/tinkernet/runtime/src/rings/statemine.rs b/tinkernet/runtime/src/rings/asset_hub.rs similarity index 61% rename from tinkernet/runtime/src/rings/statemine.rs rename to tinkernet/runtime/src/rings/asset_hub.rs index b9684400..bc8e9d58 100644 --- a/tinkernet/runtime/src/rings/statemine.rs +++ b/tinkernet/runtime/src/rings/asset_hub.rs @@ -3,31 +3,23 @@ use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use xcm::latest::{Junction, Junctions, MultiLocation}; -pub struct Statemine; +pub struct AssetHub; #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] -pub enum StatemineAssets { +pub enum AssetHubAssets { KSM, - BILLCOIN, } -impl RingsChain for Statemine { - type Assets = StatemineAssets; +impl RingsChain for AssetHub { + type Assets = AssetHubAssets; fn get_asset_location(asset: &Self::Assets) -> MultiLocation { - use StatemineAssets::*; + use AssetHubAssets::*; match asset { KSM => MultiLocation { parents: 1, interior: Junctions::Here, }, - BILLCOIN => MultiLocation { - parents: 0, - interior: Junctions::X2( - Junction::PalletInstance(50u8), - Junction::GeneralIndex(223u128), - ), - }, } } @@ -39,6 +31,6 @@ impl RingsChain for Statemine { } fn get_main_asset() -> Self::Assets { - StatemineAssets::KSM + AssetHubAssets::KSM } } diff --git a/tinkernet/runtime/src/rings/mod.rs b/tinkernet/runtime/src/rings/mod.rs index 51c02254..4e3c9560 100644 --- a/tinkernet/runtime/src/rings/mod.rs +++ b/tinkernet/runtime/src/rings/mod.rs @@ -10,6 +10,8 @@ mod basilisk; use basilisk::Basilisk; mod picasso; use picasso::Picasso; +mod asset_hub; +use asset_hub::AssetHub; parameter_types! { pub MaxXCMCallLength: u32 = 100_000; @@ -35,12 +37,14 @@ pub trait RingsChain { pub enum Chains { Basilisk, Picasso, + AssetHub, } #[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] pub enum ChainAssets { Basilisk(::Assets), Picasso(::Assets), + AssetHub(::Assets), } impl ChainAssetsList for ChainAssets { @@ -50,6 +54,7 @@ impl ChainAssetsList for ChainAssets { match self { Self::Basilisk(_) => Chains::Basilisk, Self::Picasso(_) => Chains::Picasso, + Self::AssetHub(_) => Chains::AssetHub, } } @@ -57,6 +62,7 @@ impl ChainAssetsList for ChainAssets { match self { Self::Basilisk(asset) => Basilisk::get_asset_location(asset), Self::Picasso(asset) => Picasso::get_asset_location(asset), + Self::AssetHub(asset) => AssetHub::get_asset_location(asset), } } } @@ -69,6 +75,7 @@ impl ChainList for Chains { match self { Self::Basilisk => Basilisk::get_location(), Self::Picasso => Picasso::get_location(), + Self::AssetHub => AssetHub::get_location(), } } @@ -76,6 +83,7 @@ impl ChainList for Chains { match self { Self::Basilisk => ChainAssets::Basilisk(Basilisk::get_main_asset()), Self::Picasso => ChainAssets::Picasso(Picasso::get_main_asset()), + Self::AssetHub => ChainAssets::AssetHub(AssetHub::get_main_asset()), } } From 61ccacb6bffbe5737fcf408e7d0561e4f34eeb0c Mon Sep 17 00:00:00 2001 From: Gabriel Facco de Arruda Date: Mon, 29 Jan 2024 16:33:16 +0800 Subject: [PATCH 5/7] chore: Add missing files --- tinkernet/runtime/src/xcm_simulator/mod.rs | 227 ++++++++ .../runtime/src/xcm_simulator/parachain.rs | 524 ++++++++++++++++++ .../runtime/src/xcm_simulator/relay_chain.rs | 247 +++++++++ 3 files changed, 998 insertions(+) create mode 100644 tinkernet/runtime/src/xcm_simulator/mod.rs create mode 100644 tinkernet/runtime/src/xcm_simulator/parachain.rs create mode 100644 tinkernet/runtime/src/xcm_simulator/relay_chain.rs diff --git a/tinkernet/runtime/src/xcm_simulator/mod.rs b/tinkernet/runtime/src/xcm_simulator/mod.rs new file mode 100644 index 00000000..2435c9d1 --- /dev/null +++ b/tinkernet/runtime/src/xcm_simulator/mod.rs @@ -0,0 +1,227 @@ +mod parachain; +mod relay_chain; + +use frame_support::sp_tracing; +use xcm::prelude::*; +use xcm_executor::traits::Convert; +use xcm_simulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain, TestExt}; + +pub const ALICE: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([0u8; 32]); +pub const BOB: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([1u8; 32]); +pub const CORE_0: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([ + 147, 83, 7, 98, 71, 245, 98, 15, 146, 176, 22, 221, 20, 216, 188, 203, 166, 234, 117, 86, 56, + 214, 204, 37, 238, 26, 161, 82, 2, 174, 180, 74, +]); +pub const INITIAL_BALANCE: u128 = 1_000_000_000_000_000; + +decl_test_parachain! { + pub struct Tinkernet { + Runtime = parachain::Runtime, + XcmpMessageHandler = parachain::MsgQueue, + DmpMessageHandler = parachain::MsgQueue, + new_ext = para_ext(2125), + } +} + +decl_test_parachain! { + pub struct ParaB { + Runtime = parachain::Runtime, + XcmpMessageHandler = parachain::MsgQueue, + DmpMessageHandler = parachain::MsgQueue, + new_ext = para_ext(1000), + } +} + +decl_test_relay_chain! { + pub struct Relay { + Runtime = relay_chain::Runtime, + RuntimeCall = relay_chain::RuntimeCall, + RuntimeEvent = relay_chain::RuntimeEvent, + XcmConfig = relay_chain::XcmConfig, + MessageQueue = relay_chain::MessageQueue, + System = relay_chain::System, + new_ext = relay_ext(), + } +} + +decl_test_network! { + pub struct MockNet { + relay_chain = Relay, + parachains = vec![ + (2125, Tinkernet), + (1000, ParaB), + ], + } +} + +pub fn child_account_id(para: u32) -> relay_chain::AccountId { + let location = (Parachain(para),); + relay_chain::LocationToAccountId::convert(location.into()).unwrap() +} + +pub fn child_account_account_id(para: u32, who: sp_runtime::AccountId32) -> relay_chain::AccountId { + let location = ( + Parachain(para), + AccountId32 { + network: None, + id: who.into(), + }, + ); + relay_chain::LocationToAccountId::convert(location.into()).unwrap() +} + +pub fn sibling_core_account_id(core: u32) -> parachain::AccountId { + let location = MultiLocation { + parents: 1, + interior: Junctions::X2( + Parachain(2125), + Plurality { + id: BodyId::Index(core), + part: BodyPart::Voice, + }, + ), + }; + + parachain::HashedDescription::convert(location.into()).unwrap() +} + +pub fn tinkernet_ext(para_id: u32) -> sp_io::TestExternalities { + use crate::{PolkadotXcm, Runtime, RuntimeOrigin, System}; + + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![(ALICE, INITIAL_BALANCE), (CORE_0, INITIAL_BALANCE)], + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| { + sp_tracing::try_init_simple(); + System::set_block_number(1); + let _ = PolkadotXcm::force_xcm_version( + RuntimeOrigin::root(), + Box::new(MultiLocation::new( + 1, + Junctions::X1(Junction::Parachain(1000)), + )), + 3, + ); + + System::set_block_number(2); + }); + ext +} + +pub fn para_ext(para_id: u32) -> sp_io::TestExternalities { + use parachain::{MsgQueue, PolkadotXcm, Runtime, RuntimeOrigin, System}; + + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![(ALICE, INITIAL_BALANCE), (CORE_0, INITIAL_BALANCE)], + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| { + sp_tracing::try_init_simple(); + System::set_block_number(1); + MsgQueue::set_para_id(para_id.into()); + }); + ext +} + +pub fn relay_ext() -> sp_io::TestExternalities { + use relay_chain::{Runtime, RuntimeOrigin, System}; + + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![ + (ALICE, INITIAL_BALANCE), + (child_account_id(1), INITIAL_BALANCE), + (child_account_id(2), INITIAL_BALANCE), + ], + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| { + System::set_block_number(1); + }); + ext +} + +pub type RelayChainPalletXcm = pallet_xcm::Pallet; +pub type ParachainPalletXcm = pallet_xcm::Pallet; + +#[cfg(test)] +mod tests { + use super::*; + use parachain::INV4; + + use codec::Encode; + use frame_support::{assert_ok, weights::Weight}; + use pallet_rings::ChainList; + use xcm::latest::QueryResponseInfo; + use xcm_simulator::TestExt; + + // Helper function for forming buy execution message + fn buy_execution(fees: impl Into) -> Instruction { + BuyExecution { + fees: fees.into(), + weight_limit: Unlimited, + } + } + + #[test] + fn remote_account_ids_work() { + MockNet::reset(); + + Tinkernet::execute_with(|| { + assert_eq!( + >::derive_core_account(0), + sibling_core_account_id(0) + ); + }); + } + + #[test] + fn rings_transfer_work() { + MockNet::reset(); + + Tinkernet::execute_with(|| { + log::trace!(target: "xcm::CoreAccount", "CoreAccount: account: {:?}", >::derive_core_account(0)); + + assert_ok!(parachain::Rings::transfer_assets( + pallet_inv4::Origin::::Multisig( + pallet_inv4::origin::MultisigInternalOrigin::::new(0) + ) + .into(), + ChainList::get_main_asset(&crate::rings::Chains::AssetHub), + 10_000000000000u128, + BOB, + ChainList::get_main_asset(&crate::rings::Chains::AssetHub), + 1_000000000000u128 + )); + }); + + ParaB::execute_with(|| { + assert_eq!(parachain::Balances::free_balance(BOB), 10_000000000000u128); + }); + } +} diff --git a/tinkernet/runtime/src/xcm_simulator/parachain.rs b/tinkernet/runtime/src/xcm_simulator/parachain.rs new file mode 100644 index 00000000..6b2e925e --- /dev/null +++ b/tinkernet/runtime/src/xcm_simulator/parachain.rs @@ -0,0 +1,524 @@ +use codec::{Compact, Decode, Encode}; +use frame_support::{ + construct_runtime, parameter_types, + traits::{fungibles::Credit, Currency, Everything, EverythingBut, Nothing}, + weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}, +}; +use frame_system::EnsureRoot; +use pallet_xcm::XcmPassthrough; +use polkadot_core_primitives::BlockNumber as RelayBlockNumber; +use polkadot_parachain::primitives::{ + DmpMessageHandler, Id as ParaId, Sibling, XcmpMessageFormat, XcmpMessageHandler, +}; +use scale_info::TypeInfo; +use sp_core::{blake2_256, ConstU32, H256}; +use sp_runtime::{ + testing::Header, + traits::{Hash, IdentityLookup}, + AccountId32, +}; +use sp_std::prelude::*; +use xcm::{latest::prelude::*, VersionedXcm}; +use xcm_builder::{ + Account32Hash, AccountId32Aliases, AllowUnpaidExecutionFrom, + CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, + IsConcrete, NativeAsset, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, +}; +use xcm_executor::{traits::Convert, Config, XcmExecutor}; +use xcm_simulator::PhantomData; + +pub type SovereignAccountOf = ( + SiblingParachainConvertsVia, + AccountId32Aliases, + ParentIsPreset, +); + +pub type AccountId = AccountId32; +pub type Balance = u128; + +parameter_types! { + pub const BlockHashCount: u64 = 250; +} + +impl frame_system::Config for Runtime { + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Header = Header; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = BlockHashCount; + type BlockWeights = (); + type BlockLength = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = Everything; + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; +} + +parameter_types! { + pub ExistentialDeposit: Balance = 1; + pub const MaxLocks: u32 = 50; + pub const MaxReserves: u32 = 50; +} + +impl pallet_balances::Config for Runtime { + type MaxLocks = MaxLocks; + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type HoldIdentifier = (); + type FreezeIdentifier = (); + type MaxHolds = ConstU32<0>; + type MaxFreezes = ConstU32<0>; +} + +parameter_types! { + pub const ReservedXcmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0); + pub const ReservedDmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0); +} + +parameter_types! { + pub const KsmLocation: MultiLocation = MultiLocation::parent(); + pub const RelayNetwork: NetworkId = NetworkId::Kusama; + pub UniversalLocation: InteriorMultiLocation = Parachain(MsgQueue::parachain_id().into()).into(); +} + +pub trait DescribeLocation { + fn describe_location(location: &MultiLocation) -> Option>; +} + +pub struct DescribeBodyTerminal; +impl DescribeLocation for DescribeBodyTerminal { + fn describe_location(l: &MultiLocation) -> Option> { + match (l.parents, &l.interior) { + (0, X1(Plurality { id, part })) => Some((b"Body", id, part).encode()), + _ => return None, + } + } +} + +pub struct DescribeFamily(PhantomData); +impl DescribeLocation for DescribeFamily { + fn describe_location(l: &MultiLocation) -> Option> { + match (l.parents, l.interior.first()) { + (0, Some(Parachain(index))) => { + let tail = l.interior.split_first().0; + let interior = Suffix::describe_location(&tail.into())?; + Some((b"ChildChain", Compact::::from(*index), interior).encode()) + } + (1, Some(Parachain(index))) => { + let tail = l.interior.split_first().0; + let interior = Suffix::describe_location(&tail.into())?; + Some((b"SiblingChain", Compact::::from(*index), interior).encode()) + } + (1, _) => { + let tail = l.interior.into(); + let interior = Suffix::describe_location(&tail)?; + Some((b"ParentChain", interior).encode()) + } + _ => return None, + } + } +} + +pub struct HashedDescription; +impl Convert for HashedDescription { + fn convert(value: MultiLocation) -> Result { + log::trace!(target: "xcm::HashedDescription", "HashedDescription: location: {:?}", value); + if let Some(l) = DescribeFamily::::describe_location(&value) { + let a: AccountId = blake2_256(&l).into(); + log::trace!(target: "xcm::HashedDescription", "HashedDescription Ok: location: {:?} account: {:?}", value, a); + Ok(a) + } else { + log::trace!(target: "xcm::HashedDescription", "HashedDescription Error"); + Err(value) + } + } +} + +pub type LocationToAccountId = ( + ParentIsPreset, + SiblingParachainConvertsVia, + AccountId32Aliases, + HashedDescription, +); + +pub type XcmOriginToCallOrigin = ( + SovereignSignedViaLocation, + ParentAsSuperuser, + SignedAccountId32AsNative, + XcmPassthrough, +); + +parameter_types! { + pub const UnitWeightCost: Weight = Weight::from_parts(1, 1); + pub KsmPerSecondPerByte: (AssetId, u128, u128) = (Concrete(Parent.into()), 1, 1); + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; + pub ForeignPrefix: MultiLocation = (Parent,).into(); +} + +pub type LocalAssetTransactor = + (XcmCurrencyAdapter, LocationToAccountId, AccountId, ()>,); + +pub type XcmRouter = super::ParachainXcmRouter; +pub type Barrier = AllowUnpaidExecutionFrom; + +parameter_types! { + pub NftCollectionOne: MultiAssetFilter + = Wild(AllOf { fun: WildNonFungible, id: Concrete((Parent, GeneralIndex(1)).into()) }); + pub NftCollectionOneForRelay: (MultiAssetFilter, MultiLocation) + = (NftCollectionOne::get(), (Parent,).into()); +} +pub type TrustedTeleporters = xcm_builder::Case; +pub type TrustedReserves = EverythingBut>; + +pub struct XcmConfig; +impl Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = LocalAssetTransactor; + type OriginConverter = XcmOriginToCallOrigin; + type IsReserve = (NativeAsset, TrustedReserves); + type IsTeleporter = TrustedTeleporters; + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + type Trader = FixedRateOfFungible; + type ResponseHandler = (); + type AssetTrap = (); + type AssetLocker = (); + type AssetExchanger = (); + type AssetClaims = (); + type SubscriptionService = (); + type PalletInstancesInfo = (); + type FeeManager = (); + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = RuntimeCall; + type SafeCallFilter = Everything; +} + +#[frame_support::pallet] +pub mod mock_msg_queue { + use super::*; + use frame_support::pallet_prelude::*; + + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type XcmExecutor: ExecuteXcm; + } + + #[pallet::call] + impl Pallet {} + + #[pallet::pallet] + #[pallet::without_storage_info] + pub struct Pallet(_); + + #[pallet::storage] + #[pallet::getter(fn parachain_id)] + pub type ParachainId = StorageValue<_, ParaId, ValueQuery>; + + #[pallet::storage] + #[pallet::getter(fn received_dmp)] + /// A queue of received DMP messages + pub type ReceivedDmp = StorageValue<_, Vec>, ValueQuery>; + + impl Get for Pallet { + fn get() -> ParaId { + Self::parachain_id() + } + } + + pub type MessageId = [u8; 32]; + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + // XCMP + /// Some XCM was executed OK. + Success(Option), + /// Some XCM failed. + Fail(Option, XcmError), + /// Bad XCM version used. + BadVersion(Option), + /// Bad XCM format used. + BadFormat(Option), + + // DMP + /// Downward message is invalid XCM. + InvalidFormat(MessageId), + /// Downward message is unsupported version of XCM. + UnsupportedVersion(MessageId), + /// Downward message executed with the given outcome. + ExecutedDownward(MessageId, Outcome), + } + + impl Pallet { + pub fn set_para_id(para_id: ParaId) { + ParachainId::::put(para_id); + } + + fn handle_xcmp_message( + sender: ParaId, + _sent_at: RelayBlockNumber, + xcm: VersionedXcm, + max_weight: Weight, + ) -> Result { + let hash = Encode::using_encoded(&xcm, T::Hashing::hash); + let message_hash = Encode::using_encoded(&xcm, sp_io::hashing::blake2_256); + let (result, event) = match Xcm::::try_from(xcm) { + Ok(xcm) => { + let location = (Parent, Parachain(sender.into())); + match T::XcmExecutor::execute_xcm(location, xcm, message_hash, max_weight) { + Outcome::Error(e) => (Err(e.clone()), Event::Fail(Some(hash), e)), + Outcome::Complete(w) => (Ok(w), Event::Success(Some(hash))), + // As far as the caller is concerned, this was dispatched without error, so + // we just report the weight used. + Outcome::Incomplete(w, e) => (Ok(w), Event::Fail(Some(hash), e)), + } + } + Err(()) => ( + Err(XcmError::UnhandledXcmVersion), + Event::BadVersion(Some(hash)), + ), + }; + Self::deposit_event(event); + result + } + } + + impl XcmpMessageHandler for Pallet { + fn handle_xcmp_messages<'a, I: Iterator>( + iter: I, + max_weight: Weight, + ) -> Weight { + for (sender, sent_at, data) in iter { + let mut data_ref = data; + let _ = XcmpMessageFormat::decode(&mut data_ref) + .expect("Simulator encodes with versioned xcm format; qed"); + + let mut remaining_fragments = &data_ref[..]; + while !remaining_fragments.is_empty() { + if let Ok(xcm) = + VersionedXcm::::decode(&mut remaining_fragments) + { + let _ = Self::handle_xcmp_message(sender, sent_at, xcm, max_weight); + } else { + debug_assert!(false, "Invalid incoming XCMP message data"); + } + } + } + max_weight + } + } + + impl DmpMessageHandler for Pallet { + fn handle_dmp_messages( + iter: impl Iterator)>, + limit: Weight, + ) -> Weight { + for (_i, (_sent_at, data)) in iter.enumerate() { + let id = sp_io::hashing::blake2_256(&data[..]); + let maybe_versioned = VersionedXcm::::decode(&mut &data[..]); + match maybe_versioned { + Err(_) => { + Self::deposit_event(Event::InvalidFormat(id)); + } + Ok(versioned) => match Xcm::try_from(versioned) { + Err(()) => Self::deposit_event(Event::UnsupportedVersion(id)), + Ok(x) => { + let outcome = T::XcmExecutor::execute_xcm(Parent, x.clone(), id, limit); + >::append(x); + Self::deposit_event(Event::ExecutedDownward(id, outcome)); + } + }, + } + } + limit + } + } +} + +impl mock_msg_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type XcmExecutor = XcmExecutor; +} + +pub type LocalOriginToLocation = SignedToAccountId32; + +#[cfg(feature = "runtime-benchmarks")] +parameter_types! { + pub ReachableDest: Option = Some(Parent.into()); +} + +impl pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + type ExecuteXcmOrigin = EnsureXcmOrigin; + type XcmExecuteFilter = Everything; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Nothing; + type XcmReserveTransferFilter = Everything; + type Weigher = FixedWeightBounds; + type UniversalLocation = UniversalLocation; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type Currency = Balances; + type CurrencyMatcher = (); + type TrustedLockers = (); + type SovereignAccountOf = LocationToAccountId; + type MaxLockers = ConstU32<8>; + type MaxRemoteLockConsumers = ConstU32<0>; + type RemoteLockConsumerIdentifier = (); + type WeightInfo = pallet_xcm::TestWeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type ReachableDest = ReachableDest; + type AdminOrigin = EnsureRoot; +} + +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; + +#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo, Debug)] +pub struct FeeCharger; + +impl pallet_inv4::fee_handling::MultisigFeeHandler for FeeCharger { + type Pre = (); + + fn pre_dispatch( + fee_asset: &pallet_inv4::fee_handling::FeeAsset, + who: &AccountId, + call: &RuntimeCall, + info: &sp_runtime::traits::DispatchInfoOf, + len: usize, + ) -> Result { + Ok(()) + } + + fn post_dispatch( + fee_asset: &pallet_inv4::fee_handling::FeeAsset, + pre: Option, + info: &sp_runtime::traits::DispatchInfoOf, + post_info: &sp_runtime::traits::PostDispatchInfoOf, + len: usize, + result: &sp_runtime::DispatchResult, + ) -> Result<(), frame_support::unsigned::TransactionValidityError> { + Ok(()) + } + + fn handle_creation_fee( + imbalance: pallet_inv4::fee_handling::FeeAssetNegativeImbalance< + >::NegativeImbalance, + Credit, + >, + ) { + } +} + +parameter_types! { + pub PID: u32 = MsgQueue::parachain_id().into(); + pub const RelayAssetId: u32 = 1; +} + +impl pallet_inv4::Config for Runtime { + type MaxMetadata = crate::inv4::MaxMetadata; + type CoreId = crate::common_types::CommonId; + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type RuntimeCall = RuntimeCall; + type MaxCallers = crate::inv4::MaxCallers; + type CoreSeedBalance = crate::inv4::CoreSeedBalance; + type AssetsProvider = CoreAssets; + type RuntimeOrigin = RuntimeOrigin; + type CoreCreationFee = crate::inv4::CoreCreationFee; + type FeeCharger = FeeCharger; + type WeightInfo = pallet_inv4::weights::SubstrateWeight; + + type Tokens = Tokens; + type RelayAssetId = RelayAssetId; + type RelayCoreCreationFee = crate::inv4::KSMCoreCreationFee; + + type MaxCallSize = crate::inv4::MaxCallSize; + + type ParaId = PID; +} + +impl orml_tokens::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type Amount = i128; + type CurrencyId = u32; + type WeightInfo = (); + type ExistentialDeposits = crate::assets::ExistentialDeposits; + type MaxLocks = MaxLocks; + type DustRemovalWhitelist = crate::assets::DustRemovalWhitelist; + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type CurrencyHooks = (); +} + +impl orml_tokens2::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type Amount = i128; + type CurrencyId = ::CoreId; + type WeightInfo = (); + type ExistentialDeposits = crate::inv4::CoreExistentialDeposits; + type MaxLocks = ConstU32<0u32>; + type MaxReserves = ConstU32<0u32>; + type DustRemovalWhitelist = crate::inv4::CoreDustRemovalWhitelist; + type ReserveIdentifier = [u8; 8]; + type CurrencyHooks = (); +} + +impl pallet_rings::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Chains = crate::rings::Chains; + type MaxXCMCallLength = crate::rings::MaxXCMCallLength; + type MaintenanceOrigin = EnsureRoot; + type WeightInfo = pallet_rings::weights::SubstrateWeight; +} + +construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + MsgQueue: mock_msg_queue::{Pallet, Storage, Event}, + PolkadotXcm: pallet_xcm::{Pallet, Call, Event, Origin}, + + INV4: pallet_inv4, + Tokens: orml_tokens, + CoreAssets: orml_tokens2, + Rings: pallet_rings, + } +); diff --git a/tinkernet/runtime/src/xcm_simulator/relay_chain.rs b/tinkernet/runtime/src/xcm_simulator/relay_chain.rs new file mode 100644 index 00000000..70a0250a --- /dev/null +++ b/tinkernet/runtime/src/xcm_simulator/relay_chain.rs @@ -0,0 +1,247 @@ +use frame_support::{ + construct_runtime, parameter_types, + traits::{Everything, Nothing, ProcessMessage, ProcessMessageError}, + weights::{Weight, WeightMeter}, +}; + +use frame_system::EnsureRoot; +use sp_core::{ConstU32, H256}; +use sp_runtime::{testing::Header, traits::IdentityLookup, AccountId32}; + +use polkadot_parachain::primitives::Id as ParaId; +use polkadot_runtime_parachains::{ + configuration, + inclusion::{AggregateMessageOrigin, UmpQueueId}, + origin, shared, +}; +use xcm::latest::prelude::*; +use xcm_builder::{ + Account32Hash, AccountId32Aliases, AllowUnpaidExecutionFrom, ChildParachainAsNative, + ChildParachainConvertsVia, ChildSystemParachainAsSuperuser, + CurrencyAdapter as XcmCurrencyAdapter, FixedRateOfFungible, FixedWeightBounds, IsConcrete, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, +}; +use xcm_executor::{Config, XcmExecutor}; + +pub type AccountId = AccountId32; +pub type Balance = u128; + +parameter_types! { + pub const BlockHashCount: u64 = 250; +} + +impl frame_system::Config for Runtime { + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Header = Header; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = BlockHashCount; + type BlockWeights = (); + type BlockLength = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = Everything; + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; +} + +parameter_types! { + pub ExistentialDeposit: Balance = 1; + pub const MaxLocks: u32 = 50; + pub const MaxReserves: u32 = 50; +} + +impl pallet_balances::Config for Runtime { + type MaxLocks = MaxLocks; + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type HoldIdentifier = (); + type FreezeIdentifier = (); + type MaxHolds = ConstU32<0>; + type MaxFreezes = ConstU32<0>; +} + +impl shared::Config for Runtime {} + +impl configuration::Config for Runtime { + type WeightInfo = configuration::TestWeightInfo; +} + +parameter_types! { + pub const TokenLocation: MultiLocation = Here.into_location(); + pub RelayNetwork: NetworkId = ByGenesis([0; 32]); + pub const AnyNetwork: Option = None; + pub UniversalLocation: InteriorMultiLocation = Here; + pub UnitWeightCost: u64 = 1_000; +} + +pub type LocationToAccountId = ( + ChildParachainConvertsVia, + AccountId32Aliases, + Account32Hash<(), AccountId>, +); + +pub type LocalAssetTransactor = + (XcmCurrencyAdapter, LocationToAccountId, AccountId, ()>,); + +type LocalOriginConverter = ( + SovereignSignedViaLocation, + ChildParachainAsNative, + SignedAccountId32AsNative, + ChildSystemParachainAsSuperuser, +); + +parameter_types! { + pub const BaseXcmWeight: Weight = Weight::from_parts(1_000, 1_000); + pub TokensPerSecondPerByte: (AssetId, u128, u128) = + (Concrete(TokenLocation::get()), 1_000_000_000_000, 1024 * 1024); + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; +} + +pub type XcmRouter = super::RelayChainXcmRouter; +pub type Barrier = AllowUnpaidExecutionFrom; + +pub struct XcmConfig; +impl Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = LocalAssetTransactor; + type OriginConverter = LocalOriginConverter; + type IsReserve = (); + type IsTeleporter = (); + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + type Trader = FixedRateOfFungible; + type ResponseHandler = (); + type AssetTrap = (); + type AssetLocker = XcmPallet; + type AssetExchanger = (); + type AssetClaims = (); + type SubscriptionService = (); + type PalletInstancesInfo = (); + type FeeManager = (); + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = RuntimeCall; + type SafeCallFilter = Everything; +} + +pub type LocalOriginToLocation = SignedToAccountId32; + +#[cfg(feature = "runtime-benchmarks")] +parameter_types! { + pub ReachableDest: Option = Some(Parachain(1).into()); +} + +impl pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type SendXcmOrigin = xcm_builder::EnsureXcmOrigin; + type XcmRouter = XcmRouter; + // Anyone can execute XCM messages locally... + type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin; + type XcmExecuteFilter = Nothing; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Everything; + type XcmReserveTransferFilter = Everything; + type Weigher = FixedWeightBounds; + type UniversalLocation = UniversalLocation; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type Currency = Balances; + type CurrencyMatcher = IsConcrete; + type TrustedLockers = (); + type SovereignAccountOf = LocationToAccountId; + type MaxLockers = ConstU32<8>; + type MaxRemoteLockConsumers = ConstU32<0>; + type RemoteLockConsumerIdentifier = (); + type WeightInfo = pallet_xcm::TestWeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type ReachableDest = ReachableDest; + type AdminOrigin = EnsureRoot; +} + +parameter_types! { + pub const FirstMessageFactorPercent: u64 = 100; +} + +impl origin::Config for Runtime {} + +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; + +parameter_types! { + /// Amount of weight that can be spent per block to service messages. + pub MessageQueueServiceWeight: Weight = Weight::from_parts(1_000_000_000, 1_000_000); + pub const MessageQueueHeapSize: u32 = 65_536; + pub const MessageQueueMaxStale: u32 = 16; +} + +/// Message processor to handle any messages that were enqueued into the `MessageQueue` pallet. +pub struct MessageProcessor; +impl ProcessMessage for MessageProcessor { + type Origin = AggregateMessageOrigin; + + fn process_message( + message: &[u8], + origin: Self::Origin, + meter: &mut WeightMeter, + id: &mut [u8; 32], + ) -> Result { + let para = match origin { + AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => para, + }; + xcm_builder::ProcessXcmMessage::< + Junction, + xcm_executor::XcmExecutor, + RuntimeCall, + >::process_message(message, Junction::Parachain(para.into()), meter, id) + } +} + +impl pallet_message_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Size = u32; + type HeapSize = MessageQueueHeapSize; + type MaxStale = MessageQueueMaxStale; + type ServiceWeight = MessageQueueServiceWeight; + type MessageProcessor = MessageProcessor; + type QueueChangeHandler = (); + type WeightInfo = (); +} + +construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + ParasOrigin: origin::{Pallet, Origin}, + XcmPallet: pallet_xcm::{Pallet, Call, Storage, Event, Origin}, + MessageQueue: pallet_message_queue::{Pallet, Event}, + } +); From 96d16c79985cabc2fc50c62724193e548bf5cabe Mon Sep 17 00:00:00 2001 From: Gabriel Facco de Arruda Date: Mon, 29 Jan 2024 17:08:40 +0800 Subject: [PATCH 6/7] chore: Clippy things --- tinkernet/runtime/src/migrations.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tinkernet/runtime/src/migrations.rs b/tinkernet/runtime/src/migrations.rs index b18b580b..a082b317 100644 --- a/tinkernet/runtime/src/migrations.rs +++ b/tinkernet/runtime/src/migrations.rs @@ -1,9 +1,11 @@ -use frame_support::{dispatch::GetStorageVersion, traits::OnRuntimeUpgrade, weights::Weight}; +#![allow(clippy::type_complexity)] + +use frame_support::{traits::OnRuntimeUpgrade, weights::Weight}; use log::{info, warn}; pub mod new_core_account_derivation { use super::*; - use crate::{common_types::CommonId, AccountId, Identity, Runtime, RuntimeOrigin, Vec, INV4}; + use crate::{common_types::CommonId, AccountId, Identity, Runtime, RuntimeOrigin, Vec}; use frame_support::dispatch::GetDispatchInfo; use pallet_identity::IdentityInfo; use pallet_inv4::{ From c9820d9daefaf236332f5b2aaf447610892703da Mon Sep 17 00:00:00 2001 From: Gabriel Facco de Arruda Date: Mon, 29 Jan 2024 17:44:29 +0800 Subject: [PATCH 7/7] fix: Time constants --- invarch/runtime/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/invarch/runtime/src/lib.rs b/invarch/runtime/src/lib.rs index 1118be01..72b84641 100644 --- a/invarch/runtime/src/lib.rs +++ b/invarch/runtime/src/lib.rs @@ -154,12 +154,14 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { /// Change this to adjust the block time. pub const MILLISECS_PER_BLOCK: u64 = 6000; +pub const TWELVE_SECONDS_IN_MILLISECS: u64 = 12000; + // NOTE: Currently it is not possible to change the slot duration after the chain has started. // Attempting to do so will brick block production. pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; // Time is measured by number of blocks. -pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); +pub const MINUTES: BlockNumber = 60_000 / (TWELVE_SECONDS_IN_MILLISECS as BlockNumber); pub const HOURS: BlockNumber = MINUTES * 60; pub const DAYS: BlockNumber = HOURS * 24;