difftreelog
feat updates for createERC721MetadataCompatibleCollections
in: master
13 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -665,6 +665,11 @@
property_key_from_bytes(b"schemaName").expect(EXPECT_CONVERT_ERROR)
}
+ /// Key "schemaVersion".
+ pub fn schema_version() -> up_data_structs::PropertyKey {
+ property_key_from_bytes(b"schemaVersion").expect(EXPECT_CONVERT_ERROR)
+ }
+
/// Key "baseURI".
pub fn base_uri() -> up_data_structs::PropertyKey {
property_key_from_bytes(b"baseURI").expect(EXPECT_CONVERT_ERROR)
@@ -672,12 +677,12 @@
/// Key "url".
pub fn url() -> up_data_structs::PropertyKey {
- property_key_from_bytes(b"url").expect(EXPECT_CONVERT_ERROR)
+ property_key_from_bytes(b"URI").expect(EXPECT_CONVERT_ERROR)
}
/// Key "suffix".
pub fn suffix() -> up_data_structs::PropertyKey {
- property_key_from_bytes(b"suffix").expect(EXPECT_CONVERT_ERROR)
+ property_key_from_bytes(b"URISuffix").expect(EXPECT_CONVERT_ERROR)
}
/// Key "parentNft".
@@ -685,7 +690,7 @@
property_key_from_bytes(b"parentNft").expect(EXPECT_CONVERT_ERROR)
}
- /// Key "parentNft".
+ /// Key "ERC721Metadata".
pub fn erc721_metadata() -> up_data_structs::PropertyKey {
property_key_from_bytes(b"ERC721Metadata").expect(EXPECT_CONVERT_ERROR)
}
@@ -695,6 +700,9 @@
pub mod value {
use super::*;
+ /// Value "Schema version".
+ pub const SCHEMA_VERSION: &[u8] = b"1.0.0";
+
/// Value "ERC721Metadata".
pub const ERC721_METADATA: &[u8] = b"ERC721Metadata";
@@ -709,7 +717,12 @@
property_value_from_bytes(ERC721_METADATA).expect(EXPECT_CONVERT_ERROR)
}
- /// Value for [`ERC721_METADATA`].
+ /// Value for [`SCHEMA_VERSION`].
+ pub fn schema_version() -> up_data_structs::PropertyValue {
+ property_value_from_bytes(SCHEMA_VERSION).expect(EXPECT_CONVERT_ERROR)
+ }
+
+ /// Value for [`ERC721_METADATA_SUPPORTED`].
pub fn erc721_metadata_supported() -> up_data_structs::PropertyValue {
property_value_from_bytes(ERC721_METADATA_SUPPORTED).expect(EXPECT_CONVERT_ERROR)
}
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: false,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: false,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::erc721_metadata(),136 value: property_value::erc721_metadata_supported(),137 })138 .map_err(|e| Error::Revert(format!("{:?}", e)))?;139140 if !base_uri_value.is_empty() {141 properties142 .try_push(up_data_structs::Property {143 key: key::base_uri(),144 value: base_uri_value,145 })146 .map_err(|e| Error::Revert(format!("{:?}", e)))?;147 }148 }149150 let data = CreateCollectionData {151 name,152 mode,153 description,154 token_prefix,155 token_property_permissions,156 properties,157 ..Default::default()158 };159 Ok(data)160}161162fn create_refungible_collection_internal<163 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,164>(165 caller: caller,166 value: value,167 name: string,168 description: string,169 token_prefix: string,170 base_uri: string,171 add_properties: bool,172) -> Result<address> {173 let (caller, name, description, token_prefix, base_uri_value) =174 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;175 let data = make_data::<T>(176 name,177 CollectionMode::ReFungible,178 description,179 token_prefix,180 base_uri_value,181 add_properties,182 )?;183 check_sent_amount_equals_collection_creation_price::<T>(value)?;184 let collection_helpers_address =185 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());186187 let collection_id =188 T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)189 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;190 let address = pallet_common::eth::collection_id_to_address(collection_id);191 Ok(address)192}193194fn check_sent_amount_equals_collection_creation_price<T: Config>(value: value) -> Result<()> {195 let value = value.as_u128();196 let creation_price: u128 = T::CollectionCreationPrice::get()197 .try_into()198 .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait199 .expect("Collection creation price should be convertible to u128");200 if value != creation_price {201 return Err(format!(202 "Sent amount not equals to collection creation price ({0})",203 creation_price204 )205 .into());206 }207 Ok(())208}209210/// @title Contract, which allows users to operate with collections211#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]212impl<T> EvmCollectionHelpers<T>213where214 T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,215{216 /// Create an NFT collection217 /// @param name Name of the collection218 /// @param description Informative description of the collection219 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications220 /// @return address Address of the newly created collection221 #[weight(<SelfWeightOf<T>>::create_collection())]222 #[solidity(rename_selector = "createNFTCollection")]223 fn create_nft_collection(224 &mut self,225 caller: caller,226 value: value,227 name: string,228 description: string,229 token_prefix: string,230 ) -> Result<address> {231 let (caller, name, description, token_prefix, _base_uri_value) =232 convert_data::<T>(caller, name, description, token_prefix, "".into())?;233 let data = make_data::<T>(234 name,235 CollectionMode::NFT,236 description,237 token_prefix,238 Default::default(),239 false,240 )?;241 check_sent_amount_equals_collection_creation_price::<T>(value)?;242 let collection_helpers_address =243 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());244 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)245 .map_err(dispatch_to_evm::<T>)?;246247 let address = pallet_common::eth::collection_id_to_address(collection_id);248 Ok(address)249 }250 /// 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 #[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]257 fn create_nonfungible_collection(258 &mut self,259 caller: caller,260 value: value,261 name: string,262 description: string,263 token_prefix: string,264 ) -> Result<address> {265 self.create_nft_collection(caller, value, name, description, token_prefix)266 }267268 #[weight(<SelfWeightOf<T>>::create_collection())]269 #[solidity(rename_selector = "createERC721MetadataNFTCollection")]270 fn create_nonfungible_collection_with_properties(271 &mut self,272 caller: caller,273 value: value,274 name: string,275 description: string,276 token_prefix: string,277 base_uri: string,278 ) -> Result<address> {279 let (caller, name, description, token_prefix, base_uri_value) =280 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;281 let data = make_data::<T>(282 name,283 CollectionMode::NFT,284 description,285 token_prefix,286 base_uri_value,287 true,288 )?;289 check_sent_amount_equals_collection_creation_price::<T>(value)?;290 let collection_helpers_address =291 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());292 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)293 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;294295 let address = pallet_common::eth::collection_id_to_address(collection_id);296 Ok(address)297 }298299 #[weight(<SelfWeightOf<T>>::create_collection())]300 #[solidity(rename_selector = "createRFTCollection")]301 fn create_rft_collection(302 &mut self,303 caller: caller,304 value: value,305 name: string,306 description: string,307 token_prefix: string,308 ) -> Result<address> {309 create_refungible_collection_internal::<T>(310 caller,311 value,312 name,313 description,314 token_prefix,315 Default::default(),316 false,317 )318 }319320 #[weight(<SelfWeightOf<T>>::create_collection())]321 #[deprecated(note = "mathod was renamed to `create_rft_collection`, prefer it instead")]322 fn create_refungible_collection(323 &mut self,324 caller: caller,325 value: value,326 name: string,327 description: string,328 token_prefix: string,329 ) -> Result<address> {330 create_refungible_collection_internal::<T>(331 caller,332 value,333 name,334 description,335 token_prefix,336 Default::default(),337 false,338 )339 }340341 #[weight(<SelfWeightOf<T>>::create_collection())]342 #[solidity(rename_selector = "createERC721MetadataRFTCollection")]343 fn create_refungible_collection_with_properties(344 &mut self,345 caller: caller,346 value: value,347 name: string,348 description: string,349 token_prefix: string,350 base_uri: string,351 ) -> Result<address> {352 create_refungible_collection_internal::<T>(353 caller,354 value,355 name,356 description,357 token_prefix,358 base_uri,359 true,360 )361 }362363 /// Check if a collection exists364 /// @param collectionAddress Address of the collection in question365 /// @return bool Does the collection exist?366 fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {367 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {368 let collection_id = id;369 return Ok(<CollectionById<T>>::contains_key(collection_id));370 }371372 Ok(false)373 }374375 fn collection_creation_fee(&self) -> Result<value> {376 let price: u128 = T::CollectionCreationPrice::get()377 .try_into()378 .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait379 .expect("Collection creation price should be convertible to u128");380 Ok(price.into())381 }382}383384/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]385pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);386impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>387 for CollectionHelpersOnMethodCall<T>388{389 fn is_reserved(contract: &sp_core::H160) -> bool {390 contract == &T::ContractAddress::get()391 }392393 fn is_used(contract: &sp_core::H160) -> bool {394 contract == &T::ContractAddress::get()395 }396397 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {398 if handle.code_address() != T::ContractAddress::get() {399 return None;400 }401402 let helpers =403 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));404 pallet_evm_coder_substrate::call(handle, helpers)405 }406407 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {408 (contract == &T::ContractAddress::get())409 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())410 }411}412413generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);414generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);415416fn error_field_too_long(feild: &str, bound: usize) -> Error {417 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))418}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 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: false,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 token_property_permissions127 .try_push(up_data_structs::PropertyKeyPermission {128 key: key::url(),129 permission: up_data_structs::PropertyPermission {130 mutable: true,131 collection_admin: true,132 token_owner: false,133 },134 })135 .map_err(|e| Error::Revert(format!("{:?}", e)))?;136137 properties138 .try_push(up_data_structs::Property {139 key: key::schema_name(),140 value: property_value::erc721(),141 })142 .map_err(|e| Error::Revert(format!("{:?}", e)))?;143 144 properties145 .try_push(up_data_structs::Property {146 key: key::schema_version(),147 value: property_value::schema_version(),148 })149 .map_err(|e| Error::Revert(format!("{:?}", e)))?;150151 properties152 .try_push(up_data_structs::Property {153 key: key::erc721_metadata(),154 value: property_value::erc721_metadata_supported(),155 })156 .map_err(|e| Error::Revert(format!("{:?}", e)))?;157158 if !base_uri_value.is_empty() {159 properties160 .try_push(up_data_structs::Property {161 key: key::base_uri(),162 value: base_uri_value,163 })164 .map_err(|e| Error::Revert(format!("{:?}", e)))?;165 }166 }167168 let data = CreateCollectionData {169 name,170 mode,171 description,172 token_prefix,173 token_property_permissions,174 properties,175 ..Default::default()176 };177 Ok(data)178}179180fn create_refungible_collection_internal<181 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,182>(183 caller: caller,184 value: value,185 name: string,186 description: string,187 token_prefix: string,188 base_uri: string,189 add_properties: bool,190) -> Result<address> {191 let (caller, name, description, token_prefix, base_uri_value) =192 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;193 let data = make_data::<T>(194 name,195 CollectionMode::ReFungible,196 description,197 token_prefix,198 base_uri_value,199 add_properties,200 )?;201 check_sent_amount_equals_collection_creation_price::<T>(value)?;202 let collection_helpers_address =203 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());204205 let collection_id =206 T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)207 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;208 let address = pallet_common::eth::collection_id_to_address(collection_id);209 Ok(address)210}211212fn check_sent_amount_equals_collection_creation_price<T: Config>(value: value) -> Result<()> {213 let value = value.as_u128();214 let creation_price: u128 = T::CollectionCreationPrice::get()215 .try_into()216 .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait217 .expect("Collection creation price should be convertible to u128");218 if value != creation_price {219 return Err(format!(220 "Sent amount not equals to collection creation price ({0})",221 creation_price222 )223 .into());224 }225 Ok(())226}227228/// @title Contract, which allows users to operate with collections229#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]230impl<T> EvmCollectionHelpers<T>231where232 T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,233{234 /// Create an NFT collection235 /// @param name Name of the collection236 /// @param description Informative description of the collection237 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications238 /// @return address Address of the newly created collection239 #[weight(<SelfWeightOf<T>>::create_collection())]240 #[solidity(rename_selector = "createNFTCollection")]241 fn create_nft_collection(242 &mut self,243 caller: caller,244 value: value,245 name: string,246 description: string,247 token_prefix: string,248 ) -> Result<address> {249 let (caller, name, description, token_prefix, _base_uri_value) =250 convert_data::<T>(caller, name, description, token_prefix, "".into())?;251 let data = make_data::<T>(252 name,253 CollectionMode::NFT,254 description,255 token_prefix,256 Default::default(),257 false,258 )?;259 check_sent_amount_equals_collection_creation_price::<T>(value)?;260 let collection_helpers_address =261 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());262 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)263 .map_err(dispatch_to_evm::<T>)?;264265 let address = pallet_common::eth::collection_id_to_address(collection_id);266 Ok(address)267 }268 /// Create an NFT collection269 /// @param name Name of the collection270 /// @param description Informative description of the collection271 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications272 /// @return address Address of the newly created collection273 #[weight(<SelfWeightOf<T>>::create_collection())]274 #[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]275 fn create_nonfungible_collection(276 &mut self,277 caller: caller,278 value: value,279 name: string,280 description: string,281 token_prefix: string,282 ) -> Result<address> {283 self.create_nft_collection(caller, value, name, description, token_prefix)284 }285286 #[weight(<SelfWeightOf<T>>::create_collection())]287 #[solidity(rename_selector = "createERC721MetadataCompatibleNFTCollection")]288 fn create_nonfungible_collection_with_properties(289 &mut self,290 caller: caller,291 value: value,292 name: string,293 description: string,294 token_prefix: string,295 base_uri: string,296 ) -> Result<address> {297 let (caller, name, description, token_prefix, base_uri_value) =298 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;299 let data = make_data::<T>(300 name,301 CollectionMode::NFT,302 description,303 token_prefix,304 base_uri_value,305 true,306 )?;307 check_sent_amount_equals_collection_creation_price::<T>(value)?;308 let collection_helpers_address =309 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());310 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)311 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;312313 let address = pallet_common::eth::collection_id_to_address(collection_id);314 Ok(address)315 }316317 #[weight(<SelfWeightOf<T>>::create_collection())]318 #[solidity(rename_selector = "createRFTCollection")]319 fn create_rft_collection(320 &mut self,321 caller: caller,322 value: value,323 name: string,324 description: string,325 token_prefix: string,326 ) -> Result<address> {327 create_refungible_collection_internal::<T>(328 caller,329 value,330 name,331 description,332 token_prefix,333 Default::default(),334 false,335 )336 }337338 #[weight(<SelfWeightOf<T>>::create_collection())]339 #[deprecated(note = "mathod was renamed to `create_rft_collection`, prefer it instead")]340 fn create_refungible_collection(341 &mut self,342 caller: caller,343 value: value,344 name: string,345 description: string,346 token_prefix: string,347 ) -> Result<address> {348 create_refungible_collection_internal::<T>(349 caller,350 value,351 name,352 description,353 token_prefix,354 Default::default(),355 false,356 )357 }358359 #[weight(<SelfWeightOf<T>>::create_collection())]360 #[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]361 fn create_refungible_collection_with_properties(362 &mut self,363 caller: caller,364 value: value,365 name: string,366 description: string,367 token_prefix: string,368 base_uri: string,369 ) -> Result<address> {370 create_refungible_collection_internal::<T>(371 caller,372 value,373 name,374 description,375 token_prefix,376 base_uri,377 true,378 )379 }380381 /// Check if a collection exists382 /// @param collectionAddress Address of the collection in question383 /// @return bool Does the collection exist?384 fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {385 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {386 let collection_id = id;387 return Ok(<CollectionById<T>>::contains_key(collection_id));388 }389390 Ok(false)391 }392393 fn collection_creation_fee(&self) -> Result<value> {394 let price: u128 = T::CollectionCreationPrice::get()395 .try_into()396 .map_err(|_| ()) // workaround for `expect` requiring `Debug` trait397 .expect("Collection creation price should be convertible to u128");398 Ok(price.into())399 }400}401402/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]403pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);404impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>405 for CollectionHelpersOnMethodCall<T>406{407 fn is_reserved(contract: &sp_core::H160) -> bool {408 contract == &T::ContractAddress::get()409 }410411 fn is_used(contract: &sp_core::H160) -> bool {412 contract == &T::ContractAddress::get()413 }414415 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {416 if handle.code_address() != T::ContractAddress::get() {417 return None;418 }419420 let helpers =421 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));422 pallet_evm_coder_substrate::call(handle, helpers)423 }424425 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {426 (contract == &T::ContractAddress::get())427 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())428 }429}430431generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);432generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);433434fn error_field_too_long(feild: &str, bound: usize) -> Error {435 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))436}pallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -23,7 +23,7 @@
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0xf62c7aa9
+/// @dev the ERC-165 identifier for this interface is 0x95eb98f4
contract CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
/// Create an NFT collection
/// @param name Name of the collection
@@ -65,9 +65,9 @@
return 0x0000000000000000000000000000000000000000;
}
- /// @dev EVM selector for this function is: 0xd1df968c,
- /// or in textual repr: createERC721MetadataNFTCollection(string,string,string,string)
- function createERC721MetadataNFTCollection(
+ /// @dev EVM selector for this function is: 0xa9e7b5c0,
+ /// or in textual repr: createERC721MetadataCompatibleNFTCollection(string,string,string,string)
+ function createERC721MetadataCompatibleNFTCollection(
string memory name,
string memory description,
string memory tokenPrefix,
@@ -112,9 +112,9 @@
return 0x0000000000000000000000000000000000000000;
}
- /// @dev EVM selector for this function is: 0xbea6a299,
- /// or in textual repr: createERC721MetadataRFTCollection(string,string,string,string)
- function createERC721MetadataRFTCollection(
+ /// @dev EVM selector for this function is: 0xa5596388,
+ /// or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
+ function createERC721MetadataCompatibleRFTCollection(
string memory name,
string memory description,
string memory tokenPrefix,
tests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -18,7 +18,7 @@
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0xf62c7aa9
+/// @dev the ERC-165 identifier for this interface is 0x95eb98f4
interface CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
/// Create an NFT collection
/// @param name Name of the collection
@@ -46,9 +46,9 @@
string memory tokenPrefix
) external payable returns (address);
- /// @dev EVM selector for this function is: 0xd1df968c,
- /// or in textual repr: createERC721MetadataNFTCollection(string,string,string,string)
- function createERC721MetadataNFTCollection(
+ /// @dev EVM selector for this function is: 0xa9e7b5c0,
+ /// or in textual repr: createERC721MetadataCompatibleNFTCollection(string,string,string,string)
+ function createERC721MetadataCompatibleNFTCollection(
string memory name,
string memory description,
string memory tokenPrefix,
@@ -71,9 +71,9 @@
string memory tokenPrefix
) external payable returns (address);
- /// @dev EVM selector for this function is: 0xbea6a299,
- /// or in textual repr: createERC721MetadataRFTCollection(string,string,string,string)
- function createERC721MetadataRFTCollection(
+ /// @dev EVM selector for this function is: 0xa5596388,
+ /// or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
+ function createERC721MetadataCompatibleRFTCollection(
string memory name,
string memory description,
string memory tokenPrefix,
tests/src/eth/collectionHelpersAbi.jsondiffbeforeafterboth--- a/tests/src/eth/collectionHelpersAbi.json
+++ b/tests/src/eth/collectionHelpersAbi.json
@@ -32,7 +32,7 @@
{ "internalType": "string", "name": "tokenPrefix", "type": "string" },
{ "internalType": "string", "name": "baseUri", "type": "string" }
],
- "name": "createERC721MetadataNFTCollection",
+ "name": "createERC721MetadataCompatibleNFTCollection",
"outputs": [{ "internalType": "address", "name": "", "type": "address" }],
"stateMutability": "payable",
"type": "function"
@@ -44,7 +44,7 @@
{ "internalType": "string", "name": "tokenPrefix", "type": "string" },
{ "internalType": "string", "name": "baseUri", "type": "string" }
],
- "name": "createERC721MetadataRFTCollection",
+ "name": "createERC721MetadataCompatibleRFTCollection",
"outputs": [{ "internalType": "address", "name": "", "type": "address" }],
"stateMutability": "payable",
"type": "function"
tests/src/eth/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionProperties.test.ts
+++ b/tests/src/eth/collectionProperties.test.ts
@@ -14,7 +14,7 @@
itEth('Can be set', async({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'name', description: 'test', tokenPrefix: 'test'});
+ const collection = await helper.nft.mintCollection(alice, {name: 'name', description: 'test', tokenPrefix: 'test', properties: []});
await collection.addAdmin(alice, {Ethereum: caller});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
@@ -24,7 +24,7 @@
const raw = (await collection.getData())?.raw;
- expect(raw.properties[1].value).to.equal('testValue');
+ expect(raw.properties[0].value).to.equal('testValue');
});
itEth('Can be deleted', async({helper}) => {
tests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -97,7 +97,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelpers.methods.createERC721MetadataNFTCollection('Sponsor collection', '1', '1', '').send({value: Number(2n * nominal)});
+ let result = await collectionHelpers.methods.createERC721MetadataCompatibleNFTCollection('Sponsor collection', '1', '1', '').send({value: Number(2n * nominal)});
const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
const collection = helper.nft.getCollectionObject(collectionId);
@@ -167,7 +167,7 @@
// itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {
// const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
// const collectionHelpers = evmCollectionHelpers(web3, owner);
- // const result = await collectionHelpers.methods.createERC721MetadataNFTCollection('Sponsor collection', '1', '1', '').send();
+ // const result = await collectionHelpers.methods.createERC721MetadataCompatibleNFTCollection('Sponsor collection', '1', '1', '').send();
// const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
// const sponsor = privateKeyWrapper('//Alice');
// const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
@@ -223,7 +223,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelpers.methods.createERC721MetadataNFTCollection('Sponsor collection', '1', '1', '').send({value: Number(2n * nominal)});
+ let result = await collectionHelpers.methods.createERC721MetadataCompatibleNFTCollection('Sponsor collection', '1', '1', '').send({value: Number(2n * nominal)});
const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
const collection = helper.nft.getCollectionObject(collectionId);
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -83,14 +83,12 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelper.methods.createERC721MetadataNFTCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
- const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', 'a', 'b', tokenPrefix);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const nextTokenId = await contract.methods.nextTokenId().call();
expect(nextTokenId).to.be.equal('1');
- result = await contract.methods.mint(
+ const result = await contract.methods.mint(
receiver,
nextTokenId,
).send();
@@ -115,7 +113,7 @@
});
itEth('TokenURI from url', async ({helper}) => {
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');
});
@@ -126,7 +124,7 @@
itEth('TokenURI from baseURI + suffix', async ({helper}) => {
const suffix = '/some/suffix';
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);
});
});
@@ -146,7 +144,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createERC721MetadataNFTCollection(owner, 'Mint collection', '6', '6', '');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', '6', '6', '');
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const nextTokenId = await contract.methods.nextTokenId().call();
tests/src/eth/proxy/nonFungibleProxy.test.tsdiffbeforeafterboth--- a/tests/src/eth/proxy/nonFungibleProxy.test.ts
+++ b/tests/src/eth/proxy/nonFungibleProxy.test.ts
@@ -101,7 +101,7 @@
itEth('Can perform mint()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createERC721MetadataNFTCollection(owner, 'A', 'A', 'A', '');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'A', 'A', 'A', '');
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -124,7 +124,7 @@
itEth('Can perform mint()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createERC721MetadataRFTCollection(owner, 'Minty', '6', '6', '');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Minty', '6', '6', '');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
const nextTokenId = await contract.methods.nextTokenId().call();
@@ -147,7 +147,7 @@
itEth('Can perform mintBulk()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createERC721MetadataRFTCollection(owner, 'MintBulky', '6', '6', '');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'MintBulky', '6', '6', '');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
{
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -80,14 +80,12 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelper.methods.createERC721MetadataNFTCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
- const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Mint collection', 'a', 'b', tokenPrefix);
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
const nextTokenId = await contract.methods.nextTokenId().call();
expect(nextTokenId).to.be.equal('1');
- result = await contract.methods.mint(
+ const result = await contract.methods.mint(
receiver,
nextTokenId,
).send();
@@ -112,7 +110,7 @@
});
itEth('TokenURI from url', async ({helper}) => {
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');
});
@@ -123,7 +121,7 @@
itEth('TokenURI from baseURI + suffix', async ({helper}) => {
const suffix = '/some/suffix';
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);
});
});
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -186,11 +186,11 @@
return {collectionId, collectionAddress};
}
- async createERC721MetadataNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
+ async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
- const result = await collectionHelper.methods.createERC721MetadataNFTCollection(name, description, tokenPrefix, baseUri).send({value: Number(collectionCreationPrice)});
+ const result = await collectionHelper.methods.createERC721MetadataCompatibleNFTCollection(name, description, tokenPrefix, baseUri).send({value: Number(collectionCreationPrice)});
const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);
@@ -210,11 +210,11 @@
return {collectionId, collectionAddress};
}
- async createERC721MetadataRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
+ async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
- const result = await collectionHelper.methods.createERC721MetadataRFTCollection(name, description, tokenPrefix, baseUri).send({value: Number(collectionCreationPrice)});
+ const result = await collectionHelper.methods.createERC721MetadataCompatibleRFTCollection(name, description, tokenPrefix, baseUri).send({value: Number(collectionCreationPrice)});
const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);