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

difftreelog

fmt

Trubnikov Sergey2022-09-13parent: #b5cee7d.patch.diff
in: master

3 files changed

modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -74,7 +74,7 @@
 	///
 	/// @param key Property key.
 	/// @param value Propery value.
-	#[weight(<SelfWeightOf<T>>::set_collection_properties(1_u32))]
+	#[weight(<SelfWeightOf<T>>::set_collection_properties(1))]
 	fn set_collection_property(
 		&mut self,
 		caller: caller,
@@ -94,7 +94,7 @@
 	/// Delete collection property.
 	///
 	/// @param key Property key.
-	#[weight(<SelfWeightOf<T>>::delete_collection_properties(1_u32))]
+	#[weight(<SelfWeightOf<T>>::delete_collection_properties(1))]
 	fn delete_collection_property(&mut self, caller: caller, key: string) -> Result<()> {
 		self.consume_store_reads_and_writes(1, 1)?;
 
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -71,9 +71,11 @@
 }
 
 /// Convert `CrossAccountId` to `(address, uint256)`.
-pub fn convert_cross_account_to_tuple<T: Config>(cross_account_id: &T::CrossAccountId) -> (address, uint256)
+pub fn convert_cross_account_to_tuple<T: Config>(
+	cross_account_id: &T::CrossAccountId,
+) -> (address, uint256)
 where
-	T::AccountId: AsRef<[u8; 32]>
+	T::AccountId: AsRef<[u8; 32]>,
 {
 	if cross_account_id.is_canonical_substrate() {
 		let sub = convert_cross_account_to_uint256::<T>(cross_account_id);
@@ -82,4 +84,4 @@
 		let eth = *cross_account_id.as_eth();
 		(eth, Default::default())
 	}
-}
\ No newline at end of file
+}
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
before · pallets/evm-contract-helpers/src/eth.rs
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		Ok(pallet_common::eth::convert_cross_account_to_tuple::<T>(&sponsor))175	}176177	/// Check tat contract has confirmed sponsor.178	///179	/// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.180	/// @return **true** if contract has confirmed sponsor.181	fn has_sponsor(&self, contract_address: address) -> Result<bool> {182		Ok(Pallet::<T>::get_sponsor(contract_address).is_some())183	}184185	/// Check tat contract has pending sponsor.186	///187	/// @param contractAddress The contract for which the presence of a pending sponsor is checked.188	/// @return **true** if contract has pending sponsor.189	fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {190		Ok(match Sponsoring::<T>::get(contract_address) {191			SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,192			SponsorshipState::Unconfirmed(_) => true,193		})194	}195196	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {197		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)198	}199200	fn set_sponsoring_mode(201		&mut self,202		caller: caller,203		contract_address: address,204		// TODO: implement support for enums in evm-coder205		mode: uint8,206	) -> Result<void> {207		self.recorder().consume_sload()?;208		self.recorder().consume_sstore()?;209210		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;211		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;212		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);213214		Ok(())215	}216217	/// Get current contract sponsoring rate limit218	/// @param contractAddress Contract to get sponsoring mode of219	/// @return uint32 Amount of blocks between two sponsored transactions220	fn get_sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {221		Ok(<SponsoringRateLimit<T>>::get(contract_address)222			.try_into()223			.map_err(|_| "rate limit > u32::MAX")?)224	}225226	/// Set contract sponsoring rate limit227	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should228	///  pass between two sponsored transactions229	/// @param contractAddress Contract to change sponsoring rate limit of230	/// @param rateLimit Target rate limit231	/// @dev Only contract owner can change this setting232	fn set_sponsoring_rate_limit(233		&mut self,234		caller: caller,235		contract_address: address,236		rate_limit: uint32,237	) -> Result<void> {238		self.recorder().consume_sload()?;239		self.recorder().consume_sstore()?;240241		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;242		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());243		Ok(())244	}245246	/// Is specified user present in contract allow list247	/// @dev Contract owner always implicitly included248	/// @param contractAddress Contract to check allowlist of249	/// @param user User to check250	/// @return bool Is specified users exists in contract allowlist251	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {252		self.0.consume_sload()?;253		Ok(<Pallet<T>>::allowed(contract_address, user))254	}255256	/// Toggle user presence in contract allowlist257	/// @param contractAddress Contract to change allowlist of258	/// @param user Which user presence should be toggled259	/// @param isAllowed `true` if user should be allowed to be sponsored260	///  or call this contract, `false` otherwise261	/// @dev Only contract owner can change this setting262	fn toggle_allowed(263		&mut self,264		caller: caller,265		contract_address: address,266		user: address,267		is_allowed: bool,268	) -> Result<void> {269		self.recorder().consume_sload()?;270		self.recorder().consume_sstore()?;271272		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;273		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);274275		Ok(())276	}277278	/// Is this contract has allowlist access enabled279	/// @dev Allowlist always can have users, and it is used for two purposes:280	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist281	///  in case of allowlist access enabled, only users from allowlist may call this contract282	/// @param contractAddress Contract to get allowlist access of283	/// @return bool Is specified contract has allowlist access enabled284	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {285		Ok(<AllowlistEnabled<T>>::get(contract_address))286	}287288	/// Toggle contract allowlist access289	/// @param contractAddress Contract to change allowlist access of290	/// @param enabled Should allowlist access to be enabled?291	fn toggle_allowlist(292		&mut self,293		caller: caller,294		contract_address: address,295		enabled: bool,296	) -> Result<void> {297		self.recorder().consume_sload()?;298		self.recorder().consume_sstore()?;299300		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;301		<Pallet<T>>::toggle_allowlist(contract_address, enabled);302		Ok(())303	}304}305306/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]307pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);308impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>309where310	T::AccountId: AsRef<[u8; 32]>,311{312	fn is_reserved(contract: &sp_core::H160) -> bool {313		contract == &T::ContractAddress::get()314	}315316	fn is_used(contract: &sp_core::H160) -> bool {317		contract == &T::ContractAddress::get()318	}319320	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {321		// TODO: Extract to another OnMethodCall handler322		if <AllowlistEnabled<T>>::get(handle.code_address())323			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)324		{325			return Some(Err(PrecompileFailure::Revert {326				exit_status: ExitRevert::Reverted,327				output: {328					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));329					writer.string("Target contract is allowlisted");330					writer.finish()331				},332			}));333		}334335		if handle.code_address() != T::ContractAddress::get() {336			return None;337		}338339		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));340		pallet_evm_coder_substrate::call(handle, helpers)341	}342343	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {344		(contract == &T::ContractAddress::get())345			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())346	}347}348349/// Hooks into contract creation, storing owner of newly deployed contract350pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);351impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {352	fn on_create(owner: H160, contract: H160) {353		<Owner<T>>::insert(contract, owner);354	}355}356357/// Bridge to pallet-sponsoring358pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);359impl<T: Config> SponsorshipHandler<T::CrossAccountId, (H160, Vec<u8>)>360	for HelpersContractSponsoring<T>361{362	fn get_sponsor(who: &T::CrossAccountId, call: &(H160, Vec<u8>)) -> Option<T::CrossAccountId> {363		let (contract_address, _) = call;364		let mode = <Pallet<T>>::sponsoring_mode(*contract_address);365		if mode == SponsoringModeT::Disabled {366			return None;367		}368369		let sponsor = match <Pallet<T>>::get_sponsor(*contract_address) {370			Some(sponsor) => sponsor,371			None => return None,372		};373374		if mode == SponsoringModeT::Allowlisted375			&& !<Pallet<T>>::allowed(*contract_address, *who.as_eth())376		{377			return None;378		}379		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;380381		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {382			let limit = <SponsoringRateLimit<T>>::get(contract_address);383384			let timeout = last_tx_block + limit;385			if block_number < timeout {386				return None;387			}388		}389390		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);391392		Some(sponsor)393	}394}395396generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);397generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);