difftreelog
refactor Remove variable data from tokens
in: master
23 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -71,13 +71,6 @@
token: TokenId,
at: Option<BlockHash>,
) -> Result<Vec<u8>>;
- #[rpc(name = "unique_variableMetadata")]
- fn variable_metadata(
- &self,
- collection: CollectionId,
- token: TokenId,
- at: Option<BlockHash>,
- ) -> Result<Vec<u8>>;
#[rpc(name = "unique_collectionProperties")]
fn collection_properties(
@@ -279,7 +272,6 @@
);
pass_method!(topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>);
pass_method!(const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);
- pass_method!(variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);
pass_method!(collection_properties(
collection: CollectionId,
pallets/common/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::{Deref, DerefMut};20use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};21use sp_std::vec::Vec;22use pallet_evm::account::CrossAccountId;23use frame_support::{24 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},25 ensure, fail,26 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},27 BoundedVec,28 weights::Pays,29};30use pallet_evm::GasWeightMapping;31use up_data_structs::{32 COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionId, CreateItemData,33 MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId,34 CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,35 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,36 CUSTOM_DATA_LIMIT, CollectionLimits, CustomDataLimit, CreateCollectionData, SponsorshipState,37 CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,38 PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyPermission,39 PropertiesError, PropertyKeyPermission, TokenData, TrySet,40};41pub use pallet::*;42use sp_core::H160;43use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};44#[cfg(feature = "runtime-benchmarks")]45pub mod benchmarking;46pub mod dispatch;47pub mod erc;48pub mod eth;4950#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]51pub struct CollectionHandle<T: Config> {52 pub id: CollectionId,53 collection: Collection<T::AccountId>,54 pub recorder: SubstrateRecorder<T>,55}56impl<T: Config> WithRecorder<T> for CollectionHandle<T> {57 fn recorder(&self) -> &SubstrateRecorder<T> {58 &self.recorder59 }60 fn into_recorder(self) -> SubstrateRecorder<T> {61 self.recorder62 }63}64impl<T: Config> CollectionHandle<T> {65 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {66 <CollectionById<T>>::get(id).map(|collection| Self {67 id,68 collection,69 recorder: SubstrateRecorder::new(gas_limit),70 })71 }72 pub fn new(id: CollectionId) -> Option<Self> {73 Self::new_with_gas_limit(id, u64::MAX)74 }75 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {76 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)77 }78 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {79 self.recorder80 .consume_gas(T::GasWeightMapping::weight_to_gas(81 <T as frame_system::Config>::DbWeight::get()82 .read83 .saturating_mul(reads),84 ))85 }86 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {87 self.recorder88 .consume_gas(T::GasWeightMapping::weight_to_gas(89 <T as frame_system::Config>::DbWeight::get()90 .write91 .saturating_mul(writes),92 ))93 }94 pub fn save(self) -> DispatchResult {95 <CollectionById<T>>::insert(self.id, self.collection);96 Ok(())97 }98}99impl<T: Config> Deref for CollectionHandle<T> {100 type Target = Collection<T::AccountId>;101102 fn deref(&self) -> &Self::Target {103 &self.collection104 }105}106107impl<T: Config> DerefMut for CollectionHandle<T> {108 fn deref_mut(&mut self) -> &mut Self::Target {109 &mut self.collection110 }111}112113impl<T: Config> CollectionHandle<T> {114 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {115 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);116 Ok(())117 }118 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {119 *subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))120 }121 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {122 ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);123 Ok(())124 }125 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {126 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)127 }128 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {129 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)130 }131 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {132 ensure!(133 <Allowlist<T>>::get((self.id, user)),134 <Error<T>>::AddressNotInAllowlist135 );136 Ok(())137 }138139 pub fn check_can_update_meta(140 &self,141 subject: &T::CrossAccountId,142 item_owner: &T::CrossAccountId,143 ) -> DispatchResult {144 match self.meta_update_permission {145 MetaUpdatePermission::ItemOwner => {146 ensure!(subject == item_owner, <Error<T>>::NoPermission);147 Ok(())148 }149 MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),150 MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),151 }152 }153}154155#[frame_support::pallet]156pub mod pallet {157 use super::*;158 use pallet_evm::account;159 use dispatch::CollectionDispatch;160 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};161 use frame_system::pallet_prelude::*;162 use frame_support::traits::Currency;163 use up_data_structs::{TokenId, mapping::TokenAddressMapping};164 use scale_info::TypeInfo;165166 #[pallet::config]167 pub trait Config:168 frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config169 {170 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;171172 type Currency: Currency<Self::AccountId>;173174 #[pallet::constant]175 type CollectionCreationPrice: Get<176 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,177 >;178 type CollectionDispatch: CollectionDispatch<Self>;179180 type TreasuryAccountId: Get<Self::AccountId>;181182 type EvmTokenAddressMapping: TokenAddressMapping<H160>;183 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;184 }185186 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);187188 #[pallet::pallet]189 #[pallet::storage_version(STORAGE_VERSION)]190 #[pallet::generate_store(pub(super) trait Store)]191 pub struct Pallet<T>(_);192193 #[pallet::extra_constants]194 impl<T: Config> Pallet<T> {195 pub fn collection_admins_limit() -> u32 {196 COLLECTION_ADMINS_LIMIT197 }198 }199200 #[pallet::event]201 #[pallet::generate_deposit(pub fn deposit_event)]202 pub enum Event<T: Config> {203 /// New collection was created204 ///205 /// # Arguments206 ///207 /// * collection_id: Globally unique identifier of newly created collection.208 ///209 /// * mode: [CollectionMode] converted into u8.210 ///211 /// * account_id: Collection owner.212 CollectionCreated(CollectionId, u8, T::AccountId),213214 /// New collection was destroyed215 ///216 /// # Arguments217 ///218 /// * collection_id: Globally unique identifier of collection.219 CollectionDestroyed(CollectionId),220221 /// New item was created.222 ///223 /// # Arguments224 ///225 /// * collection_id: Id of the collection where item was created.226 ///227 /// * item_id: Id of an item. Unique within the collection.228 ///229 /// * recipient: Owner of newly created item230 ///231 /// * amount: Always 1 for NFT232 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),233234 /// Collection item was burned.235 ///236 /// # Arguments237 ///238 /// * collection_id.239 ///240 /// * item_id: Identifier of burned NFT.241 ///242 /// * owner: which user has destroyed its tokens243 ///244 /// * amount: Always 1 for NFT245 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),246247 /// Item was transferred248 ///249 /// * collection_id: Id of collection to which item is belong250 ///251 /// * item_id: Id of an item252 ///253 /// * sender: Original owner of item254 ///255 /// * recipient: New owner of item256 ///257 /// * amount: Always 1 for NFT258 Transfer(259 CollectionId,260 TokenId,261 T::CrossAccountId,262 T::CrossAccountId,263 u128,264 ),265266 /// * collection_id267 ///268 /// * item_id269 ///270 /// * sender271 ///272 /// * spender273 ///274 /// * amount275 Approved(276 CollectionId,277 TokenId,278 T::CrossAccountId,279 T::CrossAccountId,280 u128,281 ),282283 CollectionPropertySet(CollectionId, PropertyKey),284285 CollectionPropertyDeleted(CollectionId, PropertyKey),286287 TokenPropertySet(CollectionId, TokenId, PropertyKey),288289 TokenPropertyDeleted(CollectionId, TokenId, PropertyKey),290291 PropertyPermissionSet(CollectionId, PropertyKey),292 }293294 #[pallet::error]295 pub enum Error<T> {296 /// This collection does not exist.297 CollectionNotFound,298 /// Sender parameter and item owner must be equal.299 MustBeTokenOwner,300 /// No permission to perform action301 NoPermission,302 /// Collection is not in mint mode.303 PublicMintingNotAllowed,304 /// Address is not in allow list.305 AddressNotInAllowlist,306307 /// Collection name can not be longer than 63 char.308 CollectionNameLimitExceeded,309 /// Collection description can not be longer than 255 char.310 CollectionDescriptionLimitExceeded,311 /// Token prefix can not be longer than 15 char.312 CollectionTokenPrefixLimitExceeded,313 /// Total collections bound exceeded.314 TotalCollectionsLimitExceeded,315 /// variable_data exceeded data limit.316 TokenVariableDataLimitExceeded,317 /// Exceeded max admin count318 CollectionAdminCountExceeded,319 /// Collection limit bounds per collection exceeded320 CollectionLimitBoundsExceeded,321 /// Tried to enable permissions which are only permitted to be disabled322 OwnerPermissionsCantBeReverted,323 /// Collection settings not allowing items transferring324 TransferNotAllowed,325 /// Account token limit exceeded per collection326 AccountTokenLimitExceeded,327 /// Collection token limit exceeded328 CollectionTokenLimitExceeded,329 /// Metadata flag frozen330 MetadataFlagFrozen,331332 /// Item not exists.333 TokenNotFound,334 /// Item balance not enough.335 TokenValueTooLow,336 /// Requested value more than approved.337 ApprovedValueTooLow,338 /// Tried to approve more than owned339 CantApproveMoreThanOwned,340341 /// Can't transfer tokens to ethereum zero address342 AddressIsZero,343 /// Target collection doesn't supports this operation344 UnsupportedOperation,345346 /// Not sufficient founds to perform action347 NotSufficientFounds,348349 /// Collection has nesting disabled350 NestingIsDisabled,351 /// Only owner may nest tokens under this collection352 OnlyOwnerAllowedToNest,353 /// Only tokens from specific collections may nest tokens under this354 SourceCollectionIsNotAllowedToNest,355356 /// Tried to store more data than allowed in collection field357 CollectionFieldSizeExceeded,358359 /// Tried to store more property data than allowed360 NoSpaceForProperty,361362 /// Tried to store more property keys than allowed363 PropertyLimitReached,364365 /// Unable to read array of unbounded keys366 UnableToReadUnboundedKeys,367368 /// Only ASCII letters, digits, and '_', '-' are allowed369 InvalidCharacterInPropertyKey,370371 /// Empty property keys are forbidden372 EmptyPropertyKey,373 }374375 #[pallet::storage]376 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;377 #[pallet::storage]378 pub type DestroyedCollectionCount<T> =379 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;380381 /// Collection info382 #[pallet::storage]383 pub type CollectionById<T> = StorageMap<384 Hasher = Blake2_128Concat,385 Key = CollectionId,386 Value = Collection<<T as frame_system::Config>::AccountId>,387 QueryKind = OptionQuery,388 >;389390 /// Collection properties391 #[pallet::storage]392 #[pallet::getter(fn collection_properties)]393 pub type CollectionProperties<T> = StorageMap<394 Hasher = Blake2_128Concat,395 Key = CollectionId,396 Value = Properties,397 QueryKind = ValueQuery,398 OnEmpty = up_data_structs::CollectionProperties,399 >;400401 #[pallet::storage]402 #[pallet::getter(fn property_permissions)]403 pub type CollectionPropertyPermissions<T> = StorageMap<404 Hasher = Blake2_128Concat,405 Key = CollectionId,406 Value = PropertiesPermissionMap,407 QueryKind = ValueQuery,408 >;409410 /// Large variable-size collection fields are extracted here411 #[pallet::storage]412 pub type CollectionData<T> = StorageNMap<413 Key = (414 Key<Twox64Concat, CollectionId>,415 Key<Twox64Concat, CollectionField>,416 ),417 Value = BoundedVec<u8, ConstU32<COLLECTION_FIELD_LIMIT>>,418 QueryKind = ValueQuery,419 >;420421 #[pallet::storage]422 pub type AdminAmount<T> = StorageMap<423 Hasher = Blake2_128Concat,424 Key = CollectionId,425 Value = u32,426 QueryKind = ValueQuery,427 >;428429 /// List of collection admins430 #[pallet::storage]431 pub type IsAdmin<T: Config> = StorageNMap<432 Key = (433 Key<Blake2_128Concat, CollectionId>,434 Key<Blake2_128Concat, T::CrossAccountId>,435 ),436 Value = bool,437 QueryKind = ValueQuery,438 >;439440 /// Allowlisted collection users441 #[pallet::storage]442 pub type Allowlist<T: Config> = StorageNMap<443 Key = (444 Key<Blake2_128Concat, CollectionId>,445 Key<Blake2_128Concat, T::CrossAccountId>,446 ),447 Value = bool,448 QueryKind = ValueQuery,449 >;450451 /// Not used by code, exists only to provide some types to metadata452 #[pallet::storage]453 pub type DummyStorageValue<T: Config> = StorageValue<454 Value = (455 CollectionStats,456 CollectionId,457 TokenId,458 PhantomType<TokenData<T::CrossAccountId>>,459 PhantomType<RpcCollection<T::AccountId>>,460 ),461 QueryKind = OptionQuery,462 >;463464 #[pallet::hooks]465 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {466 fn on_runtime_upgrade() -> Weight {467 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {468 use up_data_structs::{CollectionVersion1, CollectionVersion2};469 <CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {470 Self::set_field_raw(471 id,472 CollectionField::OffchainSchema,473 v.offchain_schema.clone().into_inner(),474 )475 .expect("data has lower bounds than field");476 Self::set_field_raw(477 id,478 CollectionField::ConstOnChainSchema,479 v.const_on_chain_schema.clone().into_inner(),480 )481 .expect("data has lower bounds than field");482483 Some(CollectionVersion2::from(v))484 });485 }486487 0488 }489 }490}491492impl<T: Config> Pallet<T> {493 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens494 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {495 ensure!(496 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,497 <Error<T>>::AddressIsZero498 );499 Ok(())500 }501 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {502 <IsAdmin<T>>::iter_prefix((collection,))503 .map(|(a, _)| a)504 .collect()505 }506 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {507 <Allowlist<T>>::iter_prefix((collection,))508 .map(|(a, _)| a)509 .collect()510 }511 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {512 <Allowlist<T>>::get((collection, user))513 }514 pub fn collection_stats() -> CollectionStats {515 let created = <CreatedCollectionCount<T>>::get();516 let destroyed = <DestroyedCollectionCount<T>>::get();517 CollectionStats {518 created: created.0,519 destroyed: destroyed.0,520 alive: created.0 - destroyed.0,521 }522 }523524 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {525 let collection = <CollectionById<T>>::get(collection);526 if collection.is_none() {527 return None;528 }529530 let collection = collection.unwrap();531 let limits = collection.limits;532 let effective_limits = CollectionLimits {533 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),534 sponsored_data_size: Some(limits.sponsored_data_size()),535 sponsored_data_rate_limit: Some(536 limits537 .sponsored_data_rate_limit538 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),539 ),540 token_limit: Some(limits.token_limit()),541 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(542 match collection.mode {543 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,544 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,545 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,546 },547 )),548 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),549 owner_can_transfer: Some(limits.owner_can_transfer()),550 owner_can_destroy: Some(limits.owner_can_destroy()),551 transfers_enabled: Some(limits.transfers_enabled()),552 nesting_rule: Some(limits.nesting_rule().clone()),553 };554555 Some(effective_limits)556 }557558 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {559 let Collection {560 name,561 description,562 owner,563 mode,564 access,565 token_prefix,566 mint_mode,567 schema_version,568 sponsorship,569 limits,570 meta_update_permission,571 } = <CollectionById<T>>::get(collection)?;572573 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)574 .iter()575 .map(|(key, permission)| PropertyKeyPermission {576 key: key.clone(),577 permission: permission.clone(),578 })579 .collect();580581 let properties = <CollectionProperties<T>>::get(collection)582 .iter()583 .map(|(key, value)| Property {584 key: key.clone(),585 value: value.clone(),586 })587 .collect();588589 Some(RpcCollection {590 name: name.into_inner(),591 description: description.into_inner(),592 owner,593 mode,594 access,595 token_prefix: token_prefix.into_inner(),596 mint_mode,597 schema_version,598 sponsorship,599 limits,600 meta_update_permission,601 offchain_schema: <CollectionData<T>>::get((602 collection,603 CollectionField::OffchainSchema,604 ))605 .into_inner(),606 const_on_chain_schema: <CollectionData<T>>::get((607 collection,608 CollectionField::ConstOnChainSchema,609 ))610 .into_inner(),611 token_property_permissions,612 properties,613 })614 }615}616617impl<T: Config> Pallet<T> {618 pub fn init_collection(619 owner: T::AccountId,620 data: CreateCollectionData<T::AccountId>,621 ) -> Result<CollectionId, DispatchError> {622 {623 ensure!(624 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,625 Error::<T>::CollectionTokenPrefixLimitExceeded626 );627 }628629 let created_count = <CreatedCollectionCount<T>>::get()630 .0631 .checked_add(1)632 .ok_or(ArithmeticError::Overflow)?;633 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;634 let id = CollectionId(created_count);635636 // bound Total number of collections637 ensure!(638 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,639 <Error<T>>::TotalCollectionsLimitExceeded640 );641642 // =========643644 let collection = Collection {645 owner: owner.clone(),646 name: data.name,647 mode: data.mode.clone(),648 mint_mode: false,649 access: data.access.unwrap_or_default(),650 description: data.description,651 token_prefix: data.token_prefix,652 schema_version: data.schema_version.unwrap_or_default(),653 sponsorship: data654 .pending_sponsor655 .map(SponsorshipState::Unconfirmed)656 .unwrap_or_default(),657 limits: data658 .limits659 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))660 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,661 meta_update_permission: data.meta_update_permission.unwrap_or_default(),662 };663664 let mut collection_properties = up_data_structs::CollectionProperties::get();665 collection_properties666 .try_set_from_iter(data.properties.into_iter().map(|p| (p.key, p.value)))667 .map_err(<Error<T>>::from)?;668669 CollectionProperties::<T>::insert(id, collection_properties);670671 let mut token_props_permissions = PropertiesPermissionMap::new();672 token_props_permissions673 .try_set_from_iter(674 data.token_property_permissions675 .into_iter()676 .map(|property| (property.key, property.permission)),677 )678 .map_err(<Error<T>>::from)?;679680 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);681682 // Take a (non-refundable) deposit of collection creation683 {684 let mut imbalance =685 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();686 imbalance.subsume(687 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(688 &T::TreasuryAccountId::get(),689 T::CollectionCreationPrice::get(),690 ),691 );692 <T as Config>::Currency::settle(693 &owner,694 imbalance,695 WithdrawReasons::TRANSFER,696 ExistenceRequirement::KeepAlive,697 )698 .map_err(|_| Error::<T>::NotSufficientFounds)?;699 }700701 <CreatedCollectionCount<T>>::put(created_count);702 <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));703 <CollectionById<T>>::insert(id, collection);704 Self::set_field_raw(705 id,706 CollectionField::OffchainSchema,707 data.offchain_schema.into_inner(),708 )709 .expect("data has lower bounds than field");710 Self::set_field_raw(711 id,712 CollectionField::ConstOnChainSchema,713 data.const_on_chain_schema.into_inner(),714 )715 .expect("data has lower bounds than field");716 Ok(id)717 }718719 pub fn destroy_collection(720 collection: CollectionHandle<T>,721 sender: &T::CrossAccountId,722 ) -> DispatchResult {723 ensure!(724 collection.limits.owner_can_destroy(),725 <Error<T>>::NoPermission,726 );727 collection.check_is_owner(sender)?;728729 let destroyed_collections = <DestroyedCollectionCount<T>>::get()730 .0731 .checked_add(1)732 .ok_or(ArithmeticError::Overflow)?;733734 // =========735736 <DestroyedCollectionCount<T>>::put(destroyed_collections);737 <CollectionById<T>>::remove(collection.id);738 <CollectionData<T>>::remove_prefix((collection.id,), None);739 <AdminAmount<T>>::remove(collection.id);740 <IsAdmin<T>>::remove_prefix((collection.id,), None);741 <Allowlist<T>>::remove_prefix((collection.id,), None);742743 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));744 Ok(())745 }746747 pub fn set_collection_property(748 collection: &CollectionHandle<T>,749 sender: &T::CrossAccountId,750 property: Property,751 ) -> DispatchResult {752 collection.check_is_owner_or_admin(sender)?;753754 CollectionProperties::<T>::try_mutate(collection.id, |properties| {755 let property = property.clone();756 properties.try_set(property.key, property.value)757 })758 .map_err(<Error<T>>::from)?;759760 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));761762 Ok(())763 }764765 pub fn set_collection_properties(766 collection: &CollectionHandle<T>,767 sender: &T::CrossAccountId,768 properties: Vec<Property>,769 ) -> DispatchResult {770 for property in properties {771 Self::set_collection_property(collection, sender, property)?;772 }773774 Ok(())775 }776777 pub fn delete_collection_property(778 collection: &CollectionHandle<T>,779 sender: &T::CrossAccountId,780 property_key: PropertyKey,781 ) -> DispatchResult {782 collection.check_is_owner_or_admin(sender)?;783784 CollectionProperties::<T>::try_mutate(collection.id, |properties| {785 properties.remove(&property_key)786 })787 .map_err(<Error<T>>::from)?;788789 Self::deposit_event(Event::CollectionPropertyDeleted(790 collection.id,791 property_key,792 ));793794 Ok(())795 }796797 pub fn delete_collection_properties(798 collection: &CollectionHandle<T>,799 sender: &T::CrossAccountId,800 property_keys: Vec<PropertyKey>,801 ) -> DispatchResult {802 for key in property_keys {803 Self::delete_collection_property(collection, sender, key)?;804 }805806 Ok(())807 }808809 pub fn set_property_permission(810 collection: &CollectionHandle<T>,811 sender: &T::CrossAccountId,812 property_permission: PropertyKeyPermission,813 ) -> DispatchResult {814 collection.check_is_owner_or_admin(sender)?;815816 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);817 let current_permission = all_permissions.get(&property_permission.key);818 if matches![819 current_permission,820 Some(PropertyPermission { mutable: false, .. })821 ] {822 return Err(<Error<T>>::NoPermission.into());823 }824825 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {826 let property_permission = property_permission.clone();827 permissions.try_set(property_permission.key, property_permission.permission)828 })829 .map_err(<Error<T>>::from)?;830831 Self::deposit_event(Event::PropertyPermissionSet(832 collection.id,833 property_permission.key,834 ));835836 Ok(())837 }838839 pub fn set_property_permissions(840 collection: &CollectionHandle<T>,841 sender: &T::CrossAccountId,842 property_permissions: Vec<PropertyKeyPermission>,843 ) -> DispatchResult {844 for prop_pemission in property_permissions {845 Self::set_property_permission(collection, sender, prop_pemission)?;846 }847848 Ok(())849 }850851 pub fn bytes_keys_to_property_keys(852 keys: Vec<Vec<u8>>,853 ) -> Result<Vec<PropertyKey>, DispatchError> {854 keys.into_iter()855 .map(|key| -> Result<PropertyKey, DispatchError> {856 key.try_into()857 .map_err(|_| <Error<T>>::UnableToReadUnboundedKeys.into())858 })859 .collect::<Result<Vec<PropertyKey>, DispatchError>>()860 }861862 pub fn check_property_key(key: &PropertyKey) -> Result<(), DispatchError> {863 let key_str = sp_std::str::from_utf8(key.as_slice())864 .map_err(|_| <Error<T>>::InvalidCharacterInPropertyKey)?;865866 for ch in key_str.chars() {867 if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {868 return Err(<Error<T>>::InvalidCharacterInPropertyKey.into());869 }870 }871872 Ok(())873 }874875 pub fn filter_collection_properties(876 collection_id: CollectionId,877 keys: Vec<PropertyKey>,878 ) -> Result<Vec<Property>, DispatchError> {879 let properties = Self::collection_properties(collection_id);880881 let properties = keys882 .into_iter()883 .filter_map(|key| {884 properties.get(&key).map(|value| Property {885 key,886 value: value.clone(),887 })888 })889 .collect();890891 Ok(properties)892 }893894 pub fn filter_property_permissions(895 collection_id: CollectionId,896 keys: Vec<PropertyKey>,897 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {898 let permissions = Self::property_permissions(collection_id);899900 let key_permissions = keys901 .into_iter()902 .filter_map(|key| {903 permissions904 .get(&key)905 .map(|permission| PropertyKeyPermission {906 key,907 permission: permission.clone(),908 })909 })910 .collect();911912 Ok(key_permissions)913 }914915 fn set_field_raw(916 collection_id: CollectionId,917 field: CollectionField,918 value: Vec<u8>,919 ) -> DispatchResult {920 if !value.is_empty() {921 <CollectionData<T>>::insert(922 (collection_id, field),923 BoundedVec::try_from(value).map_err(|_| <Error<T>>::CollectionFieldSizeExceeded)?,924 )925 } else {926 <CollectionData<T>>::remove((collection_id, field));927 }928 Ok(())929 }930931 pub fn set_field(932 collection: &CollectionHandle<T>,933 sender: &T::CrossAccountId,934 field: CollectionField,935 value: Vec<u8>,936 ) -> DispatchResult {937 collection.check_is_owner_or_admin(sender)?;938939 // =========940941 Self::set_field_raw(collection.id, field, value)942 }943944 pub fn toggle_allowlist(945 collection: &CollectionHandle<T>,946 sender: &T::CrossAccountId,947 user: &T::CrossAccountId,948 allowed: bool,949 ) -> DispatchResult {950 collection.check_is_owner_or_admin(sender)?;951952 // =========953954 if allowed {955 <Allowlist<T>>::insert((collection.id, user), true);956 } else {957 <Allowlist<T>>::remove((collection.id, user));958 }959960 Ok(())961 }962963 pub fn toggle_admin(964 collection: &CollectionHandle<T>,965 sender: &T::CrossAccountId,966 user: &T::CrossAccountId,967 admin: bool,968 ) -> DispatchResult {969 collection.check_is_owner_or_admin(sender)?;970971 let was_admin = <IsAdmin<T>>::get((collection.id, user));972 if was_admin == admin {973 return Ok(());974 }975 let amount = <AdminAmount<T>>::get(collection.id);976977 if admin {978 let amount = amount979 .checked_add(1)980 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;981 ensure!(982 amount <= Self::collection_admins_limit(),983 <Error<T>>::CollectionAdminCountExceeded,984 );985986 // =========987988 <AdminAmount<T>>::insert(collection.id, amount);989 <IsAdmin<T>>::insert((collection.id, user), true);990 } else {991 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));992 <IsAdmin<T>>::remove((collection.id, user));993 }994995 Ok(())996 }997998 pub fn clamp_limits(999 mode: CollectionMode,1000 old_limit: &CollectionLimits,1001 mut new_limit: CollectionLimits,1002 ) -> Result<CollectionLimits, DispatchError> {1003 macro_rules! limit_default {1004 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1005 $(1006 if let Some($new) = $new.$field {1007 let $old = $old.$field($($arg)?);1008 let _ = $new;1009 let _ = $old;1010 $check1011 } else {1012 $new.$field = $old.$field1013 }1014 )*1015 }};1016 }10171018 limit_default!(old_limit, new_limit,1019 account_token_ownership_limit => ensure!(1020 new_limit <= MAX_TOKEN_OWNERSHIP,1021 <Error<T>>::CollectionLimitBoundsExceeded,1022 ),1023 sponsor_transfer_timeout(match mode {1024 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1025 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1026 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1027 }) => ensure!(1028 new_limit <= MAX_SPONSOR_TIMEOUT,1029 <Error<T>>::CollectionLimitBoundsExceeded,1030 ),1031 sponsored_data_size => ensure!(1032 new_limit <= CUSTOM_DATA_LIMIT,1033 <Error<T>>::CollectionLimitBoundsExceeded,1034 ),1035 token_limit => ensure!(1036 old_limit >= new_limit && new_limit > 0,1037 <Error<T>>::CollectionTokenLimitExceeded1038 ),1039 owner_can_transfer => ensure!(1040 old_limit || !new_limit,1041 <Error<T>>::OwnerPermissionsCantBeReverted,1042 ),1043 owner_can_destroy => ensure!(1044 old_limit || !new_limit,1045 <Error<T>>::OwnerPermissionsCantBeReverted,1046 ),1047 sponsored_data_rate_limit => {},1048 transfers_enabled => {},1049 );1050 Ok(new_limit)1051 }1052}10531054#[macro_export]1055macro_rules! unsupported {1056 () => {1057 Err(<Error<T>>::UnsupportedOperation.into())1058 };1059}10601061/// Worst cases1062pub trait CommonWeightInfo<CrossAccountId> {1063 fn create_item() -> Weight;1064 fn create_multiple_items(amount: u32) -> Weight;1065 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;1066 fn burn_item() -> Weight;1067 fn set_collection_properties(amount: u32) -> Weight;1068 fn delete_collection_properties(amount: u32) -> Weight;1069 fn set_token_properties(amount: u32) -> Weight;1070 fn delete_token_properties(amount: u32) -> Weight;1071 fn set_property_permissions(amount: u32) -> Weight;1072 fn transfer() -> Weight;1073 fn approve() -> Weight;1074 fn transfer_from() -> Weight;1075 fn burn_from() -> Weight;1076 fn set_variable_metadata(bytes: u32) -> Weight;1077}10781079pub trait CommonCollectionOperations<T: Config> {1080 fn create_item(1081 &self,1082 sender: T::CrossAccountId,1083 to: T::CrossAccountId,1084 data: CreateItemData,1085 nesting_budget: &dyn Budget,1086 ) -> DispatchResultWithPostInfo;1087 fn create_multiple_items(1088 &self,1089 sender: T::CrossAccountId,1090 to: T::CrossAccountId,1091 data: Vec<CreateItemData>,1092 nesting_budget: &dyn Budget,1093 ) -> DispatchResultWithPostInfo;1094 fn create_multiple_items_ex(1095 &self,1096 sender: T::CrossAccountId,1097 data: CreateItemExData<T::CrossAccountId>,1098 nesting_budget: &dyn Budget,1099 ) -> DispatchResultWithPostInfo;1100 fn burn_item(1101 &self,1102 sender: T::CrossAccountId,1103 token: TokenId,1104 amount: u128,1105 ) -> DispatchResultWithPostInfo;1106 fn set_collection_properties(1107 &self,1108 sender: T::CrossAccountId,1109 properties: Vec<Property>,1110 ) -> DispatchResultWithPostInfo;1111 fn delete_collection_properties(1112 &self,1113 sender: &T::CrossAccountId,1114 property_keys: Vec<PropertyKey>,1115 ) -> DispatchResultWithPostInfo;1116 fn set_token_properties(1117 &self,1118 sender: T::CrossAccountId,1119 token_id: TokenId,1120 property: Vec<Property>,1121 ) -> DispatchResultWithPostInfo;1122 fn delete_token_properties(1123 &self,1124 sender: T::CrossAccountId,1125 token_id: TokenId,1126 property_keys: Vec<PropertyKey>,1127 ) -> DispatchResultWithPostInfo;1128 fn set_property_permissions(1129 &self,1130 sender: &T::CrossAccountId,1131 property_permissions: Vec<PropertyKeyPermission>,1132 ) -> DispatchResultWithPostInfo;1133 fn transfer(1134 &self,1135 sender: T::CrossAccountId,1136 to: T::CrossAccountId,1137 token: TokenId,1138 amount: u128,1139 nesting_budget: &dyn Budget,1140 ) -> DispatchResultWithPostInfo;1141 fn approve(1142 &self,1143 sender: T::CrossAccountId,1144 spender: T::CrossAccountId,1145 token: TokenId,1146 amount: u128,1147 ) -> DispatchResultWithPostInfo;1148 fn transfer_from(1149 &self,1150 sender: T::CrossAccountId,1151 from: T::CrossAccountId,1152 to: T::CrossAccountId,1153 token: TokenId,1154 amount: u128,1155 nesting_budget: &dyn Budget,1156 ) -> DispatchResultWithPostInfo;1157 fn burn_from(1158 &self,1159 sender: T::CrossAccountId,1160 from: T::CrossAccountId,1161 token: TokenId,1162 amount: u128,1163 nesting_budget: &dyn Budget,1164 ) -> DispatchResultWithPostInfo;11651166 fn set_variable_metadata(1167 &self,1168 sender: T::CrossAccountId,1169 token: TokenId,1170 data: BoundedVec<u8, CustomDataLimit>,1171 ) -> DispatchResultWithPostInfo;11721173 fn check_nesting(1174 &self,1175 sender: T::CrossAccountId,1176 from: (CollectionId, TokenId),1177 under: TokenId,1178 budget: &dyn Budget,1179 ) -> DispatchResult;11801181 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;1182 fn collection_tokens(&self) -> Vec<TokenId>;1183 fn token_exists(&self, token: TokenId) -> bool;1184 fn last_token_id(&self) -> TokenId;11851186 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;1187 fn const_metadata(&self, token: TokenId) -> Vec<u8>;1188 fn variable_metadata(&self, token: TokenId) -> Vec<u8>;1189 fn token_properties(&self, token_id: TokenId, keys: Vec<PropertyKey>) -> Vec<Property>;1190 /// Amount of unique collection tokens1191 fn total_supply(&self) -> u32;1192 /// Amount of different tokens account has (Applicable to nonfungible/refungible)1193 fn account_balance(&self, account: T::CrossAccountId) -> u32;1194 /// Amount of specific token account have (Applicable to fungible/refungible)1195 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;1196 fn allowance(1197 &self,1198 sender: T::CrossAccountId,1199 spender: T::CrossAccountId,1200 token: TokenId,1201 ) -> u128;1202}12031204// Flexible enough for implementing CommonCollectionOperations1205pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1206 let post_info = PostDispatchInfo {1207 actual_weight: Some(weight),1208 pays_fee: Pays::Yes,1209 };1210 match res {1211 Ok(()) => Ok(post_info),1212 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1213 }1214}12151216impl<T: Config> From<PropertiesError> for Error<T> {1217 fn from(error: PropertiesError) -> Self {1218 match error {1219 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1220 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1221 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1222 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1223 }1224 }1225}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::{Deref, DerefMut};20use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};21use sp_std::vec::Vec;22use pallet_evm::account::CrossAccountId;23use frame_support::{24 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},25 ensure, fail,26 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},27 BoundedVec,28 weights::Pays,29};30use pallet_evm::GasWeightMapping;31use up_data_structs::{32 COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionId, CreateItemData,33 MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId,34 CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,35 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,36 CUSTOM_DATA_LIMIT, CollectionLimits, CreateCollectionData, SponsorshipState,37 CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,38 PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyPermission,39 PropertiesError, PropertyKeyPermission, TokenData, TrySet,40};41pub use pallet::*;42use sp_core::H160;43use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};44#[cfg(feature = "runtime-benchmarks")]45pub mod benchmarking;46pub mod dispatch;47pub mod erc;48pub mod eth;4950#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]51pub struct CollectionHandle<T: Config> {52 pub id: CollectionId,53 collection: Collection<T::AccountId>,54 pub recorder: SubstrateRecorder<T>,55}56impl<T: Config> WithRecorder<T> for CollectionHandle<T> {57 fn recorder(&self) -> &SubstrateRecorder<T> {58 &self.recorder59 }60 fn into_recorder(self) -> SubstrateRecorder<T> {61 self.recorder62 }63}64impl<T: Config> CollectionHandle<T> {65 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {66 <CollectionById<T>>::get(id).map(|collection| Self {67 id,68 collection,69 recorder: SubstrateRecorder::new(gas_limit),70 })71 }72 pub fn new(id: CollectionId) -> Option<Self> {73 Self::new_with_gas_limit(id, u64::MAX)74 }75 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {76 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)77 }78 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {79 self.recorder80 .consume_gas(T::GasWeightMapping::weight_to_gas(81 <T as frame_system::Config>::DbWeight::get()82 .read83 .saturating_mul(reads),84 ))85 }86 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {87 self.recorder88 .consume_gas(T::GasWeightMapping::weight_to_gas(89 <T as frame_system::Config>::DbWeight::get()90 .write91 .saturating_mul(writes),92 ))93 }94 pub fn save(self) -> DispatchResult {95 <CollectionById<T>>::insert(self.id, self.collection);96 Ok(())97 }98}99impl<T: Config> Deref for CollectionHandle<T> {100 type Target = Collection<T::AccountId>;101102 fn deref(&self) -> &Self::Target {103 &self.collection104 }105}106107impl<T: Config> DerefMut for CollectionHandle<T> {108 fn deref_mut(&mut self) -> &mut Self::Target {109 &mut self.collection110 }111}112113impl<T: Config> CollectionHandle<T> {114 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {115 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);116 Ok(())117 }118 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {119 *subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))120 }121 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {122 ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);123 Ok(())124 }125 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {126 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)127 }128 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {129 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)130 }131 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {132 ensure!(133 <Allowlist<T>>::get((self.id, user)),134 <Error<T>>::AddressNotInAllowlist135 );136 Ok(())137 }138139 pub fn check_can_update_meta(140 &self,141 subject: &T::CrossAccountId,142 item_owner: &T::CrossAccountId,143 ) -> DispatchResult {144 match self.meta_update_permission {145 MetaUpdatePermission::ItemOwner => {146 ensure!(subject == item_owner, <Error<T>>::NoPermission);147 Ok(())148 }149 MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),150 MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),151 }152 }153}154155#[frame_support::pallet]156pub mod pallet {157 use super::*;158 use pallet_evm::account;159 use dispatch::CollectionDispatch;160 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};161 use frame_system::pallet_prelude::*;162 use frame_support::traits::Currency;163 use up_data_structs::{TokenId, mapping::TokenAddressMapping};164 use scale_info::TypeInfo;165166 #[pallet::config]167 pub trait Config:168 frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config169 {170 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;171172 type Currency: Currency<Self::AccountId>;173174 #[pallet::constant]175 type CollectionCreationPrice: Get<176 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,177 >;178 type CollectionDispatch: CollectionDispatch<Self>;179180 type TreasuryAccountId: Get<Self::AccountId>;181182 type EvmTokenAddressMapping: TokenAddressMapping<H160>;183 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;184 }185186 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);187188 #[pallet::pallet]189 #[pallet::storage_version(STORAGE_VERSION)]190 #[pallet::generate_store(pub(super) trait Store)]191 pub struct Pallet<T>(_);192193 #[pallet::extra_constants]194 impl<T: Config> Pallet<T> {195 pub fn collection_admins_limit() -> u32 {196 COLLECTION_ADMINS_LIMIT197 }198 }199200 #[pallet::event]201 #[pallet::generate_deposit(pub fn deposit_event)]202 pub enum Event<T: Config> {203 /// New collection was created204 ///205 /// # Arguments206 ///207 /// * collection_id: Globally unique identifier of newly created collection.208 ///209 /// * mode: [CollectionMode] converted into u8.210 ///211 /// * account_id: Collection owner.212 CollectionCreated(CollectionId, u8, T::AccountId),213214 /// New collection was destroyed215 ///216 /// # Arguments217 ///218 /// * collection_id: Globally unique identifier of collection.219 CollectionDestroyed(CollectionId),220221 /// New item was created.222 ///223 /// # Arguments224 ///225 /// * collection_id: Id of the collection where item was created.226 ///227 /// * item_id: Id of an item. Unique within the collection.228 ///229 /// * recipient: Owner of newly created item230 ///231 /// * amount: Always 1 for NFT232 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),233234 /// Collection item was burned.235 ///236 /// # Arguments237 ///238 /// * collection_id.239 ///240 /// * item_id: Identifier of burned NFT.241 ///242 /// * owner: which user has destroyed its tokens243 ///244 /// * amount: Always 1 for NFT245 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),246247 /// Item was transferred248 ///249 /// * collection_id: Id of collection to which item is belong250 ///251 /// * item_id: Id of an item252 ///253 /// * sender: Original owner of item254 ///255 /// * recipient: New owner of item256 ///257 /// * amount: Always 1 for NFT258 Transfer(259 CollectionId,260 TokenId,261 T::CrossAccountId,262 T::CrossAccountId,263 u128,264 ),265266 /// * collection_id267 ///268 /// * item_id269 ///270 /// * sender271 ///272 /// * spender273 ///274 /// * amount275 Approved(276 CollectionId,277 TokenId,278 T::CrossAccountId,279 T::CrossAccountId,280 u128,281 ),282283 CollectionPropertySet(CollectionId, PropertyKey),284285 CollectionPropertyDeleted(CollectionId, PropertyKey),286287 TokenPropertySet(CollectionId, TokenId, PropertyKey),288289 TokenPropertyDeleted(CollectionId, TokenId, PropertyKey),290291 PropertyPermissionSet(CollectionId, PropertyKey),292 }293294 #[pallet::error]295 pub enum Error<T> {296 /// This collection does not exist.297 CollectionNotFound,298 /// Sender parameter and item owner must be equal.299 MustBeTokenOwner,300 /// No permission to perform action301 NoPermission,302 /// Collection is not in mint mode.303 PublicMintingNotAllowed,304 /// Address is not in allow list.305 AddressNotInAllowlist,306307 /// Collection name can not be longer than 63 char.308 CollectionNameLimitExceeded,309 /// Collection description can not be longer than 255 char.310 CollectionDescriptionLimitExceeded,311 /// Token prefix can not be longer than 15 char.312 CollectionTokenPrefixLimitExceeded,313 /// Total collections bound exceeded.314 TotalCollectionsLimitExceeded,315 /// Exceeded max admin count316 CollectionAdminCountExceeded,317 /// Collection limit bounds per collection exceeded318 CollectionLimitBoundsExceeded,319 /// Tried to enable permissions which are only permitted to be disabled320 OwnerPermissionsCantBeReverted,321 /// Collection settings not allowing items transferring322 TransferNotAllowed,323 /// Account token limit exceeded per collection324 AccountTokenLimitExceeded,325 /// Collection token limit exceeded326 CollectionTokenLimitExceeded,327 /// Metadata flag frozen328 MetadataFlagFrozen,329330 /// Item not exists.331 TokenNotFound,332 /// Item balance not enough.333 TokenValueTooLow,334 /// Requested value more than approved.335 ApprovedValueTooLow,336 /// Tried to approve more than owned337 CantApproveMoreThanOwned,338339 /// Can't transfer tokens to ethereum zero address340 AddressIsZero,341 /// Target collection doesn't supports this operation342 UnsupportedOperation,343344 /// Not sufficient founds to perform action345 NotSufficientFounds,346347 /// Collection has nesting disabled348 NestingIsDisabled,349 /// Only owner may nest tokens under this collection350 OnlyOwnerAllowedToNest,351 /// Only tokens from specific collections may nest tokens under this352 SourceCollectionIsNotAllowedToNest,353354 /// Tried to store more data than allowed in collection field355 CollectionFieldSizeExceeded,356357 /// Tried to store more property data than allowed358 NoSpaceForProperty,359360 /// Tried to store more property keys than allowed361 PropertyLimitReached,362363 /// Unable to read array of unbounded keys364 UnableToReadUnboundedKeys,365366 /// Only ASCII letters, digits, and '_', '-' are allowed367 InvalidCharacterInPropertyKey,368369 /// Empty property keys are forbidden370 EmptyPropertyKey,371 }372373 #[pallet::storage]374 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;375 #[pallet::storage]376 pub type DestroyedCollectionCount<T> =377 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;378379 /// Collection info380 #[pallet::storage]381 pub type CollectionById<T> = StorageMap<382 Hasher = Blake2_128Concat,383 Key = CollectionId,384 Value = Collection<<T as frame_system::Config>::AccountId>,385 QueryKind = OptionQuery,386 >;387388 /// Collection properties389 #[pallet::storage]390 #[pallet::getter(fn collection_properties)]391 pub type CollectionProperties<T> = StorageMap<392 Hasher = Blake2_128Concat,393 Key = CollectionId,394 Value = Properties,395 QueryKind = ValueQuery,396 OnEmpty = up_data_structs::CollectionProperties,397 >;398399 #[pallet::storage]400 #[pallet::getter(fn property_permissions)]401 pub type CollectionPropertyPermissions<T> = StorageMap<402 Hasher = Blake2_128Concat,403 Key = CollectionId,404 Value = PropertiesPermissionMap,405 QueryKind = ValueQuery,406 >;407408 /// Large variable-size collection fields are extracted here409 #[pallet::storage]410 pub type CollectionData<T> = StorageNMap<411 Key = (412 Key<Twox64Concat, CollectionId>,413 Key<Twox64Concat, CollectionField>,414 ),415 Value = BoundedVec<u8, ConstU32<COLLECTION_FIELD_LIMIT>>,416 QueryKind = ValueQuery,417 >;418419 #[pallet::storage]420 pub type AdminAmount<T> = StorageMap<421 Hasher = Blake2_128Concat,422 Key = CollectionId,423 Value = u32,424 QueryKind = ValueQuery,425 >;426427 /// List of collection admins428 #[pallet::storage]429 pub type IsAdmin<T: Config> = StorageNMap<430 Key = (431 Key<Blake2_128Concat, CollectionId>,432 Key<Blake2_128Concat, T::CrossAccountId>,433 ),434 Value = bool,435 QueryKind = ValueQuery,436 >;437438 /// Allowlisted collection users439 #[pallet::storage]440 pub type Allowlist<T: Config> = StorageNMap<441 Key = (442 Key<Blake2_128Concat, CollectionId>,443 Key<Blake2_128Concat, T::CrossAccountId>,444 ),445 Value = bool,446 QueryKind = ValueQuery,447 >;448449 /// Not used by code, exists only to provide some types to metadata450 #[pallet::storage]451 pub type DummyStorageValue<T: Config> = StorageValue<452 Value = (453 CollectionStats,454 CollectionId,455 TokenId,456 PhantomType<TokenData<T::CrossAccountId>>,457 PhantomType<RpcCollection<T::AccountId>>,458 ),459 QueryKind = OptionQuery,460 >;461462 #[pallet::hooks]463 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {464 fn on_runtime_upgrade() -> Weight {465 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {466 use up_data_structs::{CollectionVersion1, CollectionVersion2};467 <CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {468 Self::set_field_raw(469 id,470 CollectionField::OffchainSchema,471 v.offchain_schema.clone().into_inner(),472 )473 .expect("data has lower bounds than field");474 Self::set_field_raw(475 id,476 CollectionField::ConstOnChainSchema,477 v.const_on_chain_schema.clone().into_inner(),478 )479 .expect("data has lower bounds than field");480481 Some(CollectionVersion2::from(v))482 });483 }484485 0486 }487 }488}489490impl<T: Config> Pallet<T> {491 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens492 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {493 ensure!(494 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,495 <Error<T>>::AddressIsZero496 );497 Ok(())498 }499 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {500 <IsAdmin<T>>::iter_prefix((collection,))501 .map(|(a, _)| a)502 .collect()503 }504 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {505 <Allowlist<T>>::iter_prefix((collection,))506 .map(|(a, _)| a)507 .collect()508 }509 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {510 <Allowlist<T>>::get((collection, user))511 }512 pub fn collection_stats() -> CollectionStats {513 let created = <CreatedCollectionCount<T>>::get();514 let destroyed = <DestroyedCollectionCount<T>>::get();515 CollectionStats {516 created: created.0,517 destroyed: destroyed.0,518 alive: created.0 - destroyed.0,519 }520 }521522 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {523 let collection = <CollectionById<T>>::get(collection);524 if collection.is_none() {525 return None;526 }527528 let collection = collection.unwrap();529 let limits = collection.limits;530 let effective_limits = CollectionLimits {531 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),532 sponsored_data_size: Some(limits.sponsored_data_size()),533 sponsored_data_rate_limit: Some(534 limits535 .sponsored_data_rate_limit536 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),537 ),538 token_limit: Some(limits.token_limit()),539 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(540 match collection.mode {541 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,542 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,543 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,544 },545 )),546 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),547 owner_can_transfer: Some(limits.owner_can_transfer()),548 owner_can_destroy: Some(limits.owner_can_destroy()),549 transfers_enabled: Some(limits.transfers_enabled()),550 nesting_rule: Some(limits.nesting_rule().clone()),551 };552553 Some(effective_limits)554 }555556 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {557 let Collection {558 name,559 description,560 owner,561 mode,562 access,563 token_prefix,564 mint_mode,565 schema_version,566 sponsorship,567 limits,568 meta_update_permission,569 } = <CollectionById<T>>::get(collection)?;570571 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)572 .iter()573 .map(|(key, permission)| PropertyKeyPermission {574 key: key.clone(),575 permission: permission.clone(),576 })577 .collect();578579 let properties = <CollectionProperties<T>>::get(collection)580 .iter()581 .map(|(key, value)| Property {582 key: key.clone(),583 value: value.clone(),584 })585 .collect();586587 Some(RpcCollection {588 name: name.into_inner(),589 description: description.into_inner(),590 owner,591 mode,592 access,593 token_prefix: token_prefix.into_inner(),594 mint_mode,595 schema_version,596 sponsorship,597 limits,598 meta_update_permission,599 offchain_schema: <CollectionData<T>>::get((600 collection,601 CollectionField::OffchainSchema,602 ))603 .into_inner(),604 const_on_chain_schema: <CollectionData<T>>::get((605 collection,606 CollectionField::ConstOnChainSchema,607 ))608 .into_inner(),609 token_property_permissions,610 properties,611 })612 }613}614615impl<T: Config> Pallet<T> {616 pub fn init_collection(617 owner: T::AccountId,618 data: CreateCollectionData<T::AccountId>,619 ) -> Result<CollectionId, DispatchError> {620 {621 ensure!(622 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,623 Error::<T>::CollectionTokenPrefixLimitExceeded624 );625 }626627 let created_count = <CreatedCollectionCount<T>>::get()628 .0629 .checked_add(1)630 .ok_or(ArithmeticError::Overflow)?;631 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;632 let id = CollectionId(created_count);633634 // bound Total number of collections635 ensure!(636 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,637 <Error<T>>::TotalCollectionsLimitExceeded638 );639640 // =========641642 let collection = Collection {643 owner: owner.clone(),644 name: data.name,645 mode: data.mode.clone(),646 mint_mode: false,647 access: data.access.unwrap_or_default(),648 description: data.description,649 token_prefix: data.token_prefix,650 schema_version: data.schema_version.unwrap_or_default(),651 sponsorship: data652 .pending_sponsor653 .map(SponsorshipState::Unconfirmed)654 .unwrap_or_default(),655 limits: data656 .limits657 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))658 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,659 meta_update_permission: data.meta_update_permission.unwrap_or_default(),660 };661662 let mut collection_properties = up_data_structs::CollectionProperties::get();663 collection_properties664 .try_set_from_iter(data.properties.into_iter().map(|p| (p.key, p.value)))665 .map_err(<Error<T>>::from)?;666667 CollectionProperties::<T>::insert(id, collection_properties);668669 let mut token_props_permissions = PropertiesPermissionMap::new();670 token_props_permissions671 .try_set_from_iter(672 data.token_property_permissions673 .into_iter()674 .map(|property| (property.key, property.permission)),675 )676 .map_err(<Error<T>>::from)?;677678 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);679680 // Take a (non-refundable) deposit of collection creation681 {682 let mut imbalance =683 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();684 imbalance.subsume(685 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(686 &T::TreasuryAccountId::get(),687 T::CollectionCreationPrice::get(),688 ),689 );690 <T as Config>::Currency::settle(691 &owner,692 imbalance,693 WithdrawReasons::TRANSFER,694 ExistenceRequirement::KeepAlive,695 )696 .map_err(|_| Error::<T>::NotSufficientFounds)?;697 }698699 <CreatedCollectionCount<T>>::put(created_count);700 <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));701 <CollectionById<T>>::insert(id, collection);702 Self::set_field_raw(703 id,704 CollectionField::OffchainSchema,705 data.offchain_schema.into_inner(),706 )707 .expect("data has lower bounds than field");708 Self::set_field_raw(709 id,710 CollectionField::ConstOnChainSchema,711 data.const_on_chain_schema.into_inner(),712 )713 .expect("data has lower bounds than field");714 Ok(id)715 }716717 pub fn destroy_collection(718 collection: CollectionHandle<T>,719 sender: &T::CrossAccountId,720 ) -> DispatchResult {721 ensure!(722 collection.limits.owner_can_destroy(),723 <Error<T>>::NoPermission,724 );725 collection.check_is_owner(sender)?;726727 let destroyed_collections = <DestroyedCollectionCount<T>>::get()728 .0729 .checked_add(1)730 .ok_or(ArithmeticError::Overflow)?;731732 // =========733734 <DestroyedCollectionCount<T>>::put(destroyed_collections);735 <CollectionById<T>>::remove(collection.id);736 <CollectionData<T>>::remove_prefix((collection.id,), None);737 <AdminAmount<T>>::remove(collection.id);738 <IsAdmin<T>>::remove_prefix((collection.id,), None);739 <Allowlist<T>>::remove_prefix((collection.id,), None);740741 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));742 Ok(())743 }744745 pub fn set_collection_property(746 collection: &CollectionHandle<T>,747 sender: &T::CrossAccountId,748 property: Property,749 ) -> DispatchResult {750 collection.check_is_owner_or_admin(sender)?;751752 CollectionProperties::<T>::try_mutate(collection.id, |properties| {753 let property = property.clone();754 properties.try_set(property.key, property.value)755 })756 .map_err(<Error<T>>::from)?;757758 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));759760 Ok(())761 }762763 pub fn set_collection_properties(764 collection: &CollectionHandle<T>,765 sender: &T::CrossAccountId,766 properties: Vec<Property>,767 ) -> DispatchResult {768 for property in properties {769 Self::set_collection_property(collection, sender, property)?;770 }771772 Ok(())773 }774775 pub fn delete_collection_property(776 collection: &CollectionHandle<T>,777 sender: &T::CrossAccountId,778 property_key: PropertyKey,779 ) -> DispatchResult {780 collection.check_is_owner_or_admin(sender)?;781782 CollectionProperties::<T>::try_mutate(collection.id, |properties| {783 properties.remove(&property_key)784 })785 .map_err(<Error<T>>::from)?;786787 Self::deposit_event(Event::CollectionPropertyDeleted(788 collection.id,789 property_key,790 ));791792 Ok(())793 }794795 pub fn delete_collection_properties(796 collection: &CollectionHandle<T>,797 sender: &T::CrossAccountId,798 property_keys: Vec<PropertyKey>,799 ) -> DispatchResult {800 for key in property_keys {801 Self::delete_collection_property(collection, sender, key)?;802 }803804 Ok(())805 }806807 pub fn set_property_permission(808 collection: &CollectionHandle<T>,809 sender: &T::CrossAccountId,810 property_permission: PropertyKeyPermission,811 ) -> DispatchResult {812 collection.check_is_owner_or_admin(sender)?;813814 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);815 let current_permission = all_permissions.get(&property_permission.key);816 if matches![817 current_permission,818 Some(PropertyPermission { mutable: false, .. })819 ] {820 return Err(<Error<T>>::NoPermission.into());821 }822823 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {824 let property_permission = property_permission.clone();825 permissions.try_set(property_permission.key, property_permission.permission)826 })827 .map_err(<Error<T>>::from)?;828829 Self::deposit_event(Event::PropertyPermissionSet(830 collection.id,831 property_permission.key,832 ));833834 Ok(())835 }836837 pub fn set_property_permissions(838 collection: &CollectionHandle<T>,839 sender: &T::CrossAccountId,840 property_permissions: Vec<PropertyKeyPermission>,841 ) -> DispatchResult {842 for prop_pemission in property_permissions {843 Self::set_property_permission(collection, sender, prop_pemission)?;844 }845846 Ok(())847 }848849 pub fn bytes_keys_to_property_keys(850 keys: Vec<Vec<u8>>,851 ) -> Result<Vec<PropertyKey>, DispatchError> {852 keys.into_iter()853 .map(|key| -> Result<PropertyKey, DispatchError> {854 key.try_into()855 .map_err(|_| <Error<T>>::UnableToReadUnboundedKeys.into())856 })857 .collect::<Result<Vec<PropertyKey>, DispatchError>>()858 }859860 pub fn check_property_key(key: &PropertyKey) -> Result<(), DispatchError> {861 let key_str = sp_std::str::from_utf8(key.as_slice())862 .map_err(|_| <Error<T>>::InvalidCharacterInPropertyKey)?;863864 for ch in key_str.chars() {865 if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {866 return Err(<Error<T>>::InvalidCharacterInPropertyKey.into());867 }868 }869870 Ok(())871 }872873 pub fn filter_collection_properties(874 collection_id: CollectionId,875 keys: Vec<PropertyKey>,876 ) -> Result<Vec<Property>, DispatchError> {877 let properties = Self::collection_properties(collection_id);878879 let properties = keys880 .into_iter()881 .filter_map(|key| {882 properties.get(&key).map(|value| Property {883 key,884 value: value.clone(),885 })886 })887 .collect();888889 Ok(properties)890 }891892 pub fn filter_property_permissions(893 collection_id: CollectionId,894 keys: Vec<PropertyKey>,895 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {896 let permissions = Self::property_permissions(collection_id);897898 let key_permissions = keys899 .into_iter()900 .filter_map(|key| {901 permissions902 .get(&key)903 .map(|permission| PropertyKeyPermission {904 key,905 permission: permission.clone(),906 })907 })908 .collect();909910 Ok(key_permissions)911 }912913 fn set_field_raw(914 collection_id: CollectionId,915 field: CollectionField,916 value: Vec<u8>,917 ) -> DispatchResult {918 if !value.is_empty() {919 <CollectionData<T>>::insert(920 (collection_id, field),921 BoundedVec::try_from(value).map_err(|_| <Error<T>>::CollectionFieldSizeExceeded)?,922 )923 } else {924 <CollectionData<T>>::remove((collection_id, field));925 }926 Ok(())927 }928929 pub fn set_field(930 collection: &CollectionHandle<T>,931 sender: &T::CrossAccountId,932 field: CollectionField,933 value: Vec<u8>,934 ) -> DispatchResult {935 collection.check_is_owner_or_admin(sender)?;936937 // =========938939 Self::set_field_raw(collection.id, field, value)940 }941942 pub fn toggle_allowlist(943 collection: &CollectionHandle<T>,944 sender: &T::CrossAccountId,945 user: &T::CrossAccountId,946 allowed: bool,947 ) -> DispatchResult {948 collection.check_is_owner_or_admin(sender)?;949950 // =========951952 if allowed {953 <Allowlist<T>>::insert((collection.id, user), true);954 } else {955 <Allowlist<T>>::remove((collection.id, user));956 }957958 Ok(())959 }960961 pub fn toggle_admin(962 collection: &CollectionHandle<T>,963 sender: &T::CrossAccountId,964 user: &T::CrossAccountId,965 admin: bool,966 ) -> DispatchResult {967 collection.check_is_owner_or_admin(sender)?;968969 let was_admin = <IsAdmin<T>>::get((collection.id, user));970 if was_admin == admin {971 return Ok(());972 }973 let amount = <AdminAmount<T>>::get(collection.id);974975 if admin {976 let amount = amount977 .checked_add(1)978 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;979 ensure!(980 amount <= Self::collection_admins_limit(),981 <Error<T>>::CollectionAdminCountExceeded,982 );983984 // =========985986 <AdminAmount<T>>::insert(collection.id, amount);987 <IsAdmin<T>>::insert((collection.id, user), true);988 } else {989 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));990 <IsAdmin<T>>::remove((collection.id, user));991 }992993 Ok(())994 }995996 pub fn clamp_limits(997 mode: CollectionMode,998 old_limit: &CollectionLimits,999 mut new_limit: CollectionLimits,1000 ) -> Result<CollectionLimits, DispatchError> {1001 macro_rules! limit_default {1002 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1003 $(1004 if let Some($new) = $new.$field {1005 let $old = $old.$field($($arg)?);1006 let _ = $new;1007 let _ = $old;1008 $check1009 } else {1010 $new.$field = $old.$field1011 }1012 )*1013 }};1014 }10151016 limit_default!(old_limit, new_limit,1017 account_token_ownership_limit => ensure!(1018 new_limit <= MAX_TOKEN_OWNERSHIP,1019 <Error<T>>::CollectionLimitBoundsExceeded,1020 ),1021 sponsor_transfer_timeout(match mode {1022 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1023 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1024 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1025 }) => ensure!(1026 new_limit <= MAX_SPONSOR_TIMEOUT,1027 <Error<T>>::CollectionLimitBoundsExceeded,1028 ),1029 sponsored_data_size => ensure!(1030 new_limit <= CUSTOM_DATA_LIMIT,1031 <Error<T>>::CollectionLimitBoundsExceeded,1032 ),1033 token_limit => ensure!(1034 old_limit >= new_limit && new_limit > 0,1035 <Error<T>>::CollectionTokenLimitExceeded1036 ),1037 owner_can_transfer => ensure!(1038 old_limit || !new_limit,1039 <Error<T>>::OwnerPermissionsCantBeReverted,1040 ),1041 owner_can_destroy => ensure!(1042 old_limit || !new_limit,1043 <Error<T>>::OwnerPermissionsCantBeReverted,1044 ),1045 sponsored_data_rate_limit => {},1046 transfers_enabled => {},1047 );1048 Ok(new_limit)1049 }1050}10511052#[macro_export]1053macro_rules! unsupported {1054 () => {1055 Err(<Error<T>>::UnsupportedOperation.into())1056 };1057}10581059/// Worst cases1060pub trait CommonWeightInfo<CrossAccountId> {1061 fn create_item() -> Weight;1062 fn create_multiple_items(amount: u32) -> Weight;1063 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;1064 fn burn_item() -> Weight;1065 fn set_collection_properties(amount: u32) -> Weight;1066 fn delete_collection_properties(amount: u32) -> Weight;1067 fn set_token_properties(amount: u32) -> Weight;1068 fn delete_token_properties(amount: u32) -> Weight;1069 fn set_property_permissions(amount: u32) -> Weight;1070 fn transfer() -> Weight;1071 fn approve() -> Weight;1072 fn transfer_from() -> Weight;1073 fn burn_from() -> Weight;1074}10751076pub trait CommonCollectionOperations<T: Config> {1077 fn create_item(1078 &self,1079 sender: T::CrossAccountId,1080 to: T::CrossAccountId,1081 data: CreateItemData,1082 nesting_budget: &dyn Budget,1083 ) -> DispatchResultWithPostInfo;1084 fn create_multiple_items(1085 &self,1086 sender: T::CrossAccountId,1087 to: T::CrossAccountId,1088 data: Vec<CreateItemData>,1089 nesting_budget: &dyn Budget,1090 ) -> DispatchResultWithPostInfo;1091 fn create_multiple_items_ex(1092 &self,1093 sender: T::CrossAccountId,1094 data: CreateItemExData<T::CrossAccountId>,1095 nesting_budget: &dyn Budget,1096 ) -> DispatchResultWithPostInfo;1097 fn burn_item(1098 &self,1099 sender: T::CrossAccountId,1100 token: TokenId,1101 amount: u128,1102 ) -> DispatchResultWithPostInfo;1103 fn set_collection_properties(1104 &self,1105 sender: T::CrossAccountId,1106 properties: Vec<Property>,1107 ) -> DispatchResultWithPostInfo;1108 fn delete_collection_properties(1109 &self,1110 sender: &T::CrossAccountId,1111 property_keys: Vec<PropertyKey>,1112 ) -> DispatchResultWithPostInfo;1113 fn set_token_properties(1114 &self,1115 sender: T::CrossAccountId,1116 token_id: TokenId,1117 property: Vec<Property>,1118 ) -> DispatchResultWithPostInfo;1119 fn delete_token_properties(1120 &self,1121 sender: T::CrossAccountId,1122 token_id: TokenId,1123 property_keys: Vec<PropertyKey>,1124 ) -> DispatchResultWithPostInfo;1125 fn set_property_permissions(1126 &self,1127 sender: &T::CrossAccountId,1128 property_permissions: Vec<PropertyKeyPermission>,1129 ) -> DispatchResultWithPostInfo;1130 fn transfer(1131 &self,1132 sender: T::CrossAccountId,1133 to: T::CrossAccountId,1134 token: TokenId,1135 amount: u128,1136 nesting_budget: &dyn Budget,1137 ) -> DispatchResultWithPostInfo;1138 fn approve(1139 &self,1140 sender: T::CrossAccountId,1141 spender: T::CrossAccountId,1142 token: TokenId,1143 amount: u128,1144 ) -> DispatchResultWithPostInfo;1145 fn transfer_from(1146 &self,1147 sender: T::CrossAccountId,1148 from: T::CrossAccountId,1149 to: T::CrossAccountId,1150 token: TokenId,1151 amount: u128,1152 nesting_budget: &dyn Budget,1153 ) -> DispatchResultWithPostInfo;1154 fn burn_from(1155 &self,1156 sender: T::CrossAccountId,1157 from: T::CrossAccountId,1158 token: TokenId,1159 amount: u128,1160 nesting_budget: &dyn Budget,1161 ) -> DispatchResultWithPostInfo;11621163 fn check_nesting(1164 &self,1165 sender: T::CrossAccountId,1166 from: (CollectionId, TokenId),1167 under: TokenId,1168 budget: &dyn Budget,1169 ) -> DispatchResult;11701171 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;1172 fn collection_tokens(&self) -> Vec<TokenId>;1173 fn token_exists(&self, token: TokenId) -> bool;1174 fn last_token_id(&self) -> TokenId;11751176 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;1177 fn const_metadata(&self, token: TokenId) -> Vec<u8>;1178 fn token_properties(&self, token_id: TokenId, keys: Vec<PropertyKey>) -> Vec<Property>;1179 /// Amount of unique collection tokens1180 fn total_supply(&self) -> u32;1181 /// Amount of different tokens account has (Applicable to nonfungible/refungible)1182 fn account_balance(&self, account: T::CrossAccountId) -> u32;1183 /// Amount of specific token account have (Applicable to fungible/refungible)1184 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;1185 fn allowance(1186 &self,1187 sender: T::CrossAccountId,1188 spender: T::CrossAccountId,1189 token: TokenId,1190 ) -> u128;1191}11921193// Flexible enough for implementing CommonCollectionOperations1194pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1195 let post_info = PostDispatchInfo {1196 actual_weight: Some(weight),1197 pays_fee: Pays::Yes,1198 };1199 match res {1200 Ok(()) => Ok(post_info),1201 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1202 }1203}12041205impl<T: Config> From<PropertiesError> for Error<T> {1206 fn from(error: PropertiesError) -> Self {1207 match error {1208 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1209 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1210 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1211 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1212 }1213 }1214}pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -16,12 +16,12 @@
use core::marker::PhantomData;
-use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
+use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
-use up_data_structs::{CustomDataLimit, Property, PropertyKey, PropertyKeyPermission};
+use up_data_structs::{Property, PropertyKey, PropertyKeyPermission};
use crate::{
Allowance, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf, weights::WeightInfo,
@@ -85,11 +85,6 @@
fn burn_from() -> Weight {
<SelfWeightOf<T>>::burn_from()
}
-
- fn set_variable_metadata(_bytes: u32) -> Weight {
- // Error
- 0
- }
}
impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {
@@ -287,15 +282,6 @@
fail!(<Error<T>>::SettingPropertiesNotAllowed)
}
- fn set_variable_metadata(
- &self,
- _sender: T::CrossAccountId,
- _token: TokenId,
- _data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::FungibleItemsDontHaveData)
- }
-
fn check_nesting(
&self,
_sender: <T>::CrossAccountId,
@@ -330,9 +316,6 @@
None
}
fn const_metadata(&self, _token: TokenId) -> Vec<u8> {
- Vec::new()
- }
- fn variable_metadata(&self, _token: TokenId) -> Vec<u8> {
Vec::new()
}
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -27,6 +27,7 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
+struct-versioning = { path = "../../crates/struct-versioning" }
[features]
default = ["std"]
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -28,10 +28,8 @@
fn create_max_item_data<T: Config>(owner: T::CrossAccountId) -> CreateItemData<T> {
let const_data = create_data::<CUSTOM_DATA_LIMIT>();
- let variable_data = create_data::<CUSTOM_DATA_LIMIT>();
CreateItemData::<T> {
const_data,
- variable_data,
owner,
}
}
@@ -125,14 +123,4 @@
let item = create_max_item(&collection, &owner, sender.clone())?;
<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&burner))?;
}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, &Unlimited)?}
-
- set_variable_metadata {
- let b in 0..CUSTOM_DATA_LIMIT;
- bench_init!{
- owner: sub; collection: collection(owner);
- owner: cross_from_sub; sender: cross_sub;
- };
- let item = create_max_item(&collection, &owner, sender.clone())?;
- let data = create_var_data(b).try_into().unwrap();
- }: {<Pallet<T>>::set_variable_metadata(&collection, &sender, item, data)?}
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -16,9 +16,9 @@
use core::marker::PhantomData;
-use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
+use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use up_data_structs::{
- TokenId, CustomDataLimit, CreateItemExData, CollectionId, budget::Budget, Property,
+ TokenId, CreateItemExData, CollectionId, budget::Budget, Property,
PropertyKey, PropertyKeyPermission,
};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
@@ -85,10 +85,6 @@
fn burn_from() -> Weight {
<SelfWeightOf<T>>::burn_from()
- }
-
- fn set_variable_metadata(bytes: u32) -> Weight {
- <SelfWeightOf<T>>::set_variable_metadata(bytes)
}
}
@@ -99,7 +95,6 @@
match data {
up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {
const_data: data.const_data,
- variable_data: data.variable_data,
properties: data.properties,
owner: to.clone(),
}),
@@ -325,19 +320,6 @@
} else {
Ok(().into())
}
- }
-
- fn set_variable_metadata(
- &self,
- sender: T::CrossAccountId,
- token: TokenId,
- data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResultWithPostInfo {
- let len = data.len();
- with_weight(
- <Pallet<T>>::set_variable_metadata(self, &sender, token, data),
- <CommonWeights<T>>::set_variable_metadata(len as u32),
- )
}
fn check_nesting(
@@ -376,12 +358,6 @@
fn const_metadata(&self, token: TokenId) -> Vec<u8> {
<TokenData<T>>::get((self.id, token))
.map(|t| t.const_data)
- .unwrap_or_default()
- .into_inner()
- }
- fn variable_metadata(&self, token: TokenId) -> Vec<u8> {
- <TokenData<T>>::get((self.id, token))
- .map(|t| t.variable_data)
.unwrap_or_default()
.into_inner()
}
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -24,7 +24,7 @@
use up_data_structs::{TokenId, SchemaVersion};
use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_core::{H160, U256};
-use sp_std::{vec::Vec, vec};
+use sp_std::vec::Vec;
use pallet_common::{
erc::{CommonEvmHandler, PrecompileResult, CollectionPropertiesCall},
CollectionHandle,
@@ -274,7 +274,6 @@
&caller,
CreateItemData::<T> {
const_data: BoundedVec::default(),
- variable_data: BoundedVec::default(),
properties: BoundedVec::default(),
owner: to,
},
@@ -322,7 +321,6 @@
const_data: Vec::<u8>::from(token_uri)
.try_into()
.map_err(|_| "token uri is too long")?,
- variable_data: BoundedVec::default(),
properties: BoundedVec::default(),
owner: to,
},
@@ -387,37 +385,6 @@
.into())
}
- #[weight(<SelfWeightOf<T>>::set_variable_metadata(data.len() as u32))]
- fn set_variable_metadata(
- &mut self,
- caller: caller,
- token_id: uint256,
- data: bytes,
- ) -> Result<void> {
- let caller = T::CrossAccountId::from_eth(caller);
- let token = token_id.try_into()?;
-
- <Pallet<T>>::set_variable_metadata(
- self,
- &caller,
- token,
- data.try_into()
- .map_err(|_| "metadata size exceeded limit")?,
- )
- .map_err(dispatch_to_evm::<T>)?;
- Ok(())
- }
-
- fn get_variable_metadata(&self, token_id: uint256) -> Result<bytes> {
- self.consume_store_reads(1)?;
- let token: TokenId = token_id.try_into()?;
-
- Ok(<TokenData<T>>::get((self.id, token))
- .ok_or("token not found")?
- .variable_data
- .into_inner())
- }
-
#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]
fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -440,7 +407,6 @@
let data = (0..total_tokens)
.map(|_| CreateItemData::<T> {
const_data: BoundedVec::default(),
- variable_data: BoundedVec::default(),
properties: BoundedVec::default(),
owner: to.clone(),
})
@@ -484,7 +450,6 @@
const_data: Vec::<u8>::from(token_uri)
.try_into()
.map_err(|_| "token uri is too long")?,
- variable_data: vec![].try_into().unwrap(),
properties: BoundedVec::default(),
owner: to.clone(),
});
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -49,17 +49,22 @@
pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;
pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
+#[struct_versioning::versioned(version = 2, upper)]
#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]
pub struct ItemData<CrossAccountId> {
pub const_data: BoundedVec<u8, CustomDataLimit>,
+
+ #[version(..2)]
pub variable_data: BoundedVec<u8, CustomDataLimit>,
+
pub owner: CrossAccountId,
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
- use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};
+ use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};
+ use frame_system::pallet_prelude::*;
use up_data_structs::{CollectionId, TokenId};
use super::weights::WeightInfo;
@@ -78,7 +83,10 @@
type WeightInfo: WeightInfo;
}
+ const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
+
#[pallet::pallet]
+ #[pallet::storage_version(STORAGE_VERSION)]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
@@ -133,6 +141,19 @@
Value = T::CrossAccountId,
QueryKind = OptionQuery,
>;
+
+ #[pallet::hooks]
+ impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
+ fn on_runtime_upgrade() -> Weight {
+ if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {
+ <TokenData<T>>::translate_values::<ItemDataVersion1<T::CrossAccountId>, _>(|v| {
+ Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))
+ })
+ }
+
+ 0
+ }
+ }
}
pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);
@@ -577,7 +598,6 @@
(collection.id, token),
ItemData {
const_data: data.const_data,
- variable_data: data.variable_data,
owner: data.owner.clone(),
},
);
@@ -773,28 +793,6 @@
// =========
Self::burn(collection, from, token)
- }
-
- pub fn set_variable_metadata(
- collection: &NonfungibleHandle<T>,
- sender: &T::CrossAccountId,
- token: TokenId,
- data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResult {
- let token_data =
- <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
- collection.check_can_update_meta(sender, &token_data.owner)?;
-
- // =========
-
- <TokenData<T>>::insert(
- (collection.id, token),
- ItemData {
- variable_data: data,
- ..token_data
- },
- );
- Ok(())
}
pub fn check_nesting(
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -61,6 +61,24 @@
}
}
+// Selector: 56fd500b
+contract CollectionProperties is Dummy, ERC165 {
+ // Selector: setProperty(string,string) 62d9491f
+ function setProperty(string memory key, string memory value) public {
+ require(false, stub_error);
+ key;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: deleteProperty(string) 34241914
+ function deleteProperty(string memory key) public {
+ require(false, stub_error);
+ key;
+ dummy = 0;
+ }
+}
+
// Selector: 58800161
contract ERC721 is Dummy, ERC165, ERC721Events {
// Selector: balanceOf(address) 70a08231
@@ -276,7 +294,7 @@
}
}
-// Selector: e562194d
+// Selector: d74d154f
contract ERC721UniqueExtensions is Dummy, ERC165 {
// Selector: transfer(address,uint256) a9059cbb
function transfer(address to, uint256 tokenId) public {
@@ -301,26 +319,6 @@
return 0;
}
- // Selector: setVariableMetadata(uint256,bytes) d4eac26d
- function setVariableMetadata(uint256 tokenId, bytes memory data) public {
- require(false, stub_error);
- tokenId;
- data;
- dummy = 0;
- }
-
- // Selector: getVariableMetadata(uint256) e6c5ce6f
- function getVariableMetadata(uint256 tokenId)
- public
- view
- returns (bytes memory)
- {
- require(false, stub_error);
- tokenId;
- dummy;
- return hex"";
- }
-
// Selector: mintBulk(address,uint256[]) 44a9945e
function mintBulk(address to, uint256[] memory tokenIds)
public
@@ -354,5 +352,6 @@
ERC721Enumerable,
ERC721UniqueExtensions,
ERC721Mintable,
- ERC721Burnable
+ ERC721Burnable,
+ CollectionProperties
{}
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -45,7 +45,6 @@
fn approve() -> Weight;
fn transfer_from() -> Weight;
fn burn_from() -> Weight;
- fn set_variable_metadata(b: u32, ) -> Weight;
}
/// Weights for pallet_nonfungible using the Substrate node and recommended hardware.
@@ -155,12 +154,6 @@
(27_580_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(5 as Weight))
- }
- // Storage: Nonfungible TokenData (r:1 w:1)
- fn set_variable_metadata(_b: u32, ) -> Weight {
- (7_700_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(1 as Weight))
- .saturating_add(T::DbWeight::get().writes(1 as Weight))
}
}
@@ -270,11 +263,5 @@
(27_580_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
- }
- // Storage: Nonfungible TokenData (r:1 w:1)
- fn set_variable_metadata(_b: u32, ) -> Weight {
- (7_700_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(1 as Weight))
- .saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
}
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -24,6 +24,7 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
+struct-versioning = { path = "../../crates/struct-versioning" }
[features]
default = ["std"]
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -31,10 +31,8 @@
users: impl IntoIterator<Item = (CrossAccountId, u128)>,
) -> CreateRefungibleExData<CrossAccountId> {
let const_data = create_data::<CUSTOM_DATA_LIMIT>();
- let variable_data = create_data::<CUSTOM_DATA_LIMIT>();
CreateRefungibleExData {
const_data,
- variable_data,
users: users
.into_iter()
.collect::<BTreeMap<_, _>>()
@@ -203,14 +201,4 @@
let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
<Pallet<T>>::set_allowance(&collection, &sender, &burner, item, 200)?;
}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, 200, &Unlimited)?}
-
- set_variable_metadata {
- let b in 0..CUSTOM_DATA_LIMIT;
- bench_init!{
- owner: sub; collection: collection(owner);
- sender: cross_from_sub(owner);
- };
- let item = create_max_item(&collection, &sender, [(sender.clone(), 200)])?;
- let data = create_var_data(b).try_into().unwrap();
- }: {<Pallet<T>>::set_variable_metadata(&collection, &sender, item, data)?}
}
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -17,9 +17,9 @@
use core::marker::PhantomData;
use sp_std::collections::btree_map::BTreeMap;
-use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight, BoundedVec};
+use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};
use up_data_structs::{
- CollectionId, TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData,
+ CollectionId, TokenId, CreateItemExData, CreateRefungibleExData,
budget::Budget, Property, PropertyKey, PropertyKeyPermission,
};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
@@ -110,10 +110,6 @@
fn burn_from() -> Weight {
<SelfWeightOf<T>>::burn_from()
- }
-
- fn set_variable_metadata(bytes: u32) -> Weight {
- <SelfWeightOf<T>>::set_variable_metadata(bytes)
}
}
@@ -124,7 +120,6 @@
match data {
up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateRefungibleExData {
const_data: data.const_data,
- variable_data: data.variable_data,
users: {
let mut out = BTreeMap::new();
out.insert(to.clone(), data.pieces);
@@ -306,19 +301,6 @@
fail!(<Error<T>>::SettingPropertiesNotAllowed)
}
- fn set_variable_metadata(
- &self,
- sender: T::CrossAccountId,
- token: TokenId,
- data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResultWithPostInfo {
- let len = data.len();
- with_weight(
- <Pallet<T>>::set_variable_metadata(self, &sender, token, data),
- <CommonWeights<T>>::set_variable_metadata(len as u32),
- )
- }
-
fn check_nesting(
&self,
_sender: <T>::CrossAccountId,
@@ -355,11 +337,6 @@
fn const_metadata(&self, token: TokenId) -> Vec<u8> {
<TokenData<T>>::get((self.id, token))
.const_data
- .into_inner()
- }
- fn variable_metadata(&self, token: TokenId) -> Vec<u8> {
- <TokenData<T>>::get((self.id, token))
- .variable_data
.into_inner()
}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -41,16 +41,20 @@
pub mod weights;
pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
+#[struct_versioning::versioned(version = 2, upper)]
#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]
pub struct ItemData {
pub const_data: BoundedVec<u8, CustomDataLimit>,
+
+ #[version(..2)]
pub variable_data: BoundedVec<u8, CustomDataLimit>,
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
- use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};
+ use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};
+ use frame_system::pallet_prelude::*;
use up_data_structs::{CollectionId, TokenId};
use super::weights::WeightInfo;
@@ -73,7 +77,10 @@
type WeightInfo: WeightInfo;
}
+ const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
+
#[pallet::pallet]
+ #[pallet::storage_version(STORAGE_VERSION)]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
@@ -146,6 +153,19 @@
Value = u128,
QueryKind = ValueQuery,
>;
+
+ #[pallet::hooks]
+ impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
+ fn on_runtime_upgrade() -> Weight {
+ if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {
+ <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {
+ Some(<ItemDataVersion2>::from(v))
+ })
+ }
+
+ 0
+ }
+ }
}
pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);
@@ -494,7 +514,6 @@
(collection.id, token_id),
ItemData {
const_data: token.const_data,
- variable_data: token.variable_data,
},
);
for (user, amount) in token.users.into_iter() {
@@ -643,31 +662,6 @@
if let Some(allowance) = allowance {
Self::set_allowance_unchecked(collection, from, spender, token, allowance);
}
- Ok(())
- }
-
- pub fn set_variable_metadata(
- collection: &RefungibleHandle<T>,
- sender: &T::CrossAccountId,
- token: TokenId,
- data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResult {
- collection.check_can_update_meta(
- sender,
- &T::CrossAccountId::from_sub(collection.owner.clone()),
- )?;
-
- let token_data = <TokenData<T>>::get((collection.id, token));
-
- // =========
-
- <TokenData<T>>::insert(
- (collection.id, token),
- ItemData {
- variable_data: data,
- ..token_data
- },
- );
Ok(())
}
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -53,7 +53,6 @@
fn transfer_from_removing() -> Weight;
fn transfer_from_creating_removing() -> Weight;
fn burn_from() -> Weight;
- fn set_variable_metadata(b: u32, ) -> Weight;
}
/// Weights for pallet_refungible using the Substrate node and recommended hardware.
@@ -242,12 +241,6 @@
(42_043_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(7 as Weight))
- }
- // Storage: Refungible TokenData (r:1 w:1)
- fn set_variable_metadata(_b: u32, ) -> Weight {
- (7_364_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(1 as Weight))
- .saturating_add(T::DbWeight::get().writes(1 as Weight))
}
}
@@ -436,11 +429,5 @@
(42_043_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(7 as Weight))
- }
- // Storage: Refungible TokenData (r:1 w:1)
- fn set_variable_metadata(_b: u32, ) -> Weight {
- (7_364_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(1 as Weight))
- .saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -38,7 +38,7 @@
CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,
- SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData, CustomDataLimit,
+ SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData,
CreateItemExData, budget, CollectionField, Property, PropertyKey, PropertyKeyPermission,
};
use pallet_evm::account::CrossAccountId;
@@ -238,9 +238,6 @@
pub ReFungibleTransferBasket get(fn refungible_transfer_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;
//#endregion
- /// Variable metadata sponsoring
- /// Collection id (controlled?2), token id (controlled?2)
- pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;
/// Approval sponsoring
pub NftApproveBasket get(fn nft_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;
pub FungibleApproveBasket get(fn fungible_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;
@@ -333,7 +330,6 @@
<FungibleTransferBasket<T>>::remove_prefix(collection_id, None);
<ReFungibleTransferBasket<T>>::remove_prefix((collection_id,), None);
- <VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);
<NftApproveBasket<T>>::remove_prefix(collection_id, None);
<FungibleApproveBasket<T>>::remove_prefix(collection_id, None);
<RefungibleApproveBasket<T>>::remove_prefix((collection_id,), None);
@@ -929,31 +925,6 @@
let budget = budget::Value::new(2);
dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))
- }
-
- /// Set off-chain data schema.
- ///
- /// # Permissions
- ///
- /// * Collection Owner
- /// * Collection Admin
- ///
- /// # Arguments
- ///
- /// * collection_id.
- ///
- /// * schema: String representing the offchain data schema.
- #[weight = T::CommonWeightInfo::set_variable_metadata(data.len() as u32)]
- #[transactional]
- pub fn set_variable_meta_data (
- origin,
- collection_id: CollectionId,
- item_id: TokenId,
- data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResultWithPostInfo {
- let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
- dispatch_call::<T, _>(collection_id, |d| d.set_variable_metadata(sender, item_id, data))
}
/// Set meta_update_permission value for particular collection
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -364,28 +364,6 @@
pub type CollectionPropertiesVec =
BoundedVec<Property, ConstU32<MAX_COLLECTION_PROPERTIES_ENCODE_LEN>>;
-#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub struct NftItemType<AccountId> {
- pub owner: AccountId,
- pub const_data: Vec<u8>,
- pub variable_data: Vec<u8>,
-}
-
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub struct FungibleItemType {
- pub value: u128,
-}
-
-#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub struct ReFungibleItemType<AccountId> {
- pub owner: Vec<Ownership<AccountId>>,
- pub const_data: Vec<u8>,
- pub variable_data: Vec<u8>,
-}
-
/// All fields are wrapped in `Option`s, where None means chain default
#[struct_versioning::versioned(version = 2, upper)]
#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
@@ -393,6 +371,8 @@
pub struct CollectionLimits {
pub account_token_ownership_limit: Option<u32>,
pub sponsored_data_size: Option<u32>,
+
+ /// FIXME should we delete this or repurpose it?
/// None - setVariableMetadata is not sponsored
/// Some(v) - setVariableMetadata is sponsored
/// if there is v block between txs
@@ -490,9 +470,6 @@
#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub const_data: BoundedVec<u8, CustomDataLimit>,
- #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
- #[derivative(Debug(format_with = "bounded::vec_debug"))]
- pub variable_data: BoundedVec<u8, CustomDataLimit>,
#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
#[derivative(Debug(format_with = "bounded::vec_debug"))]
@@ -512,9 +489,6 @@
#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub const_data: BoundedVec<u8, CustomDataLimit>,
- #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
- #[derivative(Debug(format_with = "bounded::vec_debug"))]
- pub variable_data: BoundedVec<u8, CustomDataLimit>,
pub pieces: u128,
}
@@ -545,8 +519,6 @@
pub struct CreateNftExData<CrossAccountId> {
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub const_data: BoundedVec<u8, CustomDataLimit>,
- #[derivative(Debug(format_with = "bounded::vec_debug"))]
- pub variable_data: BoundedVec<u8, CustomDataLimit>,
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub properties: CollectionPropertiesVec,
pub owner: CrossAccountId,
@@ -557,8 +529,6 @@
pub struct CreateRefungibleExData<CrossAccountId> {
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub const_data: BoundedVec<u8, CustomDataLimit>,
- #[derivative(Debug(format_with = "bounded::vec_debug"))]
- pub variable_data: BoundedVec<u8, CustomDataLimit>,
#[derivative(Debug(format_with = "bounded::map_debug"))]
pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
}
@@ -586,8 +556,8 @@
impl CreateItemData {
pub fn data_size(&self) -> usize {
match self {
- CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),
- CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),
+ CreateItemData::NFT(data) => data.const_data.len(),
+ CreateItemData::ReFungible(data) => data.const_data.len(),
_ => 0,
}
}
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -42,7 +42,6 @@
fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>>;
- fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>>;
fn collection_properties(collection: CollectionId, properties: Vec<Vec<u8>>) -> Result<Vec<Property>>;
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -32,9 +32,6 @@
fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {
dispatch_unique_runtime!(collection.const_metadata(token))
}
- fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {
- dispatch_unique_runtime!(collection.variable_metadata(token))
- }
fn collection_properties(
collection: CollectionId,
runtime/common/src/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/src/sponsoring.rs
+++ b/runtime/common/src/sponsoring.rs
@@ -21,7 +21,7 @@
storage::{StorageMap, StorageDoubleMap, StorageNMap},
};
use up_data_structs::{
- CollectionId, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MetaUpdatePermission,
+ CollectionId, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, TokenId, CollectionMode,
CreateItemData,
};
@@ -30,7 +30,7 @@
use pallet_evm::account::CrossAccountId;
use pallet_unique::{
Call as UniqueCall, Config as UniqueConfig, FungibleApproveBasket, RefungibleApproveBasket,
- NftApproveBasket, VariableMetaDataBasket, CreateItemBasket, ReFungibleTransferBasket,
+ NftApproveBasket, CreateItemBasket, ReFungibleTransferBasket,
FungibleTransferBasket, NftTransferBasket,
};
use pallet_fungible::Config as FungibleConfig;
@@ -139,64 +139,7 @@
Some(())
}
-
-pub fn withdraw_set_variable_meta_data<T: Config>(
- who: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
- item_id: &TokenId,
- data: &[u8],
-) -> Option<()> {
- // TODO: make it work for admins
- if collection.meta_update_permission != MetaUpdatePermission::ItemOwner {
- return None;
- }
- // preliminary sponsoring correctness check
- match collection.mode {
- CollectionMode::NFT => {
- let owner = pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner;
- if !owner.conv_eq(who) {
- return None;
- }
- }
- CollectionMode::Fungible(_) => {
- if item_id != &TokenId::default() {
- return None;
- }
- if <pallet_fungible::Balance<T>>::get((collection.id, who)) == 0 {
- return None;
- }
- }
- CollectionMode::ReFungible => {
- if !<pallet_refungible::Owned<T>>::get((collection.id, who, item_id)) {
- return None;
- }
- }
- }
- // Can't sponsor fungible collection, this tx will be rejected
- // as invalid
- if matches!(collection.mode, CollectionMode::Fungible(_)) {
- return None;
- }
- if data.len() > collection.limits.sponsored_data_size() as usize {
- return None;
- }
-
- let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
- let limit = collection.limits.sponsored_data_rate_limit()?;
-
- if let Some(last_tx_block) = VariableMetaDataBasket::<T>::get(collection.id, item_id) {
- let timeout = last_tx_block + limit.into();
- if block_number < timeout {
- return None;
- }
- }
-
- <VariableMetaDataBasket<T>>::insert(collection.id, item_id, block_number);
-
- Some(())
-}
-
pub fn withdraw_approve<T: Config>(
collection: &CollectionHandle<T>,
who: &T::AccountId,
@@ -290,20 +233,6 @@
} => {
let (sponsor, collection) = load(*collection_id)?;
withdraw_approve::<T>(&collection, who, item_id).map(|()| sponsor)
- }
- UniqueCall::set_variable_meta_data {
- collection_id,
- item_id,
- data,
- } => {
- let (sponsor, collection) = load(*collection_id)?;
- withdraw_set_variable_meta_data::<T>(
- &T::CrossAccountId::from_sub(who.clone()),
- &collection,
- item_id,
- data,
- )
- .map(|()| sponsor)
}
_ => None,
}
runtime/common/src/weights.rsdiffbeforeafterboth--- a/runtime/common/src/weights.rs
+++ b/runtime/common/src/weights.rs
@@ -86,10 +86,6 @@
dispatch_weight::<T>() + max_weight_of!(transfer_from())
}
- fn set_variable_metadata(bytes: u32) -> Weight {
- dispatch_weight::<T>() + max_weight_of!(set_variable_metadata(bytes))
- }
-
fn burn_from() -> Weight {
dispatch_weight::<T>() + max_weight_of!(burn_from())
}
runtime/tests/src/tests.rsdiffbeforeafterboth--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -47,7 +47,6 @@
fn default_nft_data() -> CreateNftData {
CreateNftData {
const_data: vec![1, 2, 3].try_into().unwrap(),
- variable_data: vec![3, 2, 1].try_into().unwrap(),
}
}
@@ -58,7 +57,6 @@
fn default_re_fungible_data() -> CreateReFungibleData {
CreateReFungibleData {
const_data: vec![1, 2, 3].try_into().unwrap(),
- variable_data: vec![3, 2, 1].try_into().unwrap(),
pieces: 1023,
}
}
@@ -215,7 +213,6 @@
let item = <pallet_nonfungible::TokenData<Test>>::get((collection_id, 1)).unwrap();
assert_eq!(item.const_data, data.const_data.into_inner());
- assert_eq!(item.variable_data, data.variable_data.into_inner());
});
}
@@ -247,7 +244,6 @@
))
.unwrap();
assert_eq!(item.const_data.to_vec(), data.const_data.into_inner());
- assert_eq!(item.variable_data.to_vec(), data.variable_data.into_inner());
}
});
}
@@ -263,7 +259,6 @@
let balance =
<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1)));
assert_eq!(item.const_data, data.const_data.into_inner());
- assert_eq!(item.variable_data, data.variable_data.into_inner());
assert_eq!(balance, 1023);
});
}
@@ -299,7 +294,6 @@
let balance =
<pallet_refungible::Balance<Test>>::get((CollectionId(1), TokenId(1), account(1)));
assert_eq!(item.const_data.to_vec(), data.const_data.into_inner());
- assert_eq!(item.variable_data.to_vec(), data.variable_data.into_inner());
assert_eq!(balance, 1023);
}
});
@@ -413,7 +407,6 @@
create_test_item(collection_id, &data.clone().into());
let item = <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1)));
assert_eq!(item.const_data, data.const_data.into_inner());
- assert_eq!(item.variable_data, data.variable_data.into_inner());
assert_eq!(
<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
1
@@ -2427,117 +2420,6 @@
}
#[test]
-fn set_variable_meta_data_on_nft_token_stores_variable_meta_data() {
- new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
-
- let origin1 = Origin::signed(1);
-
- let data = default_nft_data();
- create_test_item(CollectionId(1), &data.into());
-
- let variable_data = b"test data".to_vec();
- assert_ok!(Unique::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data.clone().try_into().unwrap()
- ));
-
- assert_eq!(
- <pallet_nonfungible::TokenData<Test>>::get((collection_id, 1))
- .unwrap()
- .variable_data,
- variable_data
- );
- });
-}
-
-#[test]
-fn set_variable_meta_data_on_re_fungible_token_stores_variable_meta_data() {
- new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
-
- let origin1 = Origin::signed(1);
-
- let data = default_re_fungible_data();
- create_test_item(collection_id, &data.into());
-
- let variable_data = b"test data".to_vec();
- assert_ok!(Unique::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data.clone().try_into().unwrap()
- ));
-
- assert_eq!(
- <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1))).variable_data,
- variable_data
- );
- });
-}
-
-#[test]
-fn set_variable_meta_data_on_fungible_token_fails() {
- new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
-
- let origin1 = Origin::signed(1);
-
- let data = default_fungible_data();
- create_test_item(collection_id, &data.into());
-
- let variable_data = b"test data".to_vec();
- assert_noop!(
- Unique::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(0),
- variable_data.try_into().unwrap()
- )
- .map_err(|e| e.error),
- <pallet_fungible::Error<Test>>::FungibleItemsDontHaveData
- );
- });
-}
-
-#[test]
-fn set_variable_meta_data_on_nft_with_item_owner_permission_flag() {
- new_test_ext().execute_with(|| {
- //default_limits();
-
- let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
-
- let origin1 = Origin::signed(1);
-
- let data = default_nft_data();
- create_test_item(collection_id, &data.into());
-
- assert_ok!(Unique::set_meta_update_permission_flag(
- origin1.clone(),
- collection_id,
- MetaUpdatePermission::ItemOwner,
- ));
-
- let variable_data = b"ten chars.".to_vec();
- assert_ok!(Unique::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data.clone().try_into().unwrap()
- ));
-
- assert_eq!(
- <pallet_nonfungible::TokenData<Test>>::get((collection_id, TokenId(1)))
- .unwrap()
- .variable_data,
- variable_data
- );
- });
-}
-
-#[test]
fn collection_transfer_flag_works() {
new_test_ext().execute_with(|| {
let origin1 = Origin::signed(1);
@@ -2590,105 +2472,6 @@
}
#[test]
-fn set_variable_meta_data_on_nft_with_admin_flag() {
- new_test_ext().execute_with(|| {
- // default_limits();
-
- let collection_id =
- create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));
-
- let origin1 = Origin::signed(1);
- let origin2 = Origin::signed(2);
-
- assert_ok!(Unique::set_mint_permission(
- origin2.clone(),
- collection_id,
- true
- ));
- assert_ok!(Unique::add_to_allow_list(
- origin2.clone(),
- collection_id,
- account(1)
- ));
-
- assert_ok!(Unique::add_collection_admin(
- origin2.clone(),
- collection_id,
- account(1)
- ));
-
- let data = default_nft_data();
- create_test_item(collection_id, &data.into());
-
- assert_ok!(Unique::set_meta_update_permission_flag(
- origin2.clone(),
- collection_id,
- MetaUpdatePermission::Admin,
- ));
-
- let variable_data = b"test.".to_vec();
- assert_ok!(Unique::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data.clone().try_into().unwrap()
- ));
-
- assert_eq!(
- <pallet_nonfungible::TokenData<Test>>::get((collection_id, 1))
- .unwrap()
- .variable_data,
- variable_data
- );
- });
-}
-
-#[test]
-fn set_variable_meta_data_on_nft_with_admin_flag_neg() {
- new_test_ext().execute_with(|| {
- // default_limits();
-
- let collection_id =
- create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));
-
- let origin1 = Origin::signed(1);
- let origin2 = Origin::signed(2);
-
- assert_ok!(Unique::set_mint_permission(
- origin2.clone(),
- collection_id,
- true
- ));
- assert_ok!(Unique::add_to_allow_list(
- origin2.clone(),
- collection_id,
- account(1)
- ));
-
- let data = default_nft_data();
- create_test_item(collection_id, &data.into());
-
- assert_ok!(Unique::set_meta_update_permission_flag(
- origin2.clone(),
- collection_id,
- MetaUpdatePermission::Admin,
- ));
-
- let variable_data = b"test.".to_vec();
- assert_noop!(
- Unique::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data.try_into().unwrap()
- )
- .map_err(|e| e.error),
- CommonError::<Test>::NoPermission
- );
- });
-}
-
-#[test]
fn set_variable_meta_flag_after_freeze() {
new_test_ext().execute_with(|| {
// default_limits();
@@ -2710,38 +2493,6 @@
MetaUpdatePermission::Admin
),
CommonError::<Test>::MetadataFlagFrozen
- );
- });
-}
-
-#[test]
-fn set_variable_meta_data_on_nft_with_none_flag_neg() {
- new_test_ext().execute_with(|| {
- // default_limits();
-
- let collection_id =
- create_test_collection_for_owner(&CollectionMode::NFT, 1, CollectionId(1));
- let origin1 = Origin::signed(1);
-
- let data = default_nft_data();
- create_test_item(collection_id, &data.into());
-
- assert_ok!(Unique::set_meta_update_permission_flag(
- origin1.clone(),
- collection_id,
- MetaUpdatePermission::None,
- ));
-
- let variable_data = b"test.".to_vec();
- assert_noop!(
- Unique::set_variable_meta_data(
- origin1.clone(),
- collection_id,
- TokenId(1),
- variable_data.try_into().unwrap()
- )
- .map_err(|e| e.error),
- CommonError::<Test>::NoPermission
);
});
}
smart_contracs/transfer/lib.rsdiffbeforeafterboth--- a/smart_contracs/transfer/lib.rs
+++ b/smart_contracs/transfer/lib.rs
@@ -58,14 +58,12 @@
pub enum CreateItemData {
Nft {
const_data: Vec<u8>,
- variable_data: Vec<u8>,
},
Fungible {
value: u128,
},
ReFungible {
const_data: Vec<u8>,
- variable_data: Vec<u8>,
pieces: u128,
},
}
@@ -88,8 +86,6 @@
fn approve(spender: DefaultAccountId, collection_id: u32, item_id: u32, amount: u128);
#[ink(extension = 4, returns_result = false)]
fn transfer_from(owner: DefaultAccountId, recipient: DefaultAccountId, collection_id: u32, item_id: u32, amount: u128);
- #[ink(extension = 5, returns_result = false)]
- fn set_variable_meta_data(collection_id: u32, item_id: u32, data: Vec<u8>);
#[ink(extension = 6, returns_result = false)]
fn toggle_allow_list(collection_id: u32, address: DefaultAccountId, allowlisted: bool);
}
@@ -143,12 +139,6 @@
let _ = self.env()
.extension()
.transfer_from(owner, recipient, collection_id, item_id, amount);
- }
- #[ink(message)]
- pub fn set_variable_meta_data(&mut self, collection_id: u32, item_id: u32, data: Vec<u8>) {
- let _ = self.env()
- .extension()
- .set_variable_meta_data(collection_id, item_id, data);
}
#[ink(message)]
pub fn toggle_allow_list(&mut self, collection_id: u32, address: AccountId, allowlisted: bool) {