difftreelog
chore remove URI ttp from clean collections
in: master
4 files changed
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.1819use core::marker::PhantomData;20use ethereum as _;21use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};22use frame_support::traits::Get;23use pallet_common::{24 CollectionById,25 dispatch::CollectionDispatch,26 erc::{27 CollectionHelpersEvents,28 static_property::{key, value as property_value},29 },30};31use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};32use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};33use up_data_structs::{34 CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,35 CollectionMode, PropertyValue,36};3738use crate::{Config, SelfWeightOf, weights::WeightInfo};3940use sp_std::vec::Vec;41use alloc::format;4243/// See [`CollectionHelpersCall`]44pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);45impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {46 fn recorder(&self) -> &SubstrateRecorder<T> {47 &self.048 }4950 fn into_recorder(self) -> SubstrateRecorder<T> {51 self.052 }53}5455fn convert_data<T: Config>(56 caller: caller,57 name: string,58 description: string,59 token_prefix: string,60 base_uri: string,61) -> Result<(62 T::CrossAccountId,63 CollectionName,64 CollectionDescription,65 CollectionTokenPrefix,66 PropertyValue,67)> {68 let caller = T::CrossAccountId::from_eth(caller);69 let name = name70 .encode_utf16()71 .collect::<Vec<u16>>()72 .try_into()73 .map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;74 let description = description75 .encode_utf16()76 .collect::<Vec<u16>>()77 .try_into()78 .map_err(|_| {79 error_field_too_long(stringify!(description), CollectionDescription::bound())80 })?;81 let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {82 error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())83 })?;84 let base_uri_value = base_uri85 .into_bytes()86 .try_into()87 .map_err(|_| error_field_too_long(stringify!(token_prefix), PropertyValue::bound()))?;88 Ok((caller, name, description, token_prefix, base_uri_value))89}9091fn make_data<T: Config>(92 name: CollectionName,93 mode: CollectionMode,94 description: CollectionDescription,95 token_prefix: CollectionTokenPrefix,96 base_uri_value: PropertyValue,97 add_properties: bool,98) -> Result<CreateCollectionData<T::AccountId>> {99 let mut properties = up_data_structs::CollectionPropertiesVec::default();100 let mut token_property_permissions =101 up_data_structs::CollectionPropertiesPermissionsVec::default();102103 token_property_permissions104 .try_push(up_data_structs::PropertyKeyPermission {105 key: key::url(),106 permission: up_data_structs::PropertyPermission {107 mutable: true,108 collection_admin: true,109 token_owner: false,110 },111 })112 .map_err(|e| Error::Revert(format!("{:?}", e)))?;113114 if add_properties {115 token_property_permissions116 .try_push(up_data_structs::PropertyKeyPermission {117 key: key::suffix(),118 permission: up_data_structs::PropertyPermission {119 mutable: true,120 collection_admin: true,121 token_owner: false,122 },123 })124 .map_err(|e| Error::Revert(format!("{:?}", e)))?;125126 properties127 .try_push(up_data_structs::Property {128 key: key::schema_name(),129 value: property_value::erc721(),130 })131 .map_err(|e| Error::Revert(format!("{:?}", e)))?;132133 properties134 .try_push(up_data_structs::Property {135 key: key::schema_version(),136 value: property_value::schema_version(),137 })138 .map_err(|e| Error::Revert(format!("{:?}", e)))?;139140 properties141 .try_push(up_data_structs::Property {142 key: key::erc721_metadata(),143 value: property_value::erc721_metadata_supported(),144 })145 .map_err(|e| Error::Revert(format!("{:?}", e)))?;146147 if !base_uri_value.is_empty() {148 properties149 .try_push(up_data_structs::Property {150 key: key::base_uri(),151 value: base_uri_value,152 })153 .map_err(|e| Error::Revert(format!("{:?}", e)))?;154 }155 }156157 let data = CreateCollectionData {158 name,159 mode,160 description,161 token_prefix,162 token_property_permissions,163 properties,164 ..Default::default()165 };166 Ok(data)167}168169fn create_refungible_collection_internal<170 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,171>(172 caller: caller,173 value: value,174 name: string,175 description: string,176 token_prefix: string,177 base_uri: string,178 add_properties: bool,179) -> Result<address> {180 let (caller, name, description, token_prefix, base_uri_value) =181 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;182 let data = make_data::<T>(183 name,184 CollectionMode::ReFungible,185 description,186 token_prefix,187 base_uri_value,188 add_properties,189 )?;190 check_sent_amount_equals_collection_creation_price::<T>(value)?;191 let collection_helpers_address =192 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());193194 let collection_id =195 T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)196 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;197 let address = pallet_common::eth::collection_id_to_address(collection_id);198 Ok(address)199}200201fn check_sent_amount_equals_collection_creation_price<T: Config>(value: value) -> Result<()> {202 let value = value.as_u128();203 let creation_price: u128 = T::CollectionCreationPrice::get()204 .try_into()205 .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait206 .expect("Collection creation price should be convertible to u128");207 if value != creation_price {208 return Err(format!(209 "Sent amount not equals to collection creation price ({0})",210 creation_price211 )212 .into());213 }214 Ok(())215}216217/// @title Contract, which allows users to operate with collections218#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]219impl<T> EvmCollectionHelpers<T>220where221 T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,222{223 /// Create an NFT collection224 /// @param name Name of the collection225 /// @param description Informative description of the collection226 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications227 /// @return address Address of the newly created collection228 #[weight(<SelfWeightOf<T>>::create_collection())]229 #[solidity(rename_selector = "createNFTCollection")]230 fn create_nft_collection(231 &mut self,232 caller: caller,233 value: value,234 name: string,235 description: string,236 token_prefix: string,237 ) -> Result<address> {238 let (caller, name, description, token_prefix, _base_uri_value) =239 convert_data::<T>(caller, name, description, token_prefix, "".into())?;240 let data = make_data::<T>(241 name,242 CollectionMode::NFT,243 description,244 token_prefix,245 Default::default(),246 false,247 )?;248 check_sent_amount_equals_collection_creation_price::<T>(value)?;249 let collection_helpers_address =250 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());251 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)252 .map_err(dispatch_to_evm::<T>)?;253254 let address = pallet_common::eth::collection_id_to_address(collection_id);255 Ok(address)256 }257 /// Create an NFT collection258 /// @param name Name of the collection259 /// @param description Informative description of the collection260 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications261 /// @return address Address of the newly created collection262 #[weight(<SelfWeightOf<T>>::create_collection())]263 #[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]264 fn create_nonfungible_collection(265 &mut self,266 caller: caller,267 value: value,268 name: string,269 description: string,270 token_prefix: string,271 ) -> Result<address> {272 self.create_nft_collection(caller, value, name, description, token_prefix)273 }274275 #[weight(<SelfWeightOf<T>>::create_collection())]276 #[solidity(rename_selector = "createERC721MetadataCompatibleNFTCollection")]277 fn create_nonfungible_collection_with_properties(278 &mut self,279 caller: caller,280 value: value,281 name: string,282 description: string,283 token_prefix: string,284 base_uri: string,285 ) -> Result<address> {286 let (caller, name, description, token_prefix, base_uri_value) =287 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;288 let data = make_data::<T>(289 name,290 CollectionMode::NFT,291 description,292 token_prefix,293 base_uri_value,294 true,295 )?;296 check_sent_amount_equals_collection_creation_price::<T>(value)?;297 let collection_helpers_address =298 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());299 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)300 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;301302 let address = pallet_common::eth::collection_id_to_address(collection_id);303 Ok(address)304 }305306 #[weight(<SelfWeightOf<T>>::create_collection())]307 #[solidity(rename_selector = "createRFTCollection")]308 fn create_rft_collection(309 &mut self,310 caller: caller,311 value: value,312 name: string,313 description: string,314 token_prefix: string,315 ) -> Result<address> {316 create_refungible_collection_internal::<T>(317 caller,318 value,319 name,320 description,321 token_prefix,322 Default::default(),323 false,324 )325 }326327 #[weight(<SelfWeightOf<T>>::create_collection())]328 #[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]329 fn create_refungible_collection_with_properties(330 &mut self,331 caller: caller,332 value: value,333 name: string,334 description: string,335 token_prefix: string,336 base_uri: string,337 ) -> Result<address> {338 create_refungible_collection_internal::<T>(339 caller,340 value,341 name,342 description,343 token_prefix,344 base_uri,345 true,346 )347 }348349 /// Check if a collection exists350 /// @param collectionAddress Address of the collection in question351 /// @return bool Does the collection exist?352 fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {353 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {354 let collection_id = id;355 return Ok(<CollectionById<T>>::contains_key(collection_id));356 }357358 Ok(false)359 }360361 fn collection_creation_fee(&self) -> Result<value> {362 let price: u128 = T::CollectionCreationPrice::get()363 .try_into()364 .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait365 .expect("Collection creation price should be convertible to u128");366 Ok(price.into())367 }368}369370/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]371pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);372impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>373 for CollectionHelpersOnMethodCall<T>374{375 fn is_reserved(contract: &sp_core::H160) -> bool {376 contract == &T::ContractAddress::get()377 }378379 fn is_used(contract: &sp_core::H160) -> bool {380 contract == &T::ContractAddress::get()381 }382383 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {384 if handle.code_address() != T::ContractAddress::get() {385 return None;386 }387388 let helpers =389 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));390 pallet_evm_coder_substrate::call(handle, helpers)391 }392393 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {394 (contract == &T::ContractAddress::get())395 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())396 }397}398399generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);400generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);401402fn error_field_too_long(feild: &str, bound: usize) -> Error {403 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))404}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.1819use core::marker::PhantomData;20use ethereum as _;21use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};22use frame_support::traits::Get;23use pallet_common::{24 CollectionById,25 dispatch::CollectionDispatch,26 erc::{27 CollectionHelpersEvents,28 static_property::{key, value as property_value},29 },30};31use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};32use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};33use sp_std::vec;34use up_data_structs::{35 CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,36 CollectionMode, PropertyValue,37};3839use crate::{Config, SelfWeightOf, weights::WeightInfo};4041use sp_std::vec::Vec;42use alloc::format;4344/// See [`CollectionHelpersCall`]45pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);46impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {47 fn recorder(&self) -> &SubstrateRecorder<T> {48 &self.049 }5051 fn into_recorder(self) -> SubstrateRecorder<T> {52 self.053 }54}5556fn convert_data<T: Config>(57 caller: caller,58 name: string,59 description: string,60 token_prefix: string,61 base_uri: string,62) -> Result<(63 T::CrossAccountId,64 CollectionName,65 CollectionDescription,66 CollectionTokenPrefix,67 PropertyValue,68)> {69 let caller = T::CrossAccountId::from_eth(caller);70 let name = name71 .encode_utf16()72 .collect::<Vec<u16>>()73 .try_into()74 .map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;75 let description = description76 .encode_utf16()77 .collect::<Vec<u16>>()78 .try_into()79 .map_err(|_| {80 error_field_too_long(stringify!(description), CollectionDescription::bound())81 })?;82 let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {83 error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())84 })?;85 let base_uri_value = base_uri86 .into_bytes()87 .try_into()88 .map_err(|_| error_field_too_long(stringify!(token_prefix), PropertyValue::bound()))?;89 Ok((caller, name, description, token_prefix, base_uri_value))90}9192fn make_data<T: Config>(93 name: CollectionName,94 mode: CollectionMode,95 description: CollectionDescription,96 token_prefix: CollectionTokenPrefix,97 base_uri_value: PropertyValue,98 add_properties: bool,99) -> Result<CreateCollectionData<T::AccountId>> {100 let token_property_permissions = if add_properties {101 vec![102 up_data_structs::PropertyKeyPermission {103 key: key::url(),104 permission: up_data_structs::PropertyPermission {105 mutable: true,106 collection_admin: true,107 token_owner: false,108 },109 },110 up_data_structs::PropertyKeyPermission {111 key: key::suffix(),112 permission: up_data_structs::PropertyPermission {113 mutable: true,114 collection_admin: true,115 token_owner: false,116 },117 },118 ]119 .try_into()120 .map_err(|e| Error::Revert(format!("{:?}", e)))?121 } else {122 up_data_structs::CollectionPropertiesPermissionsVec::default()123 };124 let properties = if add_properties {125 let mut properties = vec![126 up_data_structs::Property {127 key: key::schema_name(),128 value: property_value::erc721(),129 },130 up_data_structs::Property {131 key: key::schema_version(),132 value: property_value::schema_version(),133 },134 up_data_structs::Property {135 key: key::erc721_metadata(),136 value: property_value::erc721_metadata_supported(),137 },138 ];139 if !base_uri_value.is_empty() {140 properties.push(up_data_structs::Property {141 key: key::base_uri(),142 value: base_uri_value,143 })144 }145 properties146 .try_into()147 .map_err(|e| Error::Revert(format!("{:?}", e)))?148 } else {149 up_data_structs::CollectionPropertiesVec::default()150 };151152 let data = CreateCollectionData {153 name,154 mode,155 description,156 token_prefix,157 token_property_permissions,158 properties,159 ..Default::default()160 };161 Ok(data)162}163164fn create_refungible_collection_internal<165 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,166>(167 caller: caller,168 value: value,169 name: string,170 description: string,171 token_prefix: string,172 base_uri: string,173 add_properties: bool,174) -> Result<address> {175 let (caller, name, description, token_prefix, base_uri_value) =176 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;177 let data = make_data::<T>(178 name,179 CollectionMode::ReFungible,180 description,181 token_prefix,182 base_uri_value,183 add_properties,184 )?;185 check_sent_amount_equals_collection_creation_price::<T>(value)?;186 let collection_helpers_address =187 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());188189 let collection_id =190 T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)191 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;192 let address = pallet_common::eth::collection_id_to_address(collection_id);193 Ok(address)194}195196fn check_sent_amount_equals_collection_creation_price<T: Config>(value: value) -> Result<()> {197 let value = value.as_u128();198 let creation_price: u128 = T::CollectionCreationPrice::get()199 .try_into()200 .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait201 .expect("Collection creation price should be convertible to u128");202 if value != creation_price {203 return Err(format!(204 "Sent amount not equals to collection creation price ({0})",205 creation_price206 )207 .into());208 }209 Ok(())210}211212/// @title Contract, which allows users to operate with collections213#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]214impl<T> EvmCollectionHelpers<T>215where216 T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,217{218 /// Create an NFT collection219 /// @param name Name of the collection220 /// @param description Informative description of the collection221 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications222 /// @return address Address of the newly created collection223 #[weight(<SelfWeightOf<T>>::create_collection())]224 #[solidity(rename_selector = "createNFTCollection")]225 fn create_nft_collection(226 &mut self,227 caller: caller,228 value: value,229 name: string,230 description: string,231 token_prefix: string,232 ) -> Result<address> {233 let (caller, name, description, token_prefix, _base_uri_value) =234 convert_data::<T>(caller, name, description, token_prefix, "".into())?;235 let data = make_data::<T>(236 name,237 CollectionMode::NFT,238 description,239 token_prefix,240 Default::default(),241 false,242 )?;243 check_sent_amount_equals_collection_creation_price::<T>(value)?;244 let collection_helpers_address =245 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());246 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)247 .map_err(dispatch_to_evm::<T>)?;248249 let address = pallet_common::eth::collection_id_to_address(collection_id);250 Ok(address)251 }252 /// 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 #[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]259 fn create_nonfungible_collection(260 &mut self,261 caller: caller,262 value: value,263 name: string,264 description: string,265 token_prefix: string,266 ) -> Result<address> {267 self.create_nft_collection(caller, value, name, description, token_prefix)268 }269270 #[weight(<SelfWeightOf<T>>::create_collection())]271 #[solidity(rename_selector = "createERC721MetadataCompatibleNFTCollection")]272 fn create_nonfungible_collection_with_properties(273 &mut self,274 caller: caller,275 value: value,276 name: string,277 description: string,278 token_prefix: string,279 base_uri: string,280 ) -> Result<address> {281 let (caller, name, description, token_prefix, base_uri_value) =282 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;283 let data = make_data::<T>(284 name,285 CollectionMode::NFT,286 description,287 token_prefix,288 base_uri_value,289 true,290 )?;291 check_sent_amount_equals_collection_creation_price::<T>(value)?;292 let collection_helpers_address =293 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());294 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)295 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;296297 let address = pallet_common::eth::collection_id_to_address(collection_id);298 Ok(address)299 }300301 #[weight(<SelfWeightOf<T>>::create_collection())]302 #[solidity(rename_selector = "createRFTCollection")]303 fn create_rft_collection(304 &mut self,305 caller: caller,306 value: value,307 name: string,308 description: string,309 token_prefix: string,310 ) -> Result<address> {311 create_refungible_collection_internal::<T>(312 caller,313 value,314 name,315 description,316 token_prefix,317 Default::default(),318 false,319 )320 }321322 #[weight(<SelfWeightOf<T>>::create_collection())]323 #[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]324 fn create_refungible_collection_with_properties(325 &mut self,326 caller: caller,327 value: value,328 name: string,329 description: string,330 token_prefix: string,331 base_uri: string,332 ) -> Result<address> {333 create_refungible_collection_internal::<T>(334 caller,335 value,336 name,337 description,338 token_prefix,339 base_uri,340 true,341 )342 }343344 /// Check if a collection exists345 /// @param collectionAddress Address of the collection in question346 /// @return bool Does the collection exist?347 fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {348 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {349 let collection_id = id;350 return Ok(<CollectionById<T>>::contains_key(collection_id));351 }352353 Ok(false)354 }355356 fn collection_creation_fee(&self) -> Result<value> {357 let price: u128 = T::CollectionCreationPrice::get()358 .try_into()359 .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait360 .expect("Collection creation price should be convertible to u128");361 Ok(price.into())362 }363}364365/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]366pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);367impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>368 for CollectionHelpersOnMethodCall<T>369{370 fn is_reserved(contract: &sp_core::H160) -> bool {371 contract == &T::ContractAddress::get()372 }373374 fn is_used(contract: &sp_core::H160) -> bool {375 contract == &T::ContractAddress::get()376 }377378 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {379 if handle.code_address() != T::ContractAddress::get() {380 return None;381 }382383 let helpers =384 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));385 pallet_evm_coder_substrate::call(handle, helpers)386 }387388 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {389 (contract == &T::ContractAddress::get())390 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())391 }392}393394generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);395generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);396397fn error_field_too_long(feild: &str, bound: usize) -> Error {398 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))399}tests/src/eth/api/UniqueRFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRFT.sol
+++ /dev/null
@@ -1,163 +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: 7d9262e6
-interface Collection is Dummy, ERC165 {
- // Set collection property.
- //
- // @param key Property key.
- // @param value Propery value.
- //
- // Selector: setCollectionProperty(string,bytes) 2f073f66
- function setCollectionProperty(string memory key, bytes memory value)
- external;
-
- // Delete collection property.
- //
- // @param key Property key.
- //
- // Selector: deleteCollectionProperty(string) 7b7debce
- function deleteCollectionProperty(string memory key) external;
-
- // Get collection property.
- //
- // @dev Throws error if key not found.
- //
- // @param key Property key.
- // @return bytes The property corresponding to the key.
- //
- // Selector: collectionProperty(string) cf24fd6d
- function collectionProperty(string memory key)
- external
- view
- returns (bytes memory);
-
- // Set the sponsor of the collection.
- //
- // @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
- //
- // @param sponsor Address of the sponsor from whose account funds will be debited for operations with the contract.
- //
- // Selector: setCollectionSponsor(address) 7623402e
- function setCollectionSponsor(address sponsor) external;
-
- // Collection sponsorship confirmation.
- //
- // @dev After setting the sponsor for the collection, it must be confirmed with this function.
- //
- // Selector: confirmCollectionSponsorship() 3c50e97a
- function confirmCollectionSponsorship() external;
-
- // Set limits for the collection.
- // @dev Throws error if limit not found.
- // @param limit Name of the limit. Valid names:
- // "accountTokenOwnershipLimit",
- // "sponsoredDataSize",
- // "sponsoredDataRateLimit",
- // "tokenLimit",
- // "sponsorTransferTimeout",
- // "sponsorApproveTimeout"
- // @param value Value of the limit.
- //
- // Selector: setCollectionLimit(string,uint32) 6a3841db
- function setCollectionLimit(string memory limit, uint32 value) external;
-
- // Set limits for the collection.
- // @dev Throws error if limit not found.
- // @param limit Name of the limit. Valid names:
- // "ownerCanTransfer",
- // "ownerCanDestroy",
- // "transfersEnabled"
- // @param value Value of the limit.
- //
- // Selector: setCollectionLimit(string,bool) 993b7fba
- function setCollectionLimit(string memory limit, bool value) external;
-
- // Get contract address.
- //
- // Selector: contractAddress() f6b4dfb4
- function contractAddress() external view returns (address);
-
- // Add collection admin by substrate address.
- // @param new_admin Substrate administrator address.
- //
- // Selector: addCollectionAdminSubstrate(uint256) 5730062b
- function addCollectionAdminSubstrate(uint256 newAdmin) external;
-
- // Remove collection admin by substrate address.
- // @param admin Substrate administrator address.
- //
- // Selector: removeCollectionAdminSubstrate(uint256) 4048fcf9
- function removeCollectionAdminSubstrate(uint256 admin) external;
-
- // Add collection admin.
- // @param new_admin Address of the added administrator.
- //
- // Selector: addCollectionAdmin(address) 92e462c7
- function addCollectionAdmin(address newAdmin) external;
-
- // Remove collection admin.
- //
- // @param new_admin Address of the removed administrator.
- //
- // Selector: removeCollectionAdmin(address) fafd7b42
- function removeCollectionAdmin(address admin) external;
-
- // Toggle accessibility of collection nesting.
- //
- // @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
- //
- // Selector: setCollectionNesting(bool) 112d4586
- function setCollectionNesting(bool enable) external;
-
- // Toggle accessibility of collection nesting.
- //
- // @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
- // @param collections Addresses of collections that will be available for nesting.
- //
- // Selector: setCollectionNesting(bool,address[]) 64872396
- function setCollectionNesting(bool enable, address[] memory collections)
- external;
-
- // Set the collection access method.
- // @param mode Access mode
- // 0 for Normal
- // 1 for AllowList
- //
- // Selector: setCollectionAccess(uint8) 41835d4c
- function setCollectionAccess(uint8 mode) external;
-
- // Add the user to the allowed list.
- //
- // @param user Address of a trusted user.
- //
- // Selector: addToCollectionAllowList(address) 67844fe6
- function addToCollectionAllowList(address user) external;
-
- // Remove the user from the allowed list.
- //
- // @param user Address of a removed user.
- //
- // Selector: removeFromCollectionAllowList(address) 85c51acb
- function removeFromCollectionAllowList(address user) external;
-
- // Switch permission for minting.
- //
- // @param mode Enable if "true".
- //
- // Selector: setCollectionMintMode(bool) 00018e84
- function setCollectionMintMode(bool mode) external;
-}
-
-interface UniqueRFT is Dummy, ERC165, Collection {}
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -49,6 +49,46 @@
expect(data.description).to.be.eq(description);
expect(data.raw.tokenPrefix).to.be.eq(prefix);
expect(data.raw.mode).to.be.eq('NFT');
+
+ const options = await collection.getOptions();
+
+ expect(options.tokenPropertyPermissions).to.be.empty;
+ });
+
+ itEth('Create collection with properties', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const name = 'CollectionEVM';
+ const description = 'Some description';
+ const prefix = 'token prefix';
+ const baseUri = 'BaseURI';
+
+ // todo:playgrounds this might fail when in async environment.
+ const collectionCountBefore = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
+ const {collectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, name, description, prefix, baseUri);
+ const collectionCountAfter = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
+
+ const collection = helper.nft.getCollectionObject(collectionId);
+ const data = (await collection.getData())!;
+
+ expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
+ expect(collectionId).to.be.eq(collectionCountAfter);
+ expect(data.name).to.be.eq(name);
+ expect(data.description).to.be.eq(description);
+ expect(data.raw.tokenPrefix).to.be.eq(prefix);
+ expect(data.raw.mode).to.be.eq('NFT');
+
+ const options = await collection.getOptions();
+ expect(options.tokenPropertyPermissions).to.be.deep.equal([
+ {
+ key: 'URI',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ {
+ key: 'URISuffix',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ ]);
});
// todo:playgrounds this test will fail when in async environment.
tests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -42,7 +42,8 @@
const {collectionId} = await helper.eth.createRFTCollection(owner, name, description, prefix);
const collectionCountAfter = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
- const data = (await helper.rft.getData(collectionId))!;
+ const collection = helper.rft.getCollectionObject(collectionId);
+ const data = (await collection.getData())!;
expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
expect(collectionId).to.be.eq(collectionCountAfter);
@@ -50,6 +51,48 @@
expect(data.description).to.be.eq(description);
expect(data.raw.tokenPrefix).to.be.eq(prefix);
expect(data.raw.mode).to.be.eq('ReFungible');
+
+ const options = await collection.getOptions();
+
+ expect(options.tokenPropertyPermissions).to.be.empty;
+ });
+
+
+
+ itEth('Create collection with properties', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const name = 'CollectionEVM';
+ const description = 'Some description';
+ const prefix = 'token prefix';
+ const baseUri = 'BaseURI';
+
+ // todo:playgrounds this might fail when in async environment.
+ const collectionCountBefore = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
+ const {collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, name, description, prefix, baseUri);
+ const collectionCountAfter = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
+
+ const collection = helper.rft.getCollectionObject(collectionId);
+ const data = (await collection.getData())!;
+
+ expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
+ expect(collectionId).to.be.eq(collectionCountAfter);
+ expect(data.name).to.be.eq(name);
+ expect(data.description).to.be.eq(description);
+ expect(data.raw.tokenPrefix).to.be.eq(prefix);
+ expect(data.raw.mode).to.be.eq('ReFungible');
+
+ const options = await collection.getOptions();
+ expect(options.tokenPropertyPermissions).to.be.deep.equal([
+ {
+ key: 'URI',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ {
+ key: 'URISuffix',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ ]);
});
// todo:playgrounds this test will fail when in async environment.