difftreelog
feat evm collection creation event
in: master
39 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5912,6 +5912,7 @@
name = "pallet-common"
version = "0.1.0"
dependencies = [
+ "ethereum",
"evm-coder",
"fp-evm-mapping",
"frame-benchmarking",
Makefilediffbeforeafterboth--- a/Makefile
+++ b/Makefile
@@ -16,12 +16,12 @@
CONTRACT_HELPERS_ABI=./tests/src/eth/util/contractHelpersAbi.json
COLLECTION_HELPER_STUBS=./pallets/unique/src/eth/stubs/
-COLLECTION_HELPER_ABI=./tests/src/eth/collectionHelperAbi.json
+COLLECTION_HELPER_ABI=./tests/src/eth/collectionHelpersAbi.json
TESTS_API=./tests/src/eth/api/
.PHONY: regenerate_solidity
-regenerate_solidity: UniqueFungible.sol UniqueNFT.sol ContractHelpers.sol CollectionHelper.sol
+regenerate_solidity: UniqueFungible.sol UniqueNFT.sol ContractHelpers.sol CollectionHelpers.sol
UniqueFungible.sol:
PACKAGE=pallet-fungible NAME=erc::gen_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
@@ -35,7 +35,7 @@
PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_impl OUTPUT=$(CONTRACT_HELPERS_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
-CollectionHelper.sol:
+CollectionHelpers.sol:
PACKAGE=pallet-unique NAME=eth::collection_helper_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
PACKAGE=pallet-unique NAME=eth::collection_helper_impl OUTPUT=$(COLLECTION_HELPER_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
@@ -51,11 +51,11 @@
INPUT=$(CONTRACT_HELPERS_STUBS)/$< OUTPUT=$(CONTRACT_HELPERS_STUBS)/ContractHelpers.raw ./.maintain/scripts/compile_stub.sh
INPUT=$(CONTRACT_HELPERS_STUBS)/$< OUTPUT=$(CONTRACT_HELPERS_ABI) ./.maintain/scripts/generate_abi.sh
-CollectionHelper: CollectionHelper.sol
- INPUT=$(COLLECTION_HELPER_STUBS)/$< OUTPUT=$(COLLECTION_HELPER_STUBS)/CollectionHelper.raw ./.maintain/scripts/compile_stub.sh
+CollectionHelpers: CollectionHelpers.sol
+ INPUT=$(COLLECTION_HELPER_STUBS)/$< OUTPUT=$(COLLECTION_HELPER_STUBS)/CollectionHelpers.raw ./.maintain/scripts/compile_stub.sh
INPUT=$(COLLECTION_HELPER_STUBS)/$< OUTPUT=$(COLLECTION_HELPER_ABI) ./.maintain/scripts/generate_abi.sh
-evm_stubs: UniqueFungible UniqueNFT ContractHelpers CollectionHelper
+evm_stubs: UniqueFungible UniqueNFT ContractHelpers CollectionHelpers
.PHONY: _bench
_bench:
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -21,6 +21,7 @@
up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
+ethereum = { version = "0.12.0", default-features = false }
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.21-logs" }
serde = { version = "1.0.130", default-features = false }
pallets/common/src/dispatch.rsdiffbeforeafterboth--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -56,7 +56,10 @@
}
pub trait CollectionDispatch<T: Config> {
- fn create(sender: T::AccountId, data: CreateCollectionData<T::AccountId>) -> DispatchResult;
+ fn create(
+ sender: T::CrossAccountId,
+ data: CreateCollectionData<T::AccountId>,
+ ) -> DispatchResult;
fn destroy(sender: T::CrossAccountId, handle: CollectionHandle<T>) -> DispatchResult;
fn dispatch(handle: CollectionHandle<T>) -> Self;
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -15,7 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use evm_coder::{
- solidity_interface, solidity,
+ solidity_interface, solidity, ToLog,
types::*,
execution::{Result, Error},
};
@@ -28,6 +28,16 @@
use crate::{Pallet, CollectionHandle, Config, CollectionProperties};
+#[derive(ToLog)]
+pub enum CollectionHelpersEvents {
+ CollectionCreated {
+ #[indexed]
+ owner: address,
+ #[indexed]
+ collection_id: address,
+ },
+}
+
/// Does not always represent a full collection, for RFT it is either
/// collection (Implementing ERC721), or specific collection token (Implementing ERC20)
pub trait CommonEvmHandler {
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;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: 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 }156157 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> bool {158 if self.collection.sponsorship.pending_sponsor() != Some(sender) {159 return false;160 };161162 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());163 true164 }165}166impl<T: Config> Deref for CollectionHandle<T> {167 type Target = Collection<T::AccountId>;168169 fn deref(&self) -> &Self::Target {170 &self.collection171 }172}173174impl<T: Config> DerefMut for CollectionHandle<T> {175 fn deref_mut(&mut self) -> &mut Self::Target {176 &mut self.collection177 }178}179180impl<T: Config> CollectionHandle<T> {181 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {182 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);183 Ok(())184 }185 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {186 *subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))187 }188 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {189 ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);190 Ok(())191 }192 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {193 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)194 }195 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {196 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)197 }198 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {199 ensure!(200 <Allowlist<T>>::get((self.id, user)),201 <Error<T>>::AddressNotInAllowlist202 );203 Ok(())204 }205}206207#[frame_support::pallet]208pub mod pallet {209 use super::*;210 use pallet_evm::account;211 use dispatch::CollectionDispatch;212 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};213 use frame_system::pallet_prelude::*;214 use frame_support::traits::Currency;215 use up_data_structs::{TokenId, mapping::TokenAddressMapping};216 use scale_info::TypeInfo;217 use weights::WeightInfo;218219 #[pallet::config]220 pub trait Config:221 frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config222 {223 type WeightInfo: WeightInfo;224 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;225226 type Currency: Currency<Self::AccountId>;227228 #[pallet::constant]229 type CollectionCreationPrice: Get<230 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,231 >;232 type CollectionDispatch: CollectionDispatch<Self>;233234 type TreasuryAccountId: Get<Self::AccountId>;235236 type EvmTokenAddressMapping: TokenAddressMapping<H160>;237 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;238 }239240 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);241242 #[pallet::pallet]243 #[pallet::storage_version(STORAGE_VERSION)]244 #[pallet::generate_store(pub(super) trait Store)]245 pub struct Pallet<T>(_);246247 #[pallet::extra_constants]248 impl<T: Config> Pallet<T> {249 pub fn collection_admins_limit() -> u32 {250 COLLECTION_ADMINS_LIMIT251 }252 }253254 #[pallet::event]255 #[pallet::generate_deposit(pub fn deposit_event)]256 pub enum Event<T: Config> {257 /// New collection was created258 ///259 /// # Arguments260 ///261 /// * collection_id: Globally unique identifier of newly created collection.262 ///263 /// * mode: [CollectionMode] converted into u8.264 ///265 /// * account_id: Collection owner.266 CollectionCreated(CollectionId, u8, T::AccountId),267268 /// New collection was destroyed269 ///270 /// # Arguments271 ///272 /// * collection_id: Globally unique identifier of collection.273 CollectionDestroyed(CollectionId),274275 /// New item was created.276 ///277 /// # Arguments278 ///279 /// * collection_id: Id of the collection where item was created.280 ///281 /// * item_id: Id of an item. Unique within the collection.282 ///283 /// * recipient: Owner of newly created item284 ///285 /// * amount: Always 1 for NFT286 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),287288 /// Collection item was burned.289 ///290 /// # Arguments291 ///292 /// * collection_id.293 ///294 /// * item_id: Identifier of burned NFT.295 ///296 /// * owner: which user has destroyed its tokens297 ///298 /// * amount: Always 1 for NFT299 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),300301 /// Item was transferred302 ///303 /// * collection_id: Id of collection to which item is belong304 ///305 /// * item_id: Id of an item306 ///307 /// * sender: Original owner of item308 ///309 /// * recipient: New owner of item310 ///311 /// * amount: Always 1 for NFT312 Transfer(313 CollectionId,314 TokenId,315 T::CrossAccountId,316 T::CrossAccountId,317 u128,318 ),319320 /// * collection_id321 ///322 /// * item_id323 ///324 /// * sender325 ///326 /// * spender327 ///328 /// * amount329 Approved(330 CollectionId,331 TokenId,332 T::CrossAccountId,333 T::CrossAccountId,334 u128,335 ),336337 CollectionPropertySet(CollectionId, PropertyKey),338339 CollectionPropertyDeleted(CollectionId, PropertyKey),340341 TokenPropertySet(CollectionId, TokenId, PropertyKey),342343 TokenPropertyDeleted(CollectionId, TokenId, PropertyKey),344345 PropertyPermissionSet(CollectionId, PropertyKey),346 }347348 #[pallet::error]349 pub enum Error<T> {350 /// This collection does not exist.351 CollectionNotFound,352 /// Sender parameter and item owner must be equal.353 MustBeTokenOwner,354 /// No permission to perform action355 NoPermission,356 /// Destroying only empty collections is allowed357 CantDestroyNotEmptyCollection,358 /// Collection is not in mint mode.359 PublicMintingNotAllowed,360 /// Address is not in allow list.361 AddressNotInAllowlist,362363 /// Collection name can not be longer than 63 char.364 CollectionNameLimitExceeded,365 /// Collection description can not be longer than 255 char.366 CollectionDescriptionLimitExceeded,367 /// Token prefix can not be longer than 15 char.368 CollectionTokenPrefixLimitExceeded,369 /// Total collections bound exceeded.370 TotalCollectionsLimitExceeded,371 /// Exceeded max admin count372 CollectionAdminCountExceeded,373 /// Collection limit bounds per collection exceeded374 CollectionLimitBoundsExceeded,375 /// Tried to enable permissions which are only permitted to be disabled376 OwnerPermissionsCantBeReverted,377 /// Collection settings not allowing items transferring378 TransferNotAllowed,379 /// Account token limit exceeded per collection380 AccountTokenLimitExceeded,381 /// Collection token limit exceeded382 CollectionTokenLimitExceeded,383 /// Metadata flag frozen384 MetadataFlagFrozen,385386 /// Item not exists.387 TokenNotFound,388 /// Item balance not enough.389 TokenValueTooLow,390 /// Requested value more than approved.391 ApprovedValueTooLow,392 /// Tried to approve more than owned393 CantApproveMoreThanOwned,394395 /// Can't transfer tokens to ethereum zero address396 AddressIsZero,397 /// Target collection doesn't supports this operation398 UnsupportedOperation,399400 /// Not sufficient founds to perform action401 NotSufficientFounds,402403 /// Collection has nesting disabled404 NestingIsDisabled,405 /// Only owner may nest tokens under this collection406 OnlyOwnerAllowedToNest,407 /// Only tokens from specific collections may nest tokens under this408 SourceCollectionIsNotAllowedToNest,409410 /// Tried to store more data than allowed in collection field411 CollectionFieldSizeExceeded,412413 /// Tried to store more property data than allowed414 NoSpaceForProperty,415416 /// Tried to store more property keys than allowed417 PropertyLimitReached,418419 /// Property key is too long420 PropertyKeyIsTooLong,421422 /// Only ASCII letters, digits, and '_', '-' are allowed423 InvalidCharacterInPropertyKey,424425 /// Empty property keys are forbidden426 EmptyPropertyKey,427 }428429 #[pallet::storage]430 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;431 #[pallet::storage]432 pub type DestroyedCollectionCount<T> =433 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;434435 /// Collection info436 #[pallet::storage]437 pub type CollectionById<T> = StorageMap<438 Hasher = Blake2_128Concat,439 Key = CollectionId,440 Value = Collection<<T as frame_system::Config>::AccountId>,441 QueryKind = OptionQuery,442 >;443444 /// Collection properties445 #[pallet::storage]446 #[pallet::getter(fn collection_properties)]447 pub type CollectionProperties<T> = StorageMap<448 Hasher = Blake2_128Concat,449 Key = CollectionId,450 Value = Properties,451 QueryKind = ValueQuery,452 OnEmpty = up_data_structs::CollectionProperties,453 >;454455 #[pallet::storage]456 #[pallet::getter(fn property_permissions)]457 pub type CollectionPropertyPermissions<T> = StorageMap<458 Hasher = Blake2_128Concat,459 Key = CollectionId,460 Value = PropertiesPermissionMap,461 QueryKind = ValueQuery,462 >;463464 #[pallet::storage]465 pub type AdminAmount<T> = StorageMap<466 Hasher = Blake2_128Concat,467 Key = CollectionId,468 Value = u32,469 QueryKind = ValueQuery,470 >;471472 /// List of collection admins473 #[pallet::storage]474 pub type IsAdmin<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 /// Allowlisted collection users484 #[pallet::storage]485 pub type Allowlist<T: Config> = StorageNMap<486 Key = (487 Key<Blake2_128Concat, CollectionId>,488 Key<Blake2_128Concat, T::CrossAccountId>,489 ),490 Value = bool,491 QueryKind = ValueQuery,492 >;493494 /// Not used by code, exists only to provide some types to metadata495 #[pallet::storage]496 pub type DummyStorageValue<T: Config> = StorageValue<497 Value = (498 CollectionStats,499 CollectionId,500 TokenId,501 PhantomType<(502 TokenData<T::CrossAccountId>,503 RpcCollection<T::AccountId>,504 // RMRK505 RmrkCollectionInfo<T::AccountId>,506 RmrkInstanceInfo<T::AccountId>,507 RmrkResourceInfo,508 RmrkPropertyInfo,509 RmrkBaseInfo<T::AccountId>,510 RmrkPartType,511 RmrkTheme,512 RmrkNftChild,513 )>,514 ),515 QueryKind = OptionQuery,516 >;517518 #[pallet::hooks]519 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {520 fn on_runtime_upgrade() -> Weight {521 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {522 use up_data_structs::{CollectionVersion1, CollectionVersion2};523 <CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {524 let mut props = Vec::new();525 if !v.offchain_schema.is_empty() {526 props.push(Property {527 key: b"_old_offchainSchema".to_vec().try_into().unwrap(),528 value: v529 .offchain_schema530 .clone()531 .into_inner()532 .try_into()533 .expect("offchain schema too big"),534 });535 }536 if !v.variable_on_chain_schema.is_empty() {537 props.push(Property {538 key: b"_old_variableOnChainSchema".to_vec().try_into().unwrap(),539 value: v540 .variable_on_chain_schema541 .clone()542 .into_inner()543 .try_into()544 .expect("offchain schema too big"),545 });546 }547 if !v.const_on_chain_schema.is_empty() {548 props.push(Property {549 key: b"_old_constOnChainSchema".to_vec().try_into().unwrap(),550 value: v551 .const_on_chain_schema552 .clone()553 .into_inner()554 .try_into()555 .expect("offchain schema too big"),556 });557 }558 props.push(Property {559 key: b"_old_schemaVersion".to_vec().try_into().unwrap(),560 value: match v.schema_version {561 SchemaVersion::ImageURL => b"ImageUrl".as_slice(),562 SchemaVersion::Unique => b"Unique".as_slice(),563 }564 .to_vec()565 .try_into()566 .unwrap(),567 });568 Self::set_scoped_collection_properties(569 id,570 PropertyScope::None,571 props.into_iter(),572 )573 .expect("existing data larger than properties");574 let mut new = CollectionVersion2::from(v.clone());575 new.permissions.access = Some(v.access);576 new.permissions.mint_mode = Some(v.mint_mode);577 Some(new)578 });579 }580581 0582 }583 }584}585586impl<T: Config> Pallet<T> {587 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens588 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {589 ensure!(590 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,591 <Error<T>>::AddressIsZero592 );593 Ok(())594 }595 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {596 <IsAdmin<T>>::iter_prefix((collection,))597 .map(|(a, _)| a)598 .collect()599 }600 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {601 <Allowlist<T>>::iter_prefix((collection,))602 .map(|(a, _)| a)603 .collect()604 }605 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {606 <Allowlist<T>>::get((collection, user))607 }608 pub fn collection_stats() -> CollectionStats {609 let created = <CreatedCollectionCount<T>>::get();610 let destroyed = <DestroyedCollectionCount<T>>::get();611 CollectionStats {612 created: created.0,613 destroyed: destroyed.0,614 alive: created.0 - destroyed.0,615 }616 }617618 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {619 let collection = <CollectionById<T>>::get(collection);620 if collection.is_none() {621 return None;622 }623624 let collection = collection.unwrap();625 let limits = collection.limits;626 let effective_limits = CollectionLimits {627 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),628 sponsored_data_size: Some(limits.sponsored_data_size()),629 sponsored_data_rate_limit: Some(630 limits631 .sponsored_data_rate_limit632 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),633 ),634 token_limit: Some(limits.token_limit()),635 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(636 match collection.mode {637 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,638 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,639 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,640 },641 )),642 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),643 owner_can_transfer: Some(limits.owner_can_transfer()),644 owner_can_destroy: Some(limits.owner_can_destroy()),645 transfers_enabled: Some(limits.transfers_enabled()),646 };647648 Some(effective_limits)649 }650651 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {652 let Collection {653 name,654 description,655 owner,656 mode,657 token_prefix,658 sponsorship,659 limits,660 permissions,661 } = <CollectionById<T>>::get(collection)?;662663 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)664 .into_iter()665 .map(|(key, permission)| PropertyKeyPermission { key, permission })666 .collect();667668 let properties = <CollectionProperties<T>>::get(collection)669 .into_iter()670 .map(|(key, value)| Property { key, value })671 .collect();672673 let permissions = CollectionPermissions {674 access: Some(permissions.access()),675 mint_mode: Some(permissions.mint_mode()),676 nesting: Some(permissions.nesting().clone()),677 };678679 Some(RpcCollection {680 name: name.into_inner(),681 description: description.into_inner(),682 owner,683 mode,684 token_prefix: token_prefix.into_inner(),685 sponsorship,686 limits,687 permissions,688 token_property_permissions,689 properties,690 })691 }692}693694macro_rules! limit_default {695 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{696 $(697 if let Some($new) = $new.$field {698 let $old = $old.$field($($arg)?);699 let _ = $new;700 let _ = $old;701 $check702 } else {703 $new.$field = $old.$field704 }705 )*706 }};707}708macro_rules! limit_default_clone {709 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{710 $(711 if let Some($new) = $new.$field.clone() {712 let $old = $old.$field($($arg)?);713 let _ = $new;714 let _ = $old;715 $check716 } else {717 $new.$field = $old.$field.clone()718 }719 )*720 }};721}722723impl<T: Config> Pallet<T> {724 pub fn init_collection(725 owner: T::AccountId,726 data: CreateCollectionData<T::AccountId>,727 ) -> Result<CollectionId, DispatchError> {728 {729 ensure!(730 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,731 Error::<T>::CollectionTokenPrefixLimitExceeded732 );733 }734735 let created_count = <CreatedCollectionCount<T>>::get()736 .0737 .checked_add(1)738 .ok_or(ArithmeticError::Overflow)?;739 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;740 let id = CollectionId(created_count);741742 // bound Total number of collections743 ensure!(744 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,745 <Error<T>>::TotalCollectionsLimitExceeded746 );747748 // =========749750 let collection = Collection {751 owner: owner.clone(),752 name: data.name,753 mode: data.mode.clone(),754 description: data.description,755 token_prefix: data.token_prefix,756 sponsorship: data757 .pending_sponsor758 .map(SponsorshipState::Unconfirmed)759 .unwrap_or_default(),760 limits: data761 .limits762 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))763 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,764 permissions: data765 .permissions766 .map(|permissions| {767 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)768 })769 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,770 };771772 let mut collection_properties = up_data_structs::CollectionProperties::get();773 collection_properties774 .try_set_from_iter(data.properties.into_iter())775 .map_err(<Error<T>>::from)?;776777 CollectionProperties::<T>::insert(id, collection_properties);778779 let mut token_props_permissions = PropertiesPermissionMap::new();780 token_props_permissions781 .try_set_from_iter(data.token_property_permissions.into_iter())782 .map_err(<Error<T>>::from)?;783784 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);785786 // Take a (non-refundable) deposit of collection creation787 {788 let mut imbalance =789 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();790 imbalance.subsume(791 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(792 &T::TreasuryAccountId::get(),793 T::CollectionCreationPrice::get(),794 ),795 );796 <T as Config>::Currency::settle(797 &owner,798 imbalance,799 WithdrawReasons::TRANSFER,800 ExistenceRequirement::KeepAlive,801 )802 .map_err(|_| Error::<T>::NotSufficientFounds)?;803 }804805 <CreatedCollectionCount<T>>::put(created_count);806 <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));807 <CollectionById<T>>::insert(id, collection);808 Ok(id)809 }810811 pub fn destroy_collection(812 collection: CollectionHandle<T>,813 sender: &T::CrossAccountId,814 ) -> DispatchResult {815 ensure!(816 collection.limits.owner_can_destroy(),817 <Error<T>>::NoPermission,818 );819 collection.check_is_owner(sender)?;820821 let destroyed_collections = <DestroyedCollectionCount<T>>::get()822 .0823 .checked_add(1)824 .ok_or(ArithmeticError::Overflow)?;825826 // =========827828 <DestroyedCollectionCount<T>>::put(destroyed_collections);829 <CollectionById<T>>::remove(collection.id);830 <AdminAmount<T>>::remove(collection.id);831 <IsAdmin<T>>::remove_prefix((collection.id,), None);832 <Allowlist<T>>::remove_prefix((collection.id,), None);833 <CollectionProperties<T>>::remove(collection.id);834835 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));836 Ok(())837 }838839 pub fn set_collection_property(840 collection: &CollectionHandle<T>,841 sender: &T::CrossAccountId,842 property: Property,843 ) -> DispatchResult {844 collection.check_is_owner_or_admin(sender)?;845846 CollectionProperties::<T>::try_mutate(collection.id, |properties| {847 let property = property.clone();848 properties.try_set(property.key, property.value)849 })850 .map_err(<Error<T>>::from)?;851852 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));853854 Ok(())855 }856857 pub fn set_scoped_collection_property(858 collection_id: CollectionId,859 scope: PropertyScope,860 property: Property,861 ) -> DispatchResult {862 CollectionProperties::<T>::try_mutate(collection_id, |properties| {863 properties.try_scoped_set(scope, property.key, property.value)864 })865 .map_err(<Error<T>>::from)?;866867 Ok(())868 }869870 pub fn set_scoped_collection_properties(871 collection_id: CollectionId,872 scope: PropertyScope,873 properties: impl Iterator<Item = Property>,874 ) -> DispatchResult {875 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {876 stored_properties.try_scoped_set_from_iter(scope, properties)877 })878 .map_err(<Error<T>>::from)?;879880 Ok(())881 }882883 #[transactional]884 pub fn set_collection_properties(885 collection: &CollectionHandle<T>,886 sender: &T::CrossAccountId,887 properties: Vec<Property>,888 ) -> DispatchResult {889 for property in properties {890 Self::set_collection_property(collection, sender, property)?;891 }892893 Ok(())894 }895896 pub fn delete_collection_property(897 collection: &CollectionHandle<T>,898 sender: &T::CrossAccountId,899 property_key: PropertyKey,900 ) -> DispatchResult {901 collection.check_is_owner_or_admin(sender)?;902903 CollectionProperties::<T>::try_mutate(collection.id, |properties| {904 properties.remove(&property_key)905 })906 .map_err(<Error<T>>::from)?;907908 Self::deposit_event(Event::CollectionPropertyDeleted(909 collection.id,910 property_key,911 ));912913 Ok(())914 }915916 #[transactional]917 pub fn delete_collection_properties(918 collection: &CollectionHandle<T>,919 sender: &T::CrossAccountId,920 property_keys: Vec<PropertyKey>,921 ) -> DispatchResult {922 for key in property_keys {923 Self::delete_collection_property(collection, sender, key)?;924 }925926 Ok(())927 }928929 // For migrations930 pub fn set_property_permission_unchecked(931 collection: CollectionId,932 property_permission: PropertyKeyPermission,933 ) -> DispatchResult {934 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {935 permissions.try_set(property_permission.key, property_permission.permission)936 })937 .map_err(<Error<T>>::from)?;938 Ok(())939 }940941 pub fn set_property_permission(942 collection: &CollectionHandle<T>,943 sender: &T::CrossAccountId,944 property_permission: PropertyKeyPermission,945 ) -> DispatchResult {946 collection.check_is_owner_or_admin(sender)?;947948 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);949 let current_permission = all_permissions.get(&property_permission.key);950 if matches![951 current_permission,952 Some(PropertyPermission { mutable: false, .. })953 ] {954 return Err(<Error<T>>::NoPermission.into());955 }956957 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {958 let property_permission = property_permission.clone();959 permissions.try_set(property_permission.key, property_permission.permission)960 })961 .map_err(<Error<T>>::from)?;962963 Self::deposit_event(Event::PropertyPermissionSet(964 collection.id,965 property_permission.key,966 ));967968 Ok(())969 }970971 #[transactional]972 pub fn set_property_permissions(973 collection: &CollectionHandle<T>,974 sender: &T::CrossAccountId,975 property_permissions: Vec<PropertyKeyPermission>,976 ) -> DispatchResult {977 for prop_pemission in property_permissions {978 Self::set_property_permission(collection, sender, prop_pemission)?;979 }980981 Ok(())982 }983984 pub fn get_collection_property(985 collection_id: CollectionId,986 key: &PropertyKey,987 ) -> Option<PropertyValue> {988 Self::collection_properties(collection_id).get(key).cloned()989 }990991 pub fn bytes_keys_to_property_keys(992 keys: Vec<Vec<u8>>,993 ) -> Result<Vec<PropertyKey>, DispatchError> {994 keys.into_iter()995 .map(|key| -> Result<PropertyKey, DispatchError> {996 key.try_into()997 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())998 })999 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1000 }10011002 pub fn filter_collection_properties(1003 collection_id: CollectionId,1004 keys: Option<Vec<PropertyKey>>,1005 ) -> Result<Vec<Property>, DispatchError> {1006 let properties = Self::collection_properties(collection_id);10071008 let properties = keys1009 .map(|keys| {1010 keys.into_iter()1011 .filter_map(|key| {1012 properties.get(&key).map(|value| Property {1013 key,1014 value: value.clone(),1015 })1016 })1017 .collect()1018 })1019 .unwrap_or_else(|| {1020 properties1021 .into_iter()1022 .map(|(key, value)| Property { key, value })1023 .collect()1024 });10251026 Ok(properties)1027 }10281029 pub fn filter_property_permissions(1030 collection_id: CollectionId,1031 keys: Option<Vec<PropertyKey>>,1032 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1033 let permissions = Self::property_permissions(collection_id);10341035 let key_permissions = keys1036 .map(|keys| {1037 keys.into_iter()1038 .filter_map(|key| {1039 permissions1040 .get(&key)1041 .map(|permission| PropertyKeyPermission {1042 key,1043 permission: permission.clone(),1044 })1045 })1046 .collect()1047 })1048 .unwrap_or_else(|| {1049 permissions1050 .into_iter()1051 .map(|(key, permission)| PropertyKeyPermission { key, permission })1052 .collect()1053 });10541055 Ok(key_permissions)1056 }10571058 pub fn toggle_allowlist(1059 collection: &CollectionHandle<T>,1060 sender: &T::CrossAccountId,1061 user: &T::CrossAccountId,1062 allowed: bool,1063 ) -> DispatchResult {1064 collection.check_is_owner_or_admin(sender)?;10651066 // =========10671068 if allowed {1069 <Allowlist<T>>::insert((collection.id, user), true);1070 } else {1071 <Allowlist<T>>::remove((collection.id, user));1072 }10731074 Ok(())1075 }10761077 pub fn toggle_admin(1078 collection: &CollectionHandle<T>,1079 sender: &T::CrossAccountId,1080 user: &T::CrossAccountId,1081 admin: bool,1082 ) -> DispatchResult {1083 collection.check_is_owner_or_admin(sender)?;10841085 let was_admin = <IsAdmin<T>>::get((collection.id, user));1086 if was_admin == admin {1087 return Ok(());1088 }1089 let amount = <AdminAmount<T>>::get(collection.id);10901091 if admin {1092 let amount = amount1093 .checked_add(1)1094 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1095 ensure!(1096 amount <= Self::collection_admins_limit(),1097 <Error<T>>::CollectionAdminCountExceeded,1098 );10991100 // =========11011102 <AdminAmount<T>>::insert(collection.id, amount);1103 <IsAdmin<T>>::insert((collection.id, user), true);1104 } else {1105 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1106 <IsAdmin<T>>::remove((collection.id, user));1107 }11081109 Ok(())1110 }11111112 pub fn clamp_limits(1113 mode: CollectionMode,1114 old_limit: &CollectionLimits,1115 mut new_limit: CollectionLimits,1116 ) -> Result<CollectionLimits, DispatchError> {1117 limit_default!(old_limit, new_limit,1118 account_token_ownership_limit => ensure!(1119 new_limit <= MAX_TOKEN_OWNERSHIP,1120 <Error<T>>::CollectionLimitBoundsExceeded,1121 ),1122 sponsored_data_size => ensure!(1123 new_limit <= CUSTOM_DATA_LIMIT,1124 <Error<T>>::CollectionLimitBoundsExceeded,1125 ),11261127 sponsored_data_rate_limit => {},1128 token_limit => ensure!(1129 old_limit >= new_limit && new_limit > 0,1130 <Error<T>>::CollectionTokenLimitExceeded1131 ),11321133 sponsor_transfer_timeout(match mode {1134 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1135 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1136 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1137 }) => ensure!(1138 new_limit <= MAX_SPONSOR_TIMEOUT,1139 <Error<T>>::CollectionLimitBoundsExceeded,1140 ),1141 sponsor_approve_timeout => {},1142 owner_can_transfer => ensure!(1143 old_limit || !new_limit,1144 <Error<T>>::OwnerPermissionsCantBeReverted,1145 ),1146 owner_can_destroy => ensure!(1147 old_limit || !new_limit,1148 <Error<T>>::OwnerPermissionsCantBeReverted,1149 ),1150 transfers_enabled => {},1151 );1152 Ok(new_limit)1153 }1154 pub fn clamp_permissions(1155 mode: CollectionMode,1156 old_limit: &CollectionPermissions,1157 mut new_limit: CollectionPermissions,1158 ) -> Result<CollectionPermissions, DispatchError> {1159 limit_default_clone!(old_limit, new_limit,1160 access => {},1161 mint_mode => {},1162 nesting => {},1163 );1164 Ok(new_limit)1165 }1166}11671168#[macro_export]1169macro_rules! unsupported {1170 () => {1171 Err(<Error<T>>::UnsupportedOperation.into())1172 };1173}11741175/// Worst cases1176pub trait CommonWeightInfo<CrossAccountId> {1177 fn create_item() -> Weight;1178 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;1179 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;1180 fn burn_item() -> Weight;1181 fn set_collection_properties(amount: u32) -> Weight;1182 fn delete_collection_properties(amount: u32) -> Weight;1183 fn set_token_properties(amount: u32) -> Weight;1184 fn delete_token_properties(amount: u32) -> Weight;1185 fn set_property_permissions(amount: u32) -> Weight;1186 fn transfer() -> Weight;1187 fn approve() -> Weight;1188 fn transfer_from() -> Weight;1189 fn burn_from() -> Weight;1190}11911192pub trait CommonCollectionOperations<T: Config> {1193 fn create_item(1194 &self,1195 sender: T::CrossAccountId,1196 to: T::CrossAccountId,1197 data: CreateItemData,1198 nesting_budget: &dyn Budget,1199 ) -> DispatchResultWithPostInfo;1200 fn create_multiple_items(1201 &self,1202 sender: T::CrossAccountId,1203 to: T::CrossAccountId,1204 data: Vec<CreateItemData>,1205 nesting_budget: &dyn Budget,1206 ) -> DispatchResultWithPostInfo;1207 fn create_multiple_items_ex(1208 &self,1209 sender: T::CrossAccountId,1210 data: CreateItemExData<T::CrossAccountId>,1211 nesting_budget: &dyn Budget,1212 ) -> DispatchResultWithPostInfo;1213 fn burn_item(1214 &self,1215 sender: T::CrossAccountId,1216 token: TokenId,1217 amount: u128,1218 ) -> DispatchResultWithPostInfo;1219 fn set_collection_properties(1220 &self,1221 sender: T::CrossAccountId,1222 properties: Vec<Property>,1223 ) -> DispatchResultWithPostInfo;1224 fn delete_collection_properties(1225 &self,1226 sender: &T::CrossAccountId,1227 property_keys: Vec<PropertyKey>,1228 ) -> DispatchResultWithPostInfo;1229 fn set_token_properties(1230 &self,1231 sender: T::CrossAccountId,1232 token_id: TokenId,1233 property: Vec<Property>,1234 ) -> DispatchResultWithPostInfo;1235 fn delete_token_properties(1236 &self,1237 sender: T::CrossAccountId,1238 token_id: TokenId,1239 property_keys: Vec<PropertyKey>,1240 ) -> DispatchResultWithPostInfo;1241 fn set_property_permissions(1242 &self,1243 sender: &T::CrossAccountId,1244 property_permissions: Vec<PropertyKeyPermission>,1245 ) -> DispatchResultWithPostInfo;1246 fn transfer(1247 &self,1248 sender: T::CrossAccountId,1249 to: T::CrossAccountId,1250 token: TokenId,1251 amount: u128,1252 nesting_budget: &dyn Budget,1253 ) -> DispatchResultWithPostInfo;1254 fn approve(1255 &self,1256 sender: T::CrossAccountId,1257 spender: T::CrossAccountId,1258 token: TokenId,1259 amount: u128,1260 ) -> DispatchResultWithPostInfo;1261 fn transfer_from(1262 &self,1263 sender: T::CrossAccountId,1264 from: T::CrossAccountId,1265 to: T::CrossAccountId,1266 token: TokenId,1267 amount: u128,1268 nesting_budget: &dyn Budget,1269 ) -> DispatchResultWithPostInfo;1270 fn burn_from(1271 &self,1272 sender: T::CrossAccountId,1273 from: T::CrossAccountId,1274 token: TokenId,1275 amount: u128,1276 nesting_budget: &dyn Budget,1277 ) -> DispatchResultWithPostInfo;12781279 fn check_nesting(1280 &self,1281 sender: T::CrossAccountId,1282 from: (CollectionId, TokenId),1283 under: TokenId,1284 budget: &dyn Budget,1285 ) -> DispatchResult;12861287 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));12881289 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));12901291 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;1292 fn collection_tokens(&self) -> Vec<TokenId>;1293 fn token_exists(&self, token: TokenId) -> bool;1294 fn last_token_id(&self) -> TokenId;12951296 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;1297 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;1298 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;1299 /// Amount of unique collection tokens1300 fn total_supply(&self) -> u32;1301 /// Amount of different tokens account has (Applicable to nonfungible/refungible)1302 fn account_balance(&self, account: T::CrossAccountId) -> u32;1303 /// Amount of specific token account have (Applicable to fungible/refungible)1304 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;1305 fn allowance(1306 &self,1307 sender: T::CrossAccountId,1308 spender: T::CrossAccountId,1309 token: TokenId,1310 ) -> u128;1311}13121313// Flexible enough for implementing CommonCollectionOperations1314pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1315 let post_info = PostDispatchInfo {1316 actual_weight: Some(weight),1317 pays_fee: Pays::Yes,1318 };1319 match res {1320 Ok(()) => Ok(post_info),1321 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1322 }1323}13241325impl<T: Config> From<PropertiesError> for Error<T> {1326 fn from(error: PropertiesError) -> Self {1327 match error {1328 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1329 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1330 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1331 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1332 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1333 }1334 }1335}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;24use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};25use evm_coder::ToLog;26use frame_support::{27 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},28 ensure,29 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},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 PhantomType,58 Property,59 Properties,60 PropertiesPermissionMap,61 PropertyKey,62 PropertyValue,63 PropertyPermission,64 PropertiesError,65 PropertyKeyPermission,66 TokenData,67 TrySetProperty,68 PropertyScope,69 // RMRK70 RmrkCollectionInfo,71 RmrkInstanceInfo,72 RmrkResourceInfo,73 RmrkPropertyInfo,74 RmrkBaseInfo,75 RmrkPartType,76 RmrkTheme,77 RmrkNftChild,78 CollectionPermissions,79 SchemaVersion,80};8182pub use pallet::*;83use sp_core::H160;84use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};85#[cfg(feature = "runtime-benchmarks")]86pub mod benchmarking;87pub mod dispatch;88pub mod erc;89pub mod eth;90pub mod weights;9192pub type SelfWeightOf<T> = <T as Config>::WeightInfo;9394#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]95pub struct CollectionHandle<T: Config> {96 pub id: CollectionId,97 collection: Collection<T::AccountId>,98 pub recorder: SubstrateRecorder<T>,99}100impl<T: Config> WithRecorder<T> for CollectionHandle<T> {101 fn recorder(&self) -> &SubstrateRecorder<T> {102 &self.recorder103 }104 fn into_recorder(self) -> SubstrateRecorder<T> {105 self.recorder106 }107}108impl<T: Config> CollectionHandle<T> {109 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {110 <CollectionById<T>>::get(id).map(|collection| Self {111 id,112 collection,113 recorder: SubstrateRecorder::new(gas_limit),114 })115 }116117 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {118 <CollectionById<T>>::get(id).map(|collection| Self {119 id,120 collection,121 recorder,122 })123 }124125 pub fn new(id: CollectionId) -> Option<Self> {126 Self::new_with_gas_limit(id, u64::MAX)127 }128 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {129 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)130 }131 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {132 self.recorder133 .consume_gas(T::GasWeightMapping::weight_to_gas(134 <T as frame_system::Config>::DbWeight::get()135 .read136 .saturating_mul(reads),137 ))138 }139 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {140 self.recorder141 .consume_gas(T::GasWeightMapping::weight_to_gas(142 <T as frame_system::Config>::DbWeight::get()143 .write144 .saturating_mul(writes),145 ))146 }147 pub fn save(self) -> DispatchResult {148 <CollectionById<T>>::insert(self.id, self.collection);149 Ok(())150 }151152 pub fn set_sponsor(&mut self, sponsor: T::AccountId) {153 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);154 }155156 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> bool {157 if self.collection.sponsorship.pending_sponsor() != Some(sender) {158 return false;159 };160161 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());162 true163 }164}165impl<T: Config> Deref for CollectionHandle<T> {166 type Target = Collection<T::AccountId>;167168 fn deref(&self) -> &Self::Target {169 &self.collection170 }171}172173impl<T: Config> DerefMut for CollectionHandle<T> {174 fn deref_mut(&mut self) -> &mut Self::Target {175 &mut self.collection176 }177}178179impl<T: Config> CollectionHandle<T> {180 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {181 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);182 Ok(())183 }184 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {185 *subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))186 }187 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {188 ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);189 Ok(())190 }191 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {192 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)193 }194 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {195 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)196 }197 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {198 ensure!(199 <Allowlist<T>>::get((self.id, user)),200 <Error<T>>::AddressNotInAllowlist201 );202 Ok(())203 }204}205206#[frame_support::pallet]207pub mod pallet {208 use super::*;209 use pallet_evm::account;210 use dispatch::CollectionDispatch;211 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};212 use frame_system::pallet_prelude::*;213 use frame_support::traits::Currency;214 use up_data_structs::{TokenId, mapping::TokenAddressMapping};215 use scale_info::TypeInfo;216 use weights::WeightInfo;217218 #[pallet::config]219 pub trait Config:220 frame_system::Config221 + pallet_evm_coder_substrate::Config222 + pallet_evm::Config223 + TypeInfo224 + account::Config225 {226 type WeightInfo: WeightInfo;227 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;228229 type Currency: Currency<Self::AccountId>;230231 #[pallet::constant]232 type CollectionCreationPrice: Get<233 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,234 >;235 type CollectionDispatch: CollectionDispatch<Self>;236237 type TreasuryAccountId: Get<Self::AccountId>;238 type ContractAddress: Get<H160>;239240 type EvmTokenAddressMapping: TokenAddressMapping<H160>;241 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;242 }243244 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);245246 #[pallet::pallet]247 #[pallet::storage_version(STORAGE_VERSION)]248 #[pallet::generate_store(pub(super) trait Store)]249 pub struct Pallet<T>(_);250251 #[pallet::extra_constants]252 impl<T: Config> Pallet<T> {253 pub fn collection_admins_limit() -> u32 {254 COLLECTION_ADMINS_LIMIT255 }256 }257258 #[pallet::event]259 #[pallet::generate_deposit(pub fn deposit_event)]260 pub enum Event<T: Config> {261 /// New collection was created262 ///263 /// # Arguments264 ///265 /// * collection_id: Globally unique identifier of newly created collection.266 ///267 /// * mode: [CollectionMode] converted into u8.268 ///269 /// * account_id: Collection owner.270 CollectionCreated(CollectionId, u8, T::AccountId),271272 /// New collection was destroyed273 ///274 /// # Arguments275 ///276 /// * collection_id: Globally unique identifier of collection.277 CollectionDestroyed(CollectionId),278279 /// New item was created.280 ///281 /// # Arguments282 ///283 /// * collection_id: Id of the collection where item was created.284 ///285 /// * item_id: Id of an item. Unique within the collection.286 ///287 /// * recipient: Owner of newly created item288 ///289 /// * amount: Always 1 for NFT290 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),291292 /// Collection item was burned.293 ///294 /// # Arguments295 ///296 /// * collection_id.297 ///298 /// * item_id: Identifier of burned NFT.299 ///300 /// * owner: which user has destroyed its tokens301 ///302 /// * amount: Always 1 for NFT303 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),304305 /// Item was transferred306 ///307 /// * collection_id: Id of collection to which item is belong308 ///309 /// * item_id: Id of an item310 ///311 /// * sender: Original owner of item312 ///313 /// * recipient: New owner of item314 ///315 /// * amount: Always 1 for NFT316 Transfer(317 CollectionId,318 TokenId,319 T::CrossAccountId,320 T::CrossAccountId,321 u128,322 ),323324 /// * collection_id325 ///326 /// * item_id327 ///328 /// * sender329 ///330 /// * spender331 ///332 /// * amount333 Approved(334 CollectionId,335 TokenId,336 T::CrossAccountId,337 T::CrossAccountId,338 u128,339 ),340341 CollectionPropertySet(CollectionId, PropertyKey),342343 CollectionPropertyDeleted(CollectionId, PropertyKey),344345 TokenPropertySet(CollectionId, TokenId, PropertyKey),346347 TokenPropertyDeleted(CollectionId, TokenId, PropertyKey),348349 PropertyPermissionSet(CollectionId, PropertyKey),350 }351352 #[pallet::error]353 pub enum Error<T> {354 /// This collection does not exist.355 CollectionNotFound,356 /// Sender parameter and item owner must be equal.357 MustBeTokenOwner,358 /// No permission to perform action359 NoPermission,360 /// Destroying only empty collections is allowed361 CantDestroyNotEmptyCollection,362 /// Collection is not in mint mode.363 PublicMintingNotAllowed,364 /// Address is not in allow list.365 AddressNotInAllowlist,366367 /// Collection name can not be longer than 63 char.368 CollectionNameLimitExceeded,369 /// Collection description can not be longer than 255 char.370 CollectionDescriptionLimitExceeded,371 /// Token prefix can not be longer than 15 char.372 CollectionTokenPrefixLimitExceeded,373 /// Total collections bound exceeded.374 TotalCollectionsLimitExceeded,375 /// Exceeded max admin count376 CollectionAdminCountExceeded,377 /// Collection limit bounds per collection exceeded378 CollectionLimitBoundsExceeded,379 /// Tried to enable permissions which are only permitted to be disabled380 OwnerPermissionsCantBeReverted,381 /// Collection settings not allowing items transferring382 TransferNotAllowed,383 /// Account token limit exceeded per collection384 AccountTokenLimitExceeded,385 /// Collection token limit exceeded386 CollectionTokenLimitExceeded,387 /// Metadata flag frozen388 MetadataFlagFrozen,389390 /// Item not exists.391 TokenNotFound,392 /// Item balance not enough.393 TokenValueTooLow,394 /// Requested value more than approved.395 ApprovedValueTooLow,396 /// Tried to approve more than owned397 CantApproveMoreThanOwned,398399 /// Can't transfer tokens to ethereum zero address400 AddressIsZero,401 /// Target collection doesn't supports this operation402 UnsupportedOperation,403404 /// Not sufficient founds to perform action405 NotSufficientFounds,406407 /// Collection has nesting disabled408 NestingIsDisabled,409 /// Only owner may nest tokens under this collection410 OnlyOwnerAllowedToNest,411 /// Only tokens from specific collections may nest tokens under this412 SourceCollectionIsNotAllowedToNest,413414 /// Tried to store more data than allowed in collection field415 CollectionFieldSizeExceeded,416417 /// Tried to store more property data than allowed418 NoSpaceForProperty,419420 /// Tried to store more property keys than allowed421 PropertyLimitReached,422423 /// Property key is too long424 PropertyKeyIsTooLong,425426 /// Only ASCII letters, digits, and '_', '-' are allowed427 InvalidCharacterInPropertyKey,428429 /// Empty property keys are forbidden430 EmptyPropertyKey,431 }432433 #[pallet::storage]434 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;435 #[pallet::storage]436 pub type DestroyedCollectionCount<T> =437 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;438439 /// Collection info440 #[pallet::storage]441 pub type CollectionById<T> = StorageMap<442 Hasher = Blake2_128Concat,443 Key = CollectionId,444 Value = Collection<<T as frame_system::Config>::AccountId>,445 QueryKind = OptionQuery,446 >;447448 /// Collection properties449 #[pallet::storage]450 #[pallet::getter(fn collection_properties)]451 pub type CollectionProperties<T> = StorageMap<452 Hasher = Blake2_128Concat,453 Key = CollectionId,454 Value = Properties,455 QueryKind = ValueQuery,456 OnEmpty = up_data_structs::CollectionProperties,457 >;458459 #[pallet::storage]460 #[pallet::getter(fn property_permissions)]461 pub type CollectionPropertyPermissions<T> = StorageMap<462 Hasher = Blake2_128Concat,463 Key = CollectionId,464 Value = PropertiesPermissionMap,465 QueryKind = ValueQuery,466 >;467468 #[pallet::storage]469 pub type AdminAmount<T> = StorageMap<470 Hasher = Blake2_128Concat,471 Key = CollectionId,472 Value = u32,473 QueryKind = ValueQuery,474 >;475476 /// List of collection admins477 #[pallet::storage]478 pub type IsAdmin<T: Config> = StorageNMap<479 Key = (480 Key<Blake2_128Concat, CollectionId>,481 Key<Blake2_128Concat, T::CrossAccountId>,482 ),483 Value = bool,484 QueryKind = ValueQuery,485 >;486487 /// Allowlisted collection users488 #[pallet::storage]489 pub type Allowlist<T: Config> = StorageNMap<490 Key = (491 Key<Blake2_128Concat, CollectionId>,492 Key<Blake2_128Concat, T::CrossAccountId>,493 ),494 Value = bool,495 QueryKind = ValueQuery,496 >;497498 /// Not used by code, exists only to provide some types to metadata499 #[pallet::storage]500 pub type DummyStorageValue<T: Config> = StorageValue<501 Value = (502 CollectionStats,503 CollectionId,504 TokenId,505 PhantomType<(506 TokenData<T::CrossAccountId>,507 RpcCollection<T::AccountId>,508 // RMRK509 RmrkCollectionInfo<T::AccountId>,510 RmrkInstanceInfo<T::AccountId>,511 RmrkResourceInfo,512 RmrkPropertyInfo,513 RmrkBaseInfo<T::AccountId>,514 RmrkPartType,515 RmrkTheme,516 RmrkNftChild,517 )>,518 ),519 QueryKind = OptionQuery,520 >;521522 #[pallet::hooks]523 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {524 fn on_runtime_upgrade() -> Weight {525 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {526 use up_data_structs::{CollectionVersion1, CollectionVersion2};527 <CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {528 let mut props = Vec::new();529 if !v.offchain_schema.is_empty() {530 props.push(Property {531 key: b"_old_offchainSchema".to_vec().try_into().unwrap(),532 value: v533 .offchain_schema534 .clone()535 .into_inner()536 .try_into()537 .expect("offchain schema too big"),538 });539 }540 if !v.variable_on_chain_schema.is_empty() {541 props.push(Property {542 key: b"_old_variableOnChainSchema".to_vec().try_into().unwrap(),543 value: v544 .variable_on_chain_schema545 .clone()546 .into_inner()547 .try_into()548 .expect("offchain schema too big"),549 });550 }551 if !v.const_on_chain_schema.is_empty() {552 props.push(Property {553 key: b"_old_constOnChainSchema".to_vec().try_into().unwrap(),554 value: v555 .const_on_chain_schema556 .clone()557 .into_inner()558 .try_into()559 .expect("offchain schema too big"),560 });561 }562 props.push(Property {563 key: b"_old_schemaVersion".to_vec().try_into().unwrap(),564 value: match v.schema_version {565 SchemaVersion::ImageURL => b"ImageUrl".as_slice(),566 SchemaVersion::Unique => b"Unique".as_slice(),567 }568 .to_vec()569 .try_into()570 .unwrap(),571 });572 Self::set_scoped_collection_properties(573 id,574 PropertyScope::None,575 props.into_iter(),576 )577 .expect("existing data larger than properties");578 let mut new = CollectionVersion2::from(v.clone());579 new.permissions.access = Some(v.access);580 new.permissions.mint_mode = Some(v.mint_mode);581 Some(new)582 });583 }584585 0586 }587 }588}589590impl<T: Config> Pallet<T> {591 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens592 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {593 ensure!(594 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,595 <Error<T>>::AddressIsZero596 );597 Ok(())598 }599 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {600 <IsAdmin<T>>::iter_prefix((collection,))601 .map(|(a, _)| a)602 .collect()603 }604 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {605 <Allowlist<T>>::iter_prefix((collection,))606 .map(|(a, _)| a)607 .collect()608 }609 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {610 <Allowlist<T>>::get((collection, user))611 }612 pub fn collection_stats() -> CollectionStats {613 let created = <CreatedCollectionCount<T>>::get();614 let destroyed = <DestroyedCollectionCount<T>>::get();615 CollectionStats {616 created: created.0,617 destroyed: destroyed.0,618 alive: created.0 - destroyed.0,619 }620 }621622 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {623 let collection = <CollectionById<T>>::get(collection);624 if collection.is_none() {625 return None;626 }627628 let collection = collection.unwrap();629 let limits = collection.limits;630 let effective_limits = CollectionLimits {631 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),632 sponsored_data_size: Some(limits.sponsored_data_size()),633 sponsored_data_rate_limit: Some(634 limits635 .sponsored_data_rate_limit636 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),637 ),638 token_limit: Some(limits.token_limit()),639 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(640 match collection.mode {641 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,642 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,643 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,644 },645 )),646 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),647 owner_can_transfer: Some(limits.owner_can_transfer()),648 owner_can_destroy: Some(limits.owner_can_destroy()),649 transfers_enabled: Some(limits.transfers_enabled()),650 };651652 Some(effective_limits)653 }654655 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {656 let Collection {657 name,658 description,659 owner,660 mode,661 token_prefix,662 sponsorship,663 limits,664 permissions,665 } = <CollectionById<T>>::get(collection)?;666667 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)668 .into_iter()669 .map(|(key, permission)| PropertyKeyPermission { key, permission })670 .collect();671672 let properties = <CollectionProperties<T>>::get(collection)673 .into_iter()674 .map(|(key, value)| Property { key, value })675 .collect();676677 let permissions = CollectionPermissions {678 access: Some(permissions.access()),679 mint_mode: Some(permissions.mint_mode()),680 nesting: Some(permissions.nesting().clone()),681 };682683 Some(RpcCollection {684 name: name.into_inner(),685 description: description.into_inner(),686 owner,687 mode,688 token_prefix: token_prefix.into_inner(),689 sponsorship,690 limits,691 permissions,692 token_property_permissions,693 properties,694 })695 }696}697698macro_rules! limit_default {699 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{700 $(701 if let Some($new) = $new.$field {702 let $old = $old.$field($($arg)?);703 let _ = $new;704 let _ = $old;705 $check706 } else {707 $new.$field = $old.$field708 }709 )*710 }};711}712macro_rules! limit_default_clone {713 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{714 $(715 if let Some($new) = $new.$field.clone() {716 let $old = $old.$field($($arg)?);717 let _ = $new;718 let _ = $old;719 $check720 } else {721 $new.$field = $old.$field.clone()722 }723 )*724 }};725}726727impl<T: Config> Pallet<T> {728 pub fn init_collection(729 owner: T::CrossAccountId,730 data: CreateCollectionData<T::AccountId>,731 ) -> Result<CollectionId, DispatchError> {732 {733 ensure!(734 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,735 Error::<T>::CollectionTokenPrefixLimitExceeded736 );737 }738739 let created_count = <CreatedCollectionCount<T>>::get()740 .0741 .checked_add(1)742 .ok_or(ArithmeticError::Overflow)?;743 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;744 let id = CollectionId(created_count);745746 // bound Total number of collections747 ensure!(748 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,749 <Error<T>>::TotalCollectionsLimitExceeded750 );751752 // =========753754 let collection = Collection {755 owner: owner.as_sub().clone(),756 name: data.name,757 mode: data.mode.clone(),758 description: data.description,759 token_prefix: data.token_prefix,760 sponsorship: data761 .pending_sponsor762 .map(SponsorshipState::Unconfirmed)763 .unwrap_or_default(),764 limits: data765 .limits766 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))767 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,768 permissions: data769 .permissions770 .map(|permissions| {771 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)772 })773 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,774 };775776 let mut collection_properties = up_data_structs::CollectionProperties::get();777 collection_properties778 .try_set_from_iter(data.properties.into_iter())779 .map_err(<Error<T>>::from)?;780781 CollectionProperties::<T>::insert(id, collection_properties);782783 let mut token_props_permissions = PropertiesPermissionMap::new();784 token_props_permissions785 .try_set_from_iter(data.token_property_permissions.into_iter())786 .map_err(<Error<T>>::from)?;787788 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);789790 // Take a (non-refundable) deposit of collection creation791 {792 let mut imbalance =793 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();794 imbalance.subsume(795 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(796 &T::TreasuryAccountId::get(),797 T::CollectionCreationPrice::get(),798 ),799 );800 <T as Config>::Currency::settle(801 &owner.as_sub(),802 imbalance,803 WithdrawReasons::TRANSFER,804 ExistenceRequirement::KeepAlive,805 )806 .map_err(|_| Error::<T>::NotSufficientFounds)?;807 }808809 <CreatedCollectionCount<T>>::put(created_count);810 <Pallet<T>>::deposit_event(Event::CollectionCreated(811 id,812 data.mode.id(),813 owner.as_sub().clone(),814 ));815 <PalletEvm<T>>::deposit_log(816 erc::CollectionHelpersEvents::CollectionCreated {817 owner: *owner.as_eth(),818 collection_id: eth::collection_id_to_address(id),819 }820 .to_log(T::ContractAddress::get()),821 );822 <CollectionById<T>>::insert(id, collection);823 Ok(id)824 }825826 pub fn destroy_collection(827 collection: CollectionHandle<T>,828 sender: &T::CrossAccountId,829 ) -> DispatchResult {830 ensure!(831 collection.limits.owner_can_destroy(),832 <Error<T>>::NoPermission,833 );834 collection.check_is_owner(sender)?;835836 let destroyed_collections = <DestroyedCollectionCount<T>>::get()837 .0838 .checked_add(1)839 .ok_or(ArithmeticError::Overflow)?;840841 // =========842843 <DestroyedCollectionCount<T>>::put(destroyed_collections);844 <CollectionById<T>>::remove(collection.id);845 <AdminAmount<T>>::remove(collection.id);846 <IsAdmin<T>>::remove_prefix((collection.id,), None);847 <Allowlist<T>>::remove_prefix((collection.id,), None);848 <CollectionProperties<T>>::remove(collection.id);849850 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));851 Ok(())852 }853854 pub fn set_collection_property(855 collection: &CollectionHandle<T>,856 sender: &T::CrossAccountId,857 property: Property,858 ) -> DispatchResult {859 collection.check_is_owner_or_admin(sender)?;860861 CollectionProperties::<T>::try_mutate(collection.id, |properties| {862 let property = property.clone();863 properties.try_set(property.key, property.value)864 })865 .map_err(<Error<T>>::from)?;866867 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));868869 Ok(())870 }871872 pub fn set_scoped_collection_property(873 collection_id: CollectionId,874 scope: PropertyScope,875 property: Property,876 ) -> DispatchResult {877 CollectionProperties::<T>::try_mutate(collection_id, |properties| {878 properties.try_scoped_set(scope, property.key, property.value)879 })880 .map_err(<Error<T>>::from)?;881882 Ok(())883 }884885 pub fn set_scoped_collection_properties(886 collection_id: CollectionId,887 scope: PropertyScope,888 properties: impl Iterator<Item = Property>,889 ) -> DispatchResult {890 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {891 stored_properties.try_scoped_set_from_iter(scope, properties)892 })893 .map_err(<Error<T>>::from)?;894895 Ok(())896 }897898 #[transactional]899 pub fn set_collection_properties(900 collection: &CollectionHandle<T>,901 sender: &T::CrossAccountId,902 properties: Vec<Property>,903 ) -> DispatchResult {904 for property in properties {905 Self::set_collection_property(collection, sender, property)?;906 }907908 Ok(())909 }910911 pub fn delete_collection_property(912 collection: &CollectionHandle<T>,913 sender: &T::CrossAccountId,914 property_key: PropertyKey,915 ) -> DispatchResult {916 collection.check_is_owner_or_admin(sender)?;917918 CollectionProperties::<T>::try_mutate(collection.id, |properties| {919 properties.remove(&property_key)920 })921 .map_err(<Error<T>>::from)?;922923 Self::deposit_event(Event::CollectionPropertyDeleted(924 collection.id,925 property_key,926 ));927928 Ok(())929 }930931 #[transactional]932 pub fn delete_collection_properties(933 collection: &CollectionHandle<T>,934 sender: &T::CrossAccountId,935 property_keys: Vec<PropertyKey>,936 ) -> DispatchResult {937 for key in property_keys {938 Self::delete_collection_property(collection, sender, key)?;939 }940941 Ok(())942 }943944 // For migrations945 pub fn set_property_permission_unchecked(946 collection: CollectionId,947 property_permission: PropertyKeyPermission,948 ) -> DispatchResult {949 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {950 permissions.try_set(property_permission.key, property_permission.permission)951 })952 .map_err(<Error<T>>::from)?;953 Ok(())954 }955956 pub fn set_property_permission(957 collection: &CollectionHandle<T>,958 sender: &T::CrossAccountId,959 property_permission: PropertyKeyPermission,960 ) -> DispatchResult {961 collection.check_is_owner_or_admin(sender)?;962963 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);964 let current_permission = all_permissions.get(&property_permission.key);965 if matches![966 current_permission,967 Some(PropertyPermission { mutable: false, .. })968 ] {969 return Err(<Error<T>>::NoPermission.into());970 }971972 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {973 let property_permission = property_permission.clone();974 permissions.try_set(property_permission.key, property_permission.permission)975 })976 .map_err(<Error<T>>::from)?;977978 Self::deposit_event(Event::PropertyPermissionSet(979 collection.id,980 property_permission.key,981 ));982983 Ok(())984 }985986 #[transactional]987 pub fn set_property_permissions(988 collection: &CollectionHandle<T>,989 sender: &T::CrossAccountId,990 property_permissions: Vec<PropertyKeyPermission>,991 ) -> DispatchResult {992 for prop_pemission in property_permissions {993 Self::set_property_permission(collection, sender, prop_pemission)?;994 }995996 Ok(())997 }998999 pub fn get_collection_property(1000 collection_id: CollectionId,1001 key: &PropertyKey,1002 ) -> Option<PropertyValue> {1003 Self::collection_properties(collection_id).get(key).cloned()1004 }10051006 pub fn bytes_keys_to_property_keys(1007 keys: Vec<Vec<u8>>,1008 ) -> Result<Vec<PropertyKey>, DispatchError> {1009 keys.into_iter()1010 .map(|key| -> Result<PropertyKey, DispatchError> {1011 key.try_into()1012 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1013 })1014 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1015 }10161017 pub fn filter_collection_properties(1018 collection_id: CollectionId,1019 keys: Option<Vec<PropertyKey>>,1020 ) -> Result<Vec<Property>, DispatchError> {1021 let properties = Self::collection_properties(collection_id);10221023 let properties = keys1024 .map(|keys| {1025 keys.into_iter()1026 .filter_map(|key| {1027 properties.get(&key).map(|value| Property {1028 key,1029 value: value.clone(),1030 })1031 })1032 .collect()1033 })1034 .unwrap_or_else(|| {1035 properties1036 .into_iter()1037 .map(|(key, value)| Property { key, value })1038 .collect()1039 });10401041 Ok(properties)1042 }10431044 pub fn filter_property_permissions(1045 collection_id: CollectionId,1046 keys: Option<Vec<PropertyKey>>,1047 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1048 let permissions = Self::property_permissions(collection_id);10491050 let key_permissions = keys1051 .map(|keys| {1052 keys.into_iter()1053 .filter_map(|key| {1054 permissions1055 .get(&key)1056 .map(|permission| PropertyKeyPermission {1057 key,1058 permission: permission.clone(),1059 })1060 })1061 .collect()1062 })1063 .unwrap_or_else(|| {1064 permissions1065 .into_iter()1066 .map(|(key, permission)| PropertyKeyPermission { key, permission })1067 .collect()1068 });10691070 Ok(key_permissions)1071 }10721073 pub fn toggle_allowlist(1074 collection: &CollectionHandle<T>,1075 sender: &T::CrossAccountId,1076 user: &T::CrossAccountId,1077 allowed: bool,1078 ) -> DispatchResult {1079 collection.check_is_owner_or_admin(sender)?;10801081 // =========10821083 if allowed {1084 <Allowlist<T>>::insert((collection.id, user), true);1085 } else {1086 <Allowlist<T>>::remove((collection.id, user));1087 }10881089 Ok(())1090 }10911092 pub fn toggle_admin(1093 collection: &CollectionHandle<T>,1094 sender: &T::CrossAccountId,1095 user: &T::CrossAccountId,1096 admin: bool,1097 ) -> DispatchResult {1098 collection.check_is_owner_or_admin(sender)?;10991100 let was_admin = <IsAdmin<T>>::get((collection.id, user));1101 if was_admin == admin {1102 return Ok(());1103 }1104 let amount = <AdminAmount<T>>::get(collection.id);11051106 if admin {1107 let amount = amount1108 .checked_add(1)1109 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1110 ensure!(1111 amount <= Self::collection_admins_limit(),1112 <Error<T>>::CollectionAdminCountExceeded,1113 );11141115 // =========11161117 <AdminAmount<T>>::insert(collection.id, amount);1118 <IsAdmin<T>>::insert((collection.id, user), true);1119 } else {1120 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1121 <IsAdmin<T>>::remove((collection.id, user));1122 }11231124 Ok(())1125 }11261127 pub fn clamp_limits(1128 mode: CollectionMode,1129 old_limit: &CollectionLimits,1130 mut new_limit: CollectionLimits,1131 ) -> Result<CollectionLimits, DispatchError> {1132 limit_default!(old_limit, new_limit,1133 account_token_ownership_limit => ensure!(1134 new_limit <= MAX_TOKEN_OWNERSHIP,1135 <Error<T>>::CollectionLimitBoundsExceeded,1136 ),1137 sponsored_data_size => ensure!(1138 new_limit <= CUSTOM_DATA_LIMIT,1139 <Error<T>>::CollectionLimitBoundsExceeded,1140 ),11411142 sponsored_data_rate_limit => {},1143 token_limit => ensure!(1144 old_limit >= new_limit && new_limit > 0,1145 <Error<T>>::CollectionTokenLimitExceeded1146 ),11471148 sponsor_transfer_timeout(match mode {1149 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1150 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1151 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1152 }) => ensure!(1153 new_limit <= MAX_SPONSOR_TIMEOUT,1154 <Error<T>>::CollectionLimitBoundsExceeded,1155 ),1156 sponsor_approve_timeout => {},1157 owner_can_transfer => ensure!(1158 old_limit || !new_limit,1159 <Error<T>>::OwnerPermissionsCantBeReverted,1160 ),1161 owner_can_destroy => ensure!(1162 old_limit || !new_limit,1163 <Error<T>>::OwnerPermissionsCantBeReverted,1164 ),1165 transfers_enabled => {},1166 );1167 Ok(new_limit)1168 }1169 pub fn clamp_permissions(1170 mode: CollectionMode,1171 old_limit: &CollectionPermissions,1172 mut new_limit: CollectionPermissions,1173 ) -> Result<CollectionPermissions, DispatchError> {1174 limit_default_clone!(old_limit, new_limit,1175 access => {},1176 mint_mode => {},1177 nesting => {},1178 );1179 Ok(new_limit)1180 }1181}11821183#[macro_export]1184macro_rules! unsupported {1185 () => {1186 Err(<Error<T>>::UnsupportedOperation.into())1187 };1188}11891190/// Worst cases1191pub trait CommonWeightInfo<CrossAccountId> {1192 fn create_item() -> Weight;1193 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;1194 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;1195 fn burn_item() -> Weight;1196 fn set_collection_properties(amount: u32) -> Weight;1197 fn delete_collection_properties(amount: u32) -> Weight;1198 fn set_token_properties(amount: u32) -> Weight;1199 fn delete_token_properties(amount: u32) -> Weight;1200 fn set_property_permissions(amount: u32) -> Weight;1201 fn transfer() -> Weight;1202 fn approve() -> Weight;1203 fn transfer_from() -> Weight;1204 fn burn_from() -> Weight;1205}12061207pub trait CommonCollectionOperations<T: Config> {1208 fn create_item(1209 &self,1210 sender: T::CrossAccountId,1211 to: T::CrossAccountId,1212 data: CreateItemData,1213 nesting_budget: &dyn Budget,1214 ) -> DispatchResultWithPostInfo;1215 fn create_multiple_items(1216 &self,1217 sender: T::CrossAccountId,1218 to: T::CrossAccountId,1219 data: Vec<CreateItemData>,1220 nesting_budget: &dyn Budget,1221 ) -> DispatchResultWithPostInfo;1222 fn create_multiple_items_ex(1223 &self,1224 sender: T::CrossAccountId,1225 data: CreateItemExData<T::CrossAccountId>,1226 nesting_budget: &dyn Budget,1227 ) -> DispatchResultWithPostInfo;1228 fn burn_item(1229 &self,1230 sender: T::CrossAccountId,1231 token: TokenId,1232 amount: u128,1233 ) -> DispatchResultWithPostInfo;1234 fn set_collection_properties(1235 &self,1236 sender: T::CrossAccountId,1237 properties: Vec<Property>,1238 ) -> DispatchResultWithPostInfo;1239 fn delete_collection_properties(1240 &self,1241 sender: &T::CrossAccountId,1242 property_keys: Vec<PropertyKey>,1243 ) -> DispatchResultWithPostInfo;1244 fn set_token_properties(1245 &self,1246 sender: T::CrossAccountId,1247 token_id: TokenId,1248 property: Vec<Property>,1249 ) -> DispatchResultWithPostInfo;1250 fn delete_token_properties(1251 &self,1252 sender: T::CrossAccountId,1253 token_id: TokenId,1254 property_keys: Vec<PropertyKey>,1255 ) -> DispatchResultWithPostInfo;1256 fn set_property_permissions(1257 &self,1258 sender: &T::CrossAccountId,1259 property_permissions: Vec<PropertyKeyPermission>,1260 ) -> DispatchResultWithPostInfo;1261 fn transfer(1262 &self,1263 sender: T::CrossAccountId,1264 to: T::CrossAccountId,1265 token: TokenId,1266 amount: u128,1267 nesting_budget: &dyn Budget,1268 ) -> DispatchResultWithPostInfo;1269 fn approve(1270 &self,1271 sender: T::CrossAccountId,1272 spender: T::CrossAccountId,1273 token: TokenId,1274 amount: u128,1275 ) -> DispatchResultWithPostInfo;1276 fn transfer_from(1277 &self,1278 sender: T::CrossAccountId,1279 from: T::CrossAccountId,1280 to: T::CrossAccountId,1281 token: TokenId,1282 amount: u128,1283 nesting_budget: &dyn Budget,1284 ) -> DispatchResultWithPostInfo;1285 fn burn_from(1286 &self,1287 sender: T::CrossAccountId,1288 from: T::CrossAccountId,1289 token: TokenId,1290 amount: u128,1291 nesting_budget: &dyn Budget,1292 ) -> DispatchResultWithPostInfo;12931294 fn check_nesting(1295 &self,1296 sender: T::CrossAccountId,1297 from: (CollectionId, TokenId),1298 under: TokenId,1299 budget: &dyn Budget,1300 ) -> DispatchResult;13011302 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));13031304 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));13051306 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;1307 fn collection_tokens(&self) -> Vec<TokenId>;1308 fn token_exists(&self, token: TokenId) -> bool;1309 fn last_token_id(&self) -> TokenId;13101311 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;1312 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;1313 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;1314 /// Amount of unique collection tokens1315 fn total_supply(&self) -> u32;1316 /// Amount of different tokens account has (Applicable to nonfungible/refungible)1317 fn account_balance(&self, account: T::CrossAccountId) -> u32;1318 /// Amount of specific token account have (Applicable to fungible/refungible)1319 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;1320 fn allowance(1321 &self,1322 sender: T::CrossAccountId,1323 spender: T::CrossAccountId,1324 token: TokenId,1325 ) -> u128;1326}13271328// Flexible enough for implementing CommonCollectionOperations1329pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1330 let post_info = PostDispatchInfo {1331 actual_weight: Some(weight),1332 pays_fee: Pays::Yes,1333 };1334 match res {1335 Ok(()) => Ok(post_info),1336 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1337 }1338}13391340impl<T: Config> From<PropertiesError> for Error<T> {1341 fn from(error: PropertiesError) -> Self {1342 match error {1343 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1344 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1345 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1346 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1347 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1348 }1349 }1350}pallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -66,9 +66,7 @@
}
#[pallet::config]
- pub trait Config: frame_system::Config {
- type GasWeightMapping: pallet_evm::GasWeightMapping;
- }
+ pub trait Config: frame_system::Config + pallet_evm::Config {}
#[pallet::pallet]
pub struct Pallet<T>(_);
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -134,7 +134,7 @@
impl<T: Config> Pallet<T> {
pub fn init_collection(
- owner: T::AccountId,
+ owner: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
) -> Result<CollectionId, DispatchError> {
<PalletCommon<T>>::init_collection(owner, data)
pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -127,7 +127,7 @@
}
}
-// Selector: f5652829
+// Selector: c894dc35
contract Collection is Dummy, ERC165 {
// Selector: setCollectionProperty(string,bytes) 2f073f66
function setCollectionProperty(string memory key, bytes memory value)
@@ -173,8 +173,16 @@
dummy = 0;
}
- // Selector: setLimit(string,string) bf4d2014
- function setLimit(string memory limit, string memory value) public {
+ // Selector: setLimit(string,uint32) 68db30ca
+ function setLimit(string memory limit, uint32 value) public {
+ require(false, stub_error);
+ limit;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: setLimit(string,bool) ea67e4c2
+ function setLimit(string memory limit, bool value) public {
require(false, stub_error);
limit;
value;
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -295,7 +295,7 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
pub fn init_collection(
- owner: T::AccountId,
+ owner: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
) -> Result<CollectionId, DispatchError> {
<PalletCommon<T>>::init_collection(owner, data)
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -330,57 +330,7 @@
}
}
-// Selector: d74d154f
-contract ERC721UniqueExtensions is Dummy, ERC165 {
- // Selector: transfer(address,uint256) a9059cbb
- function transfer(address to, uint256 tokenId) public {
- require(false, stub_error);
- to;
- tokenId;
- dummy = 0;
- }
-
- // Selector: burnFrom(address,uint256) 79cc6790
- function burnFrom(address from, uint256 tokenId) public {
- require(false, stub_error);
- from;
- tokenId;
- dummy = 0;
- }
-
- // Selector: nextTokenId() 75794a3c
- function nextTokenId() public view returns (uint256) {
- require(false, stub_error);
- dummy;
- return 0;
- }
-
- // Selector: mintBulk(address,uint256[]) 44a9945e
- function mintBulk(address to, uint256[] memory tokenIds)
- public
- returns (bool)
- {
- require(false, stub_error);
- to;
- tokenIds;
- dummy = 0;
- return false;
- }
-
- // Selector: mintBulkWithTokenURI(address,(uint256,string)[]) 36543006
- function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
- public
- returns (bool)
- {
- require(false, stub_error);
- to;
- tokens;
- dummy = 0;
- return false;
- }
-}
-
-// Selector: f5652829
+// Selector: c894dc35
contract Collection is Dummy, ERC165 {
// Selector: setCollectionProperty(string,bytes) 2f073f66
function setCollectionProperty(string memory key, bytes memory value)
@@ -426,8 +376,16 @@
dummy = 0;
}
- // Selector: setLimit(string,string) bf4d2014
- function setLimit(string memory limit, string memory value) public {
+ // Selector: setLimit(string,uint32) 68db30ca
+ function setLimit(string memory limit, uint32 value) public {
+ require(false, stub_error);
+ limit;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: setLimit(string,bool) ea67e4c2
+ function setLimit(string memory limit, bool value) public {
require(false, stub_error);
limit;
value;
@@ -442,6 +400,56 @@
}
}
+// Selector: d74d154f
+contract ERC721UniqueExtensions is Dummy, ERC165 {
+ // Selector: transfer(address,uint256) a9059cbb
+ function transfer(address to, uint256 tokenId) public {
+ require(false, stub_error);
+ to;
+ tokenId;
+ dummy = 0;
+ }
+
+ // Selector: burnFrom(address,uint256) 79cc6790
+ function burnFrom(address from, uint256 tokenId) public {
+ require(false, stub_error);
+ from;
+ tokenId;
+ dummy = 0;
+ }
+
+ // Selector: nextTokenId() 75794a3c
+ function nextTokenId() public view returns (uint256) {
+ require(false, stub_error);
+ dummy;
+ return 0;
+ }
+
+ // Selector: mintBulk(address,uint256[]) 44a9945e
+ function mintBulk(address to, uint256[] memory tokenIds)
+ public
+ returns (bool)
+ {
+ require(false, stub_error);
+ to;
+ tokenIds;
+ dummy = 0;
+ return false;
+ }
+
+ // Selector: mintBulkWithTokenURI(address,(uint256,string)[]) 36543006
+ function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
+ public
+ returns (bool)
+ {
+ require(false, stub_error);
+ to;
+ tokens;
+ dummy = 0;
+ return false;
+ }
+}
+
contract UniqueNFT is
Dummy,
ERC165,
pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -139,7 +139,8 @@
..Default::default()
};
- let collection_id_res = <PalletNft<T>>::init_collection(sender.clone(), data);
+ let collection_id_res =
+ <PalletNft<T>>::init_collection(T::CrossAccountId::from_sub(sender.clone()), data);
if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
return Err(<Error<T>>::NoAvailableCollectionId.into());
pallets/proxy-rmrk-equip/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-equip/src/lib.rs
+++ b/pallets/proxy-rmrk-equip/src/lib.rs
@@ -94,7 +94,7 @@
..Default::default()
};
- let collection_id_res = <PalletNft<T>>::init_collection(sender.clone(), data);
+ let collection_id_res = <PalletNft<T>>::init_collection(cross_sender.clone(), data);
if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
return Err(<Error<T>>::NoAvailableBaseId.into());
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -197,7 +197,7 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
pub fn init_collection(
- owner: T::AccountId,
+ owner: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
) -> Result<CollectionId, DispatchError> {
<PalletCommon<T>>::init_collection(owner, data)
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -24,14 +24,17 @@
MAX_COLLECTION_NAME_LENGTH,
};
use frame_support::traits::Get;
-use pallet_common::{CollectionById, erc::token_uri_key};
+use pallet_common::{
+ CollectionById,
+ erc::{token_uri_key, CollectionHelpersEvents},
+};
use crate::{SelfWeightOf, Config, weights::WeightInfo};
use sp_std::vec::Vec;
use alloc::format;
-struct EvmCollectionHelper<T: Config>(SubstrateRecorder<T>);
-impl<T: Config> WithRecorder<T> for EvmCollectionHelper<T> {
+struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);
+impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {
fn recorder(&self) -> &SubstrateRecorder<T> {
&self.0
}
@@ -41,8 +44,8 @@
}
}
-#[solidity_interface(name = "CollectionHelper")]
-impl<T: Config + pallet_nonfungible::Config> EvmCollectionHelper<T> {
+#[solidity_interface(name = "CollectionHelpers", events(CollectionHelpersEvents))]
+impl<T: Config + pallet_nonfungible::Config> EvmCollectionHelpers<T> {
#[weight(<SelfWeightOf<T>>::create_collection())]
fn create_nonfungible_collection(
&self,
@@ -89,9 +92,8 @@
..Default::default()
};
- let collection_id =
- <pallet_nonfungible::Pallet<T>>::init_collection(caller.as_sub().clone(), data)
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ let collection_id = <pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data)
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
@@ -107,8 +109,8 @@
}
}
-pub struct CollectionHelperOnMethodCall<T: Config>(PhantomData<*const T>);
-impl<T: Config + pallet_nonfungible::Config> OnMethodCall<T> for CollectionHelperOnMethodCall<T> {
+pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);
+impl<T: Config + pallet_nonfungible::Config> OnMethodCall<T> for CollectionHelpersOnMethodCall<T> {
fn is_reserved(contract: &sp_core::H160) -> bool {
contract == &T::ContractAddress::get()
}
@@ -128,18 +130,18 @@
return None;
}
- let helpers = EvmCollectionHelper::<T>(SubstrateRecorder::<T>::new(gas_left));
+ let helpers = EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(gas_left));
pallet_evm_coder_substrate::call(*source, helpers, value, input)
}
fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {
(contract == &T::ContractAddress::get())
- .then(|| include_bytes!("./stubs/CollectionHelper.raw").to_vec())
+ .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())
}
}
-generate_stubgen!(collection_helper_impl, CollectionHelperCall<()>, true);
-generate_stubgen!(collection_helper_iface, CollectionHelperCall<()>, false);
+generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);
+generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);
fn error_feild_too_long(feild: &str, bound: u32) -> Error {
Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))
pallets/unique/src/eth/stubs/CollectionHelper.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelper.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/CollectionHelper.sol
+++ /dev/null
@@ -1,51 +0,0 @@
-// SPDX-License-Identifier: OTHER
-// This code is automatically generated
-
-pragma solidity >=0.8.0 <0.9.0;
-
-// Common stubs holder
-contract Dummy {
- uint8 dummy;
- string stub_error = "this contract is implemented in native";
-}
-
-contract ERC165 is Dummy {
- function supportsInterface(bytes4 interfaceID)
- external
- view
- returns (bool)
- {
- require(false, stub_error);
- interfaceID;
- return true;
- }
-}
-
-// Selector: 56c215c5
-contract CollectionHelper is Dummy, ERC165 {
- // Selector: create721Collection(string,string,string) 951c0151
- function create721Collection(
- string memory name,
- string memory description,
- string memory tokenPrefix
- ) public view returns (address) {
- require(false, stub_error);
- name;
- description;
- tokenPrefix;
- dummy;
- return 0x0000000000000000000000000000000000000000;
- }
-
- // Selector: isCollectionExist(address) c3de1494
- function isCollectionExist(address collectionAddress)
- public
- view
- returns (bool)
- {
- require(false, stub_error);
- collectionAddress;
- dummy;
- return false;
- }
-}
pallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth--- /dev/null
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+// Common stubs holder
+contract Dummy {
+ uint8 dummy;
+ string stub_error = "this contract is implemented in native";
+}
+
+contract ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID)
+ external
+ view
+ returns (bool)
+ {
+ require(false, stub_error);
+ interfaceID;
+ return true;
+ }
+}
+
+// Inline
+contract CollectionHelpersEvents {
+ event CollectionCreated(
+ address indexed owner,
+ address indexed collectionId
+ );
+}
+
+// Selector: 20947cd0
+contract CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
+ // Selector: createNonfungibleCollection(string,string,string) e34a6844
+ function createNonfungibleCollection(
+ string memory name,
+ string memory description,
+ string memory tokenPrefix
+ ) public view returns (address) {
+ require(false, stub_error);
+ name;
+ description;
+ tokenPrefix;
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+
+ // Selector: isCollectionExist(address) c3de1494
+ function isCollectionExist(address collectionAddress)
+ public
+ view
+ returns (bool)
+ {
+ require(false, stub_error);
+ collectionAddress;
+ dummy;
+ return false;
+ }
+}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -30,10 +30,9 @@
ensure,
weights::{Weight},
transactional,
- pallet_prelude::{DispatchResultWithPostInfo, ConstU32, Get},
+ pallet_prelude::{DispatchResultWithPostInfo, ConstU32},
BoundedVec,
};
-use sp_core::H160;
use scale_info::TypeInfo;
use frame_system::{self as system, ensure_signed};
use sp_runtime::{sp_std::prelude::Vec};
@@ -75,7 +74,6 @@
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
type CommonWeightInfo: CommonWeightInfo<Self::CrossAccountId>;
- type ContractAddress: Get<H160>;
}
decl_event! {
@@ -287,7 +285,7 @@
// =========
- T::CollectionDispatch::create(sender, data)?;
+ T::CollectionDispatch::create(T::CrossAccountId::from_sub(sender), data)?;
Ok(())
}
runtime/common/src/dispatch.rsdiffbeforeafterboth--- a/runtime/common/src/dispatch.rs
+++ b/runtime/common/src/dispatch.rs
@@ -30,7 +30,10 @@
+ pallet_nonfungible::Config
+ pallet_refungible::Config,
{
- fn create(sender: T::AccountId, data: CreateCollectionData<T::AccountId>) -> DispatchResult {
+ fn create(
+ sender: T::CrossAccountId,
+ data: CreateCollectionData<T::AccountId>,
+ ) -> DispatchResult {
let _id = match data.mode {
CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, data)?,
CollectionMode::Fungible(decimal_points) => {
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -306,7 +306,7 @@
pallet_evm_migration::OnMethodCall<Self>,
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
- pallet_unique::eth::CollectionHelperOnMethodCall<Self>,
+ pallet_unique::eth::CollectionHelpersOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
type ChainId = ChainId;
@@ -821,9 +821,7 @@
XcmpQueue,
);
-impl pallet_evm_coder_substrate::Config for Runtime {
- type GasWeightMapping = FixedGasWeightMapping;
-}
+impl pallet_evm_coder_substrate::Config for Runtime {}
impl pallet_xcm::Config for Runtime {
type Event = Event;
@@ -885,6 +883,7 @@
type EvmTokenAddressMapping = EvmTokenAddressMapping;
type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;
+ type ContractAddress = EvmCollectionHelpersAddress;
}
impl pallet_structure::Config for Runtime {
@@ -917,7 +916,6 @@
type Event = Event;
type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;
type CommonWeightInfo = CommonWeights<Self>;
- type ContractAddress = EvmCollectionHelperAddress;
}
parameter_types! {
@@ -980,7 +978,7 @@
]);
// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
- pub const EvmCollectionHelperAddress: H160 = H160([
+ pub const EvmCollectionHelpersAddress: H160 = H160([
0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
]);
}
runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -285,7 +285,7 @@
pallet_evm_migration::OnMethodCall<Self>,
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
- pallet_unique::eth::CollectionHelperOnMethodCall<Self>,
+ pallet_unique::eth::CollectionHelpersOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
type ChainId = ChainId;
@@ -800,9 +800,7 @@
XcmpQueue,
);
-impl pallet_evm_coder_substrate::Config for Runtime {
- type GasWeightMapping = FixedGasWeightMapping;
-}
+impl pallet_evm_coder_substrate::Config for Runtime {}
impl pallet_xcm::Config for Runtime {
type Event = Event;
@@ -864,6 +862,7 @@
type EvmTokenAddressMapping = EvmTokenAddressMapping;
type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;
+ type ContractAddress = EvmCollectionHelpersAddress;
}
impl pallet_structure::Config for Runtime {
@@ -900,7 +899,6 @@
type Event = Event;
type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;
type CommonWeightInfo = CommonWeights<Self>;
- type ContractAddress = EvmCollectionHelperAddress;
}
parameter_types! {
@@ -963,7 +961,7 @@
]);
// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
- pub const EvmCollectionHelperAddress: H160 = H160([
+ pub const EvmCollectionHelpersAddress: H160 = H160([
0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
]);
}
runtime/tests/src/lib.rsdiffbeforeafterboth--- a/runtime/tests/src/lib.rs
+++ b/runtime/tests/src/lib.rs
@@ -208,9 +208,7 @@
type BlockHashMapping = SubstrateBlockHashMapping<Self>;
type TransactionValidityHack = ();
}
-impl pallet_evm_coder_substrate::Config for Test {
- type GasWeightMapping = ();
-}
+impl pallet_evm_coder_substrate::Config for Test {}
impl pallet_common::Config for Test {
type WeightInfo = ();
@@ -222,6 +220,7 @@
type CollectionDispatch = CollectionDispatchT<Self>;
type EvmTokenAddressMapping = EvmTokenAddressMapping;
type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;
+ type ContractAddress = EvmCollectionHelpersAddress;
}
impl pallet_evm::account::Config for Test {
@@ -247,7 +246,7 @@
parameter_types! {
// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
- pub const EvmCollectionHelperAddress: H160 = H160([
+ pub const EvmCollectionHelpersAddress: H160 = H160([
0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
]);
}
@@ -256,7 +255,6 @@
type Event = ();
type WeightInfo = ();
type CommonWeightInfo = CommonWeights<Self>;
- type ContractAddress = EvmCollectionHelperAddress;
}
// Build genesis storage according to the mock runtime.
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -290,7 +290,7 @@
pallet_evm_migration::OnMethodCall<Self>,
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
- pallet_unique::eth::CollectionHelperOnMethodCall<Self>,
+ pallet_unique::eth::CollectionHelpersOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
type ChainId = ChainId;
@@ -805,9 +805,7 @@
XcmpQueue,
);
-impl pallet_evm_coder_substrate::Config for Runtime {
- type GasWeightMapping = FixedGasWeightMapping;
-}
+impl pallet_evm_coder_substrate::Config for Runtime {}
impl pallet_xcm::Config for Runtime {
type Event = Event;
@@ -869,6 +867,7 @@
type EvmTokenAddressMapping = EvmTokenAddressMapping;
type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;
+ type ContractAddress = EvmCollectionHelpersAddress;
}
impl pallet_structure::Config for Runtime {
@@ -905,7 +904,6 @@
type Event = Event;
type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;
type CommonWeightInfo = CommonWeights<Self>;
- type ContractAddress = EvmCollectionHelperAddress;
}
parameter_types! {
@@ -968,7 +966,7 @@
]);
// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
- pub const EvmCollectionHelperAddress: H160 = H160([
+ pub const EvmCollectionHelpersAddress: H160 = H160([
0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
]);
}
tests/src/eth/api/CollectionHelper.soldiffbeforeafterboth--- a/tests/src/eth/api/CollectionHelper.sol
+++ /dev/null
@@ -1,29 +0,0 @@
-// SPDX-License-Identifier: OTHER
-// This code is automatically generated
-
-pragma solidity >=0.8.0 <0.9.0;
-
-// Common stubs holder
-interface Dummy {
-
-}
-
-interface ERC165 is Dummy {
- function supportsInterface(bytes4 interfaceID) external view returns (bool);
-}
-
-// Selector: 56c215c5
-interface CollectionHelper is Dummy, ERC165 {
- // Selector: create721Collection(string,string,string) 951c0151
- function create721Collection(
- string memory name,
- string memory description,
- string memory tokenPrefix
- ) external view returns (address);
-
- // Selector: isCollectionExist(address) c3de1494
- function isCollectionExist(address collectionAddress)
- external
- view
- returns (bool);
-}
tests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+// Common stubs holder
+interface Dummy {
+
+}
+
+interface ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID) external view returns (bool);
+}
+
+// Inline
+interface CollectionHelpersEvents {
+ event CollectionCreated(
+ address indexed owner,
+ address indexed collectionId
+ );
+}
+
+// Selector: 20947cd0
+interface CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
+ // Selector: createNonfungibleCollection(string,string,string) e34a6844
+ function createNonfungibleCollection(
+ string memory name,
+ string memory description,
+ string memory tokenPrefix
+ ) external view returns (address);
+
+ // Selector: isCollectionExist(address) c3de1494
+ function isCollectionExist(address collectionAddress)
+ external
+ view
+ returns (bool);
+}
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -65,7 +65,7 @@
returns (uint256);
}
-// Selector: f5652829
+// Selector: c894dc35
interface Collection is Dummy, ERC165 {
// Selector: setCollectionProperty(string,bytes) 2f073f66
function setCollectionProperty(string memory key, bytes memory value)
@@ -88,8 +88,11 @@
// Selector: ethConfirmSponsorship() a8580d1a
function ethConfirmSponsorship() external;
- // Selector: setLimit(string,string) bf4d2014
- function setLimit(string memory limit, string memory value) external;
+ // Selector: setLimit(string,uint32) 68db30ca
+ function setLimit(string memory limit, uint32 value) external;
+
+ // Selector: setLimit(string,bool) ea67e4c2
+ function setLimit(string memory limit, bool value) external;
// Selector: contractAddress() f6b4dfb4
function contractAddress() external view returns (address);
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -191,29 +191,7 @@
function totalSupply() external view returns (uint256);
}
-// Selector: d74d154f
-interface ERC721UniqueExtensions is Dummy, ERC165 {
- // Selector: transfer(address,uint256) a9059cbb
- function transfer(address to, uint256 tokenId) external;
-
- // Selector: burnFrom(address,uint256) 79cc6790
- function burnFrom(address from, uint256 tokenId) external;
-
- // Selector: nextTokenId() 75794a3c
- function nextTokenId() external view returns (uint256);
-
- // Selector: mintBulk(address,uint256[]) 44a9945e
- function mintBulk(address to, uint256[] memory tokenIds)
- external
- returns (bool);
-
- // Selector: mintBulkWithTokenURI(address,(uint256,string)[]) 36543006
- function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
- external
- returns (bool);
-}
-
-// Selector: f5652829
+// Selector: c894dc35
interface Collection is Dummy, ERC165 {
// Selector: setCollectionProperty(string,bytes) 2f073f66
function setCollectionProperty(string memory key, bytes memory value)
@@ -236,13 +214,38 @@
// Selector: ethConfirmSponsorship() a8580d1a
function ethConfirmSponsorship() external;
- // Selector: setLimit(string,string) bf4d2014
- function setLimit(string memory limit, string memory value) external;
+ // Selector: setLimit(string,uint32) 68db30ca
+ function setLimit(string memory limit, uint32 value) external;
+
+ // Selector: setLimit(string,bool) ea67e4c2
+ function setLimit(string memory limit, bool value) external;
// Selector: contractAddress() f6b4dfb4
function contractAddress() external view returns (address);
}
+// Selector: d74d154f
+interface ERC721UniqueExtensions is Dummy, ERC165 {
+ // Selector: transfer(address,uint256) a9059cbb
+ function transfer(address to, uint256 tokenId) external;
+
+ // Selector: burnFrom(address,uint256) 79cc6790
+ function burnFrom(address from, uint256 tokenId) external;
+
+ // Selector: nextTokenId() 75794a3c
+ function nextTokenId() external view returns (uint256);
+
+ // Selector: mintBulk(address,uint256[]) 44a9945e
+ function mintBulk(address to, uint256[] memory tokenIds)
+ external
+ returns (bool);
+
+ // Selector: mintBulkWithTokenURI(address,(uint256,string)[]) 36543006
+ function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
+ external
+ returns (bool);
+}
+
interface UniqueNFT is
Dummy,
ERC165,
tests/src/eth/collectionHelperAbi.jsondiffbeforeafterboth--- a/tests/src/eth/collectionHelperAbi.json
+++ /dev/null
@@ -1,35 +0,0 @@
-[
- {
- "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": "collectionAddress",
- "type": "address"
- }
- ],
- "name": "isCollectionExist",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
- ],
- "name": "supportsInterface",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
- "stateMutability": "view",
- "type": "function"
- }
-]
tests/src/eth/collectionHelpersAbi.jsondiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/collectionHelpersAbi.json
@@ -0,0 +1,54 @@
+[
+ {
+ "anonymous": false,
+ "inputs": [
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "owner",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "collectionId",
+ "type": "address"
+ }
+ ],
+ "name": "CollectionCreated",
+ "type": "event"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "name", "type": "string" },
+ { "internalType": "string", "name": "description", "type": "string" },
+ { "internalType": "string", "name": "tokenPrefix", "type": "string" }
+ ],
+ "name": "createNonfungibleCollection",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "collectionAddress",
+ "type": "address"
+ }
+ ],
+ "name": "isCollectionExist",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
+ ],
+ "name": "supportsInterface",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ }
+]
tests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -29,7 +29,7 @@
normalizeEvents,
subToEth,
executeEthTxOnSub,
- evmCollectionHelper,
+ evmCollectionHelpers,
getCollectionAddressFromResult,
evmCollection,
} from './util/helpers';
@@ -224,8 +224,8 @@
//TODO: CORE-302 add eth methods
itWeb3.skip('Sponsoring evm address from substrate collection', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const collectionHelper = evmCollectionHelper(web3, owner);
- let result = await collectionHelper.methods.create721Collection('Sponsor collection', '1', '1').send();
+ const collectionHelpers = evmCollectionHelpers(web3, owner);
+ let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const sponsor = await createEthAccountWithBalance(api, web3);
const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
tests/src/eth/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -18,7 +18,7 @@
import {expect} from 'chai';
import {getCreatedCollectionCount, getDetailedCollectionInfo} from '../util/helpers';
import {
- evmCollectionHelper,
+ evmCollectionHelpers,
collectionIdToAddress,
createEthAccount,
createEthAccountWithBalance,
@@ -30,14 +30,14 @@
describe('Create collection from EVM', () => {
itWeb3('Create collection', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = evmCollectionHelper(web3, owner);
+ const helper = evmCollectionHelpers(web3, owner);
const collectionName = 'CollectionEVM';
const description = 'Some description';
const tokenPrefix = 'token prefix';
const collectionCountBefore = await getCreatedCollectionCount(api);
const result = await helper.methods
- .create721Collection(collectionName, description, tokenPrefix)
+ .createNonfungibleCollection(collectionName, description, tokenPrefix)
.send();
const collectionCountAfter = await getCreatedCollectionCount(api);
@@ -51,27 +51,27 @@
itWeb3('Check collection address exist', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const collectionHelper = evmCollectionHelper(web3, owner);
+ const collectionHelpers = evmCollectionHelpers(web3, owner);
const expectedCollectionId = await getCreatedCollectionCount(api) + 1;
const expectedCollectionAddress = collectionIdToAddress(expectedCollectionId);
- expect(await collectionHelper.methods
+ expect(await collectionHelpers.methods
.isCollectionExist(expectedCollectionAddress)
.call()).to.be.false;
- await collectionHelper.methods
- .create721Collection('A', 'A', 'A')
+ await collectionHelpers.methods
+ .createNonfungibleCollection('A', 'A', 'A')
.send();
- expect(await collectionHelper.methods
+ expect(await collectionHelpers.methods
.isCollectionExist(expectedCollectionAddress)
.call()).to.be.true;
});
itWeb3('Set sponsorship', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const collectionHelper = evmCollectionHelper(web3, owner);
- let result = await collectionHelper.methods.create721Collection('Sponsor collection', '1', '1').send();
+ const collectionHelpers = evmCollectionHelpers(web3, owner);
+ let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const sponsor = await createEthAccountWithBalance(api, web3);
const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
@@ -89,8 +89,8 @@
itWeb3('Set limits', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const collectionHelper = evmCollectionHelper(web3, owner);
- const result = await collectionHelper.methods.create721Collection('Const collection', '5', '5').send();
+ const collectionHelpers = evmCollectionHelpers(web3, owner);
+ const result = await collectionHelpers.methods.createNonfungibleCollection('Const collection', '5', '5').send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const limits = {
accountTokenOwnershipLimit: 1000,
@@ -105,15 +105,15 @@
};
const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
- await collectionEvm.methods.setLimit('accountTokenOwnershipLimit', limits.accountTokenOwnershipLimit.toString()).send();
- await collectionEvm.methods.setLimit('sponsoredDataSize', limits.sponsoredDataSize.toString()).send();
- await collectionEvm.methods.setLimit('sponsoredDataRateLimit', limits.sponsoredDataRateLimit.toString()).send();
- await collectionEvm.methods.setLimit('tokenLimit', limits.tokenLimit.toString()).send();
- await collectionEvm.methods.setLimit('sponsorTransferTimeout', limits.sponsorTransferTimeout.toString()).send();
- await collectionEvm.methods.setLimit('sponsorApproveTimeout', limits.sponsorApproveTimeout.toString()).send();
- await collectionEvm.methods.setLimit('ownerCanTransfer', limits.ownerCanTransfer.toString()).send();
- await collectionEvm.methods.setLimit('ownerCanDestroy', limits.ownerCanDestroy.toString()).send();
- await collectionEvm.methods.setLimit('transfersEnabled', limits.transfersEnabled.toString()).send();
+ await collectionEvm.methods['setLimit(string,uint32)']('accountTokenOwnershipLimit', limits.accountTokenOwnershipLimit).send();
+ await collectionEvm.methods['setLimit(string,uint32)']('sponsoredDataSize', limits.sponsoredDataSize).send();
+ await collectionEvm.methods['setLimit(string,uint32)']('sponsoredDataRateLimit', limits.sponsoredDataRateLimit).send();
+ await collectionEvm.methods['setLimit(string,uint32)']('tokenLimit', limits.tokenLimit).send();
+ await collectionEvm.methods['setLimit(string,uint32)']('sponsorTransferTimeout', limits.sponsorTransferTimeout).send();
+ await collectionEvm.methods['setLimit(string,uint32)']('sponsorApproveTimeout', limits.sponsorApproveTimeout).send();
+ await collectionEvm.methods['setLimit(string,bool)']('ownerCanTransfer', limits.ownerCanTransfer).send();
+ await collectionEvm.methods['setLimit(string,bool)']('ownerCanDestroy', limits.ownerCanDestroy).send();
+ await collectionEvm.methods['setLimit(string,bool)']('transfersEnabled', limits.transfersEnabled).send();
const collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
expect(collectionSub.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);
@@ -130,14 +130,14 @@
itWeb3('Collection address exist', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
const collectionAddressForNonexistentCollection = '0x17C4E6453CC49AAAAEACA894E6D9683E00112233';
- const collectionHelper = evmCollectionHelper(web3, owner);
- expect(await collectionHelper.methods
+ const collectionHelpers = evmCollectionHelpers(web3, owner);
+ expect(await collectionHelpers.methods
.isCollectionExist(collectionAddressForNonexistentCollection).call())
.to.be.false;
- const result = await collectionHelper.methods.create721Collection('Collection address exist', '7', '7').send();
+ const result = await collectionHelpers.methods.createNonfungibleCollection('Collection address exist', '7', '7').send();
const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
- expect(await collectionHelper.methods
+ expect(await collectionHelpers.methods
.isCollectionExist(collectionIdAddress).call())
.to.be.true;
});
@@ -146,7 +146,7 @@
describe('(!negative tests!) Create collection from EVM', () => {
itWeb3('(!negative test!) Create collection (bad lengths)', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = evmCollectionHelper(web3, owner);
+ const helper = evmCollectionHelpers(web3, owner);
{
const MAX_NAME_LENGHT = 64;
const collectionName = 'A'.repeat(MAX_NAME_LENGHT + 1);
@@ -154,7 +154,7 @@
const tokenPrefix = 'A';
await expect(helper.methods
- .create721Collection(collectionName, description, tokenPrefix)
+ .createNonfungibleCollection(collectionName, description, tokenPrefix)
.call()).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGHT);
}
@@ -164,7 +164,7 @@
const description = 'A'.repeat(MAX_DESCRIPTION_LENGHT + 1);
const tokenPrefix = 'A';
await expect(helper.methods
- .create721Collection(collectionName, description, tokenPrefix)
+ .createNonfungibleCollection(collectionName, description, tokenPrefix)
.call()).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGHT);
}
{
@@ -173,28 +173,28 @@
const description = 'A';
const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGHT + 1);
await expect(helper.methods
- .create721Collection(collectionName, description, tokenPrefix)
+ .createNonfungibleCollection(collectionName, description, tokenPrefix)
.call()).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGHT);
}
});
itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
const owner = await createEthAccount(web3);
- const helper = evmCollectionHelper(web3, owner);
+ const helper = evmCollectionHelpers(web3, owner);
const collectionName = 'A';
const description = 'A';
const tokenPrefix = 'A';
await expect(helper.methods
- .create721Collection(collectionName, description, tokenPrefix)
+ .createNonfungibleCollection(collectionName, description, tokenPrefix)
.call()).to.be.rejectedWith('NotSufficientFounds');
});
itWeb3('(!negative test!) Check owner', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
const notOwner = await createEthAccount(web3);
- const collectionHelper = evmCollectionHelper(web3, owner);
- const result = await collectionHelper.methods.create721Collection('A', 'A', 'A').send();
+ const collectionHelpers = evmCollectionHelpers(web3, owner);
+ const result = await collectionHelpers.methods.createNonfungibleCollection('A', 'A', 'A').send();
const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
const contractEvmFromNotOwner = evmCollection(web3, notOwner, collectionIdAddress);
const EXPECTED_ERROR = 'NoPermission';
@@ -218,18 +218,12 @@
itWeb3('(!negative test!) Set limits', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const collectionHelper = evmCollectionHelper(web3, owner);
- const result = await collectionHelper.methods.create721Collection('Schema collection', 'A', 'A').send();
+ const collectionHelpers = evmCollectionHelpers(web3, owner);
+ const result = await collectionHelpers.methods.createNonfungibleCollection('Schema collection', 'A', 'A').send();
const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
await expect(collectionEvm.methods
.setLimit('badLimit', 'true')
- .call()).to.be.rejectedWith('Unknown limit "badLimit"');
- await expect(collectionEvm.methods
- .setLimit('sponsoredDataSize', 'badValue')
- .call()).to.be.rejectedWith('Int value "badValue" parse error:');
- await expect(collectionEvm.methods
- .setLimit('ownerCanTransfer', 'badValue')
- .call()).to.be.rejectedWith('Bool value "badValue" parse error:');
+ .call()).to.be.rejectedWith('Unknown boolean limit "badLimit"');
});
});
\ No newline at end of file
tests/src/eth/fungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -152,7 +152,17 @@
{
"inputs": [
{ "internalType": "string", "name": "limit", "type": "string" },
- { "internalType": "string", "name": "value", "type": "string" }
+ { "internalType": "uint32", "name": "value", "type": "uint32" }
+ ],
+ "name": "setLimit",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "limit", "type": "string" },
+ { "internalType": "bool", "name": "value", "type": "bool" }
],
"name": "setLimit",
"outputs": [],
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -16,7 +16,7 @@
import privateKey from '../substrate/privateKey';
import {approveExpectSuccess, burnItemExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE} from '../util/helpers';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelper, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth} from './util/helpers';
+import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth} from './util/helpers';
import nonFungibleAbi from './nonFungibleAbi.json';
import {expect} from 'chai';
import {submitTransactionAsync} from '../substrate/substrate-api';
@@ -76,8 +76,8 @@
describe('NFT: Plain calls', () => {
itWeb3('Can perform mint()', async ({web3, api}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = evmCollectionHelper(web3, owner);
- let result = await helper.methods.create721Collection('Mint collection', '6', '6').send();
+ const helper = evmCollectionHelpers(web3, owner);
+ let result = await helper.methods.createNonfungibleCollection('Mint collection', '6', '6').send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const receiver = createEthAccount(web3);
const contract = evmCollection(web3, owner, collectionIdAddress);
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -326,7 +326,17 @@
{
"inputs": [
{ "internalType": "string", "name": "limit", "type": "string" },
- { "internalType": "string", "name": "value", "type": "string" }
+ { "internalType": "uint32", "name": "value", "type": "uint32" }
+ ],
+ "name": "setLimit",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "limit", "type": "string" },
+ { "internalType": "bool", "name": "value", "type": "bool" }
],
"name": "setLimit",
"outputs": [],
tests/src/eth/util/helpers.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -29,7 +29,7 @@
import privateKey from '../../substrate/privateKey';
import contractHelpersAbi from './contractHelpersAbi.json';
import nonFungibleAbi from '../nonFungibleAbi.json';
-import collectionHelperAbi from '../collectionHelperAbi.json';
+import collectionHelpersAbi from '../collectionHelpersAbi.json';
import getBalance from '../../substrate/get-balance';
import waitNewBlocks from '../../substrate/wait-new-blocks';
@@ -69,7 +69,7 @@
}
export async function getCollectionAddressFromResult(api: ApiPromise, result: any) {
- const collectionIdAddress = normalizeAddress(result.events[0].raw.topics[2]);
+ const collectionIdAddress = normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const collectionId = collectionIdFromAddress(collectionIdAddress);
const collection = (await getDetailedCollectionInfo(api, collectionId))!;
return {collectionIdAddress, collectionId, collection};
@@ -297,8 +297,8 @@
* @param caller - eth address
* @returns
*/
-export function evmCollectionHelper(web3: Web3, caller: string) {
- return new web3.eth.Contract(collectionHelperAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
+export function evmCollectionHelpers(web3: Web3, caller: string) {
+ return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
}
/**