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 codec::{Decode, Encode};17pub use frame_support::{18 construct_runtime, decl_event, decl_module, decl_storage, decl_error,19 dispatch::DispatchResult,20 ensure, fail, parameter_types,21 traits::{22 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,23 Randomness, IsSubType,24 },25 weights::{26 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},27 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,28 WeightToFeePolynomial, DispatchClass,29 },30 StorageValue,31};3233use frame_system::{self as system, ensure_signed, ensure_root};34use sp_runtime::sp_std::prelude::Vec;35use sp_runtime::{36 traits::{37 Hash, DispatchInfoOf, Dispatchable, PostDispatchInfoOf, Saturating, SaturatedConversion, SignedExtension, Zero,38 },39 transaction_validity::{40 TransactionPriority, InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction,41 },42 FixedPointOperand, FixedU128,43};44use sp_runtime::traits::StaticLookup;45use pallet_contracts::chain_extension::UncheckedFrom;46use pallet_transaction_payment::OnChargeTransaction;4748#[cfg(test)]49mod mock;5051#[cfg(test)]52mod tests;5354mod default_weights;5556pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;57pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;58pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;59pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;6061626364pub type CollectionId = u32;65pub type TokenId = u32;66pub type DecimalPoints = u8;6768#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]69#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]70pub enum CollectionMode {71 Invalid,72 NFT,73 74 Fungible(DecimalPoints),75 ReFungible,76}7778impl Default for CollectionMode {79 fn default() -> Self {80 Self::Invalid81 }82}8384impl Into<u8> for CollectionMode {85 fn into(self) -> u8 {86 match self {87 CollectionMode::Invalid => 0,88 CollectionMode::NFT => 1,89 CollectionMode::Fungible(_) => 2,90 CollectionMode::ReFungible => 3,91 }92 }93}9495#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]96#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]97pub enum AccessMode {98 Normal,99 WhiteList,100}101impl Default for AccessMode {102 fn default() -> Self {103 Self::Normal104 }105}106107#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]108#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]109pub enum SchemaVersion {110 ImageURL,111 Unique,112}113impl Default for SchemaVersion {114 fn default() -> Self {115 Self::ImageURL116 }117}118119#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]120#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]121pub struct Ownership<AccountId> {122 pub owner: AccountId,123 pub fraction: u128,124}125126#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]127#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]128pub struct CollectionType<AccountId> {129 pub owner: AccountId,130 pub mode: CollectionMode,131 pub access: AccessMode,132 pub decimal_points: DecimalPoints,133 pub name: Vec<u16>, 134 pub description: Vec<u16>, 135 pub token_prefix: Vec<u8>, 136 pub mint_mode: bool,137 pub offchain_schema: Vec<u8>,138 pub schema_version: SchemaVersion,139 pub sponsor: AccountId, 140 pub sponsor_confirmed: bool, 141 pub limits: CollectionLimits, 142 pub variable_on_chain_schema: Vec<u8>, 143 pub const_on_chain_schema: Vec<u8>, 144}145146#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]147#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]148pub struct NftItemType<AccountId> {149 pub owner: AccountId,150 pub const_data: Vec<u8>,151 pub variable_data: Vec<u8>,152}153154#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]155#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]156pub struct FungibleItemType {157 pub value: u128,158}159160#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]161#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]162pub struct ReFungibleItemType<AccountId> {163 pub owner: Vec<Ownership<AccountId>>,164 pub const_data: Vec<u8>,165 pub variable_data: Vec<u8>,166}167168169170171172173174175176177178179#[derive(Encode, Decode, Debug, Clone, PartialEq)]180#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]181pub struct CollectionLimits {182 pub account_token_ownership_limit: u32,183 pub sponsored_data_size: u32,184 pub token_limit: u32,185186 187 pub sponsor_transfer_timeout: u32,188 pub owner_can_transfer: bool,189 pub owner_can_destroy: bool,190}191192impl Default for CollectionLimits {193 fn default() -> CollectionLimits {194 CollectionLimits { 195 account_token_ownership_limit: 10_000_000, 196 token_limit: u32::max_value(),197 sponsored_data_size: u32::MAX,198 sponsor_transfer_timeout: 14400,199 owner_can_transfer: true,200 owner_can_destroy: true201 }202 }203}204205#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]206#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]207pub struct ChainLimits {208 pub collection_numbers_limit: u32,209 pub account_token_ownership_limit: u32,210 pub collections_admins_limit: u64,211 pub custom_data_limit: u32,212213 214 pub nft_sponsor_transfer_timeout: u32,215 pub fungible_sponsor_transfer_timeout: u32,216 pub refungible_sponsor_transfer_timeout: u32,217218 219 pub offchain_schema_limit: u32,220 pub variable_on_chain_schema_limit: u32,221 pub const_on_chain_schema_limit: u32,222}223224pub trait WeightInfo {225 fn create_collection() -> Weight;226 fn destroy_collection() -> Weight;227 fn add_to_white_list() -> Weight;228 fn remove_from_white_list() -> Weight;229 fn set_public_access_mode() -> Weight;230 fn set_mint_permission() -> Weight;231 fn change_collection_owner() -> Weight;232 fn add_collection_admin() -> Weight;233 fn remove_collection_admin() -> Weight;234 fn set_collection_sponsor() -> Weight;235 fn confirm_sponsorship() -> Weight;236 fn remove_collection_sponsor() -> Weight;237 fn create_item(s: usize) -> Weight;238 fn burn_item() -> Weight;239 fn transfer() -> Weight;240 fn approve() -> Weight;241 fn transfer_from() -> Weight;242 fn set_offchain_schema() -> Weight;243 fn set_const_on_chain_schema() -> Weight;244 fn set_variable_on_chain_schema() -> Weight;245 fn set_variable_meta_data() -> Weight;246 fn enable_contract_sponsoring() -> Weight;247 fn set_schema_version() -> Weight;248 fn set_chain_limits() -> Weight;249 fn set_contract_sponsoring_rate_limit() -> Weight;250 fn toggle_contract_white_list() -> Weight;251 fn add_to_contract_white_list() -> Weight;252 fn remove_from_contract_white_list() -> Weight;253 fn set_collection_limits() -> Weight;254}255256#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]257#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]258pub struct CreateNftData {259 pub const_data: Vec<u8>,260 pub variable_data: Vec<u8>,261}262263#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]264#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]265pub struct CreateFungibleData {266 pub value: u128,267}268269#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]270#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]271pub struct CreateReFungibleData {272 pub const_data: Vec<u8>,273 pub variable_data: Vec<u8>,274 pub pieces: u128,275}276277#[derive(Encode, Decode, Debug, Clone, PartialEq)]278#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]279pub enum CreateItemData {280 NFT(CreateNftData),281 Fungible(CreateFungibleData),282 ReFungible(CreateReFungibleData),283}284285impl CreateItemData {286 pub fn len(&self) -> usize {287 let len = match self {288 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),289 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),290 _ => 0291 };292 293 return len;294 }295}296297impl From<CreateNftData> for CreateItemData {298 fn from(item: CreateNftData) -> Self {299 CreateItemData::NFT(item)300 }301}302303impl From<CreateReFungibleData> for CreateItemData {304 fn from(item: CreateReFungibleData) -> Self {305 CreateItemData::ReFungible(item)306 }307}308309impl From<CreateFungibleData> for CreateItemData {310 fn from(item: CreateFungibleData) -> Self {311 CreateItemData::Fungible(item)312 }313}314315316decl_error! {317 318 pub enum Error for Module<T: Config> {319 320 TotalCollectionsLimitExceeded,321 322 CollectionDecimalPointLimitExceeded, 323 324 CollectionNameLimitExceeded, 325 326 CollectionDescriptionLimitExceeded, 327 328 CollectionTokenPrefixLimitExceeded,329 330 CollectionNotFound,331 332 TokenNotFound,333 334 AdminNotFound,335 336 NumOverflow, 337 338 AlreadyAdmin, 339 340 NoPermission,341 342 ConfirmUnsetSponsorFail,343 344 PublicMintingNotAllowed,345 346 MustBeTokenOwner,347 348 TokenValueTooLow,349 350 NftSizeLimitExceeded,351 352 ApproveNotFound,353 354 TokenValueNotEnough,355 356 ApproveRequired,357 358 AddresNotInWhiteList,359 360 CollectionAdminsLimitExceeded,361 362 AddressOwnershipLimitExceeded,363 364 EmptyArgument,365 366 TokenConstDataLimitExceeded,367 368 TokenVariableDataLimitExceeded,369 370 NotNftDataUsedToMintNftCollectionToken,371 372 NotFungibleDataUsedToMintFungibleCollectionToken,373 374 NotReFungibleDataUsedToMintReFungibleCollectionToken,375 376 UnexpectedCollectionType,377 378 CantStoreMetadataInFungibleTokens,379 380 CollectionTokenLimitExceeded,381 382 AccountTokenLimitExceeded,383 384 CollectionLimitBoundsExceeded,385 386 OwnerPermissionsCantBeReverted,387 388 SchemaDataLimitExceeded,389 390 WrongRefungiblePieces391 }392}393394pub trait Config: system::Config + Sized + pallet_transaction_payment::Config + pallet_contracts::Config {395 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;396397 398 type WeightInfo: WeightInfo;399}400401#[cfg(feature = "runtime-benchmarks")]402mod benchmarking;403404405406407408409410411412413414415416417418419420421422423424425426427428decl_storage! {429 trait Store for Module<T: Config> as Nft {430431 432 433 CreatedCollectionCount: u32;434 435 ChainVersion: u64;436 437 438 ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;439 440441 442 pub ChainLimit get(fn chain_limit) config(): ChainLimits;443 444445 446 447 448 DestroyedCollectionCount: u32;449 450 451 pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;452 453454 455 456 457 pub Collection get(fn collection) config(): map hasher(blake2_128_concat) CollectionId => CollectionType<T::AccountId>;458 459 460 pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::AccountId>;461 462 463 pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;464 465466 467 468 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => u128;469470 471 472 pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;473474 475 476 pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => NftItemType<T::AccountId>;477 478 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;479 480 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => ReFungibleItemType<T::AccountId>;481 482483 484 485 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => Vec<TokenId>;486 487488 489 490 pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;491 492 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;493 494 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;495 496 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;497 498499 500 501 pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => T::AccountId;502 503 pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;504 505 pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;506 507 pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;508 509 pub ContractWhiteListEnabled get(fn contract_white_list_enabled): map hasher(twox_64_concat) T::AccountId => bool; 510 511 pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) T::AccountId => bool; 512 513 }514 add_extra_genesis {515 build(|config: &GenesisConfig<T>| {516 517 for (_num, _c) in &config.collection {518 <Module<T>>::init_collection(_c);519 }520521 for (_num, _c, _i) in &config.nft_item_id {522 <Module<T>>::init_nft_token(*_c, _i);523 }524525 for (collection_id, account_id, fungible_item) in &config.fungible_item_id {526 <Module<T>>::init_fungible_token(*collection_id, account_id, fungible_item);527 }528529 for (_num, _c, _i) in &config.refungible_item_id {530 <Module<T>>::init_refungible_token(*_c, _i);531 }532 })533 }534}535536decl_event!(537 pub enum Event<T>538 where539 AccountId = <T as system::Config>::AccountId,540 {541 542 543 544 545 546 547 548 549 550 Created(CollectionId, u8, AccountId),551552 553 554 555 556 557 558 559 560 561 ItemCreated(CollectionId, TokenId, AccountId),562563 564 565 566 567 568 569 570 ItemDestroyed(CollectionId, TokenId),571572 573 574 575 576 577 578 579 580 581 582 583 Transfer(CollectionId, TokenId, AccountId, AccountId, u128),584 }585);586587decl_module! {588 pub struct Module<T: Config> for enum Call 589 where 590 origin: T::Origin591 {592 fn deposit_event() = default;593 type Error = Error<T>;594595 fn on_initialize(now: T::BlockNumber) -> Weight {596 0597 }598599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 #[weight = <T as Config>::WeightInfo::create_collection()]616 pub fn create_collection(origin,617 collection_name: Vec<u16>,618 collection_description: Vec<u16>,619 token_prefix: Vec<u8>,620 mode: CollectionMode) -> DispatchResult {621622 623 let who = ensure_signed(origin)?;624625 let decimal_points = match mode {626 CollectionMode::Fungible(points) => points,627 _ => 0628 };629630 let chain_limit = ChainLimit::get();631632 let created_count = CreatedCollectionCount::get();633 let destroyed_count = DestroyedCollectionCount::get();634635 636 ensure!(created_count - destroyed_count < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);637638 639 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);640 ensure!(collection_name.len() <= 64, Error::<T>::CollectionNameLimitExceeded);641 ensure!(collection_description.len() <= 256, Error::<T>::CollectionDescriptionLimitExceeded);642 ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);643644 645 let next_id = created_count646 .checked_add(1)647 .ok_or(Error::<T>::NumOverflow)?;648649 CreatedCollectionCount::put(next_id);650651 let limits = CollectionLimits {652 sponsored_data_size: chain_limit.custom_data_limit,653 ..Default::default()654 };655656 657 let new_collection = CollectionType {658 owner: who.clone(),659 name: collection_name,660 mode: mode.clone(),661 mint_mode: false,662 access: AccessMode::Normal,663 description: collection_description,664 decimal_points: decimal_points,665 token_prefix: token_prefix,666 offchain_schema: Vec::new(),667 schema_version: SchemaVersion::ImageURL,668 sponsor: T::AccountId::default(),669 sponsor_confirmed: false,670 variable_on_chain_schema: Vec::new(),671 const_on_chain_schema: Vec::new(),672 limits,673 };674675 676 <Collection<T>>::insert(next_id, new_collection);677678 679 Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));680681 Ok(())682 }683684 685 686 687 688 689 690 691 692 693 #[weight = <T as Config>::WeightInfo::destroy_collection()]694 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {695696 let sender = ensure_signed(origin)?;697 Self::check_owner_permissions(collection_id, sender)?;698699 let target_collection = <Collection<T>>::get(collection_id);700 if !target_collection.limits.owner_can_destroy {701 fail!(Error::<T>::NoPermission);702 }703704 <AddressTokens<T>>::remove_prefix(collection_id);705 <Allowances<T>>::remove_prefix(collection_id);706 <Balance<T>>::remove_prefix(collection_id);707 <ItemListIndex>::remove(collection_id);708 <AdminList<T>>::remove(collection_id);709 <Collection<T>>::remove(collection_id);710 <WhiteList<T>>::remove_prefix(collection_id);711712 <NftItemList<T>>::remove_prefix(collection_id);713 <FungibleItemList<T>>::remove_prefix(collection_id);714 <ReFungibleItemList<T>>::remove_prefix(collection_id);715716 <NftTransferBasket<T>>::remove_prefix(collection_id);717 <FungibleTransferBasket<T>>::remove_prefix(collection_id);718 <ReFungibleTransferBasket<T>>::remove_prefix(collection_id);719720 DestroyedCollectionCount::put(DestroyedCollectionCount::get()721 .checked_add(1)722 .ok_or(Error::<T>::NumOverflow)?);723724 Ok(())725 }726727 728 729 730 731 732 733 734 735 736 737 738 739 #[weight = <T as Config>::WeightInfo::add_to_white_list()]740 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{741742 let sender = ensure_signed(origin)?;743 Self::check_owner_or_admin_permissions(collection_id, sender)?;744745 <WhiteList<T>>::insert(collection_id, address, true);746 747 Ok(())748 }749750 751 752 753 754 755 756 757 758 759 760 761 762 #[weight = <T as Config>::WeightInfo::remove_from_white_list()]763 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{764765 let sender = ensure_signed(origin)?;766 Self::check_owner_or_admin_permissions(collection_id, sender)?;767768 <WhiteList<T>>::remove(collection_id, address);769770 Ok(())771 }772773 774 775 776 777 778 779 780 781 782 783 784 #[weight = <T as Config>::WeightInfo::set_public_access_mode()]785 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult786 {787 let sender = ensure_signed(origin)?;788789 Self::check_owner_permissions(collection_id, sender)?;790 let mut target_collection = <Collection<T>>::get(collection_id);791 target_collection.access = mode;792 <Collection<T>>::insert(collection_id, target_collection);793794 Ok(())795 }796797 798 799 800 801 802 803 804 805 806 807 808 809 810 #[weight = <T as Config>::WeightInfo::set_mint_permission()]811 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult812 {813 let sender = ensure_signed(origin)?;814815 Self::check_owner_permissions(collection_id, sender)?;816 let mut target_collection = <Collection<T>>::get(collection_id);817 target_collection.mint_mode = mint_permission;818 <Collection<T>>::insert(collection_id, target_collection);819820 Ok(())821 }822823 824 825 826 827 828 829 830 831 832 833 834 #[weight = <T as Config>::WeightInfo::change_collection_owner()]835 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {836837 let sender = ensure_signed(origin)?;838 Self::check_owner_permissions(collection_id, sender)?;839 let mut target_collection = <Collection<T>>::get(collection_id);840 target_collection.owner = new_owner;841 <Collection<T>>::insert(collection_id, target_collection);842843 Ok(())844 }845846 847 848 849 850 851 852 853 854 855 856 857 858 859 #[weight = <T as Config>::WeightInfo::add_collection_admin()]860 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::AccountId) -> DispatchResult {861862 let sender = ensure_signed(origin)?;863 Self::check_owner_or_admin_permissions(collection_id, sender)?;864 let mut admin_arr: Vec<T::AccountId> = Vec::new();865866 if <AdminList<T>>::contains_key(collection_id)867 {868 admin_arr = <AdminList<T>>::get(collection_id);869 ensure!(!admin_arr.contains(&new_admin_id), Error::<T>::AlreadyAdmin);870 }871872 873 ensure!((admin_arr.len() as u64) < ChainLimit::get().collections_admins_limit, Error::<T>::CollectionAdminsLimitExceeded);874875 admin_arr.push(new_admin_id);876 <AdminList<T>>::insert(collection_id, admin_arr);877878 Ok(())879 }880881 882 883 884 885 886 887 888 889 890 891 892 893 #[weight = <T as Config>::WeightInfo::remove_collection_admin()]894 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::AccountId) -> DispatchResult {895896 let sender = ensure_signed(origin)?;897 Self::check_owner_or_admin_permissions(collection_id, sender)?;898 ensure!(<AdminList<T>>::contains_key(collection_id), Error::<T>::AdminNotFound);899900 let mut admin_arr = <AdminList<T>>::get(collection_id);901 admin_arr.retain(|i| *i != account_id);902 <AdminList<T>>::insert(collection_id, admin_arr);903904 Ok(())905 }906907 908 909 910 911 912 913 914 915 916 #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]917 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {918919 let sender = ensure_signed(origin)?;920 ensure!(<Collection<T>>::contains_key(collection_id), Error::<T>::CollectionNotFound);921922 let mut target_collection = <Collection<T>>::get(collection_id);923 ensure!(sender == target_collection.owner, Error::<T>::NoPermission);924925 target_collection.sponsor = new_sponsor;926 target_collection.sponsor_confirmed = false;927 <Collection<T>>::insert(collection_id, target_collection);928929 Ok(())930 }931932 933 934 935 936 937 938 939 #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]940 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {941942 let sender = ensure_signed(origin)?;943 ensure!(<Collection<T>>::contains_key(collection_id), Error::<T>::CollectionNotFound);944945 let mut target_collection = <Collection<T>>::get(collection_id);946 ensure!(sender == target_collection.sponsor, Error::<T>::ConfirmUnsetSponsorFail);947948 target_collection.sponsor_confirmed = true;949 <Collection<T>>::insert(collection_id, target_collection);950951 Ok(())952 }953954 955 956 957 958 959 960 961 962 963 #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]964 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {965966 let sender = ensure_signed(origin)?;967 ensure!(<Collection<T>>::contains_key(collection_id), Error::<T>::CollectionNotFound);968969 let mut target_collection = <Collection<T>>::get(collection_id);970 ensure!(sender == target_collection.owner, Error::<T>::NoPermission);971972 target_collection.sponsor = T::AccountId::default();973 target_collection.sponsor_confirmed = false;974 <Collection<T>>::insert(collection_id, target_collection);975976 Ok(())977 }978979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 10021003 #[weight = <T as Config>::WeightInfo::create_item(data.len())]1004 pub fn create_item(origin, collection_id: CollectionId, owner: T::AccountId, data: CreateItemData) -> DispatchResult {10051006 let sender = ensure_signed(origin)?;10071008 Self::collection_exists(collection_id)?;10091010 let target_collection = <Collection<T>>::get(collection_id);10111012 Self::can_create_items_in_collection(collection_id, &target_collection, &sender, &owner)?;1013 Self::validate_create_item_args(&target_collection, &data)?;1014 Self::create_item_no_validation(collection_id, owner, data)?;10151016 Ok(())1017 }10181019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 #[weight = <T as Config>::WeightInfo::create_item(items_data.into_iter()1038 .map(|data| { data.len() })1039 .sum())]1040 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::AccountId, items_data: Vec<CreateItemData>) -> DispatchResult {10411042 ensure!(items_data.len() > 0, Error::<T>::EmptyArgument);1043 let sender = ensure_signed(origin)?;10441045 Self::collection_exists(collection_id)?;1046 let target_collection = <Collection<T>>::get(collection_id);10471048 Self::can_create_items_in_collection(collection_id, &target_collection, &sender, &owner)?;10491050 for data in &items_data {1051 Self::validate_create_item_args(&target_collection, data)?;1052 }1053 for data in &items_data {1054 Self::create_item_no_validation(collection_id, owner.clone(), data.clone())?;1055 }10561057 Ok(())1058 }10591060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 #[weight = <T as Config>::WeightInfo::burn_item()]1074 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {10751076 let sender = ensure_signed(origin)?;1077 Self::collection_exists(collection_id)?;10781079 1080 let target_collection = <Collection<T>>::get(collection_id);1081 ensure!(1082 Self::is_item_owner(sender.clone(), collection_id, item_id) ||1083 (1084 target_collection.limits.owner_can_transfer &&1085 Self::is_owner_or_admin_permissions(collection_id, sender.clone())1086 ),1087 Error::<T>::NoPermission1088 );10891090 if target_collection.access == AccessMode::WhiteList {1091 Self::check_white_list(collection_id, &sender)?;1092 }10931094 match target_collection.mode1095 {1096 CollectionMode::NFT => Self::burn_nft_item(collection_id, item_id)?,1097 CollectionMode::Fungible(_) => Self::burn_fungible_item(&sender, collection_id, value)?,1098 CollectionMode::ReFungible => Self::burn_refungible_item(collection_id, item_id, &sender)?,1099 _ => ()1100 };11011102 1103 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));11041105 Ok(())1106 }11071108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 #[weight = <T as Config>::WeightInfo::transfer()]1132 pub fn transfer(origin, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {1133 let sender = ensure_signed(origin)?;1134 Self::transfer_internal(sender, recipient, collection_id, item_id, value)1135 }11361137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 #[weight = <T as Config>::WeightInfo::approve()]1153 pub fn approve(origin, spender: T::AccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {11541155 let sender = ensure_signed(origin)?;11561157 Self::collection_exists(collection_id)?;1158 Self::token_exists(collection_id, item_id, &sender)?;11591160 1161 let target_collection = <Collection<T>>::get(collection_id);1162 let allowance_limit = if target_collection.limits.owner_can_transfer &&1163 Self::is_owner_or_admin_permissions(1164 collection_id,1165 sender.clone(),1166 ) {1167 None1168 } else if let Some(amount) = Self::owned_amount(1169 sender.clone(),1170 collection_id,1171 item_id,1172 ) {1173 Some(amount)1174 } else {1175 fail!(Error::<T>::NoPermission);1176 };11771178 if target_collection.access == AccessMode::WhiteList {1179 Self::check_white_list(collection_id, &sender)?;1180 Self::check_white_list(collection_id, &spender)?;1181 }11821183 let allowance_exists = <Allowances<T>>::contains_key(collection_id, (item_id, &sender, &spender));1184 let mut allowance: u128 = amount;1185 if allowance_exists {1186 allowance += <Allowances<T>>::get(collection_id, (item_id, &sender, &spender));1187 }1188 if let Some(limit) = allowance_limit {1189 ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);1190 }1191 <Allowances<T>>::insert(collection_id, (item_id, sender.clone(), spender.clone()), allowance);11921193 Ok(())1194 }1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 #[weight = <T as Config>::WeightInfo::transfer_from()]1216 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {12171218 let sender = ensure_signed(origin)?;1219 let mut appoved_transfer = false;12201221 1222 let mut approval: u128 = 0;1223 if <Allowances<T>>::contains_key(collection_id, (item_id, &from, &sender)) {1224 approval = <Allowances<T>>::get(collection_id, (item_id, &from, &sender));1225 ensure!(approval >= value, Error::<T>::TokenValueNotEnough);1226 appoved_transfer = true;1227 }12281229 let target_collection = <Collection<T>>::get(collection_id);12301231 1232 Self::is_correct_transfer(collection_id, &target_collection, &recipient)?;12331234 1235 ensure!(1236 appoved_transfer || 1237 (1238 target_collection.limits.owner_can_transfer &&1239 Self::is_owner_or_admin_permissions(collection_id, sender.clone())1240 ),1241 Error::<T>::NoPermission1242 );12431244 if target_collection.access == AccessMode::WhiteList {1245 Self::check_white_list(collection_id, &sender)?;1246 Self::check_white_list(collection_id, &recipient)?;1247 }12481249 1250 if approval.checked_sub(value).unwrap_or(0) > 0 {1251 <Allowances<T>>::insert(collection_id, (item_id, &from, &sender), approval - value);1252 }1253 else {1254 <Allowances<T>>::remove(collection_id, (item_id, &from, &sender));1255 }12561257 match target_collection.mode1258 {1259 CollectionMode::NFT => Self::transfer_nft(collection_id, item_id, from, recipient)?,1260 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, value, &from, &recipient)?,1261 CollectionMode::ReFungible => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,1262 _ => ()1263 };12641265 Ok(())1266 }12671268 1269 12701271 1272 1273 1274 12751276 12771278 12791280 1281 12821283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1296 pub fn set_variable_meta_data (1297 origin,1298 collection_id: CollectionId,1299 item_id: TokenId,1300 data: Vec<u8>1301 ) -> DispatchResult {1302 let sender = ensure_signed(origin)?;1303 1304 Self::collection_exists(collection_id)?;1305 Self::token_exists(collection_id, item_id, &sender)?;13061307 ensure!(ChainLimit::get().custom_data_limit >= data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);13081309 1310 let target_collection = <Collection<T>>::get(collection_id);1311 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) ||1312 Self::is_owner_or_admin_permissions(collection_id, sender.clone()),1313 Error::<T>::NoPermission);13141315 match target_collection.mode1316 {1317 CollectionMode::NFT => Self::set_nft_variable_data(collection_id, item_id, data)?,1318 CollectionMode::ReFungible => Self::set_re_fungible_variable_data(collection_id, item_id, data)?,1319 CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),1320 _ => fail!(Error::<T>::UnexpectedCollectionType)1321 };13221323 Ok(())1324 }1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 #[weight = <T as Config>::WeightInfo::set_schema_version()]1341 pub fn set_schema_version(1342 origin,1343 collection_id: CollectionId,1344 version: SchemaVersion1345 ) -> DispatchResult {1346 let sender = ensure_signed(origin)?;1347 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;1348 let mut target_collection = <Collection<T>>::get(collection_id);1349 target_collection.schema_version = version;1350 <Collection<T>>::insert(collection_id, target_collection);13511352 Ok(())1353 }13541355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1368 pub fn set_offchain_schema(1369 origin,1370 collection_id: CollectionId,1371 schema: Vec<u8>1372 ) -> DispatchResult {1373 let sender = ensure_signed(origin)?;1374 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;13751376 1377 ensure!(schema.len() as u32 <= ChainLimit::get().offchain_schema_limit, "");13781379 let mut target_collection = <Collection<T>>::get(collection_id);1380 target_collection.offchain_schema = schema;1381 <Collection<T>>::insert(collection_id, target_collection);13821383 Ok(())1384 }13851386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1399 pub fn set_const_on_chain_schema (1400 origin,1401 collection_id: CollectionId,1402 schema: Vec<u8>1403 ) -> DispatchResult {1404 let sender = ensure_signed(origin)?;1405 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;14061407 1408 ensure!(schema.len() as u32 <= ChainLimit::get().const_on_chain_schema_limit, "");14091410 let mut target_collection = <Collection<T>>::get(collection_id);1411 target_collection.const_on_chain_schema = schema;1412 <Collection<T>>::insert(collection_id, target_collection);14131414 Ok(())1415 }14161417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1430 pub fn set_variable_on_chain_schema (1431 origin,1432 collection_id: CollectionId,1433 schema: Vec<u8>1434 ) -> DispatchResult {1435 let sender = ensure_signed(origin)?;1436 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;14371438 1439 ensure!(schema.len() as u32 <= ChainLimit::get().variable_on_chain_schema_limit, "");14401441 let mut target_collection = <Collection<T>>::get(collection_id);1442 target_collection.variable_on_chain_schema = schema;1443 <Collection<T>>::insert(collection_id, target_collection);14441445 Ok(())1446 }14471448 1449 #[weight = <T as Config>::WeightInfo::set_chain_limits()]1450 pub fn set_chain_limits(1451 origin,1452 limits: ChainLimits1453 ) -> DispatchResult {14541455 #[cfg(not(feature = "runtime-benchmarks"))]1456 ensure_root(origin)?;14571458 <ChainLimit>::put(limits);1459 Ok(())1460 }14611462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 #[weight = <T as Config>::WeightInfo::enable_contract_sponsoring()]1474 pub fn enable_contract_sponsoring(1475 origin,1476 contract_address: T::AccountId,1477 enable: bool1478 ) -> DispatchResult {14791480 let sender = ensure_signed(origin)?;14811482 #[cfg(feature = "runtime-benchmarks")]1483 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());14841485 Self::ensure_contract_owned(sender, &contract_address)?;14861487 <ContractSelfSponsoring<T>>::insert(contract_address, enable);1488 Ok(())1489 }14901491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 #[weight = <T as Config>::WeightInfo::set_contract_sponsoring_rate_limit()]1509 pub fn set_contract_sponsoring_rate_limit(1510 origin,1511 contract_address: T::AccountId,1512 rate_limit: T::BlockNumber1513 ) -> DispatchResult {1514 let sender = ensure_signed(origin)?;15151516 #[cfg(feature = "runtime-benchmarks")]1517 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());15181519 Self::ensure_contract_owned(sender, &contract_address)?;1520 <ContractSponsoringRateLimit<T>>::insert(contract_address, rate_limit);1521 Ok(())1522 }15231524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 #[weight = <T as Config>::WeightInfo::toggle_contract_white_list()]1536 pub fn toggle_contract_white_list(1537 origin,1538 contract_address: T::AccountId,1539 enable: bool1540 ) -> DispatchResult {1541 let sender = ensure_signed(origin)?;15421543 #[cfg(feature = "runtime-benchmarks")]1544 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());15451546 Self::ensure_contract_owned(sender, &contract_address)?;1547 <ContractWhiteListEnabled<T>>::insert(contract_address, enable);1548 Ok(())1549 }1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 #[weight = <T as Config>::WeightInfo::add_to_contract_white_list()]1563 pub fn add_to_contract_white_list(1564 origin,1565 contract_address: T::AccountId,1566 account_address: T::AccountId1567 ) -> DispatchResult {1568 let sender = ensure_signed(origin)?;15691570 #[cfg(feature = "runtime-benchmarks")]1571 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());1572 1573 Self::ensure_contract_owned(sender, &contract_address)?; 1574 <ContractWhiteList<T>>::insert(contract_address, account_address, true);1575 Ok(())1576 }15771578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 #[weight = <T as Config>::WeightInfo::remove_from_contract_white_list()]1590 pub fn remove_from_contract_white_list(1591 origin,1592 contract_address: T::AccountId,1593 account_address: T::AccountId1594 ) -> DispatchResult {1595 let sender = ensure_signed(origin)?;15961597 #[cfg(feature = "runtime-benchmarks")]1598 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());15991600 Self::ensure_contract_owned(sender, &contract_address)?;1601 <ContractWhiteList<T>>::remove(contract_address, account_address);1602 Ok(())1603 }16041605 #[weight = <T as Config>::WeightInfo::set_collection_limits()]1606 pub fn set_collection_limits(1607 origin,1608 collection_id: u32,1609 new_limits: CollectionLimits,1610 ) -> DispatchResult {1611 let sender = ensure_signed(origin)?;1612 Self::check_owner_permissions(collection_id, sender.clone())?;1613 let mut target_collection = <Collection<T>>::get(collection_id);1614 let old_limits = target_collection.limits;1615 let chain_limits = ChainLimit::get();16161617 1618 ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&1619 new_limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP && 1620 new_limits.sponsored_data_size <= chain_limits.custom_data_limit,1621 Error::<T>::CollectionLimitBoundsExceeded);16221623 1624 ensure!(old_limits.token_limit >= new_limits.token_limit, Error::<T>::CollectionTokenLimitExceeded);1625 ensure!(new_limits.token_limit > 0, Error::<T>::CollectionTokenLimitExceeded);16261627 ensure!(1628 (old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&1629 (old_limits.owner_can_destroy || !new_limits.owner_can_destroy),1630 Error::<T>::OwnerPermissionsCantBeReverted,1631 );16321633 target_collection.limits = new_limits;1634 <Collection<T>>::insert(collection_id, target_collection);16351636 Ok(())1637 } 1638 }1639}16401641impl<T: Config> Module<T> {16421643 pub fn transfer_internal(sender: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {16441645 let target_collection = <Collection<T>>::get(collection_id);16461647 1648 Self::is_correct_transfer(collection_id, &target_collection, &recipient)?;16491650 1651 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) ||1652 Self::is_owner_or_admin_permissions(collection_id, sender.clone()),1653 Error::<T>::NoPermission);16541655 if target_collection.access == AccessMode::WhiteList {1656 Self::check_white_list(collection_id, &sender)?;1657 Self::check_white_list(collection_id, &recipient)?;1658 }16591660 match target_collection.mode1661 {1662 CollectionMode::NFT => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient.clone())?,1663 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, value, &sender, &recipient)?,1664 CollectionMode::ReFungible => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient.clone())?,1665 _ => ()1666 };16671668 Self::deposit_event(RawEvent::Transfer(collection_id, item_id, sender, recipient, value));16691670 Ok(())1671 }167216731674 fn is_correct_transfer(collection_id: CollectionId, collection: &CollectionType<T::AccountId>, recipient: &T::AccountId) -> DispatchResult {16751676 1677 let account_items: u32 = <AddressTokens<T>>::get(collection_id, recipient).len() as u32;1678 ensure!(collection.limits.account_token_ownership_limit > account_items, Error::<T>::AccountTokenLimitExceeded);1679 1680 Ok(())1681 }16821683 fn can_create_items_in_collection(collection_id: CollectionId, collection: &CollectionType<T::AccountId>, sender: &T::AccountId, owner: &T::AccountId) -> DispatchResult {16841685 1686 let total_items: u32 = ItemListIndex::get(collection_id);1687 let account_items: u32 = <AddressTokens<T>>::get(collection_id, owner).len() as u32;1688 ensure!(collection.limits.token_limit > total_items, Error::<T>::CollectionTokenLimitExceeded);1689 ensure!(collection.limits.account_token_ownership_limit > account_items, Error::<T>::AccountTokenLimitExceeded);16901691 if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) {1692 ensure!(collection.mint_mode == true, Error::<T>::PublicMintingNotAllowed);1693 Self::check_white_list(collection_id, owner)?;1694 Self::check_white_list(collection_id, sender)?;1695 }16961697 Ok(())1698 }16991700 fn validate_create_item_args(target_collection: &CollectionType<T::AccountId>, data: &CreateItemData) -> DispatchResult {1701 match target_collection.mode1702 {1703 CollectionMode::NFT => {1704 if let CreateItemData::NFT(data) = data {1705 1706 ensure!(ChainLimit::get().custom_data_limit >= data.const_data.len() as u32, Error::<T>::TokenConstDataLimitExceeded);1707 ensure!(ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);1708 } else {1709 fail!(Error::<T>::NotNftDataUsedToMintNftCollectionToken);1710 }1711 },1712 CollectionMode::Fungible(_) => {1713 if let CreateItemData::Fungible(_) = data {1714 } else {1715 fail!(Error::<T>::NotFungibleDataUsedToMintFungibleCollectionToken);1716 }1717 },1718 CollectionMode::ReFungible => {1719 if let CreateItemData::ReFungible(data) = data {17201721 1722 ensure!(ChainLimit::get().custom_data_limit >= data.const_data.len() as u32, Error::<T>::TokenConstDataLimitExceeded);1723 ensure!(ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);17241725 1726 ensure!(data.pieces <= MAX_REFUNGIBLE_PIECES, Error::<T>::WrongRefungiblePieces);1727 ensure!(data.pieces > 0, Error::<T>::WrongRefungiblePieces);1728 } else {1729 fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);1730 }1731 },1732 _ => { fail!(Error::<T>::UnexpectedCollectionType); }1733 };17341735 Ok(())1736 }17371738 fn create_item_no_validation(collection_id: CollectionId, owner: T::AccountId, data: CreateItemData) -> DispatchResult {1739 match data1740 {1741 CreateItemData::NFT(data) => {1742 let item = NftItemType {1743 owner: owner.clone(),1744 const_data: data.const_data,1745 variable_data: data.variable_data1746 };17471748 Self::add_nft_item(collection_id, item)?;1749 },1750 CreateItemData::Fungible(data) => {1751 Self::add_fungible_item(collection_id, &owner, data.value)?;1752 },1753 CreateItemData::ReFungible(data) => {1754 let mut owner_list = Vec::new();1755 owner_list.push(Ownership {owner: owner.clone(), fraction: data.pieces});17561757 let item = ReFungibleItemType {1758 owner: owner_list,1759 const_data: data.const_data,1760 variable_data: data.variable_data1761 };17621763 Self::add_refungible_item(collection_id, item)?;1764 }1765 };17661767 1768 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id), owner));17691770 Ok(())1771 }17721773 fn add_fungible_item(collection_id: CollectionId, owner: &T::AccountId, value: u128) -> DispatchResult {17741775 1776 let mut balance: u128 = 0;1777 if <FungibleItemList<T>>::contains_key(collection_id, owner) {1778 balance = <FungibleItemList<T>>::get(collection_id, owner).value;1779 } 17801781 1782 let item = FungibleItemType {1783 value: balance + value1784 };1785 <FungibleItemList<T>>::insert(collection_id, (*owner).clone(), item);17861787 1788 let new_balance = <Balance<T>>::get(collection_id, owner)1789 .checked_add(value)1790 .ok_or(Error::<T>::NumOverflow)?;1791 <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);17921793 Ok(())1794 }17951796 fn add_refungible_item(collection_id: CollectionId, item: ReFungibleItemType<T::AccountId>) -> DispatchResult {1797 let current_index = <ItemListIndex>::get(collection_id)1798 .checked_add(1)1799 .ok_or(Error::<T>::NumOverflow)?;1800 let itemcopy = item.clone();18011802 let value = item.owner.first().unwrap().fraction;1803 let owner = item.owner.first().unwrap().owner.clone();18041805 Self::add_token_index(collection_id, current_index, &owner)?;18061807 <ItemListIndex>::insert(collection_id, current_index);1808 <ReFungibleItemList<T>>::insert(collection_id, current_index, itemcopy);18091810 1811 let new_balance = <Balance<T>>::get(collection_id, &owner)1812 .checked_add(value)1813 .ok_or(Error::<T>::NumOverflow)?;1814 <Balance<T>>::insert(collection_id, owner.clone(), new_balance);18151816 Ok(())1817 }18181819 fn add_nft_item(collection_id: CollectionId, item: NftItemType<T::AccountId>) -> DispatchResult {1820 let current_index = <ItemListIndex>::get(collection_id)1821 .checked_add(1)1822 .ok_or(Error::<T>::NumOverflow)?;18231824 let item_owner = item.owner.clone();1825 Self::add_token_index(collection_id, current_index, &item.owner)?;18261827 <ItemListIndex>::insert(collection_id, current_index);1828 <NftItemList<T>>::insert(collection_id, current_index, item);18291830 1831 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())1832 .checked_add(1)1833 .ok_or(Error::<T>::NumOverflow)?;1834 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);18351836 Ok(())1837 }18381839 fn burn_refungible_item(1840 collection_id: CollectionId,1841 item_id: TokenId,1842 owner: &T::AccountId,1843 ) -> DispatchResult {1844 ensure!(1845 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1846 Error::<T>::TokenNotFound1847 );1848 let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id);1849 let rft_balance = token1850 .owner1851 .iter()1852 .filter(|&i| i.owner == *owner)1853 .next()1854 .unwrap();1855 Self::remove_token_index(collection_id, item_id, owner)?;18561857 1858 let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.clone())1859 .checked_sub(rft_balance.fraction)1860 .ok_or(Error::<T>::NumOverflow)?;1861 <Balance<T>>::insert(collection_id, rft_balance.owner.clone(), new_balance);18621863 1864 let index = token1865 .owner1866 .iter()1867 .position(|i| i.owner == *owner)1868 .unwrap();1869 token.owner.remove(index);1870 let owner_count = token.owner.len();18711872 1873 if owner_count == 0 {1874 <ReFungibleItemList<T>>::remove(collection_id, item_id);1875 }1876 else {1877 <ReFungibleItemList<T>>::insert(collection_id, item_id, token);1878 }18791880 Ok(())1881 }18821883 fn burn_nft_item(collection_id: CollectionId, item_id: TokenId) -> DispatchResult {1884 ensure!(1885 <NftItemList<T>>::contains_key(collection_id, item_id),1886 Error::<T>::TokenNotFound1887 );1888 let item = <NftItemList<T>>::get(collection_id, item_id);1889 Self::remove_token_index(collection_id, item_id, &item.owner)?;18901891 1892 let new_balance = <Balance<T>>::get(collection_id, &item.owner)1893 .checked_sub(1)1894 .ok_or(Error::<T>::NumOverflow)?;1895 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);1896 <NftItemList<T>>::remove(collection_id, item_id);18971898 Ok(())1899 }19001901 fn burn_fungible_item(owner: &T::AccountId, collection_id: CollectionId, value: u128) -> DispatchResult {1902 ensure!(1903 <FungibleItemList<T>>::contains_key(collection_id, owner),1904 Error::<T>::TokenNotFound1905 );1906 let mut balance = <FungibleItemList<T>>::get(collection_id, owner);1907 ensure!(balance.value >= value, Error::<T>::TokenValueNotEnough);19081909 1910 let new_balance = <Balance<T>>::get(collection_id, owner)1911 .checked_sub(value)1912 .ok_or(Error::<T>::NumOverflow)?;1913 <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);19141915 if balance.value - value > 0 {1916 balance.value -= value;1917 <FungibleItemList<T>>::insert(collection_id, (*owner).clone(), balance);1918 }1919 else {1920 <FungibleItemList<T>>::remove(collection_id, owner);1921 }19221923 Ok(())1924 }19251926 fn collection_exists(collection_id: CollectionId) -> DispatchResult {1927 ensure!(1928 <Collection<T>>::contains_key(collection_id),1929 Error::<T>::CollectionNotFound1930 );1931 Ok(())1932 }19331934 fn check_owner_permissions(collection_id: CollectionId, subject: T::AccountId) -> DispatchResult {1935 Self::collection_exists(collection_id)?;19361937 let target_collection = <Collection<T>>::get(collection_id);1938 ensure!(1939 subject == target_collection.owner,1940 Error::<T>::NoPermission1941 );19421943 Ok(())1944 }19451946 fn is_owner_or_admin_permissions(collection_id: CollectionId, subject: T::AccountId) -> bool {1947 let target_collection = <Collection<T>>::get(collection_id);1948 let mut result: bool = subject == target_collection.owner;1949 let exists = <AdminList<T>>::contains_key(collection_id);19501951 if !result & exists {1952 if <AdminList<T>>::get(collection_id).contains(&subject) {1953 result = true1954 }1955 }19561957 result1958 }19591960 fn check_owner_or_admin_permissions(1961 collection_id: CollectionId,1962 subject: T::AccountId,1963 ) -> DispatchResult {1964 Self::collection_exists(collection_id)?;1965 let result = Self::is_owner_or_admin_permissions(collection_id, subject.clone());19661967 ensure!(1968 result,1969 Error::<T>::NoPermission1970 );1971 Ok(())1972 }19731974 fn owned_amount(1975 subject: T::AccountId,1976 collection_id: CollectionId,1977 item_id: TokenId,1978 ) -> Option<u128> {1979 let target_collection = <Collection<T>>::get(collection_id);19801981 match target_collection.mode {1982 CollectionMode::NFT => {1983 if <NftItemList<T>>::get(collection_id, item_id).owner == subject {1984 return Some(1)1985 }1986 None1987 },1988 CollectionMode::Fungible(_) => {1989 if <FungibleItemList<T>>::contains_key(collection_id, &subject) {1990 return Some(<FungibleItemList<T>>::get(collection_id, &subject)1991 .value);1992 }1993 None1994 },1995 CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)1996 .owner1997 .iter()1998 .find(|i| i.owner == subject)1999 .map(|i| i.fraction),2000 CollectionMode::Invalid => None,2001 }2002 }20032004 fn is_item_owner(subject: T::AccountId, collection_id: CollectionId, item_id: TokenId) -> bool {2005 let target_collection = <Collection<T>>::get(collection_id);20062007 match target_collection.mode {2008 CollectionMode::NFT => {2009 <NftItemList<T>>::get(collection_id, item_id).owner == subject2010 }2011 CollectionMode::Fungible(_) => {2012 <FungibleItemList<T>>::contains_key(collection_id, &subject)2013 }2014 CollectionMode::ReFungible => {2015 <ReFungibleItemList<T>>::get(collection_id, item_id)2016 .owner2017 .iter()2018 .any(|i| i.owner == subject)2019 }2020 CollectionMode::Invalid => false,2021 }2022 }20232024 fn check_white_list(collection_id: CollectionId, address: &T::AccountId) -> DispatchResult {2025 let mes = Error::<T>::AddresNotInWhiteList;2026 ensure!(<WhiteList<T>>::contains_key(collection_id, address), mes);20272028 Ok(())2029 }20302031 2032 2033 fn token_exists(2034 collection_id: CollectionId,2035 item_id: TokenId,2036 owner: &T::AccountId2037 ) -> DispatchResult {2038 let target_collection = <Collection<T>>::get(collection_id);2039 let exists = match target_collection.mode2040 {2041 CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),2042 CollectionMode::Fungible(_) => <FungibleItemList<T>>::contains_key(collection_id, owner),2043 CollectionMode::ReFungible => <ReFungibleItemList<T>>::contains_key(collection_id, item_id),2044 _ => false2045 };20462047 ensure!(exists == true, Error::<T>::TokenNotFound);2048 Ok(())2049 }20502051 fn transfer_fungible(2052 collection_id: CollectionId,2053 value: u128,2054 owner: &T::AccountId,2055 recipient: &T::AccountId,2056 ) -> DispatchResult {2057 Self::token_exists(collection_id, 0, owner)?;20582059 let mut balance = <FungibleItemList<T>>::get(collection_id, owner);2060 ensure!(balance.value >= value, Error::<T>::TokenValueTooLow);20612062 2063 Self::add_fungible_item(collection_id, recipient, value)?;20642065 2066 <Balance<T>>::insert(collection_id, (*owner).clone(), balance.value - value);20672068 2069 if balance.value == value {2070 <FungibleItemList<T>>::remove(collection_id, owner);2071 }2072 else {2073 balance.value -= value;2074 <FungibleItemList<T>>::insert(collection_id, (*owner).clone(), balance);2075 }20762077 Ok(())2078 }20792080 fn transfer_refungible(2081 collection_id: CollectionId,2082 item_id: TokenId,2083 value: u128,2084 owner: T::AccountId,2085 new_owner: T::AccountId,2086 ) -> DispatchResult {2087 Self::token_exists(collection_id, item_id, &owner)?;20882089 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);2090 let item = full_item2091 .owner2092 .iter()2093 .filter(|i| i.owner == owner)2094 .next()2095 .ok_or(Error::<T>::NumOverflow)?;2096 let amount = item.fraction;20972098 ensure!(amount >= value, Error::<T>::TokenValueTooLow);20992100 2101 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())2102 .checked_sub(value)2103 .ok_or(Error::<T>::NumOverflow)?;2104 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);21052106 let balancenew_owner = <Balance<T>>::get(collection_id, new_owner.clone())2107 .checked_add(value)2108 .ok_or(Error::<T>::NumOverflow)?;2109 <Balance<T>>::insert(collection_id, new_owner.clone(), balancenew_owner);21102111 let old_owner = item.owner.clone();2112 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);21132114 2115 if amount == value && !new_owner_has_account {2116 2117 2118 let mut new_full_item = full_item.clone();2119 new_full_item2120 .owner2121 .iter_mut()2122 .find(|i| i.owner == owner)2123 .unwrap()2124 .owner = new_owner.clone();2125 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);21262127 2128 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;2129 } else {2130 let mut new_full_item = full_item.clone();2131 new_full_item2132 .owner2133 .iter_mut()2134 .find(|i| i.owner == owner)2135 .unwrap()2136 .fraction -= value;21372138 2139 if new_owner_has_account {2140 2141 new_full_item2142 .owner2143 .iter_mut()2144 .find(|i| i.owner == new_owner)2145 .unwrap()2146 .fraction += value;2147 } else {2148 2149 new_full_item.owner.push(Ownership {2150 owner: new_owner.clone(),2151 fraction: value,2152 });2153 Self::add_token_index(collection_id, item_id, &new_owner)?;2154 }21552156 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);2157 }21582159 Ok(())2160 }21612162 fn transfer_nft(2163 collection_id: CollectionId,2164 item_id: TokenId,2165 sender: T::AccountId,2166 new_owner: T::AccountId,2167 ) -> DispatchResult {2168 Self::token_exists(collection_id, item_id, &sender)?;21692170 let mut item = <NftItemList<T>>::get(collection_id, item_id);21712172 ensure!(2173 sender == item.owner,2174 Error::<T>::MustBeTokenOwner2175 );21762177 2178 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())2179 .checked_sub(1)2180 .ok_or(Error::<T>::NumOverflow)?;2181 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);21822183 let balancenew_owner = <Balance<T>>::get(collection_id, new_owner.clone())2184 .checked_add(1)2185 .ok_or(Error::<T>::NumOverflow)?;2186 <Balance<T>>::insert(collection_id, new_owner.clone(), balancenew_owner);21872188 2189 let old_owner = item.owner.clone();2190 item.owner = new_owner.clone();2191 <NftItemList<T>>::insert(collection_id, item_id, item);21922193 2194 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;21952196 Ok(())2197 }2198 2199 fn set_re_fungible_variable_data(2200 collection_id: CollectionId,2201 item_id: TokenId,2202 data: Vec<u8>2203 ) -> DispatchResult {2204 let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id);22052206 item.variable_data = data;22072208 <ReFungibleItemList<T>>::insert(collection_id, item_id, item);22092210 Ok(())2211 }22122213 fn set_nft_variable_data(2214 collection_id: CollectionId,2215 item_id: TokenId,2216 data: Vec<u8>2217 ) -> DispatchResult {2218 let mut item = <NftItemList<T>>::get(collection_id, item_id);2219 2220 item.variable_data = data;22212222 <NftItemList<T>>::insert(collection_id, item_id, item);2223 2224 Ok(())2225 }22262227 fn init_collection(item: &CollectionType<T::AccountId>) {2228 2229 assert!(2230 item.decimal_points <= MAX_DECIMAL_POINTS,2231 "decimal_points parameter must be lower than MAX_DECIMAL_POINTS"2232 );2233 assert!(2234 item.name.len() <= 64,2235 "Collection name can not be longer than 63 char"2236 );2237 assert!(2238 item.name.len() <= 256,2239 "Collection description can not be longer than 255 char"2240 );2241 assert!(2242 item.token_prefix.len() <= 16,2243 "Token prefix can not be longer than 15 char"2244 );22452246 2247 let next_id = CreatedCollectionCount::get()2248 .checked_add(1)2249 .unwrap();22502251 CreatedCollectionCount::put(next_id);2252 }22532254 fn init_nft_token(collection_id: CollectionId, item: &NftItemType<T::AccountId>) {2255 let current_index = <ItemListIndex>::get(collection_id)2256 .checked_add(1)2257 .unwrap();22582259 let item_owner = item.owner.clone();2260 Self::add_token_index(collection_id, current_index, &item.owner).unwrap();22612262 <ItemListIndex>::insert(collection_id, current_index);22632264 2265 let new_balance = <Balance<T>>::get(collection_id, &item_owner)2266 .checked_add(1)2267 .unwrap();2268 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);2269 }22702271 fn init_fungible_token(collection_id: CollectionId, owner: &T::AccountId, item: &FungibleItemType) {2272 let current_index = <ItemListIndex>::get(collection_id)2273 .checked_add(1)2274 .unwrap();22752276 Self::add_token_index(collection_id, current_index, owner).unwrap();22772278 <ItemListIndex>::insert(collection_id, current_index);22792280 2281 let new_balance = <Balance<T>>::get(collection_id, owner)2282 .checked_add(item.value)2283 .unwrap();2284 <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);2285 }22862287 fn init_refungible_token(collection_id: CollectionId, item: &ReFungibleItemType<T::AccountId>) {2288 let current_index = <ItemListIndex>::get(collection_id)2289 .checked_add(1)2290 .unwrap();22912292 let value = item.owner.first().unwrap().fraction;2293 let owner = item.owner.first().unwrap().owner.clone();22942295 Self::add_token_index(collection_id, current_index, &owner).unwrap();22962297 <ItemListIndex>::insert(collection_id, current_index);22982299 2300 let new_balance = <Balance<T>>::get(collection_id, &owner)2301 .checked_add(value)2302 .unwrap();2303 <Balance<T>>::insert(collection_id, owner.clone(), new_balance);2304 }23052306 fn add_token_index(collection_id: CollectionId, item_index: TokenId, owner: &T::AccountId) -> DispatchResult {23072308 2309 if <AccountItemCount<T>>::contains_key(owner) {23102311 2312 let count = <AccountItemCount<T>>::get(owner);2313 ensure!(count < ChainLimit::get().account_token_ownership_limit, Error::<T>::AddressOwnershipLimitExceeded);23142315 <AccountItemCount<T>>::insert(owner.clone(), count2316 .checked_add(1)2317 .ok_or(Error::<T>::NumOverflow)?);2318 }2319 else {2320 <AccountItemCount<T>>::insert(owner.clone(), 1);2321 }23222323 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner);2324 if list_exists {2325 let mut list = <AddressTokens<T>>::get(collection_id, owner);2326 let item_contains = list.contains(&item_index.clone());23272328 if !item_contains {2329 list.push(item_index.clone());2330 }23312332 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);2333 } else {2334 let mut itm = Vec::new();2335 itm.push(item_index.clone());2336 <AddressTokens<T>>::insert(collection_id, owner.clone(), itm);2337 }23382339 Ok(())2340 }23412342 fn remove_token_index(2343 collection_id: CollectionId,2344 item_index: TokenId,2345 owner: &T::AccountId,2346 ) -> DispatchResult {23472348 2349 <AccountItemCount<T>>::insert(owner.clone(), 2350 <AccountItemCount<T>>::get(owner)2351 .checked_sub(1)2352 .ok_or(Error::<T>::NumOverflow)?);235323542355 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner);2356 if list_exists {2357 let mut list = <AddressTokens<T>>::get(collection_id, owner);2358 let item_contains = list.contains(&item_index.clone());23592360 if item_contains {2361 list.retain(|&item| item != item_index);2362 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);2363 }2364 }23652366 Ok(())2367 }23682369 fn move_token_index(2370 collection_id: CollectionId,2371 item_index: TokenId,2372 old_owner: &T::AccountId,2373 new_owner: &T::AccountId,2374 ) -> DispatchResult {2375 Self::remove_token_index(collection_id, item_index, old_owner)?;2376 Self::add_token_index(collection_id, item_index, new_owner)?;23772378 Ok(())2379 }2380 2381 fn ensure_contract_owned(account: T::AccountId, contract: &T::AccountId) -> DispatchResult {2382 if <ContractOwner<T>>::contains_key(contract.clone()) {2383 let owner = <ContractOwner<T>>::get(contract);2384 ensure!(account == owner, Error::<T>::NoPermission);2385 } else {2386 fail!(Error::<T>::NoPermission);2387 }23882389 Ok(())2390 }2391}2392239323942395239623972398pub type Multiplier = FixedU128;23992400type BalanceOf<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::Balance;2401240224032404#[derive(Encode, Decode, Clone, Eq, PartialEq)]2405pub struct ChargeTransactionPayment<T: Config>(#[codec(compact)] BalanceOf<T>);24062407impl<T: Config + Send + Sync> sp_std::fmt::Debug 2408 for ChargeTransactionPayment<T>2409{2410 #[cfg(feature = "std")]2411 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {2412 write!(f, "ChargeTransactionPayment<{:?}>", self.0)2413 }2414 #[cfg(not(feature = "std"))]2415 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {2416 Ok(())2417 }2418}24192420impl<T: Config> ChargeTransactionPayment<T>2421where2422 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Call<T>> + IsSubType<pallet_contracts::Call<T>>,2423 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,2424 T::AccountId: AsRef<[u8]>,2425 T::AccountId: UncheckedFrom<T::Hash>,2426{2427 fn traditional_fee(2428 len: usize,2429 info: &DispatchInfoOf<T::Call>,2430 tip: BalanceOf<T>,2431 ) -> BalanceOf<T>2432 where2433 T::Call: Dispatchable<Info = DispatchInfo>,2434 {2435 <pallet_transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)2436 }24372438 fn get_priority(len: usize, info: &DispatchInfoOf<T::Call>, final_fee: BalanceOf<T>) -> TransactionPriority {2439 let weight_saturation = T::BlockWeights::get().max_block / info.weight.max(1);2440 let max_block_length = *T::BlockLength::get().max.get(DispatchClass::Normal);2441 let len_saturation = max_block_length as u64 / (len as u64).max(1);2442 let coefficient: BalanceOf<T> = weight_saturation2443 .min(len_saturation)2444 .saturated_into::<BalanceOf<T>>();2445 final_fee2446 .saturating_mul(coefficient)2447 .saturated_into::<TransactionPriority>()2448 }24492450 fn withdraw_fee(2451 &self,2452 who: &T::AccountId,2453 call: &T::Call,2454 info: &DispatchInfoOf<T::Call>,2455 len: usize,2456 ) -> Result<2457 (2458 BalanceOf<T>,2459 <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,2460 ),2461 TransactionValidityError,2462 > {2463 let tip = self.0;24642465 2466 2467 2468 2469 2470 2471 2472 let fee = Self::traditional_fee(len, info, tip);24732474 2475 if fee.is_zero() {2476 return <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(who, call, info, fee, tip)2477 .map(|i| (fee, i));2478 }24792480 2481 2482 let mut sponsor: T::AccountId = match IsSubType::<Call<T>>::is_sub_type(call) {2483 Some(Call::create_item(collection_id, _owner, _properties)) => {24842485 2486 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;24872488 let limit = <Collection<T>>::get(collection_id).limits.sponsor_transfer_timeout;2489 let mut sponsored = true;2490 if <CreateItemBasket<T>>::contains_key((collection_id, &who)) {2491 let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));2492 let limit_time = last_tx_block + limit.into();2493 if block_number <= limit_time {2494 sponsored = false;2495 }2496 }2497 if sponsored {2498 <CreateItemBasket<T>>::insert((collection_id, who.clone()), block_number);2499 }25002501 2502 if (<Collection<T>>::get(collection_id).limits.sponsored_data_size >= (_properties.len() as u32)) &&2503 (<Collection<T>>::get(collection_id).sponsor_confirmed) &&2504 (sponsored)2505 {2506 <Collection<T>>::get(collection_id).sponsor2507 } else {2508 T::AccountId::default()2509 }2510 }2511 Some(Call::transfer(_new_owner, collection_id, item_id, _value)) => {2512 2513 let mut sponsor_transfer = false;2514 if <Collection<T>>::get(collection_id).sponsor_confirmed {25152516 let collection_limits = <Collection<T>>::get(collection_id).limits;2517 let collection_mode = <Collection<T>>::get(collection_id).mode;2518 2519 2520 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;2521 sponsor_transfer = match collection_mode {2522 CollectionMode::NFT => {2523 2524 2525 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {2526 collection_limits.sponsor_transfer_timeout2527 } else {2528 ChainLimit::get().nft_sponsor_transfer_timeout2529 };2530 2531 let mut sponsored = true;2532 if <NftTransferBasket<T>>::contains_key(collection_id, item_id) {2533 let last_tx_block = <NftTransferBasket<T>>::get(collection_id, item_id);2534 let limit_time = last_tx_block + limit.into();2535 if block_number <= limit_time {2536 sponsored = false;2537 }2538 }2539 if sponsored {2540 <NftTransferBasket<T>>::insert(collection_id, item_id, block_number);2541 }25422543 sponsored2544 }2545 CollectionMode::Fungible(_) => {2546 2547 2548 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {2549 collection_limits.sponsor_transfer_timeout2550 } else {2551 ChainLimit::get().fungible_sponsor_transfer_timeout2552 };2553 2554 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;2555 let mut sponsored = true;2556 if <FungibleTransferBasket<T>>::contains_key(collection_id, who) {2557 let last_tx_block = <FungibleTransferBasket<T>>::get(collection_id, who);2558 let limit_time = last_tx_block + limit.into();2559 if block_number <= limit_time {2560 sponsored = false;2561 }2562 }2563 if sponsored {2564 <FungibleTransferBasket<T>>::insert(collection_id, who, block_number);2565 }25662567 sponsored2568 }2569 CollectionMode::ReFungible => {2570 2571 2572 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {2573 collection_limits.sponsor_transfer_timeout2574 } else {2575 ChainLimit::get().refungible_sponsor_transfer_timeout2576 };2577 2578 let mut sponsored = true;2579 if <ReFungibleTransferBasket<T>>::contains_key(collection_id, item_id) {2580 let last_tx_block = <ReFungibleTransferBasket<T>>::get(collection_id, item_id);2581 let limit_time = last_tx_block + limit.into();2582 if block_number <= limit_time {2583 sponsored = false;2584 }2585 }2586 if sponsored {2587 <ReFungibleTransferBasket<T>>::insert(collection_id, item_id, block_number);2588 }25892590 sponsored2591 }2592 _ => {2593 false2594 },2595 };2596 }25972598 if !sponsor_transfer {2599 T::AccountId::default()2600 } else {2601 <Collection<T>>::get(collection_id).sponsor2602 }2603 }26042605 _ => T::AccountId::default(),2606 };26072608 2609 sponsor = match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {26102611 2612 Some(pallet_contracts::Call::instantiate(_endowment, _gas_limit, code_hash, _data, salt)) => {26132614 let new_contract_address = <pallet_contracts::Module<T>>::contract_address(2615 &who,2616 code_hash,2617 salt,2618 );2619 <ContractOwner<T>>::insert(new_contract_address.clone(), who.clone());26202621 T::AccountId::default()2622 },26232624 2625 Some(pallet_contracts::Call::instantiate_with_code(_endowment, _gas_limit, _code, _data, _salt)) => {26262627 let new_contract_address = <pallet_contracts::Module<T>>::contract_address(2628 &who,2629 &T::Hashing::hash(&_code),2630 _salt,2631 );26322633 <ContractOwner<T>>::insert(new_contract_address.clone(), who.clone());26342635 T::AccountId::default()2636 }26372638 2639 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {26402641 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());26422643 let owned_contract = <ContractOwner<T>>::contains_key(called_contract.clone())2644 && <ContractOwner<T>>::get(called_contract.clone()) == *who;2645 let white_list_enabled = <ContractWhiteListEnabled<T>>::contains_key(called_contract.clone()) && <ContractWhiteListEnabled<T>>::get(called_contract.clone());2646 2647 if !owned_contract && white_list_enabled {2648 if !<ContractWhiteList<T>>::contains_key(called_contract.clone(), who) {2649 return Err(InvalidTransaction::Call.into());2650 }2651 }26522653 let mut sponsor_transfer = false;2654 if <ContractSponsoringRateLimit<T>>::contains_key(called_contract.clone()) {2655 let last_tx_block = <ContractSponsorBasket<T>>::get((&called_contract, &who));2656 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;2657 let rate_limit = <ContractSponsoringRateLimit<T>>::get(&called_contract);2658 let limit_time = last_tx_block + rate_limit;26592660 if block_number >= limit_time {2661 <ContractSponsorBasket<T>>::insert((called_contract.clone(), who.clone()), block_number);2662 sponsor_transfer = true;2663 }2664 } else {2665 sponsor_transfer = false;2666 }2667 2668 2669 let mut sp = T::AccountId::default();2670 if sponsor_transfer {2671 if <ContractSelfSponsoring<T>>::contains_key(called_contract.clone()) {2672 if <ContractSelfSponsoring<T>>::get(called_contract.clone()) {2673 sp = called_contract;2674 }2675 }2676 }26772678 sp2679 },26802681 _ => sponsor,2682 };26832684 let mut who_pays_fee: T::AccountId = sponsor.clone();2685 if sponsor == T::AccountId::default() {2686 who_pays_fee = who.clone();2687 }26882689 <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(&who_pays_fee, call, info, fee, tip)2690 .map(|i| (fee, i))2691 }2692}269326942695impl<T: Config + Send + Sync> SignedExtension2696 for ChargeTransactionPayment<T>2697where2698 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,2699 T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Call<T>> + IsSubType<pallet_contracts::Call<T>>,2700 T::AccountId: AsRef<[u8]>,2701 T::AccountId: UncheckedFrom<T::Hash>,2702{2703 const IDENTIFIER: &'static str = "ChargeTransactionPayment";2704 type AccountId = T::AccountId;2705 type Call = T::Call;2706 type AdditionalSigned = ();2707 type Pre = (2708 2709 BalanceOf<T>,2710 2711 Self::AccountId,2712 2713 <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,2714 );2715 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {2716 Ok(())2717 }27182719 fn validate(2720 &self,2721 who: &Self::AccountId,2722 call: &Self::Call,2723 info: &DispatchInfoOf<Self::Call>,2724 len: usize,2725 ) -> TransactionValidity {2726 let (fee, _) = self.withdraw_fee(who, call, info, len)?;2727 Ok(ValidTransaction {2728 priority: Self::get_priority(len, info, fee),2729 ..Default::default()2730 })2731 }27322733 fn pre_dispatch(2734 self,2735 who: &Self::AccountId,2736 call: &Self::Call,2737 info: &DispatchInfoOf<Self::Call>,2738 len: usize,2739 ) -> Result<Self::Pre, TransactionValidityError> {2740 let (_fee, imbalance) = self.withdraw_fee(who, call, info, len)?;2741 Ok((self.0, who.clone(), imbalance))2742 }27432744 fn post_dispatch(2745 pre: Self::Pre,2746 info: &DispatchInfoOf<Self::Call>,2747 post_info: &PostDispatchInfoOf<Self::Call>,2748 len: usize,2749 _result: &DispatchResult,2750 ) -> Result<(), TransactionValidityError> {2751 let (tip, who, imbalance) = pre;2752 let actual_fee = pallet_transaction_payment::Module::<T>::compute_actual_fee(2753 len as u32,2754 info,2755 post_info,2756 tip,2757 );2758 <T as pallet_transaction_payment::Config>::OnChargeTransaction::correct_and_deposit_fee(&who, info, post_info, actual_fee, tip, imbalance)?;2759 Ok(())2760 }2761}27622763