git.delta.rocks / unique-network / refs/commits / 837c29c459b6

difftreelog

fix Rename event field name. test: Add eth test for contract sponsor events.

Trubnikov Sergey2022-09-05parent: #ec123de.patch.diff
in: master

7 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_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};24use pallet_evm::{25	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,26	account::CrossAccountId,27};28use sp_core::H160;29use up_data_structs::SponsorshipState;30use crate::{31	AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringRateLimit, SponsoringModeT,32	Sponsoring,33};34use frame_support::traits::Get;35use up_sponsorship::SponsorshipHandler;36use sp_std::vec::Vec;3738/// Pallet events.39#[derive(ToLog)]40pub enum ContractHelpersEvents {41	/// Contract sponsor was set.42	ContractSponsorSet {43		/// Contract address of the affected collection.44		#[indexed]45		contract: address,46		/// New sponsor address.47		#[indexed]48		sponsor: address,49	},5051	/// New sponsor was confirm.52	ContractSponsorshipConfirmed {53		/// Contract address of the affected collection.54		#[indexed]55		contract: address,56		/// New sponsor address.57		#[indexed]58		sponsor: address,59	},6061	/// Collection sponsor was removed.62	ContractSponsorRemoved {63		/// Contract address of the affected collection.64		#[indexed]65		contract: address,66	},67}6869/// See [`ContractHelpersCall`]70pub struct ContractHelpers<T: Config>(SubstrateRecorder<T>);71impl<T: Config> WithRecorder<T> for ContractHelpers<T> {72	fn recorder(&self) -> &SubstrateRecorder<T> {73		&self.074	}7576	fn into_recorder(self) -> SubstrateRecorder<T> {77		self.078	}79}8081/// @title Magic contract, which allows users to reconfigure other contracts82#[solidity_interface(name = ContractHelpers, events(ContractHelpersEvents))]83impl<T: Config> ContractHelpers<T>84where85	T::AccountId: AsRef<[u8; 32]>,86{87	/// Get user, which deployed specified contract88	/// @dev May return zero address in case if contract is deployed89	///  using uniquenetwork evm-migration pallet, or using other terms not90	///  intended by pallet-evm91	/// @dev Returns zero address if contract does not exists92	/// @param contractAddress Contract to get owner of93	/// @return address Owner of contract94	fn contract_owner(&self, contract_address: address) -> Result<address> {95		Ok(<Owner<T>>::get(contract_address))96	}9798	/// Set sponsor.99	/// @param contractAddress Contract for which a sponsor is being established.100	/// @param sponsor User address who set as pending sponsor.101	fn set_sponsor(102		&mut self,103		caller: caller,104		contract_address: address,105		sponsor: address,106	) -> Result<void> {107		self.recorder().consume_sload()?;108		self.recorder().consume_sstore()?;109110		Pallet::<T>::set_sponsor(111			&T::CrossAccountId::from_eth(caller),112			contract_address,113			&T::CrossAccountId::from_eth(sponsor),114		)115		.map_err(dispatch_to_evm::<T>)?;116117		Ok(())118	}119120	/// Set contract as self sponsored.121	///122	/// @param contractAddress Contract for which a self sponsoring is being enabled.123	fn self_sponsored_enable(&mut self, caller: caller, contract_address: address) -> Result<void> {124		self.recorder().consume_sload()?;125		self.recorder().consume_sstore()?;126127		Pallet::<T>::force_set_sponsor(128			&T::CrossAccountId::from_eth(caller),129			contract_address,130			&T::CrossAccountId::from_eth(contract_address),131		)132		.map_err(dispatch_to_evm::<T>)?;133134		Ok(())135	}136137	/// Remove sponsor.138	///139	/// @param contractAddress Contract for which a sponsorship is being removed.140	fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {141		self.recorder().consume_sload()?;142		self.recorder().consume_sstore()?;143144		Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)145			.map_err(dispatch_to_evm::<T>)?;146147		Ok(())148	}149150	/// Confirm sponsorship.151	///152	/// @dev Caller must be same that set via [`setSponsor`].153	///154	/// @param contractAddress Сontract for which need to confirm sponsorship.155	fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {156		self.recorder().consume_sload()?;157		self.recorder().consume_sstore()?;158159		Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)160			.map_err(dispatch_to_evm::<T>)?;161162		Ok(())163	}164165	/// Get current sponsor.166	///167	/// @param contractAddress The contract for which a sponsor is requested.168	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.169	fn get_sponsor(&self, contract_address: address) -> Result<(address, uint256)> {170		let sponsor =171			Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;172		let result: (address, uint256) = if sponsor.is_canonical_substrate() {173			let sponsor = pallet_common::eth::convert_cross_account_to_uint256::<T>(&sponsor);174			(Default::default(), sponsor)175		} else {176			let sponsor = *sponsor.as_eth();177			(sponsor, Default::default())178		};179		Ok(result)180	}181182	/// Check tat contract has confirmed sponsor.183	///184	/// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.185	/// @return **true** if contract has confirmed sponsor.186	fn has_sponsor(&self, contract_address: address) -> Result<bool> {187		Ok(Pallet::<T>::get_sponsor(contract_address).is_some())188	}189190	/// Check tat contract has pending sponsor.191	///192	/// @param contractAddress The contract for which the presence of a pending sponsor is checked.193	/// @return **true** if contract has pending sponsor.194	fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {195		Ok(match Sponsoring::<T>::get(contract_address) {196			SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,197			SponsorshipState::Unconfirmed(_) => true,198		})199	}200201	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {202		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)203	}204205	fn set_sponsoring_mode(206		&mut self,207		caller: caller,208		contract_address: address,209		// TODO: implement support for enums in evm-coder210		mode: uint8,211	) -> Result<void> {212		self.recorder().consume_sload()?;213		self.recorder().consume_sstore()?;214215		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;216		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;217		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);218219		Ok(())220	}221222	/// Get current contract sponsoring rate limit223	/// @param contractAddress Contract to get sponsoring mode of224	/// @return uint32 Amount of blocks between two sponsored transactions225	fn get_sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {226		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	/// Is specified user present in contract allow list252	/// @dev Contract owner always implicitly included253	/// @param contractAddress Contract to check allowlist of254	/// @param user User to check255	/// @return bool Is specified users exists in contract allowlist256	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {257		self.0.consume_sload()?;258		Ok(<Pallet<T>>::allowed(contract_address, user))259	}260261	/// Toggle user presence in contract allowlist262	/// @param contractAddress Contract to change allowlist of263	/// @param user Which user presence should be toggled264	/// @param isAllowed `true` if user should be allowed to be sponsored265	///  or call this contract, `false` otherwise266	/// @dev Only contract owner can change this setting267	fn toggle_allowed(268		&mut self,269		caller: caller,270		contract_address: address,271		user: address,272		is_allowed: bool,273	) -> Result<void> {274		self.recorder().consume_sload()?;275		self.recorder().consume_sstore()?;276277		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;278		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);279280		Ok(())281	}282283	/// Is this contract has allowlist access enabled284	/// @dev Allowlist always can have users, and it is used for two purposes:285	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist286	///  in case of allowlist access enabled, only users from allowlist may call this contract287	/// @param contractAddress Contract to get allowlist access of288	/// @return bool Is specified contract has allowlist access enabled289	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {290		Ok(<AllowlistEnabled<T>>::get(contract_address))291	}292293	/// Toggle contract allowlist access294	/// @param contractAddress Contract to change allowlist access of295	/// @param enabled Should allowlist access to be enabled?296	fn toggle_allowlist(297		&mut self,298		caller: caller,299		contract_address: address,300		enabled: bool,301	) -> Result<void> {302		self.recorder().consume_sload()?;303		self.recorder().consume_sstore()?;304305		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;306		<Pallet<T>>::toggle_allowlist(contract_address, enabled);307		Ok(())308	}309}310311/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]312pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);313impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>314where315	T::AccountId: AsRef<[u8; 32]>,316{317	fn is_reserved(contract: &sp_core::H160) -> bool {318		contract == &T::ContractAddress::get()319	}320321	fn is_used(contract: &sp_core::H160) -> bool {322		contract == &T::ContractAddress::get()323	}324325	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {326		// TODO: Extract to another OnMethodCall handler327		if <AllowlistEnabled<T>>::get(handle.code_address())328			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)329		{330			return Some(Err(PrecompileFailure::Revert {331				exit_status: ExitRevert::Reverted,332				output: {333					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));334					writer.string("Target contract is allowlisted");335					writer.finish()336				},337			}));338		}339340		if handle.code_address() != T::ContractAddress::get() {341			return None;342		}343344		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));345		pallet_evm_coder_substrate::call(handle, helpers)346	}347348	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {349		(contract == &T::ContractAddress::get())350			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())351	}352}353354/// Hooks into contract creation, storing owner of newly deployed contract355pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);356impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {357	fn on_create(owner: H160, contract: H160) {358		<Owner<T>>::insert(contract, owner);359	}360}361362/// Bridge to pallet-sponsoring363pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);364impl<T: Config> SponsorshipHandler<T::CrossAccountId, (H160, Vec<u8>)>365	for HelpersContractSponsoring<T>366{367	fn get_sponsor(who: &T::CrossAccountId, call: &(H160, Vec<u8>)) -> Option<T::CrossAccountId> {368		let (contract_address, _) = call;369		let mode = <Pallet<T>>::sponsoring_mode(*contract_address);370		if mode == SponsoringModeT::Disabled {371			return None;372		}373374		let sponsor = match <Pallet<T>>::get_sponsor(*contract_address) {375			Some(sponsor) => sponsor,376			None => return None,377		};378379		if mode == SponsoringModeT::Allowlisted380			&& !<Pallet<T>>::allowed(*contract_address, *who.as_eth())381		{382			return None;383		}384		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;385386		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {387			let limit = <SponsoringRateLimit<T>>::get(contract_address);388389			let timeout = last_tx_block + limit;390			if block_number < timeout {391				return None;392			}393		}394395		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);396397		Some(sponsor)398	}399}400401generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);402generate_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_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};24use pallet_evm::{25	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,26	account::CrossAccountId,27};28use sp_core::H160;29use up_data_structs::SponsorshipState;30use crate::{31	AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringRateLimit, SponsoringModeT,32	Sponsoring,33};34use frame_support::traits::Get;35use up_sponsorship::SponsorshipHandler;36use sp_std::vec::Vec;3738/// Pallet events.39#[derive(ToLog)]40pub enum ContractHelpersEvents {41	/// Contract sponsor was set.42	ContractSponsorSet {43		/// Contract address of the affected collection.44		#[indexed]45		contract_address: address,46		/// New sponsor address.47		sponsor: address,48	},4950	/// New sponsor was confirm.51	ContractSponsorshipConfirmed {52		/// Contract address of the affected collection.53		#[indexed]54		contract_address: address,55		/// New sponsor address.56		sponsor: address,57	},5859	/// Collection sponsor was removed.60	ContractSponsorRemoved {61		/// Contract address of the affected collection.62		#[indexed]63		contract_address: address,64	},65}6667/// See [`ContractHelpersCall`]68pub struct ContractHelpers<T: Config>(SubstrateRecorder<T>);69impl<T: Config> WithRecorder<T> for ContractHelpers<T> {70	fn recorder(&self) -> &SubstrateRecorder<T> {71		&self.072	}7374	fn into_recorder(self) -> SubstrateRecorder<T> {75		self.076	}77}7879/// @title Magic contract, which allows users to reconfigure other contracts80#[solidity_interface(name = ContractHelpers, events(ContractHelpersEvents))]81impl<T: Config> ContractHelpers<T>82where83	T::AccountId: AsRef<[u8; 32]>,84{85	/// Get user, which deployed specified contract86	/// @dev May return zero address in case if contract is deployed87	///  using uniquenetwork evm-migration pallet, or using other terms not88	///  intended by pallet-evm89	/// @dev Returns zero address if contract does not exists90	/// @param contractAddress Contract to get owner of91	/// @return address Owner of contract92	fn contract_owner(&self, contract_address: address) -> Result<address> {93		Ok(<Owner<T>>::get(contract_address))94	}9596	/// Set sponsor.97	/// @param contractAddress Contract for which a sponsor is being established.98	/// @param sponsor User address who set as pending sponsor.99	fn set_sponsor(100		&mut self,101		caller: caller,102		contract_address: address,103		sponsor: address,104	) -> Result<void> {105		self.recorder().consume_sload()?;106		self.recorder().consume_sstore()?;107108		Pallet::<T>::set_sponsor(109			&T::CrossAccountId::from_eth(caller),110			contract_address,111			&T::CrossAccountId::from_eth(sponsor),112		)113		.map_err(dispatch_to_evm::<T>)?;114115		Ok(())116	}117118	/// Set contract as self sponsored.119	///120	/// @param contractAddress Contract for which a self sponsoring is being enabled.121	fn self_sponsored_enable(&mut self, caller: caller, contract_address: address) -> Result<void> {122		self.recorder().consume_sload()?;123		self.recorder().consume_sstore()?;124125		Pallet::<T>::force_set_sponsor(126			&T::CrossAccountId::from_eth(caller),127			contract_address,128			&T::CrossAccountId::from_eth(contract_address),129		)130		.map_err(dispatch_to_evm::<T>)?;131132		Ok(())133	}134135	/// Remove sponsor.136	///137	/// @param contractAddress Contract for which a sponsorship is being removed.138	fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {139		self.recorder().consume_sload()?;140		self.recorder().consume_sstore()?;141142		Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)143			.map_err(dispatch_to_evm::<T>)?;144145		Ok(())146	}147148	/// Confirm sponsorship.149	///150	/// @dev Caller must be same that set via [`setSponsor`].151	///152	/// @param contractAddress Сontract for which need to confirm sponsorship.153	fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {154		self.recorder().consume_sload()?;155		self.recorder().consume_sstore()?;156157		Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)158			.map_err(dispatch_to_evm::<T>)?;159160		Ok(())161	}162163	/// Get current sponsor.164	///165	/// @param contractAddress The contract for which a sponsor is requested.166	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.167	fn get_sponsor(&self, contract_address: address) -> Result<(address, uint256)> {168		let sponsor =169			Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;170		let result: (address, uint256) = if sponsor.is_canonical_substrate() {171			let sponsor = pallet_common::eth::convert_cross_account_to_uint256::<T>(&sponsor);172			(Default::default(), sponsor)173		} else {174			let sponsor = *sponsor.as_eth();175			(sponsor, Default::default())176		};177		Ok(result)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 mode of222	/// @return uint32 Amount of blocks between two sponsored transactions223	fn get_sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {224		Ok(<SponsoringRateLimit<T>>::get(contract_address)225			.try_into()226			.map_err(|_| "rate limit > u32::MAX")?)227	}228229	/// Set contract sponsoring rate limit230	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should231	///  pass between two sponsored transactions232	/// @param contractAddress Contract to change sponsoring rate limit of233	/// @param rateLimit Target rate limit234	/// @dev Only contract owner can change this setting235	fn set_sponsoring_rate_limit(236		&mut self,237		caller: caller,238		contract_address: address,239		rate_limit: uint32,240	) -> Result<void> {241		self.recorder().consume_sload()?;242		self.recorder().consume_sstore()?;243244		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;245		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());246		Ok(())247	}248249	/// Is specified user present in contract allow list250	/// @dev Contract owner always implicitly included251	/// @param contractAddress Contract to check allowlist of252	/// @param user User to check253	/// @return bool Is specified users exists in contract allowlist254	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {255		self.0.consume_sload()?;256		Ok(<Pallet<T>>::allowed(contract_address, user))257	}258259	/// Toggle user presence in contract allowlist260	/// @param contractAddress Contract to change allowlist of261	/// @param user Which user presence should be toggled262	/// @param isAllowed `true` if user should be allowed to be sponsored263	///  or call this contract, `false` otherwise264	/// @dev Only contract owner can change this setting265	fn toggle_allowed(266		&mut self,267		caller: caller,268		contract_address: address,269		user: address,270		is_allowed: bool,271	) -> Result<void> {272		self.recorder().consume_sload()?;273		self.recorder().consume_sstore()?;274275		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;276		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);277278		Ok(())279	}280281	/// Is this contract has allowlist access enabled282	/// @dev Allowlist always can have users, and it is used for two purposes:283	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist284	///  in case of allowlist access enabled, only users from allowlist may call this contract285	/// @param contractAddress Contract to get allowlist access of286	/// @return bool Is specified contract has allowlist access enabled287	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {288		Ok(<AllowlistEnabled<T>>::get(contract_address))289	}290291	/// Toggle contract allowlist access292	/// @param contractAddress Contract to change allowlist access of293	/// @param enabled Should allowlist access to be enabled?294	fn toggle_allowlist(295		&mut self,296		caller: caller,297		contract_address: address,298		enabled: bool,299	) -> Result<void> {300		self.recorder().consume_sload()?;301		self.recorder().consume_sstore()?;302303		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;304		<Pallet<T>>::toggle_allowlist(contract_address, enabled);305		Ok(())306	}307}308309/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]310pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);311impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>312where313	T::AccountId: AsRef<[u8; 32]>,314{315	fn is_reserved(contract: &sp_core::H160) -> bool {316		contract == &T::ContractAddress::get()317	}318319	fn is_used(contract: &sp_core::H160) -> bool {320		contract == &T::ContractAddress::get()321	}322323	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {324		// TODO: Extract to another OnMethodCall handler325		if <AllowlistEnabled<T>>::get(handle.code_address())326			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)327		{328			return Some(Err(PrecompileFailure::Revert {329				exit_status: ExitRevert::Reverted,330				output: {331					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));332					writer.string("Target contract is allowlisted");333					writer.finish()334				},335			}));336		}337338		if handle.code_address() != T::ContractAddress::get() {339			return None;340		}341342		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));343		pallet_evm_coder_substrate::call(handle, helpers)344	}345346	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {347		(contract == &T::ContractAddress::get())348			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())349	}350}351352/// Hooks into contract creation, storing owner of newly deployed contract353pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);354impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {355	fn on_create(owner: H160, contract: H160) {356		<Owner<T>>::insert(contract, owner);357	}358}359360/// Bridge to pallet-sponsoring361pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);362impl<T: Config> SponsorshipHandler<T::CrossAccountId, (H160, Vec<u8>)>363	for HelpersContractSponsoring<T>364{365	fn get_sponsor(who: &T::CrossAccountId, call: &(H160, Vec<u8>)) -> Option<T::CrossAccountId> {366		let (contract_address, _) = call;367		let mode = <Pallet<T>>::sponsoring_mode(*contract_address);368		if mode == SponsoringModeT::Disabled {369			return None;370		}371372		let sponsor = match <Pallet<T>>::get_sponsor(*contract_address) {373			Some(sponsor) => sponsor,374			None => return None,375		};376377		if mode == SponsoringModeT::Allowlisted378			&& !<Pallet<T>>::allowed(*contract_address, *who.as_eth())379		{380			return None;381		}382		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;383384		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {385			let limit = <SponsoringRateLimit<T>>::get(contract_address);386387			let timeout = last_tx_block + limit;388			if block_number < timeout {389				return None;390			}391		}392393		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);394395		Some(sponsor)396	}397}398399generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);400generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);
modifiedpallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -208,7 +208,7 @@
 			));
 			<PalletEvm<T>>::deposit_log(
 				ContractHelpersEvents::ContractSponsorSet {
-					contract,
+					contract_address: contract,
 					sponsor: *sponsor.as_eth(),
 				}
 				.to_log(contract),
@@ -221,14 +221,14 @@
 		/// `sender` must be owner of contract.
 		pub fn force_set_sponsor(
 			sender: &T::CrossAccountId,
-			contract: H160,
+			contract_address: H160,
 			sponsor: &T::CrossAccountId,
 		) -> DispatchResult {
-			Pallet::<T>::ensure_owner(contract, *sender.as_eth())?;
+			Pallet::<T>::ensure_owner(contract_address, *sender.as_eth())?;
 			Sponsoring::<T>::insert(
-				contract,
+				contract_address,
 				SponsorshipState::<T::CrossAccountId>::Confirmed(T::CrossAccountId::from_eth(
-					contract,
+					contract_address,
 				)),
 			);
 
@@ -236,27 +236,27 @@
 			let sub_sponsor = sponsor.as_sub().clone();
 
 			<Pallet<T>>::deposit_event(Event::<T>::ContractSponsorSet(
-				contract,
+				contract_address,
 				sub_sponsor.clone(),
 			));
 			<PalletEvm<T>>::deposit_log(
 				ContractHelpersEvents::ContractSponsorSet {
-					contract,
+					contract_address,
 					sponsor: eth_sponsor,
 				}
-				.to_log(contract),
+				.to_log(contract_address),
 			);
 
 			<Pallet<T>>::deposit_event(Event::<T>::ContractSponsorshipConfirmed(
-				contract,
+				contract_address,
 				sub_sponsor,
 			));
 			<PalletEvm<T>>::deposit_log(
 				ContractHelpersEvents::ContractSponsorshipConfirmed {
-					contract,
+					contract_address,
 					sponsor: eth_sponsor,
 				}
-				.to_log(contract),
+				.to_log(contract_address),
 			);
 
 			Ok(())
@@ -265,13 +265,13 @@
 		/// Remove sponsor for `contract`.
 		///
 		/// `sender` must be owner of contract.
-		pub fn remove_sponsor(sender: &T::CrossAccountId, contract: H160) -> DispatchResult {
-			Pallet::<T>::ensure_owner(contract, *sender.as_eth())?;
-			Sponsoring::<T>::remove(contract);
+		pub fn remove_sponsor(sender: &T::CrossAccountId, contract_address: H160) -> DispatchResult {
+			Pallet::<T>::ensure_owner(contract_address, *sender.as_eth())?;
+			Sponsoring::<T>::remove(contract_address);
 
-			<Pallet<T>>::deposit_event(Event::<T>::ContractSponsorRemoved(contract));
+			<Pallet<T>>::deposit_event(Event::<T>::ContractSponsorRemoved(contract_address));
 			<PalletEvm<T>>::deposit_log(
-				ContractHelpersEvents::ContractSponsorRemoved { contract }.to_log(contract),
+				ContractHelpersEvents::ContractSponsorRemoved { contract_address }.to_log(contract_address),
 			);
 
 			Ok(())
@@ -280,27 +280,27 @@
 		/// Confirm sponsorship.
 		///
 		/// `sender` must be same that set via [`set_sponsor`].
-		pub fn confirm_sponsorship(sender: &T::CrossAccountId, contract: H160) -> DispatchResult {
-			match Sponsoring::<T>::get(contract) {
+		pub fn confirm_sponsorship(sender: &T::CrossAccountId, contract_address: H160) -> DispatchResult {
+			match Sponsoring::<T>::get(contract_address) {
 				SponsorshipState::Unconfirmed(sponsor) => {
 					ensure!(sponsor == *sender, Error::<T>::NoPermission);
 					let eth_sponsor = *sponsor.as_eth();
 					let sub_sponsor = sponsor.as_sub().clone();
 					Sponsoring::<T>::insert(
-						contract,
+						contract_address,
 						SponsorshipState::<T::CrossAccountId>::Confirmed(sponsor),
 					);
 
 					<Pallet<T>>::deposit_event(Event::<T>::ContractSponsorshipConfirmed(
-						contract,
+						contract_address,
 						sub_sponsor,
 					));
 					<PalletEvm<T>>::deposit_log(
 						ContractHelpersEvents::ContractSponsorshipConfirmed {
-							contract,
+							contract_address,
 							sponsor: eth_sponsor,
 						}
-						.to_log(contract),
+						.to_log(contract_address),
 					);
 
 					Ok(())
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
@@ -21,9 +21,19 @@
 	}
 }
 
+/// @dev inlined interface
+contract ContractHelpersEvents {
+	event ContractSponsorSet(address indexed contractAddress, address sponsor);
+	event ContractSponsorshipConfirmed(
+		address indexed contractAddress,
+		address sponsor
+	);
+	event ContractSponsorRemoved(address indexed contractAddress);
+}
+
 /// @title Magic contract, which allows users to reconfigure other contracts
 /// @dev the ERC-165 identifier for this interface is 0xd77fab70
-contract ContractHelpers is Dummy, ERC165 {
+contract ContractHelpers is Dummy, ERC165, ContractHelpersEvents {
 	/// Get user, which deployed specified contract
 	/// @dev May return zero address in case if contract is deployed
 	///  using uniquenetwork evm-migration pallet, or using other terms not
modifiedtests/src/eth/api/ContractHelpers.soldiffbeforeafterboth
--- a/tests/src/eth/api/ContractHelpers.sol
+++ b/tests/src/eth/api/ContractHelpers.sol
@@ -12,9 +12,19 @@
 	function supportsInterface(bytes4 interfaceID) external view returns (bool);
 }
 
+/// @dev inlined interface
+interface ContractHelpersEvents {
+	event ContractSponsorSet(address indexed contractAddress, address sponsor);
+	event ContractSponsorshipConfirmed(
+		address indexed contractAddress,
+		address sponsor
+	);
+	event ContractSponsorRemoved(address indexed contractAddress);
+}
+
 /// @title Magic contract, which allows users to reconfigure other contracts
 /// @dev the ERC-165 identifier for this interface is 0xd77fab70
-interface ContractHelpers is Dummy, ERC165 {
+interface ContractHelpers is Dummy, ERC165, ContractHelpersEvents {
 	/// Get user, which deployed specified contract
 	/// @dev May return zero address in case if contract is deployed
 	///  using uniquenetwork evm-migration pallet, or using other terms not
modifiedtests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -24,6 +24,7 @@
   SponsoringMode,
   createEthAccount,
   ethBalanceViaSub,
+  normalizeEvents,
 } from './util/helpers';
 
 describe('Sponsoring EVM contracts', () => {
@@ -36,6 +37,33 @@
     expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;
   });
 
+  itWeb3.only('Set self sponsored events', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const flipper = await deployFlipper(web3, owner);
+    const helpers = contractHelpers(web3, owner);
+    
+    const result = await helpers.methods.selfSponsoredEnable(flipper.options.address).send();
+    const events = normalizeEvents(result.events);
+    expect(events).to.be.deep.equal([
+      {
+        address: flipper.options.address,
+        event: 'ContractSponsorSet',
+        args: {
+          contractAddress: flipper.options.address,
+          sponsor: flipper.options.address,
+        },
+      },
+      {
+        address: flipper.options.address,
+        event: 'ContractSponsorshipConfirmed',
+        args: {
+          contractAddress: flipper.options.address,
+          sponsor: flipper.options.address,
+        },
+      },
+    ]);
+  });
+
   itWeb3('Self sponsored can not be set by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
     const notOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
@@ -75,6 +103,26 @@
     expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.true;
   });
   
+  itWeb3('Set sponsor event', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const flipper = await deployFlipper(web3, owner);
+    const helpers = contractHelpers(web3, owner);
+    
+    const result = await helpers.methods.setSponsor(flipper.options.address, sponsor).send();
+    const events = normalizeEvents(result.events);
+    expect(events).to.be.deep.equal([
+      {
+        address: flipper.options.address,
+        event: 'ContractSponsorSet',
+        args: {
+          contractAddress: flipper.options.address,
+          sponsor: sponsor,
+        },
+      },
+    ]);
+  });
+  
   itWeb3('Sponsor can not be set by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
     const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
@@ -97,6 +145,26 @@
     expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;
   });
 
+  itWeb3('Confirm sponsorship event', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const flipper = await deployFlipper(web3, owner);
+    const helpers = contractHelpers(web3, owner);
+    await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;
+    const result = await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});
+    const events = normalizeEvents(result.events);
+    expect(events).to.be.deep.equal([
+      {
+        address: flipper.options.address,
+        event: 'ContractSponsorshipConfirmed',
+        args: {
+          contractAddress: flipper.options.address,
+          sponsor: sponsor,
+        },
+      },
+    ]);
+  });
+
   itWeb3('Sponsorship can not be confirmed by the address that not pending as sponsor', async ({api, web3, privateKeyWrapper}) => {
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
     const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
@@ -160,6 +228,28 @@
     expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;
   });
 
+  itWeb3('Remove sponsor event', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const flipper = await deployFlipper(web3, owner);
+    const helpers = contractHelpers(web3, owner);
+
+    await helpers.methods.setSponsor(flipper.options.address, sponsor).send();
+    await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});
+    
+    const result = await helpers.methods.removeSponsor(flipper.options.address).send();
+    const events = normalizeEvents(result.events);
+    expect(events).to.be.deep.equal([
+      {
+        address: flipper.options.address,
+        event: 'ContractSponsorRemoved',
+        args: {
+          contractAddress: flipper.options.address,
+        },
+      },
+    ]);
+  });
+
   itWeb3('Sponsor can not be removed by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
     const notOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
modifiedtests/src/eth/util/contractHelpersAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/util/contractHelpersAbi.json
+++ b/tests/src/eth/util/contractHelpersAbi.json
@@ -1,5 +1,56 @@
 [
   {
+    "anonymous": false,
+    "inputs": [
+      {
+        "indexed": true,
+        "internalType": "address",
+        "name": "contractAddress",
+        "type": "address"
+      }
+    ],
+    "name": "ContractSponsorRemoved",
+    "type": "event"
+  },
+  {
+    "anonymous": false,
+    "inputs": [
+      {
+        "indexed": true,
+        "internalType": "address",
+        "name": "contractAddress",
+        "type": "address"
+      },
+      {
+        "indexed": false,
+        "internalType": "address",
+        "name": "sponsor",
+        "type": "address"
+      }
+    ],
+    "name": "ContractSponsorSet",
+    "type": "event"
+  },
+  {
+    "anonymous": false,
+    "inputs": [
+      {
+        "indexed": true,
+        "internalType": "address",
+        "name": "contractAddress",
+        "type": "address"
+      },
+      {
+        "indexed": false,
+        "internalType": "address",
+        "name": "sponsor",
+        "type": "address"
+      }
+    ],
+    "name": "ContractSponsorshipConfirmed",
+    "type": "event"
+  },
+  {
     "inputs": [
       {
         "internalType": "address",