12345678910111213141516171819use core::marker::PhantomData;20use ethereum as _;21use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};22use frame_support::{traits::Get, storage::StorageNMap};2324use crate::sp_api_hidden_includes_decl_storage::hidden_include::StorageDoubleMap;25use pallet_common::{26 CollectionById,27 dispatch::CollectionDispatch,28 erc::{29 CollectionHelpersEvents,30 static_property::{key},31 },32 Pallet as PalletCommon,33};34use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};35use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};36use sp_std::vec;37use up_data_structs::{38 CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,39 CollectionMode, PropertyValue, CollectionFlags,40};4142use crate::{43 Config, SelfWeightOf, weights::WeightInfo, NftTransferBasket, FungibleTransferBasket,44 ReFungibleTransferBasket, NftApproveBasket, FungibleApproveBasket, RefungibleApproveBasket,45};4647use sp_std::vec::Vec;48use alloc::format;495051pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);52impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {53 fn recorder(&self) -> &SubstrateRecorder<T> {54 &self.055 }5657 fn into_recorder(self) -> SubstrateRecorder<T> {58 self.059 }60}6162fn convert_data<T: Config>(63 caller: caller,64 name: string,65 description: string,66 token_prefix: string,67) -> Result<(68 T::CrossAccountId,69 CollectionName,70 CollectionDescription,71 CollectionTokenPrefix,72)> {73 let caller = T::CrossAccountId::from_eth(caller);74 let name = name75 .encode_utf16()76 .collect::<Vec<u16>>()77 .try_into()78 .map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;79 let description = description80 .encode_utf16()81 .collect::<Vec<u16>>()82 .try_into()83 .map_err(|_| {84 error_field_too_long(stringify!(description), CollectionDescription::bound())85 })?;86 let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {87 error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())88 })?;89 Ok((caller, name, description, token_prefix))90}9192fn create_refungible_collection_internal<93 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,94>(95 caller: caller,96 value: value,97 name: string,98 description: string,99 token_prefix: string,100) -> Result<address> {101 let (caller, name, description, token_prefix) =102 convert_data::<T>(caller, name, description, token_prefix)?;103 let data = CreateCollectionData {104 name,105 mode: CollectionMode::ReFungible,106 description,107 token_prefix,108 ..Default::default()109 };110 check_sent_amount_equals_collection_creation_price::<T>(value)?;111 let collection_helpers_address =112 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());113114 let collection_id = T::CollectionDispatch::create(115 caller.clone(),116 collection_helpers_address,117 data,118 Default::default(),119 )120 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;121 let address = pallet_common::eth::collection_id_to_address(collection_id);122 Ok(address)123}124125fn check_sent_amount_equals_collection_creation_price<T: Config>(value: value) -> Result<()> {126 let value = value.as_u128();127 let creation_price: u128 = T::CollectionCreationPrice::get()128 .try_into()129 .map_err(|_| ()) 130 .expect("Collection creation price should be convertible to u128");131 if value != creation_price {132 return Err(format!(133 "Sent amount not equals to collection creation price ({0})",134 creation_price135 )136 .into());137 }138 Ok(())139}140141142#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]143impl<T> EvmCollectionHelpers<T>144where145 T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,146{147 148 149 150 151 152 #[weight(<SelfWeightOf<T>>::create_collection())]153 #[solidity(rename_selector = "createNFTCollection")]154 fn create_nft_collection(155 &mut self,156 caller: caller,157 value: value,158 name: string,159 description: string,160 token_prefix: string,161 ) -> Result<address> {162 let (caller, name, description, token_prefix) =163 convert_data::<T>(caller, name, description, token_prefix)?;164 let data = CreateCollectionData {165 name,166 mode: CollectionMode::NFT,167 description,168 token_prefix,169 ..Default::default()170 };171 check_sent_amount_equals_collection_creation_price::<T>(value)?;172 let collection_helpers_address =173 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());174 let collection_id = T::CollectionDispatch::create(175 caller,176 collection_helpers_address,177 data,178 Default::default(),179 )180 .map_err(dispatch_to_evm::<T>)?;181182 let address = pallet_common::eth::collection_id_to_address(collection_id);183 Ok(address)184 }185 186 187 188 189 190 #[weight(<SelfWeightOf<T>>::create_collection())]191 #[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]192 #[solidity(hide)]193 fn create_nonfungible_collection(194 &mut self,195 caller: caller,196 value: value,197 name: string,198 description: string,199 token_prefix: string,200 ) -> Result<address> {201 self.create_nft_collection(caller, value, name, description, token_prefix)202 }203204 #[weight(<SelfWeightOf<T>>::create_collection())]205 #[solidity(rename_selector = "createRFTCollection")]206 fn create_rft_collection(207 &mut self,208 caller: caller,209 value: value,210 name: string,211 description: string,212 token_prefix: string,213 ) -> Result<address> {214 create_refungible_collection_internal::<T>(caller, value, name, description, token_prefix)215 }216217 #[solidity(rename_selector = "makeCollectionERC721MetadataCompatible")]218 fn make_collection_metadata_compatible(219 &mut self,220 caller: caller,221 collection: address,222 base_uri: string,223 ) -> Result<()> {224 let caller = T::CrossAccountId::from_eth(caller);225 let collection =226 pallet_common::eth::map_eth_to_id(&collection).ok_or("not a collection address")?;227 let mut collection =228 <crate::CollectionHandle<T>>::new(collection).ok_or("collection not found")?;229230 if !matches!(231 collection.mode,232 CollectionMode::NFT | CollectionMode::ReFungible233 ) {234 return Err("target collection should be either NFT or Refungible".into());235 }236237 self.recorder().consume_sstore()?;238 collection239 .check_is_owner_or_admin(&caller)240 .map_err(dispatch_to_evm::<T>)?;241242 if collection.flags.erc721metadata {243 return Err("target collection is already Erc721Metadata compatible".into());244 }245 collection.flags.erc721metadata = true;246247 let all_permissions = <pallet_common::CollectionPropertyPermissions<T>>::get(collection.id);248 if all_permissions.get(&key::url()).is_none() {249 self.recorder().consume_sstore()?;250 <PalletCommon<T>>::set_property_permission(251 &collection,252 &caller,253 up_data_structs::PropertyKeyPermission {254 key: key::url(),255 permission: up_data_structs::PropertyPermission {256 mutable: true,257 collection_admin: true,258 token_owner: false,259 },260 },261 )262 .map_err(dispatch_to_evm::<T>)?;263 }264 if all_permissions.get(&key::suffix()).is_none() {265 self.recorder().consume_sstore()?;266 <PalletCommon<T>>::set_property_permission(267 &collection,268 &caller,269 up_data_structs::PropertyKeyPermission {270 key: key::suffix(),271 permission: up_data_structs::PropertyPermission {272 mutable: true,273 collection_admin: true,274 token_owner: false,275 },276 },277 )278 .map_err(dispatch_to_evm::<T>)?;279 }280281 let all_properties = <pallet_common::CollectionProperties<T>>::get(collection.id);282 if all_properties.get(&key::base_uri()).is_none() && !base_uri.is_empty() {283 self.recorder().consume_sstore()?;284 <PalletCommon<T>>::set_collection_properties(285 &collection,286 &caller,287 vec![up_data_structs::Property {288 key: key::base_uri(),289 value: base_uri290 .into_bytes()291 .try_into()292 .map_err(|_| "base uri is too large")?,293 }],294 )295 .map_err(dispatch_to_evm::<T>)?;296 }297298 self.recorder().consume_sstore()?;299 collection.save().map_err(dispatch_to_evm::<T>)?;300301 Ok(())302 }303304 #[weight(<SelfWeightOf<T>>::destroy_collection())]305 #[solidity(rename_selector = "destroyCollection")]306 fn destroy_collection(&mut self, caller: caller, collection_address: address) -> Result<void> {307 let caller = T::CrossAccountId::from_eth(caller);308 let collection_id = pallet_common::eth::map_eth_to_id(&collection_address)309 .ok_or("Invalid collection address format".into())310 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;311 let collection = <pallet_common::CollectionHandle<T>>::try_get(collection_id)312 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;313 collection314 .check_is_internal()315 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;316317 T::CollectionDispatch::destroy(caller, collection)318 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;319320 let _ = <NftTransferBasket<T>>::clear_prefix(collection_id, u32::MAX, None);321 let _ = <FungibleTransferBasket<T>>::clear_prefix(collection_id, u32::MAX, None);322 let _ = <ReFungibleTransferBasket<T>>::clear_prefix((collection_id,), u32::MAX, None);323324 let _ = <NftApproveBasket<T>>::clear_prefix(collection_id, u32::MAX, None);325 let _ = <FungibleApproveBasket<T>>::clear_prefix(collection_id, u32::MAX, None);326 let _ = <RefungibleApproveBasket<T>>::clear_prefix((collection_id,), u32::MAX, None);327328 Ok(())329 }330331 332 333 334 fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {335 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {336 let collection_id = id;337 return Ok(<CollectionById<T>>::contains_key(collection_id));338 }339340 Ok(false)341 }342343 fn collection_creation_fee(&self) -> Result<value> {344 let price: u128 = T::CollectionCreationPrice::get()345 .try_into()346 .map_err(|_| ()) 347 .expect("Collection creation price should be convertible to u128");348 Ok(price.into())349 }350}351352353pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);354impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>355 for CollectionHelpersOnMethodCall<T>356{357 fn is_reserved(contract: &sp_core::H160) -> bool {358 contract == &T::ContractAddress::get()359 }360361 fn is_used(contract: &sp_core::H160) -> bool {362 contract == &T::ContractAddress::get()363 }364365 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {366 if handle.code_address() != T::ContractAddress::get() {367 return None;368 }369370 let helpers =371 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));372 pallet_evm_coder_substrate::call(handle, helpers)373 }374375 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {376 (contract == &T::ContractAddress::get())377 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())378 }379}380381generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);382generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);383384fn error_field_too_long(feild: &str, bound: usize) -> Error {385 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))386}