12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63 ensure,64 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65 weights::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionFlags,74 RpcCollectionFlags,75 CollectionId,76 CreateItemData,77 MAX_TOKEN_PREFIX_LENGTH,78 COLLECTION_ADMINS_LIMIT,79 TokenId,80 TokenChild,81 CollectionStats,82 MAX_TOKEN_OWNERSHIP,83 CollectionMode,84 NFT_SPONSOR_TRANSFER_TIMEOUT,85 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87 MAX_SPONSOR_TIMEOUT,88 CUSTOM_DATA_LIMIT,89 CollectionLimits,90 CreateCollectionData,91 SponsorshipState,92 CreateItemExData,93 SponsoringRateLimit,94 budget::Budget,95 PhantomType,96 Property,97 Properties,98 PropertiesPermissionMap,99 PropertyKey,100 PropertyValue,101 PropertyPermission,102 PropertiesError,103 PropertyKeyPermission,104 TokenData,105 TrySetProperty,106 PropertyScope,107 108 RmrkCollectionInfo,109 RmrkInstanceInfo,110 RmrkResourceInfo,111 RmrkPropertyInfo,112 RmrkBaseInfo,113 RmrkPartType,114 RmrkBoundedTheme,115 RmrkNftChild,116 CollectionPermissions,117};118119pub use pallet::*;120use sp_core::H160;121use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};122#[cfg(feature = "runtime-benchmarks")]123pub mod benchmarking;124pub mod dispatch;125pub mod erc;126pub mod eth;127pub mod weights;128129130pub type SelfWeightOf<T> = <T as Config>::WeightInfo;131132133134135136137138#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]139pub struct CollectionHandle<T: Config> {140 141 pub id: CollectionId,142 collection: Collection<T::AccountId>,143 144 pub recorder: SubstrateRecorder<T>,145}146147impl<T: Config> WithRecorder<T> for CollectionHandle<T> {148 fn recorder(&self) -> &SubstrateRecorder<T> {149 &self.recorder150 }151 fn into_recorder(self) -> SubstrateRecorder<T> {152 self.recorder153 }154}155156impl<T: Config> CollectionHandle<T> {157 158 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {159 <CollectionById<T>>::get(id).map(|collection| Self {160 id,161 collection,162 recorder: SubstrateRecorder::new(gas_limit),163 })164 }165166 167 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {168 <CollectionById<T>>::get(id).map(|collection| Self {169 id,170 collection,171 recorder,172 })173 }174175 176 177 pub fn new(id: CollectionId) -> Option<Self> {178 Self::new_with_gas_limit(id, u64::MAX)179 }180181 182 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {183 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)184 }185186 187 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {188 self.recorder189 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(190 <T as frame_system::Config>::DbWeight::get()191 .read192 .saturating_mul(reads),193 )))194 }195196 197 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {198 self.recorder199 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(200 <T as frame_system::Config>::DbWeight::get()201 .write202 .saturating_mul(writes),203 )))204 }205206 207 pub fn consume_store_reads_and_writes(208 &self,209 reads: u64,210 writes: u64,211 ) -> evm_coder::execution::Result<()> {212 let weight = <T as frame_system::Config>::DbWeight::get();213 let reads = weight.read.saturating_mul(reads);214 let writes = weight.read.saturating_mul(writes);215 self.recorder216 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(217 reads.saturating_add(writes),218 )))219 }220221 222 pub fn save(&self) -> DispatchResult {223 <CollectionById<T>>::insert(self.id, &self.collection);224 Ok(())225 }226227 228 229 230 231 232 pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {233 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);234 Ok(())235 }236237 238 239 240 241 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {242 if self.collection.sponsorship.pending_sponsor() != Some(sender) {243 return Ok(false);244 }245246 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());247 Ok(true)248 }249250 251 pub fn remove_sponsor(&mut self) -> DispatchResult {252 self.collection.sponsorship = SponsorshipState::Disabled;253 Ok(())254 }255256 257 258 pub fn check_is_internal(&self) -> DispatchResult {259 if self.flags.external {260 return Err(<Error<T>>::CollectionIsExternal)?;261 }262263 Ok(())264 }265266 267 268 pub fn check_is_external(&self) -> DispatchResult {269 if !self.flags.external {270 return Err(<Error<T>>::CollectionIsInternal)?;271 }272273 Ok(())274 }275}276277impl<T: Config> Deref for CollectionHandle<T> {278 type Target = Collection<T::AccountId>;279280 fn deref(&self) -> &Self::Target {281 &self.collection282 }283}284285impl<T: Config> DerefMut for CollectionHandle<T> {286 fn deref_mut(&mut self) -> &mut Self::Target {287 &mut self.collection288 }289}290291impl<T: Config> CollectionHandle<T> {292 293 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {294 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);295 Ok(())296 }297298 299 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {300 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))301 }302303 304 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {305 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);306 Ok(())307 }308309 310 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {311 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)312 }313314 315 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {316 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)317 }318319 320 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {321 ensure!(322 <Allowlist<T>>::get((self.id, user)),323 <Error<T>>::AddressNotInAllowlist324 );325 Ok(())326 }327328 329 330 331 fn set_owner_internal(332 &mut self,333 caller: T::CrossAccountId,334 new_owner: T::CrossAccountId,335 ) -> DispatchResult {336 self.check_is_owner(&caller)?;337 self.collection.owner = new_owner.as_sub().clone();338 self.save()339 }340}341342#[frame_support::pallet]343pub mod pallet {344 use super::*;345 use pallet_evm::account;346 use dispatch::CollectionDispatch;347 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};348 use frame_system::pallet_prelude::*;349 use frame_support::traits::Currency;350 use up_data_structs::{TokenId, mapping::TokenAddressMapping};351 use scale_info::TypeInfo;352 use weights::WeightInfo;353354 #[pallet::config]355 pub trait Config:356 frame_system::Config357 + pallet_evm_coder_substrate::Config358 + pallet_evm::Config359 + TypeInfo360 + account::Config361 {362 363 type WeightInfo: WeightInfo;364365 366 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;367368 369 type Currency: Currency<Self::AccountId>;370371 372 #[pallet::constant]373 type CollectionCreationPrice: Get<374 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,375 >;376377 378 type CollectionDispatch: CollectionDispatch<Self>;379380 381 type TreasuryAccountId: Get<Self::AccountId>;382383 384 type ContractAddress: Get<H160>;385386 387 type EvmTokenAddressMapping: TokenAddressMapping<H160>;388389 390 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;391 }392393 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);394395 #[pallet::pallet]396 #[pallet::storage_version(STORAGE_VERSION)]397 #[pallet::generate_store(pub(super) trait Store)]398 pub struct Pallet<T>(_);399400 #[pallet::extra_constants]401 impl<T: Config> Pallet<T> {402 403 pub fn collection_admins_limit() -> u32 {404 COLLECTION_ADMINS_LIMIT405 }406 }407408 #[pallet::event]409 #[pallet::generate_deposit(pub fn deposit_event)]410 pub enum Event<T: Config> {411 412 CollectionCreated(413 414 CollectionId,415 416 u8,417 418 T::AccountId,419 ),420421 422 CollectionDestroyed(423 424 CollectionId,425 ),426427 428 ItemCreated(429 430 CollectionId,431 432 TokenId,433 434 T::CrossAccountId,435 436 u128,437 ),438439 440 ItemDestroyed(441 442 CollectionId,443 444 TokenId,445 446 T::CrossAccountId,447 448 u128,449 ),450451 452 Transfer(453 454 CollectionId,455 456 TokenId,457 458 T::CrossAccountId,459 460 T::CrossAccountId,461 462 u128,463 ),464465 466 Approved(467 468 CollectionId,469 470 TokenId,471 472 T::CrossAccountId,473 474 T::CrossAccountId,475 476 u128,477 ),478479 480 CollectionPropertySet(481 482 CollectionId,483 484 PropertyKey,485 ),486487 488 CollectionPropertyDeleted(489 490 CollectionId,491 492 PropertyKey,493 ),494495 496 TokenPropertySet(497 498 CollectionId,499 500 TokenId,501 502 PropertyKey,503 ),504505 506 TokenPropertyDeleted(507 508 CollectionId,509 510 TokenId,511 512 PropertyKey,513 ),514515 516 PropertyPermissionSet(517 518 CollectionId,519 520 PropertyKey,521 ),522 }523524 #[pallet::error]525 pub enum Error<T> {526 527 CollectionNotFound,528 529 MustBeTokenOwner,530 531 NoPermission,532 533 CantDestroyNotEmptyCollection,534 535 PublicMintingNotAllowed,536 537 AddressNotInAllowlist,538539 540 CollectionNameLimitExceeded,541 542 CollectionDescriptionLimitExceeded,543 544 CollectionTokenPrefixLimitExceeded,545 546 TotalCollectionsLimitExceeded,547 548 CollectionAdminCountExceeded,549 550 CollectionLimitBoundsExceeded,551 552 OwnerPermissionsCantBeReverted,553 554 TransferNotAllowed,555 556 AccountTokenLimitExceeded,557 558 CollectionTokenLimitExceeded,559 560 MetadataFlagFrozen,561562 563 TokenNotFound,564 565 TokenValueTooLow,566 567 ApprovedValueTooLow,568 569 CantApproveMoreThanOwned,570571 572 AddressIsZero,573574 575 UnsupportedOperation,576577 578 NotSufficientFounds,579580 581 UserIsNotAllowedToNest,582 583 SourceCollectionIsNotAllowedToNest,584585 586 CollectionFieldSizeExceeded,587588 589 NoSpaceForProperty,590591 592 PropertyLimitReached,593594 595 PropertyKeyIsTooLong,596597 598 InvalidCharacterInPropertyKey,599600 601 EmptyPropertyKey,602603 604 CollectionIsExternal,605606 607 CollectionIsInternal,608 }609610 611 #[pallet::storage]612 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;613614 615 #[pallet::storage]616 pub type DestroyedCollectionCount<T> =617 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;618619 620 #[pallet::storage]621 pub type CollectionById<T> = StorageMap<622 Hasher = Blake2_128Concat,623 Key = CollectionId,624 Value = Collection<<T as frame_system::Config>::AccountId>,625 QueryKind = OptionQuery,626 >;627628 629 #[pallet::storage]630 #[pallet::getter(fn collection_properties)]631 pub type CollectionProperties<T> = StorageMap<632 Hasher = Blake2_128Concat,633 Key = CollectionId,634 Value = Properties,635 QueryKind = ValueQuery,636 OnEmpty = up_data_structs::CollectionProperties,637 >;638639 640 #[pallet::storage]641 #[pallet::getter(fn property_permissions)]642 pub type CollectionPropertyPermissions<T> = StorageMap<643 Hasher = Blake2_128Concat,644 Key = CollectionId,645 Value = PropertiesPermissionMap,646 QueryKind = ValueQuery,647 >;648649 650 #[pallet::storage]651 pub type AdminAmount<T> = StorageMap<652 Hasher = Blake2_128Concat,653 Key = CollectionId,654 Value = u32,655 QueryKind = ValueQuery,656 >;657658 659 #[pallet::storage]660 pub type IsAdmin<T: Config> = StorageNMap<661 Key = (662 Key<Blake2_128Concat, CollectionId>,663 Key<Blake2_128Concat, T::CrossAccountId>,664 ),665 Value = bool,666 QueryKind = ValueQuery,667 >;668669 670 #[pallet::storage]671 pub type Allowlist<T: Config> = StorageNMap<672 Key = (673 Key<Blake2_128Concat, CollectionId>,674 Key<Blake2_128Concat, T::CrossAccountId>,675 ),676 Value = bool,677 QueryKind = ValueQuery,678 >;679680 681 #[pallet::storage]682 pub type DummyStorageValue<T: Config> = StorageValue<683 Value = (684 CollectionStats,685 CollectionId,686 TokenId,687 TokenChild,688 PhantomType<(689 TokenData<T::CrossAccountId>,690 RpcCollection<T::AccountId>,691 692 RmrkCollectionInfo<T::AccountId>,693 RmrkInstanceInfo<T::AccountId>,694 RmrkResourceInfo,695 RmrkPropertyInfo,696 RmrkBaseInfo<T::AccountId>,697 RmrkPartType,698 RmrkBoundedTheme,699 RmrkNftChild,700 )>,701 ),702 QueryKind = OptionQuery,703 >;704705 #[pallet::hooks]706 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {707 fn on_runtime_upgrade() -> Weight {708 StorageVersion::new(1).put::<Pallet<T>>();709710 Weight::zero()711 }712 }713}714715impl<T: Config> Pallet<T> {716 717 718 719 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {720 ensure!(721 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,722 <Error<T>>::AddressIsZero723 );724 Ok(())725 }726727 728 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {729 <IsAdmin<T>>::iter_prefix((collection,))730 .map(|(a, _)| a)731 .collect()732 }733734 735 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {736 <Allowlist<T>>::iter_prefix((collection,))737 .map(|(a, _)| a)738 .collect()739 }740741 742 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {743 <Allowlist<T>>::get((collection, user))744 }745746 747 pub fn collection_stats() -> CollectionStats {748 let created = <CreatedCollectionCount<T>>::get();749 let destroyed = <DestroyedCollectionCount<T>>::get();750 CollectionStats {751 created: created.0,752 destroyed: destroyed.0,753 alive: created.0 - destroyed.0,754 }755 }756757 758 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {759 let collection = <CollectionById<T>>::get(collection)?;760 let limits = collection.limits;761 let effective_limits = CollectionLimits {762 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),763 sponsored_data_size: Some(limits.sponsored_data_size()),764 sponsored_data_rate_limit: Some(765 limits766 .sponsored_data_rate_limit767 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),768 ),769 token_limit: Some(limits.token_limit()),770 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(771 match collection.mode {772 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,773 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,774 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,775 },776 )),777 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),778 owner_can_transfer: Some(limits.owner_can_transfer()),779 owner_can_destroy: Some(limits.owner_can_destroy()),780 transfers_enabled: Some(limits.transfers_enabled()),781 };782783 Some(effective_limits)784 }785786 787 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {788 let Collection {789 name,790 description,791 owner,792 mode,793 token_prefix,794 sponsorship,795 limits,796 permissions,797 flags,798 } = <CollectionById<T>>::get(collection)?;799800 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)801 .into_iter()802 .map(|(key, permission)| PropertyKeyPermission { key, permission })803 .collect();804805 let properties = <CollectionProperties<T>>::get(collection)806 .into_iter()807 .map(|(key, value)| Property { key, value })808 .collect();809810 let permissions = CollectionPermissions {811 access: Some(permissions.access()),812 mint_mode: Some(permissions.mint_mode()),813 nesting: Some(permissions.nesting().clone()),814 };815816 Some(RpcCollection {817 name: name.into_inner(),818 description: description.into_inner(),819 owner,820 mode,821 token_prefix: token_prefix.into_inner(),822 sponsorship,823 limits,824 permissions,825 token_property_permissions,826 properties,827 read_only: flags.external,828829 flags: RpcCollectionFlags {830 foreign: flags.foreign,831 erc721metadata: flags.erc721metadata,832 },833 })834 }835}836837macro_rules! limit_default {838 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{839 $(840 if let Some($new) = $new.$field {841 let $old = $old.$field($($arg)?);842 let _ = $new;843 let _ = $old;844 $check845 } else {846 $new.$field = $old.$field847 }848 )*849 }};850}851macro_rules! limit_default_clone {852 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{853 $(854 if let Some($new) = $new.$field.clone() {855 let $old = $old.$field($($arg)?);856 let _ = $new;857 let _ = $old;858 $check859 } else {860 $new.$field = $old.$field.clone()861 }862 )*863 }};864}865866impl<T: Config> Pallet<T> {867 868 869 870 871 872 pub fn init_collection(873 owner: T::CrossAccountId,874 payer: T::CrossAccountId,875 data: CreateCollectionData<T::AccountId>,876 flags: CollectionFlags,877 ) -> Result<CollectionId, DispatchError> {878 {879 ensure!(880 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,881 Error::<T>::CollectionTokenPrefixLimitExceeded882 );883 }884885 let created_count = <CreatedCollectionCount<T>>::get()886 .0887 .checked_add(1)888 .ok_or(ArithmeticError::Overflow)?;889 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;890 let id = CollectionId(created_count);891892 893 ensure!(894 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,895 <Error<T>>::TotalCollectionsLimitExceeded896 );897898 899900 let collection = Collection {901 owner: owner.as_sub().clone(),902 name: data.name,903 mode: data.mode.clone(),904 description: data.description,905 token_prefix: data.token_prefix,906 sponsorship: data907 .pending_sponsor908 .map(SponsorshipState::Unconfirmed)909 .unwrap_or_default(),910 limits: data911 .limits912 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))913 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,914 permissions: data915 .permissions916 .map(|permissions| {917 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)918 })919 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,920 flags,921 };922923 let mut collection_properties = up_data_structs::CollectionProperties::get();924 collection_properties925 .try_set_from_iter(data.properties.into_iter())926 .map_err(<Error<T>>::from)?;927928 CollectionProperties::<T>::insert(id, collection_properties);929930 let mut token_props_permissions = PropertiesPermissionMap::new();931 token_props_permissions932 .try_set_from_iter(data.token_property_permissions.into_iter())933 .map_err(<Error<T>>::from)?;934935 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);936937 938 {939 let mut imbalance =940 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();941 imbalance.subsume(942 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(943 &T::TreasuryAccountId::get(),944 T::CollectionCreationPrice::get(),945 ),946 );947 <T as Config>::Currency::settle(948 payer.as_sub(),949 imbalance,950 WithdrawReasons::TRANSFER,951 ExistenceRequirement::KeepAlive,952 )953 .map_err(|_| Error::<T>::NotSufficientFounds)?;954 }955956 <CreatedCollectionCount<T>>::put(created_count);957 <Pallet<T>>::deposit_event(Event::CollectionCreated(958 id,959 data.mode.id(),960 owner.as_sub().clone(),961 ));962 <PalletEvm<T>>::deposit_log(963 erc::CollectionHelpersEvents::CollectionCreated {964 owner: *owner.as_eth(),965 collection_id: eth::collection_id_to_address(id),966 }967 .to_log(T::ContractAddress::get()),968 );969 <CollectionById<T>>::insert(id, collection);970 Ok(id)971 }972973 974 975 976 977 pub fn destroy_collection(978 collection: CollectionHandle<T>,979 sender: &T::CrossAccountId,980 ) -> DispatchResult {981 ensure!(982 collection.limits.owner_can_destroy(),983 <Error<T>>::NoPermission,984 );985 collection.check_is_owner(sender)?;986987 let destroyed_collections = <DestroyedCollectionCount<T>>::get()988 .0989 .checked_add(1)990 .ok_or(ArithmeticError::Overflow)?;991992 993994 <DestroyedCollectionCount<T>>::put(destroyed_collections);995 <CollectionById<T>>::remove(collection.id);996 <AdminAmount<T>>::remove(collection.id);997 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);998 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);999 <CollectionProperties<T>>::remove(collection.id);10001001 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));1002 Ok(())1003 }10041005 1006 1007 1008 1009 1010 pub fn set_collection_property(1011 collection: &CollectionHandle<T>,1012 sender: &T::CrossAccountId,1013 property: Property,1014 ) -> DispatchResult {1015 collection.check_is_owner_or_admin(sender)?;10161017 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1018 let property = property.clone();1019 properties.try_set(property.key, property.value)1020 })1021 .map_err(<Error<T>>::from)?;10221023 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));10241025 Ok(())1026 }10271028 1029 1030 1031 1032 1033 pub fn set_scoped_collection_property(1034 collection_id: CollectionId,1035 scope: PropertyScope,1036 property: Property,1037 ) -> DispatchResult {1038 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1039 properties.try_scoped_set(scope, property.key, property.value)1040 })1041 .map_err(<Error<T>>::from)?;10421043 Ok(())1044 }10451046 1047 1048 1049 1050 1051 pub fn set_scoped_collection_properties(1052 collection_id: CollectionId,1053 scope: PropertyScope,1054 properties: impl Iterator<Item = Property>,1055 ) -> DispatchResult {1056 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1057 stored_properties.try_scoped_set_from_iter(scope, properties)1058 })1059 .map_err(<Error<T>>::from)?;10601061 Ok(())1062 }10631064 1065 1066 1067 1068 1069 #[transactional]1070 pub fn set_collection_properties(1071 collection: &CollectionHandle<T>,1072 sender: &T::CrossAccountId,1073 properties: Vec<Property>,1074 ) -> DispatchResult {1075 for property in properties {1076 Self::set_collection_property(collection, sender, property)?;1077 }10781079 Ok(())1080 }10811082 1083 1084 1085 1086 1087 pub fn delete_collection_property(1088 collection: &CollectionHandle<T>,1089 sender: &T::CrossAccountId,1090 property_key: PropertyKey,1091 ) -> DispatchResult {1092 collection.check_is_owner_or_admin(sender)?;10931094 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1095 properties.remove(&property_key)1096 })1097 .map_err(<Error<T>>::from)?;10981099 Self::deposit_event(Event::CollectionPropertyDeleted(1100 collection.id,1101 property_key,1102 ));11031104 Ok(())1105 }11061107 1108 1109 1110 1111 1112 #[transactional]1113 pub fn delete_collection_properties(1114 collection: &CollectionHandle<T>,1115 sender: &T::CrossAccountId,1116 property_keys: Vec<PropertyKey>,1117 ) -> DispatchResult {1118 for key in property_keys {1119 Self::delete_collection_property(collection, sender, key)?;1120 }11211122 Ok(())1123 }11241125 1126 1127 1128 1129 1130 1131 pub fn set_property_permission_unchecked(1132 collection: CollectionId,1133 property_permission: PropertyKeyPermission,1134 ) -> DispatchResult {1135 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1136 permissions.try_set(property_permission.key, property_permission.permission)1137 })1138 .map_err(<Error<T>>::from)?;1139 Ok(())1140 }11411142 1143 1144 1145 1146 1147 pub fn set_property_permission(1148 collection: &CollectionHandle<T>,1149 sender: &T::CrossAccountId,1150 property_permission: PropertyKeyPermission,1151 ) -> DispatchResult {1152 Self::set_scoped_property_permission(1153 collection,1154 sender,1155 PropertyScope::None,1156 property_permission,1157 )1158 }11591160 1161 1162 1163 1164 1165 1166 pub fn set_scoped_property_permission(1167 collection: &CollectionHandle<T>,1168 sender: &T::CrossAccountId,1169 scope: PropertyScope,1170 property_permission: PropertyKeyPermission,1171 ) -> DispatchResult {1172 collection.check_is_owner_or_admin(sender)?;11731174 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1175 let current_permission = all_permissions.get(&property_permission.key);1176 if matches![1177 current_permission,1178 Some(PropertyPermission { mutable: false, .. })1179 ] {1180 return Err(<Error<T>>::NoPermission.into());1181 }11821183 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1184 let property_permission = property_permission.clone();1185 permissions.try_scoped_set(1186 scope,1187 property_permission.key,1188 property_permission.permission,1189 )1190 })1191 .map_err(<Error<T>>::from)?;11921193 Self::deposit_event(Event::PropertyPermissionSet(1194 collection.id,1195 property_permission.key,1196 ));11971198 Ok(())1199 }12001201 1202 1203 1204 1205 1206 #[transactional]1207 pub fn set_token_property_permissions(1208 collection: &CollectionHandle<T>,1209 sender: &T::CrossAccountId,1210 property_permissions: Vec<PropertyKeyPermission>,1211 ) -> DispatchResult {1212 Self::set_scoped_token_property_permissions(1213 collection,1214 sender,1215 PropertyScope::None,1216 property_permissions,1217 )1218 }12191220 1221 1222 1223 1224 1225 1226 #[transactional]1227 pub fn set_scoped_token_property_permissions(1228 collection: &CollectionHandle<T>,1229 sender: &T::CrossAccountId,1230 scope: PropertyScope,1231 property_permissions: Vec<PropertyKeyPermission>,1232 ) -> DispatchResult {1233 for prop_pemission in property_permissions {1234 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1235 }12361237 Ok(())1238 }12391240 1241 pub fn get_collection_property(1242 collection_id: CollectionId,1243 key: &PropertyKey,1244 ) -> Option<PropertyValue> {1245 Self::collection_properties(collection_id).get(key).cloned()1246 }12471248 1249 pub fn bytes_keys_to_property_keys(1250 keys: Vec<Vec<u8>>,1251 ) -> Result<Vec<PropertyKey>, DispatchError> {1252 keys.into_iter()1253 .map(|key| -> Result<PropertyKey, DispatchError> {1254 key.try_into()1255 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1256 })1257 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1258 }12591260 1261 pub fn filter_collection_properties(1262 collection_id: CollectionId,1263 keys: Option<Vec<PropertyKey>>,1264 ) -> Result<Vec<Property>, DispatchError> {1265 let properties = Self::collection_properties(collection_id);12661267 let properties = keys1268 .map(|keys| {1269 keys.into_iter()1270 .filter_map(|key| {1271 properties.get(&key).map(|value| Property {1272 key,1273 value: value.clone(),1274 })1275 })1276 .collect()1277 })1278 .unwrap_or_else(|| {1279 properties1280 .into_iter()1281 .map(|(key, value)| Property { key, value })1282 .collect()1283 });12841285 Ok(properties)1286 }12871288 1289 pub fn filter_property_permissions(1290 collection_id: CollectionId,1291 keys: Option<Vec<PropertyKey>>,1292 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1293 let permissions = Self::property_permissions(collection_id);12941295 let key_permissions = keys1296 .map(|keys| {1297 keys.into_iter()1298 .filter_map(|key| {1299 permissions1300 .get(&key)1301 .map(|permission| PropertyKeyPermission {1302 key,1303 permission: permission.clone(),1304 })1305 })1306 .collect()1307 })1308 .unwrap_or_else(|| {1309 permissions1310 .into_iter()1311 .map(|(key, permission)| PropertyKeyPermission { key, permission })1312 .collect()1313 });13141315 Ok(key_permissions)1316 }13171318 1319 1320 1321 pub fn toggle_allowlist(1322 collection: &CollectionHandle<T>,1323 sender: &T::CrossAccountId,1324 user: &T::CrossAccountId,1325 allowed: bool,1326 ) -> DispatchResult {1327 collection.check_is_owner_or_admin(sender)?;13281329 13301331 if allowed {1332 <Allowlist<T>>::insert((collection.id, user), true);1333 } else {1334 <Allowlist<T>>::remove((collection.id, user));1335 }13361337 Ok(())1338 }13391340 1341 1342 1343 pub fn toggle_admin(1344 collection: &CollectionHandle<T>,1345 sender: &T::CrossAccountId,1346 user: &T::CrossAccountId,1347 admin: bool,1348 ) -> DispatchResult {1349 collection.check_is_owner(sender)?;13501351 let was_admin = <IsAdmin<T>>::get((collection.id, user));1352 if was_admin == admin {1353 return Ok(());1354 }1355 let amount = <AdminAmount<T>>::get(collection.id);13561357 if admin {1358 let amount = amount1359 .checked_add(1)1360 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1361 ensure!(1362 amount <= Self::collection_admins_limit(),1363 <Error<T>>::CollectionAdminCountExceeded,1364 );13651366 13671368 <AdminAmount<T>>::insert(collection.id, amount);1369 <IsAdmin<T>>::insert((collection.id, user), true);1370 } else {1371 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1372 <IsAdmin<T>>::remove((collection.id, user));1373 }13741375 Ok(())1376 }13771378 1379 pub fn clamp_limits(1380 mode: CollectionMode,1381 old_limit: &CollectionLimits,1382 mut new_limit: CollectionLimits,1383 ) -> Result<CollectionLimits, DispatchError> {1384 let limits = old_limit;1385 limit_default!(old_limit, new_limit,1386 account_token_ownership_limit => ensure!(1387 new_limit <= MAX_TOKEN_OWNERSHIP,1388 <Error<T>>::CollectionLimitBoundsExceeded,1389 ),1390 sponsored_data_size => ensure!(1391 new_limit <= CUSTOM_DATA_LIMIT,1392 <Error<T>>::CollectionLimitBoundsExceeded,1393 ),13941395 sponsored_data_rate_limit => {},1396 token_limit => ensure!(1397 old_limit >= new_limit && new_limit > 0,1398 <Error<T>>::CollectionTokenLimitExceeded1399 ),14001401 sponsor_transfer_timeout(match mode {1402 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1403 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1404 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1405 }) => ensure!(1406 new_limit <= MAX_SPONSOR_TIMEOUT,1407 <Error<T>>::CollectionLimitBoundsExceeded,1408 ),1409 sponsor_approve_timeout => {},1410 owner_can_transfer => ensure!(1411 !limits.owner_can_transfer_instaled() ||1412 old_limit || !new_limit,1413 <Error<T>>::OwnerPermissionsCantBeReverted,1414 ),1415 owner_can_destroy => ensure!(1416 old_limit || !new_limit,1417 <Error<T>>::OwnerPermissionsCantBeReverted,1418 ),1419 transfers_enabled => {},1420 );1421 Ok(new_limit)1422 }14231424 1425 pub fn clamp_permissions(1426 _mode: CollectionMode,1427 old_permission: &CollectionPermissions,1428 mut new_permission: CollectionPermissions,1429 ) -> Result<CollectionPermissions, DispatchError> {1430 limit_default_clone!(old_permission, new_permission,1431 access => {},1432 mint_mode => {},1433 nesting => { },1434 );1435 Ok(new_permission)1436 }1437}143814391440#[macro_export]1441macro_rules! unsupported {1442 ($runtime:path) => {1443 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1444 };1445}144614471448pub trait CommonWeightInfo<CrossAccountId> {1449 1450 fn create_item() -> Weight;14511452 1453 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14541455 1456 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14571458 1459 fn burn_item() -> Weight;14601461 1462 1463 1464 fn set_collection_properties(amount: u32) -> Weight;14651466 1467 1468 1469 fn delete_collection_properties(amount: u32) -> Weight;14701471 1472 1473 1474 fn set_token_properties(amount: u32) -> Weight;14751476 1477 1478 1479 fn delete_token_properties(amount: u32) -> Weight;14801481 1482 1483 1484 fn set_token_property_permissions(amount: u32) -> Weight;14851486 1487 fn transfer() -> Weight;14881489 1490 fn approve() -> Weight;14911492 1493 fn transfer_from() -> Weight;14941495 1496 fn burn_from() -> Weight;14971498 1499 1500 1501 1502 fn burn_recursively_self_raw() -> Weight;15031504 1505 1506 1507 fn burn_recursively_breadth_raw(amount: u32) -> Weight;15081509 1510 1511 1512 1513 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1514 Self::burn_recursively_self_raw()1515 .saturating_mul(max_selfs.max(1) as u64)1516 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1517 }15181519 1520 fn token_owner() -> Weight;1521}152215231524pub trait RefungibleExtensionsWeightInfo {1525 1526 fn repartition() -> Weight;1527}152815291530153115321533pub trait CommonCollectionOperations<T: Config> {1534 1535 1536 1537 1538 1539 1540 fn create_item(1541 &self,1542 sender: T::CrossAccountId,1543 to: T::CrossAccountId,1544 data: CreateItemData,1545 nesting_budget: &dyn Budget,1546 ) -> DispatchResultWithPostInfo;15471548 1549 1550 1551 1552 1553 1554 fn create_multiple_items(1555 &self,1556 sender: T::CrossAccountId,1557 to: T::CrossAccountId,1558 data: Vec<CreateItemData>,1559 nesting_budget: &dyn Budget,1560 ) -> DispatchResultWithPostInfo;15611562 1563 1564 1565 1566 1567 1568 fn create_multiple_items_ex(1569 &self,1570 sender: T::CrossAccountId,1571 data: CreateItemExData<T::CrossAccountId>,1572 nesting_budget: &dyn Budget,1573 ) -> DispatchResultWithPostInfo;15741575 1576 1577 1578 1579 1580 fn burn_item(1581 &self,1582 sender: T::CrossAccountId,1583 token: TokenId,1584 amount: u128,1585 ) -> DispatchResultWithPostInfo;15861587 1588 1589 1590 1591 1592 1593 fn burn_item_recursively(1594 &self,1595 sender: T::CrossAccountId,1596 token: TokenId,1597 self_budget: &dyn Budget,1598 breadth_budget: &dyn Budget,1599 ) -> DispatchResultWithPostInfo;16001601 1602 1603 1604 1605 fn set_collection_properties(1606 &self,1607 sender: T::CrossAccountId,1608 properties: Vec<Property>,1609 ) -> DispatchResultWithPostInfo;16101611 1612 1613 1614 1615 fn delete_collection_properties(1616 &self,1617 sender: &T::CrossAccountId,1618 property_keys: Vec<PropertyKey>,1619 ) -> DispatchResultWithPostInfo;16201621 1622 1623 1624 1625 1626 1627 1628 1629 1630 fn set_token_properties(1631 &self,1632 sender: T::CrossAccountId,1633 token_id: TokenId,1634 properties: Vec<Property>,1635 budget: &dyn Budget,1636 ) -> DispatchResultWithPostInfo;16371638 1639 1640 1641 1642 1643 1644 1645 1646 1647 fn delete_token_properties(1648 &self,1649 sender: T::CrossAccountId,1650 token_id: TokenId,1651 property_keys: Vec<PropertyKey>,1652 budget: &dyn Budget,1653 ) -> DispatchResultWithPostInfo;16541655 1656 1657 1658 1659 1660 1661 fn set_token_property_permissions(1662 &self,1663 sender: &T::CrossAccountId,1664 property_permissions: Vec<PropertyKeyPermission>,1665 ) -> DispatchResultWithPostInfo;16661667 1668 1669 1670 1671 1672 1673 1674 fn transfer(1675 &self,1676 sender: T::CrossAccountId,1677 to: T::CrossAccountId,1678 token: TokenId,1679 amount: u128,1680 budget: &dyn Budget,1681 ) -> DispatchResultWithPostInfo;16821683 1684 1685 1686 1687 1688 1689 fn approve(1690 &self,1691 sender: T::CrossAccountId,1692 spender: T::CrossAccountId,1693 token: TokenId,1694 amount: u128,1695 ) -> DispatchResultWithPostInfo;16961697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 fn transfer_from(1708 &self,1709 sender: T::CrossAccountId,1710 from: T::CrossAccountId,1711 to: T::CrossAccountId,1712 token: TokenId,1713 amount: u128,1714 budget: &dyn Budget,1715 ) -> DispatchResultWithPostInfo;17161717 1718 1719 1720 1721 1722 1723 1724 1725 1726 fn burn_from(1727 &self,1728 sender: T::CrossAccountId,1729 from: T::CrossAccountId,1730 token: TokenId,1731 amount: u128,1732 budget: &dyn Budget,1733 ) -> DispatchResultWithPostInfo;17341735 1736 1737 1738 1739 1740 1741 fn check_nesting(1742 &self,1743 sender: T::CrossAccountId,1744 from: (CollectionId, TokenId),1745 under: TokenId,1746 budget: &dyn Budget,1747 ) -> DispatchResult;17481749 1750 1751 1752 1753 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17541755 1756 1757 1758 1759 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17601761 1762 1763 1764 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17651766 1767 fn collection_tokens(&self) -> Vec<TokenId>;17681769 1770 1771 1772 fn token_exists(&self, token: TokenId) -> bool;17731774 1775 fn last_token_id(&self) -> TokenId;17761777 1778 1779 1780 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17811782 1783 1784 1785 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;17861787 1788 1789 1790 1791 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17921793 1794 1795 1796 1797 1798 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17991800 1801 fn total_supply(&self) -> u32;18021803 1804 1805 1806 fn account_balance(&self, account: T::CrossAccountId) -> u32;18071808 1809 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;18101811 1812 fn total_pieces(&self, token: TokenId) -> Option<u128>;18131814 1815 1816 1817 1818 1819 fn allowance(1820 &self,1821 sender: T::CrossAccountId,1822 spender: T::CrossAccountId,1823 token: TokenId,1824 ) -> u128;18251826 1827 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1828}182918301831pub trait RefungibleExtensions<T>1832where1833 T: Config,1834{1835 1836 1837 1838 1839 1840 1841 1842 fn repartition(1843 &self,1844 sender: &T::CrossAccountId,1845 token: TokenId,1846 amount: u128,1847 ) -> DispatchResultWithPostInfo;1848}18491850185118521853pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1854 let post_info = PostDispatchInfo {1855 actual_weight: Some(weight),1856 pays_fee: Pays::Yes,1857 };1858 match res {1859 Ok(()) => Ok(post_info),1860 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1861 }1862}18631864impl<T: Config> From<PropertiesError> for Error<T> {1865 fn from(error: PropertiesError) -> Self {1866 match error {1867 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1868 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1869 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1870 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1871 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1872 }1873 }1874}