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, ensure_root};35use sp_core::H160;36use sp_std::vec;37use sp_runtime::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 AccessMode, ChainLimits, Collection, CreateItemData, CollectionLimits, CollectionId,42 CollectionMode, TokenId, SchemaVersion, SponsorshipState, Ownership, NftItemType,43 FungibleItemType, ReFungibleItemType,44};4546#[cfg(test)]47mod mock;4849#[cfg(test)]50mod tests;5152mod default_weights;53mod eth;54mod sponsorship;55pub use sponsorship::NftSponsorshipHandler;56pub use eth::sponsoring::NftEthSponsorshipHandler;5758pub use eth::NftErcSupport;59pub use eth::account::*;60use eth::erc::{ERC20Events, ERC721Events};6162#[cfg(feature = "runtime-benchmarks")]63mod benchmarking;6465pub trait WeightInfo {66 fn create_collection() -> Weight;67 fn destroy_collection() -> Weight;68 fn add_to_white_list() -> Weight;69 fn remove_from_white_list() -> Weight;70 fn set_public_access_mode() -> Weight;71 fn set_mint_permission() -> Weight;72 fn change_collection_owner() -> Weight;73 fn add_collection_admin() -> Weight;74 fn remove_collection_admin() -> Weight;75 fn set_collection_sponsor() -> Weight;76 fn confirm_sponsorship() -> Weight;77 fn remove_collection_sponsor() -> Weight;78 fn create_item(s: usize) -> Weight;79 fn burn_item() -> Weight;80 fn transfer() -> Weight;81 fn approve() -> Weight;82 fn transfer_from() -> Weight;83 fn set_offchain_schema() -> Weight;84 fn set_const_on_chain_schema() -> Weight;85 fn set_variable_on_chain_schema() -> Weight;86 fn set_variable_meta_data() -> Weight;87 fn enable_contract_sponsoring() -> Weight;88 fn set_schema_version() -> Weight;89 fn set_chain_limits() -> Weight;90 fn set_contract_sponsoring_rate_limit() -> Weight;91 fn set_variable_meta_data_sponsoring_rate_limit() -> Weight;92 fn toggle_contract_white_list() -> Weight;93 fn add_to_contract_white_list() -> Weight;94 fn remove_from_contract_white_list() -> Weight;95 fn set_collection_limits() -> Weight;96}9798decl_error! {99 100 pub enum Error for Module<T: Config> {101 102 TotalCollectionsLimitExceeded,103 104 CollectionDecimalPointLimitExceeded,105 106 CollectionNameLimitExceeded,107 108 CollectionDescriptionLimitExceeded,109 110 CollectionTokenPrefixLimitExceeded,111 112 CollectionNotFound,113 114 TokenNotFound,115 116 AdminNotFound,117 118 NumOverflow,119 120 AlreadyAdmin,121 122 NoPermission,123 124 ConfirmUnsetSponsorFail,125 126 PublicMintingNotAllowed,127 128 MustBeTokenOwner,129 130 TokenValueTooLow,131 132 NftSizeLimitExceeded,133 134 ApproveNotFound,135 136 TokenValueNotEnough,137 138 ApproveRequired,139 140 AddresNotInWhiteList,141 142 CollectionAdminsLimitExceeded,143 144 AddressOwnershipLimitExceeded,145 146 EmptyArgument,147 148 TokenConstDataLimitExceeded,149 150 TokenVariableDataLimitExceeded,151 152 NotNftDataUsedToMintNftCollectionToken,153 154 NotFungibleDataUsedToMintFungibleCollectionToken,155 156 NotReFungibleDataUsedToMintReFungibleCollectionToken,157 158 UnexpectedCollectionType,159 160 CantStoreMetadataInFungibleTokens,161 162 CollectionTokenLimitExceeded,163 164 AccountTokenLimitExceeded,165 166 CollectionLimitBoundsExceeded,167 168 OwnerPermissionsCantBeReverted,169 170 SchemaDataLimitExceeded,171 172 WrongRefungiblePieces,173 174 BadCreateRefungibleCall,175 176 OutOfGas,177 178 TransferNotAllowed,179 }180}181182#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]183pub struct CollectionHandle<T: Config> {184 pub id: CollectionId,185 collection: Collection<T>,186 recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,187}188impl<T: Config> CollectionHandle<T> {189 pub fn get_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {190 <CollectionById<T>>::get(id).map(|collection| Self {191 id,192 collection,193 recorder: pallet_evm_coder_substrate::SubstrateRecorder::new(194 eth::collection_id_to_address(id),195 gas_limit,196 ),197 })198 }199 pub fn get(id: CollectionId) -> Option<Self> {200 Self::get_with_gas_limit(id, u64::MAX)201 }202 pub fn log(&self, log: impl evm_coder::ToLog) -> DispatchResult {203 self.recorder.log_sub(log)204 }205 fn consume_gas(&self, gas: u64) -> DispatchResult {206 self.recorder.consume_gas_sub(gas)207 }208 pub fn submit_logs(self) -> DispatchResult {209 self.recorder.submit_logs()210 }211 pub fn save(self) -> DispatchResult {212 self.recorder.submit_logs()?;213 <CollectionById<T>>::insert(self.id, self.collection);214 Ok(())215 }216}217impl<T: Config> Deref for CollectionHandle<T> {218 type Target = Collection<T>;219220 fn deref(&self) -> &Self::Target {221 &self.collection222 }223}224225impl<T: Config> DerefMut for CollectionHandle<T> {226 fn deref_mut(&mut self) -> &mut Self::Target {227 &mut self.collection228 }229}230231pub trait Config: system::Config + pallet_evm_coder_substrate::Config + Sized {232 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;233234 235 type WeightInfo: WeightInfo;236237 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;238 type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;239240 type CrossAccountId: CrossAccountId<Self::AccountId>;241 type Currency: Currency<Self::AccountId>;242 type CollectionCreationPrice: Get<243 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,244 >;245 type TreasuryAccountId: Get<Self::AccountId>;246}247248249250251252253254255256257258259260261262263264265266267268269270decl_storage! {271 trait Store for Module<T: Config> as Nft {272273 274 275 CreatedCollectionCount: u32;276 277 ChainVersion: u64;278 279 280 ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;281 282283 284 pub ChainLimit get(fn chain_limit) config(): ChainLimits;285 286287 288 289 290 DestroyedCollectionCount: u32;291 292 293 pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;294 295296 297 298 299 pub CollectionById get(fn collection_id) config(): map hasher(blake2_128_concat) CollectionId => Option<Collection<T>> = None;300 301 302 pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::CrossAccountId>;303 304 305 pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;306 307308 309 310 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => u128;311312 313 314 315 pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;316317 318 319 pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<NftItemType<T::CrossAccountId>>;320 321 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;322 323 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<ReFungibleItemType<T::CrossAccountId>>;324 325326 327 328 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => Vec<TokenId>;329 330331 332 333 334 pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;335 336 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;337 338 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;339 340 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;341 342343 344 345 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;346 }347 add_extra_genesis {348 build(|config: &GenesisConfig<T>| {349 350 for (_num, _c) in &config.collection_id {351 <Module<T>>::init_collection(_c);352 }353354 for (_num, _c, _i) in &config.nft_item_id {355 <Module<T>>::init_nft_token(*_c, _i);356 }357358 for (collection_id, account_id, fungible_item) in &config.fungible_item_id {359 <Module<T>>::init_fungible_token(*collection_id, &T::CrossAccountId::from_sub(account_id.clone()), fungible_item);360 }361362 for (_num, _c, _i) in &config.refungible_item_id {363 <Module<T>>::init_refungible_token(*_c, _i);364 }365 })366 }367}368369decl_event!(370 pub enum Event<T>371 where372 AccountId = <T as frame_system::Config>::AccountId,373 CrossAccountId = <T as Config>::CrossAccountId,374 {375 376 377 378 379 380 381 382 383 384 CollectionCreated(CollectionId, u8, AccountId),385386 387 388 389 390 391 392 393 394 395 ItemCreated(CollectionId, TokenId, CrossAccountId),396397 398 399 400 401 402 403 404 ItemDestroyed(CollectionId, TokenId),405406 407 408 409 410 411 412 413 414 415 416 417 Transfer(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),418419 420 421 422 423 424 425 426 427 428 Approved(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),429 }430);431432decl_module! {433 pub struct Module<T: Config> for enum Call434 where435 origin: T::Origin436 {437 fn deposit_event() = default;438 type Error = Error<T>;439440 fn on_initialize(_now: T::BlockNumber) -> Weight {441 0442 }443444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 #[weight = <T as Config>::WeightInfo::create_collection()]461 #[transactional]462 pub fn create_collection(origin,463 collection_name: Vec<u16>,464 collection_description: Vec<u16>,465 token_prefix: Vec<u8>,466 mode: CollectionMode) -> DispatchResult {467468 469 let who = ensure_signed(origin)?;470471 472 let mut imbalance = <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();473 imbalance.subsume(<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(474 &T::TreasuryAccountId::get(),475 T::CollectionCreationPrice::get(),476 ));477 <T as Config>::Currency::settle(478 &who,479 imbalance,480 WithdrawReasons::TRANSFER,481 ExistenceRequirement::KeepAlive,482 ).map_err(|_| Error::<T>::NoPermission)?;483484 let decimal_points = match mode {485 CollectionMode::Fungible(points) => points,486 _ => 0487 };488489 let chain_limit = ChainLimit::get();490491 let created_count = CreatedCollectionCount::get();492 let destroyed_count = DestroyedCollectionCount::get();493494 495 ensure!(created_count - destroyed_count < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);496497 498 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);499 ensure!(collection_name.len() <= 64, Error::<T>::CollectionNameLimitExceeded);500 ensure!(collection_description.len() <= 256, Error::<T>::CollectionDescriptionLimitExceeded);501 ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);502503 504 let next_id = created_count505 .checked_add(1)506 .ok_or(Error::<T>::NumOverflow)?;507508 CreatedCollectionCount::put(next_id);509510 let limits = CollectionLimits {511 sponsored_data_size: chain_limit.custom_data_limit,512 ..Default::default()513 };514515 516 let new_collection = Collection {517 owner: who.clone(),518 name: collection_name,519 mode: mode.clone(),520 mint_mode: false,521 access: AccessMode::Normal,522 description: collection_description,523 decimal_points,524 token_prefix,525 offchain_schema: Vec::new(),526 schema_version: SchemaVersion::ImageURL,527 sponsorship: SponsorshipState::Disabled,528 variable_on_chain_schema: Vec::new(),529 const_on_chain_schema: Vec::new(),530 limits,531 transfers_enabled: true,532 };533534 535 <CollectionById<T>>::insert(next_id, new_collection);536537 538 Self::deposit_event(RawEvent::CollectionCreated(next_id, mode.id(), who));539540 Ok(())541 }542543 544 545 546 547 548 549 550 551 552 #[weight = <T as Config>::WeightInfo::destroy_collection()]553 #[transactional]554 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {555556 let sender = ensure_signed(origin)?;557 let collection = Self::get_collection(collection_id)?;558 Self::check_owner_permissions(&collection, &sender)?;559 if !collection.limits.owner_can_destroy {560 fail!(Error::<T>::NoPermission);561 }562563 <AddressTokens<T>>::remove_prefix(collection_id, None);564 <Allowances<T>>::remove_prefix(collection_id, None);565 <Balance<T>>::remove_prefix(collection_id, None);566 <ItemListIndex>::remove(collection_id);567 <AdminList<T>>::remove(collection_id);568 <CollectionById<T>>::remove(collection_id);569 <WhiteList<T>>::remove_prefix(collection_id, None);570571 <NftItemList<T>>::remove_prefix(collection_id, None);572 <FungibleItemList<T>>::remove_prefix(collection_id, None);573 <ReFungibleItemList<T>>::remove_prefix(collection_id, None);574575 <NftTransferBasket<T>>::remove_prefix(collection_id, None);576 <FungibleTransferBasket<T>>::remove_prefix(collection_id, None);577 <ReFungibleTransferBasket<T>>::remove_prefix(collection_id, None);578579 <VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);580581 DestroyedCollectionCount::put(DestroyedCollectionCount::get()582 .checked_add(1)583 .ok_or(Error::<T>::NumOverflow)?);584585 Ok(())586 }587588 589 590 591 592 593 594 595 596 597 598 599 600 #[weight = <T as Config>::WeightInfo::add_to_white_list()]601 #[transactional]602 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{603604 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);605 let collection = Self::get_collection(collection_id)?;606607 Self::toggle_white_list_internal(608 &sender,609 &collection,610 &address,611 true,612 )?;613614 Ok(())615 }616617 618 619 620 621 622 623 624 625 626 627 628 629 #[weight = <T as Config>::WeightInfo::remove_from_white_list()]630 #[transactional]631 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{632633 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);634 let collection = Self::get_collection(collection_id)?;635636 Self::toggle_white_list_internal(637 &sender,638 &collection,639 &address,640 false,641 )?;642643 Ok(())644 }645646 647 648 649 650 651 652 653 654 655 656 657 #[weight = <T as Config>::WeightInfo::set_public_access_mode()]658 #[transactional]659 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult660 {661 let sender = ensure_signed(origin)?;662663 let mut target_collection = Self::get_collection(collection_id)?;664 Self::check_owner_permissions(&target_collection, &sender)?;665 target_collection.access = mode;666 target_collection.save()667 }668669 670 671 672 673 674 675 676 677 678 679 680 681 682 #[weight = <T as Config>::WeightInfo::set_mint_permission()]683 #[transactional]684 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult685 {686 let sender = ensure_signed(origin)?;687688 let mut target_collection = Self::get_collection(collection_id)?;689 Self::check_owner_permissions(&target_collection, &sender)?;690 target_collection.mint_mode = mint_permission;691 target_collection.save()692 }693694 695 696 697 698 699 700 701 702 703 704 705 #[weight = <T as Config>::WeightInfo::change_collection_owner()]706 #[transactional]707 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {708709 let sender = ensure_signed(origin)?;710 let mut target_collection = Self::get_collection(collection_id)?;711 Self::check_owner_permissions(&target_collection, &sender)?;712 target_collection.owner = new_owner;713 target_collection.save()714 }715716 717 718 719 720 721 722 723 724 725 726 727 728 729 #[weight = <T as Config>::WeightInfo::add_collection_admin()]730 #[transactional]731 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {732 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);733 let collection = Self::get_collection(collection_id)?;734 Self::check_owner_or_admin_permissions(&collection, &sender)?;735 let mut admin_arr = <AdminList<T>>::get(collection_id);736737 match admin_arr.binary_search(&new_admin_id) {738 Ok(_) => {},739 Err(idx) => {740 let limits = ChainLimit::get();741 ensure!(admin_arr.len() < limits.collections_admins_limit as usize, Error::<T>::CollectionAdminsLimitExceeded);742 admin_arr.insert(idx, new_admin_id);743 <AdminList<T>>::insert(collection_id, admin_arr);744 }745 }746 Ok(())747 }748749 750 751 752 753 754 755 756 757 758 759 760 761 #[weight = <T as Config>::WeightInfo::remove_collection_admin()]762 #[transactional]763 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {764 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);765 let collection = Self::get_collection(collection_id)?;766 Self::check_owner_or_admin_permissions(&collection, &sender)?;767 let mut admin_arr = <AdminList<T>>::get(collection_id);768769 if let Ok(idx) = admin_arr.binary_search(&account_id) {770 admin_arr.remove(idx);771 <AdminList<T>>::insert(collection_id, admin_arr);772 }773 Ok(())774 }775776 777 778 779 780 781 782 783 784 785 #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]786 #[transactional]787 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {788 let sender = ensure_signed(origin)?;789 let mut target_collection = Self::get_collection(collection_id)?;790 Self::check_owner_permissions(&target_collection, &sender)?;791792 target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);793 target_collection.save()794 }795796 797 798 799 800 801 802 803 #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]804 #[transactional]805 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {806 let sender = ensure_signed(origin)?;807808 let mut target_collection = Self::get_collection(collection_id)?;809 ensure!(810 target_collection.sponsorship.pending_sponsor() == Some(&sender),811 Error::<T>::ConfirmUnsetSponsorFail812 );813814 target_collection.sponsorship = SponsorshipState::Confirmed(sender);815 target_collection.save()816 }817818 819 820 821 822 823 824 825 826 827 #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]828 #[transactional]829 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {830 let sender = ensure_signed(origin)?;831832 let mut target_collection = Self::get_collection(collection_id)?;833 Self::check_owner_permissions(&target_collection, &sender)?;834835 target_collection.sponsorship = SponsorshipState::Disabled;836 target_collection.save()837 }838839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862863 #[weight = <T as Config>::WeightInfo::create_item(data.data_size())]864 #[transactional]865 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResult {866 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);867 let collection = Self::get_collection(collection_id)?;868869 Self::create_item_internal(&sender, &collection, &owner, data)?;870871 collection.submit_logs()872 }873874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 #[weight = <T as Config>::WeightInfo::create_item(items_data.iter()893 .map(|data| { data.data_size() })894 .sum())]895 #[transactional]896 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResult {897898 ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);899 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);900 let collection = Self::get_collection(collection_id)?;901902 Self::create_multiple_items_internal(&sender, &collection, &owner, items_data)?;903904 collection.submit_logs()905 }906907 908909 910 911 912 913 914 915 916 917 918 919 920 #[weight = <T as Config>::WeightInfo::burn_item()]921 #[transactional]922 pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {923924 let sender = ensure_signed(origin)?;925 let mut target_collection = Self::get_collection(collection_id)?;926927 Self::check_owner_permissions(&target_collection, &sender)?;928929 target_collection.transfers_enabled = value;930 target_collection.save()931 }932933 934 935 936 937 938 939 940 941 942 943 944 945 946 #[weight = <T as Config>::WeightInfo::burn_item()]947 #[transactional]948 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {949950 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);951 let target_collection = Self::get_collection(collection_id)?;952953 Self::burn_item_internal(&sender, &target_collection, item_id, value)?;954955 target_collection.submit_logs()956 }957958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 #[weight = <T as Config>::WeightInfo::transfer()]982 #[transactional]983 pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {984 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);985 let collection = Self::get_collection(collection_id)?;986987 Self::transfer_internal(&sender, &recipient, &collection, item_id, value)?;988989 collection.submit_logs()990 }991992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 #[weight = <T as Config>::WeightInfo::approve()]1008 #[transactional]1009 pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {1010 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1011 let collection = Self::get_collection(collection_id)?;10121013 Self::approve_internal(&sender, &spender, &collection, item_id, amount)?;10141015 collection.submit_logs()1016 }10171018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 #[weight = <T as Config>::WeightInfo::transfer_from()]1038 #[transactional]1039 pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {1040 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1041 let collection = Self::get_collection(collection_id)?;10421043 Self::transfer_from_internal(&sender, &from, &recipient, &collection, item_id, value)?;10441045 collection.submit_logs()1046 }1047 1048 1049 1050 1051 10521053 10541055 10561057 1058 10591060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1073 #[transactional]1074 pub fn set_variable_meta_data (1075 origin,1076 collection_id: CollectionId,1077 item_id: TokenId,1078 data: Vec<u8>1079 ) -> DispatchResult {1080 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);10811082 let collection = Self::get_collection(collection_id)?;10831084 Self::set_variable_meta_data_internal(&sender, &collection, item_id, data)?;10851086 Ok(())1087 }10881089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 #[weight = <T as Config>::WeightInfo::set_schema_version()]1104 #[transactional]1105 pub fn set_schema_version(1106 origin,1107 collection_id: CollectionId,1108 version: SchemaVersion1109 ) -> DispatchResult {1110 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1111 let mut target_collection = Self::get_collection(collection_id)?;1112 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;1113 target_collection.schema_version = version;1114 target_collection.save()1115 }11161117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1130 #[transactional]1131 pub fn set_offchain_schema(1132 origin,1133 collection_id: CollectionId,1134 schema: Vec<u8>1135 ) -> DispatchResult {1136 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1137 let mut target_collection = Self::get_collection(collection_id)?;1138 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;11391140 1141 ensure!(schema.len() as u32 <= ChainLimit::get().offchain_schema_limit, "");11421143 target_collection.offchain_schema = schema;1144 target_collection.save()1145 }11461147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1160 #[transactional]1161 pub fn set_const_on_chain_schema (1162 origin,1163 collection_id: CollectionId,1164 schema: Vec<u8>1165 ) -> DispatchResult {1166 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1167 let mut target_collection = Self::get_collection(collection_id)?;1168 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;11691170 1171 ensure!(schema.len() as u32 <= ChainLimit::get().const_on_chain_schema_limit, "");11721173 target_collection.const_on_chain_schema = schema;1174 target_collection.save()1175 }11761177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1190 #[transactional]1191 pub fn set_variable_on_chain_schema (1192 origin,1193 collection_id: CollectionId,1194 schema: Vec<u8>1195 ) -> DispatchResult {1196 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1197 let mut target_collection = Self::get_collection(collection_id)?;1198 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;11991200 1201 ensure!(schema.len() as u32 <= ChainLimit::get().variable_on_chain_schema_limit, "");12021203 target_collection.variable_on_chain_schema = schema;1204 target_collection.save()1205 }12061207 1208 #[weight = <T as Config>::WeightInfo::set_chain_limits()]1209 #[transactional]1210 pub fn set_chain_limits(1211 origin,1212 limits: ChainLimits1213 ) -> DispatchResult {12141215 #[cfg(not(feature = "runtime-benchmarks"))]1216 ensure_root(origin)?;12171218 <ChainLimit>::put(limits);1219 Ok(())1220 }12211222 #[weight = <T as Config>::WeightInfo::set_collection_limits()]1223 #[transactional]1224 pub fn set_collection_limits(1225 origin,1226 collection_id: u32,1227 new_limits: CollectionLimits<T::BlockNumber>,1228 ) -> DispatchResult {1229 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1230 let mut target_collection = Self::get_collection(collection_id)?;1231 Self::check_owner_permissions(&target_collection, sender.as_sub())?;1232 let old_limits = &target_collection.limits;1233 let chain_limits = ChainLimit::get();12341235 1236 ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&1237 new_limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP &&1238 new_limits.sponsored_data_size <= chain_limits.custom_data_limit,1239 Error::<T>::CollectionLimitBoundsExceeded);12401241 1242 ensure!(old_limits.token_limit >= new_limits.token_limit, Error::<T>::CollectionTokenLimitExceeded);1243 ensure!(new_limits.token_limit > 0, Error::<T>::CollectionTokenLimitExceeded);12441245 ensure!(1246 (old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&1247 (old_limits.owner_can_destroy || !new_limits.owner_can_destroy),1248 Error::<T>::OwnerPermissionsCantBeReverted,1249 );12501251 target_collection.limits = new_limits;12521253 target_collection.save()1254 }1255 }1256}12571258impl<T: Config> Module<T> {1259 pub fn create_item_internal(1260 sender: &T::CrossAccountId,1261 collection: &CollectionHandle<T>,1262 owner: &T::CrossAccountId,1263 data: CreateItemData,1264 ) -> DispatchResult {1265 Self::can_create_items_in_collection(collection, sender, owner, 1)?;1266 Self::validate_create_item_args(collection, &data)?;1267 Self::create_item_no_validation(collection, owner, data)?;12681269 Ok(())1270 }12711272 pub fn transfer_internal(1273 sender: &T::CrossAccountId,1274 recipient: &T::CrossAccountId,1275 target_collection: &CollectionHandle<T>,1276 item_id: TokenId,1277 value: u128,1278 ) -> DispatchResult {1279 target_collection.consume_gas(2000000)?;1280 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 collection.consume_gas(2000000)?;1334 Self::token_exists(collection, item_id)?;13351336 1337 let bypasses_limits = collection.limits.owner_can_transfer1338 && Self::is_owner_or_admin_permissions(collection, sender);13391340 let allowance_limit = if bypasses_limits {1341 None1342 } else if let Some(amount) = Self::owned_amount(sender, collection, item_id) {1343 Some(amount)1344 } else {1345 fail!(Error::<T>::NoPermission);1346 };13471348 if collection.access == AccessMode::WhiteList {1349 Self::check_white_list(collection, sender)?;1350 Self::check_white_list(collection, spender)?;1351 }13521353 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 <Allowances<T>>::insert(1363 collection.id,1364 (item_id, sender.as_sub(), spender.as_sub()),1365 allowance,1366 );13671368 if matches!(collection.mode, CollectionMode::NFT) {1369 1370 collection.log(ERC721Events::Approval {1371 owner: *sender.as_eth(),1372 approved: *spender.as_eth(),1373 token_id: item_id.into(),1374 })?;1375 }13761377 if matches!(collection.mode, CollectionMode::Fungible(_)) {1378 1379 collection.log(ERC20Events::Approval {1380 owner: *sender.as_eth(),1381 spender: *spender.as_eth(),1382 value: allowance.into(),1383 })?;1384 }13851386 Self::deposit_event(RawEvent::Approved(1387 collection.id,1388 item_id,1389 sender.clone(),1390 spender.clone(),1391 allowance,1392 ));1393 Ok(())1394 }13951396 pub fn transfer_from_internal(1397 sender: &T::CrossAccountId,1398 from: &T::CrossAccountId,1399 recipient: &T::CrossAccountId,1400 collection: &CollectionHandle<T>,1401 item_id: TokenId,1402 amount: u128,1403 ) -> DispatchResult {1404 if sender == from {1405 1406 return Self::transfer_internal(from, recipient, collection, item_id, amount);1407 }14081409 collection.consume_gas(2000000)?;1410 1411 let approval: u128 =1412 <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));14131414 1415 Self::is_correct_transfer(collection, recipient)?;14161417 1418 ensure!(1419 approval >= amount1420 || (collection.limits.owner_can_transfer1421 && Self::is_owner_or_admin_permissions(collection, sender)),1422 Error::<T>::NoPermission1423 );14241425 if collection.access == AccessMode::WhiteList {1426 Self::check_white_list(collection, sender)?;1427 Self::check_white_list(collection, recipient)?;1428 }14291430 1431 let allowance = approval.saturating_sub(amount);1432 if allowance > 0 {1433 <Allowances<T>>::insert(1434 collection.id,1435 (item_id, from.as_sub(), sender.as_sub()),1436 allowance,1437 );1438 } else {1439 <Allowances<T>>::remove(collection.id, (item_id, from.as_sub(), sender.as_sub()));1440 }14411442 match collection.mode {1443 CollectionMode::NFT => {1444 Self::transfer_nft(collection, item_id, from.clone(), recipient.clone())?1445 }1446 CollectionMode::Fungible(_) => {1447 Self::transfer_fungible(collection, amount, from, recipient)?1448 }1449 CollectionMode::ReFungible => Self::transfer_refungible(1450 collection,1451 item_id,1452 amount,1453 from.clone(),1454 recipient.clone(),1455 )?,1456 _ => (),1457 };14581459 if matches!(collection.mode, CollectionMode::Fungible(_)) {1460 collection.log(ERC20Events::Approval {1461 owner: *from.as_eth(),1462 spender: *sender.as_eth(),1463 value: allowance.into(),1464 })?;1465 }14661467 Ok(())1468 }14691470 pub fn set_variable_meta_data_internal(1471 sender: &T::CrossAccountId,1472 collection: &CollectionHandle<T>,1473 item_id: TokenId,1474 data: Vec<u8>,1475 ) -> DispatchResult {1476 Self::token_exists(collection, item_id)?;14771478 ensure!(1479 ChainLimit::get().custom_data_limit >= data.len() as u32,1480 Error::<T>::TokenVariableDataLimitExceeded1481 );14821483 1484 ensure!(1485 Self::is_item_owner(sender, collection, item_id)1486 || Self::is_owner_or_admin_permissions(collection, sender),1487 Error::<T>::NoPermission1488 );14891490 match collection.mode {1491 CollectionMode::NFT => Self::set_nft_variable_data(collection, item_id, data)?,1492 CollectionMode::ReFungible => {1493 Self::set_re_fungible_variable_data(collection, item_id, data)?1494 }1495 CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),1496 _ => fail!(Error::<T>::UnexpectedCollectionType),1497 };14981499 Ok(())1500 }15011502 pub fn create_multiple_items_internal(1503 sender: &T::CrossAccountId,1504 collection: &CollectionHandle<T>,1505 owner: &T::CrossAccountId,1506 items_data: Vec<CreateItemData>,1507 ) -> DispatchResult {1508 Self::can_create_items_in_collection(collection, sender, owner, items_data.len() as u32)?;15091510 for data in &items_data {1511 Self::validate_create_item_args(collection, data)?;1512 }1513 for data in &items_data {1514 Self::create_item_no_validation(collection, owner, data.clone())?;1515 }15161517 Ok(())1518 }15191520 pub fn burn_item_internal(1521 sender: &T::CrossAccountId,1522 collection: &CollectionHandle<T>,1523 item_id: TokenId,1524 value: u128,1525 ) -> DispatchResult {1526 ensure!(1527 Self::is_item_owner(sender, collection, item_id)1528 || (collection.limits.owner_can_transfer1529 && Self::is_owner_or_admin_permissions(collection, sender)),1530 Error::<T>::NoPermission1531 );15321533 if collection.access == AccessMode::WhiteList {1534 Self::check_white_list(collection, sender)?;1535 }15361537 match collection.mode {1538 CollectionMode::NFT => Self::burn_nft_item(collection, item_id)?,1539 CollectionMode::Fungible(_) => Self::burn_fungible_item(sender, collection, value)?,1540 CollectionMode::ReFungible => Self::burn_refungible_item(collection, item_id, sender)?,1541 _ => (),1542 };15431544 Ok(())1545 }15461547 pub fn toggle_white_list_internal(1548 sender: &T::CrossAccountId,1549 collection: &CollectionHandle<T>,1550 address: &T::CrossAccountId,1551 whitelisted: bool,1552 ) -> DispatchResult {1553 Self::check_owner_or_admin_permissions(collection, sender)?;15541555 if whitelisted {1556 <WhiteList<T>>::insert(collection.id, address.as_sub(), true);1557 } else {1558 <WhiteList<T>>::remove(collection.id, address.as_sub());1559 }15601561 Ok(())1562 }15631564 fn is_correct_transfer(1565 collection: &CollectionHandle<T>,1566 recipient: &T::CrossAccountId,1567 ) -> DispatchResult {1568 let collection_id = collection.id;15691570 1571 let account_items: u32 =1572 <AddressTokens<T>>::get(collection_id, recipient.as_sub()).len() as u32;1573 ensure!(1574 collection.limits.account_token_ownership_limit > account_items,1575 Error::<T>::AccountTokenLimitExceeded1576 );15771578 1579 ensure!(collection.transfers_enabled, Error::<T>::TransferNotAllowed);15801581 Ok(())1582 }15831584 fn can_create_items_in_collection(1585 collection: &CollectionHandle<T>,1586 sender: &T::CrossAccountId,1587 owner: &T::CrossAccountId,1588 amount: u32,1589 ) -> DispatchResult {1590 let collection_id = collection.id;15911592 1593 let total_items: u32 = ItemListIndex::get(collection_id)1594 .checked_add(amount)1595 .ok_or(Error::<T>::CollectionTokenLimitExceeded)?;1596 let account_items: u32 = (<AddressTokens<T>>::get(collection_id, owner.as_sub()).len()1597 as u32)1598 .checked_add(amount)1599 .ok_or(Error::<T>::AccountTokenLimitExceeded)?;1600 ensure!(1601 collection.limits.token_limit >= total_items,1602 Error::<T>::CollectionTokenLimitExceeded1603 );1604 ensure!(1605 collection.limits.account_token_ownership_limit >= account_items,1606 Error::<T>::AccountTokenLimitExceeded1607 );16081609 if !Self::is_owner_or_admin_permissions(collection, sender) {1610 ensure!(collection.mint_mode, Error::<T>::PublicMintingNotAllowed);1611 Self::check_white_list(collection, owner)?;1612 Self::check_white_list(collection, sender)?;1613 }16141615 Ok(())1616 }16171618 fn validate_create_item_args(1619 target_collection: &CollectionHandle<T>,1620 data: &CreateItemData,1621 ) -> DispatchResult {1622 match target_collection.mode {1623 CollectionMode::NFT => {1624 if let CreateItemData::NFT(data) = data {1625 1626 ensure!(1627 ChainLimit::get().custom_data_limit >= data.const_data.len() as u32,1628 Error::<T>::TokenConstDataLimitExceeded1629 );1630 ensure!(1631 ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32,1632 Error::<T>::TokenVariableDataLimitExceeded1633 );1634 } else {1635 fail!(Error::<T>::NotNftDataUsedToMintNftCollectionToken);1636 }1637 }1638 CollectionMode::Fungible(_) => {1639 if let CreateItemData::Fungible(_) = data {1640 } else {1641 fail!(Error::<T>::NotFungibleDataUsedToMintFungibleCollectionToken);1642 }1643 }1644 CollectionMode::ReFungible => {1645 if let CreateItemData::ReFungible(data) = data {1646 1647 ensure!(1648 ChainLimit::get().custom_data_limit >= data.const_data.len() as u32,1649 Error::<T>::TokenConstDataLimitExceeded1650 );1651 ensure!(1652 ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32,1653 Error::<T>::TokenVariableDataLimitExceeded1654 );16551656 1657 ensure!(1658 data.pieces <= MAX_REFUNGIBLE_PIECES,1659 Error::<T>::WrongRefungiblePieces1660 );1661 ensure!(data.pieces > 0, Error::<T>::WrongRefungiblePieces);1662 } else {1663 fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);1664 }1665 }1666 _ => {1667 fail!(Error::<T>::UnexpectedCollectionType);1668 }1669 };16701671 Ok(())1672 }16731674 fn create_item_no_validation(1675 collection: &CollectionHandle<T>,1676 owner: &T::CrossAccountId,1677 data: CreateItemData,1678 ) -> DispatchResult {1679 match data {1680 CreateItemData::NFT(data) => {1681 let item = NftItemType {1682 owner: owner.clone(),1683 const_data: data.const_data,1684 variable_data: data.variable_data,1685 };16861687 Self::add_nft_item(collection, item)?;1688 }1689 CreateItemData::Fungible(data) => {1690 Self::add_fungible_item(collection, owner, data.value)?;1691 }1692 CreateItemData::ReFungible(data) => {1693 let owner_list = vec![Ownership {1694 owner: owner.clone(),1695 fraction: data.pieces,1696 }];16971698 let item = ReFungibleItemType {1699 owner: owner_list,1700 const_data: data.const_data,1701 variable_data: data.variable_data,1702 };17031704 Self::add_refungible_item(collection, item)?;1705 }1706 };17071708 Ok(())1709 }17101711 fn add_fungible_item(1712 collection: &CollectionHandle<T>,1713 owner: &T::CrossAccountId,1714 value: u128,1715 ) -> DispatchResult {1716 let collection_id = collection.id;17171718 1719 let balance: u128 = <FungibleItemList<T>>::get(collection_id, owner.as_sub()).value;17201721 1722 let item = FungibleItemType {1723 value: balance.checked_add(value).ok_or(Error::<T>::NumOverflow)?,1724 };1725 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), item);17261727 1728 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1729 .checked_add(value)1730 .ok_or(Error::<T>::NumOverflow)?;1731 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);17321733 Self::deposit_event(RawEvent::ItemCreated(collection_id, 0, owner.clone()));1734 Ok(())1735 }17361737 fn add_refungible_item(1738 collection: &CollectionHandle<T>,1739 item: ReFungibleItemType<T::CrossAccountId>,1740 ) -> DispatchResult {1741 let collection_id = collection.id;17421743 let current_index = <ItemListIndex>::get(collection_id)1744 .checked_add(1)1745 .ok_or(Error::<T>::NumOverflow)?;1746 let itemcopy = item.clone();17471748 ensure!(item.owner.len() == 1, Error::<T>::BadCreateRefungibleCall,);1749 let item_owner = item.owner.first().expect("only one owner is defined");17501751 let value = item_owner.fraction;1752 let owner = item_owner.owner.clone();17531754 Self::add_token_index(collection_id, current_index, &owner)?;17551756 <ItemListIndex>::insert(collection_id, current_index);1757 <ReFungibleItemList<T>>::insert(collection_id, current_index, itemcopy);17581759 1760 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1761 .checked_add(value)1762 .ok_or(Error::<T>::NumOverflow)?;1763 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);17641765 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, owner));1766 Ok(())1767 }17681769 fn add_nft_item(1770 collection: &CollectionHandle<T>,1771 item: NftItemType<T::CrossAccountId>,1772 ) -> DispatchResult {1773 let collection_id = collection.id;17741775 let current_index = <ItemListIndex>::get(collection_id)1776 .checked_add(1)1777 .ok_or(Error::<T>::NumOverflow)?;17781779 let item_owner = item.owner.clone();1780 Self::add_token_index(collection_id, current_index, &item.owner)?;17811782 <ItemListIndex>::insert(collection_id, current_index);1783 <NftItemList<T>>::insert(collection_id, current_index, item);17841785 1786 let new_balance = <Balance<T>>::get(collection_id, item_owner.as_sub())1787 .checked_add(1)1788 .ok_or(Error::<T>::NumOverflow)?;1789 <Balance<T>>::insert(collection_id, item_owner.as_sub(), new_balance);17901791 collection.log(ERC721Events::Transfer {1792 from: H160::default(),1793 to: *item_owner.as_eth(),1794 token_id: current_index.into(),1795 })?;1796 Self::deposit_event(RawEvent::ItemCreated(1797 collection_id,1798 current_index,1799 item_owner,1800 ));1801 Ok(())1802 }18031804 fn burn_refungible_item(1805 collection: &CollectionHandle<T>,1806 item_id: TokenId,1807 owner: &T::CrossAccountId,1808 ) -> DispatchResult {1809 let collection_id = collection.id;18101811 let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id)1812 .ok_or(Error::<T>::TokenNotFound)?;1813 let rft_balance = token1814 .owner1815 .iter()1816 .find(|&i| i.owner == *owner)1817 .ok_or(Error::<T>::TokenNotFound)?;1818 Self::remove_token_index(collection_id, item_id, owner)?;18191820 1821 let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.as_sub())1822 .checked_sub(rft_balance.fraction)1823 .ok_or(Error::<T>::NumOverflow)?;1824 <Balance<T>>::insert(collection_id, rft_balance.owner.as_sub(), new_balance);18251826 1827 let index = token1828 .owner1829 .iter()1830 .position(|i| i.owner == *owner)1831 .expect("owned item is exists");1832 token.owner.remove(index);1833 let owner_count = token.owner.len();18341835 1836 if owner_count == 0 {1837 <ReFungibleItemList<T>>::remove(collection_id, item_id);1838 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);1839 } else {1840 <ReFungibleItemList<T>>::insert(collection_id, item_id, token);1841 }18421843 Ok(())1844 }18451846 fn burn_nft_item(collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {1847 let collection_id = collection.id;18481849 let item =1850 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;1851 Self::remove_token_index(collection_id, item_id, &item.owner)?;18521853 1854 let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())1855 .checked_sub(1)1856 .ok_or(Error::<T>::NumOverflow)?;1857 <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);1858 <NftItemList<T>>::remove(collection_id, item_id);1859 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);18601861 Self::deposit_event(RawEvent::ItemDestroyed(collection.id, item_id));1862 Ok(())1863 }18641865 fn burn_fungible_item(1866 owner: &T::CrossAccountId,1867 collection: &CollectionHandle<T>,1868 value: u128,1869 ) -> DispatchResult {1870 let collection_id = collection.id;18711872 let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());1873 ensure!(balance.value >= value, Error::<T>::TokenValueNotEnough);18741875 1876 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1877 .checked_sub(value)1878 .ok_or(Error::<T>::NumOverflow)?;1879 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);18801881 if balance.value - value > 0 {1882 balance.value -= value;1883 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);1884 } else {1885 <FungibleItemList<T>>::remove(collection_id, owner.as_sub());1886 }18871888 collection.log(ERC20Events::Transfer {1889 from: *owner.as_eth(),1890 to: H160::default(),1891 value: value.into(),1892 })?;1893 Ok(())1894 }18951896 pub fn get_collection(1897 collection_id: CollectionId,1898 ) -> Result<CollectionHandle<T>, sp_runtime::DispatchError> {1899 Ok(<CollectionHandle<T>>::get(collection_id).ok_or(Error::<T>::CollectionNotFound)?)1900 }19011902 fn check_owner_permissions(1903 target_collection: &CollectionHandle<T>,1904 subject: &T::AccountId,1905 ) -> DispatchResult {1906 ensure!(1907 *subject == target_collection.owner,1908 Error::<T>::NoPermission1909 );19101911 Ok(())1912 }19131914 fn is_owner_or_admin_permissions(1915 collection: &CollectionHandle<T>,1916 subject: &T::CrossAccountId,1917 ) -> bool {1918 *subject.as_sub() == collection.owner1919 || <AdminList<T>>::get(collection.id).contains(subject)1920 }19211922 fn check_owner_or_admin_permissions(1923 collection: &CollectionHandle<T>,1924 subject: &T::CrossAccountId,1925 ) -> DispatchResult {1926 ensure!(1927 Self::is_owner_or_admin_permissions(collection, subject),1928 Error::<T>::NoPermission1929 );19301931 Ok(())1932 }19331934 fn owned_amount(1935 subject: &T::CrossAccountId,1936 target_collection: &CollectionHandle<T>,1937 item_id: TokenId,1938 ) -> Option<u128> {1939 let collection_id = target_collection.id;19401941 match target_collection.mode {1942 CollectionMode::NFT => {1943 (<NftItemList<T>>::get(collection_id, item_id)?.owner == *subject).then(|| 1)1944 }1945 CollectionMode::Fungible(_) => {1946 Some(<FungibleItemList<T>>::get(collection_id, &subject.as_sub()).value)1947 }1948 CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)?1949 .owner1950 .iter()1951 .find(|i| i.owner == *subject)1952 .map(|i| i.fraction),1953 CollectionMode::Invalid => None,1954 }1955 }19561957 fn is_item_owner(1958 subject: &T::CrossAccountId,1959 target_collection: &CollectionHandle<T>,1960 item_id: TokenId,1961 ) -> bool {1962 match target_collection.mode {1963 CollectionMode::Fungible(_) => true,1964 _ => Self::owned_amount(subject, target_collection, item_id).is_some(),1965 }1966 }19671968 fn check_white_list(1969 collection: &CollectionHandle<T>,1970 address: &T::CrossAccountId,1971 ) -> DispatchResult {1972 let collection_id = collection.id;19731974 let mes = Error::<T>::AddresNotInWhiteList;1975 ensure!(1976 <WhiteList<T>>::contains_key(collection_id, address.as_sub()),1977 mes1978 );19791980 Ok(())1981 }19821983 1984 1985 fn token_exists(target_collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {1986 let collection_id = target_collection.id;1987 let exists = match target_collection.mode {1988 CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),1989 CollectionMode::Fungible(_) => true,1990 CollectionMode::ReFungible => {1991 <ReFungibleItemList<T>>::contains_key(collection_id, item_id)1992 }1993 _ => false,1994 };19951996 ensure!(exists, Error::<T>::TokenNotFound);1997 Ok(())1998 }19992000 fn transfer_fungible(2001 collection: &CollectionHandle<T>,2002 value: u128,2003 owner: &T::CrossAccountId,2004 recipient: &T::CrossAccountId,2005 ) -> DispatchResult {2006 let collection_id = collection.id;20072008 let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());2009 ensure!(balance.value >= value, Error::<T>::TokenValueTooLow);20102011 2012 Self::add_fungible_item(collection, recipient, value)?;20132014 2015 <Balance<T>>::insert(collection_id, owner.as_sub(), balance.value - value);20162017 2018 if balance.value == value {2019 <FungibleItemList<T>>::remove(collection_id, owner.as_sub());2020 } else {2021 balance.value -= value;2022 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);2023 }20242025 collection.log(ERC20Events::Transfer {2026 from: *owner.as_eth(),2027 to: *recipient.as_eth(),2028 value: value.into(),2029 })?;2030 Self::deposit_event(RawEvent::Transfer(2031 collection.id,2032 1,2033 owner.clone(),2034 recipient.clone(),2035 value,2036 ));20372038 Ok(())2039 }20402041 fn transfer_refungible(2042 collection: &CollectionHandle<T>,2043 item_id: TokenId,2044 value: u128,2045 owner: T::CrossAccountId,2046 new_owner: T::CrossAccountId,2047 ) -> DispatchResult {2048 let collection_id = collection.id;2049 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id)2050 .ok_or(Error::<T>::TokenNotFound)?;20512052 let item = full_item2053 .owner2054 .iter()2055 .find(|i| i.owner == owner)2056 .ok_or(Error::<T>::TokenNotFound)?;2057 let amount = item.fraction;20582059 ensure!(amount >= value, Error::<T>::TokenValueTooLow);20602061 2062 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())2063 .checked_sub(value)2064 .ok_or(Error::<T>::NumOverflow)?;2065 <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);20662067 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())2068 .checked_add(value)2069 .ok_or(Error::<T>::NumOverflow)?;2070 <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);20712072 let old_owner = item.owner.clone();2073 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);20742075 let mut new_full_item = full_item.clone();2076 2077 if amount == value && !new_owner_has_account {2078 2079 2080 new_full_item2081 .owner2082 .iter_mut()2083 .find(|i| i.owner == owner)2084 .expect("old owner does present in refungible")2085 .owner = new_owner.clone();2086 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);20872088 2089 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;2090 } else {2091 new_full_item2092 .owner2093 .iter_mut()2094 .find(|i| i.owner == owner)2095 .expect("old owner does present in refungible")2096 .fraction -= value;20972098 2099 if new_owner_has_account {2100 2101 new_full_item2102 .owner2103 .iter_mut()2104 .find(|i| i.owner == new_owner)2105 .expect("new owner has account")2106 .fraction += value;2107 } else {2108 2109 new_full_item.owner.push(Ownership {2110 owner: new_owner.clone(),2111 fraction: value,2112 });2113 Self::add_token_index(collection_id, item_id, &new_owner)?;2114 }21152116 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);2117 }21182119 Self::deposit_event(RawEvent::Transfer(2120 collection.id,2121 item_id,2122 owner,2123 new_owner,2124 amount,2125 ));21262127 Ok(())2128 }21292130 fn transfer_nft(2131 collection: &CollectionHandle<T>,2132 item_id: TokenId,2133 sender: T::CrossAccountId,2134 new_owner: T::CrossAccountId,2135 ) -> DispatchResult {2136 let collection_id = collection.id;2137 let mut item =2138 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;21392140 ensure!(sender == item.owner, Error::<T>::MustBeTokenOwner);21412142 2143 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())2144 .checked_sub(1)2145 .ok_or(Error::<T>::NumOverflow)?;2146 <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);21472148 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())2149 .checked_add(1)2150 .ok_or(Error::<T>::NumOverflow)?;2151 <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);21522153 2154 let old_owner = item.owner.clone();2155 item.owner = new_owner.clone();2156 <NftItemList<T>>::insert(collection_id, item_id, item);21572158 2159 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;21602161 collection.log(ERC721Events::Transfer {2162 from: *sender.as_eth(),2163 to: *new_owner.as_eth(),2164 token_id: item_id.into(),2165 })?;2166 Self::deposit_event(RawEvent::Transfer(2167 collection.id,2168 item_id,2169 sender,2170 new_owner,2171 1,2172 ));21732174 Ok(())2175 }21762177 fn set_re_fungible_variable_data(2178 collection: &CollectionHandle<T>,2179 item_id: TokenId,2180 data: Vec<u8>,2181 ) -> DispatchResult {2182 let collection_id = collection.id;2183 let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id)2184 .ok_or(Error::<T>::TokenNotFound)?;21852186 item.variable_data = data;21872188 <ReFungibleItemList<T>>::insert(collection_id, item_id, item);21892190 Ok(())2191 }21922193 fn set_nft_variable_data(2194 collection: &CollectionHandle<T>,2195 item_id: TokenId,2196 data: Vec<u8>,2197 ) -> DispatchResult {2198 let collection_id = collection.id;2199 let mut item =2200 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;22012202 item.variable_data = data;22032204 <NftItemList<T>>::insert(collection_id, item_id, item);22052206 Ok(())2207 }22082209 #[allow(dead_code)]2210 fn init_collection(item: &Collection<T>) {2211 2212 assert!(2213 item.decimal_points <= MAX_DECIMAL_POINTS,2214 "decimal_points parameter must be lower than MAX_DECIMAL_POINTS"2215 );2216 assert!(2217 item.name.len() <= 64,2218 "Collection name can not be longer than 63 char"2219 );2220 assert!(2221 item.name.len() <= 256,2222 "Collection description can not be longer than 255 char"2223 );2224 assert!(2225 item.token_prefix.len() <= 16,2226 "Token prefix can not be longer than 15 char"2227 );22282229 2230 let next_id = CreatedCollectionCount::get().checked_add(1).unwrap();22312232 CreatedCollectionCount::put(next_id);2233 }22342235 #[allow(dead_code)]2236 fn init_nft_token(collection_id: CollectionId, item: &NftItemType<T::CrossAccountId>) {2237 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();22382239 Self::add_token_index(collection_id, current_index, &item.owner).unwrap();22402241 <ItemListIndex>::insert(collection_id, current_index);22422243 2244 let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())2245 .checked_add(1)2246 .unwrap();2247 <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);2248 }22492250 #[allow(dead_code)]2251 fn init_fungible_token(2252 collection_id: CollectionId,2253 owner: &T::CrossAccountId,2254 item: &FungibleItemType,2255 ) {2256 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();22572258 Self::add_token_index(collection_id, current_index, owner).unwrap();22592260 <ItemListIndex>::insert(collection_id, current_index);22612262 2263 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())2264 .checked_add(item.value)2265 .unwrap();2266 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);2267 }22682269 #[allow(dead_code)]2270 fn init_refungible_token(2271 collection_id: CollectionId,2272 item: &ReFungibleItemType<T::CrossAccountId>,2273 ) {2274 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();22752276 let value = item.owner.first().unwrap().fraction;2277 let owner = item.owner.first().unwrap().owner.clone();22782279 Self::add_token_index(collection_id, current_index, &owner).unwrap();22802281 <ItemListIndex>::insert(collection_id, current_index);22822283 2284 let new_balance = <Balance<T>>::get(collection_id, &owner.as_sub())2285 .checked_add(value)2286 .unwrap();2287 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);2288 }22892290 fn add_token_index(2291 collection_id: CollectionId,2292 item_index: TokenId,2293 owner: &T::CrossAccountId,2294 ) -> DispatchResult {2295 2296 if <AccountItemCount<T>>::contains_key(owner.as_sub()) {2297 2298 let count = <AccountItemCount<T>>::get(owner.as_sub());2299 ensure!(2300 count < ChainLimit::get().account_token_ownership_limit,2301 Error::<T>::AddressOwnershipLimitExceeded2302 );23032304 <AccountItemCount<T>>::insert(2305 owner.as_sub(),2306 count.checked_add(1).ok_or(Error::<T>::NumOverflow)?,2307 );2308 } else {2309 <AccountItemCount<T>>::insert(owner.as_sub(), 1);2310 }23112312 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.as_sub());2313 if list_exists {2314 let mut list = <AddressTokens<T>>::get(collection_id, owner.as_sub());2315 let item_contains = list.contains(&item_index.clone());23162317 if !item_contains {2318 list.push(item_index);2319 }23202321 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), list);2322 } else {2323 let itm = vec![item_index];2324 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), itm);2325 }23262327 Ok(())2328 }23292330 fn remove_token_index(2331 collection_id: CollectionId,2332 item_index: TokenId,2333 owner: &T::CrossAccountId,2334 ) -> DispatchResult {2335 2336 <AccountItemCount<T>>::insert(2337 owner.as_sub(),2338 <AccountItemCount<T>>::get(owner.as_sub())2339 .checked_sub(1)2340 .ok_or(Error::<T>::NumOverflow)?,2341 );23422343 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.as_sub());2344 if list_exists {2345 let mut list = <AddressTokens<T>>::get(collection_id, owner.as_sub());2346 let item_contains = list.contains(&item_index.clone());23472348 if item_contains {2349 list.retain(|&item| item != item_index);2350 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), list);2351 }2352 }23532354 Ok(())2355 }23562357 fn move_token_index(2358 collection_id: CollectionId,2359 item_index: TokenId,2360 old_owner: &T::CrossAccountId,2361 new_owner: &T::CrossAccountId,2362 ) -> DispatchResult {2363 Self::remove_token_index(collection_id, item_index, old_owner)?;2364 Self::add_token_index(collection_id, item_index, new_owner)?;23652366 Ok(())2367 }2368}23692370sp_api::decl_runtime_apis! {2371 pub trait NftApi {2372 2373 fn eth_contract_code(account: H160) -> Option<Vec<u8>>;2374 }2375}