12345678910111213141516171819use 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;424344pub 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 if !base_uri_value.is_empty() {134 properties135 .try_push(up_data_structs::Property {136 key: key::base_uri(),137 value: base_uri_value,138 })139 .map_err(|e| Error::Revert(format!("{:?}", e)))?;140 }141 }142143 let data = CreateCollectionData {144 name,145 mode,146 description,147 token_prefix,148 token_property_permissions,149 properties,150 ..Default::default()151 };152 Ok(data)153}154155fn create_refungible_collection_internal<156 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,157>(158 caller: caller,159 value: value,160 name: string,161 description: string,162 token_prefix: string,163 base_uri: string,164 add_properties: bool,165) -> Result<address> {166 let (caller, name, description, token_prefix, base_uri_value) =167 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;168 let data = make_data::<T>(169 name,170 CollectionMode::ReFungible,171 description,172 token_prefix,173 base_uri_value,174 add_properties,175 )?;176 let value = value.as_u128();177 let creation_price: Result<u128> = T::CollectionCreationPrice::get()178 .try_into()179 .map_err(|_| "collection creation price should be convertible to u128".into());180 if value != creation_price? {181 return Err("Sent amount not equals to collection creation price".into());182 }183 let collection_helpers_address = T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());184185 let collection_id = T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)186 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;187 let address = pallet_common::eth::collection_id_to_address(collection_id);188 Ok(address)189}190191192#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]193impl<T> EvmCollectionHelpers<T>194where195 T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,196{197 198 199 200 201 202 #[weight(<SelfWeightOf<T>>::create_collection())]203 fn create_nonfungible_collection(204 &mut self,205 caller: caller,206 value: value,207 name: string,208 description: string,209 token_prefix: string,210 ) -> Result<address> {211 let (caller, name, description, token_prefix, _base_uri_value) =212 convert_data::<T>(caller, name, description, token_prefix, "".into())?;213 let data = make_data::<T>(214 name,215 CollectionMode::NFT,216 description,217 token_prefix,218 Default::default(),219 false,220 )?;221 let value = value.as_u128();222 let creation_price: Result<u128> = T::CollectionCreationPrice::get()223 .try_into()224 .map_err(|_| "collection creation price should be convertible to u128".into());225 let creation_price = creation_price?;226 if value != creation_price {227 return Err(format!("Sent amount not equals to collection creation price ({0})", creation_price).into());228 }229 let collection_helpers_address = T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());230 let collection_id =231 T::CollectionDispatch::create(caller, collection_helpers_address, data).map_err(dispatch_to_evm::<T>)?;232233 let address = pallet_common::eth::collection_id_to_address(collection_id);234 Ok(address)235 }236237 #[weight(<SelfWeightOf<T>>::create_collection())]238 #[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]239 fn create_nonfungible_collection_with_properties(240 &mut self,241 caller: caller,242 value: value,243 name: string,244 description: string,245 token_prefix: string,246 base_uri: string,247 ) -> Result<address> {248 let (caller, name, description, token_prefix, base_uri_value) =249 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;250 let data = make_data::<T>(251 name,252 CollectionMode::NFT,253 description,254 token_prefix,255 base_uri_value,256 true,257 )?;258 let value = value.as_u128();259 let creation_price: Result<u128> = T::CollectionCreationPrice::get()260 .try_into()261 .map_err(|_| "collection creation price should be convertible to u128".into());262 if value != creation_price? {263 return Err("Sent amount not equals to collection creation price".into());264 }265 let collection_helpers_address = T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());266 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)267 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;268269 let address = pallet_common::eth::collection_id_to_address(collection_id);270 Ok(address)271 }272273 #[weight(<SelfWeightOf<T>>::create_collection())]274 #[solidity(rename_selector = "createRFTCollection")]275 fn create_refungible_collection(276 &mut self,277 caller: caller,278 value: value,279 name: string,280 description: string,281 token_prefix: string,282 ) -> Result<address> {283 create_refungible_collection_internal::<T>(284 caller,285 value,286 name,287 description,288 token_prefix,289 Default::default(),290 false,291 )292 }293294 #[weight(<SelfWeightOf<T>>::create_collection())]295 #[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]296 fn create_refungible_collection_with_properties(297 &mut self,298 caller: caller,299 value: value,300 name: string,301 description: string,302 token_prefix: string,303 base_uri: string,304 ) -> Result<address> {305 create_refungible_collection_internal::<T>(306 caller,307 value,308 name,309 description,310 token_prefix,311 base_uri,312 true,313 )314 }315316 317 318 319 fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {320 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {321 let collection_id = id;322 return Ok(<CollectionById<T>>::contains_key(collection_id));323 }324325 Ok(false)326 }327}328329330pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);331impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>332 for CollectionHelpersOnMethodCall<T>333{334 fn is_reserved(contract: &sp_core::H160) -> bool {335 contract == &T::ContractAddress::get()336 }337338 fn is_used(contract: &sp_core::H160) -> bool {339 contract == &T::ContractAddress::get()340 }341342 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {343 if handle.code_address() != T::ContractAddress::get() {344 return None;345 }346347 let helpers =348 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));349 pallet_evm_coder_substrate::call(handle, helpers)350 }351352 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {353 (contract == &T::ContractAddress::get())354 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())355 }356}357358generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);359generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);360361fn error_field_too_long(feild: &str, bound: usize) -> Error {362 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))363}