1234567891011121314151617pub mod evm_collection {18 use core::marker::PhantomData;19 use evm_coder::{execution::*, generate_stubgen, solidity_interface, types::*, ToLog};20 use ethereum as _;21 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};22 use pallet_evm::{OnMethodCall, PrecompileResult, account::CrossAccountId, Pallet as PalletEvm};23 use up_data_structs::{24 CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,25 MAX_COLLECTION_NAME_LENGTH,26 };27 use frame_support::traits::Get;28 use sp_core::H160;29 use pallet_common::{CollectionHandle, CollectionById};30 31 use sp_std::{vec::Vec, rc::Rc};32 use alloc::format;33 34 pub trait Config:35 frame_system::Config36 + pallet_evm_coder_substrate::Config37 + pallet_evm::account::Config38 + pallet_nonfungible::Config39 {40 type ContractAddress: Get<H160>;41 }4243 struct EvmCollectionHelper<T: Config>(SubstrateRecorder<T>);44 impl<T: Config> WithRecorder<T> for EvmCollectionHelper<T> {45 fn recorder(&self) -> &SubstrateRecorder<T> {46 &self.047 }48 49 fn into_recorder(self) -> SubstrateRecorder<T> {50 self.051 }52 }5354 #[solidity_interface(name = "CollectionHelper")]55 impl<T: Config> EvmCollectionHelper<T> {56 fn create_721_collection(57 &self,58 caller: caller,59 name: string,60 description: string,61 token_prefix: string,62 ) -> Result<address> {63 let caller = T::CrossAccountId::from_eth(caller);64 let name = name65 .encode_utf16()66 .collect::<Vec<u16>>()67 .try_into()68 .map_err(|_| error_feild_too_long(stringify!(name), MAX_COLLECTION_NAME_LENGTH))?;69 let description = description70 .encode_utf16()71 .collect::<Vec<u16>>()72 .try_into()73 .map_err(|_| {74 error_feild_too_long(stringify!(description), MAX_COLLECTION_DESCRIPTION_LENGTH)75 })?;76 let token_prefix = token_prefix77 .into_bytes()78 .try_into()79 .map_err(|_| error_feild_too_long(stringify!(token_prefix), MAX_TOKEN_PREFIX_LENGTH))?;80 81 let data = CreateCollectionData {82 name,83 description,84 token_prefix,85 ..Default::default()86 };87 88 let collection_id =89 <pallet_nonfungible::Pallet<T>>::init_collection(caller.as_sub().clone(), data)90 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;91 92 let address = pallet_common::eth::collection_id_to_address(collection_id);93 <PalletEvm<T>>::deposit_log(94 EthCollectionEvent::CollectionCreated {95 owner: *caller.as_eth(),96 collection_id: address,97 }98 .to_log(address),99 );100 Ok(address)101 }102103 fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {104 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {105 let collection_id = id;106 return Ok(<CollectionById<T>>::contains_key(collection_id));107 }108109 Ok(false)110 }111 }112 113 struct EvmCollection<T: Config>(H160, SubstrateRecorder<T>);114 impl<T: Config> WithRecorder<T> for EvmCollection<T> {115 fn recorder(&self) -> &SubstrateRecorder<T> {116 &self.1117 }118 119 fn into_recorder(self) -> SubstrateRecorder<T> {120 self.1121 }122 }123 124 #[derive(ToLog)]125 pub enum EthCollectionEvent {126 CollectionCreated {127 #[indexed]128 owner: address,129 #[indexed]130 collection_id: address,131 },132 }133 134 #[solidity_interface(name = "Collection")]135 impl<T: Config> EvmCollection<T> {136 fn set_sponsor(137 &self,138 caller: caller,139 sponsor: address,140 ) -> Result<void> {141 let mut collection = collection_from_address::<T>(self.contract_address(caller).unwrap(), self.1.gas_left())?;142 check_is_owner(caller, &collection)?;143 144 let sponsor = T::CrossAccountId::from_eth(sponsor);145 collection.set_sponsor(sponsor.as_sub().clone());146 collection.save().map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;147 Ok(())148 }149 150 fn confirm_sponsorship(&self, caller: caller) -> Result<void> {151 let mut collection = collection_from_address::<T>(self.contract_address(caller).unwrap(), self.1.gas_left())?;152 let caller = T::CrossAccountId::from_eth(caller);153 if !collection.confirm_sponsorship(caller.as_sub()) {154 return Err(Error::Revert("Caller is not set as sponsor".into()));155 }156 collection.save().map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;157 Ok(())158 }159 160 fn set_limits(161 &self,162 caller: caller,163 limits_json: string,164 ) -> Result<void> {165 let mut collection = collection_from_address::<T>(self.contract_address(caller).unwrap(), self.1.gas_left())?;166 check_is_owner(caller, &collection)?;167 168 let limits = serde_json_core::from_str(limits_json.as_ref())169 .map_err(|e| Error::Revert(format!("Parse JSON error: {}", e)))?;170 collection.limits = limits.0;171 collection.save().map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;172 Ok(())173 }174175 fn contract_address(&self, _caller: caller) -> Result<address> {176 Ok(self.0)177 }178 }179 180 fn error_feild_too_long(feild: &str, bound: u32) -> Error {181 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))182 }183 184 fn collection_from_address<T: Config>(185 collection_address: address,186 gas_limit: u64187 ) -> Result<CollectionHandle<T>> {188 let collection_id = pallet_common::eth::map_eth_to_id(&collection_address)189 .ok_or(Error::Revert("Contract is not an unique collection".into()))?;190 let recorder = <SubstrateRecorder<T>>::new(gas_limit);191 let collection =192 pallet_common::CollectionHandle::new_with_recorder(collection_id, recorder)193 .ok_or(Error::Revert("Create collection handle error".into()))?;194 Ok(collection)195 }196 197 fn check_is_owner<T: Config>(caller: caller, collection: &CollectionHandle<T>) -> Result<()> {198 let caller = T::CrossAccountId::from_eth(caller);199 collection200 .check_is_owner(&caller)201 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;202 Ok(())203 }204205 pub struct CollectionHelperOnMethodCall<T: Config>(PhantomData<*const T>);206 impl<T: Config> OnMethodCall<T> for CollectionHelperOnMethodCall<T> {207 fn is_reserved(contract: &sp_core::H160) -> bool {208 contract == &T::ContractAddress::get()209 }210 211 fn is_used(contract: &sp_core::H160) -> bool {212 contract == &T::ContractAddress::get()213 }214 215 fn call(216 source: &sp_core::H160,217 target: &sp_core::H160,218 gas_left: u64,219 input: &[u8],220 value: sp_core::U256,221 ) -> Option<PrecompileResult> {222 if target != &T::ContractAddress::get() {223 return None;224 }225 226 let helpers = EvmCollectionHelper::<T>(SubstrateRecorder::<T>::new(gas_left));227 pallet_evm_coder_substrate::call(*source, helpers, value, input)228 }229 230 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {231 (contract == &T::ContractAddress::get())232 .then(|| include_bytes!("./stubs/CollectionHelper.raw").to_vec())233 }234 }235 236 generate_stubgen!(collection_helper_impl, CollectionHelperCall<()>, true);237 generate_stubgen!(collection_helper_iface, CollectionHelperCall<()>, false);238 239 pub struct CollectionOnMethodCall<T: Config>(PhantomData<*const T>);240 impl<T: Config> OnMethodCall<T> for CollectionOnMethodCall<T> {241 fn is_reserved(contract: &sp_core::H160) -> bool {242 contract == &T::ContractAddress::get()243 }244 245 fn is_used(contract: &sp_core::H160) -> bool {246 contract == &T::ContractAddress::get()247 }248 249 fn call(250 source: &sp_core::H160,251 target: &sp_core::H160,252 gas_left: u64,253 input: &[u8],254 value: sp_core::U256,255 ) -> Option<PrecompileResult> {256 if !pallet_common::eth::is_collection(target) {257 return None;258 }259260 let helpers = EvmCollection::<T>(*target, SubstrateRecorder::<T>::new(gas_left));261 pallet_evm_coder_substrate::call(*source, helpers, value, input)262 }263 264 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {265 (contract == &T::ContractAddress::get())266 .then(|| include_bytes!("./stubs/Collection.raw").to_vec())267 }268 }269 270 generate_stubgen!(collection_impl, CollectionCall<()>, true);271 generate_stubgen!(collection_iface, CollectionCall<()>, false);272}