difftreelog
refactor create collection with optional payer
in: master
5 files changed
pallets/common/src/dispatch.rsdiffbeforeafterboth--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -72,20 +72,11 @@
/// Create a collection. The collection will be created according to the value of [`data.mode`](CreateCollectionData::mode).
///
/// * `sender` - The user who will become the owner of the collection.
- /// * `payer` - The user who pays the collection creation fee.
+ /// * `payer` - If set, the user who pays the collection creation deposit.
/// * `data` - Description of the created collection.
fn create(
sender: T::CrossAccountId,
- payer: T::CrossAccountId,
- data: CreateCollectionData<T::CrossAccountId>,
- ) -> Result<CollectionId, DispatchError>;
-
- /// Create a foreign collection. The collection will be created according to the value of [`data.mode`](CreateCollectionData::mode).
- ///
- /// * `sender` - The user who will become the owner of the collection.
- /// * `data` - Description of the created collection.
- fn create_foreign(
- sender: T::CrossAccountId,
+ payer: Option<T::CrossAccountId>,
data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError>;
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -152,8 +152,10 @@
.try_into()
.expect("description length < max description length; qed");
- let collection_id = T::CollectionDispatch::create_foreign(
+ let payer = None;
+ let collection_id = T::CollectionDispatch::create(
foreign_collection_owner,
+ payer,
CreateCollectionData {
name,
description,
pallets/unique/src/eth/mod.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//! Implementation of CollectionHelpers contract.18//!19use alloc::{collections::BTreeSet, format};20use core::marker::PhantomData;2122use ethereum as _;23use evm_coder::{abi::AbiType, generate_stubgen, solidity_interface, types::*};24use frame_support::{traits::Get, BoundedVec};25use pallet_common::{26 dispatch::CollectionDispatch,27 erc::{static_property::key, CollectionHelpersEvents},28 eth::{self, collection_id_to_address, map_eth_to_id},29 CollectionById, CollectionHandle, Pallet as PalletCommon,30};31use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};32use pallet_evm_coder_substrate::{33 dispatch_to_evm,34 execution::{Error, PreDispatch, Result},35 frontier_contract, SubstrateRecorder, WithRecorder,36};37use sp_std::vec::Vec;38use up_data_structs::{39 CollectionDescription, CollectionMode, CollectionName, CollectionPermissions,40 CollectionTokenPrefix, CreateCollectionData, NestingPermissions,41};4243use crate::{weights::WeightInfo, Config, Pallet, SelfWeightOf};4445frontier_contract! {46 macro_rules! EvmCollectionHelpers_result {...}47 impl<T: Config> Contract for EvmCollectionHelpers<T> {...}48}49/// See [`CollectionHelpersCall`]50pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);51impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {52 fn recorder(&self) -> &SubstrateRecorder<T> {53 &self.054 }5556 fn into_recorder(self) -> SubstrateRecorder<T> {57 self.058 }59}6061fn convert_data<T: Config>(62 caller: Caller,63 name: String,64 description: String,65 token_prefix: String,66) -> Result<(67 T::CrossAccountId,68 CollectionName,69 CollectionDescription,70 CollectionTokenPrefix,71)> {72 let caller = T::CrossAccountId::from_eth(caller);73 let name = name74 .encode_utf16()75 .collect::<Vec<u16>>()76 .try_into()77 .map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;78 let description = description79 .encode_utf16()80 .collect::<Vec<u16>>()81 .try_into()82 .map_err(|_| {83 error_field_too_long(stringify!(description), CollectionDescription::bound())84 })?;85 let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {86 error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())87 })?;88 Ok((caller, name, description, token_prefix))89}9091#[inline(always)]92fn create_collection_internal<T: Config>(93 caller: Caller,94 value: Value,95 name: String,96 collection_mode: CollectionMode,97 description: String,98 token_prefix: String,99) -> Result<Address> {100 let (caller, name, description, token_prefix) =101 convert_data::<T>(caller, name, description, token_prefix)?;102 let data = CreateCollectionData {103 name,104 mode: collection_mode,105 description,106 token_prefix,107 ..Default::default()108 };109 check_sent_amount_equals_collection_creation_price::<T>(value)?;110 let collection_helpers_address =111 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());112113 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)114 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;115 let address = pallet_common::eth::collection_id_to_address(collection_id);116 Ok(address)117}118119fn check_sent_amount_equals_collection_creation_price<T: Config>(value: Value) -> Result<()> {120 let value = value.as_u128();121 let creation_price: u128 = T::CollectionCreationPrice::get()122 .try_into()123 .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait124 .expect("Collection creation price should be convertible to u128");125 if value != creation_price {126 return Err(format!(127 "Sent amount not equals to collection creation price ({creation_price})",128 )129 .into());130 }131 Ok(())132}133134/// @title Contract, which allows users to operate with collections135#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents), enum(derive(PreDispatch)), enum_attr(weight))]136impl<T> EvmCollectionHelpers<T>137where138 T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,139 T::AccountId: From<[u8; 32]>,140{141 /// Create a collection142 /// @return address Address of the newly created collection143 #[weight(<SelfWeightOf<T>>::create_collection())]144 #[solidity(rename_selector = "createCollection")]145 fn create_collection(146 &mut self,147 caller: Caller,148 value: Value,149 data: eth::CreateCollectionData,150 ) -> Result<Address> {151 let (caller, name, description, token_prefix) =152 convert_data::<T>(caller, data.name, data.description, data.token_prefix)?;153 if data.mode != eth::CollectionMode::Fungible && data.decimals != 0 {154 return Err("decimals are only supported for NFT and RFT collections".into());155 }156 let mode = match data.mode {157 eth::CollectionMode::Fungible => CollectionMode::Fungible(data.decimals),158 eth::CollectionMode::Nonfungible => CollectionMode::NFT,159 eth::CollectionMode::Refungible => CollectionMode::ReFungible,160 };161162 let properties: BoundedVec<_, _> = data163 .properties164 .into_iter()165 .map(eth::Property::try_into)166 .collect::<Result<Vec<_>>>()?167 .try_into()168 .map_err(|_| "too many properties")?;169170 let token_property_permissions =171 eth::TokenPropertyPermission::into_property_key_permissions(172 data.token_property_permissions,173 )?174 .try_into()175 .map_err(|_| "too many property permissions")?;176177 let limits = if !data.limits.is_empty() {178 Some(179 data.limits180 .into_iter()181 .collect::<Result<up_data_structs::CollectionLimits>>()?,182 )183 } else {184 None185 };186187 let pending_sponsor = data.pending_sponsor.into_option_sub_cross_account::<T>()?;188189 let restricted = if !data.nesting_settings.restricted.is_empty() {190 Some(191 data.nesting_settings192 .restricted193 .iter()194 .map(map_eth_to_id)195 .collect::<Option<BTreeSet<_>>>()196 .ok_or("can't convert address into collection id")?197 .try_into()198 .map_err(|_| "too many collections")?,199 )200 } else {201 None202 };203204 let admin_list = data205 .admin_list206 .into_iter()207 .map(|admin| admin.into_sub_cross_account::<T>())208 .collect::<Result<Vec<_>>>()?;209210 let flags = data.flags;211 if !flags.is_allowed_for_user() {212 return Err("internal flags were used".into());213 }214215 let data = CreateCollectionData {216 name,217 mode,218 description,219 token_prefix,220 properties,221 token_property_permissions,222 limits,223 pending_sponsor,224 access: None,225 permissions: Some(CollectionPermissions {226 access: None,227 mint_mode: None,228 nesting: Some(NestingPermissions {229 token_owner: data.nesting_settings.token_owner,230 collection_admin: data.nesting_settings.collection_admin,231 restricted,232 #[cfg(feature = "runtime-benchmarks")]233 permissive: true,234 }),235 }),236 admin_list,237 flags,238 };239 check_sent_amount_equals_collection_creation_price::<T>(value)?;240 let collection_helpers_address =241 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());242243 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)244 .map_err(dispatch_to_evm::<T>)?;245246 let address = pallet_common::eth::collection_id_to_address(collection_id);247 Ok(address)248 }249250 /// Create an NFT collection251 /// @param name Name of the collection252 /// @param description Informative description of the collection253 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications254 /// @return address Address of the newly created collection255 #[weight(<SelfWeightOf<T>>::create_collection())]256 #[solidity(rename_selector = "createNFTCollection")]257 fn create_nft_collection(258 &mut self,259 caller: Caller,260 value: Value,261 name: String,262 description: String,263 token_prefix: String,264 ) -> Result<Address> {265 let (caller, name, description, token_prefix) =266 convert_data::<T>(caller, name, description, token_prefix)?;267 let data = CreateCollectionData {268 name,269 mode: CollectionMode::NFT,270 description,271 token_prefix,272 ..Default::default()273 };274 check_sent_amount_equals_collection_creation_price::<T>(value)?;275 let collection_helpers_address =276 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());277 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)278 .map_err(dispatch_to_evm::<T>)?;279280 let address = pallet_common::eth::collection_id_to_address(collection_id);281 Ok(address)282 }283 /// Create an NFT collection284 /// @param name Name of the collection285 /// @param description Informative description of the collection286 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications287 /// @return address Address of the newly created collection288 #[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]289 #[solidity(hide)]290 #[weight(<SelfWeightOf<T>>::create_collection())]291 fn create_nonfungible_collection(292 &mut self,293 caller: Caller,294 value: Value,295 name: String,296 description: String,297 token_prefix: String,298 ) -> Result<Address> {299 create_collection_internal::<T>(300 caller,301 value,302 name,303 CollectionMode::NFT,304 description,305 token_prefix,306 )307 }308309 #[weight(<SelfWeightOf<T>>::create_collection())]310 #[solidity(rename_selector = "createRFTCollection")]311 fn create_rft_collection(312 &mut self,313 caller: Caller,314 value: Value,315 name: String,316 description: String,317 token_prefix: String,318 ) -> Result<Address> {319 create_collection_internal::<T>(320 caller,321 value,322 name,323 CollectionMode::ReFungible,324 description,325 token_prefix,326 )327 }328329 #[weight(<SelfWeightOf<T>>::create_collection())]330 #[solidity(rename_selector = "createFTCollection")]331 fn create_fungible_collection(332 &mut self,333 caller: Caller,334 value: Value,335 name: String,336 decimals: u8,337 description: String,338 token_prefix: String,339 ) -> Result<Address> {340 create_collection_internal::<T>(341 caller,342 value,343 name,344 CollectionMode::Fungible(decimals),345 description,346 token_prefix,347 )348 }349350 #[solidity(rename_selector = "makeCollectionERC721MetadataCompatible")]351 fn make_collection_metadata_compatible(352 &mut self,353 caller: Caller,354 collection: Address,355 base_uri: String,356 ) -> Result<()> {357 let caller = T::CrossAccountId::from_eth(caller);358 let collection =359 pallet_common::eth::map_eth_to_id(&collection).ok_or("not a collection address")?;360 let mut collection =361 <CollectionHandle<T>>::new(collection).ok_or("collection not found")?;362363 if !matches!(364 collection.mode,365 CollectionMode::NFT | CollectionMode::ReFungible366 ) {367 return Err("target collection should be either NFT or Refungible".into());368 }369370 self.recorder().consume_sstore()?;371 collection372 .check_is_owner_or_admin(&caller)373 .map_err(dispatch_to_evm::<T>)?;374375 if collection.flags.erc721metadata {376 return Err("target collection is already Erc721Metadata compatible".into());377 }378 collection.flags.erc721metadata = true;379380 let all_permissions = <pallet_common::CollectionPropertyPermissions<T>>::get(collection.id);381 if all_permissions.get(&key::url()).is_none() {382 self.recorder().consume_sstore()?;383 <PalletCommon<T>>::set_property_permission(384 &collection,385 &caller,386 up_data_structs::PropertyKeyPermission {387 key: key::url(),388 permission: up_data_structs::PropertyPermission {389 mutable: true,390 collection_admin: true,391 token_owner: false,392 },393 },394 )395 .map_err(dispatch_to_evm::<T>)?;396 }397 if all_permissions.get(&key::suffix()).is_none() {398 self.recorder().consume_sstore()?;399 <PalletCommon<T>>::set_property_permission(400 &collection,401 &caller,402 up_data_structs::PropertyKeyPermission {403 key: key::suffix(),404 permission: up_data_structs::PropertyPermission {405 mutable: true,406 collection_admin: true,407 token_owner: false,408 },409 },410 )411 .map_err(dispatch_to_evm::<T>)?;412 }413414 let all_properties = <pallet_common::CollectionProperties<T>>::get(collection.id);415 if all_properties.get(&key::base_uri()).is_none() && !base_uri.is_empty() {416 self.recorder().consume_sstore()?;417 <PalletCommon<T>>::set_collection_properties(418 &collection,419 &caller,420 [up_data_structs::Property {421 key: key::base_uri(),422 value: base_uri423 .into_bytes()424 .try_into()425 .map_err(|_| "base uri is too large")?,426 }]427 .into_iter(),428 )429 .map_err(dispatch_to_evm::<T>)?;430 }431432 self.recorder().consume_sstore()?;433 collection.save().map_err(dispatch_to_evm::<T>)?;434435 Ok(())436 }437438 #[weight(<SelfWeightOf<T>>::destroy_collection())]439 fn destroy_collection(&mut self, caller: Caller, collection_address: Address) -> Result<()> {440 let caller = T::CrossAccountId::from_eth(caller);441442 let collection_id = pallet_common::eth::map_eth_to_id(&collection_address)443 .ok_or("Invalid collection address format")?;444 <Pallet<T>>::destroy_collection_internal(caller, collection_id)445 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)446 }447448 /// Check if a collection exists449 /// @param collectionAddress Address of the collection in question450 /// @return bool Does the collection exist?451 fn is_collection_exist(&self, _caller: Caller, collection_address: Address) -> Result<bool> {452 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {453 let collection_id = id;454 return Ok(<CollectionById<T>>::contains_key(collection_id));455 }456457 Ok(false)458 }459460 fn collection_creation_fee(&self) -> Result<Value> {461 let price: u128 = T::CollectionCreationPrice::get()462 .try_into()463 .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait464 .expect("Collection creation price should be convertible to u128");465 Ok(price.into())466 }467468 /// Returns address of a collection.469 /// @param collectionId - CollectionId of the collection470 /// @return eth mirror address of the collection471 fn collection_address(&self, collection_id: u32) -> Result<Address> {472 Ok(collection_id_to_address(collection_id.into()))473 }474475 /// Returns collectionId of a collection.476 /// @param collectionAddress - Eth address of the collection477 /// @return collectionId of the collection478 fn collection_id(&self, collection_address: Address) -> Result<u32> {479 map_eth_to_id(&collection_address)480 .map(|id| id.0)481 .ok_or(Error::Revert(format!(482 "failed to convert address {collection_address} into collectionId."483 )))484 }485}486487/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]488pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);489impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>490 for CollectionHelpersOnMethodCall<T>491where492 T::AccountId: From<[u8; 32]>,493{494 fn is_reserved(contract: &sp_core::H160) -> bool {495 contract == &T::ContractAddress::get()496 }497498 fn is_used(contract: &sp_core::H160) -> bool {499 contract == &T::ContractAddress::get()500 }501502 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {503 if handle.code_address() != T::ContractAddress::get() {504 return None;505 }506507 let helpers =508 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));509 pallet_evm_coder_substrate::call(handle, helpers)510 }511512 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {513 (contract == &T::ContractAddress::get())514 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())515 }516}517518generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);519generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);520521fn error_field_too_long(feild: &str, bound: usize) -> Error {522 Error::Revert(format!("{feild} is too long. Max length is {bound}."))523}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//! Implementation of CollectionHelpers contract.18//!19use alloc::{collections::BTreeSet, format};20use core::marker::PhantomData;2122use ethereum as _;23use evm_coder::{abi::AbiType, generate_stubgen, solidity_interface, types::*};24use frame_support::{traits::Get, BoundedVec};25use pallet_common::{26 dispatch::CollectionDispatch,27 erc::{static_property::key, CollectionHelpersEvents},28 eth::{self, collection_id_to_address, map_eth_to_id},29 CollectionById, CollectionHandle, Pallet as PalletCommon,30};31use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};32use pallet_evm_coder_substrate::{33 dispatch_to_evm,34 execution::{Error, PreDispatch, Result},35 frontier_contract, SubstrateRecorder, WithRecorder,36};37use sp_std::vec::Vec;38use up_data_structs::{39 CollectionDescription, CollectionMode, CollectionName, CollectionPermissions,40 CollectionTokenPrefix, CreateCollectionData, NestingPermissions,41};4243use crate::{weights::WeightInfo, Config, Pallet, SelfWeightOf};4445frontier_contract! {46 macro_rules! EvmCollectionHelpers_result {...}47 impl<T: Config> Contract for EvmCollectionHelpers<T> {...}48}49/// See [`CollectionHelpersCall`]50pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);51impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {52 fn recorder(&self) -> &SubstrateRecorder<T> {53 &self.054 }5556 fn into_recorder(self) -> SubstrateRecorder<T> {57 self.058 }59}6061fn convert_data<T: Config>(62 caller: Caller,63 name: String,64 description: String,65 token_prefix: String,66) -> Result<(67 T::CrossAccountId,68 CollectionName,69 CollectionDescription,70 CollectionTokenPrefix,71)> {72 let caller = T::CrossAccountId::from_eth(caller);73 let name = name74 .encode_utf16()75 .collect::<Vec<u16>>()76 .try_into()77 .map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;78 let description = description79 .encode_utf16()80 .collect::<Vec<u16>>()81 .try_into()82 .map_err(|_| {83 error_field_too_long(stringify!(description), CollectionDescription::bound())84 })?;85 let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {86 error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())87 })?;88 Ok((caller, name, description, token_prefix))89}9091#[inline(always)]92fn create_collection_internal<T: Config>(93 caller: Caller,94 value: Value,95 name: String,96 collection_mode: CollectionMode,97 description: String,98 token_prefix: String,99) -> Result<Address> {100 let (caller, name, description, token_prefix) =101 convert_data::<T>(caller, name, description, token_prefix)?;102 let data = CreateCollectionData {103 name,104 mode: collection_mode,105 description,106 token_prefix,107 ..Default::default()108 };109 check_sent_amount_equals_collection_creation_price::<T>(value)?;110 let collection_helpers_address =111 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());112113 let collection_id =114 T::CollectionDispatch::create(caller, Some(collection_helpers_address), data)115 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;116 let address = pallet_common::eth::collection_id_to_address(collection_id);117 Ok(address)118}119120fn check_sent_amount_equals_collection_creation_price<T: Config>(value: Value) -> Result<()> {121 let value = value.as_u128();122 let creation_price: u128 = T::CollectionCreationPrice::get()123 .try_into()124 .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait125 .expect("Collection creation price should be convertible to u128");126 if value != creation_price {127 return Err(format!(128 "Sent amount not equals to collection creation price ({creation_price})",129 )130 .into());131 }132 Ok(())133}134135/// @title Contract, which allows users to operate with collections136#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents), enum(derive(PreDispatch)), enum_attr(weight))]137impl<T> EvmCollectionHelpers<T>138where139 T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,140 T::AccountId: From<[u8; 32]>,141{142 /// Create a collection143 /// @return address Address of the newly created collection144 #[weight(<SelfWeightOf<T>>::create_collection())]145 #[solidity(rename_selector = "createCollection")]146 fn create_collection(147 &mut self,148 caller: Caller,149 value: Value,150 data: eth::CreateCollectionData,151 ) -> Result<Address> {152 let (caller, name, description, token_prefix) =153 convert_data::<T>(caller, data.name, data.description, data.token_prefix)?;154 if data.mode != eth::CollectionMode::Fungible && data.decimals != 0 {155 return Err("decimals are only supported for NFT and RFT collections".into());156 }157 let mode = match data.mode {158 eth::CollectionMode::Fungible => CollectionMode::Fungible(data.decimals),159 eth::CollectionMode::Nonfungible => CollectionMode::NFT,160 eth::CollectionMode::Refungible => CollectionMode::ReFungible,161 };162163 let properties: BoundedVec<_, _> = data164 .properties165 .into_iter()166 .map(eth::Property::try_into)167 .collect::<Result<Vec<_>>>()?168 .try_into()169 .map_err(|_| "too many properties")?;170171 let token_property_permissions =172 eth::TokenPropertyPermission::into_property_key_permissions(173 data.token_property_permissions,174 )?175 .try_into()176 .map_err(|_| "too many property permissions")?;177178 let limits = if !data.limits.is_empty() {179 Some(180 data.limits181 .into_iter()182 .collect::<Result<up_data_structs::CollectionLimits>>()?,183 )184 } else {185 None186 };187188 let pending_sponsor = data.pending_sponsor.into_option_sub_cross_account::<T>()?;189190 let restricted = if !data.nesting_settings.restricted.is_empty() {191 Some(192 data.nesting_settings193 .restricted194 .iter()195 .map(map_eth_to_id)196 .collect::<Option<BTreeSet<_>>>()197 .ok_or("can't convert address into collection id")?198 .try_into()199 .map_err(|_| "too many collections")?,200 )201 } else {202 None203 };204205 let admin_list = data206 .admin_list207 .into_iter()208 .map(|admin| admin.into_sub_cross_account::<T>())209 .collect::<Result<Vec<_>>>()?;210211 let flags = data.flags;212 if !flags.is_allowed_for_user() {213 return Err("internal flags were used".into());214 }215216 let data = CreateCollectionData {217 name,218 mode,219 description,220 token_prefix,221 properties,222 token_property_permissions,223 limits,224 pending_sponsor,225 access: None,226 permissions: Some(CollectionPermissions {227 access: None,228 mint_mode: None,229 nesting: Some(NestingPermissions {230 token_owner: data.nesting_settings.token_owner,231 collection_admin: data.nesting_settings.collection_admin,232 restricted,233 #[cfg(feature = "runtime-benchmarks")]234 permissive: true,235 }),236 }),237 admin_list,238 flags,239 };240 check_sent_amount_equals_collection_creation_price::<T>(value)?;241 let collection_helpers_address =242 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());243244 let collection_id =245 T::CollectionDispatch::create(caller, Some(collection_helpers_address), data)246 .map_err(dispatch_to_evm::<T>)?;247248 let address = pallet_common::eth::collection_id_to_address(collection_id);249 Ok(address)250 }251252 /// Create an NFT collection253 /// @param name Name of the collection254 /// @param description Informative description of the collection255 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications256 /// @return address Address of the newly created collection257 #[weight(<SelfWeightOf<T>>::create_collection())]258 #[solidity(rename_selector = "createNFTCollection")]259 fn create_nft_collection(260 &mut self,261 caller: Caller,262 value: Value,263 name: String,264 description: String,265 token_prefix: String,266 ) -> Result<Address> {267 let (caller, name, description, token_prefix) =268 convert_data::<T>(caller, name, description, token_prefix)?;269 let data = CreateCollectionData {270 name,271 mode: CollectionMode::NFT,272 description,273 token_prefix,274 ..Default::default()275 };276 check_sent_amount_equals_collection_creation_price::<T>(value)?;277 let collection_helpers_address =278 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());279 let collection_id =280 T::CollectionDispatch::create(caller, Some(collection_helpers_address), data)281 .map_err(dispatch_to_evm::<T>)?;282283 let address = pallet_common::eth::collection_id_to_address(collection_id);284 Ok(address)285 }286 /// Create an NFT collection287 /// @param name Name of the collection288 /// @param description Informative description of the collection289 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications290 /// @return address Address of the newly created collection291 #[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]292 #[solidity(hide)]293 #[weight(<SelfWeightOf<T>>::create_collection())]294 fn create_nonfungible_collection(295 &mut self,296 caller: Caller,297 value: Value,298 name: String,299 description: String,300 token_prefix: String,301 ) -> Result<Address> {302 create_collection_internal::<T>(303 caller,304 value,305 name,306 CollectionMode::NFT,307 description,308 token_prefix,309 )310 }311312 #[weight(<SelfWeightOf<T>>::create_collection())]313 #[solidity(rename_selector = "createRFTCollection")]314 fn create_rft_collection(315 &mut self,316 caller: Caller,317 value: Value,318 name: String,319 description: String,320 token_prefix: String,321 ) -> Result<Address> {322 create_collection_internal::<T>(323 caller,324 value,325 name,326 CollectionMode::ReFungible,327 description,328 token_prefix,329 )330 }331332 #[weight(<SelfWeightOf<T>>::create_collection())]333 #[solidity(rename_selector = "createFTCollection")]334 fn create_fungible_collection(335 &mut self,336 caller: Caller,337 value: Value,338 name: String,339 decimals: u8,340 description: String,341 token_prefix: String,342 ) -> Result<Address> {343 create_collection_internal::<T>(344 caller,345 value,346 name,347 CollectionMode::Fungible(decimals),348 description,349 token_prefix,350 )351 }352353 #[solidity(rename_selector = "makeCollectionERC721MetadataCompatible")]354 fn make_collection_metadata_compatible(355 &mut self,356 caller: Caller,357 collection: Address,358 base_uri: String,359 ) -> Result<()> {360 let caller = T::CrossAccountId::from_eth(caller);361 let collection =362 pallet_common::eth::map_eth_to_id(&collection).ok_or("not a collection address")?;363 let mut collection =364 <CollectionHandle<T>>::new(collection).ok_or("collection not found")?;365366 if !matches!(367 collection.mode,368 CollectionMode::NFT | CollectionMode::ReFungible369 ) {370 return Err("target collection should be either NFT or Refungible".into());371 }372373 self.recorder().consume_sstore()?;374 collection375 .check_is_owner_or_admin(&caller)376 .map_err(dispatch_to_evm::<T>)?;377378 if collection.flags.erc721metadata {379 return Err("target collection is already Erc721Metadata compatible".into());380 }381 collection.flags.erc721metadata = true;382383 let all_permissions = <pallet_common::CollectionPropertyPermissions<T>>::get(collection.id);384 if all_permissions.get(&key::url()).is_none() {385 self.recorder().consume_sstore()?;386 <PalletCommon<T>>::set_property_permission(387 &collection,388 &caller,389 up_data_structs::PropertyKeyPermission {390 key: key::url(),391 permission: up_data_structs::PropertyPermission {392 mutable: true,393 collection_admin: true,394 token_owner: false,395 },396 },397 )398 .map_err(dispatch_to_evm::<T>)?;399 }400 if all_permissions.get(&key::suffix()).is_none() {401 self.recorder().consume_sstore()?;402 <PalletCommon<T>>::set_property_permission(403 &collection,404 &caller,405 up_data_structs::PropertyKeyPermission {406 key: key::suffix(),407 permission: up_data_structs::PropertyPermission {408 mutable: true,409 collection_admin: true,410 token_owner: false,411 },412 },413 )414 .map_err(dispatch_to_evm::<T>)?;415 }416417 let all_properties = <pallet_common::CollectionProperties<T>>::get(collection.id);418 if all_properties.get(&key::base_uri()).is_none() && !base_uri.is_empty() {419 self.recorder().consume_sstore()?;420 <PalletCommon<T>>::set_collection_properties(421 &collection,422 &caller,423 [up_data_structs::Property {424 key: key::base_uri(),425 value: base_uri426 .into_bytes()427 .try_into()428 .map_err(|_| "base uri is too large")?,429 }]430 .into_iter(),431 )432 .map_err(dispatch_to_evm::<T>)?;433 }434435 self.recorder().consume_sstore()?;436 collection.save().map_err(dispatch_to_evm::<T>)?;437438 Ok(())439 }440441 #[weight(<SelfWeightOf<T>>::destroy_collection())]442 fn destroy_collection(&mut self, caller: Caller, collection_address: Address) -> Result<()> {443 let caller = T::CrossAccountId::from_eth(caller);444445 let collection_id = pallet_common::eth::map_eth_to_id(&collection_address)446 .ok_or("Invalid collection address format")?;447 <Pallet<T>>::destroy_collection_internal(caller, collection_id)448 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)449 }450451 /// Check if a collection exists452 /// @param collectionAddress Address of the collection in question453 /// @return bool Does the collection exist?454 fn is_collection_exist(&self, _caller: Caller, collection_address: Address) -> Result<bool> {455 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {456 let collection_id = id;457 return Ok(<CollectionById<T>>::contains_key(collection_id));458 }459460 Ok(false)461 }462463 fn collection_creation_fee(&self) -> Result<Value> {464 let price: u128 = T::CollectionCreationPrice::get()465 .try_into()466 .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait467 .expect("Collection creation price should be convertible to u128");468 Ok(price.into())469 }470471 /// Returns address of a collection.472 /// @param collectionId - CollectionId of the collection473 /// @return eth mirror address of the collection474 fn collection_address(&self, collection_id: u32) -> Result<Address> {475 Ok(collection_id_to_address(collection_id.into()))476 }477478 /// Returns collectionId of a collection.479 /// @param collectionAddress - Eth address of the collection480 /// @return collectionId of the collection481 fn collection_id(&self, collection_address: Address) -> Result<u32> {482 map_eth_to_id(&collection_address)483 .map(|id| id.0)484 .ok_or(Error::Revert(format!(485 "failed to convert address {collection_address} into collectionId."486 )))487 }488}489490/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]491pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);492impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>493 for CollectionHelpersOnMethodCall<T>494where495 T::AccountId: From<[u8; 32]>,496{497 fn is_reserved(contract: &sp_core::H160) -> bool {498 contract == &T::ContractAddress::get()499 }500501 fn is_used(contract: &sp_core::H160) -> bool {502 contract == &T::ContractAddress::get()503 }504505 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {506 if handle.code_address() != T::ContractAddress::get() {507 return None;508 }509510 let helpers =511 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));512 pallet_evm_coder_substrate::call(handle, helpers)513 }514515 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {516 (contract == &T::ContractAddress::get())517 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())518 }519}520521generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);522generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);523524fn error_field_too_long(feild: &str, bound: usize) -> Error {525 Error::Revert(format!("{feild} is too long. Max length is {bound}."))526}pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -401,7 +401,7 @@
// =========
let sender = T::CrossAccountId::from_sub(sender);
- let _id = T::CollectionDispatch::create(sender.clone(), sender, data)?;
+ let _id = T::CollectionDispatch::create(sender.clone(), Some(sender), data)?;
Ok(())
}
runtime/common/dispatch.rsdiffbeforeafterboth--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -18,7 +18,7 @@
use pallet_balances_adapter::NativeFungibleHandle;
pub use pallet_common::dispatch::CollectionDispatch;
use pallet_common::{
- erc::CommonEvmHandler, eth::map_eth_to_id, unsupported, CollectionById, CollectionHandle,
+ erc::CommonEvmHandler, eth::map_eth_to_id, CollectionById, CollectionHandle,
CommonCollectionOperations, Pallet as PalletCommon,
};
use pallet_evm::{PrecompileHandle, PrecompileResult};
@@ -68,7 +68,7 @@
fn create(
sender: T::CrossAccountId,
- payer: T::CrossAccountId,
+ payer: Option<T::CrossAccountId>,
data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError> {
match data.mode {
@@ -85,28 +85,7 @@
_ => {}
};
-
- <PalletCommon<T>>::init_collection(sender, Some(payer), data)
- }
- fn create_foreign(
- sender: <T>::CrossAccountId,
- data: CreateCollectionData<<T>::CrossAccountId>,
- ) -> Result<CollectionId, DispatchError> {
- match data.mode {
- CollectionMode::Fungible(decimal_points) => {
- // check params
- ensure!(
- decimal_points <= MAX_DECIMAL_POINTS,
- pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded
- );
- }
-
- CollectionMode::ReFungible => return unsupported!(T),
- _ => {}
- };
-
- let payer = None;
<PalletCommon<T>>::init_collection(sender, payer, data)
}