git.delta.rocks / unique-network / refs/commits / 2ef175a77541

difftreelog

source

pallets/evm-contract-helpers/src/eth.rs14.6 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,23	execution::Result,24	generate_stubgen, solidity_interface,25	types::*,26	ToLog,27	custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},28	make_signature,29};30use pallet_evm::{31	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,32	account::CrossAccountId,33};34use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};35use pallet_evm_transaction_payment::CallContext;36use sp_core::{H160, U256};37use up_data_structs::SponsorshipState;38use crate::{39	AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringFeeLimit,40	SponsoringRateLimit, SponsoringModeT, Sponsoring,41};42use frame_support::traits::Get;43use up_sponsorship::SponsorshipHandler;44use sp_std::vec::Vec;4546/// Pallet events.47#[derive(ToLog)]48pub enum ContractHelpersEvents {49	/// Contract sponsor was set.50	ContractSponsorSet {51		/// Contract address of the affected collection.52		#[indexed]53		contract_address: address,54		/// New sponsor address.55		sponsor: address,56	},5758	/// New sponsor was confirm.59	ContractSponsorshipConfirmed {60		/// Contract address of the affected collection.61		#[indexed]62		contract_address: address,63		/// New sponsor address.64		sponsor: address,65	},6667	/// Collection sponsor was removed.68	ContractSponsorRemoved {69		/// Contract address of the affected collection.70		#[indexed]71		contract_address: address,72	},73}7475/// See [`ContractHelpersCall`]76pub struct ContractHelpers<T: Config>(SubstrateRecorder<T>);77impl<T: Config> WithRecorder<T> for ContractHelpers<T> {78	fn recorder(&self) -> &SubstrateRecorder<T> {79		&self.080	}8182	fn into_recorder(self) -> SubstrateRecorder<T> {83		self.084	}85}8687/// @title Magic contract, which allows users to reconfigure other contracts88#[solidity_interface(name = ContractHelpers, events(ContractHelpersEvents))]89impl<T: Config> ContractHelpers<T>90where91	T::AccountId: AsRef<[u8; 32]>,92{93	/// Get user, which deployed specified contract94	/// @dev May return zero address in case if contract is deployed95	///  using uniquenetwork evm-migration pallet, or using other terms not96	///  intended by pallet-evm97	/// @dev Returns zero address if contract does not exists98	/// @param contractAddress Contract to get owner of99	/// @return address Owner of contract100	fn contract_owner(&self, contract_address: address) -> Result<address> {101		Ok(<Owner<T>>::get(contract_address))102	}103104	/// Set sponsor.105	/// @param contractAddress Contract for which a sponsor is being established.106	/// @param sponsor User address who set as pending sponsor.107	fn set_sponsor(108		&mut self,109		caller: caller,110		contract_address: address,111		sponsor: address,112	) -> Result<void> {113		self.recorder().consume_sload()?;114		self.recorder().consume_sstore()?;115116		Pallet::<T>::set_sponsor(117			&T::CrossAccountId::from_eth(caller),118			contract_address,119			&T::CrossAccountId::from_eth(sponsor),120		)121		.map_err(dispatch_to_evm::<T>)?;122123		Ok(())124	}125126	/// Set contract as self sponsored.127	///128	/// @param contractAddress Contract for which a self sponsoring is being enabled.129	fn self_sponsored_enable(&mut self, caller: caller, contract_address: address) -> Result<void> {130		self.recorder().consume_sload()?;131		self.recorder().consume_sstore()?;132133		let caller = T::CrossAccountId::from_eth(caller);134135		Pallet::<T>::ensure_owner(contract_address, *caller.as_eth())136			.map_err(dispatch_to_evm::<T>)?;137138		Pallet::<T>::force_set_sponsor(139			contract_address,140			&T::CrossAccountId::from_eth(contract_address),141		)142		.map_err(dispatch_to_evm::<T>)?;143144		Ok(())145	}146147	/// Remove sponsor.148	///149	/// @param contractAddress Contract for which a sponsorship is being removed.150	fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {151		self.recorder().consume_sload()?;152		self.recorder().consume_sstore()?;153154		Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)155			.map_err(dispatch_to_evm::<T>)?;156157		Ok(())158	}159160	/// Confirm sponsorship.161	///162	/// @dev Caller must be same that set via [`setSponsor`].163	///164	/// @param contractAddress Сontract for which need to confirm sponsorship.165	fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {166		self.recorder().consume_sload()?;167		self.recorder().consume_sstore()?;168169		Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)170			.map_err(dispatch_to_evm::<T>)?;171172		Ok(())173	}174175	/// Get current sponsor.176	///177	/// @param contractAddress The contract for which a sponsor is requested.178	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.179	fn sponsor(&self, contract_address: address) -> Result<(address, uint256)> {180		let sponsor =181			Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;182		Ok(pallet_common::eth::convert_cross_account_to_tuple::<T>(183			&sponsor,184		))185	}186187	/// Check tat contract has confirmed sponsor.188	///189	/// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.190	/// @return **true** if contract has confirmed sponsor.191	fn has_sponsor(&self, contract_address: address) -> Result<bool> {192		Ok(Pallet::<T>::get_sponsor(contract_address).is_some())193	}194195	/// Check tat contract has pending sponsor.196	///197	/// @param contractAddress The contract for which the presence of a pending sponsor is checked.198	/// @return **true** if contract has pending sponsor.199	fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {200		Ok(match Sponsoring::<T>::get(contract_address) {201			SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,202			SponsorshipState::Unconfirmed(_) => true,203		})204	}205206	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {207		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)208	}209210	fn set_sponsoring_mode(211		&mut self,212		caller: caller,213		contract_address: address,214		// TODO: implement support for enums in evm-coder215		mode: uint8,216	) -> Result<void> {217		self.recorder().consume_sload()?;218		self.recorder().consume_sstore()?;219220		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;221		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;222		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);223224		Ok(())225	}226227	/// Get current contract sponsoring rate limit228	/// @param contractAddress Contract to get sponsoring rate limit of229	/// @return uint32 Amount of blocks between two sponsored transactions230	fn sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {231		self.recorder().consume_sload()?;232233		Ok(<SponsoringRateLimit<T>>::get(contract_address)234			.try_into()235			.map_err(|_| "rate limit > u32::MAX")?)236	}237238	/// Set contract sponsoring rate limit239	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should240	///  pass between two sponsored transactions241	/// @param contractAddress Contract to change sponsoring rate limit of242	/// @param rateLimit Target rate limit243	/// @dev Only contract owner can change this setting244	fn set_sponsoring_rate_limit(245		&mut self,246		caller: caller,247		contract_address: address,248		rate_limit: uint32,249	) -> Result<void> {250		self.recorder().consume_sload()?;251		self.recorder().consume_sstore()?;252253		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;254		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());255		Ok(())256	}257258	/// Set contract sponsoring fee limit259	/// @dev Sponsoring fee limit - is maximum fee that could be spent by260	///  single transaction261	/// @param contractAddress Contract to change sponsoring fee limit of262	/// @param feeLimit Fee limit263	/// @dev Only contract owner can change this setting264	fn set_sponsoring_fee_limit(265		&mut self,266		caller: caller,267		contract_address: address,268		fee_limit: uint256,269	) -> Result<void> {270		self.recorder().consume_sload()?;271		self.recorder().consume_sstore()?;272273		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;274		<Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())275			.map_err(dispatch_to_evm::<T>)?;276		Ok(())277	}278279	/// Get current contract sponsoring fee limit280	/// @param contractAddress Contract to get sponsoring fee limit of281	/// @return uint256 Maximum amount of fee that could be spent by single282	///  transaction283	fn sponsoring_fee_limit(&self, contract_address: address) -> Result<uint256> {284		self.recorder().consume_sload()?;285286		Ok(get_sponsoring_fee_limit::<T>(contract_address))287	}288289	/// Is specified user present in contract allow list290	/// @dev Contract owner always implicitly included291	/// @param contractAddress Contract to check allowlist of292	/// @param user User to check293	/// @return bool Is specified users exists in contract allowlist294	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {295		self.0.consume_sload()?;296		Ok(<Pallet<T>>::allowed(contract_address, user))297	}298299	/// Toggle user presence in contract allowlist300	/// @param contractAddress Contract to change allowlist of301	/// @param user Which user presence should be toggled302	/// @param isAllowed `true` if user should be allowed to be sponsored303	///  or call this contract, `false` otherwise304	/// @dev Only contract owner can change this setting305	fn toggle_allowed(306		&mut self,307		caller: caller,308		contract_address: address,309		user: address,310		is_allowed: bool,311	) -> Result<void> {312		self.recorder().consume_sload()?;313		self.recorder().consume_sstore()?;314315		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;316		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);317318		Ok(())319	}320321	/// Is this contract has allowlist access enabled322	/// @dev Allowlist always can have users, and it is used for two purposes:323	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist324	///  in case of allowlist access enabled, only users from allowlist may call this contract325	/// @param contractAddress Contract to get allowlist access of326	/// @return bool Is specified contract has allowlist access enabled327	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {328		Ok(<AllowlistEnabled<T>>::get(contract_address))329	}330331	/// Toggle contract allowlist access332	/// @param contractAddress Contract to change allowlist access of333	/// @param enabled Should allowlist access to be enabled?334	fn toggle_allowlist(335		&mut self,336		caller: caller,337		contract_address: address,338		enabled: bool,339	) -> Result<void> {340		self.recorder().consume_sload()?;341		self.recorder().consume_sstore()?;342343		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;344		<Pallet<T>>::toggle_allowlist(contract_address, enabled);345		Ok(())346	}347}348349/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]350pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);351impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>352where353	T::AccountId: AsRef<[u8; 32]>,354{355	fn is_reserved(contract: &sp_core::H160) -> bool {356		contract == &T::ContractAddress::get()357	}358359	fn is_used(contract: &sp_core::H160) -> bool {360		contract == &T::ContractAddress::get()361	}362363	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {364		// TODO: Extract to another OnMethodCall handler365		if <AllowlistEnabled<T>>::get(handle.code_address())366			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)367		{368			return Some(Err(PrecompileFailure::Revert {369				exit_status: ExitRevert::Reverted,370				output: {371					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));372					writer.string("Target contract is allowlisted");373					writer.finish()374				},375			}));376		}377378		if handle.code_address() != T::ContractAddress::get() {379			return None;380		}381382		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));383		pallet_evm_coder_substrate::call(handle, helpers)384	}385386	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {387		(contract == &T::ContractAddress::get())388			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())389	}390}391392/// Hooks into contract creation, storing owner of newly deployed contract393pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);394impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {395	fn on_create(owner: H160, contract: H160) {396		<Owner<T>>::insert(contract, owner);397	}398}399400/// Bridge to pallet-sponsoring401pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);402impl<T: Config> SponsorshipHandler<T::CrossAccountId, CallContext>403	for HelpersContractSponsoring<T>404{405	fn get_sponsor(406		who: &T::CrossAccountId,407		call_context: &CallContext,408	) -> Option<T::CrossAccountId> {409		let contract_address = call_context.contract_address;410		let mode = <Pallet<T>>::sponsoring_mode(contract_address);411		if mode == SponsoringModeT::Disabled {412			return None;413		}414415		let sponsor = match <Pallet<T>>::get_sponsor(contract_address) {416			Some(sponsor) => sponsor,417			None => return None,418		};419420		if mode == SponsoringModeT::Allowlisted421			&& !<Pallet<T>>::allowed(contract_address, *who.as_eth())422		{423			return None;424		}425		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;426427		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {428			let limit = <SponsoringRateLimit<T>>::get(contract_address);429430			let timeout = last_tx_block + limit;431			if block_number < timeout {432				return None;433			}434		}435436		let sponsored_fee_limit = get_sponsoring_fee_limit::<T>(contract_address);437438		if call_context.max_fee > sponsored_fee_limit {439			return None;440		}441442		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);443444		Some(sponsor)445	}446}447448fn get_sponsoring_fee_limit<T: Config>(contract_address: address) -> uint256 {449	<SponsoringFeeLimit<T>>::get(contract_address)450		.get(&0xffffffff)451		.cloned()452		.unwrap_or(U256::MAX)453}454455generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);456generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);