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

difftreelog

source

pallets/evm-contract-helpers/src/eth.rs14.5 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! Implementation of magic contract1819extern crate alloc;20use core::marker::PhantomData;21use evm_coder::{22	abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,23};24use pallet_evm::{25	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,26	account::CrossAccountId,27};28use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};29use pallet_evm_transaction_payment::CallContext;30use sp_core::{H160, U256};31use up_data_structs::SponsorshipState;32use crate::{33	AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringFeeLimit,34	SponsoringRateLimit, SponsoringModeT, Sponsoring,35};36use frame_support::traits::Get;37use up_sponsorship::SponsorshipHandler;38use sp_std::vec::Vec;3940/// Pallet events.41#[derive(ToLog)]42pub enum ContractHelpersEvents {43	/// Contract sponsor was set.44	ContractSponsorSet {45		/// Contract address of the affected collection.46		#[indexed]47		contract_address: address,48		/// New sponsor address.49		sponsor: address,50	},5152	/// New sponsor was confirm.53	ContractSponsorshipConfirmed {54		/// Contract address of the affected collection.55		#[indexed]56		contract_address: address,57		/// New sponsor address.58		sponsor: address,59	},6061	/// Collection sponsor was removed.62	ContractSponsorRemoved {63		/// Contract address of the affected collection.64		#[indexed]65		contract_address: 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		let caller = T::CrossAccountId::from_eth(caller);128129		Pallet::<T>::ensure_owner(contract_address, *caller.as_eth())130			.map_err(dispatch_to_evm::<T>)?;131132		Pallet::<T>::force_set_sponsor(133			contract_address,134			&T::CrossAccountId::from_eth(contract_address),135		)136		.map_err(dispatch_to_evm::<T>)?;137138		Ok(())139	}140141	/// Remove sponsor.142	///143	/// @param contractAddress Contract for which a sponsorship is being removed.144	fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {145		self.recorder().consume_sload()?;146		self.recorder().consume_sstore()?;147148		Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)149			.map_err(dispatch_to_evm::<T>)?;150151		Ok(())152	}153154	/// Confirm sponsorship.155	///156	/// @dev Caller must be same that set via [`setSponsor`].157	///158	/// @param contractAddress Сontract for which need to confirm sponsorship.159	fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {160		self.recorder().consume_sload()?;161		self.recorder().consume_sstore()?;162163		Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)164			.map_err(dispatch_to_evm::<T>)?;165166		Ok(())167	}168169	/// Get current sponsor.170	///171	/// @param contractAddress The contract for which a sponsor is requested.172	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.173	fn sponsor(&self, contract_address: address) -> Result<(address, uint256)> {174		let sponsor =175			Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;176		Ok(pallet_common::eth::convert_cross_account_to_tuple::<T>(177			&sponsor,178		))179	}180181	/// Check tat contract has confirmed sponsor.182	///183	/// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.184	/// @return **true** if contract has confirmed sponsor.185	fn has_sponsor(&self, contract_address: address) -> Result<bool> {186		Ok(Pallet::<T>::get_sponsor(contract_address).is_some())187	}188189	/// Check tat contract has pending sponsor.190	///191	/// @param contractAddress The contract for which the presence of a pending sponsor is checked.192	/// @return **true** if contract has pending sponsor.193	fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {194		Ok(match Sponsoring::<T>::get(contract_address) {195			SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,196			SponsorshipState::Unconfirmed(_) => true,197		})198	}199200	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {201		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)202	}203204	fn set_sponsoring_mode(205		&mut self,206		caller: caller,207		contract_address: address,208		// TODO: implement support for enums in evm-coder209		mode: uint8,210	) -> Result<void> {211		self.recorder().consume_sload()?;212		self.recorder().consume_sstore()?;213214		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;215		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;216		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);217218		Ok(())219	}220221	/// Get current contract sponsoring rate limit222	/// @param contractAddress Contract to get sponsoring rate limit of223	/// @return uint32 Amount of blocks between two sponsored transactions224	fn sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {225		self.recorder().consume_sload()?;226227		Ok(<SponsoringRateLimit<T>>::get(contract_address)228			.try_into()229			.map_err(|_| "rate limit > u32::MAX")?)230	}231232	/// Set contract sponsoring rate limit233	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should234	///  pass between two sponsored transactions235	/// @param contractAddress Contract to change sponsoring rate limit of236	/// @param rateLimit Target rate limit237	/// @dev Only contract owner can change this setting238	fn set_sponsoring_rate_limit(239		&mut self,240		caller: caller,241		contract_address: address,242		rate_limit: uint32,243	) -> Result<void> {244		self.recorder().consume_sload()?;245		self.recorder().consume_sstore()?;246247		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;248		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());249		Ok(())250	}251252	/// Set contract sponsoring fee limit253	/// @dev Sponsoring fee limit - is maximum fee that could be spent by254	///  single transaction255	/// @param contractAddress Contract to change sponsoring fee limit of256	/// @param feeLimit Fee limit257	/// @dev Only contract owner can change this setting258	fn set_sponsoring_fee_limit(259		&mut self,260		caller: caller,261		contract_address: address,262		fee_limit: uint256,263	) -> Result<void> {264		self.recorder().consume_sload()?;265		self.recorder().consume_sstore()?;266267		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;268		<Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())269			.map_err(dispatch_to_evm::<T>)?;270		Ok(())271	}272273	/// Get current contract sponsoring fee limit274	/// @param contractAddress Contract to get sponsoring fee limit of275	/// @return uint256 Maximum amount of fee that could be spent by single276	///  transaction277	fn sponsoring_fee_limit(&self, contract_address: address) -> Result<uint256> {278		self.recorder().consume_sload()?;279280		Ok(get_sponsoring_fee_limit::<T>(contract_address))281	}282283	/// Is specified user present in contract allow list284	/// @dev Contract owner always implicitly included285	/// @param contractAddress Contract to check allowlist of286	/// @param user User to check287	/// @return bool Is specified users exists in contract allowlist288	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {289		self.0.consume_sload()?;290		Ok(<Pallet<T>>::allowed(contract_address, user))291	}292293	/// Toggle user presence in contract allowlist294	/// @param contractAddress Contract to change allowlist of295	/// @param user Which user presence should be toggled296	/// @param isAllowed `true` if user should be allowed to be sponsored297	///  or call this contract, `false` otherwise298	/// @dev Only contract owner can change this setting299	fn toggle_allowed(300		&mut self,301		caller: caller,302		contract_address: address,303		user: address,304		is_allowed: bool,305	) -> Result<void> {306		self.recorder().consume_sload()?;307		self.recorder().consume_sstore()?;308309		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;310		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);311312		Ok(())313	}314315	/// Is this contract has allowlist access enabled316	/// @dev Allowlist always can have users, and it is used for two purposes:317	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist318	///  in case of allowlist access enabled, only users from allowlist may call this contract319	/// @param contractAddress Contract to get allowlist access of320	/// @return bool Is specified contract has allowlist access enabled321	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {322		Ok(<AllowlistEnabled<T>>::get(contract_address))323	}324325	/// Toggle contract allowlist access326	/// @param contractAddress Contract to change allowlist access of327	/// @param enabled Should allowlist access to be enabled?328	fn toggle_allowlist(329		&mut self,330		caller: caller,331		contract_address: address,332		enabled: bool,333	) -> Result<void> {334		self.recorder().consume_sload()?;335		self.recorder().consume_sstore()?;336337		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;338		<Pallet<T>>::toggle_allowlist(contract_address, enabled);339		Ok(())340	}341}342343/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]344pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);345impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>346where347	T::AccountId: AsRef<[u8; 32]>,348{349	fn is_reserved(contract: &sp_core::H160) -> bool {350		contract == &T::ContractAddress::get()351	}352353	fn is_used(contract: &sp_core::H160) -> bool {354		contract == &T::ContractAddress::get()355	}356357	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {358		// TODO: Extract to another OnMethodCall handler359		if <AllowlistEnabled<T>>::get(handle.code_address())360			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)361		{362			return Some(Err(PrecompileFailure::Revert {363				exit_status: ExitRevert::Reverted,364				output: {365					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));366					writer.string("Target contract is allowlisted");367					writer.finish()368				},369			}));370		}371372		if handle.code_address() != T::ContractAddress::get() {373			return None;374		}375376		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));377		pallet_evm_coder_substrate::call(handle, helpers)378	}379380	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {381		(contract == &T::ContractAddress::get())382			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())383	}384}385386/// Hooks into contract creation, storing owner of newly deployed contract387pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);388impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {389	fn on_create(owner: H160, contract: H160) {390		<Owner<T>>::insert(contract, owner);391	}392}393394/// Bridge to pallet-sponsoring395pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);396impl<T: Config> SponsorshipHandler<T::CrossAccountId, CallContext>397	for HelpersContractSponsoring<T>398{399	fn get_sponsor(400		who: &T::CrossAccountId,401		call_context: &CallContext,402	) -> Option<T::CrossAccountId> {403		let contract_address = call_context.contract_address;404		let mode = <Pallet<T>>::sponsoring_mode(contract_address);405		if mode == SponsoringModeT::Disabled {406			return None;407		}408409		let sponsor = match <Pallet<T>>::get_sponsor(contract_address) {410			Some(sponsor) => sponsor,411			None => return None,412		};413414		if mode == SponsoringModeT::Allowlisted415			&& !<Pallet<T>>::allowed(contract_address, *who.as_eth())416		{417			return None;418		}419		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;420421		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {422			let limit = <SponsoringRateLimit<T>>::get(contract_address);423424			let timeout = last_tx_block + limit;425			if block_number < timeout {426				return None;427			}428		}429430		let sponsored_fee_limit = get_sponsoring_fee_limit::<T>(contract_address);431432		if call_context.max_fee > sponsored_fee_limit {433			return None;434		}435436		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);437438		Some(sponsor)439	}440}441442fn get_sponsoring_fee_limit<T: Config>(contract_address: address) -> uint256 {443	<SponsoringFeeLimit<T>>::get(contract_address)444		.get(&0xffffffff)445		.cloned()446		.unwrap_or(U256::MAX)447}448449generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);450generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);