123456#![recursion_limit = "1024"]78#![cfg_attr(not(feature = "std"), no_std)]910extern crate alloc;1112pub use serde::{Serialize, Deserialize};1314pub use frame_support::{15 construct_runtime, decl_event, decl_module, decl_storage, decl_error,16 dispatch::DispatchResult,17 ensure, fail, parameter_types,18 traits::{19 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,20 Randomness, IsSubType, WithdrawReasons,21 },22 weights::{23 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},24 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,25 WeightToFeePolynomial, DispatchClass,26 },27 StorageValue,28 transactional,29};3031use frame_system::{self as system, ensure_signed, ensure_root};32use sp_core::H160;33use sp_runtime::sp_std::prelude::Vec;34use core::ops::{Deref, DerefMut};35use core::cell::RefCell;36use nft_data_structs::{37 MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_REFUNGIBLE_PIECES,38 AccessMode, ChainLimits, Collection, CreateItemData, CollectionLimits,39 CollectionId, CollectionMode, TokenId, 40 SchemaVersion, SponsorshipState, Ownership,41 NftItemType, FungibleItemType, ReFungibleItemType42};43use pallet_ethereum::EthereumTransactionSender;4445#[cfg(test)]46mod mock;4748#[cfg(test)]49mod tests;5051mod default_weights;52mod eth;53mod sponsorship;54pub use sponsorship::NftSponsorshipHandler;5556pub use eth::NftErcSupport;57pub use eth::account::*;58use eth::erc::{ERC20Events, ERC721Events};5960#[cfg(feature = "runtime-benchmarks")]61mod benchmarking;6263pub trait WeightInfo {64 fn create_collection() -> Weight;65 fn destroy_collection() -> Weight;66 fn add_to_white_list() -> Weight;67 fn remove_from_white_list() -> Weight;68 fn set_public_access_mode() -> Weight;69 fn set_mint_permission() -> Weight;70 fn change_collection_owner() -> Weight;71 fn add_collection_admin() -> Weight;72 fn remove_collection_admin() -> Weight;73 fn set_collection_sponsor() -> Weight;74 fn confirm_sponsorship() -> Weight;75 fn remove_collection_sponsor() -> Weight;76 fn create_item(s: usize) -> Weight;77 fn burn_item() -> Weight;78 fn transfer() -> Weight;79 fn approve() -> Weight;80 fn transfer_from() -> Weight;81 fn set_offchain_schema() -> Weight;82 fn set_const_on_chain_schema() -> Weight;83 fn set_variable_on_chain_schema() -> Weight;84 fn set_variable_meta_data() -> Weight;85 fn enable_contract_sponsoring() -> Weight;86 fn set_schema_version() -> Weight;87 fn set_chain_limits() -> Weight;88 fn set_contract_sponsoring_rate_limit() -> Weight;89 fn set_variable_meta_data_sponsoring_rate_limit() -> Weight;90 fn toggle_contract_white_list() -> Weight;91 fn add_to_contract_white_list() -> Weight;92 fn remove_from_contract_white_list() -> Weight;93 fn set_collection_limits() -> Weight;94}9596decl_error! {97 98 pub enum Error for Module<T: Config> {99 100 TotalCollectionsLimitExceeded,101 102 CollectionDecimalPointLimitExceeded, 103 104 CollectionNameLimitExceeded, 105 106 CollectionDescriptionLimitExceeded, 107 108 CollectionTokenPrefixLimitExceeded,109 110 CollectionNotFound,111 112 TokenNotFound,113 114 AdminNotFound,115 116 NumOverflow, 117 118 AlreadyAdmin, 119 120 NoPermission,121 122 ConfirmUnsetSponsorFail,123 124 PublicMintingNotAllowed,125 126 MustBeTokenOwner,127 128 TokenValueTooLow,129 130 NftSizeLimitExceeded,131 132 ApproveNotFound,133 134 TokenValueNotEnough,135 136 ApproveRequired,137 138 AddresNotInWhiteList,139 140 CollectionAdminsLimitExceeded,141 142 AddressOwnershipLimitExceeded,143 144 EmptyArgument,145 146 TokenConstDataLimitExceeded,147 148 TokenVariableDataLimitExceeded,149 150 NotNftDataUsedToMintNftCollectionToken,151 152 NotFungibleDataUsedToMintFungibleCollectionToken,153 154 NotReFungibleDataUsedToMintReFungibleCollectionToken,155 156 UnexpectedCollectionType,157 158 CantStoreMetadataInFungibleTokens,159 160 CollectionTokenLimitExceeded,161 162 AccountTokenLimitExceeded,163 164 CollectionLimitBoundsExceeded,165 166 OwnerPermissionsCantBeReverted,167 168 SchemaDataLimitExceeded,169 170 WrongRefungiblePieces,171 172 BadCreateRefungibleCall,173 174 OutOfGas,175 }176}177178pub struct CollectionHandle<T: Config> {179 pub id: CollectionId,180 collection: Collection<T>,181 logs: eth::log::LogRecorder,182 evm_address: H160,183 gas_limit: RefCell<u64>,184}185impl<T: Config> CollectionHandle<T> {186 pub fn get_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {187 <CollectionById<T>>::get(id)188 .map(|collection| Self {189 id,190 collection,191 logs: eth::log::LogRecorder::default(),192 evm_address: eth::collection_id_to_address(id),193 gas_limit: RefCell::new(gas_limit),194 })195 }196 pub fn get(id: CollectionId) -> Option<Self> {197 Self::get_with_gas_limit(id, u64::MAX)198 }199 pub fn gas_left(&self) -> u64 {200 *self.gas_limit.borrow()201 }202 pub fn consume_gas(&self, gas: u64) -> DispatchResult {203 let mut gas_limit = self.gas_limit.borrow_mut();204 if *gas_limit < gas {205 fail!(Error::<T>::OutOfGas);206 }207 *gas_limit -= gas;208 Ok(())209 }210 pub fn log(&self, log: impl evm_coder::ToLog) {211 self.logs.log(log.to_log(self.evm_address))212 }213 pub fn into_inner(self) -> Collection<T> {214 self.collection.clone()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 + 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>;239 type EvmWithdrawOrigin: pallet_evm::EnsureAddressOrigin<Self::Origin, Success = Self::AccountId>;240241 type CrossAccountId: CrossAccountId<Self::AccountId>;242 type Currency: Currency<Self::AccountId>;243 type CollectionCreationPrice: Get<<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance>;244 type TreasuryAccountId: Get<Self::AccountId>;245246 type EthereumChainId: Get<u64>;247 type EthereumTransactionSender: pallet_ethereum::EthereumTransactionSender;248}249250251252253254255256257258259260261262263264265266267268269270271272decl_storage! {273 trait Store for Module<T: Config> as Nft {274275 276 277 CreatedCollectionCount: u32;278 279 ChainVersion: u64;280 281 282 ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;283 284285 286 pub ChainLimit get(fn chain_limit) config(): ChainLimits;287 288289 290 291 292 DestroyedCollectionCount: u32;293 294 295 pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;296 297298 299 300 301 pub CollectionById get(fn collection_id) config(): map hasher(blake2_128_concat) CollectionId => Option<Collection<T>> = None;302 303 304 pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::CrossAccountId>;305 306 307 pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;308 309310 311 312 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => u128;313314 315 316 317 pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;318319 320 321 pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<NftItemType<T::CrossAccountId>>;322 323 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;324 325 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<ReFungibleItemType<T::CrossAccountId>>;326 327328 329 330 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => Vec<TokenId>;331 332333 334 335 336 pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;337 338 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;339 340 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;341 342 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;343 344345 346 347 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;348 }349 add_extra_genesis {350 build(|config: &GenesisConfig<T>| {351 352 for (_num, _c) in &config.collection_id {353 <Module<T>>::init_collection(_c);354 }355356 for (_num, _c, _i) in &config.nft_item_id {357 <Module<T>>::init_nft_token(*_c, _i);358 }359360 for (collection_id, account_id, fungible_item) in &config.fungible_item_id {361 <Module<T>>::init_fungible_token(*collection_id, &T::CrossAccountId::from_sub(account_id.clone()), fungible_item);362 }363364 for (_num, _c, _i) in &config.refungible_item_id {365 <Module<T>>::init_refungible_token(*_c, _i);366 }367 })368 }369}370371decl_event!(372 pub enum Event<T>373 where374 AccountId = <T as frame_system::Config>::AccountId,375 CrossAccountId = <T as Config>::CrossAccountId,376 {377 378 379 380 381 382 383 384 385 386 CollectionCreated(CollectionId, u8, AccountId),387388 389 390 391 392 393 394 395 396 397 ItemCreated(CollectionId, TokenId, CrossAccountId),398399 400 401 402 403 404 405 406 ItemDestroyed(CollectionId, TokenId),407408 409 410 411 412 413 414 415 416 417 418 419 Transfer(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),420421 422 423 424 425 426 427 428 429 430 Approved(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),431 }432);433434decl_module! {435 pub struct Module<T: Config> for enum Call 436 where 437 origin: T::Origin438 {439 fn deposit_event() = default;440 type Error = Error<T>;441442 fn on_initialize(_now: T::BlockNumber) -> Weight {443 0444 }445446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 #[weight = <T as Config>::WeightInfo::create_collection()]463 #[transactional]464 pub fn create_collection(origin,465 collection_name: Vec<u16>,466 collection_description: Vec<u16>,467 token_prefix: Vec<u8>,468 mode: CollectionMode) -> DispatchResult {469470 471 let who = ensure_signed(origin)?;472473 474 let mut imbalance = <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();475 imbalance.subsume(<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(476 &T::TreasuryAccountId::get(),477 T::CollectionCreationPrice::get(),478 ));479 <T as Config>::Currency::settle(480 &who,481 imbalance,482 WithdrawReasons::TRANSFER,483 ExistenceRequirement::KeepAlive,484 ).map_err(|_| Error::<T>::NoPermission)?;485486 let decimal_points = match mode {487 CollectionMode::Fungible(points) => points,488 _ => 0489 };490491 let chain_limit = ChainLimit::get();492493 let created_count = CreatedCollectionCount::get();494 let destroyed_count = DestroyedCollectionCount::get();495496 497 ensure!(created_count - destroyed_count < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);498499 500 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);501 ensure!(collection_name.len() <= 64, Error::<T>::CollectionNameLimitExceeded);502 ensure!(collection_description.len() <= 256, Error::<T>::CollectionDescriptionLimitExceeded);503 ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);504505 506 let next_id = created_count507 .checked_add(1)508 .ok_or(Error::<T>::NumOverflow)?;509510 CreatedCollectionCount::put(next_id);511512 let limits = CollectionLimits {513 sponsored_data_size: chain_limit.custom_data_limit,514 ..Default::default()515 };516517 518 let new_collection = Collection {519 owner: who.clone(),520 name: collection_name,521 mode: mode.clone(),522 mint_mode: false,523 access: AccessMode::Normal,524 description: collection_description,525 decimal_points: decimal_points,526 token_prefix: token_prefix,527 offchain_schema: Vec::new(),528 schema_version: SchemaVersion::ImageURL,529 sponsorship: SponsorshipState::Disabled,530 variable_on_chain_schema: Vec::new(),531 const_on_chain_schema: Vec::new(),532 limits,533 };534535 536 <CollectionById<T>>::insert(next_id, new_collection);537538 539 Self::deposit_event(RawEvent::CollectionCreated(next_id, mode.into(), who));540541 Ok(())542 }543544 545 546 547 548 549 550 551 552 553 #[weight = <T as Config>::WeightInfo::destroy_collection()]554 #[transactional]555 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {556557 let sender = ensure_signed(origin)?;558 let collection = Self::get_collection(collection_id)?;559 Self::check_owner_permissions(&collection, &sender)?;560 if !collection.limits.owner_can_destroy {561 fail!(Error::<T>::NoPermission);562 }563564 <AddressTokens<T>>::remove_prefix(collection_id);565 <Allowances<T>>::remove_prefix(collection_id);566 <Balance<T>>::remove_prefix(collection_id);567 <ItemListIndex>::remove(collection_id);568 <AdminList<T>>::remove(collection_id);569 <CollectionById<T>>::remove(collection_id);570 <WhiteList<T>>::remove_prefix(collection_id);571572 <NftItemList<T>>::remove_prefix(collection_id);573 <FungibleItemList<T>>::remove_prefix(collection_id);574 <ReFungibleItemList<T>>::remove_prefix(collection_id);575576 <NftTransferBasket<T>>::remove_prefix(collection_id);577 <FungibleTransferBasket<T>>::remove_prefix(collection_id);578 <ReFungibleTransferBasket<T>>::remove_prefix(collection_id);579580 <VariableMetaDataBasket<T>>::remove_prefix(collection_id);581582 DestroyedCollectionCount::put(DestroyedCollectionCount::get()583 .checked_add(1)584 .ok_or(Error::<T>::NumOverflow)?);585586 Ok(())587 }588589 590 591 592 593 594 595 596 597 598 599 600 601 #[weight = <T as Config>::WeightInfo::add_to_white_list()]602 #[transactional]603 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{604605 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);606 let collection = Self::get_collection(collection_id)?;607608 Self::toggle_white_list_internal(609 &sender,610 &collection,611 &address,612 true,613 )?;614615 Ok(())616 }617618 619 620 621 622 623 624 625 626 627 628 629 630 #[weight = <T as Config>::WeightInfo::remove_from_white_list()]631 #[transactional]632 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{633634 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);635 let collection = Self::get_collection(collection_id)?;636637 Self::toggle_white_list_internal(638 &sender,639 &collection,640 &address,641 false,642 )?;643644 Ok(())645 }646647 648 649 650 651 652 653 654 655 656 657 658 #[weight = <T as Config>::WeightInfo::set_public_access_mode()]659 #[transactional]660 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult661 {662 let sender = ensure_signed(origin)?;663664 let mut target_collection = Self::get_collection(collection_id)?;665 Self::check_owner_permissions(&target_collection, &sender)?;666 target_collection.access = mode;667 Self::save_collection(target_collection);668669 Ok(())670 }671672 673 674 675 676 677 678 679 680 681 682 683 684 685 #[weight = <T as Config>::WeightInfo::set_mint_permission()]686 #[transactional]687 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult688 {689 let sender = ensure_signed(origin)?;690691 let mut target_collection = Self::get_collection(collection_id)?;692 Self::check_owner_permissions(&target_collection, &sender)?;693 target_collection.mint_mode = mint_permission;694 Self::save_collection(target_collection);695696 Ok(())697 }698699 700 701 702 703 704 705 706 707 708 709 710 #[weight = <T as Config>::WeightInfo::change_collection_owner()]711 #[transactional]712 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {713714 let sender = ensure_signed(origin)?;715 let mut target_collection = Self::get_collection(collection_id)?;716 Self::check_owner_permissions(&target_collection, &sender)?;717 target_collection.owner = new_owner;718 Self::save_collection(target_collection);719720 Ok(())721 }722723 724 725 726 727 728 729 730 731 732 733 734 735 736 #[weight = <T as Config>::WeightInfo::add_collection_admin()]737 #[transactional]738 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {739 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);740 let collection = Self::get_collection(collection_id)?;741 Self::check_owner_or_admin_permissions(&collection, &sender)?;742 let mut admin_arr = <AdminList<T>>::get(collection_id);743744 match admin_arr.binary_search(&new_admin_id) {745 Ok(_) => {},746 Err(idx) => {747 let limits = ChainLimit::get();748 ensure!(admin_arr.len() < limits.collections_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 = <T as Config>::WeightInfo::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 match admin_arr.binary_search(&account_id) {777 Ok(idx) => {778 admin_arr.remove(idx);779 <AdminList<T>>::insert(collection_id, admin_arr);780 },781 Err(_) => {}782 }783 Ok(())784 }785786 787 788 789 790 791 792 793 794 795 #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]796 #[transactional]797 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {798 let sender = ensure_signed(origin)?;799 let mut target_collection = Self::get_collection(collection_id)?;800 Self::check_owner_permissions(&target_collection, &sender)?;801802 target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);803 Self::save_collection(target_collection);804805 Ok(())806 }807808 809 810 811 812 813 814 815 #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]816 #[transactional]817 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {818 let sender = ensure_signed(origin)?;819820 let mut target_collection = Self::get_collection(collection_id)?;821 ensure!(822 target_collection.sponsorship.pending_sponsor() == Some(&sender),823 Error::<T>::ConfirmUnsetSponsorFail824 );825826 target_collection.sponsorship = SponsorshipState::Confirmed(sender);827 Self::save_collection(target_collection);828829 Ok(())830 }831832 833 834 835 836 837 838 839 840 841 #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]842 #[transactional]843 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {844 let sender = ensure_signed(origin)?;845846 let mut target_collection = Self::get_collection(collection_id)?;847 Self::check_owner_permissions(&target_collection, &sender)?;848849 target_collection.sponsorship = SponsorshipState::Disabled;850 Self::save_collection(target_collection);851852 Ok(())853 }854855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878879 #[weight = <T as Config>::WeightInfo::create_item(data.len())]880 #[transactional]881 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResult {882 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);883 let collection = Self::get_collection(collection_id)?;884885 Self::create_item_internal(&sender, &collection, &owner, data)?;886887 Self::submit_logs(collection)?;888 Ok(())889 }890891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 #[weight = <T as Config>::WeightInfo::create_item(items_data.into_iter()910 .map(|data| { data.len() })911 .sum())]912 #[transactional]913 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResult {914915 ensure!(items_data.len() > 0, Error::<T>::EmptyArgument);916 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);917 let collection = Self::get_collection(collection_id)?;918919 Self::create_multiple_items_internal(&sender, &collection, &owner, items_data)?;920921 Self::submit_logs(collection)?;922 Ok(())923 }924925 926 927 928 929 930 931 932 933 934 935 936 937 938 #[weight = <T as Config>::WeightInfo::burn_item()]939 #[transactional]940 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {941942 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);943 let target_collection = Self::get_collection(collection_id)?;944945 Self::burn_item_internal(&sender, &target_collection, item_id, value)?;946947 Self::submit_logs(target_collection)?;948 Ok(())949 }950951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 #[weight = <T as Config>::WeightInfo::transfer()]975 #[transactional]976 pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {977 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);978 let collection = Self::get_collection(collection_id)?;979980 Self::transfer_internal(&sender, &recipient, &collection, item_id, value)?;981982 Self::submit_logs(collection)?;983 Ok(())984 }985986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 #[weight = <T as Config>::WeightInfo::approve()]1002 #[transactional]1003 pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {1004 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1005 let collection = Self::get_collection(collection_id)?;10061007 Self::approve_internal(&sender, &spender, &collection, item_id, amount)?;10081009 Self::submit_logs(collection)?;1010 Ok(())1011 }1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 #[weight = <T as Config>::WeightInfo::transfer_from()]1033 #[transactional]1034 pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {1035 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1036 let collection = Self::get_collection(collection_id)?;10371038 Self::transfer_from_internal(&sender, &from, &recipient, &collection, item_id, value)?;10391040 Self::submit_logs(collection)?;1041 Ok(())1042 }1043 1044 1045 1046 1047 10481049 10501051 10521053 1054 10551056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1069 #[transactional]1070 pub fn set_variable_meta_data (1071 origin,1072 collection_id: CollectionId,1073 item_id: TokenId,1074 data: Vec<u8>1075 ) -> DispatchResult {1076 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1077 1078 let collection = Self::get_collection(collection_id)?;10791080 Self::set_variable_meta_data_internal(&sender, &collection, item_id, data)?;10811082 Ok(())1083 }1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 #[weight = <T as Config>::WeightInfo::set_schema_version()]1100 #[transactional]1101 pub fn set_schema_version(1102 origin,1103 collection_id: CollectionId,1104 version: SchemaVersion1105 ) -> DispatchResult {1106 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1107 let mut target_collection = Self::get_collection(collection_id)?;1108 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;1109 target_collection.schema_version = version;1110 Self::save_collection(target_collection);11111112 Ok(())1113 }11141115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1128 #[transactional]1129 pub fn set_offchain_schema(1130 origin,1131 collection_id: CollectionId,1132 schema: Vec<u8>1133 ) -> DispatchResult {1134 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1135 let mut target_collection = Self::get_collection(collection_id)?;1136 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;11371138 1139 ensure!(schema.len() as u32 <= ChainLimit::get().offchain_schema_limit, "");11401141 target_collection.offchain_schema = schema;1142 Self::save_collection(target_collection);11431144 Ok(())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 Self::save_collection(target_collection);11751176 Ok(())1177 }11781179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1192 #[transactional]1193 pub fn set_variable_on_chain_schema (1194 origin,1195 collection_id: CollectionId,1196 schema: Vec<u8>1197 ) -> DispatchResult {1198 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1199 let mut target_collection = Self::get_collection(collection_id)?;1200 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;12011202 1203 ensure!(schema.len() as u32 <= ChainLimit::get().variable_on_chain_schema_limit, "");12041205 target_collection.variable_on_chain_schema = schema;1206 Self::save_collection(target_collection);12071208 Ok(())1209 }12101211 1212 #[weight = <T as Config>::WeightInfo::set_chain_limits()]1213 #[transactional]1214 pub fn set_chain_limits(1215 origin,1216 limits: ChainLimits1217 ) -> DispatchResult {12181219 #[cfg(not(feature = "runtime-benchmarks"))]1220 ensure_root(origin)?;12211222 <ChainLimit>::put(limits);1223 Ok(())1224 }12251226 #[weight = <T as Config>::WeightInfo::set_collection_limits()]1227 #[transactional]1228 pub fn set_collection_limits(1229 origin,1230 collection_id: u32,1231 new_limits: CollectionLimits<T::BlockNumber>,1232 ) -> DispatchResult {1233 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1234 let mut target_collection = Self::get_collection(collection_id)?;1235 Self::check_owner_permissions(&target_collection, &sender.as_sub())?;1236 let old_limits = &target_collection.limits;1237 let chain_limits = ChainLimit::get();12381239 1240 ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&1241 new_limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP && 1242 new_limits.sponsored_data_size <= chain_limits.custom_data_limit,1243 Error::<T>::CollectionLimitBoundsExceeded);12441245 1246 ensure!(old_limits.token_limit >= new_limits.token_limit, Error::<T>::CollectionTokenLimitExceeded);1247 ensure!(new_limits.token_limit > 0, Error::<T>::CollectionTokenLimitExceeded);12481249 ensure!(1250 (old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&1251 (old_limits.owner_can_destroy || !new_limits.owner_can_destroy),1252 Error::<T>::OwnerPermissionsCantBeReverted,1253 );12541255 target_collection.limits = new_limits;1256 Self::save_collection(target_collection);12571258 Ok(())1259 } 1260 }1261}12621263impl<T: Config> Module<T> {1264 pub fn create_item_internal(sender: &T::CrossAccountId, collection: &CollectionHandle<T>, owner: &T::CrossAccountId, data: CreateItemData) -> 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(sender: &T::CrossAccountId, recipient: &T::CrossAccountId, target_collection: &CollectionHandle<T>, item_id: TokenId, value: u128) -> DispatchResult {1273 target_collection.consume_gas(2000000)?;1274 1275 Self::is_correct_transfer(target_collection, &recipient)?;12761277 1278 ensure!(Self::is_item_owner(&sender, target_collection, item_id) ||1279 Self::is_owner_or_admin_permissions(target_collection, &sender),1280 Error::<T>::NoPermission);12811282 if target_collection.access == AccessMode::WhiteList {1283 Self::check_white_list(target_collection, &sender)?;1284 Self::check_white_list(target_collection, &recipient)?;1285 }12861287 match target_collection.mode1288 {1289 CollectionMode::NFT => Self::transfer_nft(target_collection, item_id, sender.clone(), recipient.clone())?,1290 CollectionMode::Fungible(_) => Self::transfer_fungible(target_collection, value, &sender, &recipient)?,1291 CollectionMode::ReFungible => Self::transfer_refungible(target_collection, item_id, value, sender.clone(), recipient.clone())?,1292 _ => ()1293 };12941295 Self::deposit_event(RawEvent::Transfer(target_collection.id, item_id, sender.clone(), recipient.clone(), value));12961297 Ok(())1298 }12991300 pub fn approve_internal(1301 sender: &T::CrossAccountId,1302 spender: &T::CrossAccountId,1303 collection: &CollectionHandle<T>,1304 item_id: TokenId,1305 amount: u1281306 ) -> DispatchResult {1307 collection.consume_gas(2000000)?;1308 Self::token_exists(&collection, item_id)?;13091310 1311 let bypasses_limits = collection.limits.owner_can_transfer &&1312 Self::is_owner_or_admin_permissions(1313 &collection,1314 &sender,1315 );13161317 let allowance_limit = if bypasses_limits {1318 None1319 } else if let Some(amount) = Self::owned_amount(1320 &sender,1321 &collection,1322 item_id,1323 ) {1324 Some(amount)1325 } else {1326 fail!(Error::<T>::NoPermission);1327 };13281329 if collection.access == AccessMode::WhiteList {1330 Self::check_white_list(&collection, &sender)?;1331 Self::check_white_list(&collection, &spender)?;1332 }13331334 let allowance: u128 = amount1335 .checked_add(<Allowances<T>>::get(collection.id, (item_id, sender.as_sub(), spender.as_sub())))1336 .ok_or(Error::<T>::NumOverflow)?;1337 if let Some(limit) = allowance_limit {1338 ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);1339 }1340 <Allowances<T>>::insert(collection.id, (item_id, sender.as_sub(), spender.as_sub()), allowance);13411342 if matches!(collection.mode, CollectionMode::NFT) {1343 1344 collection.log(ERC721Events::Approval {1345 owner: *sender.as_eth(),1346 approved: *spender.as_eth(),1347 token_id: item_id.into(),1348 });1349 }13501351 if matches!(collection.mode, CollectionMode::Fungible(_)) {1352 1353 collection.log(ERC20Events::Approval {1354 owner: *sender.as_eth(),1355 spender: *spender.as_eth(),1356 value: allowance.into()1357 });1358 }13591360 Self::deposit_event(RawEvent::Approved(collection.id, item_id, sender.clone(), spender.clone(), allowance));1361 Ok(())1362 }13631364 pub fn transfer_from_internal(1365 sender: &T::CrossAccountId,1366 from: &T::CrossAccountId,1367 recipient: &T::CrossAccountId,1368 collection: &CollectionHandle<T>,1369 item_id: TokenId,1370 amount: u128,1371 ) -> DispatchResult {1372 collection.consume_gas(2000000)?;1373 1374 let approval: u128 = <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));13751376 1377 Self::is_correct_transfer(&collection, &recipient)?;13781379 1380 ensure!(1381 approval >= amount || 1382 (1383 collection.limits.owner_can_transfer &&1384 Self::is_owner_or_admin_permissions(&collection, &sender)1385 ),1386 Error::<T>::NoPermission1387 );13881389 if collection.access == AccessMode::WhiteList {1390 Self::check_white_list(&collection, &sender)?;1391 Self::check_white_list(&collection, &recipient)?;1392 }13931394 1395 let allowance = approval.saturating_sub(amount);1396 if allowance > 0 {1397 <Allowances<T>>::insert(collection.id, (item_id, from.as_sub(), sender.as_sub()), allowance);1398 } else {1399 <Allowances<T>>::remove(collection.id, (item_id, from.as_sub(), sender.as_sub()));1400 }14011402 match collection.mode {1403 CollectionMode::NFT => {1404 Self::transfer_nft(&collection, item_id, from.clone(), recipient.clone())?1405 }1406 CollectionMode::Fungible(_) => {1407 Self::transfer_fungible(&collection, amount, &from, &recipient)?1408 }1409 CollectionMode::ReFungible => {1410 Self::transfer_refungible(&collection, item_id, amount, from.clone(), recipient.clone())?1411 }1412 _ => ()1413 };14141415 if matches!(collection.mode, CollectionMode::Fungible(_)) {1416 collection.log(ERC20Events::Approval {1417 owner: *from.as_eth(),1418 spender: *sender.as_eth(),1419 value: allowance.into()1420 });1421 }14221423 Ok(())1424 }14251426 pub fn set_variable_meta_data_internal(1427 sender: &T::CrossAccountId,1428 collection: &CollectionHandle<T>, 1429 item_id: TokenId,1430 data: Vec<u8>,1431 ) -> DispatchResult {1432 Self::token_exists(&collection, item_id)?;14331434 ensure!(ChainLimit::get().custom_data_limit >= data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);14351436 1437 ensure!(Self::is_item_owner(&sender, &collection, item_id) ||1438 Self::is_owner_or_admin_permissions(&collection, &sender),1439 Error::<T>::NoPermission);14401441 match collection.mode1442 {1443 CollectionMode::NFT => Self::set_nft_variable_data(&collection, item_id, data)?,1444 CollectionMode::ReFungible => Self::set_re_fungible_variable_data(&collection, item_id, data)?,1445 CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),1446 _ => fail!(Error::<T>::UnexpectedCollectionType)1447 };14481449 Ok(())1450 }14511452 pub fn create_multiple_items_internal(1453 sender: &T::CrossAccountId,1454 collection: &CollectionHandle<T>,1455 owner: &T::CrossAccountId,1456 items_data: Vec<CreateItemData>,1457 ) -> DispatchResult {1458 Self::can_create_items_in_collection(&collection, &sender, &owner, items_data.len() as u32)?;14591460 for data in &items_data {1461 Self::validate_create_item_args(&collection, data)?;1462 }1463 for data in &items_data {1464 Self::create_item_no_validation(&collection, owner, data.clone())?;1465 }14661467 Ok(())1468 }14691470 pub fn burn_item_internal(1471 sender: &T::CrossAccountId,1472 collection: &CollectionHandle<T>,1473 item_id: TokenId,1474 value: u128,1475 ) -> DispatchResult {1476 ensure!(1477 Self::is_item_owner(&sender, &collection, item_id) ||1478 (1479 collection.limits.owner_can_transfer &&1480 Self::is_owner_or_admin_permissions(&collection, &sender)1481 ),1482 Error::<T>::NoPermission1483 );14841485 if collection.access == AccessMode::WhiteList {1486 Self::check_white_list(&collection, &sender)?;1487 }14881489 match collection.mode1490 {1491 CollectionMode::NFT => Self::burn_nft_item(&collection, item_id)?,1492 CollectionMode::Fungible(_) => Self::burn_fungible_item(&sender, &collection, value)?,1493 CollectionMode::ReFungible => Self::burn_refungible_item(&collection, item_id, &sender)?,1494 _ => ()1495 };14961497 Ok(())1498 }14991500 pub fn toggle_white_list_internal(1501 sender: &T::CrossAccountId,1502 collection: &CollectionHandle<T>,1503 address: &T::CrossAccountId,1504 whitelisted: bool,1505 ) -> DispatchResult {1506 Self::check_owner_or_admin_permissions(&collection, &sender)?;15071508 if whitelisted {1509 <WhiteList<T>>::insert(collection.id, address.as_sub(), true);1510 } else {1511 <WhiteList<T>>::remove(collection.id, address.as_sub());1512 }15131514 Ok(())1515 }15161517 fn is_correct_transfer(collection: &CollectionHandle<T>, recipient: &T::CrossAccountId) -> DispatchResult {1518 let collection_id = collection.id;15191520 1521 let account_items: u32 = <AddressTokens<T>>::get(collection_id, recipient.as_sub()).len() as u32;1522 ensure!(collection.limits.account_token_ownership_limit > account_items, Error::<T>::AccountTokenLimitExceeded);1523 1524 Ok(())1525 }15261527 fn can_create_items_in_collection(collection: &CollectionHandle<T>, sender: &T::CrossAccountId, owner: &T::CrossAccountId, amount: u32) -> DispatchResult {1528 let collection_id = collection.id;15291530 1531 let total_items: u32 = ItemListIndex::get(collection_id)1532 .checked_add(amount)1533 .ok_or(Error::<T>::CollectionTokenLimitExceeded)?;1534 let account_items: u32 = (<AddressTokens<T>>::get(collection_id, owner.as_sub()).len() as u32)1535 .checked_add(amount)1536 .ok_or(Error::<T>::AccountTokenLimitExceeded)?;1537 ensure!(collection.limits.token_limit >= total_items, Error::<T>::CollectionTokenLimitExceeded);1538 ensure!(collection.limits.account_token_ownership_limit >= account_items, Error::<T>::AccountTokenLimitExceeded);15391540 if !Self::is_owner_or_admin_permissions(collection, &sender) {1541 ensure!(collection.mint_mode == true, Error::<T>::PublicMintingNotAllowed);1542 Self::check_white_list(collection, owner)?;1543 Self::check_white_list(collection, sender)?;1544 }15451546 Ok(())1547 }15481549 fn validate_create_item_args(target_collection: &CollectionHandle<T>, data: &CreateItemData) -> DispatchResult {1550 match target_collection.mode1551 {1552 CollectionMode::NFT => {1553 if let CreateItemData::NFT(data) = data {1554 1555 ensure!(ChainLimit::get().custom_data_limit >= data.const_data.len() as u32, Error::<T>::TokenConstDataLimitExceeded);1556 ensure!(ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);1557 } else {1558 fail!(Error::<T>::NotNftDataUsedToMintNftCollectionToken);1559 }1560 },1561 CollectionMode::Fungible(_) => {1562 if let CreateItemData::Fungible(_) = data {1563 } else {1564 fail!(Error::<T>::NotFungibleDataUsedToMintFungibleCollectionToken);1565 }1566 },1567 CollectionMode::ReFungible => {1568 if let CreateItemData::ReFungible(data) = data {15691570 1571 ensure!(ChainLimit::get().custom_data_limit >= data.const_data.len() as u32, Error::<T>::TokenConstDataLimitExceeded);1572 ensure!(ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);15731574 1575 ensure!(data.pieces <= MAX_REFUNGIBLE_PIECES, Error::<T>::WrongRefungiblePieces);1576 ensure!(data.pieces > 0, Error::<T>::WrongRefungiblePieces);1577 } else {1578 fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);1579 }1580 },1581 _ => { fail!(Error::<T>::UnexpectedCollectionType); }1582 };15831584 Ok(())1585 }15861587 fn create_item_no_validation(collection: &CollectionHandle<T>, owner: &T::CrossAccountId, data: CreateItemData) -> DispatchResult {1588 match data1589 {1590 CreateItemData::NFT(data) => {1591 let item = NftItemType {1592 owner: owner.clone(),1593 const_data: data.const_data,1594 variable_data: data.variable_data1595 };15961597 Self::add_nft_item(collection, item)?;1598 },1599 CreateItemData::Fungible(data) => {1600 Self::add_fungible_item(collection, &owner, data.value)?;1601 },1602 CreateItemData::ReFungible(data) => {1603 let mut owner_list = Vec::new();1604 owner_list.push(Ownership {owner: owner.clone(), fraction: data.pieces});16051606 let item = ReFungibleItemType {1607 owner: owner_list,1608 const_data: data.const_data,1609 variable_data: data.variable_data1610 };16111612 Self::add_refungible_item(collection, item)?;1613 }1614 };16151616 Ok(())1617 }16181619 fn add_fungible_item(collection: &CollectionHandle<T>, owner: &T::CrossAccountId, value: u128) -> DispatchResult {1620 let collection_id = collection.id;16211622 1623 let balance: u128 = <FungibleItemList<T>>::get(collection_id, owner.as_sub()).value;16241625 1626 let item = FungibleItemType {1627 value: balance.checked_add(value).ok_or(Error::<T>::NumOverflow)?,1628 };1629 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), item);16301631 1632 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1633 .checked_add(value)1634 .ok_or(Error::<T>::NumOverflow)?;1635 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);16361637 Self::deposit_event(RawEvent::ItemCreated(collection_id, 0, owner.clone()));1638 Ok(())1639 }16401641 fn add_refungible_item(collection: &CollectionHandle<T>, item: ReFungibleItemType<T::CrossAccountId>) -> DispatchResult {1642 let collection_id = collection.id;16431644 let current_index = <ItemListIndex>::get(collection_id)1645 .checked_add(1)1646 .ok_or(Error::<T>::NumOverflow)?;1647 let itemcopy = item.clone();16481649 ensure!(1650 item.owner.len() == 1,1651 Error::<T>::BadCreateRefungibleCall,1652 );1653 let item_owner = item.owner.first().expect("only one owner is defined");16541655 let value = item_owner.fraction;1656 let owner = item_owner.owner.clone();16571658 Self::add_token_index(collection_id, current_index, &owner)?;16591660 <ItemListIndex>::insert(collection_id, current_index);1661 <ReFungibleItemList<T>>::insert(collection_id, current_index, itemcopy);16621663 1664 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1665 .checked_add(value)1666 .ok_or(Error::<T>::NumOverflow)?;1667 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);16681669 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, owner));1670 Ok(())1671 }16721673 fn add_nft_item(collection: &CollectionHandle<T>, item: NftItemType<T::CrossAccountId>) -> DispatchResult {1674 let collection_id = collection.id;16751676 let current_index = <ItemListIndex>::get(collection_id)1677 .checked_add(1)1678 .ok_or(Error::<T>::NumOverflow)?;16791680 let item_owner = item.owner.clone();1681 Self::add_token_index(collection_id, current_index, &item.owner)?;16821683 <ItemListIndex>::insert(collection_id, current_index);1684 <NftItemList<T>>::insert(collection_id, current_index, item);16851686 1687 let new_balance = <Balance<T>>::get(collection_id, item_owner.as_sub())1688 .checked_add(1)1689 .ok_or(Error::<T>::NumOverflow)?;1690 <Balance<T>>::insert(collection_id, item_owner.as_sub(), new_balance);16911692 collection.log(ERC721Events::Transfer {1693 from: H160::default(),1694 to: *item_owner.as_eth(),1695 token_id: current_index.into(),1696 });1697 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, item_owner));1698 Ok(())1699 }17001701 fn burn_refungible_item(1702 collection: &CollectionHandle<T>,1703 item_id: TokenId,1704 owner: &T::CrossAccountId,1705 ) -> DispatchResult {1706 let collection_id = collection.id;17071708 let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id)1709 .ok_or(Error::<T>::TokenNotFound)?;1710 let rft_balance = token1711 .owner1712 .iter()1713 .find(|&i| i.owner == *owner)1714 .ok_or(Error::<T>::TokenNotFound)?;1715 Self::remove_token_index(collection_id, item_id, owner)?;17161717 1718 let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.as_sub())1719 .checked_sub(rft_balance.fraction)1720 .ok_or(Error::<T>::NumOverflow)?;1721 <Balance<T>>::insert(collection_id, rft_balance.owner.as_sub(), new_balance);17221723 1724 let index = token1725 .owner1726 .iter()1727 .position(|i| i.owner == *owner)1728 .expect("owned item is exists");1729 token.owner.remove(index);1730 let owner_count = token.owner.len();17311732 1733 if owner_count == 0 {1734 <ReFungibleItemList<T>>::remove(collection_id, item_id);1735 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);1736 }1737 else {1738 <ReFungibleItemList<T>>::insert(collection_id, item_id, token);1739 }17401741 Ok(())1742 }17431744 fn burn_nft_item(collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {1745 let collection_id = collection.id;17461747 let item = <NftItemList<T>>::get(collection_id, item_id)1748 .ok_or(Error::<T>::TokenNotFound)?;1749 Self::remove_token_index(collection_id, item_id, &item.owner)?;17501751 1752 let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())1753 .checked_sub(1)1754 .ok_or(Error::<T>::NumOverflow)?;1755 <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);1756 <NftItemList<T>>::remove(collection_id, item_id);1757 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);17581759 Self::deposit_event(RawEvent::ItemDestroyed(collection.id, item_id));1760 Ok(())1761 }17621763 fn burn_fungible_item(owner: &T::CrossAccountId, collection: &CollectionHandle<T>, value: u128) -> DispatchResult {1764 let collection_id = collection.id;17651766 let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());1767 ensure!(balance.value >= value, Error::<T>::TokenValueNotEnough);17681769 1770 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1771 .checked_sub(value)1772 .ok_or(Error::<T>::NumOverflow)?;1773 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);17741775 if balance.value - value > 0 {1776 balance.value -= value;1777 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);1778 }1779 else {1780 <FungibleItemList<T>>::remove(collection_id, owner.as_sub());1781 }17821783 collection.log(ERC20Events::Transfer {1784 from: *owner.as_eth(),1785 to: H160::default(),1786 value: value.into(),1787 });1788 Ok(())1789 }17901791 pub fn get_collection(collection_id: CollectionId) -> Result<CollectionHandle<T>, sp_runtime::DispatchError> {1792 Ok(<CollectionHandle<T>>::get(collection_id)1793 .ok_or(Error::<T>::CollectionNotFound)?)1794 }17951796 fn save_collection(collection: CollectionHandle<T>) {1797 <CollectionById<T>>::insert(collection.id, collection.into_inner());1798 }17991800 pub fn submit_logs(collection: CollectionHandle<T>) -> DispatchResult {1801 if collection.logs.is_empty() {1802 return Ok(())1803 }1804 T::EthereumTransactionSender::submit_logs_transaction(1805 eth::generate_transaction(collection.id, T::EthereumChainId::get()),1806 collection.logs.retrieve_logs(),1807 )1808 }18091810 fn check_owner_permissions(target_collection: &CollectionHandle<T>, subject: &T::AccountId) -> DispatchResult {1811 ensure!(1812 *subject == target_collection.owner,1813 Error::<T>::NoPermission1814 );18151816 Ok(())1817 }18181819 fn is_owner_or_admin_permissions(collection: &CollectionHandle<T>, subject: &T::CrossAccountId) -> bool {1820 *subject.as_sub() == collection.owner || <AdminList<T>>::get(collection.id).contains(&subject)1821 }18221823 fn check_owner_or_admin_permissions(1824 collection: &CollectionHandle<T>,1825 subject: &T::CrossAccountId,1826 ) -> DispatchResult {1827 ensure!(Self::is_owner_or_admin_permissions(collection, subject), Error::<T>::NoPermission);18281829 Ok(())1830 }18311832 fn owned_amount(1833 subject: &T::CrossAccountId,1834 target_collection: &CollectionHandle<T>,1835 item_id: TokenId,1836 ) -> Option<u128> {1837 let collection_id = target_collection.id;18381839 match target_collection.mode {1840 CollectionMode::NFT => (<NftItemList<T>>::get(collection_id, item_id)?.owner == *subject)1841 .then(|| 1),1842 CollectionMode::Fungible(_) => Some(<FungibleItemList<T>>::get(collection_id, &subject.as_sub())1843 .value),1844 CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)?1845 .owner1846 .iter()1847 .find(|i| i.owner == *subject)1848 .map(|i| i.fraction),1849 CollectionMode::Invalid => None,1850 }1851 }18521853 fn is_item_owner(subject: &T::CrossAccountId, target_collection: &CollectionHandle<T>, item_id: TokenId) -> bool {1854 match target_collection.mode {1855 CollectionMode::Fungible(_) => true,1856 _ => Self::owned_amount(&subject, target_collection, item_id).is_some(),1857 }1858 }18591860 fn check_white_list(collection: &CollectionHandle<T>, address: &T::CrossAccountId) -> DispatchResult {1861 let collection_id = collection.id;18621863 let mes = Error::<T>::AddresNotInWhiteList;1864 ensure!(<WhiteList<T>>::contains_key(collection_id, address.as_sub()), mes);18651866 Ok(())1867 }18681869 1870 1871 fn token_exists(1872 target_collection: &CollectionHandle<T>,1873 item_id: TokenId,1874 ) -> DispatchResult {1875 let collection_id = target_collection.id;1876 let exists = match target_collection.mode1877 {1878 CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),1879 CollectionMode::Fungible(_) => true,1880 CollectionMode::ReFungible => <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1881 _ => false1882 };18831884 ensure!(exists == true, Error::<T>::TokenNotFound);1885 Ok(())1886 }18871888 fn transfer_fungible(1889 collection: &CollectionHandle<T>,1890 value: u128,1891 owner: &T::CrossAccountId,1892 recipient: &T::CrossAccountId,1893 ) -> DispatchResult {1894 let collection_id = collection.id;18951896 let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());1897 ensure!(balance.value >= value, Error::<T>::TokenValueTooLow);18981899 1900 Self::add_fungible_item(collection, recipient, value)?;19011902 1903 <Balance<T>>::insert(collection_id, owner.as_sub(), balance.value - value);19041905 1906 if balance.value == value {1907 <FungibleItemList<T>>::remove(collection_id, owner.as_sub());1908 }1909 else {1910 balance.value -= value;1911 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);1912 }19131914 collection.log(ERC20Events::Transfer {1915 from: *owner.as_eth(),1916 to: *recipient.as_eth(),1917 value: value.into(),1918 });1919 Self::deposit_event(RawEvent::Transfer(collection.id, 1, owner.clone(), recipient.clone(), value));19201921 Ok(())1922 }19231924 fn transfer_refungible(1925 collection: &CollectionHandle<T>,1926 item_id: TokenId,1927 value: u128,1928 owner: T::CrossAccountId,1929 new_owner: T::CrossAccountId,1930 ) -> DispatchResult {1931 let collection_id = collection.id;1932 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id)1933 .ok_or(Error::<T>::TokenNotFound)?;19341935 let item = full_item1936 .owner1937 .iter()1938 .filter(|i| i.owner == owner)1939 .next()1940 .ok_or(Error::<T>::TokenNotFound)?;1941 let amount = item.fraction;19421943 ensure!(amount >= value, Error::<T>::TokenValueTooLow);19441945 1946 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())1947 .checked_sub(value)1948 .ok_or(Error::<T>::NumOverflow)?;1949 <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);19501951 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())1952 .checked_add(value)1953 .ok_or(Error::<T>::NumOverflow)?;1954 <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);19551956 let old_owner = item.owner.clone();1957 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);19581959 1960 if amount == value && !new_owner_has_account {1961 1962 1963 let mut new_full_item = full_item.clone();1964 new_full_item1965 .owner1966 .iter_mut()1967 .find(|i| i.owner == owner)1968 .expect("old owner does present in refungible")1969 .owner = new_owner.clone();1970 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);19711972 1973 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;1974 } else {1975 let mut new_full_item = full_item.clone();1976 new_full_item1977 .owner1978 .iter_mut()1979 .find(|i| i.owner == owner)1980 .expect("old owner does present in refungible")1981 .fraction -= value;19821983 1984 if new_owner_has_account {1985 1986 new_full_item1987 .owner1988 .iter_mut()1989 .find(|i| i.owner == new_owner)1990 .expect("new owner has account")1991 .fraction += value;1992 } else {1993 1994 new_full_item.owner.push(Ownership {1995 owner: new_owner.clone(),1996 fraction: value,1997 });1998 Self::add_token_index(collection_id, item_id, &new_owner)?;1999 }20002001 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);2002 }20032004 Self::deposit_event(RawEvent::Transfer(collection.id, item_id, owner, new_owner, amount));20052006 Ok(())2007 }20082009 fn transfer_nft(2010 collection: &CollectionHandle<T>,2011 item_id: TokenId,2012 sender: T::CrossAccountId,2013 new_owner: T::CrossAccountId,2014 ) -> DispatchResult {2015 let collection_id = collection.id;2016 let mut item = <NftItemList<T>>::get(collection_id, item_id)2017 .ok_or(Error::<T>::TokenNotFound)?;20182019 ensure!(2020 sender == item.owner,2021 Error::<T>::MustBeTokenOwner2022 );20232024 2025 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())2026 .checked_sub(1)2027 .ok_or(Error::<T>::NumOverflow)?;2028 <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);20292030 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())2031 .checked_add(1)2032 .ok_or(Error::<T>::NumOverflow)?;2033 <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);20342035 2036 let old_owner = item.owner.clone();2037 item.owner = new_owner.clone();2038 <NftItemList<T>>::insert(collection_id, item_id, item);20392040 2041 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;20422043 collection.log(ERC721Events::Transfer {2044 from: *sender.as_eth(),2045 to: *new_owner.as_eth(),2046 token_id: item_id.into(),2047 });2048 Self::deposit_event(RawEvent::Transfer(collection.id, item_id, sender, new_owner, 1));20492050 Ok(())2051 }2052 2053 fn set_re_fungible_variable_data(2054 collection: &CollectionHandle<T>,2055 item_id: TokenId,2056 data: Vec<u8>2057 ) -> DispatchResult {2058 let collection_id = collection.id;2059 let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id)2060 .ok_or(Error::<T>::TokenNotFound)?;20612062 item.variable_data = data;20632064 <ReFungibleItemList<T>>::insert(collection_id, item_id, item);20652066 Ok(())2067 }20682069 fn set_nft_variable_data(2070 collection: &CollectionHandle<T>,2071 item_id: TokenId,2072 data: Vec<u8>2073 ) -> DispatchResult {2074 let collection_id = collection.id;2075 let mut item = <NftItemList<T>>::get(collection_id, item_id)2076 .ok_or(Error::<T>::TokenNotFound)?;2077 2078 item.variable_data = data;20792080 <NftItemList<T>>::insert(collection_id, item_id, item);2081 2082 Ok(())2083 }20842085 #[allow(dead_code)]2086 fn init_collection(item: &Collection<T>) {2087 2088 assert!(2089 item.decimal_points <= MAX_DECIMAL_POINTS,2090 "decimal_points parameter must be lower than MAX_DECIMAL_POINTS"2091 );2092 assert!(2093 item.name.len() <= 64,2094 "Collection name can not be longer than 63 char"2095 );2096 assert!(2097 item.name.len() <= 256,2098 "Collection description can not be longer than 255 char"2099 );2100 assert!(2101 item.token_prefix.len() <= 16,2102 "Token prefix can not be longer than 15 char"2103 );21042105 2106 let next_id = CreatedCollectionCount::get()2107 .checked_add(1)2108 .unwrap();21092110 CreatedCollectionCount::put(next_id);2111 }21122113 #[allow(dead_code)]2114 fn init_nft_token(collection_id: CollectionId, item: &NftItemType<T::CrossAccountId>) {2115 let current_index = <ItemListIndex>::get(collection_id)2116 .checked_add(1)2117 .unwrap();21182119 Self::add_token_index(collection_id, current_index, &item.owner).unwrap();21202121 <ItemListIndex>::insert(collection_id, current_index);21222123 2124 let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())2125 .checked_add(1)2126 .unwrap();2127 <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);2128 }21292130 #[allow(dead_code)]2131 fn init_fungible_token(collection_id: CollectionId, owner: &T::CrossAccountId, item: &FungibleItemType) {2132 let current_index = <ItemListIndex>::get(collection_id)2133 .checked_add(1)2134 .unwrap();21352136 Self::add_token_index(collection_id, current_index, owner).unwrap();21372138 <ItemListIndex>::insert(collection_id, current_index);21392140 2141 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())2142 .checked_add(item.value)2143 .unwrap();2144 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);2145 }21462147 #[allow(dead_code)]2148 fn init_refungible_token(collection_id: CollectionId, item: &ReFungibleItemType<T::CrossAccountId>) {2149 let current_index = <ItemListIndex>::get(collection_id)2150 .checked_add(1)2151 .unwrap();21522153 let value = item.owner.first().unwrap().fraction;2154 let owner = item.owner.first().unwrap().owner.clone();21552156 Self::add_token_index(collection_id, current_index, &owner).unwrap();21572158 <ItemListIndex>::insert(collection_id, current_index);21592160 2161 let new_balance = <Balance<T>>::get(collection_id, &owner.as_sub())2162 .checked_add(value)2163 .unwrap();2164 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);2165 }21662167 fn add_token_index(collection_id: CollectionId, item_index: TokenId, owner: &T::CrossAccountId) -> DispatchResult {2168 2169 if <AccountItemCount<T>>::contains_key(owner.as_sub()) {21702171 2172 let count = <AccountItemCount<T>>::get(owner.as_sub());2173 ensure!(count < ChainLimit::get().account_token_ownership_limit, Error::<T>::AddressOwnershipLimitExceeded);21742175 <AccountItemCount<T>>::insert(owner.as_sub(), count2176 .checked_add(1)2177 .ok_or(Error::<T>::NumOverflow)?);2178 }2179 else {2180 <AccountItemCount<T>>::insert(owner.as_sub(), 1);2181 }21822183 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.as_sub());2184 if list_exists {2185 let mut list = <AddressTokens<T>>::get(collection_id, owner.as_sub());2186 let item_contains = list.contains(&item_index.clone());21872188 if !item_contains {2189 list.push(item_index.clone());2190 }21912192 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), list);2193 } else {2194 let mut itm = Vec::new();2195 itm.push(item_index.clone());2196 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), itm);2197 }21982199 Ok(())2200 }22012202 fn remove_token_index(2203 collection_id: CollectionId,2204 item_index: TokenId,2205 owner: &T::CrossAccountId,2206 ) -> DispatchResult {22072208 2209 <AccountItemCount<T>>::insert(owner.as_sub(), 2210 <AccountItemCount<T>>::get(owner.as_sub())2211 .checked_sub(1)2212 .ok_or(Error::<T>::NumOverflow)?);221322142215 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.as_sub());2216 if list_exists {2217 let mut list = <AddressTokens<T>>::get(collection_id, owner.as_sub());2218 let item_contains = list.contains(&item_index.clone());22192220 if item_contains {2221 list.retain(|&item| item != item_index);2222 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), list);2223 }2224 }22252226 Ok(())2227 }22282229 fn move_token_index(2230 collection_id: CollectionId,2231 item_index: TokenId,2232 old_owner: &T::CrossAccountId,2233 new_owner: &T::CrossAccountId,2234 ) -> DispatchResult {2235 Self::remove_token_index(collection_id, item_index, old_owner)?;2236 Self::add_token_index(collection_id, item_index, new_owner)?;22372238 Ok(())2239 }2240}22412242sp_api::decl_runtime_apis! {2243 pub trait NftApi {2244 2245 fn eth_contract_code(account: H160) -> Option<Vec<u8>>;2246 }2247}