difftreelog
refactor move ChainLimits to runtime config
in: master
6 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56use cumulus_primitives_core::ParaId;7use nft_runtime::*;8use nft_data_structs::*;9use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};10use sc_service::ChainType;11use sp_core::{sr25519, Pair, Public};12use sp_runtime::traits::{IdentifyAccount, Verify};13use std::collections::BTreeMap;1415use serde::{Deserialize, Serialize};16use serde_json::map::Map;1718/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.19pub type ChainSpec = sc_service::GenericChainSpec<nft_runtime::GenesisConfig, Extensions>;2021/// Helper function to generate a crypto pair from seed22pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {23 TPublic::Pair::from_string(&format!("//{}", seed), None)24 .expect("static values are valid; qed")25 .public()26}2728/// The extensions for the [`ChainSpec`].29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)]30#[serde(deny_unknown_fields)]31pub struct Extensions {32 /// The relay chain of the Parachain.33 pub relay_chain: String,34 /// The id of the Parachain.35 pub para_id: u32,36}3738impl Extensions {39 /// Try to get the extension from the given `ChainSpec`.40 pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> {41 sc_chain_spec::get_extension(chain_spec.extensions())42 }43}4445type AccountPublic = <Signature as Verify>::Signer;4647/// Helper function to generate an account ID from seed48pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId49where50 AccountPublic: From<<TPublic::Pair as Pair>::Public>,51{52 AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()53}5455pub fn development_config(id: ParaId) -> ChainSpec {56 let mut properties = Map::new();57 properties.insert("tokenSymbol".into(), "testUNQ".into());58 properties.insert("tokenDecimals".into(), 15.into());59 properties.insert("ss58Format".into(), 42.into()); // Generic Substrate wildcard (SS58 checksum preimage)6061 ChainSpec::from_genesis(62 // Name63 "Development",64 // ID65 "dev",66 ChainType::Local,67 move || {68 testnet_genesis(69 // Sudo account70 get_account_id_from_seed::<sr25519::Public>("Alice"),71 vec![72 get_from_seed::<AuraId>("Alice"),73 get_from_seed::<AuraId>("Bob"),74 ],75 // Pre-funded accounts76 vec![77 get_account_id_from_seed::<sr25519::Public>("Alice"),78 get_account_id_from_seed::<sr25519::Public>("Bob"),79 ],80 id,81 )82 },83 // Bootnodes84 vec![],85 // Telemetry86 None,87 // Protocol ID88 None,89 // Properties90 Some(properties),91 // Extensions92 Extensions {93 relay_chain: "rococo-dev".into(),94 para_id: id.into(),95 },96 )97}9899pub fn local_testnet_config(id: ParaId) -> ChainSpec {100 ChainSpec::from_genesis(101 // Name102 "Local Testnet",103 // ID104 "local_testnet",105 ChainType::Local,106 move || {107 testnet_genesis(108 // Sudo account109 get_account_id_from_seed::<sr25519::Public>("Alice"),110 vec![111 get_from_seed::<AuraId>("Alice"),112 get_from_seed::<AuraId>("Bob"),113 ],114 // Pre-funded accounts115 vec![116 get_account_id_from_seed::<sr25519::Public>("Alice"),117 get_account_id_from_seed::<sr25519::Public>("Bob"),118 get_account_id_from_seed::<sr25519::Public>("Charlie"),119 get_account_id_from_seed::<sr25519::Public>("Dave"),120 get_account_id_from_seed::<sr25519::Public>("Eve"),121 get_account_id_from_seed::<sr25519::Public>("Ferdie"),122 get_account_id_from_seed::<sr25519::Public>("Alice//stash"),123 get_account_id_from_seed::<sr25519::Public>("Bob//stash"),124 get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),125 get_account_id_from_seed::<sr25519::Public>("Dave//stash"),126 get_account_id_from_seed::<sr25519::Public>("Eve//stash"),127 get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),128 ],129 id,130 )131 },132 // Bootnodes133 vec![],134 // Telemetry135 None,136 // Protocol ID137 None,138 // Properties139 None,140 // Extensions141 Extensions {142 relay_chain: "rococo-local".into(),143 para_id: id.into(),144 },145 )146}147148fn testnet_genesis(149 root_key: AccountId,150 initial_authorities: Vec<AuraId>,151 endowed_accounts: Vec<AccountId>,152 id: ParaId,153) -> GenesisConfig {154 let vested_accounts = vec![get_account_id_from_seed::<sr25519::Public>("Bob")];155156 GenesisConfig {157 system: nft_runtime::SystemConfig {158 code: nft_runtime::WASM_BINARY159 .expect("WASM binary was not build, please build it!")160 .to_vec(),161 changes_trie_config: Default::default(),162 },163 balances: BalancesConfig {164 balances: endowed_accounts165 .iter()166 .cloned()167 .map(|k| (k, 1 << 70))168 .collect(),169 },170 treasury: Default::default(),171 sudo: SudoConfig { key: root_key },172 vesting: VestingConfig {173 vesting: vested_accounts174 .iter()175 .cloned()176 .map(|k| (k, 1000, 100, 1 << 98))177 .collect(),178 },179 nft: NftConfig {180 collection_id: vec![(181 1,182 Collection {183 owner: get_account_id_from_seed::<sr25519::Public>("Alice"),184 mode: CollectionMode::NFT,185 access: AccessMode::Normal,186 decimal_points: 0,187 name: vec![],188 description: vec![],189 token_prefix: vec![],190 mint_mode: false,191 offchain_schema: vec![],192 schema_version: SchemaVersion::default(),193 sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<194 sr25519::Public,195 >("Alice")),196 const_on_chain_schema: vec![],197 variable_on_chain_schema: vec![],198 limits: CollectionLimits::default(),199 transfers_enabled: true,200 },201 )],202 nft_item_id: vec![],203 fungible_item_id: vec![],204 refungible_item_id: vec![],205 chain_limit: ChainLimits {206 collection_numbers_limit: 100000,207 account_token_ownership_limit: 1000000,208 collections_admins_limit: 5,209 custom_data_limit: 2048,210 nft_sponsor_transfer_timeout: 15,211 fungible_sponsor_transfer_timeout: 15,212 refungible_sponsor_transfer_timeout: 15,213 offchain_schema_limit: 1024,214 variable_on_chain_schema_limit: 1024,215 const_on_chain_schema_limit: 1024,216 },217 },218 parachain_info: nft_runtime::ParachainInfoConfig { parachain_id: id },219 aura: nft_runtime::AuraConfig {220 authorities: initial_authorities,221 },222 aura_ext: Default::default(),223 evm: EVMConfig {224 accounts: BTreeMap::new(),225 },226 ethereum: EthereumConfig {},227 }228}1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56use cumulus_primitives_core::ParaId;7use nft_runtime::*;8use nft_data_structs::*;9use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};10use sc_service::ChainType;11use sp_core::{sr25519, Pair, Public};12use sp_runtime::traits::{IdentifyAccount, Verify};13use std::collections::BTreeMap;1415use serde::{Deserialize, Serialize};16use serde_json::map::Map;1718/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.19pub type ChainSpec = sc_service::GenericChainSpec<nft_runtime::GenesisConfig, Extensions>;2021/// Helper function to generate a crypto pair from seed22pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {23 TPublic::Pair::from_string(&format!("//{}", seed), None)24 .expect("static values are valid; qed")25 .public()26}2728/// The extensions for the [`ChainSpec`].29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)]30#[serde(deny_unknown_fields)]31pub struct Extensions {32 /// The relay chain of the Parachain.33 pub relay_chain: String,34 /// The id of the Parachain.35 pub para_id: u32,36}3738impl Extensions {39 /// Try to get the extension from the given `ChainSpec`.40 pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> {41 sc_chain_spec::get_extension(chain_spec.extensions())42 }43}4445type AccountPublic = <Signature as Verify>::Signer;4647/// Helper function to generate an account ID from seed48pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId49where50 AccountPublic: From<<TPublic::Pair as Pair>::Public>,51{52 AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()53}5455pub fn development_config(id: ParaId) -> ChainSpec {56 let mut properties = Map::new();57 properties.insert("tokenSymbol".into(), "testUNQ".into());58 properties.insert("tokenDecimals".into(), 15.into());59 properties.insert("ss58Format".into(), 42.into()); // Generic Substrate wildcard (SS58 checksum preimage)6061 ChainSpec::from_genesis(62 // Name63 "Development",64 // ID65 "dev",66 ChainType::Local,67 move || {68 testnet_genesis(69 // Sudo account70 get_account_id_from_seed::<sr25519::Public>("Alice"),71 vec![72 get_from_seed::<AuraId>("Alice"),73 get_from_seed::<AuraId>("Bob"),74 ],75 // Pre-funded accounts76 vec![77 get_account_id_from_seed::<sr25519::Public>("Alice"),78 get_account_id_from_seed::<sr25519::Public>("Bob"),79 ],80 id,81 )82 },83 // Bootnodes84 vec![],85 // Telemetry86 None,87 // Protocol ID88 None,89 // Properties90 Some(properties),91 // Extensions92 Extensions {93 relay_chain: "rococo-dev".into(),94 para_id: id.into(),95 },96 )97}9899pub fn local_testnet_config(id: ParaId) -> ChainSpec {100 ChainSpec::from_genesis(101 // Name102 "Local Testnet",103 // ID104 "local_testnet",105 ChainType::Local,106 move || {107 testnet_genesis(108 // Sudo account109 get_account_id_from_seed::<sr25519::Public>("Alice"),110 vec![111 get_from_seed::<AuraId>("Alice"),112 get_from_seed::<AuraId>("Bob"),113 ],114 // Pre-funded accounts115 vec![116 get_account_id_from_seed::<sr25519::Public>("Alice"),117 get_account_id_from_seed::<sr25519::Public>("Bob"),118 get_account_id_from_seed::<sr25519::Public>("Charlie"),119 get_account_id_from_seed::<sr25519::Public>("Dave"),120 get_account_id_from_seed::<sr25519::Public>("Eve"),121 get_account_id_from_seed::<sr25519::Public>("Ferdie"),122 get_account_id_from_seed::<sr25519::Public>("Alice//stash"),123 get_account_id_from_seed::<sr25519::Public>("Bob//stash"),124 get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),125 get_account_id_from_seed::<sr25519::Public>("Dave//stash"),126 get_account_id_from_seed::<sr25519::Public>("Eve//stash"),127 get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),128 ],129 id,130 )131 },132 // Bootnodes133 vec![],134 // Telemetry135 None,136 // Protocol ID137 None,138 // Properties139 None,140 // Extensions141 Extensions {142 relay_chain: "rococo-local".into(),143 para_id: id.into(),144 },145 )146}147148fn testnet_genesis(149 root_key: AccountId,150 initial_authorities: Vec<AuraId>,151 endowed_accounts: Vec<AccountId>,152 id: ParaId,153) -> GenesisConfig {154 let vested_accounts = vec![get_account_id_from_seed::<sr25519::Public>("Bob")];155156 GenesisConfig {157 system: nft_runtime::SystemConfig {158 code: nft_runtime::WASM_BINARY159 .expect("WASM binary was not build, please build it!")160 .to_vec(),161 changes_trie_config: Default::default(),162 },163 balances: BalancesConfig {164 balances: endowed_accounts165 .iter()166 .cloned()167 .map(|k| (k, 1 << 70))168 .collect(),169 },170 treasury: Default::default(),171 sudo: SudoConfig { key: root_key },172 vesting: VestingConfig {173 vesting: vested_accounts174 .iter()175 .cloned()176 .map(|k| (k, 1000, 100, 1 << 98))177 .collect(),178 },179 nft: NftConfig {180 collection_id: vec![(181 1,182 Collection {183 owner: get_account_id_from_seed::<sr25519::Public>("Alice"),184 mode: CollectionMode::NFT,185 access: AccessMode::Normal,186 decimal_points: 0,187 name: vec![],188 description: vec![],189 token_prefix: vec![],190 mint_mode: false,191 offchain_schema: vec![],192 schema_version: SchemaVersion::default(),193 sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<194 sr25519::Public,195 >("Alice")),196 const_on_chain_schema: vec![],197 variable_on_chain_schema: vec![],198 limits: CollectionLimits::default(),199 transfers_enabled: true,200 },201 )],202 nft_item_id: vec![],203 fungible_item_id: vec![],204 refungible_item_id: vec![],205 },206 parachain_info: nft_runtime::ParachainInfoConfig { parachain_id: id },207 aura: nft_runtime::AuraConfig {208 authorities: initial_authorities,209 },210 aura_ext: Default::default(),211 evm: EVMConfig {212 accounts: BTreeMap::new(),213 },214 ethereum: EthereumConfig {},215 }216}pallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth--- a/pallets/nft/src/eth/sponsoring.rs
+++ b/pallets/nft/src/eth/sponsoring.rs
@@ -1,12 +1,13 @@
//! Implements EVM sponsoring logic via OnChargeEVMTransaction
use crate::{
- ChainLimit, Collection, CollectionById, Config, FungibleTransferBasket, NftTransferBasket,
- eth::{account::EvmBackwardsAddressMapping, map_eth_to_id},
+ Collection, CollectionById, Config, FungibleTransferBasket, NftTransferBasket,
+ eth::{account::EvmBackwardsAddressMapping, map_eth_to_id}, limit,
};
use evm_coder::{Call, abi::AbiReader};
use frame_support::{
- storage::{StorageMap, StorageDoubleMap, StorageValue},
+ storage::{StorageMap, StorageDoubleMap},
+ traits::Get,
};
use sp_core::H160;
use sp_std::prelude::*;
@@ -43,7 +44,7 @@
let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
collection_limits.sponsor_transfer_timeout
} else {
- ChainLimit::get().nft_sponsor_transfer_timeout
+ <limit!(T, NftSponsorTransferTimeout)>::get()
};
let mut sponsor = true;
@@ -74,7 +75,7 @@
let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
collection_limits.sponsor_transfer_timeout
} else {
- ChainLimit::get().fungible_sponsor_transfer_timeout
+ <limit!(T, FungibleSponsorTransferTimeout)>::get()
};
let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -31,7 +31,7 @@
StorageValue, transactional,
};
-use frame_system::{self as system, ensure_signed, ensure_root};
+use frame_system::{self as system, ensure_signed};
use sp_core::H160;
use sp_std::vec;
use sp_runtime::sp_std::prelude::Vec;
@@ -243,6 +243,15 @@
<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,
>;
type TreasuryAccountId: Get<Self::AccountId>;
+ type ChainLimits: ChainLimits;
+}
+
+pub type ChainLimitsOf<T> = <T as Config>::ChainLimits;
+#[macro_export]
+macro_rules! limit {
+ ($config:ty, $limit:ident) => {
+ <$crate::ChainLimitsOf<$config> as nft_data_structs::ChainLimits>::$limit
+ }
}
// # Used definitions
@@ -280,10 +289,6 @@
ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;
//#endregion
- //#region Chain limits struct
- pub ChainLimit get(fn chain_limit) config(): ChainLimits;
- //#endregion
-
//#region Bound counters
/// Amount of collections destroyed, used for total amount tracking with
/// CreatedCollectionCount
@@ -485,14 +490,12 @@
CollectionMode::Fungible(points) => points,
_ => 0
};
-
- let chain_limit = ChainLimit::get();
let created_count = CreatedCollectionCount::get();
let destroyed_count = DestroyedCollectionCount::get();
// bound Total number of collections
- ensure!(created_count - destroyed_count < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);
+ ensure!(created_count - destroyed_count < <limit!(T, CollectionNumberLimit)>::get(), Error::<T>::TotalCollectionsLimitExceeded);
// check params
ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
@@ -508,7 +511,7 @@
CreatedCollectionCount::put(next_id);
let limits = CollectionLimits {
- sponsored_data_size: chain_limit.custom_data_limit,
+ sponsored_data_size: <limit!(T, CustomDataLimit)>::get(),
..Default::default()
};
@@ -737,8 +740,7 @@
match admin_arr.binary_search(&new_admin_id) {
Ok(_) => {},
Err(idx) => {
- let limits = ChainLimit::get();
- ensure!(admin_arr.len() < limits.collections_admins_limit as usize, Error::<T>::CollectionAdminsLimitExceeded);
+ ensure!(admin_arr.len() < <limit!(T, CollectionAdminsLimit)>::get() as usize, Error::<T>::CollectionAdminsLimitExceeded);
admin_arr.insert(idx, new_admin_id);
<AdminList<T>>::insert(collection_id, admin_arr);
}
@@ -862,7 +864,7 @@
#[weight = <T as Config>::WeightInfo::create_item(data.data_size())]
#[transactional]
- pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResult {
+ pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData<ChainLimitsOf<T>>) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let collection = Self::get_collection(collection_id)?;
@@ -893,7 +895,7 @@
.map(|data| { data.data_size() })
.sum())]
#[transactional]
- pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResult {
+ pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData<ChainLimitsOf<T>>>) -> DispatchResult {
ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
@@ -1138,7 +1140,7 @@
Self::check_owner_or_admin_permissions(&target_collection, &sender)?;
// check schema limit
- ensure!(schema.len() as u32 <= ChainLimit::get().offchain_schema_limit, "");
+ ensure!(schema.len() as u32 <= <limit!(T, OffchainSchemaLimit)>::get(), "");
target_collection.offchain_schema = schema;
target_collection.save()
@@ -1168,7 +1170,7 @@
Self::check_owner_or_admin_permissions(&target_collection, &sender)?;
// check schema limit
- ensure!(schema.len() as u32 <= ChainLimit::get().const_on_chain_schema_limit, "");
+ ensure!(schema.len() as u32 <= <limit!(T, ConstOnChainSchemaLimit)>::get(), "");
target_collection.const_on_chain_schema = schema;
target_collection.save()
@@ -1198,25 +1200,10 @@
Self::check_owner_or_admin_permissions(&target_collection, &sender)?;
// check schema limit
- ensure!(schema.len() as u32 <= ChainLimit::get().variable_on_chain_schema_limit, "");
+ ensure!(schema.len() as u32 <= <limit!(T, VariableOnChainSchemaLimit)>::get(), "");
target_collection.variable_on_chain_schema = schema;
target_collection.save()
- }
-
- // Sudo permissions function
- #[weight = <T as Config>::WeightInfo::set_chain_limits()]
- #[transactional]
- pub fn set_chain_limits(
- origin,
- limits: ChainLimits
- ) -> DispatchResult {
-
- #[cfg(not(feature = "runtime-benchmarks"))]
- ensure_root(origin)?;
-
- <ChainLimit>::put(limits);
- Ok(())
}
#[weight = <T as Config>::WeightInfo::set_collection_limits()]
@@ -1230,12 +1217,11 @@
let mut target_collection = Self::get_collection(collection_id)?;
Self::check_owner_permissions(&target_collection, sender.as_sub())?;
let old_limits = &target_collection.limits;
- let chain_limits = ChainLimit::get();
// collection bounds
ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&
new_limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP &&
- new_limits.sponsored_data_size <= chain_limits.custom_data_limit,
+ new_limits.sponsored_data_size <= <ChainLimitsOf<T> as ChainLimits>::CustomDataLimit::get(),
Error::<T>::CollectionLimitBoundsExceeded);
// token_limit check prev
@@ -1260,7 +1246,7 @@
sender: &T::CrossAccountId,
collection: &CollectionHandle<T>,
owner: &T::CrossAccountId,
- data: CreateItemData,
+ data: CreateItemData<ChainLimitsOf<T>>,
) -> DispatchResult {
Self::can_create_items_in_collection(collection, sender, owner, 1)?;
Self::validate_create_item_args(collection, &data)?;
@@ -1471,7 +1457,7 @@
Self::token_exists(collection, item_id)?;
ensure!(
- ChainLimit::get().custom_data_limit >= data.len() as u32,
+ <limit!(T, CustomDataLimit)>::get() >= data.len() as u32,
Error::<T>::TokenVariableDataLimitExceeded
);
@@ -1498,7 +1484,7 @@
sender: &T::CrossAccountId,
collection: &CollectionHandle<T>,
owner: &T::CrossAccountId,
- items_data: Vec<CreateItemData>,
+ items_data: Vec<CreateItemData<ChainLimitsOf<T>>>,
) -> DispatchResult {
Self::can_create_items_in_collection(collection, sender, owner, items_data.len() as u32)?;
@@ -1612,18 +1598,18 @@
fn validate_create_item_args(
target_collection: &CollectionHandle<T>,
- data: &CreateItemData,
+ data: &CreateItemData<ChainLimitsOf<T>>,
) -> DispatchResult {
match target_collection.mode {
CollectionMode::NFT => {
if let CreateItemData::NFT(data) = data {
// check sizes
ensure!(
- ChainLimit::get().custom_data_limit >= data.const_data.len() as u32,
+ <limit!(T, CustomDataLimit)>::get() >= data.const_data.len() as u32,
Error::<T>::TokenConstDataLimitExceeded
);
ensure!(
- ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32,
+ <limit!(T, CustomDataLimit)>::get() >= data.variable_data.len() as u32,
Error::<T>::TokenVariableDataLimitExceeded
);
} else {
@@ -1640,11 +1626,11 @@
if let CreateItemData::ReFungible(data) = data {
// check sizes
ensure!(
- ChainLimit::get().custom_data_limit >= data.const_data.len() as u32,
+ <limit!(T, CustomDataLimit)>::get() >= data.const_data.len() as u32,
Error::<T>::TokenConstDataLimitExceeded
);
ensure!(
- ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32,
+ <limit!(T, CustomDataLimit)>::get() >= data.variable_data.len() as u32,
Error::<T>::TokenVariableDataLimitExceeded
);
@@ -1669,7 +1655,7 @@
fn create_item_no_validation(
collection: &CollectionHandle<T>,
owner: &T::CrossAccountId,
- data: CreateItemData,
+ data: CreateItemData<ChainLimitsOf<T>>,
) -> DispatchResult {
match data {
CreateItemData::NFT(data) => {
@@ -2292,7 +2278,7 @@
// bound Owned tokens by a single address
let count = <AccountItemCount<T>>::get(owner.as_sub());
ensure!(
- count < ChainLimit::get().account_token_ownership_limit,
+ count < <limit!(T, AccountTokenOwnershipLimit)>::get(),
Error::<T>::AddressOwnershipLimitExceeded
);
pallets/nft/src/sponsorship.rsdiffbeforeafterboth--- a/pallets/nft/src/sponsorship.rs
+++ b/pallets/nft/src/sponsorship.rs
@@ -1,13 +1,13 @@
use crate::{
Config, Call, CollectionById, CreateItemBasket, VariableMetaDataBasket,
- ReFungibleTransferBasket, FungibleTransferBasket, NftTransferBasket, ChainLimit,
- CreateItemData, CollectionMode,
+ ReFungibleTransferBasket, FungibleTransferBasket, NftTransferBasket,
+ CreateItemData, CollectionMode, limit,
};
use core::marker::PhantomData;
use up_sponsorship::SponsorshipHandler;
use frame_support::{
- traits::IsSubType,
- storage::{StorageMap, StorageDoubleMap, StorageValue},
+ traits::{IsSubType, Get},
+ storage::{StorageMap, StorageDoubleMap},
};
use nft_data_structs::{TokenId, CollectionId};
@@ -16,7 +16,7 @@
pub fn withdraw_create_item(
who: &T::AccountId,
collection_id: &CollectionId,
- _properties: &CreateItemData,
+ _properties: &CreateItemData<T::ChainLimits>,
) -> Option<T::AccountId> {
let collection = CollectionById::<T>::get(collection_id)?;
@@ -47,7 +47,6 @@
item_id: &TokenId,
) -> Option<T::AccountId> {
let collection = CollectionById::<T>::get(collection_id)?;
- let limits = ChainLimit::get();
let mut sponsor_transfer = false;
if collection.sponsorship.confirmed() {
@@ -62,7 +61,7 @@
let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
collection_limits.sponsor_transfer_timeout
} else {
- limits.nft_sponsor_transfer_timeout
+ <limit!(T, NftSponsorTransferTimeout)>::get()
};
let mut sponsored = true;
@@ -84,7 +83,7 @@
let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
collection_limits.sponsor_transfer_timeout
} else {
- limits.fungible_sponsor_transfer_timeout
+ <limit!(T, FungibleSponsorTransferTimeout)>::get()
};
let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
@@ -107,7 +106,7 @@
let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
collection_limits.sponsor_transfer_timeout
} else {
- limits.refungible_sponsor_transfer_timeout
+ <limit!(T, ReFungibleSponsorTransferTimeout)>::get()
};
let mut sponsored = true;
primitives/nft/src/lib.rsdiffbeforeafterboth--- a/primitives/nft/src/lib.rs
+++ b/primitives/nft/src/lib.rs
@@ -28,14 +28,6 @@
pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;
pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;
-// TODO: Somehow use ChainLimits for BoundedVec len calculation?
-// Do we need ChainLimits anyway, if we can change them via forkless upgrades?
-parameter_types! {
-pub const MaxDataSize: u32 = 2048;
-// TODO: This limit isn't checked for substrate create_multiple_items call
-pub const MaxItemsPerBatch: u32 = 200;
-}
-
pub type CollectionId = u32;
pub type TokenId = u32;
pub type DecimalPoints = u8;
@@ -211,23 +203,25 @@
}
}
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub struct ChainLimits {
- pub collection_numbers_limit: u32,
- pub account_token_ownership_limit: u32,
- pub collections_admins_limit: u64,
- pub custom_data_limit: u32,
+pub trait ChainLimits {
+ type CollectionNumberLimit: Get<u32>;
+ type AccountTokenOwnershipLimit: Get<u32>;
+ type CollectionAdminsLimit: Get<u64>;
+ type CustomDataLimit: Get<u32>;
// Timeouts for item types in passed blocks
- pub nft_sponsor_transfer_timeout: u32,
- pub fungible_sponsor_transfer_timeout: u32,
- pub refungible_sponsor_transfer_timeout: u32,
+ type NftSponsorTransferTimeout: Get<u32>;
+ type FungibleSponsorTransferTimeout: Get<u32>;
+ type ReFungibleSponsorTransferTimeout: Get<u32>;
// Schema limits
- pub offchain_schema_limit: u32,
- pub variable_on_chain_schema_limit: u32,
- pub const_on_chain_schema_limit: u32,
+ type OffchainSchemaLimit: Get<u32>;
+ type VariableOnChainSchemaLimit: Get<u32>;
+ type ConstOnChainSchemaLimit: Get<u32>;
+
+ /// How much items can be created per single
+ /// create_many call
+ type MaxItemsPerBatch: Get<u32>;
}
/// BoundedVec doesn't supports serde
@@ -263,16 +257,16 @@
}
}
-#[derive(Encode, Decode, MaxEncodedLen, Default, Derivative, Clone, PartialEq)]
+#[derive(Encode, Decode, MaxEncodedLen, Default, Derivative)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-#[derivative(Debug)]
-pub struct CreateNftData {
+#[derivative(Debug(bound = ""), PartialEq(bound = ""), Clone(bound = ""))]
+pub struct CreateNftData<T: ChainLimits> {
#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
#[derivative(Debug = "ignore")]
- pub const_data: BoundedVec<u8, MaxDataSize>,
+ pub const_data: BoundedVec<u8, T::CustomDataLimit>,
#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
#[derivative(Debug = "ignore")]
- pub variable_data: BoundedVec<u8, MaxDataSize>,
+ pub variable_data: BoundedVec<u8, T::CustomDataLimit>,
}
#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq)]
@@ -281,28 +275,29 @@
pub value: u128,
}
-#[derive(Encode, Decode, MaxEncodedLen, Default, Derivative, Clone, PartialEq)]
+#[derive(Encode, Decode, MaxEncodedLen, Default, Derivative)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-#[derivative(Debug)]
-pub struct CreateReFungibleData {
+#[derivative(Debug(bound = ""), PartialEq(bound = ""), Clone(bound = ""))]
+pub struct CreateReFungibleData<T: ChainLimits> {
#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
#[derivative(Debug = "ignore")]
- pub const_data: BoundedVec<u8, MaxDataSize>,
+ pub const_data: BoundedVec<u8, T::CustomDataLimit>,
#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
#[derivative(Debug = "ignore")]
- pub variable_data: BoundedVec<u8, MaxDataSize>,
+ pub variable_data: BoundedVec<u8, T::CustomDataLimit>,
pub pieces: u128,
}
-#[derive(Encode, Decode, MaxEncodedLen, Debug, Clone, PartialEq)]
+#[derive(Encode, Decode, MaxEncodedLen, Derivative)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub enum CreateItemData {
- NFT(CreateNftData),
+#[derivative(Debug(bound = ""), PartialEq(bound = ""), Clone(bound = ""))]
+pub enum CreateItemData<T: ChainLimits> {
+ NFT(CreateNftData<T>),
Fungible(CreateFungibleData),
- ReFungible(CreateReFungibleData),
+ ReFungible(CreateReFungibleData<T>),
}
-impl CreateItemData {
+impl<T: ChainLimits> CreateItemData<T> {
pub fn data_size(&self) -> usize {
match self {
CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),
@@ -312,19 +307,19 @@
}
}
-impl From<CreateNftData> for CreateItemData {
- fn from(item: CreateNftData) -> Self {
+impl<T: ChainLimits> From<CreateNftData<T>> for CreateItemData<T> {
+ fn from(item: CreateNftData<T>) -> Self {
CreateItemData::NFT(item)
}
}
-impl From<CreateReFungibleData> for CreateItemData {
- fn from(item: CreateReFungibleData) -> Self {
+impl<T: ChainLimits> From<CreateReFungibleData<T>> for CreateItemData<T> {
+ fn from(item: CreateReFungibleData<T>) -> Self {
CreateItemData::ReFungible(item)
}
}
-impl From<CreateFungibleData> for CreateItemData {
+impl<T: ChainLimits> From<CreateFungibleData> for CreateItemData<T> {
fn from(item: CreateFungibleData) -> Self {
CreateItemData::Fungible(item)
}
runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -683,6 +683,35 @@
}
parameter_types! {
+ pub const CollectionNumberLimit: u32 = 100000;
+ pub const AccountTokenOwnershipLimit: u32 = 1000000;
+ pub const CollectionAdminsLimit: u64 = 5;
+ pub const CustomDataLimit: u32 = 2048;
+ pub const NftSponsorTransferTimeout: u32 = 5;
+ pub const FungibleSponsorTransferTimeout: u32 = 5;
+ pub const ReFungibleSponsorTransferTimeout: u32 = 5;
+ pub const OffchainSchemaLimit: u32 = 1024;
+ pub const VariableOnChainSchemaLimit: u32 = 1024;
+ pub const ConstOnChainSchemaLimit: u32 = 1024;
+ pub const MaxItemsPerBatch: u32 = 200;
+}
+
+pub struct ChainLimits;
+impl nft_data_structs::ChainLimits for ChainLimits {
+ type CollectionNumberLimit = CollectionNumberLimit;
+ type AccountTokenOwnershipLimit = AccountTokenOwnershipLimit;
+ type CollectionAdminsLimit = CollectionAdminsLimit;
+ type CustomDataLimit = CustomDataLimit;
+ type NftSponsorTransferTimeout = NftSponsorTransferTimeout;
+ type FungibleSponsorTransferTimeout = FungibleSponsorTransferTimeout;
+ type ReFungibleSponsorTransferTimeout = ReFungibleSponsorTransferTimeout;
+ type OffchainSchemaLimit = OffchainSchemaLimit;
+ type VariableOnChainSchemaLimit = VariableOnChainSchemaLimit;
+ type ConstOnChainSchemaLimit = ConstOnChainSchemaLimit;
+ type MaxItemsPerBatch = MaxItemsPerBatch;
+}
+
+parameter_types! {
pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();
pub const CollectionCreationPrice: Balance = 100 * UNIQUE;
}
@@ -699,6 +728,7 @@
type Currency = Balances;
type CollectionCreationPrice = CollectionCreationPrice;
type TreasuryAccountId = TreasuryAccountId;
+ type ChainLimits = ChainLimits;
}
parameter_types! {