difftreelog
Merge branch 'develop' into feature/CORE-302-ss58Format
in: master
17 files changed
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -20,8 +20,8 @@
use frame_benchmarking::{benchmarks, account};
use up_data_structs::{
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,
+ CollectionPermissions, NestingRule, MAX_COLLECTION_NAME_LENGTH,
+ MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, MAX_PROPERTIES_PER_ITEM,
};
use frame_support::{
traits::{Currency, Get},
@@ -74,15 +74,15 @@
}
pub fn create_collection_raw<T: Config, R>(
- owner: T::AccountId,
+ owner: T::CrossAccountId,
mode: CollectionMode,
handler: impl FnOnce(
- T::AccountId,
+ T::CrossAccountId,
CreateCollectionData<T::AccountId>,
) -> Result<CollectionId, DispatchError>,
cast: impl FnOnce(CollectionHandle<T>) -> R,
) -> Result<R, DispatchError> {
- T::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());
+ <T as Config>::Currency::deposit_creating(&owner.as_sub(), T::CollectionCreationPrice::get());
let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
@@ -93,13 +93,19 @@
name,
description,
token_prefix,
+ permissions: Some(CollectionPermissions {
+ nesting: Some(NestingRule::Permissive),
+ ..Default::default()
+ }),
..Default::default()
},
)
.and_then(CollectionHandle::try_get)
.map(cast)
}
-fn create_collection<T: Config>(owner: T::AccountId) -> Result<CollectionHandle<T>, DispatchError> {
+fn create_collection<T: Config>(
+ owner: T::CrossAccountId,
+) -> Result<CollectionHandle<T>, DispatchError> {
create_collection_raw(
owner,
CollectionMode::NFT,
@@ -127,7 +133,7 @@
bench_init!($($rest)*);
};
($name:ident: collection($owner:ident); $($rest:tt)*) => {
- let $name = create_collection::<T>($owner.clone())?;
+ let $name = create_collection::<T>(T::CrossAccountId::from_sub($owner.clone()))?;
bench_init!($($rest)*);
};
($name:ident: cross; $($rest:tt)*) => {
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1168,8 +1168,9 @@
);
Ok(new_limit)
}
+
pub fn clamp_permissions(
- mode: CollectionMode,
+ _mode: CollectionMode,
old_limit: &CollectionPermissions,
mut new_limit: CollectionPermissions,
) -> Result<CollectionPermissions, DispatchError> {
@@ -1204,6 +1205,22 @@
fn approve() -> Weight;
fn transfer_from() -> Weight;
fn burn_from() -> Weight;
+
+ /// Differs from burn_item in case of Fungible and Refungible, as it should burn
+ /// whole users's balance
+ ///
+ /// This method shouldn't be used directly, as it doesn't count breadth price, use `burn_recursively` instead
+ fn burn_recursively_self_raw() -> Weight;
+ /// Cost of iterating over `amount` children while burning, without counting child burning itself
+ ///
+ /// This method shouldn't be used directly, as it doesn't count depth price, use `burn_recursively` instead
+ fn burn_recursively_breadth_raw(amount: u32) -> Weight;
+
+ fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {
+ Self::burn_recursively_self_raw()
+ .saturating_mul(max_selfs.max(1) as u64)
+ .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))
+ }
}
pub trait CommonCollectionOperations<T: Config> {
@@ -1233,6 +1250,13 @@
token: TokenId,
amount: u128,
) -> DispatchResultWithPostInfo;
+ fn burn_item_recursively(
+ &self,
+ sender: T::CrossAccountId,
+ token: TokenId,
+ self_budget: &dyn Budget,
+ breadth_budget: &dyn Budget,
+ ) -> DispatchResultWithPostInfo;
fn set_collection_properties(
&self,
sender: T::CrossAccountId,
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -25,7 +25,9 @@
const SEED: u32 = 1;
-fn create_collection<T: Config>(owner: T::AccountId) -> Result<FungibleHandle<T>, DispatchError> {
+fn create_collection<T: Config>(
+ owner: T::CrossAccountId,
+) -> Result<FungibleHandle<T>, DispatchError> {
create_collection_raw(
owner,
CollectionMode::Fungible(0),
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -16,9 +16,10 @@
use core::marker::PhantomData;
-use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
+use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};
use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
+use pallet_structure::Error as StructureError;
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
use up_data_structs::{Property, PropertyKey, PropertyValue, PropertyKeyPermission};
@@ -91,6 +92,16 @@
fn burn_from() -> Weight {
<SelfWeightOf<T>>::burn_from()
}
+
+ fn burn_recursively_self_raw() -> Weight {
+ // Read to get total balance
+ Self::burn_item() + T::DbWeight::get().reads(1)
+ }
+
+ fn burn_recursively_breadth_raw(_amount: u32) -> Weight {
+ // Fungible tokens can't have children
+ 0
+ }
}
impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {
@@ -170,6 +181,26 @@
)
}
+ fn burn_item_recursively(
+ &self,
+ sender: T::CrossAccountId,
+ token: TokenId,
+ self_budget: &dyn Budget,
+ _breadth_budget: &dyn Budget,
+ ) -> DispatchResultWithPostInfo {
+ // Should not happen?
+ ensure!(
+ token == TokenId::default(),
+ <Error<T>>::FungibleItemsHaveNoId
+ );
+ ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);
+
+ with_weight(
+ <Pallet<T>>::burn(self, &sender, <Balance<T>>::get((self.id, &sender))),
+ <CommonWeights<T>>::burn_recursively_self_raw(),
+ )
+ }
+
fn transfer(
&self,
from: T::CrossAccountId,
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -18,12 +18,9 @@
use crate::{Pallet, Config, NonfungibleHandle};
use sp_std::prelude::*;
-use pallet_common::benchmarking::{create_collection_raw, create_data, property_key, property_value};
+use pallet_common::benchmarking::{create_collection_raw, property_key, property_value};
use frame_benchmarking::{benchmarks, account};
-use up_data_structs::{
- CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, CUSTOM_DATA_LIMIT,
- budget::Unlimited,
-};
+use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited};
use pallet_common::bench_init;
const SEED: u32 = 1;
@@ -49,7 +46,7 @@
}
fn create_collection<T: Config>(
- owner: T::AccountId,
+ owner: T::CrossAccountId,
) -> Result<NonfungibleHandle<T>, DispatchError> {
create_collection_raw(
owner,
@@ -96,6 +93,26 @@
let item = create_max_item(&collection, &sender, burner.clone())?;
}: {<Pallet<T>>::burn(&collection, &burner, item)?}
+ burn_recursively_self_raw {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); burner: cross_sub;
+ };
+ let item = create_max_item(&collection, &sender, burner.clone())?;
+ }: {<Pallet<T>>::burn_recursively(&collection, &burner, item, &Unlimited, &Unlimited)}
+
+ burn_recursively_breadth_plus_self_plus_self_per_each_raw {
+ let b in 0..200;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); burner: cross_sub;
+ };
+ let item = create_max_item(&collection, &sender, burner.clone())?;
+ for i in 0..b {
+ create_max_item(&collection, &sender, T::CrossTokenAddressMapping::token_to_address(collection.id, item))?;
+ }
+ }: {<Pallet<T>>::burn_recursively(&collection, &burner, item, &Unlimited, &Unlimited)}
+
transfer {
bench_init!{
owner: sub; collection: collection(owner);
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -108,6 +108,15 @@
fn burn_from() -> Weight {
<SelfWeightOf<T>>::burn_from()
}
+
+ fn burn_recursively_self_raw() -> Weight {
+ <SelfWeightOf<T>>::burn_recursively_self_raw()
+ }
+
+ fn burn_recursively_breadth_raw(amount: u32) -> Weight {
+ <SelfWeightOf<T>>::burn_recursively_breadth_plus_self_plus_self_per_each_raw(amount)
+ .saturating_sub(Self::burn_recursively_self_raw().saturating_mul(amount as u64 + 1))
+ }
}
fn map_create_data<T: Config>(
@@ -264,6 +273,16 @@
}
}
+ fn burn_item_recursively(
+ &self,
+ sender: T::CrossAccountId,
+ token: TokenId,
+ self_budget: &dyn Budget,
+ breadth_budget: &dyn Budget,
+ ) -> DispatchResultWithPostInfo {
+ <Pallet<T>>::burn_recursively(self, &sender, token, self_budget, breadth_budget)
+ }
+
fn transfer(
&self,
from: T::CrossAccountId,
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -18,7 +18,13 @@
use erc::ERC721Events;
use evm_coder::ToLog;
-use frame_support::{BoundedVec, ensure, fail, transactional, storage::with_transaction};
+use frame_support::{
+ BoundedVec, ensure, fail, transactional,
+ storage::with_transaction,
+ pallet_prelude::DispatchResultWithPostInfo,
+ pallet_prelude::Weight,
+ weights::{PostDispatchInfo, Pays},
+};
use up_data_structs::{
AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,
@@ -29,7 +35,7 @@
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
eth::collection_id_to_address,
};
-use pallet_structure::Pallet as PalletStructure;
+use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
@@ -39,6 +45,7 @@
use scale_info::TypeInfo;
pub use pallet::*;
+use weights::WeightInfo;
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
pub mod common;
@@ -373,7 +380,7 @@
<PalletCommon<T>>::deposit_event(CommonEvent::Approved(
collection.id,
token,
- sender.clone(),
+ token_data.owner.clone(),
old_spender,
0,
));
@@ -396,6 +403,45 @@
Ok(())
}
+ #[transactional]
+ pub fn burn_recursively(
+ collection: &NonfungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ token: TokenId,
+ self_budget: &dyn Budget,
+ breadth_budget: &dyn Budget,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);
+
+ let current_token_account =
+ T::CrossTokenAddressMapping::token_to_address(collection.id, token);
+
+ let mut weight = 0 as Weight;
+
+ // This method is transactional, if user in fact doesn't have permissions to remove token -
+ // tokens removed here will be restored after rejected transaction
+ for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {
+ ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);
+ let PostDispatchInfo { actual_weight, .. } =
+ <PalletStructure<T>>::burn_item_recursively(
+ current_token_account.clone(),
+ collection,
+ token,
+ self_budget,
+ breadth_budget,
+ )?;
+ if let Some(actual_weight) = actual_weight {
+ weight = weight.saturating_add(actual_weight);
+ }
+ }
+
+ Self::burn(collection, sender, token)?;
+ DispatchResultWithPostInfo::Ok(PostDispatchInfo {
+ actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),
+ pays_fee: Pays::Yes,
+ })
+ }
+
pub fn set_token_property(
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -964,6 +1010,7 @@
);
ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?
}
+ NestingRule::Permissive => {}
}
Ok(())
}
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -36,6 +36,8 @@
fn create_multiple_items(b: u32, ) -> Weight;
fn create_multiple_items_ex(b: u32, ) -> Weight;
fn burn_item() -> Weight;
+ fn burn_recursively_self_raw() -> Weight;
+ fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
fn transfer_from() -> Weight;
@@ -92,7 +94,35 @@
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
-
+ // Storage: Nonfungible TokenChildren (r:1 w:0)
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ // Storage: Nonfungible TokensBurnt (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:1 w:1)
+ // Storage: Nonfungible Allowance (r:1 w:0)
+ // Storage: Nonfungible Owned (r:0 w:1)
+ // Storage: Nonfungible TokenProperties (r:0 w:1)
+ fn burn_recursively_self_raw() -> Weight {
+ (86_136_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(5 as Weight))
+ .saturating_add(T::DbWeight::get().writes(5 as Weight))
+ }
+ // Storage: Nonfungible TokenChildren (r:1 w:0)
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ // Storage: Nonfungible TokensBurnt (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:1 w:1)
+ // Storage: Nonfungible Allowance (r:1 w:0)
+ // Storage: Nonfungible Owned (r:0 w:1)
+ // Storage: Nonfungible TokenProperties (r:0 w:1)
+ // Storage: Common CollectionById (r:1 w:0)
+ fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 42_828_000
+ .saturating_add((381_478_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(6 as Weight))
+ .saturating_add(T::DbWeight::get().reads((4 as Weight).saturating_mul(b as Weight)))
+ .saturating_add(T::DbWeight::get().writes(5 as Weight))
+ .saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
+ }
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible AccountBalance (r:2 w:2)
// Storage: Nonfungible Allowance (r:1 w:0)
@@ -204,7 +234,35 @@
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
-
+ // Storage: Nonfungible TokenChildren (r:1 w:0)
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ // Storage: Nonfungible TokensBurnt (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:1 w:1)
+ // Storage: Nonfungible Allowance (r:1 w:0)
+ // Storage: Nonfungible Owned (r:0 w:1)
+ // Storage: Nonfungible TokenProperties (r:0 w:1)
+ fn burn_recursively_self_raw() -> Weight {
+ (86_136_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(5 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(5 as Weight))
+ }
+ // Storage: Nonfungible TokenChildren (r:1 w:0)
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ // Storage: Nonfungible TokensBurnt (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:1 w:1)
+ // Storage: Nonfungible Allowance (r:1 w:0)
+ // Storage: Nonfungible Owned (r:0 w:1)
+ // Storage: Nonfungible TokenProperties (r:0 w:1)
+ // Storage: Common CollectionById (r:1 w:0)
+ fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 42_828_000
+ .saturating_add((381_478_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(6 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((4 as Weight).saturating_mul(b as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(5 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
+ }
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible AccountBalance (r:2 w:2)
// Storage: Nonfungible Allowance (r:1 w:0)
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -50,7 +50,9 @@
Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
}
-fn create_collection<T: Config>(owner: T::AccountId) -> Result<RefungibleHandle<T>, DispatchError> {
+fn create_collection<T: Config>(
+ owner: T::CrossAccountId,
+) -> Result<RefungibleHandle<T>, DispatchError> {
create_collection_raw(
owner,
CollectionMode::NFT,
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -17,12 +17,13 @@
use core::marker::PhantomData;
use sp_std::collections::btree_map::BTreeMap;
-use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};
+use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};
use up_data_structs::{
CollectionId, TokenId, CreateItemExData, CreateRefungibleExData, budget::Budget, Property,
PropertyKey, PropertyValue, PropertyKeyPermission, CreateItemData,
};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
+use pallet_structure::Error as StructureError;
use sp_runtime::DispatchError;
use sp_std::{vec::Vec, vec};
@@ -113,6 +114,15 @@
fn burn_from() -> Weight {
<SelfWeightOf<T>>::burn_from()
}
+
+ fn burn_recursively_self_raw() -> Weight {
+ // Read to get total balance
+ Self::burn_item() + T::DbWeight::get().reads(1)
+ }
+ fn burn_recursively_breadth_raw(_amount: u32) -> Weight {
+ // Refungible token can't have children
+ 0
+ }
}
fn map_create_data<T: Config>(
@@ -205,6 +215,25 @@
)
}
+ fn burn_item_recursively(
+ &self,
+ sender: T::CrossAccountId,
+ token: TokenId,
+ self_budget: &dyn Budget,
+ _breadth_budget: &dyn Budget,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);
+ with_weight(
+ <Pallet<T>>::burn(
+ self,
+ &sender,
+ token,
+ <Balance<T>>::get((self.id, token, &sender)),
+ ),
+ <CommonWeights<T>>::burn_recursively_self_raw(),
+ )
+ }
+
fn transfer(
&self,
from: T::CrossAccountId,
pallets/scheduler/src/lib.rsdiffbeforeafterboth--- a/pallets/scheduler/src/lib.rs
+++ b/pallets/scheduler/src/lib.rs
@@ -60,8 +60,9 @@
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
-#[cfg(feature = "runtime-benchmarks")]
-mod benchmarking;
+// FIXME
+// #[cfg(feature = "runtime-benchmarks")]
+// mod benchmarking;
pub mod weights;
pallets/structure/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/structure/src/benchmarking.rs
+++ b/pallets/structure/src/benchmarking.rs
@@ -5,6 +5,7 @@
use up_data_structs::{
CreateCollectionData, CollectionMode, CreateItemData, CreateNftData, budget::Unlimited,
};
+use pallet_common::Config as CommonConfig;
use pallet_evm::account::CrossAccountId;
const SEED: u32 = 1;
@@ -14,8 +15,8 @@
let caller: T::AccountId = account("caller", 0, SEED);
let caller_cross = T::CrossAccountId::from_sub(caller.clone());
- T::Currency::deposit_creating(&caller, T::CollectionCreationPrice::get());
- T::CollectionDispatch::create(caller, CreateCollectionData {
+ <T as CommonConfig>::Currency::deposit_creating(&caller, T::CollectionCreationPrice::get());
+ T::CollectionDispatch::create(caller_cross.clone(), CreateCollectionData {
mode: CollectionMode::NFT,
..Default::default()
})?;
pallets/structure/src/lib.rsdiffbeforeafterboth--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -3,7 +3,7 @@
use pallet_common::CommonCollectionOperations;
use sp_std::collections::btree_set::BTreeSet;
-use frame_support::dispatch::{DispatchError, DispatchResult};
+use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo};
use frame_support::fail;
pub use pallet::*;
use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};
@@ -29,6 +29,8 @@
OuroborosDetected,
/// While searched for owner, encountered depth limit
DepthLimit,
+ /// While iterating over children, encountered breadth limit
+ BreadthLimit,
/// While searched for owner, found token owner by not-yet-existing token
TokenNotFound,
}
@@ -184,6 +186,19 @@
Err(<Error<T>>::DepthLimit.into())
}
+ pub fn burn_item_recursively(
+ from: T::CrossAccountId,
+ collection: CollectionId,
+ token: TokenId,
+ self_budget: &dyn Budget,
+ breadth_budget: &dyn Budget,
+ ) -> DispatchResultWithPostInfo {
+ let handle = <CollectionHandle<T>>::try_get(collection)?;
+ let dispatch = T::CollectionDispatch::dispatch(handle);
+ let dispatch = dispatch.as_dyn();
+ dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)
+ }
+
pub fn check_nesting(
from: T::CrossAccountId,
under: &T::CrossAccountId,
pallets/unique/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/unique/src/benchmarking.rs
+++ b/pallets/unique/src/benchmarking.rs
@@ -22,7 +22,10 @@
use frame_support::traits::{tokens::currency::Currency, Get};
use frame_benchmarking::{benchmarks, account};
use sp_runtime::DispatchError;
-use pallet_common::benchmarking::{create_data, create_var_data, create_u16_data};
+use pallet_common::{
+ Config as CommonConfig,
+ benchmarking::{create_data, create_u16_data},
+};
const SEED: u32 = 1;
@@ -30,7 +33,7 @@
owner: T::AccountId,
mode: CollectionMode,
) -> Result<CollectionId, DispatchError> {
- T::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());
+ <T as CommonConfig>::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());
let col_name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
let col_desc = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
@@ -54,7 +57,7 @@
let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
let mode: CollectionMode = CollectionMode::NFT;
let caller: T::AccountId = account("caller", 0, SEED);
- T::Currency::deposit_creating(&caller, T::CollectionCreationPrice::get());
+ <T as CommonConfig>::Currency::deposit_creating(&caller, T::CollectionCreationPrice::get());
}: _(RawOrigin::Signed(caller.clone()), col_name.clone(), col_desc.clone(), token_prefix.clone(), mode)
verify {
assert_eq!(<pallet_common::CollectionById<T>>::get(CollectionId(1)).unwrap().owner, caller);
@@ -77,16 +80,6 @@
let collection = create_nft_collection::<T>(caller.clone())?;
<Pallet<T>>::add_to_allow_list(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(allowlist_account.clone()))?;
}: _(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(allowlist_account))
-
- set_public_access_mode {
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- }: _(RawOrigin::Signed(caller.clone()), collection, AccessMode::AllowList)
-
- set_mint_permission {
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- }: _(RawOrigin::Signed(caller.clone()), collection, true)
change_collection_owner {
let caller: T::AccountId = account("caller", 0, SEED);
@@ -145,7 +138,6 @@
owner_can_transfer: Some(true),
sponsored_data_rate_limit: None,
transfers_enabled: Some(true),
- nesting_rule: None,
};
}: set_collection_limits(RawOrigin::Signed(caller.clone()), collection, cl)
}
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 BasicResource as RmrkBasicResource, ComposableResource as RmrkComposableResource,53 SlotResource as RmrkSlotResource,54};5556mod bounded;57pub mod budget;58pub mod mapping;59mod migration;6061pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;62pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;63pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;6465pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {66 100_00067} else {68 1069};70pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {71 100_00072} else {73 1074};75pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {76 204877} else {78 1079};80pub const COLLECTION_ADMINS_LIMIT: u32 = 5;81pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;82pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {83 1_000_00084} else {85 1086};8788// Timeouts for item types in passed blocks89pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;90pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;91pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;9293pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;9495// Schema limits96pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;97pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;98pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;99100pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;101102pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;103pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;104pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;105106pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;107pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;108pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;109110pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;111pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;112113// RMRK constants114pub const RMRK_STRING_LIMIT: u32 = 128;115pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;116pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;117pub const RMRK_KEY_LIMIT: u32 = 32;118pub const RMRK_VALUE_LIMIT: u32 = 256;119120/// How much items can be created per single121/// create_many call122pub const MAX_ITEMS_PER_BATCH: u32 = 200;123124pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;125126#[derive(127 Encode,128 Decode,129 PartialEq,130 Eq,131 PartialOrd,132 Ord,133 Clone,134 Copy,135 Debug,136 Default,137 TypeInfo,138 MaxEncodedLen,139)]140#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]141pub struct CollectionId(pub u32);142impl EncodeLike<u32> for CollectionId {}143impl EncodeLike<CollectionId> for u32 {}144145#[derive(146 Encode,147 Decode,148 PartialEq,149 Eq,150 PartialOrd,151 Ord,152 Clone,153 Copy,154 Debug,155 Default,156 TypeInfo,157 MaxEncodedLen,158)]159#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]160pub struct TokenId(pub u32);161impl EncodeLike<u32> for TokenId {}162impl EncodeLike<TokenId> for u32 {}163164impl TokenId {165 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {166 self.0167 .checked_add(1)168 .ok_or(ArithmeticError::Overflow)169 .map(Self)170 }171}172173impl From<TokenId> for U256 {174 fn from(t: TokenId) -> Self {175 t.0.into()176 }177}178179impl TryFrom<U256> for TokenId {180 type Error = &'static str;181182 fn try_from(value: U256) -> Result<Self, Self::Error> {183 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))184 }185}186187#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]188#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]189pub struct TokenData<CrossAccountId> {190 pub properties: Vec<Property>,191 pub owner: Option<CrossAccountId>,192}193194pub struct OverflowError;195impl From<OverflowError> for &'static str {196 fn from(_: OverflowError) -> Self {197 "overflow occured"198 }199}200201pub type DecimalPoints = u8;202203#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]204#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]205pub enum CollectionMode {206 NFT,207 // decimal points208 Fungible(DecimalPoints),209 ReFungible,210}211212impl CollectionMode {213 pub fn id(&self) -> u8 {214 match self {215 CollectionMode::NFT => 1,216 CollectionMode::Fungible(_) => 2,217 CollectionMode::ReFungible => 3,218 }219 }220}221222pub trait SponsoringResolve<AccountId, Call> {223 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;224}225226#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]227#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]228pub enum AccessMode {229 Normal,230 AllowList,231}232impl Default for AccessMode {233 fn default() -> Self {234 Self::Normal235 }236}237238#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]239#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]240pub enum SchemaVersion {241 ImageURL,242 Unique,243}244impl Default for SchemaVersion {245 fn default() -> Self {246 Self::ImageURL247 }248}249250#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]251#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]252pub struct Ownership<AccountId> {253 pub owner: AccountId,254 pub fraction: u128,255}256257#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]258#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]259pub enum SponsorshipState<AccountId> {260 /// The fees are applied to the transaction sender261 Disabled,262 Unconfirmed(AccountId),263 /// Transactions are sponsored by specified account264 Confirmed(AccountId),265}266267impl<AccountId> SponsorshipState<AccountId> {268 pub fn sponsor(&self) -> Option<&AccountId> {269 match self {270 Self::Confirmed(sponsor) => Some(sponsor),271 _ => None,272 }273 }274275 pub fn pending_sponsor(&self) -> Option<&AccountId> {276 match self {277 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),278 _ => None,279 }280 }281282 pub fn confirmed(&self) -> bool {283 matches!(self, Self::Confirmed(_))284 }285}286287impl<T> Default for SponsorshipState<T> {288 fn default() -> Self {289 Self::Disabled290 }291}292293/// Used in storage294#[struct_versioning::versioned(version = 2, upper)]295#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]296pub struct Collection<AccountId> {297 pub owner: AccountId,298 pub mode: CollectionMode,299 #[version(..2)]300 pub access: AccessMode,301 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,302 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,303 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,304305 #[version(..2)]306 pub mint_mode: bool,307308 #[version(..2)]309 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,310311 #[version(..2)]312 pub schema_version: SchemaVersion,313 pub sponsorship: SponsorshipState<AccountId>,314315 pub limits: CollectionLimits,316317 #[version(2.., upper(Default::default()))]318 pub permissions: CollectionPermissions,319320 #[version(..2)]321 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,322323 #[version(..2)]324 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,325326 #[version(..2)]327 pub meta_update_permission: MetaUpdatePermission,328}329330/// Used in RPC calls331#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]332#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]333pub struct RpcCollection<AccountId> {334 pub owner: AccountId,335 pub mode: CollectionMode,336 pub name: Vec<u16>,337 pub description: Vec<u16>,338 pub token_prefix: Vec<u8>,339 pub sponsorship: SponsorshipState<AccountId>,340 pub limits: CollectionLimits,341 pub permissions: CollectionPermissions,342 pub token_property_permissions: Vec<PropertyKeyPermission>,343 pub properties: Vec<Property>,344}345346#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]347#[derivative(Debug, Default(bound = ""))]348pub struct CreateCollectionData<AccountId> {349 #[derivative(Default(value = "CollectionMode::NFT"))]350 pub mode: CollectionMode,351 pub access: Option<AccessMode>,352 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,353 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,354 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,355 pub pending_sponsor: Option<AccountId>,356 pub limits: Option<CollectionLimits>,357 pub permissions: Option<CollectionPermissions>,358 pub token_property_permissions: CollectionPropertiesPermissionsVec,359 pub properties: CollectionPropertiesVec,360}361362pub type CollectionPropertiesPermissionsVec =363 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;364365pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;366367/// All fields are wrapped in `Option`s, where None means chain default368// When adding/removing fields from this struct - don't forget to also update clamp_limits369#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]370#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]371pub struct CollectionLimits {372 pub account_token_ownership_limit: Option<u32>,373 pub sponsored_data_size: Option<u32>,374375 /// FIXME should we delete this or repurpose it?376 /// None - setVariableMetadata is not sponsored377 /// Some(v) - setVariableMetadata is sponsored378 /// if there is v block between txs379 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,380 pub token_limit: Option<u32>,381382 // Timeouts for item types in passed blocks383 pub sponsor_transfer_timeout: Option<u32>,384 pub sponsor_approve_timeout: Option<u32>,385 pub owner_can_transfer: Option<bool>,386 pub owner_can_destroy: Option<bool>,387 pub transfers_enabled: Option<bool>,388}389390impl CollectionLimits {391 pub fn account_token_ownership_limit(&self) -> u32 {392 self.account_token_ownership_limit393 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)394 .min(MAX_TOKEN_OWNERSHIP)395 }396 pub fn sponsored_data_size(&self) -> u32 {397 self.sponsored_data_size398 .unwrap_or(CUSTOM_DATA_LIMIT)399 .min(CUSTOM_DATA_LIMIT)400 }401 pub fn token_limit(&self) -> u32 {402 self.token_limit403 .unwrap_or(COLLECTION_TOKEN_LIMIT)404 .min(COLLECTION_TOKEN_LIMIT)405 }406 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {407 self.sponsor_transfer_timeout408 .unwrap_or(default)409 .min(MAX_SPONSOR_TIMEOUT)410 }411 pub fn sponsor_approve_timeout(&self) -> u32 {412 self.sponsor_approve_timeout413 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)414 .min(MAX_SPONSOR_TIMEOUT)415 }416 pub fn owner_can_transfer(&self) -> bool {417 self.owner_can_transfer.unwrap_or(true)418 }419 pub fn owner_can_destroy(&self) -> bool {420 self.owner_can_destroy.unwrap_or(true)421 }422 pub fn transfers_enabled(&self) -> bool {423 self.transfers_enabled.unwrap_or(true)424 }425 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {426 match self427 .sponsored_data_rate_limit428 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)429 {430 SponsoringRateLimit::SponsoringDisabled => None,431 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),432 }433 }434}435436// When adding/removing fields from this struct - don't forget to also update clamp_limits437#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]438#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]439pub struct CollectionPermissions {440 pub access: Option<AccessMode>,441 pub mint_mode: Option<bool>,442 pub nesting: Option<NestingRule>,443}444445impl CollectionPermissions {446 pub fn access(&self) -> AccessMode {447 self.access.unwrap_or(AccessMode::Normal)448 }449 pub fn mint_mode(&self) -> bool {450 self.mint_mode.unwrap_or(false)451 }452 pub fn nesting(&self) -> &NestingRule {453 static DEFAULT: NestingRule = NestingRule::Disabled;454 self.nesting.as_ref().unwrap_or(&DEFAULT)455 }456}457458#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]459#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]460#[derivative(Debug)]461pub enum NestingRule {462 /// No one can nest tokens463 Disabled,464 /// Owner can nest any tokens465 Owner,466 /// Owner can nest tokens from specified collections467 OwnerRestricted(468 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]469 #[derivative(Debug(format_with = "bounded::set_debug"))]470 BoundedBTreeSet<CollectionId, ConstU32<16>>,471 ),472}473474#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]475#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]476pub enum SponsoringRateLimit {477 SponsoringDisabled,478 Blocks(u32),479}480481#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]482#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]483#[derivative(Debug)]484pub struct CreateNftData {485 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]486 #[derivative(Debug(format_with = "bounded::vec_debug"))]487 pub properties: CollectionPropertiesVec,488}489490#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]491#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]492pub struct CreateFungibleData {493 pub value: u128,494}495496#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]497#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]498#[derivative(Debug)]499pub struct CreateReFungibleData {500 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]501 #[derivative(Debug(format_with = "bounded::vec_debug"))]502 pub const_data: BoundedVec<u8, CustomDataLimit>,503 pub pieces: u128,504}505506#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]507#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]508pub enum MetaUpdatePermission {509 ItemOwner,510 Admin,511 None,512}513514#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]515#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]516pub enum CreateItemData {517 NFT(CreateNftData),518 Fungible(CreateFungibleData),519 ReFungible(CreateReFungibleData),520}521522#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]523#[derivative(Debug)]524pub struct CreateNftExData<CrossAccountId> {525 #[derivative(Debug(format_with = "bounded::vec_debug"))]526 pub properties: CollectionPropertiesVec,527 pub owner: CrossAccountId,528}529530#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]531#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]532pub struct CreateRefungibleExData<CrossAccountId> {533 #[derivative(Debug(format_with = "bounded::vec_debug"))]534 pub const_data: BoundedVec<u8, CustomDataLimit>,535 #[derivative(Debug(format_with = "bounded::map_debug"))]536 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,537}538539#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]540#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]541pub enum CreateItemExData<CrossAccountId> {542 NFT(543 #[derivative(Debug(format_with = "bounded::vec_debug"))]544 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,545 ),546 Fungible(547 #[derivative(Debug(format_with = "bounded::map_debug"))]548 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,549 ),550 /// Many tokens, each may have only one owner551 RefungibleMultipleItems(552 #[derivative(Debug(format_with = "bounded::vec_debug"))]553 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,554 ),555 /// Single token, which may have many owners556 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),557}558559impl CreateItemData {560 pub fn data_size(&self) -> usize {561 match self {562 CreateItemData::ReFungible(data) => data.const_data.len(),563 _ => 0,564 }565 }566}567568impl From<CreateNftData> for CreateItemData {569 fn from(item: CreateNftData) -> Self {570 CreateItemData::NFT(item)571 }572}573574impl From<CreateReFungibleData> for CreateItemData {575 fn from(item: CreateReFungibleData) -> Self {576 CreateItemData::ReFungible(item)577 }578}579580impl From<CreateFungibleData> for CreateItemData {581 fn from(item: CreateFungibleData) -> Self {582 CreateItemData::Fungible(item)583 }584}585586#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]587#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]588// todo possibly rename to be used generally as an address pair589pub struct TokenChild {590 pub token: TokenId,591 pub collection: CollectionId,592}593594#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]595#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]596pub struct CollectionStats {597 pub created: u32,598 pub destroyed: u32,599 pub alive: u32,600}601602#[derive(Encode, Decode, Clone, Debug)]603#[cfg_attr(feature = "std", derive(PartialEq))]604pub struct PhantomType<T>(core::marker::PhantomData<T>);605606impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {607 type Identity = PhantomType<T>;608609 fn type_info() -> scale_info::Type {610 use scale_info::{611 Type, Path,612 build::{FieldsBuilder, UnnamedFields},613 type_params,614 };615 Type::builder()616 .path(Path::new("up_data_structs", "PhantomType"))617 .type_params(type_params!(T))618 .composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))619 }620}621impl<T> MaxEncodedLen for PhantomType<T> {622 fn max_encoded_len() -> usize {623 0624 }625}626627pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;628pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;629630#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]631#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]632pub struct PropertyPermission {633 pub mutable: bool,634 pub collection_admin: bool,635 pub token_owner: bool,636}637638impl PropertyPermission {639 pub fn none() -> Self {640 Self {641 mutable: true,642 collection_admin: false,643 token_owner: false,644 }645 }646}647648#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]649#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]650pub struct Property {651 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]652 pub key: PropertyKey,653654 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]655 pub value: PropertyValue,656}657658impl Into<(PropertyKey, PropertyValue)> for Property {659 fn into(self) -> (PropertyKey, PropertyValue) {660 (self.key, self.value)661 }662}663664#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]665#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]666pub struct PropertyKeyPermission {667 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]668 pub key: PropertyKey,669670 pub permission: PropertyPermission,671}672673impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {674 fn into(self) -> (PropertyKey, PropertyPermission) {675 (self.key, self.permission)676 }677}678679#[derive(Debug)]680pub enum PropertiesError {681 NoSpaceForProperty,682 PropertyLimitReached,683 InvalidCharacterInPropertyKey,684 PropertyKeyIsTooLong,685 EmptyPropertyKey,686}687688#[derive(Clone, Copy)]689pub enum PropertyScope {690 None,691 Rmrk,692}693694impl PropertyScope {695 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {696 let scope_str: &[u8] = match self {697 Self::None => return Ok(key),698 Self::Rmrk => b"rmrk",699 };700701 [scope_str, b":", key.as_slice()]702 .concat()703 .try_into()704 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)705 }706}707708pub trait TrySetProperty: Sized {709 type Value;710711 fn try_scoped_set(712 &mut self,713 scope: PropertyScope,714 key: PropertyKey,715 value: Self::Value,716 ) -> Result<(), PropertiesError>;717718 fn try_scoped_set_from_iter<I, KV>(719 &mut self,720 scope: PropertyScope,721 iter: I,722 ) -> Result<(), PropertiesError>723 where724 I: Iterator<Item = KV>,725 KV: Into<(PropertyKey, Self::Value)>,726 {727 for kv in iter {728 let (key, value) = kv.into();729 self.try_scoped_set(scope, key, value)?;730 }731732 Ok(())733 }734735 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {736 self.try_scoped_set(PropertyScope::None, key, value)737 }738739 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>740 where741 I: Iterator<Item = KV>,742 KV: Into<(PropertyKey, Self::Value)>,743 {744 self.try_scoped_set_from_iter(PropertyScope::None, iter)745 }746}747748#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]749#[derivative(Default(bound = ""))]750pub struct PropertiesMap<Value>(751 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,752);753754impl<Value> PropertiesMap<Value> {755 pub fn new() -> Self {756 Self(BoundedBTreeMap::new())757 }758759 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {760 Self::check_property_key(key)?;761762 Ok(self.0.remove(key))763 }764765 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {766 self.0.get(key)767 }768769 pub fn contains_key(&self, key: &PropertyKey) -> bool {770 self.0.contains_key(key)771 }772773 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {774 if key.is_empty() {775 return Err(PropertiesError::EmptyPropertyKey);776 }777778 for byte in key.as_slice().iter() {779 let byte = *byte;780781 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {782 return Err(PropertiesError::InvalidCharacterInPropertyKey);783 }784 }785786 Ok(())787 }788}789790impl<Value> IntoIterator for PropertiesMap<Value> {791 type Item = (PropertyKey, Value);792 type IntoIter = <793 BoundedBTreeMap<794 PropertyKey,795 Value,796 ConstU32<MAX_PROPERTIES_PER_ITEM>797 > as IntoIterator798 >::IntoIter;799800 fn into_iter(self) -> Self::IntoIter {801 self.0.into_iter()802 }803}804805impl<Value> TrySetProperty for PropertiesMap<Value> {806 type Value = Value;807808 fn try_scoped_set(809 &mut self,810 scope: PropertyScope,811 key: PropertyKey,812 value: Self::Value,813 ) -> Result<(), PropertiesError> {814 Self::check_property_key(&key)?;815816 let key = scope.apply(key)?;817 self.0818 .try_insert(key, value)819 .map_err(|_| PropertiesError::PropertyLimitReached)?;820821 Ok(())822 }823}824825pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;826827#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]828pub struct Properties {829 map: PropertiesMap<PropertyValue>,830 consumed_space: u32,831 space_limit: u32,832}833834impl Properties {835 pub fn new(space_limit: u32) -> Self {836 Self {837 map: PropertiesMap::new(),838 consumed_space: 0,839 space_limit,840 }841 }842843 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {844 let value = self.map.remove(key)?;845846 if let Some(ref value) = value {847 let value_len = value.len() as u32;848 self.consumed_space -= value_len;849 }850851 Ok(value)852 }853854 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {855 self.map.get(key)856 }857}858859impl IntoIterator for Properties {860 type Item = (PropertyKey, PropertyValue);861 type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;862863 fn into_iter(self) -> Self::IntoIter {864 self.map.into_iter()865 }866}867868impl TrySetProperty for Properties {869 type Value = PropertyValue;870871 fn try_scoped_set(872 &mut self,873 scope: PropertyScope,874 key: PropertyKey,875 value: Self::Value,876 ) -> Result<(), PropertiesError> {877 let value_len = value.len();878879 if self.consumed_space as usize + value_len > self.space_limit as usize880 && !cfg!(feature = "runtime-benchmarks")881 {882 return Err(PropertiesError::NoSpaceForProperty);883 }884885 self.map.try_scoped_set(scope, key, value)?;886887 self.consumed_space += value_len as u32;888889 Ok(())890 }891}892893pub struct CollectionProperties;894895impl Get<Properties> for CollectionProperties {896 fn get() -> Properties {897 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)898 }899}900901pub struct TokenProperties;902903impl Get<Properties> for TokenProperties {904 fn get() -> Properties {905 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)906 }907}908909// RMRK910// todo document?911parameter_types! {912 #[derive(PartialEq, TypeInfo)]913 pub const RmrkStringLimit: u32 = 128;914 #[derive(PartialEq)]915 pub const RmrkCollectionSymbolLimit: u32 = 100;916 #[derive(PartialEq)]917 pub const RmrkResourceSymbolLimit: u32 = 10;918 #[derive(PartialEq)]919 pub const RmrkKeyLimit: u32 = 32;920 #[derive(PartialEq)]921 pub const RmrkValueLimit: u32 = 256;922 #[derive(PartialEq)]923 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;924 #[derive(PartialEq)]925 pub const RmrkPartsLimit: u32 = 3;926}927928impl From<RmrkCollectionId> for CollectionId {929 fn from(id: RmrkCollectionId) -> Self {930 Self(id)931 }932}933934impl From<RmrkNftId> for TokenId {935 fn from(id: RmrkNftId) -> Self {936 Self(id)937 }938}939940pub type RmrkCollectionInfo<AccountId> =941 CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;942pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;943pub type RmrkResourceInfo = ResourceInfo<RmrkBoundedResource, RmrkString, RmrkBoundedParts>;944pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;945pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;946pub type RmrkPartType =947 PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;948pub type RmrkThemeProperty = ThemeProperty<RmrkString>;949pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;950951pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;952pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;953pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;954955type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;956type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>;957958pub type RmrkRpcString = Vec<u8>;959pub type RmrkThemeName = RmrkRpcString;960pub type RmrkPropertyKey = RmrkRpcString;961962pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;runtime/common/src/weights.rsdiffbeforeafterboth--- a/runtime/common/src/weights.rs
+++ b/runtime/common/src/weights.rs
@@ -89,4 +89,12 @@
fn burn_from() -> Weight {
dispatch_weight::<T>() + max_weight_of!(burn_from())
}
+
+ fn burn_recursively_self_raw() -> Weight {
+ max_weight_of!(burn_recursively_self_raw())
+ }
+
+ fn burn_recursively_breadth_raw(amount: u32) -> Weight {
+ max_weight_of!(burn_recursively_breadth_raw(amount))
+ }
}
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -73,6 +73,7 @@
CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits,
CollectionStats, RpcCollection,
mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping},
+ TokenChild,
};
// use pallet_contracts::weights::WeightInfo;