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, CollectionHandle,25 dispatch::CollectionDispatch,26 erc::{27 CollectionHelpersEvents,28 static_property::{key, value as property_value},29 },30 Pallet as PalletCommon,31};32use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};33use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};34use pallet_evm_coder_substrate::dispatch_to_evm;35use up_data_structs::{36 CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,37 CollectionMode, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,38};3940use crate::{Config, SelfWeightOf, weights::WeightInfo};4142use sp_std::{vec, vec::Vec};43use alloc::format;444546pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);47impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {48 fn recorder(&self) -> &SubstrateRecorder<T> {49 &self.050 }5152 fn into_recorder(self) -> SubstrateRecorder<T> {53 self.054 }55}5657fn convert_data<T: Config>(58 caller: caller,59 name: string,60 description: string,61 token_prefix: string,62 base_uri: string,63) -> Result<(64 T::CrossAccountId,65 CollectionName,66 CollectionDescription,67 CollectionTokenPrefix,68 PropertyValue,69)> {70 let caller = T::CrossAccountId::from_eth(caller);71 let name = name72 .encode_utf16()73 .collect::<Vec<u16>>()74 .try_into()75 .map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;76 let description = description77 .encode_utf16()78 .collect::<Vec<u16>>()79 .try_into()80 .map_err(|_| {81 error_field_too_long(stringify!(description), CollectionDescription::bound())82 })?;83 let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {84 error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())85 })?;86 let base_uri_value = base_uri87 .into_bytes()88 .try_into()89 .map_err(|_| error_field_too_long(stringify!(token_prefix), PropertyValue::bound()))?;90 Ok((caller, name, description, token_prefix, base_uri_value))91}9293fn make_data<T: Config>(94 name: CollectionName,95 mode: CollectionMode,96 description: CollectionDescription,97 token_prefix: CollectionTokenPrefix,98 base_uri_value: PropertyValue,99 add_properties: bool,100) -> Result<CreateCollectionData<T::AccountId>> {101 let mut properties = up_data_structs::CollectionPropertiesVec::default();102 let mut token_property_permissions =103 up_data_structs::CollectionPropertiesPermissionsVec::default();104105 token_property_permissions106 .try_push(up_data_structs::PropertyKeyPermission {107 key: key::url(),108 permission: up_data_structs::PropertyPermission {109 mutable: false,110 collection_admin: true,111 token_owner: false,112 },113 })114 .map_err(|e| Error::Revert(format!("{:?}", e)))?;115116 if add_properties {117 token_property_permissions118 .try_push(up_data_structs::PropertyKeyPermission {119 key: key::suffix(),120 permission: up_data_structs::PropertyPermission {121 mutable: false,122 collection_admin: true,123 token_owner: false,124 },125 })126 .map_err(|e| Error::Revert(format!("{:?}", e)))?;127128 properties129 .try_push(up_data_structs::Property {130 key: key::schema_name(),131 value: property_value::erc721(),132 })133 .map_err(|e| Error::Revert(format!("{:?}", e)))?;134135 if !base_uri_value.is_empty() {136 properties137 .try_push(up_data_structs::Property {138 key: key::base_uri(),139 value: base_uri_value,140 })141 .map_err(|e| Error::Revert(format!("{:?}", e)))?;142 }143 }144145 let data = CreateCollectionData {146 name,147 mode,148 description,149 token_prefix,150 token_property_permissions,151 properties,152 ..Default::default()153 };154 Ok(data)155}156157fn parent_nft_property_permissions() -> PropertyKeyPermission {158 PropertyKeyPermission {159 key: key::parent_nft(),160 permission: PropertyPermission {161 mutable: false,162 collection_admin: false,163 token_owner: true,164 },165 }166}167168fn create_refungible_collection_internal<169 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,170>(171 caller: caller,172 name: string,173 description: string,174 token_prefix: string,175 base_uri: string,176 add_properties: bool,177) -> Result<address> {178 let (caller, name, description, token_prefix, base_uri_value) =179 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;180 let data = make_data::<T>(181 name,182 CollectionMode::ReFungible,183 description,184 token_prefix,185 base_uri_value,186 add_properties,187 )?;188189 let collection_id = T::CollectionDispatch::create(caller.clone(), data)190 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;191192 let handle = <CollectionHandle<T>>::try_get(collection_id).map_err(dispatch_to_evm::<T>)?;193 <PalletCommon<T>>::set_scoped_token_property_permissions(194 &handle,195 &caller,196 PropertyScope::Eth,197 vec![parent_nft_property_permissions()],198 )199 .map_err(dispatch_to_evm::<T>)?;200201 let address = pallet_common::eth::collection_id_to_address(collection_id);202 Ok(address)203}204205206#[solidity_interface(name = "CollectionHelpers", events(CollectionHelpersEvents))]207impl<T> EvmCollectionHelpers<T>208where209 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,210{211 212 213 214 215 216 #[weight(<SelfWeightOf<T>>::create_collection())]217 fn create_nonfungible_collection(218 &mut self,219 caller: caller,220 name: string,221 description: string,222 token_prefix: string,223 ) -> Result<address> {224 let (caller, name, description, token_prefix, _base_uri_value) =225 convert_data::<T>(caller, name, description, token_prefix, "".into())?;226 let data = make_data::<T>(227 name,228 CollectionMode::NFT,229 description,230 token_prefix,231 Default::default(),232 false,233 )?;234 let collection_id = T::CollectionDispatch::create(caller, data)235 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;236237 let address = pallet_common::eth::collection_id_to_address(collection_id);238 Ok(address)239 }240241 #[weight(<SelfWeightOf<T>>::create_collection())]242 #[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]243 fn create_nonfungible_collection_with_properties(244 &mut self,245 caller: caller,246 name: string,247 description: string,248 token_prefix: string,249 base_uri: string,250 ) -> Result<address> {251 let (caller, name, description, token_prefix, base_uri_value) =252 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;253 let data = make_data::<T>(254 name,255 CollectionMode::NFT,256 description,257 token_prefix,258 base_uri_value,259 true,260 )?;261 let collection_id = T::CollectionDispatch::create(caller, data)262 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;263264 let address = pallet_common::eth::collection_id_to_address(collection_id);265 Ok(address)266 }267268 #[weight(<SelfWeightOf<T>>::create_collection())]269 fn create_refungible_collection(270 &mut self,271 caller: caller,272 name: string,273 description: string,274 token_prefix: string,275 ) -> Result<address> {276 create_refungible_collection_internal::<T>(277 caller,278 name,279 description,280 token_prefix,281 Default::default(),282 false,283 )284 }285286 #[weight(<SelfWeightOf<T>>::create_collection())]287 #[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]288 fn create_refungible_collection_with_properties(289 &mut self,290 caller: caller,291 name: string,292 description: string,293 token_prefix: string,294 base_uri: string,295 ) -> Result<address> {296 create_refungible_collection_internal::<T>(297 caller,298 name,299 description,300 token_prefix,301 base_uri,302 true,303 )304 }305306 307 308 309 fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {310 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {311 let collection_id = id;312 return Ok(<CollectionById<T>>::contains_key(collection_id));313 }314315 Ok(false)316 }317}318319320pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);321impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>322 for CollectionHelpersOnMethodCall<T>323{324 fn is_reserved(contract: &sp_core::H160) -> bool {325 contract == &T::ContractAddress::get()326 }327328 fn is_used(contract: &sp_core::H160) -> bool {329 contract == &T::ContractAddress::get()330 }331332 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {333 if handle.code_address() != T::ContractAddress::get() {334 return None;335 }336337 let helpers =338 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));339 pallet_evm_coder_substrate::call(handle, helpers)340 }341342 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {343 (contract == &T::ContractAddress::get())344 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())345 }346}347348generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);349generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);350351fn error_field_too_long(feild: &str, bound: usize) -> Error {352 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))353}