difftreelog
Merge pull request #130 from usetech-llc/NFTPAR-310_builders_review_107
in: master
Review changes
9 files changed
node/src/chain_spec.rsdiffbeforeafterboth193 mint_mode: false,193 mint_mode: false,194 offchain_schema: vec![],194 offchain_schema: vec![],195 schema_version: SchemaVersion::default(),195 schema_version: SchemaVersion::default(),196 sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),196 sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<sr25519::Public>("Alice")),197 sponsor_confirmed: true,198 const_on_chain_schema: vec![],197 const_on_chain_schema: vec![],199 variable_on_chain_schema: vec![],198 variable_on_chain_schema: vec![],200 limits: CollectionLimits::default()199 limits: CollectionLimits::default()pallets/nft/src/lib.rsdiffbeforeafterboth20 ensure, fail, parameter_types,20 ensure, fail, parameter_types,21 traits::{21 traits::{22 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,22 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,23 Randomness, IsSubType,23 Randomness, IsSubType, WithdrawReasons,24 },24 },25 weights::{25 weights::{26 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},26 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},27 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,27 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,28 WeightToFeePolynomial, DispatchClass,28 WeightToFeePolynomial, DispatchClass,29 },29 },30 StorageValue,30 StorageValue,31 transactional,31};32};323333use frame_system::{self as system, ensure_signed, ensure_root};34use frame_system::{self as system, ensure_signed, ensure_root};123 pub fraction: u128,124 pub fraction: u128,124}125}125126127#[derive(Encode, Decode, Debug, Clone, PartialEq)]128#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]129pub enum SponsorshipState<AccountId> {130 /// The fees are applied to the transaction sender131 Disabled,132 Unconfirmed(AccountId),133 /// Transactions are sponsored by specified account134 Confirmed(AccountId),135}136137impl<AccountId> SponsorshipState<AccountId> {138 fn sponsor(&self) -> Option<&AccountId> {139 match self {140 Self::Confirmed(sponsor) => Some(sponsor),141 _ => None,142 }143 }144145 fn pending_sponsor(&self) -> Option<&AccountId> {146 match self {147 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),148 _ => None,149 }150 }151152 fn confirmed(&self) -> bool {153 matches!(self, Self::Confirmed(_))154 }155}156157impl<T> Default for SponsorshipState<T> {158 fn default() -> Self {159 Self::Disabled160 }161}162126#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]163#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]127#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]164#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]128pub struct CollectionType<AccountId> {165pub struct CollectionType<AccountId> {136 pub mint_mode: bool,173 pub mint_mode: bool,137 pub offchain_schema: Vec<u8>,174 pub offchain_schema: Vec<u8>,138 pub schema_version: SchemaVersion,175 pub schema_version: SchemaVersion,139 pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender176 pub sponsorship: SponsorshipState<AccountId>,140 pub sponsor_confirmed: bool, // False if sponsor address has not yet confirmed sponsorship. True otherwise.141 pub limits: CollectionLimits, // Collection private restrictions 177 pub limits: CollectionLimits, // Collection private restrictions 142 pub variable_on_chain_schema: Vec<u8>, //178 pub variable_on_chain_schema: Vec<u8>, //143 pub const_on_chain_schema: Vec<u8>, //179 pub const_on_chain_schema: Vec<u8>, //387 /// Schema data size limit bound exceeded423 /// Schema data size limit bound exceeded388 SchemaDataLimitExceeded,424 SchemaDataLimitExceeded,389 /// Maximum refungibility exceeded425 /// Maximum refungibility exceeded390 WrongRefungiblePieces426 WrongRefungiblePieces,427 /// createRefungible should be called with one owner428 BadCreateRefungibleCall,391 }429 }392}430}393431396434397 /// Weight information for extrinsics in this pallet.435 /// Weight information for extrinsics in this pallet.398 type WeightInfo: WeightInfo;436 type WeightInfo: WeightInfo;437438 type Currency: Currency<Self::AccountId>;439 type CollectionCreationPrice: Get<<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance>;440 type TreasuryAccountId: Get<Self::AccountId>;399}441}400442401#[cfg(feature = "runtime-benchmarks")]443#[cfg(feature = "runtime-benchmarks")]402mod benchmarking;444mod benchmarking;403445404// #endregion446// #endregion405447448// # Used definitions449//450// ## User control levels451//452// chain-controlled - key is uncontrolled by user453// i.e autoincrementing index454// can use non-cryptographic hash455// real - key is controlled by user456// but it is hard to generate enough colliding values, i.e owner of signed txs457// can use non-cryptographic hash458// controlled - key is completly controlled by users459// i.e maps with mutable keys460// should use cryptographic hash461//462// ## User control level downgrade reasons463//464// ?1 - chain-controlled -> controlled465// collections/tokens can be destroyed, resulting in massive holes466// ?2 - chain-controlled -> controlled467// same as ?1, but can be only added, resulting in easier exploitation468// ?3 - real -> controlled469// no confirmation required, so addresses can be easily generated406decl_storage! {470decl_storage! {407 trait Store for Module<T: Config> as Nft {471 trait Store for Module<T: Config> as Nft {408472409 // Private members473 //#region Private members410 NextCollectionID: CollectionId;474 /// Id of next collection411 CreatedCollectionCount: u32;475 CreatedCollectionCount: u32;476 /// Used for migrations412 ChainVersion: u64;477 ChainVersion: u64;413 ItemListIndex: map hasher(identity) CollectionId => TokenId;478 /// Id of last collection token479 /// Collection id (controlled?1)480 ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;481 //#endregion414482415 // Chain limits struct483 //#region Chain limits struct416 pub ChainLimit get(fn chain_limit) config(): ChainLimits;484 pub ChainLimit get(fn chain_limit) config(): ChainLimits;485 //#endregion417486418 // Bound counters487 //#region Bound counters419 CollectionCount: u32;488 /// Amount of collections destroyed, used for total amount tracking with489 /// CreatedCollectionCount490 DestroyedCollectionCount: u32;491 /// Total amount of account owned tokens (NFTs + RFTs + unique fungibles)492 /// Account id (real)420 pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;493 pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;494 //#endregion421495422 // Basic collections496 //#region Basic collections423 pub Collection get(fn collection) config(): map hasher(identity) CollectionId => CollectionType<T::AccountId>;497 /// Collection info498 /// Collection id (controlled?1)499 pub Collection get(fn collection) config(): map hasher(blake2_128_concat) CollectionId => CollectionType<T::AccountId>;424 pub AdminList get(fn admin_list_collection): map hasher(identity) CollectionId => Vec<T::AccountId>;500 /// List of collection admins501 /// Collection id (controlled?2)502 pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::AccountId>;425 pub WhiteList get(fn white_list): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => bool;503 /// Whitelisted collection users504 /// Collection id (controlled?2), user id (controlled?3)505 pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;506 //#endregion426507427 /// Balance owner per collection map508 /// How many of collection items user have509 /// Collection id (controlled?2), account id (real)428 pub Balance get(fn balance_count): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => u128;510 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => u128;429511430 /// second parameter: item id + owner account id + spender account id512 /// Amount of items which spender can transfer out of owners account (via transferFrom)513 /// Collection id (controlled?2), (token id (controlled ?2) + owner account id (real) + spender account id (controlled?3))431 pub Allowances get(fn approved): double_map hasher(identity) CollectionId, hasher(twox_64_concat) (TokenId, T::AccountId, T::AccountId) => u128;514 pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;432515433 /// Item collections516 //#region Item collections434 pub NftItemList get(fn nft_item_id) config(): double_map hasher(identity) CollectionId, hasher(identity) TokenId => NftItemType<T::AccountId>;517 /// Collection id (controlled?2), token id (controlled?1)518 pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => NftItemType<T::AccountId>;435 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => FungibleItemType;519 /// Collection id (controlled?2), owner (controlled?2)520 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;436 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(identity) CollectionId, hasher(identity) TokenId => ReFungibleItemType<T::AccountId>;521 /// Collection id (controlled?2), token id (controlled?1)522 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => ReFungibleItemType<T::AccountId>;523 //#endregion437524438 /// Index list525 //#region Index list439 pub AddressTokens get(fn address_tokens): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => Vec<TokenId>;526 /// Collection id (controlled?2), tokens owner (controlled?2)527 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => Vec<TokenId>;528 //#endregion440529441 /// Tokens transfer baskets530 //#region Tokens transfer rate limit baskets442 pub CreateItemBasket get(fn create_item_basket): map hasher(twox_64_concat) (CollectionId, T::AccountId) => T::BlockNumber;531 /// (Collection id (controlled?2), who created (real))532 pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;443 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => T::BlockNumber;533 /// Collection id (controlled?2), token id (controlled?2)534 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;444 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;535 /// Collection id (controlled?2), owning user (real)536 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;445 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => T::BlockNumber;537 /// Collection id (controlled?2), token id (controlled?2)538 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;539 //#endregion446540447 // Contract Sponsorship and Ownership541 //#region Contract Sponsorship and Ownership542 /// Contract address (real)448 pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => T::AccountId;543 pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => T::AccountId;544 /// Contract address (real)449 pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;545 pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;546 /// (Contract address(real), caller (real))450 pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;547 pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;548 /// Contract address (real)451 pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;549 pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;550 /// Contract address (real)452 pub ContractWhiteListEnabled get(fn contract_white_list_enabled): map hasher(twox_64_concat) T::AccountId => bool; 551 pub ContractWhiteListEnabled get(fn contract_white_list_enabled): map hasher(twox_64_concat) T::AccountId => bool; 453 pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(twox_64_concat) T::AccountId => bool; 552 /// Contract address (real) => Whitelisted user (controlled?3)553 pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) T::AccountId => bool; 554 //#endregion454 }555 }455 add_extra_genesis {556 add_extra_genesis {456 build(|config: &GenesisConfig<T>| {557 build(|config: &GenesisConfig<T>| {534 type Error = Error<T>;635 type Error = Error<T>;535636536 fn on_initialize(now: T::BlockNumber) -> Weight {637 fn on_initialize(now: T::BlockNumber) -> Weight {537538 if ChainVersion::get() < 2539 {540 let value = NextCollectionID::get();541 CreatedCollectionCount::put(value);542 ChainVersion::put(2);543 }544545 0638 0546 }639 }547640562 /// * mode: [CollectionMode] collection type and type dependent data.655 /// * mode: [CollectionMode] collection type and type dependent data.563 // returns collection ID656 // returns collection ID564 #[weight = <T as Config>::WeightInfo::create_collection()]657 #[weight = <T as Config>::WeightInfo::create_collection()]658 #[transactional]565 pub fn create_collection(origin,659 pub fn create_collection(origin,566 collection_name: Vec<u16>,660 collection_name: Vec<u16>,567 collection_description: Vec<u16>,661 collection_description: Vec<u16>,571 // Anyone can create a collection665 // Anyone can create a collection572 let who = ensure_signed(origin)?;666 let who = ensure_signed(origin)?;573667668 // Take a (non-refundable) deposit of collection creation669 let mut imbalance = <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();670 imbalance.subsume(<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(671 &T::TreasuryAccountId::get(),672 T::CollectionCreationPrice::get(),673 ));674 <T as Config>::Currency::settle(675 &who,676 imbalance,677 WithdrawReasons::TRANSFER,678 ExistenceRequirement::KeepAlive,679 ).map_err(|_| Error::<T>::NoPermission)?;680574 let decimal_points = match mode {681 let decimal_points = match mode {575 CollectionMode::Fungible(points) => points,682 CollectionMode::Fungible(points) => points,576 _ => 0683 _ => 0577 };684 };578685579 let chain_limit = ChainLimit::get();686 let chain_limit = ChainLimit::get();580687688 let created_count = CreatedCollectionCount::get();689 let destroyed_count = DestroyedCollectionCount::get();690581 // bound Total number of collections691 // bound Total number of collections582 ensure!(CollectionCount::get() < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);692 ensure!(created_count - destroyed_count < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);583693584 // check params694 // check params585 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);695 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);588 ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);698 ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);589699590 // Generate next collection ID700 // Generate next collection ID591 let next_id = CreatedCollectionCount::get()701 let next_id = created_count592 .checked_add(1)702 .checked_add(1)593 .ok_or(Error::<T>::NumOverflow)?;703 .ok_or(Error::<T>::NumOverflow)?;594704595 // bound counter596 let total = CollectionCount::get()597 .checked_add(1)598 .ok_or(Error::<T>::NumOverflow)?;599600 CreatedCollectionCount::put(next_id);705 CreatedCollectionCount::put(next_id);601 CollectionCount::put(total);602706603 let limits = CollectionLimits {707 let limits = CollectionLimits {604 sponsored_data_size: chain_limit.custom_data_limit,708 sponsored_data_size: chain_limit.custom_data_limit,617 token_prefix: token_prefix,721 token_prefix: token_prefix,618 offchain_schema: Vec::new(),722 offchain_schema: Vec::new(),619 schema_version: SchemaVersion::ImageURL,723 schema_version: SchemaVersion::ImageURL,620 sponsor: T::AccountId::default(),724 sponsorship: SponsorshipState::Disabled,621 sponsor_confirmed: false,622 variable_on_chain_schema: Vec::new(),725 variable_on_chain_schema: Vec::new(),623 const_on_chain_schema: Vec::new(),726 const_on_chain_schema: Vec::new(),624 limits,727 limits,643 /// 746 /// 644 /// * collection_id: collection to destroy.747 /// * collection_id: collection to destroy.645 #[weight = <T as Config>::WeightInfo::destroy_collection()]748 #[weight = <T as Config>::WeightInfo::destroy_collection()]749 #[transactional]646 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {750 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {647751648 let sender = ensure_signed(origin)?;752 let sender = ensure_signed(origin)?;669 <FungibleTransferBasket<T>>::remove_prefix(collection_id);773 <FungibleTransferBasket<T>>::remove_prefix(collection_id);670 <ReFungibleTransferBasket<T>>::remove_prefix(collection_id);774 <ReFungibleTransferBasket<T>>::remove_prefix(collection_id);671775672 if CollectionCount::get() > 0776 DestroyedCollectionCount::put(DestroyedCollectionCount::get()673 {674 // bound couter675 let total = CollectionCount::get()676 .checked_sub(1)777 .checked_add(1)677 .ok_or(Error::<T>::NumOverflow)?;778 .ok_or(Error::<T>::NumOverflow)?);678779679 CollectionCount::put(total);680 }681682 Ok(())780 Ok(())683 }781 }684782695 /// 793 /// 696 /// * address.794 /// * address.697 #[weight = <T as Config>::WeightInfo::add_to_white_list()]795 #[weight = <T as Config>::WeightInfo::add_to_white_list()]796 #[transactional]698 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{797 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{699798700 let sender = ensure_signed(origin)?;799 let sender = ensure_signed(origin)?;718 /// 817 /// 719 /// * address.818 /// * address.720 #[weight = <T as Config>::WeightInfo::remove_from_white_list()]819 #[weight = <T as Config>::WeightInfo::remove_from_white_list()]820 #[transactional]721 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{821 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{722822723 let sender = ensure_signed(origin)?;823 let sender = ensure_signed(origin)?;740 /// 840 /// 741 /// * mode: [AccessMode]841 /// * mode: [AccessMode]742 #[weight = <T as Config>::WeightInfo::set_public_access_mode()]842 #[weight = <T as Config>::WeightInfo::set_public_access_mode()]843 #[transactional]743 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult844 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult744 {845 {745 let sender = ensure_signed(origin)?;846 let sender = ensure_signed(origin)?;766 /// 867 /// 767 /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.868 /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.768 #[weight = <T as Config>::WeightInfo::set_mint_permission()]869 #[weight = <T as Config>::WeightInfo::set_mint_permission()]870 #[transactional]769 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult871 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult770 {872 {771 let sender = ensure_signed(origin)?;873 let sender = ensure_signed(origin)?;790 /// 892 /// 791 /// * new_owner.893 /// * new_owner.792 #[weight = <T as Config>::WeightInfo::change_collection_owner()]894 #[weight = <T as Config>::WeightInfo::change_collection_owner()]895 #[transactional]793 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {896 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {794897795 let sender = ensure_signed(origin)?;898 let sender = ensure_signed(origin)?;815 /// 918 /// 816 /// * new_admin_id: Address of new admin to add.919 /// * new_admin_id: Address of new admin to add.817 #[weight = <T as Config>::WeightInfo::add_collection_admin()]920 #[weight = <T as Config>::WeightInfo::add_collection_admin()]921 #[transactional]818 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::AccountId) -> DispatchResult {922 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::AccountId) -> DispatchResult {819923820 let sender = ensure_signed(origin)?;924 let sender = ensure_signed(origin)?;849 /// 953 /// 850 /// * account_id: Address of admin to remove.954 /// * account_id: Address of admin to remove.851 #[weight = <T as Config>::WeightInfo::remove_collection_admin()]955 #[weight = <T as Config>::WeightInfo::remove_collection_admin()]956 #[transactional]852 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::AccountId) -> DispatchResult {957 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::AccountId) -> DispatchResult {853958854 let sender = ensure_signed(origin)?;959 let sender = ensure_signed(origin)?;872 /// 977 /// 873 /// * new_sponsor.978 /// * new_sponsor.874 #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]979 #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]980 #[transactional]875 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {981 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {876982877 let sender = ensure_signed(origin)?;983 let sender = ensure_signed(origin)?;880 let mut target_collection = <Collection<T>>::get(collection_id);986 let mut target_collection = <Collection<T>>::get(collection_id);881 ensure!(sender == target_collection.owner, Error::<T>::NoPermission);987 ensure!(sender == target_collection.owner, Error::<T>::NoPermission);882988883 target_collection.sponsor = new_sponsor;989 target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);884 target_collection.sponsor_confirmed = false;885 <Collection<T>>::insert(collection_id, target_collection);990 <Collection<T>>::insert(collection_id, target_collection);886991887 Ok(())992 Ok(())895 /// 1000 /// 896 /// * collection_id.1001 /// * collection_id.897 #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]1002 #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]1003 #[transactional]898 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {1004 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {8991005900 let sender = ensure_signed(origin)?;1006 let sender = ensure_signed(origin)?;901 ensure!(<Collection<T>>::contains_key(collection_id), Error::<T>::CollectionNotFound);1007 ensure!(<Collection<T>>::contains_key(collection_id), Error::<T>::CollectionNotFound);9021008903 let mut target_collection = <Collection<T>>::get(collection_id);1009 let mut target_collection = <Collection<T>>::get(collection_id);904 ensure!(sender == target_collection.sponsor, Error::<T>::ConfirmUnsetSponsorFail);1010 ensure!(1011 target_collection.sponsorship.pending_sponsor() == Some(&sender),1012 Error::<T>::ConfirmUnsetSponsorFail1013 );9051014906 target_collection.sponsor_confirmed = true;1015 target_collection.sponsorship = SponsorshipState::Confirmed(sender);907 <Collection<T>>::insert(collection_id, target_collection);1016 <Collection<T>>::insert(collection_id, target_collection);9081017909 Ok(())1018 Ok(())919 /// 1028 /// 920 /// * collection_id.1029 /// * collection_id.921 #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]1030 #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]1031 #[transactional]922 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {1032 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {9231033924 let sender = ensure_signed(origin)?;1034 let sender = ensure_signed(origin)?;927 let mut target_collection = <Collection<T>>::get(collection_id);1037 let mut target_collection = <Collection<T>>::get(collection_id);928 ensure!(sender == target_collection.owner, Error::<T>::NoPermission);1038 ensure!(sender == target_collection.owner, Error::<T>::NoPermission);9291039930 target_collection.sponsor = T::AccountId::default();1040 target_collection.sponsorship = SponsorshipState::Disabled;931 target_collection.sponsor_confirmed = false;932 <Collection<T>>::insert(collection_id, target_collection);1041 <Collection<T>>::insert(collection_id, target_collection);9331042934 Ok(())1043 Ok(())959 // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]1068 // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]9601069961 #[weight = <T as Config>::WeightInfo::create_item(data.len())]1070 #[weight = <T as Config>::WeightInfo::create_item(data.len())]1071 #[transactional]962 pub fn create_item(origin, collection_id: CollectionId, owner: T::AccountId, data: CreateItemData) -> DispatchResult {1072 pub fn create_item(origin, collection_id: CollectionId, owner: T::AccountId, data: CreateItemData) -> DispatchResult {9631073964 let sender = ensure_signed(origin)?;1074 let sender = ensure_signed(origin)?;974 Ok(())1084 Ok(())975 }1085 }9761086977 /// This method creates multiple instances of NFT Collection created with CreateCollection method.1087 /// This method creates multiple items in a collection created with CreateCollection method.978 /// 1088 /// 979 /// # Permissions1089 /// # Permissions980 /// 1090 /// 995 #[weight = <T as Config>::WeightInfo::create_item(items_data.into_iter()1105 #[weight = <T as Config>::WeightInfo::create_item(items_data.into_iter()996 .map(|data| { data.len() })1106 .map(|data| { data.len() })997 .sum())]1107 .sum())]1108 #[transactional]998 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::AccountId, items_data: Vec<CreateItemData>) -> DispatchResult {1109 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::AccountId, items_data: Vec<CreateItemData>) -> DispatchResult {99911101000 ensure!(items_data.len() > 0, Error::<T>::EmptyArgument);1111 ensure!(items_data.len() > 0, Error::<T>::EmptyArgument);1029 /// 1140 /// 1030 /// * item_id: ID of NFT to burn.1141 /// * item_id: ID of NFT to burn.1031 #[weight = <T as Config>::WeightInfo::burn_item()]1142 #[weight = <T as Config>::WeightInfo::burn_item()]1143 #[transactional]1032 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {1144 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {103311451034 let sender = ensure_signed(origin)?;1146 let sender = ensure_signed(origin)?;1087 /// * Fungible Mode: Must specify transferred amount1199 /// * Fungible Mode: Must specify transferred amount1088 /// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)1200 /// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)1089 #[weight = <T as Config>::WeightInfo::transfer()]1201 #[weight = <T as Config>::WeightInfo::transfer()]1202 #[transactional]1090 pub fn transfer(origin, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {1203 pub fn transfer(origin, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {1091 let sender = ensure_signed(origin)?;1204 let sender = ensure_signed(origin)?;1092 Self::transfer_internal(sender, recipient, collection_id, item_id, value)1205 Self::transfer_internal(sender, recipient, collection_id, item_id, value)1108 /// 1221 /// 1109 /// * item_id: ID of the item.1222 /// * item_id: ID of the item.1110 #[weight = <T as Config>::WeightInfo::approve()]1223 #[weight = <T as Config>::WeightInfo::approve()]1224 #[transactional]1111 pub fn approve(origin, spender: T::AccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {1225 pub fn approve(origin, spender: T::AccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {111212261113 let sender = ensure_signed(origin)?;1227 let sender = ensure_signed(origin)?;1171 /// 1285 /// 1172 /// * value: Amount to transfer.1286 /// * value: Amount to transfer.1173 #[weight = <T as Config>::WeightInfo::transfer_from()]1287 #[weight = <T as Config>::WeightInfo::transfer_from()]1288 #[transactional]1174 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {1289 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {117512901176 let sender = ensure_signed(origin)?;1291 let sender = ensure_signed(origin)?;1205 }1320 }120613211207 // Reduce approval by transferred amount or remove if remaining approval drops to 01322 // Reduce approval by transferred amount or remove if remaining approval drops to 01208 if approval.checked_sub(value).unwrap_or(0) > 0 {1323 if approval.saturating_sub(value) > 0 {1209 <Allowances<T>>::insert(collection_id, (item_id, &from, &sender), approval - value);1324 <Allowances<T>>::insert(collection_id, (item_id, &from, &sender), approval - value);1210 }1325 }1211 else {1326 else {1251 /// 1366 /// 1252 /// * schema: String representing the offchain data schema.1367 /// * schema: String representing the offchain data schema.1253 #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1368 #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1369 #[transactional]1254 pub fn set_variable_meta_data (1370 pub fn set_variable_meta_data (1255 origin,1371 origin,1256 collection_id: CollectionId,1372 collection_id: CollectionId,1296 /// 1412 /// 1297 /// * schema: SchemaVersion: enum1413 /// * schema: SchemaVersion: enum1298 #[weight = <T as Config>::WeightInfo::set_schema_version()]1414 #[weight = <T as Config>::WeightInfo::set_schema_version()]1415 #[transactional]1299 pub fn set_schema_version(1416 pub fn set_schema_version(1300 origin,1417 origin,1301 collection_id: CollectionId,1418 collection_id: CollectionId,1323 /// 1440 /// 1324 /// * schema: String representing the offchain data schema.1441 /// * schema: String representing the offchain data schema.1325 #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1442 #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1443 #[transactional]1326 pub fn set_offchain_schema(1444 pub fn set_offchain_schema(1327 origin,1445 origin,1328 collection_id: CollectionId,1446 collection_id: CollectionId,1354 /// 1472 /// 1355 /// * schema: String representing the const on-chain data schema.1473 /// * schema: String representing the const on-chain data schema.1356 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1474 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1475 #[transactional]1357 pub fn set_const_on_chain_schema (1476 pub fn set_const_on_chain_schema (1358 origin,1477 origin,1359 collection_id: CollectionId,1478 collection_id: CollectionId,1385 /// 1504 /// 1386 /// * schema: String representing the variable on-chain data schema.1505 /// * schema: String representing the variable on-chain data schema.1387 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1506 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1507 #[transactional]1388 pub fn set_variable_on_chain_schema (1508 pub fn set_variable_on_chain_schema (1389 origin,1509 origin,1390 collection_id: CollectionId,1510 collection_id: CollectionId,140515251406 // Sudo permissions function1526 // Sudo permissions function1407 #[weight = <T as Config>::WeightInfo::set_chain_limits()]1527 #[weight = <T as Config>::WeightInfo::set_chain_limits()]1528 #[transactional]1408 pub fn set_chain_limits(1529 pub fn set_chain_limits(1409 origin,1530 origin,1410 limits: ChainLimits1531 limits: ChainLimits1429 /// * enable flag1550 /// * enable flag1430 /// 1551 /// 1431 #[weight = <T as Config>::WeightInfo::enable_contract_sponsoring()]1552 #[weight = <T as Config>::WeightInfo::enable_contract_sponsoring()]1553 #[transactional]1432 pub fn enable_contract_sponsoring(1554 pub fn enable_contract_sponsoring(1433 origin,1555 origin,1434 contract_address: T::AccountId,1556 contract_address: T::AccountId,1464 /// -`rate_limit`: Number of blocks to wait until the next sponsored transaction is allowed1586 /// -`rate_limit`: Number of blocks to wait until the next sponsored transaction is allowed1465 /// 1587 /// 1466 #[weight = <T as Config>::WeightInfo::set_contract_sponsoring_rate_limit()]1588 #[weight = <T as Config>::WeightInfo::set_contract_sponsoring_rate_limit()]1589 #[transactional]1467 pub fn set_contract_sponsoring_rate_limit(1590 pub fn set_contract_sponsoring_rate_limit(1468 origin,1591 origin,1469 contract_address: T::AccountId,1592 contract_address: T::AccountId,1491 /// 1614 /// 1492 /// - `enable`: . 1615 /// - `enable`: . 1493 #[weight = <T as Config>::WeightInfo::toggle_contract_white_list()]1616 #[weight = <T as Config>::WeightInfo::toggle_contract_white_list()]1617 #[transactional]1494 pub fn toggle_contract_white_list(1618 pub fn toggle_contract_white_list(1495 origin,1619 origin,1496 contract_address: T::AccountId,1620 contract_address: T::AccountId,1518 ///1642 ///1519 /// -`account_address`: Address to add.1643 /// -`account_address`: Address to add.1520 #[weight = <T as Config>::WeightInfo::add_to_contract_white_list()]1644 #[weight = <T as Config>::WeightInfo::add_to_contract_white_list()]1645 #[transactional]1521 pub fn add_to_contract_white_list(1646 pub fn add_to_contract_white_list(1522 origin,1647 origin,1523 contract_address: T::AccountId,1648 contract_address: T::AccountId,1545 ///1670 ///1546 /// -`account_address`: Address to remove.1671 /// -`account_address`: Address to remove.1547 #[weight = <T as Config>::WeightInfo::remove_from_contract_white_list()]1672 #[weight = <T as Config>::WeightInfo::remove_from_contract_white_list()]1673 #[transactional]1548 pub fn remove_from_contract_white_list(1674 pub fn remove_from_contract_white_list(1549 origin,1675 origin,1550 contract_address: T::AccountId,1676 contract_address: T::AccountId,1561 }1687 }156216881563 #[weight = <T as Config>::WeightInfo::set_collection_limits()]1689 #[weight = <T as Config>::WeightInfo::set_collection_limits()]1690 #[transactional]1564 pub fn set_collection_limits(1691 pub fn set_collection_limits(1565 origin,1692 origin,1566 collection_id: u32,1693 collection_id: u32,1726 }1853 }1727 };1854 };172818551729 // call event1730 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id), owner));17311732 Ok(())1856 Ok(())1733 }1857 }173418581752 .ok_or(Error::<T>::NumOverflow)?;1876 .ok_or(Error::<T>::NumOverflow)?;1753 <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);1877 <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);175418781879 Self::deposit_event(RawEvent::ItemCreated(collection_id, 0, owner.clone()));1755 Ok(())1880 Ok(())1756 }1881 }175718821761 .ok_or(Error::<T>::NumOverflow)?;1886 .ok_or(Error::<T>::NumOverflow)?;1762 let itemcopy = item.clone();1887 let itemcopy = item.clone();176318881764 let value = item.owner.first().unwrap().fraction;1889 ensure!(1890 item.owner.len() == 1,1891 Error::<T>::BadCreateRefungibleCall,1892 );1765 let owner = item.owner.first().unwrap().owner.clone();1893 let item_owner = item.owner.first().expect("only one owner is defined");176618941895 let value = item_owner.fraction;1896 let owner = item_owner.owner.clone();18971767 Self::add_token_index(collection_id, current_index, &owner)?;1898 Self::add_token_index(collection_id, current_index, &owner)?;176818991769 <ItemListIndex>::insert(collection_id, current_index);1900 <ItemListIndex>::insert(collection_id, current_index);1775 .ok_or(Error::<T>::NumOverflow)?;1906 .ok_or(Error::<T>::NumOverflow)?;1776 <Balance<T>>::insert(collection_id, owner.clone(), new_balance);1907 <Balance<T>>::insert(collection_id, owner.clone(), new_balance);177719081909 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, owner));1778 Ok(())1910 Ok(())1779 }1911 }178019121795 .ok_or(Error::<T>::NumOverflow)?;1927 .ok_or(Error::<T>::NumOverflow)?;1796 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);1928 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);179719291930 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, item_owner));1798 Ok(())1931 Ok(())1799 }1932 }180019331811 let rft_balance = token1944 let rft_balance = token1812 .owner1945 .owner1813 .iter()1946 .iter()1814 .filter(|&i| i.owner == *owner)1947 .find(|&i| i.owner == *owner)1815 .next()1948 .ok_or(Error::<T>::TokenNotFound)?;1816 .unwrap();1817 Self::remove_token_index(collection_id, item_id, owner)?;1949 Self::remove_token_index(collection_id, item_id, owner)?;181819501819 // update balance1951 // update balance1827 .owner1959 .owner1828 .iter()1960 .iter()1829 .position(|i| i.owner == *owner)1961 .position(|i| i.owner == *owner)1830 .unwrap();1962 .expect("owned item is exists");1831 token.owner.remove(index);1963 token.owner.remove(index);1832 let owner_count = token.owner.len();1964 let owner_count = token.owner.len();183319652054 .iter()2186 .iter()2055 .filter(|i| i.owner == owner)2187 .filter(|i| i.owner == owner)2056 .next()2188 .next()2057 .ok_or(Error::<T>::NumOverflow)?;2189 .ok_or(Error::<T>::TokenNotFound)?;2058 let amount = item.fraction;2190 let amount = item.fraction;205921912060 ensure!(amount >= value, Error::<T>::TokenValueTooLow);2192 ensure!(amount >= value, Error::<T>::TokenValueTooLow);2065 .ok_or(Error::<T>::NumOverflow)?;2197 .ok_or(Error::<T>::NumOverflow)?;2066 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);2198 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);206721992068 let balancenew_owner = <Balance<T>>::get(collection_id, new_owner.clone())2200 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())2069 .checked_add(value)2201 .checked_add(value)2070 .ok_or(Error::<T>::NumOverflow)?;2202 .ok_or(Error::<T>::NumOverflow)?;2071 <Balance<T>>::insert(collection_id, new_owner.clone(), balancenew_owner);2203 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);207222042073 let old_owner = item.owner.clone();2205 let old_owner = item.owner.clone();2074 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);2206 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);2082 .owner2214 .owner2083 .iter_mut()2215 .iter_mut()2084 .find(|i| i.owner == owner)2216 .find(|i| i.owner == owner)2085 .unwrap()2217 .expect("old owner does present in refungible")2086 .owner = new_owner.clone();2218 .owner = new_owner.clone();2087 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);2219 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);208822202094 .owner2226 .owner2095 .iter_mut()2227 .iter_mut()2096 .find(|i| i.owner == owner)2228 .find(|i| i.owner == owner)2097 .unwrap()2229 .expect("old owner does present in refungible")2098 .fraction -= value;2230 .fraction -= value;209922312100 // separate amount2232 // separate amount2104 .owner2236 .owner2105 .iter_mut()2237 .iter_mut()2106 .find(|i| i.owner == new_owner)2238 .find(|i| i.owner == new_owner)2107 .unwrap()2239 .expect("new owner has account")2108 .fraction += value;2240 .fraction += value;2109 } else {2241 } else {2110 // new owner do not have account2242 // new owner do not have account2424 > {2556 > {2425 let tip = self.0;2557 let tip = self.0;242625582427 // Set fee based on call type. Creating collection costs 1 Unique.2428 // All other transactions have traditional fees so far2429 // let fee = match call.is_sub_type() {2430 // Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),2431 // _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes2432 // // _ => <BalanceOf<T>>::from(100)2433 // };2434 let fee = Self::traditional_fee(len, info, tip);2559 let fee = Self::traditional_fee(len, info, tip);243525602436 // Only mess with balances if fee is not zero.2561 // Only mess with balances if fee is not zero.244625712447 // sponsor timeout2572 // sponsor timeout2448 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;2573 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;25742575 let collection = <Collection<T>>::get(collection_id);244925762450 let limit = <Collection<T>>::get(collection_id).limits.sponsor_transfer_timeout;2577 let limit = collection.limits.sponsor_transfer_timeout;2451 let mut sponsored = true;2578 let mut sponsored = true;2452 if <CreateItemBasket<T>>::contains_key((collection_id, &who)) {2579 if <CreateItemBasket<T>>::contains_key((collection_id, &who)) {2453 let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));2580 let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));2461 }2588 }246225892463 // check free create limit2590 // check free create limit2464 if (<Collection<T>>::get(collection_id).limits.sponsored_data_size >= (_properties.len() as u32)) &&2591 if (collection.limits.sponsored_data_size >= (_properties.len() as u32)) &&2465 (<Collection<T>>::get(collection_id).sponsor_confirmed) &&2466 (sponsored)2592 (sponsored)2467 {2593 {2468 <Collection<T>>::get(collection_id).sponsor2594 collection.sponsorship.sponsor()2595 .cloned()2596 .unwrap_or_default()2469 } else {2597 } else {2470 T::AccountId::default()2598 T::AccountId::default()2471 }2599 }2472 }2600 }2473 Some(Call::transfer(_new_owner, collection_id, item_id, _value)) => {2601 Some(Call::transfer(_new_owner, collection_id, item_id, _value)) => {2474 2602 2475 let mut sponsor_transfer = false;2603 let mut sponsor_transfer = false;2476 if <Collection<T>>::get(collection_id).sponsor_confirmed {2604 if <Collection<T>>::get(collection_id).sponsorship.confirmed() {247726052478 let collection_limits = <Collection<T>>::get(collection_id).limits;2606 let collection_limits = <Collection<T>>::get(collection_id).limits;2479 let collection_mode = <Collection<T>>::get(collection_id).mode;2607 let collection_mode = <Collection<T>>::get(collection_id).mode;2560 if !sponsor_transfer {2688 if !sponsor_transfer {2561 T::AccountId::default()2689 T::AccountId::default()2562 } else {2690 } else {2563 <Collection<T>>::get(collection_id).sponsor2691 <Collection<T>>::get(collection_id).sponsorship.sponsor()2692 .cloned()2693 .unwrap_or_default()2564 }2694 }2565 }2695 }25662696pallets/nft/src/mock.rsdiffbeforeafterboth1// Creating mock runtime here23use crate::{Module, Config};1use crate as pallet_template;42use sp_core::H256;5use frame_support::{3use frame_support::{ 6 impl_outer_origin, parameter_types,4 parameter_types,7 weights::{Weight, IdentityFee},5 weights::IdentityFee,8};6};9use frame_system as system;10use system::limits::{BlockLength, BlockWeights};7use sp_runtime::{8 traits::{BlakeTwo256, IdentityLookup}, 9 testing::Header, 10 Perbill,11};11use transaction_payment::{self, CurrencyAdapter};12use pallet_transaction_payment::{ CurrencyAdapter};12use sp_core::H256;13use frame_system as system;13use sp_runtime::{1414 testing::Header,15type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;15 traits::{BlakeTwo256, IdentityLookup},16 Perbill,17};18use pallet_contracts::WeightInfo;16type Block = frame_system::mocking::MockBlock<Test>; 19pub use pallet_balances;172018// Configure a mock runtime to test the pallet.21impl_outer_origin! {19frame_support::construct_runtime!(22 pub enum Origin for Test {}20 pub enum Test where23}21 Block = Block,2422 NodeBlock = Block,25// For testing the pallet, we construct most of a mock runtime. This means23 UncheckedExtrinsic = UncheckedExtrinsic,26// first constructing a configuration type (`Test`) which `impl`s each of the24 {27// configuration traits of pallets we want to use.25 System: frame_system::{Module, Call, Config, Storage, Event<T>},28#[derive(Clone, Eq, PartialEq)]26 TemplateModule: pallet_template::{Module, Call, Storage},27 }29pub struct Test;28);2930parameter_types! {30parameter_types! {31 pub const BlockHashCount: u64 = 250;31 pub const BlockHashCount: u64 = 250;32 pub TestBlockWeights: BlockWeights = BlockWeights::default();33 pub TestBlockLength: BlockLength = BlockLength::default();34 pub SS58Prefix: u8 = 0;32 pub const SS58Prefix: u8 = 42;35}33}363437impl system::Config for Test {35impl system::Config for Test {38 type BaseCallFilter = ();36 type BaseCallFilter = ();37 type BlockWeights = ();38 type BlockLength = ();39 type DbWeight = ();39 type Origin = Origin;40 type Origin = Origin;40 type Call = ();41 type Call = Call;41 type Index = u64;42 type Index = u64;42 type BlockNumber = u64;43 type BlockNumber = u64;43 type Hash = H256;44 type Hash = H256;47 type Header = Header;48 type Header = Header;48 type Event = ();49 type Event = ();49 type BlockHashCount = BlockHashCount;50 type BlockHashCount = BlockHashCount;50 type BlockWeights = TestBlockWeights;51 type DbWeight = ();52 type BlockLength = TestBlockLength;53 type Version = ();51 type Version = ();54 type PalletInfo = ();52 type PalletInfo = PalletInfo;55 type AccountData = pallet_balances::AccountData<u64>;53 type AccountData = pallet_balances::AccountData<u64>;56 type OnNewAccount = ();54 type OnNewAccount = ();57 type OnKilledAccount = ();55 type OnKilledAccount = ();58 type SS58Prefix = SS58Prefix;56 type SystemWeightInfo = ();59 type SystemWeightInfo = ();57 type SS58Prefix = SS58Prefix;60}58}615962parameter_types! {60parameter_types! {63 pub const ExistentialDeposit: u64 = 1;61 pub const ExistentialDeposit: u64 = 1;64 pub const MaxLocks: u32 = 50;62 pub const MaxLocks: u32 = 50;65}63}6664//frame_system::Module<Test>;67type System = frame_system::Module<Test>;68impl pallet_balances::Config for Test {65impl pallet_balances::Config for Test {69 type AccountStore = System;66 type AccountStore = System;70 type Balance = u64;67 type Balance = u64;79 pub const TransactionByteFee: u64 = 1;76 pub const TransactionByteFee: u64 = 1;80}77}817882impl transaction_payment::Config for Test {79impl pallet_transaction_payment::Config for Test {83 type OnChargeTransaction = CurrencyAdapter<pallet_balances::Module<Test>, ()>;80 type OnChargeTransaction = CurrencyAdapter<pallet_balances::Module<Test>, ()>;84 type TransactionByteFee = TransactionByteFee;81 type TransactionByteFee = TransactionByteFee;85 type WeightToFee = IdentityFee<u64>;82 type WeightToFee = IdentityFee<u64>;110 pub const SignedClaimHandicap: u32 = 2;106 pub const SignedClaimHandicap: u32 = 2;111 pub const MaxDepth: u32 = 32;107 pub const MaxDepth: u32 = 32;112 pub const MaxValueSize: u32 = 16 * 1024;108 pub const MaxValueSize: u32 = 16 * 1024;113 pub DeletionWeightLimit: Weight = Perbill::from_percent(10) *109 pub DeletionWeightLimit: u64 = u64::MAX;//Perbill::from_percent(10);114 TestBlockWeights::get().max_block;115 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (110 pub DeletionQueueDepth: u32 = 10;116 <Test as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -117 <Test as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)118 )) / 5) as u32;119}111}120112121impl pallet_contracts::Config for Test {113impl pallet_contracts::Config for Test {136 type DeletionQueueDepth = DeletionQueueDepth;128 type DeletionQueueDepth = DeletionQueueDepth;137 type MaxValueSize = MaxValueSize;129 type MaxValueSize = MaxValueSize;138 type ChainExtension = ();130 type ChainExtension = ();131 type MaxCodeSize = ();139 type WeightPrice = ();132 type WeightPrice = ();140 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;133 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;141}134}135136parameter_types! {137 pub const CollectionCreationPrice: u64 = 1_000_000_000_000;138}142139143impl Config for Test {140impl pallet_template::Config for Test {144 type Event = ();141 type Event = ();145 type WeightInfo = ();142 type WeightInfo = ();146147}148pub type TemplateModule = Module<Test>;143 type CollectionCreationPrice = CollectionCreationPrice;149144}150145151// This function basically just builds a genesis storage key/value store according to146// Build genesis storage according to the mock runtime.152// our desired mockup.153pub fn new_test_ext() -> sp_io::TestExternalities {147pub fn new_test_ext() -> sp_io::TestExternalities {154 system::GenesisConfig::default()148 system::GenesisConfig::default().build_storage::<Test>().unwrap().into()155 .build_storage::<Test>()runtime/src/lib.rsdiffbeforeafterboth24 create_runtime_str, generic, impl_opaque_keys,24 create_runtime_str, generic, impl_opaque_keys,25 traits::{25 traits::{26 Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, 26 Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, 27 IdentityLookup, NumberFor, Verify,27 IdentityLookup, NumberFor, Verify, AccountIdConversion,28 },28 },29 transaction_validity::{TransactionSource, TransactionValidity},29 transaction_validity::{TransactionSource, TransactionValidity},30 ApplyExtrinsicResult, MultiSignature,30 ApplyExtrinsicResult, MultiSignature,520 type WeightInfo = ();520 type WeightInfo = ();521}521}522523parameter_types! {524 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();525 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;526}522527523/// Used for the module nft in `./nft.rs`528/// Used for the module nft in `./nft.rs`524impl pallet_nft::Config for Runtime {529impl pallet_nft::Config for Runtime {525 type Event = Event;530 type Event = Event;526 type WeightInfo = nft_weights::WeightInfo;531 type WeightInfo = nft_weights::WeightInfo;532 type Currency = Balances;533 type CollectionCreationPrice = CollectionCreationPrice;534 type TreasuryAccountId = TreasuryAccountId;527}535}528536529construct_runtime!(537construct_runtime!(runtime_types.jsondiffbeforeafterboth31 "ConstData": "Vec<u8>",31 "ConstData": "Vec<u8>",32 "VariableData": "Vec<u8>"32 "VariableData": "Vec<u8>"33 },33 },34 "SponsorshipState": {35 "_enum": {36 "Disabled": null,37 "Unconfirmed": "AccountId",38 "Confirmed": "AccountId"39 }40 },34 "CollectionType": {41 "CollectionType": {35 "Owner": "AccountId",42 "Owner": "AccountId",36 "Mode": "CollectionMode",43 "Mode": "CollectionMode",42 "MintMode": "bool",49 "MintMode": "bool",43 "OffchainSchema": "Vec<u8>",50 "OffchainSchema": "Vec<u8>",44 "SchemaVersion": "SchemaVersion",51 "SchemaVersion": "SchemaVersion",45 "Sponsor": "AccountId",52 "Sponsorship": "SponsorshipState",46 "SponsorConfirmed": "bool",47 "Limits": "CollectionLimits",53 "Limits": "CollectionLimits",48 "VariableOnChainSchema": "Vec<u8>",54 "VariableOnChainSchema": "Vec<u8>",49 "ConstOnChainSchema": "Vec<u8>"55 "ConstOnChainSchema": "Vec<u8>"tests/package.jsondiffbeforeafterboth25 "testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",25 "testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",26 "testSetVariableMetaData": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetaData.test.ts",26 "testSetVariableMetaData": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetaData.test.ts",27 "testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",27 "testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",28 "testSetCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionSponsor.test.ts",29 "testConfirmSponsorship": "mocha --timeout 9999999 -r ts-node/register ./**/confirmSponsorship.test.ts",28 "testRemoveCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionAdmin.test.ts",30 "testRemoveCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionAdmin.test.ts",31 "testRemoveCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionSponsor.test.ts",29 "testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",32 "testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",30 "testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",33 "testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",31 "testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",34 "testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",tests/src/createCollection.test.tsdiffbeforeafterboth35describe('(!negative test!) integration test: ext. createCollection():', () => {
35describe('(!negative test!) integration test: ext. createCollection():', () => {36 it('(!negative test!) create new NFT collection whith incorrect data (mode)', async () => {
36 it('(!negative test!) create new NFT collection whith incorrect data (mode)', async () => {37 await usingApi(async (api) => {
37 await usingApi(async (api) => {38 const AcollectionCount = parseInt((await api.query.nft.collectionCount()).toString(), 10);
38 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);39
3940 const badTransaction = async () => {
40 const badTransaction = async () => {41 await createCollectionExpectSuccess({mode: {type: 'Invalid'}});
41 await createCollectionExpectSuccess({mode: {type: 'Invalid'}});42 };
42 };43 // tslint:disable-next-line:no-unused-expression
43 // tslint:disable-next-line:no-unused-expression44 expect(badTransaction()).to.be.rejected;
44 expect(badTransaction()).to.be.rejected;45
4546 const BcollectionCount = parseInt((await api.query.nft.collectionCount()).toString(), 10);
46 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);47 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Incorrect collection created.');
47 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Incorrect collection created.');48 });
48 });49 });
49 });tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth25const Treasury = "5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z";25const Treasury = "5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z";26const saneMinimumFee = 0.05;26const saneMinimumFee = 0.05;27const saneMaximumFee = 0.5;27const saneMaximumFee = 0.5;28const createCollectionDeposit = 100;282929let alice: IKeyringPair;30let alice: IKeyringPair;30let bob: IKeyringPair;31let bob: IKeyringPair;127 const aliceBalanceAfter = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());128 const aliceBalanceAfter = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());128 const fee = aliceBalanceBefore.minus(aliceBalanceAfter);129 const fee = aliceBalanceBefore.minus(aliceBalanceAfter);129130130 expect(fee.dividedBy(1e15).toNumber()).to.be.lessThan(saneMaximumFee);131 expect(fee.dividedBy(1e15).toNumber()).to.be.lessThan(saneMaximumFee + createCollectionDeposit);131 expect(fee.dividedBy(1e15).toNumber()).to.be.greaterThan(saneMinimumFee);132 expect(fee.dividedBy(1e15).toNumber()).to.be.greaterThan(saneMinimumFee + createCollectionDeposit);132 });133 });133 });134 });134135tests/src/util/helpers.tsdiffbeforeafterboth377377378 // What to expect378 // What to expect379 expect(result.success).to.be.true;379 expect(result.success).to.be.true;380 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());380 expect(collection.Sponsorship).to.deep.equal({381 expect(collection.SponsorConfirmed).to.be.false;381 Unconfirmed: sponsor.toString(),382 });382 });383 });383}384}384385396397397 // What to expect398 // What to expect398 expect(result.success).to.be.true;399 expect(result.success).to.be.true;399 expect(collection.Sponsor).to.be.equal(nullPublicKey);400 expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });400 expect(collection.SponsorConfirmed).to.be.false;401 });401 });402}402}403403435435436 // What to expect436 // What to expect437 expect(result.success).to.be.true;437 expect(result.success).to.be.true;438 expect(collection.Sponsor).to.be.equal(sender.address);438 expect(collection.Sponsorship).to.be.deep.equal({439 expect(collection.SponsorConfirmed).to.be.true;439 Confirmed: sender.address,440 });440 });441 });441}442}442443