git.delta.rocks / unique-network / refs/commits / 9180c847b05a

difftreelog

Merge branch 'develop' into feature/NFTPAR-196_sponsor_setVariableMetadata

Yaroslav Bolyukin2021-03-22parents: #ce0eea9 #105eff5.patch.diff
in: master

10 files changed

modified.github/workflows/notify.ymldiffbeforeafterboth
6 build: 6 build:
7 runs-on: ubuntu-latest 7 runs-on: ubuntu-latest
8 steps: 8 steps:
9 - uses: avkviring/telegram-github-action@v0.0.89 - uses: avkviring/telegram-github-action@v0.0.13
10 env:10 env:
11 telegram_to: ${{ secrets.TELEGRAM_TO }} 11 telegram_to: ${{ secrets.TELEGRAM_TO }}
12 telegram_token: ${{ secrets.TELEGRAM_TOKEN }}12 telegram_token: ${{ secrets.TELEGRAM_TOKEN }}
modifiednode/src/chain_spec.rsdiffbeforeafterboth
193 mint_mode: false,193 mint_mode: false,
194 offchain_schema: vec![],194 offchain_schema: vec![],
195 schema_version: SchemaVersion::default(),195 schema_version: SchemaVersion::default(),
196 sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),196 sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<sr25519::Public>("Alice")),
197 sponsor_confirmed: true,
198 const_on_chain_schema: vec![],197 const_on_chain_schema: vec![],
199 variable_on_chain_schema: vec![],198 variable_on_chain_schema: vec![],
200 limits: CollectionLimits::default()199 limits: CollectionLimits::default()
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
21 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};
3334
34use 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}
126127
128#[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 sender
132 Disabled,
133 Unconfirmed(AccountId),
134 /// Transactions are sponsored by specified account
135 Confirmed(AccountId),
136}
137
138impl<AccountId> SponsorshipState<AccountId> {
139 fn sponsor(&self) -> Option<&AccountId> {
140 match self {
141 Self::Confirmed(sponsor) => Some(sponsor),
142 _ => None,
143 }
144 }
145
146 fn pending_sponsor(&self) -> Option<&AccountId> {
147 match self {
148 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),
149 _ => None,
150 }
151 }
152
153 fn confirmed(&self) -> bool {
154 matches!(self, Self::Confirmed(_))
155 }
156}
157
158impl<T> Default for SponsorshipState<T> {
159 fn default() -> Self {
160 Self::Disabled
161 }
162}
163
127#[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 exceeded
414 SchemaDataLimitExceeded,450 SchemaDataLimitExceeded,
415 /// Maximum refungibility exceeded451 /// Maximum refungibility exceeded
416 WrongRefungiblePieces452 WrongRefungiblePieces,
453 /// createRefungible should be called with one owner
454 BadCreateRefungibleCall,
417 }455 }
418}456}
419457
422460
423 /// Weight information for extrinsics in this pallet.461 /// Weight information for extrinsics in this pallet.
424 type WeightInfo: WeightInfo;462 type WeightInfo: WeightInfo;
463
464 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}
426468
427#[cfg(feature = "runtime-benchmarks")]469#[cfg(feature = "runtime-benchmarks")]
428mod benchmarking;470mod benchmarking;
429471
430// #endregion472// #endregion
431473
474// # Used definitions
475//
476// ## User control levels
477//
478// chain-controlled - key is uncontrolled by user
479// i.e autoincrementing index
480// can use non-cryptographic hash
481// real - key is controlled by user
482// but it is hard to generate enough colliding values, i.e owner of signed txs
483// can use non-cryptographic hash
484// controlled - key is completly controlled by users
485// i.e maps with mutable keys
486// should use cryptographic hash
487//
488// ## User control level downgrade reasons
489//
490// ?1 - chain-controlled -> controlled
491// collections/tokens can be destroyed, resulting in massive holes
492// ?2 - chain-controlled -> controlled
493// same as ?1, but can be only added, resulting in easier exploitation
494// ?3 - real -> controlled
495// no confirmation required, so addresses can be easily generated
432decl_storage! {496decl_storage! {
433 trait Store for Module<T: Config> as Nft {497 trait Store for Module<T: Config> as Nft {
434498
435 // Private members499 //#region Private members
436 NextCollectionID: CollectionId;500 /// Id of next collection
437 CreatedCollectionCount: u32;501 CreatedCollectionCount: u32;
502 /// Used for migrations
438 ChainVersion: u64;503 ChainVersion: u64;
439 ItemListIndex: map hasher(identity) CollectionId => TokenId;504 /// Id of last collection token
505 /// Collection id (controlled?1)
506 ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;
507 //#endregion
440508
441 // Chain limits struct509 //#region Chain limits struct
442 pub ChainLimit get(fn chain_limit) config(): ChainLimits;510 pub ChainLimit get(fn chain_limit) config(): ChainLimits;
511 //#endregion
443512
444 // Bound counters513 //#region Bound counters
445 CollectionCount: u32;514 /// Amount of collections destroyed, used for total amount tracking with
515 /// CreatedCollectionCount
516 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 //#endregion
447521
448 // Basic collections522 //#region Basic collections
449 pub CollectionById get(fn collection_id) config(): map hasher(identity) CollectionId => Option<Collection<T>> = None;523 /// Collection info
524 /// 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 admins
527 /// 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 users
530 /// 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 //#endregion
452533
453 /// Balance owner per collection map534 /// How many of collection items user have
535 /// 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;
455537
456 /// 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;
458541
459 /// Item collections542 //#region Item collections
460 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 //#endregion
463550
464 /// Index list551 //#region Index list
465 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 //#endregion
466555
467 /// Tokens transfer baskets556 //#region Tokens transfer rate limit baskets
468 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 //#endregion
472566
473 /// Variable metadata sponsoring567 /// Variable metadata sponsoring
474 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 Ownership
572 /// 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 //#endregion
483 }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>;
564666
565 fn on_initialize(now: T::BlockNumber) -> Weight {667 fn on_initialize(now: T::BlockNumber) -> Weight {
566
567 if ChainVersion::get() < 2
568 {
569 let value = NextCollectionID::get();
570 CreatedCollectionCount::put(value);
571 ChainVersion::put(2);
572 }
573
574 0668 0
575 }669 }
576670
591 /// * mode: [CollectionMode] collection type and type dependent data.685 /// * mode: [CollectionMode] collection type and type dependent data.
592 // returns collection ID686 // returns collection ID
593 #[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 collection
601 let who = ensure_signed(origin)?;696 let who = ensure_signed(origin)?;
602697
698 // Take a (non-refundable) deposit of collection creation
699 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)?;
710
603 let decimal_points = match mode {711 let decimal_points = match mode {
604 CollectionMode::Fungible(points) => points,712 CollectionMode::Fungible(points) => points,
605 _ => 0713 _ => 0
606 };714 };
607715
608 let chain_limit = ChainLimit::get();716 let chain_limit = ChainLimit::get();
609717
718 let created_count = CreatedCollectionCount::get();
719 let destroyed_count = DestroyedCollectionCount::get();
720
610 // bound Total number of collections721 // bound Total number of collections
611 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);
612723
613 // check params724 // check params
614 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);
618729
619 // Generate next collection ID730 // Generate next collection ID
620 let next_id = CreatedCollectionCount::get()731 let next_id = created_count
621 .checked_add(1)732 .checked_add(1)
622 .ok_or(Error::<T>::NumOverflow)?;733 .ok_or(Error::<T>::NumOverflow)?;
623734
624 // bound counter
625 let total = CollectionCount::get()
626 .checked_add(1)
627 .ok_or(Error::<T>::NumOverflow)?;
628
629 CreatedCollectionCount::put(next_id);735 CreatedCollectionCount::put(next_id);
630 CollectionCount::put(total);
631736
632 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 {
676781
677 let sender = ensure_signed(origin)?;782 let sender = ensure_signed(origin)?;
699804
700 <VariableMetaDataBasket<T>>::remove_prefix(collection_id);805 <VariableMetaDataBasket<T>>::remove_prefix(collection_id);
701806
702 if CollectionCount::get() > 0807 DestroyedCollectionCount::put(DestroyedCollectionCount::get()
703 {
704 // bound couter
705 let total = CollectionCount::get()
706 .checked_sub(1)808 .checked_add(1)
707 .ok_or(Error::<T>::NumOverflow)?;809 .ok_or(Error::<T>::NumOverflow)?);
708810
709 CollectionCount::put(total);
710 }
711
712 Ok(())811 Ok(())
713 }812 }
714813
725 /// 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{
729829
730 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{
753854
754 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) -> DispatchResult
776 {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) -> DispatchResult
802 {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 {
826930
827 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 {
851956
852 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 {
886992
887 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 {
9101017
911 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)?;
9141021
915 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);
9181024
919 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 {
9311038
932 let sender = ensure_signed(origin)?;1039 let sender = ensure_signed(origin)?;
9331040
934 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>::ConfirmUnsetSponsorFail
1045 );
9361046
937 target_collection.sponsor_confirmed = true;1047 target_collection.sponsorship = SponsorshipState::Confirmed(sender);
938 Self::save_collection(target_collection);1048 Self::save_collection(target_collection);
9391049
940 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 {
9541065
955 let sender = ensure_signed(origin)?;1066 let sender = ensure_signed(origin)?;
9561067
957 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)?;
9591070
960 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);
9631073
964 Ok(())1074 Ok(())
989 // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]1099 // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]
9901100
991 #[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 {
9931104
994 let sender = ensure_signed(origin)?;1105 let sender = ensure_signed(origin)?;
1002 Ok(())1113 Ok(())
1003 }1114 }
10041115
1005 /// 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 /// # Permissions
1008 /// 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 {
10271139
1028 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 {
10601173
1061 let sender = ensure_signed(origin)?;1174 let sender = ensure_signed(origin)?;
1113 /// * Fungible Mode: Must specify transferred amount1226 /// * Fungible Mode: Must specify transferred amount
1114 /// * 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 {
11401255
1141 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 {
12041320
1205 let sender = ensure_signed(origin)?;1321 let sender = ensure_signed(origin)?;
1234 }1350 }
12351351
1236 // 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 0
1237 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: enum
1326 #[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,
14331554
1434 // Sudo permissions function1555 // Sudo permissions function
1435 #[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: ChainLimits
1457 /// * enable flag1579 /// * enable flag
1458 /// 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 allowed
1493 /// 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 }
15901717
1591 #[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 };
17571885
1758 // call event
1759 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id), owner));
1760
1761 Ok(())1886 Ok(())
1762 }1887 }
17631888
1782 .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);
17841909
1910 Self::deposit_event(RawEvent::ItemCreated(collection_id, 0, owner.clone()));
1785 Ok(())1911 Ok(())
1786 }1912 }
17871913
1793 .ok_or(Error::<T>::NumOverflow)?;1919 .ok_or(Error::<T>::NumOverflow)?;
1794 let itemcopy = item.clone();1920 let itemcopy = item.clone();
17951921
1796 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");
17981927
1928 let value = item_owner.fraction;
1929 let owner = item_owner.owner.clone();
1930
1799 Self::add_token_index(collection_id, current_index, &owner)?;1931 Self::add_token_index(collection_id, current_index, &owner)?;
18001932
1801 <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);
18091941
1942 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, owner));
1810 Ok(())1943 Ok(())
1811 }1944 }
18121945
1829 .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);
18311964
1965 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, item_owner));
1832 Ok(())1966 Ok(())
1833 }1967 }
18341968
1847 let rft_balance = token1981 let rft_balance = token
1848 .owner1982 .owner
1849 .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)?;
18541987
1855 // update balance1988 // update balance
1863 .owner1996 .owner
1864 .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();
18692002
2100 .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;
21052238
2106 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);
21132246
2114 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);
21182251
2119 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 .owner
2129 .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);
21342267
2140 .owner2273 .owner
2141 .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;
21452278
2146 // separate amount2279 // separate amount
2150 .owner2283 .owner
2151 .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 account
2472 > {2605 > {
2473 let tip = self.0;2606 let tip = self.0;
24742607
2475 // Set fee based on call type. Creating collection costs 1 Unique.
2476 // All other transactions have traditional fees so far
2477 // 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 purposes
2480 // // _ => <BalanceOf<T>>::from(100)
2481 // };
2482 let fee = Self::traditional_fee(len, info, tip);2608 let fee = Self::traditional_fee(len, info, tip);
24832609
2484 // Only mess with balances if fee is not zero.2610 // Only mess with balances if fee is not zero.
2496 // sponsor timeout2622 // sponsor timeout
2497 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;2623 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
24982624
2625 let collection = <Collection<T>>::get(collection_id);
2626
2499 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();
25082637
2509 // check free create limit2638 // check free create limit
2510 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 None
2516 }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() {
25232653
2524 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 None
2608 } else {2738 } else {
2609 Some(collection.sponsor)2739 collection.sponsorship.sponsor()
2740 .cloned()
2610 }2741 }
2611 }2742 }
26122743
modifiedpallets/nft/src/mock.rsdiffbeforeafterboth
133 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;133 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
134}134}
135
136parameter_types! {
137 pub const CollectionCreationPrice: u64 = 1_000_000_000_000;
138}
135139
136impl pallet_template::Config for Test {140impl pallet_template::Config for Test {
137 type Event = ();141 type Event = ();
138 type WeightInfo = ();142 type WeightInfo = ();
143 type CollectionCreationPrice = CollectionCreationPrice;
139}144}
140145
141// Build genesis storage according to the mock runtime.146// Build genesis storage according to the mock runtime.
modifiedruntime/src/lib.rsdiffbeforeafterboth
24 create_runtime_str, generic, impl_opaque_keys,24 create_runtime_str, generic, impl_opaque_keys,
25 traits::{25 traits::{
26 Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, 26 Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount,
27 IdentityLookup, NumberFor, Verify,27 IdentityLookup, NumberFor, Verify, AccountIdConversion,
28 },28 },
29 transaction_validity::{TransactionSource, TransactionValidity},29 transaction_validity::{TransactionSource, TransactionValidity},
30 ApplyExtrinsicResult, MultiSignature,30 ApplyExtrinsicResult, MultiSignature,
520 type WeightInfo = ();520 type WeightInfo = ();
521}521}
522
523parameter_types! {
524 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();
525 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;
526}
522527
523/// Used for the module nft in `./nft.rs`528/// Used for the module nft in `./nft.rs`
524impl pallet_nft::Config for Runtime {529impl pallet_nft::Config for Runtime {
525 type Event = Event;530 type Event = Event;
526 type WeightInfo = nft_weights::WeightInfo;531 type WeightInfo = nft_weights::WeightInfo;
532 type Currency = Balances;
533 type CollectionCreationPrice = CollectionCreationPrice;
534 type TreasuryAccountId = TreasuryAccountId;
527}535}
528536
529construct_runtime!(537construct_runtime!(
modifiedruntime_types.jsondiffbeforeafterboth
31 "ConstData": "Vec<u8>",31 "ConstData": "Vec<u8>",
32 "VariableData": "Vec<u8>"32 "VariableData": "Vec<u8>"
33 },33 },
34 "SponsorshipState": {
35 "_enum": {
36 "Disabled": null,
37 "Unconfirmed": "AccountId",
38 "Confirmed": "AccountId"
39 }
40 },
34 "Collection": {41 "Collection": {
35 "Owner": "AccountId",42 "Owner": "AccountId",
36 "Mode": "CollectionMode",43 "Mode": "CollectionMode",
42 "MintMode": "bool",49 "MintMode": "bool",
43 "OffchainSchema": "Vec<u8>",50 "OffchainSchema": "Vec<u8>",
44 "SchemaVersion": "SchemaVersion",51 "SchemaVersion": "SchemaVersion",
45 "Sponsor": "AccountId",52 "Sponsorship": "SponsorshipState",
46 "SponsorConfirmed": "bool",
47 "Limits": "CollectionLimits",53 "Limits": "CollectionLimits",
48 "VariableOnChainSchema": "Vec<u8>",54 "VariableOnChainSchema": "Vec<u8>",
49 "ConstOnChainSchema": "Vec<u8>"55 "ConstOnChainSchema": "Vec<u8>"
modifiedtests/package.jsondiffbeforeafterboth
25 "testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",25 "testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",
26 "testSetVariableMetaData": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetaData.test.ts",26 "testSetVariableMetaData": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetaData.test.ts",
27 "testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",27 "testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
28 "testSetCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionSponsor.test.ts",
29 "testConfirmSponsorship": "mocha --timeout 9999999 -r ts-node/register ./**/confirmSponsorship.test.ts",
28 "testRemoveCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionAdmin.test.ts",30 "testRemoveCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionAdmin.test.ts",
31 "testRemoveCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionSponsor.test.ts",
29 "testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",32 "testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",
30 "testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",33 "testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",
31 "testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",34 "testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
35describe('(!negative test!) integration test: ext. createCollection():', () => { 35describe('(!negative test!) integration test: ext. createCollection():', () => {
36 it('(!negative test!) create new NFT collection whith incorrect data (mode)', async () => { 36 it('(!negative test!) create new NFT collection whith incorrect data (mode)', async () => {
37 await usingApi(async (api) => { 37 await usingApi(async (api) => {
38 const AcollectionCount = parseInt((await api.query.nft.collectionCount()).toString(), 10); 38 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);
39 39
40 const badTransaction = async () => { 40 const badTransaction = async () => {
41 await createCollectionExpectSuccess({mode: {type: 'Invalid'}}); 41 await createCollectionExpectSuccess({mode: {type: 'Invalid'}});
42 }; 42 };
43 // tslint:disable-next-line:no-unused-expression 43 // tslint:disable-next-line:no-unused-expression
44 expect(badTransaction()).to.be.rejected; 44 expect(badTransaction()).to.be.rejected;
45 45
46 const BcollectionCount = parseInt((await api.query.nft.collectionCount()).toString(), 10); 46 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);
47 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Incorrect collection created.'); 47 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Incorrect collection created.');
48 }); 48 });
49 }); 49 });
modifiedtests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth
25const Treasury = "5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z";25const Treasury = "5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z";
26const saneMinimumFee = 0.05;26const saneMinimumFee = 0.05;
27const saneMaximumFee = 0.5;27const saneMaximumFee = 0.5;
28const createCollectionDeposit = 100;
2829
29let alice: IKeyringPair;30let alice: IKeyringPair;
30let bob: IKeyringPair;31let bob: IKeyringPair;
127 const aliceBalanceAfter = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());128 const aliceBalanceAfter = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());
128 const fee = aliceBalanceBefore.minus(aliceBalanceAfter);129 const fee = aliceBalanceBefore.minus(aliceBalanceAfter);
129130
130 expect(fee.dividedBy(1e15).toNumber()).to.be.lessThan(saneMaximumFee);131 expect(fee.dividedBy(1e15).toNumber()).to.be.lessThan(saneMaximumFee + createCollectionDeposit);
131 expect(fee.dividedBy(1e15).toNumber()).to.be.greaterThan(saneMinimumFee);132 expect(fee.dividedBy(1e15).toNumber()).to.be.greaterThan(saneMinimumFee + createCollectionDeposit);
132 });133 });
133 });134 });
134135
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
376376
377 // What to expect377 // What to expect
378 expect(result.success).to.be.true;378 expect(result.success).to.be.true;
379 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());379 expect(collection.Sponsorship).to.deep.equal({
380 expect(collection.SponsorConfirmed).to.be.false;380 Unconfirmed: sponsor.toString(),
381 });
381 });382 });
382}383}
383384
395396
396 // What to expect397 // What to expect
397 expect(result.success).to.be.true;398 expect(result.success).to.be.true;
398 expect(collection.Sponsor).to.be.equal(nullPublicKey);399 expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });
399 expect(collection.SponsorConfirmed).to.be.false;
400 });400 });
401}401}
402402
434434
435 // What to expect435 // What to expect
436 expect(result.success).to.be.true;436 expect(result.success).to.be.true;
437 expect(collection.Sponsor).to.be.equal(sender.address);437 expect(collection.Sponsorship).to.be.deep.equal({
438 expect(collection.SponsorConfirmed).to.be.true;438 Confirmed: sender.address,
439 });
439 });440 });
440}441}
441442