123456#![recursion_limit = "1024"]78#![cfg_attr(not(feature = "std"), no_std)]910#[cfg(feature = "std")]11pub use std::*;1213#[cfg(feature = "std")]14pub use serde::*;1516use core::ops::{Deref, DerefMut};17use codec::{Decode, Encode};18pub use frame_support::{19 construct_runtime, decl_event, decl_module, decl_storage, decl_error,20 dispatch::DispatchResult,21 ensure, fail, parameter_types,22 traits::{23 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,24 Randomness, IsSubType,25 },26 weights::{27 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},28 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,29 WeightToFeePolynomial, DispatchClass,30 },31 StorageValue,32};3334use frame_system::{self as system, ensure_signed, ensure_root};35use sp_runtime::sp_std::prelude::Vec;36use sp_runtime::{37 traits::{38 Hash, DispatchInfoOf, Dispatchable, PostDispatchInfoOf, Saturating, SaturatedConversion, SignedExtension, Zero,39 },40 transaction_validity::{41 TransactionPriority, InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction,42 },43 FixedPointOperand, FixedU128,44};45use sp_runtime::traits::StaticLookup;46use pallet_contracts::chain_extension::UncheckedFrom;47use pallet_transaction_payment::OnChargeTransaction;4849#[cfg(test)]50mod mock;5152#[cfg(test)]53mod tests;5455mod default_weights;5657pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;58pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;59pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;60pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;6162636465pub type CollectionId = u32;66pub type TokenId = u32;67pub type DecimalPoints = u8;6869#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]70#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]71pub enum CollectionMode {72 Invalid,73 NFT,74 75 Fungible(DecimalPoints),76 ReFungible,77}7879impl Default for CollectionMode {80 fn default() -> Self {81 Self::Invalid82 }83}8485impl Into<u8> for CollectionMode {86 fn into(self) -> u8 {87 match self {88 CollectionMode::Invalid => 0,89 CollectionMode::NFT => 1,90 CollectionMode::Fungible(_) => 2,91 CollectionMode::ReFungible => 3,92 }93 }94}9596#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]97#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]98pub enum AccessMode {99 Normal,100 WhiteList,101}102impl Default for AccessMode {103 fn default() -> Self {104 Self::Normal105 }106}107108#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]109#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]110pub enum SchemaVersion {111 ImageURL,112 Unique,113}114impl Default for SchemaVersion {115 fn default() -> Self {116 Self::ImageURL117 }118}119120#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]121#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]122pub struct Ownership<AccountId> {123 pub owner: AccountId,124 pub fraction: u128,125}126127#[derive(Encode, Decode, Clone, PartialEq)]128#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]129pub struct Collection<T: Config> {130 pub owner: T::AccountId,131 pub mode: CollectionMode,132 pub access: AccessMode,133 pub decimal_points: DecimalPoints,134 pub name: Vec<u16>, 135 pub description: Vec<u16>, 136 pub token_prefix: Vec<u8>, 137 pub mint_mode: bool,138 pub offchain_schema: Vec<u8>,139 pub schema_version: SchemaVersion,140 pub sponsor: T::AccountId, 141 pub sponsor_confirmed: bool, 142 pub limits: CollectionLimits<T::BlockNumber>, 143 pub variable_on_chain_schema: Vec<u8>, 144 pub const_on_chain_schema: Vec<u8>, 145}146147pub struct CollectionHandle<T: Config> {148 pub id: CollectionId,149 collection: Collection<T>,150}151152impl<T: Config> Deref for CollectionHandle<T> {153 type Target = Collection<T>;154155 fn deref(&self) -> &Self::Target {156 &self.collection157 }158}159160impl<T: Config> DerefMut for CollectionHandle<T> {161 fn deref_mut(&mut self) -> &mut Self::Target {162 &mut self.collection163 }164}165166#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]167#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]168pub struct NftItemType<AccountId> {169 pub owner: AccountId,170 pub const_data: Vec<u8>,171 pub variable_data: Vec<u8>,172}173174#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]175#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]176pub struct FungibleItemType {177 pub value: u128,178}179180#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]181#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]182pub struct ReFungibleItemType<AccountId> {183 pub owner: Vec<Ownership<AccountId>>,184 pub const_data: Vec<u8>,185 pub variable_data: Vec<u8>,186}187188189190191192193194195196197198199#[derive(Encode, Decode, Debug, Clone, PartialEq)]200#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]201pub struct CollectionLimits<BlockNumber: Encode + Decode> {202 pub account_token_ownership_limit: u32,203 pub sponsored_data_size: u32,204 205 206 207 pub sponsored_data_rate_limit: Option<BlockNumber>,208 pub token_limit: u32,209210 211 pub sponsor_transfer_timeout: u32,212 pub owner_can_transfer: bool,213 pub owner_can_destroy: bool,214}215216impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {217 fn default() -> Self {218 Self { 219 account_token_ownership_limit: 10_000_000, 220 token_limit: u32::max_value(),221 sponsored_data_size: u32::MAX, 222 sponsored_data_rate_limit: None,223 sponsor_transfer_timeout: 14400,224 owner_can_transfer: true,225 owner_can_destroy: true226 }227 }228}229230#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]231#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]232pub struct ChainLimits {233 pub collection_numbers_limit: u32,234 pub account_token_ownership_limit: u32,235 pub collections_admins_limit: u64,236 pub custom_data_limit: u32,237238 239 pub nft_sponsor_transfer_timeout: u32,240 pub fungible_sponsor_transfer_timeout: u32,241 pub refungible_sponsor_transfer_timeout: u32,242243 244 pub offchain_schema_limit: u32,245 pub variable_on_chain_schema_limit: u32,246 pub const_on_chain_schema_limit: u32,247}248249pub trait WeightInfo {250 fn create_collection() -> Weight;251 fn destroy_collection() -> Weight;252 fn add_to_white_list() -> Weight;253 fn remove_from_white_list() -> Weight;254 fn set_public_access_mode() -> Weight;255 fn set_mint_permission() -> Weight;256 fn change_collection_owner() -> Weight;257 fn add_collection_admin() -> Weight;258 fn remove_collection_admin() -> Weight;259 fn set_collection_sponsor() -> Weight;260 fn confirm_sponsorship() -> Weight;261 fn remove_collection_sponsor() -> Weight;262 fn create_item(s: usize) -> Weight;263 fn burn_item() -> Weight;264 fn transfer() -> Weight;265 fn approve() -> Weight;266 fn transfer_from() -> Weight;267 fn set_offchain_schema() -> Weight;268 fn set_const_on_chain_schema() -> Weight;269 fn set_variable_on_chain_schema() -> Weight;270 fn set_variable_meta_data() -> Weight;271 fn enable_contract_sponsoring() -> Weight;272 fn set_schema_version() -> Weight;273 fn set_chain_limits() -> Weight;274 fn set_contract_sponsoring_rate_limit() -> Weight;275 fn set_variable_meta_data_sponsoring_rate_limit() -> Weight;276 fn toggle_contract_white_list() -> Weight;277 fn add_to_contract_white_list() -> Weight;278 fn remove_from_contract_white_list() -> Weight;279 fn set_collection_limits() -> Weight;280}281282#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]283#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]284pub struct CreateNftData {285 pub const_data: Vec<u8>,286 pub variable_data: Vec<u8>,287}288289#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]290#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]291pub struct CreateFungibleData {292 pub value: u128,293}294295#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]296#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]297pub struct CreateReFungibleData {298 pub const_data: Vec<u8>,299 pub variable_data: Vec<u8>,300 pub pieces: u128,301}302303#[derive(Encode, Decode, Debug, Clone, PartialEq)]304#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]305pub enum CreateItemData {306 NFT(CreateNftData),307 Fungible(CreateFungibleData),308 ReFungible(CreateReFungibleData),309}310311impl CreateItemData {312 pub fn len(&self) -> usize {313 let len = match self {314 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),315 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),316 _ => 0317 };318 319 return len;320 }321}322323impl From<CreateNftData> for CreateItemData {324 fn from(item: CreateNftData) -> Self {325 CreateItemData::NFT(item)326 }327}328329impl From<CreateReFungibleData> for CreateItemData {330 fn from(item: CreateReFungibleData) -> Self {331 CreateItemData::ReFungible(item)332 }333}334335impl From<CreateFungibleData> for CreateItemData {336 fn from(item: CreateFungibleData) -> Self {337 CreateItemData::Fungible(item)338 }339}340341342decl_error! {343 344 pub enum Error for Module<T: Config> {345 346 TotalCollectionsLimitExceeded,347 348 CollectionDecimalPointLimitExceeded, 349 350 CollectionNameLimitExceeded, 351 352 CollectionDescriptionLimitExceeded, 353 354 CollectionTokenPrefixLimitExceeded,355 356 CollectionNotFound,357 358 TokenNotFound,359 360 AdminNotFound,361 362 NumOverflow, 363 364 AlreadyAdmin, 365 366 NoPermission,367 368 ConfirmUnsetSponsorFail,369 370 PublicMintingNotAllowed,371 372 MustBeTokenOwner,373 374 TokenValueTooLow,375 376 NftSizeLimitExceeded,377 378 ApproveNotFound,379 380 TokenValueNotEnough,381 382 ApproveRequired,383 384 AddresNotInWhiteList,385 386 CollectionAdminsLimitExceeded,387 388 AddressOwnershipLimitExceeded,389 390 EmptyArgument,391 392 TokenConstDataLimitExceeded,393 394 TokenVariableDataLimitExceeded,395 396 NotNftDataUsedToMintNftCollectionToken,397 398 NotFungibleDataUsedToMintFungibleCollectionToken,399 400 NotReFungibleDataUsedToMintReFungibleCollectionToken,401 402 UnexpectedCollectionType,403 404 CantStoreMetadataInFungibleTokens,405 406 CollectionTokenLimitExceeded,407 408 AccountTokenLimitExceeded,409 410 CollectionLimitBoundsExceeded,411 412 OwnerPermissionsCantBeReverted,413 414 SchemaDataLimitExceeded,415 416 WrongRefungiblePieces417 }418}419420pub trait Config: system::Config + Sized + pallet_transaction_payment::Config + pallet_contracts::Config {421 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;422423 424 type WeightInfo: WeightInfo;425}426427#[cfg(feature = "runtime-benchmarks")]428mod benchmarking;429430431432decl_storage! {433 trait Store for Module<T: Config> as Nft {434435 436 NextCollectionID: CollectionId;437 CreatedCollectionCount: u32;438 ChainVersion: u64;439 ItemListIndex: map hasher(identity) CollectionId => TokenId;440441 442 pub ChainLimit get(fn chain_limit) config(): ChainLimits;443444 445 CollectionCount: u32;446 pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;447448 449 pub CollectionById get(fn collection_id) config(): map hasher(identity) CollectionId => Option<Collection<T>> = None;450 pub AdminList get(fn admin_list_collection): map hasher(identity) CollectionId => Vec<T::AccountId>;451 pub WhiteList get(fn white_list): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => bool;452453 454 pub Balance get(fn balance_count): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => u128;455456 457 pub Allowances get(fn approved): double_map hasher(identity) CollectionId, hasher(twox_64_concat) (TokenId, T::AccountId, T::AccountId) => u128;458459 460 pub NftItemList get(fn nft_item_id) config(): double_map hasher(identity) CollectionId, hasher(identity) 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;462 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(identity) CollectionId, hasher(identity) TokenId => ReFungibleItemType<T::AccountId>;463464 465 pub AddressTokens get(fn address_tokens): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => Vec<TokenId>;466467 468 pub CreateItemBasket get(fn create_item_basket): map hasher(twox_64_concat) (CollectionId, T::AccountId) => T::BlockNumber;469 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => T::BlockNumber;470 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(identity) 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;472473 474 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => Option<T::BlockNumber> = None;475476 477 pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => T::AccountId;478 pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;479 pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;480 pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;481 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; 483 }484 add_extra_genesis {485 build(|config: &GenesisConfig<T>| {486 487 for (_num, _c) in &config.collection_id {488 <Module<T>>::init_collection(_c);489 }490491 for (_num, _c, _i) in &config.nft_item_id {492 <Module<T>>::init_nft_token(*_c, _i);493 }494495 for (collection_id, account_id, fungible_item) in &config.fungible_item_id {496 <Module<T>>::init_fungible_token(*collection_id, account_id, fungible_item);497 }498499 for (_num, _c, _i) in &config.refungible_item_id {500 <Module<T>>::init_refungible_token(*_c, _i);501 }502 })503 }504}505506decl_event!(507 pub enum Event<T>508 where509 AccountId = <T as system::Config>::AccountId,510 {511 512 513 514 515 516 517 518 519 520 Created(CollectionId, u8, AccountId),521522 523 524 525 526 527 528 529 530 531 ItemCreated(CollectionId, TokenId, AccountId),532533 534 535 536 537 538 539 540 ItemDestroyed(CollectionId, TokenId),541542 543 544 545 546 547 548 549 550 551 552 553 Transfer(CollectionId, TokenId, AccountId, AccountId, u128),554 }555);556557decl_module! {558 pub struct Module<T: Config> for enum Call 559 where 560 origin: T::Origin561 {562 fn deposit_event() = default;563 type Error = Error<T>;564565 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 0575 }576577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 #[weight = <T as Config>::WeightInfo::create_collection()]594 pub fn create_collection(origin,595 collection_name: Vec<u16>,596 collection_description: Vec<u16>,597 token_prefix: Vec<u8>,598 mode: CollectionMode) -> DispatchResult {599600 601 let who = ensure_signed(origin)?;602603 let decimal_points = match mode {604 CollectionMode::Fungible(points) => points,605 _ => 0606 };607608 let chain_limit = ChainLimit::get();609610 611 ensure!(CollectionCount::get() < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);612613 614 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);615 ensure!(collection_name.len() <= 64, Error::<T>::CollectionNameLimitExceeded);616 ensure!(collection_description.len() <= 256, Error::<T>::CollectionDescriptionLimitExceeded);617 ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);618619 620 let next_id = CreatedCollectionCount::get()621 .checked_add(1)622 .ok_or(Error::<T>::NumOverflow)?;623624 625 let total = CollectionCount::get()626 .checked_add(1)627 .ok_or(Error::<T>::NumOverflow)?;628629 CreatedCollectionCount::put(next_id);630 CollectionCount::put(total);631632 let limits = CollectionLimits {633 sponsored_data_size: chain_limit.custom_data_limit,634 ..Default::default()635 };636637 638 let new_collection = Collection {639 owner: who.clone(),640 name: collection_name,641 mode: mode.clone(),642 mint_mode: false,643 access: AccessMode::Normal,644 description: collection_description,645 decimal_points: decimal_points,646 token_prefix: token_prefix,647 offchain_schema: Vec::new(),648 schema_version: SchemaVersion::ImageURL,649 sponsor: T::AccountId::default(),650 sponsor_confirmed: false,651 variable_on_chain_schema: Vec::new(),652 const_on_chain_schema: Vec::new(),653 limits,654 };655656 657 <CollectionById<T>>::insert(next_id, new_collection);658659 660 Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));661662 Ok(())663 }664665 666 667 668 669 670 671 672 673 674 #[weight = <T as Config>::WeightInfo::destroy_collection()]675 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {676677 let sender = ensure_signed(origin)?;678 let collection = Self::get_collection(collection_id)?;679 Self::check_owner_permissions(&collection, sender)?;680 if !collection.limits.owner_can_destroy {681 fail!(Error::<T>::NoPermission);682 }683684 <AddressTokens<T>>::remove_prefix(collection_id);685 <Allowances<T>>::remove_prefix(collection_id);686 <Balance<T>>::remove_prefix(collection_id);687 <ItemListIndex>::remove(collection_id);688 <AdminList<T>>::remove(collection_id);689 <CollectionById<T>>::remove(collection_id);690 <WhiteList<T>>::remove_prefix(collection_id);691692 <NftItemList<T>>::remove_prefix(collection_id);693 <FungibleItemList<T>>::remove_prefix(collection_id);694 <ReFungibleItemList<T>>::remove_prefix(collection_id);695696 <NftTransferBasket<T>>::remove_prefix(collection_id);697 <FungibleTransferBasket<T>>::remove_prefix(collection_id);698 <ReFungibleTransferBasket<T>>::remove_prefix(collection_id);699700 <VariableMetaDataBasket<T>>::remove_prefix(collection_id);701702 if CollectionCount::get() > 0703 {704 705 let total = CollectionCount::get()706 .checked_sub(1)707 .ok_or(Error::<T>::NumOverflow)?;708709 CollectionCount::put(total);710 }711712 Ok(())713 }714715 716 717 718 719 720 721 722 723 724 725 726 727 #[weight = <T as Config>::WeightInfo::add_to_white_list()]728 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{729730 let sender = ensure_signed(origin)?;731 let collection = Self::get_collection(collection_id)?;732 Self::check_owner_or_admin_permissions(&collection, sender)?;733734 <WhiteList<T>>::insert(collection_id, address, true);735 736 Ok(())737 }738739 740 741 742 743 744 745 746 747 748 749 750 751 #[weight = <T as Config>::WeightInfo::remove_from_white_list()]752 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{753754 let sender = ensure_signed(origin)?;755 let collection = Self::get_collection(collection_id)?;756 Self::check_owner_or_admin_permissions(&collection, sender)?;757758 <WhiteList<T>>::remove(collection_id, address);759760 Ok(())761 }762763 764 765 766 767 768 769 770 771 772 773 774 #[weight = <T as Config>::WeightInfo::set_public_access_mode()]775 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult776 {777 let sender = ensure_signed(origin)?;778779 let mut target_collection = Self::get_collection(collection_id)?;780 Self::check_owner_permissions(&target_collection, sender)?;781 target_collection.access = mode;782 Self::save_collection(target_collection);783784 Ok(())785 }786787 788 789 790 791 792 793 794 795 796 797 798 799 800 #[weight = <T as Config>::WeightInfo::set_mint_permission()]801 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult802 {803 let sender = ensure_signed(origin)?;804805 let mut target_collection = Self::get_collection(collection_id)?;806 Self::check_owner_permissions(&target_collection, sender)?;807 target_collection.mint_mode = mint_permission;808 Self::save_collection(target_collection);809810 Ok(())811 }812813 814 815 816 817 818 819 820 821 822 823 824 #[weight = <T as Config>::WeightInfo::change_collection_owner()]825 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {826827 let sender = ensure_signed(origin)?;828 let mut target_collection = Self::get_collection(collection_id)?;829 Self::check_owner_permissions(&target_collection, sender)?;830 target_collection.owner = new_owner;831 Self::save_collection(target_collection);832833 Ok(())834 }835836 837 838 839 840 841 842 843 844 845 846 847 848 849 #[weight = <T as Config>::WeightInfo::add_collection_admin()]850 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::AccountId) -> DispatchResult {851852 let sender = ensure_signed(origin)?;853 let collection = Self::get_collection(collection_id)?;854 Self::check_owner_or_admin_permissions(&collection, sender)?;855 let mut admin_arr: Vec<T::AccountId> = Vec::new();856857 if <AdminList<T>>::contains_key(collection_id)858 {859 admin_arr = <AdminList<T>>::get(collection_id);860 ensure!(!admin_arr.contains(&new_admin_id), Error::<T>::AlreadyAdmin);861 }862863 864 ensure!((admin_arr.len() as u64) < ChainLimit::get().collections_admins_limit, Error::<T>::CollectionAdminsLimitExceeded);865866 admin_arr.push(new_admin_id);867 <AdminList<T>>::insert(collection_id, admin_arr);868869 Ok(())870 }871872 873 874 875 876 877 878 879 880 881 882 883 884 #[weight = <T as Config>::WeightInfo::remove_collection_admin()]885 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::AccountId) -> DispatchResult {886887 let sender = ensure_signed(origin)?;888 let collection = Self::get_collection(collection_id)?;889 Self::check_owner_or_admin_permissions(&collection, sender)?;890 ensure!(<AdminList<T>>::contains_key(collection_id), Error::<T>::AdminNotFound);891892 let mut admin_arr = <AdminList<T>>::get(collection_id);893 admin_arr.retain(|i| *i != account_id);894 <AdminList<T>>::insert(collection_id, admin_arr);895896 Ok(())897 }898899 900 901 902 903 904 905 906 907 908 #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]909 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {910911 let sender = ensure_signed(origin)?;912 let mut target_collection = Self::get_collection(collection_id)?;913 Self::check_owner_permissions(&target_collection, sender)?;914915 target_collection.sponsor = new_sponsor;916 target_collection.sponsor_confirmed = false;917 Self::save_collection(target_collection);918919 Ok(())920 }921922 923 924 925 926 927 928 929 #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]930 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {931932 let sender = ensure_signed(origin)?;933934 let mut target_collection = Self::get_collection(collection_id)?;935 ensure!(sender == target_collection.sponsor, Error::<T>::ConfirmUnsetSponsorFail);936937 target_collection.sponsor_confirmed = true;938 Self::save_collection(target_collection);939940 Ok(())941 }942943 944 945 946 947 948 949 950 951 952 #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]953 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {954955 let sender = ensure_signed(origin)?;956957 let mut target_collection = Self::get_collection(collection_id)?;958 Self::check_owner_permissions(&target_collection, sender)?;959960 target_collection.sponsor = T::AccountId::default();961 target_collection.sponsor_confirmed = false;962 Self::save_collection(target_collection);963964 Ok(())965 }966967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990991 #[weight = <T as Config>::WeightInfo::create_item(data.len())]992 pub fn create_item(origin, collection_id: CollectionId, owner: T::AccountId, data: CreateItemData) -> DispatchResult {993994 let sender = ensure_signed(origin)?;995996 let target_collection = Self::get_collection(collection_id)?;997998 Self::can_create_items_in_collection(&target_collection, &sender, &owner, 1)?;999 Self::validate_create_item_args(&target_collection, &data)?;1000 Self::create_item_no_validation(&target_collection, owner, data)?;10011002 Ok(())1003 }10041005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 #[weight = <T as Config>::WeightInfo::create_item(items_data.into_iter()1024 .map(|data| { data.len() })1025 .sum())]1026 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::AccountId, items_data: Vec<CreateItemData>) -> DispatchResult {10271028 ensure!(items_data.len() > 0, Error::<T>::EmptyArgument);1029 let sender = ensure_signed(origin)?;10301031 let target_collection = Self::get_collection(collection_id)?;10321033 Self::can_create_items_in_collection(&target_collection, &sender, &owner, items_data.len() as u32)?;10341035 for data in &items_data {1036 Self::validate_create_item_args(&target_collection, data)?;1037 }1038 for data in &items_data {1039 Self::create_item_no_validation(&target_collection, owner.clone(), data.clone())?;1040 }10411042 Ok(())1043 }10441045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 #[weight = <T as Config>::WeightInfo::burn_item()]1059 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {10601061 let sender = ensure_signed(origin)?;10621063 1064 let target_collection = Self::get_collection(collection_id)?;1065 ensure!(1066 Self::is_item_owner(sender.clone(), &target_collection, item_id) ||1067 (1068 target_collection.limits.owner_can_transfer &&1069 Self::is_owner_or_admin_permissions(&target_collection, sender.clone())1070 ),1071 Error::<T>::NoPermission1072 );10731074 if target_collection.access == AccessMode::WhiteList {1075 Self::check_white_list(&target_collection, &sender)?;1076 }10771078 match target_collection.mode1079 {1080 CollectionMode::NFT => Self::burn_nft_item(&target_collection, item_id)?,1081 CollectionMode::Fungible(_) => Self::burn_fungible_item(&sender, &target_collection, value)?,1082 CollectionMode::ReFungible => Self::burn_refungible_item(&target_collection, item_id, &sender)?,1083 _ => ()1084 };10851086 1087 Self::deposit_event(RawEvent::ItemDestroyed(target_collection.id, item_id));10881089 Ok(())1090 }10911092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 #[weight = <T as Config>::WeightInfo::transfer()]1116 pub fn transfer(origin, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {1117 let sender = ensure_signed(origin)?;1118 let collection = Self::get_collection(collection_id)?;11191120 Self::transfer_internal(sender, recipient, &collection, item_id, value)1121 }11221123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 #[weight = <T as Config>::WeightInfo::approve()]1139 pub fn approve(origin, spender: T::AccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {11401141 let sender = ensure_signed(origin)?;1142 let target_collection = Self::get_collection(collection_id)?;11431144 Self::token_exists(&target_collection, item_id, &sender)?;11451146 1147 let bypasses_limits = target_collection.limits.owner_can_transfer &&1148 Self::is_owner_or_admin_permissions(1149 &target_collection,1150 sender.clone(),1151 );11521153 let allowance_limit = if bypasses_limits {1154 None1155 } else if let Some(amount) = Self::owned_amount(1156 sender.clone(),1157 &target_collection,1158 item_id,1159 ) {1160 Some(amount)1161 } else {1162 fail!(Error::<T>::NoPermission);1163 };11641165 if target_collection.access == AccessMode::WhiteList {1166 Self::check_white_list(&target_collection, &sender)?;1167 Self::check_white_list(&target_collection, &spender)?;1168 }11691170 let allowance_exists = <Allowances<T>>::contains_key(collection_id, (item_id, &sender, &spender));1171 let mut allowance: u128 = amount;1172 if allowance_exists {1173 allowance += <Allowances<T>>::get(collection_id, (item_id, &sender, &spender));1174 }1175 if let Some(limit) = allowance_limit {1176 ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);1177 }1178 <Allowances<T>>::insert(collection_id, (item_id, sender.clone(), spender.clone()), allowance);11791180 Ok(())1181 }1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 #[weight = <T as Config>::WeightInfo::transfer_from()]1203 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {12041205 let sender = ensure_signed(origin)?;1206 let target_collection = Self::get_collection(collection_id)?;12071208 let mut appoved_transfer = false;12091210 1211 let mut approval: u128 = 0;1212 if <Allowances<T>>::contains_key(collection_id, (item_id, &from, &sender)) {1213 approval = <Allowances<T>>::get(collection_id, (item_id, &from, &sender));1214 ensure!(approval >= value, Error::<T>::TokenValueNotEnough);1215 appoved_transfer = true;1216 }12171218 1219 Self::is_correct_transfer(&target_collection, &recipient)?;12201221 1222 ensure!(1223 appoved_transfer || 1224 (1225 target_collection.limits.owner_can_transfer &&1226 Self::is_owner_or_admin_permissions(&target_collection, sender.clone())1227 ),1228 Error::<T>::NoPermission1229 );12301231 if target_collection.access == AccessMode::WhiteList {1232 Self::check_white_list(&target_collection, &sender)?;1233 Self::check_white_list(&target_collection, &recipient)?;1234 }12351236 1237 if approval.checked_sub(value).unwrap_or(0) > 0 {1238 <Allowances<T>>::insert(collection_id, (item_id, &from, &sender), approval - value);1239 }1240 else {1241 <Allowances<T>>::remove(collection_id, (item_id, &from, &sender));1242 }12431244 match target_collection.mode1245 {1246 CollectionMode::NFT => Self::transfer_nft(&target_collection, item_id, from, recipient)?,1247 CollectionMode::Fungible(_) => Self::transfer_fungible(&target_collection, value, &from, &recipient)?,1248 CollectionMode::ReFungible => Self::transfer_refungible(&target_collection, item_id, value, from.clone(), recipient)?,1249 _ => ()1250 };12511252 Ok(())1253 }12541255 1256 12571258 1259 1260 1261 12621263 12641265 12661267 1268 12691270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1283 pub fn set_variable_meta_data (1284 origin,1285 collection_id: CollectionId,1286 item_id: TokenId,1287 data: Vec<u8>1288 ) -> DispatchResult {1289 let sender = ensure_signed(origin)?;1290 1291 let target_collection = Self::get_collection(collection_id)?;1292 Self::token_exists(&target_collection, item_id, &sender)?;12931294 ensure!(ChainLimit::get().custom_data_limit >= data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);12951296 1297 ensure!(Self::is_item_owner(sender.clone(), &target_collection, item_id) ||1298 Self::is_owner_or_admin_permissions(&target_collection, sender.clone()),1299 Error::<T>::NoPermission);13001301 match target_collection.mode1302 {1303 CollectionMode::NFT => Self::set_nft_variable_data(&target_collection, item_id, data)?,1304 CollectionMode::ReFungible => Self::set_re_fungible_variable_data(&target_collection, item_id, data)?,1305 CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),1306 _ => fail!(Error::<T>::UnexpectedCollectionType)1307 };13081309 Ok(())1310 }1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 #[weight = <T as Config>::WeightInfo::set_schema_version()]1327 pub fn set_schema_version(1328 origin,1329 collection_id: CollectionId,1330 version: SchemaVersion1331 ) -> DispatchResult {1332 let sender = ensure_signed(origin)?;1333 let mut target_collection = Self::get_collection(collection_id)?;1334 Self::check_owner_or_admin_permissions(&target_collection, sender.clone())?;1335 target_collection.schema_version = version;1336 Self::save_collection(target_collection);13371338 Ok(())1339 }13401341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1354 pub fn set_offchain_schema(1355 origin,1356 collection_id: CollectionId,1357 schema: Vec<u8>1358 ) -> DispatchResult {1359 let sender = ensure_signed(origin)?;1360 let mut target_collection = Self::get_collection(collection_id)?;1361 Self::check_owner_or_admin_permissions(&target_collection, sender.clone())?;13621363 1364 ensure!(schema.len() as u32 <= ChainLimit::get().offchain_schema_limit, "");13651366 target_collection.offchain_schema = schema;1367 Self::save_collection(target_collection);13681369 Ok(())1370 }13711372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1385 pub fn set_const_on_chain_schema (1386 origin,1387 collection_id: CollectionId,1388 schema: Vec<u8>1389 ) -> DispatchResult {1390 let sender = ensure_signed(origin)?;1391 let mut target_collection = Self::get_collection(collection_id)?;1392 Self::check_owner_or_admin_permissions(&target_collection, sender.clone())?;13931394 1395 ensure!(schema.len() as u32 <= ChainLimit::get().const_on_chain_schema_limit, "");13961397 target_collection.const_on_chain_schema = schema;1398 Self::save_collection(target_collection);13991400 Ok(())1401 }14021403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1416 pub fn set_variable_on_chain_schema (1417 origin,1418 collection_id: CollectionId,1419 schema: Vec<u8>1420 ) -> DispatchResult {1421 let sender = ensure_signed(origin)?;1422 let mut target_collection = Self::get_collection(collection_id)?;1423 Self::check_owner_or_admin_permissions(&target_collection, sender.clone())?;14241425 1426 ensure!(schema.len() as u32 <= ChainLimit::get().variable_on_chain_schema_limit, "");14271428 target_collection.variable_on_chain_schema = schema;1429 Self::save_collection(target_collection);14301431 Ok(())1432 }14331434 1435 #[weight = <T as Config>::WeightInfo::set_chain_limits()]1436 pub fn set_chain_limits(1437 origin,1438 limits: ChainLimits1439 ) -> DispatchResult {14401441 #[cfg(not(feature = "runtime-benchmarks"))]1442 ensure_root(origin)?;14431444 <ChainLimit>::put(limits);1445 Ok(())1446 }14471448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 #[weight = <T as Config>::WeightInfo::enable_contract_sponsoring()]1460 pub fn enable_contract_sponsoring(1461 origin,1462 contract_address: T::AccountId,1463 enable: bool1464 ) -> DispatchResult {14651466 let sender = ensure_signed(origin)?;14671468 #[cfg(feature = "runtime-benchmarks")]1469 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());14701471 Self::ensure_contract_owned(sender, &contract_address)?;14721473 <ContractSelfSponsoring<T>>::insert(contract_address, enable);1474 Ok(())1475 }14761477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 #[weight = <T as Config>::WeightInfo::set_contract_sponsoring_rate_limit()]1495 pub fn set_contract_sponsoring_rate_limit(1496 origin,1497 contract_address: T::AccountId,1498 rate_limit: T::BlockNumber1499 ) -> DispatchResult {1500 let sender = ensure_signed(origin)?;15011502 #[cfg(feature = "runtime-benchmarks")]1503 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());15041505 Self::ensure_contract_owned(sender, &contract_address)?;1506 <ContractSponsoringRateLimit<T>>::insert(contract_address, rate_limit);1507 Ok(())1508 }15091510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 #[weight = <T as Config>::WeightInfo::toggle_contract_white_list()]1522 pub fn toggle_contract_white_list(1523 origin,1524 contract_address: T::AccountId,1525 enable: bool1526 ) -> DispatchResult {1527 let sender = ensure_signed(origin)?;15281529 #[cfg(feature = "runtime-benchmarks")]1530 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());15311532 Self::ensure_contract_owned(sender, &contract_address)?;1533 <ContractWhiteListEnabled<T>>::insert(contract_address, enable);1534 Ok(())1535 }1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 #[weight = <T as Config>::WeightInfo::add_to_contract_white_list()]1549 pub fn add_to_contract_white_list(1550 origin,1551 contract_address: T::AccountId,1552 account_address: T::AccountId1553 ) -> DispatchResult {1554 let sender = ensure_signed(origin)?;15551556 #[cfg(feature = "runtime-benchmarks")]1557 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());1558 1559 Self::ensure_contract_owned(sender, &contract_address)?; 1560 <ContractWhiteList<T>>::insert(contract_address, account_address, true);1561 Ok(())1562 }15631564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 #[weight = <T as Config>::WeightInfo::remove_from_contract_white_list()]1576 pub fn remove_from_contract_white_list(1577 origin,1578 contract_address: T::AccountId,1579 account_address: T::AccountId1580 ) -> DispatchResult {1581 let sender = ensure_signed(origin)?;15821583 #[cfg(feature = "runtime-benchmarks")]1584 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());15851586 Self::ensure_contract_owned(sender, &contract_address)?;1587 <ContractWhiteList<T>>::remove(contract_address, account_address);1588 Ok(())1589 }15901591 #[weight = <T as Config>::WeightInfo::set_collection_limits()]1592 pub fn set_collection_limits(1593 origin,1594 collection_id: u32,1595 new_limits: CollectionLimits<T::BlockNumber>,1596 ) -> DispatchResult {1597 let sender = ensure_signed(origin)?;1598 let mut target_collection = Self::get_collection(collection_id)?;1599 Self::check_owner_permissions(&target_collection, sender.clone())?;1600 let old_limits = &target_collection.limits;1601 let chain_limits = ChainLimit::get();16021603 1604 ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&1605 new_limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP && 1606 new_limits.sponsored_data_size <= chain_limits.custom_data_limit,1607 Error::<T>::CollectionLimitBoundsExceeded);16081609 1610 ensure!(old_limits.token_limit >= new_limits.token_limit, Error::<T>::CollectionTokenLimitExceeded);1611 ensure!(new_limits.token_limit > 0, Error::<T>::CollectionTokenLimitExceeded);16121613 ensure!(1614 (old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&1615 (old_limits.owner_can_destroy || !new_limits.owner_can_destroy),1616 Error::<T>::OwnerPermissionsCantBeReverted,1617 );16181619 target_collection.limits = new_limits;1620 Self::save_collection(target_collection);16211622 Ok(())1623 } 1624 }1625}16261627impl<T: Config> Module<T> {16281629 pub fn transfer_internal(sender: T::AccountId, recipient: T::AccountId, target_collection: &CollectionHandle<T>, item_id: TokenId, value: u128) -> DispatchResult {1630 1631 Self::is_correct_transfer(target_collection, &recipient)?;16321633 1634 ensure!(Self::is_item_owner(sender.clone(), target_collection, item_id) ||1635 Self::is_owner_or_admin_permissions(target_collection, sender.clone()),1636 Error::<T>::NoPermission);16371638 if target_collection.access == AccessMode::WhiteList {1639 Self::check_white_list(target_collection, &sender)?;1640 Self::check_white_list(target_collection, &recipient)?;1641 }16421643 match target_collection.mode1644 {1645 CollectionMode::NFT => Self::transfer_nft(target_collection, item_id, sender.clone(), recipient.clone())?,1646 CollectionMode::Fungible(_) => Self::transfer_fungible(target_collection, value, &sender, &recipient)?,1647 CollectionMode::ReFungible => Self::transfer_refungible(target_collection, item_id, value, sender.clone(), recipient.clone())?,1648 _ => ()1649 };16501651 Self::deposit_event(RawEvent::Transfer(target_collection.id, item_id, sender, recipient, value));16521653 Ok(())1654 }165516561657 fn is_correct_transfer(collection: &CollectionHandle<T>, recipient: &T::AccountId) -> DispatchResult {1658 let collection_id = collection.id;16591660 1661 let account_items: u32 = <AddressTokens<T>>::get(collection_id, recipient).len() as u32;1662 ensure!(collection.limits.account_token_ownership_limit > account_items, Error::<T>::AccountTokenLimitExceeded);1663 1664 Ok(())1665 }16661667 fn can_create_items_in_collection(collection: &CollectionHandle<T>, sender: &T::AccountId, owner: &T::AccountId, amount: u32) -> DispatchResult {1668 let collection_id = collection.id;16691670 1671 let total_items: u32 = ItemListIndex::get(collection_id)1672 .checked_add(amount)1673 .ok_or(Error::<T>::CollectionTokenLimitExceeded)?;1674 let account_items: u32 = (<AddressTokens<T>>::get(collection_id, owner).len() as u32)1675 .checked_add(amount)1676 .ok_or(Error::<T>::AccountTokenLimitExceeded)?;1677 ensure!(collection.limits.token_limit >= total_items, Error::<T>::CollectionTokenLimitExceeded);1678 ensure!(collection.limits.account_token_ownership_limit >= account_items, Error::<T>::AccountTokenLimitExceeded);16791680 if !Self::is_owner_or_admin_permissions(collection, sender.clone()) {1681 ensure!(collection.mint_mode == true, Error::<T>::PublicMintingNotAllowed);1682 Self::check_white_list(collection, owner)?;1683 Self::check_white_list(collection, sender)?;1684 }16851686 Ok(())1687 }16881689 fn validate_create_item_args(target_collection: &CollectionHandle<T>, data: &CreateItemData) -> DispatchResult {1690 match target_collection.mode1691 {1692 CollectionMode::NFT => {1693 if let CreateItemData::NFT(data) = data {1694 1695 ensure!(ChainLimit::get().custom_data_limit >= data.const_data.len() as u32, Error::<T>::TokenConstDataLimitExceeded);1696 ensure!(ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);1697 } else {1698 fail!(Error::<T>::NotNftDataUsedToMintNftCollectionToken);1699 }1700 },1701 CollectionMode::Fungible(_) => {1702 if let CreateItemData::Fungible(_) = data {1703 } else {1704 fail!(Error::<T>::NotFungibleDataUsedToMintFungibleCollectionToken);1705 }1706 },1707 CollectionMode::ReFungible => {1708 if let CreateItemData::ReFungible(data) = data {17091710 1711 ensure!(ChainLimit::get().custom_data_limit >= data.const_data.len() as u32, Error::<T>::TokenConstDataLimitExceeded);1712 ensure!(ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);17131714 1715 ensure!(data.pieces <= MAX_REFUNGIBLE_PIECES, Error::<T>::WrongRefungiblePieces);1716 ensure!(data.pieces > 0, Error::<T>::WrongRefungiblePieces);1717 } else {1718 fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);1719 }1720 },1721 _ => { fail!(Error::<T>::UnexpectedCollectionType); }1722 };17231724 Ok(())1725 }17261727 fn create_item_no_validation(collection: &CollectionHandle<T>, owner: T::AccountId, data: CreateItemData) -> DispatchResult {1728 let collection_id = collection.id;17291730 match data1731 {1732 CreateItemData::NFT(data) => {1733 let item = NftItemType {1734 owner: owner.clone(),1735 const_data: data.const_data,1736 variable_data: data.variable_data1737 };17381739 Self::add_nft_item(collection, item)?;1740 },1741 CreateItemData::Fungible(data) => {1742 Self::add_fungible_item(collection, &owner, data.value)?;1743 },1744 CreateItemData::ReFungible(data) => {1745 let mut owner_list = Vec::new();1746 owner_list.push(Ownership {owner: owner.clone(), fraction: data.pieces});17471748 let item = ReFungibleItemType {1749 owner: owner_list,1750 const_data: data.const_data,1751 variable_data: data.variable_data1752 };17531754 Self::add_refungible_item(collection, item)?;1755 }1756 };17571758 1759 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id), owner));17601761 Ok(())1762 }17631764 fn add_fungible_item(collection: &CollectionHandle<T>, owner: &T::AccountId, value: u128) -> DispatchResult {1765 let collection_id = collection.id;17661767 1768 let mut balance: u128 = 0;1769 if <FungibleItemList<T>>::contains_key(collection_id, owner) {1770 balance = <FungibleItemList<T>>::get(collection_id, owner).value;1771 } 17721773 1774 let item = FungibleItemType {1775 value: balance + value1776 };1777 <FungibleItemList<T>>::insert(collection_id, (*owner).clone(), item);17781779 1780 let new_balance = <Balance<T>>::get(collection_id, owner)1781 .checked_add(value)1782 .ok_or(Error::<T>::NumOverflow)?;1783 <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);17841785 Ok(())1786 }17871788 fn add_refungible_item(collection: &CollectionHandle<T>, item: ReFungibleItemType<T::AccountId>) -> DispatchResult {1789 let collection_id = collection.id;17901791 let current_index = <ItemListIndex>::get(collection_id)1792 .checked_add(1)1793 .ok_or(Error::<T>::NumOverflow)?;1794 let itemcopy = item.clone();17951796 let value = item.owner.first().unwrap().fraction;1797 let owner = item.owner.first().unwrap().owner.clone();17981799 Self::add_token_index(collection_id, current_index, &owner)?;18001801 <ItemListIndex>::insert(collection_id, current_index);1802 <ReFungibleItemList<T>>::insert(collection_id, current_index, itemcopy);18031804 1805 let new_balance = <Balance<T>>::get(collection_id, &owner)1806 .checked_add(value)1807 .ok_or(Error::<T>::NumOverflow)?;1808 <Balance<T>>::insert(collection_id, owner.clone(), new_balance);18091810 Ok(())1811 }18121813 fn add_nft_item(collection: &CollectionHandle<T>, item: NftItemType<T::AccountId>) -> DispatchResult {1814 let collection_id = collection.id;18151816 let current_index = <ItemListIndex>::get(collection_id)1817 .checked_add(1)1818 .ok_or(Error::<T>::NumOverflow)?;18191820 let item_owner = item.owner.clone();1821 Self::add_token_index(collection_id, current_index, &item.owner)?;18221823 <ItemListIndex>::insert(collection_id, current_index);1824 <NftItemList<T>>::insert(collection_id, current_index, item);18251826 1827 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())1828 .checked_add(1)1829 .ok_or(Error::<T>::NumOverflow)?;1830 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);18311832 Ok(())1833 }18341835 fn burn_refungible_item(1836 collection: &CollectionHandle<T>,1837 item_id: TokenId,1838 owner: &T::AccountId,1839 ) -> DispatchResult {1840 let collection_id = collection.id;18411842 ensure!(1843 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1844 Error::<T>::TokenNotFound1845 );1846 let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id);1847 let rft_balance = token1848 .owner1849 .iter()1850 .filter(|&i| i.owner == *owner)1851 .next()1852 .unwrap();1853 Self::remove_token_index(collection_id, item_id, owner)?;18541855 1856 let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.clone())1857 .checked_sub(rft_balance.fraction)1858 .ok_or(Error::<T>::NumOverflow)?;1859 <Balance<T>>::insert(collection_id, rft_balance.owner.clone(), new_balance);18601861 1862 let index = token1863 .owner1864 .iter()1865 .position(|i| i.owner == *owner)1866 .unwrap();1867 token.owner.remove(index);1868 let owner_count = token.owner.len();18691870 1871 if owner_count == 0 {1872 <ReFungibleItemList<T>>::remove(collection_id, item_id);1873 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);1874 }1875 else {1876 <ReFungibleItemList<T>>::insert(collection_id, item_id, token);1877 }18781879 Ok(())1880 }18811882 fn burn_nft_item(collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {1883 let collection_id = collection.id;18841885 ensure!(1886 <NftItemList<T>>::contains_key(collection_id, item_id),1887 Error::<T>::TokenNotFound1888 );1889 let item = <NftItemList<T>>::get(collection_id, item_id);1890 Self::remove_token_index(collection_id, item_id, &item.owner)?;18911892 1893 let new_balance = <Balance<T>>::get(collection_id, &item.owner)1894 .checked_sub(1)1895 .ok_or(Error::<T>::NumOverflow)?;1896 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);1897 <NftItemList<T>>::remove(collection_id, item_id);1898 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);18991900 Ok(())1901 }19021903 fn burn_fungible_item(owner: &T::AccountId, collection: &CollectionHandle<T>, value: u128) -> DispatchResult {1904 let collection_id = collection.id;19051906 ensure!(1907 <FungibleItemList<T>>::contains_key(collection_id, owner),1908 Error::<T>::TokenNotFound1909 );1910 let mut balance = <FungibleItemList<T>>::get(collection_id, owner);1911 ensure!(balance.value >= value, Error::<T>::TokenValueNotEnough);19121913 1914 let new_balance = <Balance<T>>::get(collection_id, owner)1915 .checked_sub(value)1916 .ok_or(Error::<T>::NumOverflow)?;1917 <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);19181919 if balance.value - value > 0 {1920 balance.value -= value;1921 <FungibleItemList<T>>::insert(collection_id, (*owner).clone(), balance);1922 }1923 else {1924 <FungibleItemList<T>>::remove(collection_id, owner);1925 }19261927 Ok(())1928 }19291930 pub fn get_collection(collection_id: CollectionId) -> Result<CollectionHandle<T>, sp_runtime::DispatchError> {1931 Ok(<CollectionById<T>>::get(collection_id)1932 .map(|collection| CollectionHandle {1933 id: collection_id,1934 collection1935 })1936 .ok_or(Error::<T>::CollectionNotFound)?)1937 }19381939 fn save_collection(collection: CollectionHandle<T>) {1940 <CollectionById<T>>::insert(collection.id, collection.collection);1941 }19421943 fn check_owner_permissions(target_collection: &CollectionHandle<T>, subject: T::AccountId) -> DispatchResult {1944 ensure!(1945 subject == target_collection.owner,1946 Error::<T>::NoPermission1947 );19481949 Ok(())1950 }19511952 fn is_owner_or_admin_permissions(collection: &CollectionHandle<T>, subject: T::AccountId) -> bool {1953 let mut result: bool = subject == collection.owner;1954 let exists = <AdminList<T>>::contains_key(collection.id);19551956 if !result & exists {1957 if <AdminList<T>>::get(collection.id).contains(&subject) {1958 result = true1959 }1960 }19611962 result1963 }19641965 fn check_owner_or_admin_permissions(1966 collection: &CollectionHandle<T>,1967 subject: T::AccountId,1968 ) -> DispatchResult {1969 let result = Self::is_owner_or_admin_permissions(collection, subject.clone());19701971 ensure!(1972 result,1973 Error::<T>::NoPermission1974 );1975 Ok(())1976 }19771978 fn owned_amount(1979 subject: T::AccountId,1980 target_collection: &CollectionHandle<T>,1981 item_id: TokenId,1982 ) -> Option<u128> {1983 let collection_id = target_collection.id;19841985 match target_collection.mode {1986 CollectionMode::NFT => {1987 if <NftItemList<T>>::get(collection_id, item_id).owner == subject {1988 return Some(1)1989 }1990 None1991 },1992 CollectionMode::Fungible(_) => {1993 if <FungibleItemList<T>>::contains_key(collection_id, &subject) {1994 return Some(<FungibleItemList<T>>::get(collection_id, &subject)1995 .value);1996 }1997 None1998 },1999 CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)2000 .owner2001 .iter()2002 .find(|i| i.owner == subject)2003 .map(|i| i.fraction),2004 CollectionMode::Invalid => None,2005 }2006 }20072008 fn is_item_owner(subject: T::AccountId, target_collection: &CollectionHandle<T>, item_id: TokenId) -> bool {2009 let collection_id = target_collection.id;20102011 match target_collection.mode {2012 CollectionMode::NFT => {2013 <NftItemList<T>>::get(collection_id, item_id).owner == subject2014 }2015 CollectionMode::Fungible(_) => {2016 <FungibleItemList<T>>::contains_key(collection_id, &subject)2017 }2018 CollectionMode::ReFungible => {2019 <ReFungibleItemList<T>>::get(collection_id, item_id)2020 .owner2021 .iter()2022 .any(|i| i.owner == subject)2023 }2024 CollectionMode::Invalid => false,2025 }2026 }20272028 fn check_white_list(collection: &CollectionHandle<T>, address: &T::AccountId) -> DispatchResult {2029 let collection_id = collection.id;20302031 let mes = Error::<T>::AddresNotInWhiteList;2032 ensure!(<WhiteList<T>>::contains_key(collection_id, address), mes);20332034 Ok(())2035 }20362037 2038 2039 fn token_exists(2040 target_collection: &CollectionHandle<T>,2041 item_id: TokenId,2042 owner: &T::AccountId2043 ) -> DispatchResult {2044 let collection_id = target_collection.id;2045 let exists = match target_collection.mode2046 {2047 CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),2048 CollectionMode::Fungible(_) => <FungibleItemList<T>>::contains_key(collection_id, owner),2049 CollectionMode::ReFungible => <ReFungibleItemList<T>>::contains_key(collection_id, item_id),2050 _ => false2051 };20522053 ensure!(exists == true, Error::<T>::TokenNotFound);2054 Ok(())2055 }20562057 fn transfer_fungible(2058 collection: &CollectionHandle<T>,2059 value: u128,2060 owner: &T::AccountId,2061 recipient: &T::AccountId,2062 ) -> DispatchResult {2063 let collection_id = collection.id;2064 Self::token_exists(&collection, 0, owner)?;20652066 let mut balance = <FungibleItemList<T>>::get(collection_id, owner);2067 ensure!(balance.value >= value, Error::<T>::TokenValueTooLow);20682069 2070 Self::add_fungible_item(collection, recipient, value)?;20712072 2073 <Balance<T>>::insert(collection_id, (*owner).clone(), balance.value - value);20742075 2076 if balance.value == value {2077 <FungibleItemList<T>>::remove(collection_id, owner);2078 }2079 else {2080 balance.value -= value;2081 <FungibleItemList<T>>::insert(collection_id, (*owner).clone(), balance);2082 }20832084 Ok(())2085 }20862087 fn transfer_refungible(2088 collection: &CollectionHandle<T>,2089 item_id: TokenId,2090 value: u128,2091 owner: T::AccountId,2092 new_owner: T::AccountId,2093 ) -> DispatchResult {2094 let collection_id = collection.id;2095 Self::token_exists(collection, item_id, &owner)?;20962097 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);2098 let item = full_item2099 .owner2100 .iter()2101 .filter(|i| i.owner == owner)2102 .next()2103 .ok_or(Error::<T>::NumOverflow)?;2104 let amount = item.fraction;21052106 ensure!(amount >= value, Error::<T>::TokenValueTooLow);21072108 2109 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())2110 .checked_sub(value)2111 .ok_or(Error::<T>::NumOverflow)?;2112 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);21132114 let balancenew_owner = <Balance<T>>::get(collection_id, new_owner.clone())2115 .checked_add(value)2116 .ok_or(Error::<T>::NumOverflow)?;2117 <Balance<T>>::insert(collection_id, new_owner.clone(), balancenew_owner);21182119 let old_owner = item.owner.clone();2120 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);21212122 2123 if amount == value && !new_owner_has_account {2124 2125 2126 let mut new_full_item = full_item.clone();2127 new_full_item2128 .owner2129 .iter_mut()2130 .find(|i| i.owner == owner)2131 .unwrap()2132 .owner = new_owner.clone();2133 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);21342135 2136 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;2137 } else {2138 let mut new_full_item = full_item.clone();2139 new_full_item2140 .owner2141 .iter_mut()2142 .find(|i| i.owner == owner)2143 .unwrap()2144 .fraction -= value;21452146 2147 if new_owner_has_account {2148 2149 new_full_item2150 .owner2151 .iter_mut()2152 .find(|i| i.owner == new_owner)2153 .unwrap()2154 .fraction += value;2155 } else {2156 2157 new_full_item.owner.push(Ownership {2158 owner: new_owner.clone(),2159 fraction: value,2160 });2161 Self::add_token_index(collection_id, item_id, &new_owner)?;2162 }21632164 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);2165 }21662167 Ok(())2168 }21692170 fn transfer_nft(2171 collection: &CollectionHandle<T>,2172 item_id: TokenId,2173 sender: T::AccountId,2174 new_owner: T::AccountId,2175 ) -> DispatchResult {2176 let collection_id = collection.id;2177 Self::token_exists(&collection, item_id, &sender)?;21782179 let mut item = <NftItemList<T>>::get(collection_id, item_id);21802181 ensure!(2182 sender == item.owner,2183 Error::<T>::MustBeTokenOwner2184 );21852186 2187 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())2188 .checked_sub(1)2189 .ok_or(Error::<T>::NumOverflow)?;2190 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);21912192 let balancenew_owner = <Balance<T>>::get(collection_id, new_owner.clone())2193 .checked_add(1)2194 .ok_or(Error::<T>::NumOverflow)?;2195 <Balance<T>>::insert(collection_id, new_owner.clone(), balancenew_owner);21962197 2198 let old_owner = item.owner.clone();2199 item.owner = new_owner.clone();2200 <NftItemList<T>>::insert(collection_id, item_id, item);22012202 2203 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;22042205 Ok(())2206 }2207 2208 fn set_re_fungible_variable_data(2209 collection: &CollectionHandle<T>,2210 item_id: TokenId,2211 data: Vec<u8>2212 ) -> DispatchResult {2213 let collection_id = collection.id;2214 let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id);22152216 item.variable_data = data;22172218 <ReFungibleItemList<T>>::insert(collection_id, item_id, item);22192220 Ok(())2221 }22222223 fn set_nft_variable_data(2224 collection: &CollectionHandle<T>,2225 item_id: TokenId,2226 data: Vec<u8>2227 ) -> DispatchResult {2228 let collection_id = collection.id;2229 let mut item = <NftItemList<T>>::get(collection_id, item_id);2230 2231 item.variable_data = data;22322233 <NftItemList<T>>::insert(collection_id, item_id, item);2234 2235 Ok(())2236 }22372238 fn init_collection(item: &Collection<T>) {2239 2240 assert!(2241 item.decimal_points <= MAX_DECIMAL_POINTS,2242 "decimal_points parameter must be lower than MAX_DECIMAL_POINTS"2243 );2244 assert!(2245 item.name.len() <= 64,2246 "Collection name can not be longer than 63 char"2247 );2248 assert!(2249 item.name.len() <= 256,2250 "Collection description can not be longer than 255 char"2251 );2252 assert!(2253 item.token_prefix.len() <= 16,2254 "Token prefix can not be longer than 15 char"2255 );22562257 2258 let next_id = CreatedCollectionCount::get()2259 .checked_add(1)2260 .unwrap();22612262 CreatedCollectionCount::put(next_id);2263 }22642265 fn init_nft_token(collection_id: CollectionId, item: &NftItemType<T::AccountId>) {2266 let current_index = <ItemListIndex>::get(collection_id)2267 .checked_add(1)2268 .unwrap();22692270 let item_owner = item.owner.clone();2271 Self::add_token_index(collection_id, current_index, &item.owner).unwrap();22722273 <ItemListIndex>::insert(collection_id, current_index);22742275 2276 let new_balance = <Balance<T>>::get(collection_id, &item_owner)2277 .checked_add(1)2278 .unwrap();2279 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);2280 }22812282 fn init_fungible_token(collection_id: CollectionId, owner: &T::AccountId, item: &FungibleItemType) {2283 let current_index = <ItemListIndex>::get(collection_id)2284 .checked_add(1)2285 .unwrap();22862287 Self::add_token_index(collection_id, current_index, owner).unwrap();22882289 <ItemListIndex>::insert(collection_id, current_index);22902291 2292 let new_balance = <Balance<T>>::get(collection_id, owner)2293 .checked_add(item.value)2294 .unwrap();2295 <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);2296 }22972298 fn init_refungible_token(collection_id: CollectionId, item: &ReFungibleItemType<T::AccountId>) {2299 let current_index = <ItemListIndex>::get(collection_id)2300 .checked_add(1)2301 .unwrap();23022303 let value = item.owner.first().unwrap().fraction;2304 let owner = item.owner.first().unwrap().owner.clone();23052306 Self::add_token_index(collection_id, current_index, &owner).unwrap();23072308 <ItemListIndex>::insert(collection_id, current_index);23092310 2311 let new_balance = <Balance<T>>::get(collection_id, &owner)2312 .checked_add(value)2313 .unwrap();2314 <Balance<T>>::insert(collection_id, owner.clone(), new_balance);2315 }23162317 fn add_token_index(collection_id: CollectionId, item_index: TokenId, owner: &T::AccountId) -> DispatchResult {2318 2319 if <AccountItemCount<T>>::contains_key(owner) {23202321 2322 let count = <AccountItemCount<T>>::get(owner);2323 ensure!(count < ChainLimit::get().account_token_ownership_limit, Error::<T>::AddressOwnershipLimitExceeded);23242325 <AccountItemCount<T>>::insert(owner.clone(), count2326 .checked_add(1)2327 .ok_or(Error::<T>::NumOverflow)?);2328 }2329 else {2330 <AccountItemCount<T>>::insert(owner.clone(), 1);2331 }23322333 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner);2334 if list_exists {2335 let mut list = <AddressTokens<T>>::get(collection_id, owner);2336 let item_contains = list.contains(&item_index.clone());23372338 if !item_contains {2339 list.push(item_index.clone());2340 }23412342 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);2343 } else {2344 let mut itm = Vec::new();2345 itm.push(item_index.clone());2346 <AddressTokens<T>>::insert(collection_id, owner.clone(), itm);2347 }23482349 Ok(())2350 }23512352 fn remove_token_index(2353 collection_id: CollectionId,2354 item_index: TokenId,2355 owner: &T::AccountId,2356 ) -> DispatchResult {23572358 2359 <AccountItemCount<T>>::insert(owner.clone(), 2360 <AccountItemCount<T>>::get(owner)2361 .checked_sub(1)2362 .ok_or(Error::<T>::NumOverflow)?);236323642365 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner);2366 if list_exists {2367 let mut list = <AddressTokens<T>>::get(collection_id, owner);2368 let item_contains = list.contains(&item_index.clone());23692370 if item_contains {2371 list.retain(|&item| item != item_index);2372 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);2373 }2374 }23752376 Ok(())2377 }23782379 fn move_token_index(2380 collection_id: CollectionId,2381 item_index: TokenId,2382 old_owner: &T::AccountId,2383 new_owner: &T::AccountId,2384 ) -> DispatchResult {2385 Self::remove_token_index(collection_id, item_index, old_owner)?;2386 Self::add_token_index(collection_id, item_index, new_owner)?;23872388 Ok(())2389 }2390 2391 fn ensure_contract_owned(account: T::AccountId, contract: &T::AccountId) -> DispatchResult {2392 if <ContractOwner<T>>::contains_key(contract.clone()) {2393 let owner = <ContractOwner<T>>::get(contract);2394 ensure!(account == owner, Error::<T>::NoPermission);2395 } else {2396 fail!(Error::<T>::NoPermission);2397 }23982399 Ok(())2400 }2401}2402240324042405240624072408pub type Multiplier = FixedU128;24092410type BalanceOf<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::Balance;2411241224132414#[derive(Encode, Decode, Clone, Eq, PartialEq)]2415pub struct ChargeTransactionPayment<T: Config>(#[codec(compact)] BalanceOf<T>);24162417impl<T: Config + Send + Sync> sp_std::fmt::Debug 2418 for ChargeTransactionPayment<T>2419{2420 #[cfg(feature = "std")]2421 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {2422 write!(f, "ChargeTransactionPayment<{:?}>", self.0)2423 }2424 #[cfg(not(feature = "std"))]2425 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {2426 Ok(())2427 }2428}24292430impl<T: Config> ChargeTransactionPayment<T>2431where2432 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Call<T>> + IsSubType<pallet_contracts::Call<T>>,2433 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,2434 T::AccountId: AsRef<[u8]>,2435 T::AccountId: UncheckedFrom<T::Hash>,2436{2437 fn traditional_fee(2438 len: usize,2439 info: &DispatchInfoOf<T::Call>,2440 tip: BalanceOf<T>,2441 ) -> BalanceOf<T>2442 where2443 T::Call: Dispatchable<Info = DispatchInfo>,2444 {2445 <pallet_transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)2446 }24472448 fn get_priority(len: usize, info: &DispatchInfoOf<T::Call>, final_fee: BalanceOf<T>) -> TransactionPriority {2449 let weight_saturation = T::BlockWeights::get().max_block / info.weight.max(1);2450 let max_block_length = *T::BlockLength::get().max.get(DispatchClass::Normal);2451 let len_saturation = max_block_length as u64 / (len as u64).max(1);2452 let coefficient: BalanceOf<T> = weight_saturation2453 .min(len_saturation)2454 .saturated_into::<BalanceOf<T>>();2455 final_fee2456 .saturating_mul(coefficient)2457 .saturated_into::<TransactionPriority>()2458 }24592460 fn withdraw_fee(2461 &self,2462 who: &T::AccountId,2463 call: &T::Call,2464 info: &DispatchInfoOf<T::Call>,2465 len: usize,2466 ) -> Result<2467 (2468 BalanceOf<T>,2469 <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,2470 ),2471 TransactionValidityError,2472 > {2473 let tip = self.0;24742475 2476 2477 2478 2479 2480 2481 2482 let fee = Self::traditional_fee(len, info, tip);24832484 2485 if fee.is_zero() {2486 return <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(who, call, info, fee, tip)2487 .map(|i| (fee, i));2488 }24892490 2491 2492 let mut sponsor: Option<T::AccountId> = (|| match IsSubType::<Call<T>>::is_sub_type(call) {2493 Some(Call::create_item(collection_id, _owner, _properties)) => {2494 let collection = <CollectionById<T>>::get(collection_id)?;24952496 2497 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;24982499 let limit = collection.limits.sponsor_transfer_timeout;2500 if <CreateItemBasket<T>>::contains_key((collection_id, &who)) {2501 let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));2502 let limit_time = last_tx_block + limit.into();2503 if block_number <= limit_time {2504 return None;2505 }2506 }2507 <CreateItemBasket<T>>::insert((collection_id, who.clone()), block_number);25082509 2510 if (collection.limits.sponsored_data_size >= (_properties.len() as u32)) &&2511 (collection.sponsor_confirmed)2512 {2513 Some(collection.sponsor)2514 } else {2515 None2516 }2517 }2518 Some(Call::transfer(_new_owner, collection_id, item_id, _value)) => {2519 let collection = <CollectionById<T>>::get(collection_id)?;2520 2521 let mut sponsor_transfer = false;2522 if collection.sponsor_confirmed {25232524 let collection_limits = collection.limits;2525 let collection_mode = collection.mode;2526 2527 2528 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;2529 sponsor_transfer = match collection_mode {2530 CollectionMode::NFT => {2531 2532 2533 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {2534 collection_limits.sponsor_transfer_timeout2535 } else {2536 ChainLimit::get().nft_sponsor_transfer_timeout2537 };2538 2539 let mut sponsored = true;2540 if <NftTransferBasket<T>>::contains_key(collection_id, item_id) {2541 let last_tx_block = <NftTransferBasket<T>>::get(collection_id, item_id);2542 let limit_time = last_tx_block + limit.into();2543 if block_number <= limit_time {2544 sponsored = false;2545 }2546 }2547 if sponsored {2548 <NftTransferBasket<T>>::insert(collection_id, item_id, block_number);2549 }25502551 sponsored2552 }2553 CollectionMode::Fungible(_) => {2554 2555 2556 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {2557 collection_limits.sponsor_transfer_timeout2558 } else {2559 ChainLimit::get().fungible_sponsor_transfer_timeout2560 };2561 2562 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;2563 let mut sponsored = true;2564 if <FungibleTransferBasket<T>>::contains_key(collection_id, who) {2565 let last_tx_block = <FungibleTransferBasket<T>>::get(collection_id, who);2566 let limit_time = last_tx_block + limit.into();2567 if block_number <= limit_time {2568 sponsored = false;2569 }2570 }2571 if sponsored {2572 <FungibleTransferBasket<T>>::insert(collection_id, who, block_number);2573 }25742575 sponsored2576 }2577 CollectionMode::ReFungible => {2578 2579 2580 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {2581 collection_limits.sponsor_transfer_timeout2582 } else {2583 ChainLimit::get().refungible_sponsor_transfer_timeout2584 };2585 2586 let mut sponsored = true;2587 if <ReFungibleTransferBasket<T>>::contains_key(collection_id, item_id) {2588 let last_tx_block = <ReFungibleTransferBasket<T>>::get(collection_id, item_id);2589 let limit_time = last_tx_block + limit.into();2590 if block_number <= limit_time {2591 sponsored = false;2592 }2593 }2594 if sponsored {2595 <ReFungibleTransferBasket<T>>::insert(collection_id, item_id, block_number);2596 }25972598 sponsored2599 }2600 _ => {2601 false2602 },2603 };2604 }26052606 if !sponsor_transfer {2607 None2608 } else {2609 Some(collection.sponsor)2610 }2611 }26122613 Some(Call::set_variable_meta_data(collection_id, item_id, data)) => {2614 let mut sponsor_metadata_changes = false;26152616 let collection = <CollectionById<T>>::get(collection_id)?;26172618 if2619 collection.sponsor_confirmed &&2620 2621 2622 !matches!(collection.mode, CollectionMode::Fungible(_)) &&2623 data.len() <= collection.limits.sponsored_data_size as usize2624 {2625 if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit {2626 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;26272628 if <VariableMetaDataBasket<T>>::get(collection_id, item_id)2629 .map(|last_block| block_number - last_block > rate_limit)2630 .unwrap_or(true) 2631 {2632 sponsor_metadata_changes = true;2633 <VariableMetaDataBasket<T>>::insert(collection_id, item_id, block_number);2634 }2635 }2636 }26372638 if !sponsor_metadata_changes {2639 None2640 } else {2641 Some(collection.sponsor)2642 }2643 }26442645 _ => None,2646 })();26472648 match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {2649 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {26502651 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());26522653 let owned_contract = <ContractOwner<T>>::contains_key(called_contract.clone())2654 && <ContractOwner<T>>::get(called_contract.clone()) == *who;2655 let white_list_enabled = <ContractWhiteListEnabled<T>>::contains_key(called_contract.clone()) && <ContractWhiteListEnabled<T>>::get(called_contract.clone());2656 2657 if !owned_contract && white_list_enabled {2658 if !<ContractWhiteList<T>>::contains_key(called_contract.clone(), who) {2659 return Err(InvalidTransaction::Call.into());2660 }2661 }2662 },2663 _ => {},2664 }26652666 2667 sponsor = sponsor.or_else(|| match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {26682669 2670 Some(pallet_contracts::Call::instantiate(_endowment, _gas_limit, code_hash, _data, salt)) => {26712672 let new_contract_address = <pallet_contracts::Module<T>>::contract_address(2673 &who,2674 code_hash,2675 salt,2676 );2677 <ContractOwner<T>>::insert(new_contract_address.clone(), who.clone());26782679 None2680 },26812682 2683 Some(pallet_contracts::Call::instantiate_with_code(_endowment, _gas_limit, _code, _data, _salt)) => {26842685 let new_contract_address = <pallet_contracts::Module<T>>::contract_address(2686 &who,2687 &T::Hashing::hash(&_code),2688 _salt,2689 );26902691 <ContractOwner<T>>::insert(new_contract_address.clone(), who.clone());26922693 None2694 }26952696 2697 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {26982699 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());27002701 let mut sponsor_transfer = false;2702 if <ContractSponsoringRateLimit<T>>::contains_key(called_contract.clone()) {2703 let last_tx_block = <ContractSponsorBasket<T>>::get((&called_contract, &who));2704 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;2705 let rate_limit = <ContractSponsoringRateLimit<T>>::get(&called_contract);2706 let limit_time = last_tx_block + rate_limit;27072708 if block_number >= limit_time {2709 <ContractSponsorBasket<T>>::insert((called_contract.clone(), who.clone()), block_number);2710 sponsor_transfer = true;2711 }2712 } else {2713 sponsor_transfer = false;2714 }2715 2716 if sponsor_transfer {2717 if <ContractSelfSponsoring<T>>::contains_key(called_contract.clone()) {2718 if <ContractSelfSponsoring<T>>::get(called_contract.clone()) {2719 return Some(called_contract);2720 }2721 }2722 }27232724 None2725 },27262727 _ => None,2728 });27292730 let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());27312732 <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(&who_pays_fee, call, info, fee, tip)2733 .map(|i| (fee, i))2734 }2735}273627372738impl<T: Config + Send + Sync> SignedExtension2739 for ChargeTransactionPayment<T>2740where2741 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,2742 T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Call<T>> + IsSubType<pallet_contracts::Call<T>>,2743 T::AccountId: AsRef<[u8]>,2744 T::AccountId: UncheckedFrom<T::Hash>,2745{2746 const IDENTIFIER: &'static str = "ChargeTransactionPayment";2747 type AccountId = T::AccountId;2748 type Call = T::Call;2749 type AdditionalSigned = ();2750 type Pre = (2751 2752 BalanceOf<T>,2753 2754 Self::AccountId,2755 2756 <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,2757 );2758 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {2759 Ok(())2760 }27612762 fn validate(2763 &self,2764 who: &Self::AccountId,2765 call: &Self::Call,2766 info: &DispatchInfoOf<Self::Call>,2767 len: usize,2768 ) -> TransactionValidity {2769 let (fee, _) = self.withdraw_fee(who, call, info, len)?;2770 Ok(ValidTransaction {2771 priority: Self::get_priority(len, info, fee),2772 ..Default::default()2773 })2774 }27752776 fn pre_dispatch(2777 self,2778 who: &Self::AccountId,2779 call: &Self::Call,2780 info: &DispatchInfoOf<Self::Call>,2781 len: usize,2782 ) -> Result<Self::Pre, TransactionValidityError> {2783 let (_fee, imbalance) = self.withdraw_fee(who, call, info, len)?;2784 Ok((self.0, who.clone(), imbalance))2785 }27862787 fn post_dispatch(2788 pre: Self::Pre,2789 info: &DispatchInfoOf<Self::Call>,2790 post_info: &PostDispatchInfoOf<Self::Call>,2791 len: usize,2792 _result: &DispatchResult,2793 ) -> Result<(), TransactionValidityError> {2794 let (tip, who, imbalance) = pre;2795 let actual_fee = pallet_transaction_payment::Module::<T>::compute_actual_fee(2796 len as u32,2797 info,2798 post_info,2799 tip,2800 );2801 <T as pallet_transaction_payment::Config>::OnChargeTransaction::correct_and_deposit_fee(&who, info, post_info, actual_fee, tip, imbalance)?;2802 Ok(())2803 }2804}28052806