difftreelog
Merge pull request #9 from usetech-llc/feature_limits_nft_78_85_105
in: master
Transfer rate limit + chain bounds
4 files changed
node/src/chain_spec.rsdiffbeforeafterboth--- a/node/src/chain_spec.rs
+++ b/node/src/chain_spec.rs
@@ -130,23 +130,35 @@
}),
sudo: Some(SudoConfig { key: root_key }),
nft: Some(NftConfig {
- collection: vec![(1, CollectionType {
- owner: get_account_id_from_seed::<sr25519::Public>("Alice"),
- mode: CollectionMode::NFT(50),
- access: AccessMode::Normal,
- decimal_points: 0,
- name: vec!(),
- description: vec!(),
- token_prefix: vec!(),
- custom_data_size: 50,
- mint_mode: false,
- offchain_schema: vec!(),
- sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),
- unconfirmed_sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),
- })],
- nft_item_id: vec!(),
- fungible_item_id: vec!(),
- refungible_item_id: vec!(),
+ collection: vec![(
+ 1,
+ CollectionType {
+ owner: get_account_id_from_seed::<sr25519::Public>("Alice"),
+ mode: CollectionMode::NFT(50),
+ access: AccessMode::Normal,
+ decimal_points: 0,
+ name: vec![],
+ description: vec![],
+ token_prefix: vec![],
+ custom_data_size: 50,
+ mint_mode: false,
+ offchain_schema: vec![],
+ sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),
+ unconfirmed_sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),
+ },
+ )],
+ nft_item_id: vec![],
+ fungible_item_id: vec![],
+ refungible_item_id: vec![],
+ chain_limit: ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ },
}),
contracts: Some(ContractsConfig {
current_schedule: ContractsSchedule {
pallets/nft/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23#[cfg(feature = "std")]4pub use serde::*;56use codec::{Decode, Encode};7pub use frame_support::{8 construct_runtime, decl_event, decl_module, decl_storage,9 dispatch::DispatchResult,10 ensure, parameter_types,11 traits::{12 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,13 Randomness, WithdrawReason,14 },15 weights::{16 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},17 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,18 WeightToFeePolynomial,19 },20 IsSubType, StorageValue,21};2223use frame_system::{self as system, ensure_signed};24use sp_runtime::sp_std::prelude::Vec;25use sp_runtime::{26 traits::{27 DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SaturatedConversion, Saturating,28 SignedExtension, Zero,29 },30 transaction_validity::{31 InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,32 ValidTransaction,33 },34 FixedPointOperand, FixedU128,35};3637#[cfg(test)]38mod mock;3940#[cfg(test)]41mod tests;4243// Structs44// #region4546#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]47#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]48pub enum CollectionMode {49 Invalid,50 // custom data size51 NFT(u32),52 // decimal points53 Fungible(u32),54 // custom data size and decimal points55 ReFungible(u32, u32),56}5758impl Into<u8> for CollectionMode {59 fn into(self) -> u8 {60 match self {61 CollectionMode::Invalid => 0,62 CollectionMode::NFT(_) => 1,63 CollectionMode::Fungible(_) => 2,64 CollectionMode::ReFungible(_, _) => 3,65 }66 }67}6869#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]70#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]71pub enum AccessMode {72 Normal,73 WhiteList,74}75impl Default for AccessMode {76 fn default() -> Self {77 Self::Normal78 }79}8081impl Default for CollectionMode {82 fn default() -> Self {83 Self::Invalid84 }85}8687#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]88#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]89pub struct Ownership<AccountId> {90 pub owner: AccountId,91 pub fraction: u128,92}9394#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]95#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]96pub struct CollectionType<AccountId> {97 pub owner: AccountId,98 pub mode: CollectionMode,99 pub access: AccessMode,100 pub decimal_points: u32,101 pub name: Vec<u16>, // 64 include null escape char102 pub description: Vec<u16>, // 256 include null escape char103 pub token_prefix: Vec<u8>, // 16 include null escape char104 pub custom_data_size: u32,105 pub mint_mode: bool,106 pub offchain_schema: Vec<u8>,107 pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender108 pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship109}110111#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]112#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]113pub struct CollectionAdminsType<AccountId> {114 pub admin: AccountId,115 pub collection_id: u64,116}117118#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]119#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]120pub struct NftItemType<AccountId> {121 pub collection: u64,122 pub owner: AccountId,123 pub data: Vec<u8>,124}125126#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]127#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]128pub struct FungibleItemType<AccountId> {129 pub collection: u64,130 pub owner: AccountId,131 pub value: u128,132}133134#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]135#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]136pub struct ReFungibleItemType<AccountId> {137 pub collection: u64,138 pub owner: Vec<Ownership<AccountId>>,139 pub data: Vec<u8>,140}141142#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]143#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]144pub struct ApprovePermissions<AccountId> {145 pub approved: AccountId,146 pub amount: u64,147}148149#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]150#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]151pub struct VestingItem<AccountId, Moment> {152 pub sender: AccountId,153 pub recipient: AccountId,154 pub collection_id: u64,155 pub item_id: u64,156 pub amount: u64,157 pub vesting_date: Moment,158}159160pub trait Trait: system::Trait {161 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;162}163164// #endregion165166decl_storage! {167 trait Store for Module<T: Trait> as Nft {168169 // Private members170 NextCollectionID: u64;171 CreatedCollectionCount: u64;172 ChainVersion: u64;173 ItemListIndex: map hasher(blake2_128_concat) u64 => u64;174175 pub Collection get(fn collection) config(): map hasher(identity) u64 => CollectionType<T::AccountId>;176 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;177 pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;178179 /// Balance owner per collection map180 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;181182 /// second parameter: item id + owner account id183 pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;184185 /// Item collections186 pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;187 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;188 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;189190 /// Index list191 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;192193 // Sponsorship194 pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;195 pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;196 }197 add_extra_genesis {198 build(|config: &GenesisConfig<T>| {199 // Modification of storage200 for (_num, _c) in &config.collection {201 <Module<T>>::init_collection(_c);202 }203204 for (_num, _q, _i) in &config.nft_item_id {205 <Module<T>>::init_nft_token(_i);206 }207208 for (_num, _q, _i) in &config.fungible_item_id {209 <Module<T>>::init_fungible_token(_i);210 }211212 for (_num, _q, _i) in &config.refungible_item_id {213 <Module<T>>::init_refungible_token(_i);214 }215 })216 }217}218219decl_event!(220 pub enum Event<T>221 where222 AccountId = <T as system::Trait>::AccountId,223 {224 /// New collection was created225 /// 226 /// # Arguments227 /// 228 /// * collection_id: Globally unique identifier of newly created collection.229 /// 230 /// * mode: [CollectionMode] converted into u8.231 /// 232 /// * account_id: Collection owner.233 Created(u64, u8, AccountId),234235 /// New item was created.236 /// 237 /// # Arguments238 /// 239 /// * collection_id: Id of the collection where item was created.240 /// 241 /// * item_id: Id of an item. Unique within the collection.242 ItemCreated(u64, u64),243244 /// Collection item was burned.245 /// 246 /// # Arguments247 /// 248 /// collection_id.249 /// 250 /// item_id: Identifier of burned NFT.251 ItemDestroyed(u64, u64),252 }253);254255decl_module! {256 pub struct Module<T: Trait> for enum Call where origin: T::Origin {257258 fn deposit_event() = default;259260 fn on_initialize(now: T::BlockNumber) -> Weight {261262 if ChainVersion::get() < 2263 {264 let value = NextCollectionID::get();265 CreatedCollectionCount::put(value);266 ChainVersion::put(2);267 }268269 0270 }271272 /// This method creates a Collection of NFTs. Each Token may have multiple properties encoded as an array of bytes of certain length. The initial owner and admin of the collection are set to the address that signed the transaction. Both addresses can be changed later.273 /// 274 /// # Permissions275 /// 276 /// * Anyone.277 /// 278 /// # Arguments279 /// 280 /// * collection_name: UTF-16 string with collection name (limit 64 characters), will be stored as zero-terminated.281 /// 282 /// * collection_description: UTF-16 string with collection description (limit 256 characters), will be stored as zero-terminated.283 /// 284 /// * token_prefix: UTF-8 string with token prefix.285 /// 286 /// * mode: [CollectionMode] collection type and type dependent data.287 // returns collection ID288 #[weight = 0]289 pub fn create_collection(origin,290 collection_name: Vec<u16>,291 collection_description: Vec<u16>,292 token_prefix: Vec<u8>,293 mode: CollectionMode) -> DispatchResult {294295 // Anyone can create a collection296 let who = ensure_signed(origin)?;297 let custom_data_size = match mode {298 CollectionMode::NFT(size) => size,299 CollectionMode::ReFungible(size, _) => size,300 _ => 0301 };302303 let decimal_points = match mode {304 CollectionMode::Fungible(points) => points,305 CollectionMode::ReFungible(_, points) => points,306 _ => 0307 };308309 // check params310 ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");311312 let mut name = collection_name.to_vec();313 name.push(0);314 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");315316 let mut description = collection_description.to_vec();317 description.push(0);318 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");319320 let mut prefix = token_prefix.to_vec();321 prefix.push(0);322 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");323324 // Generate next collection ID325 let next_id = CreatedCollectionCount::get()326 .checked_add(1)327 .expect("collection id error");328329 CreatedCollectionCount::put(next_id);330331 // Create new collection332 let new_collection = CollectionType {333 owner: who.clone(),334 name: name,335 mode: mode.clone(),336 mint_mode: false,337 access: AccessMode::Normal,338 description: description,339 decimal_points: decimal_points,340 token_prefix: prefix,341 offchain_schema: Vec::new(),342 custom_data_size: custom_data_size,343 sponsor: T::AccountId::default(),344 unconfirmed_sponsor: T::AccountId::default(),345 };346347 // Add new collection to map348 <Collection<T>>::insert(next_id, new_collection);349350 // call event351 Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));352353 Ok(())354 }355356 /// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.357 /// 358 /// # Permissions359 /// 360 /// * Collection Owner.361 /// 362 /// # Arguments363 /// 364 /// * collection_id: collection to destroy.365 #[weight = 0]366 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {367368 let sender = ensure_signed(origin)?;369 Self::check_owner_permissions(collection_id, sender)?;370371 // TODO Items remove372 <AddressTokens<T>>::remove_prefix(collection_id);373 <ApprovedList<T>>::remove_prefix(collection_id);374 <Balance<T>>::remove_prefix(collection_id);375 <ItemListIndex>::remove(collection_id);376 <AdminList<T>>::remove(collection_id);377 <Collection<T>>::remove(collection_id);378 <WhiteList<T>>::remove(collection_id);379380 Ok(())381 }382383 /// Add an address to white list.384 /// 385 /// # Permissions386 /// 387 /// * Collection Owner388 /// * Collection Admin389 /// 390 /// # Arguments391 /// 392 /// * collection_id.393 /// 394 /// * address.395 #[weight = 0]396 pub fn add_to_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{397398 let sender = ensure_signed(origin)?;399 Self::check_owner_or_admin_permissions(collection_id, sender)?;400401 let mut white_list_collection: Vec<T::AccountId>;402 if <WhiteList<T>>::contains_key(collection_id) {403 white_list_collection = <WhiteList<T>>::get(collection_id);404 if !white_list_collection.contains(&address.clone())405 {406 white_list_collection.push(address.clone());407 }408 }409 else {410 white_list_collection = Vec::new();411 white_list_collection.push(address.clone());412 }413414 <WhiteList<T>>::insert(collection_id, white_list_collection);415 Ok(())416 }417418 /// Remove an address from white list.419 /// 420 /// # Permissions421 /// 422 /// * Collection Owner423 /// * Collection Admin424 /// 425 /// # Arguments426 /// 427 /// * collection_id.428 /// 429 /// * address.430 #[weight = 0]431 pub fn remove_from_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{432433 let sender = ensure_signed(origin)?;434 Self::check_owner_or_admin_permissions(collection_id, sender)?;435436 if <WhiteList<T>>::contains_key(collection_id) {437 let mut white_list_collection = <WhiteList<T>>::get(collection_id);438 if white_list_collection.contains(&address.clone())439 {440 white_list_collection.retain(|i| *i != address.clone());441 <WhiteList<T>>::insert(collection_id, white_list_collection);442 }443 }444445 Ok(())446 }447448 /// Toggle between normal and white list access for the methods with access for `Anyone`.449 /// 450 /// # Permissions451 /// 452 /// * Collection Owner.453 /// 454 /// # Arguments455 /// 456 /// * collection_id.457 /// 458 /// * mode: [AccessMode]459 #[weight = 0]460 pub fn set_public_access_mode(origin, collection_id: u64, mode: AccessMode) -> DispatchResult461 {462 let sender = ensure_signed(origin)?;463464 Self::check_owner_permissions(collection_id, sender)?;465 let mut target_collection = <Collection<T>>::get(collection_id);466 target_collection.access = mode;467 <Collection<T>>::insert(collection_id, target_collection);468469 Ok(())470 }471472 /// Allows Anyone to create tokens if:473 /// * White List is enabled, and474 /// * Address is added to white list, and475 /// * This method was called with True parameter476 /// 477 /// # Permissions478 /// * Collection Owner479 ///480 /// # Arguments481 /// 482 /// * collection_id.483 /// 484 /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.485 #[weight = 0]486 pub fn set_mint_permission(origin, collection_id: u64, mint_permission: bool) -> DispatchResult487 {488 let sender = ensure_signed(origin)?;489490 Self::check_owner_permissions(collection_id, sender)?;491 let mut target_collection = <Collection<T>>::get(collection_id);492 target_collection.mint_mode = mint_permission;493 <Collection<T>>::insert(collection_id, target_collection);494495 Ok(())496 }497498 /// Change the owner of the collection.499 /// 500 /// # Permissions501 /// 502 /// * Collection Owner.503 /// 504 /// # Arguments505 /// 506 /// * collection_id.507 /// 508 /// * new_owner.509 #[weight = 0]510 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {511512 let sender = ensure_signed(origin)?;513 Self::check_owner_permissions(collection_id, sender)?;514 let mut target_collection = <Collection<T>>::get(collection_id);515 target_collection.owner = new_owner;516 <Collection<T>>::insert(collection_id, target_collection);517518 Ok(())519 }520521 /// Adds an admin of the Collection.522 /// NFT Collection can be controlled by multiple admin addresses (some which can also be servers, for example). Admins can issue and burn NFTs, as well as add and remove other admins, but cannot change NFT or Collection ownership. 523 /// 524 /// # Permissions525 /// 526 /// * Collection Owner.527 /// * Collection Admin.528 /// 529 /// # Arguments530 /// 531 /// * collection_id: ID of the Collection to add admin for.532 /// 533 /// * new_admin_id: Address of new admin to add.534 #[weight = 0]535 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {536537 let sender = ensure_signed(origin)?;538 Self::check_owner_or_admin_permissions(collection_id, sender)?;539 let mut admin_arr: Vec<T::AccountId> = Vec::new();540541 if <AdminList<T>>::contains_key(collection_id)542 {543 admin_arr = <AdminList<T>>::get(collection_id);544 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");545 }546547 admin_arr.push(new_admin_id);548 <AdminList<T>>::insert(collection_id, admin_arr);549550 Ok(())551 }552553 /// Remove admin address of the Collection. An admin address can remove itself. List of admins may become empty, in which case only Collection Owner will be able to add an Admin.554 ///555 /// # Permissions556 /// 557 /// * Collection Owner.558 /// * Collection Admin.559 /// 560 /// # Arguments561 /// 562 /// * collection_id: ID of the Collection to remove admin for.563 /// 564 /// * account_id: Address of admin to remove.565 #[weight = 0]566 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {567568 let sender = ensure_signed(origin)?;569 Self::check_owner_or_admin_permissions(collection_id, sender)?;570571 if <AdminList<T>>::contains_key(collection_id)572 {573 let mut admin_arr = <AdminList<T>>::get(collection_id);574 admin_arr.retain(|i| *i != account_id);575 <AdminList<T>>::insert(collection_id, admin_arr);576 }577578 Ok(())579 }580581 /// # Permissions582 /// 583 /// * Collection Owner584 /// 585 /// # Arguments586 /// 587 /// * collection_id.588 /// 589 /// * new_sponsor.590 #[weight = 0]591 pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {592593 let sender = ensure_signed(origin)?;594 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");595596 let mut target_collection = <Collection<T>>::get(collection_id);597 ensure!(sender == target_collection.owner, "You do not own this collection");598599 target_collection.unconfirmed_sponsor = new_sponsor;600 <Collection<T>>::insert(collection_id, target_collection);601602 Ok(())603 }604605 /// # Permissions606 /// 607 /// * Sponsor.608 /// 609 /// # Arguments610 /// 611 /// * collection_id.612 #[weight = 0]613 pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {614615 let sender = ensure_signed(origin)?;616 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");617618 let mut target_collection = <Collection<T>>::get(collection_id);619 ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");620621 target_collection.sponsor = target_collection.unconfirmed_sponsor;622 target_collection.unconfirmed_sponsor = T::AccountId::default();623 <Collection<T>>::insert(collection_id, target_collection);624625 Ok(())626 }627628 /// Switch back to pay-per-own-transaction model.629 ///630 /// # Permissions631 ///632 /// * Collection owner.633 /// 634 /// # Arguments635 /// 636 /// * collection_id.637 #[weight = 0]638 pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {639640 let sender = ensure_signed(origin)?;641 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");642643 let mut target_collection = <Collection<T>>::get(collection_id);644 ensure!(sender == target_collection.owner, "You do not own this collection");645646 target_collection.sponsor = T::AccountId::default();647 <Collection<T>>::insert(collection_id, target_collection);648649 Ok(())650 }651652 /// This method creates a concrete instance of NFT Collection created with CreateCollection method.653 /// 654 /// # Permissions655 /// 656 /// * Collection Owner.657 /// * Collection Admin.658 /// * Anyone if659 /// * White List is enabled, and660 /// * Address is added to white list, and661 /// * MintPermission is enabled (see SetMintPermission method)662 /// 663 /// # Arguments664 /// 665 /// * collection_id: ID of the collection.666 /// 667 /// * properties: Array of bytes that contains NFT properties. Since NFT Module is agnostic of properties meaning, it is treated purely as an array of bytes.668 /// 669 /// * owner: Address, initial owner of the NFT.670 #[weight = 0]671 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {672673 let sender = ensure_signed(origin)?;674 Self::collection_exists(collection_id)?;675 let target_collection = <Collection<T>>::get(collection_id);676677 if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) {678 ensure!(target_collection.mint_mode == true, "Public minting is not allowed for this collection");679 Self::check_white_list(collection_id, &owner)?;680 Self::check_white_list(collection_id, &sender)?;681 }682683 match target_collection.mode684 {685 CollectionMode::NFT(_) => {686687 // check size688 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");689690 // Create nft item691 let item = NftItemType {692 collection: collection_id,693 owner: owner,694 data: properties.clone(),695 };696697 Self::add_nft_item(item)?;698699 },700 CollectionMode::Fungible(_) => {701702 // check size703 ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");704705 let item = FungibleItemType {706 collection: collection_id,707 owner: owner,708 value: (10 as u128).pow(target_collection.decimal_points)709 };710711 Self::add_fungible_item(item)?;712 },713 CollectionMode::ReFungible(_, _) => {714715 // check size716 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");717718 let mut owner_list = Vec::new();719 let value = (10 as u128).pow(target_collection.decimal_points);720 owner_list.push(Ownership {owner: owner.clone(), fraction: value});721722 let item = ReFungibleItemType {723 collection: collection_id,724 owner: owner_list,725 data: properties.clone()726 };727728 Self::add_refungible_item(item)?;729 },730 _ => { ensure!(1 == 0,"just error"); }731732 };733734 // call event735 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));736737 Ok(())738 }739740 /// Destroys a concrete instance of NFT.741 /// 742 /// # Permissions743 /// 744 /// * Collection Owner.745 /// * Collection Admin.746 /// * Current NFT Owner.747 /// 748 /// # Arguments749 /// 750 /// * collection_id: ID of the collection.751 /// 752 /// * item_id: ID of NFT to burn.753 #[weight = 0]754 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {755756 let sender = ensure_signed(origin)?;757 Self::collection_exists(collection_id)?;758759 // Transfer permissions check760 let target_collection = <Collection<T>>::get(collection_id);761 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) || 762 Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 763 "Only item owner, collection owner and admins can modify item");764765 if target_collection.access == AccessMode::WhiteList {766 Self::check_white_list(collection_id, &sender)?;767 }768769 match target_collection.mode770 {771 CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,772 CollectionMode::Fungible(_) => Self::burn_fungible_item(collection_id, item_id)?,773 CollectionMode::ReFungible(_, _) => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,774 _ => ()775 };776777 // call event778 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));779780 Ok(())781 }782783 /// Change ownership of the token.784 /// 785 /// # Permissions786 /// 787 /// * Collection Owner788 /// * Collection Admin789 /// * Current NFT owner790 ///791 /// # Arguments792 /// 793 /// * recipient: Address of token recipient.794 /// 795 /// * collection_id.796 /// 797 /// * item_id: ID of the item798 /// * Non-Fungible Mode: Required.799 /// * Fungible Mode: Ignored.800 /// * Re-Fungible Mode: Required.801 /// 802 /// * value: Amount to transfer.803 /// * Non-Fungible Mode: Ignored804 /// * Fungible Mode: Must specify transferred amount805 /// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)806 #[weight = 0]807 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {808809 let sender = ensure_signed(origin)?;810811 // Transfer permissions check812 let target_collection = <Collection<T>>::get(collection_id);813 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) || 814 Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 815 "Only item owner, collection owner and admins can modify item");816817 if target_collection.access == AccessMode::WhiteList {818 Self::check_white_list(collection_id, &sender)?;819 Self::check_white_list(collection_id, &recipient)?;820 }821822 match target_collection.mode823 {824 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,825 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,826 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,827 _ => ()828 };829830 Ok(())831 }832833 /// Set, change, or remove approved address to transfer the ownership of the NFT.834 /// 835 /// # Permissions836 /// 837 /// * Collection Owner838 /// * Collection Admin839 /// * Current NFT owner840 /// 841 /// # Arguments842 /// 843 /// * approved: Address that is approved to transfer this NFT or zero (if needed to remove approval).844 /// 845 /// * collection_id.846 /// 847 /// * item_id: ID of the item.848 #[weight = 0]849 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {850851 let sender = ensure_signed(origin)?;852853 // Transfer permissions check854 let target_collection = <Collection<T>>::get(collection_id);855 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) || 856 Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 857 "Only item owner, collection owner and admins can approve");858859 if target_collection.access == AccessMode::WhiteList {860 Self::check_white_list(collection_id, &sender)?;861 Self::check_white_list(collection_id, &approved)?;862 }863864 // amount param stub865 let amount = 100000000;866867 let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));868 if list_exists {869870 let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));871 let item_contains = list.iter().any(|i| i.approved == approved);872873 if !item_contains {874 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });875 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);876 }877 } else {878879 let mut list = Vec::new();880 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });881 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);882 }883884 Ok(())885 }886 887 /// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.888 /// 889 /// # Permissions890 /// * Collection Owner891 /// * Collection Admin892 /// * Current NFT owner893 /// * Address approved by current NFT owner894 /// 895 /// # Arguments896 /// 897 /// * from: Address that owns token.898 /// 899 /// * recipient: Address of token recipient.900 /// 901 /// * collection_id.902 /// 903 /// * item_id: ID of the item.904 /// 905 /// * value: Amount to transfer.906 #[weight = 0]907 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {908909 let sender = ensure_signed(origin)?;910 let mut appoved_transfer = false;911912 // Check approve913 if <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone())) {914 let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));915 let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());916 appoved_transfer = opt_item.is_some();917 ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");918 }919920 // Transfer permissions check921 let target_collection = <Collection<T>>::get(collection_id);922 ensure!(appoved_transfer || Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 923 "Only item owner, collection owner and admins can modify items");924925 if target_collection.access == AccessMode::WhiteList {926 Self::check_white_list(collection_id, &sender)?;927 Self::check_white_list(collection_id, &recipient)?;928 }929930 // remove approve931 let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))932 .into_iter().filter(|i| i.approved != sender.clone()).collect();933 <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);934935936 match target_collection.mode937 {938 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,939 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,940 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,941 _ => ()942 };943944 Ok(())945 }946947 ///948 #[weight = 0]949 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {950951 // let no_perm_mes = "You do not have permissions to modify this collection";952 // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);953 // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));954 // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);955956 // // on_nft_received call957958 // Self::transfer(origin, collection_id, item_id, new_owner)?;959960 Ok(())961 }962963 /// Set off-chain data schema.964 /// 965 /// # Permissions966 /// 967 /// * Collection Owner968 /// * Collection Admin969 /// 970 /// # Arguments971 /// 972 /// * collection_id.973 /// 974 /// * schema: String representing the offchain data schema.975 #[weight = 0]976 pub fn set_offchain_schema(977 origin,978 collection_id: u64,979 schema: Vec<u8>980 ) -> DispatchResult {981 let sender = ensure_signed(origin)?;982 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;983984 let mut target_collection = <Collection<T>>::get(collection_id);985 target_collection.offchain_schema = schema;986 <Collection<T>>::insert(collection_id, target_collection);987988 Ok(())989 }990 }991}992993impl<T: Trait> Module<T> {994 fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {995 let current_index = <ItemListIndex>::get(item.collection)996 .checked_add(1)997 .expect("Item list index id error");998 let itemcopy = item.clone();999 let owner = item.owner.clone();1000 let value = item.value as u64;10011002 Self::add_token_index(item.collection, current_index, owner.clone())?;10031004 <ItemListIndex>::insert(item.collection, current_index);1005 <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);10061007 // Update balance1008 let new_balance = <Balance<T>>::get(item.collection, owner.clone())1009 .checked_add(value)1010 .unwrap();1011 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);10121013 Ok(())1014 }10151016 fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {1017 let current_index = <ItemListIndex>::get(item.collection)1018 .checked_add(1)1019 .expect("Item list index id error");1020 let itemcopy = item.clone();10211022 let value = item.owner.first().unwrap().fraction as u64;1023 let owner = item.owner.first().unwrap().owner.clone();10241025 Self::add_token_index(item.collection, current_index, owner.clone())?;10261027 <ItemListIndex>::insert(item.collection, current_index);1028 <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);10291030 // Update balance1031 let new_balance = <Balance<T>>::get(item.collection, owner.clone())1032 .checked_add(value)1033 .unwrap();1034 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);10351036 Ok(())1037 }10381039 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {1040 let current_index = <ItemListIndex>::get(item.collection)1041 .checked_add(1)1042 .expect("Item list index id error");10431044 let item_owner = item.owner.clone();1045 let collection_id = item.collection.clone();1046 Self::add_token_index(collection_id, current_index, item.owner.clone())?;10471048 <ItemListIndex>::insert(collection_id, current_index);1049 <NftItemList<T>>::insert(collection_id, current_index, item);10501051 // Update balance1052 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())1053 .checked_add(1)1054 .unwrap();1055 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);10561057 Ok(())1058 }10591060 fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {1061 ensure!(1062 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1063 "Item does not exists"1064 );1065 let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);1066 let item = collection1067 .owner1068 .iter()1069 .filter(|&i| i.owner == owner)1070 .next()1071 .unwrap();1072 Self::remove_token_index(collection_id, item_id, owner.clone())?;10731074 // remove approve list1075 <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));10761077 // update balance1078 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())1079 .checked_sub(item.fraction as u64)1080 .unwrap();1081 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);10821083 <ReFungibleItemList<T>>::remove(collection_id, item_id);10841085 Ok(())1086 }10871088 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {1089 ensure!(1090 <NftItemList<T>>::contains_key(collection_id, item_id),1091 "Item does not exists"1092 );1093 let item = <NftItemList<T>>::get(collection_id, item_id);1094 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;10951096 // remove approve list1097 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));10981099 // update balance1100 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())1101 .checked_sub(1)1102 .unwrap();1103 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);1104 <NftItemList<T>>::remove(collection_id, item_id);11051106 Ok(())1107 }11081109 fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {1110 ensure!(1111 <FungibleItemList<T>>::contains_key(collection_id, item_id),1112 "Item does not exists"1113 );1114 let item = <FungibleItemList<T>>::get(collection_id, item_id);1115 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;11161117 // remove approve list1118 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));11191120 // update balance1121 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())1122 .checked_sub(item.value as u64)1123 .unwrap();1124 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);11251126 <FungibleItemList<T>>::remove(collection_id, item_id);11271128 Ok(())1129 }11301131 fn collection_exists(collection_id: u64) -> DispatchResult {1132 ensure!(1133 <Collection<T>>::contains_key(collection_id),1134 "This collection does not exist"1135 );1136 Ok(())1137 }11381139 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {1140 Self::collection_exists(collection_id)?;11411142 let target_collection = <Collection<T>>::get(collection_id);1143 ensure!(1144 subject == target_collection.owner,1145 "You do not own this collection"1146 );11471148 Ok(())1149 }11501151 fn is_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> bool {11521153 let target_collection = <Collection<T>>::get(collection_id);1154 let mut result: bool = subject == target_collection.owner;1155 let exists = <AdminList<T>>::contains_key(collection_id);11561157 if !result & exists {1158 if <AdminList<T>>::get(collection_id).contains(&subject) {1159 result = true1160 }1161 }11621163 result1164 }11651166 fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {1167 1168 Self::collection_exists(collection_id)?;1169 let result = Self::is_owner_or_admin_permissions(collection_id, subject.clone());11701171 ensure!(result, "You do not have permissions to modify this collection");1172 Ok(())1173 }11741175 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {1176 let target_collection = <Collection<T>>::get(collection_id);11771178 match target_collection.mode {1179 CollectionMode::NFT(_) => {1180 <NftItemList<T>>::get(collection_id, item_id).owner == subject1181 }1182 CollectionMode::Fungible(_) => {1183 <FungibleItemList<T>>::get(collection_id, item_id).owner == subject1184 }1185 CollectionMode::ReFungible(_, _) => {1186 <ReFungibleItemList<T>>::get(collection_id, item_id)1187 .owner1188 .iter()1189 .any(|i| i.owner == subject)1190 }1191 CollectionMode::Invalid => false,1192 }1193 }11941195 fn check_white_list(collection_id: u64, address: &T::AccountId) -> DispatchResult {11961197 let mes = "Address is not in white list";1198 ensure!(<WhiteList<T>>::contains_key(collection_id), mes);1199 let wl = <WhiteList<T>>::get(collection_id);1200 ensure!(wl.contains(address), mes);12011202 Ok(())1203 }12041205 fn transfer_fungible(1206 collection_id: u64,1207 item_id: u64,1208 value: u64,1209 owner: T::AccountId,1210 new_owner: T::AccountId,1211 ) -> DispatchResult {12121213 ensure!(1214 <FungibleItemList<T>>::contains_key(collection_id, item_id),1215 "Item not exists"1216 );12171218 let full_item = <FungibleItemList<T>>::get(collection_id, item_id);1219 let amount = full_item.value;12201221 ensure!(amount >= value.into(), "Item balance not enouth");12221223 // update balance1224 let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())1225 .checked_sub(value)1226 .unwrap();1227 <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);12281229 let mut new_owner_account_id = 0;1230 let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());1231 if new_owner_items.len() > 0 {1232 new_owner_account_id = new_owner_items[0];1233 }12341235 let val64 = value.into();12361237 // transfer1238 if amount == val64 && new_owner_account_id == 0 {1239 // change owner1240 // new owner do not have account1241 let mut new_full_item = full_item.clone();1242 new_full_item.owner = new_owner.clone();1243 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);12441245 // update balance1246 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1247 .checked_add(value)1248 .unwrap();1249 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);12501251 // update index collection1252 Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;1253 } else {1254 let mut new_full_item = full_item.clone();1255 new_full_item.value -= val64;12561257 // separate amount1258 if new_owner_account_id > 0 {1259 // new owner has account1260 let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);1261 item.value += val64;12621263 // update balance1264 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1265 .checked_add(value)1266 .unwrap();1267 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);12681269 <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);1270 } else {1271 // new owner do not have account1272 let item = FungibleItemType {1273 collection: collection_id,1274 owner: new_owner.clone(),1275 value: val64,1276 };12771278 Self::add_fungible_item(item)?;1279 }12801281 if amount == val64 {1282 Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;12831284 // remove approve list1285 <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));1286 <FungibleItemList<T>>::remove(collection_id, item_id);1287 }12881289 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1290 }12911292 Ok(())1293 }12941295 fn transfer_refungible(1296 collection_id: u64,1297 item_id: u64,1298 value: u64,1299 owner: T::AccountId,1300 new_owner: T::AccountId,1301 ) -> DispatchResult {13021303 ensure!(1304 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1305 "Item not exists"1306 );13071308 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);1309 let item = full_item1310 .owner1311 .iter()1312 .filter(|i| i.owner == owner)1313 .next()1314 .unwrap();1315 let amount = item.fraction;13161317 ensure!(amount >= value.into(), "Item balance not enouth");13181319 // update balance1320 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1321 .checked_sub(value)1322 .unwrap();1323 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);13241325 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1326 .checked_add(value)1327 .unwrap();1328 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);13291330 let old_owner = item.owner.clone();1331 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);1332 let val64 = value.into();13331334 // transfer1335 if amount == val64 && !new_owner_has_account {1336 // change owner1337 // new owner do not have account1338 let mut new_full_item = full_item.clone();1339 new_full_item1340 .owner1341 .iter_mut()1342 .find(|i| i.owner == owner)1343 .unwrap()1344 .owner = new_owner.clone();1345 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);13461347 // update index collection1348 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;1349 } else {1350 let mut new_full_item = full_item.clone();1351 new_full_item1352 .owner1353 .iter_mut()1354 .find(|i| i.owner == owner)1355 .unwrap()1356 .fraction -= val64;13571358 // separate amount1359 if new_owner_has_account {1360 // new owner has account1361 new_full_item1362 .owner1363 .iter_mut()1364 .find(|i| i.owner == new_owner)1365 .unwrap()1366 .fraction += val64;1367 } else {1368 // new owner do not have account1369 new_full_item.owner.push(Ownership {1370 owner: new_owner.clone(),1371 fraction: val64,1372 });1373 Self::add_token_index(collection_id, item_id, new_owner.clone())?;1374 }13751376 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1377 }13781379 Ok(())1380 }13811382 fn transfer_nft(1383 collection_id: u64,1384 item_id: u64,1385 sender: T::AccountId,1386 new_owner: T::AccountId,1387 ) -> DispatchResult {1388 1389 ensure!(1390 <NftItemList<T>>::contains_key(collection_id, item_id),1391 "Item not exists"1392 );13931394 let mut item = <NftItemList<T>>::get(collection_id, item_id);13951396 ensure!(1397 sender == item.owner,1398 "sender parameter and item owner must be equal"1399 );14001401 // update balance1402 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1403 .checked_sub(1)1404 .unwrap();1405 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);14061407 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1408 .checked_add(1)1409 .unwrap();1410 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);14111412 // change owner1413 let old_owner = item.owner.clone();1414 item.owner = new_owner.clone();1415 <NftItemList<T>>::insert(collection_id, item_id, item);14161417 // update index collection1418 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;14191420 // reset approved list1421 <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1422 Ok(())1423 }14241425 fn init_collection(item: &CollectionType<T::AccountId>){14261427 // check params1428 assert!(item.decimal_points <= 4, "decimal_points parameter must be lower than 4");1429 assert!(item.name.len() <= 64, "Collection name can not be longer than 63 char");1430 assert!(item.name.len() <= 256, "Collection description can not be longer than 255 char");1431 assert!(item.token_prefix.len() <= 16, "Token prefix can not be longer than 15 char");1432 1433 // Generate next collection ID1434 let next_id = CreatedCollectionCount::get()1435 .checked_add(1)1436 .expect("collection id error");1437 1438 CreatedCollectionCount::put(next_id); 1439 }14401441 fn init_nft_token(item: &NftItemType<T::AccountId>){14421443 let current_index = <ItemListIndex>::get(item.collection)1444 .checked_add(1)1445 .expect("Item list index id error");14461447 let item_owner = item.owner.clone();1448 let collection_id = item.collection.clone();1449 Self::add_token_index(collection_id, current_index, item.owner.clone()).unwrap();14501451 <ItemListIndex>::insert(collection_id, current_index);14521453 // Update balance1454 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())1455 .checked_add(1)1456 .unwrap();1457 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);1458 }14591460 fn init_fungible_token(item: &FungibleItemType<T::AccountId>){14611462 let current_index = <ItemListIndex>::get(item.collection)1463 .checked_add(1)1464 .expect("Item list index id error");1465 let owner = item.owner.clone();1466 let value = item.value as u64;14671468 Self::add_token_index(item.collection, current_index, owner.clone()).unwrap();14691470 <ItemListIndex>::insert(item.collection, current_index);14711472 // Update balance1473 let new_balance = <Balance<T>>::get(item.collection, owner.clone())1474 .checked_add(value)1475 .unwrap();1476 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);1477 }14781479 fn init_refungible_token(item: &ReFungibleItemType<T::AccountId>){14801481 let current_index = <ItemListIndex>::get(item.collection)1482 .checked_add(1)1483 .expect("Item list index id error");14841485 let value = item.owner.first().unwrap().fraction as u64;1486 let owner = item.owner.first().unwrap().owner.clone();14871488 Self::add_token_index(item.collection, current_index, owner.clone()).unwrap();14891490 <ItemListIndex>::insert(item.collection, current_index);14911492 // Update balance1493 let new_balance = <Balance<T>>::get(item.collection, owner.clone())1494 .checked_add(value)1495 .unwrap();1496 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);1497 }14981499 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1500 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1501 if list_exists {1502 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1503 let item_contains = list.contains(&item_index.clone());15041505 if !item_contains {1506 list.push(item_index.clone());1507 }15081509 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1510 } else {1511 let mut itm = Vec::new();1512 itm.push(item_index.clone());1513 <AddressTokens<T>>::insert(collection_id, owner, itm);1514 }15151516 Ok(())1517 }15181519 fn remove_token_index(1520 collection_id: u64,1521 item_index: u64,1522 owner: T::AccountId,1523 ) -> DispatchResult {1524 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1525 if list_exists {1526 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1527 let item_contains = list.contains(&item_index.clone());15281529 if item_contains {1530 list.retain(|&item| item != item_index);1531 <AddressTokens<T>>::insert(collection_id, owner, list);1532 }1533 }15341535 Ok(())1536 }15371538 fn move_token_index(1539 collection_id: u64,1540 item_index: u64,1541 old_owner: T::AccountId,1542 new_owner: T::AccountId,1543 ) -> DispatchResult {1544 Self::remove_token_index(collection_id, item_index, old_owner)?;1545 Self::add_token_index(collection_id, item_index, new_owner)?;15461547 Ok(())1548 }1549}15501551////////////////////////////////////////////////////////////////////////////////////////////////////1552// Economic models1553// #region15541555/// Fee multiplier.1556pub type Multiplier = FixedU128;15571558type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1559 <T as system::Trait>::AccountId,1560>>::Balance;1561type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1562 <T as system::Trait>::AccountId,1563>>::NegativeImbalance;15641565/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1566/// in the queue.1567#[derive(Encode, Decode, Clone, Eq, PartialEq)]1568pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1569 #[codec(compact)] BalanceOf<T>,1570);15711572impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1573 for ChargeTransactionPayment<T>1574{1575 #[cfg(feature = "std")]1576 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1577 write!(f, "ChargeTransactionPayment<{:?}>", self.0)1578 }1579 #[cfg(not(feature = "std"))]1580 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1581 Ok(())1582 }1583}15841585impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1586where1587 T::Call:1588 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1589 BalanceOf<T>: Send + Sync + FixedPointOperand,1590{1591 /// utility constructor. Used only in client/factory code.1592 pub fn from(fee: BalanceOf<T>) -> Self {1593 Self(fee)1594 }15951596 pub fn traditional_fee(1597 len: usize,1598 info: &DispatchInfoOf<T::Call>,1599 tip: BalanceOf<T>,1600 ) -> BalanceOf<T>1601 where1602 T::Call: Dispatchable<Info = DispatchInfo>,1603 {1604 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1605 }16061607 fn withdraw_fee(1608 &self,1609 who: &T::AccountId,1610 call: &T::Call,1611 info: &DispatchInfoOf<T::Call>,1612 len: usize,1613 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1614 let tip = self.0;16151616 // Set fee based on call type. Creating collection costs 1 Unique.1617 // All other transactions have traditional fees so far1618 let fee = match call.is_sub_type() {1619 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1620 _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1621 // _ => <BalanceOf<T>>::from(100)1622 };16231624 // Determine who is paying transaction fee based on ecnomic model1625 // Parse call to extract collection ID and access collection sponsor1626 let sponsor: T::AccountId = match call.is_sub_type() {1627 Some(Call::create_item(collection_id, _properties, _owner)) => {1628 <Collection<T>>::get(collection_id).sponsor1629 }1630 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1631 <Collection<T>>::get(collection_id).sponsor1632 }16331634 _ => T::AccountId::default(),1635 };16361637 let mut who_pays_fee: T::AccountId = sponsor.clone();1638 if sponsor == T::AccountId::default() {1639 who_pays_fee = who.clone();1640 }16411642 // Only mess with balances if fee is not zero.1643 if fee.is_zero() {1644 return Ok((fee, None));1645 }16461647 match <T as transaction_payment::Trait>::Currency::withdraw(1648 &who_pays_fee,1649 fee,1650 if tip.is_zero() {1651 WithdrawReason::TransactionPayment.into()1652 } else {1653 WithdrawReason::TransactionPayment | WithdrawReason::Tip1654 },1655 ExistenceRequirement::KeepAlive,1656 ) {1657 Ok(imbalance) => Ok((fee, Some(imbalance))),1658 Err(_) => Err(InvalidTransaction::Payment.into()),1659 }1660 }1661}16621663impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1664 for ChargeTransactionPayment<T>1665where1666 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1667 T::Call:1668 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1669{1670 const IDENTIFIER: &'static str = "ChargeTransactionPayment";1671 type AccountId = T::AccountId;1672 type Call = T::Call;1673 type AdditionalSigned = ();1674 type Pre = (1675 BalanceOf<T>,1676 Self::AccountId,1677 Option<NegativeImbalanceOf<T>>,1678 BalanceOf<T>,1679 );1680 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1681 Ok(())1682 }16831684 fn validate(1685 &self,1686 who: &Self::AccountId,1687 call: &Self::Call,1688 info: &DispatchInfoOf<Self::Call>,1689 len: usize,1690 ) -> TransactionValidity {1691 let (fee, _) = self.withdraw_fee(who, call, info, len)?;16921693 let mut r = ValidTransaction::default();1694 // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1695 // will be a bit more than setting the priority to tip. For now, this is enough.1696 r.priority = fee.saturated_into::<TransactionPriority>();1697 Ok(r)1698 }16991700 fn pre_dispatch(1701 self,1702 who: &Self::AccountId,1703 call: &Self::Call,1704 info: &DispatchInfoOf<Self::Call>,1705 len: usize,1706 ) -> Result<Self::Pre, TransactionValidityError> {1707 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1708 Ok((self.0, who.clone(), imbalance, fee))1709 }17101711 fn post_dispatch(1712 pre: Self::Pre,1713 info: &DispatchInfoOf<Self::Call>,1714 post_info: &PostDispatchInfoOf<Self::Call>,1715 len: usize,1716 _result: &DispatchResult,1717 ) -> Result<(), TransactionValidityError> {1718 let (tip, who, imbalance, fee) = pre;1719 if let Some(payed) = imbalance {1720 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1721 len as u32, info, post_info, tip,1722 );1723 let refund = fee.saturating_sub(actual_fee);1724 let actual_payment =1725 match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1726 &who, refund,1727 ) {1728 Ok(refund_imbalance) => {1729 // The refund cannot be larger than the up front payed max weight.1730 // `PostDispatchInfo::calc_unspent` guards against such a case.1731 match payed.offset(refund_imbalance) {1732 Ok(actual_payment) => actual_payment,1733 Err(_) => return Err(InvalidTransaction::Payment.into()),1734 }1735 }1736 // We do not recreate the account using the refund. The up front payment1737 // is gone in that case.1738 Err(_) => payed,1739 };1740 let imbalances = actual_payment.split(tip);1741 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1742 Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1743 );1744 }1745 Ok(())1746 }1747}1748// #endregion1#![cfg_attr(not(feature = "std"), no_std)]23#[cfg(feature = "std")]4pub use std::*;56#[cfg(feature = "std")]7pub use serde::*;89use codec::{Decode, Encode};10pub use frame_support::{11 construct_runtime, decl_event, decl_module, decl_storage,12 dispatch::DispatchResult,13 ensure, parameter_types,14 traits::{15 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,16 Randomness, WithdrawReason,17 },18 weights::{19 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},20 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,21 WeightToFeePolynomial,22 },23 IsSubType, StorageValue,24};2526use frame_system::{self as system, ensure_signed, ensure_root};27use sp_runtime::sp_std::prelude::Vec;28use sp_runtime::{29 traits::{30 DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SaturatedConversion, Saturating,31 SignedExtension, Zero,32 },33 transaction_validity::{34 InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,35 ValidTransaction,36 },37 FixedPointOperand, FixedU128,38};3940#[cfg(test)]41mod mock;4243#[cfg(test)]44mod tests;4546// Structs47// #region4849#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]50#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]51pub enum CollectionMode {52 Invalid,53 // custom data size54 NFT(u32),55 // decimal points56 Fungible(u32),57 // custom data size and decimal points58 ReFungible(u32, u32),59}6061impl Into<u8> for CollectionMode {62 fn into(self) -> u8 {63 match self {64 CollectionMode::Invalid => 0,65 CollectionMode::NFT(_) => 1,66 CollectionMode::Fungible(_) => 2,67 CollectionMode::ReFungible(_, _) => 3,68 }69 }70}7172#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]73#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]74pub enum AccessMode {75 Normal,76 WhiteList,77}78impl Default for AccessMode {79 fn default() -> Self {80 Self::Normal81 }82}8384impl Default for CollectionMode {85 fn default() -> Self {86 Self::Invalid87 }88}8990#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]91#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]92pub struct Ownership<AccountId> {93 pub owner: AccountId,94 pub fraction: u128,95}9697#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]98#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]99pub struct CollectionType<AccountId> {100 pub owner: AccountId,101 pub mode: CollectionMode,102 pub access: AccessMode,103 pub decimal_points: u32,104 pub name: Vec<u16>, // 64 include null escape char105 pub description: Vec<u16>, // 256 include null escape char106 pub token_prefix: Vec<u8>, // 16 include null escape char107 pub custom_data_size: u32,108 pub mint_mode: bool,109 pub offchain_schema: Vec<u8>,110 pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender111 pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship112}113114#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]115#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]116pub struct CollectionAdminsType<AccountId> {117 pub admin: AccountId,118 pub collection_id: u64,119}120121#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]122#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]123pub struct NftItemType<AccountId> {124 pub collection: u64,125 pub owner: AccountId,126 pub data: Vec<u8>,127}128129#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]130#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]131pub struct FungibleItemType<AccountId> {132 pub collection: u64,133 pub owner: AccountId,134 pub value: u128,135}136137#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]138#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]139pub struct ReFungibleItemType<AccountId> {140 pub collection: u64,141 pub owner: Vec<Ownership<AccountId>>,142 pub data: Vec<u8>,143}144145#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]146#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]147pub struct ApprovePermissions<AccountId> {148 pub approved: AccountId,149 pub amount: u64,150}151152#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]153#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]154pub struct VestingItem<AccountId, Moment> {155 pub sender: AccountId,156 pub recipient: AccountId,157 pub collection_id: u64,158 pub item_id: u64,159 pub amount: u64,160 pub vesting_date: Moment,161}162163#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]164#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]165pub struct BasketItem<AccountId, BlockNumber> {166 pub address: AccountId,167 pub start_block: BlockNumber,168}169170#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]171#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]172pub struct ChainLimits {173 pub collection_numbers_limit: u64,174 pub account_token_ownership_limit: u64,175 pub collections_admins_limit: u64,176 pub custom_data_limit: u32,177178 // Timeouts for item types in passed blocks179 pub nft_sponsor_transfer_timeout: u32,180 pub fungible_sponsor_transfer_timeout: u32,181 pub refungible_sponsor_transfer_timeout: u32,182}183184pub trait Trait: system::Trait {185 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;186}187188// #endregion189190decl_storage! {191 trait Store for Module<T: Trait> as Nft {192193 // Private members194 NextCollectionID: u64;195 CreatedCollectionCount: u64;196 ChainVersion: u64;197 ItemListIndex: map hasher(blake2_128_concat) u64 => u64;198199 // Chain limits struct200 pub ChainLimit get(fn chain_limit) config(): ChainLimits;201202 // Bound counters203 CollectionCount: u64;204 pub AccountItemCount get(fn account_item_count): map hasher(identity) T::AccountId => u64;205206 // Basic collections207 pub Collection get(fn collection) config(): map hasher(identity) u64 => CollectionType<T::AccountId>;208 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;209 pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;210211 /// Balance owner per collection map212 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;213214 /// second parameter: item id + owner account id215 pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;216217 /// Item collections218 pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;219 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;220 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;221222 /// Index list223 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;224225 /// Tokens transfer baskets226 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => T::BlockNumber;227 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<BasketItem<T::AccountId, T::BlockNumber>>;228 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => T::BlockNumber;229230 // Sponsorship231 pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;232 pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;233 }234 add_extra_genesis {235 build(|config: &GenesisConfig<T>| {236 // Modification of storage237 for (_num, _c) in &config.collection {238 <Module<T>>::init_collection(_c);239 }240241 for (_num, _q, _i) in &config.nft_item_id {242 <Module<T>>::init_nft_token(_i);243 }244245 for (_num, _q, _i) in &config.fungible_item_id {246 <Module<T>>::init_fungible_token(_i);247 }248249 for (_num, _q, _i) in &config.refungible_item_id {250 <Module<T>>::init_refungible_token(_i);251 }252 })253 }254}255256decl_event!(257 pub enum Event<T>258 where259 AccountId = <T as system::Trait>::AccountId,260 {261 /// New collection was created262 /// 263 /// # Arguments264 /// 265 /// * collection_id: Globally unique identifier of newly created collection.266 /// 267 /// * mode: [CollectionMode] converted into u8.268 /// 269 /// * account_id: Collection owner.270 Created(u64, u8, AccountId),271272 /// New item was created.273 /// 274 /// # Arguments275 /// 276 /// * collection_id: Id of the collection where item was created.277 /// 278 /// * item_id: Id of an item. Unique within the collection.279 ItemCreated(u64, u64),280281 /// Collection item was burned.282 /// 283 /// # Arguments284 /// 285 /// collection_id.286 /// 287 /// item_id: Identifier of burned NFT.288 ItemDestroyed(u64, u64),289 }290);291292decl_module! {293 pub struct Module<T: Trait> for enum Call where origin: T::Origin {294295 fn deposit_event() = default;296297 fn on_initialize(now: T::BlockNumber) -> Weight {298299 if ChainVersion::get() < 2300 {301 let value = NextCollectionID::get();302 CreatedCollectionCount::put(value);303 ChainVersion::put(2);304 }305306 0307 }308309 /// This method creates a Collection of NFTs. Each Token may have multiple properties encoded as an array of bytes of certain length. The initial owner and admin of the collection are set to the address that signed the transaction. Both addresses can be changed later.310 /// 311 /// # Permissions312 /// 313 /// * Anyone.314 /// 315 /// # Arguments316 /// 317 /// * collection_name: UTF-16 string with collection name (limit 64 characters), will be stored as zero-terminated.318 /// 319 /// * collection_description: UTF-16 string with collection description (limit 256 characters), will be stored as zero-terminated.320 /// 321 /// * token_prefix: UTF-8 string with token prefix.322 /// 323 /// * mode: [CollectionMode] collection type and type dependent data.324 // returns collection ID325 #[weight = 0]326 pub fn create_collection(origin,327 collection_name: Vec<u16>,328 collection_description: Vec<u16>,329 token_prefix: Vec<u8>,330 mode: CollectionMode) -> DispatchResult {331332 // Anyone can create a collection333 let who = ensure_signed(origin)?;334 let custom_data_size = match mode {335 CollectionMode::NFT(size) => {336337 // bound Custom data size338 ensure!(size < ChainLimit::get().custom_data_limit, "Custom data size bound exceeded");339 size340 },341 CollectionMode::ReFungible(size, _) => {342343 // bound Custom data size344 ensure!(size < ChainLimit::get().custom_data_limit, "Custom data size bound exceeded");345 size346 },347 _ => 0348 };349350 let decimal_points = match mode {351 CollectionMode::Fungible(points) => points,352 CollectionMode::ReFungible(_, points) => points,353 _ => 0354 };355356 // bound Total number of collections357 ensure!(CollectionCount::get() < ChainLimit::get().collection_numbers_limit, "Total collections bound exceeded");358359 // check params360 ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");361362 let mut name = collection_name.to_vec();363 name.push(0);364 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");365366 let mut description = collection_description.to_vec();367 description.push(0);368 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");369370 let mut prefix = token_prefix.to_vec();371 prefix.push(0);372 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");373374 // Generate next collection ID375 let next_id = CreatedCollectionCount::get()376 .checked_add(1)377 .expect("collection id error");378379 // bound counter380 let total = CollectionCount::get()381 .checked_add(1)382 .expect("collection counter error");383384 CreatedCollectionCount::put(next_id);385 CollectionCount::put(total);386387 // Create new collection388 let new_collection = CollectionType {389 owner: who.clone(),390 name: name,391 mode: mode.clone(),392 mint_mode: false,393 access: AccessMode::Normal,394 description: description,395 decimal_points: decimal_points,396 token_prefix: prefix,397 offchain_schema: Vec::new(),398 custom_data_size: custom_data_size,399 sponsor: T::AccountId::default(),400 unconfirmed_sponsor: T::AccountId::default(),401 };402403 // Add new collection to map404 <Collection<T>>::insert(next_id, new_collection);405406 // call event407 Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));408409 Ok(())410 }411412 /// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.413 /// 414 /// # Permissions415 /// 416 /// * Collection Owner.417 /// 418 /// # Arguments419 /// 420 /// * collection_id: collection to destroy.421 #[weight = 0]422 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {423424 let sender = ensure_signed(origin)?;425 Self::check_owner_permissions(collection_id, sender)?;426427 <AddressTokens<T>>::remove_prefix(collection_id);428 <ApprovedList<T>>::remove_prefix(collection_id);429 <Balance<T>>::remove_prefix(collection_id);430 <ItemListIndex>::remove(collection_id);431 <AdminList<T>>::remove(collection_id);432 <Collection<T>>::remove(collection_id);433 <WhiteList<T>>::remove(collection_id);434435 <NftItemList<T>>::remove_prefix(collection_id);436 <FungibleItemList<T>>::remove_prefix(collection_id);437 <ReFungibleItemList<T>>::remove_prefix(collection_id);438439 <NftTransferBasket<T>>::remove_prefix(collection_id);440 <FungibleTransferBasket<T>>::remove_prefix(collection_id);441 <ReFungibleTransferBasket<T>>::remove_prefix(collection_id);442443 if CollectionCount::get() > 0444 {445 // bound couter446 let total = CollectionCount::get()447 .checked_sub(1)448 .expect("collection counter error");449450 CollectionCount::put(total);451 }452453 Ok(())454 }455456 /// Add an address to white list.457 /// 458 /// # Permissions459 /// 460 /// * Collection Owner461 /// * Collection Admin462 /// 463 /// # Arguments464 /// 465 /// * collection_id.466 /// 467 /// * address.468 #[weight = 0]469 pub fn add_to_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{470471 let sender = ensure_signed(origin)?;472 Self::check_owner_or_admin_permissions(collection_id, sender)?;473474 let mut white_list_collection: Vec<T::AccountId>;475 if <WhiteList<T>>::contains_key(collection_id) {476 white_list_collection = <WhiteList<T>>::get(collection_id);477 if !white_list_collection.contains(&address.clone())478 {479 white_list_collection.push(address.clone());480 }481 }482 else {483 white_list_collection = Vec::new();484 white_list_collection.push(address.clone());485 }486487 <WhiteList<T>>::insert(collection_id, white_list_collection);488 Ok(())489 }490491 /// Remove an address from white list.492 /// 493 /// # Permissions494 /// 495 /// * Collection Owner496 /// * Collection Admin497 /// 498 /// # Arguments499 /// 500 /// * collection_id.501 /// 502 /// * address.503 #[weight = 0]504 pub fn remove_from_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{505506 let sender = ensure_signed(origin)?;507 Self::check_owner_or_admin_permissions(collection_id, sender)?;508509 if <WhiteList<T>>::contains_key(collection_id) {510 let mut white_list_collection = <WhiteList<T>>::get(collection_id);511 if white_list_collection.contains(&address.clone())512 {513 white_list_collection.retain(|i| *i != address.clone());514 <WhiteList<T>>::insert(collection_id, white_list_collection);515 }516 }517518 Ok(())519 }520521 /// Toggle between normal and white list access for the methods with access for `Anyone`.522 /// 523 /// # Permissions524 /// 525 /// * Collection Owner.526 /// 527 /// # Arguments528 /// 529 /// * collection_id.530 /// 531 /// * mode: [AccessMode]532 #[weight = 0]533 pub fn set_public_access_mode(origin, collection_id: u64, mode: AccessMode) -> DispatchResult534 {535 let sender = ensure_signed(origin)?;536537 Self::check_owner_permissions(collection_id, sender)?;538 let mut target_collection = <Collection<T>>::get(collection_id);539 target_collection.access = mode;540 <Collection<T>>::insert(collection_id, target_collection);541542 Ok(())543 }544545 /// Allows Anyone to create tokens if:546 /// * White List is enabled, and547 /// * Address is added to white list, and548 /// * This method was called with True parameter549 /// 550 /// # Permissions551 /// * Collection Owner552 ///553 /// # Arguments554 /// 555 /// * collection_id.556 /// 557 /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.558 #[weight = 0]559 pub fn set_mint_permission(origin, collection_id: u64, mint_permission: bool) -> DispatchResult560 {561 let sender = ensure_signed(origin)?;562563 Self::check_owner_permissions(collection_id, sender)?;564 let mut target_collection = <Collection<T>>::get(collection_id);565 target_collection.mint_mode = mint_permission;566 <Collection<T>>::insert(collection_id, target_collection);567568 Ok(())569 }570571 /// Change the owner of the collection.572 /// 573 /// # Permissions574 /// 575 /// * Collection Owner.576 /// 577 /// # Arguments578 /// 579 /// * collection_id.580 /// 581 /// * new_owner.582 #[weight = 0]583 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {584585 let sender = ensure_signed(origin)?;586 Self::check_owner_permissions(collection_id, sender)?;587 let mut target_collection = <Collection<T>>::get(collection_id);588 target_collection.owner = new_owner;589 <Collection<T>>::insert(collection_id, target_collection);590591 Ok(())592 }593594 /// Adds an admin of the Collection.595 /// NFT Collection can be controlled by multiple admin addresses (some which can also be servers, for example). Admins can issue and burn NFTs, as well as add and remove other admins, but cannot change NFT or Collection ownership. 596 /// 597 /// # Permissions598 /// 599 /// * Collection Owner.600 /// * Collection Admin.601 /// 602 /// # Arguments603 /// 604 /// * collection_id: ID of the Collection to add admin for.605 /// 606 /// * new_admin_id: Address of new admin to add.607 #[weight = 0]608 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {609610 let sender = ensure_signed(origin)?;611 Self::check_owner_or_admin_permissions(collection_id, sender)?;612 let mut admin_arr: Vec<T::AccountId> = Vec::new();613614 if <AdminList<T>>::contains_key(collection_id)615 {616 admin_arr = <AdminList<T>>::get(collection_id);617 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");618 }619620 // Number of collection admins621 ensure!((admin_arr.len() as u64) < ChainLimit::get().collections_admins_limit, "Number of collection admins bound exceeded");622623 admin_arr.push(new_admin_id);624 <AdminList<T>>::insert(collection_id, admin_arr);625626 Ok(())627 }628629 /// Remove admin address of the Collection. An admin address can remove itself. List of admins may become empty, in which case only Collection Owner will be able to add an Admin.630 ///631 /// # Permissions632 /// 633 /// * Collection Owner.634 /// * Collection Admin.635 /// 636 /// # Arguments637 /// 638 /// * collection_id: ID of the Collection to remove admin for.639 /// 640 /// * account_id: Address of admin to remove.641 #[weight = 0]642 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {643644 let sender = ensure_signed(origin)?;645 Self::check_owner_or_admin_permissions(collection_id, sender)?;646647 if <AdminList<T>>::contains_key(collection_id)648 {649 let mut admin_arr = <AdminList<T>>::get(collection_id);650 admin_arr.retain(|i| *i != account_id);651 <AdminList<T>>::insert(collection_id, admin_arr);652 }653654 Ok(())655 }656657 /// # Permissions658 /// 659 /// * Collection Owner660 /// 661 /// # Arguments662 /// 663 /// * collection_id.664 /// 665 /// * new_sponsor.666 #[weight = 0]667 pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {668669 let sender = ensure_signed(origin)?;670 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");671672 let mut target_collection = <Collection<T>>::get(collection_id);673 ensure!(sender == target_collection.owner, "You do not own this collection");674675 target_collection.unconfirmed_sponsor = new_sponsor;676 <Collection<T>>::insert(collection_id, target_collection);677678 Ok(())679 }680681 /// # Permissions682 /// 683 /// * Sponsor.684 /// 685 /// # Arguments686 /// 687 /// * collection_id.688 #[weight = 0]689 pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {690691 let sender = ensure_signed(origin)?;692 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");693694 let mut target_collection = <Collection<T>>::get(collection_id);695 ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");696697 target_collection.sponsor = target_collection.unconfirmed_sponsor;698 target_collection.unconfirmed_sponsor = T::AccountId::default();699 <Collection<T>>::insert(collection_id, target_collection);700701 Ok(())702 }703704 /// Switch back to pay-per-own-transaction model.705 ///706 /// # Permissions707 ///708 /// * Collection owner.709 /// 710 /// # Arguments711 /// 712 /// * collection_id.713 #[weight = 0]714 pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {715716 let sender = ensure_signed(origin)?;717 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");718719 let mut target_collection = <Collection<T>>::get(collection_id);720 ensure!(sender == target_collection.owner, "You do not own this collection");721722 target_collection.sponsor = T::AccountId::default();723 <Collection<T>>::insert(collection_id, target_collection);724725 Ok(())726 }727728 /// This method creates a concrete instance of NFT Collection created with CreateCollection method.729 /// 730 /// # Permissions731 /// 732 /// * Collection Owner.733 /// * Collection Admin.734 /// * Anyone if735 /// * White List is enabled, and736 /// * Address is added to white list, and737 /// * MintPermission is enabled (see SetMintPermission method)738 /// 739 /// # Arguments740 /// 741 /// * collection_id: ID of the collection.742 /// 743 /// * properties: Array of bytes that contains NFT properties. Since NFT Module is agnostic of properties meaning, it is treated purely as an array of bytes.744 /// 745 /// * owner: Address, initial owner of the NFT.746 #[weight = 0]747 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {748749 let sender = ensure_signed(origin)?;750 Self::collection_exists(collection_id)?;751 let target_collection = <Collection<T>>::get(collection_id);752753 if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) {754 ensure!(target_collection.mint_mode == true, "Public minting is not allowed for this collection");755 Self::check_white_list(collection_id, &owner)?;756 Self::check_white_list(collection_id, &sender)?;757 }758759 match target_collection.mode760 {761 CollectionMode::NFT(_) => {762763 // check size764 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");765766 // Create nft item767 let item = NftItemType {768 collection: collection_id,769 owner: owner,770 data: properties.clone(),771 };772773 Self::add_nft_item(item)?;774775 },776 CollectionMode::Fungible(_) => {777778 // check size779 ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");780781 let item = FungibleItemType {782 collection: collection_id,783 owner: owner,784 value: (10 as u128).pow(target_collection.decimal_points)785 };786787 Self::add_fungible_item(item)?;788 },789 CollectionMode::ReFungible(_, _) => {790791 // check size792 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");793794 let mut owner_list = Vec::new();795 let value = (10 as u128).pow(target_collection.decimal_points);796 owner_list.push(Ownership {owner: owner.clone(), fraction: value});797798 let item = ReFungibleItemType {799 collection: collection_id,800 owner: owner_list,801 data: properties.clone()802 };803804 Self::add_refungible_item(item)?;805 },806 _ => { ensure!(1 == 0,"just error"); }807808 };809810 // call event811 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));812813 Ok(())814 }815816 /// Destroys a concrete instance of NFT.817 /// 818 /// # Permissions819 /// 820 /// * Collection Owner.821 /// * Collection Admin.822 /// * Current NFT Owner.823 /// 824 /// # Arguments825 /// 826 /// * collection_id: ID of the collection.827 /// 828 /// * item_id: ID of NFT to burn.829 #[weight = 0]830 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {831832 let sender = ensure_signed(origin)?;833 Self::collection_exists(collection_id)?;834835 // Transfer permissions check836 let target_collection = <Collection<T>>::get(collection_id);837 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) ||838 Self::is_owner_or_admin_permissions(collection_id, sender.clone()),839 "Only item owner, collection owner and admins can modify item");840841 if target_collection.access == AccessMode::WhiteList {842 Self::check_white_list(collection_id, &sender)?;843 }844845 match target_collection.mode846 {847 CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,848 CollectionMode::Fungible(_) => Self::burn_fungible_item(collection_id, item_id)?,849 CollectionMode::ReFungible(_, _) => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,850 _ => ()851 };852853 // call event854 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));855856 Ok(())857 }858859 /// Change ownership of the token.860 /// 861 /// # Permissions862 /// 863 /// * Collection Owner864 /// * Collection Admin865 /// * Current NFT owner866 ///867 /// # Arguments868 /// 869 /// * recipient: Address of token recipient.870 /// 871 /// * collection_id.872 /// 873 /// * item_id: ID of the item874 /// * Non-Fungible Mode: Required.875 /// * Fungible Mode: Ignored.876 /// * Re-Fungible Mode: Required.877 /// 878 /// * value: Amount to transfer.879 /// * Non-Fungible Mode: Ignored880 /// * Fungible Mode: Must specify transferred amount881 /// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)882 #[weight = 0]883 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {884885 let sender = ensure_signed(origin)?;886887 // Transfer permissions check888 let target_collection = <Collection<T>>::get(collection_id);889 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) ||890 Self::is_owner_or_admin_permissions(collection_id, sender.clone()),891 "Only item owner, collection owner and admins can modify item");892893 if target_collection.access == AccessMode::WhiteList {894 Self::check_white_list(collection_id, &sender)?;895 Self::check_white_list(collection_id, &recipient)?;896 }897898 match target_collection.mode899 {900 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,901 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,902 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,903 _ => ()904 };905906 Ok(())907 }908909 /// Set, change, or remove approved address to transfer the ownership of the NFT.910 /// 911 /// # Permissions912 /// 913 /// * Collection Owner914 /// * Collection Admin915 /// * Current NFT owner916 /// 917 /// # Arguments918 /// 919 /// * approved: Address that is approved to transfer this NFT or zero (if needed to remove approval).920 /// 921 /// * collection_id.922 /// 923 /// * item_id: ID of the item.924 #[weight = 0]925 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {926927 let sender = ensure_signed(origin)?;928929 // Transfer permissions check930 let target_collection = <Collection<T>>::get(collection_id);931 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) ||932 Self::is_owner_or_admin_permissions(collection_id, sender.clone()),933 "Only item owner, collection owner and admins can approve");934935 if target_collection.access == AccessMode::WhiteList {936 Self::check_white_list(collection_id, &sender)?;937 Self::check_white_list(collection_id, &approved)?;938 }939940 // amount param stub941 let amount = 100000000;942943 let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));944 if list_exists {945946 let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));947 let item_contains = list.iter().any(|i| i.approved == approved);948949 if !item_contains {950 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });951 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);952 }953 } else {954955 let mut list = Vec::new();956 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });957 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);958 }959960 Ok(())961 }962 963 /// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.964 /// 965 /// # Permissions966 /// * Collection Owner967 /// * Collection Admin968 /// * Current NFT owner969 /// * Address approved by current NFT owner970 /// 971 /// # Arguments972 /// 973 /// * from: Address that owns token.974 /// 975 /// * recipient: Address of token recipient.976 /// 977 /// * collection_id.978 /// 979 /// * item_id: ID of the item.980 /// 981 /// * value: Amount to transfer.982 #[weight = 0]983 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {984985 let sender = ensure_signed(origin)?;986 let mut appoved_transfer = false;987988 // Check approve989 if <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone())) {990 let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));991 let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());992 appoved_transfer = opt_item.is_some();993 ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");994 }995996 // Transfer permissions check997 let target_collection = <Collection<T>>::get(collection_id);998 ensure!(appoved_transfer || Self::is_owner_or_admin_permissions(collection_id, sender.clone()),999 "Only item owner, collection owner and admins can modify items");10001001 if target_collection.access == AccessMode::WhiteList {1002 Self::check_white_list(collection_id, &sender)?;1003 Self::check_white_list(collection_id, &recipient)?;1004 }10051006 // remove approve1007 let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))1008 .into_iter().filter(|i| i.approved != sender.clone()).collect();1009 <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);101010111012 match target_collection.mode1013 {1014 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,1015 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,1016 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,1017 _ => ()1018 };10191020 Ok(())1021 }10221023 ///1024 #[weight = 0]1025 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {10261027 // let no_perm_mes = "You do not have permissions to modify this collection";1028 // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);1029 // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));1030 // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);10311032 // // on_nft_received call10331034 // Self::transfer(origin, collection_id, item_id, new_owner)?;10351036 Ok(())1037 }10381039 /// Set off-chain data schema.1040 /// 1041 /// # Permissions1042 /// 1043 /// * Collection Owner1044 /// * Collection Admin1045 /// 1046 /// # Arguments1047 /// 1048 /// * collection_id.1049 /// 1050 /// * schema: String representing the offchain data schema.1051 #[weight = 0]1052 pub fn set_offchain_schema(1053 origin,1054 collection_id: u64,1055 schema: Vec<u8>1056 ) -> DispatchResult {1057 let sender = ensure_signed(origin)?;1058 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;10591060 let mut target_collection = <Collection<T>>::get(collection_id);1061 target_collection.offchain_schema = schema;1062 <Collection<T>>::insert(collection_id, target_collection);10631064 Ok(())1065 }10661067 // Sudo permissions function1068 #[weight = 0]1069 pub fn set_chain_limits(1070 origin,1071 limits: ChainLimits1072 ) -> DispatchResult {1073 ensure_root(origin)?;1074 <ChainLimit>::put(limits);1075 Ok(())1076 } 1077 }1078}10791080impl<T: Trait> Module<T> {1081 fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {1082 let current_index = <ItemListIndex>::get(item.collection)1083 .checked_add(1)1084 .expect("Item list index id error");1085 let itemcopy = item.clone();1086 let owner = item.owner.clone();1087 let value = item.value as u64;10881089 Self::add_token_index(item.collection, current_index, owner.clone())?;10901091 <ItemListIndex>::insert(item.collection, current_index);1092 <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);10931094 // Add current block1095 let v: Vec<BasketItem<T::AccountId, T::BlockNumber>> = Vec::new();1096 <FungibleTransferBasket<T>>::insert(item.collection, current_index, v);1097 1098 // Update balance1099 let new_balance = <Balance<T>>::get(item.collection, owner.clone())1100 .checked_add(value)1101 .unwrap();1102 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);11031104 Ok(())1105 }11061107 fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {1108 let current_index = <ItemListIndex>::get(item.collection)1109 .checked_add(1)1110 .expect("Item list index id error");1111 let itemcopy = item.clone();11121113 let value = item.owner.first().unwrap().fraction as u64;1114 let owner = item.owner.first().unwrap().owner.clone();11151116 Self::add_token_index(item.collection, current_index, owner.clone())?;11171118 <ItemListIndex>::insert(item.collection, current_index);1119 <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);11201121 // Add current block1122 let block_number: T::BlockNumber = 0.into();1123 <ReFungibleTransferBasket<T>>::insert(item.collection, current_index, block_number);11241125 // Update balance1126 let new_balance = <Balance<T>>::get(item.collection, owner.clone())1127 .checked_add(value)1128 .unwrap();1129 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);11301131 Ok(())1132 }11331134 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {1135 let current_index = <ItemListIndex>::get(item.collection)1136 .checked_add(1)1137 .expect("Item list index id error");11381139 let item_owner = item.owner.clone();1140 let collection_id = item.collection.clone();1141 Self::add_token_index(collection_id, current_index, item.owner.clone())?;11421143 <ItemListIndex>::insert(collection_id, current_index);1144 <NftItemList<T>>::insert(collection_id, current_index, item);11451146 // Add current block1147 let block_number: T::BlockNumber = 0.into();1148 <NftTransferBasket<T>>::insert(collection_id, current_index, block_number);11491150 // Update balance1151 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())1152 .checked_add(1)1153 .unwrap();1154 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);11551156 Ok(())1157 }11581159 fn burn_refungible_item(1160 collection_id: u64,1161 item_id: u64,1162 owner: T::AccountId,1163 ) -> DispatchResult {1164 ensure!(1165 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1166 "Item does not exists"1167 );1168 let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);1169 let item = collection1170 .owner1171 .iter()1172 .filter(|&i| i.owner == owner)1173 .next()1174 .unwrap();1175 Self::remove_token_index(collection_id, item_id, owner.clone())?;11761177 // remove approve list1178 <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));11791180 // update balance1181 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())1182 .checked_sub(item.fraction as u64)1183 .unwrap();1184 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);11851186 <ReFungibleItemList<T>>::remove(collection_id, item_id);11871188 Ok(())1189 }11901191 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {1192 ensure!(1193 <NftItemList<T>>::contains_key(collection_id, item_id),1194 "Item does not exists"1195 );1196 let item = <NftItemList<T>>::get(collection_id, item_id);1197 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;11981199 // remove approve list1200 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));12011202 // update balance1203 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())1204 .checked_sub(1)1205 .unwrap();1206 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);1207 <NftItemList<T>>::remove(collection_id, item_id);12081209 Ok(())1210 }12111212 fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {1213 ensure!(1214 <FungibleItemList<T>>::contains_key(collection_id, item_id),1215 "Item does not exists"1216 );1217 let item = <FungibleItemList<T>>::get(collection_id, item_id);1218 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;12191220 // remove approve list1221 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));12221223 // update balance1224 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())1225 .checked_sub(item.value as u64)1226 .unwrap();1227 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);12281229 <FungibleItemList<T>>::remove(collection_id, item_id);12301231 Ok(())1232 }12331234 fn collection_exists(collection_id: u64) -> DispatchResult {1235 ensure!(1236 <Collection<T>>::contains_key(collection_id),1237 "This collection does not exist"1238 );1239 Ok(())1240 }12411242 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {1243 Self::collection_exists(collection_id)?;12441245 let target_collection = <Collection<T>>::get(collection_id);1246 ensure!(1247 subject == target_collection.owner,1248 "You do not own this collection"1249 );12501251 Ok(())1252 }12531254 fn is_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> bool {1255 let target_collection = <Collection<T>>::get(collection_id);1256 let mut result: bool = subject == target_collection.owner;1257 let exists = <AdminList<T>>::contains_key(collection_id);12581259 if !result & exists {1260 if <AdminList<T>>::get(collection_id).contains(&subject) {1261 result = true1262 }1263 }12641265 result1266 }12671268 fn check_owner_or_admin_permissions(1269 collection_id: u64,1270 subject: T::AccountId,1271 ) -> DispatchResult {1272 Self::collection_exists(collection_id)?;1273 let result = Self::is_owner_or_admin_permissions(collection_id, subject.clone());12741275 ensure!(1276 result,1277 "You do not have permissions to modify this collection"1278 );1279 Ok(())1280 }12811282 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {1283 let target_collection = <Collection<T>>::get(collection_id);12841285 match target_collection.mode {1286 CollectionMode::NFT(_) => {1287 <NftItemList<T>>::get(collection_id, item_id).owner == subject1288 }1289 CollectionMode::Fungible(_) => {1290 <FungibleItemList<T>>::get(collection_id, item_id).owner == subject1291 }1292 CollectionMode::ReFungible(_, _) => {1293 <ReFungibleItemList<T>>::get(collection_id, item_id)1294 .owner1295 .iter()1296 .any(|i| i.owner == subject)1297 }1298 CollectionMode::Invalid => false,1299 }1300 }13011302 fn check_white_list(collection_id: u64, address: &T::AccountId) -> DispatchResult {1303 let mes = "Address is not in white list";1304 ensure!(<WhiteList<T>>::contains_key(collection_id), mes);1305 let wl = <WhiteList<T>>::get(collection_id);1306 ensure!(wl.contains(address), mes);13071308 Ok(())1309 }13101311 fn transfer_fungible(1312 collection_id: u64,1313 item_id: u64,1314 value: u64,1315 owner: T::AccountId,1316 new_owner: T::AccountId,1317 ) -> DispatchResult {1318 ensure!(1319 <FungibleItemList<T>>::contains_key(collection_id, item_id),1320 "Item not exists"1321 );13221323 let full_item = <FungibleItemList<T>>::get(collection_id, item_id);1324 let amount = full_item.value;13251326 ensure!(amount >= value.into(), "Item balance not enouth");13271328 // update balance1329 let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())1330 .checked_sub(value)1331 .unwrap();1332 <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);13331334 let mut new_owner_account_id = 0;1335 let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());1336 if new_owner_items.len() > 0 {1337 new_owner_account_id = new_owner_items[0];1338 }13391340 let val64 = value.into();13411342 // transfer1343 if amount == val64 && new_owner_account_id == 0 {1344 // change owner1345 // new owner do not have account1346 let mut new_full_item = full_item.clone();1347 new_full_item.owner = new_owner.clone();1348 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);13491350 // update balance1351 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1352 .checked_add(value)1353 .unwrap();1354 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);13551356 // update index collection1357 Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;1358 } else {1359 let mut new_full_item = full_item.clone();1360 new_full_item.value -= val64;13611362 // separate amount1363 if new_owner_account_id > 0 {1364 // new owner has account1365 let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);1366 item.value += val64;13671368 // update balance1369 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1370 .checked_add(value)1371 .unwrap();1372 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);13731374 <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);1375 } else {1376 // new owner do not have account1377 let item = FungibleItemType {1378 collection: collection_id,1379 owner: new_owner.clone(),1380 value: val64,1381 };13821383 Self::add_fungible_item(item)?;1384 }13851386 if amount == val64 {1387 Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;13881389 // remove approve list1390 <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));1391 <FungibleItemList<T>>::remove(collection_id, item_id);1392 }13931394 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1395 }13961397 Ok(())1398 }13991400 fn transfer_refungible(1401 collection_id: u64,1402 item_id: u64,1403 value: u64,1404 owner: T::AccountId,1405 new_owner: T::AccountId,1406 ) -> DispatchResult {1407 ensure!(1408 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1409 "Item not exists"1410 );14111412 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);1413 let item = full_item1414 .owner1415 .iter()1416 .filter(|i| i.owner == owner)1417 .next()1418 .unwrap();1419 let amount = item.fraction;14201421 ensure!(amount >= value.into(), "Item balance not enouth");14221423 // update balance1424 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1425 .checked_sub(value)1426 .unwrap();1427 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);14281429 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1430 .checked_add(value)1431 .unwrap();1432 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);14331434 let old_owner = item.owner.clone();1435 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);1436 let val64 = value.into();14371438 // transfer1439 if amount == val64 && !new_owner_has_account {1440 // change owner1441 // new owner do not have account1442 let mut new_full_item = full_item.clone();1443 new_full_item1444 .owner1445 .iter_mut()1446 .find(|i| i.owner == owner)1447 .unwrap()1448 .owner = new_owner.clone();1449 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);14501451 // update index collection1452 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;1453 } else {1454 let mut new_full_item = full_item.clone();1455 new_full_item1456 .owner1457 .iter_mut()1458 .find(|i| i.owner == owner)1459 .unwrap()1460 .fraction -= val64;14611462 // separate amount1463 if new_owner_has_account {1464 // new owner has account1465 new_full_item1466 .owner1467 .iter_mut()1468 .find(|i| i.owner == new_owner)1469 .unwrap()1470 .fraction += val64;1471 } else {1472 // new owner do not have account1473 new_full_item.owner.push(Ownership {1474 owner: new_owner.clone(),1475 fraction: val64,1476 });1477 Self::add_token_index(collection_id, item_id, new_owner.clone())?;1478 }14791480 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1481 }14821483 Ok(())1484 }14851486 fn transfer_nft(1487 collection_id: u64,1488 item_id: u64,1489 sender: T::AccountId,1490 new_owner: T::AccountId,1491 ) -> DispatchResult {1492 ensure!(1493 <NftItemList<T>>::contains_key(collection_id, item_id),1494 "Item not exists"1495 );14961497 let mut item = <NftItemList<T>>::get(collection_id, item_id);14981499 ensure!(1500 sender == item.owner,1501 "sender parameter and item owner must be equal"1502 );15031504 // update balance1505 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1506 .checked_sub(1)1507 .unwrap();1508 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);15091510 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1511 .checked_add(1)1512 .unwrap();1513 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);15141515 // change owner1516 let old_owner = item.owner.clone();1517 item.owner = new_owner.clone();1518 <NftItemList<T>>::insert(collection_id, item_id, item);15191520 // update index collection1521 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;15221523 // reset approved list1524 <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1525 Ok(())1526 }15271528 fn init_collection(item: &CollectionType<T::AccountId>) {1529 // check params1530 assert!(1531 item.decimal_points <= 4,1532 "decimal_points parameter must be lower than 4"1533 );1534 assert!(1535 item.name.len() <= 64,1536 "Collection name can not be longer than 63 char"1537 );1538 assert!(1539 item.name.len() <= 256,1540 "Collection description can not be longer than 255 char"1541 );1542 assert!(1543 item.token_prefix.len() <= 16,1544 "Token prefix can not be longer than 15 char"1545 );15461547 // Generate next collection ID1548 let next_id = CreatedCollectionCount::get()1549 .checked_add(1)1550 .expect("collection id error");15511552 CreatedCollectionCount::put(next_id);1553 }15541555 fn init_nft_token(item: &NftItemType<T::AccountId>) {1556 let current_index = <ItemListIndex>::get(item.collection)1557 .checked_add(1)1558 .expect("Item list index id error");15591560 let item_owner = item.owner.clone();1561 let collection_id = item.collection.clone();1562 Self::add_token_index(collection_id, current_index, item.owner.clone()).unwrap();15631564 <ItemListIndex>::insert(collection_id, current_index);15651566 // Update balance1567 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())1568 .checked_add(1)1569 .unwrap();1570 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);1571 }15721573 fn init_fungible_token(item: &FungibleItemType<T::AccountId>) {1574 let current_index = <ItemListIndex>::get(item.collection)1575 .checked_add(1)1576 .expect("Item list index id error");1577 let owner = item.owner.clone();1578 let value = item.value as u64;15791580 Self::add_token_index(item.collection, current_index, owner.clone()).unwrap();15811582 <ItemListIndex>::insert(item.collection, current_index);15831584 // Update balance1585 let new_balance = <Balance<T>>::get(item.collection, owner.clone())1586 .checked_add(value)1587 .unwrap();1588 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);1589 }15901591 fn init_refungible_token(item: &ReFungibleItemType<T::AccountId>) {1592 let current_index = <ItemListIndex>::get(item.collection)1593 .checked_add(1)1594 .expect("Item list index id error");15951596 let value = item.owner.first().unwrap().fraction as u64;1597 let owner = item.owner.first().unwrap().owner.clone();15981599 Self::add_token_index(item.collection, current_index, owner.clone()).unwrap();16001601 <ItemListIndex>::insert(item.collection, current_index);16021603 // Update balance1604 let new_balance = <Balance<T>>::get(item.collection, owner.clone())1605 .checked_add(value)1606 .unwrap();1607 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);1608 }16091610 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {16111612 // add to account limit1613 if <AccountItemCount<T>>::contains_key(owner.clone()) {16141615 // bound Owned tokens by a single address1616 let count = <AccountItemCount<T>>::get(owner.clone());1617 ensure!(count < ChainLimit::get().account_token_ownership_limit, "Owned tokens by a single address bound exceeded");16181619 <AccountItemCount<T>>::insert(owner.clone(), 1620 count.checked_add(1).unwrap());1621 }1622 else {1623 <AccountItemCount<T>>::insert(owner.clone(), 1);1624 }16251626 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1627 if list_exists {1628 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1629 let item_contains = list.contains(&item_index.clone());16301631 if !item_contains {1632 list.push(item_index.clone());1633 }16341635 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1636 } else {1637 let mut itm = Vec::new();1638 itm.push(item_index.clone());1639 <AddressTokens<T>>::insert(collection_id, owner, itm);1640 1641 }16421643 Ok(())1644 }16451646 fn remove_token_index(1647 collection_id: u64,1648 item_index: u64,1649 owner: T::AccountId,1650 ) -> DispatchResult {16511652 // update counter1653 <AccountItemCount<T>>::insert(owner.clone(), 1654 <AccountItemCount<T>>::get(owner.clone()).checked_sub(1).unwrap());165516561657 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1658 if list_exists {1659 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1660 let item_contains = list.contains(&item_index.clone());16611662 if item_contains {1663 list.retain(|&item| item != item_index);1664 <AddressTokens<T>>::insert(collection_id, owner, list);1665 }1666 }16671668 Ok(())1669 }16701671 fn move_token_index(1672 collection_id: u64,1673 item_index: u64,1674 old_owner: T::AccountId,1675 new_owner: T::AccountId,1676 ) -> DispatchResult {1677 Self::remove_token_index(collection_id, item_index, old_owner)?;1678 Self::add_token_index(collection_id, item_index, new_owner)?;16791680 Ok(())1681 }1682}16831684////////////////////////////////////////////////////////////////////////////////////////////////////1685// Economic models1686// #region16871688/// Fee multiplier.1689pub type Multiplier = FixedU128;16901691type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1692 <T as system::Trait>::AccountId,1693>>::Balance;1694type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1695 <T as system::Trait>::AccountId,1696>>::NegativeImbalance;16971698/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1699/// in the queue.1700#[derive(Encode, Decode, Clone, Eq, PartialEq)]1701pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1702 #[codec(compact)] BalanceOf<T>,1703);17041705impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1706 for ChargeTransactionPayment<T>1707{1708 #[cfg(feature = "std")]1709 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1710 write!(f, "ChargeTransactionPayment<{:?}>", self.0)1711 }1712 #[cfg(not(feature = "std"))]1713 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1714 Ok(())1715 }1716}17171718impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1719where1720 T::Call:1721 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1722 BalanceOf<T>: Send + Sync + FixedPointOperand,1723{1724 /// utility constructor. Used only in client/factory code.1725 pub fn from(fee: BalanceOf<T>) -> Self {1726 Self(fee)1727 }17281729 pub fn traditional_fee(1730 len: usize,1731 info: &DispatchInfoOf<T::Call>,1732 tip: BalanceOf<T>,1733 ) -> BalanceOf<T>1734 where1735 T::Call: Dispatchable<Info = DispatchInfo>,1736 {1737 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1738 }17391740 fn withdraw_fee(1741 &self,1742 who: &T::AccountId,1743 call: &T::Call,1744 info: &DispatchInfoOf<T::Call>,1745 len: usize,1746 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1747 let tip = self.0;17481749 // Set fee based on call type. Creating collection costs 1 Unique.1750 // All other transactions have traditional fees so far1751 let fee = match call.is_sub_type() {1752 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1753 _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1754 // _ => <BalanceOf<T>>::from(100)1755 };17561757 // Determine who is paying transaction fee based on ecnomic model1758 // Parse call to extract collection ID and access collection sponsor1759 let sponsor: T::AccountId = match call.is_sub_type() {1760 Some(Call::create_item(collection_id, _properties, _owner)) => {1761 <Collection<T>>::get(collection_id).sponsor1762 }1763 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1764 let _collection_mode = <Collection<T>>::get(collection_id).mode;17651766 // sponsor timeout1767 let sponsor_transfer = match _collection_mode {1768 CollectionMode::NFT(_) => {1769 let basket = <NftTransferBasket<T>>::get(collection_id, _item_id);1770 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;1771 let limit_time = basket + ChainLimit::get().nft_sponsor_transfer_timeout.into();1772 if block_number >= limit_time {1773 <NftTransferBasket<T>>::insert(collection_id, _item_id, block_number);1774 true1775 }1776 else {1777 false1778 }1779 }1780 CollectionMode::Fungible(_) => {1781 let mut basket = <FungibleTransferBasket<T>>::get(collection_id, _item_id);1782 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;1783 if basket.iter().any(|i| i.address == _new_owner.clone())1784 {1785 let item = basket.iter_mut().find(|i| i.address == _new_owner.clone()).unwrap().clone();1786 let limit_time = item.start_block + ChainLimit::get().fungible_sponsor_transfer_timeout.into();1787 if block_number >= limit_time {1788 basket.retain(|x| x.address == item.address);1789 basket.push(BasketItem { start_block: block_number, address: _new_owner.clone() });1790 <FungibleTransferBasket<T>>::insert(collection_id, _item_id, basket);1791 true1792 }1793 else {1794 false1795 }1796 }1797 else {1798 basket.push(BasketItem { start_block: block_number, address: _new_owner.clone()});1799 true1800 }1801 }1802 CollectionMode::ReFungible(_, _) => {1803 let basket = <ReFungibleTransferBasket<T>>::get(collection_id, _item_id);1804 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;1805 let limit_time = basket + ChainLimit::get().nft_sponsor_transfer_timeout.into();1806 if block_number >= limit_time {1807 <ReFungibleTransferBasket<T>>::insert(collection_id, _item_id, block_number);1808 true1809 } else {1810 false1811 }1812 }1813 _ => {1814 false1815 },1816 };18171818 if !sponsor_transfer {1819 T::AccountId::default()1820 } else {1821 <Collection<T>>::get(collection_id).sponsor1822 }1823 }18241825 _ => T::AccountId::default(),1826 };18271828 let mut who_pays_fee: T::AccountId = sponsor.clone();1829 if sponsor == T::AccountId::default() {1830 who_pays_fee = who.clone();1831 }18321833 // Only mess with balances if fee is not zero.1834 if fee.is_zero() {1835 return Ok((fee, None));1836 }18371838 match <T as transaction_payment::Trait>::Currency::withdraw(1839 &who_pays_fee,1840 fee,1841 if tip.is_zero() {1842 WithdrawReason::TransactionPayment.into()1843 } else {1844 WithdrawReason::TransactionPayment | WithdrawReason::Tip1845 },1846 ExistenceRequirement::KeepAlive,1847 ) {1848 Ok(imbalance) => Ok((fee, Some(imbalance))),1849 Err(_) => Err(InvalidTransaction::Payment.into()),1850 }1851 }1852}18531854impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1855 for ChargeTransactionPayment<T>1856where1857 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1858 T::Call:1859 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1860{1861 const IDENTIFIER: &'static str = "ChargeTransactionPayment";1862 type AccountId = T::AccountId;1863 type Call = T::Call;1864 type AdditionalSigned = ();1865 type Pre = (1866 BalanceOf<T>,1867 Self::AccountId,1868 Option<NegativeImbalanceOf<T>>,1869 BalanceOf<T>,1870 );1871 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1872 Ok(())1873 }18741875 fn validate(1876 &self,1877 who: &Self::AccountId,1878 call: &Self::Call,1879 info: &DispatchInfoOf<Self::Call>,1880 len: usize,1881 ) -> TransactionValidity {1882 let (fee, _) = self.withdraw_fee(who, call, info, len)?;18831884 let mut r = ValidTransaction::default();1885 // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1886 // will be a bit more than setting the priority to tip. For now, this is enough.1887 r.priority = fee.saturated_into::<TransactionPriority>();1888 Ok(r)1889 }18901891 fn pre_dispatch(1892 self,1893 who: &Self::AccountId,1894 call: &Self::Call,1895 info: &DispatchInfoOf<Self::Call>,1896 len: usize,1897 ) -> Result<Self::Pre, TransactionValidityError> {1898 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1899 Ok((self.0, who.clone(), imbalance, fee))1900 }19011902 fn post_dispatch(1903 pre: Self::Pre,1904 info: &DispatchInfoOf<Self::Call>,1905 post_info: &PostDispatchInfoOf<Self::Call>,1906 len: usize,1907 _result: &DispatchResult,1908 ) -> Result<(), TransactionValidityError> {1909 let (tip, who, imbalance, fee) = pre;1910 if let Some(payed) = imbalance {1911 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1912 len as u32, info, post_info, tip,1913 );1914 let refund = fee.saturating_sub(actual_fee);1915 let actual_payment =1916 match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1917 &who, refund,1918 ) {1919 Ok(refund_imbalance) => {1920 // The refund cannot be larger than the up front payed max weight.1921 // `PostDispatchInfo::calc_unspent` guards against such a case.1922 match payed.offset(refund_imbalance) {1923 Ok(actual_payment) => actual_payment,1924 Err(_) => return Err(InvalidTransaction::Payment.into()),1925 }1926 }1927 // We do not recreate the account using the refund. The up front payment1928 // is gone in that case.1929 Err(_) => payed,1930 };1931 let imbalances = actual_payment.split(tip);1932 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1933 Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1934 );1935 }1936 Ok(())1937 }1938}1939// #endregionpallets/nft/src/mock.rsdiffbeforeafterboth--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -65,6 +65,7 @@
}
pub type TemplateModule = Module<Test>;
+
// This function basically just builds a genesis storage key/value store according to
// our desired mockup.
pub fn new_test_ext() -> sp_io::TestExternalities {
pallets/nft/src/tests.rsdiffbeforeafterboth--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -1,7 +1,8 @@
// Tests to be written here
use crate::mock::*;
-use crate::{ApprovePermissions, CollectionMode, AccessMode, Ownership};
+use crate::{AccessMode, ApprovePermissions, CollectionMode, Ownership, ChainLimits};
use frame_support::{assert_noop, assert_ok};
+use frame_system::{ RawOrigin };
// Use cases tests region
// #region
@@ -13,6 +14,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -41,6 +52,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::ReFungible(2000, 3);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -79,6 +100,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::Fungible(3);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -109,6 +140,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::Fungible(3);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
@@ -167,6 +208,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::ReFungible(2000, 3);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
@@ -264,6 +315,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -302,6 +363,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
@@ -323,8 +394,16 @@
assert_eq!(TemplateModule::balance_count(1, 1), 1);
assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ true
+ ));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
@@ -362,6 +441,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::ReFungible(2000, 3);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
@@ -393,8 +482,16 @@
assert_eq!(TemplateModule::balance_count(1, 1), 1000);
assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ true
+ ));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
@@ -444,6 +541,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::Fungible(3);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
@@ -465,8 +572,16 @@
assert_eq!(TemplateModule::balance_count(1, 1), 1000);
assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ true
+ ));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
@@ -532,6 +647,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -557,6 +682,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -577,6 +712,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -617,6 +762,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::Fungible(3);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -655,6 +810,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::ReFungible(200, 3);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
@@ -664,9 +829,17 @@
token_prefix1.clone(),
mode
));
-
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ true
+ ));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
@@ -704,6 +877,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
let origin3 = Origin::signed(3);
@@ -754,6 +937,16 @@
let origin2 = Origin::signed(2);
let origin3 = Origin::signed(3);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -809,6 +1002,16 @@
let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -881,6 +1084,16 @@
let nft_mode: CollectionMode = CollectionMode::NFT(2000);
let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -915,6 +1128,16 @@
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -937,8 +1160,16 @@
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
assert_eq!(TemplateModule::approved(1, (1, 1))[0].approved, 2);
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ true
+ ));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
@@ -972,6 +1203,16 @@
let mode: CollectionMode = CollectionMode::NFT(2000);
let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -995,6 +1236,16 @@
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -1019,6 +1270,16 @@
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -1027,16 +1288,32 @@
mode
));
- assert_noop!(TemplateModule::add_to_white_list(origin2.clone(), 1, 3), "You do not have permissions to modify this collection");
+ assert_noop!(
+ TemplateModule::add_to_white_list(origin2.clone(), 1, 3),
+ "You do not have permissions to modify this collection"
+ );
});
}
#[test]
fn nobody_can_add_address_to_white_list_of_nonexisting_collection() {
new_test_ext().execute_with(|| {
+ let origin1 = Origin::signed(1);
+
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
- let origin1 = Origin::signed(1);
- assert_noop!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2), "This collection does not exist");
+ assert_noop!(
+ TemplateModule::add_to_white_list(origin1.clone(), 1, 2),
+ "This collection does not exist"
+ );
});
}
@@ -1049,6 +1326,16 @@
let mode: CollectionMode = CollectionMode::NFT(2000);
let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -1058,7 +1345,10 @@
));
assert_ok!(TemplateModule::destroy_collection(origin1.clone(), 1));
- assert_noop!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2), "This collection does not exist");
+ assert_noop!(
+ TemplateModule::add_to_white_list(origin1.clone(), 1, 2),
+ "This collection does not exist"
+ );
});
}
@@ -1066,13 +1356,22 @@
#[test]
fn address_is_already_added_to_white_list() {
new_test_ext().execute_with(|| {
-
let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -1091,13 +1390,22 @@
#[test]
fn owner_can_remove_address_from_white_list() {
new_test_ext().execute_with(|| {
-
let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -1107,7 +1415,11 @@
));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
- assert_ok!(TemplateModule::remove_from_white_list(origin1.clone(), 1, 2));
+ assert_ok!(TemplateModule::remove_from_white_list(
+ origin1.clone(),
+ 1,
+ 2
+ ));
assert_eq!(TemplateModule::white_list(1).len(), 0);
});
}
@@ -1115,7 +1427,6 @@
#[test]
fn admin_can_remove_address_from_white_list() {
new_test_ext().execute_with(|| {
-
let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
@@ -1123,6 +1434,16 @@
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -1134,7 +1455,11 @@
assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
- assert_ok!(TemplateModule::remove_from_white_list(origin2.clone(), 1, 3));
+ assert_ok!(TemplateModule::remove_from_white_list(
+ origin2.clone(),
+ 1,
+ 3
+ ));
assert_eq!(TemplateModule::white_list(1).len(), 0);
});
}
@@ -1142,7 +1467,6 @@
#[test]
fn nonprivileged_user_cannot_remove_address_from_white_list() {
new_test_ext().execute_with(|| {
-
let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
@@ -1150,6 +1474,16 @@
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -1159,7 +1493,10 @@
));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
- assert_noop!(TemplateModule::remove_from_white_list(origin2.clone(), 1, 2), "You do not have permissions to modify this collection");
+ assert_noop!(
+ TemplateModule::remove_from_white_list(origin2.clone(), 1, 2),
+ "You do not have permissions to modify this collection"
+ );
assert_eq!(TemplateModule::white_list(1)[0], 2);
});
}
@@ -1167,16 +1504,28 @@
#[test]
fn nobody_can_remove_address_from_white_list_of_nonexisting_collection() {
new_test_ext().execute_with(|| {
+ let origin1 = Origin::signed(1);
+
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
- let origin1 = Origin::signed(1);
- assert_noop!(TemplateModule::remove_from_white_list(origin1.clone(), 1, 2), "This collection does not exist");
+ assert_noop!(
+ TemplateModule::remove_from_white_list(origin1.clone(), 1, 2),
+ "This collection does not exist"
+ );
});
}
#[test]
fn nobody_can_remove_address_from_white_list_of_deleted_collection() {
new_test_ext().execute_with(|| {
-
let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
@@ -1184,6 +1533,16 @@
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -1194,7 +1553,10 @@
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
assert_ok!(TemplateModule::destroy_collection(origin1.clone(), 1));
- assert_noop!(TemplateModule::remove_from_white_list(origin2.clone(), 1, 2), "This collection does not exist");
+ assert_noop!(
+ TemplateModule::remove_from_white_list(origin2.clone(), 1, 2),
+ "This collection does not exist"
+ );
assert_eq!(TemplateModule::white_list(1).len(), 0);
});
}
@@ -1209,6 +1571,16 @@
let mode: CollectionMode = CollectionMode::NFT(2000);
let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -1218,8 +1590,16 @@
));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
- assert_ok!(TemplateModule::remove_from_white_list(origin1.clone(), 1, 2));
- assert_ok!(TemplateModule::remove_from_white_list(origin1.clone(), 1, 2));
+ assert_ok!(TemplateModule::remove_from_white_list(
+ origin1.clone(),
+ 1,
+ 2
+ ));
+ assert_ok!(TemplateModule::remove_from_white_list(
+ origin1.clone(),
+ 1,
+ 2
+ ));
assert_eq!(TemplateModule::white_list(1).len(), 0);
});
}
@@ -1233,6 +1613,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -1250,16 +1640,17 @@
1
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
- assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
-
- assert_noop!(TemplateModule::transfer(
+ assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
- 3,
1,
- 1,
- 1
- ), "Address is not in white list");
+ AccessMode::WhiteList
+ ));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+
+ assert_noop!(
+ TemplateModule::transfer(origin1.clone(), 3, 1, 1, 1),
+ "Address is not in white list"
+ );
});
}
@@ -1271,6 +1662,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -1288,24 +1689,28 @@
1
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
// do approve
assert_ok!(TemplateModule::approve(origin1.clone(), 1, 1, 1));
assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
-
- assert_ok!(TemplateModule::remove_from_white_list(origin1.clone(), 1, 1));
- assert_noop!(TemplateModule::transfer_from(
+ assert_ok!(TemplateModule::remove_from_white_list(
origin1.clone(),
- 1,
- 3,
1,
- 1,
1
- ), "Address is not in white list");
+ ));
+
+ assert_noop!(
+ TemplateModule::transfer_from(origin1.clone(), 1, 3, 1, 1, 1),
+ "Address is not in white list"
+ );
});
}
@@ -1318,6 +1723,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -1335,16 +1750,17 @@
1
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
- assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
-
- assert_noop!(TemplateModule::transfer(
+ assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
- 3,
1,
- 1,
- 1
- ), "Address is not in white list");
+ AccessMode::WhiteList
+ ));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+
+ assert_noop!(
+ TemplateModule::transfer(origin1.clone(), 3, 1, 1, 1),
+ "Address is not in white list"
+ );
});
}
@@ -1356,6 +1772,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -1373,7 +1799,11 @@
1
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
@@ -1381,16 +1811,16 @@
assert_ok!(TemplateModule::approve(origin1.clone(), 1, 1, 1));
assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
- assert_ok!(TemplateModule::remove_from_white_list(origin1.clone(), 1, 2));
-
- assert_noop!(TemplateModule::transfer_from(
+ assert_ok!(TemplateModule::remove_from_white_list(
origin1.clone(),
- 1,
- 3,
1,
- 1,
- 1
- ), "Address is not in white list");
+ 2
+ ));
+
+ assert_noop!(
+ TemplateModule::transfer_from(origin1.clone(), 1, 3, 1, 1, 1),
+ "Address is not in white list"
+ );
});
}
@@ -1403,6 +1833,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -1420,8 +1860,15 @@
1
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
- assert_noop!(TemplateModule::burn_item(origin1.clone(), 1, 1), "Address is not in white list");
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
+ assert_noop!(
+ TemplateModule::burn_item(origin1.clone(), 1, 1),
+ "Address is not in white list"
+ );
});
}
@@ -1434,6 +1881,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -1442,10 +1899,17 @@
token_prefix1.clone(),
mode
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
// do approve
- assert_noop!(TemplateModule::approve(origin1.clone(), 1, 1, 1), "Address is not in white list");
+ assert_noop!(
+ TemplateModule::approve(origin1.clone(), 1, 1, 1),
+ "Address is not in white list"
+ );
});
}
@@ -1459,6 +1923,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -1476,17 +1950,15 @@
1
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
- assert_ok!(TemplateModule::transfer(
- origin1.clone(),
- 2,
- 1,
- 1,
- 1
- ));
+ assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1));
});
}
@@ -1498,6 +1970,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -1515,7 +1997,11 @@
1
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
@@ -1543,6 +2029,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -1552,8 +2048,16 @@
mode
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, false));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ false
+ ));
assert_ok!(TemplateModule::create_item(
origin1.clone(),
@@ -1573,6 +2077,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
@@ -1583,8 +2097,16 @@
mode
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, false));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ false
+ ));
assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
@@ -1606,6 +2128,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
@@ -1616,16 +2148,22 @@
mode
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, false));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ false
+ ));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
- assert_noop!(TemplateModule::create_item(
- origin2.clone(),
- 1,
- [1, 2, 3].to_vec(),
- 2
- ), "Collection is not in mint mode");
+ assert_noop!(
+ TemplateModule::create_item(origin2.clone(), 1, [1, 2, 3].to_vec(), 2),
+ "Collection is not in mint mode"
+ );
});
}
@@ -1638,6 +2176,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
@@ -1648,15 +2196,21 @@
mode
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, false));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ false
+ ));
- assert_noop!(TemplateModule::create_item(
- origin2.clone(),
- 1,
- [1, 2, 3].to_vec(),
- 2
- ), "Collection is not in mint mode");
+ assert_noop!(
+ TemplateModule::create_item(origin2.clone(), 1, [1, 2, 3].to_vec(), 2),
+ "Collection is not in mint mode"
+ );
});
}
@@ -1669,6 +2223,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
@@ -1678,8 +2242,16 @@
mode
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ true
+ ));
assert_ok!(TemplateModule::create_item(
origin1.clone(),
@@ -1699,6 +2271,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
@@ -1709,8 +2291,16 @@
mode
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ true
+ ));
assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
@@ -1732,6 +2322,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
@@ -1742,15 +2342,21 @@
mode
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ true
+ ));
- assert_noop!(TemplateModule::create_item(
- origin2.clone(),
- 1,
- [1, 2, 3].to_vec(),
- 2
- ), "Address is not in white list");
+ assert_noop!(
+ TemplateModule::create_item(origin2.clone(), 1, [1, 2, 3].to_vec(), 2),
+ "Address is not in white list"
+ );
});
}
@@ -1763,6 +2369,16 @@
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
let mode: CollectionMode = CollectionMode::NFT(2000);
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
@@ -1773,8 +2389,16 @@
mode
));
- assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
- assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+ assert_ok!(TemplateModule::set_public_access_mode(
+ origin1.clone(),
+ 1,
+ AccessMode::WhiteList
+ ));
+ assert_ok!(TemplateModule::set_mint_permission(
+ origin1.clone(),
+ 1,
+ true
+ ));
assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
assert_ok!(TemplateModule::create_item(
@@ -1786,4 +2410,290 @@
});
}
-// #endregion
\ No newline at end of file
+// Total number of collections. Positive test
+#[test]
+fn total_number_collections_bound() {
+ new_test_ext().execute_with(|| {
+ let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+ let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+ let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+ let mode: CollectionMode = CollectionMode::NFT(2000);
+
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
+ let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::create_collection(
+ origin1.clone(),
+ col_name1.clone(),
+ col_desc1.clone(),
+ token_prefix1.clone(),
+ mode
+ ));
+ });
+}
+
+// Total number of collections. Negotive test
+#[test]
+fn total_number_collections_bound_neg() {
+ new_test_ext().execute_with(|| {
+ let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+ let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+ let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+ let mode: CollectionMode = CollectionMode::NFT(2000);
+
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
+ let origin1 = Origin::signed(1);
+
+ for _ in 0..10 {
+
+ assert_ok!(TemplateModule::create_collection(
+ origin1.clone(),
+ col_name1.clone(),
+ col_desc1.clone(),
+ token_prefix1.clone(),
+ mode.clone()
+ ));
+ }
+
+ // 11-th collection in chain. Expects error
+ assert_noop!(TemplateModule::create_collection(
+ origin1.clone(),
+ col_name1.clone(),
+ col_desc1.clone(),
+ token_prefix1.clone(),
+ mode.clone()
+ ), "Total collections bound exceeded");
+ });
+}
+
+// Owned tokens by a single address. Positive test
+#[test]
+fn owned_tokens_bound() {
+ new_test_ext().execute_with(|| {
+ let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+ let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+ let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+ let mode: CollectionMode = CollectionMode::NFT(2000);
+
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
+ let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::create_collection(
+ origin1.clone(),
+ col_name1.clone(),
+ col_desc1.clone(),
+ token_prefix1.clone(),
+ mode
+ ));
+
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 2, 3].to_vec(),
+ 1
+ ));
+
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 2, 3].to_vec(),
+ 1
+ ));
+ });
+}
+
+// Owned tokens by a single address. Negotive test
+#[test]
+fn owned_tokens_bound_neg() {
+ new_test_ext().execute_with(|| {
+ let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+ let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+ let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+ let mode: CollectionMode = CollectionMode::NFT(2000);
+
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 1,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
+ let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::create_collection(
+ origin1.clone(),
+ col_name1.clone(),
+ col_desc1.clone(),
+ token_prefix1.clone(),
+ mode
+ ));
+
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 2, 3].to_vec(),
+ 1
+ ));
+
+ assert_noop!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 2, 3].to_vec(),
+ 1
+ ), "Owned tokens by a single address bound exceeded");
+ });
+}
+
+// Number of collection admins. Positive test
+#[test]
+fn collection_admins_bound() {
+ new_test_ext().execute_with(|| {
+ let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+ let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+ let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+ let mode: CollectionMode = CollectionMode::NFT(2000);
+
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 2,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
+ let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::create_collection(
+ origin1.clone(),
+ col_name1.clone(),
+ col_desc1.clone(),
+ token_prefix1.clone(),
+ mode
+ ));
+
+ assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
+ assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 3));
+ });
+}
+
+// Number of collection admins. Negotive test
+#[test]
+fn collection_admins_bound_neg() {
+ new_test_ext().execute_with(|| {
+ let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+ let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+ let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+ let mode: CollectionMode = CollectionMode::NFT(2000);
+
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 1,
+ collections_admins_limit: 1,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
+ let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::create_collection(
+ origin1.clone(),
+ col_name1.clone(),
+ col_desc1.clone(),
+ token_prefix1.clone(),
+ mode
+ ));
+
+ assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
+ assert_noop!(TemplateModule::add_collection_admin(origin1.clone(), 1, 3), "Number of collection admins bound exceeded");
+ });
+}
+
+// Custom data size. Positive test
+#[test]
+fn custom_data_size_bound() {
+ new_test_ext().execute_with(|| {
+ let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+ let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+ let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+ let mode: CollectionMode = CollectionMode::NFT(2000);
+
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
+ let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::create_collection(
+ origin1.clone(),
+ col_name1.clone(),
+ col_desc1.clone(),
+ token_prefix1.clone(),
+ mode
+ ));
+ });
+}
+
+// Custom data size. Negotive test
+#[test]
+fn custom_data_size_bound_neg() {
+ new_test_ext().execute_with(|| {
+ let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+ let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+ let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+ let mode: CollectionMode = CollectionMode::NFT(2000);
+
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 200,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
+ let origin1 = Origin::signed(1);
+ assert_noop!(TemplateModule::create_collection(
+ origin1.clone(),
+ col_name1.clone(),
+ col_desc1.clone(),
+ token_prefix1.clone(),
+ mode
+ ), "Custom data size bound exceeded");
+ });
+}
+// #endregion