difftreelog
Merge pull request #130 from usetech-llc/NFTPAR-310_builders_review_107
in: master
Review changes
9 files changed
node/src/chain_spec.rsdiffbeforeafterboth--- a/node/src/chain_spec.rs
+++ b/node/src/chain_spec.rs
@@ -193,8 +193,7 @@
mint_mode: false,
offchain_schema: vec![],
schema_version: SchemaVersion::default(),
- sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),
- sponsor_confirmed: true,
+ sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<sr25519::Public>("Alice")),
const_on_chain_schema: vec![],
variable_on_chain_schema: vec![],
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.rsdiffbeforeafterboth--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -1,43 +1,44 @@
-// Creating mock runtime here
-
-use crate::{Module, Config};
-
-use frame_support::{
- impl_outer_origin, parameter_types,
- weights::{Weight, IdentityFee},
+use crate as pallet_template;
+use sp_core::H256;
+use frame_support::{
+ parameter_types,
+ weights::IdentityFee,
};
-use frame_system as system;
-use system::limits::{BlockLength, BlockWeights};
-use transaction_payment::{self, CurrencyAdapter};
-use sp_core::H256;
use sp_runtime::{
- testing::Header,
- traits::{BlakeTwo256, IdentityLookup},
- Perbill,
+ traits::{BlakeTwo256, IdentityLookup},
+ testing::Header,
+ Perbill,
};
-use pallet_contracts::WeightInfo;
-pub use pallet_balances;
+use pallet_transaction_payment::{ CurrencyAdapter};
+use frame_system as system;
-impl_outer_origin! {
- pub enum Origin for Test {}
-}
+type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
+type Block = frame_system::mocking::MockBlock<Test>;
-// For testing the pallet, we construct most of a mock runtime. This means
-// first constructing a configuration type (`Test`) which `impl`s each of the
-// configuration traits of pallets we want to use.
-#[derive(Clone, Eq, PartialEq)]
-pub struct Test;
+// Configure a mock runtime to test the pallet.
+frame_support::construct_runtime!(
+ pub enum Test where
+ Block = Block,
+ NodeBlock = Block,
+ UncheckedExtrinsic = UncheckedExtrinsic,
+ {
+ System: frame_system::{Module, Call, Config, Storage, Event<T>},
+ TemplateModule: pallet_template::{Module, Call, Storage},
+ }
+);
+
parameter_types! {
- pub const BlockHashCount: u64 = 250;
- pub TestBlockWeights: BlockWeights = BlockWeights::default();
- pub TestBlockLength: BlockLength = BlockLength::default();
- pub SS58Prefix: u8 = 0;
+ pub const BlockHashCount: u64 = 250;
+ pub const SS58Prefix: u8 = 42;
}
impl system::Config for Test {
type BaseCallFilter = ();
+ type BlockWeights = ();
+ type BlockLength = ();
+ type DbWeight = ();
type Origin = Origin;
- type Call = ();
+ type Call = Call;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
@@ -47,24 +48,20 @@
type Header = Header;
type Event = ();
type BlockHashCount = BlockHashCount;
- type BlockWeights = TestBlockWeights;
- type DbWeight = ();
- type BlockLength = TestBlockLength;
type Version = ();
- type PalletInfo = ();
+ type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
+ type SystemWeightInfo = ();
type SS58Prefix = SS58Prefix;
- type SystemWeightInfo = ();
}
parameter_types! {
pub const ExistentialDeposit: u64 = 1;
pub const MaxLocks: u32 = 50;
}
-
-type System = frame_system::Module<Test>;
+//frame_system::Module<Test>;
impl pallet_balances::Config for Test {
type AccountStore = System;
type Balance = u64;
@@ -79,13 +76,12 @@
pub const TransactionByteFee: u64 = 1;
}
-impl transaction_payment::Config for Test {
+impl pallet_transaction_payment::Config for Test {
type OnChargeTransaction = CurrencyAdapter<pallet_balances::Module<Test>, ()>;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = IdentityFee<u64>;
type FeeMultiplierUpdate = ();
}
-
parameter_types! {
pub const MinimumPeriod: u64 = 1;
@@ -110,12 +106,8 @@
pub const SignedClaimHandicap: u32 = 2;
pub const MaxDepth: u32 = 32;
pub const MaxValueSize: u32 = 16 * 1024;
- pub DeletionWeightLimit: Weight = Perbill::from_percent(10) *
- TestBlockWeights::get().max_block;
- pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (
- <Test as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -
- <Test as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)
- )) / 5) as u32;
+ pub DeletionWeightLimit: u64 = u64::MAX;//Perbill::from_percent(10);
+ pub DeletionQueueDepth: u32 = 10;
}
impl pallet_contracts::Config for Test {
@@ -136,23 +128,22 @@
type DeletionQueueDepth = DeletionQueueDepth;
type MaxValueSize = MaxValueSize;
type ChainExtension = ();
+ type MaxCodeSize = ();
type WeightPrice = ();
type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
}
-impl Config for Test {
+parameter_types! {
+ pub const CollectionCreationPrice: u64 = 1_000_000_000_000;
+}
+
+impl pallet_template::Config for Test {
type Event = ();
type WeightInfo = ();
-
+ type CollectionCreationPrice = CollectionCreationPrice;
}
-pub type TemplateModule = Module<Test>;
-
-// This function basically just builds a genesis storage key/value store according to
-// our desired mockup.
+// Build genesis storage according to the mock runtime.
pub fn new_test_ext() -> sp_io::TestExternalities {
- system::GenesisConfig::default()
- .build_storage::<Test>()
- .unwrap()
- .into()
-}
+ system::GenesisConfig::default().build_storage::<Test>().unwrap().into()
+}
\ No newline at end of file
runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -24,7 +24,7 @@
create_runtime_str, generic, impl_opaque_keys,
traits::{
Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount,
- IdentityLookup, NumberFor, Verify,
+ IdentityLookup, NumberFor, Verify, AccountIdConversion,
},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, MultiSignature,
@@ -520,10 +520,18 @@
type WeightInfo = ();
}
+parameter_types! {
+ pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();
+ pub const CollectionCreationPrice: Balance = 100 * UNIQUE;
+}
+
/// Used for the module nft in `./nft.rs`
impl pallet_nft::Config for Runtime {
type Event = Event;
type WeightInfo = nft_weights::WeightInfo;
+ type Currency = Balances;
+ type CollectionCreationPrice = CollectionCreationPrice;
+ type TreasuryAccountId = TreasuryAccountId;
}
construct_runtime!(
runtime_types.jsondiffbeforeafterboth--- a/runtime_types.json
+++ b/runtime_types.json
@@ -31,6 +31,13 @@
"ConstData": "Vec<u8>",
"VariableData": "Vec<u8>"
},
+ "SponsorshipState": {
+ "_enum": {
+ "Disabled": null,
+ "Unconfirmed": "AccountId",
+ "Confirmed": "AccountId"
+ }
+ },
"CollectionType": {
"Owner": "AccountId",
"Mode": "CollectionMode",
@@ -42,8 +49,7 @@
"MintMode": "bool",
"OffchainSchema": "Vec<u8>",
"SchemaVersion": "SchemaVersion",
- "Sponsor": "AccountId",
- "SponsorConfirmed": "bool",
+ "Sponsorship": "SponsorshipState",
"Limits": "CollectionLimits",
"VariableOnChainSchema": "Vec<u8>",
"ConstOnChainSchema": "Vec<u8>"
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -25,7 +25,10 @@
"testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",
"testSetVariableMetaData": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetaData.test.ts",
"testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
+ "testSetCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionSponsor.test.ts",
+ "testConfirmSponsorship": "mocha --timeout 9999999 -r ts-node/register ./**/confirmSponsorship.test.ts",
"testRemoveCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionAdmin.test.ts",
+ "testRemoveCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionSponsor.test.ts",
"testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",
"testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",
"testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -1,59 +1,59 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import { default as usingApi } from './substrate/substrate-api';
-import { createCollectionExpectFailure, createCollectionExpectSuccess } from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-describe('integration test: ext. createCollection():', () => {
- it('Create new NFT collection', async () => {
- await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
- });
- it('Create new NFT collection whith collection_name of maximum length (64 bytes)', async () => {
- await createCollectionExpectSuccess({name: 'A'.repeat(64)});
- });
- it('Create new NFT collection whith collection_description of maximum length (256 bytes)', async () => {
- await createCollectionExpectSuccess({description: 'A'.repeat(256)});
- });
- it('Create new NFT collection whith token_prefix of maximum length (16 bytes)', async () => {
- await createCollectionExpectSuccess({tokenPrefix: 'A'.repeat(16)});
- });
- it('Create new Fungible collection', async () => {
- await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- });
- it('Create new ReFungible collection', async () => {
- await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- });
-});
-
-describe('(!negative test!) integration test: ext. createCollection():', () => {
- it('(!negative test!) create new NFT collection whith incorrect data (mode)', async () => {
- await usingApi(async (api) => {
- const AcollectionCount = parseInt((await api.query.nft.collectionCount()).toString(), 10);
-
- const badTransaction = async () => {
- await createCollectionExpectSuccess({mode: {type: 'Invalid'}});
- };
- // tslint:disable-next-line:no-unused-expression
- expect(badTransaction()).to.be.rejected;
-
- const BcollectionCount = parseInt((await api.query.nft.collectionCount()).toString(), 10);
- expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Incorrect collection created.');
- });
- });
- it('(!negative test!) create new NFT collection whith incorrect data (collection_name)', async () => {
- await createCollectionExpectFailure({ name: 'A'.repeat(65), mode: {type: 'NFT'}});
- });
- it('(!negative test!) create new NFT collection whith incorrect data (collection_description)', async () => {
- await createCollectionExpectFailure({ description: 'A'.repeat(257), mode: { type: 'NFT' }});
- });
- it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
- await createCollectionExpectFailure({tokenPrefix: 'A'.repeat(17), mode: {type: 'NFT'}});
- });
-});
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import { default as usingApi } from './substrate/substrate-api';
+import { createCollectionExpectFailure, createCollectionExpectSuccess } from './util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('integration test: ext. createCollection():', () => {
+ it('Create new NFT collection', async () => {
+ await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
+ });
+ it('Create new NFT collection whith collection_name of maximum length (64 bytes)', async () => {
+ await createCollectionExpectSuccess({name: 'A'.repeat(64)});
+ });
+ it('Create new NFT collection whith collection_description of maximum length (256 bytes)', async () => {
+ await createCollectionExpectSuccess({description: 'A'.repeat(256)});
+ });
+ it('Create new NFT collection whith token_prefix of maximum length (16 bytes)', async () => {
+ await createCollectionExpectSuccess({tokenPrefix: 'A'.repeat(16)});
+ });
+ it('Create new Fungible collection', async () => {
+ await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+ });
+ it('Create new ReFungible collection', async () => {
+ await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+ });
+});
+
+describe('(!negative test!) integration test: ext. createCollection():', () => {
+ it('(!negative test!) create new NFT collection whith incorrect data (mode)', async () => {
+ await usingApi(async (api) => {
+ const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);
+
+ const badTransaction = async () => {
+ await createCollectionExpectSuccess({mode: {type: 'Invalid'}});
+ };
+ // tslint:disable-next-line:no-unused-expression
+ expect(badTransaction()).to.be.rejected;
+
+ const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);
+ expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Incorrect collection created.');
+ });
+ });
+ it('(!negative test!) create new NFT collection whith incorrect data (collection_name)', async () => {
+ await createCollectionExpectFailure({ name: 'A'.repeat(65), mode: {type: 'NFT'}});
+ });
+ it('(!negative test!) create new NFT collection whith incorrect data (collection_description)', async () => {
+ await createCollectionExpectFailure({ description: 'A'.repeat(257), mode: { type: 'NFT' }});
+ });
+ it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
+ await createCollectionExpectFailure({tokenPrefix: 'A'.repeat(17), mode: {type: 'NFT'}});
+ });
+});
tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -25,6 +25,7 @@
const Treasury = "5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z";
const saneMinimumFee = 0.05;
const saneMaximumFee = 0.5;
+const createCollectionDeposit = 100;
let alice: IKeyringPair;
let bob: IKeyringPair;
@@ -127,8 +128,8 @@
const aliceBalanceAfter = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());
const fee = aliceBalanceBefore.minus(aliceBalanceAfter);
- expect(fee.dividedBy(1e15).toNumber()).to.be.lessThan(saneMaximumFee);
- expect(fee.dividedBy(1e15).toNumber()).to.be.greaterThan(saneMinimumFee);
+ expect(fee.dividedBy(1e15).toNumber()).to.be.lessThan(saneMaximumFee + createCollectionDeposit);
+ expect(fee.dividedBy(1e15).toNumber()).to.be.greaterThan(saneMinimumFee + createCollectionDeposit);
});
});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -377,8 +377,9 @@
// What to expect
expect(result.success).to.be.true;
- expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());
- expect(collection.SponsorConfirmed).to.be.false;
+ expect(collection.Sponsorship).to.deep.equal({
+ Unconfirmed: sponsor.toString(),
+ });
});
}
@@ -396,8 +397,7 @@
// What to expect
expect(result.success).to.be.true;
- expect(collection.Sponsor).to.be.equal(nullPublicKey);
- expect(collection.SponsorConfirmed).to.be.false;
+ expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });
});
}
@@ -435,8 +435,9 @@
// What to expect
expect(result.success).to.be.true;
- expect(collection.Sponsor).to.be.equal(sender.address);
- expect(collection.SponsorConfirmed).to.be.true;
+ expect(collection.Sponsorship).to.be.deep.equal({
+ Confirmed: sender.address,
+ });
});
}