git.delta.rocks / unique-network / refs/commits / dc6d7fbf1b22

difftreelog

source

pallets/evm-contract-helpers/src/eth.rs7.1 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use core::marker::PhantomData;18use evm_coder::{abi::AbiWriter, execution::*, generate_stubgen, solidity_interface, types::*, ToLog};19use ethereum as _;20use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};21use pallet_evm::{22	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure,23	account::CrossAccountId, Pallet as PalletEvm24};25use sp_core::H160;26use crate::{27	AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringRateLimit, SponsoringModeT,28};29use frame_support::traits::Get;30use up_sponsorship::SponsorshipHandler;31use sp_std::vec::Vec;3233struct ContractHelpers<T: Config>(SubstrateRecorder<T>);34impl<T: Config> WithRecorder<T> for ContractHelpers<T> {35	fn recorder(&self) -> &SubstrateRecorder<T> {36		&self.037	}3839	fn into_recorder(self) -> SubstrateRecorder<T> {40		self.041	}42}4344#[derive(ToLog)]45pub enum ContractHelperEvent {46	CollectionCreated {47		#[indexed]48		owner: address,49		#[indexed]50		collection_id: address,51	},52}5354#[solidity_interface(name = "ContractHelpers")]55impl<T: Config> ContractHelpers<T> {56	fn contract_owner(&self, contract_address: address) -> Result<address> {57		Ok(<Owner<T>>::get(contract_address))58	}5960	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {61		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)62	}6364	/// Deprecated65	fn toggle_sponsoring(66		&mut self,67		caller: caller,68		contract_address: address,69		enabled: bool,70	) -> Result<void> {71		<Pallet<T>>::ensure_owner(contract_address, caller)?;72		<Pallet<T>>::toggle_sponsoring(contract_address, enabled);73		Ok(())74	}7576	fn set_sponsoring_mode(77		&mut self,78		caller: caller,79		contract_address: address,80		mode: uint8,81	) -> Result<void> {82		<Pallet<T>>::ensure_owner(contract_address, caller)?;83		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;84		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);85		Ok(())86	}8788	fn sponsoring_mode(&self, contract_address: address) -> Result<uint8> {89		Ok(<Pallet<T>>::sponsoring_mode(contract_address).to_eth())90	}9192	fn set_sponsoring_rate_limit(93		&mut self,94		caller: caller,95		contract_address: address,96		rate_limit: uint32,97	) -> Result<void> {98		<Pallet<T>>::ensure_owner(contract_address, caller)?;99		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());100		Ok(())101	}102103	fn get_sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {104		Ok(<SponsoringRateLimit<T>>::get(contract_address)105			.try_into()106			.map_err(|_| "rate limit > u32::MAX")?)107	}108109	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {110		self.0.consume_sload()?;111		Ok(<Pallet<T>>::allowed(contract_address, user))112	}113114	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {115		Ok(<AllowlistEnabled<T>>::get(contract_address))116	}117118	fn toggle_allowlist(119		&mut self,120		caller: caller,121		contract_address: address,122		enabled: bool,123	) -> Result<void> {124		<Pallet<T>>::ensure_owner(contract_address, caller)?;125		<Pallet<T>>::toggle_allowlist(contract_address, enabled);126		Ok(())127	}128129	fn toggle_allowed(130		&mut self,131		caller: caller,132		contract_address: address,133		user: address,134		allowed: bool,135	) -> Result<void> {136		<Pallet<T>>::ensure_owner(contract_address, caller)?;137		<Pallet<T>>::toggle_allowed(contract_address, user, allowed);138		Ok(())139	}140141	fn create_721_collection(&self, caller: caller) -> Result<address> {142		let caller = T::CrossAccountId::from_eth(caller);143		let collection_id = <pallet_nonfungible::Pallet<T>>::init_collection(144			caller.as_sub().clone(),145			Default::default(),146		)147		.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;148		let address = pallet_common::eth::collection_id_to_address(collection_id);149150		<PalletEvm<T>>::deposit_log(151			ContractHelperEvent::CollectionCreated {152				owner: *caller.as_eth(),153				collection_id: address,154			}155			.to_log(address),156		);157		Ok(address)158	}159}160161pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);162impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T> {163	fn is_reserved(contract: &sp_core::H160) -> bool {164		contract == &T::ContractAddress::get()165	}166167	fn is_used(contract: &sp_core::H160) -> bool {168		contract == &T::ContractAddress::get()169	}170171	fn call(172		source: &sp_core::H160,173		target: &sp_core::H160,174		gas_left: u64,175		input: &[u8],176		value: sp_core::U256,177	) -> Option<PrecompileResult> {178		// TODO: Extract to another OnMethodCall handler179		if <AllowlistEnabled<T>>::get(target) && !<Pallet<T>>::allowed(*target, *source) {180			return Some(Err(PrecompileFailure::Revert {181				exit_status: ExitRevert::Reverted,182				cost: 0,183				output: {184					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));185					writer.string("Target contract is allowlisted");186					writer.finish()187				},188			}));189		}190191		if target != &T::ContractAddress::get() {192			return None;193		}194195		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(gas_left));196		pallet_evm_coder_substrate::call(*source, helpers, value, input)197	}198199	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {200		(contract == &T::ContractAddress::get())201			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())202	}203}204205pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);206impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {207	fn on_create(owner: H160, contract: H160) {208		<Owner<T>>::insert(contract, owner);209	}210}211212pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);213impl<T: Config> SponsorshipHandler<T::CrossAccountId, (H160, Vec<u8>)>214	for HelpersContractSponsoring<T>215{216	fn get_sponsor(who: &T::CrossAccountId, call: &(H160, Vec<u8>)) -> Option<T::CrossAccountId> {217		let mode = <Pallet<T>>::sponsoring_mode(call.0);218		if mode == SponsoringModeT::Disabled {219			return None;220		}221222		if mode == SponsoringModeT::Allowlisted && !<Pallet<T>>::allowed(call.0, *who.as_eth()) {223			return None;224		}225		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;226227		if let Some(last_tx_block) = <SponsorBasket<T>>::get(&call.0, who.as_eth()) {228			let limit = <SponsoringRateLimit<T>>::get(&call.0);229230			let timeout = last_tx_block + limit;231			if block_number < timeout {232				return None;233			}234		}235236		<SponsorBasket<T>>::insert(&call.0, who.as_eth(), block_number);237238		let sponsor = T::CrossAccountId::from_eth(call.0);239		Some(sponsor)240	}241}242243generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);244generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);