git.delta.rocks / unique-network / refs/commits / 6afd9fe97b2d

difftreelog

source

pallets/evm-contract-helpers/src/eth.rs14.7 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 alloc::string::ToString;21use core::marker::PhantomData;22use evm_coder::{23	abi::AbiWriter,24	execution::Result,25	generate_stubgen, solidity_interface,26	types::*,27	ToLog,28	custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},29	make_signature,30};31use pallet_evm::{32	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,33	account::CrossAccountId,34};35use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};36use pallet_evm_transaction_payment::CallContext;37use sp_core::{H160, U256};38use up_data_structs::SponsorshipState;39use crate::{40	AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringFeeLimit,41	SponsoringRateLimit, SponsoringModeT, Sponsoring,42};43use frame_support::traits::Get;44use up_sponsorship::SponsorshipHandler;45use sp_std::vec::Vec;4647/// Pallet events.48#[derive(ToLog)]49pub enum ContractHelpersEvents {50	/// Contract sponsor was set.51	ContractSponsorSet {52		/// Contract address of the affected collection.53		#[indexed]54		contract_address: address,55		/// New sponsor address.56		sponsor: address,57	},5859	/// New sponsor was confirm.60	ContractSponsorshipConfirmed {61		/// Contract address of the affected collection.62		#[indexed]63		contract_address: address,64		/// New sponsor address.65		sponsor: address,66	},6768	/// Collection sponsor was removed.69	ContractSponsorRemoved {70		/// Contract address of the affected collection.71		#[indexed]72		contract_address: address,73	},74}7576/// See [`ContractHelpersCall`]77pub struct ContractHelpers<T: Config>(SubstrateRecorder<T>);78impl<T: Config> WithRecorder<T> for ContractHelpers<T> {79	fn recorder(&self) -> &SubstrateRecorder<T> {80		&self.081	}8283	fn into_recorder(self) -> SubstrateRecorder<T> {84		self.085	}86}8788/// @title Magic contract, which allows users to reconfigure other contracts89#[solidity_interface(name = ContractHelpers, events(ContractHelpersEvents))]90impl<T: Config> ContractHelpers<T>91where92	T::AccountId: AsRef<[u8; 32]>,93{94	/// Get user, which deployed specified contract95	/// @dev May return zero address in case if contract is deployed96	///  using uniquenetwork evm-migration pallet, or using other terms not97	///  intended by pallet-evm98	/// @dev Returns zero address if contract does not exists99	/// @param contractAddress Contract to get owner of100	/// @return address Owner of contract101	fn contract_owner(&self, contract_address: address) -> Result<address> {102		Ok(<Owner<T>>::get(contract_address))103	}104105	/// Set sponsor.106	/// @param contractAddress Contract for which a sponsor is being established.107	/// @param sponsor User address who set as pending sponsor.108	fn set_sponsor(109		&mut self,110		caller: caller,111		contract_address: address,112		sponsor: address,113	) -> Result<void> {114		self.recorder().consume_sload()?;115		self.recorder().consume_sstore()?;116117		Pallet::<T>::set_sponsor(118			&T::CrossAccountId::from_eth(caller),119			contract_address,120			&T::CrossAccountId::from_eth(sponsor),121		)122		.map_err(dispatch_to_evm::<T>)?;123124		Ok(())125	}126127	/// Set contract as self sponsored.128	///129	/// @param contractAddress Contract for which a self sponsoring is being enabled.130	fn self_sponsored_enable(&mut self, caller: caller, contract_address: address) -> Result<void> {131		self.recorder().consume_sload()?;132		self.recorder().consume_sstore()?;133134		let caller = T::CrossAccountId::from_eth(caller);135136		Pallet::<T>::ensure_owner(contract_address, *caller.as_eth())137			.map_err(dispatch_to_evm::<T>)?;138139		Pallet::<T>::force_set_sponsor(140			contract_address,141			&T::CrossAccountId::from_eth(contract_address),142		)143		.map_err(dispatch_to_evm::<T>)?;144145		Ok(())146	}147148	/// Remove sponsor.149	///150	/// @param contractAddress Contract for which a sponsorship is being removed.151	fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {152		self.recorder().consume_sload()?;153		self.recorder().consume_sstore()?;154155		Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)156			.map_err(dispatch_to_evm::<T>)?;157158		Ok(())159	}160161	/// Confirm sponsorship.162	///163	/// @dev Caller must be same that set via [`setSponsor`].164	///165	/// @param contractAddress Сontract for which need to confirm sponsorship.166	fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {167		self.recorder().consume_sload()?;168		self.recorder().consume_sstore()?;169170		Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)171			.map_err(dispatch_to_evm::<T>)?;172173		Ok(())174	}175176	/// Get current sponsor.177	///178	/// @param contractAddress The contract for which a sponsor is requested.179	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.180	fn sponsor(&self, contract_address: address) -> Result<(address, uint256)> {181		let sponsor =182			Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;183		Ok(pallet_common::eth::convert_cross_account_to_tuple::<T>(184			&sponsor,185		))186	}187188	/// Check tat contract has confirmed sponsor.189	///190	/// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.191	/// @return **true** if contract has confirmed sponsor.192	fn has_sponsor(&self, contract_address: address) -> Result<bool> {193		Ok(Pallet::<T>::get_sponsor(contract_address).is_some())194	}195196	/// Check tat contract has pending sponsor.197	///198	/// @param contractAddress The contract for which the presence of a pending sponsor is checked.199	/// @return **true** if contract has pending sponsor.200	fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {201		Ok(match Sponsoring::<T>::get(contract_address) {202			SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,203			SponsorshipState::Unconfirmed(_) => true,204		})205	}206207	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {208		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)209	}210211	fn set_sponsoring_mode(212		&mut self,213		caller: caller,214		contract_address: address,215		// TODO: implement support for enums in evm-coder216		mode: uint8,217	) -> Result<void> {218		self.recorder().consume_sload()?;219		self.recorder().consume_sstore()?;220221		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;222		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;223		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);224225		Ok(())226	}227228	/// Get current contract sponsoring rate limit229	/// @param contractAddress Contract to get sponsoring rate limit of230	/// @return uint32 Amount of blocks between two sponsored transactions231	fn sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {232		self.recorder().consume_sload()?;233234		Ok(<SponsoringRateLimit<T>>::get(contract_address)235			.try_into()236			.map_err(|_| "rate limit > u32::MAX")?)237	}238239	/// Set contract sponsoring rate limit240	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should241	///  pass between two sponsored transactions242	/// @param contractAddress Contract to change sponsoring rate limit of243	/// @param rateLimit Target rate limit244	/// @dev Only contract owner can change this setting245	fn set_sponsoring_rate_limit(246		&mut self,247		caller: caller,248		contract_address: address,249		rate_limit: uint32,250	) -> Result<void> {251		self.recorder().consume_sload()?;252		self.recorder().consume_sstore()?;253254		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;255		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());256		Ok(())257	}258259	/// Set contract sponsoring fee limit260	/// @dev Sponsoring fee limit - is maximum fee that could be spent by261	///  single transaction262	/// @param contractAddress Contract to change sponsoring fee limit of263	/// @param feeLimit Fee limit264	/// @dev Only contract owner can change this setting265	fn set_sponsoring_fee_limit(266		&mut self,267		caller: caller,268		contract_address: address,269		fee_limit: uint256,270	) -> Result<void> {271		self.recorder().consume_sload()?;272		self.recorder().consume_sstore()?;273274		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;275		<Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())276			.map_err(dispatch_to_evm::<T>)?;277		Ok(())278	}279280	/// Get current contract sponsoring fee limit281	/// @param contractAddress Contract to get sponsoring fee limit of282	/// @return uint256 Maximum amount of fee that could be spent by single283	///  transaction284	fn sponsoring_fee_limit(&self, contract_address: address) -> Result<uint256> {285		self.recorder().consume_sload()?;286287		Ok(get_sponsoring_fee_limit::<T>(contract_address))288	}289290	/// Is specified user present in contract allow list291	/// @dev Contract owner always implicitly included292	/// @param contractAddress Contract to check allowlist of293	/// @param user User to check294	/// @return bool Is specified users exists in contract allowlist295	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {296		self.0.consume_sload()?;297		Ok(<Pallet<T>>::allowed(contract_address, user))298	}299300	/// Toggle user presence in contract allowlist301	/// @param contractAddress Contract to change allowlist of302	/// @param user Which user presence should be toggled303	/// @param isAllowed `true` if user should be allowed to be sponsored304	///  or call this contract, `false` otherwise305	/// @dev Only contract owner can change this setting306	fn toggle_allowed(307		&mut self,308		caller: caller,309		contract_address: address,310		user: address,311		is_allowed: bool,312	) -> Result<void> {313		self.recorder().consume_sload()?;314		self.recorder().consume_sstore()?;315316		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;317		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);318319		Ok(())320	}321322	/// Is this contract has allowlist access enabled323	/// @dev Allowlist always can have users, and it is used for two purposes:324	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist325	///  in case of allowlist access enabled, only users from allowlist may call this contract326	/// @param contractAddress Contract to get allowlist access of327	/// @return bool Is specified contract has allowlist access enabled328	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {329		Ok(<AllowlistEnabled<T>>::get(contract_address))330	}331332	/// Toggle contract allowlist access333	/// @param contractAddress Contract to change allowlist access of334	/// @param enabled Should allowlist access to be enabled?335	fn toggle_allowlist(336		&mut self,337		caller: caller,338		contract_address: address,339		enabled: bool,340	) -> Result<void> {341		self.recorder().consume_sload()?;342		self.recorder().consume_sstore()?;343344		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;345		<Pallet<T>>::toggle_allowlist(contract_address, enabled);346		Ok(())347	}348}349350/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]351pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);352impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>353where354	T::AccountId: AsRef<[u8; 32]>,355{356	fn is_reserved(contract: &sp_core::H160) -> bool {357		contract == &T::ContractAddress::get()358	}359360	fn is_used(contract: &sp_core::H160) -> bool {361		contract == &T::ContractAddress::get()362	}363364	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {365		// TODO: Extract to another OnMethodCall handler366		if <AllowlistEnabled<T>>::get(handle.code_address())367			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)368		{369			return Some(Err(PrecompileFailure::Revert {370				exit_status: ExitRevert::Reverted,371				output: {372					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));373					writer.string("Target contract is allowlisted");374					writer.finish()375				},376			}));377		}378379		if handle.code_address() != T::ContractAddress::get() {380			return None;381		}382383		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));384		pallet_evm_coder_substrate::call(handle, helpers)385	}386387	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {388		(contract == &T::ContractAddress::get())389			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())390	}391}392393/// Hooks into contract creation, storing owner of newly deployed contract394pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);395impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {396	fn on_create(owner: H160, contract: H160) {397		<Owner<T>>::insert(contract, owner);398	}399}400401/// Bridge to pallet-sponsoring402pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);403impl<T: Config> SponsorshipHandler<T::CrossAccountId, CallContext>404	for HelpersContractSponsoring<T>405{406	fn get_sponsor(407		who: &T::CrossAccountId,408		call_context: &CallContext,409	) -> Option<T::CrossAccountId> {410		let contract_address = call_context.contract_address;411		let mode = <Pallet<T>>::sponsoring_mode(contract_address);412		if mode == SponsoringModeT::Disabled {413			return None;414		}415416		let sponsor = match <Pallet<T>>::get_sponsor(contract_address) {417			Some(sponsor) => sponsor,418			None => return None,419		};420421		if mode == SponsoringModeT::Allowlisted422			&& !<Pallet<T>>::allowed(contract_address, *who.as_eth())423		{424			return None;425		}426		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;427428		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {429			let limit = <SponsoringRateLimit<T>>::get(contract_address);430431			let timeout = last_tx_block + limit;432			if block_number < timeout {433				return None;434			}435		}436437		let sponsored_fee_limit = get_sponsoring_fee_limit::<T>(contract_address);438439		if call_context.max_fee > sponsored_fee_limit {440			return None;441		}442443		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);444445		Some(sponsor)446	}447}448449fn get_sponsoring_fee_limit<T: Config>(contract_address: address) -> uint256 {450	<SponsoringFeeLimit<T>>::get(contract_address)451		.get(&0xffffffff)452		.cloned()453		.unwrap_or(U256::MAX)454}455456generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);457generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);