difftreelog
feat benchmark property calls
in: master
30 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5913,6 +5913,7 @@
dependencies = [
"evm-coder",
"fp-evm-mapping",
+ "frame-benchmarking",
"frame-support",
"frame-system",
"pallet-evm",
@@ -6649,6 +6650,7 @@
"frame-support",
"frame-system",
"pallet-common",
+ "pallet-evm",
"parity-scale-codec 3.1.2",
"scale-info",
"sp-std",
Makefilediffbeforeafterboth--- a/Makefile
+++ b/Makefile
@@ -41,6 +41,10 @@
bench-evm-migration:
make _bench PALLET=evm-migration
+.PHONY: bench-common
+bench-common:
+ make _bench PALLET=common
+
.PHONY: bench-unique
bench-unique:
make _bench PALLET=unique
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -25,6 +25,7 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
+frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
[features]
default = ["std"]
@@ -37,4 +38,6 @@
"up-data-structs/std",
"pallet-evm/std",
]
-runtime-benchmarks = []
+runtime-benchmarks = [
+ "frame-benchmarking"
+]
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -15,11 +15,13 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use sp_std::vec::Vec;
-use crate::{Config, CollectionHandle};
+use crate::{Config, CollectionHandle, Pallet};
+use pallet_evm::account::CrossAccountId;
+use frame_benchmarking::{benchmarks, account};
use up_data_structs::{
- CollectionMode, CreateCollectionData, CollectionId, MAX_COLLECTION_NAME_LENGTH,
- MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, OFFCHAIN_SCHEMA_LIMIT,
- CONST_ON_CHAIN_SCHEMA_LIMIT,
+ CollectionMode, CreateCollectionData, CollectionId, Property, PropertyKey, PropertyValue,
+ MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+ OFFCHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, MAX_PROPERTIES_PER_ITEM,
};
use frame_support::{
traits::{Currency, Get},
@@ -29,6 +31,8 @@
use core::convert::TryInto;
use sp_runtime::DispatchError;
+const SEED: u32 = 1;
+
pub fn create_data<const S: u32>() -> BoundedVec<u8, ConstU32<S>> {
create_var_data::<S>(S)
}
@@ -52,6 +56,22 @@
.try_into()
.unwrap()
}
+pub fn property_key(id: usize) -> PropertyKey {
+ #[cfg(not(feature = "std"))]
+ use alloc::string::ToString;
+ let mut data = create_data();
+ // No DerefMut available for .fill
+ for i in 0..data.len() {
+ data[i] = b'0';
+ }
+ let bytes = id.to_string();
+ let len = data.len();
+ data[len - bytes.len()..].copy_from_slice(&bytes.as_bytes());
+ data
+}
+pub fn property_value() -> PropertyValue {
+ create_data()
+}
pub fn create_collection_raw<T: Config, R>(
owner: T::AccountId,
@@ -83,6 +103,14 @@
.and_then(CollectionHandle::try_get)
.map(cast)
}
+fn create_collection<T: Config>(owner: T::AccountId) -> Result<CollectionHandle<T>, DispatchError> {
+ create_collection_raw(
+ owner,
+ CollectionMode::NFT,
+ |owner, data| <Pallet<T>>::init_collection(owner, data),
+ |h| h,
+ )
+}
/// Helper macros, which handles all benchmarking preparation in semi-declarative way
///
@@ -125,3 +153,31 @@
};
() => {}
}
+
+benchmarks! {
+ set_collection_properties {
+ let b in 0..MAX_PROPERTIES_PER_ITEM;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let props = (0..b).map(|p| Property {
+ key: property_key(p as usize),
+ value: property_value(),
+ }).collect::<Vec<_>>();
+ }: {<Pallet<T>>::set_collection_properties(&collection, &owner, props)?}
+
+ delete_collection_properties {
+ let b in 0..MAX_PROPERTIES_PER_ITEM;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let props = (0..b).map(|p| Property {
+ key: property_key(p as usize),
+ value: property_value(),
+ }).collect::<Vec<_>>();
+ <Pallet<T>>::set_collection_properties(&collection, &owner, props)?;
+ let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();
+ }: {<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete)?}
+}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -16,6 +16,8 @@
#![cfg_attr(not(feature = "std"), no_std)]
+extern crate alloc;
+
use core::ops::{Deref, DerefMut};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
use sp_std::vec::Vec;
@@ -85,6 +87,9 @@
pub mod dispatch;
pub mod erc;
pub mod eth;
+pub mod weights;
+
+pub type SelfWeightOf<T> = <T as Config>::WeightInfo;
#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]
pub struct CollectionHandle<T: Config> {
@@ -186,11 +191,13 @@
use frame_support::traits::Currency;
use up_data_structs::{TokenId, mapping::TokenAddressMapping};
use scale_info::TypeInfo;
+ use weights::WeightInfo;
#[pallet::config]
pub trait Config:
frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config
{
+ type WeightInfo: WeightInfo;
type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;
type Currency: Currency<Self::AccountId>;
@@ -804,7 +811,7 @@
pub fn set_scoped_collection_properties(
collection: &CollectionHandle<T>,
scope: PropertyScope,
- properties: impl Iterator<Item=Property>,
+ properties: impl Iterator<Item = Property>,
) -> DispatchResult {
CollectionProperties::<T>::try_mutate(collection.id, |stored_properties| {
stored_properties.try_scoped_set_from_iter(scope, properties)
@@ -903,10 +910,11 @@
Ok(())
}
- pub fn get_collection_property(collection_id: CollectionId, key: &PropertyKey) -> Option<PropertyValue> {
- Self::collection_properties(collection_id)
- .get(key)
- .cloned()
+ pub fn get_collection_property(
+ collection_id: CollectionId,
+ key: &PropertyKey,
+ ) -> Option<PropertyValue> {
+ Self::collection_properties(collection_id).get(key).cloned()
}
pub fn bytes_keys_to_property_keys(
@@ -1131,7 +1139,7 @@
/// Worst cases
pub trait CommonWeightInfo<CrossAccountId> {
fn create_item() -> Weight;
- fn create_multiple_items(amount: u32) -> Weight;
+ fn create_multiple_items(amount: &[CreateItemData]) -> Weight;
fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;
fn burn_item() -> Weight;
fn set_collection_properties(amount: u32) -> Weight;
pallets/common/src/weights.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/common/src/weights.rs
@@ -0,0 +1,79 @@
+// Template adopted from https://github.com/paritytech/substrate/blob/master/.maintain/frame-weight-template.hbs
+
+//! Autogenerated weights for pallet_common
+//!
+//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
+//! DATE: 2022-05-23, STEPS: `50`, REPEAT: 1, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
+
+// Executed Command:
+// target/release/unique-collator
+// benchmark
+// pallet
+// --pallet
+// pallet-common
+// --wasm-execution
+// compiled
+// --extrinsic
+// *
+// --template
+// .maintain/frame-weight-template.hbs
+// --steps=50
+// --repeat=1
+// --heap-pages=4096
+// --output=./pallets/common/src/weights.rs
+
+#![cfg_attr(rustfmt, rustfmt_skip)]
+#![allow(unused_parens)]
+#![allow(unused_imports)]
+#![allow(clippy::unnecessary_cast)]
+
+use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
+use sp_std::marker::PhantomData;
+
+/// Weight functions needed for pallet_common.
+pub trait WeightInfo {
+ fn set_collection_properties(b: u32, ) -> Weight;
+ fn delete_collection_properties(b: u32, ) -> Weight;
+}
+
+/// Weights for pallet_common using the Substrate node and recommended hardware.
+pub struct SubstrateWeight<T>(PhantomData<T>);
+impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
+ // Storage: Common CollectionProperties (r:1 w:1)
+ fn set_collection_properties(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 142_818_000
+ .saturating_add((2_786_252_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Common CollectionProperties (r:1 w:1)
+ fn delete_collection_properties(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 101_087_000
+ .saturating_add((2_739_521_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+}
+
+// For backwards compatibility and tests
+impl WeightInfo for () {
+ // Storage: Common CollectionProperties (r:1 w:1)
+ fn set_collection_properties(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 142_818_000
+ .saturating_add((2_786_252_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Common CollectionProperties (r:1 w:1)
+ fn delete_collection_properties(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 101_087_000
+ .saturating_add((2_739_521_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+}
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -40,7 +40,7 @@
owner: sub; collection: collection(owner);
sender: cross_from_sub(owner); to: cross_sub;
};
- }: {<Pallet<T>>::create_item(&collection, &sender, (to, 200))?}
+ }: {<Pallet<T>>::create_item(&collection, &sender, (to, 200), &Unlimited)?}
create_multiple_items_ex {
let b in 0..MAX_ITEMS_PER_BATCH;
@@ -52,14 +52,14 @@
bench_init!(to: cross_sub(i););
(to, 200)
}).collect::<BTreeMap<_, _>>().try_into().unwrap();
- }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+ }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}
burn_item {
bench_init!{
owner: sub; collection: collection(owner);
owner: cross_from_sub; burner: cross_sub;
};
- <Pallet<T>>::create_item(&collection, &owner, (burner.clone(), 200))?;
+ <Pallet<T>>::create_item(&collection, &owner, (burner.clone(), 200), &Unlimited)?;
}: {<Pallet<T>>::burn(&collection, &burner, 100)?}
transfer {
@@ -67,15 +67,15 @@
owner: sub; collection: collection(owner);
owner: cross_from_sub; sender: cross_sub; to: cross_sub;
};
- <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200))?;
- }: {<Pallet<T>>::transfer(&collection, &sender, &to, 200)?}
+ <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
+ }: {<Pallet<T>>::transfer(&collection, &sender, &to, 200, &Unlimited)?}
approve {
bench_init!{
owner: sub; collection: collection(owner);
owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
};
- <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200))?;
+ <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
}: {<Pallet<T>>::set_allowance(&collection, &sender, &spender, 100)?}
transfer_from {
@@ -83,7 +83,7 @@
owner: sub; collection: collection(owner);
owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
};
- <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200))?;
+ <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
<Pallet<T>>::set_allowance(&collection, &sender, &spender, 200)?;
}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, 100, &Unlimited)?}
@@ -92,7 +92,7 @@
owner: sub; collection: collection(owner);
owner: cross_from_sub; sender: cross_sub; burner: cross_sub;
};
- <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200))?;
+ <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
<Pallet<T>>::set_allowance(&collection, &sender, &burner, 200)?;
}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, 100, &Unlimited)?}
}
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -17,7 +17,7 @@
use core::marker::PhantomData;
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
-use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget};
+use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
@@ -33,7 +33,8 @@
<SelfWeightOf<T>>::create_item()
}
- fn create_multiple_items(_amount: u32) -> Weight {
+ fn create_multiple_items(_data: &[CreateItemData]) -> Weight {
+ // All items minted for the same user, so it works same as create_item
Self::create_item()
}
@@ -51,23 +52,28 @@
}
fn set_collection_properties(amount: u32) -> Weight {
- <SelfWeightOf<T>>::set_collection_properties(amount)
+ // Error
+ 0
}
fn delete_collection_properties(amount: u32) -> Weight {
- <SelfWeightOf<T>>::delete_collection_properties(amount)
+ // Error
+ 0
}
fn set_token_properties(amount: u32) -> Weight {
- <SelfWeightOf<T>>::set_token_properties(amount)
+ // Error
+ 0
}
fn delete_token_properties(amount: u32) -> Weight {
- <SelfWeightOf<T>>::delete_token_properties(amount)
+ // Error
+ 0
}
fn set_property_permissions(amount: u32) -> Weight {
- <SelfWeightOf<T>>::set_property_permissions(amount)
+ // Error
+ 0
}
fn transfer() -> Weight {
pallets/fungible/src/weights.rsdiffbeforeafterboth--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -35,11 +35,6 @@
fn create_item() -> Weight;
fn create_multiple_items_ex(b: u32, ) -> Weight;
fn burn_item() -> Weight;
- fn set_collection_properties(amount: u32) -> Weight;
- fn delete_collection_properties(amount: u32) -> Weight;
- fn set_token_properties(amount: u32) -> Weight;
- fn delete_token_properties(amount: u32) -> Weight;
- fn set_property_permissions(amount: u32) -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
fn transfer_from() -> Weight;
@@ -73,33 +68,8 @@
(15_565_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
- }
-
- fn set_collection_properties(_amount: u32) -> Weight {
- // Error
- 0
- }
-
- fn delete_collection_properties(_amount: u32) -> Weight {
- // Error
- 0
- }
-
- fn set_token_properties(_amount: u32) -> Weight {
- // Error
- 0
- }
-
- fn delete_token_properties(_amount: u32) -> Weight {
- // Error
- 0
}
- fn set_property_permissions(_amount: u32) -> Weight {
- // Error
- 0
- }
-
// Storage: Fungible Balance (r:2 w:2)
fn transfer() -> Weight {
(17_713_000 as Weight)
@@ -156,31 +126,6 @@
(15_565_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
- }
-
- fn set_collection_properties(_amount: u32) -> Weight {
- // Error
- 0
- }
-
- fn delete_collection_properties(_amount: u32) -> Weight {
- // Error
- 0
- }
-
- fn set_token_properties(_amount: u32) -> Weight {
- // Error
- 0
- }
-
- fn delete_token_properties(_amount: u32) -> Weight {
- // Error
- 0
- }
-
- fn set_property_permissions(_amount: u32) -> Weight {
- // Error
- 0
}
// Storage: Fungible Balance (r:2 w:2)
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -49,4 +49,5 @@
'frame-benchmarking',
'frame-support/runtime-benchmarks',
'frame-system/runtime-benchmarks',
+ 'up-data-structs/runtime-benchmarks',
]
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -18,24 +18,35 @@
use crate::{Pallet, Config, NonfungibleHandle};
use sp_std::prelude::*;
-use pallet_common::benchmarking::{create_collection_raw, create_data, create_var_data};
+use pallet_common::benchmarking::{create_collection_raw, create_data, property_key, property_value};
use frame_benchmarking::{benchmarks, account};
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT, budget::Unlimited};
+use up_data_structs::{
+ CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, CUSTOM_DATA_LIMIT,
+ budget::Unlimited,
+};
use pallet_common::bench_init;
-use core::convert::TryInto;
const SEED: u32 = 1;
fn create_max_item_data<T: Config>(owner: T::CrossAccountId) -> CreateItemData<T> {
let const_data = create_data::<CUSTOM_DATA_LIMIT>();
- CreateItemData::<T> { const_data, owner }
+ CreateItemData::<T> {
+ const_data,
+ owner,
+ properties: Default::default(),
+ }
}
fn create_max_item<T: Config>(
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
owner: T::CrossAccountId,
) -> Result<TokenId, DispatchError> {
- <Pallet<T>>::create_item(&collection, sender, create_max_item_data::<T>(owner))?;
+ <Pallet<T>>::create_item(
+ &collection,
+ sender,
+ create_max_item_data::<T>(owner),
+ &Unlimited,
+ )?;
Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
}
@@ -65,7 +76,7 @@
sender: cross_from_sub(owner); to: cross_sub;
};
let data = (0..b).map(|_| create_max_item_data::<T>(to.clone())).collect();
- }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+ }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}
create_multiple_items_ex {
let b in 0..MAX_ITEMS_PER_BATCH;
@@ -77,7 +88,7 @@
bench_init!(to: cross_sub(i););
create_max_item_data::<T>(to)
}).collect();
- }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+ }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}
burn_item {
bench_init!{
@@ -93,7 +104,7 @@
owner: cross_from_sub; sender: cross_sub; receiver: cross_sub;
};
let item = create_max_item(&collection, &owner, sender.clone())?;
- }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item)?}
+ }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, &Unlimited)?}
approve {
bench_init!{
@@ -120,4 +131,66 @@
let item = create_max_item(&collection, &owner, sender.clone())?;
<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&burner))?;
}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, &Unlimited)?}
+
+ set_property_permissions {
+ let b in 0..MAX_PROPERTIES_PER_ITEM;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let perms = (0..b).map(|k| PropertyKeyPermission {
+ key: property_key(k as usize),
+ permission: PropertyPermission {
+ mutable: false,
+ collection_admin: false,
+ token_owner: false,
+ },
+ }).collect::<Vec<_>>();
+ }: {<Pallet<T>>::set_property_permissions(&collection, &owner, perms)?}
+
+ set_token_properties {
+ let b in 0..MAX_PROPERTIES_PER_ITEM;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let perms = (0..b).map(|k| PropertyKeyPermission {
+ key: property_key(k as usize),
+ permission: PropertyPermission {
+ mutable: false,
+ collection_admin: true,
+ token_owner: true,
+ },
+ }).collect::<Vec<_>>();
+ <Pallet<T>>::set_property_permissions(&collection, &owner, perms)?;
+ let props = (0..b).map(|k| Property {
+ key: property_key(k as usize),
+ value: property_value(),
+ }).collect::<Vec<_>>();
+ let item = create_max_item(&collection, &owner, owner.clone())?;
+ }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props)?}
+
+ delete_token_properties {
+ let b in 0..MAX_PROPERTIES_PER_ITEM;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let perms = (0..b).map(|k| PropertyKeyPermission {
+ key: property_key(k as usize),
+ permission: PropertyPermission {
+ mutable: true,
+ collection_admin: true,
+ token_owner: true,
+ },
+ }).collect::<Vec<_>>();
+ <Pallet<T>>::set_property_permissions(&collection, &owner, perms)?;
+ let props = (0..b).map(|k| Property {
+ key: property_key(k as usize),
+ value: property_value(),
+ }).collect::<Vec<_>>();
+ let item = create_max_item(&collection, &owner, owner.clone())?;
+ <Pallet<T>>::set_token_properties(&collection, &owner, item, props)?;
+ let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
+ }: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete)?}
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -21,7 +21,9 @@
TokenId, CreateItemExData, CollectionId, budget::Budget, Property, PropertyKey,
PropertyKeyPermission, PropertyValue,
};
-use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
+use pallet_common::{
+ CommonCollectionOperations, CommonWeightInfo, with_weight, weights::WeightInfo as _,
+};
use sp_runtime::DispatchError;
use sp_std::vec::Vec;
@@ -38,13 +40,33 @@
fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {
match data {
- CreateItemExData::NFT(t) => <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32),
+ CreateItemExData::NFT(t) => {
+ <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)
+ + t.iter()
+ .map(|t| {
+ if t.properties.len() > 0 {
+ Self::set_token_properties(t.properties.len() as u32)
+ } else {
+ 0
+ }
+ })
+ .sum::<u64>()
+ }
_ => 0,
}
}
- fn create_multiple_items(amount: u32) -> Weight {
- <SelfWeightOf<T>>::create_multiple_items(amount)
+ fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {
+ <SelfWeightOf<T>>::create_multiple_items(data.len() as u32)
+ + data
+ .iter()
+ .filter_map(|t| match t {
+ up_data_structs::CreateItemData::NFT(n) if n.properties.len() > 0 => {
+ Some(Self::set_token_properties(n.properties.len() as u32))
+ }
+ _ => None,
+ })
+ .sum::<u64>()
}
fn burn_item() -> Weight {
@@ -52,11 +74,11 @@
}
fn set_collection_properties(amount: u32) -> Weight {
- <SelfWeightOf<T>>::set_collection_properties(amount)
+ <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)
}
fn delete_collection_properties(amount: u32) -> Weight {
- <SelfWeightOf<T>>::delete_collection_properties(amount)
+ <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)
}
fn set_token_properties(amount: u32) -> Weight {
@@ -128,15 +150,15 @@
data: Vec<up_data_structs::CreateItemData>,
nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
+ let weight = <CommonWeights<T>>::create_multiple_items(&data);
let data = data
.into_iter()
.map(|d| map_create_data::<T>(d, &to))
.collect::<Result<Vec<_>, DispatchError>>()?;
- let amount = data.len();
with_weight(
<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),
- <CommonWeights<T>>::create_multiple_items(amount as u32),
+ weight,
)
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -18,7 +18,7 @@
use erc::ERC721Events;
use evm_coder::ToLog;
-use frame_support::{BoundedVec, ensure, fail, transactional};
+use frame_support::{BoundedVec, ensure, fail, transactional, storage::with_transaction};
use up_data_structs::{
AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,
@@ -32,7 +32,7 @@
use pallet_structure::Pallet as PalletStructure;
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
use sp_core::H160;
-use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
+use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
use sp_std::{vec::Vec, vec};
use core::ops::Deref;
use sp_std::collections::btree_map::BTreeMap;
@@ -600,28 +600,37 @@
// =========
+ with_transaction(|| {
+ for (i, data) in data.iter().enumerate() {
+ let token = first_token + i as u32 + 1;
+
+ <TokenData<T>>::insert(
+ (collection.id, token),
+ ItemData {
+ const_data: data.const_data.clone(),
+ owner: data.owner.clone(),
+ },
+ );
+
+ if let Err(e) = Self::set_token_properties(
+ collection,
+ sender,
+ TokenId(token),
+ data.properties.clone().into_inner(),
+ ) {
+ return TransactionOutcome::Rollback(Err(e));
+ }
+ }
+ TransactionOutcome::Commit(Ok(()))
+ })?;
+
<TokensMinted<T>>::insert(collection.id, tokens_minted);
for (account, balance) in balances {
<AccountBalance<T>>::insert((collection.id, account), balance);
}
for (i, data) in data.into_iter().enumerate() {
let token = first_token + i as u32 + 1;
-
- <TokenData<T>>::insert(
- (collection.id, token),
- ItemData {
- const_data: data.const_data,
- owner: data.owner.clone(),
- },
- );
<Owned<T>>::insert((collection.id, &data.owner, token), true);
-
- Self::set_token_properties(
- collection,
- sender,
- TokenId(token),
- data.properties.into_inner(),
- )?;
<PalletEvm<T>>::deposit_log(
ERC721Events::Transfer {
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -151,10 +151,35 @@
// Storage: Nonfungible AccountBalance (r:1 w:1)
// Storage: Nonfungible Owned (r:0 w:1)
fn burn_from() -> Weight {
- (27_580_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(4 as Weight))
- .saturating_add(T::DbWeight::get().writes(5 as Weight))
}
+ // Storage: Common CollectionPropertyPermissions (r:1 w:1)
+ fn set_property_permissions(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 3_432_000
+ .saturating_add((126_888_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Common CollectionPropertyPermissions (r:1 w:0)
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ // Storage: Nonfungible TokenProperties (r:1 w:1)
+ fn set_token_properties(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 158_583_000
+ .saturating_add((4_707_700_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(3 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Common CollectionPropertyPermissions (r:1 w:0)
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ // Storage: Nonfungible TokenProperties (r:1 w:1)
+ fn delete_token_properties(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 169_018_000
+ .saturating_add((4_783_967_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(3 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
}
// For backwards compatibility and tests
@@ -260,8 +285,33 @@
// Storage: Nonfungible AccountBalance (r:1 w:1)
// Storage: Nonfungible Owned (r:0 w:1)
fn burn_from() -> Weight {
- (27_580_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(4 as Weight))
- .saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
+ // Storage: Common CollectionPropertyPermissions (r:1 w:1)
+ fn set_property_permissions(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 3_432_000
+ .saturating_add((126_888_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Common CollectionPropertyPermissions (r:1 w:0)
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ // Storage: Nonfungible TokenProperties (r:1 w:1)
+ fn set_token_properties(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 158_583_000
+ .saturating_add((4_707_700_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(3 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Common CollectionPropertyPermissions (r:1 w:0)
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ // Storage: Nonfungible TokenProperties (r:1 w:1)
+ fn delete_token_properties(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 169_018_000
+ .saturating_add((4_783_967_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(3 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
}
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -18,7 +18,7 @@
use crate::{Pallet, Config, RefungibleHandle};
use sp_std::prelude::*;
-use pallet_common::benchmarking::{create_collection_raw, create_data, create_var_data};
+use pallet_common::benchmarking::{create_collection_raw, create_data};
use frame_benchmarking::{benchmarks, account};
use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT, budget::Unlimited};
use pallet_common::bench_init;
@@ -46,7 +46,7 @@
users: impl IntoIterator<Item = (T::CrossAccountId, u128)>,
) -> Result<TokenId, DispatchError> {
let data: CreateRefungibleExData<T::CrossAccountId> = create_max_item_data(users);
- <Pallet<T>>::create_item(&collection, sender, data)?;
+ <Pallet<T>>::create_item(&collection, sender, data, &Unlimited)?;
Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
}
@@ -73,7 +73,7 @@
sender: cross_from_sub(owner); to: cross_sub;
};
let data = (0..b).map(|_| create_max_item_data([(to.clone(), 200)])).collect();
- }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+ }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}
create_multiple_items_ex_multiple_items {
let b in 0..MAX_ITEMS_PER_BATCH;
@@ -85,7 +85,7 @@
bench_init!(to: cross_sub(t););
create_max_item_data([(to, 200)])
}).collect();
- }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+ }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}
create_multiple_items_ex_multiple_owners {
let b in 0..MAX_ITEMS_PER_BATCH;
@@ -97,7 +97,7 @@
bench_init!(to: cross_sub(u););
(to, 200)
}))].try_into().unwrap();
- }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+ }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}
// Other user left, token data is kept
burn_item_partial {
@@ -122,7 +122,7 @@
sender: cross_from_sub(owner); receiver: cross_sub;
};
let item = create_max_item(&collection, &sender, [(sender.clone(), 200), (receiver.clone(), 200)])?;
- }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 100)?}
+ }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 100, &Unlimited)?}
// Target account is created
transfer_creating {
bench_init!{
@@ -130,7 +130,7 @@
sender: cross_from_sub(owner); receiver: cross_sub;
};
let item = create_max_item(&collection, &sender, [(sender.clone(), 200)])?;
- }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 100)?}
+ }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 100, &Unlimited)?}
// Source account is destroyed
transfer_removing {
bench_init!{
@@ -138,7 +138,7 @@
sender: cross_from_sub(owner); receiver: cross_sub;
};
let item = create_max_item(&collection, &sender, [(sender.clone(), 200), (receiver.clone(), 200)])?;
- }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 200)?}
+ }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 200, &Unlimited)?}
// Source account destroyed, target created
transfer_creating_removing {
bench_init!{
@@ -146,7 +146,7 @@
sender: cross_from_sub(owner); receiver: cross_sub;
};
let item = create_max_item(&collection, &sender, [(sender.clone(), 200)])?;
- }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 200)?}
+ }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 200, &Unlimited)?}
approve {
bench_init!{
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -20,7 +20,7 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};
use up_data_structs::{
CollectionId, TokenId, CreateItemExData, CreateRefungibleExData, budget::Budget, Property,
- PropertyKey, PropertyValue, PropertyKeyPermission,
+ PropertyKey, PropertyValue, PropertyKeyPermission, CreateItemData,
};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
@@ -46,8 +46,8 @@
<SelfWeightOf<T>>::create_item()
}
- fn create_multiple_items(amount: u32) -> Weight {
- <SelfWeightOf<T>>::create_multiple_items(amount)
+ fn create_multiple_items(data: &[CreateItemData]) -> Weight {
+ <SelfWeightOf<T>>::create_multiple_items(data.len() as u32)
}
fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {
@@ -66,12 +66,14 @@
max_weight_of!(burn_item_partial(), burn_item_fully())
}
- fn set_collection_properties(amount: u32) -> Weight {
- <SelfWeightOf<T>>::set_collection_properties(amount)
+ fn set_collection_properties(_amount: u32) -> Weight {
+ // Error
+ 0
}
- fn delete_collection_properties(amount: u32) -> Weight {
- <SelfWeightOf<T>>::delete_collection_properties(amount)
+ fn delete_collection_properties(_amount: u32) -> Weight {
+ // Error
+ 0
}
fn set_token_properties(amount: u32) -> Weight {
@@ -156,15 +158,15 @@
data: Vec<up_data_structs::CreateItemData>,
nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
+ let weight = <CommonWeights<T>>::create_multiple_items(&data);
let data = data
.into_iter()
.map(|d| map_create_data::<T>(d, &to))
.collect::<Result<Vec<_>, DispatchError>>()?;
- let amount = data.len();
with_weight(
<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),
- <CommonWeights<T>>::create_multiple_items(amount as u32),
+ weight,
)
}
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -38,8 +38,6 @@
fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight;
fn burn_item_partial() -> Weight;
fn burn_item_fully() -> Weight;
- fn set_collection_properties(amount: u32) -> Weight;
- fn delete_collection_properties(amount: u32) -> Weight;
fn set_token_properties(amount: u32) -> Weight;
fn delete_token_properties(amount: u32) -> Weight;
fn set_property_permissions(amount: u32) -> Weight;
@@ -132,16 +130,6 @@
(32_489_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
- }
-
- fn set_collection_properties(_amount: u32) -> Weight {
- // Error
- 0
- }
-
- fn delete_collection_properties(_amount: u32) -> Weight {
- // Error
- 0
}
fn set_token_properties(_amount: u32) -> Weight {
@@ -320,16 +308,6 @@
(32_489_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
- }
-
- fn set_collection_properties(_amount: u32) -> Weight {
- // Error
- 0
- }
-
- fn delete_collection_properties(_amount: u32) -> Weight {
- // Error
- 0
}
fn set_token_properties(_amount: u32) -> Weight {
pallets/structure/Cargo.tomldiffbeforeafterboth--- a/pallets/structure/Cargo.toml
+++ b/pallets/structure/Cargo.toml
@@ -16,6 +16,7 @@
"derive",
] }
up-data-structs = { path = "../../primitives/data-structs", default-features = false }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.21-logs" }
[features]
default = ["std"]
@@ -28,5 +29,6 @@
"scale-info/std",
"parity-scale-codec/std",
"up-data-structs/std",
+ "pallet-evm/std",
]
runtime-benchmarks = ['frame-benchmarking', 'pallet-common/runtime-benchmarks']
pallets/structure/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/structure/src/benchmarking.rs
+++ b/pallets/structure/src/benchmarking.rs
@@ -2,8 +2,10 @@
use frame_benchmarking::{benchmarks, account};
use frame_support::traits::{Currency, Get};
-use up_data_structs::{CreateCollectionData, CollectionMode, CreateItemData, CreateNftData};
-use pallet_common::CrossAccountId;
+use up_data_structs::{
+ CreateCollectionData, CollectionMode, CreateItemData, CreateNftData, budget::Unlimited,
+};
+use pallet_evm::account::CrossAccountId;
const SEED: u32 = 1;
@@ -20,9 +22,9 @@
let dispatch = T::CollectionDispatch::dispatch(CollectionHandle::try_get(CollectionId(1))?);
let dispatch = dispatch.as_dyn();
- dispatch.create_item(caller_cross.clone(), caller_cross.clone(), CreateItemData::NFT(CreateNftData::default()))?;
+ dispatch.create_item(caller_cross.clone(), caller_cross.clone(), CreateItemData::NFT(CreateNftData::default()), &Unlimited)?;
}: {
let parent = <Pallet<T>>::find_parent(CollectionId(1), TokenId(1))?;
- assert!(matches!(parent, Parent::Normal(_)))
+ assert!(matches!(parent, Parent::User(_)))
}
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -687,7 +687,7 @@
/// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].
///
/// * owner: Address, initial owner of the NFT.
- #[weight = T::CommonWeightInfo::create_multiple_items(items_data.len() as u32)]
+ #[weight = T::CommonWeightInfo::create_multiple_items(&items_data)]
#[transactional]
pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {
ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);
primitives/data-structs/Cargo.tomldiffbeforeafterboth--- a/primitives/data-structs/Cargo.toml
+++ b/primitives/data-structs/Cargo.toml
@@ -42,3 +42,4 @@
]
serde1 = ["serde"]
limit-testing = []
+runtime-benchmarks = []
\ No newline at end of file
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -861,7 +861,9 @@
) -> Result<(), PropertiesError> {
let value_len = value.len();
- if self.consumed_space as usize + value_len > self.space_limit as usize {
+ if self.consumed_space as usize + value_len > self.space_limit as usize
+ && !cfg!(feature = "runtime-benchmarks")
+ {
return Err(PropertiesError::NoSpaceForProperty);
}
runtime/common/src/eth_sponsoring.rsdiffbeforeafterboth--- a/runtime/common/src/eth_sponsoring.rs
+++ b/runtime/common/src/eth_sponsoring.rs
@@ -50,16 +50,20 @@
CollectionMode::NFT => {
let call = <UniqueNFTCall<T>>::parse(method_id, &mut reader).ok()??;
match call {
- UniqueNFTCall::TokenProperties(
- TokenPropertiesCall::SetProperty { token_id, key, value, .. },
- ) => {
+ UniqueNFTCall::TokenProperties(TokenPropertiesCall::SetProperty {
+ token_id,
+ key,
+ value,
+ ..
+ }) => {
let token_id: TokenId = token_id.try_into().ok()?;
withdraw_set_token_property::<T>(
&collection,
&who,
&token_id,
key.len() + value.len(),
- ).map(|()| sponsor)
+ )
+ .map(|()| sponsor)
}
UniqueNFTCall::ERC721UniqueExtensions(
ERC721UniqueExtensionsCall::Transfer { token_id, .. },
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -776,6 +776,7 @@
let mut list = Vec::<BenchmarkList>::new();
list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);
+ list_benchmark!(list, extra, pallet_common, Common);
list_benchmark!(list, extra, pallet_unique, Unique);
list_benchmark!(list, extra, pallet_structure, Structure);
list_benchmark!(list, extra, pallet_inflation, Inflation);
@@ -814,6 +815,7 @@
let params = (&config, &allowlist);
add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);
+ add_benchmark!(params, batches, pallet_common, Common);
add_benchmark!(params, batches, pallet_unique, Unique);
add_benchmark!(params, batches, pallet_structure, Structure);
add_benchmark!(params, batches, pallet_inflation, Inflation);
runtime/common/src/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/src/sponsoring.rs
+++ b/runtime/common/src/sponsoring.rs
@@ -29,8 +29,8 @@
use pallet_evm::account::CrossAccountId;
use pallet_unique::{
Call as UniqueCall, Config as UniqueConfig, FungibleApproveBasket, RefungibleApproveBasket,
- NftApproveBasket, CreateItemBasket, ReFungibleTransferBasket,
- FungibleTransferBasket, NftTransferBasket, TokenPropertyBasket,
+ NftApproveBasket, CreateItemBasket, ReFungibleTransferBasket, FungibleTransferBasket,
+ NftTransferBasket, TokenPropertyBasket,
};
use pallet_fungible::Config as FungibleConfig;
use pallet_nonfungible::Config as NonfungibleConfig;
@@ -247,7 +247,7 @@
&T::CrossAccountId::from_sub(who.clone()),
&token_id,
// No overflow may happen, as data larger than usize can't reach here
- properties.iter().map(|p| p.key.len() + p.value.len()).sum()
+ properties.iter().map(|p| p.key.len() + p.value.len()).sum(),
)
.map(|()| sponsor)
}
runtime/common/src/weights.rsdiffbeforeafterboth--- a/runtime/common/src/weights.rs
+++ b/runtime/common/src/weights.rs
@@ -21,7 +21,7 @@
use pallet_fungible::{Config as FungibleConfig, common::CommonWeights as FungibleWeights};
use pallet_nonfungible::{Config as NonfungibleConfig, common::CommonWeights as NonfungibleWeights};
use pallet_refungible::{Config as RefungibleConfig, common::CommonWeights as RefungibleWeights};
-use up_data_structs::CreateItemExData;
+use up_data_structs::{CreateItemExData, CreateItemData};
macro_rules! max_weight_of {
($method:ident ( $($args:tt)* )) => {
@@ -42,8 +42,8 @@
dispatch_weight::<T>() + max_weight_of!(create_item())
}
- fn create_multiple_items(amount: u32) -> Weight {
- dispatch_weight::<T>() + max_weight_of!(create_multiple_items(amount))
+ fn create_multiple_items(data: &[CreateItemData]) -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(create_multiple_items(data))
}
fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -875,6 +875,7 @@
}
impl pallet_common::Config for Runtime {
+ type WeightInfo = pallet_common::weights::SubstrateWeight<Self>;
type Event = Event;
type Currency = Balances;
type CollectionCreationPrice = CollectionCreationPrice;
runtime/tests/src/lib.rsdiffbeforeafterboth--- a/runtime/tests/src/lib.rs
+++ b/runtime/tests/src/lib.rs
@@ -212,6 +212,7 @@
}
impl pallet_common::Config for Test {
+ type WeightInfo = ();
type Event = ();
type Currency = Balances;
type CollectionCreationPrice = CollectionCreationPrice;
runtime/unique/Cargo.tomldiffbeforeafterboth--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -39,6 +39,7 @@
'pallet-xcm/runtime-benchmarks',
'sp-runtime/runtime-benchmarks',
'xcm-builder/runtime-benchmarks',
+ 'up-data-structs/runtime-benchmarks',
]
try-runtime = [
'frame-try-runtime',
runtime/unique/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.1819#![cfg_attr(not(feature = "std"), no_std)]20// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.21#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]24// Make the WASM binary available.25#[cfg(feature = "std")]26include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));2728use sp_api::impl_runtime_apis;29use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};30use sp_runtime::DispatchError;31// #[cfg(any(feature = "std", test))]32// pub use sp_runtime::BuildStorage;3334use sp_runtime::{35 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,36 traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},37 transaction_validity::{TransactionSource, TransactionValidity},38 ApplyExtrinsicResult, RuntimeAppPublic,39};4041use sp_std::prelude::*;4243#[cfg(feature = "std")]44use sp_version::NativeVersion;45use sp_version::RuntimeVersion;46pub use pallet_transaction_payment::{47 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,48};49// A few exports that help ease life for downstream crates.50pub use pallet_balances::Call as BalancesCall;51pub use pallet_evm::{52 EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,53};54pub use frame_support::{55 construct_runtime, match_types,56 dispatch::DispatchResult,57 PalletId, parameter_types, StorageValue, ConsensusEngineId,58 traits::{59 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,60 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,61 OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,62 },63 weights::{64 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},65 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,66 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,67 },68};69use unique_runtime_common::dispatch::{CollectionDispatchT, CollectionDispatch};70use up_data_structs::*;71// use pallet_contracts::weights::WeightInfo;72// #[cfg(any(feature = "std", test))]73use frame_system::{74 self as frame_system, EnsureRoot, EnsureSigned,75 limits::{BlockWeights, BlockLength},76};77use sp_arithmetic::{78 traits::{BaseArithmetic, Unsigned},79};80use smallvec::smallvec;81use codec::{Encode, Decode};82use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};83use fp_rpc::TransactionStatus;84use sp_runtime::{85 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},86 transaction_validity::TransactionValidityError,87 SaturatedConversion,88};8990// pub use pallet_timestamp::Call as TimestampCall;9192// Polkadot imports93use pallet_xcm::XcmPassthrough;94use polkadot_parachain::primitives::Sibling;95use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};96use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};97use xcm_builder::{98 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,99 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,100 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,101 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,102 ParentIsPreset,103};104use xcm_executor::{Config, XcmExecutor, Assets};105use sp_std::{marker::PhantomData};106107use xcm::latest::{108 // Xcm,109 AssetId::{Concrete},110 Fungibility::Fungible as XcmFungible,111 MultiAsset,112 Error as XcmError,113};114use xcm_executor::traits::{MatchesFungible, WeightTrader};115//use xcm_executor::traits::MatchesFungible;116use sp_runtime::traits::CheckedConversion;117118use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};119120pub const RUNTIME_NAME: &str = "unique";121pub const TOKEN_SYMBOL: &str = "UNQ";122123type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;124125impl RuntimeInstance for Runtime {126 type CrossAccountId = self::CrossAccountId;127128 type TransactionConverter = self::TransactionConverter;129130 fn get_transaction_converter() -> TransactionConverter {131 TransactionConverter132 }133}134135/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know136/// the specifics of the runtime. They can then be made to be agnostic over specific formats137/// of data like extrinsics, allowing for them to continue syncing the network through upgrades138/// to even the core data structures.139pub mod opaque {140 use sp_std::prelude::*;141 use sp_runtime::impl_opaque_keys;142 use super::Aura;143144 pub use unique_runtime_common::types::*;145146 impl_opaque_keys! {147 pub struct SessionKeys {148 pub aura: Aura,149 }150 }151}152153/// This runtime version.154pub const VERSION: RuntimeVersion = RuntimeVersion {155 spec_name: create_runtime_str!(RUNTIME_NAME),156 impl_name: create_runtime_str!(RUNTIME_NAME),157 authoring_version: 1,158 spec_version: 920000,159 impl_version: 0,160 apis: RUNTIME_API_VERSIONS,161 transaction_version: 1,162 state_version: 0,163};164165#[derive(codec::Encode, codec::Decode)]166pub enum XCMPMessage<XAccountId, XBalance> {167 /// Transfer tokens to the given account from the Parachain account.168 TransferToken(XAccountId, XBalance),169}170171/// The version information used to identify this runtime when compiled natively.172#[cfg(feature = "std")]173pub fn native_version() -> NativeVersion {174 NativeVersion {175 runtime_version: VERSION,176 can_author_with: Default::default(),177 }178}179180type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;181182pub struct DealWithFees;183impl OnUnbalanced<NegativeImbalance> for DealWithFees {184 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {185 if let Some(fees) = fees_then_tips.next() {186 // for fees, 100% to treasury187 let mut split = fees.ration(100, 0);188 if let Some(tips) = fees_then_tips.next() {189 // for tips, if any, 100% to treasury190 tips.ration_merge_into(100, 0, &mut split);191 }192 Treasury::on_unbalanced(split.0);193 // Author::on_unbalanced(split.1);194 }195 }196}197198parameter_types! {199 pub const BlockHashCount: BlockNumber = 2400;200 pub RuntimeBlockLength: BlockLength =201 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);202 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);203 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;204 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()205 .base_block(BlockExecutionWeight::get())206 .for_class(DispatchClass::all(), |weights| {207 weights.base_extrinsic = ExtrinsicBaseWeight::get();208 })209 .for_class(DispatchClass::Normal, |weights| {210 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);211 })212 .for_class(DispatchClass::Operational, |weights| {213 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);214 // Operational transactions have some extra reserved space, so that they215 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.216 weights.reserved = Some(217 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT218 );219 })220 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)221 .build_or_panic();222 pub const Version: RuntimeVersion = VERSION;223 pub const SS58Prefix: u16 = 7391;224}225226parameter_types! {227 pub const ChainId: u64 = 8880;228}229230pub struct FixedFee;231impl FeeCalculator for FixedFee {232 fn min_gas_price() -> U256 {233 MIN_GAS_PRICE.into()234 }235}236237// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case238// (contract, which only writes a lot of data),239// approximating on top of our real store write weight240parameter_types! {241 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;242 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;243 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();244}245246/// Limiting EVM execution to 50% of block for substrate users and management tasks247/// EVM transaction consumes more weight than substrate's, so we can't rely on them being248/// scheduled fairly249const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);250parameter_types! {251 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());252}253254pub enum FixedGasWeightMapping {}255impl GasWeightMapping for FixedGasWeightMapping {256 fn gas_to_weight(gas: u64) -> Weight {257 gas.saturating_mul(WeightPerGas::get())258 }259 fn weight_to_gas(weight: Weight) -> u64 {260 weight / WeightPerGas::get()261 }262}263264impl pallet_evm::Config for Runtime {265 type BlockGasLimit = BlockGasLimit;266 type FeeCalculator = FixedFee;267 type GasWeightMapping = FixedGasWeightMapping;268 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;269 type CallOrigin = EnsureAddressTruncated<Self>;270 type WithdrawOrigin = EnsureAddressTruncated<Self>;271 type AddressMapping = HashedAddressMapping<Self::Hashing>;272 type PrecompilesType = ();273 type PrecompilesValue = ();274 type Currency = Balances;275 type Event = Event;276 type OnMethodCall = (277 pallet_evm_migration::OnMethodCall<Self>,278 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,279 CollectionDispatchT<Self>,280 );281 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;282 type ChainId = ChainId;283 type Runner = pallet_evm::runner::stack::Runner<Self>;284 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;285 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;286 type FindAuthor = EthereumFindAuthor<Aura>;287}288289impl pallet_evm_migration::Config for Runtime {290 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;291}292293pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);294impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {295 fn find_author<'a, I>(digests: I) -> Option<H160>296 where297 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,298 {299 if let Some(author_index) = F::find_author(digests) {300 let authority_id = Aura::authorities()[author_index as usize].clone();301 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));302 }303 None304 }305}306307impl pallet_ethereum::Config for Runtime {308 type Event = Event;309 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;310}311312impl pallet_randomness_collective_flip::Config for Runtime {}313314impl frame_system::Config for Runtime {315 /// The data to be stored in an account.316 type AccountData = pallet_balances::AccountData<Balance>;317 /// The identifier used to distinguish between accounts.318 type AccountId = AccountId;319 /// The basic call filter to use in dispatchable.320 type BaseCallFilter = Everything;321 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).322 type BlockHashCount = BlockHashCount;323 /// The maximum length of a block (in bytes).324 type BlockLength = RuntimeBlockLength;325 /// The index type for blocks.326 type BlockNumber = BlockNumber;327 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.328 type BlockWeights = RuntimeBlockWeights;329 /// The aggregated dispatch type that is available for extrinsics.330 type Call = Call;331 /// The weight of database operations that the runtime can invoke.332 type DbWeight = RocksDbWeight;333 /// The ubiquitous event type.334 type Event = Event;335 /// The type for hashing blocks and tries.336 type Hash = Hash;337 /// The hashing algorithm used.338 type Hashing = BlakeTwo256;339 /// The header type.340 type Header = generic::Header<BlockNumber, BlakeTwo256>;341 /// The index type for storing how many extrinsics an account has signed.342 type Index = Index;343 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.344 type Lookup = AccountIdLookup<AccountId, ()>;345 /// What to do if an account is fully reaped from the system.346 type OnKilledAccount = ();347 /// What to do if a new account is created.348 type OnNewAccount = ();349 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;350 /// The ubiquitous origin type.351 type Origin = Origin;352 /// This type is being generated by `construct_runtime!`.353 type PalletInfo = PalletInfo;354 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.355 type SS58Prefix = SS58Prefix;356 /// Weight information for the extrinsics of this pallet.357 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;358 /// Version of the runtime.359 type Version = Version;360 type MaxConsumers = ConstU32<16>;361}362363parameter_types! {364 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;365}366367impl pallet_timestamp::Config for Runtime {368 /// A timestamp: milliseconds since the unix epoch.369 type Moment = u64;370 type OnTimestampSet = ();371 type MinimumPeriod = MinimumPeriod;372 type WeightInfo = ();373}374375parameter_types! {376 // pub const ExistentialDeposit: u128 = 500;377 pub const ExistentialDeposit: u128 = 0;378 pub const MaxLocks: u32 = 50;379}380381impl pallet_balances::Config for Runtime {382 type MaxLocks = MaxLocks;383 type MaxReserves = ();384 type ReserveIdentifier = [u8; 8];385 /// The type for recording an account's balance.386 type Balance = Balance;387 /// The ubiquitous event type.388 type Event = Event;389 type DustRemoval = Treasury;390 type ExistentialDeposit = ExistentialDeposit;391 type AccountStore = System;392 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;393}394395pub const fn deposit(items: u32, bytes: u32) -> Balance {396 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE397}398399/*400parameter_types! {401 pub TombstoneDeposit: Balance = deposit(402 1,403 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,404 );405 pub DepositPerContract: Balance = TombstoneDeposit::get();406 pub const DepositPerStorageByte: Balance = deposit(0, 1);407 pub const DepositPerStorageItem: Balance = deposit(1, 0);408 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);409 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;410 pub const SignedClaimHandicap: u32 = 2;411 pub const MaxDepth: u32 = 32;412 pub const MaxValueSize: u32 = 16 * 1024;413 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb414 // The lazy deletion runs inside on_initialize.415 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *416 RuntimeBlockWeights::get().max_block;417 // The weight needed for decoding the queue should be less or equal than a fifth418 // of the overall weight dedicated to the lazy deletion.419 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (420 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -421 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)422 )) / 5) as u32;423 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();424}425426impl pallet_contracts::Config for Runtime {427 type Time = Timestamp;428 type Randomness = RandomnessCollectiveFlip;429 type Currency = Balances;430 type Event = Event;431 type RentPayment = ();432 type SignedClaimHandicap = SignedClaimHandicap;433 type TombstoneDeposit = TombstoneDeposit;434 type DepositPerContract = DepositPerContract;435 type DepositPerStorageByte = DepositPerStorageByte;436 type DepositPerStorageItem = DepositPerStorageItem;437 type RentFraction = RentFraction;438 type SurchargeReward = SurchargeReward;439 type WeightPrice = pallet_transaction_payment::Pallet<Self>;440 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;441 type ChainExtension = NFTExtension;442 type DeletionQueueDepth = DeletionQueueDepth;443 type DeletionWeightLimit = DeletionWeightLimit;444 type Schedule = Schedule;445 type CallStack = [pallet_contracts::Frame<Self>; 31];446}447*/448449parameter_types! {450 /// This value increases the priority of `Operational` transactions by adding451 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.452 pub const OperationalFeeMultiplier: u8 = 5;453}454455/// Linear implementor of `WeightToFeePolynomial`456pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);457458impl<T> WeightToFeePolynomial for LinearFee<T>459where460 T: BaseArithmetic + From<u32> + Copy + Unsigned,461{462 type Balance = T;463464 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {465 smallvec!(WeightToFeeCoefficient {466 // Targeting 0.1 Unique per NFT transfer467 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),468 coeff_frac: Perbill::zero(),469 negative: false,470 degree: 1,471 })472 }473}474475impl pallet_transaction_payment::Config for Runtime {476 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;477 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;478 type OperationalFeeMultiplier = OperationalFeeMultiplier;479 type WeightToFee = LinearFee<Balance>;480 type FeeMultiplierUpdate = ();481}482483parameter_types! {484 pub const ProposalBond: Permill = Permill::from_percent(5);485 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;486 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;487 pub const SpendPeriod: BlockNumber = 5 * MINUTES;488 pub const Burn: Permill = Permill::from_percent(0);489 pub const TipCountdown: BlockNumber = 1 * DAYS;490 pub const TipFindersFee: Percent = Percent::from_percent(20);491 pub const TipReportDepositBase: Balance = 1 * UNIQUE;492 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;493 pub const BountyDepositBase: Balance = 1 * UNIQUE;494 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;495 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");496 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;497 pub const MaximumReasonLength: u32 = 16384;498 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);499 pub const BountyValueMinimum: Balance = 5 * UNIQUE;500 pub const MaxApprovals: u32 = 100;501}502503impl pallet_treasury::Config for Runtime {504 type PalletId = TreasuryModuleId;505 type Currency = Balances;506 type ApproveOrigin = EnsureRoot<AccountId>;507 type RejectOrigin = EnsureRoot<AccountId>;508 type Event = Event;509 type OnSlash = ();510 type ProposalBond = ProposalBond;511 type ProposalBondMinimum = ProposalBondMinimum;512 type ProposalBondMaximum = ProposalBondMaximum;513 type SpendPeriod = SpendPeriod;514 type Burn = Burn;515 type BurnDestination = ();516 type SpendFunds = ();517 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;518 type MaxApprovals = MaxApprovals;519}520521impl pallet_sudo::Config for Runtime {522 type Event = Event;523 type Call = Call;524}525526pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);527528impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider529 for RelayChainBlockNumberProvider<T>530{531 type BlockNumber = BlockNumber;532533 fn current_block_number() -> Self::BlockNumber {534 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()535 .map(|d| d.relay_parent_number)536 .unwrap_or_default()537 }538}539540parameter_types! {541 pub const MinVestedTransfer: Balance = 10 * UNIQUE;542 pub const MaxVestingSchedules: u32 = 28;543}544545impl orml_vesting::Config for Runtime {546 type Event = Event;547 type Currency = pallet_balances::Pallet<Runtime>;548 type MinVestedTransfer = MinVestedTransfer;549 type VestedTransferOrigin = EnsureSigned<AccountId>;550 type WeightInfo = ();551 type MaxVestingSchedules = MaxVestingSchedules;552 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;553}554555parameter_types! {556 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;557 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;558}559560impl cumulus_pallet_parachain_system::Config for Runtime {561 type Event = Event;562 type SelfParaId = parachain_info::Pallet<Self>;563 type OnSystemEvent = ();564 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<565 // MaxDownwardMessageWeight,566 // XcmExecutor<XcmConfig>,567 // Call,568 // >;569 type OutboundXcmpMessageSource = XcmpQueue;570 type DmpMessageHandler = DmpQueue;571 type ReservedDmpWeight = ReservedDmpWeight;572 type ReservedXcmpWeight = ReservedXcmpWeight;573 type XcmpMessageHandler = XcmpQueue;574}575576impl parachain_info::Config for Runtime {}577578impl cumulus_pallet_aura_ext::Config for Runtime {}579580parameter_types! {581 pub const RelayLocation: MultiLocation = MultiLocation::parent();582 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;583 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();584 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();585}586587/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used588/// when determining ownership of accounts for asset transacting and when attempting to use XCM589/// `Transact` in order to determine the dispatch Origin.590pub type LocationToAccountId = (591 // The parent (Relay-chain) origin converts to the default `AccountId`.592 ParentIsPreset<AccountId>,593 // Sibling parachain origins convert to AccountId via the `ParaId::into`.594 SiblingParachainConvertsVia<Sibling, AccountId>,595 // Straight up local `AccountId32` origins just alias directly to `AccountId`.596 AccountId32Aliases<RelayNetwork, AccountId>,597);598599pub struct OnlySelfCurrency;600impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {601 fn matches_fungible(a: &MultiAsset) -> Option<B> {602 match (&a.id, &a.fun) {603 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),604 _ => None,605 }606 }607}608609/// Means for transacting assets on this chain.610pub type LocalAssetTransactor = CurrencyAdapter<611 // Use this currency:612 Balances,613 // Use this currency when it is a fungible asset matching the given location or name:614 OnlySelfCurrency,615 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:616 LocationToAccountId,617 // Our chain's account ID type (we can't get away without mentioning it explicitly):618 AccountId,619 // We don't track any teleports.620 (),621>;622623/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,624/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can625/// biases the kind of local `Origin` it will become.626pub type XcmOriginToTransactDispatchOrigin = (627 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location628 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for629 // foreign chains who want to have a local sovereign account on this chain which they control.630 SovereignSignedViaLocation<LocationToAccountId, Origin>,631 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when632 // recognised.633 RelayChainAsNative<RelayOrigin, Origin>,634 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when635 // recognised.636 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,637 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a638 // transaction from the Root origin.639 ParentAsSuperuser<Origin>,640 // Native signed account converter; this just converts an `AccountId32` origin into a normal641 // `Origin::Signed` origin of the same 32-byte value.642 SignedAccountId32AsNative<RelayNetwork, Origin>,643 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.644 XcmPassthrough<Origin>,645);646647parameter_types! {648 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.649 pub UnitWeightCost: Weight = 1_000_000;650 // 1200 UNIQUEs buy 1 second of weight.651 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);652 pub const MaxInstructions: u32 = 100;653 pub const MaxAuthorities: u32 = 100_000;654}655656match_types! {657 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {658 MultiLocation { parents: 1, interior: Here } |659 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }660 };661}662663pub type Barrier = (664 TakeWeightCredit,665 AllowTopLevelPaidExecutionFrom<Everything>,666 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,667 // ^^^ Parent & its unit plurality gets free execution668);669670pub struct UsingOnlySelfCurrencyComponents<671 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,672 AssetId: Get<MultiLocation>,673 AccountId,674 Currency: CurrencyT<AccountId>,675 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,676>(677 Weight,678 Currency::Balance,679 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,680);681impl<682 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,683 AssetId: Get<MultiLocation>,684 AccountId,685 Currency: CurrencyT<AccountId>,686 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,687 > WeightTrader688 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>689{690 fn new() -> Self {691 Self(0, Zero::zero(), PhantomData)692 }693694 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {695 let amount = WeightToFee::calc(&weight);696 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;697698 // location to this parachain through relay chain699 let option1: xcm::v1::AssetId = Concrete(MultiLocation {700 parents: 1,701 interior: X1(Parachain(ParachainInfo::parachain_id().into())),702 });703 // direct location704 let option2: xcm::v1::AssetId = Concrete(MultiLocation {705 parents: 0,706 interior: Here,707 });708709 let required = if payment.fungible.contains_key(&option1) {710 (option1, u128_amount).into()711 } else if payment.fungible.contains_key(&option2) {712 (option2, u128_amount).into()713 } else {714 (Concrete(MultiLocation::default()), u128_amount).into()715 };716717 let unused = payment718 .checked_sub(required)719 .map_err(|_| XcmError::TooExpensive)?;720 self.0 = self.0.saturating_add(weight);721 self.1 = self.1.saturating_add(amount);722 Ok(unused)723 }724725 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {726 let weight = weight.min(self.0);727 let amount = WeightToFee::calc(&weight);728 self.0 -= weight;729 self.1 = self.1.saturating_sub(amount);730 let amount: u128 = amount.saturated_into();731 if amount > 0 {732 Some((AssetId::get(), amount).into())733 } else {734 None735 }736 }737}738impl<739 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,740 AssetId: Get<MultiLocation>,741 AccountId,742 Currency: CurrencyT<AccountId>,743 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,744 > Drop745 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>746{747 fn drop(&mut self) {748 OnUnbalanced::on_unbalanced(Currency::issue(self.1));749 }750}751752pub struct XcmConfig;753impl Config for XcmConfig {754 type Call = Call;755 type XcmSender = XcmRouter;756 // How to withdraw and deposit an asset.757 type AssetTransactor = LocalAssetTransactor;758 type OriginConverter = XcmOriginToTransactDispatchOrigin;759 type IsReserve = NativeAsset;760 type IsTeleporter = (); // Teleportation is disabled761 type LocationInverter = LocationInverter<Ancestry>;762 type Barrier = Barrier;763 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;764 type Trader = UsingOnlySelfCurrencyComponents<765 IdentityFee<Balance>,766 RelayLocation,767 AccountId,768 Balances,769 (),770 >;771 type ResponseHandler = (); // Don't handle responses for now.772 type SubscriptionService = PolkadotXcm;773774 type AssetTrap = PolkadotXcm;775 type AssetClaims = PolkadotXcm;776}777778// parameter_types! {779// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;780// }781782/// No local origins on this chain are allowed to dispatch XCM sends/executions.783pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);784785/// The means for routing XCM messages which are not for local execution into the right message786/// queues.787pub type XcmRouter = (788 // Two routers - use UMP to communicate with the relay chain:789 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,790 // ..and XCMP to communicate with the sibling chains.791 XcmpQueue,792);793794impl pallet_evm_coder_substrate::Config for Runtime {795 type GasWeightMapping = FixedGasWeightMapping;796}797798impl pallet_xcm::Config for Runtime {799 type Event = Event;800 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;801 type XcmRouter = XcmRouter;802 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;803 type XcmExecuteFilter = Everything;804 type XcmExecutor = XcmExecutor<XcmConfig>;805 type XcmTeleportFilter = Everything;806 type XcmReserveTransferFilter = Everything;807 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;808 type LocationInverter = LocationInverter<Ancestry>;809 type Origin = Origin;810 type Call = Call;811 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;812 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;813}814815impl cumulus_pallet_xcm::Config for Runtime {816 type Event = Event;817 type XcmExecutor = XcmExecutor<XcmConfig>;818}819820impl cumulus_pallet_xcmp_queue::Config for Runtime {821 type WeightInfo = ();822 type Event = Event;823 type XcmExecutor = XcmExecutor<XcmConfig>;824 type ChannelInfo = ParachainSystem;825 type VersionWrapper = ();826 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;827 type ControllerOrigin = EnsureRoot<AccountId>;828 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;829}830831impl cumulus_pallet_dmp_queue::Config for Runtime {832 type Event = Event;833 type XcmExecutor = XcmExecutor<XcmConfig>;834 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;835}836837impl pallet_aura::Config for Runtime {838 type AuthorityId = AuraId;839 type DisabledValidators = ();840 type MaxAuthorities = MaxAuthorities;841}842843parameter_types! {844 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();845 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;846}847848impl pallet_common::Config for Runtime {849 type Event = Event;850 type Currency = Balances;851 type CollectionCreationPrice = CollectionCreationPrice;852 type TreasuryAccountId = TreasuryAccountId;853 type CollectionDispatch = CollectionDispatchT<Self>;854855 type EvmTokenAddressMapping = EvmTokenAddressMapping;856 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;857}858859impl pallet_structure::Config for Runtime {860 type Event = Event;861 type Call = Call;862 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;863}864865impl pallet_evm::account::Config for Runtime {866 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;867 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;868 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;869}870871impl pallet_fungible::Config for Runtime {872 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;873}874impl pallet_refungible::Config for Runtime {875 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;876}877impl pallet_nonfungible::Config for Runtime {878 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;879}880881impl pallet_unique::Config for Runtime {882 type Event = Event;883 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;884}885886parameter_types! {887 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied888}889890/// Used for the pallet inflation891impl pallet_inflation::Config for Runtime {892 type Currency = Balances;893 type TreasuryAccountId = TreasuryAccountId;894 type InflationBlockInterval = InflationBlockInterval;895 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;896}897898// parameter_types! {899// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *900// RuntimeBlockWeights::get().max_block;901// pub const MaxScheduledPerBlock: u32 = 50;902// }903904type EvmSponsorshipHandler = (905 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,906 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,907);908type SponsorshipHandler = (909 pallet_unique::UniqueSponsorshipHandler<Runtime>,910 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,911 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,912);913914// impl pallet_unq_scheduler::Config for Runtime {915// type Event = Event;916// type Origin = Origin;917// type PalletsOrigin = OriginCaller;918// type Call = Call;919// type MaximumWeight = MaximumSchedulerWeight;920// type ScheduleOrigin = EnsureSigned<AccountId>;921// type MaxScheduledPerBlock = MaxScheduledPerBlock;922// type SponsorshipHandler = SponsorshipHandler;923// type WeightInfo = ();924// }925926impl pallet_evm_transaction_payment::Config for Runtime {927 type EvmSponsorshipHandler = EvmSponsorshipHandler;928 type Currency = Balances;929}930931impl pallet_charge_transaction::Config for Runtime {932 type SponsorshipHandler = SponsorshipHandler;933}934935// impl pallet_contract_helpers::Config for Runtime {936// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;937// }938939parameter_types! {940 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049941 pub const HelpersContractAddress: H160 = H160([942 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,943 ]);944}945946impl pallet_evm_contract_helpers::Config for Runtime {947 type ContractAddress = HelpersContractAddress;948 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;949}950951construct_runtime!(952 pub enum Runtime where953 Block = Block,954 NodeBlock = opaque::Block,955 UncheckedExtrinsic = UncheckedExtrinsic956 {957 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,958 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,959960 Aura: pallet_aura::{Pallet, Config<T>} = 22,961 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,962963 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,964 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,965 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,966 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,967 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,968 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,969 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,970 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,971 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,972 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,973974 // XCM helpers.975 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,976 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,977 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,978 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,979980 // Unique Pallets981 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,982 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,983 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,984 // free = 63985 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,986 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,987 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,988 Fungible: pallet_fungible::{Pallet, Storage} = 67,989 Refungible: pallet_refungible::{Pallet, Storage} = 68,990 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,991 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,992993 // Frontier994 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,995 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,996997 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,998 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,999 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1000 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1001 }1002);10031004pub struct TransactionConverter;10051006impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1007 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1008 UncheckedExtrinsic::new_unsigned(1009 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1010 )1011 }1012}10131014impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1015 fn convert_transaction(1016 &self,1017 transaction: pallet_ethereum::Transaction,1018 ) -> opaque::UncheckedExtrinsic {1019 let extrinsic = UncheckedExtrinsic::new_unsigned(1020 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1021 );1022 let encoded = extrinsic.encode();1023 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1024 .expect("Encoded extrinsic is always valid")1025 }1026}10271028/// The address format for describing accounts.1029pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1030/// Block header type as expected by this runtime.1031pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1032/// Block type as expected by this runtime.1033pub type Block = generic::Block<Header, UncheckedExtrinsic>;1034/// A Block signed with a Justification1035pub type SignedBlock = generic::SignedBlock<Block>;1036/// BlockId type as expected by this runtime.1037pub type BlockId = generic::BlockId<Block>;1038/// The SignedExtension to the basic transaction logic.1039pub type SignedExtra = (1040 frame_system::CheckSpecVersion<Runtime>,1041 // system::CheckTxVersion<Runtime>,1042 frame_system::CheckGenesis<Runtime>,1043 frame_system::CheckEra<Runtime>,1044 frame_system::CheckNonce<Runtime>,1045 frame_system::CheckWeight<Runtime>,1046 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1047 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1048 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1049);1050/// Unchecked extrinsic type as expected by this runtime.1051pub type UncheckedExtrinsic =1052 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1053/// Extrinsic type that has already been checked.1054pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1055/// Executive: handles dispatch to the various modules.1056pub type Executive = frame_executive::Executive<1057 Runtime,1058 Block,1059 frame_system::ChainContext<Runtime>,1060 Runtime,1061 AllPalletsReversedWithSystemFirst,1062>;10631064impl_opaque_keys! {1065 pub struct SessionKeys {1066 pub aura: Aura,1067 }1068}10691070impl fp_self_contained::SelfContainedCall for Call {1071 type SignedInfo = H160;10721073 fn is_self_contained(&self) -> bool {1074 match self {1075 Call::Ethereum(call) => call.is_self_contained(),1076 _ => false,1077 }1078 }10791080 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1081 match self {1082 Call::Ethereum(call) => call.check_self_contained(),1083 _ => None,1084 }1085 }10861087 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1088 match self {1089 Call::Ethereum(call) => call.validate_self_contained(info),1090 _ => None,1091 }1092 }10931094 fn pre_dispatch_self_contained(1095 &self,1096 info: &Self::SignedInfo,1097 ) -> Option<Result<(), TransactionValidityError>> {1098 match self {1099 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1100 _ => None,1101 }1102 }11031104 fn apply_self_contained(1105 self,1106 info: Self::SignedInfo,1107 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1108 match self {1109 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1110 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1111 )),1112 _ => None,1113 }1114 }1115}11161117macro_rules! dispatch_unique_runtime {1118 ($collection:ident.$method:ident($($name:ident),*)) => {{1119 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1120 let dispatch = collection.as_dyn();11211122 Ok(dispatch.$method($($name),*))1123 }};1124}11251126impl_common_runtime_apis!();11271128struct CheckInherents;11291130impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1131 fn check_inherents(1132 block: &Block,1133 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1134 ) -> sp_inherents::CheckInherentsResult {1135 let relay_chain_slot = relay_state_proof1136 .read_slot()1137 .expect("Could not read the relay chain slot from the proof");11381139 let inherent_data =1140 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1141 relay_chain_slot,1142 sp_std::time::Duration::from_secs(6),1143 )1144 .create_inherent_data()1145 .expect("Could not create the timestamp inherent data");11461147 inherent_data.check_extrinsics(block)1148 }1149}11501151cumulus_pallet_parachain_system::register_validate_block!(1152 Runtime = Runtime,1153 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1154 CheckInherents = CheckInherents,1155);1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.1819#![cfg_attr(not(feature = "std"), no_std)]20// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.21#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]24// Make the WASM binary available.25#[cfg(feature = "std")]26include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));2728use sp_api::impl_runtime_apis;29use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};30use sp_runtime::DispatchError;31// #[cfg(any(feature = "std", test))]32// pub use sp_runtime::BuildStorage;3334use sp_runtime::{35 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,36 traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},37 transaction_validity::{TransactionSource, TransactionValidity},38 ApplyExtrinsicResult, RuntimeAppPublic,39};4041use sp_std::prelude::*;4243#[cfg(feature = "std")]44use sp_version::NativeVersion;45use sp_version::RuntimeVersion;46pub use pallet_transaction_payment::{47 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,48};49// A few exports that help ease life for downstream crates.50pub use pallet_balances::Call as BalancesCall;51pub use pallet_evm::{52 EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,53};54pub use frame_support::{55 construct_runtime, match_types,56 dispatch::DispatchResult,57 PalletId, parameter_types, StorageValue, ConsensusEngineId,58 traits::{59 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,60 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,61 OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,62 },63 weights::{64 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},65 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,66 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,67 },68};69use unique_runtime_common::{70 dispatch::{CollectionDispatchT, CollectionDispatch},71 weights::CommonWeights,72 sponsoring::UniqueSponsorshipHandler,73 eth_sponsoring::UniqueEthSponsorshipHandler,74};75use up_data_structs::*;76// use pallet_contracts::weights::WeightInfo;77// #[cfg(any(feature = "std", test))]78use frame_system::{79 self as frame_system, EnsureRoot, EnsureSigned,80 limits::{BlockWeights, BlockLength},81};82use sp_arithmetic::{83 traits::{BaseArithmetic, Unsigned},84};85use smallvec::smallvec;86use codec::{Encode, Decode};87use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};88use fp_rpc::TransactionStatus;89use sp_runtime::{90 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},91 transaction_validity::TransactionValidityError,92 SaturatedConversion,93};9495// pub use pallet_timestamp::Call as TimestampCall;9697// Polkadot imports98use pallet_xcm::XcmPassthrough;99use polkadot_parachain::primitives::Sibling;100use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};101use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};102use xcm_builder::{103 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,104 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,105 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,106 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,107 ParentIsPreset,108};109use xcm_executor::{Config, XcmExecutor, Assets};110use sp_std::{marker::PhantomData};111112use xcm::latest::{113 // Xcm,114 AssetId::{Concrete},115 Fungibility::Fungible as XcmFungible,116 MultiAsset,117 Error as XcmError,118};119use xcm_executor::traits::{MatchesFungible, WeightTrader};120//use xcm_executor::traits::MatchesFungible;121use sp_runtime::traits::CheckedConversion;122123use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};124125pub const RUNTIME_NAME: &str = "unique";126pub const TOKEN_SYMBOL: &str = "UNQ";127128type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;129130impl RuntimeInstance for Runtime {131 type CrossAccountId = self::CrossAccountId;132133 type TransactionConverter = self::TransactionConverter;134135 fn get_transaction_converter() -> TransactionConverter {136 TransactionConverter137 }138}139140/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know141/// the specifics of the runtime. They can then be made to be agnostic over specific formats142/// of data like extrinsics, allowing for them to continue syncing the network through upgrades143/// to even the core data structures.144pub mod opaque {145 use sp_std::prelude::*;146 use sp_runtime::impl_opaque_keys;147 use super::Aura;148149 pub use unique_runtime_common::types::*;150151 impl_opaque_keys! {152 pub struct SessionKeys {153 pub aura: Aura,154 }155 }156}157158/// This runtime version.159pub const VERSION: RuntimeVersion = RuntimeVersion {160 spec_name: create_runtime_str!(RUNTIME_NAME),161 impl_name: create_runtime_str!(RUNTIME_NAME),162 authoring_version: 1,163 spec_version: 920000,164 impl_version: 0,165 apis: RUNTIME_API_VERSIONS,166 transaction_version: 1,167 state_version: 0,168};169170#[derive(codec::Encode, codec::Decode)]171pub enum XCMPMessage<XAccountId, XBalance> {172 /// Transfer tokens to the given account from the Parachain account.173 TransferToken(XAccountId, XBalance),174}175176/// The version information used to identify this runtime when compiled natively.177#[cfg(feature = "std")]178pub fn native_version() -> NativeVersion {179 NativeVersion {180 runtime_version: VERSION,181 can_author_with: Default::default(),182 }183}184185type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;186187pub struct DealWithFees;188impl OnUnbalanced<NegativeImbalance> for DealWithFees {189 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {190 if let Some(fees) = fees_then_tips.next() {191 // for fees, 100% to treasury192 let mut split = fees.ration(100, 0);193 if let Some(tips) = fees_then_tips.next() {194 // for tips, if any, 100% to treasury195 tips.ration_merge_into(100, 0, &mut split);196 }197 Treasury::on_unbalanced(split.0);198 // Author::on_unbalanced(split.1);199 }200 }201}202203parameter_types! {204 pub const BlockHashCount: BlockNumber = 2400;205 pub RuntimeBlockLength: BlockLength =206 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);207 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);208 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;209 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()210 .base_block(BlockExecutionWeight::get())211 .for_class(DispatchClass::all(), |weights| {212 weights.base_extrinsic = ExtrinsicBaseWeight::get();213 })214 .for_class(DispatchClass::Normal, |weights| {215 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);216 })217 .for_class(DispatchClass::Operational, |weights| {218 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);219 // Operational transactions have some extra reserved space, so that they220 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.221 weights.reserved = Some(222 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT223 );224 })225 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)226 .build_or_panic();227 pub const Version: RuntimeVersion = VERSION;228 pub const SS58Prefix: u16 = 7391;229}230231parameter_types! {232 pub const ChainId: u64 = 8880;233}234235pub struct FixedFee;236impl FeeCalculator for FixedFee {237 fn min_gas_price() -> U256 {238 MIN_GAS_PRICE.into()239 }240}241242// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case243// (contract, which only writes a lot of data),244// approximating on top of our real store write weight245parameter_types! {246 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;247 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;248 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();249}250251/// Limiting EVM execution to 50% of block for substrate users and management tasks252/// EVM transaction consumes more weight than substrate's, so we can't rely on them being253/// scheduled fairly254const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);255parameter_types! {256 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());257}258259pub enum FixedGasWeightMapping {}260impl GasWeightMapping for FixedGasWeightMapping {261 fn gas_to_weight(gas: u64) -> Weight {262 gas.saturating_mul(WeightPerGas::get())263 }264 fn weight_to_gas(weight: Weight) -> u64 {265 weight / WeightPerGas::get()266 }267}268269impl pallet_evm::Config for Runtime {270 type BlockGasLimit = BlockGasLimit;271 type FeeCalculator = FixedFee;272 type GasWeightMapping = FixedGasWeightMapping;273 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;274 type CallOrigin = EnsureAddressTruncated<Self>;275 type WithdrawOrigin = EnsureAddressTruncated<Self>;276 type AddressMapping = HashedAddressMapping<Self::Hashing>;277 type PrecompilesType = ();278 type PrecompilesValue = ();279 type Currency = Balances;280 type Event = Event;281 type OnMethodCall = (282 pallet_evm_migration::OnMethodCall<Self>,283 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,284 CollectionDispatchT<Self>,285 );286 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;287 type ChainId = ChainId;288 type Runner = pallet_evm::runner::stack::Runner<Self>;289 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;290 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;291 type FindAuthor = EthereumFindAuthor<Aura>;292}293294impl pallet_evm_migration::Config for Runtime {295 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;296}297298pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);299impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {300 fn find_author<'a, I>(digests: I) -> Option<H160>301 where302 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,303 {304 if let Some(author_index) = F::find_author(digests) {305 let authority_id = Aura::authorities()[author_index as usize].clone();306 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));307 }308 None309 }310}311312impl pallet_ethereum::Config for Runtime {313 type Event = Event;314 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;315}316317impl pallet_randomness_collective_flip::Config for Runtime {}318319impl frame_system::Config for Runtime {320 /// The data to be stored in an account.321 type AccountData = pallet_balances::AccountData<Balance>;322 /// The identifier used to distinguish between accounts.323 type AccountId = AccountId;324 /// The basic call filter to use in dispatchable.325 type BaseCallFilter = Everything;326 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).327 type BlockHashCount = BlockHashCount;328 /// The maximum length of a block (in bytes).329 type BlockLength = RuntimeBlockLength;330 /// The index type for blocks.331 type BlockNumber = BlockNumber;332 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.333 type BlockWeights = RuntimeBlockWeights;334 /// The aggregated dispatch type that is available for extrinsics.335 type Call = Call;336 /// The weight of database operations that the runtime can invoke.337 type DbWeight = RocksDbWeight;338 /// The ubiquitous event type.339 type Event = Event;340 /// The type for hashing blocks and tries.341 type Hash = Hash;342 /// The hashing algorithm used.343 type Hashing = BlakeTwo256;344 /// The header type.345 type Header = generic::Header<BlockNumber, BlakeTwo256>;346 /// The index type for storing how many extrinsics an account has signed.347 type Index = Index;348 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.349 type Lookup = AccountIdLookup<AccountId, ()>;350 /// What to do if an account is fully reaped from the system.351 type OnKilledAccount = ();352 /// What to do if a new account is created.353 type OnNewAccount = ();354 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;355 /// The ubiquitous origin type.356 type Origin = Origin;357 /// This type is being generated by `construct_runtime!`.358 type PalletInfo = PalletInfo;359 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.360 type SS58Prefix = SS58Prefix;361 /// Weight information for the extrinsics of this pallet.362 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;363 /// Version of the runtime.364 type Version = Version;365 type MaxConsumers = ConstU32<16>;366}367368parameter_types! {369 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;370}371372impl pallet_timestamp::Config for Runtime {373 /// A timestamp: milliseconds since the unix epoch.374 type Moment = u64;375 type OnTimestampSet = ();376 type MinimumPeriod = MinimumPeriod;377 type WeightInfo = ();378}379380parameter_types! {381 // pub const ExistentialDeposit: u128 = 500;382 pub const ExistentialDeposit: u128 = 0;383 pub const MaxLocks: u32 = 50;384}385386impl pallet_balances::Config for Runtime {387 type MaxLocks = MaxLocks;388 type MaxReserves = ();389 type ReserveIdentifier = [u8; 8];390 /// The type for recording an account's balance.391 type Balance = Balance;392 /// The ubiquitous event type.393 type Event = Event;394 type DustRemoval = Treasury;395 type ExistentialDeposit = ExistentialDeposit;396 type AccountStore = System;397 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;398}399400pub const fn deposit(items: u32, bytes: u32) -> Balance {401 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE402}403404/*405parameter_types! {406 pub TombstoneDeposit: Balance = deposit(407 1,408 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,409 );410 pub DepositPerContract: Balance = TombstoneDeposit::get();411 pub const DepositPerStorageByte: Balance = deposit(0, 1);412 pub const DepositPerStorageItem: Balance = deposit(1, 0);413 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);414 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;415 pub const SignedClaimHandicap: u32 = 2;416 pub const MaxDepth: u32 = 32;417 pub const MaxValueSize: u32 = 16 * 1024;418 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb419 // The lazy deletion runs inside on_initialize.420 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *421 RuntimeBlockWeights::get().max_block;422 // The weight needed for decoding the queue should be less or equal than a fifth423 // of the overall weight dedicated to the lazy deletion.424 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (425 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -426 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)427 )) / 5) as u32;428 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();429}430431impl pallet_contracts::Config for Runtime {432 type Time = Timestamp;433 type Randomness = RandomnessCollectiveFlip;434 type Currency = Balances;435 type Event = Event;436 type RentPayment = ();437 type SignedClaimHandicap = SignedClaimHandicap;438 type TombstoneDeposit = TombstoneDeposit;439 type DepositPerContract = DepositPerContract;440 type DepositPerStorageByte = DepositPerStorageByte;441 type DepositPerStorageItem = DepositPerStorageItem;442 type RentFraction = RentFraction;443 type SurchargeReward = SurchargeReward;444 type WeightPrice = pallet_transaction_payment::Pallet<Self>;445 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;446 type ChainExtension = NFTExtension;447 type DeletionQueueDepth = DeletionQueueDepth;448 type DeletionWeightLimit = DeletionWeightLimit;449 type Schedule = Schedule;450 type CallStack = [pallet_contracts::Frame<Self>; 31];451}452*/453454parameter_types! {455 /// This value increases the priority of `Operational` transactions by adding456 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.457 pub const OperationalFeeMultiplier: u8 = 5;458}459460/// Linear implementor of `WeightToFeePolynomial`461pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);462463impl<T> WeightToFeePolynomial for LinearFee<T>464where465 T: BaseArithmetic + From<u32> + Copy + Unsigned,466{467 type Balance = T;468469 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {470 smallvec!(WeightToFeeCoefficient {471 // Targeting 0.1 Unique per NFT transfer472 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),473 coeff_frac: Perbill::zero(),474 negative: false,475 degree: 1,476 })477 }478}479480impl pallet_transaction_payment::Config for Runtime {481 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;482 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;483 type OperationalFeeMultiplier = OperationalFeeMultiplier;484 type WeightToFee = LinearFee<Balance>;485 type FeeMultiplierUpdate = ();486}487488parameter_types! {489 pub const ProposalBond: Permill = Permill::from_percent(5);490 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;491 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;492 pub const SpendPeriod: BlockNumber = 5 * MINUTES;493 pub const Burn: Permill = Permill::from_percent(0);494 pub const TipCountdown: BlockNumber = 1 * DAYS;495 pub const TipFindersFee: Percent = Percent::from_percent(20);496 pub const TipReportDepositBase: Balance = 1 * UNIQUE;497 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;498 pub const BountyDepositBase: Balance = 1 * UNIQUE;499 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;500 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");501 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;502 pub const MaximumReasonLength: u32 = 16384;503 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);504 pub const BountyValueMinimum: Balance = 5 * UNIQUE;505 pub const MaxApprovals: u32 = 100;506}507508impl pallet_treasury::Config for Runtime {509 type PalletId = TreasuryModuleId;510 type Currency = Balances;511 type ApproveOrigin = EnsureRoot<AccountId>;512 type RejectOrigin = EnsureRoot<AccountId>;513 type Event = Event;514 type OnSlash = ();515 type ProposalBond = ProposalBond;516 type ProposalBondMinimum = ProposalBondMinimum;517 type ProposalBondMaximum = ProposalBondMaximum;518 type SpendPeriod = SpendPeriod;519 type Burn = Burn;520 type BurnDestination = ();521 type SpendFunds = ();522 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;523 type MaxApprovals = MaxApprovals;524}525526impl pallet_sudo::Config for Runtime {527 type Event = Event;528 type Call = Call;529}530531pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);532533impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider534 for RelayChainBlockNumberProvider<T>535{536 type BlockNumber = BlockNumber;537538 fn current_block_number() -> Self::BlockNumber {539 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()540 .map(|d| d.relay_parent_number)541 .unwrap_or_default()542 }543}544545parameter_types! {546 pub const MinVestedTransfer: Balance = 10 * UNIQUE;547 pub const MaxVestingSchedules: u32 = 28;548}549550impl orml_vesting::Config for Runtime {551 type Event = Event;552 type Currency = pallet_balances::Pallet<Runtime>;553 type MinVestedTransfer = MinVestedTransfer;554 type VestedTransferOrigin = EnsureSigned<AccountId>;555 type WeightInfo = ();556 type MaxVestingSchedules = MaxVestingSchedules;557 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;558}559560parameter_types! {561 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;562 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;563}564565impl cumulus_pallet_parachain_system::Config for Runtime {566 type Event = Event;567 type SelfParaId = parachain_info::Pallet<Self>;568 type OnSystemEvent = ();569 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<570 // MaxDownwardMessageWeight,571 // XcmExecutor<XcmConfig>,572 // Call,573 // >;574 type OutboundXcmpMessageSource = XcmpQueue;575 type DmpMessageHandler = DmpQueue;576 type ReservedDmpWeight = ReservedDmpWeight;577 type ReservedXcmpWeight = ReservedXcmpWeight;578 type XcmpMessageHandler = XcmpQueue;579}580581impl parachain_info::Config for Runtime {}582583impl cumulus_pallet_aura_ext::Config for Runtime {}584585parameter_types! {586 pub const RelayLocation: MultiLocation = MultiLocation::parent();587 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;588 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();589 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();590}591592/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used593/// when determining ownership of accounts for asset transacting and when attempting to use XCM594/// `Transact` in order to determine the dispatch Origin.595pub type LocationToAccountId = (596 // The parent (Relay-chain) origin converts to the default `AccountId`.597 ParentIsPreset<AccountId>,598 // Sibling parachain origins convert to AccountId via the `ParaId::into`.599 SiblingParachainConvertsVia<Sibling, AccountId>,600 // Straight up local `AccountId32` origins just alias directly to `AccountId`.601 AccountId32Aliases<RelayNetwork, AccountId>,602);603604pub struct OnlySelfCurrency;605impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {606 fn matches_fungible(a: &MultiAsset) -> Option<B> {607 match (&a.id, &a.fun) {608 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),609 _ => None,610 }611 }612}613614/// Means for transacting assets on this chain.615pub type LocalAssetTransactor = CurrencyAdapter<616 // Use this currency:617 Balances,618 // Use this currency when it is a fungible asset matching the given location or name:619 OnlySelfCurrency,620 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:621 LocationToAccountId,622 // Our chain's account ID type (we can't get away without mentioning it explicitly):623 AccountId,624 // We don't track any teleports.625 (),626>;627628/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,629/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can630/// biases the kind of local `Origin` it will become.631pub type XcmOriginToTransactDispatchOrigin = (632 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location633 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for634 // foreign chains who want to have a local sovereign account on this chain which they control.635 SovereignSignedViaLocation<LocationToAccountId, Origin>,636 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when637 // recognised.638 RelayChainAsNative<RelayOrigin, Origin>,639 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when640 // recognised.641 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,642 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a643 // transaction from the Root origin.644 ParentAsSuperuser<Origin>,645 // Native signed account converter; this just converts an `AccountId32` origin into a normal646 // `Origin::Signed` origin of the same 32-byte value.647 SignedAccountId32AsNative<RelayNetwork, Origin>,648 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.649 XcmPassthrough<Origin>,650);651652parameter_types! {653 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.654 pub UnitWeightCost: Weight = 1_000_000;655 // 1200 UNIQUEs buy 1 second of weight.656 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);657 pub const MaxInstructions: u32 = 100;658 pub const MaxAuthorities: u32 = 100_000;659}660661match_types! {662 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {663 MultiLocation { parents: 1, interior: Here } |664 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }665 };666}667668pub type Barrier = (669 TakeWeightCredit,670 AllowTopLevelPaidExecutionFrom<Everything>,671 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,672 // ^^^ Parent & its unit plurality gets free execution673);674675pub struct UsingOnlySelfCurrencyComponents<676 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,677 AssetId: Get<MultiLocation>,678 AccountId,679 Currency: CurrencyT<AccountId>,680 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,681>(682 Weight,683 Currency::Balance,684 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,685);686impl<687 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,688 AssetId: Get<MultiLocation>,689 AccountId,690 Currency: CurrencyT<AccountId>,691 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,692 > WeightTrader693 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>694{695 fn new() -> Self {696 Self(0, Zero::zero(), PhantomData)697 }698699 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {700 let amount = WeightToFee::calc(&weight);701 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;702703 // location to this parachain through relay chain704 let option1: xcm::v1::AssetId = Concrete(MultiLocation {705 parents: 1,706 interior: X1(Parachain(ParachainInfo::parachain_id().into())),707 });708 // direct location709 let option2: xcm::v1::AssetId = Concrete(MultiLocation {710 parents: 0,711 interior: Here,712 });713714 let required = if payment.fungible.contains_key(&option1) {715 (option1, u128_amount).into()716 } else if payment.fungible.contains_key(&option2) {717 (option2, u128_amount).into()718 } else {719 (Concrete(MultiLocation::default()), u128_amount).into()720 };721722 let unused = payment723 .checked_sub(required)724 .map_err(|_| XcmError::TooExpensive)?;725 self.0 = self.0.saturating_add(weight);726 self.1 = self.1.saturating_add(amount);727 Ok(unused)728 }729730 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {731 let weight = weight.min(self.0);732 let amount = WeightToFee::calc(&weight);733 self.0 -= weight;734 self.1 = self.1.saturating_sub(amount);735 let amount: u128 = amount.saturated_into();736 if amount > 0 {737 Some((AssetId::get(), amount).into())738 } else {739 None740 }741 }742}743impl<744 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,745 AssetId: Get<MultiLocation>,746 AccountId,747 Currency: CurrencyT<AccountId>,748 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,749 > Drop750 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>751{752 fn drop(&mut self) {753 OnUnbalanced::on_unbalanced(Currency::issue(self.1));754 }755}756757pub struct XcmConfig;758impl Config for XcmConfig {759 type Call = Call;760 type XcmSender = XcmRouter;761 // How to withdraw and deposit an asset.762 type AssetTransactor = LocalAssetTransactor;763 type OriginConverter = XcmOriginToTransactDispatchOrigin;764 type IsReserve = NativeAsset;765 type IsTeleporter = (); // Teleportation is disabled766 type LocationInverter = LocationInverter<Ancestry>;767 type Barrier = Barrier;768 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;769 type Trader = UsingOnlySelfCurrencyComponents<770 IdentityFee<Balance>,771 RelayLocation,772 AccountId,773 Balances,774 (),775 >;776 type ResponseHandler = (); // Don't handle responses for now.777 type SubscriptionService = PolkadotXcm;778779 type AssetTrap = PolkadotXcm;780 type AssetClaims = PolkadotXcm;781}782783// parameter_types! {784// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;785// }786787/// No local origins on this chain are allowed to dispatch XCM sends/executions.788pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);789790/// The means for routing XCM messages which are not for local execution into the right message791/// queues.792pub type XcmRouter = (793 // Two routers - use UMP to communicate with the relay chain:794 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,795 // ..and XCMP to communicate with the sibling chains.796 XcmpQueue,797);798799impl pallet_evm_coder_substrate::Config for Runtime {800 type GasWeightMapping = FixedGasWeightMapping;801}802803impl pallet_xcm::Config for Runtime {804 type Event = Event;805 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;806 type XcmRouter = XcmRouter;807 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;808 type XcmExecuteFilter = Everything;809 type XcmExecutor = XcmExecutor<XcmConfig>;810 type XcmTeleportFilter = Everything;811 type XcmReserveTransferFilter = Everything;812 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;813 type LocationInverter = LocationInverter<Ancestry>;814 type Origin = Origin;815 type Call = Call;816 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;817 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;818}819820impl cumulus_pallet_xcm::Config for Runtime {821 type Event = Event;822 type XcmExecutor = XcmExecutor<XcmConfig>;823}824825impl cumulus_pallet_xcmp_queue::Config for Runtime {826 type WeightInfo = ();827 type Event = Event;828 type XcmExecutor = XcmExecutor<XcmConfig>;829 type ChannelInfo = ParachainSystem;830 type VersionWrapper = ();831 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;832 type ControllerOrigin = EnsureRoot<AccountId>;833 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;834}835836impl cumulus_pallet_dmp_queue::Config for Runtime {837 type Event = Event;838 type XcmExecutor = XcmExecutor<XcmConfig>;839 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;840}841842impl pallet_aura::Config for Runtime {843 type AuthorityId = AuraId;844 type DisabledValidators = ();845 type MaxAuthorities = MaxAuthorities;846}847848parameter_types! {849 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();850 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;851}852853impl pallet_common::Config for Runtime {854 type WeightInfo = pallet_common::weights::SubstrateWeight<Self>;855 type Event = Event;856 type Currency = Balances;857 type CollectionCreationPrice = CollectionCreationPrice;858 type TreasuryAccountId = TreasuryAccountId;859 type CollectionDispatch = CollectionDispatchT<Self>;860861 type EvmTokenAddressMapping = EvmTokenAddressMapping;862 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;863}864865impl pallet_structure::Config for Runtime {866 type Event = Event;867 type Call = Call;868 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;869}870871impl pallet_evm::account::Config for Runtime {872 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;873 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;874 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;875}876877impl pallet_fungible::Config for Runtime {878 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;879}880impl pallet_refungible::Config for Runtime {881 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;882}883impl pallet_nonfungible::Config for Runtime {884 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;885}886887impl pallet_unique::Config for Runtime {888 type Event = Event;889 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;890 type CommonWeightInfo = CommonWeights<Self>;891}892893parameter_types! {894 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied895}896897/// Used for the pallet inflation898impl pallet_inflation::Config for Runtime {899 type Currency = Balances;900 type TreasuryAccountId = TreasuryAccountId;901 type InflationBlockInterval = InflationBlockInterval;902 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;903}904905// parameter_types! {906// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *907// RuntimeBlockWeights::get().max_block;908// pub const MaxScheduledPerBlock: u32 = 50;909// }910911type EvmSponsorshipHandler = (912 UniqueEthSponsorshipHandler<Runtime>,913 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,914);915type SponsorshipHandler = (916 UniqueSponsorshipHandler<Runtime>,917 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,918 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,919);920921// impl pallet_unq_scheduler::Config for Runtime {922// type Event = Event;923// type Origin = Origin;924// type PalletsOrigin = OriginCaller;925// type Call = Call;926// type MaximumWeight = MaximumSchedulerWeight;927// type ScheduleOrigin = EnsureSigned<AccountId>;928// type MaxScheduledPerBlock = MaxScheduledPerBlock;929// type SponsorshipHandler = SponsorshipHandler;930// type WeightInfo = ();931// }932933impl pallet_evm_transaction_payment::Config for Runtime {934 type EvmSponsorshipHandler = EvmSponsorshipHandler;935 type Currency = Balances;936}937938impl pallet_charge_transaction::Config for Runtime {939 type SponsorshipHandler = SponsorshipHandler;940}941942// impl pallet_contract_helpers::Config for Runtime {943// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;944// }945946parameter_types! {947 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049948 pub const HelpersContractAddress: H160 = H160([949 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,950 ]);951}952953impl pallet_evm_contract_helpers::Config for Runtime {954 type ContractAddress = HelpersContractAddress;955 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;956}957958construct_runtime!(959 pub enum Runtime where960 Block = Block,961 NodeBlock = opaque::Block,962 UncheckedExtrinsic = UncheckedExtrinsic963 {964 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,965 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,966967 Aura: pallet_aura::{Pallet, Config<T>} = 22,968 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,969970 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,971 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,972 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,973 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,974 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,975 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,976 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,977 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,978 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,979 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,980981 // XCM helpers.982 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,983 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,984 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,985 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,986987 // Unique Pallets988 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,989 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,990 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,991 // free = 63992 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,993 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,994 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,995 Fungible: pallet_fungible::{Pallet, Storage} = 67,996 Refungible: pallet_refungible::{Pallet, Storage} = 68,997 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,998 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,9991000 // Frontier1001 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1002 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10031004 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1005 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1006 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1007 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1008 }1009);10101011pub struct TransactionConverter;10121013impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1014 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1015 UncheckedExtrinsic::new_unsigned(1016 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1017 )1018 }1019}10201021impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1022 fn convert_transaction(1023 &self,1024 transaction: pallet_ethereum::Transaction,1025 ) -> opaque::UncheckedExtrinsic {1026 let extrinsic = UncheckedExtrinsic::new_unsigned(1027 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1028 );1029 let encoded = extrinsic.encode();1030 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1031 .expect("Encoded extrinsic is always valid")1032 }1033}10341035/// The address format for describing accounts.1036pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1037/// Block header type as expected by this runtime.1038pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1039/// Block type as expected by this runtime.1040pub type Block = generic::Block<Header, UncheckedExtrinsic>;1041/// A Block signed with a Justification1042pub type SignedBlock = generic::SignedBlock<Block>;1043/// BlockId type as expected by this runtime.1044pub type BlockId = generic::BlockId<Block>;1045/// The SignedExtension to the basic transaction logic.1046pub type SignedExtra = (1047 frame_system::CheckSpecVersion<Runtime>,1048 // system::CheckTxVersion<Runtime>,1049 frame_system::CheckGenesis<Runtime>,1050 frame_system::CheckEra<Runtime>,1051 frame_system::CheckNonce<Runtime>,1052 frame_system::CheckWeight<Runtime>,1053 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1054 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1055 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1056);1057/// Unchecked extrinsic type as expected by this runtime.1058pub type UncheckedExtrinsic =1059 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1060/// Extrinsic type that has already been checked.1061pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1062/// Executive: handles dispatch to the various modules.1063pub type Executive = frame_executive::Executive<1064 Runtime,1065 Block,1066 frame_system::ChainContext<Runtime>,1067 Runtime,1068 AllPalletsReversedWithSystemFirst,1069>;10701071impl_opaque_keys! {1072 pub struct SessionKeys {1073 pub aura: Aura,1074 }1075}10761077impl fp_self_contained::SelfContainedCall for Call {1078 type SignedInfo = H160;10791080 fn is_self_contained(&self) -> bool {1081 match self {1082 Call::Ethereum(call) => call.is_self_contained(),1083 _ => false,1084 }1085 }10861087 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1088 match self {1089 Call::Ethereum(call) => call.check_self_contained(),1090 _ => None,1091 }1092 }10931094 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1095 match self {1096 Call::Ethereum(call) => call.validate_self_contained(info),1097 _ => None,1098 }1099 }11001101 fn pre_dispatch_self_contained(1102 &self,1103 info: &Self::SignedInfo,1104 ) -> Option<Result<(), TransactionValidityError>> {1105 match self {1106 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1107 _ => None,1108 }1109 }11101111 fn apply_self_contained(1112 self,1113 info: Self::SignedInfo,1114 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1115 match self {1116 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1117 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1118 )),1119 _ => None,1120 }1121 }1122}11231124macro_rules! dispatch_unique_runtime {1125 ($collection:ident.$method:ident($($name:ident),*)) => {{1126 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1127 let dispatch = collection.as_dyn();11281129 Ok(dispatch.$method($($name),*))1130 }};1131}11321133impl_common_runtime_apis!();11341135struct CheckInherents;11361137impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1138 fn check_inherents(1139 block: &Block,1140 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1141 ) -> sp_inherents::CheckInherentsResult {1142 let relay_chain_slot = relay_state_proof1143 .read_slot()1144 .expect("Could not read the relay chain slot from the proof");11451146 let inherent_data =1147 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1148 relay_chain_slot,1149 sp_std::time::Duration::from_secs(6),1150 )1151 .create_inherent_data()1152 .expect("Could not create the timestamp inherent data");11531154 inherent_data.check_extrinsics(block)1155 }1156}11571158cumulus_pallet_parachain_system::register_validate_block!(1159 Runtime = Runtime,1160 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1161 CheckInherents = CheckInherents,1162);