difftreelog
chore add sload/sstore and doucumentation
in: master
1 file changed
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth1// 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, U256};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 .map_err(dispatch_to_evm::<T>)?;263 Ok(())264 }265266 fn get_sponsoring_fee_limit(&self, contract_address: address) -> Result<uint256> {267 Ok(get_sponsoring_fee_limit::<T>(contract_address))268 }269270 /// Is specified user present in contract allow list271 /// @dev Contract owner always implicitly included272 /// @param contractAddress Contract to check allowlist of273 /// @param user User to check274 /// @return bool Is specified users exists in contract allowlist275 fn allowed(&self, contract_address: address, user: address) -> Result<bool> {276 self.0.consume_sload()?;277 Ok(<Pallet<T>>::allowed(contract_address, user))278 }279280 /// Toggle user presence in contract allowlist281 /// @param contractAddress Contract to change allowlist of282 /// @param user Which user presence should be toggled283 /// @param isAllowed `true` if user should be allowed to be sponsored284 /// or call this contract, `false` otherwise285 /// @dev Only contract owner can change this setting286 fn toggle_allowed(287 &mut self,288 caller: caller,289 contract_address: address,290 user: address,291 is_allowed: bool,292 ) -> Result<void> {293 self.recorder().consume_sload()?;294 self.recorder().consume_sstore()?;295296 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;297 <Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);298299 Ok(())300 }301302 /// Is this contract has allowlist access enabled303 /// @dev Allowlist always can have users, and it is used for two purposes:304 /// in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist305 /// in case of allowlist access enabled, only users from allowlist may call this contract306 /// @param contractAddress Contract to get allowlist access of307 /// @return bool Is specified contract has allowlist access enabled308 fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {309 Ok(<AllowlistEnabled<T>>::get(contract_address))310 }311312 /// Toggle contract allowlist access313 /// @param contractAddress Contract to change allowlist access of314 /// @param enabled Should allowlist access to be enabled?315 fn toggle_allowlist(316 &mut self,317 caller: caller,318 contract_address: address,319 enabled: bool,320 ) -> Result<void> {321 self.recorder().consume_sload()?;322 self.recorder().consume_sstore()?;323324 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;325 <Pallet<T>>::toggle_allowlist(contract_address, enabled);326 Ok(())327 }328}329330/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]331pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);332impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>333where334 T::AccountId: AsRef<[u8; 32]>,335{336 fn is_reserved(contract: &sp_core::H160) -> bool {337 contract == &T::ContractAddress::get()338 }339340 fn is_used(contract: &sp_core::H160) -> bool {341 contract == &T::ContractAddress::get()342 }343344 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {345 // TODO: Extract to another OnMethodCall handler346 if <AllowlistEnabled<T>>::get(handle.code_address())347 && !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)348 {349 return Some(Err(PrecompileFailure::Revert {350 exit_status: ExitRevert::Reverted,351 output: {352 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));353 writer.string("Target contract is allowlisted");354 writer.finish()355 },356 }));357 }358359 if handle.code_address() != T::ContractAddress::get() {360 return None;361 }362363 let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));364 pallet_evm_coder_substrate::call(handle, helpers)365 }366367 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {368 (contract == &T::ContractAddress::get())369 .then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())370 }371}372373/// Hooks into contract creation, storing owner of newly deployed contract374pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);375impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {376 fn on_create(owner: H160, contract: H160) {377 <Owner<T>>::insert(contract, owner);378 }379}380381/// Bridge to pallet-sponsoring382pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);383impl<T: Config> SponsorshipHandler<T::CrossAccountId, CallContext>384 for HelpersContractSponsoring<T>385{386 fn get_sponsor(387 who: &T::CrossAccountId,388 call_context: &CallContext,389 ) -> Option<T::CrossAccountId> {390 let contract_address = call_context.contract_address;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 = get_sponsoring_fee_limit::<T>(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}428429fn get_sponsoring_fee_limit<T: Config>(contract_address: address) -> uint256 {430 <SponsoringFeeLimit<T>>::get(contract_address)431 .get(&0xffffffff)432 .cloned()433 .unwrap_or(U256::MAX)434}435436generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);437generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);