12345678910111213141516171819use core::marker::PhantomData;20use ethereum as _;21use evm_coder::{abi::AbiType, generate_stubgen, solidity_interface, types::*};22use frame_support::{BoundedVec, traits::Get};23use pallet_common::{24 CollectionById,25 dispatch::CollectionDispatch,26 erc::{CollectionHelpersEvents, static_property::key},27 eth::{self, map_eth_to_id, collection_id_to_address},28 Pallet as PalletCommon, CollectionHandle,29};30use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};31use pallet_evm_coder_substrate::{32 dispatch_to_evm, SubstrateRecorder, WithRecorder,33 execution::{PreDispatch, Result, Error},34 frontier_contract,35};36use up_data_structs::{37 CollectionDescription, CollectionMode, CollectionName, CollectionPermissions,38 CollectionTokenPrefix, CreateCollectionData, NestingPermissions,39};4041use crate::{weights::WeightInfo, Config, Pallet, SelfWeightOf};4243use alloc::{format, collections::BTreeSet};44use sp_std::vec::Vec;4546frontier_contract! {47 macro_rules! EvmCollectionHelpers_result {...}48 impl<T: Config> Contract for EvmCollectionHelpers<T> {...}49}5051pub 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}9192#[inline(always)]93fn create_collection_internal<T: Config>(94 caller: Caller,95 value: Value,96 name: String,97 collection_mode: CollectionMode,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: collection_mode,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(caller, collection_helpers_address, data)115 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;116 let address = pallet_common::eth::collection_id_to_address(collection_id);117 Ok(address)118}119120fn check_sent_amount_equals_collection_creation_price<T: Config>(value: Value) -> Result<()> {121 let value = value.as_u128();122 let creation_price: u128 = T::CollectionCreationPrice::get()123 .try_into()124 .map_err(|_| ()) 125 .expect("Collection creation price should be convertible to u128");126 if value != creation_price {127 return Err(format!(128 "Sent amount not equals to collection creation price ({creation_price})",129 )130 .into());131 }132 Ok(())133}134135136#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents), enum(derive(PreDispatch)), enum_attr(weight))]137impl<T> EvmCollectionHelpers<T>138where139 T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,140 T::AccountId: From<[u8; 32]>,141{142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253 254 255 256 257 258 #[weight(<SelfWeightOf<T>>::create_collection())]259 #[solidity(rename_selector = "createNFTCollection")]260 fn create_nft_collection(261 &mut self,262 caller: Caller,263 value: Value,264 name: String,265 description: String,266 token_prefix: String,267 ) -> Result<Address> {268 let (caller, name, description, token_prefix) =269 convert_data::<T>(caller, name, description, token_prefix)?;270 let data = CreateCollectionData {271 name,272 mode: CollectionMode::NFT,273 description,274 token_prefix,275 ..Default::default()276 };277 check_sent_amount_equals_collection_creation_price::<T>(value)?;278 let collection_helpers_address =279 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());280 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)281 .map_err(dispatch_to_evm::<T>)?;282283 let address = pallet_common::eth::collection_id_to_address(collection_id);284 Ok(address)285 }286 287 288 289 290 291 #[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]292 #[solidity(hide)]293 #[weight(<SelfWeightOf<T>>::create_collection())]294 fn create_nonfungible_collection(295 &mut self,296 caller: Caller,297 value: Value,298 name: String,299 description: String,300 token_prefix: String,301 ) -> Result<Address> {302 create_collection_internal::<T>(303 caller,304 value,305 name,306 CollectionMode::NFT,307 description,308 token_prefix,309 )310 }311312 #[weight(<SelfWeightOf<T>>::create_collection())]313 #[solidity(rename_selector = "createRFTCollection")]314 fn create_rft_collection(315 &mut self,316 caller: Caller,317 value: Value,318 name: String,319 description: String,320 token_prefix: String,321 ) -> Result<Address> {322 create_collection_internal::<T>(323 caller,324 value,325 name,326 CollectionMode::ReFungible,327 description,328 token_prefix,329 )330 }331332 #[weight(<SelfWeightOf<T>>::create_collection())]333 #[solidity(rename_selector = "createFTCollection")]334 fn create_fungible_collection(335 &mut self,336 caller: Caller,337 value: Value,338 name: String,339 decimals: u8,340 description: String,341 token_prefix: String,342 ) -> Result<Address> {343 create_collection_internal::<T>(344 caller,345 value,346 name,347 CollectionMode::Fungible(decimals),348 description,349 token_prefix,350 )351 }352353 #[solidity(rename_selector = "makeCollectionERC721MetadataCompatible")]354 fn make_collection_metadata_compatible(355 &mut self,356 caller: Caller,357 collection: Address,358 base_uri: String,359 ) -> Result<()> {360 let caller = T::CrossAccountId::from_eth(caller);361 let collection =362 pallet_common::eth::map_eth_to_id(&collection).ok_or("not a collection address")?;363 let mut collection =364 <CollectionHandle<T>>::new(collection).ok_or("collection not found")?;365366 if !matches!(367 collection.mode,368 CollectionMode::NFT | CollectionMode::ReFungible369 ) {370 return Err("target collection should be either NFT or Refungible".into());371 }372373 self.recorder().consume_sstore()?;374 collection375 .check_is_owner_or_admin(&caller)376 .map_err(dispatch_to_evm::<T>)?;377378 if collection.flags.erc721metadata {379 return Err("target collection is already Erc721Metadata compatible".into());380 }381 collection.flags.erc721metadata = true;382383 let all_permissions = <pallet_common::CollectionPropertyPermissions<T>>::get(collection.id);384 if all_permissions.get(&key::url()).is_none() {385 self.recorder().consume_sstore()?;386 <PalletCommon<T>>::set_property_permission(387 &collection,388 &caller,389 up_data_structs::PropertyKeyPermission {390 key: key::url(),391 permission: up_data_structs::PropertyPermission {392 mutable: true,393 collection_admin: true,394 token_owner: false,395 },396 },397 )398 .map_err(dispatch_to_evm::<T>)?;399 }400 if all_permissions.get(&key::suffix()).is_none() {401 self.recorder().consume_sstore()?;402 <PalletCommon<T>>::set_property_permission(403 &collection,404 &caller,405 up_data_structs::PropertyKeyPermission {406 key: key::suffix(),407 permission: up_data_structs::PropertyPermission {408 mutable: true,409 collection_admin: true,410 token_owner: false,411 },412 },413 )414 .map_err(dispatch_to_evm::<T>)?;415 }416417 let all_properties = <pallet_common::CollectionProperties<T>>::get(collection.id);418 if all_properties.get(&key::base_uri()).is_none() && !base_uri.is_empty() {419 self.recorder().consume_sstore()?;420 <PalletCommon<T>>::set_collection_properties(421 &collection,422 &caller,423 [up_data_structs::Property {424 key: key::base_uri(),425 value: base_uri426 .into_bytes()427 .try_into()428 .map_err(|_| "base uri is too large")?,429 }]430 .into_iter(),431 )432 .map_err(dispatch_to_evm::<T>)?;433 }434435 self.recorder().consume_sstore()?;436 collection.save().map_err(dispatch_to_evm::<T>)?;437438 Ok(())439 }440441 #[weight(<SelfWeightOf<T>>::destroy_collection())]442 fn destroy_collection(&mut self, caller: Caller, collection_address: Address) -> Result<()> {443 let caller = T::CrossAccountId::from_eth(caller);444445 let collection_id = pallet_common::eth::map_eth_to_id(&collection_address)446 .ok_or("Invalid collection address format")?;447 <Pallet<T>>::destroy_collection_internal(caller, collection_id)448 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)449 }450451 452 453 454 fn is_collection_exist(&self, _caller: Caller, collection_address: Address) -> Result<bool> {455 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {456 let collection_id = id;457 return Ok(<CollectionById<T>>::contains_key(collection_id));458 }459460 Ok(false)461 }462463 fn collection_creation_fee(&self) -> Result<Value> {464 let price: u128 = T::CollectionCreationPrice::get()465 .try_into()466 .map_err(|_| ()) 467 .expect("Collection creation price should be convertible to u128");468 Ok(price.into())469 }470471 472 473 474 fn collection_address(&self, collection_id: u32) -> Result<Address> {475 Ok(collection_id_to_address(collection_id.into()))476 }477478 479 480 481 fn collection_id(&self, collection_address: Address) -> Result<u32> {482 map_eth_to_id(&collection_address)483 .map(|id| id.0)484 .ok_or(Error::Revert(format!(485 "failed to convert address {collection_address} into collectionId."486 )))487 }488}489490491pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);492impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>493 for CollectionHelpersOnMethodCall<T>494where495 T::AccountId: From<[u8; 32]>,496{497 fn is_reserved(contract: &sp_core::H160) -> bool {498 contract == &T::ContractAddress::get()499 }500501 fn is_used(contract: &sp_core::H160) -> bool {502 contract == &T::ContractAddress::get()503 }504505 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {506 if handle.code_address() != T::ContractAddress::get() {507 return None;508 }509510 let helpers =511 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));512 pallet_evm_coder_substrate::call(handle, helpers)513 }514515 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {516 (contract == &T::ContractAddress::get())517 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())518 }519}520521generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);522generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);523524fn error_field_too_long(feild: &str, bound: usize) -> Error {525 Error::Revert(format!("{feild} is too long. Max length is {bound}."))526}