123456#![recursion_limit = "1024"]7#![cfg_attr(not(feature = "std"), no_std)]8#![allow(9 clippy::too_many_arguments,10 clippy::unnecessary_mut_passed,11 clippy::unused_unit12)]1314extern crate alloc;1516pub use serde::{Serialize, Deserialize};1718pub 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, WithdrawReasons,25 },26 weights::{27 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},28 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,29 WeightToFeePolynomial, DispatchClass,30 },31 StorageValue, transactional,32};3334use frame_system::{self as system, ensure_signed};35use sp_core::H160;36use sp_std::vec;37use sp_runtime::{DispatchError, sp_std::prelude::Vec};38use core::ops::{Deref, DerefMut};39use nft_data_structs::{40 MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_REFUNGIBLE_PIECES,41 CUSTOM_DATA_LIMIT, COLLECTION_NUMBER_LIMIT, ACCOUNT_TOKEN_OWNERSHIP_LIMIT,42 VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, COLLECTION_ADMINS_LIMIT,43 OFFCHAIN_SCHEMA_LIMIT, MAX_TOKEN_PREFIX_LENGTH, MAX_COLLECTION_NAME_LENGTH,44 MAX_COLLECTION_DESCRIPTION_LENGTH, AccessMode, Collection, CreateItemData, CollectionLimits,45 CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, Ownership, NftItemType,46 FungibleItemType, ReFungibleItemType,47};4849#[cfg(test)]50mod mock;5152#[cfg(test)]53mod tests;5455mod eth;56mod sponsorship;57pub use sponsorship::NftSponsorshipHandler;58pub use eth::sponsoring::NftEthSponsorshipHandler;5960pub use eth::NftErcSupport;61pub use eth::account::*;62use eth::erc::{ERC20Events, ERC721Events};6364#[cfg(feature = "runtime-benchmarks")]65mod benchmarking;66pub mod weights;67use weights::WeightInfo;6869decl_error! {70 71 pub enum Error for Module<T: Config> {72 73 TotalCollectionsLimitExceeded,74 75 CollectionDecimalPointLimitExceeded,76 77 CollectionNameLimitExceeded,78 79 CollectionDescriptionLimitExceeded,80 81 CollectionTokenPrefixLimitExceeded,82 83 CollectionNotFound,84 85 TokenNotFound,86 87 AdminNotFound,88 89 NumOverflow,90 91 AlreadyAdmin,92 93 NoPermission,94 95 ConfirmUnsetSponsorFail,96 97 PublicMintingNotAllowed,98 99 MustBeTokenOwner,100 101 TokenValueTooLow,102 103 NftSizeLimitExceeded,104 105 ApproveNotFound,106 107 TokenValueNotEnough,108 109 ApproveRequired,110 111 AddresNotInWhiteList,112 113 CollectionAdminsLimitExceeded,114 115 AddressOwnershipLimitExceeded,116 117 EmptyArgument,118 119 TokenConstDataLimitExceeded,120 121 TokenVariableDataLimitExceeded,122 123 NotNftDataUsedToMintNftCollectionToken,124 125 NotFungibleDataUsedToMintFungibleCollectionToken,126 127 NotReFungibleDataUsedToMintReFungibleCollectionToken,128 129 UnexpectedCollectionType,130 131 CantStoreMetadataInFungibleTokens,132 133 CollectionTokenLimitExceeded,134 135 AccountTokenLimitExceeded,136 137 CollectionLimitBoundsExceeded,138 139 OwnerPermissionsCantBeReverted,140 141 SchemaDataLimitExceeded,142 143 WrongRefungiblePieces,144 145 BadCreateRefungibleCall,146 147 OutOfGas,148 149 TransferNotAllowed,150 151 AddressIsZero,152 }153}154155#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]156pub struct CollectionHandle<T: Config> {157 pub id: CollectionId,158 collection: Collection<T>,159 recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,160}161impl<T: Config> CollectionHandle<T> {162 pub fn get_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {163 <CollectionById<T>>::get(id).map(|collection| Self {164 id,165 collection,166 recorder: pallet_evm_coder_substrate::SubstrateRecorder::new(167 eth::collection_id_to_address(id),168 gas_limit,169 ),170 })171 }172 pub fn get(id: CollectionId) -> Option<Self> {173 Self::get_with_gas_limit(id, u64::MAX)174 }175 pub fn log(&self, log: impl evm_coder::ToLog) -> DispatchResult {176 self.recorder.log_sub(log)177 }178 #[allow(dead_code)]179 fn consume_gas(&self, gas: u64) -> DispatchResult {180 self.recorder.consume_gas_sub(gas)181 }182 fn consume_sload(&self) -> DispatchResult {183 self.recorder.consume_sload_sub()184 }185 fn consume_sstore(&self) -> DispatchResult {186 self.recorder.consume_sstore_sub()187 }188 pub fn submit_logs(self) -> DispatchResult {189 self.recorder.submit_logs()190 }191 pub fn save(self) -> DispatchResult {192 self.recorder.submit_logs()?;193 <CollectionById<T>>::insert(self.id, self.collection);194 Ok(())195 }196}197impl<T: Config> Deref for CollectionHandle<T> {198 type Target = Collection<T>;199200 fn deref(&self) -> &Self::Target {201 &self.collection202 }203}204205impl<T: Config> DerefMut for CollectionHandle<T> {206 fn deref_mut(&mut self) -> &mut Self::Target {207 &mut self.collection208 }209}210211pub trait Config: system::Config + pallet_evm_coder_substrate::Config + Sized {212 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;213214 215 type WeightInfo: WeightInfo;216217 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;218 type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;219220 type CrossAccountId: CrossAccountId<Self::AccountId>;221 type Currency: Currency<Self::AccountId>;222 type CollectionCreationPrice: Get<223 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,224 >;225 type TreasuryAccountId: Get<Self::AccountId>;226}227228type SelfWeightOf<T> = <T as Config>::WeightInfo;229230trait WeightInfoHelpers: WeightInfo {231 fn transfer() -> Weight {232 Self::transfer_nft()233 .max(Self::transfer_fungible())234 .max(Self::transfer_refungible())235 }236 fn transfer_from() -> Weight {237 Self::transfer_from_nft()238 .max(Self::transfer_from_fungible())239 .max(Self::transfer_from_refungible())240 }241 fn approve() -> Weight {242 243 Self::approve_nft()244 }245 fn set_variable_meta_data(data: u32) -> Weight {246 247 Self::set_variable_meta_data_nft(data)248 }249 fn create_item(data: u32) -> Weight {250 Self::create_item_nft(data)251 .max(Self::create_item_fungible())252 .max(Self::create_item_refungible(data))253 }254 fn burn_item() -> Weight {255 256 Self::burn_item_nft()257 }258}259impl<T: WeightInfo> WeightInfoHelpers for T {}260261262263264265266267268269270271272273274275276277278279280281282283decl_storage! {284 trait Store for Module<T: Config> as Nft {285286 287 288 CreatedCollectionCount: u32;289 290 ChainVersion: u64;291 292 293 ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;294 295296 297 298 299 DestroyedCollectionCount: u32;300 301 302 pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;303 304305 306 307 308 pub CollectionById get(fn collection_id) config(): map hasher(blake2_128_concat) CollectionId => Option<Collection<T>> = None;309 310 311 pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::CrossAccountId>;312 313 314 pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;315 316317 318 319 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => u128;320321 322 323 324 pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;325326 327 328 pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<NftItemType<T::CrossAccountId>>;329 330 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;331 332 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<ReFungibleItemType<T::CrossAccountId>>;333 334335 336 337 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => Vec<TokenId>;338 339340 341 342 343 pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;344 345 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;346 347 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;348 349 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;350 351352 353 354 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;355 }356 add_extra_genesis {357 build(|config: &GenesisConfig<T>| {358 359 for (_num, _c) in &config.collection_id {360 <Module<T>>::init_collection(_c);361 }362363 for (_num, _c, _i) in &config.nft_item_id {364 <Module<T>>::init_nft_token(*_c, _i);365 }366367 for (collection_id, account_id, fungible_item) in &config.fungible_item_id {368 <Module<T>>::init_fungible_token(*collection_id, &T::CrossAccountId::from_sub(account_id.clone()), fungible_item);369 }370371 for (_num, _c, _i) in &config.refungible_item_id {372 <Module<T>>::init_refungible_token(*_c, _i);373 }374 })375 }376}377378decl_event!(379 pub enum Event<T>380 where381 AccountId = <T as frame_system::Config>::AccountId,382 CrossAccountId = <T as Config>::CrossAccountId,383 {384 385 386 387 388 389 390 391 392 393 CollectionCreated(CollectionId, u8, AccountId),394395 396 397 398 399 400 401 402 403 404 ItemCreated(CollectionId, TokenId, CrossAccountId),405406 407 408 409 410 411 412 413 ItemDestroyed(CollectionId, TokenId),414415 416 417 418 419 420 421 422 423 424 425 426 Transfer(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),427428 429 430 431 432 433 434 435 436 437 Approved(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),438 }439);440441decl_module! {442 pub struct Module<T: Config> for enum Call443 where444 origin: T::Origin445 {446 fn deposit_event() = default;447 const CollectionAdminsLimit: u64 = COLLECTION_ADMINS_LIMIT;448 type Error = Error<T>;449450 fn on_initialize(_now: T::BlockNumber) -> Weight {451 0452 }453454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 #[weight = <SelfWeightOf<T>>::create_collection()]471 #[transactional]472 pub fn create_collection(origin,473 collection_name: Vec<u16>,474 collection_description: Vec<u16>,475 token_prefix: Vec<u8>,476 mode: CollectionMode) -> DispatchResult {477478 479 let who = ensure_signed(origin)?;480481 482 let mut imbalance = <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();483 imbalance.subsume(<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(484 &T::TreasuryAccountId::get(),485 T::CollectionCreationPrice::get(),486 ));487 <T as Config>::Currency::settle(488 &who,489 imbalance,490 WithdrawReasons::TRANSFER,491 ExistenceRequirement::KeepAlive,492 ).map_err(|_| Error::<T>::NoPermission)?;493494 let decimal_points = match mode {495 CollectionMode::Fungible(points) => points,496 _ => 0497 };498499 let created_count = CreatedCollectionCount::get();500 let destroyed_count = DestroyedCollectionCount::get();501502 503 ensure!(created_count - destroyed_count < COLLECTION_NUMBER_LIMIT, Error::<T>::TotalCollectionsLimitExceeded);504505 506 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);507 ensure!(collection_name.len() <= MAX_COLLECTION_NAME_LENGTH, Error::<T>::CollectionNameLimitExceeded);508 ensure!(collection_description.len() <= MAX_COLLECTION_DESCRIPTION_LENGTH, Error::<T>::CollectionDescriptionLimitExceeded);509 ensure!(token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH, Error::<T>::CollectionTokenPrefixLimitExceeded);510511 512 let next_id = created_count513 .checked_add(1)514 .ok_or(Error::<T>::NumOverflow)?;515516 CreatedCollectionCount::put(next_id);517518 let limits = CollectionLimits {519 sponsored_data_size: CUSTOM_DATA_LIMIT,520 ..Default::default()521 };522523 524 let new_collection = Collection {525 owner: who.clone(),526 name: collection_name,527 mode: mode.clone(),528 mint_mode: false,529 access: AccessMode::Normal,530 description: collection_description,531 decimal_points,532 token_prefix,533 offchain_schema: Vec::new(),534 schema_version: SchemaVersion::ImageURL,535 sponsorship: SponsorshipState::Disabled,536 variable_on_chain_schema: Vec::new(),537 const_on_chain_schema: Vec::new(),538 limits,539 transfers_enabled: true,540 };541542 543 <CollectionById<T>>::insert(next_id, new_collection);544545 546 Self::deposit_event(RawEvent::CollectionCreated(next_id, mode.id(), who));547548 Ok(())549 }550551 552 553 554 555 556 557 558 559 560 #[weight = <SelfWeightOf<T>>::destroy_collection()]561 #[transactional]562 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {563564 let sender = ensure_signed(origin)?;565 let collection = Self::get_collection(collection_id)?;566 Self::check_owner_permissions(&collection, &sender)?;567 if !collection.limits.owner_can_destroy {568 fail!(Error::<T>::NoPermission);569 }570571 <AddressTokens<T>>::remove_prefix(collection_id, None);572 <Allowances<T>>::remove_prefix(collection_id, None);573 <Balance<T>>::remove_prefix(collection_id, None);574 <ItemListIndex>::remove(collection_id);575 <AdminList<T>>::remove(collection_id);576 <CollectionById<T>>::remove(collection_id);577 <WhiteList<T>>::remove_prefix(collection_id, None);578579 <NftItemList<T>>::remove_prefix(collection_id, None);580 <FungibleItemList<T>>::remove_prefix(collection_id, None);581 <ReFungibleItemList<T>>::remove_prefix(collection_id, None);582583 <NftTransferBasket<T>>::remove_prefix(collection_id, None);584 <FungibleTransferBasket<T>>::remove_prefix(collection_id, None);585 <ReFungibleTransferBasket<T>>::remove_prefix(collection_id, None);586587 <VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);588589 DestroyedCollectionCount::put(DestroyedCollectionCount::get()590 .checked_add(1)591 .ok_or(Error::<T>::NumOverflow)?);592593 Ok(())594 }595596 597 598 599 600 601 602 603 604 605 606 607 608 #[weight = <SelfWeightOf<T>>::add_to_white_list()]609 #[transactional]610 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{611612 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);613 let collection = Self::get_collection(collection_id)?;614615 Self::toggle_white_list_internal(616 &sender,617 &collection,618 &address,619 true,620 )?;621622 Ok(())623 }624625 626 627 628 629 630 631 632 633 634 635 636 637 #[weight = <SelfWeightOf<T>>::remove_from_white_list()]638 #[transactional]639 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{640641 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);642 let collection = Self::get_collection(collection_id)?;643644 Self::toggle_white_list_internal(645 &sender,646 &collection,647 &address,648 false,649 )?;650651 Ok(())652 }653654 655 656 657 658 659 660 661 662 663 664 665 #[weight = <SelfWeightOf<T>>::set_public_access_mode()]666 #[transactional]667 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult668 {669 let sender = ensure_signed(origin)?;670671 let mut target_collection = Self::get_collection(collection_id)?;672 Self::check_owner_permissions(&target_collection, &sender)?;673 target_collection.access = mode;674 target_collection.save()675 }676677 678 679 680 681 682 683 684 685 686 687 688 689 690 #[weight = <SelfWeightOf<T>>::set_mint_permission()]691 #[transactional]692 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult693 {694 let sender = ensure_signed(origin)?;695696 let mut target_collection = Self::get_collection(collection_id)?;697 Self::check_owner_permissions(&target_collection, &sender)?;698 target_collection.mint_mode = mint_permission;699 target_collection.save()700 }701702 703 704 705 706 707 708 709 710 711 712 713 #[weight = <SelfWeightOf<T>>::change_collection_owner()]714 #[transactional]715 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {716717 let sender = ensure_signed(origin)?;718 let mut target_collection = Self::get_collection(collection_id)?;719 Self::check_owner_permissions(&target_collection, &sender)?;720 target_collection.owner = new_owner;721 target_collection.save()722 }723724 725 726 727 728 729 730 731 732 733 734 735 736 737 #[weight = <SelfWeightOf<T>>::add_collection_admin()]738 #[transactional]739 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {740 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);741 let collection = Self::get_collection(collection_id)?;742 Self::check_owner_or_admin_permissions(&collection, &sender)?;743 let mut admin_arr = <AdminList<T>>::get(collection_id);744745 match admin_arr.binary_search(&new_admin_id) {746 Ok(_) => {},747 Err(idx) => {748 ensure!(admin_arr.len() < COLLECTION_ADMINS_LIMIT as usize, Error::<T>::CollectionAdminsLimitExceeded);749 admin_arr.insert(idx, new_admin_id);750 <AdminList<T>>::insert(collection_id, admin_arr);751 }752 }753 Ok(())754 }755756 757 758 759 760 761 762 763 764 765 766 767 768 #[weight = <SelfWeightOf<T>>::remove_collection_admin()]769 #[transactional]770 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {771 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);772 let collection = Self::get_collection(collection_id)?;773 Self::check_owner_or_admin_permissions(&collection, &sender)?;774 let mut admin_arr = <AdminList<T>>::get(collection_id);775776 if let Ok(idx) = admin_arr.binary_search(&account_id) {777 admin_arr.remove(idx);778 <AdminList<T>>::insert(collection_id, admin_arr);779 }780 Ok(())781 }782783 784 785 786 787 788 789 790 791 792 #[weight = <SelfWeightOf<T>>::set_collection_sponsor()]793 #[transactional]794 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {795 let sender = ensure_signed(origin)?;796 let mut target_collection = Self::get_collection(collection_id)?;797 Self::check_owner_permissions(&target_collection, &sender)?;798799 target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);800 target_collection.save()801 }802803 804 805 806 807 808 809 810 #[weight = <SelfWeightOf<T>>::confirm_sponsorship()]811 #[transactional]812 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {813 let sender = ensure_signed(origin)?;814815 let mut target_collection = Self::get_collection(collection_id)?;816 ensure!(817 target_collection.sponsorship.pending_sponsor() == Some(&sender),818 Error::<T>::ConfirmUnsetSponsorFail819 );820821 target_collection.sponsorship = SponsorshipState::Confirmed(sender);822 target_collection.save()823 }824825 826 827 828 829 830 831 832 833 834 #[weight = <SelfWeightOf<T>>::remove_collection_sponsor()]835 #[transactional]836 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {837 let sender = ensure_signed(origin)?;838839 let mut target_collection = Self::get_collection(collection_id)?;840 Self::check_owner_permissions(&target_collection, &sender)?;841842 target_collection.sponsorship = SponsorshipState::Disabled;843 target_collection.save()844 }845846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869870 #[weight = <SelfWeightOf<T>>::create_item(data.data_size() as u32)]871 #[transactional]872 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResult {873 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);874 let collection = Self::get_collection(collection_id)?;875876 Self::create_item_internal(&sender, &collection, &owner, data)?;877878 collection.submit_logs()879 }880881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 #[weight = <SelfWeightOf<T>>::create_item(items_data.iter()900 .map(|data| { data.data_size() as u32 })901 .sum())]902 #[transactional]903 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResult {904905 ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);906 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);907 let collection = Self::get_collection(collection_id)?;908909 Self::create_multiple_items_internal(&sender, &collection, &owner, items_data)?;910911 collection.submit_logs()912 }913914 915916 917 918 919 920 921 922 923 924 925 926 927 #[weight = <SelfWeightOf<T>>::burn_item()]928 #[transactional]929 pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {930931 let sender = ensure_signed(origin)?;932 let mut target_collection = Self::get_collection(collection_id)?;933934 Self::check_owner_permissions(&target_collection, &sender)?;935936 target_collection.transfers_enabled = value;937 target_collection.save()938 }939940 941 942 943 944 945 946 947 948 949 950 951 952 953 #[weight = <SelfWeightOf<T>>::burn_item()]954 #[transactional]955 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {956957 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);958 let target_collection = Self::get_collection(collection_id)?;959960 Self::burn_item_internal(&sender, &target_collection, item_id, value)?;961962 target_collection.submit_logs()963 }964965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 #[weight = <SelfWeightOf<T>>::transfer()]989 #[transactional]990 pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {991 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);992 let collection = Self::get_collection(collection_id)?;993994 Self::transfer_internal(&sender, &recipient, &collection, item_id, value)?;995996 collection.submit_logs()997 }998999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 #[weight = <SelfWeightOf<T>>::approve()]1015 #[transactional]1016 pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {1017 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1018 let collection = Self::get_collection(collection_id)?;10191020 Self::approve_internal(&sender, &spender, &collection, item_id, amount)?;10211022 collection.submit_logs()1023 }10241025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 #[weight = <SelfWeightOf<T>>::transfer_from()]1045 #[transactional]1046 pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {1047 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1048 let collection = Self::get_collection(collection_id)?;10491050 Self::transfer_from_internal(&sender, &from, &recipient, &collection, item_id, value)?;10511052 collection.submit_logs()1053 }1054 1055 1056 1057 1058 10591060 10611062 10631064 1065 10661067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 #[weight = <SelfWeightOf<T>>::set_variable_meta_data(data.len() as u32)]1080 #[transactional]1081 pub fn set_variable_meta_data (1082 origin,1083 collection_id: CollectionId,1084 item_id: TokenId,1085 data: Vec<u8>1086 ) -> DispatchResult {1087 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);10881089 let collection = Self::get_collection(collection_id)?;10901091 Self::set_variable_meta_data_internal(&sender, &collection, item_id, data)?;10921093 Ok(())1094 }10951096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 #[weight = <SelfWeightOf<T>>::set_schema_version()]1111 #[transactional]1112 pub fn set_schema_version(1113 origin,1114 collection_id: CollectionId,1115 version: SchemaVersion1116 ) -> DispatchResult {1117 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1118 let mut target_collection = Self::get_collection(collection_id)?;1119 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;1120 target_collection.schema_version = version;1121 target_collection.save()1122 }11231124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 #[weight = <SelfWeightOf<T>>::set_offchain_schema(schema.len() as u32)]1137 #[transactional]1138 pub fn set_offchain_schema(1139 origin,1140 collection_id: CollectionId,1141 schema: Vec<u8>1142 ) -> DispatchResult {1143 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1144 let mut target_collection = Self::get_collection(collection_id)?;1145 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;11461147 1148 ensure!(schema.len() as u32 <= OFFCHAIN_SCHEMA_LIMIT, "");11491150 target_collection.offchain_schema = schema;1151 target_collection.save()1152 }11531154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 #[weight = <SelfWeightOf<T>>::set_const_on_chain_schema(schema.len() as u32)]1167 #[transactional]1168 pub fn set_const_on_chain_schema (1169 origin,1170 collection_id: CollectionId,1171 schema: Vec<u8>1172 ) -> DispatchResult {1173 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1174 let mut target_collection = Self::get_collection(collection_id)?;1175 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;11761177 1178 ensure!(schema.len() as u32 <= CONST_ON_CHAIN_SCHEMA_LIMIT, "");11791180 target_collection.const_on_chain_schema = schema;1181 target_collection.save()1182 }11831184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 #[weight = <SelfWeightOf<T>>::set_const_on_chain_schema(schema.len() as u32)]1197 #[transactional]1198 pub fn set_variable_on_chain_schema (1199 origin,1200 collection_id: CollectionId,1201 schema: Vec<u8>1202 ) -> DispatchResult {1203 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1204 let mut target_collection = Self::get_collection(collection_id)?;1205 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;12061207 1208 ensure!(schema.len() as u32 <= VARIABLE_ON_CHAIN_SCHEMA_LIMIT, "");12091210 target_collection.variable_on_chain_schema = schema;1211 target_collection.save()1212 }12131214 #[weight = <SelfWeightOf<T>>::set_collection_limits()]1215 #[transactional]1216 pub fn set_collection_limits(1217 origin,1218 collection_id: u32,1219 new_limits: CollectionLimits<T::BlockNumber>,1220 ) -> DispatchResult {1221 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1222 let mut target_collection = Self::get_collection(collection_id)?;1223 Self::check_owner_permissions(&target_collection, sender.as_sub())?;1224 let old_limits = &target_collection.limits;12251226 1227 ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&1228 new_limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP &&1229 new_limits.sponsored_data_size <= CUSTOM_DATA_LIMIT,1230 Error::<T>::CollectionLimitBoundsExceeded);12311232 1233 ensure!(old_limits.token_limit >= new_limits.token_limit, Error::<T>::CollectionTokenLimitExceeded);1234 ensure!(new_limits.token_limit > 0, Error::<T>::CollectionTokenLimitExceeded);12351236 ensure!(1237 (old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&1238 (old_limits.owner_can_destroy || !new_limits.owner_can_destroy),1239 Error::<T>::OwnerPermissionsCantBeReverted,1240 );12411242 target_collection.limits = new_limits;12431244 target_collection.save()1245 }1246 }1247}12481249impl<T: Config> Module<T> {1250 pub fn create_item_internal(1251 sender: &T::CrossAccountId,1252 collection: &CollectionHandle<T>,1253 owner: &T::CrossAccountId,1254 data: CreateItemData,1255 ) -> DispatchResult {1256 ensure!(1257 owner != &T::CrossAccountId::from_eth(H160([0; 20])),1258 Error::<T>::AddressIsZero1259 );12601261 Self::can_create_items_in_collection(collection, sender, owner, 1)?;1262 Self::validate_create_item_args(collection, &data)?;1263 Self::create_item_no_validation(collection, owner, data)?;12641265 Ok(())1266 }12671268 pub fn transfer_internal(1269 sender: &T::CrossAccountId,1270 recipient: &T::CrossAccountId,1271 target_collection: &CollectionHandle<T>,1272 item_id: TokenId,1273 value: u128,1274 ) -> DispatchResult {1275 ensure!(1276 recipient != &T::CrossAccountId::from_eth(H160([0; 20])),1277 Error::<T>::AddressIsZero1278 );12791280 1281 Self::is_correct_transfer(target_collection, recipient)?;12821283 1284 ensure!(1285 Self::is_item_owner(sender, target_collection, item_id)?1286 || Self::is_owner_or_admin_permissions(target_collection, sender)?,1287 Error::<T>::NoPermission1288 );12891290 if target_collection.access == AccessMode::WhiteList {1291 Self::check_white_list(target_collection, sender)?;1292 Self::check_white_list(target_collection, recipient)?;1293 }12941295 match target_collection.mode {1296 CollectionMode::NFT => Self::transfer_nft(1297 target_collection,1298 item_id,1299 sender.clone(),1300 recipient.clone(),1301 )?,1302 CollectionMode::Fungible(_) => {1303 Self::transfer_fungible(target_collection, value, sender, recipient)?1304 }1305 CollectionMode::ReFungible => Self::transfer_refungible(1306 target_collection,1307 item_id,1308 value,1309 sender.clone(),1310 recipient.clone(),1311 )?,1312 _ => (),1313 };13141315 Self::deposit_event(RawEvent::Transfer(1316 target_collection.id,1317 item_id,1318 sender.clone(),1319 recipient.clone(),1320 value,1321 ));13221323 Ok(())1324 }13251326 pub fn approve_internal(1327 sender: &T::CrossAccountId,1328 spender: &T::CrossAccountId,1329 collection: &CollectionHandle<T>,1330 item_id: TokenId,1331 amount: u128,1332 ) -> DispatchResult {1333 Self::token_exists(collection, item_id)?;13341335 1336 let bypasses_limits = collection.limits.owner_can_transfer1337 && Self::is_owner_or_admin_permissions(collection, sender)?;13381339 let allowance_limit = if bypasses_limits {1340 None1341 } else if let Some(amount) = Self::owned_amount(sender, collection, item_id)? {1342 Some(amount)1343 } else {1344 fail!(Error::<T>::NoPermission);1345 };13461347 if collection.access == AccessMode::WhiteList {1348 Self::check_white_list(collection, sender)?;1349 Self::check_white_list(collection, spender)?;1350 }13511352 collection.consume_sload()?;1353 let allowance: u128 = amount1354 .checked_add(<Allowances<T>>::get(1355 collection.id,1356 (item_id, sender.as_sub(), spender.as_sub()),1357 ))1358 .ok_or(Error::<T>::NumOverflow)?;1359 if let Some(limit) = allowance_limit {1360 ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);1361 }1362 collection.consume_sstore()?;1363 <Allowances<T>>::insert(1364 collection.id,1365 (item_id, sender.as_sub(), spender.as_sub()),1366 allowance,1367 );13681369 if matches!(collection.mode, CollectionMode::NFT) {1370 1371 collection.log(ERC721Events::Approval {1372 owner: *sender.as_eth(),1373 approved: *spender.as_eth(),1374 token_id: item_id.into(),1375 })?;1376 }13771378 if matches!(collection.mode, CollectionMode::Fungible(_)) {1379 1380 collection.log(ERC20Events::Approval {1381 owner: *sender.as_eth(),1382 spender: *spender.as_eth(),1383 value: allowance.into(),1384 })?;1385 }13861387 Self::deposit_event(RawEvent::Approved(1388 collection.id,1389 item_id,1390 sender.clone(),1391 spender.clone(),1392 allowance,1393 ));1394 Ok(())1395 }13961397 pub fn transfer_from_internal(1398 sender: &T::CrossAccountId,1399 from: &T::CrossAccountId,1400 recipient: &T::CrossAccountId,1401 collection: &CollectionHandle<T>,1402 item_id: TokenId,1403 amount: u128,1404 ) -> DispatchResult {1405 if sender == from {1406 1407 return Self::transfer_internal(from, recipient, collection, item_id, amount);1408 }14091410 1411 collection.consume_sload()?;1412 let approval: u128 =1413 <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));14141415 1416 Self::is_correct_transfer(collection, recipient)?;14171418 1419 ensure!(1420 approval >= amount1421 || (collection.limits.owner_can_transfer1422 && Self::is_owner_or_admin_permissions(collection, sender)?),1423 Error::<T>::NoPermission1424 );14251426 if collection.access == AccessMode::WhiteList {1427 Self::check_white_list(collection, sender)?;1428 Self::check_white_list(collection, recipient)?;1429 }14301431 1432 let allowance = approval.saturating_sub(amount);1433 collection.consume_sstore()?;1434 if allowance > 0 {1435 <Allowances<T>>::insert(1436 collection.id,1437 (item_id, from.as_sub(), sender.as_sub()),1438 allowance,1439 );1440 } else {1441 <Allowances<T>>::remove(collection.id, (item_id, from.as_sub(), sender.as_sub()));1442 }14431444 match collection.mode {1445 CollectionMode::NFT => {1446 Self::transfer_nft(collection, item_id, from.clone(), recipient.clone())?1447 }1448 CollectionMode::Fungible(_) => {1449 Self::transfer_fungible(collection, amount, from, recipient)?1450 }1451 CollectionMode::ReFungible => Self::transfer_refungible(1452 collection,1453 item_id,1454 amount,1455 from.clone(),1456 recipient.clone(),1457 )?,1458 _ => (),1459 };14601461 if matches!(collection.mode, CollectionMode::Fungible(_)) {1462 collection.log(ERC20Events::Approval {1463 owner: *from.as_eth(),1464 spender: *sender.as_eth(),1465 value: allowance.into(),1466 })?;1467 }14681469 Ok(())1470 }14711472 pub fn set_variable_meta_data_internal(1473 sender: &T::CrossAccountId,1474 collection: &CollectionHandle<T>,1475 item_id: TokenId,1476 data: Vec<u8>,1477 ) -> DispatchResult {1478 Self::token_exists(collection, item_id)?;14791480 ensure!(1481 CUSTOM_DATA_LIMIT >= data.len() as u32,1482 Error::<T>::TokenVariableDataLimitExceeded1483 );14841485 1486 ensure!(1487 Self::is_item_owner(sender, collection, item_id)?1488 || Self::is_owner_or_admin_permissions(collection, sender)?,1489 Error::<T>::NoPermission1490 );14911492 match collection.mode {1493 CollectionMode::NFT => Self::set_nft_variable_data(collection, item_id, data)?,1494 CollectionMode::ReFungible => {1495 Self::set_re_fungible_variable_data(collection, item_id, data)?1496 }1497 CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),1498 _ => fail!(Error::<T>::UnexpectedCollectionType),1499 };15001501 Ok(())1502 }15031504 pub fn get_variable_metadata(1505 collection: &CollectionHandle<T>,1506 item_id: TokenId,1507 ) -> Result<Vec<u8>, DispatchError> {1508 Ok(match collection.mode {1509 CollectionMode::NFT => {1510 <NftItemList<T>>::get(collection.id, item_id)1511 .ok_or(Error::<T>::TokenNotFound)?1512 .variable_data1513 }1514 CollectionMode::ReFungible => {1515 <ReFungibleItemList<T>>::get(collection.id, item_id)1516 .ok_or(Error::<T>::TokenNotFound)?1517 .variable_data1518 }1519 _ => fail!(Error::<T>::UnexpectedCollectionType),1520 })1521 }15221523 pub fn create_multiple_items_internal(1524 sender: &T::CrossAccountId,1525 collection: &CollectionHandle<T>,1526 owner: &T::CrossAccountId,1527 items_data: Vec<CreateItemData>,1528 ) -> DispatchResult {1529 Self::can_create_items_in_collection(collection, sender, owner, items_data.len() as u32)?;15301531 for data in &items_data {1532 Self::validate_create_item_args(collection, data)?;1533 }1534 for data in &items_data {1535 Self::create_item_no_validation(collection, owner, data.clone())?;1536 }15371538 Ok(())1539 }15401541 pub fn burn_item_internal(1542 sender: &T::CrossAccountId,1543 collection: &CollectionHandle<T>,1544 item_id: TokenId,1545 value: u128,1546 ) -> DispatchResult {1547 ensure!(1548 Self::is_item_owner(sender, collection, item_id)?1549 || (collection.limits.owner_can_transfer1550 && Self::is_owner_or_admin_permissions(collection, sender)?),1551 Error::<T>::NoPermission1552 );15531554 if collection.access == AccessMode::WhiteList {1555 Self::check_white_list(collection, sender)?;1556 }15571558 match collection.mode {1559 CollectionMode::NFT => Self::burn_nft_item(collection, item_id)?,1560 CollectionMode::Fungible(_) => Self::burn_fungible_item(sender, collection, value)?,1561 CollectionMode::ReFungible => Self::burn_refungible_item(collection, item_id, sender)?,1562 _ => (),1563 };15641565 Ok(())1566 }15671568 pub fn toggle_white_list_internal(1569 sender: &T::CrossAccountId,1570 collection: &CollectionHandle<T>,1571 address: &T::CrossAccountId,1572 whitelisted: bool,1573 ) -> DispatchResult {1574 Self::check_owner_or_admin_permissions(collection, sender)?;15751576 if whitelisted {1577 <WhiteList<T>>::insert(collection.id, address.as_sub(), true);1578 } else {1579 <WhiteList<T>>::remove(collection.id, address.as_sub());1580 }15811582 Ok(())1583 }15841585 fn is_correct_transfer(1586 collection: &CollectionHandle<T>,1587 recipient: &T::CrossAccountId,1588 ) -> DispatchResult {1589 let collection_id = collection.id;15901591 1592 collection.consume_sload()?;1593 let account_items: u32 =1594 <AddressTokens<T>>::get(collection_id, recipient.as_sub()).len() as u32;1595 ensure!(1596 collection.limits.account_token_ownership_limit > account_items,1597 Error::<T>::AccountTokenLimitExceeded1598 );15991600 1601 ensure!(collection.transfers_enabled, Error::<T>::TransferNotAllowed);16021603 Ok(())1604 }16051606 fn can_create_items_in_collection(1607 collection: &CollectionHandle<T>,1608 sender: &T::CrossAccountId,1609 owner: &T::CrossAccountId,1610 amount: u32,1611 ) -> DispatchResult {1612 let collection_id = collection.id;16131614 1615 let total_items: u32 = ItemListIndex::get(collection_id)1616 .checked_add(amount)1617 .ok_or(Error::<T>::CollectionTokenLimitExceeded)?;1618 let account_items: u32 = (<AddressTokens<T>>::get(collection_id, owner.as_sub()).len()1619 as u32)1620 .checked_add(amount)1621 .ok_or(Error::<T>::AccountTokenLimitExceeded)?;1622 ensure!(1623 collection.limits.token_limit >= total_items,1624 Error::<T>::CollectionTokenLimitExceeded1625 );1626 ensure!(1627 collection.limits.account_token_ownership_limit >= account_items,1628 Error::<T>::AccountTokenLimitExceeded1629 );16301631 if !Self::is_owner_or_admin_permissions(collection, sender)? {1632 ensure!(collection.mint_mode, Error::<T>::PublicMintingNotAllowed);1633 Self::check_white_list(collection, owner)?;1634 Self::check_white_list(collection, sender)?;1635 }16361637 Ok(())1638 }16391640 fn validate_create_item_args(1641 target_collection: &CollectionHandle<T>,1642 data: &CreateItemData,1643 ) -> DispatchResult {1644 match target_collection.mode {1645 CollectionMode::NFT => {1646 if !matches!(data, CreateItemData::NFT(_)) {1647 fail!(Error::<T>::NotNftDataUsedToMintNftCollectionToken);1648 }1649 }1650 CollectionMode::Fungible(_) => {1651 if !matches!(data, CreateItemData::Fungible(_)) {1652 fail!(Error::<T>::NotFungibleDataUsedToMintFungibleCollectionToken);1653 }1654 }1655 CollectionMode::ReFungible => {1656 if let CreateItemData::ReFungible(data) = data {1657 1658 ensure!(1659 data.pieces <= MAX_REFUNGIBLE_PIECES,1660 Error::<T>::WrongRefungiblePieces1661 );1662 ensure!(data.pieces > 0, Error::<T>::WrongRefungiblePieces);1663 } else {1664 fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);1665 }1666 }1667 _ => {1668 fail!(Error::<T>::UnexpectedCollectionType);1669 }1670 };16711672 Ok(())1673 }16741675 fn create_item_no_validation(1676 collection: &CollectionHandle<T>,1677 owner: &T::CrossAccountId,1678 data: CreateItemData,1679 ) -> DispatchResult {1680 match data {1681 CreateItemData::NFT(data) => {1682 let item = NftItemType {1683 owner: owner.clone(),1684 const_data: data.const_data.into_inner(),1685 variable_data: data.variable_data.into_inner(),1686 };16871688 Self::add_nft_item(collection, item)?;1689 }1690 CreateItemData::Fungible(data) => {1691 Self::add_fungible_item(collection, owner, data.value)?;1692 }1693 CreateItemData::ReFungible(data) => {1694 let owner_list = vec![Ownership {1695 owner: owner.clone(),1696 fraction: data.pieces,1697 }];16981699 let item = ReFungibleItemType {1700 owner: owner_list,1701 const_data: data.const_data.into_inner(),1702 variable_data: data.variable_data.into_inner(),1703 };17041705 Self::add_refungible_item(collection, item)?;1706 }1707 };17081709 Ok(())1710 }17111712 fn add_fungible_item(1713 collection: &CollectionHandle<T>,1714 owner: &T::CrossAccountId,1715 value: u128,1716 ) -> DispatchResult {1717 let collection_id = collection.id;17181719 1720 collection.consume_sload()?;1721 let balance: u128 = <FungibleItemList<T>>::get(collection_id, owner.as_sub()).value;17221723 1724 let item = FungibleItemType {1725 value: balance.checked_add(value).ok_or(Error::<T>::NumOverflow)?,1726 };1727 collection.consume_sstore()?;1728 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), item);17291730 1731 collection.consume_sload()?;1732 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1733 .checked_add(value)1734 .ok_or(Error::<T>::NumOverflow)?;1735 collection.consume_sstore()?;1736 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);17371738 collection.log(ERC20Events::Transfer {1739 from: H160::default(),1740 to: *owner.as_eth(),1741 value: value.into(),1742 })?;1743 Self::deposit_event(RawEvent::ItemCreated(collection_id, 0, owner.clone()));1744 Ok(())1745 }17461747 fn add_refungible_item(1748 collection: &CollectionHandle<T>,1749 item: ReFungibleItemType<T::CrossAccountId>,1750 ) -> DispatchResult {1751 let collection_id = collection.id;17521753 let current_index = <ItemListIndex>::get(collection_id)1754 .checked_add(1)1755 .ok_or(Error::<T>::NumOverflow)?;1756 let itemcopy = item.clone();17571758 ensure!(item.owner.len() == 1, Error::<T>::BadCreateRefungibleCall,);1759 let item_owner = item.owner.first().expect("only one owner is defined");17601761 let value = item_owner.fraction;1762 let owner = item_owner.owner.clone();17631764 Self::add_token_index(collection, current_index, &owner)?;17651766 <ItemListIndex>::insert(collection_id, current_index);1767 <ReFungibleItemList<T>>::insert(collection_id, current_index, itemcopy);17681769 1770 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1771 .checked_add(value)1772 .ok_or(Error::<T>::NumOverflow)?;1773 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);17741775 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, owner));1776 Ok(())1777 }17781779 fn add_nft_item(1780 collection: &CollectionHandle<T>,1781 item: NftItemType<T::CrossAccountId>,1782 ) -> DispatchResult {1783 let collection_id = collection.id;17841785 let current_index = <ItemListIndex>::get(collection_id)1786 .checked_add(1)1787 .ok_or(Error::<T>::NumOverflow)?;17881789 let item_owner = item.owner.clone();1790 Self::add_token_index(collection, current_index, &item.owner)?;17911792 <ItemListIndex>::insert(collection_id, current_index);1793 <NftItemList<T>>::insert(collection_id, current_index, item);17941795 1796 let new_balance = <Balance<T>>::get(collection_id, item_owner.as_sub())1797 .checked_add(1)1798 .ok_or(Error::<T>::NumOverflow)?;1799 <Balance<T>>::insert(collection_id, item_owner.as_sub(), new_balance);18001801 collection.log(ERC721Events::Transfer {1802 from: H160::default(),1803 to: *item_owner.as_eth(),1804 token_id: current_index.into(),1805 })?;1806 Self::deposit_event(RawEvent::ItemCreated(1807 collection_id,1808 current_index,1809 item_owner,1810 ));1811 Ok(())1812 }18131814 fn burn_refungible_item(1815 collection: &CollectionHandle<T>,1816 item_id: TokenId,1817 owner: &T::CrossAccountId,1818 ) -> DispatchResult {1819 let collection_id = collection.id;18201821 let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id)1822 .ok_or(Error::<T>::TokenNotFound)?;1823 let rft_balance = token1824 .owner1825 .iter()1826 .find(|&i| i.owner == *owner)1827 .ok_or(Error::<T>::TokenNotFound)?;1828 Self::remove_token_index(collection, item_id, owner)?;18291830 1831 let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.as_sub())1832 .checked_sub(rft_balance.fraction)1833 .ok_or(Error::<T>::NumOverflow)?;1834 <Balance<T>>::insert(collection_id, rft_balance.owner.as_sub(), new_balance);18351836 1837 let index = token1838 .owner1839 .iter()1840 .position(|i| i.owner == *owner)1841 .expect("owned item is exists");1842 token.owner.remove(index);1843 let owner_count = token.owner.len();18441845 1846 if owner_count == 0 {1847 <ReFungibleItemList<T>>::remove(collection_id, item_id);1848 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);1849 } else {1850 <ReFungibleItemList<T>>::insert(collection_id, item_id, token);1851 }18521853 Ok(())1854 }18551856 fn burn_nft_item(collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {1857 let collection_id = collection.id;18581859 let item =1860 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;1861 Self::remove_token_index(collection, item_id, &item.owner)?;18621863 1864 let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())1865 .checked_sub(1)1866 .ok_or(Error::<T>::NumOverflow)?;1867 <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);1868 <NftItemList<T>>::remove(collection_id, item_id);1869 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);18701871 collection.log(ERC721Events::Transfer {1872 from: *item.owner.as_eth(),1873 to: H160::default(),1874 token_id: item_id.into(),1875 })?;1876 Self::deposit_event(RawEvent::ItemDestroyed(collection.id, item_id));1877 Ok(())1878 }18791880 fn burn_fungible_item(1881 owner: &T::CrossAccountId,1882 collection: &CollectionHandle<T>,1883 value: u128,1884 ) -> DispatchResult {1885 let collection_id = collection.id;18861887 let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());1888 ensure!(balance.value >= value, Error::<T>::TokenValueNotEnough);18891890 1891 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1892 .checked_sub(value)1893 .ok_or(Error::<T>::NumOverflow)?;1894 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);18951896 if balance.value - value > 0 {1897 balance.value -= value;1898 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);1899 } else {1900 <FungibleItemList<T>>::remove(collection_id, owner.as_sub());1901 }19021903 collection.log(ERC20Events::Transfer {1904 from: *owner.as_eth(),1905 to: H160::default(),1906 value: value.into(),1907 })?;1908 Ok(())1909 }19101911 pub fn get_collection(1912 collection_id: CollectionId,1913 ) -> Result<CollectionHandle<T>, sp_runtime::DispatchError> {1914 Ok(<CollectionHandle<T>>::get(collection_id).ok_or(Error::<T>::CollectionNotFound)?)1915 }19161917 fn check_owner_permissions(1918 target_collection: &CollectionHandle<T>,1919 subject: &T::AccountId,1920 ) -> DispatchResult {1921 ensure!(1922 *subject == target_collection.owner,1923 Error::<T>::NoPermission1924 );19251926 Ok(())1927 }19281929 fn is_owner_or_admin_permissions(1930 collection: &CollectionHandle<T>,1931 subject: &T::CrossAccountId,1932 ) -> Result<bool, DispatchError> {1933 collection.consume_sload()?;1934 Ok(*subject.as_sub() == collection.owner1935 || <AdminList<T>>::get(collection.id).contains(subject))1936 }19371938 fn check_owner_or_admin_permissions(1939 collection: &CollectionHandle<T>,1940 subject: &T::CrossAccountId,1941 ) -> DispatchResult {1942 ensure!(1943 Self::is_owner_or_admin_permissions(collection, subject)?,1944 Error::<T>::NoPermission1945 );19461947 Ok(())1948 }19491950 fn owned_amount(1951 subject: &T::CrossAccountId,1952 collection: &CollectionHandle<T>,1953 item_id: TokenId,1954 ) -> Result<Option<u128>, DispatchError> {1955 collection.consume_sload()?;1956 Ok(Self::owned_amount_unchecked(subject, collection, item_id))1957 }19581959 fn owned_amount_unchecked(1960 subject: &T::CrossAccountId,1961 target_collection: &CollectionHandle<T>,1962 item_id: TokenId,1963 ) -> Option<u128> {1964 let collection_id = target_collection.id;19651966 match target_collection.mode {1967 CollectionMode::NFT => {1968 (<NftItemList<T>>::get(collection_id, item_id)?.owner == *subject).then(|| 1)1969 }1970 CollectionMode::Fungible(_) => {1971 Some(<FungibleItemList<T>>::get(collection_id, &subject.as_sub()).value)1972 }1973 CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)?1974 .owner1975 .iter()1976 .find(|i| i.owner == *subject)1977 .map(|i| i.fraction),1978 CollectionMode::Invalid => None,1979 }1980 }19811982 fn is_item_owner(1983 subject: &T::CrossAccountId,1984 target_collection: &CollectionHandle<T>,1985 item_id: TokenId,1986 ) -> Result<bool, DispatchError> {1987 Ok(match target_collection.mode {1988 CollectionMode::Fungible(_) => true,1989 _ => Self::owned_amount(subject, target_collection, item_id)?.is_some(),1990 })1991 }19921993 fn check_white_list(1994 collection: &CollectionHandle<T>,1995 address: &T::CrossAccountId,1996 ) -> DispatchResult {1997 collection.consume_sload()?;1998 ensure!(1999 <WhiteList<T>>::contains_key(collection.id, address.as_sub()),2000 Error::<T>::AddresNotInWhiteList,2001 );2002 Ok(())2003 }20042005 2006 2007 fn token_exists(target_collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {2008 let collection_id = target_collection.id;2009 let exists = match target_collection.mode {2010 CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),2011 CollectionMode::Fungible(_) => true,2012 CollectionMode::ReFungible => {2013 <ReFungibleItemList<T>>::contains_key(collection_id, item_id)2014 }2015 _ => false,2016 };20172018 ensure!(exists, Error::<T>::TokenNotFound);2019 Ok(())2020 }20212022 fn transfer_fungible(2023 collection: &CollectionHandle<T>,2024 value: u128,2025 owner: &T::CrossAccountId,2026 recipient: &T::CrossAccountId,2027 ) -> DispatchResult {2028 let collection_id = collection.id;20292030 collection.consume_sload()?;2031 collection.consume_sload()?;2032 let mut recipient_balance = <FungibleItemList<T>>::get(collection_id, recipient.as_sub());2033 let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());20342035 recipient_balance.value = recipient_balance2036 .value2037 .checked_add(value)2038 .ok_or(Error::<T>::NumOverflow)?;2039 balance.value = balance2040 .value2041 .checked_sub(value)2042 .ok_or(Error::<T>::TokenValueTooLow)?;20432044 2045 collection.consume_sstore()?;2046 collection.consume_sstore()?;2047 if balance.value != 0 {2048 <Balance<T>>::insert(collection_id, owner.as_sub(), balance.value);2049 } else {2050 <Balance<T>>::remove(collection_id, owner.as_sub());2051 }2052 <Balance<T>>::insert(collection_id, recipient.as_sub(), recipient_balance.value);20532054 2055 collection.consume_sstore()?;2056 collection.consume_sstore()?;2057 if balance.value != 0 {2058 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);2059 } else {2060 <FungibleItemList<T>>::remove(collection_id, owner.as_sub());2061 }2062 <FungibleItemList<T>>::insert(collection_id, recipient.as_sub(), recipient_balance);20632064 collection.log(ERC20Events::Transfer {2065 from: *owner.as_eth(),2066 to: *recipient.as_eth(),2067 value: value.into(),2068 })?;2069 Self::deposit_event(RawEvent::Transfer(2070 collection.id,2071 1,2072 owner.clone(),2073 recipient.clone(),2074 value,2075 ));20762077 Ok(())2078 }20792080 fn transfer_refungible(2081 collection: &CollectionHandle<T>,2082 item_id: TokenId,2083 value: u128,2084 owner: T::CrossAccountId,2085 new_owner: T::CrossAccountId,2086 ) -> DispatchResult {2087 let collection_id = collection.id;2088 collection.consume_sload()?;2089 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id)2090 .ok_or(Error::<T>::TokenNotFound)?;20912092 let item = full_item2093 .owner2094 .iter()2095 .find(|i| i.owner == owner)2096 .ok_or(Error::<T>::TokenNotFound)?;2097 let amount = item.fraction;20982099 ensure!(amount >= value, Error::<T>::TokenValueTooLow);21002101 collection.consume_sload()?;2102 2103 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())2104 .checked_sub(value)2105 .ok_or(Error::<T>::NumOverflow)?;2106 collection.consume_sstore()?;2107 <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);21082109 collection.consume_sload()?;2110 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())2111 .checked_add(value)2112 .ok_or(Error::<T>::NumOverflow)?;2113 collection.consume_sstore()?;2114 <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);21152116 let old_owner = item.owner.clone();2117 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);21182119 let mut new_full_item = full_item.clone();2120 2121 if amount == value && !new_owner_has_account {2122 2123 2124 new_full_item2125 .owner2126 .iter_mut()2127 .find(|i| i.owner == owner)2128 .expect("old owner does present in refungible")2129 .owner = new_owner.clone();2130 collection.consume_sstore()?;2131 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);21322133 2134 Self::move_token_index(collection, item_id, &old_owner, &new_owner)?;2135 } else {2136 new_full_item2137 .owner2138 .iter_mut()2139 .find(|i| i.owner == owner)2140 .expect("old owner does present in refungible")2141 .fraction -= value;21422143 2144 if new_owner_has_account {2145 2146 new_full_item2147 .owner2148 .iter_mut()2149 .find(|i| i.owner == new_owner)2150 .expect("new owner has account")2151 .fraction += value;2152 } else {2153 2154 new_full_item.owner.push(Ownership {2155 owner: new_owner.clone(),2156 fraction: value,2157 });2158 Self::add_token_index(collection, item_id, &new_owner)?;2159 }21602161 collection.consume_sstore()?;2162 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);2163 }21642165 Self::deposit_event(RawEvent::Transfer(2166 collection.id,2167 item_id,2168 owner,2169 new_owner,2170 amount,2171 ));21722173 Ok(())2174 }21752176 fn transfer_nft(2177 collection: &CollectionHandle<T>,2178 item_id: TokenId,2179 sender: T::CrossAccountId,2180 new_owner: T::CrossAccountId,2181 ) -> DispatchResult {2182 let collection_id = collection.id;2183 collection.consume_sload()?;2184 let mut item =2185 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;21862187 ensure!(sender == item.owner, Error::<T>::MustBeTokenOwner);21882189 collection.consume_sload()?;2190 2191 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())2192 .checked_sub(1)2193 .ok_or(Error::<T>::NumOverflow)?;2194 collection.consume_sstore()?;2195 <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);21962197 collection.consume_sload()?;2198 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())2199 .checked_add(1)2200 .ok_or(Error::<T>::NumOverflow)?;2201 collection.consume_sstore()?;2202 <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);22032204 2205 let old_owner = item.owner.clone();2206 item.owner = new_owner.clone();2207 collection.consume_sstore()?;2208 <NftItemList<T>>::insert(collection_id, item_id, item);22092210 2211 Self::move_token_index(collection, item_id, &old_owner, &new_owner)?;22122213 collection.log(ERC721Events::Transfer {2214 from: *sender.as_eth(),2215 to: *new_owner.as_eth(),2216 token_id: item_id.into(),2217 })?;2218 Self::deposit_event(RawEvent::Transfer(2219 collection.id,2220 item_id,2221 sender,2222 new_owner,2223 1,2224 ));22252226 Ok(())2227 }22282229 fn set_re_fungible_variable_data(2230 collection: &CollectionHandle<T>,2231 item_id: TokenId,2232 data: Vec<u8>,2233 ) -> DispatchResult {2234 let collection_id = collection.id;2235 let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id)2236 .ok_or(Error::<T>::TokenNotFound)?;22372238 item.variable_data = data;22392240 <ReFungibleItemList<T>>::insert(collection_id, item_id, item);22412242 Ok(())2243 }22442245 fn set_nft_variable_data(2246 collection: &CollectionHandle<T>,2247 item_id: TokenId,2248 data: Vec<u8>,2249 ) -> DispatchResult {2250 let collection_id = collection.id;2251 let mut item =2252 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;22532254 item.variable_data = data;22552256 <NftItemList<T>>::insert(collection_id, item_id, item);22572258 Ok(())2259 }22602261 #[allow(dead_code)]2262 fn init_collection(item: &Collection<T>) {2263 2264 assert!(2265 item.decimal_points <= MAX_DECIMAL_POINTS,2266 "decimal_points parameter must be lower than MAX_DECIMAL_POINTS"2267 );2268 assert!(2269 item.name.len() <= 64,2270 "Collection name can not be longer than 63 char"2271 );2272 assert!(2273 item.name.len() <= 256,2274 "Collection description can not be longer than 255 char"2275 );2276 assert!(2277 item.token_prefix.len() <= 16,2278 "Token prefix can not be longer than 15 char"2279 );22802281 2282 let next_id = CreatedCollectionCount::get().checked_add(1).unwrap();22832284 CreatedCollectionCount::put(next_id);2285 }22862287 #[allow(dead_code)]2288 fn init_nft_token(collection_id: CollectionId, item: &NftItemType<T::CrossAccountId>) {2289 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();22902291 Self::add_token_index(2292 &CollectionHandle::get(collection_id).unwrap(),2293 current_index,2294 &item.owner,2295 )2296 .unwrap();22972298 <ItemListIndex>::insert(collection_id, current_index);22992300 2301 let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())2302 .checked_add(1)2303 .unwrap();2304 <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);2305 }23062307 #[allow(dead_code)]2308 fn init_fungible_token(2309 collection_id: CollectionId,2310 owner: &T::CrossAccountId,2311 item: &FungibleItemType,2312 ) {2313 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();23142315 Self::add_token_index(2316 &CollectionHandle::get(collection_id).unwrap(),2317 current_index,2318 owner,2319 )2320 .unwrap();23212322 <ItemListIndex>::insert(collection_id, current_index);23232324 2325 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())2326 .checked_add(item.value)2327 .unwrap();2328 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);2329 }23302331 #[allow(dead_code)]2332 fn init_refungible_token(2333 collection_id: CollectionId,2334 item: &ReFungibleItemType<T::CrossAccountId>,2335 ) {2336 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();23372338 let value = item.owner.first().unwrap().fraction;2339 let owner = item.owner.first().unwrap().owner.clone();23402341 Self::add_token_index(2342 &CollectionHandle::get(collection_id).unwrap(),2343 current_index,2344 &owner,2345 )2346 .unwrap();23472348 <ItemListIndex>::insert(collection_id, current_index);23492350 2351 let new_balance = <Balance<T>>::get(collection_id, &owner.as_sub())2352 .checked_add(value)2353 .unwrap();2354 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);2355 }23562357 fn add_token_index(2358 collection: &CollectionHandle<T>,2359 item_index: TokenId,2360 owner: &T::CrossAccountId,2361 ) -> DispatchResult {2362 2363 collection.consume_sload()?;2364 if <AccountItemCount<T>>::contains_key(owner.as_sub()) {2365 2366 collection.consume_sload()?;2367 let count = <AccountItemCount<T>>::get(owner.as_sub());2368 ensure!(2369 count < ACCOUNT_TOKEN_OWNERSHIP_LIMIT,2370 Error::<T>::AddressOwnershipLimitExceeded2371 );23722373 collection.consume_sstore()?;2374 <AccountItemCount<T>>::insert(2375 owner.as_sub(),2376 count.checked_add(1).ok_or(Error::<T>::NumOverflow)?,2377 );2378 } else {2379 collection.consume_sstore()?;2380 <AccountItemCount<T>>::insert(owner.as_sub(), 1);2381 }23822383 collection.consume_sload()?;2384 let list_exists = <AddressTokens<T>>::contains_key(collection.id, owner.as_sub());2385 if list_exists {2386 collection.consume_sload()?;2387 let mut list = <AddressTokens<T>>::get(collection.id, owner.as_sub());2388 let item_contains = list.contains(&item_index.clone());23892390 if !item_contains {2391 list.push(item_index);2392 }23932394 collection.consume_sstore()?;2395 <AddressTokens<T>>::insert(collection.id, owner.as_sub(), list);2396 } else {2397 let itm = vec![item_index];2398 collection.consume_sstore()?;2399 <AddressTokens<T>>::insert(collection.id, owner.as_sub(), itm);2400 }24012402 Ok(())2403 }24042405 fn remove_token_index(2406 collection: &CollectionHandle<T>,2407 item_index: TokenId,2408 owner: &T::CrossAccountId,2409 ) -> DispatchResult {2410 2411 collection.consume_sload()?;2412 collection.consume_sstore()?;2413 <AccountItemCount<T>>::insert(2414 owner.as_sub(),2415 <AccountItemCount<T>>::get(owner.as_sub())2416 .checked_sub(1)2417 .ok_or(Error::<T>::NumOverflow)?,2418 );24192420 collection.consume_sload()?;2421 let list_exists = <AddressTokens<T>>::contains_key(collection.id, owner.as_sub());2422 if list_exists {2423 collection.consume_sload()?;2424 let mut list = <AddressTokens<T>>::get(collection.id, owner.as_sub());2425 let item_contains = list.contains(&item_index.clone());24262427 if item_contains {2428 list.retain(|&item| item != item_index);2429 collection.consume_sstore()?;2430 <AddressTokens<T>>::insert(collection.id, owner.as_sub(), list);2431 }2432 }24332434 Ok(())2435 }24362437 fn move_token_index(2438 collection: &CollectionHandle<T>,2439 item_index: TokenId,2440 old_owner: &T::CrossAccountId,2441 new_owner: &T::CrossAccountId,2442 ) -> DispatchResult {2443 Self::remove_token_index(collection, item_index, old_owner)?;2444 Self::add_token_index(collection, item_index, new_owner)?;24452446 Ok(())2447 }2448}24492450sp_api::decl_runtime_apis! {2451 pub trait NftApi {2452 2453 fn eth_contract_code(account: H160) -> Option<Vec<u8>>;2454 }2455}