From 251e8cdc15f91e7793071935c7cc3e05c83262d5 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 29 Aug 2023 16:22:54 +0200 Subject: [PATCH 001/115] boilerplate type changes --- Cargo.lock | 3 + .../frame/contracts/src/benchmarking/mod.rs | 72 +++++++++---------- substrate/frame/contracts/src/exec.rs | 9 +-- substrate/frame/contracts/src/lib.rs | 45 +++++++----- substrate/frame/contracts/src/migration.rs | 10 +-- .../frame/contracts/src/migration/v09.rs | 6 +- .../frame/contracts/src/migration/v10.rs | 6 +- .../frame/contracts/src/migration/v11.rs | 4 +- .../frame/contracts/src/migration/v12.rs | 6 +- .../frame/contracts/src/migration/v13.rs | 6 +- .../frame/contracts/src/migration/v14.rs | 14 ++-- .../frame/contracts/src/migration/v15.rs | 22 +++--- substrate/frame/contracts/src/schedule.rs | 4 +- substrate/frame/contracts/src/storage.rs | 6 +- .../frame/contracts/src/storage/meter.rs | 14 ++-- substrate/frame/contracts/src/wasm/mod.rs | 8 +-- 16 files changed, 123 insertions(+), 112 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5ffb73c9c677..935468746338 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9407,6 +9407,7 @@ dependencies = [ "pallet-proxy", "pallet-timestamp", "pallet-utility", + "pallet-xcm", "parity-scale-codec", "pretty_assertions", "rand 0.8.5", @@ -9423,6 +9424,8 @@ dependencies = [ "wasm-instrument 0.4.0", "wasmi 0.30.0", "wat", + "xcm", + "xcm-executor", ] [[package]] diff --git a/substrate/frame/contracts/src/benchmarking/mod.rs b/substrate/frame/contracts/src/benchmarking/mod.rs index ac5787e23404..3fa66b966b24 100644 --- a/substrate/frame/contracts/src/benchmarking/mod.rs +++ b/substrate/frame/contracts/src/benchmarking/mod.rs @@ -97,7 +97,7 @@ where data: Vec, ) -> Result, &'static str> { let value = Pallet::::min_balance(); - T::Currency::set_balance(&caller, caller_funding::()); + ::Currency::set_balance(&caller, caller_funding::()); let salt = vec![0xff]; let addr = Contracts::::contract_address(&caller, &module.hash, &data, &salt); @@ -163,7 +163,7 @@ where /// Set the balance of the contract to the supplied amount. fn set_balance(&self, balance: BalanceOf) { - T::Currency::set_balance(&self.account_id, balance); + ::Currency::set_balance(&self.account_id, balance); } /// Returns `true` iff all storage entries related to code storage exist. @@ -291,7 +291,7 @@ benchmarks! { #[pov_mode = Measured] v14_migration_step { let account = account::("account", 0, 0); - T::Currency::set_balance(&account, caller_funding::()); + ::Currency::set_balance(&account, caller_funding::()); v14::store_dummy_code::>(account); let mut m = v14::Migration::>::default(); }: { @@ -406,21 +406,21 @@ benchmarks! { let salt = vec![42u8; s as usize]; let value = Pallet::::min_balance(); let caller = whitelisted_caller(); - T::Currency::set_balance(&caller, caller_funding::()); + ::Currency::set_balance(&caller, caller_funding::()); let WasmModule { code, hash, .. } = WasmModule::::sized(c, Location::Call); let origin = RawOrigin::Signed(caller.clone()); let addr = Contracts::::contract_address(&caller, &hash, &input, &salt); }: _(origin, value, Weight::MAX, None, code, input, salt) verify { - let deposit = T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr); + let deposit = ::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr); // uploading the code reserves some balance in the callers account - let code_deposit = T::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &caller); + let code_deposit = ::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &caller); assert_eq!( - T::Currency::balance(&caller), + ::Currency::balance(&caller), caller_funding::() - value - deposit - code_deposit - Pallet::::min_balance(), ); // contract has the full value - assert_eq!(T::Currency::balance(&addr), value + Pallet::::min_balance()); + assert_eq!(::Currency::balance(&addr), value + Pallet::::min_balance()); } // Instantiate uses a dummy contract constructor to measure the overhead of the instantiate. @@ -434,21 +434,21 @@ benchmarks! { let salt = vec![42u8; s as usize]; let value = Pallet::::min_balance(); let caller = whitelisted_caller(); - T::Currency::set_balance(&caller, caller_funding::()); + ::Currency::set_balance(&caller, caller_funding::()); let WasmModule { code, hash, .. } = WasmModule::::dummy(); let origin = RawOrigin::Signed(caller.clone()); let addr = Contracts::::contract_address(&caller, &hash, &input, &salt); Contracts::::store_code_raw(code, caller.clone())?; }: _(origin, value, Weight::MAX, None, hash, input, salt) verify { - let deposit = T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr); + let deposit = ::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr); // value was removed from the caller assert_eq!( - T::Currency::balance(&caller), + ::Currency::balance(&caller), caller_funding::() - value - deposit - Pallet::::min_balance(), ); // contract has the full value - assert_eq!(T::Currency::balance(&addr), value + Pallet::::min_balance()); + assert_eq!(::Currency::balance(&addr), value + Pallet::::min_balance()); } // We just call a dummy contract to measure the overhead of the call extrinsic. @@ -467,17 +467,17 @@ benchmarks! { let value = Pallet::::min_balance(); let origin = RawOrigin::Signed(instance.caller.clone()); let callee = instance.addr.clone(); - let before = T::Currency::balance(&instance.account_id); + let before = ::Currency::balance(&instance.account_id); }: _(origin, callee, value, Weight::MAX, None, data) verify { - let deposit = T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id); + let deposit = ::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id); // value and value transferred via call should be removed from the caller assert_eq!( - T::Currency::balance(&instance.caller), + ::Currency::balance(&instance.caller), caller_funding::() - instance.value - value - deposit - Pallet::::min_balance(), ); // contract should have received the value - assert_eq!(T::Currency::balance(&instance.account_id), before + value); + assert_eq!(::Currency::balance(&instance.account_id), before + value); // contract should still exist instance.info()?; } @@ -489,13 +489,13 @@ benchmarks! { upload_code { let c in 0 .. T::MaxCodeLen::get(); let caller = whitelisted_caller(); - T::Currency::set_balance(&caller, caller_funding::()); + ::Currency::set_balance(&caller, caller_funding::()); let WasmModule { code, hash, .. } = WasmModule::::sized(c, Location::Call); let origin = RawOrigin::Signed(caller.clone()); }: _(origin, code, None, Determinism::Enforced) verify { // uploading the code reserves some balance in the callers account - assert!(T::Currency::total_balance_on_hold(&caller) > 0u32.into()); + assert!(::Currency::total_balance_on_hold(&caller) > 0u32.into()); assert!(>::code_exists(&hash)); } @@ -505,17 +505,17 @@ benchmarks! { #[pov_mode = Measured] remove_code { let caller = whitelisted_caller(); - T::Currency::set_balance(&caller, caller_funding::()); + ::Currency::set_balance(&caller, caller_funding::()); let WasmModule { code, hash, .. } = WasmModule::::dummy(); let origin = RawOrigin::Signed(caller.clone()); let uploaded = >::bare_upload_code(caller.clone(), code, None, Determinism::Enforced)?; assert_eq!(uploaded.code_hash, hash); - assert_eq!(uploaded.deposit, T::Currency::total_balance_on_hold(&caller)); + assert_eq!(uploaded.deposit, ::Currency::total_balance_on_hold(&caller)); assert!(>::code_exists(&hash)); }: _(origin, hash) verify { // removing the code should have unreserved the deposit - assert_eq!(T::Currency::total_balance_on_hold(&caller), 0u32.into()); + assert_eq!(::Currency::total_balance_on_hold(&caller), 0u32.into()); assert!(>::code_removed(&hash)); } @@ -889,7 +889,7 @@ benchmarks! { let beneficiary_len = beneficiary_bytes.len(); let caller = whitelisted_caller(); - T::Currency::set_balance(&caller, caller_funding::()); + ::Currency::set_balance(&caller, caller_funding::()); // Maximize the delegate_dependencies to account for the worst-case scenario. let code_hashes = (0..T::MaxDelegateDependencies::get()) @@ -941,15 +941,15 @@ benchmarks! { }); let instance = Contract::::new(code, vec![])?; let origin = RawOrigin::Signed(instance.caller.clone()); - assert_eq!(T::Currency::total_balance(&beneficiary), 0u32.into()); - assert_eq!(T::Currency::balance(&instance.account_id), Pallet::::min_balance() * 2u32.into()); - assert_ne!(T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id), 0u32.into()); + assert_eq!(::Currency::total_balance(&beneficiary), 0u32.into()); + assert_eq!(::Currency::balance(&instance.account_id), Pallet::::min_balance() * 2u32.into()); + assert_ne!(::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id), 0u32.into()); }: call(origin, instance.addr.clone(), 0u32.into(), Weight::MAX, None, vec![]) verify { if r > 0 { - assert_eq!(T::Currency::total_balance(&instance.account_id), 0u32.into()); - assert_eq!(T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id), 0u32.into()); - assert_eq!(T::Currency::total_balance(&beneficiary), Pallet::::min_balance() * 2u32.into()); + assert_eq!(::Currency::total_balance(&instance.account_id), 0u32.into()); + assert_eq!(::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id), 0u32.into()); + assert_eq!(::Currency::total_balance(&beneficiary), Pallet::::min_balance() * 2u32.into()); } } @@ -1718,12 +1718,12 @@ benchmarks! { instance.set_balance(value * (r + 1).into()); let origin = RawOrigin::Signed(instance.caller.clone()); for account in &accounts { - assert_eq!(T::Currency::total_balance(account), 0u32.into()); + assert_eq!(::Currency::total_balance(account), 0u32.into()); } }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) verify { for account in &accounts { - assert_eq!(T::Currency::total_balance(account), value); + assert_eq!(::Currency::total_balance(account), value); } } @@ -1812,7 +1812,7 @@ benchmarks! { .map(|i| { let code = WasmModule::::dummy_with_bytes(i); let caller = whitelisted_caller(); - T::Currency::set_balance(&caller, caller_funding::()); + ::Currency::set_balance(&caller, caller_funding::()); Contracts::::store_code_raw(code.code, caller)?; Ok(code.hash) }) @@ -1934,7 +1934,7 @@ benchmarks! { .. Default::default() }); let caller = whitelisted_caller(); - T::Currency::set_balance(&caller, caller_funding::()); + ::Currency::set_balance(&caller, caller_funding::()); Contracts::::store_code_raw(code.code, caller)?; Ok(code.hash) }) @@ -2040,7 +2040,7 @@ benchmarks! { let hash_bytes = callee_code.hash.encode(); let hash_len = hash_bytes.len(); let caller = whitelisted_caller(); - T::Currency::set_balance(&caller, caller_funding::()); + ::Currency::set_balance(&caller, caller_funding::()); Contracts::::store_code_raw(callee_code.code, caller)?; let value: BalanceOf = t.into(); let value_bytes = value.encode(); @@ -2384,7 +2384,7 @@ benchmarks! { .map(|i| { let new_code = WasmModule::::dummy_with_bytes(i); let caller = whitelisted_caller(); - T::Currency::set_balance(&caller, caller_funding::()); + ::Currency::set_balance(&caller, caller_funding::()); Contracts::::store_code_raw(new_code.code, caller)?; Ok(new_code.hash) }) @@ -2427,7 +2427,7 @@ benchmarks! { .map(|i| { let new_code = WasmModule::::dummy_with_bytes(65 + i); let caller = whitelisted_caller(); - T::Currency::set_balance(&caller, caller_funding::()); + ::Currency::set_balance(&caller, caller_funding::()); Contracts::::store_code_raw(new_code.code, caller)?; Ok(new_code.hash) }) @@ -2465,7 +2465,7 @@ benchmarks! { .map(|i| { let new_code = WasmModule::::dummy_with_bytes(65 + i); let caller = whitelisted_caller(); - T::Currency::set_balance(&caller, caller_funding::()); + ::Currency::set_balance(&caller, caller_funding::()); Contracts::::store_code_raw(new_code.code, caller)?; Ok(new_code.hash) }) diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index 38c15a807c5d..1cb672c4d2ae 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -1102,7 +1102,7 @@ where value: BalanceOf, ) -> DispatchResult { if !value.is_zero() && from != to { - T::Currency::transfer(from, to, value, preservation) + ::Currency::transfer(from, to, value, preservation) .map_err(|_| Error::::TransferFailed)?; } Ok(()) @@ -1368,7 +1368,7 @@ where } fn balance(&self) -> BalanceOf { - T::Currency::balance(&self.top_frame().account_id) + ::Currency::balance(&self.top_frame().account_id) } fn value_transferred(&self) -> BalanceOf { @@ -1384,7 +1384,7 @@ where } fn minimum_balance(&self) -> BalanceOf { - T::Currency::minimum_balance() + ::Currency::minimum_balance() } fn deposit_event(&mut self, topics: Vec, data: Vec) { @@ -1441,7 +1441,8 @@ where } fn call_runtime(&self, call: ::RuntimeCall) -> DispatchResultWithPostInfo { - let mut origin: T::RuntimeOrigin = RawOrigin::Signed(self.address().clone()).into(); + let mut origin: ::RuntimeOrigin = + RawOrigin::Signed(self.address().clone()).into(); origin.add_filter(T::CallFilter::contains); call.dispatch(origin) } diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index e22e4a3f9ff8..5176e4baa13a 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -253,8 +253,10 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// The overarching call type. - type RuntimeCall: Dispatchable - + GetDispatchInfo + type RuntimeCall: Dispatchable< + RuntimeOrigin = ::RuntimeOrigin, + PostInfo = PostDispatchInfo, + > + GetDispatchInfo + codec::Decode + IsType<::RuntimeCall>; @@ -425,7 +427,7 @@ pub mod pallet { } ContractInfo::::process_deletion_queue_batch(remaining_weight) - .saturating_add(T::WeightInfo::on_process_deletion_queue_batch()) + .saturating_add(::WeightInfo::on_process_deletion_queue_batch()) } fn integrity_test() { @@ -503,7 +505,7 @@ pub mod pallet { { /// Deprecated version if [`Self::call`] for use in an in-storage `Call`. #[pallet::call_index(0)] - #[pallet::weight(T::WeightInfo::call().saturating_add(>::compat_weight_limit(*gas_limit)))] + #[pallet::weight(::WeightInfo::call().saturating_add(>::compat_weight_limit(*gas_limit)))] #[allow(deprecated)] #[deprecated(note = "1D weight is used in this extrinsic, please migrate to `call`")] pub fn call_old_weight( @@ -527,7 +529,7 @@ pub mod pallet { /// Deprecated version if [`Self::instantiate_with_code`] for use in an in-storage `Call`. #[pallet::call_index(1)] #[pallet::weight( - T::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32, salt.len() as u32) + ::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32, salt.len() as u32) .saturating_add(>::compat_weight_limit(*gas_limit)) )] #[allow(deprecated)] @@ -557,7 +559,7 @@ pub mod pallet { /// Deprecated version if [`Self::instantiate`] for use in an in-storage `Call`. #[pallet::call_index(2)] #[pallet::weight( - T::WeightInfo::instantiate(data.len() as u32, salt.len() as u32).saturating_add(>::compat_weight_limit(*gas_limit)) + ::WeightInfo::instantiate(data.len() as u32, salt.len() as u32).saturating_add(>::compat_weight_limit(*gas_limit)) )] #[allow(deprecated)] #[deprecated(note = "1D weight is used in this extrinsic, please migrate to `instantiate`")] @@ -602,7 +604,7 @@ pub mod pallet { /// only be instantiated by permissioned entities. The same is true when uploading /// through [`Self::instantiate_with_code`]. #[pallet::call_index(3)] - #[pallet::weight(T::WeightInfo::upload_code(code.len() as u32))] + #[pallet::weight(::WeightInfo::upload_code(code.len() as u32))] pub fn upload_code( origin: OriginFor, code: Vec, @@ -620,7 +622,7 @@ pub mod pallet { /// A code can only be removed by its original uploader (its owner) and only if it is /// not used by any contract. #[pallet::call_index(4)] - #[pallet::weight(T::WeightInfo::remove_code())] + #[pallet::weight(::WeightInfo::remove_code())] pub fn remove_code( origin: OriginFor, code_hash: CodeHash, @@ -643,7 +645,7 @@ pub mod pallet { /// that the contract address is no longer derived from its code hash after calling /// this dispatchable. #[pallet::call_index(5)] - #[pallet::weight(T::WeightInfo::set_code())] + #[pallet::weight(::WeightInfo::set_code())] pub fn set_code( origin: OriginFor, dest: AccountIdLookupOf, @@ -690,7 +692,7 @@ pub mod pallet { /// * If no account exists and the call value is not less than `existential_deposit`, /// a regular account will be created and any value will be transferred. #[pallet::call_index(6)] - #[pallet::weight(T::WeightInfo::call().saturating_add(*gas_limit))] + #[pallet::weight(::WeightInfo::call().saturating_add(*gas_limit))] pub fn call( origin: OriginFor, dest: AccountIdLookupOf, @@ -716,7 +718,9 @@ pub mod pallet { output.result = Err(>::ContractReverted.into()); } } - output.gas_meter.into_dispatch_result(output.result, T::WeightInfo::call()) + output + .gas_meter + .into_dispatch_result(output.result, ::WeightInfo::call()) } /// Instantiates a new contract from the supplied `code` optionally transferring @@ -746,7 +750,7 @@ pub mod pallet { /// - The `deploy` function is executed in the context of the newly-created account. #[pallet::call_index(7)] #[pallet::weight( - T::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32, salt.len() as u32) + ::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32, salt.len() as u32) .saturating_add(*gas_limit) )] pub fn instantiate_with_code( @@ -795,7 +799,9 @@ pub mod pallet { output.gas_meter.into_dispatch_result( output.result.map(|(_address, output)| output), - T::WeightInfo::instantiate_with_code(code_len, data_len, salt_len), + ::WeightInfo::instantiate_with_code( + code_len, data_len, salt_len, + ), ) } @@ -806,7 +812,7 @@ pub mod pallet { /// must be supplied. #[pallet::call_index(8)] #[pallet::weight( - T::WeightInfo::instantiate(data.len() as u32, salt.len() as u32).saturating_add(*gas_limit) + ::WeightInfo::instantiate(data.len() as u32, salt.len() as u32).saturating_add(*gas_limit) )] pub fn instantiate( origin: OriginFor, @@ -837,7 +843,7 @@ pub mod pallet { } output.gas_meter.into_dispatch_result( output.result.map(|(_address, output)| output), - T::WeightInfo::instantiate(data_len, salt_len), + ::WeightInfo::instantiate(data_len, salt_len), ) } @@ -846,12 +852,13 @@ pub mod pallet { /// for the chain. Note that while the migration is in progress, the pallet will also /// leverage the `on_idle` hooks to run migration steps. #[pallet::call_index(9)] - #[pallet::weight(T::WeightInfo::migrate().saturating_add(*weight_limit))] + #[pallet::weight(::WeightInfo::migrate().saturating_add(*weight_limit))] pub fn migrate(origin: OriginFor, weight_limit: Weight) -> DispatchResultWithPostInfo { use migration::MigrateResult::*; ensure_signed(origin)?; - let weight_limit = weight_limit.saturating_add(T::WeightInfo::migrate()); + let weight_limit = + weight_limit.saturating_add(::WeightInfo::migrate()); let (result, weight) = Migration::::migrate(weight_limit); match result { @@ -863,7 +870,7 @@ pub mod pallet { Ok(PostDispatchInfo { actual_weight: Some(weight), pays_fee: Pays::Yes }), NoMigrationInProgress | NoMigrationPerformed => { let err: DispatchError = >::NoMigrationPerformed.into(); - Err(err.with_weight(T::WeightInfo::migrate())) + Err(err.with_weight(::WeightInfo::migrate())) }, } } @@ -1648,7 +1655,7 @@ impl Pallet { /// Return the existential deposit of [`Config::Currency`]. fn min_balance() -> BalanceOf { - >>::minimum_balance() + <::Currency as Inspect>>::minimum_balance() } /// Convert gas_limit from 1D Weight to a 2D Weight. diff --git a/substrate/frame/contracts/src/migration.rs b/substrate/frame/contracts/src/migration.rs index 3e3d6f37884c..8c3e048cd625 100644 --- a/substrate/frame/contracts/src/migration.rs +++ b/substrate/frame/contracts/src/migration.rs @@ -272,7 +272,7 @@ impl OnRuntimeUpgrade for Migration::WeightInfo::on_runtime_upgrade_noop() } // In case a migration is already in progress we create the next migration @@ -284,7 +284,7 @@ impl OnRuntimeUpgrade for Migration::WeightInfo::on_runtime_upgrade_in_progress() } log::info!( @@ -300,7 +300,7 @@ impl OnRuntimeUpgrade for Migration::WeightInfo::on_runtime_upgrade() } #[cfg(feature = "try-runtime")] @@ -364,13 +364,13 @@ impl Migration { let name = >::name(); let mut weight_left = weight_limit; - if weight_left.checked_reduce(T::WeightInfo::migrate()).is_none() { + if weight_left.checked_reduce(::WeightInfo::migrate()).is_none() { return (MigrateResult::NoMigrationPerformed, Weight::zero()) } MigrationInProgress::::mutate_exists(|progress| { let Some(cursor_before) = progress.as_mut() else { - return (MigrateResult::NoMigrationInProgress, T::WeightInfo::migration_noop()) + return (MigrateResult::NoMigrationInProgress, ::WeightInfo::migration_noop()) }; // if a migration is running it is always upgrading to the next version diff --git a/substrate/frame/contracts/src/migration/v09.rs b/substrate/frame/contracts/src/migration/v09.rs index 98fcccc2c0be..3761c9e90a8a 100644 --- a/substrate/frame/contracts/src/migration/v09.rs +++ b/substrate/frame/contracts/src/migration/v09.rs @@ -84,7 +84,7 @@ impl MigrationStep for Migration { const VERSION: u16 = 9; fn max_step_weight() -> Weight { - T::WeightInfo::v9_migration_step(T::MaxCodeLen::get()) + ::WeightInfo::v9_migration_step(T::MaxCodeLen::get()) } fn step(&mut self) -> (IsFinished, Weight) { @@ -106,10 +106,10 @@ impl MigrationStep for Migration { }; CodeStorage::::insert(key, module); self.last_code_hash = Some(key); - (IsFinished::No, T::WeightInfo::v9_migration_step(len)) + (IsFinished::No, ::WeightInfo::v9_migration_step(len)) } else { log::debug!(target: LOG_TARGET, "No more contracts code to migrate"); - (IsFinished::Yes, T::WeightInfo::v9_migration_step(0)) + (IsFinished::Yes, ::WeightInfo::v9_migration_step(0)) } } diff --git a/substrate/frame/contracts/src/migration/v10.rs b/substrate/frame/contracts/src/migration/v10.rs index f02e28f6fde3..8a6a933ed1f2 100644 --- a/substrate/frame/contracts/src/migration/v10.rs +++ b/substrate/frame/contracts/src/migration/v10.rs @@ -154,7 +154,7 @@ where const VERSION: u16 = 10; fn max_step_weight() -> Weight { - T::WeightInfo::v10_migration_step() + ::WeightInfo::v10_migration_step() } fn step(&mut self) -> (IsFinished, Weight) { @@ -264,10 +264,10 @@ where // Store last key for next migration step self.last_account = Some(account); - (IsFinished::No, T::WeightInfo::v10_migration_step()) + (IsFinished::No, ::WeightInfo::v10_migration_step()) } else { log::debug!(target: LOG_TARGET, "Done Migrating contract info"); - (IsFinished::Yes, T::WeightInfo::v10_migration_step()) + (IsFinished::Yes, ::WeightInfo::v10_migration_step()) } } diff --git a/substrate/frame/contracts/src/migration/v11.rs b/substrate/frame/contracts/src/migration/v11.rs index a5b11f6e0897..8b7f70a1963b 100644 --- a/substrate/frame/contracts/src/migration/v11.rs +++ b/substrate/frame/contracts/src/migration/v11.rs @@ -76,7 +76,7 @@ impl MigrationStep for Migration { // but in practice the queue is always empty, so 128 is a good enough approximation for not // underestimating the weight of our migration. fn max_step_weight() -> Weight { - T::WeightInfo::v11_migration_step(128) + ::WeightInfo::v11_migration_step(128) } fn step(&mut self) -> (IsFinished, Weight) { @@ -101,7 +101,7 @@ impl MigrationStep for Migration { >::set(queue); } - (IsFinished::Yes, T::WeightInfo::v11_migration_step(len as u32)) + (IsFinished::Yes, ::WeightInfo::v11_migration_step(len as u32)) } #[cfg(feature = "try-runtime")] diff --git a/substrate/frame/contracts/src/migration/v12.rs b/substrate/frame/contracts/src/migration/v12.rs index eb045aa42e9d..919636b353b7 100644 --- a/substrate/frame/contracts/src/migration/v12.rs +++ b/substrate/frame/contracts/src/migration/v12.rs @@ -143,7 +143,7 @@ where const VERSION: u16 = 12; fn max_step_weight() -> Weight { - T::WeightInfo::v12_migration_step(T::MaxCodeLen::get()) + ::WeightInfo::v12_migration_step(T::MaxCodeLen::get()) } fn step(&mut self) -> (IsFinished, Weight) { @@ -230,10 +230,10 @@ where self.last_code_hash = Some(hash); - (IsFinished::No, T::WeightInfo::v12_migration_step(code_len as u32)) + (IsFinished::No, ::WeightInfo::v12_migration_step(code_len as u32)) } else { log::debug!(target: LOG_TARGET, "No more OwnerInfo to migrate"); - (IsFinished::Yes, T::WeightInfo::v12_migration_step(0)) + (IsFinished::Yes, ::WeightInfo::v12_migration_step(0)) } } diff --git a/substrate/frame/contracts/src/migration/v13.rs b/substrate/frame/contracts/src/migration/v13.rs index dd2eb12eb62a..6a9f225a5bfe 100644 --- a/substrate/frame/contracts/src/migration/v13.rs +++ b/substrate/frame/contracts/src/migration/v13.rs @@ -99,7 +99,7 @@ impl MigrationStep for Migration { const VERSION: u16 = 13; fn max_step_weight() -> Weight { - T::WeightInfo::v13_migration_step() + ::WeightInfo::v13_migration_step() } fn step(&mut self) -> (IsFinished, Weight) { @@ -126,10 +126,10 @@ impl MigrationStep for Migration { }; ContractInfoOf::::insert(key.clone(), info); self.last_account = Some(key); - (IsFinished::No, T::WeightInfo::v13_migration_step()) + (IsFinished::No, ::WeightInfo::v13_migration_step()) } else { log::debug!(target: LOG_TARGET, "No more contracts to migrate"); - (IsFinished::Yes, T::WeightInfo::v13_migration_step()) + (IsFinished::Yes, ::WeightInfo::v13_migration_step()) } } } diff --git a/substrate/frame/contracts/src/migration/v14.rs b/substrate/frame/contracts/src/migration/v14.rs index efb49dff4f10..3e1ded534e42 100644 --- a/substrate/frame/contracts/src/migration/v14.rs +++ b/substrate/frame/contracts/src/migration/v14.rs @@ -129,7 +129,7 @@ where const VERSION: u16 = 14; fn max_step_weight() -> Weight { - T::WeightInfo::v14_migration_step() + ::WeightInfo::v14_migration_step() } fn step(&mut self) -> (IsFinished, Weight) { @@ -168,7 +168,7 @@ where hash, ); - T::Currency::hold( + ::Currency::hold( &HoldReason::CodeUploadDepositReserve.into(), &code_info.owner, amount, @@ -185,10 +185,10 @@ where }); self.last_code_hash = Some(hash); - (IsFinished::No, T::WeightInfo::v14_migration_step()) + (IsFinished::No, ::WeightInfo::v14_migration_step()) } else { log::debug!(target: LOG_TARGET, "No more code upload deposit to migrate"); - (IsFinished::Yes, T::WeightInfo::v14_migration_step()) + (IsFinished::Yes, ::WeightInfo::v14_migration_step()) } } @@ -228,7 +228,7 @@ where let count = owner_balance_allocation.len(); for (owner, old_balance_allocation) in owner_balance_allocation { let held = - T::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &owner); + ::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &owner); log::debug!( target: LOG_TARGET, "Validating code upload deposit for owner 0x{:?}, reserved: {:?}, held: {:?}", @@ -242,11 +242,11 @@ where target: LOG_TARGET, "Validating total balance for owner 0x{:?}, new: {:?}, old: {:?}", HexDisplay::from(&owner.encode()), - T::Currency::total_balance(&owner), + ::Currency::total_balance(&owner), old_balance_allocation.total ); ensure!( - T::Currency::total_balance(&owner) == + ::Currency::total_balance(&owner) == BalanceOf::::decode(&mut &old_balance_allocation.total.encode()[..]) .unwrap(), "Balance mismatch " diff --git a/substrate/frame/contracts/src/migration/v15.rs b/substrate/frame/contracts/src/migration/v15.rs index 180fe855ca66..018d6f3c838e 100644 --- a/substrate/frame/contracts/src/migration/v15.rs +++ b/substrate/frame/contracts/src/migration/v15.rs @@ -122,7 +122,7 @@ impl MigrationStep for Migration { const VERSION: u16 = 15; fn max_step_weight() -> Weight { - T::WeightInfo::v15_migration_step() + ::WeightInfo::v15_migration_step() } fn step(&mut self) -> (IsFinished, Weight) { @@ -139,8 +139,8 @@ impl MigrationStep for Migration { System::::dec_consumers(deposit_account); // Get the deposit balance to transfer. - let total_deposit_balance = T::Currency::total_balance(deposit_account); - let reducible_deposit_balance = T::Currency::reducible_balance( + let total_deposit_balance = ::Currency::total_balance(deposit_account); + let reducible_deposit_balance = ::Currency::reducible_balance( deposit_account, Preservation::Expendable, Fortitude::Force, @@ -169,7 +169,7 @@ impl MigrationStep for Migration { HexDisplay::from(&deposit_account.encode()), HexDisplay::from(&account.encode()) ); - let transferred_deposit_balance = T::Currency::transfer( + let transferred_deposit_balance = ::Currency::transfer( deposit_account, &account, reducible_deposit_balance, @@ -202,7 +202,7 @@ impl MigrationStep for Migration { HexDisplay::from(&account.encode()) ); - T::Currency::hold( + ::Currency::hold( &HoldReason::StorageDepositReserve.into(), &account, transferred_deposit_balance, @@ -234,10 +234,10 @@ impl MigrationStep for Migration { // Store last key for next migration step self.last_account = Some(account); - (IsFinished::No, T::WeightInfo::v15_migration_step()) + (IsFinished::No, ::WeightInfo::v15_migration_step()) } else { log::info!(target: LOG_TARGET, "Done Migrating Storage Deposits."); - (IsFinished::Yes, T::WeightInfo::v15_migration_step()) + (IsFinished::Yes, ::WeightInfo::v15_migration_step()) } } @@ -253,8 +253,8 @@ impl MigrationStep for Migration { ( account.clone(), contract.clone(), - T::Currency::total_balance(&account), - T::Currency::total_balance(&contract.deposit_account), + ::Currency::total_balance(&account), + ::Currency::total_balance(&contract.deposit_account), ) }) .collect(); @@ -276,8 +276,8 @@ impl MigrationStep for Migration { log::debug!(target: LOG_TARGET, "Account: 0x{} ", HexDisplay::from(&account.encode())); let on_hold = - T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &account); - let account_balance = T::Currency::total_balance(&account); + ::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &account); + let account_balance = ::Currency::total_balance(&account); log::debug!( target: LOG_TARGET, diff --git a/substrate/frame/contracts/src/schedule.rs b/substrate/frame/contracts/src/schedule.rs index 5ca18af026a4..71b50f5c913e 100644 --- a/substrate/frame/contracts/src/schedule.rs +++ b/substrate/frame/contracts/src/schedule.rs @@ -348,13 +348,13 @@ macro_rules! replace_token { macro_rules! call_zero { ($name:ident, $( $arg:expr ),*) => { - T::WeightInfo::$name($( replace_token!($arg 0) ),*) + ::WeightInfo::$name($( replace_token!($arg 0) ),*) }; } macro_rules! cost_args { ($name:ident, $( $arg: expr ),+) => { - (T::WeightInfo::$name($( $arg ),+).saturating_sub(call_zero!($name, $( $arg ),+))) + (::WeightInfo::$name($( $arg ),+).saturating_sub(call_zero!($name, $( $arg ),+))) } } diff --git a/substrate/frame/contracts/src/storage.rs b/substrate/frame/contracts/src/storage.rs index d4d261f4ec1f..f678d3468056 100644 --- a/substrate/frame/contracts/src/storage.rs +++ b/substrate/frame/contracts/src/storage.rs @@ -275,9 +275,9 @@ impl ContractInfo { /// Calculates the weight that is necessary to remove one key from the trie and how many /// of those keys can be deleted from the deletion queue given the supplied weight limit. pub fn deletion_budget(weight_limit: Weight) -> (Weight, u32) { - let base_weight = T::WeightInfo::on_process_deletion_queue_batch(); - let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) - - T::WeightInfo::on_initialize_per_trie_key(0); + let base_weight = ::WeightInfo::on_process_deletion_queue_batch(); + let weight_per_key = ::WeightInfo::on_initialize_per_trie_key(1) - + ::WeightInfo::on_initialize_per_trie_key(0); // `weight_per_key` being zero makes no sense and would constitute a failure to // benchmark properly. We opt for not removing any keys at all in this case. diff --git a/substrate/frame/contracts/src/storage/meter.rs b/substrate/frame/contracts/src/storage/meter.rs index 9f098090bc8b..11f12593aed0 100644 --- a/substrate/frame/contracts/src/storage/meter.rs +++ b/substrate/frame/contracts/src/storage/meter.rs @@ -452,7 +452,7 @@ where self.total_deposit = Deposit::Charge(ed); // We need to make sure that the contract's account exists. - T::Currency::transfer(origin, contract, ed, Preservation::Preserve)?; + ::Currency::transfer(origin, contract, ed, Preservation::Preserve)?; // A consumer is added at account creation and removed it on termination, otherwise the // runtime could remove the account. As long as a contract exists its account must exist. @@ -526,14 +526,14 @@ impl Ext for ReservingExt { // We are sending the `min_leftover` and the `min_balance` from the origin // account as part of a contract call. Hence origin needs to have those left over // as free balance after accounting for all deposits. - let max = T::Currency::reducible_balance(origin, Preservation::Preserve, Polite) + let max = ::Currency::reducible_balance(origin, Preservation::Preserve, Polite) .saturating_sub(min_leftover) .saturating_sub(Pallet::::min_balance()); let default = max.min(T::DefaultDepositLimit::get()); let limit = limit.unwrap_or(default); ensure!( limit <= max && - matches!(T::Currency::can_withdraw(origin, limit), WithdrawConsequence::Success), + matches!(::Currency::can_withdraw(origin, limit), WithdrawConsequence::Success), >::StorageDepositNotEnoughFunds, ); Ok(limit) @@ -550,7 +550,7 @@ impl Ext for ReservingExt { Deposit::Charge(amount) => { // This could fail if the `origin` does not have enough liquidity. Ideally, though, // this should have been checked before with `check_limit`. - T::Currency::transfer_and_hold( + ::Currency::transfer_and_hold( &HoldReason::StorageDepositReserve.into(), origin, contract, @@ -570,7 +570,7 @@ impl Ext for ReservingExt { ); }, Deposit::Refund(amount) => { - let transferred = T::Currency::transfer_on_hold( + let transferred = ::Currency::transfer_on_hold( &HoldReason::StorageDepositReserve.into(), contract, origin, @@ -604,10 +604,10 @@ impl Ext for ReservingExt { if let ContractState::::Terminated { beneficiary } = state { System::::dec_consumers(&contract); // Whatever is left in the contract is sent to the termination beneficiary. - T::Currency::transfer( + ::Currency::transfer( &contract, &beneficiary, - T::Currency::reducible_balance(&contract, Preservation::Expendable, Polite), + ::Currency::reducible_balance(&contract, Preservation::Expendable, Polite), Preservation::Expendable, )?; } diff --git a/substrate/frame/contracts/src/wasm/mod.rs b/substrate/frame/contracts/src/wasm/mod.rs index 5fc65e314ad9..d999f497535a 100644 --- a/substrate/frame/contracts/src/wasm/mod.rs +++ b/substrate/frame/contracts/src/wasm/mod.rs @@ -139,8 +139,8 @@ impl Token for CodeLoadToken { // contract code. This is why we subtract `T::*::(0)`. We need to do this at this // point because when charging the general weight for calling the contract we don't know the // size of the contract. - T::WeightInfo::call_with_code_per_byte(self.0) - .saturating_sub(T::WeightInfo::call_with_code_per_byte(0)) + ::WeightInfo::call_with_code_per_byte(self.0) + .saturating_sub(::WeightInfo::call_with_code_per_byte(0)) } } @@ -237,7 +237,7 @@ impl WasmBlob { // the `owner` is always the origin of the current transaction. None => { let deposit = self.code_info.deposit; - T::Currency::hold( + ::Currency::hold( &HoldReason::CodeUploadDepositReserve.into(), &self.code_info.owner, deposit, @@ -267,7 +267,7 @@ impl WasmBlob { if let Some(code_info) = existing { ensure!(code_info.refcount == 0, >::CodeInUse); ensure!(&code_info.owner == origin, BadOrigin); - let _ = T::Currency::release( + let _ = ::Currency::release( &HoldReason::CodeUploadDepositReserve.into(), &code_info.owner, code_info.deposit, From 3b1cc37ee2d73a07f7eebb02b867db84323370a3 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 29 Aug 2023 16:26:58 +0200 Subject: [PATCH 002/115] Add pallet_xcm::execute --- substrate/frame/contracts/Cargo.toml | 7 ++++ substrate/frame/contracts/src/exec.rs | 19 +++++++++ substrate/frame/contracts/src/lib.rs | 2 +- substrate/frame/contracts/src/wasm/runtime.rs | 42 +++++++++++++++++++ 4 files changed, 69 insertions(+), 1 deletion(-) diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 8d6a9fd9cdb3..92283ca53748 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -48,6 +48,10 @@ sp-io = { path = "../../primitives/io", default-features = false} sp-runtime = { path = "../../primitives/runtime", default-features = false} sp-std = { path = "../../primitives/std", default-features = false} +xcm = { path = "../../../polkadot/xcm", default-features = false} +xcm-executor = { path = "../../../polkadot/xcm/xcm-executor", default-features = false} +pallet-xcm = { path = "../../../polkadot/xcm/pallet-xcm", default-features = false} + [dev-dependencies] array-bytes = "6.1" assert_matches = "1" @@ -90,6 +94,9 @@ std = [ "sp-std/std", "wasm-instrument/std", "wasmi/std", + "pallet-xcm/std", + "xcm/std", + "xcm-executor/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index 1cb672c4d2ae..0ce9f565801b 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -50,6 +50,7 @@ use sp_runtime::{ DispatchError, }; use sp_std::{fmt::Debug, marker::PhantomData, mem, prelude::*, vec::Vec}; +use xcm::VersionedXcm; pub type AccountIdOf = ::AccountId; pub type MomentOf = <::Time as Time>::Moment; @@ -62,6 +63,8 @@ pub type TopicOf = ::Hash; /// Type for variable sized storage key. Used for transparent hashing. type VarSizedKey = BoundedVec::MaxStorageKeyLen>; +pub type CallOf = ::RuntimeCall; + /// Combined key type for both fixed and variable sized storage keys. pub enum Key { /// Variant for fixed sized keys. @@ -346,6 +349,13 @@ pub trait Ext: sealing::Sealed { &mut self, code_hash: &CodeHash, ) -> Result<(), DispatchError>; + + /// Execute an XCM message locally, using the contract's address as the origin. + fn xcm_execute( + &mut self, + message: VersionedXcm>, + max_weight: Weight, + ) -> DispatchResultWithPostInfo; } /// Describes the different functions that can be exported by an [`Executable`]. @@ -1447,6 +1457,15 @@ where call.dispatch(origin) } + fn xcm_execute( + &mut self, + message: VersionedXcm>, + max_weight: Weight, + ) -> DispatchResultWithPostInfo { + let origin = RawOrigin::Signed(self.address().clone()).into(); + pallet_xcm::Pallet::::execute(origin, Box::new(message), max_weight) + } + fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()> { secp256k1_ecdsa_recover_compressed(signature, message_hash).map_err(|_| ()) } diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 5176e4baa13a..ca6daebc483b 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -230,7 +230,7 @@ pub mod pallet { pub struct Pallet(_); #[pallet::config] - pub trait Config: frame_system::Config { + pub trait Config: frame_system::Config + pallet_xcm::Config { /// The time implementation used to supply timestamps to contracts through `seal_now`. type Time: Time; diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 4bc00388f726..59dee7e2f90c 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -113,6 +113,8 @@ pub enum ReturnCode { EcdsaRecoverFailed = 11, /// sr25519 signature verification failed. Sr25519VerifyFailed = 12, + /// The `seal_xcm_execute` was executed but returned an error. + XcmExcuteFailed = 13, } impl From for ReturnCode { @@ -260,6 +262,8 @@ pub enum RuntimeCosts { ChainExtension(Weight), /// Weight charged for calling into the runtime. CallRuntime(Weight), + /// Weight charged for Executing an XCM message. + XcmExecute(Weight), /// Weight of calling `seal_set_code_hash` SetCodeHash, /// Weight of calling `ecdsa_to_eth_address` @@ -350,6 +354,7 @@ impl RuntimeCosts { .saturating_add(s.sr25519_verify_per_byte.saturating_mul(len.into())), ChainExtension(weight) => weight, CallRuntime(weight) => weight, + XcmExecute(weight) => weight, SetCodeHash => s.set_code_hash, EcdsaToEthAddress => s.ecdsa_to_eth_address, ReentrantCount => s.reentrance_count, @@ -2626,6 +2631,43 @@ pub mod env { } } + fn xcm_execute( + ctx: _, + memory: _, + call_ptr: u32, + call_len: u32, + max_weight_ptr: u32, + ) -> Result { + use crate::exec::CallOf; + use frame_support::dispatch::{extract_actual_weight, DispatchInfo}; + use pallet_xcm::WeightInfo; + use xcm::VersionedXcm; + + ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; + let message: VersionedXcm> = + ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; + let max_weight: Weight = ctx.read_sandbox_memory_as(memory, max_weight_ptr)?; + + let weight = max_weight.saturating_add(::WeightInfo::execute()); + let dispatch_info = DispatchInfo { weight, ..Default::default() }; + + let charged = ctx.charge_gas(RuntimeCosts::XcmExecute(weight))?; + let result = ctx.ext.xcm_execute(message, max_weight); + let actual_weight = extract_actual_weight(&result, &dispatch_info); + ctx.adjust_gas(charged, RuntimeCosts::XcmExecute(actual_weight)); + + match result { + Ok(_) => Ok(ReturnCode::Success), + Err(e) => { + if ctx.ext.append_debug_buffer("") { + ctx.ext.append_debug_buffer("seal0::xcm_execute failed with: "); + ctx.ext.append_debug_buffer(e.into()); + }; + Ok(ReturnCode::XcmExcuteFailed) + }, + } + } + /// Recovers the ECDSA public key from the given message hash and signature. /// /// Writes the public key into the given output buffer. From 22430a3b0fc1dca17cbead72c183907c32dbf281 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Wed, 30 Aug 2023 09:20:08 +0200 Subject: [PATCH 003/115] wip --- substrate/frame/contracts/src/exec.rs | 15 +++- substrate/frame/contracts/src/wasm/runtime.rs | 83 ++++++++++++------- 2 files changed, 66 insertions(+), 32 deletions(-) diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index 0ce9f565801b..abe56add3c43 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -50,7 +50,7 @@ use sp_runtime::{ DispatchError, }; use sp_std::{fmt::Debug, marker::PhantomData, mem, prelude::*, vec::Vec}; -use xcm::VersionedXcm; +use xcm::{VersionedMultiLocation, VersionedXcm}; pub type AccountIdOf = ::AccountId; pub type MomentOf = <::Time as Time>::Moment; @@ -352,10 +352,12 @@ pub trait Ext: sealing::Sealed { /// Execute an XCM message locally, using the contract's address as the origin. fn xcm_execute( - &mut self, - message: VersionedXcm>, + &self, + msg: VersionedXcm>, max_weight: Weight, ) -> DispatchResultWithPostInfo; + + fn xcm_send(&self, dest: VersionedMultiLocation, msg: VersionedXcm<()>) -> DispatchResult; } /// Describes the different functions that can be exported by an [`Executable`]. @@ -1458,7 +1460,7 @@ where } fn xcm_execute( - &mut self, + &self, message: VersionedXcm>, max_weight: Weight, ) -> DispatchResultWithPostInfo { @@ -1466,6 +1468,11 @@ where pallet_xcm::Pallet::::execute(origin, Box::new(message), max_weight) } + fn xcm_send(&self, dest: VersionedMultiLocation, msg: VersionedXcm<()>) -> DispatchResult { + let origin = RawOrigin::Signed(self.address().clone()).into(); + pallet_xcm::Pallet::::send(origin, Box::new(dest), Box::new(msg)) + } + fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()> { secp256k1_ecdsa_recover_compressed(signature, message_hash).map_err(|_| ()) } diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 59dee7e2f90c..b18ae0352b2a 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -26,7 +26,13 @@ use crate::{ use bitflags::bitflags; use codec::{Decode, DecodeLimit, Encode, MaxEncodedLen}; -use frame_support::{ensure, traits::Get, weights::Weight}; +use frame_support::{ + dispatch::{DispatchError, DispatchInfo}, + ensure, + pallet_prelude::DispatchResultWithPostInfo, + traits::Get, + weights::Weight, +}; use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags}; use pallet_contracts_proc_macro::define_env; use sp_io::hashing::{blake2_128, blake2_256, keccak_256, sha2_256}; @@ -262,8 +268,6 @@ pub enum RuntimeCosts { ChainExtension(Weight), /// Weight charged for calling into the runtime. CallRuntime(Weight), - /// Weight charged for Executing an XCM message. - XcmExecute(Weight), /// Weight of calling `seal_set_code_hash` SetCodeHash, /// Weight of calling `ecdsa_to_eth_address` @@ -354,7 +358,6 @@ impl RuntimeCosts { .saturating_add(s.sr25519_verify_per_byte.saturating_mul(len.into())), ChainExtension(weight) => weight, CallRuntime(weight) => weight, - XcmExecute(weight) => weight, SetCodeHash => s.set_code_hash, EcdsaToEthAddress => s.ecdsa_to_eth_address, ReentrantCount => s.reentrance_count, @@ -563,6 +566,29 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { self.ext.gas_meter_mut().adjust_gas(charged, token); } + /// Charge, Run and adjust gas, for executing the given dispatchable. + fn call_dispatchable DispatchResultWithPostInfo>( + &mut self, + dispatch_info: DispatchInfo, + run: F, + ) -> Result { + use frame_support::dispatch::extract_actual_weight; + let charged = self.charge_gas(RuntimeCosts::CallRuntime(dispatch_info.weight))?; + let result = run(self.ext); + let actual_weight = extract_actual_weight(&result, &dispatch_info); + self.adjust_gas(charged, RuntimeCosts::CallRuntime(actual_weight)); + match result { + Ok(_) => Ok(ReturnCode::Success), + Err(e) => { + if self.ext.append_debug_buffer("") { + self.ext.append_debug_buffer("call failed with: "); + self.ext.append_debug_buffer(e.into()); + }; + Ok(ReturnCode::CallRuntimeFailed) + }, + } + } + /// Read designated chunk from the sandbox memory. /// /// Returns `Err` if one of the following conditions occurs: @@ -1028,6 +1054,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { // for every function. #[define_env(doc)] pub mod env { + /// Set the value at the given key in the contract storage. /// /// Equivalent to the newer [`seal1`][`super::api_doc::Version1::set_storage`] version with the @@ -2610,25 +2637,11 @@ pub mod env { call_ptr: u32, call_len: u32, ) -> Result { - use frame_support::dispatch::{extract_actual_weight, GetDispatchInfo}; + use frame_support::dispatch::GetDispatchInfo; ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; let call: ::RuntimeCall = ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; - let dispatch_info = call.get_dispatch_info(); - let charged = ctx.charge_gas(RuntimeCosts::CallRuntime(dispatch_info.weight))?; - let result = ctx.ext.call_runtime(call); - let actual_weight = extract_actual_weight(&result, &dispatch_info); - ctx.adjust_gas(charged, RuntimeCosts::CallRuntime(actual_weight)); - match result { - Ok(_) => Ok(ReturnCode::Success), - Err(e) => { - if ctx.ext.append_debug_buffer("") { - ctx.ext.append_debug_buffer("seal0::call_runtime failed with: "); - ctx.ext.append_debug_buffer(e.into()); - }; - Ok(ReturnCode::CallRuntimeFailed) - }, - } + ctx.call_dispatchable(call.get_dispatch_info(), |ext| ext.call_runtime(call)) } fn xcm_execute( @@ -2639,7 +2652,7 @@ pub mod env { max_weight_ptr: u32, ) -> Result { use crate::exec::CallOf; - use frame_support::dispatch::{extract_actual_weight, DispatchInfo}; + use frame_support::dispatch::DispatchInfo; use pallet_xcm::WeightInfo; use xcm::VersionedXcm; @@ -2650,20 +2663,34 @@ pub mod env { let weight = max_weight.saturating_add(::WeightInfo::execute()); let dispatch_info = DispatchInfo { weight, ..Default::default() }; + ctx.call_dispatchable(dispatch_info, |ext| ext.xcm_execute(message, max_weight)) + } - let charged = ctx.charge_gas(RuntimeCosts::XcmExecute(weight))?; - let result = ctx.ext.xcm_execute(message, max_weight); - let actual_weight = extract_actual_weight(&result, &dispatch_info); - ctx.adjust_gas(charged, RuntimeCosts::XcmExecute(actual_weight)); + fn xcm_send( + ctx: _, + memory: _, + call_ptr: u32, + call_len: u32, + dest_ptr: u32, + ) -> Result { + use pallet_xcm::WeightInfo; + use xcm::{VersionedMultiLocation, VersionedXcm}; - match result { + ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; + let dest: VersionedMultiLocation = ctx.read_sandbox_memory_as(memory, dest_ptr)?; + let message: VersionedXcm<()> = + ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; + + let weight = ::WeightInfo::send(); + ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; + match ctx.ext.xcm_send(dest, message) { Ok(_) => Ok(ReturnCode::Success), Err(e) => { if ctx.ext.append_debug_buffer("") { - ctx.ext.append_debug_buffer("seal0::xcm_execute failed with: "); + ctx.ext.append_debug_buffer("call failed with: "); ctx.ext.append_debug_buffer(e.into()); }; - Ok(ReturnCode::XcmExcuteFailed) + Ok(ReturnCode::CallRuntimeFailed) }, } } From c6e1f49144f2ba14644087b00c61b14ac105642d Mon Sep 17 00:00:00 2001 From: pgherveou Date: Wed, 30 Aug 2023 11:16:22 +0200 Subject: [PATCH 004/115] add other xcm_methods --- .../xcm-executor/src/traits/on_response.rs | 9 ++-- substrate/frame/contracts/src/exec.rs | 48 ++++++++++++++++--- substrate/frame/contracts/src/wasm/runtime.rs | 46 ++++++++++++++++++ 3 files changed, 94 insertions(+), 9 deletions(-) diff --git a/polkadot/xcm/xcm-executor/src/traits/on_response.rs b/polkadot/xcm/xcm-executor/src/traits/on_response.rs index 3558160dc87d..ec15053e4482 100644 --- a/polkadot/xcm/xcm-executor/src/traits/on_response.rs +++ b/polkadot/xcm/xcm-executor/src/traits/on_response.rs @@ -16,8 +16,11 @@ use crate::Xcm; use core::result; -use frame_support::pallet_prelude::{Get, TypeInfo}; -use parity_scale_codec::{FullCodec, MaxEncodedLen}; +use frame_support::{ + dispatch::fmt::Debug, + pallet_prelude::{Get, TypeInfo}, +}; +use parity_scale_codec::{Decode, Encode, FullCodec, MaxEncodedLen}; use sp_arithmetic::traits::Zero; use sp_std::fmt::Debug; use xcm::latest::{ @@ -103,7 +106,7 @@ impl VersionChangeNotifier for () { } /// The possible state of an XCM query response. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Encode, Decode)] pub enum QueryResponseStatus { /// The response has arrived, and includes the inner Response and the block number it arrived /// at. diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index abe56add3c43..519f23f84251 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -45,12 +45,10 @@ use sp_core::{ Get, }; use sp_io::{crypto::secp256k1_ecdsa_recover_compressed, hashing::blake2_256}; -use sp_runtime::{ - traits::{Convert, Dispatchable, Hash, Zero}, - DispatchError, -}; -use sp_std::{fmt::Debug, marker::PhantomData, mem, prelude::*, vec::Vec}; -use xcm::{VersionedMultiLocation, VersionedXcm}; +use sp_runtime::traits::{Convert, Hash, Zero}; +use sp_std::{marker::PhantomData, mem, prelude::*, vec::Vec}; +use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; +use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; pub type AccountIdOf = ::AccountId; pub type MomentOf = <::Time as Time>::Moment; @@ -358,6 +356,17 @@ pub trait Ext: sealing::Sealed { ) -> DispatchResultWithPostInfo; fn xcm_send(&self, dest: VersionedMultiLocation, msg: VersionedXcm<()>) -> DispatchResult; + + fn xcm_query( + &self, + timeout: BlockNumberFor, + match_querier: VersionedMultiLocation, + ) -> Result< as QueryHandler>::QueryId, DispatchError>; + + fn xcm_take_response( + &self, + query_id: as QueryHandler>::QueryId, + ) -> QueryResponseStatus>; } /// Describes the different functions that can be exported by an [`Executable`]. @@ -1473,6 +1482,33 @@ where pallet_xcm::Pallet::::send(origin, Box::new(dest), Box::new(msg)) } + fn xcm_query( + &self, + timeout: BlockNumberFor, + match_querier: VersionedMultiLocation, + ) -> Result< as QueryHandler>::QueryId, DispatchError> { + use frame_support::traits::EnsureOrigin; + + let origin = RawOrigin::Signed(self.address().clone()).into(); + let responder = ::ExecuteXcmOrigin::ensure_origin(origin)?; + + let query_id = as QueryHandler>::new_query( + responder, + timeout.into(), + MultiLocation::try_from(match_querier) + .map_err(|_| Into::::into(pallet_xcm::Error::::BadVersion))?, + ); + + Ok(query_id) + } + + fn xcm_take_response( + &self, + query_id: as QueryHandler>::QueryId, + ) -> QueryResponseStatus> { + as QueryHandler>::take_response(query_id) + } + fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()> { secp256k1_ecdsa_recover_compressed(signature, message_hash).map_err(|_| ()) } diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index b18ae0352b2a..1a5a4bdf0495 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2695,6 +2695,52 @@ pub mod env { } } + fn xcm_query( + ctx: _, + memory: _, + timeout_ptr: u32, + match_querier_ptr: u32, + output_ptr: u32, + ) -> Result { + use frame_system::pallet_prelude::BlockNumberFor; + use xcm::VersionedMultiLocation; + + let timeout: BlockNumberFor = ctx.read_sandbox_memory_as(memory, timeout_ptr)?; + let match_querier: VersionedMultiLocation = + ctx.read_sandbox_memory_as(memory, match_querier_ptr)?; + // TODO benchmark + match ctx.ext.xcm_query(timeout, match_querier) { + Ok(query_id) => { + ctx.write_sandbox_memory(memory, output_ptr, &query_id.encode())?; + Ok(ReturnCode::Success) + }, + Err(e) => { + if ctx.ext.append_debug_buffer("") { + ctx.ext.append_debug_buffer("call failed with: "); + ctx.ext.append_debug_buffer(e.into()); + }; + Ok(ReturnCode::CallRuntimeFailed) + }, + } + } + + fn xcm_take_response( + ctx: _, + memory: _, + query_id_ptr: u32, + output_ptr: u32, + ) -> Result { + use xcm_executor::traits::QueryHandler; + + let query_id: as QueryHandler>::QueryId = + ctx.read_sandbox_memory_as(memory, query_id_ptr)?; + + // TODO benchmark + let response = ctx.ext.xcm_take_response(query_id); + ctx.write_sandbox_memory(memory, output_ptr, &response.encode())?; + Ok(ReturnCode::Success) + } + /// Recovers the ECDSA public key from the given message hash and signature. /// /// Writes the public key into the given output buffer. From bf668392842dea50b388a94e3d785853c6b5612e Mon Sep 17 00:00:00 2001 From: pgherveou Date: Thu, 31 Aug 2023 11:52:07 +0200 Subject: [PATCH 005/115] add benchmarks --- polkadot/xcm/pallet-xcm/src/benchmarking.rs | 27 +++++++++++++++++++ polkadot/xcm/pallet-xcm/src/lib.rs | 15 +++++++++++ substrate/frame/contracts/src/wasm/runtime.rs | 11 ++++++-- 3 files changed, 51 insertions(+), 2 deletions(-) diff --git a/polkadot/xcm/pallet-xcm/src/benchmarking.rs b/polkadot/xcm/pallet-xcm/src/benchmarking.rs index aca4bd1fb3fa..e1a9835ce667 100644 --- a/polkadot/xcm/pallet-xcm/src/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm/src/benchmarking.rs @@ -190,6 +190,33 @@ benchmarks! { Pallet::::check_xcm_version_change(VersionMigrationStage::MigrateAndNotifyOldTargets, Weight::zero()); } + new_query { + let responder = MultiLocation::from(Parent); + let timeout = 1u32.into(); + let match_querier = MultiLocation::from(Here); + }: { + Pallet::::new_query(responder, timeout, match_querier); + } + + take_response { + let responder = MultiLocation::from(Parent); + let timeout = 1u32.into(); + let match_querier = MultiLocation::from(Here); + let query_id = Pallet::::new_query(responder, timeout, match_querier); + let infos = (0 .. xcm::v3::MaxPalletsInfo::get()).map(|_| PalletInfo::new( + 1u32, + (0..xcm::v3::MaxPalletNameLen::get()).map(|_| 97u8).collect::>().try_into().unwrap(), + (0..xcm::v3::MaxPalletNameLen::get()).map(|_| 97u8).collect::>().try_into().unwrap(), + 1u32, + 0u32, + 0u32, + ).unwrap()).collect::>(); + Pallet::::expect_response(query_id, Response::PalletsInfo(infos.try_into().unwrap())); + + }: { + Pallet::::take_response(query_id); + } + impl_benchmark_test_suite!( Pallet, crate::mock::new_test_ext_with_balances(Vec::new()), diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 9dfb63c2c9c6..b08ec0032e57 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -73,6 +73,13 @@ pub trait WeightInfo { fn notify_target_migration_fail() -> Weight; fn migrate_version_notify_targets() -> Weight; fn migrate_and_notify_old_targets() -> Weight; + // TODO remove after benchmark are regenerated + fn new_query() -> Weight { + Weight::zero() + } + fn take_response() -> Weight { + Weight::zero() + } } /// fallback implementation @@ -141,6 +148,14 @@ impl WeightInfo for TestWeightInfo { fn migrate_and_notify_old_targets() -> Weight { Weight::from_parts(100_000_000, 0) } + + fn new_query() -> Weight { + Weight::from_parts(100_000_000, 0) + } + + fn take_response() -> Weight { + Weight::from_parts(100_000_000, 0) + } } #[frame_support::pallet] diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 1a5a4bdf0495..37dee861979a 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2703,12 +2703,16 @@ pub mod env { output_ptr: u32, ) -> Result { use frame_system::pallet_prelude::BlockNumberFor; + use pallet_xcm::WeightInfo; use xcm::VersionedMultiLocation; let timeout: BlockNumberFor = ctx.read_sandbox_memory_as(memory, timeout_ptr)?; let match_querier: VersionedMultiLocation = ctx.read_sandbox_memory_as(memory, match_querier_ptr)?; - // TODO benchmark + + let weight = ::WeightInfo::new_query(); + ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; + match ctx.ext.xcm_query(timeout, match_querier) { Ok(query_id) => { ctx.write_sandbox_memory(memory, output_ptr, &query_id.encode())?; @@ -2730,12 +2734,15 @@ pub mod env { query_id_ptr: u32, output_ptr: u32, ) -> Result { + use pallet_xcm::WeightInfo; use xcm_executor::traits::QueryHandler; let query_id: as QueryHandler>::QueryId = ctx.read_sandbox_memory_as(memory, query_id_ptr)?; - // TODO benchmark + let weight = ::WeightInfo::take_response(); + ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; + let response = ctx.ext.xcm_take_response(query_id); ctx.write_sandbox_memory(memory, output_ptr, &response.encode())?; Ok(ReturnCode::Success) From a348bd92f9327f0357f1c49a5903e9150b71e3bc Mon Sep 17 00:00:00 2001 From: pgherveou Date: Thu, 31 Aug 2023 21:21:49 +0200 Subject: [PATCH 006/115] build fixes --- Cargo.lock | 4 ++-- polkadot/xcm/xcm-executor/src/traits/on_response.rs | 5 +---- substrate/frame/contracts/Cargo.toml | 4 ++-- 3 files changed, 5 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 935468746338..2e94827d9e70 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9421,11 +9421,11 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-std", + "staging-xcm", + "staging-xcm-executor", "wasm-instrument 0.4.0", "wasmi 0.30.0", "wat", - "xcm", - "xcm-executor", ] [[package]] diff --git a/polkadot/xcm/xcm-executor/src/traits/on_response.rs b/polkadot/xcm/xcm-executor/src/traits/on_response.rs index ec15053e4482..eb6008edbdc2 100644 --- a/polkadot/xcm/xcm-executor/src/traits/on_response.rs +++ b/polkadot/xcm/xcm-executor/src/traits/on_response.rs @@ -16,10 +16,7 @@ use crate::Xcm; use core::result; -use frame_support::{ - dispatch::fmt::Debug, - pallet_prelude::{Get, TypeInfo}, -}; +use frame_support::{ensure, traits::Get, weights::Weight}; use parity_scale_codec::{Decode, Encode, FullCodec, MaxEncodedLen}; use sp_arithmetic::traits::Zero; use sp_std::fmt::Debug; diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 92283ca53748..050443c3fdeb 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -48,8 +48,8 @@ sp-io = { path = "../../primitives/io", default-features = false} sp-runtime = { path = "../../primitives/runtime", default-features = false} sp-std = { path = "../../primitives/std", default-features = false} -xcm = { path = "../../../polkadot/xcm", default-features = false} -xcm-executor = { path = "../../../polkadot/xcm/xcm-executor", default-features = false} +xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false} +xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor", default-features = false} pallet-xcm = { path = "../../../polkadot/xcm/pallet-xcm", default-features = false} [dev-dependencies] From b2a9f4e647ea5717465ebe67b49d45a0a3c5227a Mon Sep 17 00:00:00 2001 From: pgherveou Date: Thu, 31 Aug 2023 21:28:14 +0200 Subject: [PATCH 007/115] fix --- polkadot/xcm/xcm-executor/src/traits/on_response.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/polkadot/xcm/xcm-executor/src/traits/on_response.rs b/polkadot/xcm/xcm-executor/src/traits/on_response.rs index eb6008edbdc2..a0ed9522df6c 100644 --- a/polkadot/xcm/xcm-executor/src/traits/on_response.rs +++ b/polkadot/xcm/xcm-executor/src/traits/on_response.rs @@ -16,7 +16,7 @@ use crate::Xcm; use core::result; -use frame_support::{ensure, traits::Get, weights::Weight}; +use frame_support::pallet_prelude::{Get, TypeInfo}; use parity_scale_codec::{Decode, Encode, FullCodec, MaxEncodedLen}; use sp_arithmetic::traits::Zero; use sp_std::fmt::Debug; From d20d6cac7a0133f831406442f275f887437df082 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 1 Sep 2023 09:34:17 +0200 Subject: [PATCH 008/115] fix post-rebase missing imports --- substrate/frame/contracts/src/exec.rs | 7 +++++-- substrate/frame/contracts/src/wasm/runtime.rs | 5 +---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index 519f23f84251..1a055813f2e9 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -45,8 +45,11 @@ use sp_core::{ Get, }; use sp_io::{crypto::secp256k1_ecdsa_recover_compressed, hashing::blake2_256}; -use sp_runtime::traits::{Convert, Hash, Zero}; -use sp_std::{marker::PhantomData, mem, prelude::*, vec::Vec}; +use sp_runtime::{ + traits::{Convert, Dispatchable, Hash, Zero}, + DispatchError, +}; +use sp_std::{fmt::Debug, marker::PhantomData, mem, prelude::*, vec::Vec}; use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 37dee861979a..31ac76f17b11 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -27,10 +27,7 @@ use crate::{ use bitflags::bitflags; use codec::{Decode, DecodeLimit, Encode, MaxEncodedLen}; use frame_support::{ - dispatch::{DispatchError, DispatchInfo}, - ensure, - pallet_prelude::DispatchResultWithPostInfo, - traits::Get, + dispatch::DispatchInfo, ensure, pallet_prelude::DispatchResultWithPostInfo, traits::Get, weights::Weight, }; use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags}; From 83885854b618b4a7877fa6bc1f6536d43e28c16d Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 1 Sep 2023 10:56:46 +0200 Subject: [PATCH 009/115] Revert "boilerplate type changes" This reverts commit 251e8cdc15f91e7793071935c7cc3e05c83262d5. --- Cargo.lock | 1 - .../frame/contracts/src/benchmarking/mod.rs | 72 +++++++++---------- substrate/frame/contracts/src/exec.rs | 9 ++- substrate/frame/contracts/src/lib.rs | 45 +++++------- substrate/frame/contracts/src/migration.rs | 10 +-- .../frame/contracts/src/migration/v09.rs | 6 +- .../frame/contracts/src/migration/v10.rs | 6 +- .../frame/contracts/src/migration/v11.rs | 4 +- .../frame/contracts/src/migration/v12.rs | 6 +- .../frame/contracts/src/migration/v13.rs | 6 +- .../frame/contracts/src/migration/v14.rs | 14 ++-- .../frame/contracts/src/migration/v15.rs | 22 +++--- substrate/frame/contracts/src/schedule.rs | 4 +- substrate/frame/contracts/src/storage.rs | 6 +- .../frame/contracts/src/storage/meter.rs | 14 ++-- substrate/frame/contracts/src/wasm/mod.rs | 8 +-- 16 files changed, 112 insertions(+), 121 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2e94827d9e70..a7e7b7907f30 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9407,7 +9407,6 @@ dependencies = [ "pallet-proxy", "pallet-timestamp", "pallet-utility", - "pallet-xcm", "parity-scale-codec", "pretty_assertions", "rand 0.8.5", diff --git a/substrate/frame/contracts/src/benchmarking/mod.rs b/substrate/frame/contracts/src/benchmarking/mod.rs index 3fa66b966b24..ac5787e23404 100644 --- a/substrate/frame/contracts/src/benchmarking/mod.rs +++ b/substrate/frame/contracts/src/benchmarking/mod.rs @@ -97,7 +97,7 @@ where data: Vec, ) -> Result, &'static str> { let value = Pallet::::min_balance(); - ::Currency::set_balance(&caller, caller_funding::()); + T::Currency::set_balance(&caller, caller_funding::()); let salt = vec![0xff]; let addr = Contracts::::contract_address(&caller, &module.hash, &data, &salt); @@ -163,7 +163,7 @@ where /// Set the balance of the contract to the supplied amount. fn set_balance(&self, balance: BalanceOf) { - ::Currency::set_balance(&self.account_id, balance); + T::Currency::set_balance(&self.account_id, balance); } /// Returns `true` iff all storage entries related to code storage exist. @@ -291,7 +291,7 @@ benchmarks! { #[pov_mode = Measured] v14_migration_step { let account = account::("account", 0, 0); - ::Currency::set_balance(&account, caller_funding::()); + T::Currency::set_balance(&account, caller_funding::()); v14::store_dummy_code::>(account); let mut m = v14::Migration::>::default(); }: { @@ -406,21 +406,21 @@ benchmarks! { let salt = vec![42u8; s as usize]; let value = Pallet::::min_balance(); let caller = whitelisted_caller(); - ::Currency::set_balance(&caller, caller_funding::()); + T::Currency::set_balance(&caller, caller_funding::()); let WasmModule { code, hash, .. } = WasmModule::::sized(c, Location::Call); let origin = RawOrigin::Signed(caller.clone()); let addr = Contracts::::contract_address(&caller, &hash, &input, &salt); }: _(origin, value, Weight::MAX, None, code, input, salt) verify { - let deposit = ::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr); + let deposit = T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr); // uploading the code reserves some balance in the callers account - let code_deposit = ::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &caller); + let code_deposit = T::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &caller); assert_eq!( - ::Currency::balance(&caller), + T::Currency::balance(&caller), caller_funding::() - value - deposit - code_deposit - Pallet::::min_balance(), ); // contract has the full value - assert_eq!(::Currency::balance(&addr), value + Pallet::::min_balance()); + assert_eq!(T::Currency::balance(&addr), value + Pallet::::min_balance()); } // Instantiate uses a dummy contract constructor to measure the overhead of the instantiate. @@ -434,21 +434,21 @@ benchmarks! { let salt = vec![42u8; s as usize]; let value = Pallet::::min_balance(); let caller = whitelisted_caller(); - ::Currency::set_balance(&caller, caller_funding::()); + T::Currency::set_balance(&caller, caller_funding::()); let WasmModule { code, hash, .. } = WasmModule::::dummy(); let origin = RawOrigin::Signed(caller.clone()); let addr = Contracts::::contract_address(&caller, &hash, &input, &salt); Contracts::::store_code_raw(code, caller.clone())?; }: _(origin, value, Weight::MAX, None, hash, input, salt) verify { - let deposit = ::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr); + let deposit = T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr); // value was removed from the caller assert_eq!( - ::Currency::balance(&caller), + T::Currency::balance(&caller), caller_funding::() - value - deposit - Pallet::::min_balance(), ); // contract has the full value - assert_eq!(::Currency::balance(&addr), value + Pallet::::min_balance()); + assert_eq!(T::Currency::balance(&addr), value + Pallet::::min_balance()); } // We just call a dummy contract to measure the overhead of the call extrinsic. @@ -467,17 +467,17 @@ benchmarks! { let value = Pallet::::min_balance(); let origin = RawOrigin::Signed(instance.caller.clone()); let callee = instance.addr.clone(); - let before = ::Currency::balance(&instance.account_id); + let before = T::Currency::balance(&instance.account_id); }: _(origin, callee, value, Weight::MAX, None, data) verify { - let deposit = ::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id); + let deposit = T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id); // value and value transferred via call should be removed from the caller assert_eq!( - ::Currency::balance(&instance.caller), + T::Currency::balance(&instance.caller), caller_funding::() - instance.value - value - deposit - Pallet::::min_balance(), ); // contract should have received the value - assert_eq!(::Currency::balance(&instance.account_id), before + value); + assert_eq!(T::Currency::balance(&instance.account_id), before + value); // contract should still exist instance.info()?; } @@ -489,13 +489,13 @@ benchmarks! { upload_code { let c in 0 .. T::MaxCodeLen::get(); let caller = whitelisted_caller(); - ::Currency::set_balance(&caller, caller_funding::()); + T::Currency::set_balance(&caller, caller_funding::()); let WasmModule { code, hash, .. } = WasmModule::::sized(c, Location::Call); let origin = RawOrigin::Signed(caller.clone()); }: _(origin, code, None, Determinism::Enforced) verify { // uploading the code reserves some balance in the callers account - assert!(::Currency::total_balance_on_hold(&caller) > 0u32.into()); + assert!(T::Currency::total_balance_on_hold(&caller) > 0u32.into()); assert!(>::code_exists(&hash)); } @@ -505,17 +505,17 @@ benchmarks! { #[pov_mode = Measured] remove_code { let caller = whitelisted_caller(); - ::Currency::set_balance(&caller, caller_funding::()); + T::Currency::set_balance(&caller, caller_funding::()); let WasmModule { code, hash, .. } = WasmModule::::dummy(); let origin = RawOrigin::Signed(caller.clone()); let uploaded = >::bare_upload_code(caller.clone(), code, None, Determinism::Enforced)?; assert_eq!(uploaded.code_hash, hash); - assert_eq!(uploaded.deposit, ::Currency::total_balance_on_hold(&caller)); + assert_eq!(uploaded.deposit, T::Currency::total_balance_on_hold(&caller)); assert!(>::code_exists(&hash)); }: _(origin, hash) verify { // removing the code should have unreserved the deposit - assert_eq!(::Currency::total_balance_on_hold(&caller), 0u32.into()); + assert_eq!(T::Currency::total_balance_on_hold(&caller), 0u32.into()); assert!(>::code_removed(&hash)); } @@ -889,7 +889,7 @@ benchmarks! { let beneficiary_len = beneficiary_bytes.len(); let caller = whitelisted_caller(); - ::Currency::set_balance(&caller, caller_funding::()); + T::Currency::set_balance(&caller, caller_funding::()); // Maximize the delegate_dependencies to account for the worst-case scenario. let code_hashes = (0..T::MaxDelegateDependencies::get()) @@ -941,15 +941,15 @@ benchmarks! { }); let instance = Contract::::new(code, vec![])?; let origin = RawOrigin::Signed(instance.caller.clone()); - assert_eq!(::Currency::total_balance(&beneficiary), 0u32.into()); - assert_eq!(::Currency::balance(&instance.account_id), Pallet::::min_balance() * 2u32.into()); - assert_ne!(::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id), 0u32.into()); + assert_eq!(T::Currency::total_balance(&beneficiary), 0u32.into()); + assert_eq!(T::Currency::balance(&instance.account_id), Pallet::::min_balance() * 2u32.into()); + assert_ne!(T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id), 0u32.into()); }: call(origin, instance.addr.clone(), 0u32.into(), Weight::MAX, None, vec![]) verify { if r > 0 { - assert_eq!(::Currency::total_balance(&instance.account_id), 0u32.into()); - assert_eq!(::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id), 0u32.into()); - assert_eq!(::Currency::total_balance(&beneficiary), Pallet::::min_balance() * 2u32.into()); + assert_eq!(T::Currency::total_balance(&instance.account_id), 0u32.into()); + assert_eq!(T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id), 0u32.into()); + assert_eq!(T::Currency::total_balance(&beneficiary), Pallet::::min_balance() * 2u32.into()); } } @@ -1718,12 +1718,12 @@ benchmarks! { instance.set_balance(value * (r + 1).into()); let origin = RawOrigin::Signed(instance.caller.clone()); for account in &accounts { - assert_eq!(::Currency::total_balance(account), 0u32.into()); + assert_eq!(T::Currency::total_balance(account), 0u32.into()); } }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) verify { for account in &accounts { - assert_eq!(::Currency::total_balance(account), value); + assert_eq!(T::Currency::total_balance(account), value); } } @@ -1812,7 +1812,7 @@ benchmarks! { .map(|i| { let code = WasmModule::::dummy_with_bytes(i); let caller = whitelisted_caller(); - ::Currency::set_balance(&caller, caller_funding::()); + T::Currency::set_balance(&caller, caller_funding::()); Contracts::::store_code_raw(code.code, caller)?; Ok(code.hash) }) @@ -1934,7 +1934,7 @@ benchmarks! { .. Default::default() }); let caller = whitelisted_caller(); - ::Currency::set_balance(&caller, caller_funding::()); + T::Currency::set_balance(&caller, caller_funding::()); Contracts::::store_code_raw(code.code, caller)?; Ok(code.hash) }) @@ -2040,7 +2040,7 @@ benchmarks! { let hash_bytes = callee_code.hash.encode(); let hash_len = hash_bytes.len(); let caller = whitelisted_caller(); - ::Currency::set_balance(&caller, caller_funding::()); + T::Currency::set_balance(&caller, caller_funding::()); Contracts::::store_code_raw(callee_code.code, caller)?; let value: BalanceOf = t.into(); let value_bytes = value.encode(); @@ -2384,7 +2384,7 @@ benchmarks! { .map(|i| { let new_code = WasmModule::::dummy_with_bytes(i); let caller = whitelisted_caller(); - ::Currency::set_balance(&caller, caller_funding::()); + T::Currency::set_balance(&caller, caller_funding::()); Contracts::::store_code_raw(new_code.code, caller)?; Ok(new_code.hash) }) @@ -2427,7 +2427,7 @@ benchmarks! { .map(|i| { let new_code = WasmModule::::dummy_with_bytes(65 + i); let caller = whitelisted_caller(); - ::Currency::set_balance(&caller, caller_funding::()); + T::Currency::set_balance(&caller, caller_funding::()); Contracts::::store_code_raw(new_code.code, caller)?; Ok(new_code.hash) }) @@ -2465,7 +2465,7 @@ benchmarks! { .map(|i| { let new_code = WasmModule::::dummy_with_bytes(65 + i); let caller = whitelisted_caller(); - ::Currency::set_balance(&caller, caller_funding::()); + T::Currency::set_balance(&caller, caller_funding::()); Contracts::::store_code_raw(new_code.code, caller)?; Ok(new_code.hash) }) diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index 1a055813f2e9..1e50ecb82238 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -1126,7 +1126,7 @@ where value: BalanceOf, ) -> DispatchResult { if !value.is_zero() && from != to { - ::Currency::transfer(from, to, value, preservation) + T::Currency::transfer(from, to, value, preservation) .map_err(|_| Error::::TransferFailed)?; } Ok(()) @@ -1392,7 +1392,7 @@ where } fn balance(&self) -> BalanceOf { - ::Currency::balance(&self.top_frame().account_id) + T::Currency::balance(&self.top_frame().account_id) } fn value_transferred(&self) -> BalanceOf { @@ -1408,7 +1408,7 @@ where } fn minimum_balance(&self) -> BalanceOf { - ::Currency::minimum_balance() + T::Currency::minimum_balance() } fn deposit_event(&mut self, topics: Vec, data: Vec) { @@ -1465,8 +1465,7 @@ where } fn call_runtime(&self, call: ::RuntimeCall) -> DispatchResultWithPostInfo { - let mut origin: ::RuntimeOrigin = - RawOrigin::Signed(self.address().clone()).into(); + let mut origin: T::RuntimeOrigin = RawOrigin::Signed(self.address().clone()).into(); origin.add_filter(T::CallFilter::contains); call.dispatch(origin) } diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index ca6daebc483b..46152529e1b4 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -253,10 +253,8 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// The overarching call type. - type RuntimeCall: Dispatchable< - RuntimeOrigin = ::RuntimeOrigin, - PostInfo = PostDispatchInfo, - > + GetDispatchInfo + type RuntimeCall: Dispatchable + + GetDispatchInfo + codec::Decode + IsType<::RuntimeCall>; @@ -427,7 +425,7 @@ pub mod pallet { } ContractInfo::::process_deletion_queue_batch(remaining_weight) - .saturating_add(::WeightInfo::on_process_deletion_queue_batch()) + .saturating_add(T::WeightInfo::on_process_deletion_queue_batch()) } fn integrity_test() { @@ -505,7 +503,7 @@ pub mod pallet { { /// Deprecated version if [`Self::call`] for use in an in-storage `Call`. #[pallet::call_index(0)] - #[pallet::weight(::WeightInfo::call().saturating_add(>::compat_weight_limit(*gas_limit)))] + #[pallet::weight(T::WeightInfo::call().saturating_add(>::compat_weight_limit(*gas_limit)))] #[allow(deprecated)] #[deprecated(note = "1D weight is used in this extrinsic, please migrate to `call`")] pub fn call_old_weight( @@ -529,7 +527,7 @@ pub mod pallet { /// Deprecated version if [`Self::instantiate_with_code`] for use in an in-storage `Call`. #[pallet::call_index(1)] #[pallet::weight( - ::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32, salt.len() as u32) + T::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32, salt.len() as u32) .saturating_add(>::compat_weight_limit(*gas_limit)) )] #[allow(deprecated)] @@ -559,7 +557,7 @@ pub mod pallet { /// Deprecated version if [`Self::instantiate`] for use in an in-storage `Call`. #[pallet::call_index(2)] #[pallet::weight( - ::WeightInfo::instantiate(data.len() as u32, salt.len() as u32).saturating_add(>::compat_weight_limit(*gas_limit)) + T::WeightInfo::instantiate(data.len() as u32, salt.len() as u32).saturating_add(>::compat_weight_limit(*gas_limit)) )] #[allow(deprecated)] #[deprecated(note = "1D weight is used in this extrinsic, please migrate to `instantiate`")] @@ -604,7 +602,7 @@ pub mod pallet { /// only be instantiated by permissioned entities. The same is true when uploading /// through [`Self::instantiate_with_code`]. #[pallet::call_index(3)] - #[pallet::weight(::WeightInfo::upload_code(code.len() as u32))] + #[pallet::weight(T::WeightInfo::upload_code(code.len() as u32))] pub fn upload_code( origin: OriginFor, code: Vec, @@ -622,7 +620,7 @@ pub mod pallet { /// A code can only be removed by its original uploader (its owner) and only if it is /// not used by any contract. #[pallet::call_index(4)] - #[pallet::weight(::WeightInfo::remove_code())] + #[pallet::weight(T::WeightInfo::remove_code())] pub fn remove_code( origin: OriginFor, code_hash: CodeHash, @@ -645,7 +643,7 @@ pub mod pallet { /// that the contract address is no longer derived from its code hash after calling /// this dispatchable. #[pallet::call_index(5)] - #[pallet::weight(::WeightInfo::set_code())] + #[pallet::weight(T::WeightInfo::set_code())] pub fn set_code( origin: OriginFor, dest: AccountIdLookupOf, @@ -692,7 +690,7 @@ pub mod pallet { /// * If no account exists and the call value is not less than `existential_deposit`, /// a regular account will be created and any value will be transferred. #[pallet::call_index(6)] - #[pallet::weight(::WeightInfo::call().saturating_add(*gas_limit))] + #[pallet::weight(T::WeightInfo::call().saturating_add(*gas_limit))] pub fn call( origin: OriginFor, dest: AccountIdLookupOf, @@ -718,9 +716,7 @@ pub mod pallet { output.result = Err(>::ContractReverted.into()); } } - output - .gas_meter - .into_dispatch_result(output.result, ::WeightInfo::call()) + output.gas_meter.into_dispatch_result(output.result, T::WeightInfo::call()) } /// Instantiates a new contract from the supplied `code` optionally transferring @@ -750,7 +746,7 @@ pub mod pallet { /// - The `deploy` function is executed in the context of the newly-created account. #[pallet::call_index(7)] #[pallet::weight( - ::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32, salt.len() as u32) + T::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32, salt.len() as u32) .saturating_add(*gas_limit) )] pub fn instantiate_with_code( @@ -799,9 +795,7 @@ pub mod pallet { output.gas_meter.into_dispatch_result( output.result.map(|(_address, output)| output), - ::WeightInfo::instantiate_with_code( - code_len, data_len, salt_len, - ), + T::WeightInfo::instantiate_with_code(code_len, data_len, salt_len), ) } @@ -812,7 +806,7 @@ pub mod pallet { /// must be supplied. #[pallet::call_index(8)] #[pallet::weight( - ::WeightInfo::instantiate(data.len() as u32, salt.len() as u32).saturating_add(*gas_limit) + T::WeightInfo::instantiate(data.len() as u32, salt.len() as u32).saturating_add(*gas_limit) )] pub fn instantiate( origin: OriginFor, @@ -843,7 +837,7 @@ pub mod pallet { } output.gas_meter.into_dispatch_result( output.result.map(|(_address, output)| output), - ::WeightInfo::instantiate(data_len, salt_len), + T::WeightInfo::instantiate(data_len, salt_len), ) } @@ -852,13 +846,12 @@ pub mod pallet { /// for the chain. Note that while the migration is in progress, the pallet will also /// leverage the `on_idle` hooks to run migration steps. #[pallet::call_index(9)] - #[pallet::weight(::WeightInfo::migrate().saturating_add(*weight_limit))] + #[pallet::weight(T::WeightInfo::migrate().saturating_add(*weight_limit))] pub fn migrate(origin: OriginFor, weight_limit: Weight) -> DispatchResultWithPostInfo { use migration::MigrateResult::*; ensure_signed(origin)?; - let weight_limit = - weight_limit.saturating_add(::WeightInfo::migrate()); + let weight_limit = weight_limit.saturating_add(T::WeightInfo::migrate()); let (result, weight) = Migration::::migrate(weight_limit); match result { @@ -870,7 +863,7 @@ pub mod pallet { Ok(PostDispatchInfo { actual_weight: Some(weight), pays_fee: Pays::Yes }), NoMigrationInProgress | NoMigrationPerformed => { let err: DispatchError = >::NoMigrationPerformed.into(); - Err(err.with_weight(::WeightInfo::migrate())) + Err(err.with_weight(T::WeightInfo::migrate())) }, } } @@ -1655,7 +1648,7 @@ impl Pallet { /// Return the existential deposit of [`Config::Currency`]. fn min_balance() -> BalanceOf { - <::Currency as Inspect>>::minimum_balance() + >>::minimum_balance() } /// Convert gas_limit from 1D Weight to a 2D Weight. diff --git a/substrate/frame/contracts/src/migration.rs b/substrate/frame/contracts/src/migration.rs index 8c3e048cd625..3e3d6f37884c 100644 --- a/substrate/frame/contracts/src/migration.rs +++ b/substrate/frame/contracts/src/migration.rs @@ -272,7 +272,7 @@ impl OnRuntimeUpgrade for Migration::WeightInfo::on_runtime_upgrade_noop() + return T::WeightInfo::on_runtime_upgrade_noop() } // In case a migration is already in progress we create the next migration @@ -284,7 +284,7 @@ impl OnRuntimeUpgrade for Migration::WeightInfo::on_runtime_upgrade_in_progress() + return T::WeightInfo::on_runtime_upgrade_in_progress() } log::info!( @@ -300,7 +300,7 @@ impl OnRuntimeUpgrade for Migration::WeightInfo::on_runtime_upgrade() + T::WeightInfo::on_runtime_upgrade() } #[cfg(feature = "try-runtime")] @@ -364,13 +364,13 @@ impl Migration { let name = >::name(); let mut weight_left = weight_limit; - if weight_left.checked_reduce(::WeightInfo::migrate()).is_none() { + if weight_left.checked_reduce(T::WeightInfo::migrate()).is_none() { return (MigrateResult::NoMigrationPerformed, Weight::zero()) } MigrationInProgress::::mutate_exists(|progress| { let Some(cursor_before) = progress.as_mut() else { - return (MigrateResult::NoMigrationInProgress, ::WeightInfo::migration_noop()) + return (MigrateResult::NoMigrationInProgress, T::WeightInfo::migration_noop()) }; // if a migration is running it is always upgrading to the next version diff --git a/substrate/frame/contracts/src/migration/v09.rs b/substrate/frame/contracts/src/migration/v09.rs index 3761c9e90a8a..98fcccc2c0be 100644 --- a/substrate/frame/contracts/src/migration/v09.rs +++ b/substrate/frame/contracts/src/migration/v09.rs @@ -84,7 +84,7 @@ impl MigrationStep for Migration { const VERSION: u16 = 9; fn max_step_weight() -> Weight { - ::WeightInfo::v9_migration_step(T::MaxCodeLen::get()) + T::WeightInfo::v9_migration_step(T::MaxCodeLen::get()) } fn step(&mut self) -> (IsFinished, Weight) { @@ -106,10 +106,10 @@ impl MigrationStep for Migration { }; CodeStorage::::insert(key, module); self.last_code_hash = Some(key); - (IsFinished::No, ::WeightInfo::v9_migration_step(len)) + (IsFinished::No, T::WeightInfo::v9_migration_step(len)) } else { log::debug!(target: LOG_TARGET, "No more contracts code to migrate"); - (IsFinished::Yes, ::WeightInfo::v9_migration_step(0)) + (IsFinished::Yes, T::WeightInfo::v9_migration_step(0)) } } diff --git a/substrate/frame/contracts/src/migration/v10.rs b/substrate/frame/contracts/src/migration/v10.rs index 8a6a933ed1f2..f02e28f6fde3 100644 --- a/substrate/frame/contracts/src/migration/v10.rs +++ b/substrate/frame/contracts/src/migration/v10.rs @@ -154,7 +154,7 @@ where const VERSION: u16 = 10; fn max_step_weight() -> Weight { - ::WeightInfo::v10_migration_step() + T::WeightInfo::v10_migration_step() } fn step(&mut self) -> (IsFinished, Weight) { @@ -264,10 +264,10 @@ where // Store last key for next migration step self.last_account = Some(account); - (IsFinished::No, ::WeightInfo::v10_migration_step()) + (IsFinished::No, T::WeightInfo::v10_migration_step()) } else { log::debug!(target: LOG_TARGET, "Done Migrating contract info"); - (IsFinished::Yes, ::WeightInfo::v10_migration_step()) + (IsFinished::Yes, T::WeightInfo::v10_migration_step()) } } diff --git a/substrate/frame/contracts/src/migration/v11.rs b/substrate/frame/contracts/src/migration/v11.rs index 8b7f70a1963b..a5b11f6e0897 100644 --- a/substrate/frame/contracts/src/migration/v11.rs +++ b/substrate/frame/contracts/src/migration/v11.rs @@ -76,7 +76,7 @@ impl MigrationStep for Migration { // but in practice the queue is always empty, so 128 is a good enough approximation for not // underestimating the weight of our migration. fn max_step_weight() -> Weight { - ::WeightInfo::v11_migration_step(128) + T::WeightInfo::v11_migration_step(128) } fn step(&mut self) -> (IsFinished, Weight) { @@ -101,7 +101,7 @@ impl MigrationStep for Migration { >::set(queue); } - (IsFinished::Yes, ::WeightInfo::v11_migration_step(len as u32)) + (IsFinished::Yes, T::WeightInfo::v11_migration_step(len as u32)) } #[cfg(feature = "try-runtime")] diff --git a/substrate/frame/contracts/src/migration/v12.rs b/substrate/frame/contracts/src/migration/v12.rs index 919636b353b7..eb045aa42e9d 100644 --- a/substrate/frame/contracts/src/migration/v12.rs +++ b/substrate/frame/contracts/src/migration/v12.rs @@ -143,7 +143,7 @@ where const VERSION: u16 = 12; fn max_step_weight() -> Weight { - ::WeightInfo::v12_migration_step(T::MaxCodeLen::get()) + T::WeightInfo::v12_migration_step(T::MaxCodeLen::get()) } fn step(&mut self) -> (IsFinished, Weight) { @@ -230,10 +230,10 @@ where self.last_code_hash = Some(hash); - (IsFinished::No, ::WeightInfo::v12_migration_step(code_len as u32)) + (IsFinished::No, T::WeightInfo::v12_migration_step(code_len as u32)) } else { log::debug!(target: LOG_TARGET, "No more OwnerInfo to migrate"); - (IsFinished::Yes, ::WeightInfo::v12_migration_step(0)) + (IsFinished::Yes, T::WeightInfo::v12_migration_step(0)) } } diff --git a/substrate/frame/contracts/src/migration/v13.rs b/substrate/frame/contracts/src/migration/v13.rs index 6a9f225a5bfe..dd2eb12eb62a 100644 --- a/substrate/frame/contracts/src/migration/v13.rs +++ b/substrate/frame/contracts/src/migration/v13.rs @@ -99,7 +99,7 @@ impl MigrationStep for Migration { const VERSION: u16 = 13; fn max_step_weight() -> Weight { - ::WeightInfo::v13_migration_step() + T::WeightInfo::v13_migration_step() } fn step(&mut self) -> (IsFinished, Weight) { @@ -126,10 +126,10 @@ impl MigrationStep for Migration { }; ContractInfoOf::::insert(key.clone(), info); self.last_account = Some(key); - (IsFinished::No, ::WeightInfo::v13_migration_step()) + (IsFinished::No, T::WeightInfo::v13_migration_step()) } else { log::debug!(target: LOG_TARGET, "No more contracts to migrate"); - (IsFinished::Yes, ::WeightInfo::v13_migration_step()) + (IsFinished::Yes, T::WeightInfo::v13_migration_step()) } } } diff --git a/substrate/frame/contracts/src/migration/v14.rs b/substrate/frame/contracts/src/migration/v14.rs index 3e1ded534e42..efb49dff4f10 100644 --- a/substrate/frame/contracts/src/migration/v14.rs +++ b/substrate/frame/contracts/src/migration/v14.rs @@ -129,7 +129,7 @@ where const VERSION: u16 = 14; fn max_step_weight() -> Weight { - ::WeightInfo::v14_migration_step() + T::WeightInfo::v14_migration_step() } fn step(&mut self) -> (IsFinished, Weight) { @@ -168,7 +168,7 @@ where hash, ); - ::Currency::hold( + T::Currency::hold( &HoldReason::CodeUploadDepositReserve.into(), &code_info.owner, amount, @@ -185,10 +185,10 @@ where }); self.last_code_hash = Some(hash); - (IsFinished::No, ::WeightInfo::v14_migration_step()) + (IsFinished::No, T::WeightInfo::v14_migration_step()) } else { log::debug!(target: LOG_TARGET, "No more code upload deposit to migrate"); - (IsFinished::Yes, ::WeightInfo::v14_migration_step()) + (IsFinished::Yes, T::WeightInfo::v14_migration_step()) } } @@ -228,7 +228,7 @@ where let count = owner_balance_allocation.len(); for (owner, old_balance_allocation) in owner_balance_allocation { let held = - ::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &owner); + T::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &owner); log::debug!( target: LOG_TARGET, "Validating code upload deposit for owner 0x{:?}, reserved: {:?}, held: {:?}", @@ -242,11 +242,11 @@ where target: LOG_TARGET, "Validating total balance for owner 0x{:?}, new: {:?}, old: {:?}", HexDisplay::from(&owner.encode()), - ::Currency::total_balance(&owner), + T::Currency::total_balance(&owner), old_balance_allocation.total ); ensure!( - ::Currency::total_balance(&owner) == + T::Currency::total_balance(&owner) == BalanceOf::::decode(&mut &old_balance_allocation.total.encode()[..]) .unwrap(), "Balance mismatch " diff --git a/substrate/frame/contracts/src/migration/v15.rs b/substrate/frame/contracts/src/migration/v15.rs index 018d6f3c838e..180fe855ca66 100644 --- a/substrate/frame/contracts/src/migration/v15.rs +++ b/substrate/frame/contracts/src/migration/v15.rs @@ -122,7 +122,7 @@ impl MigrationStep for Migration { const VERSION: u16 = 15; fn max_step_weight() -> Weight { - ::WeightInfo::v15_migration_step() + T::WeightInfo::v15_migration_step() } fn step(&mut self) -> (IsFinished, Weight) { @@ -139,8 +139,8 @@ impl MigrationStep for Migration { System::::dec_consumers(deposit_account); // Get the deposit balance to transfer. - let total_deposit_balance = ::Currency::total_balance(deposit_account); - let reducible_deposit_balance = ::Currency::reducible_balance( + let total_deposit_balance = T::Currency::total_balance(deposit_account); + let reducible_deposit_balance = T::Currency::reducible_balance( deposit_account, Preservation::Expendable, Fortitude::Force, @@ -169,7 +169,7 @@ impl MigrationStep for Migration { HexDisplay::from(&deposit_account.encode()), HexDisplay::from(&account.encode()) ); - let transferred_deposit_balance = ::Currency::transfer( + let transferred_deposit_balance = T::Currency::transfer( deposit_account, &account, reducible_deposit_balance, @@ -202,7 +202,7 @@ impl MigrationStep for Migration { HexDisplay::from(&account.encode()) ); - ::Currency::hold( + T::Currency::hold( &HoldReason::StorageDepositReserve.into(), &account, transferred_deposit_balance, @@ -234,10 +234,10 @@ impl MigrationStep for Migration { // Store last key for next migration step self.last_account = Some(account); - (IsFinished::No, ::WeightInfo::v15_migration_step()) + (IsFinished::No, T::WeightInfo::v15_migration_step()) } else { log::info!(target: LOG_TARGET, "Done Migrating Storage Deposits."); - (IsFinished::Yes, ::WeightInfo::v15_migration_step()) + (IsFinished::Yes, T::WeightInfo::v15_migration_step()) } } @@ -253,8 +253,8 @@ impl MigrationStep for Migration { ( account.clone(), contract.clone(), - ::Currency::total_balance(&account), - ::Currency::total_balance(&contract.deposit_account), + T::Currency::total_balance(&account), + T::Currency::total_balance(&contract.deposit_account), ) }) .collect(); @@ -276,8 +276,8 @@ impl MigrationStep for Migration { log::debug!(target: LOG_TARGET, "Account: 0x{} ", HexDisplay::from(&account.encode())); let on_hold = - ::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &account); - let account_balance = ::Currency::total_balance(&account); + T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &account); + let account_balance = T::Currency::total_balance(&account); log::debug!( target: LOG_TARGET, diff --git a/substrate/frame/contracts/src/schedule.rs b/substrate/frame/contracts/src/schedule.rs index 71b50f5c913e..5ca18af026a4 100644 --- a/substrate/frame/contracts/src/schedule.rs +++ b/substrate/frame/contracts/src/schedule.rs @@ -348,13 +348,13 @@ macro_rules! replace_token { macro_rules! call_zero { ($name:ident, $( $arg:expr ),*) => { - ::WeightInfo::$name($( replace_token!($arg 0) ),*) + T::WeightInfo::$name($( replace_token!($arg 0) ),*) }; } macro_rules! cost_args { ($name:ident, $( $arg: expr ),+) => { - (::WeightInfo::$name($( $arg ),+).saturating_sub(call_zero!($name, $( $arg ),+))) + (T::WeightInfo::$name($( $arg ),+).saturating_sub(call_zero!($name, $( $arg ),+))) } } diff --git a/substrate/frame/contracts/src/storage.rs b/substrate/frame/contracts/src/storage.rs index f678d3468056..d4d261f4ec1f 100644 --- a/substrate/frame/contracts/src/storage.rs +++ b/substrate/frame/contracts/src/storage.rs @@ -275,9 +275,9 @@ impl ContractInfo { /// Calculates the weight that is necessary to remove one key from the trie and how many /// of those keys can be deleted from the deletion queue given the supplied weight limit. pub fn deletion_budget(weight_limit: Weight) -> (Weight, u32) { - let base_weight = ::WeightInfo::on_process_deletion_queue_batch(); - let weight_per_key = ::WeightInfo::on_initialize_per_trie_key(1) - - ::WeightInfo::on_initialize_per_trie_key(0); + let base_weight = T::WeightInfo::on_process_deletion_queue_batch(); + let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) - + T::WeightInfo::on_initialize_per_trie_key(0); // `weight_per_key` being zero makes no sense and would constitute a failure to // benchmark properly. We opt for not removing any keys at all in this case. diff --git a/substrate/frame/contracts/src/storage/meter.rs b/substrate/frame/contracts/src/storage/meter.rs index 11f12593aed0..9f098090bc8b 100644 --- a/substrate/frame/contracts/src/storage/meter.rs +++ b/substrate/frame/contracts/src/storage/meter.rs @@ -452,7 +452,7 @@ where self.total_deposit = Deposit::Charge(ed); // We need to make sure that the contract's account exists. - ::Currency::transfer(origin, contract, ed, Preservation::Preserve)?; + T::Currency::transfer(origin, contract, ed, Preservation::Preserve)?; // A consumer is added at account creation and removed it on termination, otherwise the // runtime could remove the account. As long as a contract exists its account must exist. @@ -526,14 +526,14 @@ impl Ext for ReservingExt { // We are sending the `min_leftover` and the `min_balance` from the origin // account as part of a contract call. Hence origin needs to have those left over // as free balance after accounting for all deposits. - let max = ::Currency::reducible_balance(origin, Preservation::Preserve, Polite) + let max = T::Currency::reducible_balance(origin, Preservation::Preserve, Polite) .saturating_sub(min_leftover) .saturating_sub(Pallet::::min_balance()); let default = max.min(T::DefaultDepositLimit::get()); let limit = limit.unwrap_or(default); ensure!( limit <= max && - matches!(::Currency::can_withdraw(origin, limit), WithdrawConsequence::Success), + matches!(T::Currency::can_withdraw(origin, limit), WithdrawConsequence::Success), >::StorageDepositNotEnoughFunds, ); Ok(limit) @@ -550,7 +550,7 @@ impl Ext for ReservingExt { Deposit::Charge(amount) => { // This could fail if the `origin` does not have enough liquidity. Ideally, though, // this should have been checked before with `check_limit`. - ::Currency::transfer_and_hold( + T::Currency::transfer_and_hold( &HoldReason::StorageDepositReserve.into(), origin, contract, @@ -570,7 +570,7 @@ impl Ext for ReservingExt { ); }, Deposit::Refund(amount) => { - let transferred = ::Currency::transfer_on_hold( + let transferred = T::Currency::transfer_on_hold( &HoldReason::StorageDepositReserve.into(), contract, origin, @@ -604,10 +604,10 @@ impl Ext for ReservingExt { if let ContractState::::Terminated { beneficiary } = state { System::::dec_consumers(&contract); // Whatever is left in the contract is sent to the termination beneficiary. - ::Currency::transfer( + T::Currency::transfer( &contract, &beneficiary, - ::Currency::reducible_balance(&contract, Preservation::Expendable, Polite), + T::Currency::reducible_balance(&contract, Preservation::Expendable, Polite), Preservation::Expendable, )?; } diff --git a/substrate/frame/contracts/src/wasm/mod.rs b/substrate/frame/contracts/src/wasm/mod.rs index d999f497535a..5fc65e314ad9 100644 --- a/substrate/frame/contracts/src/wasm/mod.rs +++ b/substrate/frame/contracts/src/wasm/mod.rs @@ -139,8 +139,8 @@ impl Token for CodeLoadToken { // contract code. This is why we subtract `T::*::(0)`. We need to do this at this // point because when charging the general weight for calling the contract we don't know the // size of the contract. - ::WeightInfo::call_with_code_per_byte(self.0) - .saturating_sub(::WeightInfo::call_with_code_per_byte(0)) + T::WeightInfo::call_with_code_per_byte(self.0) + .saturating_sub(T::WeightInfo::call_with_code_per_byte(0)) } } @@ -237,7 +237,7 @@ impl WasmBlob { // the `owner` is always the origin of the current transaction. None => { let deposit = self.code_info.deposit; - ::Currency::hold( + T::Currency::hold( &HoldReason::CodeUploadDepositReserve.into(), &self.code_info.owner, deposit, @@ -267,7 +267,7 @@ impl WasmBlob { if let Some(code_info) = existing { ensure!(code_info.refcount == 0, >::CodeInUse); ensure!(&code_info.owner == origin, BadOrigin); - let _ = ::Currency::release( + let _ = T::Currency::release( &HoldReason::CodeUploadDepositReserve.into(), &code_info.owner, code_info.deposit, From 4bae246294111d228e1990448fb6d07d59d0ff85 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 1 Sep 2023 12:34:07 +0200 Subject: [PATCH 010/115] Use trait instead of tight coupling --- Cargo.lock | 1 + substrate/frame/contracts/src/exec.rs | 65 -------- substrate/frame/contracts/src/lib.rs | 7 +- substrate/frame/contracts/src/tests.rs | 1 + substrate/frame/contracts/src/wasm/runtime.rs | 36 ++-- substrate/frame/contracts/src/xcm.rs | 154 ++++++++++++++++++ 6 files changed, 182 insertions(+), 82 deletions(-) create mode 100644 substrate/frame/contracts/src/xcm.rs diff --git a/Cargo.lock b/Cargo.lock index a7e7b7907f30..2e94827d9e70 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9407,6 +9407,7 @@ dependencies = [ "pallet-proxy", "pallet-timestamp", "pallet-utility", + "pallet-xcm", "parity-scale-codec", "pretty_assertions", "rand 0.8.5", diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index 1e50ecb82238..38c15a807c5d 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -50,8 +50,6 @@ use sp_runtime::{ DispatchError, }; use sp_std::{fmt::Debug, marker::PhantomData, mem, prelude::*, vec::Vec}; -use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; -use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; pub type AccountIdOf = ::AccountId; pub type MomentOf = <::Time as Time>::Moment; @@ -64,8 +62,6 @@ pub type TopicOf = ::Hash; /// Type for variable sized storage key. Used for transparent hashing. type VarSizedKey = BoundedVec::MaxStorageKeyLen>; -pub type CallOf = ::RuntimeCall; - /// Combined key type for both fixed and variable sized storage keys. pub enum Key { /// Variant for fixed sized keys. @@ -350,26 +346,6 @@ pub trait Ext: sealing::Sealed { &mut self, code_hash: &CodeHash, ) -> Result<(), DispatchError>; - - /// Execute an XCM message locally, using the contract's address as the origin. - fn xcm_execute( - &self, - msg: VersionedXcm>, - max_weight: Weight, - ) -> DispatchResultWithPostInfo; - - fn xcm_send(&self, dest: VersionedMultiLocation, msg: VersionedXcm<()>) -> DispatchResult; - - fn xcm_query( - &self, - timeout: BlockNumberFor, - match_querier: VersionedMultiLocation, - ) -> Result< as QueryHandler>::QueryId, DispatchError>; - - fn xcm_take_response( - &self, - query_id: as QueryHandler>::QueryId, - ) -> QueryResponseStatus>; } /// Describes the different functions that can be exported by an [`Executable`]. @@ -1470,47 +1446,6 @@ where call.dispatch(origin) } - fn xcm_execute( - &self, - message: VersionedXcm>, - max_weight: Weight, - ) -> DispatchResultWithPostInfo { - let origin = RawOrigin::Signed(self.address().clone()).into(); - pallet_xcm::Pallet::::execute(origin, Box::new(message), max_weight) - } - - fn xcm_send(&self, dest: VersionedMultiLocation, msg: VersionedXcm<()>) -> DispatchResult { - let origin = RawOrigin::Signed(self.address().clone()).into(); - pallet_xcm::Pallet::::send(origin, Box::new(dest), Box::new(msg)) - } - - fn xcm_query( - &self, - timeout: BlockNumberFor, - match_querier: VersionedMultiLocation, - ) -> Result< as QueryHandler>::QueryId, DispatchError> { - use frame_support::traits::EnsureOrigin; - - let origin = RawOrigin::Signed(self.address().clone()).into(); - let responder = ::ExecuteXcmOrigin::ensure_origin(origin)?; - - let query_id = as QueryHandler>::new_query( - responder, - timeout.into(), - MultiLocation::try_from(match_querier) - .map_err(|_| Into::::into(pallet_xcm::Error::::BadVersion))?, - ); - - Ok(query_id) - } - - fn xcm_take_response( - &self, - query_id: as QueryHandler>::QueryId, - ) -> QueryResponseStatus> { - as QueryHandler>::take_response(query_id) - } - fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()> { secp256k1_ecdsa_recover_compressed(signature, message_hash).map_err(|_| ()) } diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 46152529e1b4..3668774edf69 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -94,6 +94,7 @@ mod gas; mod schedule; mod storage; mod wasm; +mod xcm; pub mod chain_extension; pub mod debug; @@ -230,7 +231,7 @@ pub mod pallet { pub struct Pallet(_); #[pallet::config] - pub trait Config: frame_system::Config + pallet_xcm::Config { + pub trait Config: frame_system::Config { /// The time implementation used to supply timestamps to contracts through `seal_now`. type Time: Time; @@ -401,6 +402,8 @@ pub mod pallet { /// its type appears in the metadata. Only valid value is `()`. #[pallet::constant] type Environment: Get>; + + type Xcm: crate::xcm::XCM; } #[pallet::hooks] @@ -1002,6 +1005,8 @@ pub mod pallet { /// in this error. Note that this usually shouldn't happen as deploying such contracts /// is rejected. NoChainExtension, + /// TODO doc + XcmDisabled, /// A contract with the same AccountId already exists. DuplicateContract, /// A contract self destructed in its constructor. diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index 9d03a29b038c..20837ebe8fea 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -484,6 +484,7 @@ impl Config for Test { type MaxDelegateDependencies = MaxDelegateDependencies; type Debug = TestDebug; type Environment = (); + type Xcm = crate::xcm::NoopXcmConfig; } pub const ALICE: AccountId32 = AccountId32::new([1u8; 32]); diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 31ac76f17b11..72a59e92dafa 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -1051,6 +1051,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { // for every function. #[define_env(doc)] pub mod env { + use crate::xcm::XCM; /// Set the value at the given key in the contract storage. /// @@ -2648,9 +2649,8 @@ pub mod env { call_len: u32, max_weight_ptr: u32, ) -> Result { - use crate::exec::CallOf; + use crate::xcm::{CallOf, WeightInfo, XCM}; use frame_support::dispatch::DispatchInfo; - use pallet_xcm::WeightInfo; use xcm::VersionedXcm; ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; @@ -2658,9 +2658,13 @@ pub mod env { ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; let max_weight: Weight = ctx.read_sandbox_memory_as(memory, max_weight_ptr)?; - let weight = max_weight.saturating_add(::WeightInfo::execute()); + let weight = + max_weight.saturating_add(<::Xcm as XCM>::WeightInfo::execute()); let dispatch_info = DispatchInfo { weight, ..Default::default() }; - ctx.call_dispatchable(dispatch_info, |ext| ext.xcm_execute(message, max_weight)) + + ctx.call_dispatchable(dispatch_info, |ext| { + <::Xcm as XCM>::execute(ext.address(), message, max_weight) + }) } fn xcm_send( @@ -2670,7 +2674,7 @@ pub mod env { call_len: u32, dest_ptr: u32, ) -> Result { - use pallet_xcm::WeightInfo; + use crate::xcm::{WeightInfo, XCM}; use xcm::{VersionedMultiLocation, VersionedXcm}; ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; @@ -2678,9 +2682,9 @@ pub mod env { let message: VersionedXcm<()> = ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; - let weight = ::WeightInfo::send(); + let weight = <::Xcm as XCM>::WeightInfo::send(); ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; - match ctx.ext.xcm_send(dest, message) { + match <::Xcm as XCM>::send(ctx.ext.address(), dest, message) { Ok(_) => Ok(ReturnCode::Success), Err(e) => { if ctx.ext.append_debug_buffer("") { @@ -2699,18 +2703,19 @@ pub mod env { match_querier_ptr: u32, output_ptr: u32, ) -> Result { + use crate::xcm::{WeightInfo, XCM}; use frame_system::pallet_prelude::BlockNumberFor; - use pallet_xcm::WeightInfo; use xcm::VersionedMultiLocation; let timeout: BlockNumberFor = ctx.read_sandbox_memory_as(memory, timeout_ptr)?; let match_querier: VersionedMultiLocation = ctx.read_sandbox_memory_as(memory, match_querier_ptr)?; - let weight = ::WeightInfo::new_query(); + let weight = <::Xcm as XCM>::WeightInfo::query(); ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; - match ctx.ext.xcm_query(timeout, match_querier) { + match <::Xcm as XCM>::query(ctx.ext.address(), timeout, match_querier) + { Ok(query_id) => { ctx.write_sandbox_memory(memory, output_ptr, &query_id.encode())?; Ok(ReturnCode::Success) @@ -2731,16 +2736,15 @@ pub mod env { query_id_ptr: u32, output_ptr: u32, ) -> Result { - use pallet_xcm::WeightInfo; - use xcm_executor::traits::QueryHandler; + use crate::xcm::{WeightInfo, XCM}; - let query_id: as QueryHandler>::QueryId = + let query_id: <::Xcm as XCM>::QueryId = ctx.read_sandbox_memory_as(memory, query_id_ptr)?; - let weight = ::WeightInfo::take_response(); + let weight = <::Xcm as XCM>::WeightInfo::take_response(); ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; - - let response = ctx.ext.xcm_take_response(query_id); + // + let response = <::Xcm as XCM>::take_response(query_id); ctx.write_sandbox_memory(memory, output_ptr, &response.encode())?; Ok(ReturnCode::Success) } diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs new file mode 100644 index 000000000000..95f87c3d07a6 --- /dev/null +++ b/substrate/frame/contracts/src/xcm.rs @@ -0,0 +1,154 @@ +use crate::{AccountIdOf, Config, Error, RawOrigin}; +use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight}; +use frame_system::pallet_prelude::BlockNumberFor; +use sp_runtime::{DispatchError, DispatchResult}; +use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; +use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; +pub type CallOf = ::RuntimeCall; + +pub trait XCM { + type QueryId: Encode + Decode + MaxEncodedLen; + type WeightInfo: WeightInfo; + + fn execute( + origin: &AccountIdOf, + message: VersionedXcm>, + max_weight: Weight, + ) -> DispatchResultWithPostInfo; + fn send( + origin: &AccountIdOf, + dest: VersionedMultiLocation, + msg: VersionedXcm<()>, + ) -> DispatchResult; + fn query( + origin: &AccountIdOf, + timeout: BlockNumberFor, + match_querier: VersionedMultiLocation, + ) -> Result; + fn take_response(query_id: Self::QueryId) -> QueryResponseStatus>; +} + +pub struct NoopXcmConfig; + +impl XCM for NoopXcmConfig { + type QueryId = (); + type WeightInfo = Self; + fn execute( + _origin: &AccountIdOf, + _message: VersionedXcm>, + _max_weight: Weight, + ) -> DispatchResultWithPostInfo { + Err(Error::::XcmDisabled.into()).into() + } + fn send( + _origin: &AccountIdOf, + _dest: VersionedMultiLocation, + _msg: VersionedXcm<()>, + ) -> DispatchResult { + Err(Error::::XcmDisabled.into()) + } + fn query( + _origin: &AccountIdOf, + _timeout: BlockNumberFor, + _match_querier: VersionedMultiLocation, + ) -> Result { + Err(Error::::XcmDisabled.into()) + } + fn take_response(_query_id: Self::QueryId) -> QueryResponseStatus> { + QueryResponseStatus::UnexpectedVersion + } +} + +pub trait WeightInfo { + fn execute() -> Weight; + fn send() -> Weight; + fn query() -> Weight; + fn take_response() -> Weight; +} + +impl WeightInfo for NoopXcmConfig { + fn execute() -> Weight { + Weight::zero() + } + fn send() -> Weight { + Weight::zero() + } + fn query() -> Weight { + Weight::zero() + } + fn take_response() -> Weight { + Weight::zero() + } +} + +use pallet_xcm::WeightInfo as XcmWeightInfo; + +impl WeightInfo for T +where + T: pallet_xcm::Config, +{ + fn execute() -> Weight { + ::WeightInfo::execute() + } + fn send() -> Weight { + ::WeightInfo::send() + } + fn query() -> Weight { + ::WeightInfo::new_query() + } + fn take_response() -> Weight { + ::WeightInfo::take_response() + } +} + +impl XCM for T +where + T: pallet_xcm::Config, +{ + type QueryId = as QueryHandler>::QueryId; + type WeightInfo = T; + + fn execute( + origin: &AccountIdOf, + message: VersionedXcm>, + max_weight: Weight, + ) -> DispatchResultWithPostInfo { + let origin = RawOrigin::Signed(origin.clone()).into(); + pallet_xcm::Pallet::::execute(origin, Box::new(message), max_weight) + } + fn send( + origin: &AccountIdOf, + dest: VersionedMultiLocation, + msg: VersionedXcm<()>, + ) -> DispatchResult { + let origin = RawOrigin::Signed(origin.clone()).into(); + pallet_xcm::Pallet::::send(origin, Box::new(dest), Box::new(msg)) + } + + fn query( + origin: &AccountIdOf, + timeout: BlockNumberFor, + match_querier: VersionedMultiLocation, + ) -> Result { + use frame_support::traits::EnsureOrigin; + + let origin = RawOrigin::Signed(origin.clone()).into(); + let responder = ::ExecuteXcmOrigin::ensure_origin(origin)?; + + let query_id = as QueryHandler>::new_query( + responder, + timeout.into(), + MultiLocation::try_from(match_querier) + .map_err(|_| Into::::into(pallet_xcm::Error::::BadVersion))?, + ); + + Ok(query_id) + } + + fn take_response(query_id: Self::QueryId) -> QueryResponseStatus> { + as QueryHandler>::take_response(query_id) + } +} + +// impl From 06758990ee847156037f0269142f59ee267148d9 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 1 Sep 2023 14:27:00 +0200 Subject: [PATCH 011/115] add mock_network setup --- Cargo.lock | 9 + substrate/frame/contracts/Cargo.toml | 11 + substrate/frame/contracts/src/tests.rs | 2 + .../src/tests/mock_network/mocks/mod.rs | 18 + .../src/tests/mock_network/mocks/msg_queue.rs | 172 ++++++++ .../mock_network/mocks/relay_message_queue.rs | 52 +++ .../contracts/src/tests/mock_network/mod.rs | 152 +++++++ .../parachain/contracts_config.rs | 87 ++++ .../src/tests/mock_network/parachain/mod.rs | 383 ++++++++++++++++++ .../src/tests/mock_network/primitives.rs | 23 ++ .../src/tests/mock_network/relay_chain/mod.rs | 303 ++++++++++++++ .../src/tests/mock_network/xcm_utils.rs | 106 +++++ .../frame/contracts/src/tests/test_xcm.rs | 283 +++++++++++++ 13 files changed, 1601 insertions(+) create mode 100644 substrate/frame/contracts/src/tests/mock_network/mocks/mod.rs create mode 100644 substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs create mode 100644 substrate/frame/contracts/src/tests/mock_network/mocks/relay_message_queue.rs create mode 100644 substrate/frame/contracts/src/tests/mock_network/mod.rs create mode 100644 substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs create mode 100644 substrate/frame/contracts/src/tests/mock_network/parachain/mod.rs create mode 100644 substrate/frame/contracts/src/tests/mock_network/primitives.rs create mode 100644 substrate/frame/contracts/src/tests/mock_network/relay_chain/mod.rs create mode 100644 substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs create mode 100644 substrate/frame/contracts/src/tests/test_xcm.rs diff --git a/Cargo.lock b/Cargo.lock index 2e94827d9e70..61deb7825c1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9400,15 +9400,21 @@ dependencies = [ "frame-system", "impl-trait-for-tuples", "log", + "pallet-assets", "pallet-balances", "pallet-contracts-primitives", "pallet-contracts-proc-macro", "pallet-insecure-randomness-collective-flip", + "pallet-message-queue", "pallet-proxy", "pallet-timestamp", + "pallet-uniques", "pallet-utility", "pallet-xcm", "parity-scale-codec", + "polkadot-parachain", + "polkadot-primitives", + "polkadot-runtime-parachains", "pretty_assertions", "rand 0.8.5", "rand_pcg", @@ -9421,11 +9427,14 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-std", + "sp-tracing", "staging-xcm", + "staging-xcm-builder", "staging-xcm-executor", "wasm-instrument 0.4.0", "wasmi 0.30.0", "wat", + "xcm-simulator", ] [[package]] diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 050443c3fdeb..599581d56abf 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -59,13 +59,24 @@ env_logger = "0.9" pretty_assertions = "1" wat = "1" +# Polkadot Dependencies +xcm-simulator = {path = "../../../polkadot/xcm/xcm-simulator"} +polkadot-runtime-parachains = {path = "../../../polkadot/runtime/parachains"} +xcm-builder = {package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder"} +polkadot-parachain = { path = "../../../polkadot/parachain" } +polkadot-primitives = { path = "../../../polkadot/primitives" } + # Substrate Dependencies pallet-balances = { path = "../balances" } pallet-timestamp = { path = "../timestamp" } +pallet-message-queue = { path = "../message-queue" } pallet-insecure-randomness-collective-flip = { path = "../insecure-randomness-collective-flip" } pallet-utility = { path = "../utility" } +pallet-assets = { path = "../assets" } +pallet-uniques = { path = "../uniques" } pallet-proxy = { path = "../proxy" } sp-keystore = { path = "../../primitives/keystore" } +sp-tracing = { path = "../../primitives/tracing" } [features] default = [ "std" ] diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index 20837ebe8fea..7e4344a487b1 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -15,6 +15,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +mod mock_network; +mod test_xcm; mod pallet_dummy; mod test_debug; diff --git a/substrate/frame/contracts/src/tests/mock_network/mocks/mod.rs b/substrate/frame/contracts/src/tests/mock_network/mocks/mod.rs new file mode 100644 index 000000000000..bf3baec7a524 --- /dev/null +++ b/substrate/frame/contracts/src/tests/mock_network/mocks/mod.rs @@ -0,0 +1,18 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +pub mod msg_queue; +pub mod relay_message_queue; diff --git a/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs b/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs new file mode 100644 index 000000000000..21d5c67476be --- /dev/null +++ b/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs @@ -0,0 +1,172 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! Parachain runtime mock. + +use codec::{Decode, Encode}; + +use frame_support::weights::Weight; +use polkadot_parachain::primitives::{ + DmpMessageHandler, Id as ParaId, XcmpMessageFormat, XcmpMessageHandler, +}; +use polkadot_primitives::BlockNumber as RelayBlockNumber; +use sp_runtime::traits::{Get, Hash}; + +use sp_std::prelude::*; +use xcm::{latest::prelude::*, VersionedXcm}; + +#[frame_support::pallet] +pub mod pallet { + 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(super) type ParachainId = StorageValue<_, ParaId, ValueQuery>; + + #[pallet::storage] + #[pallet::getter(fn received_dmp)] + /// A queue of received DMP messages + pub(super) 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 + } + } +} diff --git a/substrate/frame/contracts/src/tests/mock_network/mocks/relay_message_queue.rs b/substrate/frame/contracts/src/tests/mock_network/mocks/relay_message_queue.rs new file mode 100644 index 000000000000..5d745e6742e4 --- /dev/null +++ b/substrate/frame/contracts/src/tests/mock_network/mocks/relay_message_queue.rs @@ -0,0 +1,52 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +use frame_support::{parameter_types, weights::Weight}; +use xcm::latest::prelude::*; +use xcm_simulator::{ + AggregateMessageOrigin, ProcessMessage, ProcessMessageError, UmpQueueId, WeightMeter, +}; + +use crate::tests::mock_network::relay_chain::{RuntimeCall, XcmConfig}; + +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) + } +} diff --git a/substrate/frame/contracts/src/tests/mock_network/mod.rs b/substrate/frame/contracts/src/tests/mock_network/mod.rs new file mode 100644 index 000000000000..0683bed0a502 --- /dev/null +++ b/substrate/frame/contracts/src/tests/mock_network/mod.rs @@ -0,0 +1,152 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +pub mod mocks; +pub mod parachain; +pub mod primitives; +pub mod relay_chain; +pub mod xcm_utils; + +use crate::tests::mock_network::primitives::{AccountId, UNITS}; +use sp_runtime::BuildStorage; +use xcm::latest::{prelude::*, MultiLocation}; +use xcm_executor::traits::ConvertLocation; +use xcm_simulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain, TestExt}; + +// Accounts +pub const ADMIN: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([0u8; 32]); +pub const ALICE: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([1u8; 32]); +pub const BOB: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([2u8; 32]); + +// Balances +pub const INITIAL_BALANCE: u128 = 1_000_000_000 * UNITS; + +decl_test_parachain! { + pub struct ParaA { + Runtime = parachain::Runtime, + XcmpMessageHandler = parachain::MsgQueue, + DmpMessageHandler = parachain::MsgQueue, + new_ext = para_ext(1), + } +} + +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![ + (1, ParaA), + ], + } +} + +pub fn relay_sovereign_account_id() -> AccountId { + let location: MultiLocation = (Parent,).into(); + parachain::SovereignAccountOf::convert_location(&location).unwrap() +} + +pub fn parachain_sovereign_account_id(para: u32) -> AccountId { + let location: MultiLocation = (Parachain(para),).into(); + crate::tests::mock_network::relay_chain::SovereignAccountOf::convert_location(&location).unwrap() +} + +pub fn parachain_account_sovereign_account_id( + para: u32, + who: sp_runtime::AccountId32, +) -> AccountId { + let location: MultiLocation = ( + Parachain(para), + AccountId32 { network: Some(relay_chain::RelayNetwork::get()), id: who.into() }, + ) + .into(); + relay_chain::SovereignAccountOf::convert_location(&location).unwrap() +} + +pub fn para_ext(para_id: u32) -> sp_io::TestExternalities { + use crate::tests::mock_network::parachain::{MsgQueue, Runtime, System}; + + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![ + (ALICE, INITIAL_BALANCE), + (relay_sovereign_account_id(), INITIAL_BALANCE), + (BOB, INITIAL_BALANCE), + ], + } + .assimilate_storage(&mut t) + .unwrap(); + + pallet_assets::GenesisConfig:: { + assets: vec![ + (0u128, ADMIN, false, 1u128), // Create derivative asset for relay's native token + ], + metadata: Default::default(), + accounts: vec![ + (0u128, ALICE, INITIAL_BALANCE), + (0u128, relay_sovereign_account_id(), 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, System}; + + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![ + (ALICE, INITIAL_BALANCE), + (parachain_sovereign_account_id(1), INITIAL_BALANCE), + (parachain_account_sovereign_account_id(1, ALICE), 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; +pub type RelaychainBalances = pallet_balances::Pallet; +pub type ParachainBalances = pallet_balances::Pallet; +pub type ParachainAssets = pallet_assets::Pallet; diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs new file mode 100644 index 000000000000..4f6a822371bf --- /dev/null +++ b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs @@ -0,0 +1,87 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +use super::{Balances, Runtime, RuntimeCall, RuntimeEvent}; +use crate::{ + tests::mock_network::{ + parachain::RuntimeHoldReason, + primitives::{Balance, CENTS}, }, + Config, +}; +use frame_support::{ + parameter_types, + traits::{ConstBool, ConstU32, Everything, Randomness}, + weights::Weight, +}; +use frame_system::pallet_prelude::BlockNumberFor; +use pallet_xcm::BalanceOf; +use sp_runtime::{traits::Convert, Perbill}; + +pub const fn deposit(items: u32, bytes: u32) -> Balance { + items as Balance * 1 * CENTS + (bytes as Balance) * 1 * CENTS +} + +parameter_types! { + pub const DepositPerItem: Balance = deposit(1, 0); + pub const DepositPerByte: Balance = deposit(0, 1); + pub const DefaultDepositLimit: Balance = deposit(1024, 1024 * 1024); + pub Schedule: crate::Schedule = Default::default(); + pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0); + pub const MaxDelegateDependencies: u32 = 32; +} + +pub struct DummyRandomness(sp_std::marker::PhantomData); + +impl Randomness> for DummyRandomness { + fn random(_subject: &[u8]) -> (T::Hash, BlockNumberFor) { + (Default::default(), Default::default()) + } +} + +impl Convert> for Runtime { + fn convert(w: Weight) -> BalanceOf { + w.ref_time().into() + } +} + +impl Config for Runtime { + type AddressGenerator = crate::DefaultAddressGenerator; + type CallFilter = Everything; + type CallStack = [crate::Frame; 5]; + type ChainExtension = (); + type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; + type Currency = Balances; + type DefaultDepositLimit = DefaultDepositLimit; + type DepositPerByte = DepositPerByte; + type DepositPerItem = DepositPerItem; + type MaxCodeLen = ConstU32<{ 123 * 1024 }>; + type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>; + type MaxDelegateDependencies = MaxDelegateDependencies; + type MaxStorageKeyLen = ConstU32<128>; + type Migrations = (); + type Randomness = DummyRandomness; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeHoldReason = RuntimeHoldReason; + type Schedule = Schedule; + type Time = super::Timestamp; + type UnsafeUnstableInterface = ConstBool; + type WeightInfo = (); + type WeightPrice = Self; + type Debug = (); + type Environment = (); + type Xcm = crate::xcm::NoopXcmConfig; +} diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/mod.rs b/substrate/frame/contracts/src/tests/mock_network/parachain/mod.rs new file mode 100644 index 000000000000..4e8cabac72fc --- /dev/null +++ b/substrate/frame/contracts/src/tests/mock_network/parachain/mod.rs @@ -0,0 +1,383 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! Parachain runtime mock. + +mod contracts_config; +use crate::tests::mock_network::{ + primitives::{AccountId, AssetIdForAssets, Balance}, + mocks::msg_queue::pallet as mock_msg_queue, + xcm_utils::{AllowNoteUnlockables, ForeignChainAliasAccount}, +}; +use core::marker::PhantomData; +use frame_support::{ + construct_runtime, parameter_types, + traits::{AsEnsureOriginWithArg, Contains, ContainsPair, Everything, EverythingBut, Nothing}, + weights::{ + constants::{WEIGHT_PROOF_SIZE_PER_MB, WEIGHT_REF_TIME_PER_SECOND}, + Weight, + }, +}; +use frame_system::{EnsureRoot, EnsureSigned}; +use pallet_xcm::XcmPassthrough; +use polkadot_parachain::primitives::Sibling; +use sp_core::{ConstU128, ConstU32, ConstU64, H256}; +use sp_runtime::traits::{Get, IdentityLookup, MaybeEquivalence}; + +use sp_std::prelude::*; +use xcm::latest::prelude::*; +use xcm_builder::{ + AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, + AsPrefixedGeneralIndex, ConvertedConcreteId, CurrencyAdapter as XcmCurrencyAdapter, + EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, FungiblesAdapter, IsConcrete, + NativeAsset, NoChecking, NonFungiblesAdapter, ParentAsSuperuser, ParentIsPreset, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, WithComputedOrigin, +}; +use xcm_executor::{traits::JustTry, Config, XcmExecutor}; + +pub type SovereignAccountOf = ( + ForeignChainAliasAccount, + SiblingParachainConvertsVia, + AccountId32Aliases, + ParentIsPreset, +); + +parameter_types! { + pub const BlockHashCount: u64 = 250; +} + +impl frame_system::Config for Runtime { + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Nonce = u64; + type Block = Block; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + 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 AccountStore = System; + type Balance = Balance; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type FreezeIdentifier = (); + type MaxFreezes = ConstU32<0>; + type MaxHolds = ConstU32<1>; + type MaxLocks = MaxLocks; + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type RuntimeEvent = RuntimeEvent; + type RuntimeHoldReason = RuntimeHoldReason; + type WeightInfo = (); +} + +parameter_types! { + pub const AssetDeposit: u128 = 1_000_000; + pub const MetadataDepositBase: u128 = 1_000_000; + pub const MetadataDepositPerByte: u128 = 100_000; + pub const AssetAccountDeposit: u128 = 1_000_000; + pub const ApprovalDeposit: u128 = 1_000_000; + pub const AssetsStringLimit: u32 = 50; + pub const RemoveItemsLimit: u32 = 50; +} + +impl pallet_assets::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type AssetId = AssetIdForAssets; + type Currency = Balances; + type CreateOrigin = AsEnsureOriginWithArg>; + type ForceOrigin = EnsureRoot; + type AssetDeposit = AssetDeposit; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type AssetAccountDeposit = AssetAccountDeposit; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = AssetsStringLimit; + type Freezer = (); + type Extra = (); + type WeightInfo = (); + type RemoveItemsLimit = RemoveItemsLimit; + type AssetIdParameter = AssetIdForAssets; + type CallbackHandle = (); +} + +impl pallet_uniques::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type CollectionId = u32; + type ItemId = u32; + type Currency = Balances; + type CreateOrigin = AsEnsureOriginWithArg>; + type ForceOrigin = EnsureRoot; + type CollectionDeposit = ConstU128<1_000>; + type ItemDeposit = ConstU128<1_000>; + type MetadataDepositBase = ConstU128<1_000>; + type AttributeDepositBase = ConstU128<1_000>; + type DepositPerByte = ConstU128<1>; + type StringLimit = ConstU32<64>; + type KeyLimit = ConstU32<64>; + type ValueLimit = ConstU32<128>; + type Locker = (); + type WeightInfo = (); + #[cfg(feature = "runtime-benchmarks")] + type Helper = (); +} + +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 TokenLocation: MultiLocation = Here.into_location(); + pub const RelayNetwork: NetworkId = ByGenesis([0; 32]); + pub UniversalLocation: InteriorMultiLocation = Parachain(MsgQueue::parachain_id().into()).into(); +} + +pub type XcmOriginToCallOrigin = ( + SovereignSignedViaLocation, + ParentAsSuperuser, + SignedAccountId32AsNative, + XcmPassthrough, +); + +parameter_types! { + pub const XcmInstructionWeight: Weight = Weight::from_parts(1_000, 1_000); + pub TokensPerSecondPerMegabyte: (AssetId, u128, u128) = (Concrete(Parent.into()), 1_000_000_000_000, 1024 * 1024); + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; + pub ForeignPrefix: MultiLocation = (Parent,).into(); + pub CheckingAccount: AccountId = PolkadotXcm::check_account(); + pub TrustedLockPairs: (MultiLocation, MultiAssetFilter) = + (Parent.into(), Wild(AllOf { id: Concrete(Parent.into()), fun: WildFungible })); +} + +pub fn estimate_message_fee(number_of_instructions: u64) -> u128 { + let weight = estimate_weight(number_of_instructions); + + estimate_fee_for_weight(weight) +} + +pub fn estimate_weight(number_of_instructions: u64) -> Weight { + XcmInstructionWeight::get().saturating_mul(number_of_instructions) +} + +pub fn estimate_fee_for_weight(weight: Weight) -> u128 { + let (_, units_per_second, units_per_mb) = TokensPerSecondPerMegabyte::get(); + + units_per_second * (weight.ref_time() as u128) / (WEIGHT_REF_TIME_PER_SECOND as u128) + + units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128) +} + +pub type LocalBalancesTransactor = + XcmCurrencyAdapter, SovereignAccountOf, AccountId, ()>; + +pub struct FromMultiLocationToAsset(PhantomData<(MultiLocation, AssetId)>); +impl MaybeEquivalence + for FromMultiLocationToAsset +{ + fn convert(value: &MultiLocation) -> Option { + match *value { + MultiLocation { parents: 1, interior: Here } => Some(0 as AssetIdForAssets), + MultiLocation { parents: 1, interior: X1(Parachain(para_id)) } => + Some(para_id as AssetIdForAssets), + _ => None, + } + } + + fn convert_back(_id: &AssetIdForAssets) -> Option { + None + } +} + +pub type ForeignAssetsTransactor = FungiblesAdapter< + Assets, + ConvertedConcreteId< + AssetIdForAssets, + Balance, + FromMultiLocationToAsset, + JustTry, + >, + SovereignAccountOf, + AccountId, + NoChecking, + CheckingAccount, +>; + +pub type ForeignUniquesTransactor = NonFungiblesAdapter< + ForeignUniques, + ConvertedConcreteId, JustTry>, + SovereignAccountOf, + AccountId, + NoChecking, + (), +>; + +/// Means for transacting assets on this chain +pub type AssetTransactors = + (LocalBalancesTransactor, ForeignAssetsTransactor, ForeignUniquesTransactor); + +pub struct ParentRelay; +impl Contains for ParentRelay { + fn contains(location: &MultiLocation) -> bool { + location.contains_parents_only(1) + } +} + +pub type XcmRouter = crate::tests::mock_network::ParachainXcmRouter; + +pub type Barrier = WithComputedOrigin< + ( + AllowNoteUnlockables, + AllowExplicitUnpaidExecutionFrom, + AllowTopLevelPaidExecutionFrom, + ), + UniversalLocation, + ConstU32<1>, +>; + +parameter_types! { + pub NftCollectionOne: MultiAssetFilter + = Wild(AllOf { fun: WildNonFungible, id: Concrete((Parent, GeneralIndex(1)).into()) }); + pub NftCollectionOneForRelay: (MultiAssetFilter, MultiLocation) + = (NftCollectionOne::get(), Parent.into()); + pub RelayNativeAsset: MultiAssetFilter = Wild(AllOf { fun: WildFungible, id: Concrete((Parent, Here).into()) }); + pub RelayNativeAssetForRelay: (MultiAssetFilter, MultiLocation) = (RelayNativeAsset::get(), Parent.into()); +} +pub type TrustedTeleporters = + (xcm_builder::Case, xcm_builder::Case); +pub type TrustedReserves = EverythingBut>; + +pub struct XcmConfig; +impl Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = AssetTransactors; + type OriginConverter = XcmOriginToCallOrigin; + type IsReserve = (NativeAsset, TrustedReserves); + type IsTeleporter = TrustedTeleporters; + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + type Trader = FixedRateOfFungible; + type ResponseHandler = PolkadotXcm; + type AssetTrap = PolkadotXcm; + type AssetLocker = PolkadotXcm; + type AssetExchanger = (); + type AssetClaims = PolkadotXcm; + type SubscriptionService = PolkadotXcm; + type PalletInstancesInfo = AllPalletsWithSystem; + type FeeManager = (); + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = RuntimeCall; + type SafeCallFilter = Everything; + type Aliasers = Nothing; +} + +impl mock_msg_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type XcmExecutor = XcmExecutor; +} + +pub type LocalOriginToLocation = SignedToAccountId32; + +pub struct TrustedLockerCase(PhantomData); +impl> ContainsPair + for TrustedLockerCase +{ + fn contains(origin: &MultiLocation, asset: &MultiAsset) -> bool { + let (o, a) = T::get(); + a.matches(asset) && &o == origin + } +} + +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 = IsConcrete; + type TrustedLockers = TrustedLockerCase; + type SovereignAccountOf = SovereignAccountOf; + 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 Block = frame_system::mocking::MockBlock; + +impl pallet_timestamp::Config for Runtime { + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = ConstU64<1>; + type WeightInfo = (); +} + +construct_runtime!( + pub enum Runtime + { + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, + MsgQueue: mock_msg_queue::{Pallet, Storage, Event}, + PolkadotXcm: pallet_xcm::{Pallet, Call, Event, Origin}, + Contracts: crate::{Pallet, Call, Storage, Event, HoldReason}, + Assets: pallet_assets, + ForeignUniques: pallet_uniques, + } +); diff --git a/substrate/frame/contracts/src/tests/mock_network/primitives.rs b/substrate/frame/contracts/src/tests/mock_network/primitives.rs new file mode 100644 index 000000000000..efc42772f88a --- /dev/null +++ b/substrate/frame/contracts/src/tests/mock_network/primitives.rs @@ -0,0 +1,23 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +pub type Balance = u128; + +pub const UNITS: Balance = 10_000_000_000; +pub const CENTS: Balance = UNITS / 100; // 100_000_000 + +pub type AccountId = sp_runtime::AccountId32; +pub type AssetIdForAssets = u128; diff --git a/substrate/frame/contracts/src/tests/mock_network/relay_chain/mod.rs b/substrate/frame/contracts/src/tests/mock_network/relay_chain/mod.rs new file mode 100644 index 000000000000..510665d4cc74 --- /dev/null +++ b/substrate/frame/contracts/src/tests/mock_network/relay_chain/mod.rs @@ -0,0 +1,303 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! Relay chain runtime mock. + +use frame_support::{ + construct_runtime, parameter_types, + traits::{AsEnsureOriginWithArg, Contains, Everything, Nothing}, + weights::{ + constants::{WEIGHT_PROOF_SIZE_PER_MB, WEIGHT_REF_TIME_PER_SECOND}, + Weight, + }, +}; + +use frame_system::EnsureRoot; +use sp_core::{ConstU128, ConstU32, H256}; +use sp_runtime::traits::IdentityLookup; + +use polkadot_parachain::primitives::Id as ParaId; +use polkadot_runtime_parachains::{configuration, origin, shared}; +use xcm::latest::prelude::*; +use xcm_builder::{ + AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, AsPrefixedGeneralIndex, ChildParachainAsNative, + ChildParachainConvertsVia, ChildSystemParachainAsSuperuser, ConvertedConcreteId, + CurrencyAdapter as XcmCurrencyAdapter, FixedRateOfFungible, FixedWeightBounds, IsConcrete, + NoChecking, NonFungiblesAdapter, SiblingParachainConvertsVia, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, +}; +use xcm_executor::{traits::JustTry, Config, XcmExecutor}; + +use super::{ + mocks::relay_message_queue::*, + primitives::{AccountId, Balance}, + xcm_utils::{AllowNoteUnlockables, AllowUnlocks, ForeignChainAliasAccount}, +}; + +parameter_types! { + pub const BlockHashCount: u64 = 250; +} + +impl frame_system::Config for Runtime { + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Block = Block; + type Nonce = u64; + // 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>; + type RuntimeHoldReason = (); +} + +impl pallet_uniques::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type CollectionId = u32; + type ItemId = u32; + type Currency = Balances; + type CreateOrigin = AsEnsureOriginWithArg>; + type ForceOrigin = EnsureRoot; + type CollectionDeposit = ConstU128<1_000>; + type ItemDeposit = ConstU128<1_000>; + type MetadataDepositBase = ConstU128<1_000>; + type AttributeDepositBase = ConstU128<1_000>; + type DepositPerByte = ConstU128<1>; + type StringLimit = ConstU32<64>; + type KeyLimit = ConstU32<64>; + type ValueLimit = ConstU32<128>; + type Locker = (); + type WeightInfo = (); + #[cfg(feature = "runtime-benchmarks")] + type Helper = (); +} + +impl shared::Config for Runtime {} + +impl configuration::Config for Runtime { + type WeightInfo = configuration::TestWeightInfo; +} + +parameter_types! { + pub RelayNetwork: NetworkId = ByGenesis([0; 32]); + pub const TokenLocation: MultiLocation = Here.into_location(); + pub UniversalLocation: InteriorMultiLocation = Here; + pub UnitWeightCost: u64 = 1_000; +} + +pub type SovereignAccountOf = ( + ForeignChainAliasAccount, + AccountId32Aliases, + ChildParachainConvertsVia, + SiblingParachainConvertsVia, +); + +pub type LocalBalancesTransactor = + XcmCurrencyAdapter, SovereignAccountOf, AccountId, ()>; + +pub type LocalUniquesTransactor = NonFungiblesAdapter< + Uniques, + ConvertedConcreteId, JustTry>, + SovereignAccountOf, + AccountId, + NoChecking, + (), +>; + +pub type AssetTransactors = (LocalBalancesTransactor, LocalUniquesTransactor); + +type LocalOriginConverter = ( + SovereignSignedViaLocation, + ChildParachainAsNative, + SignedAccountId32AsNative, + ChildSystemParachainAsSuperuser, +); + +parameter_types! { + pub const XcmInstructionWeight: Weight = Weight::from_parts(1_000, 1_000); + pub TokensPerSecondPerMegabyte: (AssetId, u128, u128) = + (Concrete(TokenLocation::get()), 1_000_000_000_000, 1024 * 1024); + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; +} + +pub fn estimate_message_fee(number_of_instructions: u64) -> u128 { + let weight = estimate_message_weight(number_of_instructions); + + estimate_fee_for_weight(weight) +} + +pub fn estimate_message_weight(number_of_instructions: u64) -> Weight { + XcmInstructionWeight::get().saturating_mul(number_of_instructions) +} + +pub fn estimate_fee_for_weight(weight: Weight) -> u128 { + let (_, units_per_second, units_per_mb) = TokensPerSecondPerMegabyte::get(); + + units_per_second * (weight.ref_time() as u128) / (WEIGHT_REF_TIME_PER_SECOND as u128) + + units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128) +} + +pub struct ChildrenParachains; +impl Contains for ChildrenParachains { + fn contains(location: &MultiLocation) -> bool { + matches!(location, MultiLocation { parents: 0, interior: X1(Parachain(_)) }) + } +} + +pub type XcmRouter = crate::tests::mock_network::RelayChainXcmRouter; +pub type Barrier = WithComputedOrigin< + ( + AllowNoteUnlockables, + AllowUnlocks, + AllowExplicitUnpaidExecutionFrom, + AllowTopLevelPaidExecutionFrom, + AllowSubscriptionsFrom, + ), + UniversalLocation, + ConstU32<1>, +>; + +pub struct XcmConfig; +impl Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = AssetTransactors; + type OriginConverter = LocalOriginConverter; + type IsReserve = (); + type IsTeleporter = (); + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + type Trader = FixedRateOfFungible; + type ResponseHandler = XcmPallet; + type AssetTrap = XcmPallet; + type AssetLocker = XcmPallet; + type AssetExchanger = (); + type AssetClaims = XcmPallet; + type SubscriptionService = XcmPallet; + type PalletInstancesInfo = AllPalletsWithSystem; + type FeeManager = (); + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = RuntimeCall; + type SafeCallFilter = Everything; + type Aliasers = Nothing; +} + +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 = Everything; + 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 = SovereignAccountOf; + 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; +} + +impl origin::Config for Runtime {} + +type Block = frame_system::mocking::MockBlock; + +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 = (); + type QueuePausedQuery = (); +} + +construct_runtime!( + pub enum Runtime { + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + Uniques: pallet_uniques, + ParasOrigin: origin::{Pallet, Origin}, + XcmPallet: pallet_xcm::{Pallet, Call, Storage, Event, Origin}, + MessageQueue: pallet_message_queue::{Pallet, Event}, + } +); diff --git a/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs b/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs new file mode 100644 index 000000000000..96319f9a4a7a --- /dev/null +++ b/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs @@ -0,0 +1,106 @@ +// Copyright Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +use codec::Encode; +use core::{borrow::Borrow, marker::PhantomData}; +use frame_support::{ensure, pallet_prelude::Weight, traits::ProcessMessageError}; +use sp_core::blake2_256; +use xcm::prelude::*; +use xcm_executor::traits::Properties; +use xcm_executor::traits::{ConvertLocation, ShouldExecute}; + +// TODO: Is this vulnerable to DoS? It's how the instructions work +pub struct AllowNoteUnlockables; +impl ShouldExecute for AllowNoteUnlockables { + fn should_execute( + _origin: &MultiLocation, + instructions: &mut [Instruction], + _max_weight: Weight, + _properties: &mut Properties, + ) -> Result<(), ProcessMessageError> { + ensure!(instructions.len() == 1, ProcessMessageError::BadFormat); + match instructions.first() { + Some(NoteUnlockable { .. }) => Ok(()), + _ => Err(ProcessMessageError::BadFormat), + } + } +} + +pub struct AllowUnlocks; +impl ShouldExecute for AllowUnlocks { + fn should_execute( + _origin: &MultiLocation, + instructions: &mut [Instruction], + _max_weight: Weight, + _properties: &mut Properties, + ) -> Result<(), ProcessMessageError> { + ensure!(instructions.len() == 1, ProcessMessageError::BadFormat); + match instructions.first() { + Some(UnlockAsset { .. }) => Ok(()), + _ => Err(ProcessMessageError::BadFormat), + } + } +} + +/// Prefix for generating alias account for accounts coming +/// from chains that use 32 byte long representations. +pub const FOREIGN_CHAIN_PREFIX_PARA_32: [u8; 37] = *b"ForeignChainAliasAccountPrefix_Para32"; + +/// Prefix for generating alias account for accounts coming +/// from the relay chain using 32 byte long representations. +pub const FOREIGN_CHAIN_PREFIX_RELAY: [u8; 36] = *b"ForeignChainAliasAccountPrefix_Relay"; + +pub struct ForeignChainAliasAccount(PhantomData); +impl + Clone> ConvertLocation + for ForeignChainAliasAccount +{ + fn convert_location(location: &MultiLocation) -> Option { + let entropy = match location.borrow() { + // Used on the relay chain for sending paras that use 32 byte accounts + MultiLocation { + parents: 0, + interior: X2(Parachain(para_id), AccountId32 { id, .. }), + } => ForeignChainAliasAccount::::from_para_32(para_id, id, 0), + + // Used on para-chain for sending paras that use 32 byte accounts + MultiLocation { + parents: 1, + interior: X2(Parachain(para_id), AccountId32 { id, .. }), + } => ForeignChainAliasAccount::::from_para_32(para_id, id, 1), + + // Used on para-chain for sending from the relay chain + MultiLocation { + parents: 1, + interior: X1(AccountId32 { id, .. }), + } => ForeignChainAliasAccount::::from_relay_32(id, 1), + + // No other conversions provided + _ => return None, + }; + + Some(entropy.into()) + } +} + +impl ForeignChainAliasAccount { + fn from_para_32(para_id: &u32, id: &[u8; 32], parents: u8) -> [u8; 32] { + (FOREIGN_CHAIN_PREFIX_PARA_32, para_id, id, parents).using_encoded(blake2_256) + } + + fn from_relay_32(id: &[u8; 32], parents: u8) -> [u8; 32] { + (FOREIGN_CHAIN_PREFIX_RELAY, id, parents).using_encoded(blake2_256) + } +} diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs new file mode 100644 index 000000000000..f6a0891d71ab --- /dev/null +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -0,0 +1,283 @@ +use crate::tests::mock_network::{ + parachain::{self, RuntimeOrigin}, + parachain_account_sovereign_account_id, + primitives::{AccountId, CENTS}, + relay_chain, MockNet, ParaA, ParachainBalances, ParachainPalletXcm, Relay, ALICE, BOB, + INITIAL_BALANCE, +}; +use codec::Decode; +use codec::Encode; +use frame_support::pallet_prelude::Weight; +use frame_support::traits::Currency; +use frame_support::{assert_ok, traits::fungibles::Mutate}; +use frame_system::pallet_prelude::BlockNumberFor; +use pallet_balances::{BalanceLock, Reasons}; +use crate::{CollectEvents, DebugInfo, Determinism}; +use pallet_contracts_primitives::Code; +use xcm::{v3::prelude::*, VersionedResponse, VersionedXcm}; +use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; +use xcm_simulator::TestExt; + +type ParachainContracts = crate::Pallet; + +/// Instantiate the tests contract, and fund it with some balance and assets. +fn instantiate_test_contract() -> AccountId { + let wasm = vec![]; // TODO + + // Instantiate contract. + let contract_addr = ParaA::execute_with(|| { + ParachainContracts::bare_instantiate( + ALICE, + 0, + Weight::MAX, + None, + Code::Upload(wasm), + vec![], + vec![], + DebugInfo::UnsafeDebug, + CollectEvents::Skip, + ) + .result + .unwrap() + .account_id + }); + + // Funds contract account with some balance and assets. + ParaA::execute_with(|| { + parachain::Balances::make_free_balance_be(&contract_addr, INITIAL_BALANCE); + parachain::Assets::mint_into(0u32.into(), &contract_addr, INITIAL_BALANCE).unwrap(); + }); + Relay::execute_with(|| { + let sovereign_account = parachain_account_sovereign_account_id(1u32, contract_addr.clone()); + relay_chain::Balances::make_free_balance_be(&sovereign_account, INITIAL_BALANCE); + }); + + contract_addr +} + +#[test] +fn test_xcm_execute() { + MockNet::reset(); + + let contract_addr = instantiate_test_contract(); + + // Execute XCM instructions through the contract. + ParaA::execute_with(|| { + let amount: u128 = 10 * CENTS; + let fee = parachain::estimate_message_fee(3); + + // The XCM used to transfer funds to Bob. + let message: xcm_simulator::Xcm<()> = Xcm(vec![ + WithdrawAsset(vec![(Here, amount).into(), (Parent, fee).into()].into()), + BuyExecution { + fees: (Parent, fee).into(), + weight_limit: WeightLimit::Unlimited, + }, + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: AccountId32 { + network: None, + id: BOB.clone().into(), + } + .into(), + } + .into(), + }, + ]); + + // Execute the XCM message, through the contract. + assert_ok!( + ParachainContracts::bare_call( + ALICE, + contract_addr.clone(), + 0, + Weight::MAX, + None, + message.encode(), + DebugInfo::UnsafeDebug, + CollectEvents::UnsafeCollect, + Determinism::Enforced, + ) + .result + ); + + // Check if the funds are subtracted from the account of Alice and added to the account of Bob. + let initial = INITIAL_BALANCE; + assert_eq!(parachain::Assets::balance(0, contract_addr), initial - fee); + assert_eq!(ParachainBalances::free_balance(BOB), initial + amount); + }); +} + +#[test] +fn test_xcm_send() { + MockNet::reset(); + let contract_addr = instantiate_test_contract(); + let fee = parachain::estimate_message_fee(4); // Accounts for the `DescendOrigin` instruction added by `send_xcm` + + ParaA::execute_with(|| { + let message: xcm_simulator::Xcm<()> = Xcm(vec![ + WithdrawAsset((Here, fee).into()), + BuyExecution { + fees: (Here, fee).into(), + weight_limit: WeightLimit::Unlimited, + }, + LockAsset { + asset: (Here, 5 * CENTS).into(), + unlocker: (Parachain(1)).into(), + }, + ]); + + assert_ok!( + ParachainContracts::bare_call( + ALICE, + contract_addr.clone(), + 0, + Weight::MAX, + None, + ( + MultiLocation::from(Parent), + message + ) + .encode(), + DebugInfo::UnsafeDebug, + CollectEvents::UnsafeCollect, + Determinism::Enforced, + ) + .result + ); + }); + + Relay::execute_with(|| { + // Check if the funds are locked on the relay chain. + assert_eq!( + relay_chain::Balances::locks(¶chain_account_sovereign_account_id(1, contract_addr)), + vec![BalanceLock { + id: *b"py/xcmlk", + amount: 5 * CENTS, + reasons: Reasons::All + }] + ); + }); +} + +#[test] +fn test_xcm_new_query() { + MockNet::reset(); + let contract_addr = instantiate_test_contract(); + + ParaA::execute_with(|| { + let match_querier = MultiLocation::from(AccountId32 { + network: None, + id: ALICE.into(), + }); + let timeout = 1u32; + + let exec = ParachainContracts::bare_call( + ALICE, + contract_addr.clone(), + 0, + Weight::MAX, + None, + ( + timeout, + match_querier, + ) + .encode(), + DebugInfo::UnsafeDebug, + CollectEvents::UnsafeCollect, + Determinism::Enforced, + ); + + let query_id = Result::, u8>::decode(&mut &exec.result.unwrap().data[..]) + .expect("Failed to decode message") + .expect("Contract execution trapped") + .expect("xcm_new_query failed"); + + let response = ParachainPalletXcm::take_response(query_id); + let expected_response = QueryResponseStatus::Pending { + timeout: timeout as BlockNumberFor, + }; + assert_eq!(response, expected_response); + }); +} + +#[test] +fn test_xcm_take_response() { + MockNet::reset(); + let contract_addr = instantiate_test_contract(); + ParaA::execute_with(|| { + let querier: MultiLocation = ( + Parent, + AccountId32 { + network: None, + id: ALICE.into(), + }, + ) + .into(); + let responder = MultiLocation::from(AccountId32 { + network: Some(NetworkId::ByGenesis([0u8; 32])), + id: ALICE.into(), + }); + let query_id = ParachainPalletXcm::new_query(responder, 1u32.into(), querier.clone()); + + let fee = parachain::estimate_message_fee(4); + let message = Xcm(vec![ + WithdrawAsset(vec![(Parent, fee).into()].into()), + BuyExecution { + fees: (Parent, fee).into(), + weight_limit: WeightLimit::Unlimited, + }, + QueryResponse { + query_id, + response: Response::ExecutionResult(None), + max_weight: Weight::zero(), + querier: Some(querier), + }, + ]); + + let call = |query_id| { + let exec = ParachainContracts::bare_call( + ALICE, + contract_addr.clone(), + 0, + Weight::MAX, + None, + ( + query_id, + ) + .encode(), + DebugInfo::UnsafeDebug, + CollectEvents::UnsafeCollect, + Determinism::Enforced, + ); + + Result::, u8>, u8>::decode( + &mut &exec.result.unwrap().data[..], + ) + .expect("Failed to decode message") + .expect("Contract execution trapped") + }; + + // Query is not yet answered. + assert_eq!(Ok(None), call(query_id)); + + ParachainPalletXcm::execute( + RuntimeOrigin::signed(ALICE), + Box::new(VersionedXcm::V3(message)), + Weight::from_parts(1_000_000_000, 1_000_000_000), + ) + .unwrap(); + + // Query is answered. + assert_eq!( + Ok(Some(VersionedResponse::V3(Response::ExecutionResult(None)))), + call(query_id) + ); + + // Query is not found. (Query was already answered) + assert_eq!(Err(1u8), call(query_id)); + }) +} + From 2049b574d7b67bc2a94379cdc00af0f766059439 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 4 Sep 2023 17:03:23 +0200 Subject: [PATCH 012/115] fixes --- .../frame/contracts/fixtures/xcm_execute.wat | 43 ++ .../frame/contracts/fixtures/xcm_query.wat | 43 ++ .../frame/contracts/fixtures/xcm_send.wat | 44 ++ .../contracts/fixtures/xcm_take_response.wat | 43 ++ substrate/frame/contracts/src/tests.rs | 6 +- .../contracts/src/tests/mock_network/mod.rs | 3 - .../parachain/contracts_config.rs | 4 +- .../src/tests/mock_network/parachain/mod.rs | 2 +- .../src/tests/mock_network/relay_chain/mod.rs | 22 +- .../frame/contracts/src/tests/test_xcm.rs | 447 +++++++++--------- substrate/frame/contracts/src/wasm/runtime.rs | 89 +++- substrate/frame/contracts/src/xcm.rs | 27 +- 12 files changed, 494 insertions(+), 279 deletions(-) create mode 100644 substrate/frame/contracts/fixtures/xcm_execute.wat create mode 100644 substrate/frame/contracts/fixtures/xcm_query.wat create mode 100644 substrate/frame/contracts/fixtures/xcm_send.wat create mode 100644 substrate/frame/contracts/fixtures/xcm_take_response.wat diff --git a/substrate/frame/contracts/fixtures/xcm_execute.wat b/substrate/frame/contracts/fixtures/xcm_execute.wat new file mode 100644 index 000000000000..df4a237b4d54 --- /dev/null +++ b/substrate/frame/contracts/fixtures/xcm_execute.wat @@ -0,0 +1,43 @@ +;; This passes its input to `seal_xcm_execute` and returns the return value to its caller. +(module + (import "seal0" "xcm_execute" (func $xcm_execute (param i32 i32 i32) (result i32))) + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; 0x1000 = 4k in little endian + ;; Size of input buffer + (data (i32.const 0) "\00\10") + + (func (export "call") + ;; Receive the encoded call + (call $seal_input + (i32.const 4) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the length buffer + ) + ;; Input data layout. + ;; [0..4) - size of the call + ;; [4..12) - max_weight (Weight::from_all(1_000_000_000) -> 8 bytes) + ;; [12..) - xcm message + + ;; Just use the call passed as input and store result to memory + (i32.store (i32.const 0) + (call $xcm_execute + (i32.const 4) ;; Pointer to the max_weight + (i32.const 16) ;; Pointer where the xcm msg is stored + (i32.sub ;; Size of the xcm msg + (i32.load (i32.const 0)) + (i32.const 12) + ) + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 0) ;; returned value + (i32.const 4) ;; length of returned value + ) + ) + + (func (export "deploy")) +) + diff --git a/substrate/frame/contracts/fixtures/xcm_query.wat b/substrate/frame/contracts/fixtures/xcm_query.wat new file mode 100644 index 000000000000..de101d7fe16d --- /dev/null +++ b/substrate/frame/contracts/fixtures/xcm_query.wat @@ -0,0 +1,43 @@ +;; This passes its input to `seal_xcm_query` and returns the return value to its caller. +(module + (import "seal0" "xcm_query" (func $xcm_query (param i32 i32 i32) (result i32))) + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; 0x1000 = 4k in little endian + ;; size of input buffer + (data (i32.const 0) "\00\10") + + (func (export "call") + ;; Receive the encoded call + (call $seal_input + (i32.const 4) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the length buffer + ) + ;; Input data layout. + ;; [0..4) - size of the call + ;; [4..12) - timeout + ;; [12..49) - match_querier + ;; [8..10) response + + ;; Just use the call passed as input and store result to memory + (i32.store (i32.const 0) + (call $xcm_query + (i32.const 4) ;; Pointer where the timeout is stored + (i32.const 12) ;; Pointer where the match_querier is stored + (i32.const 49) ;; ... + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 49) ;; returned value + (i32.const 8) ;; length of returned value + ) + ) + + (func (export "deploy")) +) + + + diff --git a/substrate/frame/contracts/fixtures/xcm_send.wat b/substrate/frame/contracts/fixtures/xcm_send.wat new file mode 100644 index 000000000000..701918651d25 --- /dev/null +++ b/substrate/frame/contracts/fixtures/xcm_send.wat @@ -0,0 +1,44 @@ +;; This passes its input to `seal_xcm_send` and returns the return value to its caller. +(module + (import "seal0" "xcm_send" (func $xcm_send (param i32 i32 i32) (result i32))) + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; 0x1000 = 4k in little endian + ;; size of input buffer + (data (i32.const 0) "\00\10") + + (func (export "call") + ;; Receive the encoded call + (call $seal_input + (i32.const 4) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the length buffer + ) + ;; Input data layout. + ;; [0..4) - size of the call + ;; [4..7) - dest + ;; [7..) - xcm message + + ;; Just use the call passed as input and store result to memory + (i32.store (i32.const 0) + (call $xcm_send + (i32.const 4) ;; Pointer where the dest is stored + (i32.const 7) ;; Pointer where the xcm msg is stored + (i32.sub ;; Size of the xcm msg + (i32.load (i32.const 0)) + (i32.const 3) + ) + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 0) ;; returned value + (i32.const 4) ;; length of returned value + ) + ) + + (func (export "deploy")) +) + + diff --git a/substrate/frame/contracts/fixtures/xcm_take_response.wat b/substrate/frame/contracts/fixtures/xcm_take_response.wat new file mode 100644 index 000000000000..3bff75aa7f32 --- /dev/null +++ b/substrate/frame/contracts/fixtures/xcm_take_response.wat @@ -0,0 +1,43 @@ +;; This passes its input to `seal_xcm_take_response` and returns the return value to its caller. +(module + (import "seal0" "xcm_take_response" (func $xcm_take_response (param i32 i32) (result i32))) + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; 0x1000 = 4k in little endian + ;; size of input buffer + (data (i32.const 0) "\00\10") + + (func (export "call") + ;; Receive the encoded call + (call $seal_input + (i32.const 4) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the length buffer + ) + ;; Input data layout. + ;; [0..4) - size of the call + ;; [4..12) - query_id + ;; [12..) - response + + ;; Just use the call passed as input and store result to memory + (i32.store (i32.const 0) + (call $xcm_take_response + (i32.const 4) ;; Pointer where the query_id is stored + (i32.const 12) ;; Pointer where the response is stored + ) + ) + + (call $seal_return + (i32.const 0) ;; flags + (i32.const 12) ;; returned value + (i32.const 112) ;; length of returned value + ) + ) + + (func (export "deploy")) +) + + + + diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index 7e4344a487b1..64041ec800bc 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -16,9 +16,9 @@ // limitations under the License. mod mock_network; -mod test_xcm; mod pallet_dummy; mod test_debug; +mod test_xcm; use self::{ test_debug::TestDebug, @@ -567,7 +567,9 @@ where { let fixture_path = [ // When `CARGO_MANIFEST_DIR` is not set, Rust resolves relative paths from the root folder - std::env::var("CARGO_MANIFEST_DIR").as_deref().unwrap_or("frame/contracts"), + std::env::var("CARGO_MANIFEST_DIR") + .as_deref() + .unwrap_or("substrate/frame/contracts"), "/fixtures/", fixture_name, ".wat", diff --git a/substrate/frame/contracts/src/tests/mock_network/mod.rs b/substrate/frame/contracts/src/tests/mock_network/mod.rs index 0683bed0a502..b9055d1fb178 100644 --- a/substrate/frame/contracts/src/tests/mock_network/mod.rs +++ b/substrate/frame/contracts/src/tests/mock_network/mod.rs @@ -145,8 +145,5 @@ pub fn relay_ext() -> sp_io::TestExternalities { ext } -pub type RelaychainPalletXcm = pallet_xcm::Pallet; pub type ParachainPalletXcm = pallet_xcm::Pallet; -pub type RelaychainBalances = pallet_balances::Pallet; pub type ParachainBalances = pallet_balances::Pallet; -pub type ParachainAssets = pallet_assets::Pallet; diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs index 4f6a822371bf..1ce652475e7f 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs @@ -78,10 +78,10 @@ impl Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type Schedule = Schedule; type Time = super::Timestamp; - type UnsafeUnstableInterface = ConstBool; + type UnsafeUnstableInterface = ConstBool; type WeightInfo = (); type WeightPrice = Self; type Debug = (); type Environment = (); - type Xcm = crate::xcm::NoopXcmConfig; + type Xcm = Self; } diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/mod.rs b/substrate/frame/contracts/src/tests/mock_network/parachain/mod.rs index 4e8cabac72fc..162054585a6b 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain/mod.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain/mod.rs @@ -18,8 +18,8 @@ mod contracts_config; use crate::tests::mock_network::{ - primitives::{AccountId, AssetIdForAssets, Balance}, mocks::msg_queue::pallet as mock_msg_queue, + primitives::{AccountId, AssetIdForAssets, Balance}, xcm_utils::{AllowNoteUnlockables, ForeignChainAliasAccount}, }; use core::marker::PhantomData; diff --git a/substrate/frame/contracts/src/tests/mock_network/relay_chain/mod.rs b/substrate/frame/contracts/src/tests/mock_network/relay_chain/mod.rs index 510665d4cc74..837aab80077b 100644 --- a/substrate/frame/contracts/src/tests/mock_network/relay_chain/mod.rs +++ b/substrate/frame/contracts/src/tests/mock_network/relay_chain/mod.rs @@ -19,10 +19,7 @@ use frame_support::{ construct_runtime, parameter_types, traits::{AsEnsureOriginWithArg, Contains, Everything, Nothing}, - weights::{ - constants::{WEIGHT_PROOF_SIZE_PER_MB, WEIGHT_REF_TIME_PER_SECOND}, - Weight, - }, + weights::Weight, }; use frame_system::EnsureRoot; @@ -174,23 +171,6 @@ parameter_types! { pub const MaxAssetsIntoHolding: u32 = 64; } -pub fn estimate_message_fee(number_of_instructions: u64) -> u128 { - let weight = estimate_message_weight(number_of_instructions); - - estimate_fee_for_weight(weight) -} - -pub fn estimate_message_weight(number_of_instructions: u64) -> Weight { - XcmInstructionWeight::get().saturating_mul(number_of_instructions) -} - -pub fn estimate_fee_for_weight(weight: Weight) -> u128 { - let (_, units_per_second, units_per_mb) = TokensPerSecondPerMegabyte::get(); - - units_per_second * (weight.ref_time() as u128) / (WEIGHT_REF_TIME_PER_SECOND as u128) + - units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128) -} - pub struct ChildrenParachains; impl Contains for ChildrenParachains { fn contains(location: &MultiLocation) -> bool { diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index f6a0891d71ab..e96c93c19894 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -1,283 +1,260 @@ -use crate::tests::mock_network::{ - parachain::{self, RuntimeOrigin}, - parachain_account_sovereign_account_id, - primitives::{AccountId, CENTS}, - relay_chain, MockNet, ParaA, ParachainBalances, ParachainPalletXcm, Relay, ALICE, BOB, - INITIAL_BALANCE, +use crate::{ + tests::{ + compile_module, + mock_network::{ + parachain::{self, Runtime, RuntimeOrigin}, + parachain_account_sovereign_account_id, + primitives::{AccountId, CENTS}, + relay_chain, MockNet, ParaA, ParachainBalances, ParachainPalletXcm, Relay, ALICE, BOB, + INITIAL_BALANCE, + }, + }, + xcm::XCM, + CollectEvents, DebugInfo, Determinism, +}; +use codec::{Decode, Encode}; +use frame_support::{ + assert_ok, + pallet_prelude::Weight, + traits::{fungibles::Mutate, Currency}, }; -use codec::Decode; -use codec::Encode; -use frame_support::pallet_prelude::Weight; -use frame_support::traits::Currency; -use frame_support::{assert_ok, traits::fungibles::Mutate}; use frame_system::pallet_prelude::BlockNumberFor; use pallet_balances::{BalanceLock, Reasons}; -use crate::{CollectEvents, DebugInfo, Determinism}; use pallet_contracts_primitives::Code; -use xcm::{v3::prelude::*, VersionedResponse, VersionedXcm}; +use xcm::{v3::prelude::*, VersionedMultiLocation, VersionedResponse, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; use xcm_simulator::TestExt; type ParachainContracts = crate::Pallet; +type QueryId = <::Xcm as XCM>::QueryId; /// Instantiate the tests contract, and fund it with some balance and assets. -fn instantiate_test_contract() -> AccountId { - let wasm = vec![]; // TODO +fn instantiate_test_contract(name: &str) -> AccountId { + let (wasm, _) = compile_module::(name).unwrap(); - // Instantiate contract. - let contract_addr = ParaA::execute_with(|| { - ParachainContracts::bare_instantiate( - ALICE, - 0, - Weight::MAX, - None, - Code::Upload(wasm), - vec![], - vec![], - DebugInfo::UnsafeDebug, - CollectEvents::Skip, - ) - .result - .unwrap() - .account_id - }); + // Instantiate contract. + let contract_addr = ParaA::execute_with(|| { + ParachainContracts::bare_instantiate( + ALICE, + 0, + Weight::MAX, + None, + Code::Upload(wasm), + vec![], + vec![], + DebugInfo::UnsafeDebug, + CollectEvents::Skip, + ) + .result + .unwrap() + .account_id + }); - // Funds contract account with some balance and assets. - ParaA::execute_with(|| { - parachain::Balances::make_free_balance_be(&contract_addr, INITIAL_BALANCE); - parachain::Assets::mint_into(0u32.into(), &contract_addr, INITIAL_BALANCE).unwrap(); - }); - Relay::execute_with(|| { - let sovereign_account = parachain_account_sovereign_account_id(1u32, contract_addr.clone()); - relay_chain::Balances::make_free_balance_be(&sovereign_account, INITIAL_BALANCE); - }); + // Funds contract account with some balance and assets. + ParaA::execute_with(|| { + parachain::Balances::make_free_balance_be(&contract_addr, INITIAL_BALANCE); + parachain::Assets::mint_into(0u32.into(), &contract_addr, INITIAL_BALANCE).unwrap(); + }); + Relay::execute_with(|| { + let sovereign_account = parachain_account_sovereign_account_id(1u32, contract_addr.clone()); + relay_chain::Balances::make_free_balance_be(&sovereign_account, INITIAL_BALANCE); + }); - contract_addr + contract_addr } #[test] fn test_xcm_execute() { - MockNet::reset(); + MockNet::reset(); + + let contract_addr = instantiate_test_contract("xcm_execute"); - let contract_addr = instantiate_test_contract(); + // Execute XCM instructions through the contract. + ParaA::execute_with(|| { + let amount: u128 = 10 * CENTS; + let fee = parachain::estimate_message_fee(4); - // Execute XCM instructions through the contract. - ParaA::execute_with(|| { - let amount: u128 = 10 * CENTS; - let fee = parachain::estimate_message_fee(3); + // The XCM used to transfer funds to Bob. + let message: xcm_simulator::Xcm<()> = Xcm(vec![ + WithdrawAsset(vec![(Parent, fee).into()].into()), + BuyExecution { fees: (Parent, fee).into(), weight_limit: WeightLimit::Unlimited }, + WithdrawAsset(vec![(Here, amount).into()].into()), + DepositAsset { + assets: All.into(), + beneficiary: AccountId32 { network: None, id: BOB.clone().into() }.into(), + }, + ]); + let message = VersionedXcm::V3(message); - // The XCM used to transfer funds to Bob. - let message: xcm_simulator::Xcm<()> = Xcm(vec![ - WithdrawAsset(vec![(Here, amount).into(), (Parent, fee).into()].into()), - BuyExecution { - fees: (Parent, fee).into(), - weight_limit: WeightLimit::Unlimited, - }, - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: AccountId32 { - network: None, - id: BOB.clone().into(), - } - .into(), - } - .into(), - }, - ]); + // Execute the XCM message, through the contract. + let max_weight = Weight::from_all(10_000_000_000); + let data = (max_weight, message.clone()).encode(); - // Execute the XCM message, through the contract. - assert_ok!( - ParachainContracts::bare_call( - ALICE, - contract_addr.clone(), - 0, - Weight::MAX, - None, - message.encode(), - DebugInfo::UnsafeDebug, - CollectEvents::UnsafeCollect, - Determinism::Enforced, - ) - .result - ); + assert_ok!( + ParachainContracts::bare_call( + ALICE, + contract_addr.clone(), + 0, + Weight::MAX, + None, + data, + DebugInfo::UnsafeDebug, + CollectEvents::UnsafeCollect, + Determinism::Enforced, + ) + .result + ); - // Check if the funds are subtracted from the account of Alice and added to the account of Bob. - let initial = INITIAL_BALANCE; - assert_eq!(parachain::Assets::balance(0, contract_addr), initial - fee); - assert_eq!(ParachainBalances::free_balance(BOB), initial + amount); - }); + // Check if the funds are subtracted from the account of Alice and added to the account of + // Bob. + let initial = INITIAL_BALANCE; + assert_eq!(parachain::Assets::balance(0, contract_addr), initial - fee); + assert_eq!(ParachainBalances::free_balance(BOB), initial + amount); + }); } #[test] fn test_xcm_send() { - MockNet::reset(); - let contract_addr = instantiate_test_contract(); - let fee = parachain::estimate_message_fee(4); // Accounts for the `DescendOrigin` instruction added by `send_xcm` + MockNet::reset(); + let contract_addr = instantiate_test_contract("xcm_send"); + let fee = parachain::estimate_message_fee(4); // Accounts for the `DescendOrigin` instruction added by `send_xcm` + + ParaA::execute_with(|| { + let dest = MultiLocation::from(Parent); + let dest = VersionedMultiLocation::V3(dest); - ParaA::execute_with(|| { - let message: xcm_simulator::Xcm<()> = Xcm(vec![ - WithdrawAsset((Here, fee).into()), - BuyExecution { - fees: (Here, fee).into(), - weight_limit: WeightLimit::Unlimited, - }, - LockAsset { - asset: (Here, 5 * CENTS).into(), - unlocker: (Parachain(1)).into(), - }, - ]); + let message: xcm_simulator::Xcm<()> = Xcm(vec![ + WithdrawAsset((Here, fee).into()), + BuyExecution { fees: (Here, fee).into(), weight_limit: WeightLimit::Unlimited }, + LockAsset { asset: (Here, 5 * CENTS).into(), unlocker: (Parachain(1)).into() }, + ]); + let message = VersionedXcm::V3(message); - assert_ok!( - ParachainContracts::bare_call( - ALICE, - contract_addr.clone(), - 0, - Weight::MAX, - None, - ( - MultiLocation::from(Parent), - message - ) - .encode(), - DebugInfo::UnsafeDebug, - CollectEvents::UnsafeCollect, - Determinism::Enforced, - ) - .result - ); - }); + println!("msg: \n{:?}", message.clone().encode()); - Relay::execute_with(|| { - // Check if the funds are locked on the relay chain. - assert_eq!( - relay_chain::Balances::locks(¶chain_account_sovereign_account_id(1, contract_addr)), - vec![BalanceLock { - id: *b"py/xcmlk", - amount: 5 * CENTS, - reasons: Reasons::All - }] - ); - }); + assert_ok!( + ParachainContracts::bare_call( + ALICE, + contract_addr.clone(), + 0, + Weight::MAX, + None, + (dest, message).encode(), + DebugInfo::UnsafeDebug, + CollectEvents::UnsafeCollect, + Determinism::Enforced, + ) + .result + ); + }); + + Relay::execute_with(|| { + // Check if the funds are locked on the relay chain. + assert_eq!( + relay_chain::Balances::locks(¶chain_account_sovereign_account_id(1, contract_addr)), + vec![BalanceLock { id: *b"py/xcmlk", amount: 5 * CENTS, reasons: Reasons::All }] + ); + }); } #[test] -fn test_xcm_new_query() { - MockNet::reset(); - let contract_addr = instantiate_test_contract(); +fn test_xcm_query() { + MockNet::reset(); + let contract_addr = instantiate_test_contract("xcm_query"); - ParaA::execute_with(|| { - let match_querier = MultiLocation::from(AccountId32 { - network: None, - id: ALICE.into(), - }); - let timeout = 1u32; + ParaA::execute_with(|| { + let match_querier = MultiLocation::from(AccountId32 { network: None, id: ALICE.into() }); + let match_querier = VersionedMultiLocation::V3(match_querier); + let timeout: BlockNumberFor = 1u32.into(); - let exec = ParachainContracts::bare_call( - ALICE, - contract_addr.clone(), - 0, - Weight::MAX, - None, - ( - timeout, - match_querier, - ) - .encode(), - DebugInfo::UnsafeDebug, - CollectEvents::UnsafeCollect, - Determinism::Enforced, - ); + println!("timeout encoded: {:?}", timeout.encode()); + println!("match_querier encoded len: {:?}", match_querier.clone().encode().len()); + println!("encoded: {:?}", (timeout, match_querier.clone()).encode()); + let exec = ParachainContracts::bare_call( + ALICE, + contract_addr.clone(), + 0, + Weight::MAX, + None, + (timeout, match_querier).encode(), + DebugInfo::UnsafeDebug, + CollectEvents::UnsafeCollect, + Determinism::Enforced, + ); - let query_id = Result::, u8>::decode(&mut &exec.result.unwrap().data[..]) - .expect("Failed to decode message") - .expect("Contract execution trapped") - .expect("xcm_new_query failed"); + let mut data = &exec.result.unwrap().data[..]; - let response = ParachainPalletXcm::take_response(query_id); - let expected_response = QueryResponseStatus::Pending { - timeout: timeout as BlockNumberFor, - }; - assert_eq!(response, expected_response); - }); + let query_id = QueryId::decode(&mut data).expect("Failed to decode message"); + let response = ParachainPalletXcm::take_response(query_id); + let expected_response = QueryResponseStatus::Pending { timeout }; + assert_eq!(response, expected_response); + }); } #[test] fn test_xcm_take_response() { - MockNet::reset(); - let contract_addr = instantiate_test_contract(); - ParaA::execute_with(|| { - let querier: MultiLocation = ( - Parent, - AccountId32 { - network: None, - id: ALICE.into(), - }, - ) - .into(); - let responder = MultiLocation::from(AccountId32 { - network: Some(NetworkId::ByGenesis([0u8; 32])), - id: ALICE.into(), - }); - let query_id = ParachainPalletXcm::new_query(responder, 1u32.into(), querier.clone()); + MockNet::reset(); + let contract_addr = instantiate_test_contract("xcm_take_response"); + ParaA::execute_with(|| { + let querier: MultiLocation = + (Parent, AccountId32 { network: None, id: ALICE.into() }).into(); + let responder = MultiLocation::from(AccountId32 { + network: Some(NetworkId::ByGenesis([0u8; 32])), + id: ALICE.into(), + }); + let query_id = ParachainPalletXcm::new_query(responder, 1u32.into(), querier.clone()); - let fee = parachain::estimate_message_fee(4); - let message = Xcm(vec![ - WithdrawAsset(vec![(Parent, fee).into()].into()), - BuyExecution { - fees: (Parent, fee).into(), - weight_limit: WeightLimit::Unlimited, - }, - QueryResponse { - query_id, - response: Response::ExecutionResult(None), - max_weight: Weight::zero(), - querier: Some(querier), - }, - ]); + let fee = parachain::estimate_message_fee(4); + let message = Xcm(vec![ + WithdrawAsset(vec![(Parent, fee).into()].into()), + BuyExecution { fees: (Parent, fee).into(), weight_limit: WeightLimit::Unlimited }, + QueryResponse { + query_id, + response: Response::ExecutionResult(None), + max_weight: Weight::zero(), + querier: Some(querier), + }, + ]); - let call = |query_id| { - let exec = ParachainContracts::bare_call( - ALICE, - contract_addr.clone(), - 0, - Weight::MAX, - None, - ( - query_id, - ) - .encode(), - DebugInfo::UnsafeDebug, - CollectEvents::UnsafeCollect, - Determinism::Enforced, - ); + let call = |query_id: QueryId| { + let exec = ParachainContracts::bare_call( + ALICE, + contract_addr.clone(), + 0, + Weight::MAX, + None, + query_id.encode(), + DebugInfo::UnsafeDebug, + CollectEvents::UnsafeCollect, + Determinism::Enforced, + ); - Result::, u8>, u8>::decode( - &mut &exec.result.unwrap().data[..], - ) - .expect("Failed to decode message") - .expect("Contract execution trapped") - }; + QueryResponseStatus::>::decode( + &mut &exec.result.unwrap().data[..], + ) + .expect("Failed to decode message") + }; - // Query is not yet answered. - assert_eq!(Ok(None), call(query_id)); + // Query is not yet answered. + assert_eq!(QueryResponseStatus::Pending { timeout: 1u32.into() }, call(query_id)); - ParachainPalletXcm::execute( - RuntimeOrigin::signed(ALICE), - Box::new(VersionedXcm::V3(message)), - Weight::from_parts(1_000_000_000, 1_000_000_000), - ) - .unwrap(); + ParachainPalletXcm::execute( + RuntimeOrigin::signed(ALICE), + Box::new(VersionedXcm::V3(message)), + Weight::from_parts(1_000_000_000, 1_000_000_000), + ) + .unwrap(); - // Query is answered. - assert_eq!( - Ok(Some(VersionedResponse::V3(Response::ExecutionResult(None)))), - call(query_id) - ); + // Query is answered. + assert_eq!( + QueryResponseStatus::Ready { + response: Response::ExecutionResult(None), + at: 1u32.into() + }, + call(query_id) + ); - // Query is not found. (Query was already answered) - assert_eq!(Err(1u8), call(query_id)); - }) + // Query is not found. (Query was already answered) + assert_eq!(QueryResponseStatus::NotFound, call(query_id)); + }) } - diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 72a59e92dafa..1d34c3e305b4 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -116,8 +116,10 @@ pub enum ReturnCode { EcdsaRecoverFailed = 11, /// sr25519 signature verification failed. Sr25519VerifyFailed = 12, - /// The `seal_xcm_execute` was executed but returned an error. - XcmExcuteFailed = 13, + /// The `seal_xcm_query` was executed but returned an error. + XcmQueryFailed = 13, + /// The `seal_xcm_take_response` was executed but returned an error. + XcmTakeResponseFailed = 14, } impl From for ReturnCode { @@ -636,7 +638,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { let mut bound_checked = memory .get(ptr..ptr + D::max_encoded_len() as usize) .ok_or_else(|| Error::::OutOfBounds)?; - let decoded = D::decode_all_with_depth_limit(MAX_DECODE_NESTING, &mut bound_checked) + let decoded = D::decode_with_depth_limit(MAX_DECODE_NESTING, &mut bound_checked) .map_err(|_| DispatchError::from(Error::::DecodingFailed))?; Ok(decoded) } @@ -661,8 +663,10 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { let ptr = ptr as usize; let mut bound_checked = memory.get(ptr..ptr + len as usize).ok_or_else(|| Error::::OutOfBounds)?; + let decoded = D::decode_all_with_depth_limit(MAX_DECODE_NESTING, &mut bound_checked) .map_err(|_| DispatchError::from(Error::::DecodingFailed))?; + Ok(decoded) } @@ -2614,7 +2618,7 @@ pub mod env { /// # Return Value /// /// Returns `ReturnCode::Success` when the dispatchable was successfully executed and - /// returned `Ok`. When the dispatchable was exeuted but returned an error + /// returned `Ok`. When the dispatchable was executed but returned an error /// `ReturnCode::CallRuntimeFailed` is returned. The full error is not /// provided because it is not guaranteed to be stable. /// @@ -2642,24 +2646,40 @@ pub mod env { ctx.call_dispatchable(call.get_dispatch_info(), |ext| ext.call_runtime(call)) } + /// Execute an XCM message locally, using the contract's address as the origin. + /// This is equivalent to dispatching `pallet_xcm::execute` through call_runtime, except that + /// the function is called directly instead of being dispatched. + /// + /// # Parameters + /// + /// - `max_weight_ptr`: the pointer into the linear memory where the maximum weight is placed. + /// - `msg_ptr`: the pointer into the linear memory where the XCM message is placed. + /// - `msg_len`: the length of the XCM message in bytes. + /// + /// # Return Value + /// + /// Returns `ReturnCode::Success` when the XCM message was successfully executed. When the XCM + /// execution fails, `ReturnCode::CallRuntimeFailed` is returned. + #[unstable] fn xcm_execute( ctx: _, memory: _, - call_ptr: u32, - call_len: u32, max_weight_ptr: u32, + msg_ptr: u32, + msg_len: u32, ) -> Result { use crate::xcm::{CallOf, WeightInfo, XCM}; use frame_support::dispatch::DispatchInfo; use xcm::VersionedXcm; - ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; - let message: VersionedXcm> = - ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; + ctx.charge_gas(RuntimeCosts::CopyFromContract(msg_len))?; let max_weight: Weight = ctx.read_sandbox_memory_as(memory, max_weight_ptr)?; - let weight = max_weight.saturating_add(<::Xcm as XCM>::WeightInfo::execute()); + + let message: VersionedXcm> = + ctx.read_sandbox_memory_as_unbounded(memory, msg_ptr, msg_len)?; + let dispatch_info = DispatchInfo { weight, ..Default::default() }; ctx.call_dispatchable(dispatch_info, |ext| { @@ -2667,23 +2687,40 @@ pub mod env { }) } + /// Send an XCM message from the contract to the specified destination. + /// This is equivalent to dispatching `pallet_xcm::send` through call_runtime, except that + /// the function is called directly instead of being dispatched. + /// + /// # Parameters + /// + /// - `dest_ptr`: the pointer into the linear memory where the [`xcm::VersionedMultiLocation`] + /// is placed. + /// - `msg_ptr`: the pointer into the linear memory where the XCM message is placed. + /// - `msg_len`: the length of the XCM message in bytes. + /// + /// # Return Value + /// + /// Returns `ReturnCode::Success` when the XCM message was successfully sent. When the XCM + /// execution fails, `ReturnCode::CallRuntimeFailed` is returned. + #[unstable] fn xcm_send( ctx: _, memory: _, + dest_ptr: u32, call_ptr: u32, call_len: u32, - dest_ptr: u32, ) -> Result { use crate::xcm::{WeightInfo, XCM}; use xcm::{VersionedMultiLocation, VersionedXcm}; ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; let dest: VersionedMultiLocation = ctx.read_sandbox_memory_as(memory, dest_ptr)?; + let message: VersionedXcm<()> = ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; - let weight = <::Xcm as XCM>::WeightInfo::send(); ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; + match <::Xcm as XCM>::send(ctx.ext.address(), dest, message) { Ok(_) => Ok(ReturnCode::Success), Err(e) => { @@ -2696,6 +2733,19 @@ pub mod env { } } + /// Create a new query, using the contract's address as the responder. + /// + /// # Parameters + /// + /// - `timeout_ptr`: the pointer into the linear memory where the timeout is placed. + /// - `match_querier_ptr`: the pointer into the linear memory where the match_querier is placed. + /// - `output_ptr`: the pointer into the linear memory where the query id is placed. + /// + /// # Return Value + /// + /// Returns `ReturnCode::Success` when the query was successfully created. When the query + /// creation fails, `ReturnCode::XcmQueryFailed` is returned. + #[unstable] fn xcm_query( ctx: _, memory: _, @@ -2725,11 +2775,23 @@ pub mod env { ctx.ext.append_debug_buffer("call failed with: "); ctx.ext.append_debug_buffer(e.into()); }; - Ok(ReturnCode::CallRuntimeFailed) + Ok(ReturnCode::XcmQueryFailed) }, } } + /// Take an XCM response for the specified query. + /// + /// # Parameters + /// + /// - `query_id_ptr`: the pointer into the linear memory where the query id is placed. + /// - `output_ptr`: the pointer into the linear memory where the response is placed. + /// - `output_len_ptr`: the pointer into the linear memory where the response length is placed. + /// + /// # Return Value + /// + /// Returns `ReturnCode::Success` when successful, `ReturnCode::TakeResponseFailed` otherwise. + #[unstable] fn xcm_take_response( ctx: _, memory: _, @@ -2977,3 +3039,4 @@ pub mod env { Ok(()) } } + diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 95f87c3d07a6..711701714d62 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -2,6 +2,7 @@ use crate::{AccountIdOf, Config, Error, RawOrigin}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight}; use frame_system::pallet_prelude::BlockNumberFor; +use pallet_xcm::WeightInfo as XcmWeightInfo; use sp_runtime::{DispatchError, DispatchResult}; use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; @@ -11,16 +12,33 @@ pub trait XCM { type QueryId: Encode + Decode + MaxEncodedLen; type WeightInfo: WeightInfo; + /// Execute an XCM message locally. see [`pallet_xcm::execute`] + /// + /// - `origin`: the origin of the call. + /// - `message`: the XCM message to be executed. + /// - `max_weight`: the maximum weight that can be consumed by the execution. fn execute( origin: &AccountIdOf, message: VersionedXcm>, max_weight: Weight, ) -> DispatchResultWithPostInfo; + + /// Send an XCM message to be executed by a remote location. see [`pallet_xcm::send`] + /// + /// - `origin`: the origin of the call. + /// - `dest`: the destination of the message. + /// - `msg`: the XCM message to be sent. fn send( origin: &AccountIdOf, dest: VersionedMultiLocation, msg: VersionedXcm<()>, ) -> DispatchResult; + + /// Query a remote location. see [`QueryHandler::new_query`] + /// + /// - `origin`: the origin of the call, used to determine the responder. + /// - `timeout`: the maximum block number that the query should be responded to. + /// - `match_querier`: the querier that the query should be responded to. fn query( origin: &AccountIdOf, timeout: BlockNumberFor, @@ -29,6 +47,7 @@ pub trait XCM { fn take_response(query_id: Self::QueryId) -> QueryResponseStatus>; } +/// A no-op implementation of [`XCM`]. pub struct NoopXcmConfig; impl XCM for NoopXcmConfig { @@ -60,10 +79,15 @@ impl XCM for NoopXcmConfig { } } +/// Weight info trait for methods exposed by the [`XCM`] trait. pub trait WeightInfo { + /// Weight of the [`XCM::execute`] function. fn execute() -> Weight; + /// Weight of the [`XCM::send`] function. fn send() -> Weight; + /// Weight of the [`XCM::query`] function. fn query() -> Weight; + /// Weight of the [`XCM::take_response`] function. fn take_response() -> Weight; } @@ -82,8 +106,7 @@ impl WeightInfo for NoopXcmConfig { } } -use pallet_xcm::WeightInfo as XcmWeightInfo; - +/// TODO use feature flag to compile this only when xcm is enabled impl WeightInfo for T where T: pallet_xcm::Config, From be04741a5c20c67890947f692ce454774fefd0db Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 4 Sep 2023 17:12:04 +0200 Subject: [PATCH 013/115] fix clippy --- substrate/frame/contracts/build.rs | 2 +- .../frame/contracts/src/tests/mock_network/mocks/msg_queue.rs | 4 ++-- substrate/frame/contracts/src/tests/test_xcm.rs | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/substrate/frame/contracts/build.rs b/substrate/frame/contracts/build.rs index 7817ace9c98e..42bc45d563d3 100644 --- a/substrate/frame/contracts/build.rs +++ b/substrate/frame/contracts/build.rs @@ -53,7 +53,7 @@ fn get_latest_version() -> u16 { fn main() -> Result<(), Box> { let out_dir = std::env::var("OUT_DIR")?; let path = std::path::Path::new(&out_dir).join("migration_codegen.rs"); - let mut f = std::fs::File::create(&path)?; + let mut f = std::fs::File::create(path)?; let version = get_latest_version(); write!( f, diff --git a/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs b/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs index 21d5c67476be..fd169d8b336c 100644 --- a/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs +++ b/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs @@ -102,7 +102,7 @@ pub mod pallet { 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::Error(e) => (Err(e), 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. @@ -129,7 +129,7 @@ pub mod pallet { let _ = XcmpMessageFormat::decode(&mut data_ref) .expect("Simulator encodes with versioned xcm format; qed"); - let mut remaining_fragments = &data_ref[..]; + let mut remaining_fragments = data_ref; while !remaining_fragments.is_empty() { if let Ok(xcm) = VersionedXcm::::decode(&mut remaining_fragments) diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index e96c93c19894..258e1ba4d30d 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -21,7 +21,7 @@ use frame_support::{ use frame_system::pallet_prelude::BlockNumberFor; use pallet_balances::{BalanceLock, Reasons}; use pallet_contracts_primitives::Code; -use xcm::{v3::prelude::*, VersionedMultiLocation, VersionedResponse, VersionedXcm}; +use xcm::{v3::prelude::*, VersionedMultiLocation,VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; use xcm_simulator::TestExt; @@ -202,7 +202,7 @@ fn test_xcm_take_response() { network: Some(NetworkId::ByGenesis([0u8; 32])), id: ALICE.into(), }); - let query_id = ParachainPalletXcm::new_query(responder, 1u32.into(), querier.clone()); + let query_id = ParachainPalletXcm::new_query(responder, 1u32.into(), querier); let fee = parachain::estimate_message_fee(4); let message = Xcm(vec![ From b7875ad18d77f1bfe65bf3169c66e848fafd6d2c Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 4 Sep 2023 17:37:31 +0200 Subject: [PATCH 014/115] quick fixes --- .../{mock_network/mod.rs => mock_network.rs} | 3 +- .../mock_network/{mocks/mod.rs => mocks.rs} | 0 .../src/tests/mock_network/mocks/msg_queue.rs | 277 +++++++++--------- .../{parachain/mod.rs => parachain.rs} | 45 +-- .../parachain/contracts_config.rs | 3 +- .../{relay_chain/mod.rs => relay_chain.rs} | 50 +--- .../src/tests/mock_network/xcm_utils.rs | 107 ++++--- .../frame/contracts/src/tests/test_xcm.rs | 2 +- substrate/frame/contracts/src/wasm/runtime.rs | 1 - 9 files changed, 207 insertions(+), 281 deletions(-) rename substrate/frame/contracts/src/tests/{mock_network/mod.rs => mock_network.rs} (99%) rename substrate/frame/contracts/src/tests/mock_network/{mocks/mod.rs => mocks.rs} (100%) rename substrate/frame/contracts/src/tests/mock_network/{parachain/mod.rs => parachain.rs} (88%) rename substrate/frame/contracts/src/tests/mock_network/{relay_chain/mod.rs => relay_chain.rs} (82%) diff --git a/substrate/frame/contracts/src/tests/mock_network/mod.rs b/substrate/frame/contracts/src/tests/mock_network.rs similarity index 99% rename from substrate/frame/contracts/src/tests/mock_network/mod.rs rename to substrate/frame/contracts/src/tests/mock_network.rs index b9055d1fb178..1254fcc970d9 100644 --- a/substrate/frame/contracts/src/tests/mock_network/mod.rs +++ b/substrate/frame/contracts/src/tests/mock_network.rs @@ -71,7 +71,8 @@ pub fn relay_sovereign_account_id() -> AccountId { pub fn parachain_sovereign_account_id(para: u32) -> AccountId { let location: MultiLocation = (Parachain(para),).into(); - crate::tests::mock_network::relay_chain::SovereignAccountOf::convert_location(&location).unwrap() + crate::tests::mock_network::relay_chain::SovereignAccountOf::convert_location(&location) + .unwrap() } pub fn parachain_account_sovereign_account_id( diff --git a/substrate/frame/contracts/src/tests/mock_network/mocks/mod.rs b/substrate/frame/contracts/src/tests/mock_network/mocks.rs similarity index 100% rename from substrate/frame/contracts/src/tests/mock_network/mocks/mod.rs rename to substrate/frame/contracts/src/tests/mock_network/mocks.rs diff --git a/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs b/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs index fd169d8b336c..d8f291cfd717 100644 --- a/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs +++ b/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs @@ -20,7 +20,7 @@ use codec::{Decode, Encode}; use frame_support::weights::Weight; use polkadot_parachain::primitives::{ - DmpMessageHandler, Id as ParaId, XcmpMessageFormat, XcmpMessageHandler, + DmpMessageHandler, Id as ParaId, XcmpMessageFormat, XcmpMessageHandler, }; use polkadot_primitives::BlockNumber as RelayBlockNumber; use sp_runtime::traits::{Get, Hash}; @@ -30,143 +30,140 @@ use xcm::{latest::prelude::*, VersionedXcm}; #[frame_support::pallet] pub mod pallet { - 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(super) type ParachainId = StorageValue<_, ParaId, ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn received_dmp)] - /// A queue of received DMP messages - pub(super) 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), 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 - } - } + 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(super) type ParachainId = StorageValue<_, ParaId, ValueQuery>; + + #[pallet::storage] + #[pallet::getter(fn received_dmp)] + /// A queue of received DMP messages + pub(super) 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), 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 + } + } } diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/mod.rs b/substrate/frame/contracts/src/tests/mock_network/parachain.rs similarity index 88% rename from substrate/frame/contracts/src/tests/mock_network/parachain/mod.rs rename to substrate/frame/contracts/src/tests/mock_network/parachain.rs index 162054585a6b..f5cc10e215d3 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain/mod.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain.rs @@ -34,18 +34,17 @@ use frame_support::{ use frame_system::{EnsureRoot, EnsureSigned}; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; -use sp_core::{ConstU128, ConstU32, ConstU64, H256}; +use sp_core::{ConstU32, ConstU64, H256}; use sp_runtime::traits::{Get, IdentityLookup, MaybeEquivalence}; use sp_std::prelude::*; use xcm::latest::prelude::*; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, - AsPrefixedGeneralIndex, ConvertedConcreteId, CurrencyAdapter as XcmCurrencyAdapter, - EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, FungiblesAdapter, IsConcrete, - NativeAsset, NoChecking, NonFungiblesAdapter, ParentAsSuperuser, ParentIsPreset, - SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, - SovereignSignedViaLocation, WithComputedOrigin, + ConvertedConcreteId, CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, + FixedRateOfFungible, FixedWeightBounds, FungiblesAdapter, IsConcrete, NativeAsset, NoChecking, + ParentAsSuperuser, ParentIsPreset, SiblingParachainConvertsVia, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, }; use xcm_executor::{traits::JustTry, Config, XcmExecutor}; @@ -139,27 +138,6 @@ impl pallet_assets::Config for Runtime { type CallbackHandle = (); } -impl pallet_uniques::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type CollectionId = u32; - type ItemId = u32; - type Currency = Balances; - type CreateOrigin = AsEnsureOriginWithArg>; - type ForceOrigin = EnsureRoot; - type CollectionDeposit = ConstU128<1_000>; - type ItemDeposit = ConstU128<1_000>; - type MetadataDepositBase = ConstU128<1_000>; - type AttributeDepositBase = ConstU128<1_000>; - type DepositPerByte = ConstU128<1>; - type StringLimit = ConstU32<64>; - type KeyLimit = ConstU32<64>; - type ValueLimit = ConstU32<128>; - type Locker = (); - type WeightInfo = (); - #[cfg(feature = "runtime-benchmarks")] - type Helper = (); -} - 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); @@ -242,18 +220,8 @@ pub type ForeignAssetsTransactor = FungiblesAdapter< CheckingAccount, >; -pub type ForeignUniquesTransactor = NonFungiblesAdapter< - ForeignUniques, - ConvertedConcreteId, JustTry>, - SovereignAccountOf, - AccountId, - NoChecking, - (), ->; - /// Means for transacting assets on this chain -pub type AssetTransactors = - (LocalBalancesTransactor, ForeignAssetsTransactor, ForeignUniquesTransactor); +pub type AssetTransactors = (LocalBalancesTransactor, ForeignAssetsTransactor); pub struct ParentRelay; impl Contains for ParentRelay { @@ -378,6 +346,5 @@ construct_runtime!( PolkadotXcm: pallet_xcm::{Pallet, Call, Event, Origin}, Contracts: crate::{Pallet, Call, Storage, Event, HoldReason}, Assets: pallet_assets, - ForeignUniques: pallet_uniques, } ); diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs index 1ce652475e7f..dda5fb0d42c2 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs @@ -18,7 +18,8 @@ use super::{Balances, Runtime, RuntimeCall, RuntimeEvent}; use crate::{ tests::mock_network::{ parachain::RuntimeHoldReason, - primitives::{Balance, CENTS}, }, + primitives::{Balance, CENTS}, + }, Config, }; use frame_support::{ diff --git a/substrate/frame/contracts/src/tests/mock_network/relay_chain/mod.rs b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs similarity index 82% rename from substrate/frame/contracts/src/tests/mock_network/relay_chain/mod.rs rename to substrate/frame/contracts/src/tests/mock_network/relay_chain.rs index 837aab80077b..711983edf914 100644 --- a/substrate/frame/contracts/src/tests/mock_network/relay_chain/mod.rs +++ b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs @@ -18,12 +18,12 @@ use frame_support::{ construct_runtime, parameter_types, - traits::{AsEnsureOriginWithArg, Contains, Everything, Nothing}, + traits::{Contains, Everything, Nothing}, weights::Weight, }; use frame_system::EnsureRoot; -use sp_core::{ConstU128, ConstU32, H256}; +use sp_core::{ConstU32, H256}; use sp_runtime::traits::IdentityLookup; use polkadot_parachain::primitives::Id as ParaId; @@ -31,13 +31,12 @@ use polkadot_runtime_parachains::{configuration, origin, shared}; use xcm::latest::prelude::*; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, AsPrefixedGeneralIndex, ChildParachainAsNative, - ChildParachainConvertsVia, ChildSystemParachainAsSuperuser, ConvertedConcreteId, - CurrencyAdapter as XcmCurrencyAdapter, FixedRateOfFungible, FixedWeightBounds, IsConcrete, - NoChecking, NonFungiblesAdapter, SiblingParachainConvertsVia, SignedAccountId32AsNative, + AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, ChildParachainConvertsVia, + ChildSystemParachainAsSuperuser, CurrencyAdapter as XcmCurrencyAdapter, FixedRateOfFungible, + FixedWeightBounds, IsConcrete, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, }; -use xcm_executor::{traits::JustTry, Config, XcmExecutor}; +use xcm_executor::{Config, XcmExecutor}; use super::{ mocks::relay_message_queue::*, @@ -54,13 +53,10 @@ impl frame_system::Config for Runtime { type RuntimeCall = RuntimeCall; type Block = Block; type Nonce = u64; - // 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 = (); @@ -94,34 +90,12 @@ impl pallet_balances::Config for Runtime { type WeightInfo = (); type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; - // type HoldIdentifier = (); type FreezeIdentifier = (); type MaxHolds = ConstU32<0>; type MaxFreezes = ConstU32<0>; type RuntimeHoldReason = (); } -impl pallet_uniques::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type CollectionId = u32; - type ItemId = u32; - type Currency = Balances; - type CreateOrigin = AsEnsureOriginWithArg>; - type ForceOrigin = EnsureRoot; - type CollectionDeposit = ConstU128<1_000>; - type ItemDeposit = ConstU128<1_000>; - type MetadataDepositBase = ConstU128<1_000>; - type AttributeDepositBase = ConstU128<1_000>; - type DepositPerByte = ConstU128<1>; - type StringLimit = ConstU32<64>; - type KeyLimit = ConstU32<64>; - type ValueLimit = ConstU32<128>; - type Locker = (); - type WeightInfo = (); - #[cfg(feature = "runtime-benchmarks")] - type Helper = (); -} - impl shared::Config for Runtime {} impl configuration::Config for Runtime { @@ -145,16 +119,7 @@ pub type SovereignAccountOf = ( pub type LocalBalancesTransactor = XcmCurrencyAdapter, SovereignAccountOf, AccountId, ()>; -pub type LocalUniquesTransactor = NonFungiblesAdapter< - Uniques, - ConvertedConcreteId, JustTry>, - SovereignAccountOf, - AccountId, - NoChecking, - (), ->; - -pub type AssetTransactors = (LocalBalancesTransactor, LocalUniquesTransactor); +pub type AssetTransactors = LocalBalancesTransactor; type LocalOriginConverter = ( SovereignSignedViaLocation, @@ -275,7 +240,6 @@ construct_runtime!( pub enum Runtime { System: frame_system::{Pallet, Call, Storage, Config, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Uniques: pallet_uniques, ParasOrigin: origin::{Pallet, Origin}, XcmPallet: pallet_xcm::{Pallet, Call, Storage, Event, Origin}, MessageQueue: pallet_message_queue::{Pallet, Event}, diff --git a/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs b/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs index 96319f9a4a7a..497162f5000a 100644 --- a/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs +++ b/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs @@ -19,40 +19,39 @@ use core::{borrow::Borrow, marker::PhantomData}; use frame_support::{ensure, pallet_prelude::Weight, traits::ProcessMessageError}; use sp_core::blake2_256; use xcm::prelude::*; -use xcm_executor::traits::Properties; -use xcm_executor::traits::{ConvertLocation, ShouldExecute}; +use xcm_executor::traits::{ConvertLocation, Properties, ShouldExecute}; // TODO: Is this vulnerable to DoS? It's how the instructions work pub struct AllowNoteUnlockables; impl ShouldExecute for AllowNoteUnlockables { - fn should_execute( - _origin: &MultiLocation, - instructions: &mut [Instruction], - _max_weight: Weight, - _properties: &mut Properties, - ) -> Result<(), ProcessMessageError> { - ensure!(instructions.len() == 1, ProcessMessageError::BadFormat); - match instructions.first() { - Some(NoteUnlockable { .. }) => Ok(()), - _ => Err(ProcessMessageError::BadFormat), - } - } + fn should_execute( + _origin: &MultiLocation, + instructions: &mut [Instruction], + _max_weight: Weight, + _properties: &mut Properties, + ) -> Result<(), ProcessMessageError> { + ensure!(instructions.len() == 1, ProcessMessageError::BadFormat); + match instructions.first() { + Some(NoteUnlockable { .. }) => Ok(()), + _ => Err(ProcessMessageError::BadFormat), + } + } } pub struct AllowUnlocks; impl ShouldExecute for AllowUnlocks { - fn should_execute( - _origin: &MultiLocation, - instructions: &mut [Instruction], - _max_weight: Weight, - _properties: &mut Properties, - ) -> Result<(), ProcessMessageError> { - ensure!(instructions.len() == 1, ProcessMessageError::BadFormat); - match instructions.first() { - Some(UnlockAsset { .. }) => Ok(()), - _ => Err(ProcessMessageError::BadFormat), - } - } + fn should_execute( + _origin: &MultiLocation, + instructions: &mut [Instruction], + _max_weight: Weight, + _properties: &mut Properties, + ) -> Result<(), ProcessMessageError> { + ensure!(instructions.len() == 1, ProcessMessageError::BadFormat); + match instructions.first() { + Some(UnlockAsset { .. }) => Ok(()), + _ => Err(ProcessMessageError::BadFormat), + } + } } /// Prefix for generating alias account for accounts coming @@ -65,42 +64,40 @@ pub const FOREIGN_CHAIN_PREFIX_RELAY: [u8; 36] = *b"ForeignChainAliasAccountPref pub struct ForeignChainAliasAccount(PhantomData); impl + Clone> ConvertLocation - for ForeignChainAliasAccount + for ForeignChainAliasAccount { - fn convert_location(location: &MultiLocation) -> Option { - let entropy = match location.borrow() { - // Used on the relay chain for sending paras that use 32 byte accounts - MultiLocation { - parents: 0, - interior: X2(Parachain(para_id), AccountId32 { id, .. }), - } => ForeignChainAliasAccount::::from_para_32(para_id, id, 0), + fn convert_location(location: &MultiLocation) -> Option { + let entropy = match location.borrow() { + // Used on the relay chain for sending paras that use 32 byte accounts + MultiLocation { + parents: 0, + interior: X2(Parachain(para_id), AccountId32 { id, .. }), + } => ForeignChainAliasAccount::::from_para_32(para_id, id, 0), - // Used on para-chain for sending paras that use 32 byte accounts - MultiLocation { - parents: 1, - interior: X2(Parachain(para_id), AccountId32 { id, .. }), - } => ForeignChainAliasAccount::::from_para_32(para_id, id, 1), + // Used on para-chain for sending paras that use 32 byte accounts + MultiLocation { + parents: 1, + interior: X2(Parachain(para_id), AccountId32 { id, .. }), + } => ForeignChainAliasAccount::::from_para_32(para_id, id, 1), - // Used on para-chain for sending from the relay chain - MultiLocation { - parents: 1, - interior: X1(AccountId32 { id, .. }), - } => ForeignChainAliasAccount::::from_relay_32(id, 1), + // Used on para-chain for sending from the relay chain + MultiLocation { parents: 1, interior: X1(AccountId32 { id, .. }) } => + ForeignChainAliasAccount::::from_relay_32(id, 1), - // No other conversions provided - _ => return None, - }; + // No other conversions provided + _ => return None, + }; - Some(entropy.into()) - } + Some(entropy.into()) + } } impl ForeignChainAliasAccount { - fn from_para_32(para_id: &u32, id: &[u8; 32], parents: u8) -> [u8; 32] { - (FOREIGN_CHAIN_PREFIX_PARA_32, para_id, id, parents).using_encoded(blake2_256) - } + fn from_para_32(para_id: &u32, id: &[u8; 32], parents: u8) -> [u8; 32] { + (FOREIGN_CHAIN_PREFIX_PARA_32, para_id, id, parents).using_encoded(blake2_256) + } - fn from_relay_32(id: &[u8; 32], parents: u8) -> [u8; 32] { - (FOREIGN_CHAIN_PREFIX_RELAY, id, parents).using_encoded(blake2_256) - } + fn from_relay_32(id: &[u8; 32], parents: u8) -> [u8; 32] { + (FOREIGN_CHAIN_PREFIX_RELAY, id, parents).using_encoded(blake2_256) + } } diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 258e1ba4d30d..823001f571db 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -21,7 +21,7 @@ use frame_support::{ use frame_system::pallet_prelude::BlockNumberFor; use pallet_balances::{BalanceLock, Reasons}; use pallet_contracts_primitives::Code; -use xcm::{v3::prelude::*, VersionedMultiLocation,VersionedXcm}; +use xcm::{v3::prelude::*, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; use xcm_simulator::TestExt; diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 1d34c3e305b4..b14590c0e283 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -3039,4 +3039,3 @@ pub mod env { Ok(()) } } - From c312b9806a424206aa52739f0e559553ecd6ac93 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 4 Sep 2023 17:54:35 +0200 Subject: [PATCH 015/115] simplify --- Cargo.lock | 1 - substrate/frame/contracts/Cargo.toml | 1 - .../src/tests/mock_network/parachain.rs | 3 +- .../src/tests/mock_network/relay_chain.rs | 4 +- .../src/tests/mock_network/xcm_utils.rs | 40 ++----------------- 5 files changed, 5 insertions(+), 44 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 61deb7825c1e..5822259a1670 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9408,7 +9408,6 @@ dependencies = [ "pallet-message-queue", "pallet-proxy", "pallet-timestamp", - "pallet-uniques", "pallet-utility", "pallet-xcm", "parity-scale-codec", diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 599581d56abf..ddc205d99efa 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -73,7 +73,6 @@ pallet-message-queue = { path = "../message-queue" } pallet-insecure-randomness-collective-flip = { path = "../insecure-randomness-collective-flip" } pallet-utility = { path = "../utility" } pallet-assets = { path = "../assets" } -pallet-uniques = { path = "../uniques" } pallet-proxy = { path = "../proxy" } sp-keystore = { path = "../../primitives/keystore" } sp-tracing = { path = "../../primitives/tracing" } diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain.rs b/substrate/frame/contracts/src/tests/mock_network/parachain.rs index f5cc10e215d3..c02af0d0506e 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain.rs @@ -20,7 +20,7 @@ mod contracts_config; use crate::tests::mock_network::{ mocks::msg_queue::pallet as mock_msg_queue, primitives::{AccountId, AssetIdForAssets, Balance}, - xcm_utils::{AllowNoteUnlockables, ForeignChainAliasAccount}, + xcm_utils::{ ForeignChainAliasAccount}, }; use core::marker::PhantomData; use frame_support::{ @@ -234,7 +234,6 @@ pub type XcmRouter = crate::tests::mock_network::ParachainXcmRouter; pub type Barrier = WithComputedOrigin< ( - AllowNoteUnlockables, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, ), diff --git a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs index 711983edf914..0d93e0fd75cf 100644 --- a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs @@ -41,7 +41,7 @@ use xcm_executor::{Config, XcmExecutor}; use super::{ mocks::relay_message_queue::*, primitives::{AccountId, Balance}, - xcm_utils::{AllowNoteUnlockables, AllowUnlocks, ForeignChainAliasAccount}, + xcm_utils::{ ForeignChainAliasAccount}, }; parameter_types! { @@ -146,8 +146,6 @@ impl Contains for ChildrenParachains { pub type XcmRouter = crate::tests::mock_network::RelayChainXcmRouter; pub type Barrier = WithComputedOrigin< ( - AllowNoteUnlockables, - AllowUnlocks, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, AllowSubscriptionsFrom, diff --git a/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs b/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs index 497162f5000a..2e98720ef3b5 100644 --- a/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs +++ b/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs @@ -16,49 +16,15 @@ use codec::Encode; use core::{borrow::Borrow, marker::PhantomData}; -use frame_support::{ensure, pallet_prelude::Weight, traits::ProcessMessageError}; use sp_core::blake2_256; use xcm::prelude::*; -use xcm_executor::traits::{ConvertLocation, Properties, ShouldExecute}; +use xcm_executor::traits::{ConvertLocation }; -// TODO: Is this vulnerable to DoS? It's how the instructions work -pub struct AllowNoteUnlockables; -impl ShouldExecute for AllowNoteUnlockables { - fn should_execute( - _origin: &MultiLocation, - instructions: &mut [Instruction], - _max_weight: Weight, - _properties: &mut Properties, - ) -> Result<(), ProcessMessageError> { - ensure!(instructions.len() == 1, ProcessMessageError::BadFormat); - match instructions.first() { - Some(NoteUnlockable { .. }) => Ok(()), - _ => Err(ProcessMessageError::BadFormat), - } - } -} - -pub struct AllowUnlocks; -impl ShouldExecute for AllowUnlocks { - fn should_execute( - _origin: &MultiLocation, - instructions: &mut [Instruction], - _max_weight: Weight, - _properties: &mut Properties, - ) -> Result<(), ProcessMessageError> { - ensure!(instructions.len() == 1, ProcessMessageError::BadFormat); - match instructions.first() { - Some(UnlockAsset { .. }) => Ok(()), - _ => Err(ProcessMessageError::BadFormat), - } - } -} - -/// Prefix for generating alias account for accounts coming +/// Prefix for generating alias account for accounts coming /// from chains that use 32 byte long representations. pub const FOREIGN_CHAIN_PREFIX_PARA_32: [u8; 37] = *b"ForeignChainAliasAccountPrefix_Para32"; -/// Prefix for generating alias account for accounts coming +/// Prefix for generating alias account for accounts coming /// from the relay chain using 32 byte long representations. pub const FOREIGN_CHAIN_PREFIX_RELAY: [u8; 36] = *b"ForeignChainAliasAccountPrefix_Relay"; From 5983dbd10c37ad510bbd7c840c507eec5b3e652f Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 4 Sep 2023 18:02:48 +0200 Subject: [PATCH 016/115] move stuff to pallet_xcm_extension --- substrate/frame/contracts/src/xcm.rs | 79 ++----------------- .../contracts/src/xcm/pallet_xcm_extension.rs | 76 ++++++++++++++++++ 2 files changed, 82 insertions(+), 73 deletions(-) create mode 100644 substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 711701714d62..e250e83d3c00 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -1,13 +1,15 @@ -use crate::{AccountIdOf, Config, Error, RawOrigin}; +use crate::{AccountIdOf, Config, Error}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight}; use frame_system::pallet_prelude::BlockNumberFor; -use pallet_xcm::WeightInfo as XcmWeightInfo; use sp_runtime::{DispatchError, DispatchResult}; -use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; -use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; +use xcm::{VersionedMultiLocation, VersionedXcm}; +use xcm_executor::traits::{QueryResponseStatus}; pub type CallOf = ::RuntimeCall; +// TODO move behind feature flag +mod pallet_xcm_extension; + pub trait XCM { type QueryId: Encode + Decode + MaxEncodedLen; type WeightInfo: WeightInfo; @@ -106,72 +108,3 @@ impl WeightInfo for NoopXcmConfig { } } -/// TODO use feature flag to compile this only when xcm is enabled -impl WeightInfo for T -where - T: pallet_xcm::Config, -{ - fn execute() -> Weight { - ::WeightInfo::execute() - } - fn send() -> Weight { - ::WeightInfo::send() - } - fn query() -> Weight { - ::WeightInfo::new_query() - } - fn take_response() -> Weight { - ::WeightInfo::take_response() - } -} - -impl XCM for T -where - T: pallet_xcm::Config, -{ - type QueryId = as QueryHandler>::QueryId; - type WeightInfo = T; - - fn execute( - origin: &AccountIdOf, - message: VersionedXcm>, - max_weight: Weight, - ) -> DispatchResultWithPostInfo { - let origin = RawOrigin::Signed(origin.clone()).into(); - pallet_xcm::Pallet::::execute(origin, Box::new(message), max_weight) - } - fn send( - origin: &AccountIdOf, - dest: VersionedMultiLocation, - msg: VersionedXcm<()>, - ) -> DispatchResult { - let origin = RawOrigin::Signed(origin.clone()).into(); - pallet_xcm::Pallet::::send(origin, Box::new(dest), Box::new(msg)) - } - - fn query( - origin: &AccountIdOf, - timeout: BlockNumberFor, - match_querier: VersionedMultiLocation, - ) -> Result { - use frame_support::traits::EnsureOrigin; - - let origin = RawOrigin::Signed(origin.clone()).into(); - let responder = ::ExecuteXcmOrigin::ensure_origin(origin)?; - - let query_id = as QueryHandler>::new_query( - responder, - timeout.into(), - MultiLocation::try_from(match_querier) - .map_err(|_| Into::::into(pallet_xcm::Error::::BadVersion))?, - ); - - Ok(query_id) - } - - fn take_response(query_id: Self::QueryId) -> QueryResponseStatus> { - as QueryHandler>::take_response(query_id) - } -} - -// impl diff --git a/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs b/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs new file mode 100644 index 000000000000..92418e225a35 --- /dev/null +++ b/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs @@ -0,0 +1,76 @@ +use crate::{AccountIdOf, Config, RawOrigin}; +use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight}; +use frame_system::pallet_prelude::BlockNumberFor; +use pallet_xcm::WeightInfo as XcmWeightInfo; +use sp_runtime::{DispatchError, DispatchResult}; +use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; +use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; +use crate::xcm::{XCM, WeightInfo, CallOf}; + +impl WeightInfo for T +where + T: pallet_xcm::Config, +{ + fn execute() -> Weight { + ::WeightInfo::execute() + } + fn send() -> Weight { + ::WeightInfo::send() + } + fn query() -> Weight { + ::WeightInfo::new_query() + } + fn take_response() -> Weight { + ::WeightInfo::take_response() + } +} + +impl XCM for T +where + T: pallet_xcm::Config, +{ + type QueryId = as QueryHandler>::QueryId; + type WeightInfo = T; + + fn execute( + origin: &AccountIdOf, + message: VersionedXcm>, + max_weight: Weight, + ) -> DispatchResultWithPostInfo { + let origin = RawOrigin::Signed(origin.clone()).into(); + pallet_xcm::Pallet::::execute(origin, Box::new(message), max_weight) + } + fn send( + origin: &AccountIdOf, + dest: VersionedMultiLocation, + msg: VersionedXcm<()>, + ) -> DispatchResult { + let origin = RawOrigin::Signed(origin.clone()).into(); + pallet_xcm::Pallet::::send(origin, Box::new(dest), Box::new(msg)) + } + + fn query( + origin: &AccountIdOf, + timeout: BlockNumberFor, + match_querier: VersionedMultiLocation, + ) -> Result { + use frame_support::traits::EnsureOrigin; + + let origin = RawOrigin::Signed(origin.clone()).into(); + let responder = ::ExecuteXcmOrigin::ensure_origin(origin)?; + + let query_id = as QueryHandler>::new_query( + responder, + timeout.into(), + MultiLocation::try_from(match_querier) + .map_err(|_| Into::::into(pallet_xcm::Error::::BadVersion))?, + ); + + Ok(query_id) + } + + fn take_response(query_id: Self::QueryId) -> QueryResponseStatus> { + as QueryHandler>::take_response(query_id) + } +} + From 7484d32b9dd1acfdf19ced202f5d425f02159ca7 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 4 Sep 2023 18:03:54 +0200 Subject: [PATCH 017/115] fmt --- .../frame/contracts/src/tests/mock_network/parachain.rs | 7 ++----- .../frame/contracts/src/tests/mock_network/relay_chain.rs | 2 +- .../frame/contracts/src/tests/mock_network/xcm_utils.rs | 2 +- substrate/frame/contracts/src/xcm.rs | 3 +-- substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs | 7 ++++--- 5 files changed, 9 insertions(+), 12 deletions(-) diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain.rs b/substrate/frame/contracts/src/tests/mock_network/parachain.rs index c02af0d0506e..825ccbaba275 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain.rs @@ -20,7 +20,7 @@ mod contracts_config; use crate::tests::mock_network::{ mocks::msg_queue::pallet as mock_msg_queue, primitives::{AccountId, AssetIdForAssets, Balance}, - xcm_utils::{ ForeignChainAliasAccount}, + xcm_utils::ForeignChainAliasAccount, }; use core::marker::PhantomData; use frame_support::{ @@ -233,10 +233,7 @@ impl Contains for ParentRelay { pub type XcmRouter = crate::tests::mock_network::ParachainXcmRouter; pub type Barrier = WithComputedOrigin< - ( - AllowExplicitUnpaidExecutionFrom, - AllowTopLevelPaidExecutionFrom, - ), + (AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom), UniversalLocation, ConstU32<1>, >; diff --git a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs index 0d93e0fd75cf..a968a3d4f35f 100644 --- a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs @@ -41,7 +41,7 @@ use xcm_executor::{Config, XcmExecutor}; use super::{ mocks::relay_message_queue::*, primitives::{AccountId, Balance}, - xcm_utils::{ ForeignChainAliasAccount}, + xcm_utils::ForeignChainAliasAccount, }; parameter_types! { diff --git a/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs b/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs index 2e98720ef3b5..bc157569be00 100644 --- a/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs +++ b/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs @@ -18,7 +18,7 @@ use codec::Encode; use core::{borrow::Borrow, marker::PhantomData}; use sp_core::blake2_256; use xcm::prelude::*; -use xcm_executor::traits::{ConvertLocation }; +use xcm_executor::traits::ConvertLocation; /// Prefix for generating alias account for accounts coming /// from chains that use 32 byte long representations. diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index e250e83d3c00..8c1b5390805c 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -4,7 +4,7 @@ use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight} use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::{DispatchError, DispatchResult}; use xcm::{VersionedMultiLocation, VersionedXcm}; -use xcm_executor::traits::{QueryResponseStatus}; +use xcm_executor::traits::QueryResponseStatus; pub type CallOf = ::RuntimeCall; // TODO move behind feature flag @@ -107,4 +107,3 @@ impl WeightInfo for NoopXcmConfig { Weight::zero() } } - diff --git a/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs b/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs index 92418e225a35..4ddc797d6e31 100644 --- a/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs +++ b/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs @@ -1,11 +1,13 @@ -use crate::{AccountIdOf, Config, RawOrigin}; +use crate::{ + xcm::{CallOf, WeightInfo, XCM}, + AccountIdOf, Config, RawOrigin, +}; use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight}; use frame_system::pallet_prelude::BlockNumberFor; use pallet_xcm::WeightInfo as XcmWeightInfo; use sp_runtime::{DispatchError, DispatchResult}; use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; -use crate::xcm::{XCM, WeightInfo, CallOf}; impl WeightInfo for T where @@ -73,4 +75,3 @@ where as QueryHandler>::take_response(query_id) } } - From b40f92c4feedc62163f0d284531aeb9356c6801b Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 4 Sep 2023 18:04:25 +0200 Subject: [PATCH 018/115] headr --- .../contracts/src/xcm/pallet_xcm_extension.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs b/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs index 4ddc797d6e31..32d514c73a64 100644 --- a/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs +++ b/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs @@ -1,3 +1,20 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use crate::{ xcm::{CallOf, WeightInfo, XCM}, AccountIdOf, Config, RawOrigin, From c3f7d40b0673de22a4f6f95373e0bd903eee5b5b Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 4 Sep 2023 18:05:25 +0200 Subject: [PATCH 019/115] missing headers --- substrate/frame/contracts/src/tests/test_xcm.rs | 17 +++++++++++++++++ substrate/frame/contracts/src/xcm.rs | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 823001f571db..c86c26a6ff62 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -1,3 +1,20 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use crate::{ tests::{ compile_module, diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 8c1b5390805c..bb75f12f81cf 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -1,3 +1,20 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use crate::{AccountIdOf, Config, Error}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight}; From a08e41b8f4ae3c103d4da275bae6ce0891ca36f6 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 4 Sep 2023 20:35:17 +0200 Subject: [PATCH 020/115] fix missing comment --- substrate/frame/contracts/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 3668774edf69..d8a47a47203a 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -1005,7 +1005,7 @@ pub mod pallet { /// in this error. Note that this usually shouldn't happen as deploying such contracts /// is rejected. NoChainExtension, - /// TODO doc + /// Xcm function was invoked while the feature is disabled. XcmDisabled, /// A contract with the same AccountId already exists. DuplicateContract, From 376a6b39c32305a63dc23c3fd3fc116b2ddc9daa Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 4 Sep 2023 21:22:14 +0200 Subject: [PATCH 021/115] fixes --- substrate/frame/contracts/src/lib.rs | 2 ++ substrate/frame/contracts/src/tests.rs | 2 +- substrate/frame/contracts/src/xcm.rs | 7 +++---- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index d8a47a47203a..97fc4fe92603 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -403,6 +403,8 @@ pub mod pallet { #[pallet::constant] type Environment: Get>; + /// Type that expose XCM API, to allows contracts to interact with other parachains. + /// Implement `pallet-xcm` for your config and set to `Self` to enable XCM API. type Xcm: crate::xcm::XCM; } diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index 64041ec800bc..2c3c88958ca5 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -486,7 +486,7 @@ impl Config for Test { type MaxDelegateDependencies = MaxDelegateDependencies; type Debug = TestDebug; type Environment = (); - type Xcm = crate::xcm::NoopXcmConfig; + type Xcm = crate::xcm::Noop; } pub const ALICE: AccountId32 = AccountId32::new([1u8; 32]); diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index bb75f12f81cf..724f44f5fc1e 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -24,7 +24,6 @@ use xcm::{VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::QueryResponseStatus; pub type CallOf = ::RuntimeCall; -// TODO move behind feature flag mod pallet_xcm_extension; pub trait XCM { @@ -67,9 +66,9 @@ pub trait XCM { } /// A no-op implementation of [`XCM`]. -pub struct NoopXcmConfig; +pub struct Noop; -impl XCM for NoopXcmConfig { +impl XCM for Noop { type QueryId = (); type WeightInfo = Self; fn execute( @@ -110,7 +109,7 @@ pub trait WeightInfo { fn take_response() -> Weight; } -impl WeightInfo for NoopXcmConfig { +impl WeightInfo for Noop { fn execute() -> Weight { Weight::zero() } From d2b5ba34ab8b7143e548f1682eb72a4529299da2 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 00:08:27 +0200 Subject: [PATCH 022/115] refactoring --- substrate/frame/contracts/src/lib.rs | 9 ++++++--- substrate/frame/contracts/src/tests.rs | 2 +- .../mock_network/parachain/contracts_config.rs | 3 ++- substrate/frame/contracts/src/xcm.rs | 13 ++++++------- ...allet_xcm_extension.rs => pallet_xcm_adapter.rs} | 9 ++++++--- 5 files changed, 21 insertions(+), 15 deletions(-) rename substrate/frame/contracts/src/xcm/{pallet_xcm_extension.rs => pallet_xcm_adapter.rs} (92%) diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 97fc4fe92603..56edfe7d3c47 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -108,6 +108,7 @@ use crate::{ gas::GasMeter, storage::{meter::Meter as StorageMeter, ContractInfo, DeletionQueueManager}, wasm::{CodeInfo, WasmBlob}, + xcm::XCM, }; use codec::{Codec, Decode, Encode, HasCompact, MaxEncodedLen}; use environmental::*; @@ -403,9 +404,11 @@ pub mod pallet { #[pallet::constant] type Environment: Get>; - /// Type that expose XCM API, to allows contracts to interact with other parachains. - /// Implement `pallet-xcm` for your config and set to `Self` to enable XCM API. - type Xcm: crate::xcm::XCM; + /// A type that exposes XCM APIs, allowing contracts to interact with other parachains, and + /// execute XCM messages. + /// + /// Use [`xcm::PalletXCMAdapter`] to enable or `()` to disable. + type Xcm: XCM; } #[pallet::hooks] diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index 956af1bfde1e..1fc310243c85 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -486,7 +486,7 @@ impl Config for Test { type MaxDelegateDependencies = MaxDelegateDependencies; type Debug = TestDebug; type Environment = (); - type Xcm = crate::xcm::Noop; + type Xcm = (); } pub const ALICE: AccountId32 = AccountId32::new([1u8; 32]); diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs index dda5fb0d42c2..2f4a13d24abd 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs @@ -20,6 +20,7 @@ use crate::{ parachain::RuntimeHoldReason, primitives::{Balance, CENTS}, }, + xcm::PalletXCMAdapter, Config, }; use frame_support::{ @@ -84,5 +85,5 @@ impl Config for Runtime { type WeightPrice = Self; type Debug = (); type Environment = (); - type Xcm = Self; + type Xcm = PalletXCMAdapter; } diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 724f44f5fc1e..701fc3e92c15 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -22,9 +22,11 @@ use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::{DispatchError, DispatchResult}; use xcm::{VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::QueryResponseStatus; -pub type CallOf = ::RuntimeCall; -mod pallet_xcm_extension; +mod pallet_xcm_adapter; + +pub use pallet_xcm_adapter::PalletXCMAdapter; +pub type CallOf = ::RuntimeCall; pub trait XCM { type QueryId: Encode + Decode + MaxEncodedLen; @@ -65,10 +67,7 @@ pub trait XCM { fn take_response(query_id: Self::QueryId) -> QueryResponseStatus>; } -/// A no-op implementation of [`XCM`]. -pub struct Noop; - -impl XCM for Noop { +impl XCM for () { type QueryId = (); type WeightInfo = Self; fn execute( @@ -109,7 +108,7 @@ pub trait WeightInfo { fn take_response() -> Weight; } -impl WeightInfo for Noop { +impl WeightInfo for () { fn execute() -> Weight { Weight::zero() } diff --git a/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs b/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs similarity index 92% rename from substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs rename to substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs index 32d514c73a64..495a46fd93f0 100644 --- a/substrate/frame/contracts/src/xcm/pallet_xcm_extension.rs +++ b/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs @@ -26,7 +26,10 @@ use sp_runtime::{DispatchError, DispatchResult}; use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; -impl WeightInfo for T +/// A pallet-xcm adapter for the XCM trait. +pub struct PalletXCMAdapter(sp_std::marker::PhantomData); + +impl WeightInfo for PalletXCMAdapter where T: pallet_xcm::Config, { @@ -44,12 +47,12 @@ where } } -impl XCM for T +impl XCM for PalletXCMAdapter where T: pallet_xcm::Config, { type QueryId = as QueryHandler>::QueryId; - type WeightInfo = T; + type WeightInfo = Self; fn execute( origin: &AccountIdOf, From d7fe1bc16c22058a98d824ac0cc0c78fd67ae589 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 00:18:43 +0200 Subject: [PATCH 023/115] fix build --- Cargo.lock | 2 +- substrate/frame/contracts/Cargo.toml | 4 ++-- .../frame/contracts/src/tests/mock_network/mocks/msg_queue.rs | 2 +- substrate/frame/contracts/src/tests/mock_network/parachain.rs | 2 +- .../frame/contracts/src/tests/mock_network/relay_chain.rs | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 46458abd90d7..5adf4af40d63 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9371,7 +9371,7 @@ dependencies = [ "pallet-utility", "pallet-xcm", "parity-scale-codec", - "polkadot-parachain", + "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-runtime-parachains", "pretty_assertions", diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index d5f10bd48394..34a03e3204f2 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -61,9 +61,9 @@ wat = "1" # Polkadot Dependencies xcm-simulator = {path = "../../../polkadot/xcm/xcm-simulator"} -polkadot-runtime-parachains = {path = "../../../polkadot/runtime/parachains"} xcm-builder = {package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder"} -polkadot-parachain = { path = "../../../polkadot/parachain" } +polkadot-runtime-parachains = {path = "../../../polkadot/runtime/parachains"} +polkadot-parachain-primitives = { path = "../../../polkadot/parachain" } polkadot-primitives = { path = "../../../polkadot/primitives" } # Substrate Dependencies diff --git a/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs b/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs index d8f291cfd717..6fe79b129c08 100644 --- a/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs +++ b/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs @@ -19,7 +19,7 @@ use codec::{Decode, Encode}; use frame_support::weights::Weight; -use polkadot_parachain::primitives::{ +use polkadot_parachain_primitives::primitives::{ DmpMessageHandler, Id as ParaId, XcmpMessageFormat, XcmpMessageHandler, }; use polkadot_primitives::BlockNumber as RelayBlockNumber; diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain.rs b/substrate/frame/contracts/src/tests/mock_network/parachain.rs index 825ccbaba275..800f5e075fb9 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain.rs @@ -33,7 +33,7 @@ use frame_support::{ }; use frame_system::{EnsureRoot, EnsureSigned}; use pallet_xcm::XcmPassthrough; -use polkadot_parachain::primitives::Sibling; +use polkadot_parachain_primitives::primitives::Sibling; use sp_core::{ConstU32, ConstU64, H256}; use sp_runtime::traits::{Get, IdentityLookup, MaybeEquivalence}; diff --git a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs index a968a3d4f35f..0d0e7681bc04 100644 --- a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs @@ -26,7 +26,7 @@ use frame_system::EnsureRoot; use sp_core::{ConstU32, H256}; use sp_runtime::traits::IdentityLookup; -use polkadot_parachain::primitives::Id as ParaId; +use polkadot_parachain_primitives::primitives::Id as ParaId; use polkadot_runtime_parachains::{configuration, origin, shared}; use xcm::latest::prelude::*; use xcm_builder::{ From c15adab7c31f7f27be72bb2d38681f9177162999 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 09:36:38 +0200 Subject: [PATCH 024/115] missing type in node/runtime --- substrate/bin/node/runtime/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 4f34e4ecd812..300748aea06a 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -1327,6 +1327,7 @@ impl pallet_contracts::Config for Runtime { type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; type Debug = (); type Environment = (); + type Xcm = (); } impl pallet_sudo::Config for Runtime { From e15c7eb6750df58bb01bd847c16017a234bef905 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 09:45:16 +0200 Subject: [PATCH 025/115] format cargo.toml --- substrate/frame/contracts/Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 34a03e3204f2..17915317215a 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -93,6 +93,7 @@ std = [ "pallet-proxy/std", "pallet-timestamp/std", "pallet-utility/std", + "pallet-xcm/std", "rand/std", "scale-info/std", "serde", @@ -104,9 +105,8 @@ std = [ "sp-std/std", "wasm-instrument/std", "wasmi/std", - "pallet-xcm/std", - "xcm/std", "xcm-executor/std", + "xcm/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", From 971b16781195596a7b11d11d5f0af9692851461c Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 10:51:42 +0200 Subject: [PATCH 026/115] more zepter fixes --- substrate/frame/contracts/Cargo.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 17915317215a..fe941c438f94 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -130,4 +130,8 @@ try-runtime = [ "pallet-timestamp/try-runtime", "pallet-utility/try-runtime", "sp-runtime/try-runtime", + "pallet-assets/try-runtime", + "pallet-message-queue/try-runtime", + "pallet-xcm/try-runtime", + "polkadot-runtime-parachains/try-runtime" ] From 3dba8d1f8819770faac9ab12deee48108c96432d Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 11:12:20 +0200 Subject: [PATCH 027/115] fixes --- substrate/frame/contracts/Cargo.toml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index fe941c438f94..152d6fe01ac8 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -120,6 +120,14 @@ runtime-benchmarks = [ "rand_pcg", "sp-runtime/runtime-benchmarks", "wasm-instrument", + "pallet-assets/runtime-benchmarks", + "pallet-message-queue/runtime-benchmarks", + "pallet-xcm/runtime-benchmarks", + "polkadot-parachain-primitives/runtime-benchmarks", + "polkadot-primitives/runtime-benchmarks", + "polkadot-runtime-parachains/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", + "xcm-executor/runtime-benchmarks" ] try-runtime = [ "frame-support/try-runtime", From be1a46d4921846afff8e7b75dbd0b0907f75163c Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 11:37:30 +0200 Subject: [PATCH 028/115] missing trait implementation --- .../runtimes/contracts/contracts-rococo/src/contracts.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs index 6598fd3fae0a..d44808e8a045 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs @@ -79,4 +79,5 @@ impl Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type Debug = (); type Environment = (); + type Xcm = (); } From a4d706c656336038efbcae444871b714bfe7e221 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 13:03:01 +0200 Subject: [PATCH 029/115] fix tests --- substrate/frame/contracts/src/tests/mock_network/parachain.rs | 4 +++- substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain.rs b/substrate/frame/contracts/src/tests/mock_network/parachain.rs index 800f5e075fb9..159e67e9306d 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain.rs @@ -136,6 +136,8 @@ impl pallet_assets::Config for Runtime { type RemoveItemsLimit = RemoveItemsLimit; type AssetIdParameter = AssetIdForAssets; type CallbackHandle = (); + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); } parameter_types! { @@ -319,7 +321,7 @@ impl pallet_xcm::Config for Runtime { type RemoteLockConsumerIdentifier = (); type WeightInfo = pallet_xcm::TestWeightInfo; #[cfg(feature = "runtime-benchmarks")] - type ReachableDest = ReachableDest; + type ReachableDest = crate::tests::mock_network::relay_chain::ReachableDest; type AdminOrigin = EnsureRoot; } diff --git a/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs b/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs index 495a46fd93f0..deb8d041582b 100644 --- a/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs +++ b/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs @@ -16,6 +16,7 @@ // limitations under the License. use crate::{ + Box, xcm::{CallOf, WeightInfo, XCM}, AccountIdOf, Config, RawOrigin, }; From b15ea884d1191a09c298ee05a48ffdb2224e26c0 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 13:09:47 +0200 Subject: [PATCH 030/115] fixes --- .../runtimes/contracts/contracts-rococo/src/contracts.rs | 3 ++- substrate/frame/contracts/src/lib.rs | 2 +- substrate/frame/contracts/src/xcm.rs | 2 +- substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs | 3 +-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs index d44808e8a045..f6b402625d1b 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs @@ -25,6 +25,7 @@ use pallet_contracts::{ migration::{v12, v13, v14, v15}, weights::SubstrateWeight, Config, DebugInfo, DefaultAddressGenerator, Frame, Schedule, + xcm::PalletXCMAdapter }; use sp_runtime::Perbill; @@ -79,5 +80,5 @@ impl Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type Debug = (); type Environment = (); - type Xcm = (); + type Xcm = PalletXCMAdapter; } diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 56edfe7d3c47..b9aaf42d9e00 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -94,12 +94,12 @@ mod gas; mod schedule; mod storage; mod wasm; -mod xcm; pub mod chain_extension; pub mod debug; pub mod migration; pub mod weights; +pub mod xcm; #[cfg(test)] mod tests; diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 701fc3e92c15..bf9430e7a33f 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -23,7 +23,7 @@ use sp_runtime::{DispatchError, DispatchResult}; use xcm::{VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::QueryResponseStatus; -mod pallet_xcm_adapter; +pub mod pallet_xcm_adapter; pub use pallet_xcm_adapter::PalletXCMAdapter; pub type CallOf = ::RuntimeCall; diff --git a/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs b/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs index deb8d041582b..09a51c965839 100644 --- a/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs +++ b/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs @@ -16,9 +16,8 @@ // limitations under the License. use crate::{ - Box, xcm::{CallOf, WeightInfo, XCM}, - AccountIdOf, Config, RawOrigin, + AccountIdOf, Box, Config, RawOrigin, }; use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight}; use frame_system::pallet_prelude::BlockNumberFor; From b938df4763f86762e15959123bad1e868cea81c6 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 13:35:20 +0200 Subject: [PATCH 031/115] fmt fix --- .../runtimes/contracts/contracts-rococo/src/contracts.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs index f6b402625d1b..9eab908625a5 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs @@ -24,8 +24,8 @@ use frame_support::{ use pallet_contracts::{ migration::{v12, v13, v14, v15}, weights::SubstrateWeight, + xcm::PalletXCMAdapter, Config, DebugInfo, DefaultAddressGenerator, Frame, Schedule, - xcm::PalletXCMAdapter }; use sp_runtime::Perbill; From fcc37f53c4b6f6d51025597b6dc1c3d062d6a10f Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 13:42:25 +0200 Subject: [PATCH 032/115] zepter format --- substrate/frame/contracts/Cargo.toml | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 152d6fe01ac8..c867c1285a6b 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -112,34 +112,34 @@ runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", + "pallet-assets/runtime-benchmarks", "pallet-balances/runtime-benchmarks", + "pallet-message-queue/runtime-benchmarks", "pallet-proxy/runtime-benchmarks", "pallet-timestamp/runtime-benchmarks", "pallet-utility/runtime-benchmarks", - "rand", - "rand_pcg", - "sp-runtime/runtime-benchmarks", - "wasm-instrument", - "pallet-assets/runtime-benchmarks", - "pallet-message-queue/runtime-benchmarks", "pallet-xcm/runtime-benchmarks", "polkadot-parachain-primitives/runtime-benchmarks", "polkadot-primitives/runtime-benchmarks", "polkadot-runtime-parachains/runtime-benchmarks", + "rand", + "rand_pcg", + "sp-runtime/runtime-benchmarks", + "wasm-instrument", "xcm-builder/runtime-benchmarks", - "xcm-executor/runtime-benchmarks" + "xcm-executor/runtime-benchmarks", ] try-runtime = [ "frame-support/try-runtime", "frame-system/try-runtime", + "pallet-assets/try-runtime", "pallet-balances/try-runtime", "pallet-insecure-randomness-collective-flip/try-runtime", + "pallet-message-queue/try-runtime", "pallet-proxy/try-runtime", "pallet-timestamp/try-runtime", "pallet-utility/try-runtime", - "sp-runtime/try-runtime", - "pallet-assets/try-runtime", - "pallet-message-queue/try-runtime", "pallet-xcm/try-runtime", - "polkadot-runtime-parachains/try-runtime" + "polkadot-runtime-parachains/try-runtime", + "sp-runtime/try-runtime", ] From 9cc990f6a0dd72264033bb5cae39917dde275d05 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 13:57:54 +0200 Subject: [PATCH 033/115] fix doc links --- substrate/frame/contracts/src/xcm.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index bf9430e7a33f..e40988a0c3ff 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -32,7 +32,7 @@ pub trait XCM { type QueryId: Encode + Decode + MaxEncodedLen; type WeightInfo: WeightInfo; - /// Execute an XCM message locally. see [`pallet_xcm::execute`] + /// Execute an XCM message locally. see [`pallet_xcm::pallet::Pallet::execute`] /// /// - `origin`: the origin of the call. /// - `message`: the XCM message to be executed. @@ -43,7 +43,8 @@ pub trait XCM { max_weight: Weight, ) -> DispatchResultWithPostInfo; - /// Send an XCM message to be executed by a remote location. see [`pallet_xcm::send`] + /// Send an XCM message to be executed by a remote location. see + /// [`pallet_xcm::pallet::Pallet::send`] /// /// - `origin`: the origin of the call. /// - `dest`: the destination of the message. @@ -54,7 +55,7 @@ pub trait XCM { msg: VersionedXcm<()>, ) -> DispatchResult; - /// Query a remote location. see [`QueryHandler::new_query`] + /// Query a remote location. see [`xcm_executor::traits::QueryHandler::new_query`] /// /// - `origin`: the origin of the call, used to determine the responder. /// - `timeout`: the maximum block number that the query should be responded to. From 7ff220b0a47b9abec40ca8b93998842f7ceb202e Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 16:52:40 +0200 Subject: [PATCH 034/115] rm println! --- substrate/frame/contracts/src/tests/test_xcm.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index c86c26a6ff62..0a4109ce3daa 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -147,8 +147,6 @@ fn test_xcm_send() { ]); let message = VersionedXcm::V3(message); - println!("msg: \n{:?}", message.clone().encode()); - assert_ok!( ParachainContracts::bare_call( ALICE, @@ -184,9 +182,6 @@ fn test_xcm_query() { let match_querier = VersionedMultiLocation::V3(match_querier); let timeout: BlockNumberFor = 1u32.into(); - println!("timeout encoded: {:?}", timeout.encode()); - println!("match_querier encoded len: {:?}", match_querier.clone().encode().len()); - println!("encoded: {:?}", (timeout, match_querier.clone()).encode()); let exec = ParachainContracts::bare_call( ALICE, contract_addr.clone(), From bdf0ae7604fe111d699c2c73afe50c3aff945c47 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 17:24:35 +0200 Subject: [PATCH 035/115] add tests comments --- .../frame/contracts/src/tests/test_xcm.rs | 37 +++++++++++-------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 0a4109ce3daa..41249502011f 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -136,6 +136,7 @@ fn test_xcm_send() { let contract_addr = instantiate_test_contract("xcm_send"); let fee = parachain::estimate_message_fee(4); // Accounts for the `DescendOrigin` instruction added by `send_xcm` + // Send XCM instructions through the contract, to lock some funds on the relay chain. ParaA::execute_with(|| { let dest = MultiLocation::from(Parent); let dest = VersionedMultiLocation::V3(dest); @@ -182,6 +183,7 @@ fn test_xcm_query() { let match_querier = VersionedMultiLocation::V3(match_querier); let timeout: BlockNumberFor = 1u32.into(); + // Invoke the contract to create an XCM query. let exec = ParachainContracts::bare_call( ALICE, contract_addr.clone(), @@ -195,8 +197,9 @@ fn test_xcm_query() { ); let mut data = &exec.result.unwrap().data[..]; - let query_id = QueryId::decode(&mut data).expect("Failed to decode message"); + + // Verify that the query exists and is pending. let response = ParachainPalletXcm::take_response(query_id); let expected_response = QueryResponseStatus::Pending { timeout }; assert_eq!(response, expected_response); @@ -207,6 +210,7 @@ fn test_xcm_query() { fn test_xcm_take_response() { MockNet::reset(); let contract_addr = instantiate_test_contract("xcm_take_response"); + ParaA::execute_with(|| { let querier: MultiLocation = (Parent, AccountId32 { network: None, id: ALICE.into() }).into(); @@ -214,20 +218,11 @@ fn test_xcm_take_response() { network: Some(NetworkId::ByGenesis([0u8; 32])), id: ALICE.into(), }); - let query_id = ParachainPalletXcm::new_query(responder, 1u32.into(), querier); - let fee = parachain::estimate_message_fee(4); - let message = Xcm(vec![ - WithdrawAsset(vec![(Parent, fee).into()].into()), - BuyExecution { fees: (Parent, fee).into(), weight_limit: WeightLimit::Unlimited }, - QueryResponse { - query_id, - response: Response::ExecutionResult(None), - max_weight: Weight::zero(), - querier: Some(querier), - }, - ]); + // Register a new query. + let query_id = ParachainPalletXcm::new_query(responder, 1u32.into(), querier); + // Helper closure to call the contract to take the response. let call = |query_id: QueryId| { let exec = ParachainContracts::bare_call( ALICE, @@ -250,6 +245,18 @@ fn test_xcm_take_response() { // Query is not yet answered. assert_eq!(QueryResponseStatus::Pending { timeout: 1u32.into() }, call(query_id)); + // Execute the XCM message that answers the query. + let fee = parachain::estimate_message_fee(4); + let message = Xcm(vec![ + WithdrawAsset(vec![(Parent, fee).into()].into()), + BuyExecution { fees: (Parent, fee).into(), weight_limit: WeightLimit::Unlimited }, + QueryResponse { + query_id, + response: Response::ExecutionResult(None), + max_weight: Weight::zero(), + querier: Some(querier), + }, + ]); ParachainPalletXcm::execute( RuntimeOrigin::signed(ALICE), Box::new(VersionedXcm::V3(message)), @@ -257,7 +264,7 @@ fn test_xcm_take_response() { ) .unwrap(); - // Query is answered. + // First call returns the response. assert_eq!( QueryResponseStatus::Ready { response: Response::ExecutionResult(None), @@ -266,7 +273,7 @@ fn test_xcm_take_response() { call(query_id) ); - // Query is not found. (Query was already answered) + // Second call returns `NotFound`. (Query was already answered) assert_eq!(QueryResponseStatus::NotFound, call(query_id)); }) } From 14e15149ebc000f77a2b181fefe8ff7cb05f5f74 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 5 Sep 2023 20:38:04 +0200 Subject: [PATCH 036/115] worst case --- polkadot/xcm/pallet-xcm/src/benchmarking.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/polkadot/xcm/pallet-xcm/src/benchmarking.rs b/polkadot/xcm/pallet-xcm/src/benchmarking.rs index e1a9835ce667..c80751c8ebea 100644 --- a/polkadot/xcm/pallet-xcm/src/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm/src/benchmarking.rs @@ -204,12 +204,12 @@ benchmarks! { let match_querier = MultiLocation::from(Here); let query_id = Pallet::::new_query(responder, timeout, match_querier); let infos = (0 .. xcm::v3::MaxPalletsInfo::get()).map(|_| PalletInfo::new( - 1u32, + u32::MAX, (0..xcm::v3::MaxPalletNameLen::get()).map(|_| 97u8).collect::>().try_into().unwrap(), (0..xcm::v3::MaxPalletNameLen::get()).map(|_| 97u8).collect::>().try_into().unwrap(), - 1u32, - 0u32, - 0u32, + u32::MAX, + u32::MAX, + u32::MAX, ).unwrap()).collect::>(); Pallet::::expect_response(query_id, Response::PalletsInfo(infos.try_into().unwrap())); From e9d2cdf4f66302d7bd252559ace98f533b704d69 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Thu, 14 Sep 2023 15:46:43 +0200 Subject: [PATCH 037/115] simplify XCM --- substrate/frame/contracts/fixtures/xcm_execute.wat | 13 ++++--------- substrate/frame/contracts/src/tests/test_xcm.rs | 7 +------ substrate/frame/contracts/src/wasm/runtime.rs | 13 ++++++------- substrate/frame/contracts/src/xcm.rs | 2 +- 4 files changed, 12 insertions(+), 23 deletions(-) diff --git a/substrate/frame/contracts/fixtures/xcm_execute.wat b/substrate/frame/contracts/fixtures/xcm_execute.wat index df4a237b4d54..4ff7ef26c87d 100644 --- a/substrate/frame/contracts/fixtures/xcm_execute.wat +++ b/substrate/frame/contracts/fixtures/xcm_execute.wat @@ -1,6 +1,6 @@ ;; This passes its input to `seal_xcm_execute` and returns the return value to its caller. (module - (import "seal0" "xcm_execute" (func $xcm_execute (param i32 i32 i32) (result i32))) + (import "seal0" "xcm_execute" (func $xcm_execute (param i32 i32) (result i32))) (import "seal0" "seal_input" (func $seal_input (param i32 i32))) (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) (import "env" "memory" (memory 1 1)) @@ -17,18 +17,13 @@ ) ;; Input data layout. ;; [0..4) - size of the call - ;; [4..12) - max_weight (Weight::from_all(1_000_000_000) -> 8 bytes) - ;; [12..) - xcm message + ;; [4..) - xcm message ;; Just use the call passed as input and store result to memory (i32.store (i32.const 0) (call $xcm_execute - (i32.const 4) ;; Pointer to the max_weight - (i32.const 16) ;; Pointer where the xcm msg is stored - (i32.sub ;; Size of the xcm msg - (i32.load (i32.const 0)) - (i32.const 12) - ) + (i32.const 4) ;; Pointer where the xcm msg is stored + (i32.load (i32.const 0)) ;; Size of the xcm msg ) ) (call $seal_return diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 41249502011f..74cb63251a25 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -101,11 +101,6 @@ fn test_xcm_execute() { beneficiary: AccountId32 { network: None, id: BOB.clone().into() }.into(), }, ]); - let message = VersionedXcm::V3(message); - - // Execute the XCM message, through the contract. - let max_weight = Weight::from_all(10_000_000_000); - let data = (max_weight, message.clone()).encode(); assert_ok!( ParachainContracts::bare_call( @@ -114,7 +109,7 @@ fn test_xcm_execute() { 0, Weight::MAX, None, - data, + VersionedXcm::V3(message).encode(), DebugInfo::UnsafeDebug, CollectEvents::UnsafeCollect, Determinism::Enforced, diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index b14590c0e283..d1b1526a0b31 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -40,6 +40,8 @@ use sp_runtime::{ use sp_std::{fmt, prelude::*}; use wasmi::{core::HostError, errors::LinkerError, Linker, Memory, Store}; +// type XcmOf = <::Xcm as XCM>; + /// The maximum nesting depth a contract can use when encoding types. const MAX_DECODE_NESTING: u32 = 256; @@ -2652,7 +2654,6 @@ pub mod env { /// /// # Parameters /// - /// - `max_weight_ptr`: the pointer into the linear memory where the maximum weight is placed. /// - `msg_ptr`: the pointer into the linear memory where the XCM message is placed. /// - `msg_len`: the length of the XCM message in bytes. /// @@ -2664,7 +2665,6 @@ pub mod env { fn xcm_execute( ctx: _, memory: _, - max_weight_ptr: u32, msg_ptr: u32, msg_len: u32, ) -> Result { @@ -2673,14 +2673,13 @@ pub mod env { use xcm::VersionedXcm; ctx.charge_gas(RuntimeCosts::CopyFromContract(msg_len))?; - let max_weight: Weight = ctx.read_sandbox_memory_as(memory, max_weight_ptr)?; - let weight = - max_weight.saturating_add(<::Xcm as XCM>::WeightInfo::execute()); - let message: VersionedXcm> = ctx.read_sandbox_memory_as_unbounded(memory, msg_ptr, msg_len)?; - let dispatch_info = DispatchInfo { weight, ..Default::default() }; + let max_weight = ctx.ext.gas_meter().gas_left(); + let max_weight = + max_weight.max(<::Xcm as XCM>::WeightInfo::execute()); + let dispatch_info = DispatchInfo { weight: max_weight, ..Default::default() }; ctx.call_dispatchable(dispatch_info, |ext| { <::Xcm as XCM>::execute(ext.address(), message, max_weight) diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index e40988a0c3ff..15fc51039585 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -76,7 +76,7 @@ impl XCM for () { _message: VersionedXcm>, _max_weight: Weight, ) -> DispatchResultWithPostInfo { - Err(Error::::XcmDisabled.into()).into() + Err(Error::::XcmDisabled.into()) } fn send( _origin: &AccountIdOf, From c9f8f3560981547d774c5db301ae7c65e03bca14 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Thu, 14 Sep 2023 15:55:33 +0200 Subject: [PATCH 038/115] add docs --- substrate/frame/contracts/src/xcm.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 15fc51039585..7ac3ca1a8a52 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -34,6 +34,8 @@ pub trait XCM { /// Execute an XCM message locally. see [`pallet_xcm::pallet::Pallet::execute`] /// + /// # Parameters + /// /// - `origin`: the origin of the call. /// - `message`: the XCM message to be executed. /// - `max_weight`: the maximum weight that can be consumed by the execution. @@ -46,6 +48,8 @@ pub trait XCM { /// Send an XCM message to be executed by a remote location. see /// [`pallet_xcm::pallet::Pallet::send`] /// + /// # Parameters + /// /// - `origin`: the origin of the call. /// - `dest`: the destination of the message. /// - `msg`: the XCM message to be sent. @@ -57,6 +61,8 @@ pub trait XCM { /// Query a remote location. see [`xcm_executor::traits::QueryHandler::new_query`] /// + /// # Parameters + /// /// - `origin`: the origin of the call, used to determine the responder. /// - `timeout`: the maximum block number that the query should be responded to. /// - `match_querier`: the querier that the query should be responded to. @@ -65,6 +71,13 @@ pub trait XCM { timeout: BlockNumberFor, match_querier: VersionedMultiLocation, ) -> Result; + + /// Take an XCM response for the specified query. see + /// [`xcm_executor::traits::QueryHandler::take_response`] + /// + /// # Parameters + /// + /// - `query_id`: the query id returned by [`Self::query`]. fn take_response(query_id: Self::QueryId) -> QueryResponseStatus>; } From 151175b74e72a71ceeaf84c8966890e5ea5c92ff Mon Sep 17 00:00:00 2001 From: pgherveou Date: Thu, 21 Sep 2023 14:00:15 +0200 Subject: [PATCH 039/115] Filter out transact calls --- substrate/frame/contracts/src/tests.rs | 1 + .../parachain/contracts_config.rs | 4 +- .../frame/contracts/src/tests/test_xcm.rs | 93 +++++++++++++------ .../contracts/src/xcm/pallet_xcm_adapter.rs | 37 +++++++- 4 files changed, 101 insertions(+), 34 deletions(-) diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index 1fc310243c85..1d966f0f128c 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -82,6 +82,7 @@ frame_support::construct_runtime!( } ); +#[macro_export] macro_rules! assert_return_code { ( $x:expr , $y:expr $(,)? ) => {{ assert_eq!(u32::from_le_bytes($x.data[..].try_into().unwrap()), $y as u32); diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs index 2f4a13d24abd..27762c6cd46e 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs @@ -25,7 +25,7 @@ use crate::{ }; use frame_support::{ parameter_types, - traits::{ConstBool, ConstU32, Everything, Randomness}, + traits::{ConstBool, ConstU32, Nothing, Randomness}, weights::Weight, }; use frame_system::pallet_prelude::BlockNumberFor; @@ -61,7 +61,7 @@ impl Convert> for Runtime { impl Config for Runtime { type AddressGenerator = crate::DefaultAddressGenerator; - type CallFilter = Everything; + type CallFilter = Nothing; type CallStack = [crate::Frame; 5]; type ChainExtension = (); type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 74cb63251a25..d5a6571c351c 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -16,6 +16,7 @@ // limitations under the License. use crate::{ + assert_return_code, tests::{ compile_module, mock_network::{ @@ -25,13 +26,13 @@ use crate::{ relay_chain, MockNet, ParaA, ParachainBalances, ParachainPalletXcm, Relay, ALICE, BOB, INITIAL_BALANCE, }, + RuntimeReturnCode, }, xcm::XCM, CollectEvents, DebugInfo, Determinism, }; use codec::{Decode, Encode}; use frame_support::{ - assert_ok, pallet_prelude::Weight, traits::{fungibles::Mutate, Currency}, }; @@ -102,20 +103,21 @@ fn test_xcm_execute() { }, ]); - assert_ok!( - ParachainContracts::bare_call( - ALICE, - contract_addr.clone(), - 0, - Weight::MAX, - None, - VersionedXcm::V3(message).encode(), - DebugInfo::UnsafeDebug, - CollectEvents::UnsafeCollect, - Determinism::Enforced, - ) - .result - ); + let result = ParachainContracts::bare_call( + ALICE, + contract_addr.clone(), + 0, + Weight::MAX, + None, + VersionedXcm::V3(message).encode(), + DebugInfo::UnsafeDebug, + CollectEvents::UnsafeCollect, + Determinism::Enforced, + ) + .result + .unwrap(); + + assert_return_code!(result, RuntimeReturnCode::Success); // Check if the funds are subtracted from the account of Alice and added to the account of // Bob. @@ -125,6 +127,39 @@ fn test_xcm_execute() { }); } +#[test] +fn test_xcm_execute_filtered_call() { + MockNet::reset(); + + let contract_addr = instantiate_test_contract("xcm_execute"); + + ParaA::execute_with(|| { + // `remark` transact inside the Xcm message should be rejected, as CallFilter is set to `Nothing`. + let call = parachain::RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); + let message: Xcm = Xcm(vec![Transact { + origin_kind: OriginKind::Native, + require_weight_at_most: Weight::MAX, + call: call.encode().into(), + }]); + + let result = ParachainContracts::bare_call( + ALICE, + contract_addr.clone(), + 0, + Weight::MAX, + None, + VersionedXcm::V3(message).encode(), + DebugInfo::UnsafeDebug, + CollectEvents::UnsafeCollect, + Determinism::Enforced, + ) + .result + .unwrap(); + + assert_return_code!(result, RuntimeReturnCode::CallRuntimeFailed); + }); +} + #[test] fn test_xcm_send() { MockNet::reset(); @@ -142,21 +177,21 @@ fn test_xcm_send() { LockAsset { asset: (Here, 5 * CENTS).into(), unlocker: (Parachain(1)).into() }, ]); let message = VersionedXcm::V3(message); + let result = ParachainContracts::bare_call( + ALICE, + contract_addr.clone(), + 0, + Weight::MAX, + None, + (dest, message).encode(), + DebugInfo::UnsafeDebug, + CollectEvents::UnsafeCollect, + Determinism::Enforced, + ) + .result + .unwrap(); - assert_ok!( - ParachainContracts::bare_call( - ALICE, - contract_addr.clone(), - 0, - Weight::MAX, - None, - (dest, message).encode(), - DebugInfo::UnsafeDebug, - CollectEvents::UnsafeCollect, - Determinism::Enforced, - ) - .result - ); + assert_return_code!(result, RuntimeReturnCode::Success); }); Relay::execute_with(|| { diff --git a/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs b/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs index 09a51c965839..17c0e801cbdf 100644 --- a/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs +++ b/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs @@ -19,10 +19,12 @@ use crate::{ xcm::{CallOf, WeightInfo, XCM}, AccountIdOf, Box, Config, RawOrigin, }; -use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight}; +use frame_support::{ + dispatch::PostDispatchInfo, pallet_prelude::DispatchResultWithPostInfo, weights::Weight, +}; use frame_system::pallet_prelude::BlockNumberFor; use pallet_xcm::WeightInfo as XcmWeightInfo; -use sp_runtime::{DispatchError, DispatchResult}; +use sp_runtime::{DispatchError, DispatchErrorWithPostInfo, DispatchResult}; use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; @@ -59,9 +61,38 @@ where message: VersionedXcm>, max_weight: Weight, ) -> DispatchResultWithPostInfo { + // TODO since we are doing more than just calling pallet_xcm::Pallet::::execute, we + // should benchmark the filtering part + use frame_support::traits::Contains; + use xcm::prelude::{Transact, Xcm}; + + let mut message: Xcm> = + message.try_into().map_err(|_| pallet_xcm::Error::::BadVersion)?; + + message + .iter_mut() + .try_for_each(|inst| -> Result<(), DispatchError> { + let Transact { ref mut call, .. } = inst else { return Ok(()) }; + let call = call.ensure_decoded().map_err(|_| pallet_xcm::Error::::BadVersion)?; + + if !::CallFilter::contains(call) { + return Err(frame_system::Error::::CallFiltered.into()) + } + + Ok(()) + }) + .map_err(|err| DispatchErrorWithPostInfo { + post_info: PostDispatchInfo { + actual_weight: Some(Weight::zero()), + pays_fee: Default::default(), + }, + error: err.into(), + })?; + let origin = RawOrigin::Signed(origin.clone()).into(); - pallet_xcm::Pallet::::execute(origin, Box::new(message), max_weight) + pallet_xcm::Pallet::::execute(origin, Box::new(VersionedXcm::from(message)), max_weight) } + fn send( origin: &AccountIdOf, dest: VersionedMultiLocation, From 43f38d22712062ac0fcf5dba581a0f83aea36683 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Thu, 21 Sep 2023 14:06:47 +0200 Subject: [PATCH 040/115] fmt --- substrate/frame/contracts/src/tests/test_xcm.rs | 3 ++- substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs | 5 +---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index d5a6571c351c..64838b884613 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -134,7 +134,8 @@ fn test_xcm_execute_filtered_call() { let contract_addr = instantiate_test_contract("xcm_execute"); ParaA::execute_with(|| { - // `remark` transact inside the Xcm message should be rejected, as CallFilter is set to `Nothing`. + // `remark` transact inside the Xcm message should be rejected, as CallFilter is set to + // `Nothing`. let call = parachain::RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); let message: Xcm = Xcm(vec![Transact { origin_kind: OriginKind::Native, diff --git a/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs b/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs index 17c0e801cbdf..60c99b761642 100644 --- a/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs +++ b/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs @@ -49,10 +49,7 @@ where } } -impl XCM for PalletXCMAdapter -where - T: pallet_xcm::Config, -{ +impl XCM for PalletXCMAdapter { type QueryId = as QueryHandler>::QueryId; type WeightInfo = Self; From 4583e035222affa9eee174606aee6f514f119f13 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Thu, 21 Sep 2023 14:31:51 +0200 Subject: [PATCH 041/115] move ensure to it's own function for benchmark --- .../contracts/src/xcm/pallet_xcm_adapter.rs | 63 +++++++++++-------- 1 file changed, 36 insertions(+), 27 deletions(-) diff --git a/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs b/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs index 60c99b761642..11a71be0ba98 100644 --- a/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs +++ b/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs @@ -49,6 +49,33 @@ where } } +impl PalletXCMAdapter { + /// Ensure that the message is executable, by checking that it does not contain any Transact + /// instruction with a call that is not allowed by the CallFilter. + fn ensure_executable( + message: VersionedXcm>, + ) -> Result>>, DispatchError> { + use frame_support::traits::Contains; + use xcm::prelude::{Transact, Xcm}; + + let mut message: Xcm> = + message.try_into().map_err(|_| pallet_xcm::Error::::BadVersion)?; + + message.iter_mut().try_for_each(|inst| -> Result<(), DispatchError> { + let Transact { ref mut call, .. } = inst else { return Ok(()) }; + let call = call.ensure_decoded().map_err(|_| pallet_xcm::Error::::BadVersion)?; + + if !::CallFilter::contains(call) { + return Err(frame_system::Error::::CallFiltered.into()) + } + + Ok(()) + })?; + + Ok(Box::new(VersionedXcm::from(message))) + } +} + impl XCM for PalletXCMAdapter { type QueryId = as QueryHandler>::QueryId; type WeightInfo = Self; @@ -59,35 +86,17 @@ impl XCM for PalletXCMAdapter { max_weight: Weight, ) -> DispatchResultWithPostInfo { // TODO since we are doing more than just calling pallet_xcm::Pallet::::execute, we - // should benchmark the filtering part - use frame_support::traits::Contains; - use xcm::prelude::{Transact, Xcm}; - - let mut message: Xcm> = - message.try_into().map_err(|_| pallet_xcm::Error::::BadVersion)?; - - message - .iter_mut() - .try_for_each(|inst| -> Result<(), DispatchError> { - let Transact { ref mut call, .. } = inst else { return Ok(()) }; - let call = call.ensure_decoded().map_err(|_| pallet_xcm::Error::::BadVersion)?; - - if !::CallFilter::contains(call) { - return Err(frame_system::Error::::CallFiltered.into()) - } - - Ok(()) - }) - .map_err(|err| DispatchErrorWithPostInfo { - post_info: PostDispatchInfo { - actual_weight: Some(Weight::zero()), - pays_fee: Default::default(), - }, - error: err.into(), - })?; + // should benchmark this ensure_executable + let msg = Self::ensure_executable(message).map_err(|err| DispatchErrorWithPostInfo { + post_info: PostDispatchInfo { + actual_weight: Some(Weight::zero()), + pays_fee: Default::default(), + }, + error: err.into(), + })?; let origin = RawOrigin::Signed(origin.clone()).into(); - pallet_xcm::Pallet::::execute(origin, Box::new(VersionedXcm::from(message)), max_weight) + pallet_xcm::Pallet::::execute(origin, msg, max_weight) } fn send( From ceb3fc8ec8939843d957f970d7925e2ea1ba9fd4 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Thu, 21 Sep 2023 18:38:46 +0200 Subject: [PATCH 042/115] fix error handling --- .../contracts-rococo/src/contracts.rs | 4 +-- substrate/frame/contracts/src/lib.rs | 2 +- .../parachain/contracts_config.rs | 4 +-- .../frame/contracts/src/tests/test_xcm.rs | 15 ++++++++--- substrate/frame/contracts/src/xcm.rs | 4 +-- .../xcm/{pallet_xcm_adapter.rs => adapter.rs} | 27 ++++++------------- 6 files changed, 26 insertions(+), 30 deletions(-) rename substrate/frame/contracts/src/xcm/{pallet_xcm_adapter.rs => adapter.rs} (81%) diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs index 9eab908625a5..52fdd1eebf75 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs @@ -24,7 +24,7 @@ use frame_support::{ use pallet_contracts::{ migration::{v12, v13, v14, v15}, weights::SubstrateWeight, - xcm::PalletXCMAdapter, + xcm::XCMAdapter, Config, DebugInfo, DefaultAddressGenerator, Frame, Schedule, }; use sp_runtime::Perbill; @@ -80,5 +80,5 @@ impl Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type Debug = (); type Environment = (); - type Xcm = PalletXCMAdapter; + type Xcm = XCMAdapter; } diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index b9aaf42d9e00..de88d0412b39 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -407,7 +407,7 @@ pub mod pallet { /// A type that exposes XCM APIs, allowing contracts to interact with other parachains, and /// execute XCM messages. /// - /// Use [`xcm::PalletXCMAdapter`] to enable or `()` to disable. + /// Use [`xcm::XCMAdapter`] to enable or `()` to disable. type Xcm: XCM; } diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs index 27762c6cd46e..161b2faba8c7 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs @@ -20,7 +20,7 @@ use crate::{ parachain::RuntimeHoldReason, primitives::{Balance, CENTS}, }, - xcm::PalletXCMAdapter, + xcm::XCMAdapter, Config, }; use frame_support::{ @@ -85,5 +85,5 @@ impl Config for Runtime { type WeightPrice = Self; type Debug = (); type Environment = (); - type Xcm = PalletXCMAdapter; + type Xcm = XCMAdapter; } diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 64838b884613..db42013ccd08 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -33,6 +33,7 @@ use crate::{ }; use codec::{Decode, Encode}; use frame_support::{ + assert_err, pallet_prelude::Weight, traits::{fungibles::Mutate, Currency}, }; @@ -153,11 +154,17 @@ fn test_xcm_execute_filtered_call() { DebugInfo::UnsafeDebug, CollectEvents::UnsafeCollect, Determinism::Enforced, - ) - .result - .unwrap(); + ); + + // The debug message should say that the call was filtered. + assert_eq!( + std::str::from_utf8(&result.debug_message).unwrap(), + "call failed with: CallFiltered" + ); - assert_return_code!(result, RuntimeReturnCode::CallRuntimeFailed); + // The call should fail, with an `OutOfGas` error, as the failed xcm::execute will not + // refund the max_weight gas passed to it. + assert_err!(result.result, crate::Error::::OutOfGas); }); } diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 7ac3ca1a8a52..9a62153e8e81 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -23,9 +23,9 @@ use sp_runtime::{DispatchError, DispatchResult}; use xcm::{VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::QueryResponseStatus; -pub mod pallet_xcm_adapter; +pub mod adapter; -pub use pallet_xcm_adapter::PalletXCMAdapter; +pub use adapter::XCMAdapter; pub type CallOf = ::RuntimeCall; pub trait XCM { diff --git a/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs b/substrate/frame/contracts/src/xcm/adapter.rs similarity index 81% rename from substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs rename to substrate/frame/contracts/src/xcm/adapter.rs index 11a71be0ba98..a5fa179d682d 100644 --- a/substrate/frame/contracts/src/xcm/pallet_xcm_adapter.rs +++ b/substrate/frame/contracts/src/xcm/adapter.rs @@ -19,19 +19,17 @@ use crate::{ xcm::{CallOf, WeightInfo, XCM}, AccountIdOf, Box, Config, RawOrigin, }; -use frame_support::{ - dispatch::PostDispatchInfo, pallet_prelude::DispatchResultWithPostInfo, weights::Weight, -}; +use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight}; use frame_system::pallet_prelude::BlockNumberFor; use pallet_xcm::WeightInfo as XcmWeightInfo; -use sp_runtime::{DispatchError, DispatchErrorWithPostInfo, DispatchResult}; +use sp_runtime::{DispatchError, DispatchResult}; use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; /// A pallet-xcm adapter for the XCM trait. -pub struct PalletXCMAdapter(sp_std::marker::PhantomData); +pub struct XCMAdapter(sp_std::marker::PhantomData); -impl WeightInfo for PalletXCMAdapter +impl WeightInfo for XCMAdapter where T: pallet_xcm::Config, { @@ -49,8 +47,8 @@ where } } -impl PalletXCMAdapter { - /// Ensure that the message is executable, by checking that it does not contain any Transact +impl XCMAdapter { + /// Ensure that the message is executable, by checking that it does not contain any [`Transact`] /// instruction with a call that is not allowed by the CallFilter. fn ensure_executable( message: VersionedXcm>, @@ -76,7 +74,7 @@ impl PalletXCMAdapter { } } -impl XCM for PalletXCMAdapter { +impl XCM for XCMAdapter { type QueryId = as QueryHandler>::QueryId; type WeightInfo = Self; @@ -85,16 +83,7 @@ impl XCM for PalletXCMAdapter { message: VersionedXcm>, max_weight: Weight, ) -> DispatchResultWithPostInfo { - // TODO since we are doing more than just calling pallet_xcm::Pallet::::execute, we - // should benchmark this ensure_executable - let msg = Self::ensure_executable(message).map_err(|err| DispatchErrorWithPostInfo { - post_info: PostDispatchInfo { - actual_weight: Some(Weight::zero()), - pays_fee: Default::default(), - }, - error: err.into(), - })?; - + let msg = Self::ensure_executable(message)?; let origin = RawOrigin::Signed(origin.clone()).into(); pallet_xcm::Pallet::::execute(origin, msg, max_weight) } From db7c479149e1a7fffbb9afa956c9f369f97602b2 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 22 Sep 2023 10:17:15 +0200 Subject: [PATCH 043/115] doc fixes --- substrate/frame/contracts/fixtures/xcm_query.wat | 3 +-- substrate/frame/contracts/fixtures/xcm_take_response.wat | 1 - substrate/frame/contracts/src/xcm/adapter.rs | 3 ++- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/substrate/frame/contracts/fixtures/xcm_query.wat b/substrate/frame/contracts/fixtures/xcm_query.wat index de101d7fe16d..9cefe9e75c28 100644 --- a/substrate/frame/contracts/fixtures/xcm_query.wat +++ b/substrate/frame/contracts/fixtures/xcm_query.wat @@ -19,14 +19,13 @@ ;; [0..4) - size of the call ;; [4..12) - timeout ;; [12..49) - match_querier - ;; [8..10) response ;; Just use the call passed as input and store result to memory (i32.store (i32.const 0) (call $xcm_query (i32.const 4) ;; Pointer where the timeout is stored (i32.const 12) ;; Pointer where the match_querier is stored - (i32.const 49) ;; ... + (i32.const 49) ;; Pointer to the where the query_id is stored ) ) (call $seal_return diff --git a/substrate/frame/contracts/fixtures/xcm_take_response.wat b/substrate/frame/contracts/fixtures/xcm_take_response.wat index 3bff75aa7f32..d57da6835fde 100644 --- a/substrate/frame/contracts/fixtures/xcm_take_response.wat +++ b/substrate/frame/contracts/fixtures/xcm_take_response.wat @@ -18,7 +18,6 @@ ;; Input data layout. ;; [0..4) - size of the call ;; [4..12) - query_id - ;; [12..) - response ;; Just use the call passed as input and store result to memory (i32.store (i32.const 0) diff --git a/substrate/frame/contracts/src/xcm/adapter.rs b/substrate/frame/contracts/src/xcm/adapter.rs index a5fa179d682d..c301182fbf3e 100644 --- a/substrate/frame/contracts/src/xcm/adapter.rs +++ b/substrate/frame/contracts/src/xcm/adapter.rs @@ -14,6 +14,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +//! Adapter exposes an implementation of the [`XCM`] trait using pallet-xcm. use crate::{ xcm::{CallOf, WeightInfo, XCM}, @@ -26,7 +27,7 @@ use sp_runtime::{DispatchError, DispatchResult}; use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; -/// A pallet-xcm adapter for the XCM trait. +/// An implementation of the [`XCM`] trait using pallet-xcm. pub struct XCMAdapter(sp_std::marker::PhantomData); impl WeightInfo for XCMAdapter From cd8281ea81333a8778c0821ea8ba098d943feb89 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 22 Sep 2023 10:31:40 +0200 Subject: [PATCH 044/115] fix weight --- substrate/frame/contracts/src/wasm/runtime.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index d1b1526a0b31..70fcc85c26c9 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2676,13 +2676,17 @@ pub mod env { let message: VersionedXcm> = ctx.read_sandbox_memory_as_unbounded(memory, msg_ptr, msg_len)?; - let max_weight = ctx.ext.gas_meter().gas_left(); - let max_weight = - max_weight.max(<::Xcm as XCM>::WeightInfo::execute()); - let dispatch_info = DispatchInfo { weight: max_weight, ..Default::default() }; + let gas_left = ctx.ext.gas_meter().gas_left(); + let execute_weight = <::Xcm as XCM>::WeightInfo::execute(); + let dispatch_info = + DispatchInfo { weight: gas_left.max(execute_weight), ..Default::default() }; ctx.call_dispatchable(dispatch_info, |ext| { - <::Xcm as XCM>::execute(ext.address(), message, max_weight) + <::Xcm as XCM>::execute( + ext.address(), + message, + gas_left.saturating_sub(execute_weight), + ) }) } From c00490905cf8f0fad3dae1aaaa6c4e81c6168bf3 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 22 Sep 2023 10:35:17 +0200 Subject: [PATCH 045/115] improve weight --- substrate/frame/contracts/src/wasm/runtime.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 70fcc85c26c9..8732a828908a 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2676,16 +2676,15 @@ pub mod env { let message: VersionedXcm> = ctx.read_sandbox_memory_as_unbounded(memory, msg_ptr, msg_len)?; - let gas_left = ctx.ext.gas_meter().gas_left(); let execute_weight = <::Xcm as XCM>::WeightInfo::execute(); - let dispatch_info = - DispatchInfo { weight: gas_left.max(execute_weight), ..Default::default() }; + let weight = ctx.ext.gas_meter().gas_left().max(execute_weight); + let dispatch_info = DispatchInfo { weight, ..Default::default() }; ctx.call_dispatchable(dispatch_info, |ext| { <::Xcm as XCM>::execute( ext.address(), message, - gas_left.saturating_sub(execute_weight), + weight.saturating_sub(execute_weight), ) }) } From 526abbd8a5e8db44f2e9e8aee3b70fdabeceef66 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 25 Sep 2023 09:18:21 +0200 Subject: [PATCH 046/115] XCMAdapter -> XcmAdapter --- .../runtimes/contracts/contracts-rococo/src/contracts.rs | 4 ++-- .../src/tests/mock_network/parachain/contracts_config.rs | 4 ++-- substrate/frame/contracts/src/xcm.rs | 2 +- substrate/frame/contracts/src/xcm/adapter.rs | 8 ++++---- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs index 52fdd1eebf75..edb86a9eb5e7 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs @@ -24,7 +24,7 @@ use frame_support::{ use pallet_contracts::{ migration::{v12, v13, v14, v15}, weights::SubstrateWeight, - xcm::XCMAdapter, + xcm::XcmAdapter, Config, DebugInfo, DefaultAddressGenerator, Frame, Schedule, }; use sp_runtime::Perbill; @@ -80,5 +80,5 @@ impl Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type Debug = (); type Environment = (); - type Xcm = XCMAdapter; + type Xcm = XcmAdapter; } diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs index 161b2faba8c7..d31ea73ede6d 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs @@ -20,7 +20,7 @@ use crate::{ parachain::RuntimeHoldReason, primitives::{Balance, CENTS}, }, - xcm::XCMAdapter, + xcm::XcmAdapter, Config, }; use frame_support::{ @@ -85,5 +85,5 @@ impl Config for Runtime { type WeightPrice = Self; type Debug = (); type Environment = (); - type Xcm = XCMAdapter; + type Xcm = XcmAdapter; } diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 9a62153e8e81..8bcebb0e7b8e 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -25,7 +25,7 @@ use xcm_executor::traits::QueryResponseStatus; pub mod adapter; -pub use adapter::XCMAdapter; +pub use adapter::XcmAdapter; pub type CallOf = ::RuntimeCall; pub trait XCM { diff --git a/substrate/frame/contracts/src/xcm/adapter.rs b/substrate/frame/contracts/src/xcm/adapter.rs index c301182fbf3e..3029a9cf4bba 100644 --- a/substrate/frame/contracts/src/xcm/adapter.rs +++ b/substrate/frame/contracts/src/xcm/adapter.rs @@ -28,9 +28,9 @@ use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; /// An implementation of the [`XCM`] trait using pallet-xcm. -pub struct XCMAdapter(sp_std::marker::PhantomData); +pub struct XcmAdapter(sp_std::marker::PhantomData); -impl WeightInfo for XCMAdapter +impl WeightInfo for XcmAdapter where T: pallet_xcm::Config, { @@ -48,7 +48,7 @@ where } } -impl XCMAdapter { +impl XcmAdapter { /// Ensure that the message is executable, by checking that it does not contain any [`Transact`] /// instruction with a call that is not allowed by the CallFilter. fn ensure_executable( @@ -75,7 +75,7 @@ impl XCMAdapter { } } -impl XCM for XCMAdapter { +impl XCM for XcmAdapter { type QueryId = as QueryHandler>::QueryId; type WeightInfo = Self; From 0a98a8991e01fbd35c0c4a98dbfa89bf75dfc06a Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 25 Sep 2023 09:19:23 +0200 Subject: [PATCH 047/115] XCM -> Xcm --- substrate/frame/contracts/src/lib.rs | 4 +-- .../frame/contracts/src/tests/test_xcm.rs | 4 +-- substrate/frame/contracts/src/wasm/runtime.rs | 28 +++++++++---------- substrate/frame/contracts/src/xcm.rs | 4 +-- substrate/frame/contracts/src/xcm/adapter.rs | 4 +-- 5 files changed, 22 insertions(+), 22 deletions(-) diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index de88d0412b39..f8b2e430c85f 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -108,7 +108,7 @@ use crate::{ gas::GasMeter, storage::{meter::Meter as StorageMeter, ContractInfo, DeletionQueueManager}, wasm::{CodeInfo, WasmBlob}, - xcm::XCM, + xcm::Xcm, }; use codec::{Codec, Decode, Encode, HasCompact, MaxEncodedLen}; use environmental::*; @@ -408,7 +408,7 @@ pub mod pallet { /// execute XCM messages. /// /// Use [`xcm::XCMAdapter`] to enable or `()` to disable. - type Xcm: XCM; + type Xcm: Xcm; } #[pallet::hooks] diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index db42013ccd08..e6641193118d 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -28,7 +28,7 @@ use crate::{ }, RuntimeReturnCode, }, - xcm::XCM, + xcm::Xcm, CollectEvents, DebugInfo, Determinism, }; use codec::{Decode, Encode}; @@ -45,7 +45,7 @@ use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; use xcm_simulator::TestExt; type ParachainContracts = crate::Pallet; -type QueryId = <::Xcm as XCM>::QueryId; +type QueryId = <::Xcm as Xcm>::QueryId; /// Instantiate the tests contract, and fund it with some balance and assets. fn instantiate_test_contract(name: &str) -> AccountId { diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 8732a828908a..261549ac7398 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -1057,7 +1057,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { // for every function. #[define_env(doc)] pub mod env { - use crate::xcm::XCM; + use crate::xcm::Xcm; /// Set the value at the given key in the contract storage. /// @@ -2668,7 +2668,7 @@ pub mod env { msg_ptr: u32, msg_len: u32, ) -> Result { - use crate::xcm::{CallOf, WeightInfo, XCM}; + use crate::xcm::{CallOf, WeightInfo, Xcm}; use frame_support::dispatch::DispatchInfo; use xcm::VersionedXcm; @@ -2676,12 +2676,12 @@ pub mod env { let message: VersionedXcm> = ctx.read_sandbox_memory_as_unbounded(memory, msg_ptr, msg_len)?; - let execute_weight = <::Xcm as XCM>::WeightInfo::execute(); + let execute_weight = <::Xcm as Xcm>::WeightInfo::execute(); let weight = ctx.ext.gas_meter().gas_left().max(execute_weight); let dispatch_info = DispatchInfo { weight, ..Default::default() }; ctx.call_dispatchable(dispatch_info, |ext| { - <::Xcm as XCM>::execute( + <::Xcm as Xcm>::execute( ext.address(), message, weight.saturating_sub(execute_weight), @@ -2712,7 +2712,7 @@ pub mod env { call_ptr: u32, call_len: u32, ) -> Result { - use crate::xcm::{WeightInfo, XCM}; + use crate::xcm::{WeightInfo, Xcm}; use xcm::{VersionedMultiLocation, VersionedXcm}; ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; @@ -2720,10 +2720,10 @@ pub mod env { let message: VersionedXcm<()> = ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; - let weight = <::Xcm as XCM>::WeightInfo::send(); + let weight = <::Xcm as Xcm>::WeightInfo::send(); ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; - match <::Xcm as XCM>::send(ctx.ext.address(), dest, message) { + match <::Xcm as Xcm>::send(ctx.ext.address(), dest, message) { Ok(_) => Ok(ReturnCode::Success), Err(e) => { if ctx.ext.append_debug_buffer("") { @@ -2755,7 +2755,7 @@ pub mod env { match_querier_ptr: u32, output_ptr: u32, ) -> Result { - use crate::xcm::{WeightInfo, XCM}; + use crate::xcm::{WeightInfo, Xcm}; use frame_system::pallet_prelude::BlockNumberFor; use xcm::VersionedMultiLocation; @@ -2763,10 +2763,10 @@ pub mod env { let match_querier: VersionedMultiLocation = ctx.read_sandbox_memory_as(memory, match_querier_ptr)?; - let weight = <::Xcm as XCM>::WeightInfo::query(); + let weight = <::Xcm as Xcm>::WeightInfo::query(); ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; - match <::Xcm as XCM>::query(ctx.ext.address(), timeout, match_querier) + match <::Xcm as Xcm>::query(ctx.ext.address(), timeout, match_querier) { Ok(query_id) => { ctx.write_sandbox_memory(memory, output_ptr, &query_id.encode())?; @@ -2800,15 +2800,15 @@ pub mod env { query_id_ptr: u32, output_ptr: u32, ) -> Result { - use crate::xcm::{WeightInfo, XCM}; + use crate::xcm::{WeightInfo, Xcm}; - let query_id: <::Xcm as XCM>::QueryId = + let query_id: <::Xcm as Xcm>::QueryId = ctx.read_sandbox_memory_as(memory, query_id_ptr)?; - let weight = <::Xcm as XCM>::WeightInfo::take_response(); + let weight = <::Xcm as Xcm>::WeightInfo::take_response(); ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; // - let response = <::Xcm as XCM>::take_response(query_id); + let response = <::Xcm as Xcm>::take_response(query_id); ctx.write_sandbox_memory(memory, output_ptr, &response.encode())?; Ok(ReturnCode::Success) } diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 8bcebb0e7b8e..7b390ce0ebb7 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -28,7 +28,7 @@ pub mod adapter; pub use adapter::XcmAdapter; pub type CallOf = ::RuntimeCall; -pub trait XCM { +pub trait Xcm { type QueryId: Encode + Decode + MaxEncodedLen; type WeightInfo: WeightInfo; @@ -81,7 +81,7 @@ pub trait XCM { fn take_response(query_id: Self::QueryId) -> QueryResponseStatus>; } -impl XCM for () { +impl Xcm for () { type QueryId = (); type WeightInfo = Self; fn execute( diff --git a/substrate/frame/contracts/src/xcm/adapter.rs b/substrate/frame/contracts/src/xcm/adapter.rs index 3029a9cf4bba..44f19bf30434 100644 --- a/substrate/frame/contracts/src/xcm/adapter.rs +++ b/substrate/frame/contracts/src/xcm/adapter.rs @@ -17,7 +17,7 @@ //! Adapter exposes an implementation of the [`XCM`] trait using pallet-xcm. use crate::{ - xcm::{CallOf, WeightInfo, XCM}, + xcm::{CallOf, WeightInfo, Xcm}, AccountIdOf, Box, Config, RawOrigin, }; use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight}; @@ -75,7 +75,7 @@ impl XcmAdapter { } } -impl XCM for XcmAdapter { +impl Xcm for XcmAdapter { type QueryId = as QueryHandler>::QueryId; type WeightInfo = Self; From 1d1f40a4485743ae84af789b41c9f4ad91fd54cd Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Mon, 25 Sep 2023 09:20:23 +0200 Subject: [PATCH 048/115] Update substrate/frame/contracts/src/xcm.rs Co-authored-by: Keith Yeung --- substrate/frame/contracts/src/xcm.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 7b390ce0ebb7..c3bf0854eea5 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -32,7 +32,7 @@ pub trait Xcm { type QueryId: Encode + Decode + MaxEncodedLen; type WeightInfo: WeightInfo; - /// Execute an XCM message locally. see [`pallet_xcm::pallet::Pallet::execute`] + /// Execute an XCM locally. see [`pallet_xcm::pallet::Pallet::execute`] /// /// # Parameters /// From e01cb2c63fb552cca3e2fafd7a96a6543afe4f5f Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Mon, 25 Sep 2023 09:20:34 +0200 Subject: [PATCH 049/115] Update substrate/frame/contracts/src/xcm.rs Co-authored-by: Keith Yeung --- substrate/frame/contracts/src/xcm.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index c3bf0854eea5..0872fc771d24 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -37,7 +37,7 @@ pub trait Xcm { /// # Parameters /// /// - `origin`: the origin of the call. - /// - `message`: the XCM message to be executed. + /// - `message`: the XCM program to be executed. /// - `max_weight`: the maximum weight that can be consumed by the execution. fn execute( origin: &AccountIdOf, From 2c7735b457c59a230e81c9b9d3123b1bb34cf163 Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Mon, 25 Sep 2023 09:20:44 +0200 Subject: [PATCH 050/115] Update substrate/frame/contracts/src/xcm.rs Co-authored-by: Keith Yeung --- substrate/frame/contracts/src/xcm.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 0872fc771d24..665a8baa9bd5 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -45,7 +45,7 @@ pub trait Xcm { max_weight: Weight, ) -> DispatchResultWithPostInfo; - /// Send an XCM message to be executed by a remote location. see + /// Send an XCM to be executed by a remote location. see /// [`pallet_xcm::pallet::Pallet::send`] /// /// # Parameters From 4e3de866819e710ad8d07047418d87337b15e2fd Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Mon, 25 Sep 2023 09:20:55 +0200 Subject: [PATCH 051/115] Update substrate/frame/contracts/src/xcm.rs Co-authored-by: Keith Yeung --- substrate/frame/contracts/src/xcm.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 665a8baa9bd5..7f2888a99856 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -52,7 +52,7 @@ pub trait Xcm { /// /// - `origin`: the origin of the call. /// - `dest`: the destination of the message. - /// - `msg`: the XCM message to be sent. + /// - `msg`: the XCM to be sent. fn send( origin: &AccountIdOf, dest: VersionedMultiLocation, From e52f85fcdf9c37cb0c20446efe42fa1033df9eb7 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 25 Sep 2023 09:36:41 +0200 Subject: [PATCH 052/115] s/xcm message/message --- .../frame/contracts/fixtures/xcm_execute.wat | 6 +++--- substrate/frame/contracts/fixtures/xcm_send.wat | 6 +++--- substrate/frame/contracts/src/lib.rs | 2 +- .../src/tests/mock_network/relay_chain.rs | 1 - substrate/frame/contracts/src/tests/test_xcm.rs | 4 ++-- substrate/frame/contracts/src/wasm/runtime.rs | 16 ++++++++-------- 6 files changed, 17 insertions(+), 18 deletions(-) diff --git a/substrate/frame/contracts/fixtures/xcm_execute.wat b/substrate/frame/contracts/fixtures/xcm_execute.wat index 4ff7ef26c87d..7f8b78b21269 100644 --- a/substrate/frame/contracts/fixtures/xcm_execute.wat +++ b/substrate/frame/contracts/fixtures/xcm_execute.wat @@ -17,13 +17,13 @@ ) ;; Input data layout. ;; [0..4) - size of the call - ;; [4..) - xcm message + ;; [4..) - message ;; Just use the call passed as input and store result to memory (i32.store (i32.const 0) (call $xcm_execute - (i32.const 4) ;; Pointer where the xcm msg is stored - (i32.load (i32.const 0)) ;; Size of the xcm msg + (i32.const 4) ;; Pointer where the message is stored + (i32.load (i32.const 0)) ;; Size of the message ) ) (call $seal_return diff --git a/substrate/frame/contracts/fixtures/xcm_send.wat b/substrate/frame/contracts/fixtures/xcm_send.wat index 701918651d25..50f6b7c4ffbf 100644 --- a/substrate/frame/contracts/fixtures/xcm_send.wat +++ b/substrate/frame/contracts/fixtures/xcm_send.wat @@ -18,14 +18,14 @@ ;; Input data layout. ;; [0..4) - size of the call ;; [4..7) - dest - ;; [7..) - xcm message + ;; [7..) - message ;; Just use the call passed as input and store result to memory (i32.store (i32.const 0) (call $xcm_send (i32.const 4) ;; Pointer where the dest is stored - (i32.const 7) ;; Pointer where the xcm msg is stored - (i32.sub ;; Size of the xcm msg + (i32.const 7) ;; Pointer where the message is stored + (i32.sub ;; Size of the message (i32.load (i32.const 0)) (i32.const 3) ) diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index f8b2e430c85f..7ae2b57bf7e0 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -405,7 +405,7 @@ pub mod pallet { type Environment: Get>; /// A type that exposes XCM APIs, allowing contracts to interact with other parachains, and - /// execute XCM messages. + /// execute XCM program. /// /// Use [`xcm::XCMAdapter`] to enable or `()` to disable. type Xcm: Xcm; diff --git a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs index 0d0e7681bc04..c755cbbfac15 100644 --- a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs @@ -193,7 +193,6 @@ 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 = Everything; type XcmExecutor = XcmExecutor; diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index e6641193118d..233f219f6c85 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -135,7 +135,7 @@ fn test_xcm_execute_filtered_call() { let contract_addr = instantiate_test_contract("xcm_execute"); ParaA::execute_with(|| { - // `remark` transact inside the Xcm message should be rejected, as CallFilter is set to + // `remark` transact inside the Xcm should be rejected, as CallFilter is set to // `Nothing`. let call = parachain::RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); let message: Xcm = Xcm(vec![Transact { @@ -283,7 +283,7 @@ fn test_xcm_take_response() { // Query is not yet answered. assert_eq!(QueryResponseStatus::Pending { timeout: 1u32.into() }, call(query_id)); - // Execute the XCM message that answers the query. + // Execute the XCM program that answers the query. let fee = parachain::estimate_message_fee(4); let message = Xcm(vec![ WithdrawAsset(vec![(Parent, fee).into()].into()), diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 261549ac7398..34de3bf9ea70 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2648,18 +2648,18 @@ pub mod env { ctx.call_dispatchable(call.get_dispatch_info(), |ext| ext.call_runtime(call)) } - /// Execute an XCM message locally, using the contract's address as the origin. + /// Execute an XCM program locally, using the contract's address as the origin. /// This is equivalent to dispatching `pallet_xcm::execute` through call_runtime, except that /// the function is called directly instead of being dispatched. /// /// # Parameters /// - /// - `msg_ptr`: the pointer into the linear memory where the XCM message is placed. - /// - `msg_len`: the length of the XCM message in bytes. + /// - `msg_ptr`: the pointer into the linear memory where the message is placed. + /// - `msg_len`: the length of the message in bytes. /// /// # Return Value /// - /// Returns `ReturnCode::Success` when the XCM message was successfully executed. When the XCM + /// Returns `ReturnCode::Success` when the XCM was successfully executed. When the XCM /// execution fails, `ReturnCode::CallRuntimeFailed` is returned. #[unstable] fn xcm_execute( @@ -2689,7 +2689,7 @@ pub mod env { }) } - /// Send an XCM message from the contract to the specified destination. + /// Send an XCM program from the contract to the specified destination. /// This is equivalent to dispatching `pallet_xcm::send` through call_runtime, except that /// the function is called directly instead of being dispatched. /// @@ -2697,12 +2697,12 @@ pub mod env { /// /// - `dest_ptr`: the pointer into the linear memory where the [`xcm::VersionedMultiLocation`] /// is placed. - /// - `msg_ptr`: the pointer into the linear memory where the XCM message is placed. - /// - `msg_len`: the length of the XCM message in bytes. + /// - `msg_ptr`: the pointer into the linear memory where the message is placed. + /// - `msg_len`: the length of the message in bytes. /// /// # Return Value /// - /// Returns `ReturnCode::Success` when the XCM message was successfully sent. When the XCM + /// Returns `ReturnCode::Success` when the message was successfully sent. When the XCM /// execution fails, `ReturnCode::CallRuntimeFailed` is returned. #[unstable] fn xcm_send( From d78ec479636634554961bf9485b1c6db90f79707 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 25 Sep 2023 09:38:17 +0200 Subject: [PATCH 053/115] typo --- substrate/frame/contracts/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 7ae2b57bf7e0..5d2d3e0e3767 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -405,7 +405,7 @@ pub mod pallet { type Environment: Get>; /// A type that exposes XCM APIs, allowing contracts to interact with other parachains, and - /// execute XCM program. + /// execute XCM programs. /// /// Use [`xcm::XCMAdapter`] to enable or `()` to disable. type Xcm: Xcm; From 435de45c5304c7ebe0c9f22036dd4f1f38e0d1f2 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Wed, 27 Sep 2023 14:20:16 +0200 Subject: [PATCH 054/115] fix build issues --- substrate/frame/contracts/src/lib.rs | 2 +- substrate/frame/contracts/src/tests/test_xcm.rs | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 5d2d3e0e3767..23de8a582c6d 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -407,7 +407,7 @@ pub mod pallet { /// A type that exposes XCM APIs, allowing contracts to interact with other parachains, and /// execute XCM programs. /// - /// Use [`xcm::XCMAdapter`] to enable or `()` to disable. + /// Use [`xcm::XcmAdapter`] to enable or `()` to disable. type Xcm: Xcm; } diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 233f219f6c85..5bec89dbdc12 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -28,7 +28,6 @@ use crate::{ }, RuntimeReturnCode, }, - xcm::Xcm, CollectEvents, DebugInfo, Determinism, }; use codec::{Decode, Encode}; @@ -45,7 +44,7 @@ use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; use xcm_simulator::TestExt; type ParachainContracts = crate::Pallet; -type QueryId = <::Xcm as Xcm>::QueryId; +type QueryId = <::Xcm as crate::Xcm>::QueryId; /// Instantiate the tests contract, and fund it with some balance and assets. fn instantiate_test_contract(name: &str) -> AccountId { From c4d87ff42be74aab641b8e826e52d0d6ffd99fbb Mon Sep 17 00:00:00 2001 From: pgherveou Date: Wed, 27 Sep 2023 14:33:53 +0200 Subject: [PATCH 055/115] fix fmt --- substrate/frame/contracts/src/tests/test_xcm.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 5bec89dbdc12..19def2289b66 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -44,7 +44,8 @@ use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; use xcm_simulator::TestExt; type ParachainContracts = crate::Pallet; -type QueryId = <::Xcm as crate::Xcm>::QueryId; +type QueryId = + <::Xcm as crate::Xcm>::QueryId; /// Instantiate the tests contract, and fund it with some balance and assets. fn instantiate_test_contract(name: &str) -> AccountId { From 4363e6d9ad5890622bce495a5c15f8d99a96e63b Mon Sep 17 00:00:00 2001 From: pgherveou Date: Wed, 27 Sep 2023 15:36:10 +0200 Subject: [PATCH 056/115] More doc fix changes --- .../src/tests/mock_network/mocks/msg_queue.rs | 1 - substrate/frame/contracts/src/wasm/runtime.rs | 2 -- substrate/frame/contracts/src/xcm.rs | 10 +++++----- substrate/frame/contracts/src/xcm/adapter.rs | 4 ++-- 4 files changed, 7 insertions(+), 10 deletions(-) diff --git a/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs b/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs index 6fe79b129c08..82fb8590e269 100644 --- a/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs +++ b/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs @@ -66,7 +66,6 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - // XCMP /// Some XCM was executed OK. Success(Option), /// Some XCM failed. diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 34de3bf9ea70..134bf96c354e 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -40,8 +40,6 @@ use sp_runtime::{ use sp_std::{fmt, prelude::*}; use wasmi::{core::HostError, errors::LinkerError, Linker, Memory, Store}; -// type XcmOf = <::Xcm as XCM>; - /// The maximum nesting depth a contract can use when encoding types. const MAX_DECODE_NESTING: u32 = 256; diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs index 7f2888a99856..bb7964cce1c3 100644 --- a/substrate/frame/contracts/src/xcm.rs +++ b/substrate/frame/contracts/src/xcm.rs @@ -110,15 +110,15 @@ impl Xcm for () { } } -/// Weight info trait for methods exposed by the [`XCM`] trait. +/// Weight info trait for methods exposed by the [`Xcm`] trait. pub trait WeightInfo { - /// Weight of the [`XCM::execute`] function. + /// Weight of the [`Xcm::execute`] function. fn execute() -> Weight; - /// Weight of the [`XCM::send`] function. + /// Weight of the [`Xcm::send`] function. fn send() -> Weight; - /// Weight of the [`XCM::query`] function. + /// Weight of the [`Xcm::query`] function. fn query() -> Weight; - /// Weight of the [`XCM::take_response`] function. + /// Weight of the [`Xcm::take_response`] function. fn take_response() -> Weight; } diff --git a/substrate/frame/contracts/src/xcm/adapter.rs b/substrate/frame/contracts/src/xcm/adapter.rs index 44f19bf30434..74214eaca8c0 100644 --- a/substrate/frame/contracts/src/xcm/adapter.rs +++ b/substrate/frame/contracts/src/xcm/adapter.rs @@ -14,7 +14,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -//! Adapter exposes an implementation of the [`XCM`] trait using pallet-xcm. +//! Adapter exposes an implementation of the [`Xcm`] trait using pallet-xcm. use crate::{ xcm::{CallOf, WeightInfo, Xcm}, @@ -27,7 +27,7 @@ use sp_runtime::{DispatchError, DispatchResult}; use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; -/// An implementation of the [`XCM`] trait using pallet-xcm. +/// An implementation of the [`Xcm`] trait using pallet-xcm. pub struct XcmAdapter(sp_std::marker::PhantomData); impl WeightInfo for XcmAdapter From ac39a5001f99a44881cf4dd61ba5b0e0ccb97c0f Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Fri, 29 Sep 2023 21:41:19 +0200 Subject: [PATCH 057/115] Apply suggestions from code review Co-authored-by: Sasha Gryaznov --- substrate/frame/contracts/src/wasm/runtime.rs | 9 +++------ substrate/frame/contracts/src/xcm/adapter.rs | 1 + 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 134bf96c354e..e199dbae775e 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -118,8 +118,6 @@ pub enum ReturnCode { Sr25519VerifyFailed = 12, /// The `seal_xcm_query` was executed but returned an error. XcmQueryFailed = 13, - /// The `seal_xcm_take_response` was executed but returned an error. - XcmTakeResponseFailed = 14, } impl From for ReturnCode { @@ -2695,9 +2693,8 @@ pub mod env { /// /// - `dest_ptr`: the pointer into the linear memory where the [`xcm::VersionedMultiLocation`] /// is placed. - /// - `msg_ptr`: the pointer into the linear memory where the message is placed. - /// - `msg_len`: the length of the message in bytes. - /// + /// - `call_ptr`: the pointer into the linear memory where the message is placed. + /// - `call_len`: the length of the message in bytes. /// # Return Value /// /// Returns `ReturnCode::Success` when the message was successfully sent. When the XCM @@ -2790,7 +2787,7 @@ pub mod env { /// /// # Return Value /// - /// Returns `ReturnCode::Success` when successful, `ReturnCode::TakeResponseFailed` otherwise. + /// Returns `ReturnCode::Success` when successful. #[unstable] fn xcm_take_response( ctx: _, diff --git a/substrate/frame/contracts/src/xcm/adapter.rs b/substrate/frame/contracts/src/xcm/adapter.rs index 74214eaca8c0..b8b3031f5d96 100644 --- a/substrate/frame/contracts/src/xcm/adapter.rs +++ b/substrate/frame/contracts/src/xcm/adapter.rs @@ -14,6 +14,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + //! Adapter exposes an implementation of the [`Xcm`] trait using pallet-xcm. use crate::{ From 0bf6e1ab48f2a3918a95e6001da618a2ef0ed750 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 29 Sep 2023 22:39:32 +0200 Subject: [PATCH 058/115] address PR comments --- substrate/frame/contracts/fixtures/xcm_send.wat | 2 +- substrate/frame/contracts/src/wasm/runtime.rs | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/substrate/frame/contracts/fixtures/xcm_send.wat b/substrate/frame/contracts/fixtures/xcm_send.wat index 50f6b7c4ffbf..d818447f58b1 100644 --- a/substrate/frame/contracts/fixtures/xcm_send.wat +++ b/substrate/frame/contracts/fixtures/xcm_send.wat @@ -27,7 +27,7 @@ (i32.const 7) ;; Pointer where the message is stored (i32.sub ;; Size of the message (i32.load (i32.const 0)) - (i32.const 3) + (i32.const 3) ;; Size of the XCM dest ) ) ) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index e199dbae775e..3e36bee6be6b 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -1053,7 +1053,6 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { // for every function. #[define_env(doc)] pub mod env { - use crate::xcm::Xcm; /// Set the value at the given key in the contract storage. /// From ddf485ad50c9308ebc7df6770f496402994c6c1c Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 9 Oct 2023 18:29:36 +0200 Subject: [PATCH 059/115] Add reentrency test --- .../src/tests/mock_network/parachain.rs | 22 ++++++-- .../parachain/contracts_config.rs | 17 +++++- .../frame/contracts/src/tests/test_xcm.rs | 52 ++++++++++++++++++- 3 files changed, 82 insertions(+), 9 deletions(-) diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain.rs b/substrate/frame/contracts/src/tests/mock_network/parachain.rs index 159e67e9306d..d5a88e598a2c 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain.rs @@ -231,14 +231,26 @@ impl Contains for ParentRelay { location.contains_parents_only(1) } } +pub struct ThisParachain; +impl Contains for ThisParachain { + fn contains(location: &MultiLocation) -> bool { + matches!( + location, + MultiLocation { parents: 0, interior: Junctions::X1(Junction::AccountId32 { .. }) } + ) + } +} pub type XcmRouter = crate::tests::mock_network::ParachainXcmRouter; -pub type Barrier = WithComputedOrigin< - (AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom), - UniversalLocation, - ConstU32<1>, ->; +pub type Barrier = ( + xcm_builder::AllowUnpaidExecutionFrom, + WithComputedOrigin< + (AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom), + UniversalLocation, + ConstU32<1>, + >, +); parameter_types! { pub NftCollectionOne: MultiAssetFilter diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs index d31ea73ede6d..38491f47f078 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs @@ -17,6 +17,7 @@ use super::{Balances, Runtime, RuntimeCall, RuntimeEvent}; use crate::{ tests::mock_network::{ + parachain, parachain::RuntimeHoldReason, primitives::{Balance, CENTS}, }, @@ -25,7 +26,7 @@ use crate::{ }; use frame_support::{ parameter_types, - traits::{ConstBool, ConstU32, Nothing, Randomness}, + traits::{ConstBool, ConstU32, Contains, Randomness}, weights::Weight, }; use frame_system::pallet_prelude::BlockNumberFor; @@ -59,9 +60,21 @@ impl Convert> for Runtime { } } +#[derive(Clone, Default)] +pub struct Filters; + +impl Contains for Filters { + fn contains(call: &RuntimeCall) -> bool { + match call { + parachain::RuntimeCall::Contracts(_) => true, + _ => false, + } + } +} + impl Config for Runtime { type AddressGenerator = crate::DefaultAddressGenerator; - type CallFilter = Nothing; + type CallFilter = Filters; type CallStack = [crate::Frame; 5]; type ChainExtension = (); type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 19def2289b66..2db5c75e6893 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -135,8 +135,7 @@ fn test_xcm_execute_filtered_call() { let contract_addr = instantiate_test_contract("xcm_execute"); ParaA::execute_with(|| { - // `remark` transact inside the Xcm should be rejected, as CallFilter is set to - // `Nothing`. + // `remark` should be rejected, as CallFilter is not allowed by our CallFilter. let call = parachain::RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); let message: Xcm = Xcm(vec![Transact { origin_kind: OriginKind::Native, @@ -168,6 +167,55 @@ fn test_xcm_execute_filtered_call() { }); } +#[test] +fn test_xcm_execute_reentrant_call() { + MockNet::reset(); + + let contract_addr = instantiate_test_contract("xcm_execute"); + + ParaA::execute_with(|| { + let transact_call = parachain::RuntimeCall::Contracts(crate::Call::call { + dest: contract_addr.clone(), + gas_limit: 1_000_000.into(), + storage_deposit_limit: None, + data: vec![], + value: 0u128, + }); + + let message: Xcm = Xcm(vec![ + Transact { + origin_kind: OriginKind::Native, + require_weight_at_most: 1_000_000_000.into(), + call: transact_call.encode().into(), + }, + ExpectTransactStatus(MaybeErrorCode::Success), + ]); + + ParachainContracts::bare_call( + ALICE, + contract_addr.clone(), + 0, + Weight::MAX, + None, + VersionedXcm::V3(message).encode(), + DebugInfo::UnsafeDebug, + CollectEvents::UnsafeCollect, + Determinism::Enforced, + ); + + // assert that the Transact failed + // use crate::tests::{test_xcm::Outcome::Incomplete}; + assert!(parachain::System::events().iter().any(|r| { + matches!( + r.event, + parachain::RuntimeEvent::PolkadotXcm(pallet_xcm::Event::Attempted { + outcome: Outcome::Incomplete(_, XcmError::ExpectationFalse) + }), + ) + })); + }); +} + #[test] fn test_xcm_send() { MockNet::reset(); From 975ef56e776333f1907e12939454adb4e2789adf Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 9 Oct 2023 23:56:28 +0200 Subject: [PATCH 060/115] Simplify tests --- .../frame/contracts/src/tests/test_xcm.rs | 23 +++++++------------ 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 2db5c75e6893..b9063f627b80 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -91,12 +91,9 @@ fn test_xcm_execute() { // Execute XCM instructions through the contract. ParaA::execute_with(|| { let amount: u128 = 10 * CENTS; - let fee = parachain::estimate_message_fee(4); // The XCM used to transfer funds to Bob. let message: xcm_simulator::Xcm<()> = Xcm(vec![ - WithdrawAsset(vec![(Parent, fee).into()].into()), - BuyExecution { fees: (Parent, fee).into(), weight_limit: WeightLimit::Unlimited }, WithdrawAsset(vec![(Here, amount).into()].into()), DepositAsset { assets: All.into(), @@ -123,7 +120,7 @@ fn test_xcm_execute() { // Check if the funds are subtracted from the account of Alice and added to the account of // Bob. let initial = INITIAL_BALANCE; - assert_eq!(parachain::Assets::balance(0, contract_addr), initial - fee); + assert_eq!(parachain::Assets::balance(0, contract_addr), initial); assert_eq!(ParachainBalances::free_balance(BOB), initial + amount); }); } @@ -182,6 +179,7 @@ fn test_xcm_execute_reentrant_call() { value: 0u128, }); + // The XCM used to transfer funds to Bob. let message: Xcm = Xcm(vec![ Transact { origin_kind: OriginKind::Native, @@ -332,17 +330,12 @@ fn test_xcm_take_response() { assert_eq!(QueryResponseStatus::Pending { timeout: 1u32.into() }, call(query_id)); // Execute the XCM program that answers the query. - let fee = parachain::estimate_message_fee(4); - let message = Xcm(vec![ - WithdrawAsset(vec![(Parent, fee).into()].into()), - BuyExecution { fees: (Parent, fee).into(), weight_limit: WeightLimit::Unlimited }, - QueryResponse { - query_id, - response: Response::ExecutionResult(None), - max_weight: Weight::zero(), - querier: Some(querier), - }, - ]); + let message = Xcm(vec![QueryResponse { + query_id, + response: Response::ExecutionResult(None), + max_weight: Weight::zero(), + querier: Some(querier), + }]); ParachainPalletXcm::execute( RuntimeOrigin::signed(ALICE), Box::new(VersionedXcm::V3(message)), From 448c9d4515dfedeed4b80a336c9a529dddddb813 Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Tue, 24 Oct 2023 09:33:48 +0200 Subject: [PATCH 061/115] Apply suggestions from code review Co-authored-by: Sasha Gryaznov --- substrate/frame/contracts/fixtures/xcm_execute.wat | 4 ++-- substrate/frame/contracts/fixtures/xcm_query.wat | 9 +++------ substrate/frame/contracts/fixtures/xcm_send.wat | 4 +--- substrate/frame/contracts/fixtures/xcm_take_response.wat | 4 ---- substrate/frame/contracts/src/wasm/runtime.rs | 5 +++-- 5 files changed, 9 insertions(+), 17 deletions(-) diff --git a/substrate/frame/contracts/fixtures/xcm_execute.wat b/substrate/frame/contracts/fixtures/xcm_execute.wat index 7f8b78b21269..a08d29c1be81 100644 --- a/substrate/frame/contracts/fixtures/xcm_execute.wat +++ b/substrate/frame/contracts/fixtures/xcm_execute.wat @@ -13,7 +13,7 @@ ;; Receive the encoded call (call $seal_input (i32.const 4) ;; Pointer to the input buffer - (i32.const 0) ;; Size of the length buffer + (i32.const 0) ;; Pointer to the buffer length (before call) and to the copied data length (after call) ) ;; Input data layout. ;; [0..4) - size of the call @@ -28,7 +28,7 @@ ) (call $seal_return (i32.const 0) ;; flags - (i32.const 0) ;; returned value + (i32.const 0) ;; Pointer to returned value (i32.const 4) ;; length of returned value ) ) diff --git a/substrate/frame/contracts/fixtures/xcm_query.wat b/substrate/frame/contracts/fixtures/xcm_query.wat index 9cefe9e75c28..966b0669d2b3 100644 --- a/substrate/frame/contracts/fixtures/xcm_query.wat +++ b/substrate/frame/contracts/fixtures/xcm_query.wat @@ -13,10 +13,10 @@ ;; Receive the encoded call (call $seal_input (i32.const 4) ;; Pointer to the input buffer - (i32.const 0) ;; Size of the length buffer + (i32.const 0) ;; Pointer to the buffer length (before call) and to the copied data length (after call) ) ;; Input data layout. - ;; [0..4) - size of the call + ;; [0..4) - size of the input buffer ;; [4..12) - timeout ;; [12..49) - match_querier @@ -30,13 +30,10 @@ ) (call $seal_return (i32.const 0) ;; flags - (i32.const 49) ;; returned value + (i32.const 49) ;; Pointer to returned value (i32.const 8) ;; length of returned value ) ) (func (export "deploy")) ) - - - diff --git a/substrate/frame/contracts/fixtures/xcm_send.wat b/substrate/frame/contracts/fixtures/xcm_send.wat index d818447f58b1..8416d35d759c 100644 --- a/substrate/frame/contracts/fixtures/xcm_send.wat +++ b/substrate/frame/contracts/fixtures/xcm_send.wat @@ -33,12 +33,10 @@ ) (call $seal_return (i32.const 0) ;; flags - (i32.const 0) ;; returned value + (i32.const 0) ;; ptr to returned value (i32.const 4) ;; length of returned value ) ) (func (export "deploy")) ) - - diff --git a/substrate/frame/contracts/fixtures/xcm_take_response.wat b/substrate/frame/contracts/fixtures/xcm_take_response.wat index d57da6835fde..1e608adf3f97 100644 --- a/substrate/frame/contracts/fixtures/xcm_take_response.wat +++ b/substrate/frame/contracts/fixtures/xcm_take_response.wat @@ -36,7 +36,3 @@ (func (export "deploy")) ) - - - - diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 3e36bee6be6b..4c2afd05e946 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2685,7 +2685,7 @@ pub mod env { } /// Send an XCM program from the contract to the specified destination. - /// This is equivalent to dispatching `pallet_xcm::send` through call_runtime, except that + /// This is equivalent to dispatching `pallet_xcm::send` through `call_runtime`, except that /// the function is called directly instead of being dispatched. /// /// # Parameters @@ -2694,6 +2694,7 @@ pub mod env { /// is placed. /// - `call_ptr`: the pointer into the linear memory where the message is placed. /// - `call_len`: the length of the message in bytes. + /// /// # Return Value /// /// Returns `ReturnCode::Success` when the message was successfully sent. When the XCM @@ -2721,7 +2722,7 @@ pub mod env { Ok(_) => Ok(ReturnCode::Success), Err(e) => { if ctx.ext.append_debug_buffer("") { - ctx.ext.append_debug_buffer("call failed with: "); + ctx.ext.append_debug_buffer("seal0::xcm_send failed with: "); ctx.ext.append_debug_buffer(e.into()); }; Ok(ReturnCode::CallRuntimeFailed) From 132e203de134118cbde9161f63f28980cf9e909d Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 24 Oct 2023 10:05:54 +0200 Subject: [PATCH 062/115] PR review comment --- substrate/frame/contracts/src/tests/test_xcm.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index b9063f627b80..38e14d28e6c3 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -202,7 +202,6 @@ fn test_xcm_execute_reentrant_call() { ); // assert that the Transact failed - // use crate::tests::{test_xcm::Outcome::Incomplete}; assert!(parachain::System::events().iter().any(|r| { matches!( r.event, @@ -211,6 +210,9 @@ fn test_xcm_execute_reentrant_call() { }), ) })); + + // Funds should not change hands as the XCM transact failed. + assert_eq!(ParachainBalances::free_balance(BOB), INITIAL_BALANCE); }); } From 7bf716dfe6afda54dfe1abe1d6695d0aba1b0e01 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 24 Oct 2023 11:14:32 +0200 Subject: [PATCH 063/115] Fix lint --- substrate/frame/contracts/src/tests/test_xcm.rs | 2 +- substrate/frame/contracts/src/wasm/runtime.rs | 13 +++++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 38e14d28e6c3..988627993cdc 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -212,7 +212,7 @@ fn test_xcm_execute_reentrant_call() { })); // Funds should not change hands as the XCM transact failed. - assert_eq!(ParachainBalances::free_balance(BOB), INITIAL_BALANCE); + assert_eq!(ParachainBalances::free_balance(BOB), INITIAL_BALANCE); }); } diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 4c2afd05e946..f56e0b856425 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -116,8 +116,13 @@ pub enum ReturnCode { EcdsaRecoverFailed = 11, /// sr25519 signature verification failed. Sr25519VerifyFailed = 12, - /// The `seal_xcm_query` was executed but returned an error. - XcmQueryFailed = 13, + /// The `xcm_execute` call failed. + XcmExecutionFailed = 13, + /// The `xcm_send` call failed. + XcmSendFailed = 14, + /// The `xcm_query` was executed but returned an error. + XcmQueryFailed = 15, +} } impl From for ReturnCode { @@ -2694,7 +2699,7 @@ pub mod env { /// is placed. /// - `call_ptr`: the pointer into the linear memory where the message is placed. /// - `call_len`: the length of the message in bytes. - /// + /// /// # Return Value /// /// Returns `ReturnCode::Success` when the message was successfully sent. When the XCM @@ -2725,7 +2730,7 @@ pub mod env { ctx.ext.append_debug_buffer("seal0::xcm_send failed with: "); ctx.ext.append_debug_buffer(e.into()); }; - Ok(ReturnCode::CallRuntimeFailed) + Ok(ReturnCode::XcmSendFailed) }, } } From 6a7a8bd513798a9777db24de599f43e1b95e5624 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 24 Oct 2023 11:18:46 +0200 Subject: [PATCH 064/115] return proper error code --- substrate/frame/contracts/src/wasm/runtime.rs | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index f56e0b856425..9e8f8bc8efd4 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -27,8 +27,8 @@ use crate::{ use bitflags::bitflags; use codec::{Decode, DecodeLimit, Encode, MaxEncodedLen}; use frame_support::{ - dispatch::DispatchInfo, ensure, pallet_prelude::DispatchResultWithPostInfo, traits::Get, - weights::Weight, + dispatch::DispatchInfo, ensure, pallet_prelude::DispatchResultWithPostInfo, parameter_types, + traits::Get, weights::Weight, }; use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags}; use pallet_contracts_proc_macro::define_env; @@ -123,6 +123,12 @@ pub enum ReturnCode { /// The `xcm_query` was executed but returned an error. XcmQueryFailed = 15, } + +parameter_types! { + /// Getter types used by [`crate::api_doc::Current::call_runtime`] + const CallRuntimeFailed: ReturnCode = ReturnCode::CallRuntimeFailed; + /// Getter types used by [`crate::api_doc::Current::xcm_execute`] + const XcmExecutionFailed: ReturnCode = ReturnCode::XcmExecutionFailed; } impl From for ReturnCode { @@ -569,7 +575,10 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { } /// Charge, Run and adjust gas, for executing the given dispatchable. - fn call_dispatchable DispatchResultWithPostInfo>( + fn call_dispatchable< + ErrorReturnCode: Get, + F: FnOnce(&E) -> DispatchResultWithPostInfo, + >( &mut self, dispatch_info: DispatchInfo, run: F, @@ -586,7 +595,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { self.ext.append_debug_buffer("call failed with: "); self.ext.append_debug_buffer(e.into()); }; - Ok(ReturnCode::CallRuntimeFailed) + Ok(ErrorReturnCode::get()) }, } } @@ -2645,7 +2654,9 @@ pub mod env { ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; let call: ::RuntimeCall = ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; - ctx.call_dispatchable(call.get_dispatch_info(), |ext| ext.call_runtime(call)) + ctx.call_dispatchable::(call.get_dispatch_info(), |ext| { + ext.call_runtime(call) + }) } /// Execute an XCM program locally, using the contract's address as the origin. @@ -2680,7 +2691,7 @@ pub mod env { let weight = ctx.ext.gas_meter().gas_left().max(execute_weight); let dispatch_info = DispatchInfo { weight, ..Default::default() }; - ctx.call_dispatchable(dispatch_info, |ext| { + ctx.call_dispatchable::(dispatch_info, |ext| { <::Xcm as Xcm>::execute( ext.address(), message, From 06a5c9aa4343a5c2b535fc08084ac779df14209a Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 24 Oct 2023 12:00:51 +0200 Subject: [PATCH 065/115] fix compilation issues after rebase --- .../src/tests/mock_network/xcm_utils.rs | 4 +-- substrate/frame/contracts/src/xcm/adapter.rs | 29 +++++++++++++------ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs b/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs index bc157569be00..81889f5a63f3 100644 --- a/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs +++ b/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs @@ -15,7 +15,7 @@ // along with Polkadot. If not, see . use codec::Encode; -use core::{borrow::Borrow, marker::PhantomData}; +use core::marker::PhantomData; use sp_core::blake2_256; use xcm::prelude::*; use xcm_executor::traits::ConvertLocation; @@ -33,7 +33,7 @@ impl + Clone> ConvertLocation for ForeignChainAliasAccount { fn convert_location(location: &MultiLocation) -> Option { - let entropy = match location.borrow() { + let entropy = match location { // Used on the relay chain for sending paras that use 32 byte accounts MultiLocation { parents: 0, diff --git a/substrate/frame/contracts/src/xcm/adapter.rs b/substrate/frame/contracts/src/xcm/adapter.rs index b8b3031f5d96..d0cd13bafe4d 100644 --- a/substrate/frame/contracts/src/xcm/adapter.rs +++ b/substrate/frame/contracts/src/xcm/adapter.rs @@ -21,20 +21,22 @@ use crate::{ xcm::{CallOf, WeightInfo, Xcm}, AccountIdOf, Box, Config, RawOrigin, }; -use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight}; +use frame_support::{ + pallet_prelude::{DispatchResultWithPostInfo, IsType}, + weights::Weight, +}; use frame_system::pallet_prelude::BlockNumberFor; use pallet_xcm::WeightInfo as XcmWeightInfo; use sp_runtime::{DispatchError, DispatchResult}; use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; +pub type XcmCallOf = ::RuntimeCall; + /// An implementation of the [`Xcm`] trait using pallet-xcm. pub struct XcmAdapter(sp_std::marker::PhantomData); -impl WeightInfo for XcmAdapter -where - T: pallet_xcm::Config, -{ +impl WeightInfo for XcmAdapter { fn execute() -> Weight { ::WeightInfo::execute() } @@ -49,12 +51,16 @@ where } } -impl XcmAdapter { +impl XcmAdapter +where + T: Config + pallet_xcm::Config, + ::RuntimeCall: IsType<::RuntimeCall>, +{ /// Ensure that the message is executable, by checking that it does not contain any [`Transact`] /// instruction with a call that is not allowed by the CallFilter. fn ensure_executable( message: VersionedXcm>, - ) -> Result>>, DispatchError> { + ) -> Result>>, DispatchError> { use frame_support::traits::Contains; use xcm::prelude::{Transact, Xcm}; @@ -72,11 +78,16 @@ impl XcmAdapter { Ok(()) })?; - Ok(Box::new(VersionedXcm::from(message))) + Ok(Box::new(VersionedXcm::from(message.into()))) } } -impl Xcm for XcmAdapter { +impl Xcm for XcmAdapter +where + T: Config + pallet_xcm::Config, + + ::RuntimeCall: IsType<::RuntimeCall>, +{ type QueryId = as QueryHandler>::QueryId; type WeightInfo = Self; From b47f660824c455cde0de4b23faa4832f0e677b53 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 24 Oct 2023 12:01:41 +0200 Subject: [PATCH 066/115] lint --- substrate/frame/contracts/src/xcm/adapter.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/substrate/frame/contracts/src/xcm/adapter.rs b/substrate/frame/contracts/src/xcm/adapter.rs index d0cd13bafe4d..bca2aff818aa 100644 --- a/substrate/frame/contracts/src/xcm/adapter.rs +++ b/substrate/frame/contracts/src/xcm/adapter.rs @@ -85,7 +85,6 @@ where impl Xcm for XcmAdapter where T: Config + pallet_xcm::Config, - ::RuntimeCall: IsType<::RuntimeCall>, { type QueryId = as QueryHandler>::QueryId; From 0949455dc67b8bd0f8da5ce697b3d57bfd33e1f2 Mon Sep 17 00:00:00 2001 From: command-bot <> Date: Tue, 24 Oct 2023 12:44:32 +0000 Subject: [PATCH 067/115] ".git/.scripts/commands/bench/bench.sh" --subcommand=runtime --runtime=rococo --target_dir=polkadot --pallet=pallet_xcm --- .../runtime/rococo/src/weights/pallet_xcm.rs | 329 +++++++++--------- 1 file changed, 172 insertions(+), 157 deletions(-) diff --git a/polkadot/runtime/rococo/src/weights/pallet_xcm.rs b/polkadot/runtime/rococo/src/weights/pallet_xcm.rs index 43b4358b8903..5b001c5816c7 100644 --- a/polkadot/runtime/rococo/src/weights/pallet_xcm.rs +++ b/polkadot/runtime/rococo/src/weights/pallet_xcm.rs @@ -17,10 +17,10 @@ //! Autogenerated weights for `pallet_xcm` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-05-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-10-24, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `bm5`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("rococo-dev"), DB CACHE: 1024 +//! HOSTNAME: `runner-t2sp1qqs-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("rococo-dev")`, DB CACHE: 1024 // Executed Command: // target/production/polkadot @@ -29,14 +29,13 @@ // --steps=50 // --repeat=20 // --extrinsic=* -// --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --json-file=/var/lib/gitlab-runner/builds/zyw4fam_/0/parity/mirrors/polkadot/.git/.artifacts/bench.json +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json // --pallet=pallet_xcm // --chain=rococo-dev -// --header=./file_header.txt -// --output=./runtime/rococo/src/weights/ +// --header=./polkadot/file_header.txt +// --output=./polkadot/runtime/rococo/src/weights/ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -49,58 +48,56 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { - /// Storage: Configuration ActiveConfig (r:1 w:0) - /// Proof Skipped: Configuration ActiveConfig (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) fn send() -> Weight { // Proof Size summary in bytes: - // Measured: `565` - // Estimated: `4030` - // Minimum execution time: 37_039_000 picoseconds. - Weight::from_parts(37_605_000, 0) - .saturating_add(Weight::from_parts(0, 4030)) - .saturating_add(T::DbWeight::get().reads(7)) - .saturating_add(T::DbWeight::get().writes(3)) + // Measured: `142` + // Estimated: `3607` + // Minimum execution time: 28_378_000 picoseconds. + Weight::from_parts(29_137_000, 0) + .saturating_add(Weight::from_parts(0, 3607)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) } fn teleport_assets() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 21_646_000 picoseconds. - Weight::from_parts(22_119_000, 0) + // Minimum execution time: 17_649_000 picoseconds. + Weight::from_parts(17_869_000, 0) .saturating_add(Weight::from_parts(0, 0)) } fn reserve_transfer_assets() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 21_353_000 picoseconds. - Weight::from_parts(21_768_000, 0) + // Minimum execution time: 17_293_000 picoseconds. + Weight::from_parts(17_443_000, 0) .saturating_add(Weight::from_parts(0, 0)) } fn execute() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 9_942_000 picoseconds. - Weight::from_parts(10_110_000, 0) + // Minimum execution time: 7_728_000 picoseconds. + Weight::from_parts(8_180_000, 0) .saturating_add(Weight::from_parts(0, 0)) } - /// Storage: XcmPallet SupportedVersion (r:0 w:1) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::SupportedVersion` (r:0 w:1) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) fn force_xcm_version() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 9_951_000 picoseconds. - Weight::from_parts(10_182_000, 0) + // Minimum execution time: 7_630_000 picoseconds. + Weight::from_parts(7_941_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -108,171 +105,189 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_163_000 picoseconds. - Weight::from_parts(3_298_000, 0) + // Minimum execution time: 2_259_000 picoseconds. + Weight::from_parts(2_406_000, 0) .saturating_add(Weight::from_parts(0, 0)) } - /// Storage: XcmPallet VersionNotifiers (r:1 w:1) - /// Proof Skipped: XcmPallet VersionNotifiers (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet QueryCounter (r:1 w:1) - /// Proof Skipped: XcmPallet QueryCounter (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Configuration ActiveConfig (r:1 w:0) - /// Proof Skipped: Configuration ActiveConfig (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet Queries (r:0 w:1) - /// Proof Skipped: XcmPallet Queries (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::VersionNotifiers` (r:1 w:1) + /// Proof: `XcmPallet::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::QueryCounter` (r:1 w:1) + /// Proof: `XcmPallet::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::Queries` (r:0 w:1) + /// Proof: `XcmPallet::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) fn force_subscribe_version_notify() -> Weight { // Proof Size summary in bytes: - // Measured: `565` - // Estimated: `4030` - // Minimum execution time: 41_207_000 picoseconds. - Weight::from_parts(41_879_000, 0) - .saturating_add(Weight::from_parts(0, 4030)) - .saturating_add(T::DbWeight::get().reads(9)) - .saturating_add(T::DbWeight::get().writes(6)) + // Measured: `142` + // Estimated: `3607` + // Minimum execution time: 32_168_000 picoseconds. + Weight::from_parts(33_116_000, 0) + .saturating_add(Weight::from_parts(0, 3607)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(5)) } - /// Storage: XcmPallet VersionNotifiers (r:1 w:1) - /// Proof Skipped: XcmPallet VersionNotifiers (max_values: None, max_size: None, mode: Measured) - /// Storage: Configuration ActiveConfig (r:1 w:0) - /// Proof Skipped: Configuration ActiveConfig (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet Queries (r:0 w:1) - /// Proof Skipped: XcmPallet Queries (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::VersionNotifiers` (r:1 w:1) + /// Proof: `XcmPallet::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::Queries` (r:0 w:1) + /// Proof: `XcmPallet::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) fn force_unsubscribe_version_notify() -> Weight { // Proof Size summary in bytes: - // Measured: `837` - // Estimated: `4302` - // Minimum execution time: 44_763_000 picoseconds. - Weight::from_parts(45_368_000, 0) - .saturating_add(Weight::from_parts(0, 4302)) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(5)) + // Measured: `322` + // Estimated: `3787` + // Minimum execution time: 37_943_000 picoseconds. + Weight::from_parts(39_073_000, 0) + .saturating_add(Weight::from_parts(0, 3787)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) } - /// Storage: XcmPallet XcmExecutionSuspended (r:0 w:1) - /// Proof Skipped: XcmPallet XcmExecutionSuspended (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: `XcmPallet::XcmExecutionSuspended` (r:0 w:1) + /// Proof: `XcmPallet::XcmExecutionSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn force_suspension() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_089_000 picoseconds. - Weight::from_parts(3_246_000, 0) + // Minimum execution time: 2_298_000 picoseconds. + Weight::from_parts(2_429_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } - /// Storage: XcmPallet SupportedVersion (r:4 w:2) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::SupportedVersion` (r:4 w:2) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) fn migrate_supported_version() -> Weight { // Proof Size summary in bytes: - // Measured: `229` - // Estimated: `11119` - // Minimum execution time: 16_733_000 picoseconds. - Weight::from_parts(17_354_000, 0) - .saturating_add(Weight::from_parts(0, 11119)) + // Measured: `26` + // Estimated: `10916` + // Minimum execution time: 14_725_000 picoseconds. + Weight::from_parts(15_254_000, 0) + .saturating_add(Weight::from_parts(0, 10916)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } - /// Storage: XcmPallet VersionNotifiers (r:4 w:2) - /// Proof Skipped: XcmPallet VersionNotifiers (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::VersionNotifiers` (r:4 w:2) + /// Proof: `XcmPallet::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) fn migrate_version_notifiers() -> Weight { // Proof Size summary in bytes: - // Measured: `233` - // Estimated: `11123` - // Minimum execution time: 16_959_000 picoseconds. - Weight::from_parts(17_306_000, 0) - .saturating_add(Weight::from_parts(0, 11123)) + // Measured: `30` + // Estimated: `10920` + // Minimum execution time: 14_979_000 picoseconds. + Weight::from_parts(15_633_000, 0) + .saturating_add(Weight::from_parts(0, 10920)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } - /// Storage: XcmPallet VersionNotifyTargets (r:5 w:0) - /// Proof Skipped: XcmPallet VersionNotifyTargets (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::VersionNotifyTargets` (r:5 w:0) + /// Proof: `XcmPallet::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) fn already_notified_target() -> Weight { // Proof Size summary in bytes: - // Measured: `243` - // Estimated: `13608` - // Minimum execution time: 17_964_000 picoseconds. - Weight::from_parts(18_548_000, 0) - .saturating_add(Weight::from_parts(0, 13608)) + // Measured: `40` + // Estimated: `13405` + // Minimum execution time: 16_822_000 picoseconds. + Weight::from_parts(17_330_000, 0) + .saturating_add(Weight::from_parts(0, 13405)) .saturating_add(T::DbWeight::get().reads(5)) } - /// Storage: XcmPallet VersionNotifyTargets (r:2 w:1) - /// Proof Skipped: XcmPallet VersionNotifyTargets (max_values: None, max_size: None, mode: Measured) - /// Storage: Configuration ActiveConfig (r:1 w:0) - /// Proof Skipped: Configuration ActiveConfig (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::VersionNotifyTargets` (r:2 w:1) + /// Proof: `XcmPallet::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) fn notify_current_targets() -> Weight { // Proof Size summary in bytes: - // Measured: `635` - // Estimated: `6575` - // Minimum execution time: 39_436_000 picoseconds. - Weight::from_parts(39_669_000, 0) - .saturating_add(Weight::from_parts(0, 6575)) - .saturating_add(T::DbWeight::get().reads(9)) - .saturating_add(T::DbWeight::get().writes(4)) + // Measured: `178` + // Estimated: `6118` + // Minimum execution time: 30_893_000 picoseconds. + Weight::from_parts(31_564_000, 0) + .saturating_add(Weight::from_parts(0, 6118)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: XcmPallet VersionNotifyTargets (r:3 w:0) - /// Proof Skipped: XcmPallet VersionNotifyTargets (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::VersionNotifyTargets` (r:3 w:0) + /// Proof: `XcmPallet::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) fn notify_target_migration_fail() -> Weight { // Proof Size summary in bytes: - // Measured: `272` - // Estimated: `8687` - // Minimum execution time: 8_991_000 picoseconds. - Weight::from_parts(9_248_000, 0) - .saturating_add(Weight::from_parts(0, 8687)) + // Measured: `69` + // Estimated: `8484` + // Minimum execution time: 9_609_000 picoseconds. + Weight::from_parts(10_052_000, 0) + .saturating_add(Weight::from_parts(0, 8484)) .saturating_add(T::DbWeight::get().reads(3)) } - /// Storage: XcmPallet VersionNotifyTargets (r:4 w:2) - /// Proof Skipped: XcmPallet VersionNotifyTargets (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::VersionNotifyTargets` (r:4 w:2) + /// Proof: `XcmPallet::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) fn migrate_version_notify_targets() -> Weight { // Proof Size summary in bytes: - // Measured: `240` - // Estimated: `11130` - // Minimum execution time: 17_614_000 picoseconds. - Weight::from_parts(17_948_000, 0) - .saturating_add(Weight::from_parts(0, 11130)) + // Measured: `37` + // Estimated: `10927` + // Minimum execution time: 15_131_000 picoseconds. + Weight::from_parts(15_812_000, 0) + .saturating_add(Weight::from_parts(0, 10927)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } - /// Storage: XcmPallet VersionNotifyTargets (r:4 w:2) - /// Proof Skipped: XcmPallet VersionNotifyTargets (max_values: None, max_size: None, mode: Measured) - /// Storage: Configuration ActiveConfig (r:1 w:0) - /// Proof Skipped: Configuration ActiveConfig (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::VersionNotifyTargets` (r:4 w:2) + /// Proof: `XcmPallet::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) fn migrate_and_notify_old_targets() -> Weight { // Proof Size summary in bytes: - // Measured: `639` - // Estimated: `11529` - // Minimum execution time: 45_531_000 picoseconds. - Weight::from_parts(46_533_000, 0) - .saturating_add(Weight::from_parts(0, 11529)) - .saturating_add(T::DbWeight::get().reads(11)) - .saturating_add(T::DbWeight::get().writes(5)) + // Measured: `182` + // Estimated: `11072` + // Minimum execution time: 37_980_000 picoseconds. + Weight::from_parts(39_233_000, 0) + .saturating_add(Weight::from_parts(0, 11072)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `XcmPallet::QueryCounter` (r:1 w:1) + /// Proof: `XcmPallet::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::Queries` (r:0 w:1) + /// Proof: `XcmPallet::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn new_query() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `1485` + // Minimum execution time: 2_739_000 picoseconds. + Weight::from_parts(2_846_000, 0) + .saturating_add(Weight::from_parts(0, 1485)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `XcmPallet::Queries` (r:1 w:1) + /// Proof: `XcmPallet::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn take_response() -> Weight { + // Proof Size summary in bytes: + // Measured: `7576` + // Estimated: `11041` + // Minimum execution time: 24_109_000 picoseconds. + Weight::from_parts(24_456_000, 0) + .saturating_add(Weight::from_parts(0, 11041)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } } From 14fed0e912330ba17c00e340ca7348ce0fde6919 Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Wed, 25 Oct 2023 11:00:39 +0200 Subject: [PATCH 068/115] Update substrate/frame/contracts/src/tests/test_xcm.rs Co-authored-by: Francisco Aguirre --- substrate/frame/contracts/src/tests/test_xcm.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 988627993cdc..9130432981c2 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -132,7 +132,7 @@ fn test_xcm_execute_filtered_call() { let contract_addr = instantiate_test_contract("xcm_execute"); ParaA::execute_with(|| { - // `remark` should be rejected, as CallFilter is not allowed by our CallFilter. + // `remark` should be rejected, as it is not allowed by our CallFilter. let call = parachain::RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); let message: Xcm = Xcm(vec![Transact { origin_kind: OriginKind::Native, From e6949415fc48faf934901016fd8f18c6463330c8 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Wed, 25 Oct 2023 11:08:05 +0200 Subject: [PATCH 069/115] simplify mock_network --- .../frame/contracts/src/tests/mock_network.rs | 1 - .../src/tests/mock_network/parachain.rs | 6 +- .../src/tests/mock_network/relay_chain.rs | 7 +- .../src/tests/mock_network/xcm_utils.rs | 69 ------------------- 4 files changed, 4 insertions(+), 79 deletions(-) delete mode 100644 substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs diff --git a/substrate/frame/contracts/src/tests/mock_network.rs b/substrate/frame/contracts/src/tests/mock_network.rs index 1254fcc970d9..412bc49ca9f0 100644 --- a/substrate/frame/contracts/src/tests/mock_network.rs +++ b/substrate/frame/contracts/src/tests/mock_network.rs @@ -18,7 +18,6 @@ pub mod mocks; pub mod parachain; pub mod primitives; pub mod relay_chain; -pub mod xcm_utils; use crate::tests::mock_network::primitives::{AccountId, UNITS}; use sp_runtime::BuildStorage; diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain.rs b/substrate/frame/contracts/src/tests/mock_network/parachain.rs index d5a88e598a2c..a6421d596161 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain.rs @@ -20,7 +20,6 @@ mod contracts_config; use crate::tests::mock_network::{ mocks::msg_queue::pallet as mock_msg_queue, primitives::{AccountId, AssetIdForAssets, Balance}, - xcm_utils::ForeignChainAliasAccount, }; use core::marker::PhantomData; use frame_support::{ @@ -33,7 +32,6 @@ use frame_support::{ }; use frame_system::{EnsureRoot, EnsureSigned}; use pallet_xcm::XcmPassthrough; -use polkadot_parachain_primitives::primitives::Sibling; use sp_core::{ConstU32, ConstU64, H256}; use sp_runtime::traits::{Get, IdentityLookup, MaybeEquivalence}; @@ -43,14 +41,12 @@ use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, ConvertedConcreteId, CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, FungiblesAdapter, IsConcrete, NativeAsset, NoChecking, - ParentAsSuperuser, ParentIsPreset, SiblingParachainConvertsVia, SignedAccountId32AsNative, + ParentAsSuperuser, ParentIsPreset, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, }; use xcm_executor::{traits::JustTry, Config, XcmExecutor}; pub type SovereignAccountOf = ( - ForeignChainAliasAccount, - SiblingParachainConvertsVia, AccountId32Aliases, ParentIsPreset, ); diff --git a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs index c755cbbfac15..8e659415abe8 100644 --- a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs @@ -30,10 +30,11 @@ use polkadot_parachain_primitives::primitives::Id as ParaId; use polkadot_runtime_parachains::{configuration, origin, shared}; use xcm::latest::prelude::*; use xcm_builder::{ + HashedDescription, DescribeFamily, DescribeAllTerminal, AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, ChildParachainConvertsVia, ChildSystemParachainAsSuperuser, CurrencyAdapter as XcmCurrencyAdapter, FixedRateOfFungible, - FixedWeightBounds, IsConcrete, SiblingParachainConvertsVia, SignedAccountId32AsNative, + FixedWeightBounds, IsConcrete, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, }; use xcm_executor::{Config, XcmExecutor}; @@ -41,7 +42,6 @@ use xcm_executor::{Config, XcmExecutor}; use super::{ mocks::relay_message_queue::*, primitives::{AccountId, Balance}, - xcm_utils::ForeignChainAliasAccount, }; parameter_types! { @@ -110,10 +110,9 @@ parameter_types! { } pub type SovereignAccountOf = ( - ForeignChainAliasAccount, + HashedDescription>, AccountId32Aliases, ChildParachainConvertsVia, - SiblingParachainConvertsVia, ); pub type LocalBalancesTransactor = diff --git a/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs b/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs deleted file mode 100644 index 81889f5a63f3..000000000000 --- a/substrate/frame/contracts/src/tests/mock_network/xcm_utils.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Polkadot is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Polkadot. If not, see . - -use codec::Encode; -use core::marker::PhantomData; -use sp_core::blake2_256; -use xcm::prelude::*; -use xcm_executor::traits::ConvertLocation; - -/// Prefix for generating alias account for accounts coming -/// from chains that use 32 byte long representations. -pub const FOREIGN_CHAIN_PREFIX_PARA_32: [u8; 37] = *b"ForeignChainAliasAccountPrefix_Para32"; - -/// Prefix for generating alias account for accounts coming -/// from the relay chain using 32 byte long representations. -pub const FOREIGN_CHAIN_PREFIX_RELAY: [u8; 36] = *b"ForeignChainAliasAccountPrefix_Relay"; - -pub struct ForeignChainAliasAccount(PhantomData); -impl + Clone> ConvertLocation - for ForeignChainAliasAccount -{ - fn convert_location(location: &MultiLocation) -> Option { - let entropy = match location { - // Used on the relay chain for sending paras that use 32 byte accounts - MultiLocation { - parents: 0, - interior: X2(Parachain(para_id), AccountId32 { id, .. }), - } => ForeignChainAliasAccount::::from_para_32(para_id, id, 0), - - // Used on para-chain for sending paras that use 32 byte accounts - MultiLocation { - parents: 1, - interior: X2(Parachain(para_id), AccountId32 { id, .. }), - } => ForeignChainAliasAccount::::from_para_32(para_id, id, 1), - - // Used on para-chain for sending from the relay chain - MultiLocation { parents: 1, interior: X1(AccountId32 { id, .. }) } => - ForeignChainAliasAccount::::from_relay_32(id, 1), - - // No other conversions provided - _ => return None, - }; - - Some(entropy.into()) - } -} - -impl ForeignChainAliasAccount { - fn from_para_32(para_id: &u32, id: &[u8; 32], parents: u8) -> [u8; 32] { - (FOREIGN_CHAIN_PREFIX_PARA_32, para_id, id, parents).using_encoded(blake2_256) - } - - fn from_relay_32(id: &[u8; 32], parents: u8) -> [u8; 32] { - (FOREIGN_CHAIN_PREFIX_RELAY, id, parents).using_encoded(blake2_256) - } -} From 72f15c19b4ab03ff8c4d3c1de3d6332a89dcf496 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Thu, 26 Oct 2023 14:00:36 +0200 Subject: [PATCH 070/115] fix return type in comment --- substrate/frame/contracts/src/wasm/runtime.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 9e8f8bc8efd4..30f89c95271c 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2671,7 +2671,7 @@ pub mod env { /// # Return Value /// /// Returns `ReturnCode::Success` when the XCM was successfully executed. When the XCM - /// execution fails, `ReturnCode::CallRuntimeFailed` is returned. + /// execution fails, `ReturnCode::XcmExecutionFailed` is returned. #[unstable] fn xcm_execute( ctx: _, From c8f39e7f79a29c5cbb2ec84da7396b0600b0e54c Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Fri, 27 Oct 2023 18:28:05 +0200 Subject: [PATCH 071/115] Contracts expose pallet-xcm - tweaks (#2062) Follow up from https://github.com/paritytech/polkadot-sdk/pull/1248 Attempt to move xcm stuff into trait inside xcm folder --- polkadot/xcm/pallet-xcm/src/lib.rs | 150 +++++++++++++----- .../xcm/xcm-executor/src/traits/controller.rs | 150 ++++++++++++++++++ polkadot/xcm/xcm-executor/src/traits/mod.rs | 6 +- substrate/frame/contracts/Cargo.toml | 2 +- .../frame/contracts/fixtures/xcm_query.wat | 26 ++- .../frame/contracts/fixtures/xcm_send.wat | 39 +++-- substrate/frame/contracts/src/lib.rs | 14 +- .../src/tests/mock_network/parachain.rs | 11 +- .../parachain/contracts_config.rs | 3 +- .../src/tests/mock_network/relay_chain.rs | 10 +- .../frame/contracts/src/tests/test_xcm.rs | 24 +-- substrate/frame/contracts/src/wasm/runtime.rs | 82 +++++++--- substrate/frame/contracts/src/xcm.rs | 138 ---------------- substrate/frame/contracts/src/xcm/adapter.rs | 135 ---------------- 14 files changed, 401 insertions(+), 389 deletions(-) create mode 100644 polkadot/xcm/xcm-executor/src/traits/controller.rs delete mode 100644 substrate/frame/contracts/src/xcm.rs delete mode 100644 substrate/frame/contracts/src/xcm/adapter.rs diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 0840ab322c52..4635c23f0833 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -28,9 +28,17 @@ mod tests; pub mod migration; use codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; -use frame_support::traits::{ - Contains, ContainsPair, Currency, Defensive, EnsureOrigin, Get, LockableCurrency, OriginTrait, +use frame_support::{ + dispatch::GetDispatchInfo, + pallet_prelude::*, + traits::{ + Contains, ContainsPair, Currency, Defensive, EnsureOrigin, Get, LockableCurrency, + OriginTrait, WithdrawReasons, + }, + PalletId, }; +use frame_system::pallet_prelude::{BlockNumberFor, *}; +pub use pallet::*; use scale_info::TypeInfo; use sp_runtime::{ traits::{ @@ -41,17 +49,13 @@ use sp_runtime::{ }; use sp_std::{boxed::Box, marker::PhantomData, prelude::*, result::Result, vec}; use xcm::{latest::QueryResponseInfo, prelude::*}; -use xcm_executor::traits::{ConvertOrigin, Properties}; - -use frame_support::{ - dispatch::GetDispatchInfo, pallet_prelude::*, traits::WithdrawReasons, PalletId, -}; -use frame_system::pallet_prelude::*; -pub use pallet::*; use xcm_executor::{ traits::{ - CheckSuspension, ClaimAssets, ConvertLocation, DropAssets, MatchesFungible, OnResponse, - QueryHandler, QueryResponseStatus, VersionChangeNotifier, WeightBounds, + CheckSuspension, ClaimAssets, ConvertLocation, ConvertOrigin, DropAssets, + ExecuteController, ExecuteControllerWeightInfo, MatchesFungible, OnResponse, Properties, + QueryController, QueryControllerWeightInfo, QueryHandler, + QueryResponseStatus, SendController, SendControllerWeightInfo, VersionChangeNotifier, + WeightBounds, }, Assets, }; @@ -282,6 +286,101 @@ pub mod pallet { type ReachableDest: Get>; } + impl ExecuteControllerWeightInfo for Pallet { + fn execute() -> Weight { + T::WeightInfo::execute() + } + } + + impl ExecuteController, ::RuntimeCall> for Pallet { + type WeightInfo = Self; + fn execute( + origin: OriginFor, + message: Box::RuntimeCall>>, + max_weight: Weight, + ) -> DispatchResultWithPostInfo { + let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?; + let hash = message.using_encoded(sp_io::hashing::blake2_256); + let message = (*message).try_into().map_err(|()| Error::::BadVersion)?; + let value = (origin_location, message); + ensure!(T::XcmExecuteFilter::contains(&value), Error::::Filtered); + let (origin_location, message) = value; + let outcome = T::XcmExecutor::execute_xcm_in_credit( + origin_location, + message, + hash, + max_weight, + max_weight, + ); + let result = + Ok(Some(outcome.weight_used().saturating_add(T::WeightInfo::execute())).into()); + Self::deposit_event(Event::Attempted { outcome }); + result + } + } + + impl SendControllerWeightInfo for Pallet { + fn send() -> Weight { + T::WeightInfo::send() + } + } + + impl SendController> for Pallet { + type WeightInfo = Self; + fn send( + origin: OriginFor, + dest: Box, + message: Box>, + ) -> Result { + let origin_location = T::SendXcmOrigin::ensure_origin(origin)?; + let interior: Junctions = + origin_location.try_into().map_err(|_| Error::::InvalidOrigin)?; + let dest = MultiLocation::try_from(*dest).map_err(|()| Error::::BadVersion)?; + let message: Xcm<()> = (*message).try_into().map_err(|()| Error::::BadVersion)?; + + let message_id = + Self::send_xcm(interior, dest, message.clone()).map_err(Error::::from)?; + let e = Event::Sent { origin: origin_location, destination: dest, message, message_id }; + Self::deposit_event(e); + Ok(message_id) + } + } + + impl QueryControllerWeightInfo for Pallet { + fn query() -> Weight { + T::WeightInfo::new_query() + } + fn take_response() -> Weight { + T::WeightInfo::take_response() + } + } + + impl QueryController, BlockNumberFor> for Pallet { + type WeightInfo = Self; + type QueryId = ::QueryId; + type BlockNumber = BlockNumberFor; + + fn query( + origin: OriginFor, + timeout: BlockNumberFor, + match_querier: VersionedMultiLocation, + ) -> Result { + let responder = ::ExecuteXcmOrigin::ensure_origin(origin)?; + let query_id = ::new_query( + responder, + timeout.into(), + MultiLocation::try_from(match_querier) + .map_err(|_| Into::::into(Error::::BadVersion))?, + ); + + Ok(query_id) + } + + fn take_response(query_id: Self::QueryId) -> QueryResponseStatus { + ::take_response(query_id) + } + } + #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { @@ -786,16 +885,7 @@ pub mod pallet { dest: Box, message: Box>, ) -> DispatchResult { - let origin_location = T::SendXcmOrigin::ensure_origin(origin)?; - let interior: Junctions = - origin_location.try_into().map_err(|_| Error::::InvalidOrigin)?; - let dest = MultiLocation::try_from(*dest).map_err(|()| Error::::BadVersion)?; - let message: Xcm<()> = (*message).try_into().map_err(|()| Error::::BadVersion)?; - - let message_id = - Self::send_xcm(interior, dest, message.clone()).map_err(Error::::from)?; - let e = Event::Sent { origin: origin_location, destination: dest, message, message_id }; - Self::deposit_event(e); + >::send(origin, dest, message)?; Ok(()) } @@ -919,23 +1009,7 @@ pub mod pallet { message: Box::RuntimeCall>>, max_weight: Weight, ) -> DispatchResultWithPostInfo { - let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?; - let hash = message.using_encoded(sp_io::hashing::blake2_256); - let message = (*message).try_into().map_err(|()| Error::::BadVersion)?; - let value = (origin_location, message); - ensure!(T::XcmExecuteFilter::contains(&value), Error::::Filtered); - let (origin_location, message) = value; - let outcome = T::XcmExecutor::execute_xcm_in_credit( - origin_location, - message, - hash, - max_weight, - max_weight, - ); - let result = - Ok(Some(outcome.weight_used().saturating_add(T::WeightInfo::execute())).into()); - Self::deposit_event(Event::Attempted { outcome }); - result + >::execute(origin, message, max_weight) } /// Extoll that a particular destination can be communicated with through a particular diff --git a/polkadot/xcm/xcm-executor/src/traits/controller.rs b/polkadot/xcm/xcm-executor/src/traits/controller.rs new file mode 100644 index 000000000000..c74b8c5fff50 --- /dev/null +++ b/polkadot/xcm/xcm-executor/src/traits/controller.rs @@ -0,0 +1,150 @@ +use frame_support::pallet_prelude::*; +use sp_weights::Weight; +use xcm::{v3::XcmHash, VersionedMultiLocation, VersionedXcm}; +use crate::traits::QueryResponseStatus; + +/// Umbrella trait for all Controller traits. +pub trait Controller: ExecuteController + SendController + QueryController {} +impl Controller for T +where T: ExecuteController + SendController + QueryController +{} + +/// Weight functions needed for [`ExecuteController`]. +pub trait ExecuteControllerWeightInfo { + /// Weight for [`ExecuteController::execute`] + fn execute() -> Weight; +} + +/// Execute an XCM locally, for a given origin. +pub trait ExecuteController { + type WeightInfo: ExecuteControllerWeightInfo; + + /// Execute an XCM locally. + /// + /// # Parameters + /// + /// - `origin`: the origin of the call. + /// - `message`: the XCM program to be executed. + /// - `max_weight`: the maximum weight that can be consumed by the execution. + fn execute( + origin: Origin, + message: Box>, + max_weight: Weight, + ) -> DispatchResultWithPostInfo; +} + +impl ExecuteController for () { + type WeightInfo = (); + fn execute( + _origin: Origin, + _message: Box>, + _max_weight: Weight, + ) -> DispatchResultWithPostInfo { + Ok(().into()) + } +} + +impl ExecuteControllerWeightInfo for () { + fn execute() -> Weight { + Weight::zero() + } +} + +/// Weight functions needed for [`SendController`]. +pub trait SendControllerWeightInfo { + /// Weight for [`SendController::send`] + fn send() -> Weight; +} + +/// Send an XCM from a given origin. +pub trait SendController { + type WeightInfo: SendControllerWeightInfo; + + /// Send an XCM to be executed by a remote location. + /// + /// # Parameters + /// + /// - `origin`: the origin of the call. + /// - `dest`: the destination of the message. + /// - `msg`: the XCM to be sent. + fn send( + origin: Origin, + dest: Box, + message: Box>, + ) -> Result; +} + +impl SendController for () { + type WeightInfo = (); + fn send( + _origin: Origin, + _dest: Box, + _message: Box>, + ) -> Result { + Ok(Default::default()) + } +} + +impl SendControllerWeightInfo for () { + fn send() -> Weight { + Weight::zero() + } +} + +/// Weight functions needed for [`QueryController`]. +pub trait QueryControllerWeightInfo { + /// Weight for [`QueryController::query`] + fn query() -> Weight; + + /// Weight for [`QueryController::take_response`] + fn take_response() -> Weight; +} + +/// Query a remote location, from a given origin. +pub trait QueryController { + type QueryId: Encode + Decode + MaxEncodedLen; + type BlockNumber: Encode + Decode + MaxEncodedLen; + type WeightInfo: QueryControllerWeightInfo; + + /// Query a remote location. + /// + /// # Parameters + /// + /// - `origin`: the origin of the call, used to determine the responder. + /// - `timeout`: the maximum block number that the query should be responded to. + /// - `match_querier`: the querier that the query should be responded to. + fn query( + origin: Origin, + timeout: Timeout, + match_querier: VersionedMultiLocation, + ) -> Result; + + /// Take an XCM response for the specified query. + /// + /// - `query_id`: the query id returned by [`Self::query`]. + fn take_response(query_id: Self::QueryId) -> QueryResponseStatus; +} + +impl QueryController for () { + type QueryId = u64; + type BlockNumber = u64; + type WeightInfo = (); + fn query( + _origin: Origin, + _timeout: Timeout, + _match_querier: VersionedMultiLocation, + ) -> Result { + Ok(Default::default()) + } + fn take_response(_query_id: Self::QueryId) -> QueryResponseStatus { + QueryResponseStatus::NotFound + } +} +impl QueryControllerWeightInfo for () { + fn query() -> Weight { + Weight::zero() + } + fn take_response() -> Weight { + Weight::zero() + } +} diff --git a/polkadot/xcm/xcm-executor/src/traits/mod.rs b/polkadot/xcm/xcm-executor/src/traits/mod.rs index a9439968fa6c..069bcb3bf9c7 100644 --- a/polkadot/xcm/xcm-executor/src/traits/mod.rs +++ b/polkadot/xcm/xcm-executor/src/traits/mod.rs @@ -16,6 +16,8 @@ //! Various traits used in configuring the executor. +mod controller; +pub use controller::*; mod conversion; pub use conversion::{CallDispatcher, ConvertLocation, ConvertOrigin, WithOriginFilter}; mod drop_assets; @@ -36,7 +38,9 @@ pub use token_matching::{ Error, MatchesFungible, MatchesFungibles, MatchesNonFungible, MatchesNonFungibles, }; mod on_response; -pub use on_response::{OnResponse, QueryHandler, QueryResponseStatus, VersionChangeNotifier}; +pub use on_response::{ + OnResponse, QueryHandler, QueryResponseStatus, VersionChangeNotifier, +}; mod should_execute; pub use should_execute::{CheckSuspension, Properties, ShouldExecute}; mod transact_asset; diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 33218ab09669..1d3dec7ec0e2 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -50,7 +50,6 @@ sp-std = { path = "../../primitives/std", default-features = false} xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false} xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor", default-features = false} -pallet-xcm = { path = "../../../polkadot/xcm/pallet-xcm", default-features = false} [dev-dependencies] array-bytes = "6.1" @@ -60,6 +59,7 @@ pretty_assertions = "1" wat = "1" # Polkadot Dependencies +pallet-xcm = { path = "../../../polkadot/xcm/pallet-xcm", default-features = false} xcm-simulator = {path = "../../../polkadot/xcm/xcm-simulator"} xcm-builder = {package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder"} polkadot-runtime-parachains = {path = "../../../polkadot/runtime/parachains"} diff --git a/substrate/frame/contracts/fixtures/xcm_query.wat b/substrate/frame/contracts/fixtures/xcm_query.wat index 966b0669d2b3..5f3ed88d3ae1 100644 --- a/substrate/frame/contracts/fixtures/xcm_query.wat +++ b/substrate/frame/contracts/fixtures/xcm_query.wat @@ -9,6 +9,15 @@ ;; size of input buffer (data (i32.const 0) "\00\10") + (func $assert (param i32) + (block $ok + (br_if $ok + (get_local 0) + ) + (unreachable) + ) + ) + (func (export "call") ;; Receive the encoded call (call $seal_input @@ -20,14 +29,19 @@ ;; [4..12) - timeout ;; [12..49) - match_querier - ;; Just use the call passed as input and store result to memory - (i32.store (i32.const 0) - (call $xcm_query - (i32.const 4) ;; Pointer where the timeout is stored - (i32.const 12) ;; Pointer where the match_querier is stored - (i32.const 49) ;; Pointer to the where the query_id is stored + ;; Call xcm_query with provided input. + (call $assert + (i32.eq + (call $xcm_query + (i32.const 4) ;; Pointer where the timeout is stored + (i32.const 12) ;; Pointer where the match_querier is stored + (i32.const 49) ;; Pointer to the where the query_id is stored + ) + (i32.const 0) ) ) + + ;; Return the the query_id (call $seal_return (i32.const 0) ;; flags (i32.const 49) ;; Pointer to returned value diff --git a/substrate/frame/contracts/fixtures/xcm_send.wat b/substrate/frame/contracts/fixtures/xcm_send.wat index 8416d35d759c..9eec6388de9b 100644 --- a/substrate/frame/contracts/fixtures/xcm_send.wat +++ b/substrate/frame/contracts/fixtures/xcm_send.wat @@ -1,6 +1,6 @@ ;; This passes its input to `seal_xcm_send` and returns the return value to its caller. (module - (import "seal0" "xcm_send" (func $xcm_send (param i32 i32 i32) (result i32))) + (import "seal0" "xcm_send" (func $xcm_send (param i32 i32 i32 i32) (result i32))) (import "seal0" "seal_input" (func $seal_input (param i32 i32))) (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) (import "env" "memory" (memory 1 1)) @@ -9,32 +9,49 @@ ;; size of input buffer (data (i32.const 0) "\00\10") + (func $assert (param i32) + (block $ok + (br_if $ok + (get_local 0) + ) + (unreachable) + ) + ) + (func (export "call") + ;; Receive the encoded call (call $seal_input (i32.const 4) ;; Pointer to the input buffer (i32.const 0) ;; Size of the length buffer ) + ;; Input data layout. ;; [0..4) - size of the call ;; [4..7) - dest ;; [7..) - message - ;; Just use the call passed as input and store result to memory - (i32.store (i32.const 0) - (call $xcm_send - (i32.const 4) ;; Pointer where the dest is stored - (i32.const 7) ;; Pointer where the message is stored - (i32.sub ;; Size of the message - (i32.load (i32.const 0)) - (i32.const 3) ;; Size of the XCM dest + ;; Call xcm_send with provided input. + (call $assert + (i32.eq + (call $xcm_send + (i32.const 4) ;; Pointer where the dest is stored + (i32.const 7) ;; Pointer where the message is stored + (i32.sub + (i32.load (i32.const 0)) ;; length of the input buffer + (i32.const 3) ;; Size of the XCM dest + ) + (i32.const 100) ;; Pointer to the where the message_id is stored ) + (i32.const 0) ) ) + + ;; Return the the message_id (call $seal_return (i32.const 0) ;; flags - (i32.const 0) ;; ptr to returned value - (i32.const 4) ;; length of returned value + (i32.const 100) ;; Pointer to returned value + (i32.const 32) ;; length of returned value ) ) diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 4ad108b18d33..c6c456ea9d52 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -99,7 +99,6 @@ pub mod chain_extension; pub mod debug; pub mod migration; pub mod weights; -pub mod xcm; #[cfg(test)] mod tests; @@ -110,7 +109,6 @@ use crate::{ gas::GasMeter, storage::{meter::Meter as StorageMeter, ContractInfo, DeletionQueueManager}, wasm::{CodeInfo, WasmBlob}, - xcm::Xcm, }; use codec::{Codec, Decode, Encode, HasCompact, MaxEncodedLen}; use environmental::*; @@ -408,9 +406,11 @@ pub mod pallet { /// A type that exposes XCM APIs, allowing contracts to interact with other parachains, and /// execute XCM programs. - /// - /// Use [`xcm::XcmAdapter`] to enable or `()` to disable. - type Xcm: Xcm; + type Xcm: xcm_executor::traits::Controller< + OriginFor, + ::RuntimeCall, + BlockNumberFor, + >; } #[pallet::hooks] @@ -1012,8 +1012,8 @@ pub mod pallet { /// in this error. Note that this usually shouldn't happen as deploying such contracts /// is rejected. NoChainExtension, - /// Xcm function was invoked while the feature is disabled. - XcmDisabled, + /// Failed to decode the XCM program. + XCMDecodeFailed, /// A contract with the same AccountId already exists. DuplicateContract, /// A contract self destructed in its constructor. diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain.rs b/substrate/frame/contracts/src/tests/mock_network/parachain.rs index a6421d596161..978879b64933 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain.rs @@ -41,15 +41,13 @@ use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, ConvertedConcreteId, CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, FungiblesAdapter, IsConcrete, NativeAsset, NoChecking, - ParentAsSuperuser, ParentIsPreset, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, + ParentAsSuperuser, ParentIsPreset, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, WithComputedOrigin, }; use xcm_executor::{traits::JustTry, Config, XcmExecutor}; -pub type SovereignAccountOf = ( - AccountId32Aliases, - ParentIsPreset, -); +pub type SovereignAccountOf = + (AccountId32Aliases, ParentIsPreset); parameter_types! { pub const BlockHashCount: u64 = 250; @@ -100,6 +98,7 @@ impl pallet_balances::Config for Runtime { type ReserveIdentifier = [u8; 8]; type RuntimeEvent = RuntimeEvent; type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; type WeightInfo = (); } diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs index 38491f47f078..163d565daac0 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs +++ b/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs @@ -21,7 +21,6 @@ use crate::{ parachain::RuntimeHoldReason, primitives::{Balance, CENTS}, }, - xcm::XcmAdapter, Config, }; use frame_support::{ @@ -98,5 +97,5 @@ impl Config for Runtime { type WeightPrice = Self; type Debug = (); type Environment = (); - type Xcm = XcmAdapter; + type Xcm = pallet_xcm::Pallet; } diff --git a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs index 8e659415abe8..69207ea6985c 100644 --- a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs +++ b/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs @@ -30,12 +30,11 @@ use polkadot_parachain_primitives::primitives::Id as ParaId; use polkadot_runtime_parachains::{configuration, origin, shared}; use xcm::latest::prelude::*; use xcm_builder::{ - HashedDescription, DescribeFamily, DescribeAllTerminal, AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, ChildParachainConvertsVia, - ChildSystemParachainAsSuperuser, CurrencyAdapter as XcmCurrencyAdapter, FixedRateOfFungible, - FixedWeightBounds, IsConcrete, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, + ChildSystemParachainAsSuperuser, CurrencyAdapter as XcmCurrencyAdapter, DescribeAllTerminal, + DescribeFamily, FixedRateOfFungible, FixedWeightBounds, HashedDescription, IsConcrete, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, }; use xcm_executor::{Config, XcmExecutor}; @@ -93,7 +92,8 @@ impl pallet_balances::Config for Runtime { type FreezeIdentifier = (); type MaxHolds = ConstU32<0>; type MaxFreezes = ConstU32<0>; - type RuntimeHoldReason = (); + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; } impl shared::Config for Runtime {} diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index 9130432981c2..a7dc54584b90 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -44,8 +44,7 @@ use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; use xcm_simulator::TestExt; type ParachainContracts = crate::Pallet; -type QueryId = - <::Xcm as crate::Xcm>::QueryId; +type QueryId = as QueryHandler>::QueryId; /// Instantiate the tests contract, and fund it with some balance and assets. fn instantiate_test_contract(name: &str) -> AccountId { @@ -152,15 +151,7 @@ fn test_xcm_execute_filtered_call() { Determinism::Enforced, ); - // The debug message should say that the call was filtered. - assert_eq!( - std::str::from_utf8(&result.debug_message).unwrap(), - "call failed with: CallFiltered" - ); - - // The call should fail, with an `OutOfGas` error, as the failed xcm::execute will not - // refund the max_weight gas passed to it. - assert_err!(result.result, crate::Error::::OutOfGas); + assert_err!(result.result, frame_system::Error::::CallFiltered); }); } @@ -233,7 +224,7 @@ fn test_xcm_send() { LockAsset { asset: (Here, 5 * CENTS).into(), unlocker: (Parachain(1)).into() }, ]); let message = VersionedXcm::V3(message); - let result = ParachainContracts::bare_call( + let exec = ParachainContracts::bare_call( ALICE, contract_addr.clone(), 0, @@ -243,11 +234,10 @@ fn test_xcm_send() { DebugInfo::UnsafeDebug, CollectEvents::UnsafeCollect, Determinism::Enforced, - ) - .result - .unwrap(); + ); - assert_return_code!(result, RuntimeReturnCode::Success); + let mut data = &exec.result.unwrap().data[..]; + XcmHash::decode(&mut data).expect("Failed to decode message"); }); Relay::execute_with(|| { @@ -286,7 +276,7 @@ fn test_xcm_query() { let query_id = QueryId::decode(&mut data).expect("Failed to decode message"); // Verify that the query exists and is pending. - let response = ParachainPalletXcm::take_response(query_id); + let response = ::take_response(query_id); let expected_response = QueryResponseStatus::Pending { timeout }; assert_eq!(response, expected_response); }); diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 30f89c95271c..77d40582ae60 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -23,12 +23,15 @@ use crate::{ schedule::HostFnWeights, BalanceOf, CodeHash, Config, DebugBufferVec, Error, SENTINEL, }; - use bitflags::bitflags; use codec::{Decode, DecodeLimit, Encode, MaxEncodedLen}; use frame_support::{ - dispatch::DispatchInfo, ensure, pallet_prelude::DispatchResultWithPostInfo, parameter_types, - traits::Get, weights::Weight, + dispatch::DispatchInfo, + ensure, + pallet_prelude::{DispatchResult, DispatchResultWithPostInfo}, + parameter_types, + traits::Get, + weights::Weight, }; use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags}; use pallet_contracts_proc_macro::define_env; @@ -39,6 +42,9 @@ use sp_runtime::{ }; use sp_std::{fmt, prelude::*}; use wasmi::{core::HostError, errors::LinkerError, Linker, Memory, Store}; +use xcm::VersionedXcm; + +type CallOf = ::RuntimeCall; /// The maximum nesting depth a contract can use when encoding types. const MAX_DECODE_NESTING: u32 = 256; @@ -477,6 +483,29 @@ fn already_charged(_: u32) -> Option { None } +/// Ensure that the XCM program is executable, by checking that it does not contain any [`Transact`] +/// instruction with a call that is not allowed by the CallFilter. +fn ensure_executable(message: &VersionedXcm>) -> DispatchResult { + use frame_support::traits::Contains; + use xcm::prelude::{Transact, Xcm}; + + let mut message: Xcm> = + message.clone().try_into().map_err(|_| Error::::XCMDecodeFailed)?; + + message.iter_mut().try_for_each(|inst| -> DispatchResult { + let Transact { ref mut call, .. } = inst else { return Ok(()) }; + let call = call.ensure_decoded().map_err(|_| Error::::XCMDecodeFailed)?; + + if !::CallFilter::contains(call) { + return Err(frame_system::Error::::CallFiltered.into()) + } + + Ok(()) + })?; + + Ok(()) +} + /// Can only be used for one call. pub struct Runtime<'a, E: Ext + 'a> { ext: &'a mut E, @@ -2679,22 +2708,25 @@ pub mod env { msg_ptr: u32, msg_len: u32, ) -> Result { - use crate::xcm::{CallOf, WeightInfo, Xcm}; use frame_support::dispatch::DispatchInfo; use xcm::VersionedXcm; + use xcm_executor::traits::{ExecuteController, ExecuteControllerWeightInfo}; ctx.charge_gas(RuntimeCosts::CopyFromContract(msg_len))?; let message: VersionedXcm> = ctx.read_sandbox_memory_as_unbounded(memory, msg_ptr, msg_len)?; - let execute_weight = <::Xcm as Xcm>::WeightInfo::execute(); + let execute_weight = + <::Xcm as ExecuteController<_, _>>::WeightInfo::execute(); let weight = ctx.ext.gas_meter().gas_left().max(execute_weight); let dispatch_info = DispatchInfo { weight, ..Default::default() }; + ensure_executable::(&message)?; ctx.call_dispatchable::(dispatch_info, |ext| { - <::Xcm as Xcm>::execute( - ext.address(), - message, + let origin = crate::RawOrigin::Signed(ext.address().clone()).into(); + <::Xcm>::execute( + origin, + Box::new(message), weight.saturating_sub(execute_weight), ) }) @@ -2710,6 +2742,7 @@ pub mod env { /// is placed. /// - `call_ptr`: the pointer into the linear memory where the message is placed. /// - `call_len`: the length of the message in bytes. + /// - `output_ptr`: the pointer into the linear memory where the message id is placed. /// /// # Return Value /// @@ -2722,20 +2755,25 @@ pub mod env { dest_ptr: u32, call_ptr: u32, call_len: u32, + output_ptr: u32, ) -> Result { - use crate::xcm::{WeightInfo, Xcm}; use xcm::{VersionedMultiLocation, VersionedXcm}; + use xcm_executor::traits::{SendController, SendControllerWeightInfo}; ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; let dest: VersionedMultiLocation = ctx.read_sandbox_memory_as(memory, dest_ptr)?; let message: VersionedXcm<()> = ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; - let weight = <::Xcm as Xcm>::WeightInfo::send(); + let weight = <::Xcm as SendController<_>>::WeightInfo::send(); ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; + let origin = crate::RawOrigin::Signed(ctx.ext.address().clone()).into(); - match <::Xcm as Xcm>::send(ctx.ext.address(), dest, message) { - Ok(_) => Ok(ReturnCode::Success), + match <::Xcm>::send(origin, dest.into(), message.into()) { + Ok(message_id) => { + ctx.write_sandbox_memory(memory, output_ptr, &message_id.encode())?; + Ok(ReturnCode::Success) + }, Err(e) => { if ctx.ext.append_debug_buffer("") { ctx.ext.append_debug_buffer("seal0::xcm_send failed with: "); @@ -2766,19 +2804,19 @@ pub mod env { match_querier_ptr: u32, output_ptr: u32, ) -> Result { - use crate::xcm::{WeightInfo, Xcm}; use frame_system::pallet_prelude::BlockNumberFor; use xcm::VersionedMultiLocation; + use xcm_executor::traits::{QueryController, QueryControllerWeightInfo}; let timeout: BlockNumberFor = ctx.read_sandbox_memory_as(memory, timeout_ptr)?; let match_querier: VersionedMultiLocation = ctx.read_sandbox_memory_as(memory, match_querier_ptr)?; - let weight = <::Xcm as Xcm>::WeightInfo::query(); + let weight = <::Xcm as QueryController<_, _>>::WeightInfo::query(); ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; + let origin = crate::RawOrigin::Signed(ctx.ext.address().clone()).into(); - match <::Xcm as Xcm>::query(ctx.ext.address(), timeout, match_querier) - { + match <::Xcm>::query(origin, timeout, match_querier) { Ok(query_id) => { ctx.write_sandbox_memory(memory, output_ptr, &query_id.encode())?; Ok(ReturnCode::Success) @@ -2811,16 +2849,16 @@ pub mod env { query_id_ptr: u32, output_ptr: u32, ) -> Result { - use crate::xcm::{WeightInfo, Xcm}; + use xcm_executor::traits::{QueryController, QueryControllerWeightInfo}; - let query_id: <::Xcm as Xcm>::QueryId = + let query_id: <::Xcm as QueryController<_, _>>::QueryId = ctx.read_sandbox_memory_as(memory, query_id_ptr)?; - let weight = <::Xcm as Xcm>::WeightInfo::take_response(); + let weight = <::Xcm as QueryController<_, _>>::WeightInfo::take_response(); ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; - // - let response = <::Xcm as Xcm>::take_response(query_id); - ctx.write_sandbox_memory(memory, output_ptr, &response.encode())?; + + let response = <::Xcm>::take_response(query_id).encode(); + ctx.write_sandbox_memory(memory, output_ptr, &response)?; Ok(ReturnCode::Success) } diff --git a/substrate/frame/contracts/src/xcm.rs b/substrate/frame/contracts/src/xcm.rs deleted file mode 100644 index bb7964cce1c3..000000000000 --- a/substrate/frame/contracts/src/xcm.rs +++ /dev/null @@ -1,138 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::{AccountIdOf, Config, Error}; -use codec::{Decode, Encode, MaxEncodedLen}; -use frame_support::{pallet_prelude::DispatchResultWithPostInfo, weights::Weight}; -use frame_system::pallet_prelude::BlockNumberFor; -use sp_runtime::{DispatchError, DispatchResult}; -use xcm::{VersionedMultiLocation, VersionedXcm}; -use xcm_executor::traits::QueryResponseStatus; - -pub mod adapter; - -pub use adapter::XcmAdapter; -pub type CallOf = ::RuntimeCall; - -pub trait Xcm { - type QueryId: Encode + Decode + MaxEncodedLen; - type WeightInfo: WeightInfo; - - /// Execute an XCM locally. see [`pallet_xcm::pallet::Pallet::execute`] - /// - /// # Parameters - /// - /// - `origin`: the origin of the call. - /// - `message`: the XCM program to be executed. - /// - `max_weight`: the maximum weight that can be consumed by the execution. - fn execute( - origin: &AccountIdOf, - message: VersionedXcm>, - max_weight: Weight, - ) -> DispatchResultWithPostInfo; - - /// Send an XCM to be executed by a remote location. see - /// [`pallet_xcm::pallet::Pallet::send`] - /// - /// # Parameters - /// - /// - `origin`: the origin of the call. - /// - `dest`: the destination of the message. - /// - `msg`: the XCM to be sent. - fn send( - origin: &AccountIdOf, - dest: VersionedMultiLocation, - msg: VersionedXcm<()>, - ) -> DispatchResult; - - /// Query a remote location. see [`xcm_executor::traits::QueryHandler::new_query`] - /// - /// # Parameters - /// - /// - `origin`: the origin of the call, used to determine the responder. - /// - `timeout`: the maximum block number that the query should be responded to. - /// - `match_querier`: the querier that the query should be responded to. - fn query( - origin: &AccountIdOf, - timeout: BlockNumberFor, - match_querier: VersionedMultiLocation, - ) -> Result; - - /// Take an XCM response for the specified query. see - /// [`xcm_executor::traits::QueryHandler::take_response`] - /// - /// # Parameters - /// - /// - `query_id`: the query id returned by [`Self::query`]. - fn take_response(query_id: Self::QueryId) -> QueryResponseStatus>; -} - -impl Xcm for () { - type QueryId = (); - type WeightInfo = Self; - fn execute( - _origin: &AccountIdOf, - _message: VersionedXcm>, - _max_weight: Weight, - ) -> DispatchResultWithPostInfo { - Err(Error::::XcmDisabled.into()) - } - fn send( - _origin: &AccountIdOf, - _dest: VersionedMultiLocation, - _msg: VersionedXcm<()>, - ) -> DispatchResult { - Err(Error::::XcmDisabled.into()) - } - fn query( - _origin: &AccountIdOf, - _timeout: BlockNumberFor, - _match_querier: VersionedMultiLocation, - ) -> Result { - Err(Error::::XcmDisabled.into()) - } - fn take_response(_query_id: Self::QueryId) -> QueryResponseStatus> { - QueryResponseStatus::UnexpectedVersion - } -} - -/// Weight info trait for methods exposed by the [`Xcm`] trait. -pub trait WeightInfo { - /// Weight of the [`Xcm::execute`] function. - fn execute() -> Weight; - /// Weight of the [`Xcm::send`] function. - fn send() -> Weight; - /// Weight of the [`Xcm::query`] function. - fn query() -> Weight; - /// Weight of the [`Xcm::take_response`] function. - fn take_response() -> Weight; -} - -impl WeightInfo for () { - fn execute() -> Weight { - Weight::zero() - } - fn send() -> Weight { - Weight::zero() - } - fn query() -> Weight { - Weight::zero() - } - fn take_response() -> Weight { - Weight::zero() - } -} diff --git a/substrate/frame/contracts/src/xcm/adapter.rs b/substrate/frame/contracts/src/xcm/adapter.rs deleted file mode 100644 index bca2aff818aa..000000000000 --- a/substrate/frame/contracts/src/xcm/adapter.rs +++ /dev/null @@ -1,135 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Adapter exposes an implementation of the [`Xcm`] trait using pallet-xcm. - -use crate::{ - xcm::{CallOf, WeightInfo, Xcm}, - AccountIdOf, Box, Config, RawOrigin, -}; -use frame_support::{ - pallet_prelude::{DispatchResultWithPostInfo, IsType}, - weights::Weight, -}; -use frame_system::pallet_prelude::BlockNumberFor; -use pallet_xcm::WeightInfo as XcmWeightInfo; -use sp_runtime::{DispatchError, DispatchResult}; -use xcm::{v3::MultiLocation, VersionedMultiLocation, VersionedXcm}; -use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; - -pub type XcmCallOf = ::RuntimeCall; - -/// An implementation of the [`Xcm`] trait using pallet-xcm. -pub struct XcmAdapter(sp_std::marker::PhantomData); - -impl WeightInfo for XcmAdapter { - fn execute() -> Weight { - ::WeightInfo::execute() - } - fn send() -> Weight { - ::WeightInfo::send() - } - fn query() -> Weight { - ::WeightInfo::new_query() - } - fn take_response() -> Weight { - ::WeightInfo::take_response() - } -} - -impl XcmAdapter -where - T: Config + pallet_xcm::Config, - ::RuntimeCall: IsType<::RuntimeCall>, -{ - /// Ensure that the message is executable, by checking that it does not contain any [`Transact`] - /// instruction with a call that is not allowed by the CallFilter. - fn ensure_executable( - message: VersionedXcm>, - ) -> Result>>, DispatchError> { - use frame_support::traits::Contains; - use xcm::prelude::{Transact, Xcm}; - - let mut message: Xcm> = - message.try_into().map_err(|_| pallet_xcm::Error::::BadVersion)?; - - message.iter_mut().try_for_each(|inst| -> Result<(), DispatchError> { - let Transact { ref mut call, .. } = inst else { return Ok(()) }; - let call = call.ensure_decoded().map_err(|_| pallet_xcm::Error::::BadVersion)?; - - if !::CallFilter::contains(call) { - return Err(frame_system::Error::::CallFiltered.into()) - } - - Ok(()) - })?; - - Ok(Box::new(VersionedXcm::from(message.into()))) - } -} - -impl Xcm for XcmAdapter -where - T: Config + pallet_xcm::Config, - ::RuntimeCall: IsType<::RuntimeCall>, -{ - type QueryId = as QueryHandler>::QueryId; - type WeightInfo = Self; - - fn execute( - origin: &AccountIdOf, - message: VersionedXcm>, - max_weight: Weight, - ) -> DispatchResultWithPostInfo { - let msg = Self::ensure_executable(message)?; - let origin = RawOrigin::Signed(origin.clone()).into(); - pallet_xcm::Pallet::::execute(origin, msg, max_weight) - } - - fn send( - origin: &AccountIdOf, - dest: VersionedMultiLocation, - msg: VersionedXcm<()>, - ) -> DispatchResult { - let origin = RawOrigin::Signed(origin.clone()).into(); - pallet_xcm::Pallet::::send(origin, Box::new(dest), Box::new(msg)) - } - - fn query( - origin: &AccountIdOf, - timeout: BlockNumberFor, - match_querier: VersionedMultiLocation, - ) -> Result { - use frame_support::traits::EnsureOrigin; - - let origin = RawOrigin::Signed(origin.clone()).into(); - let responder = ::ExecuteXcmOrigin::ensure_origin(origin)?; - - let query_id = as QueryHandler>::new_query( - responder, - timeout.into(), - MultiLocation::try_from(match_querier) - .map_err(|_| Into::::into(pallet_xcm::Error::::BadVersion))?, - ); - - Ok(query_id) - } - - fn take_response(query_id: Self::QueryId) -> QueryResponseStatus> { - as QueryHandler>::take_response(query_id) - } -} From 54e28034d04327f964f5172f99e98d56a9b31333 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 27 Oct 2023 18:43:12 +0200 Subject: [PATCH 072/115] Add copyright --- .../xcm/xcm-executor/src/traits/controller.rs | 88 ++++++++++++------- 1 file changed, 54 insertions(+), 34 deletions(-) diff --git a/polkadot/xcm/xcm-executor/src/traits/controller.rs b/polkadot/xcm/xcm-executor/src/traits/controller.rs index c74b8c5fff50..8cc2da9607ff 100644 --- a/polkadot/xcm/xcm-executor/src/traits/controller.rs +++ b/polkadot/xcm/xcm-executor/src/traits/controller.rs @@ -1,8 +1,27 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! A set of traits that define how a pallet interface with XCM. + use frame_support::pallet_prelude::*; use sp_weights::Weight; use xcm::{v3::XcmHash, VersionedMultiLocation, VersionedXcm}; use crate::traits::QueryResponseStatus; + /// Umbrella trait for all Controller traits. pub trait Controller: ExecuteController + SendController + QueryController {} impl Controller for T @@ -33,23 +52,6 @@ pub trait ExecuteController { ) -> DispatchResultWithPostInfo; } -impl ExecuteController for () { - type WeightInfo = (); - fn execute( - _origin: Origin, - _message: Box>, - _max_weight: Weight, - ) -> DispatchResultWithPostInfo { - Ok(().into()) - } -} - -impl ExecuteControllerWeightInfo for () { - fn execute() -> Weight { - Weight::zero() - } -} - /// Weight functions needed for [`SendController`]. pub trait SendControllerWeightInfo { /// Weight for [`SendController::send`] @@ -74,23 +76,6 @@ pub trait SendController { ) -> Result; } -impl SendController for () { - type WeightInfo = (); - fn send( - _origin: Origin, - _dest: Box, - _message: Box>, - ) -> Result { - Ok(Default::default()) - } -} - -impl SendControllerWeightInfo for () { - fn send() -> Weight { - Weight::zero() - } -} - /// Weight functions needed for [`QueryController`]. pub trait QueryControllerWeightInfo { /// Weight for [`QueryController::query`] @@ -125,6 +110,40 @@ pub trait QueryController { fn take_response(query_id: Self::QueryId) -> QueryResponseStatus; } +impl ExecuteController for () { + type WeightInfo = (); + fn execute( + _origin: Origin, + _message: Box>, + _max_weight: Weight, + ) -> DispatchResultWithPostInfo { + Ok(().into()) + } +} + +impl ExecuteControllerWeightInfo for () { + fn execute() -> Weight { + Weight::zero() + } +} + +impl SendController for () { + type WeightInfo = (); + fn send( + _origin: Origin, + _dest: Box, + _message: Box>, + ) -> Result { + Ok(Default::default()) + } +} + +impl SendControllerWeightInfo for () { + fn send() -> Weight { + Weight::zero() + } +} + impl QueryController for () { type QueryId = u64; type BlockNumber = u64; @@ -140,6 +159,7 @@ impl QueryController for () { QueryResponseStatus::NotFound } } + impl QueryControllerWeightInfo for () { fn query() -> Weight { Weight::zero() From ce637dcb0256ac8d2e39e8f2d0983d3f6909f34f Mon Sep 17 00:00:00 2001 From: pgherveou Date: Sun, 29 Oct 2023 07:27:32 +0100 Subject: [PATCH 073/115] reuse QueryHandler --- polkadot/xcm/pallet-xcm/src/lib.rs | 6 -- .../xcm/xcm-executor/src/traits/controller.rs | 66 ++++++++++++++----- polkadot/xcm/xcm-executor/src/traits/mod.rs | 4 +- .../xcm-executor/src/traits/on_response.rs | 2 +- substrate/frame/contracts/src/wasm/runtime.rs | 4 +- 5 files changed, 53 insertions(+), 29 deletions(-) diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 4635c23f0833..c39fc0f5d766 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -357,8 +357,6 @@ pub mod pallet { impl QueryController, BlockNumberFor> for Pallet { type WeightInfo = Self; - type QueryId = ::QueryId; - type BlockNumber = BlockNumberFor; fn query( origin: OriginFor, @@ -375,10 +373,6 @@ pub mod pallet { Ok(query_id) } - - fn take_response(query_id: Self::QueryId) -> QueryResponseStatus { - ::take_response(query_id) - } } #[pallet::event] diff --git a/polkadot/xcm/xcm-executor/src/traits/controller.rs b/polkadot/xcm/xcm-executor/src/traits/controller.rs index 8cc2da9607ff..81b93daf2292 100644 --- a/polkadot/xcm/xcm-executor/src/traits/controller.rs +++ b/polkadot/xcm/xcm-executor/src/traits/controller.rs @@ -16,17 +16,27 @@ //! A set of traits that define how a pallet interface with XCM. -use frame_support::pallet_prelude::*; +use crate::{ + traits::{QueryHandler, QueryResponseStatus}, + InteriorMultiLocation, + Junctions::Here, + MultiLocation, Xcm, +}; +use frame_support::{pallet_prelude::*, parameter_types}; use sp_weights::Weight; use xcm::{v3::XcmHash, VersionedMultiLocation, VersionedXcm}; -use crate::traits::QueryResponseStatus; - /// Umbrella trait for all Controller traits. -pub trait Controller: ExecuteController + SendController + QueryController {} -impl Controller for T -where T: ExecuteController + SendController + QueryController -{} +pub trait Controller: + ExecuteController + SendController + QueryController +{ +} +impl Controller for T where + T: ExecuteController + + SendController + + QueryController +{ +} /// Weight functions needed for [`ExecuteController`]. pub trait ExecuteControllerWeightInfo { @@ -86,9 +96,7 @@ pub trait QueryControllerWeightInfo { } /// Query a remote location, from a given origin. -pub trait QueryController { - type QueryId: Encode + Decode + MaxEncodedLen; - type BlockNumber: Encode + Decode + MaxEncodedLen; +pub trait QueryController: QueryHandler { type WeightInfo: QueryControllerWeightInfo; /// Query a remote location. @@ -103,11 +111,6 @@ pub trait QueryController { timeout: Timeout, match_querier: VersionedMultiLocation, ) -> Result; - - /// Take an XCM response for the specified query. - /// - /// - `query_id`: the query id returned by [`Self::query`]. - fn take_response(query_id: Self::QueryId) -> QueryResponseStatus; } impl ExecuteController for () { @@ -145,9 +148,8 @@ impl SendControllerWeightInfo for () { } impl QueryController for () { - type QueryId = u64; - type BlockNumber = u64; type WeightInfo = (); + fn query( _origin: Origin, _timeout: Timeout, @@ -155,9 +157,39 @@ impl QueryController for () { ) -> Result { Ok(Default::default()) } +} + +parameter_types! { + pub UniversalLocation: InteriorMultiLocation = Here; +} + +impl QueryHandler for () { + type BlockNumber = u64; + type Error = (); + type QueryId = u64; + type UniversalLocation = UniversalLocation; + fn take_response(_query_id: Self::QueryId) -> QueryResponseStatus { QueryResponseStatus::NotFound } + fn new_query( + _responder: impl Into, + _timeout: Self::BlockNumber, + _match_querier: impl Into, + ) -> Self::QueryId { + 0u64 + } + + fn report_outcome( + _message: &mut Xcm<()>, + _responder: impl Into, + _timeout: Self::BlockNumber, + ) -> Result { + Err(()) + } + + #[cfg(feature = "runtime-benchmarks")] + fn expect_response(_id: Self::QueryId, _response: Response) {} } impl QueryControllerWeightInfo for () { diff --git a/polkadot/xcm/xcm-executor/src/traits/mod.rs b/polkadot/xcm/xcm-executor/src/traits/mod.rs index 069bcb3bf9c7..2240936b6ef8 100644 --- a/polkadot/xcm/xcm-executor/src/traits/mod.rs +++ b/polkadot/xcm/xcm-executor/src/traits/mod.rs @@ -38,9 +38,7 @@ pub use token_matching::{ Error, MatchesFungible, MatchesFungibles, MatchesNonFungible, MatchesNonFungibles, }; mod on_response; -pub use on_response::{ - OnResponse, QueryHandler, QueryResponseStatus, VersionChangeNotifier, -}; +pub use on_response::{OnResponse, QueryHandler, QueryResponseStatus, VersionChangeNotifier}; mod should_execute; pub use should_execute::{CheckSuspension, Properties, ShouldExecute}; mod transact_asset; diff --git a/polkadot/xcm/xcm-executor/src/traits/on_response.rs b/polkadot/xcm/xcm-executor/src/traits/on_response.rs index a0ed9522df6c..7d20a36419f1 100644 --- a/polkadot/xcm/xcm-executor/src/traits/on_response.rs +++ b/polkadot/xcm/xcm-executor/src/traits/on_response.rs @@ -129,7 +129,7 @@ pub trait QueryHandler { + PartialEq + Debug + Copy; - type BlockNumber: Zero; + type BlockNumber: Zero + Encode; type Error; type UniversalLocation: Get; diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 77d40582ae60..acfbd2d101b3 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2849,9 +2849,9 @@ pub mod env { query_id_ptr: u32, output_ptr: u32, ) -> Result { - use xcm_executor::traits::{QueryController, QueryControllerWeightInfo}; + use xcm_executor::traits::{QueryController, QueryHandler, QueryControllerWeightInfo}; - let query_id: <::Xcm as QueryController<_, _>>::QueryId = + let query_id: <::Xcm as QueryHandler>::QueryId = ctx.read_sandbox_memory_as(memory, query_id_ptr)?; let weight = <::Xcm as QueryController<_, _>>::WeightInfo::take_response(); From 582467d9d2e3b0a90b7c0ba1ca45db03b456d284 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 30 Oct 2023 17:12:40 +0100 Subject: [PATCH 074/115] Contracts: Add XCM traits to interface with contracts --- polkadot/xcm/pallet-xcm/src/benchmarking.rs | 27 +++ polkadot/xcm/pallet-xcm/src/lib.rs | 159 ++++++++++---- .../xcm/xcm-executor/src/traits/controller.rs | 202 ++++++++++++++++++ polkadot/xcm/xcm-executor/src/traits/mod.rs | 2 + .../xcm-executor/src/traits/on_response.rs | 6 +- 5 files changed, 355 insertions(+), 41 deletions(-) create mode 100644 polkadot/xcm/xcm-executor/src/traits/controller.rs diff --git a/polkadot/xcm/pallet-xcm/src/benchmarking.rs b/polkadot/xcm/pallet-xcm/src/benchmarking.rs index aca4bd1fb3fa..c80751c8ebea 100644 --- a/polkadot/xcm/pallet-xcm/src/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm/src/benchmarking.rs @@ -190,6 +190,33 @@ benchmarks! { Pallet::::check_xcm_version_change(VersionMigrationStage::MigrateAndNotifyOldTargets, Weight::zero()); } + new_query { + let responder = MultiLocation::from(Parent); + let timeout = 1u32.into(); + let match_querier = MultiLocation::from(Here); + }: { + Pallet::::new_query(responder, timeout, match_querier); + } + + take_response { + let responder = MultiLocation::from(Parent); + let timeout = 1u32.into(); + let match_querier = MultiLocation::from(Here); + let query_id = Pallet::::new_query(responder, timeout, match_querier); + let infos = (0 .. xcm::v3::MaxPalletsInfo::get()).map(|_| PalletInfo::new( + u32::MAX, + (0..xcm::v3::MaxPalletNameLen::get()).map(|_| 97u8).collect::>().try_into().unwrap(), + (0..xcm::v3::MaxPalletNameLen::get()).map(|_| 97u8).collect::>().try_into().unwrap(), + u32::MAX, + u32::MAX, + u32::MAX, + ).unwrap()).collect::>(); + Pallet::::expect_response(query_id, Response::PalletsInfo(infos.try_into().unwrap())); + + }: { + Pallet::::take_response(query_id); + } + impl_benchmark_test_suite!( Pallet, crate::mock::new_test_ext_with_balances(Vec::new()), diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 321bb294b88d..c39fc0f5d766 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -28,9 +28,17 @@ mod tests; pub mod migration; use codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; -use frame_support::traits::{ - Contains, ContainsPair, Currency, Defensive, EnsureOrigin, Get, LockableCurrency, OriginTrait, +use frame_support::{ + dispatch::GetDispatchInfo, + pallet_prelude::*, + traits::{ + Contains, ContainsPair, Currency, Defensive, EnsureOrigin, Get, LockableCurrency, + OriginTrait, WithdrawReasons, + }, + PalletId, }; +use frame_system::pallet_prelude::{BlockNumberFor, *}; +pub use pallet::*; use scale_info::TypeInfo; use sp_runtime::{ traits::{ @@ -41,17 +49,13 @@ use sp_runtime::{ }; use sp_std::{boxed::Box, marker::PhantomData, prelude::*, result::Result, vec}; use xcm::{latest::QueryResponseInfo, prelude::*}; -use xcm_executor::traits::{ConvertOrigin, Properties}; - -use frame_support::{ - dispatch::GetDispatchInfo, pallet_prelude::*, traits::WithdrawReasons, PalletId, -}; -use frame_system::pallet_prelude::*; -pub use pallet::*; use xcm_executor::{ traits::{ - CheckSuspension, ClaimAssets, ConvertLocation, DropAssets, MatchesFungible, OnResponse, - QueryHandler, QueryResponseStatus, VersionChangeNotifier, WeightBounds, + CheckSuspension, ClaimAssets, ConvertLocation, ConvertOrigin, DropAssets, + ExecuteController, ExecuteControllerWeightInfo, MatchesFungible, OnResponse, Properties, + QueryController, QueryControllerWeightInfo, QueryHandler, + QueryResponseStatus, SendController, SendControllerWeightInfo, VersionChangeNotifier, + WeightBounds, }, Assets, }; @@ -73,6 +77,13 @@ pub trait WeightInfo { fn notify_target_migration_fail() -> Weight; fn migrate_version_notify_targets() -> Weight; fn migrate_and_notify_old_targets() -> Weight; + // TODO remove after benchmark are regenerated + fn new_query() -> Weight { + Weight::zero() + } + fn take_response() -> Weight { + Weight::zero() + } } /// fallback implementation @@ -141,6 +152,14 @@ impl WeightInfo for TestWeightInfo { fn migrate_and_notify_old_targets() -> Weight { Weight::from_parts(100_000_000, 0) } + + fn new_query() -> Weight { + Weight::from_parts(100_000_000, 0) + } + + fn take_response() -> Weight { + Weight::from_parts(100_000_000, 0) + } } #[frame_support::pallet] @@ -267,6 +286,95 @@ pub mod pallet { type ReachableDest: Get>; } + impl ExecuteControllerWeightInfo for Pallet { + fn execute() -> Weight { + T::WeightInfo::execute() + } + } + + impl ExecuteController, ::RuntimeCall> for Pallet { + type WeightInfo = Self; + fn execute( + origin: OriginFor, + message: Box::RuntimeCall>>, + max_weight: Weight, + ) -> DispatchResultWithPostInfo { + let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?; + let hash = message.using_encoded(sp_io::hashing::blake2_256); + let message = (*message).try_into().map_err(|()| Error::::BadVersion)?; + let value = (origin_location, message); + ensure!(T::XcmExecuteFilter::contains(&value), Error::::Filtered); + let (origin_location, message) = value; + let outcome = T::XcmExecutor::execute_xcm_in_credit( + origin_location, + message, + hash, + max_weight, + max_weight, + ); + let result = + Ok(Some(outcome.weight_used().saturating_add(T::WeightInfo::execute())).into()); + Self::deposit_event(Event::Attempted { outcome }); + result + } + } + + impl SendControllerWeightInfo for Pallet { + fn send() -> Weight { + T::WeightInfo::send() + } + } + + impl SendController> for Pallet { + type WeightInfo = Self; + fn send( + origin: OriginFor, + dest: Box, + message: Box>, + ) -> Result { + let origin_location = T::SendXcmOrigin::ensure_origin(origin)?; + let interior: Junctions = + origin_location.try_into().map_err(|_| Error::::InvalidOrigin)?; + let dest = MultiLocation::try_from(*dest).map_err(|()| Error::::BadVersion)?; + let message: Xcm<()> = (*message).try_into().map_err(|()| Error::::BadVersion)?; + + let message_id = + Self::send_xcm(interior, dest, message.clone()).map_err(Error::::from)?; + let e = Event::Sent { origin: origin_location, destination: dest, message, message_id }; + Self::deposit_event(e); + Ok(message_id) + } + } + + impl QueryControllerWeightInfo for Pallet { + fn query() -> Weight { + T::WeightInfo::new_query() + } + fn take_response() -> Weight { + T::WeightInfo::take_response() + } + } + + impl QueryController, BlockNumberFor> for Pallet { + type WeightInfo = Self; + + fn query( + origin: OriginFor, + timeout: BlockNumberFor, + match_querier: VersionedMultiLocation, + ) -> Result { + let responder = ::ExecuteXcmOrigin::ensure_origin(origin)?; + let query_id = ::new_query( + responder, + timeout.into(), + MultiLocation::try_from(match_querier) + .map_err(|_| Into::::into(Error::::BadVersion))?, + ); + + Ok(query_id) + } + } + #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { @@ -771,16 +879,7 @@ pub mod pallet { dest: Box, message: Box>, ) -> DispatchResult { - let origin_location = T::SendXcmOrigin::ensure_origin(origin)?; - let interior: Junctions = - origin_location.try_into().map_err(|_| Error::::InvalidOrigin)?; - let dest = MultiLocation::try_from(*dest).map_err(|()| Error::::BadVersion)?; - let message: Xcm<()> = (*message).try_into().map_err(|()| Error::::BadVersion)?; - - let message_id = - Self::send_xcm(interior, dest, message.clone()).map_err(Error::::from)?; - let e = Event::Sent { origin: origin_location, destination: dest, message, message_id }; - Self::deposit_event(e); + >::send(origin, dest, message)?; Ok(()) } @@ -904,23 +1003,7 @@ pub mod pallet { message: Box::RuntimeCall>>, max_weight: Weight, ) -> DispatchResultWithPostInfo { - let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?; - let hash = message.using_encoded(sp_io::hashing::blake2_256); - let message = (*message).try_into().map_err(|()| Error::::BadVersion)?; - let value = (origin_location, message); - ensure!(T::XcmExecuteFilter::contains(&value), Error::::Filtered); - let (origin_location, message) = value; - let outcome = T::XcmExecutor::execute_xcm_in_credit( - origin_location, - message, - hash, - max_weight, - max_weight, - ); - let result = - Ok(Some(outcome.weight_used().saturating_add(T::WeightInfo::execute())).into()); - Self::deposit_event(Event::Attempted { outcome }); - result + >::execute(origin, message, max_weight) } /// Extoll that a particular destination can be communicated with through a particular diff --git a/polkadot/xcm/xcm-executor/src/traits/controller.rs b/polkadot/xcm/xcm-executor/src/traits/controller.rs new file mode 100644 index 000000000000..81b93daf2292 --- /dev/null +++ b/polkadot/xcm/xcm-executor/src/traits/controller.rs @@ -0,0 +1,202 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! A set of traits that define how a pallet interface with XCM. + +use crate::{ + traits::{QueryHandler, QueryResponseStatus}, + InteriorMultiLocation, + Junctions::Here, + MultiLocation, Xcm, +}; +use frame_support::{pallet_prelude::*, parameter_types}; +use sp_weights::Weight; +use xcm::{v3::XcmHash, VersionedMultiLocation, VersionedXcm}; + +/// Umbrella trait for all Controller traits. +pub trait Controller: + ExecuteController + SendController + QueryController +{ +} +impl Controller for T where + T: ExecuteController + + SendController + + QueryController +{ +} + +/// Weight functions needed for [`ExecuteController`]. +pub trait ExecuteControllerWeightInfo { + /// Weight for [`ExecuteController::execute`] + fn execute() -> Weight; +} + +/// Execute an XCM locally, for a given origin. +pub trait ExecuteController { + type WeightInfo: ExecuteControllerWeightInfo; + + /// Execute an XCM locally. + /// + /// # Parameters + /// + /// - `origin`: the origin of the call. + /// - `message`: the XCM program to be executed. + /// - `max_weight`: the maximum weight that can be consumed by the execution. + fn execute( + origin: Origin, + message: Box>, + max_weight: Weight, + ) -> DispatchResultWithPostInfo; +} + +/// Weight functions needed for [`SendController`]. +pub trait SendControllerWeightInfo { + /// Weight for [`SendController::send`] + fn send() -> Weight; +} + +/// Send an XCM from a given origin. +pub trait SendController { + type WeightInfo: SendControllerWeightInfo; + + /// Send an XCM to be executed by a remote location. + /// + /// # Parameters + /// + /// - `origin`: the origin of the call. + /// - `dest`: the destination of the message. + /// - `msg`: the XCM to be sent. + fn send( + origin: Origin, + dest: Box, + message: Box>, + ) -> Result; +} + +/// Weight functions needed for [`QueryController`]. +pub trait QueryControllerWeightInfo { + /// Weight for [`QueryController::query`] + fn query() -> Weight; + + /// Weight for [`QueryController::take_response`] + fn take_response() -> Weight; +} + +/// Query a remote location, from a given origin. +pub trait QueryController: QueryHandler { + type WeightInfo: QueryControllerWeightInfo; + + /// Query a remote location. + /// + /// # Parameters + /// + /// - `origin`: the origin of the call, used to determine the responder. + /// - `timeout`: the maximum block number that the query should be responded to. + /// - `match_querier`: the querier that the query should be responded to. + fn query( + origin: Origin, + timeout: Timeout, + match_querier: VersionedMultiLocation, + ) -> Result; +} + +impl ExecuteController for () { + type WeightInfo = (); + fn execute( + _origin: Origin, + _message: Box>, + _max_weight: Weight, + ) -> DispatchResultWithPostInfo { + Ok(().into()) + } +} + +impl ExecuteControllerWeightInfo for () { + fn execute() -> Weight { + Weight::zero() + } +} + +impl SendController for () { + type WeightInfo = (); + fn send( + _origin: Origin, + _dest: Box, + _message: Box>, + ) -> Result { + Ok(Default::default()) + } +} + +impl SendControllerWeightInfo for () { + fn send() -> Weight { + Weight::zero() + } +} + +impl QueryController for () { + type WeightInfo = (); + + fn query( + _origin: Origin, + _timeout: Timeout, + _match_querier: VersionedMultiLocation, + ) -> Result { + Ok(Default::default()) + } +} + +parameter_types! { + pub UniversalLocation: InteriorMultiLocation = Here; +} + +impl QueryHandler for () { + type BlockNumber = u64; + type Error = (); + type QueryId = u64; + type UniversalLocation = UniversalLocation; + + fn take_response(_query_id: Self::QueryId) -> QueryResponseStatus { + QueryResponseStatus::NotFound + } + fn new_query( + _responder: impl Into, + _timeout: Self::BlockNumber, + _match_querier: impl Into, + ) -> Self::QueryId { + 0u64 + } + + fn report_outcome( + _message: &mut Xcm<()>, + _responder: impl Into, + _timeout: Self::BlockNumber, + ) -> Result { + Err(()) + } + + #[cfg(feature = "runtime-benchmarks")] + fn expect_response(_id: Self::QueryId, _response: Response) {} +} + +impl QueryControllerWeightInfo for () { + fn query() -> Weight { + Weight::zero() + } + fn take_response() -> Weight { + Weight::zero() + } +} diff --git a/polkadot/xcm/xcm-executor/src/traits/mod.rs b/polkadot/xcm/xcm-executor/src/traits/mod.rs index a9439968fa6c..2240936b6ef8 100644 --- a/polkadot/xcm/xcm-executor/src/traits/mod.rs +++ b/polkadot/xcm/xcm-executor/src/traits/mod.rs @@ -16,6 +16,8 @@ //! Various traits used in configuring the executor. +mod controller; +pub use controller::*; mod conversion; pub use conversion::{CallDispatcher, ConvertLocation, ConvertOrigin, WithOriginFilter}; mod drop_assets; diff --git a/polkadot/xcm/xcm-executor/src/traits/on_response.rs b/polkadot/xcm/xcm-executor/src/traits/on_response.rs index 3558160dc87d..7d20a36419f1 100644 --- a/polkadot/xcm/xcm-executor/src/traits/on_response.rs +++ b/polkadot/xcm/xcm-executor/src/traits/on_response.rs @@ -17,7 +17,7 @@ use crate::Xcm; use core::result; use frame_support::pallet_prelude::{Get, TypeInfo}; -use parity_scale_codec::{FullCodec, MaxEncodedLen}; +use parity_scale_codec::{Decode, Encode, FullCodec, MaxEncodedLen}; use sp_arithmetic::traits::Zero; use sp_std::fmt::Debug; use xcm::latest::{ @@ -103,7 +103,7 @@ impl VersionChangeNotifier for () { } /// The possible state of an XCM query response. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Encode, Decode)] pub enum QueryResponseStatus { /// The response has arrived, and includes the inner Response and the block number it arrived /// at. @@ -129,7 +129,7 @@ pub trait QueryHandler { + PartialEq + Debug + Copy; - type BlockNumber: Zero; + type BlockNumber: Zero + Encode; type Error; type UniversalLocation: Get; From 79535cbff1b4e95c4f905dfad2ae1d70476a32a4 Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Mon, 30 Oct 2023 17:29:48 +0100 Subject: [PATCH 075/115] Update polkadot/xcm/xcm-executor/src/traits/controller.rs --- polkadot/xcm/xcm-executor/src/traits/controller.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/polkadot/xcm/xcm-executor/src/traits/controller.rs b/polkadot/xcm/xcm-executor/src/traits/controller.rs index 81b93daf2292..37ec90be8ccb 100644 --- a/polkadot/xcm/xcm-executor/src/traits/controller.rs +++ b/polkadot/xcm/xcm-executor/src/traits/controller.rs @@ -31,6 +31,7 @@ pub trait Controller: ExecuteController + SendController + QueryController { } + impl Controller for T where T: ExecuteController + SendController From 0a02451bd0fa6cefcdfdc396b8c676f3461b4185 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Mon, 30 Oct 2023 17:33:33 +0100 Subject: [PATCH 076/115] Update doc --- polkadot/xcm/pallet-xcm/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index c39fc0f5d766..6462fa0dc329 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -995,7 +995,7 @@ pub mod pallet { /// execution attempt will be made. /// /// NOTE: A successful return to this does *not* imply that the `msg` was executed - /// successfully to completion; only that *some* of it was executed. + /// successfully to completion; only that it was attempted. #[pallet::call_index(3)] #[pallet::weight(max_weight.saturating_add(T::WeightInfo::execute()))] pub fn execute( From 9413874f2a7abf1b7a8d83ccfe165b8bac4aa82e Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 31 Oct 2023 10:38:34 +0100 Subject: [PATCH 077/115] use Outcome return value for xcm_execute --- .../frame/contracts/fixtures/xcm_execute.wat | 30 ++++++++++++++----- .../frame/contracts/src/tests/test_xcm.rs | 27 ++++++++--------- substrate/frame/contracts/src/wasm/runtime.rs | 24 +++++++++------ 3 files changed, 49 insertions(+), 32 deletions(-) diff --git a/substrate/frame/contracts/fixtures/xcm_execute.wat b/substrate/frame/contracts/fixtures/xcm_execute.wat index a08d29c1be81..b3459996a2e8 100644 --- a/substrate/frame/contracts/fixtures/xcm_execute.wat +++ b/substrate/frame/contracts/fixtures/xcm_execute.wat @@ -1,6 +1,6 @@ ;; This passes its input to `seal_xcm_execute` and returns the return value to its caller. (module - (import "seal0" "xcm_execute" (func $xcm_execute (param i32 i32) (result i32))) + (import "seal0" "xcm_execute" (func $xcm_execute (param i32 i32 i32) (result i32))) (import "seal0" "seal_input" (func $seal_input (param i32 i32))) (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) (import "env" "memory" (memory 1 1)) @@ -9,6 +9,15 @@ ;; Size of input buffer (data (i32.const 0) "\00\10") + (func $assert (param i32) + (block $ok + (br_if $ok + (get_local 0) + ) + (unreachable) + ) + ) + (func (export "call") ;; Receive the encoded call (call $seal_input @@ -19,17 +28,22 @@ ;; [0..4) - size of the call ;; [4..) - message - ;; Just use the call passed as input and store result to memory - (i32.store (i32.const 0) - (call $xcm_execute - (i32.const 4) ;; Pointer where the message is stored - (i32.load (i32.const 0)) ;; Size of the message + ;; Call xcm_execute with provided input. + (call $assert + (i32.eq + (call $xcm_execute + (i32.const 4) ;; Pointer where the message is stored + (i32.load (i32.const 0)) ;; Size of the message + (i32.const 100) ;; Pointer to the where the outcome is stored + ) + (i32.const 0) ) ) + (call $seal_return (i32.const 0) ;; flags - (i32.const 0) ;; Pointer to returned value - (i32.const 4) ;; length of returned value + (i32.const 100) ;; Pointer to returned value + (i32.const 10) ;; length of returned value ) ) diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/src/tests/test_xcm.rs index a7dc54584b90..d34bc23dee0c 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/src/tests/test_xcm.rs @@ -16,7 +16,6 @@ // limitations under the License. use crate::{ - assert_return_code, tests::{ compile_module, mock_network::{ @@ -26,10 +25,10 @@ use crate::{ relay_chain, MockNet, ParaA, ParachainBalances, ParachainPalletXcm, Relay, ALICE, BOB, INITIAL_BALANCE, }, - RuntimeReturnCode, }, CollectEvents, DebugInfo, Determinism, }; +use assert_matches::assert_matches; use codec::{Decode, Encode}; use frame_support::{ assert_err, @@ -114,7 +113,9 @@ fn test_xcm_execute() { .result .unwrap(); - assert_return_code!(result, RuntimeReturnCode::Success); + let mut data = &result.data[..]; + let outcome = Outcome::decode(&mut data).expect("Failed to decode xcm_execute Outcome"); + assert_matches!(outcome, Outcome::Complete(_)); // Check if the funds are subtracted from the account of Alice and added to the account of // Bob. @@ -180,7 +181,7 @@ fn test_xcm_execute_reentrant_call() { ExpectTransactStatus(MaybeErrorCode::Success), ]); - ParachainContracts::bare_call( + let result = ParachainContracts::bare_call( ALICE, contract_addr.clone(), 0, @@ -190,17 +191,13 @@ fn test_xcm_execute_reentrant_call() { DebugInfo::UnsafeDebug, CollectEvents::UnsafeCollect, Determinism::Enforced, - ); + ) + .result + .unwrap(); - // assert that the Transact failed - assert!(parachain::System::events().iter().any(|r| { - matches!( - r.event, - parachain::RuntimeEvent::PolkadotXcm(pallet_xcm::Event::Attempted { - outcome: Outcome::Incomplete(_, XcmError::ExpectationFalse) - }), - ) - })); + let mut data = &result.data[..]; + let outcome = Outcome::decode(&mut data).expect("Failed to decode xcm_execute Outcome"); + assert_matches!(outcome, Outcome::Incomplete(_, XcmError::ExpectationFalse)); // Funds should not change hands as the XCM transact failed. assert_eq!(ParachainBalances::free_balance(BOB), INITIAL_BALANCE); @@ -237,7 +234,7 @@ fn test_xcm_send() { ); let mut data = &exec.result.unwrap().data[..]; - XcmHash::decode(&mut data).expect("Failed to decode message"); + XcmHash::decode(&mut data).expect("Failed to decode xcm_send message_id"); }); Relay::execute_with(|| { diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index acfbd2d101b3..df06710a7101 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -606,7 +606,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { /// Charge, Run and adjust gas, for executing the given dispatchable. fn call_dispatchable< ErrorReturnCode: Get, - F: FnOnce(&E) -> DispatchResultWithPostInfo, + F: FnOnce(&mut Self) -> DispatchResultWithPostInfo, >( &mut self, dispatch_info: DispatchInfo, @@ -614,7 +614,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { ) -> Result { use frame_support::dispatch::extract_actual_weight; let charged = self.charge_gas(RuntimeCosts::CallRuntime(dispatch_info.weight))?; - let result = run(self.ext); + let result = run(self); let actual_weight = extract_actual_weight(&result, &dispatch_info); self.adjust_gas(charged, RuntimeCosts::CallRuntime(actual_weight)); match result { @@ -2683,8 +2683,8 @@ pub mod env { ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; let call: ::RuntimeCall = ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; - ctx.call_dispatchable::(call.get_dispatch_info(), |ext| { - ext.call_runtime(call) + ctx.call_dispatchable::(call.get_dispatch_info(), |ctx| { + ctx.ext.call_runtime(call) }) } @@ -2707,6 +2707,7 @@ pub mod env { memory: _, msg_ptr: u32, msg_len: u32, + output_ptr: u32, ) -> Result { use frame_support::dispatch::DispatchInfo; use xcm::VersionedXcm; @@ -2722,13 +2723,18 @@ pub mod env { let dispatch_info = DispatchInfo { weight, ..Default::default() }; ensure_executable::(&message)?; - ctx.call_dispatchable::(dispatch_info, |ext| { - let origin = crate::RawOrigin::Signed(ext.address().clone()).into(); - <::Xcm>::execute( + ctx.call_dispatchable::(dispatch_info, |ctx| { + let origin = crate::RawOrigin::Signed(ctx.ext.address().clone()).into(); + let outcome = <::Xcm>::execute( origin, Box::new(message), weight.saturating_sub(execute_weight), - ) + )?; + + ctx.write_sandbox_memory(memory, output_ptr, &outcome.encode())?; + let pre_dispatch_weight = + <::Xcm as ExecuteController<_, _>>::WeightInfo::execute(); + Ok(Some(outcome.weight_used().saturating_add(pre_dispatch_weight)).into()) }) } @@ -2849,7 +2855,7 @@ pub mod env { query_id_ptr: u32, output_ptr: u32, ) -> Result { - use xcm_executor::traits::{QueryController, QueryHandler, QueryControllerWeightInfo}; + use xcm_executor::traits::{QueryController, QueryControllerWeightInfo, QueryHandler}; let query_id: <::Xcm as QueryHandler>::QueryId = ctx.read_sandbox_memory_as(memory, query_id_ptr)?; From 18c6bb446282ecf608d00835e621d5bec76b9eb1 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 31 Oct 2023 10:40:39 +0100 Subject: [PATCH 078/115] Use outcome in controller --- polkadot/xcm/pallet-xcm/src/lib.rs | 16 ++++++++-------- .../xcm/xcm-executor/src/traits/controller.rs | 10 +++++----- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 6462fa0dc329..79f92b582c0d 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -298,24 +298,20 @@ pub mod pallet { origin: OriginFor, message: Box::RuntimeCall>>, max_weight: Weight, - ) -> DispatchResultWithPostInfo { + ) -> Result { let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?; let hash = message.using_encoded(sp_io::hashing::blake2_256); let message = (*message).try_into().map_err(|()| Error::::BadVersion)?; let value = (origin_location, message); ensure!(T::XcmExecuteFilter::contains(&value), Error::::Filtered); let (origin_location, message) = value; - let outcome = T::XcmExecutor::execute_xcm_in_credit( + Ok(T::XcmExecutor::execute_xcm_in_credit( origin_location, message, hash, max_weight, max_weight, - ); - let result = - Ok(Some(outcome.weight_used().saturating_add(T::WeightInfo::execute())).into()); - Self::deposit_event(Event::Attempted { outcome }); - result + )) } } @@ -1003,7 +999,11 @@ pub mod pallet { message: Box::RuntimeCall>>, max_weight: Weight, ) -> DispatchResultWithPostInfo { - >::execute(origin, message, max_weight) + let outcome = >::execute(origin, message, max_weight)?; + let result = + Ok(Some(outcome.weight_used().saturating_add(T::WeightInfo::execute())).into()); + Self::deposit_event(Event::Attempted { outcome }); + result } /// Extoll that a particular destination can be communicated with through a particular diff --git a/polkadot/xcm/xcm-executor/src/traits/controller.rs b/polkadot/xcm/xcm-executor/src/traits/controller.rs index 37ec90be8ccb..22f1777e9385 100644 --- a/polkadot/xcm/xcm-executor/src/traits/controller.rs +++ b/polkadot/xcm/xcm-executor/src/traits/controller.rs @@ -20,7 +20,7 @@ use crate::{ traits::{QueryHandler, QueryResponseStatus}, InteriorMultiLocation, Junctions::Here, - MultiLocation, Xcm, + MultiLocation, Xcm, Outcome, XcmError }; use frame_support::{pallet_prelude::*, parameter_types}; use sp_weights::Weight; @@ -49,7 +49,7 @@ pub trait ExecuteControllerWeightInfo { pub trait ExecuteController { type WeightInfo: ExecuteControllerWeightInfo; - /// Execute an XCM locally. + /// Attempt to execute an XCM locally, and return the outcome. /// /// # Parameters /// @@ -60,7 +60,7 @@ pub trait ExecuteController { origin: Origin, message: Box>, max_weight: Weight, - ) -> DispatchResultWithPostInfo; + ) -> Result; } /// Weight functions needed for [`SendController`]. @@ -120,8 +120,8 @@ impl ExecuteController for () { _origin: Origin, _message: Box>, _max_weight: Weight, - ) -> DispatchResultWithPostInfo { - Ok(().into()) + ) -> Result { + Ok(Outcome::Error(XcmError::Unimplemented)) } } From 198d69202a65e2634896356e1534d9604288a20a Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 31 Oct 2023 10:55:59 +0100 Subject: [PATCH 079/115] add docstring --- polkadot/xcm/xcm-executor/src/traits/controller.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/polkadot/xcm/xcm-executor/src/traits/controller.rs b/polkadot/xcm/xcm-executor/src/traits/controller.rs index 22f1777e9385..7ef7e61d0532 100644 --- a/polkadot/xcm/xcm-executor/src/traits/controller.rs +++ b/polkadot/xcm/xcm-executor/src/traits/controller.rs @@ -47,6 +47,7 @@ pub trait ExecuteControllerWeightInfo { /// Execute an XCM locally, for a given origin. pub trait ExecuteController { + /// Weight information for ExecuteController functions. type WeightInfo: ExecuteControllerWeightInfo; /// Attempt to execute an XCM locally, and return the outcome. @@ -71,6 +72,7 @@ pub trait SendControllerWeightInfo { /// Send an XCM from a given origin. pub trait SendController { + /// Weight information for SendController functions. type WeightInfo: SendControllerWeightInfo; /// Send an XCM to be executed by a remote location. @@ -98,6 +100,7 @@ pub trait QueryControllerWeightInfo { /// Query a remote location, from a given origin. pub trait QueryController: QueryHandler { + /// Weight information for QueryController functions. type WeightInfo: QueryControllerWeightInfo; /// Query a remote location. From e3ce2e0585c1bf92aa4b324d3aaba4123a97fef9 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 31 Oct 2023 15:26:02 +0100 Subject: [PATCH 080/115] Event consistency --- polkadot/xcm/pallet-xcm/src/lib.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 79f92b582c0d..ee0a3ebef4f8 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -305,13 +305,15 @@ pub mod pallet { let value = (origin_location, message); ensure!(T::XcmExecuteFilter::contains(&value), Error::::Filtered); let (origin_location, message) = value; - Ok(T::XcmExecutor::execute_xcm_in_credit( + let outcome = T::XcmExecutor::execute_xcm_in_credit( origin_location, message, hash, max_weight, max_weight, - )) + ); + Self::deposit_event(Event::Attempted { outcome: outcome.clone() }); + Ok(outcome) } } @@ -1000,10 +1002,7 @@ pub mod pallet { max_weight: Weight, ) -> DispatchResultWithPostInfo { let outcome = >::execute(origin, message, max_weight)?; - let result = - Ok(Some(outcome.weight_used().saturating_add(T::WeightInfo::execute())).into()); - Self::deposit_event(Event::Attempted { outcome }); - result + Ok(Some(outcome.weight_used().saturating_add(T::WeightInfo::execute())).into()) } /// Extoll that a particular destination can be communicated with through a particular From 634296291c56d38bfd6c7903d490465d110f98ef Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 31 Oct 2023 16:07:56 +0100 Subject: [PATCH 081/115] Add more docs --- polkadot/xcm/pallet-xcm/src/lib.rs | 5 ++--- .../xcm/xcm-executor/src/traits/controller.rs | 21 ++++++++++++++++++- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index ee0a3ebef4f8..51deb06d98db 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -53,9 +53,8 @@ use xcm_executor::{ traits::{ CheckSuspension, ClaimAssets, ConvertLocation, ConvertOrigin, DropAssets, ExecuteController, ExecuteControllerWeightInfo, MatchesFungible, OnResponse, Properties, - QueryController, QueryControllerWeightInfo, QueryHandler, - QueryResponseStatus, SendController, SendControllerWeightInfo, VersionChangeNotifier, - WeightBounds, + QueryController, QueryControllerWeightInfo, QueryHandler, QueryResponseStatus, + SendController, SendControllerWeightInfo, VersionChangeNotifier, WeightBounds, }, Assets, }; diff --git a/polkadot/xcm/xcm-executor/src/traits/controller.rs b/polkadot/xcm/xcm-executor/src/traits/controller.rs index 7ef7e61d0532..6a7a27513182 100644 --- a/polkadot/xcm/xcm-executor/src/traits/controller.rs +++ b/polkadot/xcm/xcm-executor/src/traits/controller.rs @@ -15,12 +15,14 @@ // along with Polkadot. If not, see . //! A set of traits that define how a pallet interface with XCM. +//! Controller traits defined in this module are high-level traits that will rely on other more +//! low-level traits of this crate to perform their tasks. use crate::{ traits::{QueryHandler, QueryResponseStatus}, InteriorMultiLocation, Junctions::Here, - MultiLocation, Xcm, Outcome, XcmError + MultiLocation, Outcome, Xcm, XcmError, }; use frame_support::{pallet_prelude::*, parameter_types}; use sp_weights::Weight; @@ -46,6 +48,11 @@ pub trait ExecuteControllerWeightInfo { } /// Execute an XCM locally, for a given origin. +/// +/// An implementation of that trait will handle the low-level details of the execution, such as: +/// - Validating and Converting the origin to a MultiLocation. +/// - Handling versioning. +/// - Calling the internal executor, which implements [`ExecuteXcm`]. pub trait ExecuteController { /// Weight information for ExecuteController functions. type WeightInfo: ExecuteControllerWeightInfo; @@ -71,6 +78,12 @@ pub trait SendControllerWeightInfo { } /// Send an XCM from a given origin. +/// +/// An implementation of that trait will handle the low-level details of dispatching an XCM, such +/// as: +/// - Validating and Converting the origin to an interior location. +/// - Handling versioning. +/// - Calling the internal router, which implements [`SendXcm`]. pub trait SendController { /// Weight information for SendController functions. type WeightInfo: SendControllerWeightInfo; @@ -99,6 +112,12 @@ pub trait QueryControllerWeightInfo { } /// Query a remote location, from a given origin. +/// +/// An implementation of that trait will handle the low-level details of querying a remote location, +/// such as: +/// - Validating and Converting the origin to an interior location. +/// - Handling versioning. +/// - Calling the [`QueryHandler`] to register the query. pub trait QueryController: QueryHandler { /// Weight information for QueryController functions. type WeightInfo: QueryControllerWeightInfo; From a2fde63fdbfaea738c4e168fdb62149c4621972b Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Tue, 31 Oct 2023 16:09:24 +0100 Subject: [PATCH 082/115] Update polkadot/xcm/xcm-executor/src/traits/controller.rs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alexander Theißen --- polkadot/xcm/xcm-executor/src/traits/controller.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/polkadot/xcm/xcm-executor/src/traits/controller.rs b/polkadot/xcm/xcm-executor/src/traits/controller.rs index 6a7a27513182..b3b6dbff413b 100644 --- a/polkadot/xcm/xcm-executor/src/traits/controller.rs +++ b/polkadot/xcm/xcm-executor/src/traits/controller.rs @@ -107,7 +107,7 @@ pub trait QueryControllerWeightInfo { /// Weight for [`QueryController::query`] fn query() -> Weight; - /// Weight for [`QueryController::take_response`] + /// Weight for [`QueryHandler::take_response`] fn take_response() -> Weight; } From 0ae8763f6f4537a9a38da92ce54dfb56e8f54fa5 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 31 Oct 2023 16:21:37 +0100 Subject: [PATCH 083/115] fix doc --- polkadot/xcm/xcm-executor/src/traits/controller.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/polkadot/xcm/xcm-executor/src/traits/controller.rs b/polkadot/xcm/xcm-executor/src/traits/controller.rs index b3b6dbff413b..76887b3b883d 100644 --- a/polkadot/xcm/xcm-executor/src/traits/controller.rs +++ b/polkadot/xcm/xcm-executor/src/traits/controller.rs @@ -52,7 +52,7 @@ pub trait ExecuteControllerWeightInfo { /// An implementation of that trait will handle the low-level details of the execution, such as: /// - Validating and Converting the origin to a MultiLocation. /// - Handling versioning. -/// - Calling the internal executor, which implements [`ExecuteXcm`]. +/// - Calling the internal executor, which implements [`crate::ExecuteXcm`]. pub trait ExecuteController { /// Weight information for ExecuteController functions. type WeightInfo: ExecuteControllerWeightInfo; @@ -83,7 +83,7 @@ pub trait SendControllerWeightInfo { /// as: /// - Validating and Converting the origin to an interior location. /// - Handling versioning. -/// - Calling the internal router, which implements [`SendXcm`]. +/// - Calling the internal router, which implements [`crate::SendXcm`]. pub trait SendController { /// Weight information for SendController functions. type WeightInfo: SendControllerWeightInfo; From 034150c2348800bb03503e9e3e8ec10ec4a121b7 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 31 Oct 2023 16:31:03 +0100 Subject: [PATCH 084/115] fix CI --- polkadot/xcm/xcm-executor/src/traits/controller.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/polkadot/xcm/xcm-executor/src/traits/controller.rs b/polkadot/xcm/xcm-executor/src/traits/controller.rs index 76887b3b883d..3e60bbed06e0 100644 --- a/polkadot/xcm/xcm-executor/src/traits/controller.rs +++ b/polkadot/xcm/xcm-executor/src/traits/controller.rs @@ -212,7 +212,7 @@ impl QueryHandler for () { } #[cfg(feature = "runtime-benchmarks")] - fn expect_response(_id: Self::QueryId, _response: Response) {} + fn expect_response(_id: Self::QueryId, _response: crate::Response) {} } impl QueryControllerWeightInfo for () { From 7848e2fea245dbe08ba4dfd2a4b142ca20419e0c Mon Sep 17 00:00:00 2001 From: pgherveou Date: Wed, 1 Nov 2023 16:22:58 +0100 Subject: [PATCH 085/115] move to xcm-builder --- .../traits => xcm-builder/src}/controller.rs | 72 +++++-------------- polkadot/xcm/xcm-builder/src/lib.rs | 3 + polkadot/xcm/xcm-executor/src/traits/mod.rs | 2 - .../xcm-executor/src/traits/on_response.rs | 36 ++++++++++ 4 files changed, 55 insertions(+), 58 deletions(-) rename polkadot/xcm/{xcm-executor/src/traits => xcm-builder/src}/controller.rs (81%) diff --git a/polkadot/xcm/xcm-executor/src/traits/controller.rs b/polkadot/xcm/xcm-builder/src/controller.rs similarity index 81% rename from polkadot/xcm/xcm-executor/src/traits/controller.rs rename to polkadot/xcm/xcm-builder/src/controller.rs index 3e60bbed06e0..5091dde245c2 100644 --- a/polkadot/xcm/xcm-executor/src/traits/controller.rs +++ b/polkadot/xcm/xcm-builder/src/controller.rs @@ -15,20 +15,13 @@ // along with Polkadot. If not, see . //! A set of traits that define how a pallet interface with XCM. -//! Controller traits defined in this module are high-level traits that will rely on other more -//! low-level traits of this crate to perform their tasks. - -use crate::{ - traits::{QueryHandler, QueryResponseStatus}, - InteriorMultiLocation, - Junctions::Here, - MultiLocation, Outcome, Xcm, XcmError, -}; -use frame_support::{pallet_prelude::*, parameter_types}; -use sp_weights::Weight; -use xcm::{v3::XcmHash, VersionedMultiLocation, VersionedXcm}; - -/// Umbrella trait for all Controller traits. +//! Controller traits defined in this module are high-level traits that will rely on other traits +//! from `xcm-executor` to perform their tasks. + +use frame_support::pallet_prelude::DispatchError; +use xcm::prelude::*; +use xcm_executor::traits::QueryHandler; + pub trait Controller: ExecuteController + SendController + QueryController { @@ -170,6 +163,15 @@ impl SendControllerWeightInfo for () { } } +impl QueryControllerWeightInfo for () { + fn query() -> Weight { + Weight::zero() + } + fn take_response() -> Weight { + Weight::zero() + } +} + impl QueryController for () { type WeightInfo = (); @@ -181,45 +183,3 @@ impl QueryController for () { Ok(Default::default()) } } - -parameter_types! { - pub UniversalLocation: InteriorMultiLocation = Here; -} - -impl QueryHandler for () { - type BlockNumber = u64; - type Error = (); - type QueryId = u64; - type UniversalLocation = UniversalLocation; - - fn take_response(_query_id: Self::QueryId) -> QueryResponseStatus { - QueryResponseStatus::NotFound - } - fn new_query( - _responder: impl Into, - _timeout: Self::BlockNumber, - _match_querier: impl Into, - ) -> Self::QueryId { - 0u64 - } - - fn report_outcome( - _message: &mut Xcm<()>, - _responder: impl Into, - _timeout: Self::BlockNumber, - ) -> Result { - Err(()) - } - - #[cfg(feature = "runtime-benchmarks")] - fn expect_response(_id: Self::QueryId, _response: crate::Response) {} -} - -impl QueryControllerWeightInfo for () { - fn query() -> Weight { - Weight::zero() - } - fn take_response() -> Weight { - Weight::zero() - } -} diff --git a/polkadot/xcm/xcm-builder/src/lib.rs b/polkadot/xcm/xcm-builder/src/lib.rs index 34371398cdc3..5d224bf5de0d 100644 --- a/polkadot/xcm/xcm-builder/src/lib.rs +++ b/polkadot/xcm/xcm-builder/src/lib.rs @@ -113,3 +113,6 @@ pub use origin_aliases::AliasForeignAccountId32; mod pay; pub use pay::{FixedLocation, LocatableAssetId, PayAccountId32OnChainOverXcm, PayOverXcm}; + +mod controller; +pub use controller::*; diff --git a/polkadot/xcm/xcm-executor/src/traits/mod.rs b/polkadot/xcm/xcm-executor/src/traits/mod.rs index 2240936b6ef8..a9439968fa6c 100644 --- a/polkadot/xcm/xcm-executor/src/traits/mod.rs +++ b/polkadot/xcm/xcm-executor/src/traits/mod.rs @@ -16,8 +16,6 @@ //! Various traits used in configuring the executor. -mod controller; -pub use controller::*; mod conversion; pub use conversion::{CallDispatcher, ConvertLocation, ConvertOrigin, WithOriginFilter}; mod drop_assets; diff --git a/polkadot/xcm/xcm-executor/src/traits/on_response.rs b/polkadot/xcm/xcm-executor/src/traits/on_response.rs index 7d20a36419f1..a316209e6c07 100644 --- a/polkadot/xcm/xcm-executor/src/traits/on_response.rs +++ b/polkadot/xcm/xcm-executor/src/traits/on_response.rs @@ -15,11 +15,13 @@ // along with Polkadot. If not, see . use crate::Xcm; +use crate::Junctions::Here; use core::result; use frame_support::pallet_prelude::{Get, TypeInfo}; use parity_scale_codec::{Decode, Encode, FullCodec, MaxEncodedLen}; use sp_arithmetic::traits::Zero; use sp_std::fmt::Debug; +use frame_support::parameter_types; use xcm::latest::{ Error as XcmError, InteriorMultiLocation, MultiLocation, QueryId, Response, Result as XcmResult, Weight, XcmContext, @@ -165,3 +167,37 @@ pub trait QueryHandler { #[cfg(feature = "runtime-benchmarks")] fn expect_response(id: Self::QueryId, response: Response); } + +parameter_types! { + pub UniversalLocation: InteriorMultiLocation = Here; +} + +impl QueryHandler for () { + type BlockNumber = u64; + type Error = (); + type QueryId = u64; + type UniversalLocation = UniversalLocation; + + fn take_response(_query_id: Self::QueryId) -> QueryResponseStatus { + QueryResponseStatus::NotFound + } + fn new_query( + _responder: impl Into, + _timeout: Self::BlockNumber, + _match_querier: impl Into, + ) -> Self::QueryId { + 0u64 + } + + fn report_outcome( + _message: &mut Xcm<()>, + _responder: impl Into, + _timeout: Self::BlockNumber, + ) -> Result { + Err(()) + } + + #[cfg(feature = "runtime-benchmarks")] + fn expect_response(_id: Self::QueryId, _response: crate::Response) {} +} + From b7155b6fea522c44457b0a34fc7fadc4634cc027 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Wed, 1 Nov 2023 16:29:55 +0100 Subject: [PATCH 086/115] move to pallet-xcm --- .../{xcm-builder => pallet-xcm}/src/controller.rs | 0 polkadot/xcm/pallet-xcm/src/lib.rs | 13 +++++++------ polkadot/xcm/xcm-builder/src/lib.rs | 3 --- 3 files changed, 7 insertions(+), 9 deletions(-) rename polkadot/xcm/{xcm-builder => pallet-xcm}/src/controller.rs (100%) diff --git a/polkadot/xcm/xcm-builder/src/controller.rs b/polkadot/xcm/pallet-xcm/src/controller.rs similarity index 100% rename from polkadot/xcm/xcm-builder/src/controller.rs rename to polkadot/xcm/pallet-xcm/src/controller.rs diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 51deb06d98db..8dc668859e27 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -25,9 +25,11 @@ mod mock; #[cfg(test)] mod tests; +pub mod controller; pub mod migration; use codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; +pub use controller::*; use frame_support::{ dispatch::GetDispatchInfo, pallet_prelude::*, @@ -51,10 +53,9 @@ use sp_std::{boxed::Box, marker::PhantomData, prelude::*, result::Result, vec}; use xcm::{latest::QueryResponseInfo, prelude::*}; use xcm_executor::{ traits::{ - CheckSuspension, ClaimAssets, ConvertLocation, ConvertOrigin, DropAssets, - ExecuteController, ExecuteControllerWeightInfo, MatchesFungible, OnResponse, Properties, - QueryController, QueryControllerWeightInfo, QueryHandler, QueryResponseStatus, - SendController, SendControllerWeightInfo, VersionChangeNotifier, WeightBounds, + CheckSuspension, ClaimAssets, ConvertLocation, ConvertOrigin, DropAssets, MatchesFungible, + OnResponse, Properties, QueryHandler, QueryResponseStatus, VersionChangeNotifier, + WeightBounds, }, Assets, }; @@ -363,7 +364,7 @@ pub mod pallet { let responder = ::ExecuteXcmOrigin::ensure_origin(origin)?; let query_id = ::new_query( responder, - timeout.into(), + timeout, MultiLocation::try_from(match_querier) .map_err(|_| Into::::into(Error::::BadVersion))?, ); @@ -1226,7 +1227,7 @@ impl QueryHandler for Pallet { timeout: BlockNumberFor, match_querier: impl Into, ) -> Self::QueryId { - Self::do_new_query(responder, None, timeout, match_querier).into() + Self::do_new_query(responder, None, timeout, match_querier) } /// To check the status of the query, use `fn query()` passing the resultant `QueryId` diff --git a/polkadot/xcm/xcm-builder/src/lib.rs b/polkadot/xcm/xcm-builder/src/lib.rs index 5d224bf5de0d..34371398cdc3 100644 --- a/polkadot/xcm/xcm-builder/src/lib.rs +++ b/polkadot/xcm/xcm-builder/src/lib.rs @@ -113,6 +113,3 @@ pub use origin_aliases::AliasForeignAccountId32; mod pay; pub use pay::{FixedLocation, LocatableAssetId, PayAccountId32OnChainOverXcm, PayOverXcm}; - -mod controller; -pub use controller::*; From 34329e541346ac3f70329ef8448592f828e66cce Mon Sep 17 00:00:00 2001 From: pgherveou Date: Wed, 1 Nov 2023 16:43:37 +0100 Subject: [PATCH 087/115] Update doc links --- polkadot/xcm/pallet-xcm/src/controller.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/polkadot/xcm/pallet-xcm/src/controller.rs b/polkadot/xcm/pallet-xcm/src/controller.rs index 5091dde245c2..2a4d3940e68f 100644 --- a/polkadot/xcm/pallet-xcm/src/controller.rs +++ b/polkadot/xcm/pallet-xcm/src/controller.rs @@ -45,7 +45,7 @@ pub trait ExecuteControllerWeightInfo { /// An implementation of that trait will handle the low-level details of the execution, such as: /// - Validating and Converting the origin to a MultiLocation. /// - Handling versioning. -/// - Calling the internal executor, which implements [`crate::ExecuteXcm`]. +/// - Calling the internal executor, which implements [`ExecuteXcm`]. pub trait ExecuteController { /// Weight information for ExecuteController functions. type WeightInfo: ExecuteControllerWeightInfo; @@ -76,7 +76,7 @@ pub trait SendControllerWeightInfo { /// as: /// - Validating and Converting the origin to an interior location. /// - Handling versioning. -/// - Calling the internal router, which implements [`crate::SendXcm`]. +/// - Calling the internal router, which implements [`SendXcm`]. pub trait SendController { /// Weight information for SendController functions. type WeightInfo: SendControllerWeightInfo; From b37d1692e042a6ddab39f3d9005c6b8a6c260012 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Wed, 1 Nov 2023 18:19:30 +0100 Subject: [PATCH 088/115] wip --- polkadot/xcm/xcm-executor/src/traits/on_response.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/polkadot/xcm/xcm-executor/src/traits/on_response.rs b/polkadot/xcm/xcm-executor/src/traits/on_response.rs index a316209e6c07..df846ae5722a 100644 --- a/polkadot/xcm/xcm-executor/src/traits/on_response.rs +++ b/polkadot/xcm/xcm-executor/src/traits/on_response.rs @@ -131,7 +131,7 @@ pub trait QueryHandler { + PartialEq + Debug + Copy; - type BlockNumber: Zero + Encode; + type BlockNumber: Zero; type Error; type UniversalLocation: Get; From 7cd84a2eb3d0be2b02d73e25b13b6f7fdc2825ec Mon Sep 17 00:00:00 2001 From: pgherveou Date: Wed, 1 Nov 2023 19:59:16 +0100 Subject: [PATCH 089/115] update xcm stuff --- substrate/frame/contracts/Cargo.toml | 2 +- substrate/frame/contracts/src/exec.rs | 1 + substrate/frame/contracts/src/lib.rs | 8 +++++--- substrate/frame/contracts/src/wasm/runtime.rs | 9 +++++---- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index aab19bcd567c..809a50b9db64 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -50,6 +50,7 @@ sp-std = { path = "../../primitives/std", default-features = false} xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false} xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor", default-features = false} +pallet-xcm = { path = "../../../polkadot/xcm/pallet-xcm", default-features = false} [dev-dependencies] array-bytes = "6.1" @@ -59,7 +60,6 @@ pretty_assertions = "1" wat = "1" # Polkadot Dependencies -pallet-xcm = { path = "../../../polkadot/xcm/pallet-xcm", default-features = false} xcm-simulator = {path = "../../../polkadot/xcm/xcm-simulator"} xcm-builder = {package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder"} polkadot-runtime-parachains = {path = "../../../polkadot/runtime/parachains"} diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index 9090aa9cb112..437561d31df9 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -138,6 +138,7 @@ impl> From for ExecError { pub trait Ext: sealing::Sealed { type T: Config; + /// Call (possibly transferring some amount of funds) into the specified account. /// /// Returns the code size of the called contract. diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index c6c456ea9d52..4dcfa1b6c848 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -207,7 +207,8 @@ pub struct EnvironmentType(PhantomData); #[derive(Encode, Decode, DefaultNoBound, TypeInfo)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] #[scale_info(skip_type_params(T))] -pub struct Environment { +pub struct Environment +{ account_id: EnvironmentType>, balance: EnvironmentType>, hash: EnvironmentType<::Hash>, @@ -232,7 +233,8 @@ pub mod pallet { pub struct Pallet(_); #[pallet::config] - pub trait Config: frame_system::Config { + pub trait Config: frame_system::Config + { /// The time implementation used to supply timestamps to contracts through `seal_now`. type Time: Time; @@ -406,7 +408,7 @@ pub mod pallet { /// A type that exposes XCM APIs, allowing contracts to interact with other parachains, and /// execute XCM programs. - type Xcm: xcm_executor::traits::Controller< + type Xcm: pallet_xcm::Controller< OriginFor, ::RuntimeCall, BlockNumberFor, diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index df06710a7101..322e69699d83 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2711,7 +2711,7 @@ pub mod env { ) -> Result { use frame_support::dispatch::DispatchInfo; use xcm::VersionedXcm; - use xcm_executor::traits::{ExecuteController, ExecuteControllerWeightInfo}; + use pallet_xcm::{ExecuteController, ExecuteControllerWeightInfo}; ctx.charge_gas(RuntimeCosts::CopyFromContract(msg_len))?; let message: VersionedXcm> = @@ -2764,7 +2764,7 @@ pub mod env { output_ptr: u32, ) -> Result { use xcm::{VersionedMultiLocation, VersionedXcm}; - use xcm_executor::traits::{SendController, SendControllerWeightInfo}; + use pallet_xcm::{SendController, SendControllerWeightInfo}; ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; let dest: VersionedMultiLocation = ctx.read_sandbox_memory_as(memory, dest_ptr)?; @@ -2812,7 +2812,7 @@ pub mod env { ) -> Result { use frame_system::pallet_prelude::BlockNumberFor; use xcm::VersionedMultiLocation; - use xcm_executor::traits::{QueryController, QueryControllerWeightInfo}; + use pallet_xcm::{QueryController, QueryControllerWeightInfo}; let timeout: BlockNumberFor = ctx.read_sandbox_memory_as(memory, timeout_ptr)?; let match_querier: VersionedMultiLocation = @@ -2855,7 +2855,8 @@ pub mod env { query_id_ptr: u32, output_ptr: u32, ) -> Result { - use xcm_executor::traits::{QueryController, QueryControllerWeightInfo, QueryHandler}; + use xcm_executor::traits::QueryHandler; + use pallet_xcm::{QueryController, QueryControllerWeightInfo}; let query_id: <::Xcm as QueryHandler>::QueryId = ctx.read_sandbox_memory_as(memory, query_id_ptr)?; From 8ac21dae844be6fb14ca9b6be0920539d43e9319 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Wed, 1 Nov 2023 20:00:53 +0100 Subject: [PATCH 090/115] Bench compile fix --- polkadot/xcm/pallet-xcm/src/benchmarking.rs | 2 +- polkadot/xcm/xcm-executor/src/traits/on_response.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/polkadot/xcm/pallet-xcm/src/benchmarking.rs b/polkadot/xcm/pallet-xcm/src/benchmarking.rs index c80751c8ebea..3eecbfec5180 100644 --- a/polkadot/xcm/pallet-xcm/src/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm/src/benchmarking.rs @@ -214,7 +214,7 @@ benchmarks! { Pallet::::expect_response(query_id, Response::PalletsInfo(infos.try_into().unwrap())); }: { - Pallet::::take_response(query_id); + as QueryHandler>::take_response(query_id); } impl_benchmark_test_suite!( diff --git a/polkadot/xcm/xcm-executor/src/traits/on_response.rs b/polkadot/xcm/xcm-executor/src/traits/on_response.rs index df846ae5722a..a316209e6c07 100644 --- a/polkadot/xcm/xcm-executor/src/traits/on_response.rs +++ b/polkadot/xcm/xcm-executor/src/traits/on_response.rs @@ -131,7 +131,7 @@ pub trait QueryHandler { + PartialEq + Debug + Copy; - type BlockNumber: Zero; + type BlockNumber: Zero + Encode; type Error; type UniversalLocation: Get; From 7ee5d083c086b67a5733edee29e8320e14412379 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Thu, 2 Nov 2023 10:52:15 +0100 Subject: [PATCH 091/115] add missing use --- polkadot/xcm/pallet-xcm/src/controller.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/polkadot/xcm/pallet-xcm/src/controller.rs b/polkadot/xcm/pallet-xcm/src/controller.rs index 2a4d3940e68f..61ce6702999d 100644 --- a/polkadot/xcm/pallet-xcm/src/controller.rs +++ b/polkadot/xcm/pallet-xcm/src/controller.rs @@ -19,6 +19,7 @@ //! from `xcm-executor` to perform their tasks. use frame_support::pallet_prelude::DispatchError; +use sp_std::boxed::Box; use xcm::prelude::*; use xcm_executor::traits::QueryHandler; From 2359fa07df2dfa8db1445b61907a79a28f316a3a Mon Sep 17 00:00:00 2001 From: pgherveou Date: Thu, 2 Nov 2023 11:18:40 +0100 Subject: [PATCH 092/115] fix test --- polkadot/xcm/xcm-builder/src/tests/mock.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/polkadot/xcm/xcm-builder/src/tests/mock.rs b/polkadot/xcm/xcm-builder/src/tests/mock.rs index 543b00e0118c..189274eb5f5b 100644 --- a/polkadot/xcm/xcm-builder/src/tests/mock.rs +++ b/polkadot/xcm/xcm-builder/src/tests/mock.rs @@ -414,7 +414,7 @@ pub fn response(query_id: u64) -> Option { /// Mock implementation of the [`QueryHandler`] trait for creating XCM success queries and expecting /// responses. pub struct TestQueryHandler(core::marker::PhantomData<(T, BlockNumber)>); -impl QueryHandler +impl QueryHandler for TestQueryHandler { type QueryId = u64; From 41215d322925d9d453b129ae391f07f026ef9e2b Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 10 Nov 2023 13:33:05 +0100 Subject: [PATCH 093/115] mock-network crate --- Cargo.lock | 35 ++++++++++ Cargo.toml | 1 + .../frame/contracts/mock-network/Cargo.toml | 68 +++++++++++++++++++ .../src/lib.rs} | 10 +-- .../src}/mocks.rs | 0 .../src}/mocks/msg_queue.rs | 0 .../src}/mocks/relay_message_queue.rs | 2 +- .../src}/parachain.rs | 16 ++--- .../src}/parachain/contracts_config.rs | 21 +++--- .../src}/primitives.rs | 0 .../src}/relay_chain.rs | 2 +- .../test_xcm.rs => mock-network/src/tests.rs} | 18 ++--- substrate/frame/contracts/src/tests.rs | 2 - 13 files changed, 136 insertions(+), 39 deletions(-) create mode 100644 substrate/frame/contracts/mock-network/Cargo.toml rename substrate/frame/contracts/{src/tests/mock_network.rs => mock-network/src/lib.rs} (94%) rename substrate/frame/contracts/{src/tests/mock_network => mock-network/src}/mocks.rs (100%) rename substrate/frame/contracts/{src/tests/mock_network => mock-network/src}/mocks/msg_queue.rs (100%) rename substrate/frame/contracts/{src/tests/mock_network => mock-network/src}/mocks/relay_message_queue.rs (96%) rename substrate/frame/contracts/{src/tests/mock_network => mock-network/src}/parachain.rs (95%) rename substrate/frame/contracts/{src/tests/mock_network => mock-network/src}/parachain/contracts_config.rs (84%) rename substrate/frame/contracts/{src/tests/mock_network => mock-network/src}/primitives.rs (100%) rename substrate/frame/contracts/{src/tests/mock_network => mock-network/src}/relay_chain.rs (99%) rename substrate/frame/contracts/{src/tests/test_xcm.rs => mock-network/src/tests.rs} (96%) diff --git a/Cargo.lock b/Cargo.lock index 17f3576f1be6..92002af4661b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9495,6 +9495,41 @@ dependencies = [ "xcm-simulator", ] +[[package]] +name = "pallet-contracts-mock-network" +version = "1.0.0" +dependencies = [ + "frame-support", + "frame-system", + "pallet-assets", + "pallet-balances", + "pallet-contracts", + "pallet-contracts-primitives", + "pallet-contracts-proc-macro", + "pallet-insecure-randomness-collective-flip", + "pallet-message-queue", + "pallet-proxy", + "pallet-timestamp", + "pallet-utility", + "pallet-xcm", + "parity-scale-codec", + "polkadot-parachain-primitives", + "polkadot-primitives", + "polkadot-runtime-parachains", + "scale-info", + "sp-api", + "sp-core", + "sp-io", + "sp-keystore", + "sp-runtime", + "sp-std", + "sp-tracing", + "staging-xcm", + "staging-xcm-builder", + "staging-xcm-executor", + "xcm-simulator", +] + [[package]] name = "pallet-contracts-primitives" version = "24.0.0" diff --git a/Cargo.toml b/Cargo.toml index 2c63aabf9352..f683f37ef6d9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -278,6 +278,7 @@ members = [ "substrate/frame/contracts", "substrate/frame/contracts/primitives", "substrate/frame/contracts/proc-macro", + "substrate/frame/contracts/mock-network", "substrate/frame/conviction-voting", "substrate/frame/core-fellowship", "substrate/frame/democracy", diff --git a/substrate/frame/contracts/mock-network/Cargo.toml b/substrate/frame/contracts/mock-network/Cargo.toml new file mode 100644 index 000000000000..74d26031b114 --- /dev/null +++ b/substrate/frame/contracts/mock-network/Cargo.toml @@ -0,0 +1,68 @@ +[package] +name = "pallet-contracts-mock-network" +version = "1.0.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +homepage = "https://substrate.io" +repository.workspace = true +description = "A mock network for testing pallet-contracts" + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = [ "derive", "max-encoded-len"] } + +frame-support = { path = "../../support", default-features = false} +frame-system = { path = "../../system", default-features = false} +pallet-assets = { path = "../../assets" } +pallet-balances = { path = "../../balances" } +pallet-contracts = { path = ".." } +pallet-contracts-primitives = { path = "../primitives", default-features = false} +pallet-contracts-proc-macro = { path = "../proc-macro" } +pallet-insecure-randomness-collective-flip = { path = "../../insecure-randomness-collective-flip" } +pallet-message-queue = { path = "../../message-queue" } +pallet-proxy = { path = "../../proxy" } +pallet-timestamp = { path = "../../timestamp" } +pallet-utility = { path = "../../utility" } +pallet-xcm = { path = "../../../../polkadot/xcm/pallet-xcm", default-features = false} +polkadot-parachain-primitives = { path = "../../../../polkadot/parachain" } +polkadot-primitives = { path = "../../../../polkadot/primitives" } +polkadot-runtime-parachains = {path = "../../../../polkadot/runtime/parachains"} +scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } +sp-api = { path = "../../../primitives/api", default-features = false} +sp-core = { path = "../../../primitives/core", default-features = false} +sp-io = { path = "../../../primitives/io", default-features = false} +sp-keystore = { path = "../../../primitives/keystore" } +sp-runtime = { path = "../../../primitives/runtime", default-features = false} +sp-std = { path = "../../../primitives/std", default-features = false} +sp-tracing = { path = "../../../primitives/tracing" } +xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false} +xcm-builder = {package = "staging-xcm-builder", path = "../../../../polkadot/xcm/xcm-builder"} +xcm-executor = { package = "staging-xcm-executor", path = "../../../../polkadot/xcm/xcm-executor", default-features = false} +xcm-simulator = {path = "../../../../polkadot/xcm/xcm-simulator"} + +[features] +default = [ "std" ] +std = [ + "codec/std", + "frame-support/std", + "frame-system/std", + "pallet-balances/std", + "pallet-contracts-primitives/std", + "pallet-contracts-proc-macro/full", + "pallet-contracts/std", + "pallet-insecure-randomness-collective-flip/std", + "pallet-proxy/std", + "pallet-timestamp/std", + "pallet-utility/std", + "pallet-xcm/std", + "scale-info/std", + "sp-api/std", + "sp-core/std", + "sp-io/std", + "sp-keystore/std", + "sp-runtime/std", + "sp-std/std", + "xcm-executor/std", + "xcm/std", +] + diff --git a/substrate/frame/contracts/src/tests/mock_network.rs b/substrate/frame/contracts/mock-network/src/lib.rs similarity index 94% rename from substrate/frame/contracts/src/tests/mock_network.rs rename to substrate/frame/contracts/mock-network/src/lib.rs index 412bc49ca9f0..345c69541b6f 100644 --- a/substrate/frame/contracts/src/tests/mock_network.rs +++ b/substrate/frame/contracts/mock-network/src/lib.rs @@ -19,7 +19,10 @@ pub mod parachain; pub mod primitives; pub mod relay_chain; -use crate::tests::mock_network::primitives::{AccountId, UNITS}; +#[cfg(test)] +mod tests; + +use crate::primitives::{AccountId, UNITS}; use sp_runtime::BuildStorage; use xcm::latest::{prelude::*, MultiLocation}; use xcm_executor::traits::ConvertLocation; @@ -70,8 +73,7 @@ pub fn relay_sovereign_account_id() -> AccountId { pub fn parachain_sovereign_account_id(para: u32) -> AccountId { let location: MultiLocation = (Parachain(para),).into(); - crate::tests::mock_network::relay_chain::SovereignAccountOf::convert_location(&location) - .unwrap() + relay_chain::SovereignAccountOf::convert_location(&location).unwrap() } pub fn parachain_account_sovereign_account_id( @@ -87,7 +89,7 @@ pub fn parachain_account_sovereign_account_id( } pub fn para_ext(para_id: u32) -> sp_io::TestExternalities { - use crate::tests::mock_network::parachain::{MsgQueue, Runtime, System}; + use parachain::{MsgQueue, Runtime, System}; let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); diff --git a/substrate/frame/contracts/src/tests/mock_network/mocks.rs b/substrate/frame/contracts/mock-network/src/mocks.rs similarity index 100% rename from substrate/frame/contracts/src/tests/mock_network/mocks.rs rename to substrate/frame/contracts/mock-network/src/mocks.rs diff --git a/substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs b/substrate/frame/contracts/mock-network/src/mocks/msg_queue.rs similarity index 100% rename from substrate/frame/contracts/src/tests/mock_network/mocks/msg_queue.rs rename to substrate/frame/contracts/mock-network/src/mocks/msg_queue.rs diff --git a/substrate/frame/contracts/src/tests/mock_network/mocks/relay_message_queue.rs b/substrate/frame/contracts/mock-network/src/mocks/relay_message_queue.rs similarity index 96% rename from substrate/frame/contracts/src/tests/mock_network/mocks/relay_message_queue.rs rename to substrate/frame/contracts/mock-network/src/mocks/relay_message_queue.rs index 5d745e6742e4..14099965e3f1 100644 --- a/substrate/frame/contracts/src/tests/mock_network/mocks/relay_message_queue.rs +++ b/substrate/frame/contracts/mock-network/src/mocks/relay_message_queue.rs @@ -20,7 +20,7 @@ use xcm_simulator::{ AggregateMessageOrigin, ProcessMessage, ProcessMessageError, UmpQueueId, WeightMeter, }; -use crate::tests::mock_network::relay_chain::{RuntimeCall, XcmConfig}; +use crate::relay_chain::{RuntimeCall, XcmConfig}; parameter_types! { /// Amount of weight that can be spent per block to service messages. diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain.rs b/substrate/frame/contracts/mock-network/src/parachain.rs similarity index 95% rename from substrate/frame/contracts/src/tests/mock_network/parachain.rs rename to substrate/frame/contracts/mock-network/src/parachain.rs index 978879b64933..510895b918b4 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain.rs +++ b/substrate/frame/contracts/mock-network/src/parachain.rs @@ -17,7 +17,7 @@ //! Parachain runtime mock. mod contracts_config; -use crate::tests::mock_network::{ +use crate::{ mocks::msg_queue::pallet as mock_msg_queue, primitives::{AccountId, AssetIdForAssets, Balance}, }; @@ -236,7 +236,7 @@ impl Contains for ThisParachain { } } -pub type XcmRouter = crate::tests::mock_network::ParachainXcmRouter; +pub type XcmRouter = crate::ParachainXcmRouter; pub type Barrier = ( xcm_builder::AllowUnpaidExecutionFrom, @@ -344,12 +344,12 @@ impl pallet_timestamp::Config for Runtime { construct_runtime!( pub enum Runtime { - System: frame_system::{Pallet, Call, Storage, Config, Event}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, - MsgQueue: mock_msg_queue::{Pallet, Storage, Event}, - PolkadotXcm: pallet_xcm::{Pallet, Call, Event, Origin}, - Contracts: crate::{Pallet, Call, Storage, Event, HoldReason}, + System: frame_system, + Balances: pallet_balances, + Timestamp: pallet_timestamp, + MsgQueue: mock_msg_queue, + PolkadotXcm: pallet_xcm, + Contracts: pallet_contracts, Assets: pallet_assets, } ); diff --git a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs b/substrate/frame/contracts/mock-network/src/parachain/contracts_config.rs similarity index 84% rename from substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs rename to substrate/frame/contracts/mock-network/src/parachain/contracts_config.rs index 163d565daac0..dadba394e264 100644 --- a/substrate/frame/contracts/src/tests/mock_network/parachain/contracts_config.rs +++ b/substrate/frame/contracts/mock-network/src/parachain/contracts_config.rs @@ -16,12 +16,9 @@ use super::{Balances, Runtime, RuntimeCall, RuntimeEvent}; use crate::{ - tests::mock_network::{ - parachain, - parachain::RuntimeHoldReason, - primitives::{Balance, CENTS}, - }, - Config, + parachain, + parachain::RuntimeHoldReason, + primitives::{Balance, CENTS}, }; use frame_support::{ parameter_types, @@ -40,14 +37,14 @@ parameter_types! { pub const DepositPerItem: Balance = deposit(1, 0); pub const DepositPerByte: Balance = deposit(0, 1); pub const DefaultDepositLimit: Balance = deposit(1024, 1024 * 1024); - pub Schedule: crate::Schedule = Default::default(); + pub Schedule: pallet_contracts::Schedule = Default::default(); pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0); pub const MaxDelegateDependencies: u32 = 32; } -pub struct DummyRandomness(sp_std::marker::PhantomData); +pub struct DummyRandomness(sp_std::marker::PhantomData); -impl Randomness> for DummyRandomness { +impl Randomness> for DummyRandomness { fn random(_subject: &[u8]) -> (T::Hash, BlockNumberFor) { (Default::default(), Default::default()) } @@ -71,10 +68,10 @@ impl Contains for Filters { } } -impl Config for Runtime { - type AddressGenerator = crate::DefaultAddressGenerator; +impl pallet_contracts::Config for Runtime { + type AddressGenerator = pallet_contracts::DefaultAddressGenerator; type CallFilter = Filters; - type CallStack = [crate::Frame; 5]; + type CallStack = [pallet_contracts::Frame; 5]; type ChainExtension = (); type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; type Currency = Balances; diff --git a/substrate/frame/contracts/src/tests/mock_network/primitives.rs b/substrate/frame/contracts/mock-network/src/primitives.rs similarity index 100% rename from substrate/frame/contracts/src/tests/mock_network/primitives.rs rename to substrate/frame/contracts/mock-network/src/primitives.rs diff --git a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs b/substrate/frame/contracts/mock-network/src/relay_chain.rs similarity index 99% rename from substrate/frame/contracts/src/tests/mock_network/relay_chain.rs rename to substrate/frame/contracts/mock-network/src/relay_chain.rs index 69207ea6985c..cab75d9fbf06 100644 --- a/substrate/frame/contracts/src/tests/mock_network/relay_chain.rs +++ b/substrate/frame/contracts/mock-network/src/relay_chain.rs @@ -142,7 +142,7 @@ impl Contains for ChildrenParachains { } } -pub type XcmRouter = crate::tests::mock_network::RelayChainXcmRouter; +pub type XcmRouter = crate::RelayChainXcmRouter; pub type Barrier = WithComputedOrigin< ( AllowExplicitUnpaidExecutionFrom, diff --git a/substrate/frame/contracts/src/tests/test_xcm.rs b/substrate/frame/contracts/mock-network/src/tests.rs similarity index 96% rename from substrate/frame/contracts/src/tests/test_xcm.rs rename to substrate/frame/contracts/mock-network/src/tests.rs index d34bc23dee0c..b8f8ccfde6e9 100644 --- a/substrate/frame/contracts/src/tests/test_xcm.rs +++ b/substrate/frame/contracts/mock-network/src/tests.rs @@ -16,18 +16,14 @@ // limitations under the License. use crate::{ - tests::{ - compile_module, - mock_network::{ - parachain::{self, Runtime, RuntimeOrigin}, - parachain_account_sovereign_account_id, - primitives::{AccountId, CENTS}, - relay_chain, MockNet, ParaA, ParachainBalances, ParachainPalletXcm, Relay, ALICE, BOB, - INITIAL_BALANCE, - }, - }, - CollectEvents, DebugInfo, Determinism, + parachain::{self, Runtime, RuntimeOrigin}, + parachain_account_sovereign_account_id, + primitives::{AccountId, CENTS}, + relay_chain, MockNet, ParaA, ParachainBalances, ParachainPalletXcm, Relay, ALICE, BOB, + INITIAL_BALANCE, }; +use pallet_contracts::{CollectEvents, DebugInfo, Determinism}; +// TODO add crate and use pallet_contracts_fixtures::compile_module; use assert_matches::assert_matches; use codec::{Decode, Encode}; use frame_support::{ diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index a5cd56f2899f..f4b4bfe0adb2 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -15,10 +15,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -mod mock_network; mod pallet_dummy; mod test_debug; -mod test_xcm; use self::{ test_debug::TestDebug, From 8b0f8ac16a97d62048841c50065a21365e5276fc Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 10 Nov 2023 16:52:00 +0100 Subject: [PATCH 094/115] revert bad merge --- Cargo.lock | 1471 +++++++++++------ .../contracts-rococo/src/contracts.rs | 2 - .../runtime/rococo/src/weights/pallet_xcm.rs | 76 +- polkadot/xcm/pallet-xcm/src/controller.rs | 186 --- polkadot/xcm/pallet-xcm/src/lib.rs | 15 +- .../xcm-executor/src/traits/on_response.rs | 10 +- 6 files changed, 1035 insertions(+), 725 deletions(-) delete mode 100644 polkadot/xcm/pallet-xcm/src/controller.rs diff --git a/Cargo.lock b/Cargo.lock index 92002af4661b..2a091ce6817d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -544,7 +544,7 @@ dependencies = [ [[package]] name = "ark-secret-scalar" version = "0.0.2" -source = "git+https://github.com/w3f/ring-vrf?rev=4b09416#4b09416fd23383ec436ddac127d58c7b7cd392c6" +source = "git+https://github.com/w3f/ring-vrf?rev=cbc342e#cbc342e95d3cbcd3c5ba8d45af7200eb58e63502" dependencies = [ "ark-ec", "ark-ff", @@ -593,7 +593,7 @@ dependencies = [ [[package]] name = "ark-transcript" version = "0.0.2" -source = "git+https://github.com/w3f/ring-vrf?rev=4b09416#4b09416fd23383ec436ddac127d58c7b7cd392c6" +source = "git+https://github.com/w3f/ring-vrf?rev=cbc342e#cbc342e95d3cbcd3c5ba8d45af7200eb58e63502" dependencies = [ "ark-ff", "ark-serialize", @@ -760,6 +760,7 @@ dependencies = [ "pallet-authorship", "pallet-balances", "pallet-collator-selection", + "pallet-message-queue", "pallet-multisig", "pallet-nft-fractionalization", "pallet-nfts", @@ -791,8 +792,8 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "sp-weights", @@ -832,6 +833,7 @@ dependencies = [ "pallet-authorship", "pallet-balances", "pallet-collator-selection", + "pallet-message-queue", "pallet-multisig", "pallet-nfts", "pallet-nfts-runtime-api", @@ -860,8 +862,8 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "sp-weights", @@ -872,6 +874,21 @@ dependencies = [ "substrate-wasm-builder", ] +[[package]] +name = "asset-hub-rococo-emulated-chain" +version = "0.0.0" +dependencies = [ + "asset-hub-rococo-runtime", + "cumulus-primitives-core", + "emulated-integration-tests-common", + "frame-support", + "parachains-common", + "rococo-emulated-chain", + "serde_json", + "sp-core", + "sp-runtime", +] + [[package]] name = "asset-hub-rococo-integration-tests" version = "1.0.0" @@ -879,23 +896,19 @@ dependencies = [ "assert_matches", "asset-hub-rococo-runtime", "asset-test-utils", + "emulated-integration-tests-common", "frame-support", - "frame-system", - "integration-tests-common", "pallet-asset-conversion", "pallet-assets", "pallet-balances", "pallet-xcm", "parachains-common", "parity-scale-codec", - "polkadot-core-primitives", - "polkadot-parachain-primitives", - "polkadot-runtime-parachains", "rococo-runtime", + "rococo-system-emulated-network", "sp-runtime", "staging-xcm", "staging-xcm-executor", - "xcm-emulator", ] [[package]] @@ -905,8 +918,10 @@ dependencies = [ "asset-test-utils", "assets-common", "bp-asset-hub-rococo", + "bp-asset-hub-westend", "bp-asset-hub-wococo", "bp-bridge-hub-rococo", + "bp-bridge-hub-westend", "bp-bridge-hub-wococo", "cumulus-pallet-aura-ext", "cumulus-pallet-dmp-queue", @@ -932,6 +947,7 @@ dependencies = [ "pallet-authorship", "pallet-balances", "pallet-collator-selection", + "pallet-message-queue", "pallet-multisig", "pallet-nft-fractionalization", "pallet-nfts", @@ -960,12 +976,13 @@ dependencies = [ "sp-block-builder", "sp-consensus-aura", "sp-core", + "sp-genesis-builder", "sp-inherents", "sp-offchain", "sp-runtime", "sp-session", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "sp-weights", @@ -976,6 +993,21 @@ dependencies = [ "substrate-wasm-builder", ] +[[package]] +name = "asset-hub-westend-emulated-chain" +version = "0.0.0" +dependencies = [ + "asset-hub-westend-runtime", + "cumulus-primitives-core", + "emulated-integration-tests-common", + "frame-support", + "parachains-common", + "serde_json", + "sp-core", + "sp-runtime", + "westend-emulated-chain", +] + [[package]] name = "asset-hub-westend-integration-tests" version = "1.0.0" @@ -985,28 +1017,26 @@ dependencies = [ "asset-test-utils", "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", + "emulated-integration-tests-common", "frame-support", "frame-system", - "integration-tests-common", "pallet-asset-conversion", "pallet-asset-rate", "pallet-assets", "pallet-balances", + "pallet-message-queue", "pallet-treasury", "pallet-xcm", "parachains-common", "parity-scale-codec", - "polkadot-core-primitives", - "polkadot-parachain-primitives", "polkadot-runtime-common", - "polkadot-runtime-parachains", "sp-runtime", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", "westend-runtime", "westend-runtime-constants", - "xcm-emulator", + "westend-system-emulated-network", ] [[package]] @@ -1015,6 +1045,10 @@ version = "0.9.420" dependencies = [ "asset-test-utils", "assets-common", + "bp-asset-hub-rococo", + "bp-asset-hub-westend", + "bp-bridge-hub-rococo", + "bp-bridge-hub-westend", "cumulus-pallet-aura-ext", "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", @@ -1039,6 +1073,7 @@ dependencies = [ "pallet-authorship", "pallet-balances", "pallet-collator-selection", + "pallet-message-queue", "pallet-multisig", "pallet-nft-fractionalization", "pallet-nfts", @@ -1052,6 +1087,7 @@ dependencies = [ "pallet-utility", "pallet-xcm", "pallet-xcm-benchmarks", + "pallet-xcm-bridge-hub-router", "parachains-common", "parity-scale-codec", "polkadot-core-primitives", @@ -1066,12 +1102,11 @@ dependencies = [ "sp-core", "sp-genesis-builder", "sp-inherents", - "sp-io", "sp-offchain", "sp-runtime", "sp-session", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -1082,12 +1117,27 @@ dependencies = [ "westend-runtime-constants", ] +[[package]] +name = "asset-hub-wococo-emulated-chain" +version = "0.0.0" +dependencies = [ + "asset-hub-rococo-emulated-chain", + "asset-hub-rococo-runtime", + "cumulus-primitives-core", + "emulated-integration-tests-common", + "frame-support", + "parachains-common", + "serde_json", + "sp-core", + "sp-runtime", + "wococo-emulated-chain", +] + [[package]] name = "asset-test-utils" version = "1.0.0" dependencies = [ "assets-common", - "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", "cumulus-pallet-xcmp-queue", "cumulus-primitives-core", @@ -1110,7 +1160,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", @@ -1134,7 +1184,7 @@ dependencies = [ "scale-info", "sp-api", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -1335,8 +1385,8 @@ dependencies = [ [[package]] name = "bandersnatch_vrfs" -version = "0.0.1" -source = "git+https://github.com/w3f/ring-vrf?rev=4b09416#4b09416fd23383ec436ddac127d58c7b7cd392c6" +version = "0.0.3" +source = "git+https://github.com/w3f/ring-vrf?rev=cbc342e#cbc342e95d3cbcd3c5ba8d45af7200eb58e63502" dependencies = [ "ark-bls12-381", "ark-ec", @@ -1351,6 +1401,8 @@ dependencies = [ "rand_core 0.6.4", "ring 0.1.0", "sha2 0.10.7", + "sp-ark-bls12-381", + "sp-ark-ed-on-bls12-381-bandersnatch", "zeroize", ] @@ -1457,8 +1509,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93f2635620bf0b9d4576eb7bb9a38a55df78bd1205d26fa994b25911a69f212f" dependencies = [ "bitcoin_hashes", - "rand 0.7.3", - "rand_core 0.5.1", + "rand 0.8.5", + "rand_core 0.6.4", "serde", "unicode-normalization", ] @@ -1682,6 +1734,16 @@ dependencies = [ "scale-info", ] +[[package]] +name = "bp-asset-hub-westend" +version = "0.1.0" +dependencies = [ + "bp-xcm-bridge-hub-router", + "frame-support", + "parity-scale-codec", + "scale-info", +] + [[package]] name = "bp-asset-hub-wococo" version = "0.1.0" @@ -1703,7 +1765,7 @@ dependencies = [ "frame-system", "polkadot-primitives", "sp-api", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1716,7 +1778,7 @@ dependencies = [ "frame-support", "sp-api", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1729,7 +1791,7 @@ dependencies = [ "frame-support", "sp-api", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1742,7 +1804,20 @@ dependencies = [ "frame-support", "sp-api", "sp-runtime", - "sp-std", + "sp-std 8.0.0", +] + +[[package]] +name = "bp-bridge-hub-westend" +version = "0.1.0" +dependencies = [ + "bp-bridge-hub-cumulus", + "bp-messages", + "bp-runtime", + "frame-support", + "sp-api", + "sp-runtime", + "sp-std 8.0.0", ] [[package]] @@ -1755,7 +1830,7 @@ dependencies = [ "frame-support", "sp-api", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1774,7 +1849,7 @@ dependencies = [ "sp-consensus-grandpa", "sp-core", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1786,7 +1861,7 @@ dependencies = [ "bp-runtime", "frame-support", "sp-api", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1802,7 +1877,7 @@ dependencies = [ "scale-info", "serde", "sp-core", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1818,7 +1893,7 @@ dependencies = [ "scale-info", "sp-core", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1830,7 +1905,7 @@ dependencies = [ "bp-runtime", "frame-support", "sp-api", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1847,7 +1922,7 @@ dependencies = [ "scale-info", "sp-api", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1865,7 +1940,7 @@ dependencies = [ "serde", "sp-core", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1880,7 +1955,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1892,7 +1967,7 @@ dependencies = [ "bp-runtime", "frame-support", "sp-api", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1913,7 +1988,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-state-machine", - "sp-std", + "sp-std 8.0.0", "sp-trie", "trie-db", ] @@ -1933,10 +2008,22 @@ dependencies = [ "sp-consensus-grandpa", "sp-core", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-trie", ] +[[package]] +name = "bp-westend" +version = "0.1.0" +dependencies = [ + "bp-header-chain", + "bp-polkadot-core", + "bp-runtime", + "frame-support", + "sp-api", + "sp-std 8.0.0", +] + [[package]] name = "bp-wococo" version = "0.1.0" @@ -1947,7 +2034,7 @@ dependencies = [ "bp-runtime", "frame-support", "sp-api", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -1986,6 +2073,7 @@ dependencies = [ "pallet-authorship", "pallet-balances", "pallet-collator-selection", + "pallet-message-queue", "pallet-multisig", "pallet-session", "pallet-timestamp", @@ -2012,8 +2100,8 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -2049,6 +2137,7 @@ dependencies = [ "pallet-authorship", "pallet-balances", "pallet-collator-selection", + "pallet-message-queue", "pallet-multisig", "pallet-session", "pallet-timestamp", @@ -2075,8 +2164,8 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -2086,6 +2175,20 @@ dependencies = [ "substrate-wasm-builder", ] +[[package]] +name = "bridge-hub-rococo-emulated-chain" +version = "0.0.0" +dependencies = [ + "bridge-hub-rococo-runtime", + "cumulus-primitives-core", + "emulated-integration-tests-common", + "frame-support", + "parachains-common", + "serde_json", + "sp-core", + "sp-runtime", +] + [[package]] name = "bridge-hub-rococo-integration-tests" version = "1.0.0" @@ -2095,18 +2198,16 @@ dependencies = [ "bridge-hub-rococo-runtime", "cumulus-pallet-dmp-queue", "cumulus-pallet-xcmp-queue", + "emulated-integration-tests-common", "frame-support", - "integration-tests-common", "pallet-bridge-messages", + "pallet-message-queue", "pallet-xcm", "parachains-common", "parity-scale-codec", - "polkadot-core-primitives", - "polkadot-parachain-primitives", - "polkadot-runtime-parachains", + "rococo-wococo-system-emulated-network", "staging-xcm", "staging-xcm-executor", - "xcm-emulator", ] [[package]] @@ -2114,8 +2215,10 @@ name = "bridge-hub-rococo-runtime" version = "0.1.0" dependencies = [ "bp-asset-hub-rococo", + "bp-asset-hub-westend", "bp-asset-hub-wococo", "bp-bridge-hub-rococo", + "bp-bridge-hub-westend", "bp-bridge-hub-wococo", "bp-header-chain", "bp-messages", @@ -2124,6 +2227,7 @@ dependencies = [ "bp-relayers", "bp-rococo", "bp-runtime", + "bp-westend", "bp-wococo", "bridge-hub-test-utils", "bridge-runtime-common", @@ -2152,6 +2256,7 @@ dependencies = [ "pallet-bridge-parachains", "pallet-bridge-relayers", "pallet-collator-selection", + "pallet-message-queue", "pallet-multisig", "pallet-session", "pallet-timestamp", @@ -2180,8 +2285,8 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -2207,7 +2312,6 @@ dependencies = [ "bp-runtime", "bp-test-utils", "bridge-runtime-common", - "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", "cumulus-pallet-xcmp-queue", "frame-benchmarking", @@ -2232,13 +2336,146 @@ dependencies = [ "sp-io", "sp-keyring", "sp-runtime", - "sp-tracing", + "sp-tracing 10.0.0", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", ] +[[package]] +name = "bridge-hub-westend-emulated-chain" +version = "0.0.0" +dependencies = [ + "bridge-hub-westend-runtime", + "cumulus-primitives-core", + "emulated-integration-tests-common", + "frame-support", + "parachains-common", + "serde_json", + "sp-core", + "sp-runtime", +] + +[[package]] +name = "bridge-hub-westend-integration-tests" +version = "1.0.0" +dependencies = [ + "asset-test-utils", + "bp-messages", + "bridge-hub-westend-runtime", + "cumulus-pallet-dmp-queue", + "cumulus-pallet-xcmp-queue", + "emulated-integration-tests-common", + "frame-support", + "pallet-bridge-messages", + "pallet-message-queue", + "pallet-xcm", + "parachains-common", + "parity-scale-codec", + "staging-xcm", + "staging-xcm-executor", + "westend-system-emulated-network", +] + +[[package]] +name = "bridge-hub-westend-runtime" +version = "0.1.0" +dependencies = [ + "bp-asset-hub-westend", + "bp-bridge-hub-rococo", + "bp-bridge-hub-westend", + "bp-header-chain", + "bp-messages", + "bp-parachains", + "bp-polkadot-core", + "bp-relayers", + "bp-rococo", + "bp-runtime", + "bp-westend", + "bridge-hub-test-utils", + "bridge-runtime-common", + "cumulus-pallet-aura-ext", + "cumulus-pallet-dmp-queue", + "cumulus-pallet-parachain-system", + "cumulus-pallet-session-benchmarking", + "cumulus-pallet-xcm", + "cumulus-pallet-xcmp-queue", + "cumulus-primitives-core", + "cumulus-primitives-utility", + "frame-benchmarking", + "frame-executive", + "frame-support", + "frame-system", + "frame-system-benchmarking", + "frame-system-rpc-runtime-api", + "frame-try-runtime", + "hex-literal", + "log", + "pallet-aura", + "pallet-authorship", + "pallet-balances", + "pallet-bridge-grandpa", + "pallet-bridge-messages", + "pallet-bridge-parachains", + "pallet-bridge-relayers", + "pallet-collator-selection", + "pallet-message-queue", + "pallet-multisig", + "pallet-session", + "pallet-timestamp", + "pallet-transaction-payment", + "pallet-transaction-payment-rpc-runtime-api", + "pallet-utility", + "pallet-xcm", + "pallet-xcm-benchmarks", + "parachains-common", + "parity-scale-codec", + "polkadot-core-primitives", + "polkadot-parachain-primitives", + "polkadot-runtime-common", + "scale-info", + "serde", + "smallvec", + "sp-api", + "sp-block-builder", + "sp-consensus-aura", + "sp-core", + "sp-genesis-builder", + "sp-inherents", + "sp-io", + "sp-keyring", + "sp-offchain", + "sp-runtime", + "sp-session", + "sp-std 8.0.0", + "sp-storage 13.0.0", + "sp-transaction-pool", + "sp-version", + "staging-parachain-info", + "staging-xcm", + "staging-xcm-builder", + "staging-xcm-executor", + "static_assertions", + "substrate-wasm-builder", + "westend-runtime-constants", +] + +[[package]] +name = "bridge-hub-wococo-emulated-chain" +version = "0.0.0" +dependencies = [ + "bridge-hub-rococo-emulated-chain", + "bridge-hub-rococo-runtime", + "cumulus-primitives-core", + "emulated-integration-tests-common", + "frame-support", + "parachains-common", + "serde_json", + "sp-core", + "sp-runtime", +] + [[package]] name = "bridge-runtime-common" version = "0.1.0" @@ -2268,7 +2505,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-trie", "staging-xcm", "staging-xcm-builder", @@ -2745,6 +2982,7 @@ dependencies = [ "pallet-collective", "pallet-collective-content", "pallet-core-fellowship", + "pallet-message-queue", "pallet-multisig", "pallet-preimage", "pallet-proxy", @@ -2776,8 +3014,8 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -2961,6 +3199,7 @@ dependencies = [ "pallet-contracts", "pallet-contracts-primitives", "pallet-insecure-randomness-collective-flip", + "pallet-message-queue", "pallet-multisig", "pallet-session", "pallet-sudo", @@ -2986,8 +3225,8 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -3436,7 +3675,7 @@ dependencies = [ "sp-maybe-compressed-blob", "sp-runtime", "sp-state-machine", - "sp-tracing", + "sp-tracing 10.0.0", "tracing", ] @@ -3507,7 +3746,7 @@ dependencies = [ "sp-core", "sp-runtime", "sp-timestamp", - "sp-tracing", + "sp-tracing 10.0.0", "sp-trie", "substrate-prometheus-endpoint", "tracing", @@ -3658,7 +3897,7 @@ dependencies = [ "sp-application-crypto", "sp-consensus-aura", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -3666,6 +3905,7 @@ name = "cumulus-pallet-dmp-queue" version = "0.1.0" dependencies = [ "cumulus-primitives-core", + "frame-benchmarking", "frame-support", "frame-system", "log", @@ -3674,8 +3914,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", - "sp-version", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "staging-xcm", ] @@ -3691,26 +3931,30 @@ dependencies = [ "cumulus-test-client", "cumulus-test-relay-sproof-builder", "environmental", + "frame-benchmarking", "frame-support", "frame-system", + "futures", "hex-literal", "impl-trait-for-tuples", "lazy_static", "log", + "pallet-message-queue", "parity-scale-codec", "polkadot-parachain-primitives", "polkadot-runtime-parachains", + "rand 0.8.5", "sc-client-api", "scale-info", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-inherents", "sp-io", "sp-keyring", "sp-runtime", "sp-state-machine", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "sp-trie", "sp-version", "staging-xcm", @@ -3737,7 +3981,7 @@ dependencies = [ "pallet-session", "parity-scale-codec", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -3752,7 +3996,7 @@ dependencies = [ "polkadot-primitives", "scale-info", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -3766,7 +4010,7 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "staging-xcm", ] @@ -3774,6 +4018,7 @@ dependencies = [ name = "cumulus-pallet-xcmp-queue" version = "0.1.0" dependencies = [ + "bounded-collections", "bp-xcm-bridge-hub-router", "cumulus-pallet-parachain-system", "cumulus-primitives-core", @@ -3782,15 +4027,15 @@ dependencies = [ "frame-system", "log", "pallet-balances", + "pallet-message-queue", "parity-scale-codec", "polkadot-runtime-common", "polkadot-runtime-parachains", - "rand_chacha 0.3.1", "scale-info", "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -3807,7 +4052,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "staging-xcm", ] @@ -3821,7 +4066,7 @@ dependencies = [ "sp-api", "sp-consensus-aura", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -3835,7 +4080,7 @@ dependencies = [ "scale-info", "sp-api", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-trie", "staging-xcm", ] @@ -3856,8 +4101,8 @@ dependencies = [ "sp-inherents", "sp-runtime", "sp-state-machine", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-trie", "tracing", ] @@ -3870,7 +4115,7 @@ dependencies = [ "futures", "parity-scale-codec", "sp-inherents", - "sp-std", + "sp-std 8.0.0", "sp-timestamp", ] @@ -3887,7 +4132,7 @@ dependencies = [ "polkadot-runtime-parachains", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -3953,6 +4198,7 @@ dependencies = [ "polkadot-core-primitives", "polkadot-network-bridge", "polkadot-node-collation-generation", + "polkadot-node-core-prospective-parachains", "polkadot-node-core-runtime-api", "polkadot-node-network-protocol", "polkadot-node-subsystem-util", @@ -4001,7 +4247,7 @@ dependencies = [ "sp-core", "sp-runtime", "sp-state-machine", - "sp-storage", + "sp-storage 13.0.0", "thiserror", "tokio", "tokio-util", @@ -4049,7 +4295,7 @@ dependencies = [ "polkadot-primitives", "sp-runtime", "sp-state-machine", - "sp-std", + "sp-std 8.0.0", "sp-trie", ] @@ -4065,6 +4311,7 @@ dependencies = [ "frame-system-rpc-runtime-api", "pallet-balances", "pallet-glutton", + "pallet-message-queue", "pallet-sudo", "pallet-timestamp", "pallet-transaction-payment", @@ -4073,12 +4320,13 @@ dependencies = [ "sp-api", "sp-block-builder", "sp-core", + "sp-genesis-builder", "sp-inherents", "sp-io", "sp-offchain", "sp-runtime", "sp-session", - "sp-std", + "sp-std 8.0.0", "sp-transaction-pool", "sp-version", "substrate-wasm-builder", @@ -4139,6 +4387,7 @@ dependencies = [ "sc-transaction-pool", "sc-transaction-pool-api", "serde", + "serde_json", "sp-api", "sp-arithmetic", "sp-authority-discovery", @@ -4151,7 +4400,7 @@ dependencies = [ "sp-runtime", "sp-state-machine", "sp-timestamp", - "sp-tracing", + "sp-tracing 10.0.0", "substrate-test-client", "substrate-test-utils", "tempfile", @@ -4579,7 +4828,7 @@ checksum = "86e3bdc80eee6e16b2b6b0f87fbc98c04bee3455e35174c0de1a125d0688c632" [[package]] name = "dleq_vrf" version = "0.0.2" -source = "git+https://github.com/w3f/ring-vrf?rev=4b09416#4b09416fd23383ec436ddac127d58c7b7cd392c6" +source = "git+https://github.com/w3f/ring-vrf?rev=cbc342e#cbc342e95d3cbcd3c5ba8d45af7200eb58e63502" dependencies = [ "ark-ec", "ark-ff", @@ -4806,6 +5055,40 @@ dependencies = [ "zeroize", ] +[[package]] +name = "emulated-integration-tests-common" +version = "1.0.0" +dependencies = [ + "asset-test-utils", + "bp-messages", + "bridge-runtime-common", + "cumulus-pallet-parachain-system", + "cumulus-pallet-xcmp-queue", + "cumulus-primitives-core", + "frame-support", + "pallet-assets", + "pallet-balances", + "pallet-bridge-messages", + "pallet-im-online", + "pallet-message-queue", + "pallet-xcm", + "parachains-common", + "parity-scale-codec", + "paste", + "polkadot-primitives", + "polkadot-runtime-parachains", + "polkadot-service", + "sc-consensus-grandpa", + "serde_json", + "sp-authority-discovery", + "sp-consensus-babe", + "sp-consensus-beefy", + "sp-core", + "sp-runtime", + "staging-xcm", + "xcm-emulator", +] + [[package]] name = "encode_unicode" version = "0.3.6" @@ -5287,7 +5570,7 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", + "sp-std 8.0.0", "sp-transaction-pool", "sp-version", ] @@ -5313,9 +5596,9 @@ dependencies = [ "sp-io", "sp-keystore", "sp-runtime", - "sp-runtime-interface", - "sp-std", - "sp-storage", + "sp-runtime-interface 17.0.0", + "sp-std 8.0.0", + "sp-storage 13.0.0", "static_assertions", ] @@ -5353,15 +5636,15 @@ dependencies = [ "sp-blockchain", "sp-core", "sp-database", - "sp-externalities", + "sp-externalities 0.19.0", "sp-inherents", "sp-io", "sp-keystore", "sp-runtime", "sp-state-machine", - "sp-storage", + "sp-storage 13.0.0", "sp-trie", - "sp-wasm-interface", + "sp-wasm-interface 14.0.0", "thiserror", "thousands", ] @@ -5377,7 +5660,7 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -5411,7 +5694,7 @@ dependencies = [ "sp-io", "sp-npos-elections", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -5448,8 +5731,8 @@ dependencies = [ "sp-inherents", "sp-io", "sp-runtime", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "sp-version", ] @@ -5479,7 +5762,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-state-machine", - "sp-tracing", + "sp-tracing 10.0.0", "spinners", "substrate-rpc-client", "tokio", @@ -5514,7 +5797,7 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-core-hashing-proc-macro", - "sp-debug-derive", + "sp-debug-derive 8.0.0", "sp-genesis-builder", "sp-inherents", "sp-io", @@ -5522,8 +5805,8 @@ dependencies = [ "sp-runtime", "sp-staking", "sp-state-machine", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "sp-weights", "static_assertions", "tt-call", @@ -5589,7 +5872,7 @@ dependencies = [ "sp-metadata-ir", "sp-runtime", "sp-state-machine", - "sp-std", + "sp-std 8.0.0", "sp-version", "static_assertions", "trybuild", @@ -5641,10 +5924,10 @@ dependencies = [ "scale-info", "serde", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-version", "sp-weights", "substrate-test-runtime-client", @@ -5660,10 +5943,10 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-version", ] @@ -5683,7 +5966,7 @@ dependencies = [ "parity-scale-codec", "sp-api", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -5995,6 +6278,7 @@ dependencies = [ "frame-try-runtime", "pallet-aura", "pallet-glutton", + "pallet-message-queue", "pallet-sudo", "pallet-timestamp", "parachains-common", @@ -6009,8 +6293,8 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -6552,55 +6836,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "integration-tests-common" -version = "1.0.0" -dependencies = [ - "asset-hub-kusama-runtime", - "asset-hub-polkadot-runtime", - "asset-hub-rococo-runtime", - "asset-hub-westend-runtime", - "bp-messages", - "bridge-hub-kusama-runtime", - "bridge-hub-polkadot-runtime", - "bridge-hub-rococo-runtime", - "bridge-runtime-common", - "collectives-polkadot-runtime", - "cumulus-pallet-dmp-queue", - "cumulus-pallet-parachain-system", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-core", - "frame-support", - "pallet-assets", - "pallet-balances", - "pallet-bridge-messages", - "pallet-im-online", - "pallet-message-queue", - "pallet-staking", - "pallet-xcm", - "parachains-common", - "parity-scale-codec", - "paste", - "penpal-runtime", - "polkadot-core-primitives", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", - "polkadot-service", - "rococo-runtime", - "rococo-runtime-constants", - "sc-consensus-grandpa", - "sp-authority-discovery", - "sp-consensus-babe", - "sp-consensus-beefy", - "sp-core", - "sp-runtime", - "staging-xcm", - "westend-runtime", - "westend-runtime-constants", - "xcm-emulator", -] - [[package]] name = "interceptor" version = "0.8.2" @@ -7010,6 +7245,7 @@ dependencies = [ "parity-scale-codec", "primitive-types", "scale-info", + "serde_json", "sp-api", "sp-authority-discovery", "sp-block-builder", @@ -7025,8 +7261,8 @@ dependencies = [ "sp-session", "sp-staking", "sp-statement-store", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "static_assertions", @@ -8050,6 +8286,7 @@ dependencies = [ "sc-telemetry", "sc-transaction-pool", "sc-transaction-pool-api", + "serde_json", "sp-api", "sp-block-builder", "sp-blockchain", @@ -8066,6 +8303,7 @@ name = "minimal-runtime" version = "0.1.0" dependencies = [ "frame", + "frame-support", "pallet-balances", "pallet-sudo", "pallet-timestamp", @@ -8073,6 +8311,7 @@ dependencies = [ "pallet-transaction-payment-rpc-runtime-api", "parity-scale-codec", "scale-info", + "sp-genesis-builder", "substrate-wasm-builder", ] @@ -8139,7 +8378,7 @@ dependencies = [ "sp-core", "sp-mmr-primitives", "sp-runtime", - "sp-tracing", + "sp-tracing 10.0.0", "substrate-test-runtime-client", "tokio", ] @@ -8449,7 +8688,7 @@ dependencies = [ "sp-runtime", "sp-state-machine", "sp-timestamp", - "sp-tracing", + "sp-tracing 10.0.0", "sp-trie", "tempfile", ] @@ -8530,6 +8769,7 @@ dependencies = [ "sc-telemetry", "sc-transaction-pool", "sc-transaction-pool-api", + "serde_json", "sp-api", "sp-block-builder", "sp-blockchain", @@ -8581,6 +8821,7 @@ dependencies = [ "pallet-transaction-payment-rpc-runtime-api", "parity-scale-codec", "scale-info", + "serde_json", "sp-api", "sp-block-builder", "sp-consensus-aura", @@ -8591,8 +8832,8 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "substrate-wasm-builder", @@ -8937,7 +9178,7 @@ dependencies = [ "sp-core-hashing", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -8957,7 +9198,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -8975,8 +9216,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", ] [[package]] @@ -8992,7 +9233,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9013,8 +9254,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", ] [[package]] @@ -9031,7 +9272,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9046,7 +9287,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9064,7 +9305,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9081,7 +9322,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9096,7 +9337,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9124,7 +9365,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9144,8 +9385,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", ] [[package]] @@ -9171,9 +9412,9 @@ dependencies = [ "pallet-staking", "sp-core", "sp-runtime", - "sp-std", - "sp-storage", - "sp-tracing", + "sp-std 8.0.0", + "sp-storage 13.0.0", + "sp-tracing 10.0.0", ] [[package]] @@ -9191,7 +9432,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9219,7 +9460,7 @@ dependencies = [ "sp-session", "sp-staking", "sp-state-machine", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9244,7 +9485,7 @@ dependencies = [ "sp-runtime", "sp-staking", "sp-state-machine", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9262,7 +9503,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9283,7 +9524,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-trie", ] @@ -9305,7 +9546,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9327,7 +9568,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-trie", ] @@ -9350,7 +9591,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9367,7 +9608,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9386,7 +9627,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9410,8 +9651,8 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", ] [[package]] @@ -9427,7 +9668,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9442,7 +9683,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9459,20 +9700,15 @@ dependencies = [ "frame-system", "impl-trait-for-tuples", "log", - "pallet-assets", "pallet-balances", + "pallet-contracts-fixtures", "pallet-contracts-primitives", "pallet-contracts-proc-macro", "pallet-insecure-randomness-collective-flip", - "pallet-message-queue", "pallet-proxy", "pallet-timestamp", "pallet-utility", - "pallet-xcm", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", + "parity-scale-codec", "pretty_assertions", "rand 0.8.5", "rand_pcg", @@ -9484,50 +9720,19 @@ dependencies = [ "sp-io", "sp-keystore", "sp-runtime", - "sp-std", - "sp-tracing", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "sp-std 8.0.0", "wasm-instrument 0.4.0", "wasmi", "wat", - "xcm-simulator", ] [[package]] -name = "pallet-contracts-mock-network" +name = "pallet-contracts-fixtures" version = "1.0.0" dependencies = [ - "frame-support", "frame-system", - "pallet-assets", - "pallet-balances", - "pallet-contracts", - "pallet-contracts-primitives", - "pallet-contracts-proc-macro", - "pallet-insecure-randomness-collective-flip", - "pallet-message-queue", - "pallet-proxy", - "pallet-timestamp", - "pallet-utility", - "pallet-xcm", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", - "scale-info", - "sp-api", - "sp-core", - "sp-io", - "sp-keystore", "sp-runtime", - "sp-std", - "sp-tracing", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "xcm-simulator", + "wat", ] [[package]] @@ -9538,7 +9743,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-weights", ] @@ -9567,7 +9772,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9584,7 +9789,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9598,7 +9803,7 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9618,7 +9823,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9634,7 +9839,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9659,8 +9864,8 @@ dependencies = [ "sp-npos-elections", "sp-runtime", "sp-staking", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", ] [[package]] @@ -9683,8 +9888,8 @@ dependencies = [ "sp-io", "sp-npos-elections", "sp-runtime", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "strum", ] @@ -9698,7 +9903,7 @@ dependencies = [ "parity-scale-codec", "sp-npos-elections", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9717,8 +9922,8 @@ dependencies = [ "sp-npos-elections", "sp-runtime", "sp-staking", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "substrate-test-utils", ] @@ -9736,7 +9941,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9762,7 +9967,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9779,7 +9984,7 @@ dependencies = [ "sp-io", "sp-keystore", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9794,7 +9999,7 @@ dependencies = [ "scale-info", "sp-core", "sp-io", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9830,8 +10035,8 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "substrate-test-utils", ] @@ -9850,7 +10055,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9880,7 +10085,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9897,7 +10102,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9917,7 +10122,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9934,7 +10139,7 @@ dependencies = [ "sp-io", "sp-keyring", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9949,7 +10154,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9966,7 +10171,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -9982,7 +10187,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10002,8 +10207,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "sp-weights", ] @@ -10023,7 +10228,7 @@ dependencies = [ "sp-io", "sp-mixnet", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10043,7 +10248,7 @@ dependencies = [ "sp-io", "sp-mmr-primitives", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10059,7 +10264,7 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10078,7 +10283,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10097,7 +10302,7 @@ dependencies = [ "sp-io", "sp-keystore", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10121,7 +10326,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10138,7 +10343,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10153,7 +10358,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10170,8 +10375,8 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", ] [[package]] @@ -10193,9 +10398,9 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-runtime-interface", + "sp-runtime-interface 17.0.0", "sp-staking", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10210,7 +10415,7 @@ dependencies = [ "rand 0.8.5", "sp-io", "sp-runtime", - "sp-tracing", + "sp-tracing 10.0.0", ] [[package]] @@ -10220,7 +10425,7 @@ dependencies = [ "pallet-nomination-pools", "parity-scale-codec", "sp-api", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10243,8 +10448,8 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", ] [[package]] @@ -10262,7 +10467,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10289,7 +10494,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10306,7 +10511,7 @@ dependencies = [ "sp-io", "sp-metadata-ir", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10349,7 +10554,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10366,7 +10571,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10383,7 +10588,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10399,7 +10604,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10421,7 +10626,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10437,7 +10642,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10458,7 +10663,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10472,7 +10677,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10491,7 +10696,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10508,7 +10713,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10526,7 +10731,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-weights", "substrate-test-utils", ] @@ -10543,7 +10748,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10563,7 +10768,7 @@ dependencies = [ "sp-session", "sp-staking", "sp-state-machine", - "sp-std", + "sp-std 8.0.0", "sp-trie", ] @@ -10587,7 +10792,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-session", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10607,7 +10812,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10635,8 +10840,8 @@ dependencies = [ "sp-npos-elections", "sp-runtime", "sp-staking", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "substrate-test-utils", ] @@ -10685,8 +10890,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "substrate-state-trie-migration-rpc", "thousands", "tokio", @@ -10708,7 +10913,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-statement-store", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10724,7 +10929,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10739,7 +10944,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10757,8 +10962,8 @@ dependencies = [ "sp-inherents", "sp-io", "sp-runtime", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-timestamp", ] @@ -10778,8 +10983,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", ] [[package]] @@ -10796,7 +11001,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10842,7 +11047,7 @@ dependencies = [ "sp-inherents", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-transaction-storage-proof", ] @@ -10863,7 +11068,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10881,7 +11086,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10898,7 +11103,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10917,7 +11122,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10934,7 +11139,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10952,7 +11157,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -10973,7 +11178,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -10997,8 +11202,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -11018,7 +11223,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "staging-xcm", "staging-xcm-builder", ] @@ -11065,6 +11270,7 @@ dependencies = [ "sc-transaction-pool", "sc-transaction-pool-api", "serde", + "serde_json", "sp-api", "sp-block-builder", "sp-blockchain", @@ -11105,6 +11311,7 @@ dependencies = [ "pallet-authorship", "pallet-balances", "pallet-collator-selection", + "pallet-message-queue", "pallet-parachain-template", "pallet-session", "pallet-sudo", @@ -11112,6 +11319,7 @@ dependencies = [ "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", "pallet-xcm", + "parachains-common", "parity-scale-codec", "polkadot-parachain-primitives", "polkadot-runtime-common", @@ -11126,7 +11334,7 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", + "sp-std 8.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -11151,6 +11359,7 @@ dependencies = [ "pallet-authorship", "pallet-balances", "pallet-collator-selection", + "pallet-message-queue", "parity-scale-codec", "polkadot-core-primitives", "polkadot-primitives", @@ -11161,7 +11370,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", @@ -11174,7 +11383,6 @@ name = "parachains-runtimes-test-utils" version = "1.0.0" dependencies = [ "assets-common", - "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", "cumulus-pallet-xcmp-queue", "cumulus-primitives-core", @@ -11195,8 +11403,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "staging-parachain-info", "staging-xcm", "staging-xcm-executor", @@ -11399,6 +11607,20 @@ dependencies = [ "base64ct", ] +[[package]] +name = "penpal-emulated-chain" +version = "0.0.0" +dependencies = [ + "cumulus-primitives-core", + "emulated-integration-tests-common", + "frame-support", + "parachains-common", + "penpal-runtime", + "serde_json", + "sp-core", + "sp-runtime", +] + [[package]] name = "penpal-runtime" version = "0.9.27" @@ -11426,6 +11648,7 @@ dependencies = [ "pallet-authorship", "pallet-balances", "pallet-collator-selection", + "pallet-message-queue", "pallet-session", "pallet-sudo", "pallet-timestamp", @@ -11448,8 +11671,8 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", - "sp-storage", + "sp-std 8.0.0", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -11643,9 +11866,11 @@ name = "polkadot-approval-distribution" version = "1.0.0" dependencies = [ "assert_matches", + "bitvec", "env_logger 0.9.3", "futures", "futures-timer", + "itertools 0.10.5", "log", "polkadot-node-jaeger", "polkadot-node-metrics", @@ -11716,7 +11941,7 @@ dependencies = [ "sp-core", "sp-keyring", "sp-keystore", - "sp-tracing", + "sp-tracing 10.0.0", "thiserror", "tracing-gum", ] @@ -11817,7 +12042,7 @@ dependencies = [ "scale-info", "sp-core", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -11848,7 +12073,7 @@ dependencies = [ "sp-application-crypto", "sp-keyring", "sp-keystore", - "sp-tracing", + "sp-tracing 10.0.0", "thiserror", "tracing-gum", ] @@ -11891,7 +12116,7 @@ dependencies = [ "sp-core", "sp-keyring", "sp-keystore", - "sp-tracing", + "sp-tracing 10.0.0", "tracing-gum", ] @@ -11953,10 +12178,13 @@ dependencies = [ "async-trait", "bitvec", "derive_more", + "env_logger 0.9.3", "futures", "futures-timer", + "itertools 0.10.5", "kvdb", "kvdb-memorydb", + "log", "merlin 2.0.1", "parity-scale-codec", "parking_lot 0.12.1", @@ -11968,6 +12196,8 @@ dependencies = [ "polkadot-overseer", "polkadot-primitives", "polkadot-primitives-test-helpers", + "rand 0.8.5", + "rand_chacha 0.3.1", "rand_core 0.5.1", "sc-keystore", "schnellru", @@ -12035,7 +12265,7 @@ dependencies = [ "sp-core", "sp-keyring", "sp-keystore", - "sp-tracing", + "sp-tracing 10.0.0", "thiserror", "tracing-gum", ] @@ -12144,7 +12374,7 @@ dependencies = [ "sp-core", "sp-keyring", "sp-keystore", - "sp-tracing", + "sp-tracing 10.0.0", "thiserror", "tracing-gum", ] @@ -12241,7 +12471,7 @@ dependencies = [ "slotmap", "sp-core", "sp-maybe-compressed-blob", - "sp-wasm-interface", + "sp-wasm-interface 14.0.0", "tempfile", "test-parachain-adder", "test-parachain-halt", @@ -12290,9 +12520,9 @@ dependencies = [ "sc-executor-wasmtime", "seccompiler", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-io", - "sp-tracing", + "sp-tracing 10.0.0", "tempfile", "thiserror", "tracing-gum", @@ -12315,14 +12545,19 @@ name = "polkadot-node-core-pvf-prepare-worker" version = "1.0.0" dependencies = [ "cfg-if", + "criterion 0.4.0", "libc", "parity-scale-codec", "polkadot-node-core-pvf-common", "polkadot-primitives", "rayon", + "rococo-runtime", "sc-executor-common", "sc-executor-wasmtime", + "sp-maybe-compressed-blob", + "staging-tracking-allocator", "tikv-jemalloc-ctl", + "tikv-jemallocator", "tracing-gum", ] @@ -12418,6 +12653,7 @@ dependencies = [ name = "polkadot-node-primitives" version = "1.0.0" dependencies = [ + "bitvec", "bounded-vec", "futures", "parity-scale-codec", @@ -12469,6 +12705,7 @@ name = "polkadot-node-subsystem-types" version = "1.0.0" dependencies = [ "async-trait", + "bitvec", "derive_more", "futures", "orchestra", @@ -12570,6 +12807,7 @@ dependencies = [ "bridge-hub-kusama-runtime", "bridge-hub-polkadot-runtime", "bridge-hub-rococo-runtime", + "bridge-hub-westend-runtime", "clap 4.4.6", "collectives-polkadot-runtime", "color-print", @@ -12631,6 +12869,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-timestamp", + "sp-tracing 10.0.0", "sp-transaction-pool", "staging-xcm", "substrate-build-script-utils", @@ -12654,7 +12893,7 @@ dependencies = [ "serde", "sp-core", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-weights", ] @@ -12680,7 +12919,7 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-staking", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -12774,7 +13013,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std", + "sp-std 8.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -12789,8 +13028,8 @@ dependencies = [ "frame-benchmarking", "parity-scale-codec", "polkadot-primitives", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", ] [[package]] @@ -12841,8 +13080,8 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "staging-xcm", "staging-xcm-executor", "static_assertions", @@ -12908,6 +13147,7 @@ dependencies = [ "polkadot-overseer", "polkadot-parachain-primitives", "polkadot-primitives", + "polkadot-primitives-test-helpers", "polkadot-rpc", "polkadot-runtime-parachains", "polkadot-statement-distribution", @@ -12959,7 +13199,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-state-machine", - "sp-storage", + "sp-storage 13.0.0", "sp-timestamp", "sp-transaction-pool", "sp-version", @@ -13002,7 +13242,7 @@ dependencies = [ "sp-keyring", "sp-keystore", "sp-staking", - "sp-tracing", + "sp-tracing 10.0.0", "thiserror", "tracing-gum", ] @@ -13130,7 +13370,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std", + "sp-std 8.0.0", "sp-transaction-pool", "sp-trie", "sp-version", @@ -13989,7 +14229,7 @@ dependencies = [ "log", "pallet-bags-list-remote-tests", "sp-core", - "sp-tracing", + "sp-tracing 10.0.0", "tokio", "westend-runtime", "westend-runtime-constants", @@ -14122,6 +14362,25 @@ dependencies = [ "librocksdb-sys", ] +[[package]] +name = "rococo-emulated-chain" +version = "0.0.0" +dependencies = [ + "emulated-integration-tests-common", + "pallet-im-online", + "parachains-common", + "polkadot-primitives", + "rococo-runtime", + "rococo-runtime-constants", + "sc-consensus-grandpa", + "serde_json", + "sp-authority-discovery", + "sp-consensus-babe", + "sp-consensus-beefy", + "sp-core", + "sp-runtime", +] + [[package]] name = "rococo-parachain-runtime" version = "0.1.0" @@ -14142,6 +14401,7 @@ dependencies = [ "pallet-assets", "pallet-aura", "pallet-balances", + "pallet-message-queue", "pallet-sudo", "pallet-timestamp", "pallet-transaction-payment", @@ -14161,7 +14421,7 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", + "sp-std 8.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -14259,9 +14519,9 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std", - "sp-storage", - "sp-tracing", + "sp-std 8.0.0", + "sp-storage 13.0.0", + "sp-tracing 10.0.0", "sp-transaction-pool", "sp-trie", "sp-version", @@ -14288,6 +14548,30 @@ dependencies = [ "staging-xcm", ] +[[package]] +name = "rococo-system-emulated-network" +version = "0.0.0" +dependencies = [ + "asset-hub-rococo-emulated-chain", + "bridge-hub-rococo-emulated-chain", + "emulated-integration-tests-common", + "penpal-emulated-chain", + "rococo-emulated-chain", +] + +[[package]] +name = "rococo-wococo-system-emulated-network" +version = "0.0.0" +dependencies = [ + "asset-hub-rococo-emulated-chain", + "asset-hub-wococo-emulated-chain", + "bridge-hub-rococo-emulated-chain", + "bridge-hub-wococo-emulated-chain", + "emulated-integration-tests-common", + "rococo-emulated-chain", + "wococo-emulated-chain", +] + [[package]] name = "rpassword" version = "7.2.0" @@ -14592,7 +14876,7 @@ version = "4.1.0-dev" dependencies = [ "log", "sp-core", - "sp-wasm-interface", + "sp-wasm-interface 14.0.0", "thiserror", ] @@ -14620,7 +14904,7 @@ dependencies = [ "sp-core", "sp-keystore", "sp-runtime", - "sp-tracing", + "sp-tracing 10.0.0", "substrate-prometheus-endpoint", "substrate-test-runtime-client", "thiserror", @@ -14656,7 +14940,6 @@ name = "sc-block-builder" version = "0.10.0-dev" dependencies = [ "parity-scale-codec", - "sc-client-api", "sp-api", "sp-block-builder", "sp-blockchain", @@ -14671,7 +14954,11 @@ dependencies = [ name = "sc-chain-spec" version = "4.0.0-dev" dependencies = [ + "array-bytes 6.1.0", + "docify", + "log", "memmap2", + "parity-scale-codec", "sc-chain-spec-derive", "sc-client-api", "sc-executor", @@ -14679,10 +14966,16 @@ dependencies = [ "sc-telemetry", "serde", "serde_json", + "sp-application-crypto", "sp-blockchain", + "sp-consensus-babe", "sp-core", + "sp-genesis-builder", + "sp-io", + "sp-keyring", "sp-runtime", "sp-state-machine", + "substrate-test-runtime", ] [[package]] @@ -14731,7 +15024,7 @@ dependencies = [ "sp-keystore", "sp-panic-handler", "sp-runtime", - "sp-tracing", + "sp-tracing 10.0.0", "sp-version", "tempfile", "thiserror", @@ -14755,11 +15048,11 @@ dependencies = [ "sp-consensus", "sp-core", "sp-database", - "sp-externalities", + "sp-externalities 0.19.0", "sp-runtime", "sp-state-machine", "sp-statement-store", - "sp-storage", + "sp-storage 13.0.0", "sp-test-primitives", "sp-trie", "substrate-prometheus-endpoint", @@ -14794,7 +15087,7 @@ dependencies = [ "sp-database", "sp-runtime", "sp-state-machine", - "sp-tracing", + "sp-tracing 10.0.0", "sp-trie", "substrate-test-runtime-client", "tempfile", @@ -14855,7 +15148,7 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-timestamp", - "sp-tracing", + "sp-tracing 10.0.0", "substrate-prometheus-endpoint", "substrate-test-runtime-client", "tempfile", @@ -14897,7 +15190,7 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-timestamp", - "sp-tracing", + "sp-tracing 10.0.0", "substrate-prometheus-endpoint", "substrate-test-runtime-client", "thiserror", @@ -14965,7 +15258,7 @@ dependencies = [ "sp-keystore", "sp-mmr-primitives", "sp-runtime", - "sp-tracing", + "sp-tracing 10.0.0", "substrate-prometheus-endpoint", "substrate-test-runtime-client", "tempfile", @@ -15048,7 +15341,7 @@ dependencies = [ "sp-keyring", "sp-keystore", "sp-runtime", - "sp-tracing", + "sp-tracing 10.0.0", "substrate-prometheus-endpoint", "substrate-test-runtime-client", "thiserror", @@ -15184,17 +15477,17 @@ dependencies = [ "schnellru", "sp-api", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-io", "sp-maybe-compressed-blob", "sp-panic-handler", "sp-runtime", - "sp-runtime-interface", + "sp-runtime-interface 17.0.0", "sp-state-machine", - "sp-tracing", + "sp-tracing 10.0.0", "sp-trie", "sp-version", - "sp-wasm-interface", + "sp-wasm-interface 14.0.0", "substrate-test-runtime", "tempfile", "tracing", @@ -15208,7 +15501,7 @@ version = "0.10.0-dev" dependencies = [ "sc-allocator", "sp-maybe-compressed-blob", - "sp-wasm-interface", + "sp-wasm-interface 14.0.0", "thiserror", "wasm-instrument 0.3.0", ] @@ -15230,8 +15523,8 @@ dependencies = [ "sc-executor-common", "sc-runtime-test", "sp-io", - "sp-runtime-interface", - "sp-wasm-interface", + "sp-runtime-interface 17.0.0", + "sp-wasm-interface 14.0.0", "tempfile", "wasmtime", "wat", @@ -15332,7 +15625,7 @@ dependencies = [ "sp-core", "sp-runtime", "sp-test-primitives", - "sp-tracing", + "sp-tracing 10.0.0", "substrate-prometheus-endpoint", "substrate-test-runtime", "substrate-test-runtime-client", @@ -15480,7 +15773,7 @@ dependencies = [ "sp-core", "sp-runtime", "sp-test-primitives", - "sp-tracing", + "sp-tracing 10.0.0", "substrate-prometheus-endpoint", "substrate-test-runtime-client", "thiserror", @@ -15512,7 +15805,7 @@ dependencies = [ "sp-consensus", "sp-core", "sp-runtime", - "sp-tracing", + "sp-tracing 10.0.0", "substrate-test-runtime", "substrate-test-runtime-client", "tokio", @@ -15566,11 +15859,11 @@ dependencies = [ "sp-api", "sp-consensus", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-keystore", "sp-offchain", "sp-runtime", - "sp-tracing", + "sp-tracing 10.0.0", "substrate-test-runtime-client", "threadpool", "tokio", @@ -15701,8 +15994,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-runtime-interface", - "sp-std", + "sp-runtime-interface 17.0.0", + "sp-std 8.0.0", "substrate-wasm-builder", ] @@ -15721,7 +16014,6 @@ dependencies = [ "parking_lot 0.12.1", "pin-project", "rand 0.8.5", - "sc-block-builder", "sc-chain-spec", "sc-client-api", "sc-client-db", @@ -15750,12 +16042,12 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-keystore", "sp-runtime", "sp-session", "sp-state-machine", - "sp-storage", + "sp-storage 13.0.0", "sp-transaction-pool", "sp-transaction-storage-proof", "sp-trie", @@ -15798,8 +16090,8 @@ dependencies = [ "sp-io", "sp-runtime", "sp-state-machine", - "sp-storage", - "sp-tracing", + "sp-storage 13.0.0", + "sp-tracing 10.0.0", "sp-trie", "substrate-test-runtime", "substrate-test-runtime-client", @@ -15872,6 +16164,7 @@ dependencies = [ name = "sc-sysinfo" version = "6.0.0-dev" dependencies = [ + "derive_more", "futures", "libc", "log", @@ -15884,7 +16177,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -15927,7 +16220,7 @@ dependencies = [ "sp-core", "sp-rpc", "sp-runtime", - "sp-tracing", + "sp-tracing 10.0.0", "thiserror", "tracing", "tracing-log", @@ -15968,7 +16261,7 @@ dependencies = [ "sp-consensus", "sp-core", "sp-runtime", - "sp-tracing", + "sp-tracing 10.0.0", "sp-transaction-pool", "substrate-prometheus-endpoint", "substrate-test-runtime", @@ -16247,7 +16540,7 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", + "sp-std 8.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -16324,9 +16617,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.107" +version = "1.0.108" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b420ce6e3d8bd882e9b243c6eed35dbc9a6110c9769e74b584e0d68d1f20c65" +checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" dependencies = [ "itoa", "ryu", @@ -16482,6 +16775,7 @@ dependencies = [ "frame-system", "frame-try-runtime", "pallet-aura", + "pallet-message-queue", "pallet-timestamp", "parachains-common", "parity-scale-codec", @@ -16495,7 +16789,7 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std", + "sp-std 8.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -16597,7 +16891,7 @@ dependencies = [ "parity-scale-codec", "paste", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -16792,11 +17086,11 @@ dependencies = [ "scale-info", "sp-api-proc-macro", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-metadata-ir", "sp-runtime", "sp-state-machine", - "sp-std", + "sp-std 8.0.0", "sp-test-primitives", "sp-trie", "sp-version", @@ -16833,7 +17127,7 @@ dependencies = [ "sp-core", "sp-runtime", "sp-state-machine", - "sp-tracing", + "sp-tracing 10.0.0", "sp-version", "static_assertions", "substrate-test-runtime-client", @@ -16849,7 +17143,7 @@ dependencies = [ "serde", "sp-core", "sp-io", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -16876,7 +17170,7 @@ dependencies = [ "scale-info", "serde", "sp-core", - "sp-std", + "sp-std 8.0.0", "static_assertions", ] @@ -16891,6 +17185,24 @@ dependencies = [ "sp-arithmetic", ] +[[package]] +name = "sp-ark-bls12-381" +version = "0.4.2" +source = "git+https://github.com/paritytech/arkworks-substrate#caa2eed74beb885dd07c7db5f916f2281dad818f" +dependencies = [ + "ark-bls12-381-ext", + "sp-crypto-ec-utils 0.4.1 (git+https://github.com/paritytech/polkadot-sdk)", +] + +[[package]] +name = "sp-ark-ed-on-bls12-381-bandersnatch" +version = "0.4.2" +source = "git+https://github.com/paritytech/arkworks-substrate#caa2eed74beb885dd07c7db5f916f2281dad818f" +dependencies = [ + "ark-ed-on-bls12-381-bandersnatch-ext", + "sp-crypto-ec-utils 0.4.1 (git+https://github.com/paritytech/polkadot-sdk)", +] + [[package]] name = "sp-authority-discovery" version = "4.0.0-dev" @@ -16900,7 +17212,7 @@ dependencies = [ "sp-api", "sp-application-crypto", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -16910,7 +17222,7 @@ dependencies = [ "sp-api", "sp-inherents", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -16957,7 +17269,7 @@ dependencies = [ "sp-consensus-slots", "sp-inherents", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-timestamp", ] @@ -16975,7 +17287,7 @@ dependencies = [ "sp-core", "sp-inherents", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-timestamp", ] @@ -16994,7 +17306,7 @@ dependencies = [ "sp-io", "sp-mmr-primitives", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "strum", "w3f-bls", ] @@ -17013,7 +17325,7 @@ dependencies = [ "sp-core", "sp-keystore", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -17024,7 +17336,7 @@ dependencies = [ "sp-api", "sp-core", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -17039,7 +17351,7 @@ dependencies = [ "sp-consensus-slots", "sp-core", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -17049,7 +17361,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-std", + "sp-std 8.0.0", "sp-timestamp", ] @@ -17090,11 +17402,11 @@ dependencies = [ "serde_json", "sp-core-hashing", "sp-core-hashing-proc-macro", - "sp-debug-derive", - "sp-externalities", - "sp-runtime-interface", - "sp-std", - "sp-storage", + "sp-debug-derive 8.0.0", + "sp-externalities 0.19.0", + "sp-runtime-interface 17.0.0", + "sp-std 8.0.0", + "sp-storage 13.0.0", "ss58-registry", "substrate-bip39", "thiserror", @@ -17140,8 +17452,29 @@ dependencies = [ "ark-ed-on-bls12-381-bandersnatch", "ark-ed-on-bls12-381-bandersnatch-ext", "ark-scale", - "sp-runtime-interface", - "sp-std", + "sp-runtime-interface 17.0.0", + "sp-std 8.0.0", +] + +[[package]] +name = "sp-crypto-ec-utils" +version = "0.4.1" +source = "git+https://github.com/paritytech/polkadot-sdk#fe9435db2fda7c9e2f4e29521564c72cac38f59b" +dependencies = [ + "ark-bls12-377", + "ark-bls12-377-ext", + "ark-bls12-381", + "ark-bls12-381-ext", + "ark-bw6-761", + "ark-bw6-761-ext", + "ark-ec", + "ark-ed-on-bls12-377", + "ark-ed-on-bls12-377-ext", + "ark-ed-on-bls12-381-bandersnatch", + "ark-ed-on-bls12-381-bandersnatch-ext", + "ark-scale", + "sp-runtime-interface 17.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-std 8.0.0 (git+https://github.com/paritytech/polkadot-sdk)", ] [[package]] @@ -17161,14 +17494,35 @@ dependencies = [ "syn 2.0.38", ] +[[package]] +name = "sp-debug-derive" +version = "8.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#fe9435db2fda7c9e2f4e29521564c72cac38f59b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.38", +] + +[[package]] +name = "sp-externalities" +version = "0.19.0" +dependencies = [ + "environmental", + "parity-scale-codec", + "sp-std 8.0.0", + "sp-storage 13.0.0", +] + [[package]] name = "sp-externalities" version = "0.19.0" +source = "git+https://github.com/paritytech/polkadot-sdk#fe9435db2fda7c9e2f4e29521564c72cac38f59b" dependencies = [ "environmental", "parity-scale-codec", - "sp-std", - "sp-storage", + "sp-std 8.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-storage 13.0.0 (git+https://github.com/paritytech/polkadot-sdk)", ] [[package]] @@ -17178,7 +17532,7 @@ dependencies = [ "serde_json", "sp-api", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -17191,7 +17545,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "thiserror", ] @@ -17207,12 +17561,12 @@ dependencies = [ "rustversion", "secp256k1", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-keystore", - "sp-runtime-interface", + "sp-runtime-interface 17.0.0", "sp-state-machine", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "sp-trie", "tracing", "tracing-core", @@ -17237,7 +17591,7 @@ dependencies = [ "rand 0.7.3", "rand_chacha 0.2.2", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "thiserror", ] @@ -17256,7 +17610,7 @@ dependencies = [ "frame-metadata", "parity-scale-codec", "scale-info", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -17267,7 +17621,7 @@ dependencies = [ "scale-info", "sp-api", "sp-application-crypto", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -17282,9 +17636,9 @@ dependencies = [ "serde", "sp-api", "sp-core", - "sp-debug-derive", + "sp-debug-derive 8.0.0", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "thiserror", ] @@ -17299,7 +17653,7 @@ dependencies = [ "sp-arithmetic", "sp-core", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "substrate-test-utils", ] @@ -17362,8 +17716,8 @@ dependencies = [ "sp-core", "sp-io", "sp-state-machine", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "sp-weights", "substrate-test-runtime-client", "zstd 0.12.4", @@ -17379,22 +17733,52 @@ dependencies = [ "primitive-types", "rustversion", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-io", - "sp-runtime-interface-proc-macro", + "sp-runtime-interface-proc-macro 11.0.0", "sp-runtime-interface-test-wasm", "sp-state-machine", - "sp-std", - "sp-storage", - "sp-tracing", - "sp-wasm-interface", + "sp-std 8.0.0", + "sp-storage 13.0.0", + "sp-tracing 10.0.0", + "sp-wasm-interface 14.0.0", "static_assertions", "trybuild", ] +[[package]] +name = "sp-runtime-interface" +version = "17.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#fe9435db2fda7c9e2f4e29521564c72cac38f59b" +dependencies = [ + "bytes", + "impl-trait-for-tuples", + "parity-scale-codec", + "primitive-types", + "sp-externalities 0.19.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-runtime-interface-proc-macro 11.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-std 8.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-storage 13.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-tracing 10.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-wasm-interface 14.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "static_assertions", +] + +[[package]] +name = "sp-runtime-interface-proc-macro" +version = "11.0.0" +dependencies = [ + "Inflector", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.38", +] + [[package]] name = "sp-runtime-interface-proc-macro" version = "11.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#fe9435db2fda7c9e2f4e29521564c72cac38f59b" dependencies = [ "Inflector", "proc-macro-crate", @@ -17411,7 +17795,7 @@ dependencies = [ "sc-executor-common", "sp-io", "sp-runtime", - "sp-runtime-interface", + "sp-runtime-interface 17.0.0", "sp-runtime-interface-test-wasm", "sp-runtime-interface-test-wasm-deprecated", "sp-state-machine", @@ -17426,8 +17810,8 @@ dependencies = [ "bytes", "sp-core", "sp-io", - "sp-runtime-interface", - "sp-std", + "sp-runtime-interface 17.0.0", + "sp-std 8.0.0", "substrate-wasm-builder", ] @@ -17437,7 +17821,7 @@ version = "2.0.0" dependencies = [ "sp-core", "sp-io", - "sp-runtime-interface", + "sp-runtime-interface 17.0.0", "substrate-wasm-builder", ] @@ -17452,7 +17836,7 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-staking", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -17465,7 +17849,7 @@ dependencies = [ "serde", "sp-core", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -17482,10 +17866,10 @@ dependencies = [ "rand 0.8.5", "smallvec", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-panic-handler", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-trie", "thiserror", "tracing", @@ -17507,10 +17891,10 @@ dependencies = [ "sp-api", "sp-application-crypto", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-runtime", - "sp-runtime-interface", - "sp-std", + "sp-runtime-interface 17.0.0", + "sp-std 8.0.0", "thiserror", "x25519-dalek 2.0.0", ] @@ -17519,16 +17903,34 @@ dependencies = [ name = "sp-std" version = "8.0.0" +[[package]] +name = "sp-std" +version = "8.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#fe9435db2fda7c9e2f4e29521564c72cac38f59b" + +[[package]] +name = "sp-storage" +version = "13.0.0" +dependencies = [ + "impl-serde", + "parity-scale-codec", + "ref-cast", + "serde", + "sp-debug-derive 8.0.0", + "sp-std 8.0.0", +] + [[package]] name = "sp-storage" version = "13.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#fe9435db2fda7c9e2f4e29521564c72cac38f59b" dependencies = [ "impl-serde", "parity-scale-codec", "ref-cast", "serde", - "sp-debug-derive", - "sp-std", + "sp-debug-derive 8.0.0 (git+https://github.com/paritytech/polkadot-sdk)", + "sp-std 8.0.0 (git+https://github.com/paritytech/polkadot-sdk)", ] [[package]] @@ -17541,7 +17943,7 @@ dependencies = [ "sp-application-crypto", "sp-core", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] [[package]] @@ -17552,7 +17954,7 @@ dependencies = [ "parity-scale-codec", "sp-inherents", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "thiserror", ] @@ -17561,7 +17963,19 @@ name = "sp-tracing" version = "10.0.0" dependencies = [ "parity-scale-codec", - "sp-std", + "sp-std 8.0.0", + "tracing", + "tracing-core", + "tracing-subscriber", +] + +[[package]] +name = "sp-tracing" +version = "10.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#fe9435db2fda7c9e2f4e29521564c72cac38f59b" +dependencies = [ + "parity-scale-codec", + "sp-std 8.0.0 (git+https://github.com/paritytech/polkadot-sdk)", "tracing", "tracing-core", "tracing-subscriber", @@ -17585,7 +17999,7 @@ dependencies = [ "sp-core", "sp-inherents", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-trie", ] @@ -17608,7 +18022,7 @@ dependencies = [ "schnellru", "sp-core", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "thiserror", "tracing", "trie-bench", @@ -17628,7 +18042,7 @@ dependencies = [ "serde", "sp-core-hashing-proc-macro", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-version-proc-macro", "thiserror", ] @@ -17652,7 +18066,20 @@ dependencies = [ "impl-trait-for-tuples", "log", "parity-scale-codec", - "sp-std", + "sp-std 8.0.0", + "wasmtime", +] + +[[package]] +name = "sp-wasm-interface" +version = "14.0.0" +source = "git+https://github.com/paritytech/polkadot-sdk#fe9435db2fda7c9e2f4e29521564c72cac38f59b" +dependencies = [ + "anyhow", + "impl-trait-for-tuples", + "log", + "parity-scale-codec", + "sp-std 8.0.0 (git+https://github.com/paritytech/polkadot-sdk)", "wasmtime", ] @@ -17666,8 +18093,8 @@ dependencies = [ "smallvec", "sp-arithmetic", "sp-core", - "sp-debug-derive", - "sp-std", + "sp-debug-derive 8.0.0", + "sp-std 8.0.0", ] [[package]] @@ -17740,11 +18167,15 @@ version = "2.0.0" dependencies = [ "ansi_term", "clap 4.4.6", + "kitchensink-runtime", + "log", "rand 0.8.5", "sc-chain-spec", "sc-keystore", + "serde_json", "sp-core", "sp-keystore", + "sp-tracing 10.0.0", "staging-node-cli", ] @@ -17825,7 +18256,7 @@ dependencies = [ "sp-runtime", "sp-statement-store", "sp-timestamp", - "sp-tracing", + "sp-tracing 10.0.0", "sp-transaction-storage-proof", "staging-node-executor", "staging-node-inspect", @@ -17864,16 +18295,17 @@ dependencies = [ "parity-scale-codec", "sc-executor", "scale-info", + "serde_json", "sp-application-crypto", "sp-consensus-babe", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-keyring", "sp-keystore", "sp-runtime", "sp-state-machine", "sp-statement-store", - "sp-tracing", + "sp-tracing 10.0.0", "sp-trie", "wat", ] @@ -17903,9 +18335,13 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std", + "sp-std 8.0.0", ] +[[package]] +name = "staging-tracking-allocator" +version = "1.0.0" + [[package]] name = "staging-xcm" version = "1.0.0" @@ -17949,7 +18385,7 @@ dependencies = [ "sp-arithmetic", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-weights", "staging-xcm", "staging-xcm-executor", @@ -17969,7 +18405,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "sp-weights", "staging-xcm", ] @@ -18093,6 +18529,7 @@ name = "substrate" version = "1.0.0" dependencies = [ "frame-support", + "sc-chain-spec", "sc-cli", "sc-consensus-aura", "sc-consensus-babe", @@ -18166,7 +18603,7 @@ dependencies = [ "serde", "sp-core", "sp-runtime", - "sp-storage", + "sp-storage 13.0.0", "tokio", ] @@ -18188,7 +18625,7 @@ dependencies = [ "sp-blockchain", "sp-core", "sp-runtime", - "sp-tracing", + "sp-tracing 10.0.0", "substrate-test-runtime-client", "tokio", ] @@ -18291,7 +18728,7 @@ dependencies = [ "sp-consensus-babe", "sp-consensus-grandpa", "sp-core", - "sp-externalities", + "sp-externalities 0.19.0", "sp-genesis-builder", "sp-inherents", "sp-io", @@ -18300,8 +18737,8 @@ dependencies = [ "sp-runtime", "sp-session", "sp-state-machine", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "sp-transaction-pool", "sp-trie", "sp-version", @@ -18611,7 +19048,7 @@ dependencies = [ "parity-scale-codec", "polkadot-parachain-primitives", "sp-io", - "sp-std", + "sp-std 8.0.0", "substrate-wasm-builder", "tiny-keccak", ] @@ -18659,7 +19096,7 @@ dependencies = [ "parity-scale-codec", "polkadot-parachain-primitives", "sp-io", - "sp-std", + "sp-std 8.0.0", "substrate-wasm-builder", "tiny-keccak", ] @@ -19321,8 +19758,8 @@ dependencies = [ "sp-consensus-aura", "sp-consensus-babe", "sp-core", - "sp-debug-derive", - "sp-externalities", + "sp-debug-derive 8.0.0", + "sp-externalities 0.19.0", "sp-inherents", "sp-io", "sp-keystore", @@ -20362,6 +20799,26 @@ dependencies = [ "winapi", ] +[[package]] +name = "westend-emulated-chain" +version = "0.0.0" +dependencies = [ + "emulated-integration-tests-common", + "pallet-im-online", + "pallet-staking", + "parachains-common", + "polkadot-primitives", + "sc-consensus-grandpa", + "serde_json", + "sp-authority-discovery", + "sp-consensus-babe", + "sp-consensus-beefy", + "sp-core", + "sp-runtime", + "westend-runtime", + "westend-runtime-constants", +] + [[package]] name = "westend-runtime" version = "1.0.0" @@ -20459,9 +20916,9 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std", - "sp-storage", - "sp-tracing", + "sp-std 8.0.0", + "sp-storage 13.0.0", + "sp-tracing 10.0.0", "sp-transaction-pool", "sp-version", "staging-xcm", @@ -20487,6 +20944,17 @@ dependencies = [ "staging-xcm", ] +[[package]] +name = "westend-system-emulated-network" +version = "0.0.0" +dependencies = [ + "asset-hub-westend-emulated-chain", + "bridge-hub-westend-emulated-chain", + "emulated-integration-tests-common", + "penpal-emulated-chain", + "westend-emulated-chain", +] + [[package]] name = "which" version = "4.4.0" @@ -20748,6 +21216,37 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "wococo-emulated-chain" +version = "0.0.0" +dependencies = [ + "emulated-integration-tests-common", + "pallet-im-online", + "parachains-common", + "polkadot-primitives", + "rococo-emulated-chain", + "rococo-runtime", + "rococo-runtime-constants", + "sc-consensus-grandpa", + "serde_json", + "sp-authority-discovery", + "sp-consensus-babe", + "sp-consensus-beefy", + "sp-core", + "sp-runtime", +] + +[[package]] +name = "wococo-system-emulated-network" +version = "0.0.0" +dependencies = [ + "asset-hub-wococo-emulated-chain", + "bridge-hub-wococo-emulated-chain", + "emulated-integration-tests-common", + "penpal-emulated-chain", + "wococo-emulated-chain", +] + [[package]] name = "wyz" version = "0.5.1" @@ -20831,6 +21330,7 @@ name = "xcm-emulator" version = "0.1.0" dependencies = [ "cumulus-pallet-parachain-system", + "cumulus-pallet-xcmp-queue", "cumulus-primitives-core", "cumulus-primitives-parachain-inherent", "cumulus-test-relay-sproof-builder", @@ -20851,8 +21351,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "staging-xcm", "staging-xcm-executor", ] @@ -20873,7 +21373,7 @@ dependencies = [ "sp-keyring", "sp-runtime", "sp-state-machine", - "sp-tracing", + "sp-tracing 10.0.0", "staging-xcm", "staging-xcm-executor", ] @@ -20886,6 +21386,7 @@ dependencies = [ "proc-macro2", "quote", "syn 2.0.38", + "trybuild", ] [[package]] @@ -20899,7 +21400,7 @@ dependencies = [ "polkadot-parachain-primitives", "polkadot-runtime-parachains", "sp-io", - "sp-std", + "sp-std 8.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -20924,8 +21425,8 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", - "sp-tracing", + "sp-std 8.0.0", + "sp-tracing 10.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -20951,7 +21452,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std", + "sp-std 8.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs index e574e08bec35..1c99393d5e52 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs @@ -24,7 +24,6 @@ use frame_support::{ use pallet_contracts::{ migration::{v12, v13, v14, v15}, weights::SubstrateWeight, - xcm::XcmAdapter, Config, DebugInfo, DefaultAddressGenerator, Frame, Schedule, }; use sp_runtime::Perbill; @@ -80,5 +79,4 @@ impl Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type Debug = (); type Environment = (); - type Xcm = XcmAdapter; } diff --git a/polkadot/runtime/rococo/src/weights/pallet_xcm.rs b/polkadot/runtime/rococo/src/weights/pallet_xcm.rs index 5b001c5816c7..aafded3f7319 100644 --- a/polkadot/runtime/rococo/src/weights/pallet_xcm.rs +++ b/polkadot/runtime/rococo/src/weights/pallet_xcm.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-10-24, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-11-07, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-t2sp1qqs-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("rococo-dev")`, DB CACHE: 1024 // Executed Command: @@ -60,8 +60,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 28_378_000 picoseconds. - Weight::from_parts(29_137_000, 0) + // Minimum execution time: 27_328_000 picoseconds. + Weight::from_parts(27_976_000, 0) .saturating_add(Weight::from_parts(0, 3607)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -70,24 +70,24 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 17_649_000 picoseconds. - Weight::from_parts(17_869_000, 0) + // Minimum execution time: 16_280_000 picoseconds. + Weight::from_parts(16_904_000, 0) .saturating_add(Weight::from_parts(0, 0)) } fn reserve_transfer_assets() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 17_293_000 picoseconds. - Weight::from_parts(17_443_000, 0) + // Minimum execution time: 15_869_000 picoseconds. + Weight::from_parts(16_264_000, 0) .saturating_add(Weight::from_parts(0, 0)) } fn execute() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_728_000 picoseconds. - Weight::from_parts(8_180_000, 0) + // Minimum execution time: 6_923_000 picoseconds. + Weight::from_parts(7_432_000, 0) .saturating_add(Weight::from_parts(0, 0)) } /// Storage: `XcmPallet::SupportedVersion` (r:0 w:1) @@ -96,8 +96,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_630_000 picoseconds. - Weight::from_parts(7_941_000, 0) + // Minimum execution time: 7_333_000 picoseconds. + Weight::from_parts(7_566_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -105,8 +105,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_259_000 picoseconds. - Weight::from_parts(2_406_000, 0) + // Minimum execution time: 2_219_000 picoseconds. + Weight::from_parts(2_375_000, 0) .saturating_add(Weight::from_parts(0, 0)) } /// Storage: `XcmPallet::VersionNotifiers` (r:1 w:1) @@ -127,8 +127,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 32_168_000 picoseconds. - Weight::from_parts(33_116_000, 0) + // Minimum execution time: 30_650_000 picoseconds. + Weight::from_parts(31_683_000, 0) .saturating_add(Weight::from_parts(0, 3607)) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(5)) @@ -149,8 +149,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `322` // Estimated: `3787` - // Minimum execution time: 37_943_000 picoseconds. - Weight::from_parts(39_073_000, 0) + // Minimum execution time: 37_666_000 picoseconds. + Weight::from_parts(38_920_000, 0) .saturating_add(Weight::from_parts(0, 3787)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) @@ -161,8 +161,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_298_000 picoseconds. - Weight::from_parts(2_429_000, 0) + // Minimum execution time: 2_244_000 picoseconds. + Weight::from_parts(2_425_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -172,8 +172,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `26` // Estimated: `10916` - // Minimum execution time: 14_725_000 picoseconds. - Weight::from_parts(15_254_000, 0) + // Minimum execution time: 14_710_000 picoseconds. + Weight::from_parts(15_156_000, 0) .saturating_add(Weight::from_parts(0, 10916)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -184,8 +184,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `30` // Estimated: `10920` - // Minimum execution time: 14_979_000 picoseconds. - Weight::from_parts(15_633_000, 0) + // Minimum execution time: 14_630_000 picoseconds. + Weight::from_parts(15_290_000, 0) .saturating_add(Weight::from_parts(0, 10920)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -196,8 +196,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `40` // Estimated: `13405` - // Minimum execution time: 16_822_000 picoseconds. - Weight::from_parts(17_330_000, 0) + // Minimum execution time: 16_686_000 picoseconds. + Weight::from_parts(17_332_000, 0) .saturating_add(Weight::from_parts(0, 13405)) .saturating_add(T::DbWeight::get().reads(5)) } @@ -215,8 +215,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `178` // Estimated: `6118` - // Minimum execution time: 30_893_000 picoseconds. - Weight::from_parts(31_564_000, 0) + // Minimum execution time: 30_180_000 picoseconds. + Weight::from_parts(31_351_000, 0) .saturating_add(Weight::from_parts(0, 6118)) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(3)) @@ -227,8 +227,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `69` // Estimated: `8484` - // Minimum execution time: 9_609_000 picoseconds. - Weight::from_parts(10_052_000, 0) + // Minimum execution time: 9_624_000 picoseconds. + Weight::from_parts(10_029_000, 0) .saturating_add(Weight::from_parts(0, 8484)) .saturating_add(T::DbWeight::get().reads(3)) } @@ -238,8 +238,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `37` // Estimated: `10927` - // Minimum execution time: 15_131_000 picoseconds. - Weight::from_parts(15_812_000, 0) + // Minimum execution time: 15_139_000 picoseconds. + Weight::from_parts(15_575_000, 0) .saturating_add(Weight::from_parts(0, 10927)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -258,8 +258,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `182` // Estimated: `11072` - // Minimum execution time: 37_980_000 picoseconds. - Weight::from_parts(39_233_000, 0) + // Minimum execution time: 37_871_000 picoseconds. + Weight::from_parts(38_940_000, 0) .saturating_add(Weight::from_parts(0, 11072)) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(4)) @@ -272,8 +272,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `1485` - // Minimum execution time: 2_739_000 picoseconds. - Weight::from_parts(2_846_000, 0) + // Minimum execution time: 2_732_000 picoseconds. + Weight::from_parts(2_892_000, 0) .saturating_add(Weight::from_parts(0, 1485)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(2)) @@ -284,8 +284,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `7576` // Estimated: `11041` - // Minimum execution time: 24_109_000 picoseconds. - Weight::from_parts(24_456_000, 0) + // Minimum execution time: 23_813_000 picoseconds. + Weight::from_parts(24_201_000, 0) .saturating_add(Weight::from_parts(0, 11041)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) diff --git a/polkadot/xcm/pallet-xcm/src/controller.rs b/polkadot/xcm/pallet-xcm/src/controller.rs deleted file mode 100644 index 61ce6702999d..000000000000 --- a/polkadot/xcm/pallet-xcm/src/controller.rs +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Polkadot is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Polkadot. If not, see . - -//! A set of traits that define how a pallet interface with XCM. -//! Controller traits defined in this module are high-level traits that will rely on other traits -//! from `xcm-executor` to perform their tasks. - -use frame_support::pallet_prelude::DispatchError; -use sp_std::boxed::Box; -use xcm::prelude::*; -use xcm_executor::traits::QueryHandler; - -pub trait Controller: - ExecuteController + SendController + QueryController -{ -} - -impl Controller for T where - T: ExecuteController - + SendController - + QueryController -{ -} - -/// Weight functions needed for [`ExecuteController`]. -pub trait ExecuteControllerWeightInfo { - /// Weight for [`ExecuteController::execute`] - fn execute() -> Weight; -} - -/// Execute an XCM locally, for a given origin. -/// -/// An implementation of that trait will handle the low-level details of the execution, such as: -/// - Validating and Converting the origin to a MultiLocation. -/// - Handling versioning. -/// - Calling the internal executor, which implements [`ExecuteXcm`]. -pub trait ExecuteController { - /// Weight information for ExecuteController functions. - type WeightInfo: ExecuteControllerWeightInfo; - - /// Attempt to execute an XCM locally, and return the outcome. - /// - /// # Parameters - /// - /// - `origin`: the origin of the call. - /// - `message`: the XCM program to be executed. - /// - `max_weight`: the maximum weight that can be consumed by the execution. - fn execute( - origin: Origin, - message: Box>, - max_weight: Weight, - ) -> Result; -} - -/// Weight functions needed for [`SendController`]. -pub trait SendControllerWeightInfo { - /// Weight for [`SendController::send`] - fn send() -> Weight; -} - -/// Send an XCM from a given origin. -/// -/// An implementation of that trait will handle the low-level details of dispatching an XCM, such -/// as: -/// - Validating and Converting the origin to an interior location. -/// - Handling versioning. -/// - Calling the internal router, which implements [`SendXcm`]. -pub trait SendController { - /// Weight information for SendController functions. - type WeightInfo: SendControllerWeightInfo; - - /// Send an XCM to be executed by a remote location. - /// - /// # Parameters - /// - /// - `origin`: the origin of the call. - /// - `dest`: the destination of the message. - /// - `msg`: the XCM to be sent. - fn send( - origin: Origin, - dest: Box, - message: Box>, - ) -> Result; -} - -/// Weight functions needed for [`QueryController`]. -pub trait QueryControllerWeightInfo { - /// Weight for [`QueryController::query`] - fn query() -> Weight; - - /// Weight for [`QueryHandler::take_response`] - fn take_response() -> Weight; -} - -/// Query a remote location, from a given origin. -/// -/// An implementation of that trait will handle the low-level details of querying a remote location, -/// such as: -/// - Validating and Converting the origin to an interior location. -/// - Handling versioning. -/// - Calling the [`QueryHandler`] to register the query. -pub trait QueryController: QueryHandler { - /// Weight information for QueryController functions. - type WeightInfo: QueryControllerWeightInfo; - - /// Query a remote location. - /// - /// # Parameters - /// - /// - `origin`: the origin of the call, used to determine the responder. - /// - `timeout`: the maximum block number that the query should be responded to. - /// - `match_querier`: the querier that the query should be responded to. - fn query( - origin: Origin, - timeout: Timeout, - match_querier: VersionedMultiLocation, - ) -> Result; -} - -impl ExecuteController for () { - type WeightInfo = (); - fn execute( - _origin: Origin, - _message: Box>, - _max_weight: Weight, - ) -> Result { - Ok(Outcome::Error(XcmError::Unimplemented)) - } -} - -impl ExecuteControllerWeightInfo for () { - fn execute() -> Weight { - Weight::zero() - } -} - -impl SendController for () { - type WeightInfo = (); - fn send( - _origin: Origin, - _dest: Box, - _message: Box>, - ) -> Result { - Ok(Default::default()) - } -} - -impl SendControllerWeightInfo for () { - fn send() -> Weight { - Weight::zero() - } -} - -impl QueryControllerWeightInfo for () { - fn query() -> Weight { - Weight::zero() - } - fn take_response() -> Weight { - Weight::zero() - } -} - -impl QueryController for () { - type WeightInfo = (); - - fn query( - _origin: Origin, - _timeout: Timeout, - _match_querier: VersionedMultiLocation, - ) -> Result { - Ok(Default::default()) - } -} diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 8dc668859e27..2d969fb870c9 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -25,11 +25,9 @@ mod mock; #[cfg(test)] mod tests; -pub mod controller; pub mod migration; use codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; -pub use controller::*; use frame_support::{ dispatch::GetDispatchInfo, pallet_prelude::*, @@ -51,6 +49,10 @@ use sp_runtime::{ }; use sp_std::{boxed::Box, marker::PhantomData, prelude::*, result::Result, vec}; use xcm::{latest::QueryResponseInfo, prelude::*}; +use xcm_builder::{ + ExecuteController, ExecuteControllerWeightInfo, QueryController, QueryControllerWeightInfo, + SendController, SendControllerWeightInfo, +}; use xcm_executor::{ traits::{ CheckSuspension, ClaimAssets, ConvertLocation, ConvertOrigin, DropAssets, MatchesFungible, @@ -77,13 +79,8 @@ pub trait WeightInfo { fn notify_target_migration_fail() -> Weight; fn migrate_version_notify_targets() -> Weight; fn migrate_and_notify_old_targets() -> Weight; - // TODO remove after benchmark are regenerated - fn new_query() -> Weight { - Weight::zero() - } - fn take_response() -> Weight { - Weight::zero() - } + fn new_query() -> Weight; + fn take_response() -> Weight; } /// fallback implementation diff --git a/polkadot/xcm/xcm-executor/src/traits/on_response.rs b/polkadot/xcm/xcm-executor/src/traits/on_response.rs index a316209e6c07..ea41f242a97d 100644 --- a/polkadot/xcm/xcm-executor/src/traits/on_response.rs +++ b/polkadot/xcm/xcm-executor/src/traits/on_response.rs @@ -14,14 +14,15 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use crate::Xcm; -use crate::Junctions::Here; +use crate::{Junctions::Here, Xcm}; use core::result; -use frame_support::pallet_prelude::{Get, TypeInfo}; +use frame_support::{ + pallet_prelude::{Get, TypeInfo}, + parameter_types, +}; use parity_scale_codec::{Decode, Encode, FullCodec, MaxEncodedLen}; use sp_arithmetic::traits::Zero; use sp_std::fmt::Debug; -use frame_support::parameter_types; use xcm::latest::{ Error as XcmError, InteriorMultiLocation, MultiLocation, QueryId, Response, Result as XcmResult, Weight, XcmContext, @@ -200,4 +201,3 @@ impl QueryHandler for () { #[cfg(feature = "runtime-benchmarks")] fn expect_response(_id: Self::QueryId, _response: crate::Response) {} } - From 3526658a500f68e000a8c71ce5cb5156dbad1be0 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 10 Nov 2023 16:53:46 +0100 Subject: [PATCH 095/115] move fixtures files --- substrate/frame/contracts/fixtures/{ => data}/xcm_execute.wat | 0 substrate/frame/contracts/fixtures/{ => data}/xcm_query.wat | 0 substrate/frame/contracts/fixtures/{ => data}/xcm_send.wat | 0 .../frame/contracts/fixtures/{ => data}/xcm_take_response.wat | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename substrate/frame/contracts/fixtures/{ => data}/xcm_execute.wat (100%) rename substrate/frame/contracts/fixtures/{ => data}/xcm_query.wat (100%) rename substrate/frame/contracts/fixtures/{ => data}/xcm_send.wat (100%) rename substrate/frame/contracts/fixtures/{ => data}/xcm_take_response.wat (100%) diff --git a/substrate/frame/contracts/fixtures/xcm_execute.wat b/substrate/frame/contracts/fixtures/data/xcm_execute.wat similarity index 100% rename from substrate/frame/contracts/fixtures/xcm_execute.wat rename to substrate/frame/contracts/fixtures/data/xcm_execute.wat diff --git a/substrate/frame/contracts/fixtures/xcm_query.wat b/substrate/frame/contracts/fixtures/data/xcm_query.wat similarity index 100% rename from substrate/frame/contracts/fixtures/xcm_query.wat rename to substrate/frame/contracts/fixtures/data/xcm_query.wat diff --git a/substrate/frame/contracts/fixtures/xcm_send.wat b/substrate/frame/contracts/fixtures/data/xcm_send.wat similarity index 100% rename from substrate/frame/contracts/fixtures/xcm_send.wat rename to substrate/frame/contracts/fixtures/data/xcm_send.wat diff --git a/substrate/frame/contracts/fixtures/xcm_take_response.wat b/substrate/frame/contracts/fixtures/data/xcm_take_response.wat similarity index 100% rename from substrate/frame/contracts/fixtures/xcm_take_response.wat rename to substrate/frame/contracts/fixtures/data/xcm_take_response.wat From 784f8df5a4706417558cf6329889eea677c7bfa8 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 10 Nov 2023 16:55:13 +0100 Subject: [PATCH 096/115] rm pallet-xcm dep --- substrate/frame/contracts/Cargo.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 6ee2ecc67ce4..83e0f845a6d0 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -50,7 +50,6 @@ sp-std = { path = "../../primitives/std", default-features = false} xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false} xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor", default-features = false} -pallet-xcm = { path = "../../../polkadot/xcm/pallet-xcm", default-features = false} [dev-dependencies] array-bytes = "6.1" From 0b5517a270676316d34f9b6f28a9fb3d9d899ed4 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 10 Nov 2023 17:10:38 +0100 Subject: [PATCH 097/115] fix xcm deps --- Cargo.lock | 45 +++++++++++++++++++ polkadot/xcm/xcm-builder/src/controller.rs | 2 +- polkadot/xcm/xcm-builder/src/lib.rs | 2 +- substrate/frame/contracts/Cargo.toml | 8 +--- substrate/frame/contracts/fixtures/src/lib.rs | 1 + .../frame/contracts/mock-network/Cargo.toml | 1 + .../frame/contracts/mock-network/src/tests.rs | 2 +- substrate/frame/contracts/src/lib.rs | 2 +- substrate/frame/contracts/src/wasm/runtime.rs | 9 ++-- 9 files changed, 57 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2a091ce6817d..645f744d8905 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9700,15 +9700,20 @@ dependencies = [ "frame-system", "impl-trait-for-tuples", "log", + "pallet-assets", "pallet-balances", "pallet-contracts-fixtures", "pallet-contracts-primitives", "pallet-contracts-proc-macro", "pallet-insecure-randomness-collective-flip", + "pallet-message-queue", "pallet-proxy", "pallet-timestamp", "pallet-utility", "parity-scale-codec", + "polkadot-parachain-primitives", + "polkadot-primitives", + "polkadot-runtime-parachains", "pretty_assertions", "rand 0.8.5", "rand_pcg", @@ -9721,9 +9726,13 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-std 8.0.0", + "sp-tracing 10.0.0", + "staging-xcm", + "staging-xcm-builder", "wasm-instrument 0.4.0", "wasmi", "wat", + "xcm-simulator", ] [[package]] @@ -9735,6 +9744,42 @@ dependencies = [ "wat", ] +[[package]] +name = "pallet-contracts-mock-network" +version = "1.0.0" +dependencies = [ + "frame-support", + "frame-system", + "pallet-assets", + "pallet-balances", + "pallet-contracts", + "pallet-contracts-fixtures", + "pallet-contracts-primitives", + "pallet-contracts-proc-macro", + "pallet-insecure-randomness-collective-flip", + "pallet-message-queue", + "pallet-proxy", + "pallet-timestamp", + "pallet-utility", + "pallet-xcm", + "parity-scale-codec", + "polkadot-parachain-primitives", + "polkadot-primitives", + "polkadot-runtime-parachains", + "scale-info", + "sp-api", + "sp-core", + "sp-io", + "sp-keystore", + "sp-runtime", + "sp-std 8.0.0", + "sp-tracing 10.0.0", + "staging-xcm", + "staging-xcm-builder", + "staging-xcm-executor", + "xcm-simulator", +] + [[package]] name = "pallet-contracts-primitives" version = "24.0.0" diff --git a/polkadot/xcm/xcm-builder/src/controller.rs b/polkadot/xcm/xcm-builder/src/controller.rs index 0ee638b73e1c..931d812eaaf1 100644 --- a/polkadot/xcm/xcm-builder/src/controller.rs +++ b/polkadot/xcm/xcm-builder/src/controller.rs @@ -21,7 +21,7 @@ use frame_support::pallet_prelude::DispatchError; use sp_std::boxed::Box; use xcm::prelude::*; -use xcm_executor::traits::QueryHandler; +pub use xcm_executor::traits::QueryHandler; /// Umbrella trait for all Controller traits. pub trait Controller: diff --git a/polkadot/xcm/xcm-builder/src/lib.rs b/polkadot/xcm/xcm-builder/src/lib.rs index 35f95b85c89c..b34bdb24d8af 100644 --- a/polkadot/xcm/xcm-builder/src/lib.rs +++ b/polkadot/xcm/xcm-builder/src/lib.rs @@ -118,6 +118,6 @@ pub use pay::{FixedLocation, LocatableAssetId, PayAccountId32OnChainOverXcm, Pay mod controller; pub use controller::{ - Controller, ExecuteController, ExecuteControllerWeightInfo, QueryController, + Controller, ExecuteController, ExecuteControllerWeightInfo, QueryController, QueryHandler, QueryControllerWeightInfo, SendController, SendControllerWeightInfo, }; diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 83e0f845a6d0..180f55e3efd4 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -49,7 +49,7 @@ sp-runtime = { path = "../../primitives/runtime", default-features = false} sp-std = { path = "../../primitives/std", default-features = false} xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false} -xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor", default-features = false} +xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder", default-features = false} [dev-dependencies] array-bytes = "6.1" @@ -94,7 +94,6 @@ std = [ "pallet-proxy/std", "pallet-timestamp/std", "pallet-utility/std", - "pallet-xcm/std", "rand/std", "scale-info/std", "serde", @@ -106,7 +105,7 @@ std = [ "sp-std/std", "wasm-instrument/std", "wasmi/std", - "xcm-executor/std", + "xcm-builder/std", "xcm/std", ] runtime-benchmarks = [ @@ -119,7 +118,6 @@ runtime-benchmarks = [ "pallet-proxy/runtime-benchmarks", "pallet-timestamp/runtime-benchmarks", "pallet-utility/runtime-benchmarks", - "pallet-xcm/runtime-benchmarks", "polkadot-parachain-primitives/runtime-benchmarks", "polkadot-primitives/runtime-benchmarks", "polkadot-runtime-parachains/runtime-benchmarks", @@ -128,7 +126,6 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "wasm-instrument", "xcm-builder/runtime-benchmarks", - "xcm-executor/runtime-benchmarks", ] try-runtime = [ "frame-support/try-runtime", @@ -140,7 +137,6 @@ try-runtime = [ "pallet-proxy/try-runtime", "pallet-timestamp/try-runtime", "pallet-utility/try-runtime", - "pallet-xcm/try-runtime", "polkadot-runtime-parachains/try-runtime", "sp-runtime/try-runtime", ] diff --git a/substrate/frame/contracts/fixtures/src/lib.rs b/substrate/frame/contracts/fixtures/src/lib.rs index 32f4023e6446..5d662c9937d4 100644 --- a/substrate/frame/contracts/fixtures/src/lib.rs +++ b/substrate/frame/contracts/fixtures/src/lib.rs @@ -23,6 +23,7 @@ fn fixtures_root_dir() -> PathBuf { // When `CARGO_MANIFEST_DIR` is not set, Rust resolves relative paths from the root folder (Err(_), _) => "substrate/frame/contracts/fixtures/data".into(), (Ok(path), Ok(s)) if s == "pallet-contracts" => PathBuf::from(path).join("fixtures/data"), + (Ok(path), Ok(s)) if s == "pallet-contracts-mock-network" => PathBuf::from(path).parent().unwrap().join("fixtures/data"), (Ok(_), pkg_name) => panic!("Failed to resolve fixture dir for tests from {pkg_name:?}."), } } diff --git a/substrate/frame/contracts/mock-network/Cargo.toml b/substrate/frame/contracts/mock-network/Cargo.toml index 74d26031b114..7781134f2842 100644 --- a/substrate/frame/contracts/mock-network/Cargo.toml +++ b/substrate/frame/contracts/mock-network/Cargo.toml @@ -16,6 +16,7 @@ frame-system = { path = "../../system", default-features = false} pallet-assets = { path = "../../assets" } pallet-balances = { path = "../../balances" } pallet-contracts = { path = ".." } +pallet-contracts-fixtures = { path = "../fixtures" } pallet-contracts-primitives = { path = "../primitives", default-features = false} pallet-contracts-proc-macro = { path = "../proc-macro" } pallet-insecure-randomness-collective-flip = { path = "../../insecure-randomness-collective-flip" } diff --git a/substrate/frame/contracts/mock-network/src/tests.rs b/substrate/frame/contracts/mock-network/src/tests.rs index b8f8ccfde6e9..aae89cbc62c6 100644 --- a/substrate/frame/contracts/mock-network/src/tests.rs +++ b/substrate/frame/contracts/mock-network/src/tests.rs @@ -23,7 +23,7 @@ use crate::{ INITIAL_BALANCE, }; use pallet_contracts::{CollectEvents, DebugInfo, Determinism}; -// TODO add crate and use pallet_contracts_fixtures::compile_module; +use pallet_contracts_fixtures::compile_module; use assert_matches::assert_matches; use codec::{Decode, Encode}; use frame_support::{ diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 4dcfa1b6c848..72ca91c5158b 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -408,7 +408,7 @@ pub mod pallet { /// A type that exposes XCM APIs, allowing contracts to interact with other parachains, and /// execute XCM programs. - type Xcm: pallet_xcm::Controller< + type Xcm: xcm_builder::Controller< OriginFor, ::RuntimeCall, BlockNumberFor, diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 322e69699d83..2144b6a8d5b7 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2711,7 +2711,7 @@ pub mod env { ) -> Result { use frame_support::dispatch::DispatchInfo; use xcm::VersionedXcm; - use pallet_xcm::{ExecuteController, ExecuteControllerWeightInfo}; + use xcm_builder::{ExecuteController, ExecuteControllerWeightInfo}; ctx.charge_gas(RuntimeCosts::CopyFromContract(msg_len))?; let message: VersionedXcm> = @@ -2764,7 +2764,7 @@ pub mod env { output_ptr: u32, ) -> Result { use xcm::{VersionedMultiLocation, VersionedXcm}; - use pallet_xcm::{SendController, SendControllerWeightInfo}; + use xcm_builder::{SendController, SendControllerWeightInfo}; ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; let dest: VersionedMultiLocation = ctx.read_sandbox_memory_as(memory, dest_ptr)?; @@ -2812,7 +2812,7 @@ pub mod env { ) -> Result { use frame_system::pallet_prelude::BlockNumberFor; use xcm::VersionedMultiLocation; - use pallet_xcm::{QueryController, QueryControllerWeightInfo}; + use xcm_builder::{QueryController, QueryControllerWeightInfo}; let timeout: BlockNumberFor = ctx.read_sandbox_memory_as(memory, timeout_ptr)?; let match_querier: VersionedMultiLocation = @@ -2855,8 +2855,7 @@ pub mod env { query_id_ptr: u32, output_ptr: u32, ) -> Result { - use xcm_executor::traits::QueryHandler; - use pallet_xcm::{QueryController, QueryControllerWeightInfo}; + use xcm_builder::{QueryController, QueryHandler, QueryControllerWeightInfo}; let query_id: <::Xcm as QueryHandler>::QueryId = ctx.read_sandbox_memory_as(memory, query_id_ptr)?; From 7b3ad3daae717fcaba14ee2601533c6b724adaa3 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 10 Nov 2023 17:31:37 +0100 Subject: [PATCH 098/115] fix tests --- Cargo.lock | 2 ++ substrate/frame/contracts/mock-network/Cargo.toml | 6 +++++- substrate/frame/contracts/mock-network/src/tests.rs | 4 ++-- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 645f744d8905..f3b6a24a1195 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9748,6 +9748,7 @@ dependencies = [ name = "pallet-contracts-mock-network" version = "1.0.0" dependencies = [ + "assert_matches", "frame-support", "frame-system", "pallet-assets", @@ -9766,6 +9767,7 @@ dependencies = [ "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-runtime-parachains", + "pretty_assertions", "scale-info", "sp-api", "sp-core", diff --git a/substrate/frame/contracts/mock-network/Cargo.toml b/substrate/frame/contracts/mock-network/Cargo.toml index 7781134f2842..af1b0df45037 100644 --- a/substrate/frame/contracts/mock-network/Cargo.toml +++ b/substrate/frame/contracts/mock-network/Cargo.toml @@ -16,7 +16,6 @@ frame-system = { path = "../../system", default-features = false} pallet-assets = { path = "../../assets" } pallet-balances = { path = "../../balances" } pallet-contracts = { path = ".." } -pallet-contracts-fixtures = { path = "../fixtures" } pallet-contracts-primitives = { path = "../primitives", default-features = false} pallet-contracts-proc-macro = { path = "../proc-macro" } pallet-insecure-randomness-collective-flip = { path = "../../insecure-randomness-collective-flip" } @@ -41,6 +40,11 @@ xcm-builder = {package = "staging-xcm-builder", path = "../../../../polkadot/xcm xcm-executor = { package = "staging-xcm-executor", path = "../../../../polkadot/xcm/xcm-executor", default-features = false} xcm-simulator = {path = "../../../../polkadot/xcm/xcm-simulator"} +[dev-dependencies] +assert_matches = "1" +pretty_assertions = "1" +pallet-contracts-fixtures = { path = "../fixtures" } + [features] default = [ "std" ] std = [ diff --git a/substrate/frame/contracts/mock-network/src/tests.rs b/substrate/frame/contracts/mock-network/src/tests.rs index aae89cbc62c6..927e2672978c 100644 --- a/substrate/frame/contracts/mock-network/src/tests.rs +++ b/substrate/frame/contracts/mock-network/src/tests.rs @@ -38,7 +38,7 @@ use xcm::{v3::prelude::*, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; use xcm_simulator::TestExt; -type ParachainContracts = crate::Pallet; +type ParachainContracts = pallet_contracts::Pallet; type QueryId = as QueryHandler>::QueryId; /// Instantiate the tests contract, and fund it with some balance and assets. @@ -159,7 +159,7 @@ fn test_xcm_execute_reentrant_call() { let contract_addr = instantiate_test_contract("xcm_execute"); ParaA::execute_with(|| { - let transact_call = parachain::RuntimeCall::Contracts(crate::Call::call { + let transact_call = parachain::RuntimeCall::Contracts(pallet_contracts::Call::call { dest: contract_addr.clone(), gas_limit: 1_000_000.into(), storage_deposit_limit: None, From 0b4c8406a3af7ed1c0c84783f3d24400ad008e8b Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 10 Nov 2023 17:35:58 +0100 Subject: [PATCH 099/115] fix lint --- polkadot/xcm/xcm-builder/src/lib.rs | 4 ++-- substrate/frame/contracts/fixtures/src/lib.rs | 3 ++- substrate/frame/contracts/mock-network/src/tests.rs | 4 ++-- substrate/frame/contracts/src/exec.rs | 1 - substrate/frame/contracts/src/lib.rs | 6 ++---- substrate/frame/contracts/src/wasm/runtime.rs | 2 +- 6 files changed, 9 insertions(+), 11 deletions(-) diff --git a/polkadot/xcm/xcm-builder/src/lib.rs b/polkadot/xcm/xcm-builder/src/lib.rs index b34bdb24d8af..455f17a5348c 100644 --- a/polkadot/xcm/xcm-builder/src/lib.rs +++ b/polkadot/xcm/xcm-builder/src/lib.rs @@ -118,6 +118,6 @@ pub use pay::{FixedLocation, LocatableAssetId, PayAccountId32OnChainOverXcm, Pay mod controller; pub use controller::{ - Controller, ExecuteController, ExecuteControllerWeightInfo, QueryController, QueryHandler, - QueryControllerWeightInfo, SendController, SendControllerWeightInfo, + Controller, ExecuteController, ExecuteControllerWeightInfo, QueryController, + QueryControllerWeightInfo, QueryHandler, SendController, SendControllerWeightInfo, }; diff --git a/substrate/frame/contracts/fixtures/src/lib.rs b/substrate/frame/contracts/fixtures/src/lib.rs index 5d662c9937d4..48117f7ca944 100644 --- a/substrate/frame/contracts/fixtures/src/lib.rs +++ b/substrate/frame/contracts/fixtures/src/lib.rs @@ -23,7 +23,8 @@ fn fixtures_root_dir() -> PathBuf { // When `CARGO_MANIFEST_DIR` is not set, Rust resolves relative paths from the root folder (Err(_), _) => "substrate/frame/contracts/fixtures/data".into(), (Ok(path), Ok(s)) if s == "pallet-contracts" => PathBuf::from(path).join("fixtures/data"), - (Ok(path), Ok(s)) if s == "pallet-contracts-mock-network" => PathBuf::from(path).parent().unwrap().join("fixtures/data"), + (Ok(path), Ok(s)) if s == "pallet-contracts-mock-network" => + PathBuf::from(path).parent().unwrap().join("fixtures/data"), (Ok(_), pkg_name) => panic!("Failed to resolve fixture dir for tests from {pkg_name:?}."), } } diff --git a/substrate/frame/contracts/mock-network/src/tests.rs b/substrate/frame/contracts/mock-network/src/tests.rs index 927e2672978c..5fd221e6d614 100644 --- a/substrate/frame/contracts/mock-network/src/tests.rs +++ b/substrate/frame/contracts/mock-network/src/tests.rs @@ -22,8 +22,6 @@ use crate::{ relay_chain, MockNet, ParaA, ParachainBalances, ParachainPalletXcm, Relay, ALICE, BOB, INITIAL_BALANCE, }; -use pallet_contracts::{CollectEvents, DebugInfo, Determinism}; -use pallet_contracts_fixtures::compile_module; use assert_matches::assert_matches; use codec::{Decode, Encode}; use frame_support::{ @@ -33,6 +31,8 @@ use frame_support::{ }; use frame_system::pallet_prelude::BlockNumberFor; use pallet_balances::{BalanceLock, Reasons}; +use pallet_contracts::{CollectEvents, DebugInfo, Determinism}; +use pallet_contracts_fixtures::compile_module; use pallet_contracts_primitives::Code; use xcm::{v3::prelude::*, VersionedMultiLocation, VersionedXcm}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index ad722d61b5d2..c26d82f7f110 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -138,7 +138,6 @@ impl> From for ExecError { pub trait Ext: sealing::Sealed { type T: Config; - /// Call (possibly transferring some amount of funds) into the specified account. /// /// Returns the code size of the called contract. diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 72ca91c5158b..188679dbf490 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -207,8 +207,7 @@ pub struct EnvironmentType(PhantomData); #[derive(Encode, Decode, DefaultNoBound, TypeInfo)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] #[scale_info(skip_type_params(T))] -pub struct Environment -{ +pub struct Environment { account_id: EnvironmentType>, balance: EnvironmentType>, hash: EnvironmentType<::Hash>, @@ -233,8 +232,7 @@ pub mod pallet { pub struct Pallet(_); #[pallet::config] - pub trait Config: frame_system::Config - { + pub trait Config: frame_system::Config { /// The time implementation used to supply timestamps to contracts through `seal_now`. type Time: Time; diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 2144b6a8d5b7..d36e6f84f5a9 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2855,7 +2855,7 @@ pub mod env { query_id_ptr: u32, output_ptr: u32, ) -> Result { - use xcm_builder::{QueryController, QueryHandler, QueryControllerWeightInfo}; + use xcm_builder::{QueryController, QueryControllerWeightInfo, QueryHandler}; let query_id: <::Xcm as QueryHandler>::QueryId = ctx.read_sandbox_memory_as(memory, query_id_ptr)?; From 80e0c537523579baaf93586016ade1bacb3a2e0d Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 10 Nov 2023 18:31:05 +0100 Subject: [PATCH 100/115] fixes --- .../contracts-rococo/src/contracts.rs | 1 + .../frame/contracts/mock-network/Cargo.toml | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs index 1c99393d5e52..3e4633c6cab1 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs @@ -79,4 +79,5 @@ impl Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type Debug = (); type Environment = (); + type Xcm = pallet_xcm::Pallet; } diff --git a/substrate/frame/contracts/mock-network/Cargo.toml b/substrate/frame/contracts/mock-network/Cargo.toml index af1b0df45037..9d5fe1aaf4ec 100644 --- a/substrate/frame/contracts/mock-network/Cargo.toml +++ b/substrate/frame/contracts/mock-network/Cargo.toml @@ -71,3 +71,21 @@ std = [ "xcm/std", ] +runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-assets/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", + "pallet-contracts/runtime-benchmarks", + "pallet-message-queue/runtime-benchmarks", + "pallet-proxy/runtime-benchmarks", + "pallet-timestamp/runtime-benchmarks", + "pallet-utility/runtime-benchmarks", + "pallet-xcm/runtime-benchmarks", + "polkadot-parachain-primitives/runtime-benchmarks", + "polkadot-primitives/runtime-benchmarks", + "polkadot-runtime-parachains/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", + "xcm-executor/runtime-benchmarks", +] From 59d67a0a3ef3edc8f9eb942deb12e650d8c6598a Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 10 Nov 2023 19:20:52 +0100 Subject: [PATCH 101/115] fix --- substrate/frame/contracts/mock-network/src/parachain.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/contracts/mock-network/src/parachain.rs b/substrate/frame/contracts/mock-network/src/parachain.rs index 510895b918b4..ecb4ddcd1c4b 100644 --- a/substrate/frame/contracts/mock-network/src/parachain.rs +++ b/substrate/frame/contracts/mock-network/src/parachain.rs @@ -328,7 +328,7 @@ impl pallet_xcm::Config for Runtime { type RemoteLockConsumerIdentifier = (); type WeightInfo = pallet_xcm::TestWeightInfo; #[cfg(feature = "runtime-benchmarks")] - type ReachableDest = crate::tests::mock_network::relay_chain::ReachableDest; + type ReachableDest = relay_chain::ReachableDest; type AdminOrigin = EnsureRoot; } From 9a9d572a4898281ee777b89dda47554e19ef9eb4 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Fri, 10 Nov 2023 20:04:46 +0100 Subject: [PATCH 102/115] fix --- substrate/frame/contracts/mock-network/src/parachain.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/contracts/mock-network/src/parachain.rs b/substrate/frame/contracts/mock-network/src/parachain.rs index ecb4ddcd1c4b..71fee5e969f2 100644 --- a/substrate/frame/contracts/mock-network/src/parachain.rs +++ b/substrate/frame/contracts/mock-network/src/parachain.rs @@ -328,7 +328,7 @@ impl pallet_xcm::Config for Runtime { type RemoteLockConsumerIdentifier = (); type WeightInfo = pallet_xcm::TestWeightInfo; #[cfg(feature = "runtime-benchmarks")] - type ReachableDest = relay_chain::ReachableDest; + type ReachableDest = crate::relay_chain::ReachableDest; type AdminOrigin = EnsureRoot; } From 3adde147789a52cf6b62627a499596cf8a6cd078 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 11:18:08 +0100 Subject: [PATCH 103/115] fixed deps moved to pallet-contracts-mock-network --- Cargo.lock | 4 ---- substrate/frame/contracts/Cargo.toml | 8 -------- 2 files changed, 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f3b6a24a1195..129c0f034d1f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9711,9 +9711,6 @@ dependencies = [ "pallet-timestamp", "pallet-utility", "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", "pretty_assertions", "rand 0.8.5", "rand_pcg", @@ -9732,7 +9729,6 @@ dependencies = [ "wasm-instrument 0.4.0", "wasmi", "wat", - "xcm-simulator", ] [[package]] diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 180f55e3efd4..239b0865e0f0 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -60,11 +60,7 @@ wat = "1" pallet-contracts-fixtures = { path = "./fixtures" } # Polkadot Dependencies -xcm-simulator = {path = "../../../polkadot/xcm/xcm-simulator"} xcm-builder = {package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder"} -polkadot-runtime-parachains = {path = "../../../polkadot/runtime/parachains"} -polkadot-parachain-primitives = { path = "../../../polkadot/parachain" } -polkadot-primitives = { path = "../../../polkadot/primitives" } # Substrate Dependencies pallet-balances = { path = "../balances" } @@ -118,9 +114,6 @@ runtime-benchmarks = [ "pallet-proxy/runtime-benchmarks", "pallet-timestamp/runtime-benchmarks", "pallet-utility/runtime-benchmarks", - "polkadot-parachain-primitives/runtime-benchmarks", - "polkadot-primitives/runtime-benchmarks", - "polkadot-runtime-parachains/runtime-benchmarks", "rand", "rand_pcg", "sp-runtime/runtime-benchmarks", @@ -137,6 +130,5 @@ try-runtime = [ "pallet-proxy/try-runtime", "pallet-timestamp/try-runtime", "pallet-utility/try-runtime", - "polkadot-runtime-parachains/try-runtime", "sp-runtime/try-runtime", ] From c70aca549a7b4a03d46329fb3e2e97f7a4738c5c Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 12:35:47 +0100 Subject: [PATCH 104/115] Review https://github.com/paritytech/polkadot-sdk/pull/1248#discussion_r1392366394 --- substrate/frame/contracts/src/wasm/runtime.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index d36e6f84f5a9..a9685e0f46e8 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2746,8 +2746,8 @@ pub mod env { /// /// - `dest_ptr`: the pointer into the linear memory where the [`xcm::VersionedMultiLocation`] /// is placed. - /// - `call_ptr`: the pointer into the linear memory where the message is placed. - /// - `call_len`: the length of the message in bytes. + /// - `msg_ptr`: the pointer into the linear memory where the [`xcm::VersionedMessage`] is placed. + /// - `msg_len`: the length of the message in bytes. /// - `output_ptr`: the pointer into the linear memory where the message id is placed. /// /// # Return Value @@ -2759,18 +2759,18 @@ pub mod env { ctx: _, memory: _, dest_ptr: u32, - call_ptr: u32, - call_len: u32, + msg_ptr: u32, + msg_len: u32, output_ptr: u32, ) -> Result { use xcm::{VersionedMultiLocation, VersionedXcm}; use xcm_builder::{SendController, SendControllerWeightInfo}; - ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; + ctx.charge_gas(RuntimeCosts::CopyFromContract(msg_len))?; let dest: VersionedMultiLocation = ctx.read_sandbox_memory_as(memory, dest_ptr)?; let message: VersionedXcm<()> = - ctx.read_sandbox_memory_as_unbounded(memory, call_ptr, call_len)?; + ctx.read_sandbox_memory_as_unbounded(memory, msg_ptr, msg_len)?; let weight = <::Xcm as SendController<_>>::WeightInfo::send(); ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; let origin = crate::RawOrigin::Signed(ctx.ext.address().clone()).into(); From 5d6363603c4719cac033d868525aa710858a5fd2 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 12:38:41 +0100 Subject: [PATCH 105/115] Review https://github.com/paritytech/polkadot-sdk/pull/1248#discussion_r1392369016 --- substrate/frame/contracts/src/wasm/runtime.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index a9685e0f46e8..a262d18d8710 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2694,7 +2694,7 @@ pub mod env { /// /// # Parameters /// - /// - `msg_ptr`: the pointer into the linear memory where the message is placed. + /// - `msg_ptr`: the pointer into the linear memory where the [`xcm::VersionedXcm`] is placed. /// - `msg_len`: the length of the message in bytes. /// /// # Return Value From 57b7ca50950fb5c7fdf46bd03fd3b1357f8712d1 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 12:43:17 +0100 Subject: [PATCH 106/115] PR review https://github.com/paritytech/polkadot-sdk/pull/1248#discussion_r1392376779 --- substrate/frame/contracts/src/wasm/runtime.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index a262d18d8710..38b30908efc4 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2748,7 +2748,7 @@ pub mod env { /// is placed. /// - `msg_ptr`: the pointer into the linear memory where the [`xcm::VersionedMessage`] is placed. /// - `msg_len`: the length of the message in bytes. - /// - `output_ptr`: the pointer into the linear memory where the message id is placed. + /// - `output_ptr`: the pointer into the linear memory where the [`xcm::v3::XcmHash`] message id is placed. /// /// # Return Value /// From 10f22fb506f49cccd3811a702c17efbe778db395 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 12:47:11 +0100 Subject: [PATCH 107/115] PR review https://github.com/paritytech/polkadot-sdk/pull/1248#discussion_r1392377522 --- substrate/frame/contracts/src/wasm/runtime.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 38b30908efc4..b1fc4cfe7af8 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2746,9 +2746,11 @@ pub mod env { /// /// - `dest_ptr`: the pointer into the linear memory where the [`xcm::VersionedMultiLocation`] /// is placed. - /// - `msg_ptr`: the pointer into the linear memory where the [`xcm::VersionedMessage`] is placed. + /// - `msg_ptr`: the pointer into the linear memory where the [`xcm::VersionedMessage`] is + /// placed. /// - `msg_len`: the length of the message in bytes. - /// - `output_ptr`: the pointer into the linear memory where the [`xcm::v3::XcmHash`] message id is placed. + /// - `output_ptr`: the pointer into the linear memory where the [`xcm::v3::XcmHash`] message id + /// is placed. /// /// # Return Value /// @@ -2796,7 +2798,8 @@ pub mod env { /// /// - `timeout_ptr`: the pointer into the linear memory where the timeout is placed. /// - `match_querier_ptr`: the pointer into the linear memory where the match_querier is placed. - /// - `output_ptr`: the pointer into the linear memory where the query id is placed. + /// - `output_ptr`: the pointer into the linear memory where the + /// [`xcm_builder::QueryHandler::QueryId`] is placed. /// /// # Return Value /// From 162ad545104ef474fb4f140ea2c567b0b9049f0b Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 12:51:31 +0100 Subject: [PATCH 108/115] PR review https://github.com/paritytech/polkadot-sdk/pull/1248#discussion_r1392378359 --- substrate/frame/contracts/src/wasm/runtime.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index b1fc4cfe7af8..fd3630c886e0 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2844,9 +2844,10 @@ pub mod env { /// /// # Parameters /// - /// - `query_id_ptr`: the pointer into the linear memory where the query id is placed. - /// - `output_ptr`: the pointer into the linear memory where the response is placed. - /// - `output_len_ptr`: the pointer into the linear memory where the response length is placed. + /// - `query_id_ptr`: the pointer into the linear memory where the + /// [`xcm_builder::QueryHandler::QueryId`] is placed. + /// - `output_ptr`: the pointer into the linear memory where the response + /// [`xcm_builder::QueryResponseStatus`] is placed. /// /// # Return Value /// From 3a4a2519f750c7cf280d70592d43b51b0c891b96 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 12:55:27 +0100 Subject: [PATCH 109/115] rm macro_export --- substrate/frame/contracts/src/tests.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index f71504c33e94..76fd012852a9 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -81,7 +81,6 @@ frame_support::construct_runtime!( } ); -#[macro_export] macro_rules! assert_return_code { ( $x:expr , $y:expr $(,)? ) => {{ assert_eq!(u32::from_le_bytes($x.data[..].try_into().unwrap()), $y as u32); From dab8314b14f2d776156b3e793da0c22813c93e7a Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 16:26:48 +0100 Subject: [PATCH 110/115] Temporary remove xcm_query and xcm_take_response fns --- .../contracts/fixtures/data/xcm_query.wat | 53 ---------- .../fixtures/data/xcm_take_response.wat | 38 ------- .../frame/contracts/mock-network/src/tests.rs | 100 ------------------ substrate/frame/contracts/src/wasm/runtime.rs | 82 -------------- 4 files changed, 273 deletions(-) delete mode 100644 substrate/frame/contracts/fixtures/data/xcm_query.wat delete mode 100644 substrate/frame/contracts/fixtures/data/xcm_take_response.wat diff --git a/substrate/frame/contracts/fixtures/data/xcm_query.wat b/substrate/frame/contracts/fixtures/data/xcm_query.wat deleted file mode 100644 index 5f3ed88d3ae1..000000000000 --- a/substrate/frame/contracts/fixtures/data/xcm_query.wat +++ /dev/null @@ -1,53 +0,0 @@ -;; This passes its input to `seal_xcm_query` and returns the return value to its caller. -(module - (import "seal0" "xcm_query" (func $xcm_query (param i32 i32 i32) (result i32))) - (import "seal0" "seal_input" (func $seal_input (param i32 i32))) - (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) - (import "env" "memory" (memory 1 1)) - - ;; 0x1000 = 4k in little endian - ;; size of input buffer - (data (i32.const 0) "\00\10") - - (func $assert (param i32) - (block $ok - (br_if $ok - (get_local 0) - ) - (unreachable) - ) - ) - - (func (export "call") - ;; Receive the encoded call - (call $seal_input - (i32.const 4) ;; Pointer to the input buffer - (i32.const 0) ;; Pointer to the buffer length (before call) and to the copied data length (after call) - ) - ;; Input data layout. - ;; [0..4) - size of the input buffer - ;; [4..12) - timeout - ;; [12..49) - match_querier - - ;; Call xcm_query with provided input. - (call $assert - (i32.eq - (call $xcm_query - (i32.const 4) ;; Pointer where the timeout is stored - (i32.const 12) ;; Pointer where the match_querier is stored - (i32.const 49) ;; Pointer to the where the query_id is stored - ) - (i32.const 0) - ) - ) - - ;; Return the the query_id - (call $seal_return - (i32.const 0) ;; flags - (i32.const 49) ;; Pointer to returned value - (i32.const 8) ;; length of returned value - ) - ) - - (func (export "deploy")) -) diff --git a/substrate/frame/contracts/fixtures/data/xcm_take_response.wat b/substrate/frame/contracts/fixtures/data/xcm_take_response.wat deleted file mode 100644 index 1e608adf3f97..000000000000 --- a/substrate/frame/contracts/fixtures/data/xcm_take_response.wat +++ /dev/null @@ -1,38 +0,0 @@ -;; This passes its input to `seal_xcm_take_response` and returns the return value to its caller. -(module - (import "seal0" "xcm_take_response" (func $xcm_take_response (param i32 i32) (result i32))) - (import "seal0" "seal_input" (func $seal_input (param i32 i32))) - (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) - (import "env" "memory" (memory 1 1)) - - ;; 0x1000 = 4k in little endian - ;; size of input buffer - (data (i32.const 0) "\00\10") - - (func (export "call") - ;; Receive the encoded call - (call $seal_input - (i32.const 4) ;; Pointer to the input buffer - (i32.const 0) ;; Size of the length buffer - ) - ;; Input data layout. - ;; [0..4) - size of the call - ;; [4..12) - query_id - - ;; Just use the call passed as input and store result to memory - (i32.store (i32.const 0) - (call $xcm_take_response - (i32.const 4) ;; Pointer where the query_id is stored - (i32.const 12) ;; Pointer where the response is stored - ) - ) - - (call $seal_return - (i32.const 0) ;; flags - (i32.const 12) ;; returned value - (i32.const 112) ;; length of returned value - ) - ) - - (func (export "deploy")) -) diff --git a/substrate/frame/contracts/mock-network/src/tests.rs b/substrate/frame/contracts/mock-network/src/tests.rs index 5fd221e6d614..982e2b13f6e7 100644 --- a/substrate/frame/contracts/mock-network/src/tests.rs +++ b/substrate/frame/contracts/mock-network/src/tests.rs @@ -241,103 +241,3 @@ fn test_xcm_send() { ); }); } - -#[test] -fn test_xcm_query() { - MockNet::reset(); - let contract_addr = instantiate_test_contract("xcm_query"); - - ParaA::execute_with(|| { - let match_querier = MultiLocation::from(AccountId32 { network: None, id: ALICE.into() }); - let match_querier = VersionedMultiLocation::V3(match_querier); - let timeout: BlockNumberFor = 1u32.into(); - - // Invoke the contract to create an XCM query. - let exec = ParachainContracts::bare_call( - ALICE, - contract_addr.clone(), - 0, - Weight::MAX, - None, - (timeout, match_querier).encode(), - DebugInfo::UnsafeDebug, - CollectEvents::UnsafeCollect, - Determinism::Enforced, - ); - - let mut data = &exec.result.unwrap().data[..]; - let query_id = QueryId::decode(&mut data).expect("Failed to decode message"); - - // Verify that the query exists and is pending. - let response = ::take_response(query_id); - let expected_response = QueryResponseStatus::Pending { timeout }; - assert_eq!(response, expected_response); - }); -} - -#[test] -fn test_xcm_take_response() { - MockNet::reset(); - let contract_addr = instantiate_test_contract("xcm_take_response"); - - ParaA::execute_with(|| { - let querier: MultiLocation = - (Parent, AccountId32 { network: None, id: ALICE.into() }).into(); - let responder = MultiLocation::from(AccountId32 { - network: Some(NetworkId::ByGenesis([0u8; 32])), - id: ALICE.into(), - }); - - // Register a new query. - let query_id = ParachainPalletXcm::new_query(responder, 1u32.into(), querier); - - // Helper closure to call the contract to take the response. - let call = |query_id: QueryId| { - let exec = ParachainContracts::bare_call( - ALICE, - contract_addr.clone(), - 0, - Weight::MAX, - None, - query_id.encode(), - DebugInfo::UnsafeDebug, - CollectEvents::UnsafeCollect, - Determinism::Enforced, - ); - - QueryResponseStatus::>::decode( - &mut &exec.result.unwrap().data[..], - ) - .expect("Failed to decode message") - }; - - // Query is not yet answered. - assert_eq!(QueryResponseStatus::Pending { timeout: 1u32.into() }, call(query_id)); - - // Execute the XCM program that answers the query. - let message = Xcm(vec![QueryResponse { - query_id, - response: Response::ExecutionResult(None), - max_weight: Weight::zero(), - querier: Some(querier), - }]); - ParachainPalletXcm::execute( - RuntimeOrigin::signed(ALICE), - Box::new(VersionedXcm::V3(message)), - Weight::from_parts(1_000_000_000, 1_000_000_000), - ) - .unwrap(); - - // First call returns the response. - assert_eq!( - QueryResponseStatus::Ready { - response: Response::ExecutionResult(None), - at: 1u32.into() - }, - call(query_id) - ); - - // Second call returns `NotFound`. (Query was already answered) - assert_eq!(QueryResponseStatus::NotFound, call(query_id)); - }) -} diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index fd3630c886e0..5ff0ba6e35eb 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -126,8 +126,6 @@ pub enum ReturnCode { XcmExecutionFailed = 13, /// The `xcm_send` call failed. XcmSendFailed = 14, - /// The `xcm_query` was executed but returned an error. - XcmQueryFailed = 15, } parameter_types! { @@ -2792,86 +2790,6 @@ pub mod env { } } - /// Create a new query, using the contract's address as the responder. - /// - /// # Parameters - /// - /// - `timeout_ptr`: the pointer into the linear memory where the timeout is placed. - /// - `match_querier_ptr`: the pointer into the linear memory where the match_querier is placed. - /// - `output_ptr`: the pointer into the linear memory where the - /// [`xcm_builder::QueryHandler::QueryId`] is placed. - /// - /// # Return Value - /// - /// Returns `ReturnCode::Success` when the query was successfully created. When the query - /// creation fails, `ReturnCode::XcmQueryFailed` is returned. - #[unstable] - fn xcm_query( - ctx: _, - memory: _, - timeout_ptr: u32, - match_querier_ptr: u32, - output_ptr: u32, - ) -> Result { - use frame_system::pallet_prelude::BlockNumberFor; - use xcm::VersionedMultiLocation; - use xcm_builder::{QueryController, QueryControllerWeightInfo}; - - let timeout: BlockNumberFor = ctx.read_sandbox_memory_as(memory, timeout_ptr)?; - let match_querier: VersionedMultiLocation = - ctx.read_sandbox_memory_as(memory, match_querier_ptr)?; - - let weight = <::Xcm as QueryController<_, _>>::WeightInfo::query(); - ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; - let origin = crate::RawOrigin::Signed(ctx.ext.address().clone()).into(); - - match <::Xcm>::query(origin, timeout, match_querier) { - Ok(query_id) => { - ctx.write_sandbox_memory(memory, output_ptr, &query_id.encode())?; - Ok(ReturnCode::Success) - }, - Err(e) => { - if ctx.ext.append_debug_buffer("") { - ctx.ext.append_debug_buffer("call failed with: "); - ctx.ext.append_debug_buffer(e.into()); - }; - Ok(ReturnCode::XcmQueryFailed) - }, - } - } - - /// Take an XCM response for the specified query. - /// - /// # Parameters - /// - /// - `query_id_ptr`: the pointer into the linear memory where the - /// [`xcm_builder::QueryHandler::QueryId`] is placed. - /// - `output_ptr`: the pointer into the linear memory where the response - /// [`xcm_builder::QueryResponseStatus`] is placed. - /// - /// # Return Value - /// - /// Returns `ReturnCode::Success` when successful. - #[unstable] - fn xcm_take_response( - ctx: _, - memory: _, - query_id_ptr: u32, - output_ptr: u32, - ) -> Result { - use xcm_builder::{QueryController, QueryControllerWeightInfo, QueryHandler}; - - let query_id: <::Xcm as QueryHandler>::QueryId = - ctx.read_sandbox_memory_as(memory, query_id_ptr)?; - - let weight = <::Xcm as QueryController<_, _>>::WeightInfo::take_response(); - ctx.charge_gas(RuntimeCosts::CallRuntime(weight))?; - - let response = <::Xcm>::take_response(query_id).encode(); - ctx.write_sandbox_memory(memory, output_ptr, &response)?; - Ok(ReturnCode::Success) - } - /// Recovers the ECDSA public key from the given message hash and signature. /// /// Writes the public key into the given output buffer. From e3161c90553ef65e5c657f3755200bb8ac0442df Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 17:32:05 +0100 Subject: [PATCH 111/115] misc removed stuff from query --- substrate/frame/contracts/mock-network/src/tests.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/substrate/frame/contracts/mock-network/src/tests.rs b/substrate/frame/contracts/mock-network/src/tests.rs index 982e2b13f6e7..bab664e93129 100644 --- a/substrate/frame/contracts/mock-network/src/tests.rs +++ b/substrate/frame/contracts/mock-network/src/tests.rs @@ -35,11 +35,9 @@ use pallet_contracts::{CollectEvents, DebugInfo, Determinism}; use pallet_contracts_fixtures::compile_module; use pallet_contracts_primitives::Code; use xcm::{v3::prelude::*, VersionedMultiLocation, VersionedXcm}; -use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; use xcm_simulator::TestExt; type ParachainContracts = pallet_contracts::Pallet; -type QueryId = as QueryHandler>::QueryId; /// Instantiate the tests contract, and fund it with some balance and assets. fn instantiate_test_contract(name: &str) -> AccountId { From 4128aa6dc7dc13ea2517e857e0bf1fdbec5fff79 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 17:36:00 +0100 Subject: [PATCH 112/115] fix doc --- substrate/frame/contracts/src/wasm/runtime.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 5ff0ba6e35eb..b3013adb790e 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -2692,8 +2692,11 @@ pub mod env { /// /// # Parameters /// - /// - `msg_ptr`: the pointer into the linear memory where the [`xcm::VersionedXcm`] is placed. + /// - `msg_ptr`: the pointer into the linear memory where the [`xcm::prelude::VersionedXcm`] is + /// placed. /// - `msg_len`: the length of the message in bytes. + /// - `output_ptr`: the pointer into the linear memory where the [`xcm::prelude::Outcome`] + /// message id is placed. /// /// # Return Value /// @@ -2742,9 +2745,9 @@ pub mod env { /// /// # Parameters /// - /// - `dest_ptr`: the pointer into the linear memory where the [`xcm::VersionedMultiLocation`] - /// is placed. - /// - `msg_ptr`: the pointer into the linear memory where the [`xcm::VersionedMessage`] is + /// - `dest_ptr`: the pointer into the linear memory where the + /// [`xcm::prelude::VersionedMultiLocation`] is placed. + /// - `msg_ptr`: the pointer into the linear memory where the [`xcm::prelude::VersionedXcm`] is /// placed. /// - `msg_len`: the length of the message in bytes. /// - `output_ptr`: the pointer into the linear memory where the [`xcm::v3::XcmHash`] message id From f0df85b0a466945a81573a58ef8350059dd17816 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 19:23:04 +0100 Subject: [PATCH 113/115] rm more stuff from query & take_response --- substrate/frame/contracts/mock-network/src/tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/substrate/frame/contracts/mock-network/src/tests.rs b/substrate/frame/contracts/mock-network/src/tests.rs index bab664e93129..ee95345318ff 100644 --- a/substrate/frame/contracts/mock-network/src/tests.rs +++ b/substrate/frame/contracts/mock-network/src/tests.rs @@ -16,10 +16,10 @@ // limitations under the License. use crate::{ - parachain::{self, Runtime, RuntimeOrigin}, + parachain::{self, Runtime}, parachain_account_sovereign_account_id, primitives::{AccountId, CENTS}, - relay_chain, MockNet, ParaA, ParachainBalances, ParachainPalletXcm, Relay, ALICE, BOB, + relay_chain, MockNet, ParaA, ParachainBalances, Relay, ALICE, BOB, INITIAL_BALANCE, }; use assert_matches::assert_matches; @@ -29,7 +29,6 @@ use frame_support::{ pallet_prelude::Weight, traits::{fungibles::Mutate, Currency}, }; -use frame_system::pallet_prelude::BlockNumberFor; use pallet_balances::{BalanceLock, Reasons}; use pallet_contracts::{CollectEvents, DebugInfo, Determinism}; use pallet_contracts_fixtures::compile_module; From b48a8f925cb60fb8fe3567d4a0769ca12f561675 Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 19:28:39 +0100 Subject: [PATCH 114/115] fmt --- substrate/frame/contracts/mock-network/src/tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/substrate/frame/contracts/mock-network/src/tests.rs b/substrate/frame/contracts/mock-network/src/tests.rs index ee95345318ff..5193f6570551 100644 --- a/substrate/frame/contracts/mock-network/src/tests.rs +++ b/substrate/frame/contracts/mock-network/src/tests.rs @@ -19,8 +19,7 @@ use crate::{ parachain::{self, Runtime}, parachain_account_sovereign_account_id, primitives::{AccountId, CENTS}, - relay_chain, MockNet, ParaA, ParachainBalances, Relay, ALICE, BOB, - INITIAL_BALANCE, + relay_chain, MockNet, ParaA, ParachainBalances, Relay, ALICE, BOB, INITIAL_BALANCE, }; use assert_matches::assert_matches; use codec::{Decode, Encode}; From b34e24570ea90bfed348f50b815a51755a0e716f Mon Sep 17 00:00:00 2001 From: pgherveou Date: Tue, 14 Nov 2023 20:53:18 +0100 Subject: [PATCH 115/115] doc test --- substrate/frame/contracts/mock-network/src/parachain.rs | 2 -- substrate/frame/contracts/mock-network/src/relay_chain.rs | 7 ------- 2 files changed, 9 deletions(-) diff --git a/substrate/frame/contracts/mock-network/src/parachain.rs b/substrate/frame/contracts/mock-network/src/parachain.rs index 71fee5e969f2..1465b02f903b 100644 --- a/substrate/frame/contracts/mock-network/src/parachain.rs +++ b/substrate/frame/contracts/mock-network/src/parachain.rs @@ -327,8 +327,6 @@ impl pallet_xcm::Config for Runtime { type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); type WeightInfo = pallet_xcm::TestWeightInfo; - #[cfg(feature = "runtime-benchmarks")] - type ReachableDest = crate::relay_chain::ReachableDest; type AdminOrigin = EnsureRoot; } diff --git a/substrate/frame/contracts/mock-network/src/relay_chain.rs b/substrate/frame/contracts/mock-network/src/relay_chain.rs index cab75d9fbf06..c59c8e4bfa84 100644 --- a/substrate/frame/contracts/mock-network/src/relay_chain.rs +++ b/substrate/frame/contracts/mock-network/src/relay_chain.rs @@ -183,11 +183,6 @@ impl Config for XcmConfig { 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; @@ -211,8 +206,6 @@ impl pallet_xcm::Config for Runtime { type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); type WeightInfo = pallet_xcm::TestWeightInfo; - #[cfg(feature = "runtime-benchmarks")] - type ReachableDest = ReachableDest; type AdminOrigin = EnsureRoot; }