difftreelog
CORE-302 Implement setSponsor method.
in: master
10 files changed
Makefilediffbeforeafterboth--- a/Makefile
+++ b/Makefile
@@ -21,7 +21,7 @@
TESTS_API=./tests/src/eth/api/
.PHONY: regenerate_solidity
-regenerate_solidity: UniqueFungible.sol UniqueNFT.sol ContractHelpers.sol
+regenerate_solidity: UniqueFungible.sol UniqueNFT.sol ContractHelpers.sol Collection.sol
UniqueFungible.sol:
PACKAGE=pallet-fungible NAME=erc::gen_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
@@ -36,8 +36,8 @@
PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_impl OUTPUT=$(CONTRACT_HELPERS_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
Collection.sol:
- PACKAGE=pallet-evm-collection NAME=eth::contract_helpers_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
- PACKAGE=pallet-evm-collection NAME=eth::contract_helpers_impl OUTPUT=$(COLLECTION_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+ PACKAGE=pallet-evm-collection NAME=eth::collection_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
+ PACKAGE=pallet-evm-collection NAME=eth::collection_impl OUTPUT=$(COLLECTION_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
UniqueFungible: UniqueFungible.sol
INPUT=$(FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw ./.maintain/scripts/compile_stub.sh
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)]1819extern crate alloc;2021use core::ops::{Deref, DerefMut};22use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};23use sp_std::{vec::Vec, rc::Rc};24use pallet_evm::account::CrossAccountId;25use frame_support::{26 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},27 ensure,28 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},29 BoundedVec,30 weights::Pays,31 transactional,32};33use pallet_evm::GasWeightMapping;34use up_data_structs::{35 COLLECTION_NUMBER_LIMIT,36 Collection,37 RpcCollection,38 CollectionId,39 CreateItemData,40 MAX_TOKEN_PREFIX_LENGTH,41 COLLECTION_ADMINS_LIMIT,42 TokenId,43 CollectionStats,44 MAX_TOKEN_OWNERSHIP,45 CollectionMode,46 NFT_SPONSOR_TRANSFER_TIMEOUT,47 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,48 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,49 MAX_SPONSOR_TIMEOUT,50 CUSTOM_DATA_LIMIT,51 CollectionLimits,52 CreateCollectionData,53 SponsorshipState,54 CreateItemExData,55 SponsoringRateLimit,56 budget::Budget,57 COLLECTION_FIELD_LIMIT,58 PhantomType,59 Property,60 Properties,61 PropertiesPermissionMap,62 PropertyKey,63 PropertyValue,64 PropertyPermission,65 PropertiesError,66 PropertyKeyPermission,67 TokenData,68 TrySetProperty,69 PropertyScope,70 // RMRK71 RmrkCollectionInfo,72 RmrkInstanceInfo,73 RmrkResourceInfo,74 RmrkPropertyInfo,75 RmrkBaseInfo,76 RmrkPartType,77 RmrkTheme,78 RmrkNftChild,79 CollectionPermissions,80 SchemaVersion,81};8283pub use pallet::*;84use sp_core::H160;85use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};86#[cfg(feature = "runtime-benchmarks")]87pub mod benchmarking;88pub mod dispatch;89pub mod erc;90pub mod eth;91pub mod weights;9293pub type SelfWeightOf<T> = <T as Config>::WeightInfo;9495#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]96pub struct CollectionHandle<T: Config> {97 pub id: CollectionId,98 collection: Collection<T::AccountId>,99 pub recorder: SubstrateRecorder<T>,100}101impl<T: Config> WithRecorder<T> for CollectionHandle<T> {102 fn recorder(&self) -> &SubstrateRecorder<T> {103 &self.recorder104 }105 fn into_recorder(self) -> SubstrateRecorder<T> {106 self.recorder107 }108}109impl<T: Config> CollectionHandle<T> {110 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {111 <CollectionById<T>>::get(id).map(|collection| Self {112 id,113 collection,114 recorder: SubstrateRecorder::new(gas_limit),115 })116 }117 pub fn new(id: CollectionId) -> Option<Self> {118 Self::new_with_gas_limit(id, u64::MAX)119 }120 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {121 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)122 }123 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {124 self.recorder125 .consume_gas(T::GasWeightMapping::weight_to_gas(126 <T as frame_system::Config>::DbWeight::get()127 .read128 .saturating_mul(reads),129 ))130 }131 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {132 self.recorder133 .consume_gas(T::GasWeightMapping::weight_to_gas(134 <T as frame_system::Config>::DbWeight::get()135 .write136 .saturating_mul(writes),137 ))138 }139 pub fn save(self) -> DispatchResult {140 <CollectionById<T>>::insert(self.id, self.collection);141 Ok(())142 }143}144impl<T: Config> Deref for CollectionHandle<T> {145 type Target = Collection<T::AccountId>;146147 fn deref(&self) -> &Self::Target {148 &self.collection149 }150}151152impl<T: Config> DerefMut for CollectionHandle<T> {153 fn deref_mut(&mut self) -> &mut Self::Target {154 &mut self.collection155 }156}157158impl<T: Config> CollectionHandle<T> {159 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {160 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);161 Ok(())162 }163 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {164 *subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))165 }166 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {167 ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);168 Ok(())169 }170 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {171 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)172 }173 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {174 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)175 }176 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {177 ensure!(178 <Allowlist<T>>::get((self.id, user)),179 <Error<T>>::AddressNotInAllowlist180 );181 Ok(())182 }183}184185#[frame_support::pallet]186pub mod pallet {187 use super::*;188 use pallet_evm::account;189 use dispatch::CollectionDispatch;190 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};191 use frame_system::pallet_prelude::*;192 use frame_support::traits::Currency;193 use up_data_structs::{TokenId, mapping::TokenAddressMapping};194 use scale_info::TypeInfo;195 use weights::WeightInfo;196197 #[pallet::config]198 pub trait Config:199 frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config200 {201 type WeightInfo: WeightInfo;202 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;203204 type Currency: Currency<Self::AccountId>;205206 #[pallet::constant]207 type CollectionCreationPrice: Get<208 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,209 >;210 type CollectionDispatch: CollectionDispatch<Self>;211212 type TreasuryAccountId: Get<Self::AccountId>;213214 type EvmTokenAddressMapping: TokenAddressMapping<H160>;215 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;216 }217218 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);219220 #[pallet::pallet]221 #[pallet::storage_version(STORAGE_VERSION)]222 #[pallet::generate_store(pub(super) trait Store)]223 pub struct Pallet<T>(_);224225 #[pallet::extra_constants]226 impl<T: Config> Pallet<T> {227 pub fn collection_admins_limit() -> u32 {228 COLLECTION_ADMINS_LIMIT229 }230 }231232 #[pallet::event]233 #[pallet::generate_deposit(pub fn deposit_event)]234 pub enum Event<T: Config> {235 /// New collection was created236 ///237 /// # Arguments238 ///239 /// * collection_id: Globally unique identifier of newly created collection.240 ///241 /// * mode: [CollectionMode] converted into u8.242 ///243 /// * account_id: Collection owner.244 CollectionCreated(CollectionId, u8, T::AccountId),245246 /// New collection was destroyed247 ///248 /// # Arguments249 ///250 /// * collection_id: Globally unique identifier of collection.251 CollectionDestroyed(CollectionId),252253 /// New item was created.254 ///255 /// # Arguments256 ///257 /// * collection_id: Id of the collection where item was created.258 ///259 /// * item_id: Id of an item. Unique within the collection.260 ///261 /// * recipient: Owner of newly created item262 ///263 /// * amount: Always 1 for NFT264 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),265266 /// Collection item was burned.267 ///268 /// # Arguments269 ///270 /// * collection_id.271 ///272 /// * item_id: Identifier of burned NFT.273 ///274 /// * owner: which user has destroyed its tokens275 ///276 /// * amount: Always 1 for NFT277 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),278279 /// Item was transferred280 ///281 /// * collection_id: Id of collection to which item is belong282 ///283 /// * item_id: Id of an item284 ///285 /// * sender: Original owner of item286 ///287 /// * recipient: New owner of item288 ///289 /// * amount: Always 1 for NFT290 Transfer(291 CollectionId,292 TokenId,293 T::CrossAccountId,294 T::CrossAccountId,295 u128,296 ),297298 /// * collection_id299 ///300 /// * item_id301 ///302 /// * sender303 ///304 /// * spender305 ///306 /// * amount307 Approved(308 CollectionId,309 TokenId,310 T::CrossAccountId,311 T::CrossAccountId,312 u128,313 ),314315 CollectionPropertySet(CollectionId, PropertyKey),316317 CollectionPropertyDeleted(CollectionId, PropertyKey),318319 TokenPropertySet(CollectionId, TokenId, PropertyKey),320321 TokenPropertyDeleted(CollectionId, TokenId, PropertyKey),322323 PropertyPermissionSet(CollectionId, PropertyKey),324 }325326 #[pallet::error]327 pub enum Error<T> {328 /// This collection does not exist.329 CollectionNotFound,330 /// Sender parameter and item owner must be equal.331 MustBeTokenOwner,332 /// No permission to perform action333 NoPermission,334 /// Collection is not in mint mode.335 PublicMintingNotAllowed,336 /// Address is not in allow list.337 AddressNotInAllowlist,338339 /// Collection name can not be longer than 63 char.340 CollectionNameLimitExceeded,341 /// Collection description can not be longer than 255 char.342 CollectionDescriptionLimitExceeded,343 /// Token prefix can not be longer than 15 char.344 CollectionTokenPrefixLimitExceeded,345 /// Total collections bound exceeded.346 TotalCollectionsLimitExceeded,347 /// Exceeded max admin count348 CollectionAdminCountExceeded,349 /// Collection limit bounds per collection exceeded350 CollectionLimitBoundsExceeded,351 /// Tried to enable permissions which are only permitted to be disabled352 OwnerPermissionsCantBeReverted,353 /// Collection settings not allowing items transferring354 TransferNotAllowed,355 /// Account token limit exceeded per collection356 AccountTokenLimitExceeded,357 /// Collection token limit exceeded358 CollectionTokenLimitExceeded,359 /// Metadata flag frozen360 MetadataFlagFrozen,361362 /// Item not exists.363 TokenNotFound,364 /// Item balance not enough.365 TokenValueTooLow,366 /// Requested value more than approved.367 ApprovedValueTooLow,368 /// Tried to approve more than owned369 CantApproveMoreThanOwned,370371 /// Can't transfer tokens to ethereum zero address372 AddressIsZero,373 /// Target collection doesn't supports this operation374 UnsupportedOperation,375376 /// Not sufficient founds to perform action377 NotSufficientFounds,378379 /// Collection has nesting disabled380 NestingIsDisabled,381 /// Only owner may nest tokens under this collection382 OnlyOwnerAllowedToNest,383 /// Only tokens from specific collections may nest tokens under this384 SourceCollectionIsNotAllowedToNest,385386 /// Tried to store more data than allowed in collection field387 CollectionFieldSizeExceeded,388389 /// Tried to store more property data than allowed390 NoSpaceForProperty,391392 /// Tried to store more property keys than allowed393 PropertyLimitReached,394395 /// Property key is too long396 PropertyKeyIsTooLong,397398 /// Only ASCII letters, digits, and '_', '-' are allowed399 InvalidCharacterInPropertyKey,400401 /// Empty property keys are forbidden402 EmptyPropertyKey,403 }404405 #[pallet::storage]406 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;407 #[pallet::storage]408 pub type DestroyedCollectionCount<T> =409 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;410411 /// Collection info412 #[pallet::storage]413 pub type CollectionById<T> = StorageMap<414 Hasher = Blake2_128Concat,415 Key = CollectionId,416 Value = Collection<<T as frame_system::Config>::AccountId>,417 QueryKind = OptionQuery,418 >;419420 /// Collection properties421 #[pallet::storage]422 #[pallet::getter(fn collection_properties)]423 pub type CollectionProperties<T> = StorageMap<424 Hasher = Blake2_128Concat,425 Key = CollectionId,426 Value = Properties,427 QueryKind = ValueQuery,428 OnEmpty = up_data_structs::CollectionProperties,429 >;430431 #[pallet::storage]432 #[pallet::getter(fn property_permissions)]433 pub type CollectionPropertyPermissions<T> = StorageMap<434 Hasher = Blake2_128Concat,435 Key = CollectionId,436 Value = PropertiesPermissionMap,437 QueryKind = ValueQuery,438 >;439440 #[pallet::storage]441 pub type AdminAmount<T> = StorageMap<442 Hasher = Blake2_128Concat,443 Key = CollectionId,444 Value = u32,445 QueryKind = ValueQuery,446 >;447448 /// List of collection admins449 #[pallet::storage]450 pub type IsAdmin<T: Config> = StorageNMap<451 Key = (452 Key<Blake2_128Concat, CollectionId>,453 Key<Blake2_128Concat, T::CrossAccountId>,454 ),455 Value = bool,456 QueryKind = ValueQuery,457 >;458459 /// Allowlisted collection users460 #[pallet::storage]461 pub type Allowlist<T: Config> = StorageNMap<462 Key = (463 Key<Blake2_128Concat, CollectionId>,464 Key<Blake2_128Concat, T::CrossAccountId>,465 ),466 Value = bool,467 QueryKind = ValueQuery,468 >;469470 /// Not used by code, exists only to provide some types to metadata471 #[pallet::storage]472 pub type DummyStorageValue<T: Config> = StorageValue<473 Value = (474 CollectionStats,475 CollectionId,476 TokenId,477 PhantomType<TokenData<T::CrossAccountId>>,478 PhantomType<RpcCollection<T::AccountId>>,479 // RMRK480 PhantomType<RmrkCollectionInfo<T::AccountId>>,481 PhantomType<RmrkInstanceInfo<T::AccountId>>,482 PhantomType<RmrkResourceInfo>,483 PhantomType<RmrkPropertyInfo>,484 PhantomType<RmrkBaseInfo<T::AccountId>>,485 PhantomType<RmrkPartType>,486 PhantomType<RmrkTheme>,487 PhantomType<RmrkNftChild>,488 ),489 QueryKind = OptionQuery,490 >;491492 #[pallet::hooks]493 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {494 fn on_runtime_upgrade() -> Weight {495 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {496 use up_data_structs::{CollectionVersion1, CollectionVersion2};497 <CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {498 let mut props = Vec::new();499 if !v.offchain_schema.is_empty() {500 props.push(Property {501 key: b"_old_offchainSchema".to_vec().try_into().unwrap(),502 value: v.offchain_schema.clone().into_inner().try_into().expect("offchain schema too big"),503 });504 }505 if !v.variable_on_chain_schema.is_empty() {506 props.push(Property {507 key: b"_old_variableOnChainSchema".to_vec().try_into().unwrap(),508 value: v.variable_on_chain_schema.clone().into_inner().try_into().expect("offchain schema too big"),509 });510 }511 if !v.const_on_chain_schema.is_empty() {512 props.push(Property {513 key: b"_old_constOnChainSchema".to_vec().try_into().unwrap(),514 value: v.const_on_chain_schema.clone().into_inner().try_into().expect("offchain schema too big"),515 });516 }517 props.push(Property {518 key: b"_old_schemaVersion".to_vec().try_into().unwrap(),519 value: match v.schema_version {520 SchemaVersion::ImageURL => b"ImageUrl".as_slice(),521 SchemaVersion::Unique => b"Unique".as_slice(),522 }.to_vec().try_into().unwrap(),523 });524 Self::set_scoped_collection_properties(525 id,526 PropertyScope::None,527 props.into_iter(),528 ).expect("existing data larger than properties");529 let mut new = CollectionVersion2::from(v.clone());530 new.permissions.access = Some(v.access);531 new.permissions.mint_mode = Some(v.mint_mode);532 Some(new)533 });534 }535536 0537 }538 }539}540541impl<T: Config> Pallet<T> {542 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens543 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {544 ensure!(545 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,546 <Error<T>>::AddressIsZero547 );548 Ok(())549 }550 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {551 <IsAdmin<T>>::iter_prefix((collection,))552 .map(|(a, _)| a)553 .collect()554 }555 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {556 <Allowlist<T>>::iter_prefix((collection,))557 .map(|(a, _)| a)558 .collect()559 }560 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {561 <Allowlist<T>>::get((collection, user))562 }563 pub fn collection_stats() -> CollectionStats {564 let created = <CreatedCollectionCount<T>>::get();565 let destroyed = <DestroyedCollectionCount<T>>::get();566 CollectionStats {567 created: created.0,568 destroyed: destroyed.0,569 alive: created.0 - destroyed.0,570 }571 }572573 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {574 let collection = <CollectionById<T>>::get(collection);575 if collection.is_none() {576 return None;577 }578579 let collection = collection.unwrap();580 let limits = collection.limits;581 let effective_limits = CollectionLimits {582 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),583 sponsored_data_size: Some(limits.sponsored_data_size()),584 sponsored_data_rate_limit: Some(585 limits586 .sponsored_data_rate_limit587 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),588 ),589 token_limit: Some(limits.token_limit()),590 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(591 match collection.mode {592 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,593 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,594 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,595 },596 )),597 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),598 owner_can_transfer: Some(limits.owner_can_transfer()),599 owner_can_destroy: Some(limits.owner_can_destroy()),600 transfers_enabled: Some(limits.transfers_enabled()),601 };602603 Some(effective_limits)604 }605606 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {607 let Collection {608 name,609 description,610 owner,611 mode,612 token_prefix,613 sponsorship,614 limits,615 permissions,616 } = <CollectionById<T>>::get(collection)?;617618 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)619 .into_iter()620 .map(|(key, permission)| PropertyKeyPermission {621 key,622 permission,623 })624 .collect();625626 let properties = <CollectionProperties<T>>::get(collection)627 .into_iter()628 .map(|(key, value)| Property {629 key,630 value,631 })632 .collect();633634 Some(RpcCollection {635 name: name.into_inner(),636 description: description.into_inner(),637 owner,638 mode,639 token_prefix: token_prefix.into_inner(),640 sponsorship,641 limits,642 permissions,643 token_property_permissions,644 properties,645 })646 }647}648649macro_rules! limit_default {650 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{651 $(652 if let Some($new) = $new.$field {653 let $old = $old.$field($($arg)?);654 let _ = $new;655 let _ = $old;656 $check657 } else {658 $new.$field = $old.$field659 }660 )*661 }};662}663macro_rules! limit_default_clone {664 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{665 $(666 if let Some($new) = $new.$field.clone() {667 let $old = $old.$field($($arg)?);668 let _ = $new;669 let _ = $old;670 $check671 } else {672 $new.$field = $old.$field.clone()673 }674 )*675 }};676}677678impl<T: Config> Pallet<T> {679 pub fn init_collection(680 owner: T::AccountId,681 data: CreateCollectionData<T::AccountId>,682 ) -> Result<CollectionId, DispatchError> {683 {684 ensure!(685 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,686 Error::<T>::CollectionTokenPrefixLimitExceeded687 );688 }689690 let created_count = <CreatedCollectionCount<T>>::get()691 .0692 .checked_add(1)693 .ok_or(ArithmeticError::Overflow)?;694 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;695 let id = CollectionId(created_count);696697 // bound Total number of collections698 ensure!(699 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,700 <Error<T>>::TotalCollectionsLimitExceeded701 );702703 // =========704705 let collection = Collection {706 owner: owner.clone(),707 name: data.name,708 mode: data.mode.clone(),709 description: data.description,710 token_prefix: data.token_prefix,711 sponsorship: data712 .pending_sponsor713 .map(SponsorshipState::Unconfirmed)714 .unwrap_or_default(),715 limits: data716 .limits717 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))718 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,719 permissions: data720 .permissions721 .map(|permissions| Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions))722 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,723 };724725 let mut collection_properties = up_data_structs::CollectionProperties::get();726 collection_properties727 .try_set_from_iter(data.properties.into_iter())728 .map_err(<Error<T>>::from)?;729730 CollectionProperties::<T>::insert(id, collection_properties);731732 let mut token_props_permissions = PropertiesPermissionMap::new();733 token_props_permissions734 .try_set_from_iter(data.token_property_permissions.into_iter())735 .map_err(<Error<T>>::from)?;736737 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);738739 // Take a (non-refundable) deposit of collection creation740 {741 let mut imbalance =742 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();743 imbalance.subsume(744 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(745 &T::TreasuryAccountId::get(),746 T::CollectionCreationPrice::get(),747 ),748 );749 <T as Config>::Currency::settle(750 &owner,751 imbalance,752 WithdrawReasons::TRANSFER,753 ExistenceRequirement::KeepAlive,754 )755 .map_err(|_| Error::<T>::NotSufficientFounds)?;756 }757758 <CreatedCollectionCount<T>>::put(created_count);759 <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));760 <CollectionById<T>>::insert(id, collection);761 Ok(id)762 }763764 pub fn destroy_collection(765 collection: CollectionHandle<T>,766 sender: &T::CrossAccountId,767 ) -> DispatchResult {768 ensure!(769 collection.limits.owner_can_destroy(),770 <Error<T>>::NoPermission,771 );772 collection.check_is_owner(sender)?;773774 let destroyed_collections = <DestroyedCollectionCount<T>>::get()775 .0776 .checked_add(1)777 .ok_or(ArithmeticError::Overflow)?;778779 // =========780781 <DestroyedCollectionCount<T>>::put(destroyed_collections);782 <CollectionById<T>>::remove(collection.id);783 <AdminAmount<T>>::remove(collection.id);784 <IsAdmin<T>>::remove_prefix((collection.id,), None);785 <Allowlist<T>>::remove_prefix((collection.id,), None);786 <CollectionProperties<T>>::remove(collection.id);787788 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));789 Ok(())790 }791792 pub fn set_collection_property(793 collection: &CollectionHandle<T>,794 sender: &T::CrossAccountId,795 property: Property,796 ) -> DispatchResult {797 collection.check_is_owner_or_admin(sender)?;798799 CollectionProperties::<T>::try_mutate(collection.id, |properties| {800 let property = property.clone();801 properties.try_set(property.key, property.value)802 })803 .map_err(<Error<T>>::from)?;804805 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));806807 Ok(())808 }809810 pub fn set_scoped_collection_property(811 collection_id: CollectionId,812 scope: PropertyScope,813 property: Property,814 ) -> DispatchResult {815 CollectionProperties::<T>::try_mutate(collection_id, |properties| {816 properties.try_scoped_set(scope, property.key, property.value)817 })818 .map_err(<Error<T>>::from)?;819820 Ok(())821 }822823 pub fn set_scoped_collection_properties(824 collection_id: CollectionId,825 scope: PropertyScope,826 properties: impl Iterator<Item = Property>,827 ) -> DispatchResult {828 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {829 stored_properties.try_scoped_set_from_iter(scope, properties)830 })831 .map_err(<Error<T>>::from)?;832833 Ok(())834 }835836 #[transactional]837 pub fn set_collection_properties(838 collection: &CollectionHandle<T>,839 sender: &T::CrossAccountId,840 properties: Vec<Property>,841 ) -> DispatchResult {842 for property in properties {843 Self::set_collection_property(collection, sender, property)?;844 }845846 Ok(())847 }848849 pub fn delete_collection_property(850 collection: &CollectionHandle<T>,851 sender: &T::CrossAccountId,852 property_key: PropertyKey,853 ) -> DispatchResult {854 collection.check_is_owner_or_admin(sender)?;855856 CollectionProperties::<T>::try_mutate(collection.id, |properties| {857 properties.remove(&property_key)858 })859 .map_err(<Error<T>>::from)?;860861 Self::deposit_event(Event::CollectionPropertyDeleted(862 collection.id,863 property_key,864 ));865866 Ok(())867 }868869 #[transactional]870 pub fn delete_collection_properties(871 collection: &CollectionHandle<T>,872 sender: &T::CrossAccountId,873 property_keys: Vec<PropertyKey>,874 ) -> DispatchResult {875 for key in property_keys {876 Self::delete_collection_property(collection, sender, key)?;877 }878879 Ok(())880 }881882 // For migrations883 pub fn set_property_permission_unchecked(884 collection: CollectionId,885 property_permission: PropertyKeyPermission,886 ) -> DispatchResult {887 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {888 permissions.try_set(property_permission.key, property_permission.permission)889 })890 .map_err(<Error<T>>::from)?;891 Ok(())892 }893894 pub fn set_property_permission(895 collection: &CollectionHandle<T>,896 sender: &T::CrossAccountId,897 property_permission: PropertyKeyPermission,898 ) -> DispatchResult {899 collection.check_is_owner_or_admin(sender)?;900901 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);902 let current_permission = all_permissions.get(&property_permission.key);903 if matches![904 current_permission,905 Some(PropertyPermission { mutable: false, .. })906 ] {907 return Err(<Error<T>>::NoPermission.into());908 }909910 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {911 let property_permission = property_permission.clone();912 permissions.try_set(property_permission.key, property_permission.permission)913 })914 .map_err(<Error<T>>::from)?;915916 Self::deposit_event(Event::PropertyPermissionSet(917 collection.id,918 property_permission.key,919 ));920921 Ok(())922 }923924 #[transactional]925 pub fn set_property_permissions(926 collection: &CollectionHandle<T>,927 sender: &T::CrossAccountId,928 property_permissions: Vec<PropertyKeyPermission>,929 ) -> DispatchResult {930 for prop_pemission in property_permissions {931 Self::set_property_permission(collection, sender, prop_pemission)?;932 }933934 Ok(())935 }936937 pub fn get_collection_property(938 collection_id: CollectionId,939 key: &PropertyKey,940 ) -> Option<PropertyValue> {941 Self::collection_properties(collection_id).get(key).cloned()942 }943944 pub fn bytes_keys_to_property_keys(945 keys: Vec<Vec<u8>>,946 ) -> Result<Vec<PropertyKey>, DispatchError> {947 keys.into_iter()948 .map(|key| -> Result<PropertyKey, DispatchError> {949 key.try_into()950 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())951 })952 .collect::<Result<Vec<PropertyKey>, DispatchError>>()953 }954955 pub fn filter_collection_properties(956 collection_id: CollectionId,957 keys: Option<Vec<PropertyKey>>,958 ) -> Result<Vec<Property>, DispatchError> {959 let properties = Self::collection_properties(collection_id);960961 let properties = keys962 .map(|keys| {963 keys.into_iter()964 .filter_map(|key| {965 properties.get(&key).map(|value| Property {966 key,967 value: value.clone(),968 })969 })970 .collect()971 })972 .unwrap_or_else(|| {973 properties974 .into_iter()975 .map(|(key, value)| Property {976 key,977 value,978 })979 .collect()980 });981982 Ok(properties)983 }984985 pub fn filter_property_permissions(986 collection_id: CollectionId,987 keys: Option<Vec<PropertyKey>>,988 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {989 let permissions = Self::property_permissions(collection_id);990991 let key_permissions = keys992 .map(|keys| {993 keys.into_iter()994 .filter_map(|key| {995 permissions996 .get(&key)997 .map(|permission| PropertyKeyPermission {998 key,999 permission: permission.clone(),1000 })1001 })1002 .collect()1003 })1004 .unwrap_or_else(|| {1005 permissions1006 .into_iter()1007 .map(|(key, permission)| PropertyKeyPermission {1008 key,1009 permission,1010 })1011 .collect()1012 });10131014 Ok(key_permissions)1015 }10161017 pub fn toggle_allowlist(1018 collection: &CollectionHandle<T>,1019 sender: &T::CrossAccountId,1020 user: &T::CrossAccountId,1021 allowed: bool,1022 ) -> DispatchResult {1023 collection.check_is_owner_or_admin(sender)?;10241025 // =========10261027 if allowed {1028 <Allowlist<T>>::insert((collection.id, user), true);1029 } else {1030 <Allowlist<T>>::remove((collection.id, user));1031 }10321033 Ok(())1034 }10351036 pub fn toggle_admin(1037 collection: &CollectionHandle<T>,1038 sender: &T::CrossAccountId,1039 user: &T::CrossAccountId,1040 admin: bool,1041 ) -> DispatchResult {1042 collection.check_is_owner_or_admin(sender)?;10431044 let was_admin = <IsAdmin<T>>::get((collection.id, user));1045 if was_admin == admin {1046 return Ok(());1047 }1048 let amount = <AdminAmount<T>>::get(collection.id);10491050 if admin {1051 let amount = amount1052 .checked_add(1)1053 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1054 ensure!(1055 amount <= Self::collection_admins_limit(),1056 <Error<T>>::CollectionAdminCountExceeded,1057 );10581059 // =========10601061 <AdminAmount<T>>::insert(collection.id, amount);1062 <IsAdmin<T>>::insert((collection.id, user), true);1063 } else {1064 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1065 <IsAdmin<T>>::remove((collection.id, user));1066 }10671068 Ok(())1069 }10701071 pub fn clamp_limits(1072 mode: CollectionMode,1073 old_limit: &CollectionLimits,1074 mut new_limit: CollectionLimits,1075 ) -> Result<CollectionLimits, DispatchError> {1076 limit_default!(old_limit, new_limit,1077 account_token_ownership_limit => ensure!(1078 new_limit <= MAX_TOKEN_OWNERSHIP,1079 <Error<T>>::CollectionLimitBoundsExceeded,1080 ),1081 sponsor_transfer_timeout(match mode {1082 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1083 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1084 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1085 }) => ensure!(1086 new_limit <= MAX_SPONSOR_TIMEOUT,1087 <Error<T>>::CollectionLimitBoundsExceeded,1088 ),1089 sponsored_data_size => ensure!(1090 new_limit <= CUSTOM_DATA_LIMIT,1091 <Error<T>>::CollectionLimitBoundsExceeded,1092 ),1093 token_limit => ensure!(1094 old_limit >= new_limit && new_limit > 0,1095 <Error<T>>::CollectionTokenLimitExceeded1096 ),1097 owner_can_transfer => ensure!(1098 old_limit || !new_limit,1099 <Error<T>>::OwnerPermissionsCantBeReverted,1100 ),1101 owner_can_destroy => ensure!(1102 old_limit || !new_limit,1103 <Error<T>>::OwnerPermissionsCantBeReverted,1104 ),1105 sponsored_data_rate_limit => {},1106 transfers_enabled => {},1107 );1108 Ok(new_limit)1109 }1110 pub fn clamp_permissions(1111 mode: CollectionMode,1112 old_limit: &CollectionPermissions,1113 mut new_limit: CollectionPermissions,1114 ) -> Result<CollectionPermissions, DispatchError> {1115 limit_default_clone!(old_limit, new_limit,1116 );1117 Ok(new_limit)1118 }1119}11201121#[macro_export]1122macro_rules! unsupported {1123 () => {1124 Err(<Error<T>>::UnsupportedOperation.into())1125 };1126}11271128/// Worst cases1129pub trait CommonWeightInfo<CrossAccountId> {1130 fn create_item() -> Weight;1131 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;1132 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;1133 fn burn_item() -> Weight;1134 fn set_collection_properties(amount: u32) -> Weight;1135 fn delete_collection_properties(amount: u32) -> Weight;1136 fn set_token_properties(amount: u32) -> Weight;1137 fn delete_token_properties(amount: u32) -> Weight;1138 fn set_property_permissions(amount: u32) -> Weight;1139 fn transfer() -> Weight;1140 fn approve() -> Weight;1141 fn transfer_from() -> Weight;1142 fn burn_from() -> Weight;1143}11441145pub trait CommonCollectionOperations<T: Config> {1146 fn create_item(1147 &self,1148 sender: T::CrossAccountId,1149 to: T::CrossAccountId,1150 data: CreateItemData,1151 nesting_budget: &dyn Budget,1152 ) -> DispatchResultWithPostInfo;1153 fn create_multiple_items(1154 &self,1155 sender: T::CrossAccountId,1156 to: T::CrossAccountId,1157 data: Vec<CreateItemData>,1158 nesting_budget: &dyn Budget,1159 ) -> DispatchResultWithPostInfo;1160 fn create_multiple_items_ex(1161 &self,1162 sender: T::CrossAccountId,1163 data: CreateItemExData<T::CrossAccountId>,1164 nesting_budget: &dyn Budget,1165 ) -> DispatchResultWithPostInfo;1166 fn burn_item(1167 &self,1168 sender: T::CrossAccountId,1169 token: TokenId,1170 amount: u128,1171 ) -> DispatchResultWithPostInfo;1172 fn set_collection_properties(1173 &self,1174 sender: T::CrossAccountId,1175 properties: Vec<Property>,1176 ) -> DispatchResultWithPostInfo;1177 fn delete_collection_properties(1178 &self,1179 sender: &T::CrossAccountId,1180 property_keys: Vec<PropertyKey>,1181 ) -> DispatchResultWithPostInfo;1182 fn set_token_properties(1183 &self,1184 sender: T::CrossAccountId,1185 token_id: TokenId,1186 property: Vec<Property>,1187 ) -> DispatchResultWithPostInfo;1188 fn delete_token_properties(1189 &self,1190 sender: T::CrossAccountId,1191 token_id: TokenId,1192 property_keys: Vec<PropertyKey>,1193 ) -> DispatchResultWithPostInfo;1194 fn set_property_permissions(1195 &self,1196 sender: &T::CrossAccountId,1197 property_permissions: Vec<PropertyKeyPermission>,1198 ) -> DispatchResultWithPostInfo;1199 fn transfer(1200 &self,1201 sender: T::CrossAccountId,1202 to: T::CrossAccountId,1203 token: TokenId,1204 amount: u128,1205 nesting_budget: &dyn Budget,1206 ) -> DispatchResultWithPostInfo;1207 fn approve(1208 &self,1209 sender: T::CrossAccountId,1210 spender: T::CrossAccountId,1211 token: TokenId,1212 amount: u128,1213 ) -> DispatchResultWithPostInfo;1214 fn transfer_from(1215 &self,1216 sender: T::CrossAccountId,1217 from: T::CrossAccountId,1218 to: T::CrossAccountId,1219 token: TokenId,1220 amount: u128,1221 nesting_budget: &dyn Budget,1222 ) -> DispatchResultWithPostInfo;1223 fn burn_from(1224 &self,1225 sender: T::CrossAccountId,1226 from: T::CrossAccountId,1227 token: TokenId,1228 amount: u128,1229 nesting_budget: &dyn Budget,1230 ) -> DispatchResultWithPostInfo;12311232 fn check_nesting(1233 &self,1234 sender: T::CrossAccountId,1235 from: (CollectionId, TokenId),1236 under: TokenId,1237 budget: &dyn Budget,1238 ) -> DispatchResult;12391240 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;1241 fn collection_tokens(&self) -> Vec<TokenId>;1242 fn token_exists(&self, token: TokenId) -> bool;1243 fn last_token_id(&self) -> TokenId;12441245 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;1246 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;1247 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;1248 /// Amount of unique collection tokens1249 fn total_supply(&self) -> u32;1250 /// Amount of different tokens account has (Applicable to nonfungible/refungible)1251 fn account_balance(&self, account: T::CrossAccountId) -> u32;1252 /// Amount of specific token account have (Applicable to fungible/refungible)1253 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;1254 fn allowance(1255 &self,1256 sender: T::CrossAccountId,1257 spender: T::CrossAccountId,1258 token: TokenId,1259 ) -> u128;1260}12611262// Flexible enough for implementing CommonCollectionOperations1263pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1264 let post_info = PostDispatchInfo {1265 actual_weight: Some(weight),1266 pays_fee: Pays::Yes,1267 };1268 match res {1269 Ok(()) => Ok(post_info),1270 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1271 }1272}12731274impl<T: Config> From<PropertiesError> for Error<T> {1275 fn from(error: PropertiesError) -> Self {1276 match error {1277 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1278 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1279 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1280 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1281 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1282 }1283 }1284}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)]1819extern crate alloc;2021use core::ops::{Deref, DerefMut};22use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};23use sp_std::{vec::Vec, rc::Rc};24use pallet_evm::account::CrossAccountId;25use frame_support::{26 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},27 ensure,28 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},29 BoundedVec,30 weights::Pays,31 transactional,32};33use pallet_evm::GasWeightMapping;34use up_data_structs::{35 COLLECTION_NUMBER_LIMIT,36 Collection,37 RpcCollection,38 CollectionId,39 CreateItemData,40 MAX_TOKEN_PREFIX_LENGTH,41 COLLECTION_ADMINS_LIMIT,42 TokenId,43 CollectionStats,44 MAX_TOKEN_OWNERSHIP,45 CollectionMode,46 NFT_SPONSOR_TRANSFER_TIMEOUT,47 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,48 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,49 MAX_SPONSOR_TIMEOUT,50 CUSTOM_DATA_LIMIT,51 CollectionLimits,52 CreateCollectionData,53 SponsorshipState,54 CreateItemExData,55 SponsoringRateLimit,56 budget::Budget,57 COLLECTION_FIELD_LIMIT,58 PhantomType,59 Property,60 Properties,61 PropertiesPermissionMap,62 PropertyKey,63 PropertyValue,64 PropertyPermission,65 PropertiesError,66 PropertyKeyPermission,67 TokenData,68 TrySetProperty,69 PropertyScope,70 // RMRK71 RmrkCollectionInfo,72 RmrkInstanceInfo,73 RmrkResourceInfo,74 RmrkPropertyInfo,75 RmrkBaseInfo,76 RmrkPartType,77 RmrkTheme,78 RmrkNftChild,79 CollectionPermissions,80 SchemaVersion,81};8283pub use pallet::*;84use sp_core::H160;85use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};86#[cfg(feature = "runtime-benchmarks")]87pub mod benchmarking;88pub mod dispatch;89pub mod erc;90pub mod eth;91pub mod weights;9293pub type SelfWeightOf<T> = <T as Config>::WeightInfo;9495#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]96pub struct CollectionHandle<T: Config> {97 pub id: CollectionId,98 collection: Collection<T::AccountId>,99 pub recorder: SubstrateRecorder<T>,100}101impl<T: Config> WithRecorder<T> for CollectionHandle<T> {102 fn recorder(&self) -> &SubstrateRecorder<T> {103 &self.recorder104 }105 fn into_recorder(self) -> SubstrateRecorder<T> {106 self.recorder107 }108}109impl<T: Config> CollectionHandle<T> {110 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {111 <CollectionById<T>>::get(id).map(|collection| Self {112 id,113 collection,114 recorder: SubstrateRecorder::new(gas_limit),115 })116 }117118 pub fn new_with_recorder(id: CollectionId, recorder: Rc<SubstrateRecorder<T>>) -> Option<Self> {119 <CollectionById<T>>::get(id).map(|collection| Self {120 id,121 collection,122 recorder,123 })124 }125126 pub fn new(id: CollectionId) -> Option<Self> {127 Self::new_with_gas_limit(id, u64::MAX)128 }129 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {130 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)131 }132 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {133 self.recorder134 .consume_gas(T::GasWeightMapping::weight_to_gas(135 <T as frame_system::Config>::DbWeight::get()136 .read137 .saturating_mul(reads),138 ))139 }140 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {141 self.recorder142 .consume_gas(T::GasWeightMapping::weight_to_gas(143 <T as frame_system::Config>::DbWeight::get()144 .write145 .saturating_mul(writes),146 ))147 }148 pub fn save(self) -> DispatchResult {149 <CollectionById<T>>::insert(self.id, self.collection);150 Ok(())151 }152153 pub fn set_sponsor(&mut self, sponsor: T::AccountId) {154 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);155 }156}157impl<T: Config> Deref for CollectionHandle<T> {158 type Target = Collection<T::AccountId>;159160 fn deref(&self) -> &Self::Target {161 &self.collection162 }163}164165impl<T: Config> DerefMut for CollectionHandle<T> {166 fn deref_mut(&mut self) -> &mut Self::Target {167 &mut self.collection168 }169}170171impl<T: Config> CollectionHandle<T> {172 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {173 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);174 Ok(())175 }176 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {177 *subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))178 }179 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {180 ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);181 Ok(())182 }183 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {184 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)185 }186 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {187 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)188 }189 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {190 ensure!(191 <Allowlist<T>>::get((self.id, user)),192 <Error<T>>::AddressNotInAllowlist193 );194 Ok(())195 }196}197198#[frame_support::pallet]199pub mod pallet {200 use super::*;201 use pallet_evm::account;202 use dispatch::CollectionDispatch;203 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};204 use frame_system::pallet_prelude::*;205 use frame_support::traits::Currency;206 use up_data_structs::{TokenId, mapping::TokenAddressMapping};207 use scale_info::TypeInfo;208 use weights::WeightInfo;209210 #[pallet::config]211 pub trait Config:212 frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config213 {214 type WeightInfo: WeightInfo;215 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;216217 type Currency: Currency<Self::AccountId>;218219 #[pallet::constant]220 type CollectionCreationPrice: Get<221 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,222 >;223 type CollectionDispatch: CollectionDispatch<Self>;224225 type TreasuryAccountId: Get<Self::AccountId>;226227 type EvmTokenAddressMapping: TokenAddressMapping<H160>;228 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;229 }230231 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);232233 #[pallet::pallet]234 #[pallet::storage_version(STORAGE_VERSION)]235 #[pallet::generate_store(pub(super) trait Store)]236 pub struct Pallet<T>(_);237238 #[pallet::extra_constants]239 impl<T: Config> Pallet<T> {240 pub fn collection_admins_limit() -> u32 {241 COLLECTION_ADMINS_LIMIT242 }243 }244245 #[pallet::event]246 #[pallet::generate_deposit(pub fn deposit_event)]247 pub enum Event<T: Config> {248 /// New collection was created249 ///250 /// # Arguments251 ///252 /// * collection_id: Globally unique identifier of newly created collection.253 ///254 /// * mode: [CollectionMode] converted into u8.255 ///256 /// * account_id: Collection owner.257 CollectionCreated(CollectionId, u8, T::AccountId),258259 /// New collection was destroyed260 ///261 /// # Arguments262 ///263 /// * collection_id: Globally unique identifier of collection.264 CollectionDestroyed(CollectionId),265266 /// New item was created.267 ///268 /// # Arguments269 ///270 /// * collection_id: Id of the collection where item was created.271 ///272 /// * item_id: Id of an item. Unique within the collection.273 ///274 /// * recipient: Owner of newly created item275 ///276 /// * amount: Always 1 for NFT277 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),278279 /// Collection item was burned.280 ///281 /// # Arguments282 ///283 /// * collection_id.284 ///285 /// * item_id: Identifier of burned NFT.286 ///287 /// * owner: which user has destroyed its tokens288 ///289 /// * amount: Always 1 for NFT290 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),291292 /// Item was transferred293 ///294 /// * collection_id: Id of collection to which item is belong295 ///296 /// * item_id: Id of an item297 ///298 /// * sender: Original owner of item299 ///300 /// * recipient: New owner of item301 ///302 /// * amount: Always 1 for NFT303 Transfer(304 CollectionId,305 TokenId,306 T::CrossAccountId,307 T::CrossAccountId,308 u128,309 ),310311 /// * collection_id312 ///313 /// * item_id314 ///315 /// * sender316 ///317 /// * spender318 ///319 /// * amount320 Approved(321 CollectionId,322 TokenId,323 T::CrossAccountId,324 T::CrossAccountId,325 u128,326 ),327328 CollectionPropertySet(CollectionId, PropertyKey),329330 CollectionPropertyDeleted(CollectionId, PropertyKey),331332 TokenPropertySet(CollectionId, TokenId, PropertyKey),333334 TokenPropertyDeleted(CollectionId, TokenId, PropertyKey),335336 PropertyPermissionSet(CollectionId, PropertyKey),337 }338339 #[pallet::error]340 pub enum Error<T> {341 /// This collection does not exist.342 CollectionNotFound,343 /// Sender parameter and item owner must be equal.344 MustBeTokenOwner,345 /// No permission to perform action346 NoPermission,347 /// Collection is not in mint mode.348 PublicMintingNotAllowed,349 /// Address is not in allow list.350 AddressNotInAllowlist,351352 /// Collection name can not be longer than 63 char.353 CollectionNameLimitExceeded,354 /// Collection description can not be longer than 255 char.355 CollectionDescriptionLimitExceeded,356 /// Token prefix can not be longer than 15 char.357 CollectionTokenPrefixLimitExceeded,358 /// Total collections bound exceeded.359 TotalCollectionsLimitExceeded,360 /// Exceeded max admin count361 CollectionAdminCountExceeded,362 /// Collection limit bounds per collection exceeded363 CollectionLimitBoundsExceeded,364 /// Tried to enable permissions which are only permitted to be disabled365 OwnerPermissionsCantBeReverted,366 /// Collection settings not allowing items transferring367 TransferNotAllowed,368 /// Account token limit exceeded per collection369 AccountTokenLimitExceeded,370 /// Collection token limit exceeded371 CollectionTokenLimitExceeded,372 /// Metadata flag frozen373 MetadataFlagFrozen,374375 /// Item not exists.376 TokenNotFound,377 /// Item balance not enough.378 TokenValueTooLow,379 /// Requested value more than approved.380 ApprovedValueTooLow,381 /// Tried to approve more than owned382 CantApproveMoreThanOwned,383384 /// Can't transfer tokens to ethereum zero address385 AddressIsZero,386 /// Target collection doesn't supports this operation387 UnsupportedOperation,388389 /// Not sufficient founds to perform action390 NotSufficientFounds,391392 /// Collection has nesting disabled393 NestingIsDisabled,394 /// Only owner may nest tokens under this collection395 OnlyOwnerAllowedToNest,396 /// Only tokens from specific collections may nest tokens under this397 SourceCollectionIsNotAllowedToNest,398399 /// Tried to store more data than allowed in collection field400 CollectionFieldSizeExceeded,401402 /// Tried to store more property data than allowed403 NoSpaceForProperty,404405 /// Tried to store more property keys than allowed406 PropertyLimitReached,407408 /// Property key is too long409 PropertyKeyIsTooLong,410411 /// Only ASCII letters, digits, and '_', '-' are allowed412 InvalidCharacterInPropertyKey,413414 /// Empty property keys are forbidden415 EmptyPropertyKey,416 }417418 #[pallet::storage]419 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;420 #[pallet::storage]421 pub type DestroyedCollectionCount<T> =422 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;423424 /// Collection info425 #[pallet::storage]426 pub type CollectionById<T> = StorageMap<427 Hasher = Blake2_128Concat,428 Key = CollectionId,429 Value = Collection<<T as frame_system::Config>::AccountId>,430 QueryKind = OptionQuery,431 >;432433 /// Collection properties434 #[pallet::storage]435 #[pallet::getter(fn collection_properties)]436 pub type CollectionProperties<T> = StorageMap<437 Hasher = Blake2_128Concat,438 Key = CollectionId,439 Value = Properties,440 QueryKind = ValueQuery,441 OnEmpty = up_data_structs::CollectionProperties,442 >;443444 #[pallet::storage]445 #[pallet::getter(fn property_permissions)]446 pub type CollectionPropertyPermissions<T> = StorageMap<447 Hasher = Blake2_128Concat,448 Key = CollectionId,449 Value = PropertiesPermissionMap,450 QueryKind = ValueQuery,451 >;452453 #[pallet::storage]454 pub type AdminAmount<T> = StorageMap<455 Hasher = Blake2_128Concat,456 Key = CollectionId,457 Value = u32,458 QueryKind = ValueQuery,459 >;460461 /// List of collection admins462 #[pallet::storage]463 pub type IsAdmin<T: Config> = StorageNMap<464 Key = (465 Key<Blake2_128Concat, CollectionId>,466 Key<Blake2_128Concat, T::CrossAccountId>,467 ),468 Value = bool,469 QueryKind = ValueQuery,470 >;471472 /// Allowlisted collection users473 #[pallet::storage]474 pub type Allowlist<T: Config> = StorageNMap<475 Key = (476 Key<Blake2_128Concat, CollectionId>,477 Key<Blake2_128Concat, T::CrossAccountId>,478 ),479 Value = bool,480 QueryKind = ValueQuery,481 >;482483 /// Not used by code, exists only to provide some types to metadata484 #[pallet::storage]485 pub type DummyStorageValue<T: Config> = StorageValue<486 Value = (487 CollectionStats,488 CollectionId,489 TokenId,490 PhantomType<TokenData<T::CrossAccountId>>,491 PhantomType<RpcCollection<T::AccountId>>,492 // RMRK493 PhantomType<RmrkCollectionInfo<T::AccountId>>,494 PhantomType<RmrkInstanceInfo<T::AccountId>>,495 PhantomType<RmrkResourceInfo>,496 PhantomType<RmrkPropertyInfo>,497 PhantomType<RmrkBaseInfo<T::AccountId>>,498 PhantomType<RmrkPartType>,499 PhantomType<RmrkTheme>,500 PhantomType<RmrkNftChild>,501 ),502 QueryKind = OptionQuery,503 >;504505 #[pallet::hooks]506 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {507 fn on_runtime_upgrade() -> Weight {508 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {509 use up_data_structs::{CollectionVersion1, CollectionVersion2};510 <CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {511 let mut props = Vec::new();512 if !v.offchain_schema.is_empty() {513 props.push(Property {514 key: b"_old_offchainSchema".to_vec().try_into().unwrap(),515 value: v.offchain_schema.clone().into_inner().try_into().expect("offchain schema too big"),516 });517 }518 if !v.variable_on_chain_schema.is_empty() {519 props.push(Property {520 key: b"_old_variableOnChainSchema".to_vec().try_into().unwrap(),521 value: v.variable_on_chain_schema.clone().into_inner().try_into().expect("offchain schema too big"),522 });523 }524 if !v.const_on_chain_schema.is_empty() {525 props.push(Property {526 key: b"_old_constOnChainSchema".to_vec().try_into().unwrap(),527 value: v.const_on_chain_schema.clone().into_inner().try_into().expect("offchain schema too big"),528 });529 }530 props.push(Property {531 key: b"_old_schemaVersion".to_vec().try_into().unwrap(),532 value: match v.schema_version {533 SchemaVersion::ImageURL => b"ImageUrl".as_slice(),534 SchemaVersion::Unique => b"Unique".as_slice(),535 }.to_vec().try_into().unwrap(),536 });537 Self::set_scoped_collection_properties(538 id,539 PropertyScope::None,540 props.into_iter(),541 ).expect("existing data larger than properties");542 let mut new = CollectionVersion2::from(v.clone());543 new.permissions.access = Some(v.access);544 new.permissions.mint_mode = Some(v.mint_mode);545 Some(new)546 });547 }548549 0550 }551 }552}553554impl<T: Config> Pallet<T> {555 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens556 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {557 ensure!(558 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,559 <Error<T>>::AddressIsZero560 );561 Ok(())562 }563 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {564 <IsAdmin<T>>::iter_prefix((collection,))565 .map(|(a, _)| a)566 .collect()567 }568 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {569 <Allowlist<T>>::iter_prefix((collection,))570 .map(|(a, _)| a)571 .collect()572 }573 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {574 <Allowlist<T>>::get((collection, user))575 }576 pub fn collection_stats() -> CollectionStats {577 let created = <CreatedCollectionCount<T>>::get();578 let destroyed = <DestroyedCollectionCount<T>>::get();579 CollectionStats {580 created: created.0,581 destroyed: destroyed.0,582 alive: created.0 - destroyed.0,583 }584 }585586 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {587 let collection = <CollectionById<T>>::get(collection);588 if collection.is_none() {589 return None;590 }591592 let collection = collection.unwrap();593 let limits = collection.limits;594 let effective_limits = CollectionLimits {595 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),596 sponsored_data_size: Some(limits.sponsored_data_size()),597 sponsored_data_rate_limit: Some(598 limits599 .sponsored_data_rate_limit600 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),601 ),602 token_limit: Some(limits.token_limit()),603 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(604 match collection.mode {605 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,606 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,607 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,608 },609 )),610 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),611 owner_can_transfer: Some(limits.owner_can_transfer()),612 owner_can_destroy: Some(limits.owner_can_destroy()),613 transfers_enabled: Some(limits.transfers_enabled()),614 };615616 Some(effective_limits)617 }618619 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {620 let Collection {621 name,622 description,623 owner,624 mode,625 token_prefix,626 sponsorship,627 limits,628 permissions,629 } = <CollectionById<T>>::get(collection)?;630631 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)632 .into_iter()633 .map(|(key, permission)| PropertyKeyPermission {634 key,635 permission,636 })637 .collect();638639 let properties = <CollectionProperties<T>>::get(collection)640 .into_iter()641 .map(|(key, value)| Property {642 key,643 value,644 })645 .collect();646647 Some(RpcCollection {648 name: name.into_inner(),649 description: description.into_inner(),650 owner,651 mode,652 token_prefix: token_prefix.into_inner(),653 sponsorship,654 limits,655 permissions,656 token_property_permissions,657 properties,658 })659 }660}661662macro_rules! limit_default {663 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{664 $(665 if let Some($new) = $new.$field {666 let $old = $old.$field($($arg)?);667 let _ = $new;668 let _ = $old;669 $check670 } else {671 $new.$field = $old.$field672 }673 )*674 }};675}676macro_rules! limit_default_clone {677 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{678 $(679 if let Some($new) = $new.$field.clone() {680 let $old = $old.$field($($arg)?);681 let _ = $new;682 let _ = $old;683 $check684 } else {685 $new.$field = $old.$field.clone()686 }687 )*688 }};689}690691impl<T: Config> Pallet<T> {692 pub fn init_collection(693 owner: T::AccountId,694 data: CreateCollectionData<T::AccountId>,695 ) -> Result<CollectionId, DispatchError> {696 {697 ensure!(698 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,699 Error::<T>::CollectionTokenPrefixLimitExceeded700 );701 }702703 let created_count = <CreatedCollectionCount<T>>::get()704 .0705 .checked_add(1)706 .ok_or(ArithmeticError::Overflow)?;707 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;708 let id = CollectionId(created_count);709710 // bound Total number of collections711 ensure!(712 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,713 <Error<T>>::TotalCollectionsLimitExceeded714 );715716 // =========717718 let collection = Collection {719 owner: owner.clone(),720 name: data.name,721 mode: data.mode.clone(),722 description: data.description,723 token_prefix: data.token_prefix,724 sponsorship: data725 .pending_sponsor726 .map(SponsorshipState::Unconfirmed)727 .unwrap_or_default(),728 limits: data729 .limits730 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))731 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,732 permissions: data733 .permissions734 .map(|permissions| Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions))735 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,736 };737738 let mut collection_properties = up_data_structs::CollectionProperties::get();739 collection_properties740 .try_set_from_iter(data.properties.into_iter())741 .map_err(<Error<T>>::from)?;742743 CollectionProperties::<T>::insert(id, collection_properties);744745 let mut token_props_permissions = PropertiesPermissionMap::new();746 token_props_permissions747 .try_set_from_iter(data.token_property_permissions.into_iter())748 .map_err(<Error<T>>::from)?;749750 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);751752 // Take a (non-refundable) deposit of collection creation753 {754 let mut imbalance =755 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();756 imbalance.subsume(757 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(758 &T::TreasuryAccountId::get(),759 T::CollectionCreationPrice::get(),760 ),761 );762 <T as Config>::Currency::settle(763 &owner,764 imbalance,765 WithdrawReasons::TRANSFER,766 ExistenceRequirement::KeepAlive,767 )768 .map_err(|_| Error::<T>::NotSufficientFounds)?;769 }770771 <CreatedCollectionCount<T>>::put(created_count);772 <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));773 <CollectionById<T>>::insert(id, collection);774 Ok(id)775 }776777 pub fn destroy_collection(778 collection: CollectionHandle<T>,779 sender: &T::CrossAccountId,780 ) -> DispatchResult {781 ensure!(782 collection.limits.owner_can_destroy(),783 <Error<T>>::NoPermission,784 );785 collection.check_is_owner(sender)?;786787 let destroyed_collections = <DestroyedCollectionCount<T>>::get()788 .0789 .checked_add(1)790 .ok_or(ArithmeticError::Overflow)?;791792 // =========793794 <DestroyedCollectionCount<T>>::put(destroyed_collections);795 <CollectionById<T>>::remove(collection.id);796 <AdminAmount<T>>::remove(collection.id);797 <IsAdmin<T>>::remove_prefix((collection.id,), None);798 <Allowlist<T>>::remove_prefix((collection.id,), None);799 <CollectionProperties<T>>::remove(collection.id);800801 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));802 Ok(())803 }804805 pub fn set_collection_property(806 collection: &CollectionHandle<T>,807 sender: &T::CrossAccountId,808 property: Property,809 ) -> DispatchResult {810 collection.check_is_owner_or_admin(sender)?;811812 CollectionProperties::<T>::try_mutate(collection.id, |properties| {813 let property = property.clone();814 properties.try_set(property.key, property.value)815 })816 .map_err(<Error<T>>::from)?;817818 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));819820 Ok(())821 }822823 pub fn set_scoped_collection_property(824 collection_id: CollectionId,825 scope: PropertyScope,826 property: Property,827 ) -> DispatchResult {828 CollectionProperties::<T>::try_mutate(collection_id, |properties| {829 properties.try_scoped_set(scope, property.key, property.value)830 })831 .map_err(<Error<T>>::from)?;832833 Ok(())834 }835836 pub fn set_scoped_collection_properties(837 collection_id: CollectionId,838 scope: PropertyScope,839 properties: impl Iterator<Item = Property>,840 ) -> DispatchResult {841 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {842 stored_properties.try_scoped_set_from_iter(scope, properties)843 })844 .map_err(<Error<T>>::from)?;845846 Ok(())847 }848849 #[transactional]850 pub fn set_collection_properties(851 collection: &CollectionHandle<T>,852 sender: &T::CrossAccountId,853 properties: Vec<Property>,854 ) -> DispatchResult {855 for property in properties {856 Self::set_collection_property(collection, sender, property)?;857 }858859 Ok(())860 }861862 pub fn delete_collection_property(863 collection: &CollectionHandle<T>,864 sender: &T::CrossAccountId,865 property_key: PropertyKey,866 ) -> DispatchResult {867 collection.check_is_owner_or_admin(sender)?;868869 CollectionProperties::<T>::try_mutate(collection.id, |properties| {870 properties.remove(&property_key)871 })872 .map_err(<Error<T>>::from)?;873874 Self::deposit_event(Event::CollectionPropertyDeleted(875 collection.id,876 property_key,877 ));878879 Ok(())880 }881882 #[transactional]883 pub fn delete_collection_properties(884 collection: &CollectionHandle<T>,885 sender: &T::CrossAccountId,886 property_keys: Vec<PropertyKey>,887 ) -> DispatchResult {888 for key in property_keys {889 Self::delete_collection_property(collection, sender, key)?;890 }891892 Ok(())893 }894895 // For migrations896 pub fn set_property_permission_unchecked(897 collection: CollectionId,898 property_permission: PropertyKeyPermission,899 ) -> DispatchResult {900 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {901 permissions.try_set(property_permission.key, property_permission.permission)902 })903 .map_err(<Error<T>>::from)?;904 Ok(())905 }906907 pub fn set_property_permission(908 collection: &CollectionHandle<T>,909 sender: &T::CrossAccountId,910 property_permission: PropertyKeyPermission,911 ) -> DispatchResult {912 collection.check_is_owner_or_admin(sender)?;913914 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);915 let current_permission = all_permissions.get(&property_permission.key);916 if matches![917 current_permission,918 Some(PropertyPermission { mutable: false, .. })919 ] {920 return Err(<Error<T>>::NoPermission.into());921 }922923 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {924 let property_permission = property_permission.clone();925 permissions.try_set(property_permission.key, property_permission.permission)926 })927 .map_err(<Error<T>>::from)?;928929 Self::deposit_event(Event::PropertyPermissionSet(930 collection.id,931 property_permission.key,932 ));933934 Ok(())935 }936937 #[transactional]938 pub fn set_property_permissions(939 collection: &CollectionHandle<T>,940 sender: &T::CrossAccountId,941 property_permissions: Vec<PropertyKeyPermission>,942 ) -> DispatchResult {943 for prop_pemission in property_permissions {944 Self::set_property_permission(collection, sender, prop_pemission)?;945 }946947 Ok(())948 }949950 pub fn get_collection_property(951 collection_id: CollectionId,952 key: &PropertyKey,953 ) -> Option<PropertyValue> {954 Self::collection_properties(collection_id).get(key).cloned()955 }956957 pub fn bytes_keys_to_property_keys(958 keys: Vec<Vec<u8>>,959 ) -> Result<Vec<PropertyKey>, DispatchError> {960 keys.into_iter()961 .map(|key| -> Result<PropertyKey, DispatchError> {962 key.try_into()963 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())964 })965 .collect::<Result<Vec<PropertyKey>, DispatchError>>()966 }967968 pub fn filter_collection_properties(969 collection_id: CollectionId,970 keys: Option<Vec<PropertyKey>>,971 ) -> Result<Vec<Property>, DispatchError> {972 let properties = Self::collection_properties(collection_id);973974 let properties = keys975 .map(|keys| {976 keys.into_iter()977 .filter_map(|key| {978 properties.get(&key).map(|value| Property {979 key,980 value: value.clone(),981 })982 })983 .collect()984 })985 .unwrap_or_else(|| {986 properties987 .into_iter()988 .map(|(key, value)| Property {989 key,990 value,991 })992 .collect()993 });994995 Ok(properties)996 }997998 pub fn filter_property_permissions(999 collection_id: CollectionId,1000 keys: Option<Vec<PropertyKey>>,1001 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1002 let permissions = Self::property_permissions(collection_id);10031004 let key_permissions = keys1005 .map(|keys| {1006 keys.into_iter()1007 .filter_map(|key| {1008 permissions1009 .get(&key)1010 .map(|permission| PropertyKeyPermission {1011 key,1012 permission: permission.clone(),1013 })1014 })1015 .collect()1016 })1017 .unwrap_or_else(|| {1018 permissions1019 .into_iter()1020 .map(|(key, permission)| PropertyKeyPermission {1021 key,1022 permission,1023 })1024 .collect()1025 });10261027 Ok(key_permissions)1028 }10291030 pub fn toggle_allowlist(1031 collection: &CollectionHandle<T>,1032 sender: &T::CrossAccountId,1033 user: &T::CrossAccountId,1034 allowed: bool,1035 ) -> DispatchResult {1036 collection.check_is_owner_or_admin(sender)?;10371038 // =========10391040 if allowed {1041 <Allowlist<T>>::insert((collection.id, user), true);1042 } else {1043 <Allowlist<T>>::remove((collection.id, user));1044 }10451046 Ok(())1047 }10481049 pub fn toggle_admin(1050 collection: &CollectionHandle<T>,1051 sender: &T::CrossAccountId,1052 user: &T::CrossAccountId,1053 admin: bool,1054 ) -> DispatchResult {1055 collection.check_is_owner_or_admin(sender)?;10561057 let was_admin = <IsAdmin<T>>::get((collection.id, user));1058 if was_admin == admin {1059 return Ok(());1060 }1061 let amount = <AdminAmount<T>>::get(collection.id);10621063 if admin {1064 let amount = amount1065 .checked_add(1)1066 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1067 ensure!(1068 amount <= Self::collection_admins_limit(),1069 <Error<T>>::CollectionAdminCountExceeded,1070 );10711072 // =========10731074 <AdminAmount<T>>::insert(collection.id, amount);1075 <IsAdmin<T>>::insert((collection.id, user), true);1076 } else {1077 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1078 <IsAdmin<T>>::remove((collection.id, user));1079 }10801081 Ok(())1082 }10831084 pub fn clamp_limits(1085 mode: CollectionMode,1086 old_limit: &CollectionLimits,1087 mut new_limit: CollectionLimits,1088 ) -> Result<CollectionLimits, DispatchError> {1089 limit_default!(old_limit, new_limit,1090 account_token_ownership_limit => ensure!(1091 new_limit <= MAX_TOKEN_OWNERSHIP,1092 <Error<T>>::CollectionLimitBoundsExceeded,1093 ),1094 sponsor_transfer_timeout(match mode {1095 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1096 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1097 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1098 }) => ensure!(1099 new_limit <= MAX_SPONSOR_TIMEOUT,1100 <Error<T>>::CollectionLimitBoundsExceeded,1101 ),1102 sponsored_data_size => ensure!(1103 new_limit <= CUSTOM_DATA_LIMIT,1104 <Error<T>>::CollectionLimitBoundsExceeded,1105 ),1106 token_limit => ensure!(1107 old_limit >= new_limit && new_limit > 0,1108 <Error<T>>::CollectionTokenLimitExceeded1109 ),1110 owner_can_transfer => ensure!(1111 old_limit || !new_limit,1112 <Error<T>>::OwnerPermissionsCantBeReverted,1113 ),1114 owner_can_destroy => ensure!(1115 old_limit || !new_limit,1116 <Error<T>>::OwnerPermissionsCantBeReverted,1117 ),1118 sponsored_data_rate_limit => {},1119 transfers_enabled => {},1120 );1121 Ok(new_limit)1122 }1123 pub fn clamp_permissions(1124 mode: CollectionMode,1125 old_limit: &CollectionPermissions,1126 mut new_limit: CollectionPermissions,1127 ) -> Result<CollectionPermissions, DispatchError> {1128 limit_default_clone!(old_limit, new_limit,1129 );1130 Ok(new_limit)1131 }1132}11331134#[macro_export]1135macro_rules! unsupported {1136 () => {1137 Err(<Error<T>>::UnsupportedOperation.into())1138 };1139}11401141/// Worst cases1142pub trait CommonWeightInfo<CrossAccountId> {1143 fn create_item() -> Weight;1144 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;1145 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;1146 fn burn_item() -> Weight;1147 fn set_collection_properties(amount: u32) -> Weight;1148 fn delete_collection_properties(amount: u32) -> Weight;1149 fn set_token_properties(amount: u32) -> Weight;1150 fn delete_token_properties(amount: u32) -> Weight;1151 fn set_property_permissions(amount: u32) -> Weight;1152 fn transfer() -> Weight;1153 fn approve() -> Weight;1154 fn transfer_from() -> Weight;1155 fn burn_from() -> Weight;1156}11571158pub trait CommonCollectionOperations<T: Config> {1159 fn create_item(1160 &self,1161 sender: T::CrossAccountId,1162 to: T::CrossAccountId,1163 data: CreateItemData,1164 nesting_budget: &dyn Budget,1165 ) -> DispatchResultWithPostInfo;1166 fn create_multiple_items(1167 &self,1168 sender: T::CrossAccountId,1169 to: T::CrossAccountId,1170 data: Vec<CreateItemData>,1171 nesting_budget: &dyn Budget,1172 ) -> DispatchResultWithPostInfo;1173 fn create_multiple_items_ex(1174 &self,1175 sender: T::CrossAccountId,1176 data: CreateItemExData<T::CrossAccountId>,1177 nesting_budget: &dyn Budget,1178 ) -> DispatchResultWithPostInfo;1179 fn burn_item(1180 &self,1181 sender: T::CrossAccountId,1182 token: TokenId,1183 amount: u128,1184 ) -> DispatchResultWithPostInfo;1185 fn set_collection_properties(1186 &self,1187 sender: T::CrossAccountId,1188 properties: Vec<Property>,1189 ) -> DispatchResultWithPostInfo;1190 fn delete_collection_properties(1191 &self,1192 sender: &T::CrossAccountId,1193 property_keys: Vec<PropertyKey>,1194 ) -> DispatchResultWithPostInfo;1195 fn set_token_properties(1196 &self,1197 sender: T::CrossAccountId,1198 token_id: TokenId,1199 property: Vec<Property>,1200 ) -> DispatchResultWithPostInfo;1201 fn delete_token_properties(1202 &self,1203 sender: T::CrossAccountId,1204 token_id: TokenId,1205 property_keys: Vec<PropertyKey>,1206 ) -> DispatchResultWithPostInfo;1207 fn set_property_permissions(1208 &self,1209 sender: &T::CrossAccountId,1210 property_permissions: Vec<PropertyKeyPermission>,1211 ) -> DispatchResultWithPostInfo;1212 fn transfer(1213 &self,1214 sender: T::CrossAccountId,1215 to: T::CrossAccountId,1216 token: TokenId,1217 amount: u128,1218 nesting_budget: &dyn Budget,1219 ) -> DispatchResultWithPostInfo;1220 fn approve(1221 &self,1222 sender: T::CrossAccountId,1223 spender: T::CrossAccountId,1224 token: TokenId,1225 amount: u128,1226 ) -> DispatchResultWithPostInfo;1227 fn transfer_from(1228 &self,1229 sender: T::CrossAccountId,1230 from: T::CrossAccountId,1231 to: T::CrossAccountId,1232 token: TokenId,1233 amount: u128,1234 nesting_budget: &dyn Budget,1235 ) -> DispatchResultWithPostInfo;1236 fn burn_from(1237 &self,1238 sender: T::CrossAccountId,1239 from: T::CrossAccountId,1240 token: TokenId,1241 amount: u128,1242 nesting_budget: &dyn Budget,1243 ) -> DispatchResultWithPostInfo;12441245 fn check_nesting(1246 &self,1247 sender: T::CrossAccountId,1248 from: (CollectionId, TokenId),1249 under: TokenId,1250 budget: &dyn Budget,1251 ) -> DispatchResult;12521253 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;1254 fn collection_tokens(&self) -> Vec<TokenId>;1255 fn token_exists(&self, token: TokenId) -> bool;1256 fn last_token_id(&self) -> TokenId;12571258 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;1259 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;1260 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;1261 /// Amount of unique collection tokens1262 fn total_supply(&self) -> u32;1263 /// Amount of different tokens account has (Applicable to nonfungible/refungible)1264 fn account_balance(&self, account: T::CrossAccountId) -> u32;1265 /// Amount of specific token account have (Applicable to fungible/refungible)1266 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;1267 fn allowance(1268 &self,1269 sender: T::CrossAccountId,1270 spender: T::CrossAccountId,1271 token: TokenId,1272 ) -> u128;1273}12741275// Flexible enough for implementing CommonCollectionOperations1276pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1277 let post_info = PostDispatchInfo {1278 actual_weight: Some(weight),1279 pays_fee: Pays::Yes,1280 };1281 match res {1282 Ok(()) => Ok(post_info),1283 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1284 }1285}12861287impl<T: Config> From<PropertiesError> for Error<T> {1288 fn from(error: PropertiesError) -> Self {1289 match error {1290 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1291 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1292 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1293 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1294 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1295 }1296 }1297}pallets/evm-collection/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-collection/src/eth.rs
+++ b/pallets/evm-collection/src/eth.rs
@@ -17,7 +17,7 @@
use core::marker::PhantomData;
use evm_coder::{abi::AbiWriter, execution::*, generate_stubgen, solidity_interface, types::*, ToLog};
use ethereum as _;
-use pallet_common::CollectionById;
+use pallet_common::{CollectionById, CollectionHandle};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
use pallet_evm::{
ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure,
@@ -26,7 +26,7 @@
use sp_core::H160;
use up_data_structs::{
CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
- MAX_COLLECTION_NAME_LENGTH,
+ MAX_COLLECTION_NAME_LENGTH, SponsorshipState,
};
use crate::{Config, Pallet};
use frame_support::traits::Get;
@@ -57,6 +57,7 @@
#[solidity_interface(name = "Collection")]
impl<T: Config> EvmCollection<T> {
+
fn create_721_collection(
&self,
caller: caller,
@@ -102,15 +103,27 @@
Ok(address)
}
- // fn set_sponsor(collection_id: address, sponsor: address) -> Result<void> {
- // let collection_id =
- // pallet_common::eth::map_eth_to_id(&collection_id).ok_or(Error::Revert("".into()))?;
- // let mut collection = <CollectionById<T>>::get(collection_id).ok_or(Error::Revert("".into()))?;
- // let sponsor = T::CrossAccountId::from_eth(sponsor);
- // collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.as_sub().clone());
- // <CollectionById<T>>::insert(collection_id, collection);
- // Ok(())
- // }
+ fn set_sponsor(
+ &self,
+ caller: caller,
+ contract_address: address,
+ sponsor: address,
+ ) -> Result<void> {
+ let collection_id =
+ pallet_common::eth::map_eth_to_id(&contract_address).ok_or(Error::Revert("".into()))?;
+ let mut collection =
+ pallet_common::CollectionHandle::new_with_recorder(collection_id, self.0.clone())
+ .ok_or(Error::Revert("".into()))?;
+
+ let caller = T::CrossAccountId::from_eth(caller);
+ collection.check_is_owner(&caller).map_err(|e| Error::Revert(format!("{:?}", e)))?;
+
+ let sponsor = T::CrossAccountId::from_eth(sponsor);
+ collection.set_sponsor(sponsor.as_sub().clone());
+ collection
+ .save()
+ .map_err(|e| Error::Revert(format!("{:?}", e)))
+ }
// fn set_offchain_shema(shema: string) -> Result<void> {
// Ok(())
pallets/evm-collection/src/stubs/Collection.rawdiffbeforeafterbothbinary blob — no preview
pallets/evm-collection/src/stubs/Collection.soldiffbeforeafterboth--- a/pallets/evm-collection/src/stubs/Collection.sol
+++ b/pallets/evm-collection/src/stubs/Collection.sol
@@ -21,130 +21,8 @@
}
}
-// Selector: ee5467a8
+// Selector: 6503bbc2
contract Collection is Dummy, ERC165 {
- // Selector: contractOwner(address) 5152b14c
- function contractOwner(address contractAddress)
- public
- view
- returns (address)
- {
- require(false, stub_error);
- contractAddress;
- dummy;
- return 0x0000000000000000000000000000000000000000;
- }
-
- // Selector: sponsoringEnabled(address) 6027dc61
- function sponsoringEnabled(address contractAddress)
- public
- view
- returns (bool)
- {
- require(false, stub_error);
- contractAddress;
- dummy;
- return false;
- }
-
- // Deprecated
- //
- // Selector: toggleSponsoring(address,bool) fcac6d86
- function toggleSponsoring(address contractAddress, bool enabled) public {
- require(false, stub_error);
- contractAddress;
- enabled;
- dummy = 0;
- }
-
- // Selector: setSponsoringMode(address,uint8) fde8a560
- function setSponsoringMode(address contractAddress, uint8 mode) public {
- require(false, stub_error);
- contractAddress;
- mode;
- dummy = 0;
- }
-
- // Selector: sponsoringMode(address) b70c7267
- function sponsoringMode(address contractAddress)
- public
- view
- returns (uint8)
- {
- require(false, stub_error);
- contractAddress;
- dummy;
- return 0;
- }
-
- // Selector: setSponsoringRateLimit(address,uint32) 77b6c908
- function setSponsoringRateLimit(address contractAddress, uint32 rateLimit)
- public
- {
- require(false, stub_error);
- contractAddress;
- rateLimit;
- dummy = 0;
- }
-
- // Selector: getSponsoringRateLimit(address) 610cfabd
- function getSponsoringRateLimit(address contractAddress)
- public
- view
- returns (uint32)
- {
- require(false, stub_error);
- contractAddress;
- dummy;
- return 0;
- }
-
- // Selector: allowed(address,address) 5c658165
- function allowed(address contractAddress, address user)
- public
- view
- returns (bool)
- {
- require(false, stub_error);
- contractAddress;
- user;
- dummy;
- return false;
- }
-
- // Selector: allowlistEnabled(address) c772ef6c
- function allowlistEnabled(address contractAddress)
- public
- view
- returns (bool)
- {
- require(false, stub_error);
- contractAddress;
- dummy;
- return false;
- }
-
- // Selector: toggleAllowlist(address,bool) 36de20f5
- function toggleAllowlist(address contractAddress, bool enabled) public {
- require(false, stub_error);
- contractAddress;
- enabled;
- dummy = 0;
- }
-
- // Selector: toggleAllowed(address,address,bool) 4706cc1c
- function toggleAllowed(
- address contractAddress,
- address user,
- bool allowed
- ) public {
- require(false, stub_error);
- contractAddress;
- user;
- allowed;
- dummy = 0;
- }
-
// Selector: create721Collection(string,string,string) 951c0151
function create721Collection(
string memory name,
@@ -158,4 +36,12 @@
dummy;
return 0x0000000000000000000000000000000000000000;
}
+
+ // Selector: setSponsor(address,address) f01fba93
+ function setSponsor(address contractAddress, address sponsor) public view {
+ require(false, stub_error);
+ contractAddress;
+ sponsor;
+ dummy;
+ }
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -520,7 +520,7 @@
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
target_collection.check_is_owner(&sender)?;
- target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor.clone());
+ target_collection.set_sponsor(new_sponsor.clone());
<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(
collection_id,
tests/src/eth/api/Collection.soldiffbeforeafterboth--- a/tests/src/eth/api/Collection.sol
+++ b/tests/src/eth/api/Collection.sol
@@ -12,70 +12,15 @@
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
-// Selector: ee5467a8
+// Selector: 6503bbc2
interface Collection is Dummy, ERC165 {
- // Selector: contractOwner(address) 5152b14c
- function contractOwner(address contractAddress)
- external
- view
- returns (address);
-
- // Selector: sponsoringEnabled(address) 6027dc61
- function sponsoringEnabled(address contractAddress)
- external
- view
- returns (bool);
-
- // Deprecated
- //
- // Selector: toggleSponsoring(address,bool) fcac6d86
- function toggleSponsoring(address contractAddress, bool enabled) external;
-
- // Selector: setSponsoringMode(address,uint8) fde8a560
- function setSponsoringMode(address contractAddress, uint8 mode) external;
-
- // Selector: sponsoringMode(address) b70c7267
- function sponsoringMode(address contractAddress)
- external
- view
- returns (uint8);
-
- // Selector: setSponsoringRateLimit(address,uint32) 77b6c908
- function setSponsoringRateLimit(address contractAddress, uint32 rateLimit)
- external;
-
- // Selector: getSponsoringRateLimit(address) 610cfabd
- function getSponsoringRateLimit(address contractAddress)
- external
- view
- returns (uint32);
-
- // Selector: allowed(address,address) 5c658165
- function allowed(address contractAddress, address user)
- external
- view
- returns (bool);
-
- // Selector: allowlistEnabled(address) c772ef6c
- function allowlistEnabled(address contractAddress)
- external
- view
- returns (bool);
-
- // Selector: toggleAllowlist(address,bool) 36de20f5
- function toggleAllowlist(address contractAddress, bool enabled) external;
-
- // Selector: toggleAllowed(address,address,bool) 4706cc1c
- function toggleAllowed(
- address contractAddress,
- address user,
- bool allowed
- ) external;
-
// Selector: create721Collection(string,string,string) 951c0151
function create721Collection(
string memory name,
string memory description,
string memory tokenPrefix
) external view returns (address);
+
+ // Selector: setSponsor(address,address) f01fba93
+ function setSponsor(address contractAddress, address sponsor) external view;
}
tests/src/eth/collectionAbi.jsondiffbeforeafterboth--- a/tests/src/eth/collectionAbi.json
+++ b/tests/src/eth/collectionAbi.json
@@ -1,65 +1,12 @@
[
{
"inputs": [
- {
- "internalType": "address",
- "name": "contractAddress",
- "type": "address"
- },
- { "internalType": "address", "name": "user", "type": "address" }
- ],
- "name": "allowed",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "contractAddress",
- "type": "address"
- }
- ],
- "name": "allowlistEnabled",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "contractAddress",
- "type": "address"
- }
- ],
- "name": "contractOwner",
- "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
{ "internalType": "string", "name": "name", "type": "string" },
{ "internalType": "string", "name": "description", "type": "string" },
{ "internalType": "string", "name": "tokenPrefix", "type": "string" }
],
"name": "create721Collection",
"outputs": [{ "internalType": "address", "name": "", "type": "address" }],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "contractAddress",
- "type": "address"
- }
- ],
- "name": "getSponsoringRateLimit",
- "outputs": [{ "internalType": "uint32", "name": "", "type": "uint32" }],
"stateMutability": "view",
"type": "function"
},
@@ -70,103 +17,20 @@
"name": "contractAddress",
"type": "address"
},
- { "internalType": "uint8", "name": "mode", "type": "uint8" }
- ],
- "name": "setSponsoringMode",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "contractAddress",
- "type": "address"
- },
- { "internalType": "uint32", "name": "rateLimit", "type": "uint32" }
+ { "internalType": "address", "name": "sponsor", "type": "address" }
],
- "name": "setSponsoringRateLimit",
+ "name": "setSponsor",
"outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "contractAddress",
- "type": "address"
- }
- ],
- "name": "sponsoringEnabled",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
- {
- "internalType": "address",
- "name": "contractAddress",
- "type": "address"
- }
- ],
- "name": "sponsoringMode",
- "outputs": [{ "internalType": "uint8", "name": "", "type": "uint8" }],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
{ "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
],
"name": "supportsInterface",
"outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
"stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "contractAddress",
- "type": "address"
- },
- { "internalType": "address", "name": "user", "type": "address" },
- { "internalType": "bool", "name": "allowed", "type": "bool" }
- ],
- "name": "toggleAllowed",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "contractAddress",
- "type": "address"
- },
- { "internalType": "bool", "name": "enabled", "type": "bool" }
- ],
- "name": "toggleAllowlist",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- {
- "internalType": "address",
- "name": "contractAddress",
- "type": "address"
- },
- { "internalType": "bool", "name": "enabled", "type": "bool" }
- ],
- "name": "toggleSponsoring",
- "outputs": [],
- "stateMutability": "nonpayable",
"type": "function"
}
]
tests/src/eth/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -14,32 +14,53 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+import {ApiPromise} from '@polkadot/api';
+import {evmToAddress} from '@polkadot/util-crypto';
import {expect} from 'chai';
import {getCreatedCollectionCount, getDetailedCollectionInfo} from '../util/helpers';
-import {collectionHelper, collectionIdFromAddress, contractHelpers, createEthAccountWithBalance, itWeb3} from './util/helpers';
+import {collectionHelper, collectionIdFromAddress, createEthAccountWithBalance, itWeb3, normalizeAddress} from './util/helpers';
+async function getCollectionAddressFromResult(api: ApiPromise, result: any) {
+ const collectionIdAddress = normalizeAddress(result.events[0].raw.topics[2]);
+ const collectionId = collectionIdFromAddress(collectionIdAddress);
+ const collection = (await getDetailedCollectionInfo(api, collectionId))!;
+ return {collectionIdAddress, collectionId, collection};
+}
+
describe('Create collection from EVM', () => {
itWeb3('Create collection', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helpers = collectionHelper(web3, owner);
+ const helper = collectionHelper(web3, owner);
const collectionName = 'CollectionEVM';
const description = 'Some description';
const tokenPrefix = 'token prefix';
const collectionCountBefore = await getCreatedCollectionCount(api);
- const result = await helpers.methods
+ const result = await helper.methods
.create721Collection(collectionName, description, tokenPrefix)
.send();
const collectionCountAfter = await getCreatedCollectionCount(api);
- const collectionId = collectionIdFromAddress(result.events[0].raw.topics[2]);
+ const {collectionId, collection} = await getCollectionAddressFromResult(api, result);
expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
expect(collectionId).to.be.eq(collectionCountAfter);
-
- const collection = (await getDetailedCollectionInfo(api, collectionId))!;
expect(collection.name.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(collectionName);
expect(collection.description.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(description);
expect(collection.tokenPrefix.toHuman()).to.be.eq(tokenPrefix);
expect(collection.schemaVersion.type).to.be.eq('ImageURL');
});
+
+ itWeb3('Set sponsorship', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const helper = collectionHelper(web3, owner);
+ let result = await helper.methods.create721Collection('Sponsor collection', '1', '1').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const sponsor = await createEthAccountWithBalance(api, web3);
+ result = await helper.methods.setSponsor(collectionIdAddress, sponsor).send();
+ const collection = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collection.sponsorship.isUnconfirmed).to.be.true;
+ expect(collection.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+ });
+
+
});
\ No newline at end of file
tests/src/eth/util/helpers.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -74,7 +74,15 @@
return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
}
export function collectionIdFromAddress(address: string): number {
- return Number('0x' + address.substring(address.length - 8));
+ if (!address.startsWith('0x'))
+ throw 'address not starts with "0x"';
+ if (address.length > 42)
+ throw 'address length is more than 20 bytes';
+ return Number('0x' + address.substring(address.length - 8));
+}
+
+export function normalizeAddress(address: string): string {
+ return '0x' + address.substring(address.length - 40);
}
export function tokenIdToAddress(collection: number, token: number): string {