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

difftreelog

source

pallets/evm-contract-helpers/src/eth.rs13.9 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 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;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		let result: (address, uint256) = if sponsor.is_canonical_substrate() {176			let sponsor = pallet_common::eth::convert_cross_account_to_uint256::<T>(&sponsor);177			(Default::default(), sponsor)178		} else {179			let sponsor = *sponsor.as_eth();180			(sponsor, Default::default())181		};182		Ok(result)183	}184185	/// Check tat contract has confirmed sponsor.186	///187	/// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.188	/// @return **true** if contract has confirmed sponsor.189	fn has_sponsor(&self, contract_address: address) -> Result<bool> {190		Ok(Pallet::<T>::get_sponsor(contract_address).is_some())191	}192193	/// Check tat contract has pending sponsor.194	///195	/// @param contractAddress The contract for which the presence of a pending sponsor is checked.196	/// @return **true** if contract has pending sponsor.197	fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {198		Ok(match Sponsoring::<T>::get(contract_address) {199			SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,200			SponsorshipState::Unconfirmed(_) => true,201		})202	}203204	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {205		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)206	}207208	fn set_sponsoring_mode(209		&mut self,210		caller: caller,211		contract_address: address,212		// TODO: implement support for enums in evm-coder213		mode: uint8,214	) -> Result<void> {215		self.recorder().consume_sload()?;216		self.recorder().consume_sstore()?;217218		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;219		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;220		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);221222		Ok(())223	}224225	/// Get current contract sponsoring rate limit226	/// @param contractAddress Contract to get sponsoring mode of227	/// @return uint32 Amount of blocks between two sponsored transactions228	fn get_sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {229		Ok(<SponsoringRateLimit<T>>::get(contract_address)230			.try_into()231			.map_err(|_| "rate limit > u32::MAX")?)232	}233234	/// Set contract sponsoring rate limit235	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should236	///  pass between two sponsored transactions237	/// @param contractAddress Contract to change sponsoring rate limit of238	/// @param rateLimit Target rate limit239	/// @dev Only contract owner can change this setting240	fn set_sponsoring_rate_limit(241		&mut self,242		caller: caller,243		contract_address: address,244		rate_limit: uint32,245	) -> Result<void> {246		self.recorder().consume_sload()?;247		self.recorder().consume_sstore()?;248249		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;250		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());251		Ok(())252	}253254	fn set_sponsoring_fee_limit(255		&mut self,256		caller: caller,257		contract_address: address,258		fee_limit: uint256,259	) -> Result<void> {260		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;261		<Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into());262		Ok(())263	}264265	fn get_sponsoring_fee_limit(&self, contract_address: address) -> Result<uint256> {266		Ok(<SponsoringFeeLimit<T>>::get(contract_address))267	}268269	/// Is specified user present in contract allow list270	/// @dev Contract owner always implicitly included271	/// @param contractAddress Contract to check allowlist of272	/// @param user User to check273	/// @return bool Is specified users exists in contract allowlist274	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {275		self.0.consume_sload()?;276		Ok(<Pallet<T>>::allowed(contract_address, user))277	}278279	/// Toggle user presence in contract allowlist280	/// @param contractAddress Contract to change allowlist of281	/// @param user Which user presence should be toggled282	/// @param isAllowed `true` if user should be allowed to be sponsored283	///  or call this contract, `false` otherwise284	/// @dev Only contract owner can change this setting285	fn toggle_allowed(286		&mut self,287		caller: caller,288		contract_address: address,289		user: address,290		is_allowed: bool,291	) -> Result<void> {292		self.recorder().consume_sload()?;293		self.recorder().consume_sstore()?;294295		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;296		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);297298		Ok(())299	}300301	/// Is this contract has allowlist access enabled302	/// @dev Allowlist always can have users, and it is used for two purposes:303	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist304	///  in case of allowlist access enabled, only users from allowlist may call this contract305	/// @param contractAddress Contract to get allowlist access of306	/// @return bool Is specified contract has allowlist access enabled307	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {308		Ok(<AllowlistEnabled<T>>::get(contract_address))309	}310311	/// Toggle contract allowlist access312	/// @param contractAddress Contract to change allowlist access of313	/// @param enabled Should allowlist access to be enabled?314	fn toggle_allowlist(315		&mut self,316		caller: caller,317		contract_address: address,318		enabled: bool,319	) -> Result<void> {320		self.recorder().consume_sload()?;321		self.recorder().consume_sstore()?;322323		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;324		<Pallet<T>>::toggle_allowlist(contract_address, enabled);325		Ok(())326	}327}328329/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]330pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);331impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>332where333	T::AccountId: AsRef<[u8; 32]>,334{335	fn is_reserved(contract: &sp_core::H160) -> bool {336		contract == &T::ContractAddress::get()337	}338339	fn is_used(contract: &sp_core::H160) -> bool {340		contract == &T::ContractAddress::get()341	}342343	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {344		// TODO: Extract to another OnMethodCall handler345		if <AllowlistEnabled<T>>::get(handle.code_address())346			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)347		{348			return Some(Err(PrecompileFailure::Revert {349				exit_status: ExitRevert::Reverted,350				output: {351					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));352					writer.string("Target contract is allowlisted");353					writer.finish()354				},355			}));356		}357358		if handle.code_address() != T::ContractAddress::get() {359			return None;360		}361362		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));363		pallet_evm_coder_substrate::call(handle, helpers)364	}365366	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {367		(contract == &T::ContractAddress::get())368			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())369	}370}371372/// Hooks into contract creation, storing owner of newly deployed contract373pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);374impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {375	fn on_create(owner: H160, contract: H160) {376		<Owner<T>>::insert(contract, owner);377	}378}379380/// Bridge to pallet-sponsoring381pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);382impl<T: Config> SponsorshipHandler<T::CrossAccountId, (H160, Vec<u8>), CallContext>383	for HelpersContractSponsoring<T>384{385	fn get_sponsor(386		who: &T::CrossAccountId,387		call: &(H160, Vec<u8>),388		call_context: &CallContext,389	) -> Option<T::CrossAccountId> {390		let (contract_address, _) = call;391		let mode = <Pallet<T>>::sponsoring_mode(*contract_address);392		if mode == SponsoringModeT::Disabled {393			return None;394		}395396		let sponsor = match <Pallet<T>>::get_sponsor(*contract_address) {397			Some(sponsor) => sponsor,398			None => return None,399		};400401		if mode == SponsoringModeT::Allowlisted402			&& !<Pallet<T>>::allowed(*contract_address, *who.as_eth())403		{404			return None;405		}406		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;407408		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {409			let limit = <SponsoringRateLimit<T>>::get(contract_address);410411			let timeout = last_tx_block + limit;412			if block_number < timeout {413				return None;414			}415		}416417		let sponsored_fee_limit = <SponsoringFeeLimit<T>>::get(contract_address);418419		if call_context.max_fee > sponsored_fee_limit {420			return None;421		}422423		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);424425		Some(sponsor)426	}427}428429generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);430generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);