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

difftreelog

source

pallets/evm-contract-helpers/src/eth.rs13.2 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_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		let caller = T::CrossAccountId::from_eth(caller);126127		Pallet::<T>::ensure_owner(contract_address, *caller.as_eth())128			.map_err(dispatch_to_evm::<T>)?;129130		Pallet::<T>::force_set_sponsor(131			contract_address,132			&T::CrossAccountId::from_eth(contract_address),133		)134		.map_err(dispatch_to_evm::<T>)?;135136		Ok(())137	}138139	/// Remove sponsor.140	///141	/// @param contractAddress Contract for which a sponsorship is being removed.142	fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {143		self.recorder().consume_sload()?;144		self.recorder().consume_sstore()?;145146		Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)147			.map_err(dispatch_to_evm::<T>)?;148149		Ok(())150	}151152	/// Confirm sponsorship.153	///154	/// @dev Caller must be same that set via [`setSponsor`].155	///156	/// @param contractAddress Сontract for which need to confirm sponsorship.157	fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {158		self.recorder().consume_sload()?;159		self.recorder().consume_sstore()?;160161		Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)162			.map_err(dispatch_to_evm::<T>)?;163164		Ok(())165	}166167	/// Get current sponsor.168	///169	/// @param contractAddress The contract for which a sponsor is requested.170	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.171	fn get_sponsor(&self, contract_address: address) -> Result<(address, uint256)> {172		let sponsor =173			Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;174		let result: (address, uint256) = if sponsor.is_canonical_substrate() {175			let sponsor = pallet_common::eth::convert_cross_account_to_uint256::<T>(&sponsor);176			(Default::default(), sponsor)177		} else {178			let sponsor = *sponsor.as_eth();179			(sponsor, Default::default())180		};181		Ok(result)182	}183184	/// Check tat contract has confirmed sponsor.185	///186	/// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.187	/// @return **true** if contract has confirmed sponsor.188	fn has_sponsor(&self, contract_address: address) -> Result<bool> {189		Ok(Pallet::<T>::get_sponsor(contract_address).is_some())190	}191192	/// Check tat contract has pending sponsor.193	///194	/// @param contractAddress The contract for which the presence of a pending sponsor is checked.195	/// @return **true** if contract has pending sponsor.196	fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {197		Ok(match Sponsoring::<T>::get(contract_address) {198			SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,199			SponsorshipState::Unconfirmed(_) => true,200		})201	}202203	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {204		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)205	}206207	fn set_sponsoring_mode(208		&mut self,209		caller: caller,210		contract_address: address,211		// TODO: implement support for enums in evm-coder212		mode: uint8,213	) -> Result<void> {214		self.recorder().consume_sload()?;215		self.recorder().consume_sstore()?;216217		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;218		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;219		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);220221		Ok(())222	}223224	/// Get current contract sponsoring rate limit225	/// @param contractAddress Contract to get sponsoring mode of226	/// @return uint32 Amount of blocks between two sponsored transactions227	fn get_sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {228		Ok(<SponsoringRateLimit<T>>::get(contract_address)229			.try_into()230			.map_err(|_| "rate limit > u32::MAX")?)231	}232233	/// Set contract sponsoring rate limit234	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should235	///  pass between two sponsored transactions236	/// @param contractAddress Contract to change sponsoring rate limit of237	/// @param rateLimit Target rate limit238	/// @dev Only contract owner can change this setting239	fn set_sponsoring_rate_limit(240		&mut self,241		caller: caller,242		contract_address: address,243		rate_limit: uint32,244	) -> Result<void> {245		self.recorder().consume_sload()?;246		self.recorder().consume_sstore()?;247248		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;249		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());250		Ok(())251	}252253	/// Is specified user present in contract allow list254	/// @dev Contract owner always implicitly included255	/// @param contractAddress Contract to check allowlist of256	/// @param user User to check257	/// @return bool Is specified users exists in contract allowlist258	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {259		self.0.consume_sload()?;260		Ok(<Pallet<T>>::allowed(contract_address, user))261	}262263	/// Toggle user presence in contract allowlist264	/// @param contractAddress Contract to change allowlist of265	/// @param user Which user presence should be toggled266	/// @param isAllowed `true` if user should be allowed to be sponsored267	///  or call this contract, `false` otherwise268	/// @dev Only contract owner can change this setting269	fn toggle_allowed(270		&mut self,271		caller: caller,272		contract_address: address,273		user: address,274		is_allowed: bool,275	) -> Result<void> {276		self.recorder().consume_sload()?;277		self.recorder().consume_sstore()?;278279		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;280		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);281282		Ok(())283	}284285	/// Is this contract has allowlist access enabled286	/// @dev Allowlist always can have users, and it is used for two purposes:287	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist288	///  in case of allowlist access enabled, only users from allowlist may call this contract289	/// @param contractAddress Contract to get allowlist access of290	/// @return bool Is specified contract has allowlist access enabled291	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {292		Ok(<AllowlistEnabled<T>>::get(contract_address))293	}294295	/// Toggle contract allowlist access296	/// @param contractAddress Contract to change allowlist access of297	/// @param enabled Should allowlist access to be enabled?298	fn toggle_allowlist(299		&mut self,300		caller: caller,301		contract_address: address,302		enabled: bool,303	) -> Result<void> {304		self.recorder().consume_sload()?;305		self.recorder().consume_sstore()?;306307		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;308		<Pallet<T>>::toggle_allowlist(contract_address, enabled);309		Ok(())310	}311}312313/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]314pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);315impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>316where317	T::AccountId: AsRef<[u8; 32]>,318{319	fn is_reserved(contract: &sp_core::H160) -> bool {320		contract == &T::ContractAddress::get()321	}322323	fn is_used(contract: &sp_core::H160) -> bool {324		contract == &T::ContractAddress::get()325	}326327	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {328		// TODO: Extract to another OnMethodCall handler329		if <AllowlistEnabled<T>>::get(handle.code_address())330			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)331		{332			return Some(Err(PrecompileFailure::Revert {333				exit_status: ExitRevert::Reverted,334				output: {335					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));336					writer.string("Target contract is allowlisted");337					writer.finish()338				},339			}));340		}341342		if handle.code_address() != T::ContractAddress::get() {343			return None;344		}345346		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));347		pallet_evm_coder_substrate::call(handle, helpers)348	}349350	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {351		(contract == &T::ContractAddress::get())352			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())353	}354}355356/// Hooks into contract creation, storing owner of newly deployed contract357pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);358impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {359	fn on_create(owner: H160, contract: H160) {360		<Owner<T>>::insert(contract, owner);361	}362}363364/// Bridge to pallet-sponsoring365pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);366impl<T: Config> SponsorshipHandler<T::CrossAccountId, (H160, Vec<u8>)>367	for HelpersContractSponsoring<T>368{369	fn get_sponsor(who: &T::CrossAccountId, call: &(H160, Vec<u8>)) -> Option<T::CrossAccountId> {370		let (contract_address, _) = call;371		let mode = <Pallet<T>>::sponsoring_mode(*contract_address);372		if mode == SponsoringModeT::Disabled {373			return None;374		}375376		let sponsor = match <Pallet<T>>::get_sponsor(*contract_address) {377			Some(sponsor) => sponsor,378			None => return None,379		};380381		if mode == SponsoringModeT::Allowlisted382			&& !<Pallet<T>>::allowed(*contract_address, *who.as_eth())383		{384			return None;385		}386		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;387388		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {389			let limit = <SponsoringRateLimit<T>>::get(contract_address);390391			let timeout = last_tx_block + limit;392			if block_number < timeout {393				return None;394			}395		}396397		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);398399		Some(sponsor)400	}401}402403generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);404generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);