difftreelog
Merge branch 'develop' into feature/NFTPAR-196_sponsor_setVariableMetadata
in: master
10 files changed
.github/workflows/notify.ymldiffbeforeafterboth--- a/.github/workflows/notify.yml
+++ b/.github/workflows/notify.yml
@@ -6,8 +6,8 @@
build:
runs-on: ubuntu-latest
steps:
- - uses: avkviring/telegram-github-action@v0.0.8
+ - uses: avkviring/telegram-github-action@v0.0.13
env:
telegram_to: ${{ secrets.TELEGRAM_TO }}
telegram_token: ${{ secrets.TELEGRAM_TOKEN }}
- event: ${{ toJson(github.event) }}
\ No newline at end of file
+ event: ${{ toJson(github.event) }}
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.rsdiffbeforeafterboth21 ensure, fail, parameter_types,21 ensure, fail, parameter_types,22 traits::{22 traits::{23 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,23 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,24 Randomness, IsSubType,24 Randomness, IsSubType, WithdrawReasons,25 },25 },26 weights::{26 weights::{27 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},27 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},28 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,28 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,29 WeightToFeePolynomial, DispatchClass,29 WeightToFeePolynomial, DispatchClass,30 },30 },31 StorageValue,31 StorageValue,32 transactional,32};33};333434use frame_system::{self as system, ensure_signed, ensure_root};35use frame_system::{self as system, ensure_signed, ensure_root};124 pub fraction: u128,125 pub fraction: u128,125}126}126127128#[derive(Encode, Decode, Debug, Clone, PartialEq)]129#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]130pub enum SponsorshipState<AccountId> {131 /// The fees are applied to the transaction sender132 Disabled,133 Unconfirmed(AccountId),134 /// Transactions are sponsored by specified account135 Confirmed(AccountId),136}137138impl<AccountId> SponsorshipState<AccountId> {139 fn sponsor(&self) -> Option<&AccountId> {140 match self {141 Self::Confirmed(sponsor) => Some(sponsor),142 _ => None,143 }144 }145146 fn pending_sponsor(&self) -> Option<&AccountId> {147 match self {148 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),149 _ => None,150 }151 }152153 fn confirmed(&self) -> bool {154 matches!(self, Self::Confirmed(_))155 }156}157158impl<T> Default for SponsorshipState<T> {159 fn default() -> Self {160 Self::Disabled161 }162}163127#[derive(Encode, Decode, Clone, PartialEq)]164#[derive(Encode, Decode, Clone, PartialEq)]128#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]165#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]129pub struct Collection<T: Config> {166pub struct Collection<T: Config> {137 pub mint_mode: bool,174 pub mint_mode: bool,138 pub offchain_schema: Vec<u8>,175 pub offchain_schema: Vec<u8>,139 pub schema_version: SchemaVersion,176 pub schema_version: SchemaVersion,140 pub sponsor: T::AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender177 pub sponsorship: SponsorshipState<AccountId>,141 pub sponsor_confirmed: bool, // False if sponsor address has not yet confirmed sponsorship. True otherwise.142 pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions 178 pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions 143 pub variable_on_chain_schema: Vec<u8>, //179 pub variable_on_chain_schema: Vec<u8>, //144 pub const_on_chain_schema: Vec<u8>, //180 pub const_on_chain_schema: Vec<u8>, //413 /// Schema data size limit bound exceeded449 /// Schema data size limit bound exceeded414 SchemaDataLimitExceeded,450 SchemaDataLimitExceeded,415 /// Maximum refungibility exceeded451 /// Maximum refungibility exceeded416 WrongRefungiblePieces452 WrongRefungiblePieces,453 /// createRefungible should be called with one owner454 BadCreateRefungibleCall,417 }455 }418}456}419457422460423 /// Weight information for extrinsics in this pallet.461 /// Weight information for extrinsics in this pallet.424 type WeightInfo: WeightInfo;462 type WeightInfo: WeightInfo;463464 type Currency: Currency<Self::AccountId>;465 type CollectionCreationPrice: Get<<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance>;466 type TreasuryAccountId: Get<Self::AccountId>;425}467}426468427#[cfg(feature = "runtime-benchmarks")]469#[cfg(feature = "runtime-benchmarks")]428mod benchmarking;470mod benchmarking;429471430// #endregion472// #endregion431473474// # Used definitions475//476// ## User control levels477//478// chain-controlled - key is uncontrolled by user479// i.e autoincrementing index480// can use non-cryptographic hash481// real - key is controlled by user482// but it is hard to generate enough colliding values, i.e owner of signed txs483// can use non-cryptographic hash484// controlled - key is completly controlled by users485// i.e maps with mutable keys486// should use cryptographic hash487//488// ## User control level downgrade reasons489//490// ?1 - chain-controlled -> controlled491// collections/tokens can be destroyed, resulting in massive holes492// ?2 - chain-controlled -> controlled493// same as ?1, but can be only added, resulting in easier exploitation494// ?3 - real -> controlled495// no confirmation required, so addresses can be easily generated432decl_storage! {496decl_storage! {433 trait Store for Module<T: Config> as Nft {497 trait Store for Module<T: Config> as Nft {434498435 // Private members499 //#region Private members436 NextCollectionID: CollectionId;500 /// Id of next collection437 CreatedCollectionCount: u32;501 CreatedCollectionCount: u32;502 /// Used for migrations438 ChainVersion: u64;503 ChainVersion: u64;439 ItemListIndex: map hasher(identity) CollectionId => TokenId;504 /// Id of last collection token505 /// Collection id (controlled?1)506 ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;507 //#endregion440508441 // Chain limits struct509 //#region Chain limits struct442 pub ChainLimit get(fn chain_limit) config(): ChainLimits;510 pub ChainLimit get(fn chain_limit) config(): ChainLimits;511 //#endregion443512444 // Bound counters513 //#region Bound counters445 CollectionCount: u32;514 /// Amount of collections destroyed, used for total amount tracking with515 /// CreatedCollectionCount516 DestroyedCollectionCount: u32;517 /// Total amount of account owned tokens (NFTs + RFTs + unique fungibles)518 /// Account id (real)446 pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;519 pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;520 //#endregion447521448 // Basic collections522 //#region Basic collections449 pub CollectionById get(fn collection_id) config(): map hasher(identity) CollectionId => Option<Collection<T>> = None;523 /// Collection info524 /// Collection id (controlled?1)525 pub CollectionById get(fn collection_id) config(): map hasher(blake2_128_concat) CollectionId => Option<Collection<T>> = None;450 pub AdminList get(fn admin_list_collection): map hasher(identity) CollectionId => Vec<T::AccountId>;526 /// List of collection admins527 /// Collection id (controlled?2)528 pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::AccountId>;451 pub WhiteList get(fn white_list): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => bool;529 /// Whitelisted collection users530 /// Collection id (controlled?2), user id (controlled?3)531 pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;532 //#endregion452533453 /// Balance owner per collection map534 /// How many of collection items user have535 /// Collection id (controlled?2), account id (real)454 pub Balance get(fn balance_count): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => u128;536 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => u128;455537456 /// second parameter: item id + owner account id + spender account id538 /// Amount of items which spender can transfer out of owners account (via transferFrom)539 /// Collection id (controlled?2), (token id (controlled ?2) + owner account id (real) + spender account id (controlled?3))457 pub Allowances get(fn approved): double_map hasher(identity) CollectionId, hasher(twox_64_concat) (TokenId, T::AccountId, T::AccountId) => u128;540 pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;458541459 /// Item collections542 //#region Item collections460 pub NftItemList get(fn nft_item_id) config(): double_map hasher(identity) CollectionId, hasher(identity) TokenId => NftItemType<T::AccountId>;543 /// Collection id (controlled?2), token id (controlled?1)544 pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => NftItemType<T::AccountId>;461 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => FungibleItemType;545 /// Collection id (controlled?2), owner (controlled?2)546 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;462 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(identity) CollectionId, hasher(identity) TokenId => ReFungibleItemType<T::AccountId>;547 /// Collection id (controlled?2), token id (controlled?1)548 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => ReFungibleItemType<T::AccountId>;549 //#endregion463550464 /// Index list551 //#region Index list465 pub AddressTokens get(fn address_tokens): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => Vec<TokenId>;552 /// Collection id (controlled?2), tokens owner (controlled?2)553 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => Vec<TokenId>;554 //#endregion466555467 /// Tokens transfer baskets556 //#region Tokens transfer rate limit baskets468 pub CreateItemBasket get(fn create_item_basket): map hasher(twox_64_concat) (CollectionId, T::AccountId) => T::BlockNumber;557 /// (Collection id (controlled?2), who created (real))558 pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;469 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => T::BlockNumber;559 /// Collection id (controlled?2), token id (controlled?2)560 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;470 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;561 /// Collection id (controlled?2), owning user (real)562 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;471 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => T::BlockNumber;563 /// Collection id (controlled?2), token id (controlled?2)564 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;565 //#endregion472566473 /// Variable metadata sponsoring567 /// Variable metadata sponsoring474 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => Option<T::BlockNumber> = None;568 /// Collection id (controlled?2), token id (controlled?2)475569 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;570 476 // Contract Sponsorship and Ownership571 //#region Contract Sponsorship and Ownership572 /// Contract address (real)477 pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => T::AccountId;573 pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => T::AccountId;574 /// Contract address (real)478 pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;575 pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;576 /// (Contract address(real), caller (real))479 pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;577 pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;578 /// Contract address (real)480 pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;579 pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;580 /// Contract address (real)481 pub ContractWhiteListEnabled get(fn contract_white_list_enabled): map hasher(twox_64_concat) T::AccountId => bool; 581 pub ContractWhiteListEnabled get(fn contract_white_list_enabled): map hasher(twox_64_concat) T::AccountId => bool; 482 pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(twox_64_concat) T::AccountId => bool; 582 /// Contract address (real) => Whitelisted user (controlled?3)583 pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) T::AccountId => bool; 584 //#endregion483 }585 }484 add_extra_genesis {586 add_extra_genesis {485 build(|config: &GenesisConfig<T>| {587 build(|config: &GenesisConfig<T>| {563 type Error = Error<T>;665 type Error = Error<T>;564666565 fn on_initialize(now: T::BlockNumber) -> Weight {667 fn on_initialize(now: T::BlockNumber) -> Weight {566567 if ChainVersion::get() < 2568 {569 let value = NextCollectionID::get();570 CreatedCollectionCount::put(value);571 ChainVersion::put(2);572 }573574 0668 0575 }669 }576670591 /// * mode: [CollectionMode] collection type and type dependent data.685 /// * mode: [CollectionMode] collection type and type dependent data.592 // returns collection ID686 // returns collection ID593 #[weight = <T as Config>::WeightInfo::create_collection()]687 #[weight = <T as Config>::WeightInfo::create_collection()]688 #[transactional]594 pub fn create_collection(origin,689 pub fn create_collection(origin,595 collection_name: Vec<u16>,690 collection_name: Vec<u16>,596 collection_description: Vec<u16>,691 collection_description: Vec<u16>,600 // Anyone can create a collection695 // Anyone can create a collection601 let who = ensure_signed(origin)?;696 let who = ensure_signed(origin)?;602697698 // Take a (non-refundable) deposit of collection creation699 let mut imbalance = <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();700 imbalance.subsume(<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(701 &T::TreasuryAccountId::get(),702 T::CollectionCreationPrice::get(),703 ));704 <T as Config>::Currency::settle(705 &who,706 imbalance,707 WithdrawReasons::TRANSFER,708 ExistenceRequirement::KeepAlive,709 ).map_err(|_| Error::<T>::NoPermission)?;710603 let decimal_points = match mode {711 let decimal_points = match mode {604 CollectionMode::Fungible(points) => points,712 CollectionMode::Fungible(points) => points,605 _ => 0713 _ => 0606 };714 };607715608 let chain_limit = ChainLimit::get();716 let chain_limit = ChainLimit::get();609717718 let created_count = CreatedCollectionCount::get();719 let destroyed_count = DestroyedCollectionCount::get();720610 // bound Total number of collections721 // bound Total number of collections611 ensure!(CollectionCount::get() < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);722 ensure!(created_count - destroyed_count < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);612723613 // check params724 // check params614 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);725 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);617 ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);728 ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);618729619 // Generate next collection ID730 // Generate next collection ID620 let next_id = CreatedCollectionCount::get()731 let next_id = created_count621 .checked_add(1)732 .checked_add(1)622 .ok_or(Error::<T>::NumOverflow)?;733 .ok_or(Error::<T>::NumOverflow)?;623734624 // bound counter625 let total = CollectionCount::get()626 .checked_add(1)627 .ok_or(Error::<T>::NumOverflow)?;628629 CreatedCollectionCount::put(next_id);735 CreatedCollectionCount::put(next_id);630 CollectionCount::put(total);631736632 let limits = CollectionLimits {737 let limits = CollectionLimits {633 sponsored_data_size: chain_limit.custom_data_limit,738 sponsored_data_size: chain_limit.custom_data_limit,646 token_prefix: token_prefix,751 token_prefix: token_prefix,647 offchain_schema: Vec::new(),752 offchain_schema: Vec::new(),648 schema_version: SchemaVersion::ImageURL,753 schema_version: SchemaVersion::ImageURL,649 sponsor: T::AccountId::default(),754 sponsorship: SponsorshipState::Disabled,650 sponsor_confirmed: false,651 variable_on_chain_schema: Vec::new(),755 variable_on_chain_schema: Vec::new(),652 const_on_chain_schema: Vec::new(),756 const_on_chain_schema: Vec::new(),653 limits,757 limits,672 /// 776 /// 673 /// * collection_id: collection to destroy.777 /// * collection_id: collection to destroy.674 #[weight = <T as Config>::WeightInfo::destroy_collection()]778 #[weight = <T as Config>::WeightInfo::destroy_collection()]779 #[transactional]675 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {780 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {676781677 let sender = ensure_signed(origin)?;782 let sender = ensure_signed(origin)?;699804700 <VariableMetaDataBasket<T>>::remove_prefix(collection_id);805 <VariableMetaDataBasket<T>>::remove_prefix(collection_id);701806702 if CollectionCount::get() > 0807 DestroyedCollectionCount::put(DestroyedCollectionCount::get()703 {704 // bound couter705 let total = CollectionCount::get()706 .checked_sub(1)808 .checked_add(1)707 .ok_or(Error::<T>::NumOverflow)?;809 .ok_or(Error::<T>::NumOverflow)?);708810709 CollectionCount::put(total);710 }711712 Ok(())811 Ok(())713 }812 }714813725 /// 824 /// 726 /// * address.825 /// * address.727 #[weight = <T as Config>::WeightInfo::add_to_white_list()]826 #[weight = <T as Config>::WeightInfo::add_to_white_list()]827 #[transactional]728 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{828 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{729829730 let sender = ensure_signed(origin)?;830 let sender = ensure_signed(origin)?;749 /// 849 /// 750 /// * address.850 /// * address.751 #[weight = <T as Config>::WeightInfo::remove_from_white_list()]851 #[weight = <T as Config>::WeightInfo::remove_from_white_list()]852 #[transactional]752 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{853 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{753854754 let sender = ensure_signed(origin)?;855 let sender = ensure_signed(origin)?;772 /// 873 /// 773 /// * mode: [AccessMode]874 /// * mode: [AccessMode]774 #[weight = <T as Config>::WeightInfo::set_public_access_mode()]875 #[weight = <T as Config>::WeightInfo::set_public_access_mode()]876 #[transactional]775 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult877 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult776 {878 {777 let sender = ensure_signed(origin)?;879 let sender = ensure_signed(origin)?;798 /// 900 /// 799 /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.901 /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.800 #[weight = <T as Config>::WeightInfo::set_mint_permission()]902 #[weight = <T as Config>::WeightInfo::set_mint_permission()]903 #[transactional]801 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult904 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult802 {905 {803 let sender = ensure_signed(origin)?;906 let sender = ensure_signed(origin)?;822 /// 925 /// 823 /// * new_owner.926 /// * new_owner.824 #[weight = <T as Config>::WeightInfo::change_collection_owner()]927 #[weight = <T as Config>::WeightInfo::change_collection_owner()]928 #[transactional]825 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {929 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {826930827 let sender = ensure_signed(origin)?;931 let sender = ensure_signed(origin)?;847 /// 951 /// 848 /// * new_admin_id: Address of new admin to add.952 /// * new_admin_id: Address of new admin to add.849 #[weight = <T as Config>::WeightInfo::add_collection_admin()]953 #[weight = <T as Config>::WeightInfo::add_collection_admin()]954 #[transactional]850 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::AccountId) -> DispatchResult {955 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::AccountId) -> DispatchResult {851956852 let sender = ensure_signed(origin)?;957 let sender = ensure_signed(origin)?;882 /// 987 /// 883 /// * account_id: Address of admin to remove.988 /// * account_id: Address of admin to remove.884 #[weight = <T as Config>::WeightInfo::remove_collection_admin()]989 #[weight = <T as Config>::WeightInfo::remove_collection_admin()]990 #[transactional]885 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::AccountId) -> DispatchResult {991 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::AccountId) -> DispatchResult {886992887 let sender = ensure_signed(origin)?;993 let sender = ensure_signed(origin)?;906 /// 1012 /// 907 /// * new_sponsor.1013 /// * new_sponsor.908 #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]1014 #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]1015 #[transactional]909 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {1016 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {9101017911 let sender = ensure_signed(origin)?;1018 let sender = ensure_signed(origin)?;912 let mut target_collection = Self::get_collection(collection_id)?;1019 let mut target_collection = Self::get_collection(collection_id)?;913 Self::check_owner_permissions(&target_collection, sender)?;1020 Self::check_owner_permissions(&target_collection, sender)?;9141021915 target_collection.sponsor = new_sponsor;1022 target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);916 target_collection.sponsor_confirmed = false;917 Self::save_collection(target_collection);1023 Self::save_collection(target_collection);9181024919 Ok(())1025 Ok(())927 /// 1033 /// 928 /// * collection_id.1034 /// * collection_id.929 #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]1035 #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]1036 #[transactional]930 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {1037 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {9311038932 let sender = ensure_signed(origin)?;1039 let sender = ensure_signed(origin)?;9331040934 let mut target_collection = Self::get_collection(collection_id)?;1041 let mut target_collection = Self::get_collection(collection_id)?;935 ensure!(sender == target_collection.sponsor, Error::<T>::ConfirmUnsetSponsorFail);1042 ensure!(1043 target_collection.sponsorship.pending_sponsor() == Some(&sender),1044 Error::<T>::ConfirmUnsetSponsorFail1045 );9361046937 target_collection.sponsor_confirmed = true;1047 target_collection.sponsorship = SponsorshipState::Confirmed(sender);938 Self::save_collection(target_collection);1048 Self::save_collection(target_collection);9391049940 Ok(())1050 Ok(())950 /// 1060 /// 951 /// * collection_id.1061 /// * collection_id.952 #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]1062 #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]1063 #[transactional]953 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {1064 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {9541065955 let sender = ensure_signed(origin)?;1066 let sender = ensure_signed(origin)?;9561067957 let mut target_collection = Self::get_collection(collection_id)?;1068 let mut target_collection = Self::get_collection(collection_id)?;958 Self::check_owner_permissions(&target_collection, sender)?;1069 Self::check_owner_permissions(&target_collection, sender)?;9591070960 target_collection.sponsor = T::AccountId::default();1071 target_collection.sponsorship = SponsorshipState::Disabled;961 target_collection.sponsor_confirmed = false;962 Self::save_collection(target_collection);1072 Self::save_collection(target_collection);9631073964 Ok(())1074 Ok(())989 // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]1099 // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]9901100991 #[weight = <T as Config>::WeightInfo::create_item(data.len())]1101 #[weight = <T as Config>::WeightInfo::create_item(data.len())]1102 #[transactional]992 pub fn create_item(origin, collection_id: CollectionId, owner: T::AccountId, data: CreateItemData) -> DispatchResult {1103 pub fn create_item(origin, collection_id: CollectionId, owner: T::AccountId, data: CreateItemData) -> DispatchResult {9931104994 let sender = ensure_signed(origin)?;1105 let sender = ensure_signed(origin)?;1002 Ok(())1113 Ok(())1003 }1114 }100411151005 /// This method creates multiple instances of NFT Collection created with CreateCollection method.1116 /// This method creates multiple items in a collection created with CreateCollection method.1006 /// 1117 /// 1007 /// # Permissions1118 /// # Permissions1008 /// 1119 /// 1023 #[weight = <T as Config>::WeightInfo::create_item(items_data.into_iter()1134 #[weight = <T as Config>::WeightInfo::create_item(items_data.into_iter()1024 .map(|data| { data.len() })1135 .map(|data| { data.len() })1025 .sum())]1136 .sum())]1137 #[transactional]1026 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::AccountId, items_data: Vec<CreateItemData>) -> DispatchResult {1138 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::AccountId, items_data: Vec<CreateItemData>) -> DispatchResult {102711391028 ensure!(items_data.len() > 0, Error::<T>::EmptyArgument);1140 ensure!(items_data.len() > 0, Error::<T>::EmptyArgument);1056 /// 1168 /// 1057 /// * item_id: ID of NFT to burn.1169 /// * item_id: ID of NFT to burn.1058 #[weight = <T as Config>::WeightInfo::burn_item()]1170 #[weight = <T as Config>::WeightInfo::burn_item()]1171 #[transactional]1059 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {1172 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {106011731061 let sender = ensure_signed(origin)?;1174 let sender = ensure_signed(origin)?;1113 /// * Fungible Mode: Must specify transferred amount1226 /// * Fungible Mode: Must specify transferred amount1114 /// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)1227 /// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)1115 #[weight = <T as Config>::WeightInfo::transfer()]1228 #[weight = <T as Config>::WeightInfo::transfer()]1229 #[transactional]1116 pub fn transfer(origin, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {1230 pub fn transfer(origin, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {1117 let sender = ensure_signed(origin)?;1231 let sender = ensure_signed(origin)?;1118 let collection = Self::get_collection(collection_id)?;1232 let collection = Self::get_collection(collection_id)?;1136 /// 1250 /// 1137 /// * item_id: ID of the item.1251 /// * item_id: ID of the item.1138 #[weight = <T as Config>::WeightInfo::approve()]1252 #[weight = <T as Config>::WeightInfo::approve()]1253 #[transactional]1139 pub fn approve(origin, spender: T::AccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {1254 pub fn approve(origin, spender: T::AccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {114012551141 let sender = ensure_signed(origin)?;1256 let sender = ensure_signed(origin)?;1200 /// 1315 /// 1201 /// * value: Amount to transfer.1316 /// * value: Amount to transfer.1202 #[weight = <T as Config>::WeightInfo::transfer_from()]1317 #[weight = <T as Config>::WeightInfo::transfer_from()]1318 #[transactional]1203 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {1319 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {120413201205 let sender = ensure_signed(origin)?;1321 let sender = ensure_signed(origin)?;1234 }1350 }123513511236 // Reduce approval by transferred amount or remove if remaining approval drops to 01352 // Reduce approval by transferred amount or remove if remaining approval drops to 01237 if approval.checked_sub(value).unwrap_or(0) > 0 {1353 if approval.saturating_sub(value) > 0 {1238 <Allowances<T>>::insert(collection_id, (item_id, &from, &sender), approval - value);1354 <Allowances<T>>::insert(collection_id, (item_id, &from, &sender), approval - value);1239 }1355 }1240 else {1356 else {1280 /// 1396 /// 1281 /// * schema: String representing the offchain data schema.1397 /// * schema: String representing the offchain data schema.1282 #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1398 #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1399 #[transactional]1283 pub fn set_variable_meta_data (1400 pub fn set_variable_meta_data (1284 origin,1401 origin,1285 collection_id: CollectionId,1402 collection_id: CollectionId,1324 /// 1441 /// 1325 /// * schema: SchemaVersion: enum1442 /// * schema: SchemaVersion: enum1326 #[weight = <T as Config>::WeightInfo::set_schema_version()]1443 #[weight = <T as Config>::WeightInfo::set_schema_version()]1444 #[transactional]1327 pub fn set_schema_version(1445 pub fn set_schema_version(1328 origin,1446 origin,1329 collection_id: CollectionId,1447 collection_id: CollectionId,1351 /// 1469 /// 1352 /// * schema: String representing the offchain data schema.1470 /// * schema: String representing the offchain data schema.1353 #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1471 #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1472 #[transactional]1354 pub fn set_offchain_schema(1473 pub fn set_offchain_schema(1355 origin,1474 origin,1356 collection_id: CollectionId,1475 collection_id: CollectionId,1382 /// 1501 /// 1383 /// * schema: String representing the const on-chain data schema.1502 /// * schema: String representing the const on-chain data schema.1384 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1503 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1504 #[transactional]1385 pub fn set_const_on_chain_schema (1505 pub fn set_const_on_chain_schema (1386 origin,1506 origin,1387 collection_id: CollectionId,1507 collection_id: CollectionId,1413 /// 1533 /// 1414 /// * schema: String representing the variable on-chain data schema.1534 /// * schema: String representing the variable on-chain data schema.1415 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1535 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1536 #[transactional]1416 pub fn set_variable_on_chain_schema (1537 pub fn set_variable_on_chain_schema (1417 origin,1538 origin,1418 collection_id: CollectionId,1539 collection_id: CollectionId,143315541434 // Sudo permissions function1555 // Sudo permissions function1435 #[weight = <T as Config>::WeightInfo::set_chain_limits()]1556 #[weight = <T as Config>::WeightInfo::set_chain_limits()]1557 #[transactional]1436 pub fn set_chain_limits(1558 pub fn set_chain_limits(1437 origin,1559 origin,1438 limits: ChainLimits1560 limits: ChainLimits1457 /// * enable flag1579 /// * enable flag1458 /// 1580 /// 1459 #[weight = <T as Config>::WeightInfo::enable_contract_sponsoring()]1581 #[weight = <T as Config>::WeightInfo::enable_contract_sponsoring()]1582 #[transactional]1460 pub fn enable_contract_sponsoring(1583 pub fn enable_contract_sponsoring(1461 origin,1584 origin,1462 contract_address: T::AccountId,1585 contract_address: T::AccountId,1492 /// -`rate_limit`: Number of blocks to wait until the next sponsored transaction is allowed1615 /// -`rate_limit`: Number of blocks to wait until the next sponsored transaction is allowed1493 /// 1616 /// 1494 #[weight = <T as Config>::WeightInfo::set_contract_sponsoring_rate_limit()]1617 #[weight = <T as Config>::WeightInfo::set_contract_sponsoring_rate_limit()]1618 #[transactional]1495 pub fn set_contract_sponsoring_rate_limit(1619 pub fn set_contract_sponsoring_rate_limit(1496 origin,1620 origin,1497 contract_address: T::AccountId,1621 contract_address: T::AccountId,1519 /// 1643 /// 1520 /// - `enable`: . 1644 /// - `enable`: . 1521 #[weight = <T as Config>::WeightInfo::toggle_contract_white_list()]1645 #[weight = <T as Config>::WeightInfo::toggle_contract_white_list()]1646 #[transactional]1522 pub fn toggle_contract_white_list(1647 pub fn toggle_contract_white_list(1523 origin,1648 origin,1524 contract_address: T::AccountId,1649 contract_address: T::AccountId,1546 ///1671 ///1547 /// -`account_address`: Address to add.1672 /// -`account_address`: Address to add.1548 #[weight = <T as Config>::WeightInfo::add_to_contract_white_list()]1673 #[weight = <T as Config>::WeightInfo::add_to_contract_white_list()]1674 #[transactional]1549 pub fn add_to_contract_white_list(1675 pub fn add_to_contract_white_list(1550 origin,1676 origin,1551 contract_address: T::AccountId,1677 contract_address: T::AccountId,1573 ///1699 ///1574 /// -`account_address`: Address to remove.1700 /// -`account_address`: Address to remove.1575 #[weight = <T as Config>::WeightInfo::remove_from_contract_white_list()]1701 #[weight = <T as Config>::WeightInfo::remove_from_contract_white_list()]1702 #[transactional]1576 pub fn remove_from_contract_white_list(1703 pub fn remove_from_contract_white_list(1577 origin,1704 origin,1578 contract_address: T::AccountId,1705 contract_address: T::AccountId,1589 }1716 }159017171591 #[weight = <T as Config>::WeightInfo::set_collection_limits()]1718 #[weight = <T as Config>::WeightInfo::set_collection_limits()]1719 #[transactional]1592 pub fn set_collection_limits(1720 pub fn set_collection_limits(1593 origin,1721 origin,1594 collection_id: u32,1722 collection_id: u32,1755 }1883 }1756 };1884 };175718851758 // call event1759 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id), owner));17601761 Ok(())1886 Ok(())1762 }1887 }176318881782 .ok_or(Error::<T>::NumOverflow)?;1907 .ok_or(Error::<T>::NumOverflow)?;1783 <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);1908 <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);178419091910 Self::deposit_event(RawEvent::ItemCreated(collection_id, 0, owner.clone()));1785 Ok(())1911 Ok(())1786 }1912 }178719131793 .ok_or(Error::<T>::NumOverflow)?;1919 .ok_or(Error::<T>::NumOverflow)?;1794 let itemcopy = item.clone();1920 let itemcopy = item.clone();179519211796 let value = item.owner.first().unwrap().fraction;1922 ensure!(1923 item.owner.len() == 1,1924 Error::<T>::BadCreateRefungibleCall,1925 );1797 let owner = item.owner.first().unwrap().owner.clone();1926 let item_owner = item.owner.first().expect("only one owner is defined");179819271928 let value = item_owner.fraction;1929 let owner = item_owner.owner.clone();19301799 Self::add_token_index(collection_id, current_index, &owner)?;1931 Self::add_token_index(collection_id, current_index, &owner)?;180019321801 <ItemListIndex>::insert(collection_id, current_index);1933 <ItemListIndex>::insert(collection_id, current_index);1807 .ok_or(Error::<T>::NumOverflow)?;1939 .ok_or(Error::<T>::NumOverflow)?;1808 <Balance<T>>::insert(collection_id, owner.clone(), new_balance);1940 <Balance<T>>::insert(collection_id, owner.clone(), new_balance);180919411942 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, owner));1810 Ok(())1943 Ok(())1811 }1944 }181219451829 .ok_or(Error::<T>::NumOverflow)?;1962 .ok_or(Error::<T>::NumOverflow)?;1830 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);1963 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);183119641965 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, item_owner));1832 Ok(())1966 Ok(())1833 }1967 }183419681847 let rft_balance = token1981 let rft_balance = token1848 .owner1982 .owner1849 .iter()1983 .iter()1850 .filter(|&i| i.owner == *owner)1984 .find(|&i| i.owner == *owner)1851 .next()1985 .ok_or(Error::<T>::TokenNotFound)?;1852 .unwrap();1853 Self::remove_token_index(collection_id, item_id, owner)?;1986 Self::remove_token_index(collection_id, item_id, owner)?;185419871855 // update balance1988 // update balance1863 .owner1996 .owner1864 .iter()1997 .iter()1865 .position(|i| i.owner == *owner)1998 .position(|i| i.owner == *owner)1866 .unwrap();1999 .expect("owned item is exists");1867 token.owner.remove(index);2000 token.owner.remove(index);1868 let owner_count = token.owner.len();2001 let owner_count = token.owner.len();186920022100 .iter()2233 .iter()2101 .filter(|i| i.owner == owner)2234 .filter(|i| i.owner == owner)2102 .next()2235 .next()2103 .ok_or(Error::<T>::NumOverflow)?;2236 .ok_or(Error::<T>::TokenNotFound)?;2104 let amount = item.fraction;2237 let amount = item.fraction;210522382106 ensure!(amount >= value, Error::<T>::TokenValueTooLow);2239 ensure!(amount >= value, Error::<T>::TokenValueTooLow);2111 .ok_or(Error::<T>::NumOverflow)?;2244 .ok_or(Error::<T>::NumOverflow)?;2112 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);2245 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);211322462114 let balancenew_owner = <Balance<T>>::get(collection_id, new_owner.clone())2247 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())2115 .checked_add(value)2248 .checked_add(value)2116 .ok_or(Error::<T>::NumOverflow)?;2249 .ok_or(Error::<T>::NumOverflow)?;2117 <Balance<T>>::insert(collection_id, new_owner.clone(), balancenew_owner);2250 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);211822512119 let old_owner = item.owner.clone();2252 let old_owner = item.owner.clone();2120 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);2253 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);2128 .owner2261 .owner2129 .iter_mut()2262 .iter_mut()2130 .find(|i| i.owner == owner)2263 .find(|i| i.owner == owner)2131 .unwrap()2264 .expect("old owner does present in refungible")2132 .owner = new_owner.clone();2265 .owner = new_owner.clone();2133 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);2266 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);213422672140 .owner2273 .owner2141 .iter_mut()2274 .iter_mut()2142 .find(|i| i.owner == owner)2275 .find(|i| i.owner == owner)2143 .unwrap()2276 .expect("old owner does present in refungible")2144 .fraction -= value;2277 .fraction -= value;214522782146 // separate amount2279 // separate amount2150 .owner2283 .owner2151 .iter_mut()2284 .iter_mut()2152 .find(|i| i.owner == new_owner)2285 .find(|i| i.owner == new_owner)2153 .unwrap()2286 .expect("new owner has account")2154 .fraction += value;2287 .fraction += value;2155 } else {2288 } else {2156 // new owner do not have account2289 // new owner do not have account2472 > {2605 > {2473 let tip = self.0;2606 let tip = self.0;247426072475 // Set fee based on call type. Creating collection costs 1 Unique.2476 // All other transactions have traditional fees so far2477 // let fee = match call.is_sub_type() {2478 // Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),2479 // _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes2480 // // _ => <BalanceOf<T>>::from(100)2481 // };2482 let fee = Self::traditional_fee(len, info, tip);2608 let fee = Self::traditional_fee(len, info, tip);248326092484 // Only mess with balances if fee is not zero.2610 // Only mess with balances if fee is not zero.2496 // sponsor timeout2622 // sponsor timeout2497 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;2623 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;249826242625 let collection = <Collection<T>>::get(collection_id);26262499 let limit = collection.limits.sponsor_transfer_timeout;2627 let limit = collection.limits.sponsor_transfer_timeout;2628 let mut sponsored = true;2500 if <CreateItemBasket<T>>::contains_key((collection_id, &who)) {2629 if <CreateItemBasket<T>>::contains_key((collection_id, &who)) {2501 let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));2630 let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));2502 let limit_time = last_tx_block + limit.into();2631 let limit_time = last_tx_block + limit.into();250826372509 // check free create limit2638 // check free create limit2510 if (collection.limits.sponsored_data_size >= (_properties.len() as u32)) &&2639 if (collection.limits.sponsored_data_size >= (_properties.len() as u32)) &&2511 (collection.sponsor_confirmed)2640 (sponsored)2512 {2641 {2513 Some(collection.sponsor)2642 collection.sponsorship.sponsor()2643 .cloned()2514 } else {2644 } else {2515 None2645 None2516 }2646 }2519 let collection = <CollectionById<T>>::get(collection_id)?;2649 let collection = <CollectionById<T>>::get(collection_id)?;2520 2650 2521 let mut sponsor_transfer = false;2651 let mut sponsor_transfer = false;2522 if collection.sponsor_confirmed {2652 if collection.sponsorship.confirmed() {252326532524 let collection_limits = collection.limits;2654 let collection_limits = collection.limits;2525 let collection_mode = collection.mode;2655 let collection_mode = collection.mode;2606 if !sponsor_transfer {2736 if !sponsor_transfer {2607 None2737 None2608 } else {2738 } else {2609 Some(collection.sponsor)2739 collection.sponsorship.sponsor()2740 .cloned()2610 }2741 }2611 }2742 }26122743pallets/nft/src/mock.rsdiffbeforeafterboth--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -133,9 +133,14 @@
type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
}
+parameter_types! {
+ pub const CollectionCreationPrice: u64 = 1_000_000_000_000;
+}
+
impl pallet_template::Config for Test {
type Event = ();
type WeightInfo = ();
+ type CollectionCreationPrice = CollectionCreationPrice;
}
// Build genesis storage according to the mock runtime.
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"
+ }
+ },
"Collection": {
"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
@@ -376,8 +376,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(),
+ });
});
}
@@ -395,8 +396,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 });
});
}
@@ -434,8 +434,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,
+ });
});
}