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.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#![cfg_attr(not(feature = "std"), no_std)]1819use core::{20 convert::{TryFrom, TryInto},21 fmt,22};23use frame_support::{24 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},25 traits::Get,26 parameter_types,27};2829#[cfg(feature = "serde")]30use serde::{Serialize, Deserialize};3132use sp_core::U256;33use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};34use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};35use frame_support::{BoundedVec, traits::ConstU32};36use derivative::Derivative;37use scale_info::TypeInfo;3839pub mod rmrk;4041// RMRK42use rmrk::{43 CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,44};45pub use rmrk::{46 primitives::{47 CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,48 PartId as RmrkPartId, ResourceId as RmrkResourceId,49 },50 NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,51 FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart, EquippableList as RmrkEquippableList,52};5354mod bounded;55pub mod budget;56pub mod mapping;57mod migration;5859pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;60pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;61pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;6263pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {64 100_00065} else {66 1067};68pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {69 100_00070} else {71 1072};73pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {74 204875} else {76 1077};78pub const COLLECTION_ADMINS_LIMIT: u32 = 5;79pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;80pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {81 1_000_00082} else {83 1084};8586// Timeouts for item types in passed blocks87pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;88pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;89pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;9091pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;9293// Schema limits94pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;95pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;96pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9798pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;99100pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;101pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;102pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;103104pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;105pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;106pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;107108// pub const MAX_PROPERTY_KEYS_OVERALL_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH * MAX_PROPERTIES_PER_ITEM;109pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;110pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;111112pub const MAX_COLLECTION_PROPERTIES_ENCODE_LEN: u32 =113 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH + MAX_COLLECTION_PROPERTIES_SIZE;114115// RMRK constants116pub const RMRK_STRING_LIMIT: u32 = 128;117pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;118pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;119pub const RMRK_KEY_LIMIT: u32 = 32;120pub const RMRK_VALUE_LIMIT: u32 = 256;121122pub struct MaxPropertiesPermissionsEncodeLen;123124impl Get<u32> for MaxPropertiesPermissionsEncodeLen {125 fn get() -> u32 {126 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH127 + <PropertyPermission as MaxEncodedLen>::max_encoded_len() as u32128 }129}130131/// How much items can be created per single132/// create_many call133pub const MAX_ITEMS_PER_BATCH: u32 = 200;134135pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;136137#[derive(138 Encode,139 Decode,140 PartialEq,141 Eq,142 PartialOrd,143 Ord,144 Clone,145 Copy,146 Debug,147 Default,148 TypeInfo,149 MaxEncodedLen,150)]151#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]152pub struct CollectionId(pub u32);153impl EncodeLike<u32> for CollectionId {}154impl EncodeLike<CollectionId> for u32 {}155156#[derive(157 Encode,158 Decode,159 PartialEq,160 Eq,161 PartialOrd,162 Ord,163 Clone,164 Copy,165 Debug,166 Default,167 TypeInfo,168 MaxEncodedLen,169)]170#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]171pub struct TokenId(pub u32);172impl EncodeLike<u32> for TokenId {}173impl EncodeLike<TokenId> for u32 {}174175impl TokenId {176 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {177 self.0178 .checked_add(1)179 .ok_or(ArithmeticError::Overflow)180 .map(Self)181 }182}183184impl From<TokenId> for U256 {185 fn from(t: TokenId) -> Self {186 t.0.into()187 }188}189190impl TryFrom<U256> for TokenId {191 type Error = &'static str;192193 fn try_from(value: U256) -> Result<Self, Self::Error> {194 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))195 }196}197198#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]199#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]200pub struct TokenData<CrossAccountId> {201 pub const_data: Vec<u8>,202 pub properties: Vec<Property>,203 pub owner: Option<CrossAccountId>,204}205206pub struct OverflowError;207impl From<OverflowError> for &'static str {208 fn from(_: OverflowError) -> Self {209 "overflow occured"210 }211}212213pub type DecimalPoints = u8;214215#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]216#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]217pub enum CollectionMode {218 NFT,219 // decimal points220 Fungible(DecimalPoints),221 ReFungible,222}223224impl CollectionMode {225 pub fn id(&self) -> u8 {226 match self {227 CollectionMode::NFT => 1,228 CollectionMode::Fungible(_) => 2,229 CollectionMode::ReFungible => 3,230 }231 }232}233234pub trait SponsoringResolve<AccountId, Call> {235 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;236}237238#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]239#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]240pub enum AccessMode {241 Normal,242 AllowList,243}244impl Default for AccessMode {245 fn default() -> Self {246 Self::Normal247 }248}249250#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]251#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]252pub enum SchemaVersion {253 ImageURL,254 Unique,255}256impl Default for SchemaVersion {257 fn default() -> Self {258 Self::ImageURL259 }260}261262#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]263#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]264pub struct Ownership<AccountId> {265 pub owner: AccountId,266 pub fraction: u128,267}268269#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]270#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]271pub enum SponsorshipState<AccountId> {272 /// The fees are applied to the transaction sender273 Disabled,274 Unconfirmed(AccountId),275 /// Transactions are sponsored by specified account276 Confirmed(AccountId),277}278279impl<AccountId> SponsorshipState<AccountId> {280 pub fn sponsor(&self) -> Option<&AccountId> {281 match self {282 Self::Confirmed(sponsor) => Some(sponsor),283 _ => None,284 }285 }286287 pub fn pending_sponsor(&self) -> Option<&AccountId> {288 match self {289 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),290 _ => None,291 }292 }293294 pub fn confirmed(&self) -> bool {295 matches!(self, Self::Confirmed(_))296 }297}298299impl<T> Default for SponsorshipState<T> {300 fn default() -> Self {301 Self::Disabled302 }303}304305/// Used in storage306#[struct_versioning::versioned(version = 2, upper)]307#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]308pub struct Collection<AccountId> {309 pub owner: AccountId,310 pub mode: CollectionMode,311 pub access: AccessMode,312 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,313 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,314 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,315 pub mint_mode: bool,316317 #[version(..2)]318 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,319320 pub schema_version: SchemaVersion,321 pub sponsorship: SponsorshipState<AccountId>,322323 #[version(..2)]324 pub limits: CollectionLimitsVersion1, // Collection private restrictions325 #[version(2.., upper(limits.into()))]326 pub limits: CollectionLimitsVersion2,327328 #[version(..2)]329 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,330331 #[version(..2)]332 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,333334 #[version(..2)]335 pub meta_update_permission: MetaUpdatePermission,336}337338/// Used in RPC calls339#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]340#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]341pub struct RpcCollection<AccountId> {342 pub owner: AccountId,343 pub mode: CollectionMode,344 pub access: AccessMode,345 pub name: Vec<u16>,346 pub description: Vec<u16>,347 pub token_prefix: Vec<u8>,348 pub mint_mode: bool,349 pub offchain_schema: Vec<u8>,350 pub schema_version: SchemaVersion,351 pub sponsorship: SponsorshipState<AccountId>,352 pub limits: CollectionLimits,353 pub const_on_chain_schema: Vec<u8>,354 pub token_property_permissions: Vec<PropertyKeyPermission>,355 pub properties: Vec<Property>,356}357358#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]359#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]360pub enum CollectionField {361 ConstOnChainSchema,362 OffchainSchema,363}364365#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]366#[derivative(Debug, Default(bound = ""))]367pub struct CreateCollectionData<AccountId> {368 #[derivative(Default(value = "CollectionMode::NFT"))]369 pub mode: CollectionMode,370 pub access: Option<AccessMode>,371 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,372 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,373 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,374 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,375 pub schema_version: Option<SchemaVersion>,376 pub pending_sponsor: Option<AccountId>,377 pub limits: Option<CollectionLimits>,378 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,379 pub token_property_permissions: CollectionPropertiesPermissionsVec,380 pub properties: CollectionPropertiesVec,381}382383pub type CollectionPropertiesPermissionsVec =384 BoundedVec<PropertyKeyPermission, MaxPropertiesPermissionsEncodeLen>;385386pub type CollectionPropertiesVec =387 BoundedVec<Property, ConstU32<MAX_COLLECTION_PROPERTIES_ENCODE_LEN>>;388389/// All fields are wrapped in `Option`s, where None means chain default390#[struct_versioning::versioned(version = 2, upper)]391#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]392#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]393pub struct CollectionLimits {394 pub account_token_ownership_limit: Option<u32>,395 pub sponsored_data_size: Option<u32>,396397 /// FIXME should we delete this or repurpose it?398 /// None - setVariableMetadata is not sponsored399 /// Some(v) - setVariableMetadata is sponsored400 /// if there is v block between txs401 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,402 pub token_limit: Option<u32>,403404 // Timeouts for item types in passed blocks405 pub sponsor_transfer_timeout: Option<u32>,406 pub sponsor_approve_timeout: Option<u32>,407 pub owner_can_transfer: Option<bool>,408 pub owner_can_destroy: Option<bool>,409 pub transfers_enabled: Option<bool>,410411 #[version(2.., upper(None))]412 pub nesting_rule: Option<NestingRule>,413}414415impl CollectionLimits {416 pub fn account_token_ownership_limit(&self) -> u32 {417 self.account_token_ownership_limit418 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)419 .min(MAX_TOKEN_OWNERSHIP)420 }421 pub fn sponsored_data_size(&self) -> u32 {422 self.sponsored_data_size423 .unwrap_or(CUSTOM_DATA_LIMIT)424 .min(CUSTOM_DATA_LIMIT)425 }426 pub fn token_limit(&self) -> u32 {427 self.token_limit428 .unwrap_or(COLLECTION_TOKEN_LIMIT)429 .min(COLLECTION_TOKEN_LIMIT)430 }431 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {432 self.sponsor_transfer_timeout433 .unwrap_or(default)434 .min(MAX_SPONSOR_TIMEOUT)435 }436 pub fn sponsor_approve_timeout(&self) -> u32 {437 self.sponsor_approve_timeout438 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)439 .min(MAX_SPONSOR_TIMEOUT)440 }441 pub fn owner_can_transfer(&self) -> bool {442 self.owner_can_transfer.unwrap_or(true)443 }444 pub fn owner_can_destroy(&self) -> bool {445 self.owner_can_destroy.unwrap_or(true)446 }447 pub fn transfers_enabled(&self) -> bool {448 self.transfers_enabled.unwrap_or(true)449 }450 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {451 match self452 .sponsored_data_rate_limit453 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)454 {455 SponsoringRateLimit::SponsoringDisabled => None,456 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),457 }458 }459 pub fn nesting_rule(&self) -> &NestingRule {460 static DEFAULT: NestingRule = NestingRule::Disabled;461 self.nesting_rule.as_ref().unwrap_or(&DEFAULT)462 }463}464465#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]466#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]467#[derivative(Debug)]468pub enum NestingRule {469 /// No one can nest tokens470 Disabled,471 /// Owner can nest any tokens472 Owner,473 /// Owner can nest tokens from specified collections474 OwnerRestricted(475 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]476 #[derivative(Debug(format_with = "bounded::set_debug"))]477 BoundedBTreeSet<CollectionId, ConstU32<16>>,478 ),479}480481#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]482#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]483pub enum SponsoringRateLimit {484 SponsoringDisabled,485 Blocks(u32),486}487488#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]489#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]490#[derivative(Debug)]491pub struct CreateNftData {492 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]493 #[derivative(Debug(format_with = "bounded::vec_debug"))]494 pub const_data: BoundedVec<u8, CustomDataLimit>,495496 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]497 #[derivative(Debug(format_with = "bounded::vec_debug"))]498 pub properties: CollectionPropertiesVec,499}500501#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]502#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]503pub struct CreateFungibleData {504 pub value: u128,505}506507#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]508#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]509#[derivative(Debug)]510pub struct CreateReFungibleData {511 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]512 #[derivative(Debug(format_with = "bounded::vec_debug"))]513 pub const_data: BoundedVec<u8, CustomDataLimit>,514 pub pieces: u128,515}516517#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]518pub enum MetaUpdatePermission {519 ItemOwner,520 Admin,521 None,522}523524#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]525#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]526pub enum CreateItemData {527 NFT(CreateNftData),528 Fungible(CreateFungibleData),529 ReFungible(CreateReFungibleData),530}531532#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]533#[derivative(Debug)]534pub struct CreateNftExData<CrossAccountId> {535 #[derivative(Debug(format_with = "bounded::vec_debug"))]536 pub const_data: BoundedVec<u8, CustomDataLimit>,537 #[derivative(Debug(format_with = "bounded::vec_debug"))]538 pub properties: CollectionPropertiesVec,539 pub owner: CrossAccountId,540}541542#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]543#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]544pub struct CreateRefungibleExData<CrossAccountId> {545 #[derivative(Debug(format_with = "bounded::vec_debug"))]546 pub const_data: BoundedVec<u8, CustomDataLimit>,547 #[derivative(Debug(format_with = "bounded::map_debug"))]548 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,549}550551#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]552#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]553pub enum CreateItemExData<CrossAccountId> {554 NFT(555 #[derivative(Debug(format_with = "bounded::vec_debug"))]556 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,557 ),558 Fungible(559 #[derivative(Debug(format_with = "bounded::map_debug"))]560 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,561 ),562 /// Many tokens, each may have only one owner563 RefungibleMultipleItems(564 #[derivative(Debug(format_with = "bounded::vec_debug"))]565 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,566 ),567 /// Single token, which may have many owners568 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),569}570571impl CreateItemData {572 pub fn data_size(&self) -> usize {573 match self {574 CreateItemData::NFT(data) => data.const_data.len(),575 CreateItemData::ReFungible(data) => data.const_data.len(),576 _ => 0,577 }578 }579}580581impl From<CreateNftData> for CreateItemData {582 fn from(item: CreateNftData) -> Self {583 CreateItemData::NFT(item)584 }585}586587impl From<CreateReFungibleData> for CreateItemData {588 fn from(item: CreateReFungibleData) -> Self {589 CreateItemData::ReFungible(item)590 }591}592593impl From<CreateFungibleData> for CreateItemData {594 fn from(item: CreateFungibleData) -> Self {595 CreateItemData::Fungible(item)596 }597}598599#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]600#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]601pub struct CollectionStats {602 pub created: u32,603 pub destroyed: u32,604 pub alive: u32,605}606607#[derive(Encode, Decode, Clone, Debug)]608#[cfg_attr(feature = "std", derive(PartialEq))]609pub struct PhantomType<T>(core::marker::PhantomData<T>);610611impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {612 type Identity = PhantomType<T>;613614 fn type_info() -> scale_info::Type {615 use scale_info::{616 Type, Path,617 build::{FieldsBuilder, UnnamedFields},618 type_params,619 };620 Type::builder()621 .path(Path::new("up_data_structs", "PhantomType"))622 .type_params(type_params!(T))623 .composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))624 }625}626impl<T> MaxEncodedLen for PhantomType<T> {627 fn max_encoded_len() -> usize {628 0629 }630}631632pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;633pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;634635#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]636#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]637pub struct PropertyPermission {638 pub mutable: bool,639 pub collection_admin: bool,640 pub token_owner: bool,641}642643impl PropertyPermission {644 pub fn none() -> Self {645 Self {646 mutable: true,647 collection_admin: false,648 token_owner: false,649 }650 }651}652653#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]654#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]655pub struct Property {656 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]657 pub key: PropertyKey,658659 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]660 pub value: PropertyValue,661}662663impl Into<(PropertyKey, PropertyValue)> for Property {664 fn into(self) -> (PropertyKey, PropertyValue) {665 (self.key, self.value)666 }667}668669#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]670#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]671pub struct PropertyKeyPermission {672 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]673 pub key: PropertyKey,674675 pub permission: PropertyPermission,676}677678impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {679 fn into(self) -> (PropertyKey, PropertyPermission) {680 (self.key, self.permission)681 }682}683684#[derive(Debug)]685pub enum PropertiesError {686 NoSpaceForProperty,687 PropertyLimitReached,688 InvalidCharacterInPropertyKey,689 PropertyKeyIsTooLong,690 EmptyPropertyKey,691}692693#[derive(Clone, Copy)]694pub enum PropertyScope {695 None,696 Rmrk,697}698699impl PropertyScope {700 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {701 let scope_str: &[u8] = match self {702 Self::None => return Ok(key),703 Self::Rmrk => b"rmrk",704 };705706 [scope_str, b":", key.as_slice()]707 .concat()708 .try_into()709 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)710 }711}712713pub trait TrySetProperty: Sized {714 type Value;715716 fn try_scoped_set(717 &mut self,718 scope: PropertyScope,719 key: PropertyKey,720 value: Self::Value,721 ) -> Result<(), PropertiesError>;722723 fn try_scoped_set_from_iter<I, KV>(724 &mut self,725 scope: PropertyScope,726 iter: I,727 ) -> Result<(), PropertiesError>728 where729 I: Iterator<Item = KV>,730 KV: Into<(PropertyKey, Self::Value)>,731 {732 for kv in iter {733 let (key, value) = kv.into();734 self.try_scoped_set(scope, key, value)?;735 }736737 Ok(())738 }739740 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {741 self.try_scoped_set(PropertyScope::None, key, value)742 }743744 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>745 where746 I: Iterator<Item = KV>,747 KV: Into<(PropertyKey, Self::Value)>,748 {749 self.try_scoped_set_from_iter(PropertyScope::None, iter)750 }751}752753#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]754#[derivative(Default(bound = ""))]755pub struct PropertiesMap<Value>(756 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,757);758759impl<Value> PropertiesMap<Value> {760 pub fn new() -> Self {761 Self(BoundedBTreeMap::new())762 }763764 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {765 Self::check_property_key(key)?;766767 Ok(self.0.remove(key))768 }769770 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {771 self.0.get(key)772 }773774 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {775 self.0.iter()776 }777778 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {779 if key.is_empty() {780 return Err(PropertiesError::EmptyPropertyKey);781 }782783 for byte in key.as_slice().iter() {784 let byte = *byte;785786 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {787 return Err(PropertiesError::InvalidCharacterInPropertyKey);788 }789 }790791 Ok(())792 }793}794795impl<Value> TrySetProperty for PropertiesMap<Value> {796 type Value = Value;797798 fn try_scoped_set(799 &mut self,800 scope: PropertyScope,801 key: PropertyKey,802 value: Self::Value,803 ) -> Result<(), PropertiesError> {804 Self::check_property_key(&key)?;805806 let key = scope.apply(key)?;807 self.0808 .try_insert(key, value)809 .map_err(|_| PropertiesError::PropertyLimitReached)?;810811 Ok(())812 }813}814815pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;816817#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]818pub struct Properties {819 map: PropertiesMap<PropertyValue>,820 consumed_space: u32,821 space_limit: u32,822}823824impl Properties {825 pub fn new(space_limit: u32) -> Self {826 Self {827 map: PropertiesMap::new(),828 consumed_space: 0,829 space_limit,830 }831 }832833 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {834 let value = self.map.remove(key)?;835836 if let Some(ref value) = value {837 let value_len = value.len() as u32;838 self.consumed_space -= value_len;839 }840841 Ok(value)842 }843844 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {845 self.map.get(key)846 }847848 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {849 self.map.iter()850 }851}852853impl TrySetProperty for Properties {854 type Value = PropertyValue;855856 fn try_scoped_set(857 &mut self,858 scope: PropertyScope,859 key: PropertyKey,860 value: Self::Value,861 ) -> Result<(), PropertiesError> {862 let value_len = value.len();863864 if self.consumed_space as usize + value_len > self.space_limit as usize {865 return Err(PropertiesError::NoSpaceForProperty);866 }867868 self.map.try_scoped_set(scope, key, value)?;869870 self.consumed_space += value_len as u32;871872 Ok(())873 }874}875876pub struct CollectionProperties;877878impl Get<Properties> for CollectionProperties {879 fn get() -> Properties {880 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)881 }882}883884pub struct TokenProperties;885886impl Get<Properties> for TokenProperties {887 fn get() -> Properties {888 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)889 }890}891892// RMRK893// todo document?894parameter_types! {895 #[derive(PartialEq, TypeInfo)]896 pub const RmrkStringLimit: u32 = 128;897 #[derive(PartialEq)]898 pub const RmrkCollectionSymbolLimit: u32 = 100;899 #[derive(PartialEq)]900 pub const RmrkResourceSymbolLimit: u32 = 10;901 #[derive(PartialEq)]902 pub const RmrkKeyLimit: u32 = 32;903 #[derive(PartialEq)]904 pub const RmrkValueLimit: u32 = 256;905 #[derive(PartialEq)]906 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;907 #[derive(PartialEq)]908 pub const RmrkPartsLimit: u32 = 3;909}910911impl From<RmrkCollectionId> for CollectionId {912 fn from(id: RmrkCollectionId) -> Self {913 Self(id)914 }915}916917impl From<RmrkNftId> for TokenId {918 fn from(id: RmrkNftId) -> Self {919 Self(id)920 }921}922923pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;924pub type RmrkCollectionInfo<AccountId> =925 CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;926pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;927pub type RmrkResourceInfo = ResourceInfo<928 BoundedVec<u8, RmrkResourceSymbolLimit>,929 RmrkString,930 BoundedVec<RmrkPartId, RmrkPartsLimit>,931>;932pub type RmrkPropertyInfo =933 PropertyInfo<BoundedVec<u8, RmrkKeyLimit>, BoundedVec<u8, RmrkValueLimit>>;934pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;935pub type RmrkPartType =936 PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;937pub type RmrkTheme = Theme<RmrkString, Vec<ThemeProperty<RmrkString>>>;938939pub type RmrkRpcString = Vec<u8>;940pub type RmrkThemeName = RmrkRpcString;941pub type RmrkPropertyKey = RmrkRpcString;942943pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;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.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -66,7 +66,12 @@
WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
},
};
-use unique_runtime_common::dispatch::{CollectionDispatchT, CollectionDispatch};
+use unique_runtime_common::{
+ dispatch::{CollectionDispatchT, CollectionDispatch},
+ weights::CommonWeights,
+ sponsoring::UniqueSponsorshipHandler,
+ eth_sponsoring::UniqueEthSponsorshipHandler,
+};
use up_data_structs::*;
// use pallet_contracts::weights::WeightInfo;
// #[cfg(any(feature = "std", test))]
@@ -846,6 +851,7 @@
}
impl pallet_common::Config for Runtime {
+ type WeightInfo = pallet_common::weights::SubstrateWeight<Self>;
type Event = Event;
type Currency = Balances;
type CollectionCreationPrice = CollectionCreationPrice;
@@ -881,6 +887,7 @@
impl pallet_unique::Config for Runtime {
type Event = Event;
type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;
+ type CommonWeightInfo = CommonWeights<Self>;
}
parameter_types! {
@@ -902,11 +909,11 @@
// }
type EvmSponsorshipHandler = (
- pallet_unique::UniqueEthSponsorshipHandler<Runtime>,
+ UniqueEthSponsorshipHandler<Runtime>,
pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
);
type SponsorshipHandler = (
- pallet_unique::UniqueSponsorshipHandler<Runtime>,
+ UniqueSponsorshipHandler<Runtime>,
//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
);