difftreelog
Remove variableOnChainSchema
in: master
12 files changed
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -19,7 +19,7 @@
use up_data_structs::{
CollectionMode, CreateCollectionData, CollectionId, MAX_COLLECTION_NAME_LENGTH,
MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, OFFCHAIN_SCHEMA_LIMIT,
- VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
+ CONST_ON_CHAIN_SCHEMA_LIMIT,
};
use frame_support::{
traits::{Currency, Get},
@@ -67,7 +67,6 @@
let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
let offchain_schema = create_data::<OFFCHAIN_SCHEMA_LIMIT>();
- let variable_on_chain_schema = create_data::<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>();
let const_on_chain_schema = create_data::<CONST_ON_CHAIN_SCHEMA_LIMIT>();
handler(
owner,
@@ -77,7 +76,6 @@
description,
token_prefix,
offchain_schema,
- variable_on_chain_schema,
const_on_chain_schema,
..Default::default()
},
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -482,12 +482,6 @@
.expect("data has lower bounds than field");
Self::set_field_raw(
id,
- CollectionField::VariableOnChainSchema,
- v.variable_on_chain_schema.clone().into_inner(),
- )
- .expect("data has lower bounds than field");
- Self::set_field_raw(
- id,
CollectionField::ConstOnChainSchema,
v.const_on_chain_schema.clone().into_inner(),
)
@@ -621,11 +615,6 @@
CollectionField::ConstOnChainSchema,
))
.into_inner(),
- variable_on_chain_schema: <CollectionData<T>>::get((
- collection,
- CollectionField::VariableOnChainSchema,
- ))
- .into_inner(),
token_property_permissions,
properties,
})
@@ -723,12 +712,6 @@
id,
CollectionField::OffchainSchema,
data.offchain_schema.into_inner(),
- )
- .expect("data has lower bounds than field");
- Self::set_field_raw(
- id,
- CollectionField::VariableOnChainSchema,
- data.variable_on_chain_schema.into_inner(),
)
.expect("data has lower bounds than field");
Self::set_field_raw(
pallets/unique/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/unique/src/benchmarking.rs
+++ b/pallets/unique/src/benchmarking.rs
@@ -146,14 +146,6 @@
let data = create_var_data(b);
}: set_const_on_chain_schema(RawOrigin::Signed(caller.clone()), collection, data)
- set_variable_on_chain_schema {
- let b in 0..VARIABLE_ON_CHAIN_SCHEMA_LIMIT;
-
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- let data = create_var_data(b);
- }: set_variable_on_chain_schema(RawOrigin::Signed(caller.clone()), collection, data)
-
set_schema_version {
let caller: T::AccountId = account("caller", 0, SEED);
let collection = create_nft_collection::<T>(caller.clone())?;
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -35,7 +35,7 @@
use frame_system::{self as system, ensure_signed};
use sp_runtime::{sp_std::prelude::Vec};
use up_data_structs::{
- VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
+ CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,
SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData, CustomDataLimit,
@@ -191,13 +191,6 @@
///
/// * collection_id: Globally unique collection identifier.
SchemaVersionSet(CollectionId),
-
- /// Variable on chain schema was set
- ///
- /// # Arguments
- ///
- /// * collection_id: Globally unique collection identifier.
- VariableOnChainSchemaSet(CollectionId),
}
}
@@ -1083,38 +1076,6 @@
<PalletCommon<T>>::set_field(&collection, &sender, CollectionField::ConstOnChainSchema, schema.into_inner())?;
<Pallet<T>>::deposit_event(Event::<T>::ConstOnChainSchemaSet(
- collection_id
- ));
- Ok(())
- }
-
- /// Set variable on-chain data schema.
- ///
- /// # Permissions
- ///
- /// * Collection Owner
- /// * Collection Admin
- ///
- /// # Arguments
- ///
- /// * collection_id.
- ///
- /// * schema: String representing the variable on-chain data schema.
- #[weight = <SelfWeightOf<T>>::set_const_on_chain_schema(schema.len() as u32)]
- #[transactional]
- pub fn set_variable_on_chain_schema (
- origin,
- collection_id: CollectionId,
- schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>
- ) -> DispatchResult {
- let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = <CollectionHandle<T>>::try_get(collection_id)?;
-
- // =========
-
- <PalletCommon<T>>::set_field(&collection, &sender, CollectionField::VariableOnChainSchema, schema.into_inner())?;
-
- <Pallet<T>>::deposit_event(Event::<T>::VariableOnChainSchemaSet(
collection_id
));
Ok(())
pallets/unique/src/weights.rsdiffbeforeafterboth--- a/pallets/unique/src/weights.rs
+++ b/pallets/unique/src/weights.rs
@@ -47,7 +47,6 @@
fn set_transfers_enabled_flag() -> Weight;
fn set_offchain_schema(b: u32, ) -> Weight;
fn set_const_on_chain_schema(b: u32, ) -> Weight;
- fn set_variable_on_chain_schema(b: u32, ) -> Weight;
fn set_schema_version() -> Weight;
fn set_collection_limits() -> Weight;
fn set_meta_update_permission_flag() -> Weight;
@@ -156,12 +155,6 @@
// Storage: Common CollectionById (r:1 w:1)
fn set_const_on_chain_schema(_b: u32, ) -> Weight {
(14_984_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(1 as Weight))
- .saturating_add(T::DbWeight::get().writes(1 as Weight))
- }
- // Storage: Common CollectionById (r:1 w:1)
- fn set_variable_on_chain_schema(_b: u32, ) -> Weight {
- (15_196_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
@@ -287,12 +280,6 @@
// Storage: Common CollectionById (r:1 w:1)
fn set_const_on_chain_schema(_b: u32, ) -> Weight {
(14_984_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(1 as Weight))
- .saturating_add(RocksDbWeight::get().writes(1 as Weight))
- }
- // Storage: Common CollectionById (r:1 w:1)
- fn set_variable_on_chain_schema(_b: u32, ) -> Weight {
- (15_196_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
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};2728#[cfg(feature = "serde")]29use serde::{Serialize, Deserialize};3031use sp_core::U256;32use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};33use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};34use frame_support::{BoundedVec, traits::ConstU32};35use derivative::Derivative;36use scale_info::TypeInfo;3738mod bounded;39pub mod budget;40pub mod mapping;41mod migration;4243pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;44pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;45pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;4647pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {48 100_00049} else {50 1051};52pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {53 100_00054} else {55 1056};57pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {58 204859} else {60 1061};62pub const COLLECTION_ADMINS_LIMIT: u32 = 5;63pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;64pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {65 1_000_00066} else {67 1068};6970// Timeouts for item types in passed blocks71pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;72pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;73pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;7475pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;7677// Schema limits78pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;79pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;80pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;8182pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;83// u32::max is not const: OFFCHAIN_SCHEMA_LIMIT.max(VARIABLE_ON_CHAIN_SCHEMA_LIMIT).max(CONST_ON_CHAIN_SCHEMA_LIMIT);8485pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;86pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;87pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;8889pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;90pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;91pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;9293// pub const MAX_PROPERTY_KEYS_OVERALL_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH * MAX_PROPERTIES_PER_ITEM;94pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;95pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;9697pub const MAX_COLLECTION_PROPERTIES_ENCODE_LEN: u32 =98 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH + MAX_COLLECTION_PROPERTIES_SIZE;99100pub struct MaxPropertiesPermissionsEncodeLen;101102impl Get<u32> for MaxPropertiesPermissionsEncodeLen {103 fn get() -> u32 {104 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH105 + <PropertyPermission as MaxEncodedLen>::max_encoded_len() as u32106 }107}108109/// How much items can be created per single110/// create_many call111pub const MAX_ITEMS_PER_BATCH: u32 = 200;112113pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;114115#[derive(116 Encode,117 Decode,118 PartialEq,119 Eq,120 PartialOrd,121 Ord,122 Clone,123 Copy,124 Debug,125 Default,126 TypeInfo,127 MaxEncodedLen,128)]129#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]130pub struct CollectionId(pub u32);131impl EncodeLike<u32> for CollectionId {}132impl EncodeLike<CollectionId> for u32 {}133134#[derive(135 Encode,136 Decode,137 PartialEq,138 Eq,139 PartialOrd,140 Ord,141 Clone,142 Copy,143 Debug,144 Default,145 TypeInfo,146 MaxEncodedLen,147)]148#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]149pub struct TokenId(pub u32);150impl EncodeLike<u32> for TokenId {}151impl EncodeLike<TokenId> for u32 {}152153impl TokenId {154 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {155 self.0156 .checked_add(1)157 .ok_or(ArithmeticError::Overflow)158 .map(Self)159 }160}161162impl From<TokenId> for U256 {163 fn from(t: TokenId) -> Self {164 t.0.into()165 }166}167168impl TryFrom<U256> for TokenId {169 type Error = &'static str;170171 fn try_from(value: U256) -> Result<Self, Self::Error> {172 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))173 }174}175176#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]177#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]178pub struct TokenData<CrossAccountId> {179 pub const_data: Vec<u8>,180 pub properties: Vec<Property>,181 pub owner: Option<CrossAccountId>,182}183184pub struct OverflowError;185impl From<OverflowError> for &'static str {186 fn from(_: OverflowError) -> Self {187 "overflow occured"188 }189}190191pub type DecimalPoints = u8;192193#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]194#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]195pub enum CollectionMode {196 NFT,197 // decimal points198 Fungible(DecimalPoints),199 ReFungible,200}201202impl CollectionMode {203 pub fn id(&self) -> u8 {204 match self {205 CollectionMode::NFT => 1,206 CollectionMode::Fungible(_) => 2,207 CollectionMode::ReFungible => 3,208 }209 }210}211212pub trait SponsoringResolve<AccountId, Call> {213 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;214}215216#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]217#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]218pub enum AccessMode {219 Normal,220 AllowList,221}222impl Default for AccessMode {223 fn default() -> Self {224 Self::Normal225 }226}227228#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]229#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]230pub enum SchemaVersion {231 ImageURL,232 Unique,233}234impl Default for SchemaVersion {235 fn default() -> Self {236 Self::ImageURL237 }238}239240#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]241#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]242pub struct Ownership<AccountId> {243 pub owner: AccountId,244 pub fraction: u128,245}246247#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]248#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]249pub enum SponsorshipState<AccountId> {250 /// The fees are applied to the transaction sender251 Disabled,252 Unconfirmed(AccountId),253 /// Transactions are sponsored by specified account254 Confirmed(AccountId),255}256257impl<AccountId> SponsorshipState<AccountId> {258 pub fn sponsor(&self) -> Option<&AccountId> {259 match self {260 Self::Confirmed(sponsor) => Some(sponsor),261 _ => None,262 }263 }264265 pub fn pending_sponsor(&self) -> Option<&AccountId> {266 match self {267 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),268 _ => None,269 }270 }271272 pub fn confirmed(&self) -> bool {273 matches!(self, Self::Confirmed(_))274 }275}276277impl<T> Default for SponsorshipState<T> {278 fn default() -> Self {279 Self::Disabled280 }281}282283/// Used in storage284#[struct_versioning::versioned(version = 2, upper)]285#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]286pub struct Collection<AccountId> {287 pub owner: AccountId,288 pub mode: CollectionMode,289 pub access: AccessMode,290 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,291 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,292 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,293 pub mint_mode: bool,294295 #[version(..2)]296 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,297298 pub schema_version: SchemaVersion,299 pub sponsorship: SponsorshipState<AccountId>,300301 #[version(..2)]302 pub limits: CollectionLimitsVersion1, // Collection private restrictions303 #[version(2.., upper(limits.into()))]304 pub limits: CollectionLimitsVersion2,305306 #[version(..2)]307 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,308 #[version(..2)]309 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,310311 pub meta_update_permission: MetaUpdatePermission,312}313314/// Used in RPC calls315#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]316#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]317pub struct RpcCollection<AccountId> {318 pub owner: AccountId,319 pub mode: CollectionMode,320 pub access: AccessMode,321 pub name: Vec<u16>,322 pub description: Vec<u16>,323 pub token_prefix: Vec<u8>,324 pub mint_mode: bool,325 pub offchain_schema: Vec<u8>,326 pub schema_version: SchemaVersion,327 pub sponsorship: SponsorshipState<AccountId>,328 pub limits: CollectionLimits,329 pub variable_on_chain_schema: Vec<u8>,330 pub const_on_chain_schema: Vec<u8>,331 pub meta_update_permission: MetaUpdatePermission,332 pub token_property_permissions: Vec<PropertyKeyPermission>,333 pub properties: Vec<Property>,334}335336#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]337#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]338pub enum CollectionField {339 VariableOnChainSchema,340 ConstOnChainSchema,341 OffchainSchema,342}343344#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]345#[derivative(Debug, Default(bound = ""))]346pub struct CreateCollectionData<AccountId> {347 #[derivative(Default(value = "CollectionMode::NFT"))]348 pub mode: CollectionMode,349 pub access: Option<AccessMode>,350 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,351 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,352 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,353 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,354 pub schema_version: Option<SchemaVersion>,355 pub pending_sponsor: Option<AccountId>,356 pub limits: Option<CollectionLimits>,357 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,358 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,359 pub meta_update_permission: Option<MetaUpdatePermission>,360 pub token_property_permissions: CollectionPropertiesPermissionsVec,361 pub properties: CollectionPropertiesVec,362}363364pub type CollectionPropertiesPermissionsVec =365 BoundedVec<PropertyKeyPermission, MaxPropertiesPermissionsEncodeLen>;366367pub type CollectionPropertiesVec =368 BoundedVec<Property, ConstU32<MAX_COLLECTION_PROPERTIES_ENCODE_LEN>>;369370#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]371#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]372pub struct NftItemType<AccountId> {373 pub owner: AccountId,374 pub const_data: Vec<u8>,375 pub variable_data: Vec<u8>,376}377378#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]379#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]380pub struct FungibleItemType {381 pub value: u128,382}383384#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]385#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]386pub struct ReFungibleItemType<AccountId> {387 pub owner: Vec<Ownership<AccountId>>,388 pub const_data: Vec<u8>,389 pub variable_data: Vec<u8>,390}391392/// All fields are wrapped in `Option`s, where None means chain default393#[struct_versioning::versioned(version = 2, upper)]394#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]395#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]396pub struct CollectionLimits {397 pub account_token_ownership_limit: Option<u32>,398 pub sponsored_data_size: Option<u32>,399 /// None - setVariableMetadata is not sponsored400 /// Some(v) - setVariableMetadata is sponsored401 /// if there is v block between txs402 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,403 pub token_limit: Option<u32>,404405 // Timeouts for item types in passed blocks406 pub sponsor_transfer_timeout: Option<u32>,407 pub sponsor_approve_timeout: Option<u32>,408 pub owner_can_transfer: Option<bool>,409 pub owner_can_destroy: Option<bool>,410 pub transfers_enabled: Option<bool>,411412 #[version(2.., upper(None))]413 pub nesting_rule: Option<NestingRule>,414}415416impl CollectionLimits {417 pub fn account_token_ownership_limit(&self) -> u32 {418 self.account_token_ownership_limit419 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)420 .min(MAX_TOKEN_OWNERSHIP)421 }422 pub fn sponsored_data_size(&self) -> u32 {423 self.sponsored_data_size424 .unwrap_or(CUSTOM_DATA_LIMIT)425 .min(CUSTOM_DATA_LIMIT)426 }427 pub fn token_limit(&self) -> u32 {428 self.token_limit429 .unwrap_or(COLLECTION_TOKEN_LIMIT)430 .min(COLLECTION_TOKEN_LIMIT)431 }432 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {433 self.sponsor_transfer_timeout434 .unwrap_or(default)435 .min(MAX_SPONSOR_TIMEOUT)436 }437 pub fn sponsor_approve_timeout(&self) -> u32 {438 self.sponsor_approve_timeout439 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)440 .min(MAX_SPONSOR_TIMEOUT)441 }442 pub fn owner_can_transfer(&self) -> bool {443 self.owner_can_transfer.unwrap_or(true)444 }445 pub fn owner_can_destroy(&self) -> bool {446 self.owner_can_destroy.unwrap_or(true)447 }448 pub fn transfers_enabled(&self) -> bool {449 self.transfers_enabled.unwrap_or(true)450 }451 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {452 match self453 .sponsored_data_rate_limit454 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)455 {456 SponsoringRateLimit::SponsoringDisabled => None,457 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),458 }459 }460 pub fn nesting_rule(&self) -> &NestingRule {461 static DEFAULT: NestingRule = NestingRule::Disabled;462 self.nesting_rule.as_ref().unwrap_or(&DEFAULT)463 }464}465466#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]467#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]468#[derivative(Debug)]469pub enum NestingRule {470 /// No one can nest tokens471 Disabled,472 /// Owner can nest any tokens473 Owner,474 /// Owner can nest tokens from specified collections475 OwnerRestricted(476 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]477 #[derivative(Debug(format_with = "bounded::set_debug"))]478 BoundedBTreeSet<CollectionId, ConstU32<16>>,479 ),480}481482#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]483#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]484pub enum SponsoringRateLimit {485 SponsoringDisabled,486 Blocks(u32),487}488489#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]490#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]491#[derivative(Debug)]492pub struct CreateNftData {493 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]494 #[derivative(Debug(format_with = "bounded::vec_debug"))]495 pub const_data: BoundedVec<u8, CustomDataLimit>,496 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]497 #[derivative(Debug(format_with = "bounded::vec_debug"))]498 pub variable_data: BoundedVec<u8, CustomDataLimit>,499500 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]501 #[derivative(Debug(format_with = "bounded::vec_debug"))]502 pub properties: CollectionPropertiesVec,503}504505#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]506#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]507pub struct CreateFungibleData {508 pub value: u128,509}510511#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]512#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]513#[derivative(Debug)]514pub struct CreateReFungibleData {515 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]516 #[derivative(Debug(format_with = "bounded::vec_debug"))]517 pub const_data: BoundedVec<u8, CustomDataLimit>,518 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]519 #[derivative(Debug(format_with = "bounded::vec_debug"))]520 pub variable_data: BoundedVec<u8, CustomDataLimit>,521 pub pieces: u128,522}523524#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]525#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]526pub enum MetaUpdatePermission {527 ItemOwner,528 Admin,529 None,530}531532impl Default for MetaUpdatePermission {533 fn default() -> Self {534 Self::ItemOwner535 }536}537538#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]539#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]540pub enum CreateItemData {541 NFT(CreateNftData),542 Fungible(CreateFungibleData),543 ReFungible(CreateReFungibleData),544}545546#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]547#[derivative(Debug)]548pub struct CreateNftExData<CrossAccountId> {549 #[derivative(Debug(format_with = "bounded::vec_debug"))]550 pub const_data: BoundedVec<u8, CustomDataLimit>,551 #[derivative(Debug(format_with = "bounded::vec_debug"))]552 pub variable_data: BoundedVec<u8, CustomDataLimit>,553 #[derivative(Debug(format_with = "bounded::vec_debug"))]554 pub properties: CollectionPropertiesVec,555 pub owner: CrossAccountId,556}557558#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]559#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]560pub struct CreateRefungibleExData<CrossAccountId> {561 #[derivative(Debug(format_with = "bounded::vec_debug"))]562 pub const_data: BoundedVec<u8, CustomDataLimit>,563 #[derivative(Debug(format_with = "bounded::vec_debug"))]564 pub variable_data: BoundedVec<u8, CustomDataLimit>,565 #[derivative(Debug(format_with = "bounded::map_debug"))]566 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,567}568569#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]570#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]571pub enum CreateItemExData<CrossAccountId> {572 NFT(573 #[derivative(Debug(format_with = "bounded::vec_debug"))]574 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,575 ),576 Fungible(577 #[derivative(Debug(format_with = "bounded::map_debug"))]578 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,579 ),580 /// Many tokens, each may have only one owner581 RefungibleMultipleItems(582 #[derivative(Debug(format_with = "bounded::vec_debug"))]583 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,584 ),585 /// Single token, which may have many owners586 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),587}588589impl CreateItemData {590 pub fn data_size(&self) -> usize {591 match self {592 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),593 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),594 _ => 0,595 }596 }597}598599impl From<CreateNftData> for CreateItemData {600 fn from(item: CreateNftData) -> Self {601 CreateItemData::NFT(item)602 }603}604605impl From<CreateReFungibleData> for CreateItemData {606 fn from(item: CreateReFungibleData) -> Self {607 CreateItemData::ReFungible(item)608 }609}610611impl From<CreateFungibleData> for CreateItemData {612 fn from(item: CreateFungibleData) -> Self {613 CreateItemData::Fungible(item)614 }615}616617#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]618#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]619pub struct CollectionStats {620 pub created: u32,621 pub destroyed: u32,622 pub alive: u32,623}624625#[derive(Encode, Decode, PartialEq, Clone, Debug)]626pub struct PhantomType<T>(core::marker::PhantomData<T>);627628impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {629 type Identity = PhantomType<T>;630631 fn type_info() -> scale_info::Type {632 use scale_info::{633 Type, Path,634 build::{FieldsBuilder, UnnamedFields},635 type_params,636 };637 Type::builder()638 .path(Path::new("up_data_structs", "PhantomType"))639 .type_params(type_params!(T))640 .composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))641 }642}643impl<T> MaxEncodedLen for PhantomType<T> {644 fn max_encoded_len() -> usize {645 0646 }647}648649pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;650pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;651652#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]653#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]654pub struct PropertyPermission {655 pub mutable: bool,656 pub collection_admin: bool,657 pub token_owner: bool,658}659660impl PropertyPermission {661 pub fn none() -> Self {662 Self {663 mutable: true,664 collection_admin: false,665 token_owner: false,666 }667 }668}669670#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]671#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]672pub struct Property {673 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]674 pub key: PropertyKey,675676 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]677 pub value: PropertyValue,678}679680#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]681#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]682pub struct PropertyKeyPermission {683 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]684 pub key: PropertyKey,685686 pub permission: PropertyPermission,687}688689pub enum PropertiesError {690 NoSpaceForProperty,691 PropertyLimitReached,692 InvalidCharacterInPropertyKey,693}694695pub trait TrySet: Sized {696 type Value;697698 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError>;699700 fn try_set_from_iter<I>(&mut self, iter: I) -> Result<(), PropertiesError>701 where702 I: Iterator<Item = (PropertyKey, Self::Value)>,703 {704 for (key, value) in iter {705 self.try_set(key, value)?;706 }707708 Ok(())709 }710}711712#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]713#[derivative(Default(bound = ""))]714pub struct PropertiesMap<Value>(715 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,716);717718impl<Value> PropertiesMap<Value> {719 pub fn new() -> Self {720 Self(BoundedBTreeMap::new())721 }722723 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {724 Self::check_property_key(key)?;725726 Ok(self.0.remove(key))727 }728729 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {730 self.0.get(key)731 }732733 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {734 self.0.iter()735 }736737 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {738 let key_str = sp_std::str::from_utf8(key.as_slice())739 .map_err(|_| PropertiesError::InvalidCharacterInPropertyKey)?;740741 for ch in key_str.chars() {742 if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {743 return Err(PropertiesError::InvalidCharacterInPropertyKey);744 }745 }746747 Ok(())748 }749}750751impl<Value> TrySet for PropertiesMap<Value> {752 type Value = Value;753754 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {755 Self::check_property_key(&key)?;756757 self.0758 .try_insert(key, value)759 .map_err(|_| PropertiesError::PropertyLimitReached)?;760761 Ok(())762 }763}764765pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;766767#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]768pub struct Properties {769 map: PropertiesMap<PropertyValue>,770 consumed_space: u32,771 space_limit: u32,772}773774impl Properties {775 pub fn new(space_limit: u32) -> Self {776 Self {777 map: PropertiesMap::new(),778 consumed_space: 0,779 space_limit,780 }781 }782783 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {784 let value = self.map.remove(key)?;785786 if let Some(ref value) = value {787 let value_len = value.len() as u32;788 self.consumed_space -= value_len;789 }790791 Ok(value)792 }793794 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {795 self.map.get(key)796 }797798 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {799 self.map.iter()800 }801}802803impl TrySet for Properties {804 type Value = PropertyValue;805806 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {807 let value_len = value.len();808809 if self.consumed_space as usize + value_len > self.space_limit as usize {810 return Err(PropertiesError::NoSpaceForProperty);811 }812813 self.map.try_set(key, value)?;814815 self.consumed_space += value_len as u32;816817 Ok(())818 }819}820821pub struct CollectionProperties;822823impl Get<Properties> for CollectionProperties {824 fn get() -> Properties {825 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)826 }827}828829pub struct TokenProperties;830831impl Get<Properties> for TokenProperties {832 fn get() -> Properties {833 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)834 }835}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![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};2728#[cfg(feature = "serde")]29use serde::{Serialize, Deserialize};3031use sp_core::U256;32use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};33use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};34use frame_support::{BoundedVec, traits::ConstU32};35use derivative::Derivative;36use scale_info::TypeInfo;3738mod bounded;39pub mod budget;40pub mod mapping;41mod migration;4243pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;44pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;45pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;4647pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {48 100_00049} else {50 1051};52pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {53 100_00054} else {55 1056};57pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {58 204859} else {60 1061};62pub const COLLECTION_ADMINS_LIMIT: u32 = 5;63pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;64pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {65 1_000_00066} else {67 1068};6970// Timeouts for item types in passed blocks71pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;72pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;73pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;7475pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;7677// Schema limits78pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;79pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;8081pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;8283pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;84pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;85pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;8687pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;88pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;89pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;9091// pub const MAX_PROPERTY_KEYS_OVERALL_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH * MAX_PROPERTIES_PER_ITEM;92pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;93pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;9495pub const MAX_COLLECTION_PROPERTIES_ENCODE_LEN: u32 =96 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH + MAX_COLLECTION_PROPERTIES_SIZE;9798pub struct MaxPropertiesPermissionsEncodeLen;99100impl Get<u32> for MaxPropertiesPermissionsEncodeLen {101 fn get() -> u32 {102 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH103 + <PropertyPermission as MaxEncodedLen>::max_encoded_len() as u32104 }105}106107/// How much items can be created per single108/// create_many call109pub const MAX_ITEMS_PER_BATCH: u32 = 200;110111pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;112113#[derive(114 Encode,115 Decode,116 PartialEq,117 Eq,118 PartialOrd,119 Ord,120 Clone,121 Copy,122 Debug,123 Default,124 TypeInfo,125 MaxEncodedLen,126)]127#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]128pub struct CollectionId(pub u32);129impl EncodeLike<u32> for CollectionId {}130impl EncodeLike<CollectionId> for u32 {}131132#[derive(133 Encode,134 Decode,135 PartialEq,136 Eq,137 PartialOrd,138 Ord,139 Clone,140 Copy,141 Debug,142 Default,143 TypeInfo,144 MaxEncodedLen,145)]146#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]147pub struct TokenId(pub u32);148impl EncodeLike<u32> for TokenId {}149impl EncodeLike<TokenId> for u32 {}150151impl TokenId {152 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {153 self.0154 .checked_add(1)155 .ok_or(ArithmeticError::Overflow)156 .map(Self)157 }158}159160impl From<TokenId> for U256 {161 fn from(t: TokenId) -> Self {162 t.0.into()163 }164}165166impl TryFrom<U256> for TokenId {167 type Error = &'static str;168169 fn try_from(value: U256) -> Result<Self, Self::Error> {170 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))171 }172}173174#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]175#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]176pub struct TokenData<CrossAccountId> {177 pub const_data: Vec<u8>,178 pub properties: Vec<Property>,179 pub owner: Option<CrossAccountId>,180}181182pub struct OverflowError;183impl From<OverflowError> for &'static str {184 fn from(_: OverflowError) -> Self {185 "overflow occured"186 }187}188189pub type DecimalPoints = u8;190191#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]192#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]193pub enum CollectionMode {194 NFT,195 // decimal points196 Fungible(DecimalPoints),197 ReFungible,198}199200impl CollectionMode {201 pub fn id(&self) -> u8 {202 match self {203 CollectionMode::NFT => 1,204 CollectionMode::Fungible(_) => 2,205 CollectionMode::ReFungible => 3,206 }207 }208}209210pub trait SponsoringResolve<AccountId, Call> {211 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;212}213214#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]215#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]216pub enum AccessMode {217 Normal,218 AllowList,219}220impl Default for AccessMode {221 fn default() -> Self {222 Self::Normal223 }224}225226#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]227#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]228pub enum SchemaVersion {229 ImageURL,230 Unique,231}232impl Default for SchemaVersion {233 fn default() -> Self {234 Self::ImageURL235 }236}237238#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]239#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]240pub struct Ownership<AccountId> {241 pub owner: AccountId,242 pub fraction: u128,243}244245#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]246#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]247pub enum SponsorshipState<AccountId> {248 /// The fees are applied to the transaction sender249 Disabled,250 Unconfirmed(AccountId),251 /// Transactions are sponsored by specified account252 Confirmed(AccountId),253}254255impl<AccountId> SponsorshipState<AccountId> {256 pub fn sponsor(&self) -> Option<&AccountId> {257 match self {258 Self::Confirmed(sponsor) => Some(sponsor),259 _ => None,260 }261 }262263 pub fn pending_sponsor(&self) -> Option<&AccountId> {264 match self {265 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),266 _ => None,267 }268 }269270 pub fn confirmed(&self) -> bool {271 matches!(self, Self::Confirmed(_))272 }273}274275impl<T> Default for SponsorshipState<T> {276 fn default() -> Self {277 Self::Disabled278 }279}280281/// Used in storage282#[struct_versioning::versioned(version = 2, upper)]283#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]284pub struct Collection<AccountId> {285 pub owner: AccountId,286 pub mode: CollectionMode,287 pub access: AccessMode,288 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,289 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,290 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,291 pub mint_mode: bool,292293 #[version(..2)]294 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,295296 pub schema_version: SchemaVersion,297 pub sponsorship: SponsorshipState<AccountId>,298299 #[version(..2)]300 pub limits: CollectionLimitsVersion1, // Collection private restrictions301 #[version(2.., upper(limits.into()))]302 pub limits: CollectionLimitsVersion2,303304 #[version(..2)]305 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,306307 pub meta_update_permission: MetaUpdatePermission,308}309310/// Used in RPC calls311#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]312#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]313pub struct RpcCollection<AccountId> {314 pub owner: AccountId,315 pub mode: CollectionMode,316 pub access: AccessMode,317 pub name: Vec<u16>,318 pub description: Vec<u16>,319 pub token_prefix: Vec<u8>,320 pub mint_mode: bool,321 pub offchain_schema: Vec<u8>,322 pub schema_version: SchemaVersion,323 pub sponsorship: SponsorshipState<AccountId>,324 pub limits: CollectionLimits,325 pub const_on_chain_schema: Vec<u8>,326 pub meta_update_permission: MetaUpdatePermission,327 pub token_property_permissions: Vec<PropertyKeyPermission>,328 pub properties: Vec<Property>,329}330331#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]332#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]333pub enum CollectionField {334 ConstOnChainSchema,335 OffchainSchema,336}337338#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]339#[derivative(Debug, Default(bound = ""))]340pub struct CreateCollectionData<AccountId> {341 #[derivative(Default(value = "CollectionMode::NFT"))]342 pub mode: CollectionMode,343 pub access: Option<AccessMode>,344 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,345 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,346 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,347 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,348 pub schema_version: Option<SchemaVersion>,349 pub pending_sponsor: Option<AccountId>,350 pub limits: Option<CollectionLimits>,351 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,352 pub meta_update_permission: Option<MetaUpdatePermission>,353 pub token_property_permissions: CollectionPropertiesPermissionsVec,354 pub properties: CollectionPropertiesVec,355}356357pub type CollectionPropertiesPermissionsVec =358 BoundedVec<PropertyKeyPermission, MaxPropertiesPermissionsEncodeLen>;359360pub type CollectionPropertiesVec =361 BoundedVec<Property, ConstU32<MAX_COLLECTION_PROPERTIES_ENCODE_LEN>>;362363#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]364#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]365pub struct NftItemType<AccountId> {366 pub owner: AccountId,367 pub const_data: Vec<u8>,368 pub variable_data: Vec<u8>,369}370371#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]372#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]373pub struct FungibleItemType {374 pub value: u128,375}376377#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]378#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]379pub struct ReFungibleItemType<AccountId> {380 pub owner: Vec<Ownership<AccountId>>,381 pub const_data: Vec<u8>,382 pub variable_data: Vec<u8>,383}384385/// All fields are wrapped in `Option`s, where None means chain default386#[struct_versioning::versioned(version = 2, upper)]387#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]388#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]389pub struct CollectionLimits {390 pub account_token_ownership_limit: Option<u32>,391 pub sponsored_data_size: Option<u32>,392 /// None - setVariableMetadata is not sponsored393 /// Some(v) - setVariableMetadata is sponsored394 /// if there is v block between txs395 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,396 pub token_limit: Option<u32>,397398 // Timeouts for item types in passed blocks399 pub sponsor_transfer_timeout: Option<u32>,400 pub sponsor_approve_timeout: Option<u32>,401 pub owner_can_transfer: Option<bool>,402 pub owner_can_destroy: Option<bool>,403 pub transfers_enabled: Option<bool>,404405 #[version(2.., upper(None))]406 pub nesting_rule: Option<NestingRule>,407}408409impl CollectionLimits {410 pub fn account_token_ownership_limit(&self) -> u32 {411 self.account_token_ownership_limit412 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)413 .min(MAX_TOKEN_OWNERSHIP)414 }415 pub fn sponsored_data_size(&self) -> u32 {416 self.sponsored_data_size417 .unwrap_or(CUSTOM_DATA_LIMIT)418 .min(CUSTOM_DATA_LIMIT)419 }420 pub fn token_limit(&self) -> u32 {421 self.token_limit422 .unwrap_or(COLLECTION_TOKEN_LIMIT)423 .min(COLLECTION_TOKEN_LIMIT)424 }425 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {426 self.sponsor_transfer_timeout427 .unwrap_or(default)428 .min(MAX_SPONSOR_TIMEOUT)429 }430 pub fn sponsor_approve_timeout(&self) -> u32 {431 self.sponsor_approve_timeout432 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)433 .min(MAX_SPONSOR_TIMEOUT)434 }435 pub fn owner_can_transfer(&self) -> bool {436 self.owner_can_transfer.unwrap_or(true)437 }438 pub fn owner_can_destroy(&self) -> bool {439 self.owner_can_destroy.unwrap_or(true)440 }441 pub fn transfers_enabled(&self) -> bool {442 self.transfers_enabled.unwrap_or(true)443 }444 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {445 match self446 .sponsored_data_rate_limit447 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)448 {449 SponsoringRateLimit::SponsoringDisabled => None,450 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),451 }452 }453 pub fn nesting_rule(&self) -> &NestingRule {454 static DEFAULT: NestingRule = NestingRule::Disabled;455 self.nesting_rule.as_ref().unwrap_or(&DEFAULT)456 }457}458459#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]460#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]461#[derivative(Debug)]462pub enum NestingRule {463 /// No one can nest tokens464 Disabled,465 /// Owner can nest any tokens466 Owner,467 /// Owner can nest tokens from specified collections468 OwnerRestricted(469 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]470 #[derivative(Debug(format_with = "bounded::set_debug"))]471 BoundedBTreeSet<CollectionId, ConstU32<16>>,472 ),473}474475#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]476#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]477pub enum SponsoringRateLimit {478 SponsoringDisabled,479 Blocks(u32),480}481482#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]483#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]484#[derivative(Debug)]485pub struct CreateNftData {486 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]487 #[derivative(Debug(format_with = "bounded::vec_debug"))]488 pub const_data: BoundedVec<u8, CustomDataLimit>,489 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]490 #[derivative(Debug(format_with = "bounded::vec_debug"))]491 pub variable_data: BoundedVec<u8, CustomDataLimit>,492493 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]494 #[derivative(Debug(format_with = "bounded::vec_debug"))]495 pub properties: CollectionPropertiesVec,496}497498#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]499#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]500pub struct CreateFungibleData {501 pub value: u128,502}503504#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]505#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]506#[derivative(Debug)]507pub struct CreateReFungibleData {508 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]509 #[derivative(Debug(format_with = "bounded::vec_debug"))]510 pub const_data: BoundedVec<u8, CustomDataLimit>,511 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]512 #[derivative(Debug(format_with = "bounded::vec_debug"))]513 pub variable_data: BoundedVec<u8, CustomDataLimit>,514 pub pieces: u128,515}516517#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]518#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]519pub enum MetaUpdatePermission {520 ItemOwner,521 Admin,522 None,523}524525impl Default for MetaUpdatePermission {526 fn default() -> Self {527 Self::ItemOwner528 }529}530531#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]532#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]533pub enum CreateItemData {534 NFT(CreateNftData),535 Fungible(CreateFungibleData),536 ReFungible(CreateReFungibleData),537}538539#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]540#[derivative(Debug)]541pub struct CreateNftExData<CrossAccountId> {542 #[derivative(Debug(format_with = "bounded::vec_debug"))]543 pub const_data: BoundedVec<u8, CustomDataLimit>,544 #[derivative(Debug(format_with = "bounded::vec_debug"))]545 pub variable_data: BoundedVec<u8, CustomDataLimit>,546 #[derivative(Debug(format_with = "bounded::vec_debug"))]547 pub properties: CollectionPropertiesVec,548 pub owner: CrossAccountId,549}550551#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]552#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]553pub struct CreateRefungibleExData<CrossAccountId> {554 #[derivative(Debug(format_with = "bounded::vec_debug"))]555 pub const_data: BoundedVec<u8, CustomDataLimit>,556 #[derivative(Debug(format_with = "bounded::vec_debug"))]557 pub variable_data: BoundedVec<u8, CustomDataLimit>,558 #[derivative(Debug(format_with = "bounded::map_debug"))]559 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,560}561562#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]563#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]564pub enum CreateItemExData<CrossAccountId> {565 NFT(566 #[derivative(Debug(format_with = "bounded::vec_debug"))]567 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,568 ),569 Fungible(570 #[derivative(Debug(format_with = "bounded::map_debug"))]571 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,572 ),573 /// Many tokens, each may have only one owner574 RefungibleMultipleItems(575 #[derivative(Debug(format_with = "bounded::vec_debug"))]576 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,577 ),578 /// Single token, which may have many owners579 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),580}581582impl CreateItemData {583 pub fn data_size(&self) -> usize {584 match self {585 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),586 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),587 _ => 0,588 }589 }590}591592impl From<CreateNftData> for CreateItemData {593 fn from(item: CreateNftData) -> Self {594 CreateItemData::NFT(item)595 }596}597598impl From<CreateReFungibleData> for CreateItemData {599 fn from(item: CreateReFungibleData) -> Self {600 CreateItemData::ReFungible(item)601 }602}603604impl From<CreateFungibleData> for CreateItemData {605 fn from(item: CreateFungibleData) -> Self {606 CreateItemData::Fungible(item)607 }608}609610#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]611#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]612pub struct CollectionStats {613 pub created: u32,614 pub destroyed: u32,615 pub alive: u32,616}617618#[derive(Encode, Decode, PartialEq, Clone, Debug)]619pub struct PhantomType<T>(core::marker::PhantomData<T>);620621impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {622 type Identity = PhantomType<T>;623624 fn type_info() -> scale_info::Type {625 use scale_info::{626 Type, Path,627 build::{FieldsBuilder, UnnamedFields},628 type_params,629 };630 Type::builder()631 .path(Path::new("up_data_structs", "PhantomType"))632 .type_params(type_params!(T))633 .composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))634 }635}636impl<T> MaxEncodedLen for PhantomType<T> {637 fn max_encoded_len() -> usize {638 0639 }640}641642pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;643pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;644645#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]646#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]647pub struct PropertyPermission {648 pub mutable: bool,649 pub collection_admin: bool,650 pub token_owner: bool,651}652653impl PropertyPermission {654 pub fn none() -> Self {655 Self {656 mutable: true,657 collection_admin: false,658 token_owner: false,659 }660 }661}662663#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]664#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]665pub struct Property {666 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]667 pub key: PropertyKey,668669 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]670 pub value: PropertyValue,671}672673#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]674#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]675pub struct PropertyKeyPermission {676 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]677 pub key: PropertyKey,678679 pub permission: PropertyPermission,680}681682pub enum PropertiesError {683 NoSpaceForProperty,684 PropertyLimitReached,685 InvalidCharacterInPropertyKey,686}687688pub trait TrySet: Sized {689 type Value;690691 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError>;692693 fn try_set_from_iter<I>(&mut self, iter: I) -> Result<(), PropertiesError>694 where695 I: Iterator<Item = (PropertyKey, Self::Value)>,696 {697 for (key, value) in iter {698 self.try_set(key, value)?;699 }700701 Ok(())702 }703}704705#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]706#[derivative(Default(bound = ""))]707pub struct PropertiesMap<Value>(708 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,709);710711impl<Value> PropertiesMap<Value> {712 pub fn new() -> Self {713 Self(BoundedBTreeMap::new())714 }715716 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {717 Self::check_property_key(key)?;718719 Ok(self.0.remove(key))720 }721722 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {723 self.0.get(key)724 }725726 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {727 self.0.iter()728 }729730 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {731 let key_str = sp_std::str::from_utf8(key.as_slice())732 .map_err(|_| PropertiesError::InvalidCharacterInPropertyKey)?;733734 for ch in key_str.chars() {735 if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {736 return Err(PropertiesError::InvalidCharacterInPropertyKey);737 }738 }739740 Ok(())741 }742}743744impl<Value> TrySet for PropertiesMap<Value> {745 type Value = Value;746747 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {748 Self::check_property_key(&key)?;749750 self.0751 .try_insert(key, value)752 .map_err(|_| PropertiesError::PropertyLimitReached)?;753754 Ok(())755 }756}757758pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;759760#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]761pub struct Properties {762 map: PropertiesMap<PropertyValue>,763 consumed_space: u32,764 space_limit: u32,765}766767impl Properties {768 pub fn new(space_limit: u32) -> Self {769 Self {770 map: PropertiesMap::new(),771 consumed_space: 0,772 space_limit,773 }774 }775776 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {777 let value = self.map.remove(key)?;778779 if let Some(ref value) = value {780 let value_len = value.len() as u32;781 self.consumed_space -= value_len;782 }783784 Ok(value)785 }786787 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {788 self.map.get(key)789 }790791 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {792 self.map.iter()793 }794}795796impl TrySet for Properties {797 type Value = PropertyValue;798799 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {800 let value_len = value.len();801802 if self.consumed_space as usize + value_len > self.space_limit as usize {803 return Err(PropertiesError::NoSpaceForProperty);804 }805806 self.map.try_set(key, value)?;807808 self.consumed_space += value_len as u32;809810 Ok(())811 }812}813814pub struct CollectionProperties;815816impl Get<Properties> for CollectionProperties {817 fn get() -> Properties {818 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)819 }820}821822pub struct TokenProperties;823824impl Get<Properties> for TokenProperties {825 fn get() -> Properties {826 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)827 }828}runtime/tests/src/tests.rsdiffbeforeafterboth--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -2423,45 +2423,6 @@
)),
b"test const on chain schema".to_vec()
);
- assert_eq!(
- <pallet_common::CollectionData<Test>>::get((
- collection_id,
- CollectionField::VariableOnChainSchema
- )),
- b"".to_vec()
- );
- });
-}
-
-#[test]
-fn set_variable_on_chain_schema() {
- new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
-
- let origin1 = Origin::signed(1);
- assert_ok!(Unique::set_variable_on_chain_schema(
- origin1,
- collection_id,
- b"test variable on chain schema"
- .to_vec()
- .try_into()
- .unwrap()
- ));
-
- assert_eq!(
- <pallet_common::CollectionData<Test>>::get((
- collection_id,
- CollectionField::ConstOnChainSchema
- )),
- b"".to_vec()
- );
- assert_eq!(
- <pallet_common::CollectionData<Test>>::get((
- collection_id,
- CollectionField::VariableOnChainSchema
- )),
- b"test variable on chain schema".to_vec()
- );
});
}
tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -40,20 +40,20 @@
});
it('create new collection with properties #1', async () => {
- await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'},
- properties: [{key: 'key1', value: 'val1'}],
+ await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'},
+ properties: [{key: 'key1', value: 'val1'}],
propPerm: [{key: 'key1', tokenOwner: true, mutable: false, collectionAdmin: true}]});
});
it('create new collection with properties #2', async () => {
- await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'},
- properties: [{key: 'key1', value: 'val1'}],
+ await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'},
+ properties: [{key: 'key1', value: 'val1'}],
propPerm: [{key: 'key1', tokenOwner: false, mutable: true, collectionAdmin: false}]});
});
it('create new collection with properties #3', async () => {
- await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'},
- properties: [{key: 'key1', value: 'val1'}],
+ await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'},
+ properties: [{key: 'key1', value: 'val1'}],
propPerm: [{key: 'key1', tokenOwner: true, mutable: false, collectionAdmin: false}]});
});
@@ -73,7 +73,6 @@
limits: {
accountTokenOwnershipLimit: 3,
},
- variableOnChainSchema: '0x222222',
constOnChainSchema: '0x333333',
metaUpdatePermission: 'Admin',
});
@@ -91,7 +90,6 @@
expect(collection.schemaVersion.isUnique).to.be.true;
expect(collection.sponsorship.asUnconfirmed.toString()).to.equal(bob.address);
expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.equal(3);
- expect(collection.variableOnChainSchema.toString()).to.equal('0x222222');
expect(collection.constOnChainSchema.toString()).to.equal('0x333333');
expect(collection.metaUpdatePermission.isAdmin).to.be.true;
});
tests/src/nesting/migration-check.test.tsdiffbeforeafterboth--- a/tests/src/nesting/migration-check.test.ts
+++ b/tests/src/nesting/migration-check.test.ts
@@ -11,7 +11,7 @@
// todo skip
describe('Migration testing for pallet-common', () => {
let alice: IKeyringPair;
-
+
before(async() => {
await usingApi(async () => {
alice = privateKey('//Alice');
@@ -36,7 +36,6 @@
limits: {
accountTokenOwnershipLimit: 3,
},
- variableOnChainSchema: '0x222222',
constOnChainSchema: '0x333333',
metaUpdatePermission: 'Admin',
});
@@ -78,13 +77,11 @@
await usingApi(async api => {
const collectionNew = (await api.query.common.collectionById(collectionId)).toJSON() as any;
-
+
// Make sure the extra fields are what they should be
- const variableOnChainSchema = await api.query.common.collectionData(collectionId, 'VariableOnChainSchema');
const constOnChainSchema = await api.query.common.collectionData(collectionId, 'ConstOnChainSchema');
const offchainSchema = await api.query.common.collectionData(collectionId, 'OffchainSchema');
- expect(variableOnChainSchema.toHex()).to.be.deep.equal((collectionOld.variableOnChainSchema));
expect(constOnChainSchema.toHex()).to.be.deep.equal(collectionOld.constOnChainSchema);
expect(offchainSchema.toHex()).to.be.deep.equal(collectionOld.offchainSchema);
expect(collectionNew).to.have.nested.property('limits.nestingRule');
@@ -93,10 +90,8 @@
delete collectionNew.limits.nestingRule;
delete collectionOld.constOnChainSchema;
delete collectionOld.offchainSchema;
- delete collectionOld.variableOnChainSchema;
expect(collectionNew).to.be.deep.equal(collectionOld);
});
});
});
-
\ No newline at end of file
tests/src/setChainLimits.test.tsdiffbeforeafterboth--- a/tests/src/setChainLimits.test.ts
+++ b/tests/src/setChainLimits.test.ts
@@ -44,7 +44,6 @@
fungibleSponsorTransferTimeout: 1,
refungibleSponsorTransferTimeout: 1,
offchainSchemaLimit: 1,
- variableOnChainSchemaLimit: 1,
constOnChainSchemaLimit: 1,
};
});
tests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth--- a/tests/src/setVariableOnChainSchema.test.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {Keyring} from '@polkadot/api';
-import {IKeyringPair} from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- destroyCollectionExpectSuccess,
- addCollectionAdminExpectSuccess,
- queryCollectionExpectSuccess,
- getCreatedCollectionCount,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let schema: any;
-let largeSchema: any;
-
-before(async () => {
- await usingApi(async () => {
- const keyring = new Keyring({type: 'sr25519'});
- alice = keyring.addFromUri('//Alice');
- bob = keyring.addFromUri('//Bob');
- schema = '0x31';
- largeSchema = new Array(8 * 1024 + 10).fill(0xff);
-
- });
-});
-describe('Integration Test ext. setVariableOnChainSchema()', () => {
-
- it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const collection = await queryCollectionExpectSuccess(api, collectionId);
- expect(collection.owner.toString()).to.be.eq(alice.address);
- const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
- await submitTransactionAsync(alice, setSchema);
- });
- });
-
- it('Checking collection data using the setVariableOnChainSchema parameter', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
- await submitTransactionAsync(alice, setSchema);
- const collection = await queryCollectionExpectSuccess(api, collectionId);
- expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);
-
- });
- });
-});
-
-describe('Integration Test ext. collection admin setVariableOnChainSchema()', () => {
-
- it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const collection = await queryCollectionExpectSuccess(api, collectionId);
- expect(collection.owner.toString()).to.be.eq(alice.address);
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
- await submitTransactionAsync(bob, setSchema);
- });
- });
-
- it('Checking collection data using the setVariableOnChainSchema parameter', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
- await submitTransactionAsync(bob, setSchema);
- const collection = await queryCollectionExpectSuccess(api, collectionId);
- expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);
-
- });
- });
-});
-
-describe('Negative Integration Test ext. setVariableOnChainSchema()', () => {
-
- it('Set a non-existent collection', async () => {
- await usingApi(async (api) => {
- // tslint:disable-next-line: radix
- const collectionId = await getCreatedCollectionCount(api) + 1;
- const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
- await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
- });
- });
-
- it('Set a previously deleted collection', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- await destroyCollectionExpectSuccess(collectionId);
- const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
- await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
- });
- });
-
- it('Set invalid data in schema (size too large:> 8kB)', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, largeSchema);
- await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
- });
- });
-
- it('Execute method not on behalf of the collection owner', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const collection = await queryCollectionExpectSuccess(api, collectionId);
- expect(collection.owner.toString()).to.be.eq(alice.address);
- const setSchema = api.tx.unique.setVariableOnChainSchema(collectionId, schema);
- await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;
- });
- });
-
-});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -136,7 +136,6 @@
fungibleSponsorTransferTimeout: number;
refungibleSponsorTransferTimeout: number;
offchainSchemaLimit: number;
- variableOnChainSchemaLimit: number;
constOnChainSchemaLimit: number;
}