git.delta.rocks / unique-network / refs/commits / 231992803ffe

difftreelog

fix rename some methods

Trubnikov Sergey2022-09-19parent: #b85120e.patch.diff
in: master

6 files changed

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 contract1819use core::marker::PhantomData;20use evm_coder::{21	abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,22};23use pallet_evm::{24	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,25	account::CrossAccountId,26};27use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};28use pallet_evm_transaction_payment::CallContext;29use sp_core::{H160, U256};30use up_data_structs::SponsorshipState;31use crate::{32	AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringFeeLimit,33	SponsoringRateLimit, SponsoringModeT, Sponsoring,34};35use frame_support::traits::Get;36use up_sponsorship::SponsorshipHandler;37use sp_std::vec::Vec;3839/// Pallet events.40#[derive(ToLog)]41pub enum ContractHelpersEvents {42	/// Contract sponsor was set.43	ContractSponsorSet {44		/// Contract address of the affected collection.45		#[indexed]46		contract_address: address,47		/// New sponsor address.48		sponsor: address,49	},5051	/// New sponsor was confirm.52	ContractSponsorshipConfirmed {53		/// Contract address of the affected collection.54		#[indexed]55		contract_address: address,56		/// New sponsor address.57		sponsor: address,58	},5960	/// Collection sponsor was removed.61	ContractSponsorRemoved {62		/// Contract address of the affected collection.63		#[indexed]64		contract_address: address,65	},66}6768/// See [`ContractHelpersCall`]69pub struct ContractHelpers<T: Config>(SubstrateRecorder<T>);70impl<T: Config> WithRecorder<T> for ContractHelpers<T> {71	fn recorder(&self) -> &SubstrateRecorder<T> {72		&self.073	}7475	fn into_recorder(self) -> SubstrateRecorder<T> {76		self.077	}78}7980/// @title Magic contract, which allows users to reconfigure other contracts81#[solidity_interface(name = ContractHelpers, events(ContractHelpersEvents))]82impl<T: Config> ContractHelpers<T>83where84	T::AccountId: AsRef<[u8; 32]>,85{86	/// Get user, which deployed specified contract87	/// @dev May return zero address in case if contract is deployed88	///  using uniquenetwork evm-migration pallet, or using other terms not89	///  intended by pallet-evm90	/// @dev Returns zero address if contract does not exists91	/// @param contractAddress Contract to get owner of92	/// @return address Owner of contract93	fn contract_owner(&self, contract_address: address) -> Result<address> {94		Ok(<Owner<T>>::get(contract_address))95	}9697	/// Set sponsor.98	/// @param contractAddress Contract for which a sponsor is being established.99	/// @param sponsor User address who set as pending sponsor.100	fn set_sponsor(101		&mut self,102		caller: caller,103		contract_address: address,104		sponsor: address,105	) -> Result<void> {106		self.recorder().consume_sload()?;107		self.recorder().consume_sstore()?;108109		Pallet::<T>::set_sponsor(110			&T::CrossAccountId::from_eth(caller),111			contract_address,112			&T::CrossAccountId::from_eth(sponsor),113		)114		.map_err(dispatch_to_evm::<T>)?;115116		Ok(())117	}118119	/// Set contract as self sponsored.120	///121	/// @param contractAddress Contract for which a self sponsoring is being enabled.122	fn self_sponsored_enable(&mut self, caller: caller, contract_address: address) -> Result<void> {123		self.recorder().consume_sload()?;124		self.recorder().consume_sstore()?;125126		let caller = T::CrossAccountId::from_eth(caller);127128		Pallet::<T>::ensure_owner(contract_address, *caller.as_eth())129			.map_err(dispatch_to_evm::<T>)?;130131		Pallet::<T>::force_set_sponsor(132			contract_address,133			&T::CrossAccountId::from_eth(contract_address),134		)135		.map_err(dispatch_to_evm::<T>)?;136137		Ok(())138	}139140	/// Remove sponsor.141	///142	/// @param contractAddress Contract for which a sponsorship is being removed.143	fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {144		self.recorder().consume_sload()?;145		self.recorder().consume_sstore()?;146147		Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)148			.map_err(dispatch_to_evm::<T>)?;149150		Ok(())151	}152153	/// Confirm sponsorship.154	///155	/// @dev Caller must be same that set via [`setSponsor`].156	///157	/// @param contractAddress Сontract for which need to confirm sponsorship.158	fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {159		self.recorder().consume_sload()?;160		self.recorder().consume_sstore()?;161162		Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)163			.map_err(dispatch_to_evm::<T>)?;164165		Ok(())166	}167168	/// Get current sponsor.169	///170	/// @param contractAddress The contract for which a sponsor is requested.171	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.172	fn get_sponsor(&self, contract_address: address) -> Result<(address, uint256)> {173		let sponsor =174			Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;175		Ok(pallet_common::eth::convert_cross_account_to_tuple::<T>(176			&sponsor,177		))178	}179180	/// Check tat contract has confirmed sponsor.181	///182	/// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.183	/// @return **true** if contract has confirmed sponsor.184	fn has_sponsor(&self, contract_address: address) -> Result<bool> {185		Ok(Pallet::<T>::get_sponsor(contract_address).is_some())186	}187188	/// Check tat contract has pending sponsor.189	///190	/// @param contractAddress The contract for which the presence of a pending sponsor is checked.191	/// @return **true** if contract has pending sponsor.192	fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {193		Ok(match Sponsoring::<T>::get(contract_address) {194			SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,195			SponsorshipState::Unconfirmed(_) => true,196		})197	}198199	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {200		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)201	}202203	fn set_sponsoring_mode(204		&mut self,205		caller: caller,206		contract_address: address,207		// TODO: implement support for enums in evm-coder208		mode: uint8,209	) -> Result<void> {210		self.recorder().consume_sload()?;211		self.recorder().consume_sstore()?;212213		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;214		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;215		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);216217		Ok(())218	}219220	/// Get current contract sponsoring rate limit221	/// @param contractAddress Contract to get sponsoring rate limit of222	/// @return uint32 Amount of blocks between two sponsored transactions223	fn get_sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {224		self.recorder().consume_sload()?;225226		Ok(<SponsoringRateLimit<T>>::get(contract_address)227			.try_into()228			.map_err(|_| "rate limit > u32::MAX")?)229	}230231	/// Set contract sponsoring rate limit232	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should233	///  pass between two sponsored transactions234	/// @param contractAddress Contract to change sponsoring rate limit of235	/// @param rateLimit Target rate limit236	/// @dev Only contract owner can change this setting237	fn set_sponsoring_rate_limit(238		&mut self,239		caller: caller,240		contract_address: address,241		rate_limit: uint32,242	) -> Result<void> {243		self.recorder().consume_sload()?;244		self.recorder().consume_sstore()?;245246		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;247		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());248		Ok(())249	}250251	/// Set contract sponsoring fee limit252	/// @dev Sponsoring fee limit - is maximum fee that could be spent by253	///  single transaction254	/// @param contractAddress Contract to change sponsoring fee limit of255	/// @param feeLimit Fee limit256	/// @dev Only contract owner can change this setting257	fn set_sponsoring_fee_limit(258		&mut self,259		caller: caller,260		contract_address: address,261		fee_limit: uint256,262	) -> Result<void> {263		self.recorder().consume_sload()?;264		self.recorder().consume_sstore()?;265266		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;267		<Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())268			.map_err(dispatch_to_evm::<T>)?;269		Ok(())270	}271272	/// Get current contract sponsoring fee limit273	/// @param contractAddress Contract to get sponsoring fee limit of274	/// @return uint256 Maximum amount of fee that could be spent by single275	///  transaction276	fn get_sponsoring_fee_limit(&self, contract_address: address) -> Result<uint256> {277		self.recorder().consume_sload()?;278279		Ok(get_sponsoring_fee_limit::<T>(contract_address))280	}281282	/// Is specified user present in contract allow list283	/// @dev Contract owner always implicitly included284	/// @param contractAddress Contract to check allowlist of285	/// @param user User to check286	/// @return bool Is specified users exists in contract allowlist287	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {288		self.0.consume_sload()?;289		Ok(<Pallet<T>>::allowed(contract_address, user))290	}291292	/// Toggle user presence in contract allowlist293	/// @param contractAddress Contract to change allowlist of294	/// @param user Which user presence should be toggled295	/// @param isAllowed `true` if user should be allowed to be sponsored296	///  or call this contract, `false` otherwise297	/// @dev Only contract owner can change this setting298	fn toggle_allowed(299		&mut self,300		caller: caller,301		contract_address: address,302		user: address,303		is_allowed: bool,304	) -> Result<void> {305		self.recorder().consume_sload()?;306		self.recorder().consume_sstore()?;307308		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;309		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);310311		Ok(())312	}313314	/// Is this contract has allowlist access enabled315	/// @dev Allowlist always can have users, and it is used for two purposes:316	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist317	///  in case of allowlist access enabled, only users from allowlist may call this contract318	/// @param contractAddress Contract to get allowlist access of319	/// @return bool Is specified contract has allowlist access enabled320	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {321		Ok(<AllowlistEnabled<T>>::get(contract_address))322	}323324	/// Toggle contract allowlist access325	/// @param contractAddress Contract to change allowlist access of326	/// @param enabled Should allowlist access to be enabled?327	fn toggle_allowlist(328		&mut self,329		caller: caller,330		contract_address: address,331		enabled: bool,332	) -> Result<void> {333		self.recorder().consume_sload()?;334		self.recorder().consume_sstore()?;335336		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;337		<Pallet<T>>::toggle_allowlist(contract_address, enabled);338		Ok(())339	}340}341342/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]343pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);344impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>345where346	T::AccountId: AsRef<[u8; 32]>,347{348	fn is_reserved(contract: &sp_core::H160) -> bool {349		contract == &T::ContractAddress::get()350	}351352	fn is_used(contract: &sp_core::H160) -> bool {353		contract == &T::ContractAddress::get()354	}355356	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {357		// TODO: Extract to another OnMethodCall handler358		if <AllowlistEnabled<T>>::get(handle.code_address())359			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)360		{361			return Some(Err(PrecompileFailure::Revert {362				exit_status: ExitRevert::Reverted,363				output: {364					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));365					writer.string("Target contract is allowlisted");366					writer.finish()367				},368			}));369		}370371		if handle.code_address() != T::ContractAddress::get() {372			return None;373		}374375		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));376		pallet_evm_coder_substrate::call(handle, helpers)377	}378379	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {380		(contract == &T::ContractAddress::get())381			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())382	}383}384385/// Hooks into contract creation, storing owner of newly deployed contract386pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);387impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {388	fn on_create(owner: H160, contract: H160) {389		<Owner<T>>::insert(contract, owner);390	}391}392393/// Bridge to pallet-sponsoring394pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);395impl<T: Config> SponsorshipHandler<T::CrossAccountId, CallContext>396	for HelpersContractSponsoring<T>397{398	fn get_sponsor(399		who: &T::CrossAccountId,400		call_context: &CallContext,401	) -> Option<T::CrossAccountId> {402		let contract_address = call_context.contract_address;403		let mode = <Pallet<T>>::sponsoring_mode(contract_address);404		if mode == SponsoringModeT::Disabled {405			return None;406		}407408		let sponsor = match <Pallet<T>>::get_sponsor(contract_address) {409			Some(sponsor) => sponsor,410			None => return None,411		};412413		if mode == SponsoringModeT::Allowlisted414			&& !<Pallet<T>>::allowed(contract_address, *who.as_eth())415		{416			return None;417		}418		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;419420		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {421			let limit = <SponsoringRateLimit<T>>::get(contract_address);422423			let timeout = last_tx_block + limit;424			if block_number < timeout {425				return None;426			}427		}428429		let sponsored_fee_limit = get_sponsoring_fee_limit::<T>(contract_address);430431		if call_context.max_fee > sponsored_fee_limit {432			return None;433		}434435		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);436437		Some(sponsor)438	}439}440441fn get_sponsoring_fee_limit<T: Config>(contract_address: address) -> uint256 {442	<SponsoringFeeLimit<T>>::get(contract_address)443		.get(&0xffffffff)444		.cloned()445		.unwrap_or(U256::MAX)446}447448generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);449generate_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 contract1819use core::marker::PhantomData;20use evm_coder::{21	abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,22};23use pallet_evm::{24	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,25	account::CrossAccountId,26};27use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};28use pallet_evm_transaction_payment::CallContext;29use sp_core::{H160, U256};30use up_data_structs::SponsorshipState;31use crate::{32	AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringFeeLimit,33	SponsoringRateLimit, SponsoringModeT, Sponsoring,34};35use frame_support::traits::Get;36use up_sponsorship::SponsorshipHandler;37use sp_std::vec::Vec;3839/// Pallet events.40#[derive(ToLog)]41pub enum ContractHelpersEvents {42	/// Contract sponsor was set.43	ContractSponsorSet {44		/// Contract address of the affected collection.45		#[indexed]46		contract_address: address,47		/// New sponsor address.48		sponsor: address,49	},5051	/// New sponsor was confirm.52	ContractSponsorshipConfirmed {53		/// Contract address of the affected collection.54		#[indexed]55		contract_address: address,56		/// New sponsor address.57		sponsor: address,58	},5960	/// Collection sponsor was removed.61	ContractSponsorRemoved {62		/// Contract address of the affected collection.63		#[indexed]64		contract_address: address,65	},66}6768/// See [`ContractHelpersCall`]69pub struct ContractHelpers<T: Config>(SubstrateRecorder<T>);70impl<T: Config> WithRecorder<T> for ContractHelpers<T> {71	fn recorder(&self) -> &SubstrateRecorder<T> {72		&self.073	}7475	fn into_recorder(self) -> SubstrateRecorder<T> {76		self.077	}78}7980/// @title Magic contract, which allows users to reconfigure other contracts81#[solidity_interface(name = ContractHelpers, events(ContractHelpersEvents))]82impl<T: Config> ContractHelpers<T>83where84	T::AccountId: AsRef<[u8; 32]>,85{86	/// Get user, which deployed specified contract87	/// @dev May return zero address in case if contract is deployed88	///  using uniquenetwork evm-migration pallet, or using other terms not89	///  intended by pallet-evm90	/// @dev Returns zero address if contract does not exists91	/// @param contractAddress Contract to get owner of92	/// @return address Owner of contract93	fn contract_owner(&self, contract_address: address) -> Result<address> {94		Ok(<Owner<T>>::get(contract_address))95	}9697	/// Set sponsor.98	/// @param contractAddress Contract for which a sponsor is being established.99	/// @param sponsor User address who set as pending sponsor.100	fn set_sponsor(101		&mut self,102		caller: caller,103		contract_address: address,104		sponsor: address,105	) -> Result<void> {106		self.recorder().consume_sload()?;107		self.recorder().consume_sstore()?;108109		Pallet::<T>::set_sponsor(110			&T::CrossAccountId::from_eth(caller),111			contract_address,112			&T::CrossAccountId::from_eth(sponsor),113		)114		.map_err(dispatch_to_evm::<T>)?;115116		Ok(())117	}118119	/// Set contract as self sponsored.120	///121	/// @param contractAddress Contract for which a self sponsoring is being enabled.122	fn self_sponsored_enable(&mut self, caller: caller, contract_address: address) -> Result<void> {123		self.recorder().consume_sload()?;124		self.recorder().consume_sstore()?;125126		let caller = T::CrossAccountId::from_eth(caller);127128		Pallet::<T>::ensure_owner(contract_address, *caller.as_eth())129			.map_err(dispatch_to_evm::<T>)?;130131		Pallet::<T>::force_set_sponsor(132			contract_address,133			&T::CrossAccountId::from_eth(contract_address),134		)135		.map_err(dispatch_to_evm::<T>)?;136137		Ok(())138	}139140	/// Remove sponsor.141	///142	/// @param contractAddress Contract for which a sponsorship is being removed.143	fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {144		self.recorder().consume_sload()?;145		self.recorder().consume_sstore()?;146147		Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)148			.map_err(dispatch_to_evm::<T>)?;149150		Ok(())151	}152153	/// Confirm sponsorship.154	///155	/// @dev Caller must be same that set via [`setSponsor`].156	///157	/// @param contractAddress Сontract for which need to confirm sponsorship.158	fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {159		self.recorder().consume_sload()?;160		self.recorder().consume_sstore()?;161162		Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)163			.map_err(dispatch_to_evm::<T>)?;164165		Ok(())166	}167168	/// Get current sponsor.169	///170	/// @param contractAddress The contract for which a sponsor is requested.171	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.172	fn sponsor(&self, contract_address: address) -> Result<(address, uint256)> {173		let sponsor =174			Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;175		Ok(pallet_common::eth::convert_cross_account_to_tuple::<T>(176			&sponsor,177		))178	}179180	/// Check tat contract has confirmed sponsor.181	///182	/// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.183	/// @return **true** if contract has confirmed sponsor.184	fn has_sponsor(&self, contract_address: address) -> Result<bool> {185		Ok(Pallet::<T>::get_sponsor(contract_address).is_some())186	}187188	/// Check tat contract has pending sponsor.189	///190	/// @param contractAddress The contract for which the presence of a pending sponsor is checked.191	/// @return **true** if contract has pending sponsor.192	fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {193		Ok(match Sponsoring::<T>::get(contract_address) {194			SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,195			SponsorshipState::Unconfirmed(_) => true,196		})197	}198199	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {200		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)201	}202203	fn set_sponsoring_mode(204		&mut self,205		caller: caller,206		contract_address: address,207		// TODO: implement support for enums in evm-coder208		mode: uint8,209	) -> Result<void> {210		self.recorder().consume_sload()?;211		self.recorder().consume_sstore()?;212213		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;214		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;215		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);216217		Ok(())218	}219220	/// Get current contract sponsoring rate limit221	/// @param contractAddress Contract to get sponsoring rate limit of222	/// @return uint32 Amount of blocks between two sponsored transactions223	fn sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {224		self.recorder().consume_sload()?;225226		Ok(<SponsoringRateLimit<T>>::get(contract_address)227			.try_into()228			.map_err(|_| "rate limit > u32::MAX")?)229	}230231	/// Set contract sponsoring rate limit232	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should233	///  pass between two sponsored transactions234	/// @param contractAddress Contract to change sponsoring rate limit of235	/// @param rateLimit Target rate limit236	/// @dev Only contract owner can change this setting237	fn set_sponsoring_rate_limit(238		&mut self,239		caller: caller,240		contract_address: address,241		rate_limit: uint32,242	) -> Result<void> {243		self.recorder().consume_sload()?;244		self.recorder().consume_sstore()?;245246		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;247		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());248		Ok(())249	}250251	/// Set contract sponsoring fee limit252	/// @dev Sponsoring fee limit - is maximum fee that could be spent by253	///  single transaction254	/// @param contractAddress Contract to change sponsoring fee limit of255	/// @param feeLimit Fee limit256	/// @dev Only contract owner can change this setting257	fn set_sponsoring_fee_limit(258		&mut self,259		caller: caller,260		contract_address: address,261		fee_limit: uint256,262	) -> Result<void> {263		self.recorder().consume_sload()?;264		self.recorder().consume_sstore()?;265266		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;267		<Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())268			.map_err(dispatch_to_evm::<T>)?;269		Ok(())270	}271272	/// Get current contract sponsoring fee limit273	/// @param contractAddress Contract to get sponsoring fee limit of274	/// @return uint256 Maximum amount of fee that could be spent by single275	///  transaction276	fn sponsoring_fee_limit(&self, contract_address: address) -> Result<uint256> {277		self.recorder().consume_sload()?;278279		Ok(get_sponsoring_fee_limit::<T>(contract_address))280	}281282	/// Is specified user present in contract allow list283	/// @dev Contract owner always implicitly included284	/// @param contractAddress Contract to check allowlist of285	/// @param user User to check286	/// @return bool Is specified users exists in contract allowlist287	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {288		self.0.consume_sload()?;289		Ok(<Pallet<T>>::allowed(contract_address, user))290	}291292	/// Toggle user presence in contract allowlist293	/// @param contractAddress Contract to change allowlist of294	/// @param user Which user presence should be toggled295	/// @param isAllowed `true` if user should be allowed to be sponsored296	///  or call this contract, `false` otherwise297	/// @dev Only contract owner can change this setting298	fn toggle_allowed(299		&mut self,300		caller: caller,301		contract_address: address,302		user: address,303		is_allowed: bool,304	) -> Result<void> {305		self.recorder().consume_sload()?;306		self.recorder().consume_sstore()?;307308		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;309		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);310311		Ok(())312	}313314	/// Is this contract has allowlist access enabled315	/// @dev Allowlist always can have users, and it is used for two purposes:316	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist317	///  in case of allowlist access enabled, only users from allowlist may call this contract318	/// @param contractAddress Contract to get allowlist access of319	/// @return bool Is specified contract has allowlist access enabled320	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {321		Ok(<AllowlistEnabled<T>>::get(contract_address))322	}323324	/// Toggle contract allowlist access325	/// @param contractAddress Contract to change allowlist access of326	/// @param enabled Should allowlist access to be enabled?327	fn toggle_allowlist(328		&mut self,329		caller: caller,330		contract_address: address,331		enabled: bool,332	) -> Result<void> {333		self.recorder().consume_sload()?;334		self.recorder().consume_sstore()?;335336		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;337		<Pallet<T>>::toggle_allowlist(contract_address, enabled);338		Ok(())339	}340}341342/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]343pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);344impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>345where346	T::AccountId: AsRef<[u8; 32]>,347{348	fn is_reserved(contract: &sp_core::H160) -> bool {349		contract == &T::ContractAddress::get()350	}351352	fn is_used(contract: &sp_core::H160) -> bool {353		contract == &T::ContractAddress::get()354	}355356	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {357		// TODO: Extract to another OnMethodCall handler358		if <AllowlistEnabled<T>>::get(handle.code_address())359			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)360		{361			return Some(Err(PrecompileFailure::Revert {362				exit_status: ExitRevert::Reverted,363				output: {364					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));365					writer.string("Target contract is allowlisted");366					writer.finish()367				},368			}));369		}370371		if handle.code_address() != T::ContractAddress::get() {372			return None;373		}374375		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));376		pallet_evm_coder_substrate::call(handle, helpers)377	}378379	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {380		(contract == &T::ContractAddress::get())381			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())382	}383}384385/// Hooks into contract creation, storing owner of newly deployed contract386pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);387impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {388	fn on_create(owner: H160, contract: H160) {389		<Owner<T>>::insert(contract, owner);390	}391}392393/// Bridge to pallet-sponsoring394pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);395impl<T: Config> SponsorshipHandler<T::CrossAccountId, CallContext>396	for HelpersContractSponsoring<T>397{398	fn get_sponsor(399		who: &T::CrossAccountId,400		call_context: &CallContext,401	) -> Option<T::CrossAccountId> {402		let contract_address = call_context.contract_address;403		let mode = <Pallet<T>>::sponsoring_mode(contract_address);404		if mode == SponsoringModeT::Disabled {405			return None;406		}407408		let sponsor = match <Pallet<T>>::get_sponsor(contract_address) {409			Some(sponsor) => sponsor,410			None => return None,411		};412413		if mode == SponsoringModeT::Allowlisted414			&& !<Pallet<T>>::allowed(contract_address, *who.as_eth())415		{416			return None;417		}418		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;419420		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {421			let limit = <SponsoringRateLimit<T>>::get(contract_address);422423			let timeout = last_tx_block + limit;424			if block_number < timeout {425				return None;426			}427		}428429		let sponsored_fee_limit = get_sponsoring_fee_limit::<T>(contract_address);430431		if call_context.max_fee > sponsored_fee_limit {432			return None;433		}434435		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);436437		Some(sponsor)438	}439}440441fn get_sponsoring_fee_limit<T: Config>(contract_address: address) -> uint256 {442	<SponsoringFeeLimit<T>>::get(contract_address)443		.get(&0xffffffff)444		.cloned()445		.unwrap_or(U256::MAX)446}447448generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);449generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);
modifiedpallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/evm-contract-helpers/src/stubs/ContractHelpers.soldiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
+++ b/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
@@ -25,7 +25,7 @@
 }
 
 /// @title Magic contract, which allows users to reconfigure other contracts
-/// @dev the ERC-165 identifier for this interface is 0x172cb4fb
+/// @dev the ERC-165 identifier for this interface is 0x30afad04
 contract ContractHelpers is Dummy, ERC165, ContractHelpersEvents {
 	/// Get user, which deployed specified contract
 	/// @dev May return zero address in case if contract is deployed
@@ -94,9 +94,9 @@
 	///
 	/// @param contractAddress The contract for which a sponsor is requested.
 	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
-	/// @dev EVM selector for this function is: 0x743fc745,
-	///  or in textual repr: getSponsor(address)
-	function getSponsor(address contractAddress) public view returns (Tuple0 memory) {
+	/// @dev EVM selector for this function is: 0x766c4f37,
+	///  or in textual repr: sponsor(address)
+	function sponsor(address contractAddress) public view returns (Tuple0 memory) {
 		require(false, stub_error);
 		contractAddress;
 		dummy;
@@ -150,9 +150,9 @@
 	/// Get current contract sponsoring rate limit
 	/// @param contractAddress Contract to get sponsoring rate limit of
 	/// @return uint32 Amount of blocks between two sponsored transactions
-	/// @dev EVM selector for this function is: 0x610cfabd,
-	///  or in textual repr: getSponsoringRateLimit(address)
-	function getSponsoringRateLimit(address contractAddress) public view returns (uint32) {
+	/// @dev EVM selector for this function is: 0xf29694d8,
+	///  or in textual repr: sponsoringRateLimit(address)
+	function sponsoringRateLimit(address contractAddress) public view returns (uint32) {
 		require(false, stub_error);
 		contractAddress;
 		dummy;
@@ -193,9 +193,9 @@
 	/// @param contractAddress Contract to get sponsoring fee limit of
 	/// @return uint256 Maximum amount of fee that could be spent by single
 	///  transaction
-	/// @dev EVM selector for this function is: 0xc3fdc9ee,
-	///  or in textual repr: getSponsoringFeeLimit(address)
-	function getSponsoringFeeLimit(address contractAddress) public view returns (uint256) {
+	/// @dev EVM selector for this function is: 0x75b73606,
+	///  or in textual repr: sponsoringFeeLimit(address)
+	function sponsoringFeeLimit(address contractAddress) public view returns (uint256) {
 		require(false, stub_error);
 		contractAddress;
 		dummy;
modifiedtests/src/eth/api/ContractHelpers.soldiffbeforeafterboth
--- a/tests/src/eth/api/ContractHelpers.sol
+++ b/tests/src/eth/api/ContractHelpers.sol
@@ -20,7 +20,7 @@
 }
 
 /// @title Magic contract, which allows users to reconfigure other contracts
-/// @dev the ERC-165 identifier for this interface is 0x172cb4fb
+/// @dev the ERC-165 identifier for this interface is 0x30afad04
 interface ContractHelpers is Dummy, ERC165, ContractHelpersEvents {
 	/// Get user, which deployed specified contract
 	/// @dev May return zero address in case if contract is deployed
@@ -67,9 +67,9 @@
 	///
 	/// @param contractAddress The contract for which a sponsor is requested.
 	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
-	/// @dev EVM selector for this function is: 0x743fc745,
-	///  or in textual repr: getSponsor(address)
-	function getSponsor(address contractAddress) external view returns (Tuple0 memory);
+	/// @dev EVM selector for this function is: 0x766c4f37,
+	///  or in textual repr: sponsor(address)
+	function sponsor(address contractAddress) external view returns (Tuple0 memory);
 
 	/// Check tat contract has confirmed sponsor.
 	///
@@ -98,9 +98,9 @@
 	/// Get current contract sponsoring rate limit
 	/// @param contractAddress Contract to get sponsoring rate limit of
 	/// @return uint32 Amount of blocks between two sponsored transactions
-	/// @dev EVM selector for this function is: 0x610cfabd,
-	///  or in textual repr: getSponsoringRateLimit(address)
-	function getSponsoringRateLimit(address contractAddress) external view returns (uint32);
+	/// @dev EVM selector for this function is: 0xf29694d8,
+	///  or in textual repr: sponsoringRateLimit(address)
+	function sponsoringRateLimit(address contractAddress) external view returns (uint32);
 
 	/// Set contract sponsoring rate limit
 	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should
@@ -126,9 +126,9 @@
 	/// @param contractAddress Contract to get sponsoring fee limit of
 	/// @return uint256 Maximum amount of fee that could be spent by single
 	///  transaction
-	/// @dev EVM selector for this function is: 0xc3fdc9ee,
-	///  or in textual repr: getSponsoringFeeLimit(address)
-	function getSponsoringFeeLimit(address contractAddress) external view returns (uint256);
+	/// @dev EVM selector for this function is: 0x75b73606,
+	///  or in textual repr: sponsoringFeeLimit(address)
+	function sponsoringFeeLimit(address contractAddress) external view returns (uint256);
 
 	/// Is specified user present in contract allow list
 	/// @dev Contract owner always implicitly included
modifiedtests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -223,7 +223,7 @@
     const helpers = contractHelpers(web3, owner);
     await helpers.methods.selfSponsoredEnable(flipper.options.address).send();
     
-    const result = await helpers.methods.getSponsor(flipper.options.address).call();
+    const result = await helpers.methods.sponsor(flipper.options.address).call();
 
     expect(result[0]).to.be.eq(flipper.options.address);
     expect(result[1]).to.be.eq('0');
@@ -237,7 +237,7 @@
     await helpers.methods.setSponsor(flipper.options.address, sponsor).send();
     await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});
     
-    const result = await helpers.methods.getSponsor(flipper.options.address).call();
+    const result = await helpers.methods.sponsor(flipper.options.address).call();
 
     expect(result[0]).to.be.eq(sponsor);
     expect(result[1]).to.be.eq('0');
@@ -482,7 +482,7 @@
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
     const flipper = await deployFlipper(web3, owner);
     const helpers = contractHelpers(web3, owner);
-    expect(await helpers.methods.getSponsoringRateLimit(flipper.options.address).call()).to.be.equals('7200');
+    expect(await helpers.methods.sponsoringRateLimit(flipper.options.address).call()).to.be.equals('7200');
   });
 });
 
@@ -551,7 +551,7 @@
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
     const flipper = await deployFlipper(web3, owner);
     const helpers = contractHelpers(web3, owner);
-    expect(await helpers.methods.getSponsoringFeeLimit(flipper.options.address).call()).to.be.equals('115792089237316195423570985008687907853269984665640564039457584007913129639935');
+    expect(await helpers.methods.sponsoringFeeLimit(flipper.options.address).call()).to.be.equals('115792089237316195423570985008687907853269984665640564039457584007913129639935');
   });
 
   itWeb3('Set fee limit', async ({api, web3, privateKeyWrapper}) => {
@@ -559,7 +559,7 @@
     const flipper = await deployFlipper(web3, owner);
     const helpers = contractHelpers(web3, owner);
     await helpers.methods.setSponsoringFeeLimit(flipper.options.address, 100).send();
-    expect(await helpers.methods.getSponsoringFeeLimit(flipper.options.address).call()).to.be.equals('100');
+    expect(await helpers.methods.sponsoringFeeLimit(flipper.options.address).call()).to.be.equals('100');
   });
 
   itWeb3('Negative test - set fee limit by non-owner', async ({api, web3, privateKeyWrapper}) => {
modifiedtests/src/eth/util/contractHelpersAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/util/contractHelpersAbi.json
+++ b/tests/src/eth/util/contractHelpersAbi.json
@@ -111,18 +111,8 @@
         "type": "address"
       }
     ],
-    "name": "getSponsor",
-    "outputs": [
-      {
-        "components": [
-          { "internalType": "address", "name": "field_0", "type": "address" },
-          { "internalType": "uint256", "name": "field_1", "type": "uint256" }
-        ],
-        "internalType": "struct Tuple0",
-        "name": "",
-        "type": "tuple"
-      }
-    ],
+    "name": "hasPendingSponsor",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "view",
     "type": "function"
   },
@@ -134,8 +124,8 @@
         "type": "address"
       }
     ],
-    "name": "getSponsoringFeeLimit",
-    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+    "name": "hasSponsor",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "view",
     "type": "function"
   },
@@ -147,9 +137,9 @@
         "type": "address"
       }
     ],
-    "name": "getSponsoringRateLimit",
-    "outputs": [{ "internalType": "uint32", "name": "", "type": "uint32" }],
-    "stateMutability": "view",
+    "name": "removeSponsor",
+    "outputs": [],
+    "stateMutability": "nonpayable",
     "type": "function"
   },
   {
@@ -160,9 +150,9 @@
         "type": "address"
       }
     ],
-    "name": "hasPendingSponsor",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
-    "stateMutability": "view",
+    "name": "selfSponsoredEnable",
+    "outputs": [],
+    "stateMutability": "nonpayable",
     "type": "function"
   },
   {
@@ -171,11 +161,12 @@
         "internalType": "address",
         "name": "contractAddress",
         "type": "address"
-      }
+      },
+      { "internalType": "address", "name": "sponsor", "type": "address" }
     ],
-    "name": "hasSponsor",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
-    "stateMutability": "view",
+    "name": "setSponsor",
+    "outputs": [],
+    "stateMutability": "nonpayable",
     "type": "function"
   },
   {
@@ -184,9 +175,10 @@
         "internalType": "address",
         "name": "contractAddress",
         "type": "address"
-      }
+      },
+      { "internalType": "uint256", "name": "feeLimit", "type": "uint256" }
     ],
-    "name": "removeSponsor",
+    "name": "setSponsoringFeeLimit",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
@@ -197,9 +189,10 @@
         "internalType": "address",
         "name": "contractAddress",
         "type": "address"
-      }
+      },
+      { "internalType": "uint8", "name": "mode", "type": "uint8" }
     ],
-    "name": "selfSponsoredEnable",
+    "name": "setSponsoringMode",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
@@ -211,9 +204,9 @@
         "name": "contractAddress",
         "type": "address"
       },
-      { "internalType": "address", "name": "sponsor", "type": "address" }
+      { "internalType": "uint32", "name": "rateLimit", "type": "uint32" }
     ],
-    "name": "setSponsor",
+    "name": "setSponsoringRateLimit",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
@@ -224,12 +217,21 @@
         "internalType": "address",
         "name": "contractAddress",
         "type": "address"
-      },
-      { "internalType": "uint256", "name": "feeLimit", "type": "uint256" }
+      }
+    ],
+    "name": "sponsor",
+    "outputs": [
+      {
+        "components": [
+          { "internalType": "address", "name": "field_0", "type": "address" },
+          { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+        ],
+        "internalType": "struct Tuple0",
+        "name": "",
+        "type": "tuple"
+      }
     ],
-    "name": "setSponsoringFeeLimit",
-    "outputs": [],
-    "stateMutability": "nonpayable",
+    "stateMutability": "view",
     "type": "function"
   },
   {
@@ -238,12 +240,11 @@
         "internalType": "address",
         "name": "contractAddress",
         "type": "address"
-      },
-      { "internalType": "uint8", "name": "mode", "type": "uint8" }
+      }
     ],
-    "name": "setSponsoringMode",
-    "outputs": [],
-    "stateMutability": "nonpayable",
+    "name": "sponsoringEnabled",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "view",
     "type": "function"
   },
   {
@@ -252,12 +253,11 @@
         "internalType": "address",
         "name": "contractAddress",
         "type": "address"
-      },
-      { "internalType": "uint32", "name": "rateLimit", "type": "uint32" }
+      }
     ],
-    "name": "setSponsoringRateLimit",
-    "outputs": [],
-    "stateMutability": "nonpayable",
+    "name": "sponsoringFeeLimit",
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+    "stateMutability": "view",
     "type": "function"
   },
   {
@@ -268,8 +268,8 @@
         "type": "address"
       }
     ],
-    "name": "sponsoringEnabled",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "name": "sponsoringRateLimit",
+    "outputs": [{ "internalType": "uint32", "name": "", "type": "uint32" }],
     "stateMutability": "view",
     "type": "function"
   },