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

difftreelog

refac code

PraetorP2022-12-12parent: #78c3cae.patch.diff
in: master

3 files changed

modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -295,7 +295,7 @@
 			None => return Ok(Default::default()),
 		};
 
-		Ok(EthCrossAccount::from_substrate::<T>(&sponsor))
+		Ok(EthCrossAccount::from_sub::<T>(&sponsor))
 	}
 
 	/// Get current collection limits.
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -140,7 +140,7 @@
 		}
 	}
 	/// Creates `EthCrossAccount` from substrate account
-	pub fn from_substrate<T>(account_id: &T::AccountId) -> Self
+	pub fn from_sub<T>(account_id: &T::AccountId) -> Self
 	where
 		T: pallet_evm::Config,
 		T::AccountId: AsRef<[u8; 32]>,
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
before · pallets/evm-contract-helpers/src/eth.rs
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/>.1617//! Implementation of magic contract1819extern crate alloc;20use core::marker::PhantomData;21use evm_coder::{22	abi::{AbiWriter, AbiType},23	execution::Result,24	generate_stubgen, solidity_interface,25	types::*,26	ToLog,27};28use pallet_evm::{29	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,30	account::CrossAccountId,31};32use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};33use pallet_evm_transaction_payment::CallContext;34use sp_core::{H160, U256};35use up_data_structs::SponsorshipState;36use crate::{37	AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringFeeLimit,38	SponsoringRateLimit, SponsoringModeT, Sponsoring,39};40use frame_support::traits::Get;41use up_sponsorship::SponsorshipHandler;42use sp_std::vec::Vec;4344/// Pallet events.45#[derive(ToLog)]46pub enum ContractHelpersEvents {47	/// Contract sponsor was set.48	ContractSponsorSet {49		/// Contract address of the affected collection.50		#[indexed]51		contract_address: address,52		/// New sponsor address.53		sponsor: address,54	},5556	/// New sponsor was confirm.57	ContractSponsorshipConfirmed {58		/// Contract address of the affected collection.59		#[indexed]60		contract_address: address,61		/// New sponsor address.62		sponsor: address,63	},6465	/// Collection sponsor was removed.66	ContractSponsorRemoved {67		/// Contract address of the affected collection.68		#[indexed]69		contract_address: address,70	},71}7273/// See [`ContractHelpersCall`]74pub struct ContractHelpers<T: Config>(SubstrateRecorder<T>);75impl<T: Config> WithRecorder<T> for ContractHelpers<T> {76	fn recorder(&self) -> &SubstrateRecorder<T> {77		&self.078	}7980	fn into_recorder(self) -> SubstrateRecorder<T> {81		self.082	}83}8485/// @title Magic contract, which allows users to reconfigure other contracts86#[solidity_interface(name = ContractHelpers, events(ContractHelpersEvents))]87impl<T: Config> ContractHelpers<T>88where89	T::AccountId: AsRef<[u8; 32]>,90{91	/// Get user, which deployed specified contract92	/// @dev May return zero address in case if contract is deployed93	///  using uniquenetwork evm-migration pallet, or using other terms not94	///  intended by pallet-evm95	/// @dev Returns zero address if contract does not exists96	/// @param contractAddress Contract to get owner of97	/// @return address Owner of contract98	fn contract_owner(&self, contract_address: address) -> Result<address> {99		Ok(<Owner<T>>::get(contract_address))100	}101102	/// Set sponsor.103	/// @param contractAddress Contract for which a sponsor is being established.104	/// @param sponsor User address who set as pending sponsor.105	fn set_sponsor(106		&mut self,107		caller: caller,108		contract_address: address,109		sponsor: address,110	) -> Result<void> {111		self.recorder().consume_sload()?;112		self.recorder().consume_sstore()?;113114		Pallet::<T>::set_sponsor(115			&T::CrossAccountId::from_eth(caller),116			contract_address,117			&T::CrossAccountId::from_eth(sponsor),118		)119		.map_err(dispatch_to_evm::<T>)?;120121		Ok(())122	}123124	/// Set contract as self sponsored.125	///126	/// @param contractAddress Contract for which a self sponsoring is being enabled.127	fn self_sponsored_enable(&mut self, caller: caller, contract_address: address) -> Result<void> {128		self.recorder().consume_sload()?;129		self.recorder().consume_sstore()?;130131		let caller = T::CrossAccountId::from_eth(caller);132133		Pallet::<T>::ensure_owner(contract_address, *caller.as_eth())134			.map_err(dispatch_to_evm::<T>)?;135136		Pallet::<T>::force_set_sponsor(137			contract_address,138			&T::CrossAccountId::from_eth(contract_address),139		)140		.map_err(dispatch_to_evm::<T>)?;141142		Ok(())143	}144145	/// Remove sponsor.146	///147	/// @param contractAddress Contract for which a sponsorship is being removed.148	fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {149		self.recorder().consume_sload()?;150		self.recorder().consume_sstore()?;151152		Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)153			.map_err(dispatch_to_evm::<T>)?;154155		Ok(())156	}157158	/// Confirm sponsorship.159	///160	/// @dev Caller must be same that set via [`setSponsor`].161	///162	/// @param contractAddress Сontract for which need to confirm sponsorship.163	fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {164		self.recorder().consume_sload()?;165		self.recorder().consume_sstore()?;166167		Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)168			.map_err(dispatch_to_evm::<T>)?;169170		Ok(())171	}172173	/// Get current sponsor.174	///175	/// @param contractAddress The contract for which a sponsor is requested.176	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.177	fn sponsor(&self, contract_address: address) -> Result<(address, uint256)> {178		let sponsor =179			Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;180		Ok(pallet_common::eth::convert_cross_account_to_tuple::<T>(181			&sponsor,182		))183	}184185	/// Check tat contract has confirmed sponsor.186	///187	/// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.188	/// @return **true** if contract has confirmed sponsor.189	fn has_sponsor(&self, contract_address: address) -> Result<bool> {190		Ok(Pallet::<T>::get_sponsor(contract_address).is_some())191	}192193	/// Check tat contract has pending sponsor.194	///195	/// @param contractAddress The contract for which the presence of a pending sponsor is checked.196	/// @return **true** if contract has pending sponsor.197	fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {198		Ok(match Sponsoring::<T>::get(contract_address) {199			SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,200			SponsorshipState::Unconfirmed(_) => true,201		})202	}203204	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {205		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)206	}207208	fn set_sponsoring_mode(209		&mut self,210		caller: caller,211		contract_address: address,212		// TODO: implement support for enums in evm-coder213		mode: uint8,214	) -> Result<void> {215		self.recorder().consume_sload()?;216		self.recorder().consume_sstore()?;217218		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;219		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;220		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);221222		Ok(())223	}224225	/// Get current contract sponsoring rate limit226	/// @param contractAddress Contract to get sponsoring rate limit of227	/// @return uint32 Amount of blocks between two sponsored transactions228	fn sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {229		self.recorder().consume_sload()?;230231		Ok(<SponsoringRateLimit<T>>::get(contract_address)232			.try_into()233			.map_err(|_| "rate limit > u32::MAX")?)234	}235236	/// Set contract sponsoring rate limit237	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should238	///  pass between two sponsored transactions239	/// @param contractAddress Contract to change sponsoring rate limit of240	/// @param rateLimit Target rate limit241	/// @dev Only contract owner can change this setting242	fn set_sponsoring_rate_limit(243		&mut self,244		caller: caller,245		contract_address: address,246		rate_limit: uint32,247	) -> Result<void> {248		self.recorder().consume_sload()?;249		self.recorder().consume_sstore()?;250251		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;252		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());253		Ok(())254	}255256	/// Set contract sponsoring fee limit257	/// @dev Sponsoring fee limit - is maximum fee that could be spent by258	///  single transaction259	/// @param contractAddress Contract to change sponsoring fee limit of260	/// @param feeLimit Fee limit261	/// @dev Only contract owner can change this setting262	fn set_sponsoring_fee_limit(263		&mut self,264		caller: caller,265		contract_address: address,266		fee_limit: uint256,267	) -> Result<void> {268		self.recorder().consume_sload()?;269		self.recorder().consume_sstore()?;270271		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;272		<Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())273			.map_err(dispatch_to_evm::<T>)?;274		Ok(())275	}276277	/// Get current contract sponsoring fee limit278	/// @param contractAddress Contract to get sponsoring fee limit of279	/// @return uint256 Maximum amount of fee that could be spent by single280	///  transaction281	fn sponsoring_fee_limit(&self, contract_address: address) -> Result<uint256> {282		self.recorder().consume_sload()?;283284		Ok(get_sponsoring_fee_limit::<T>(contract_address))285	}286287	/// Is specified user present in contract allow list288	/// @dev Contract owner always implicitly included289	/// @param contractAddress Contract to check allowlist of290	/// @param user User to check291	/// @return bool Is specified users exists in contract allowlist292	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {293		self.0.consume_sload()?;294		Ok(<Pallet<T>>::allowed(contract_address, user))295	}296297	/// Toggle user presence in contract allowlist298	/// @param contractAddress Contract to change allowlist of299	/// @param user Which user presence should be toggled300	/// @param isAllowed `true` if user should be allowed to be sponsored301	///  or call this contract, `false` otherwise302	/// @dev Only contract owner can change this setting303	fn toggle_allowed(304		&mut self,305		caller: caller,306		contract_address: address,307		user: address,308		is_allowed: bool,309	) -> Result<void> {310		self.recorder().consume_sload()?;311		self.recorder().consume_sstore()?;312313		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;314		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);315316		Ok(())317	}318319	/// Is this contract has allowlist access enabled320	/// @dev Allowlist always can have users, and it is used for two purposes:321	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist322	///  in case of allowlist access enabled, only users from allowlist may call this contract323	/// @param contractAddress Contract to get allowlist access of324	/// @return bool Is specified contract has allowlist access enabled325	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {326		Ok(<AllowlistEnabled<T>>::get(contract_address))327	}328329	/// Toggle contract allowlist access330	/// @param contractAddress Contract to change allowlist access of331	/// @param enabled Should allowlist access to be enabled?332	fn toggle_allowlist(333		&mut self,334		caller: caller,335		contract_address: address,336		enabled: bool,337	) -> Result<void> {338		self.recorder().consume_sload()?;339		self.recorder().consume_sstore()?;340341		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;342		<Pallet<T>>::toggle_allowlist(contract_address, enabled);343		Ok(())344	}345}346347/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]348pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);349impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>350where351	T::AccountId: AsRef<[u8; 32]>,352{353	fn is_reserved(contract: &sp_core::H160) -> bool {354		contract == &T::ContractAddress::get()355	}356357	fn is_used(contract: &sp_core::H160) -> bool {358		contract == &T::ContractAddress::get()359	}360361	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {362		// TODO: Extract to another OnMethodCall handler363		if <AllowlistEnabled<T>>::get(handle.code_address())364			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)365		{366			return Some(Err(PrecompileFailure::Revert {367				exit_status: ExitRevert::Reverted,368				output: {369					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));370					writer.string("Target contract is allowlisted");371					writer.finish()372				},373			}));374		}375376		if handle.code_address() != T::ContractAddress::get() {377			return None;378		}379380		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));381		pallet_evm_coder_substrate::call(handle, helpers)382	}383384	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {385		(contract == &T::ContractAddress::get())386			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())387	}388}389390/// Hooks into contract creation, storing owner of newly deployed contract391pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);392impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {393	fn on_create(owner: H160, contract: H160) {394		<Owner<T>>::insert(contract, owner);395	}396}397398/// Bridge to pallet-sponsoring399pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);400impl<T: Config> SponsorshipHandler<T::CrossAccountId, CallContext>401	for HelpersContractSponsoring<T>402{403	fn get_sponsor(404		who: &T::CrossAccountId,405		call_context: &CallContext,406	) -> Option<T::CrossAccountId> {407		let contract_address = call_context.contract_address;408		let mode = <Pallet<T>>::sponsoring_mode(contract_address);409		if mode == SponsoringModeT::Disabled {410			return None;411		}412413		let sponsor = match <Pallet<T>>::get_sponsor(contract_address) {414			Some(sponsor) => sponsor,415			None => return None,416		};417418		if mode == SponsoringModeT::Allowlisted419			&& !<Pallet<T>>::allowed(contract_address, *who.as_eth())420		{421			return None;422		}423		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;424425		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {426			let limit = <SponsoringRateLimit<T>>::get(contract_address);427428			let timeout = last_tx_block + limit;429			if block_number < timeout {430				return None;431			}432		}433434		let sponsored_fee_limit = get_sponsoring_fee_limit::<T>(contract_address);435436		if call_context.max_fee > sponsored_fee_limit {437			return None;438		}439440		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);441442		Some(sponsor)443	}444}445446fn get_sponsoring_fee_limit<T: Config>(contract_address: address) -> uint256 {447	<SponsoringFeeLimit<T>>::get(contract_address)448		.get(&0xffffffff)449		.cloned()450		.unwrap_or(U256::MAX)451}452453generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);454generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);
after · pallets/evm-contract-helpers/src/eth.rs
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/>.1617//! Implementation of magic contract1819extern crate alloc;20use core::marker::PhantomData;21use evm_coder::{22	abi::{AbiWriter, AbiType},23	execution::Result,24	generate_stubgen, solidity_interface,25	types::*,26	ToLog,27};28use pallet_common::eth::EthCrossAccount;29use pallet_evm::{30	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,31	account::CrossAccountId,32};33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};34use pallet_evm_transaction_payment::CallContext;35use sp_core::{H160, U256};36use up_data_structs::SponsorshipState;37use crate::{38	AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringFeeLimit,39	SponsoringRateLimit, SponsoringModeT, Sponsoring,40};41use frame_support::traits::Get;42use up_sponsorship::SponsorshipHandler;43use sp_std::vec::Vec;4445/// Pallet events.46#[derive(ToLog)]47pub enum ContractHelpersEvents {48	/// Contract sponsor was set.49	ContractSponsorSet {50		/// Contract address of the affected collection.51		#[indexed]52		contract_address: address,53		/// New sponsor address.54		sponsor: address,55	},5657	/// New sponsor was confirm.58	ContractSponsorshipConfirmed {59		/// Contract address of the affected collection.60		#[indexed]61		contract_address: address,62		/// New sponsor address.63		sponsor: address,64	},6566	/// Collection sponsor was removed.67	ContractSponsorRemoved {68		/// Contract address of the affected collection.69		#[indexed]70		contract_address: address,71	},72}7374/// See [`ContractHelpersCall`]75pub struct ContractHelpers<T: Config>(SubstrateRecorder<T>);76impl<T: Config> WithRecorder<T> for ContractHelpers<T> {77	fn recorder(&self) -> &SubstrateRecorder<T> {78		&self.079	}8081	fn into_recorder(self) -> SubstrateRecorder<T> {82		self.083	}84}8586/// @title Magic contract, which allows users to reconfigure other contracts87#[solidity_interface(name = ContractHelpers, events(ContractHelpersEvents))]88impl<T: Config> ContractHelpers<T>89where90	T::AccountId: AsRef<[u8; 32]>,91{92	/// Get user, which deployed specified contract93	/// @dev May return zero address in case if contract is deployed94	///  using uniquenetwork evm-migration pallet, or using other terms not95	///  intended by pallet-evm96	/// @dev Returns zero address if contract does not exists97	/// @param contractAddress Contract to get owner of98	/// @return address Owner of contract99	fn contract_owner(&self, contract_address: address) -> Result<address> {100		Ok(<Owner<T>>::get(contract_address))101	}102103	/// Set sponsor.104	/// @param contractAddress Contract for which a sponsor is being established.105	/// @param sponsor User address who set as pending sponsor.106	fn set_sponsor(107		&mut self,108		caller: caller,109		contract_address: address,110		sponsor: address,111	) -> Result<void> {112		self.recorder().consume_sload()?;113		self.recorder().consume_sstore()?;114115		Pallet::<T>::set_sponsor(116			&T::CrossAccountId::from_eth(caller),117			contract_address,118			&T::CrossAccountId::from_eth(sponsor),119		)120		.map_err(dispatch_to_evm::<T>)?;121122		Ok(())123	}124125	/// Set contract as self sponsored.126	///127	/// @param contractAddress Contract for which a self sponsoring is being enabled.128	fn self_sponsored_enable(&mut self, caller: caller, contract_address: address) -> Result<void> {129		self.recorder().consume_sload()?;130		self.recorder().consume_sstore()?;131132		let caller = T::CrossAccountId::from_eth(caller);133134		Pallet::<T>::ensure_owner(contract_address, *caller.as_eth())135			.map_err(dispatch_to_evm::<T>)?;136137		Pallet::<T>::force_set_sponsor(138			contract_address,139			&T::CrossAccountId::from_eth(contract_address),140		)141		.map_err(dispatch_to_evm::<T>)?;142143		Ok(())144	}145146	/// Remove sponsor.147	///148	/// @param contractAddress Contract for which a sponsorship is being removed.149	fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {150		self.recorder().consume_sload()?;151		self.recorder().consume_sstore()?;152153		Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)154			.map_err(dispatch_to_evm::<T>)?;155156		Ok(())157	}158159	/// Confirm sponsorship.160	///161	/// @dev Caller must be same that set via [`setSponsor`].162	///163	/// @param contractAddress Сontract for which need to confirm sponsorship.164	fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {165		self.recorder().consume_sload()?;166		self.recorder().consume_sstore()?;167168		Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)169			.map_err(dispatch_to_evm::<T>)?;170171		Ok(())172	}173174	/// Get current sponsor.175	///176	/// @param contractAddress The contract for which a sponsor is requested.177	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.178	fn sponsor(&self, contract_address: address) -> Result<EthCrossAccount> {179		Ok(EthCrossAccount::from_sub_cross_account::<T>(180			&Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?,181		))182	}183184	/// Check tat contract has confirmed sponsor.185	///186	/// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.187	/// @return **true** if contract has confirmed sponsor.188	fn has_sponsor(&self, contract_address: address) -> Result<bool> {189		Ok(Pallet::<T>::get_sponsor(contract_address).is_some())190	}191192	/// Check tat contract has pending sponsor.193	///194	/// @param contractAddress The contract for which the presence of a pending sponsor is checked.195	/// @return **true** if contract has pending sponsor.196	fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {197		Ok(match Sponsoring::<T>::get(contract_address) {198			SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,199			SponsorshipState::Unconfirmed(_) => true,200		})201	}202203	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {204		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)205	}206207	fn set_sponsoring_mode(208		&mut self,209		caller: caller,210		contract_address: address,211		// TODO: implement support for enums in evm-coder212		mode: uint8,213	) -> Result<void> {214		self.recorder().consume_sload()?;215		self.recorder().consume_sstore()?;216217		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;218		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;219		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);220221		Ok(())222	}223224	/// Get current contract sponsoring rate limit225	/// @param contractAddress Contract to get sponsoring rate limit of226	/// @return uint32 Amount of blocks between two sponsored transactions227	fn sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {228		self.recorder().consume_sload()?;229230		Ok(<SponsoringRateLimit<T>>::get(contract_address)231			.try_into()232			.map_err(|_| "rate limit > u32::MAX")?)233	}234235	/// Set contract sponsoring rate limit236	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should237	///  pass between two sponsored transactions238	/// @param contractAddress Contract to change sponsoring rate limit of239	/// @param rateLimit Target rate limit240	/// @dev Only contract owner can change this setting241	fn set_sponsoring_rate_limit(242		&mut self,243		caller: caller,244		contract_address: address,245		rate_limit: uint32,246	) -> Result<void> {247		self.recorder().consume_sload()?;248		self.recorder().consume_sstore()?;249250		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;251		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());252		Ok(())253	}254255	/// Set contract sponsoring fee limit256	/// @dev Sponsoring fee limit - is maximum fee that could be spent by257	///  single transaction258	/// @param contractAddress Contract to change sponsoring fee limit of259	/// @param feeLimit Fee limit260	/// @dev Only contract owner can change this setting261	fn set_sponsoring_fee_limit(262		&mut self,263		caller: caller,264		contract_address: address,265		fee_limit: uint256,266	) -> Result<void> {267		self.recorder().consume_sload()?;268		self.recorder().consume_sstore()?;269270		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;271		<Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())272			.map_err(dispatch_to_evm::<T>)?;273		Ok(())274	}275276	/// Get current contract sponsoring fee limit277	/// @param contractAddress Contract to get sponsoring fee limit of278	/// @return uint256 Maximum amount of fee that could be spent by single279	///  transaction280	fn sponsoring_fee_limit(&self, contract_address: address) -> Result<uint256> {281		self.recorder().consume_sload()?;282283		Ok(get_sponsoring_fee_limit::<T>(contract_address))284	}285286	/// Is specified user present in contract allow list287	/// @dev Contract owner always implicitly included288	/// @param contractAddress Contract to check allowlist of289	/// @param user User to check290	/// @return bool Is specified users exists in contract allowlist291	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {292		self.0.consume_sload()?;293		Ok(<Pallet<T>>::allowed(contract_address, user))294	}295296	/// Toggle user presence in contract allowlist297	/// @param contractAddress Contract to change allowlist of298	/// @param user Which user presence should be toggled299	/// @param isAllowed `true` if user should be allowed to be sponsored300	///  or call this contract, `false` otherwise301	/// @dev Only contract owner can change this setting302	fn toggle_allowed(303		&mut self,304		caller: caller,305		contract_address: address,306		user: address,307		is_allowed: bool,308	) -> Result<void> {309		self.recorder().consume_sload()?;310		self.recorder().consume_sstore()?;311312		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;313		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);314315		Ok(())316	}317318	/// Is this contract has allowlist access enabled319	/// @dev Allowlist always can have users, and it is used for two purposes:320	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist321	///  in case of allowlist access enabled, only users from allowlist may call this contract322	/// @param contractAddress Contract to get allowlist access of323	/// @return bool Is specified contract has allowlist access enabled324	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {325		Ok(<AllowlistEnabled<T>>::get(contract_address))326	}327328	/// Toggle contract allowlist access329	/// @param contractAddress Contract to change allowlist access of330	/// @param enabled Should allowlist access to be enabled?331	fn toggle_allowlist(332		&mut self,333		caller: caller,334		contract_address: address,335		enabled: bool,336	) -> Result<void> {337		self.recorder().consume_sload()?;338		self.recorder().consume_sstore()?;339340		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;341		<Pallet<T>>::toggle_allowlist(contract_address, enabled);342		Ok(())343	}344}345346/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]347pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);348impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>349where350	T::AccountId: AsRef<[u8; 32]>,351{352	fn is_reserved(contract: &sp_core::H160) -> bool {353		contract == &T::ContractAddress::get()354	}355356	fn is_used(contract: &sp_core::H160) -> bool {357		contract == &T::ContractAddress::get()358	}359360	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {361		// TODO: Extract to another OnMethodCall handler362		if <AllowlistEnabled<T>>::get(handle.code_address())363			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)364		{365			return Some(Err(PrecompileFailure::Revert {366				exit_status: ExitRevert::Reverted,367				output: {368					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));369					writer.string("Target contract is allowlisted");370					writer.finish()371				},372			}));373		}374375		if handle.code_address() != T::ContractAddress::get() {376			return None;377		}378379		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));380		pallet_evm_coder_substrate::call(handle, helpers)381	}382383	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {384		(contract == &T::ContractAddress::get())385			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())386	}387}388389/// Hooks into contract creation, storing owner of newly deployed contract390pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);391impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {392	fn on_create(owner: H160, contract: H160) {393		<Owner<T>>::insert(contract, owner);394	}395}396397/// Bridge to pallet-sponsoring398pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);399impl<T: Config> SponsorshipHandler<T::CrossAccountId, CallContext>400	for HelpersContractSponsoring<T>401{402	fn get_sponsor(403		who: &T::CrossAccountId,404		call_context: &CallContext,405	) -> Option<T::CrossAccountId> {406		let contract_address = call_context.contract_address;407		let mode = <Pallet<T>>::sponsoring_mode(contract_address);408		if mode == SponsoringModeT::Disabled {409			return None;410		}411412		let sponsor = match <Pallet<T>>::get_sponsor(contract_address) {413			Some(sponsor) => sponsor,414			None => return None,415		};416417		if mode == SponsoringModeT::Allowlisted418			&& !<Pallet<T>>::allowed(contract_address, *who.as_eth())419		{420			return None;421		}422		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;423424		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {425			let limit = <SponsoringRateLimit<T>>::get(contract_address);426427			let timeout = last_tx_block + limit;428			if block_number < timeout {429				return None;430			}431		}432433		let sponsored_fee_limit = get_sponsoring_fee_limit::<T>(contract_address);434435		if call_context.max_fee > sponsored_fee_limit {436			return None;437		}438439		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);440441		Some(sponsor)442	}443}444445fn get_sponsoring_fee_limit<T: Config>(contract_address: address) -> uint256 {446	<SponsoringFeeLimit<T>>::get(contract_address)447		.get(&0xffffffff)448		.cloned()449		.unwrap_or(U256::MAX)450}451452generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);453generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);