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::{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 name: string,160 description: string,161 token_prefix: string,162 base_uri: string,163 add_properties: bool,164) -> Result<address> {165 let (caller, name, description, token_prefix, base_uri_value) =166 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;167 let data = make_data::<T>(168 name,169 CollectionMode::ReFungible,170 description,171 token_prefix,172 base_uri_value,173 add_properties,174 )?;175176 let collection_id = T::CollectionDispatch::create(caller.clone(), data)177 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;178 let address = pallet_common::eth::collection_id_to_address(collection_id);179 Ok(address)180}181182183#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]184impl<T> EvmCollectionHelpers<T>185where186 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,187{188 189 190 191 192 193 #[weight(<SelfWeightOf<T>>::create_collection())]194 fn create_nonfungible_collection(195 &mut self,196 caller: caller,197 name: string,198 description: string,199 token_prefix: string,200 ) -> Result<address> {201 let (caller, name, description, token_prefix, _base_uri_value) =202 convert_data::<T>(caller, name, description, token_prefix, "".into())?;203 let data = make_data::<T>(204 name,205 CollectionMode::NFT,206 description,207 token_prefix,208 Default::default(),209 false,210 )?;211 let collection_id = T::CollectionDispatch::create(caller, data)212 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;213214 let address = pallet_common::eth::collection_id_to_address(collection_id);215 Ok(address)216 }217218 #[weight(<SelfWeightOf<T>>::create_collection())]219 #[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]220 fn create_nonfungible_collection_with_properties(221 &mut self,222 caller: caller,223 name: string,224 description: string,225 token_prefix: string,226 base_uri: string,227 ) -> Result<address> {228 let (caller, name, description, token_prefix, base_uri_value) =229 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;230 let data = make_data::<T>(231 name,232 CollectionMode::NFT,233 description,234 token_prefix,235 base_uri_value,236 true,237 )?;238 let collection_id = T::CollectionDispatch::create(caller, data)239 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;240241 let address = pallet_common::eth::collection_id_to_address(collection_id);242 Ok(address)243 }244245 #[weight(<SelfWeightOf<T>>::create_collection())]246 #[solidity(rename_selector = "createRFTCollection")]247 fn create_refungible_collection(248 &mut self,249 caller: caller,250 name: string,251 description: string,252 token_prefix: string,253 ) -> Result<address> {254 create_refungible_collection_internal::<T>(255 caller,256 name,257 description,258 token_prefix,259 Default::default(),260 false,261 )262 }263264 #[weight(<SelfWeightOf<T>>::create_collection())]265 #[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]266 fn create_refungible_collection_with_properties(267 &mut self,268 caller: caller,269 name: string,270 description: string,271 token_prefix: string,272 base_uri: string,273 ) -> Result<address> {274 create_refungible_collection_internal::<T>(275 caller,276 name,277 description,278 token_prefix,279 base_uri,280 true,281 )282 }283284 285 286 287 fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {288 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {289 let collection_id = id;290 return Ok(<CollectionById<T>>::contains_key(collection_id));291 }292293 Ok(false)294 }295}296297298pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);299impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>300 for CollectionHelpersOnMethodCall<T>301{302 fn is_reserved(contract: &sp_core::H160) -> bool {303 contract == &T::ContractAddress::get()304 }305306 fn is_used(contract: &sp_core::H160) -> bool {307 contract == &T::ContractAddress::get()308 }309310 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {311 if handle.code_address() != T::ContractAddress::get() {312 return None;313 }314315 let helpers =316 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));317 pallet_evm_coder_substrate::call(handle, helpers)318 }319320 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {321 (contract == &T::ContractAddress::get())322 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())323 }324}325326generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);327generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);328329fn error_field_too_long(feild: &str, bound: usize) -> Error {330 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))331}