git.delta.rocks / unique-network / refs/commits / 90b12dae5069

difftreelog

misk: Remove some warnings. Add over_max_size test

Trubnikov Sergey2022-10-28parent: #0257bf0.patch.diff
in: master

12 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2347,6 +2347,7 @@
  "sha3-const",
  "similar-asserts",
  "sp-std",
+ "trybuild",
 ]
 
 [[package]]
@@ -12671,6 +12672,21 @@
 ]
 
 [[package]]
+name = "trybuild"
+version = "1.0.71"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea496675d71016e9bc76aa42d87f16aefd95447cc5818e671e12b2d7e269075d"
+dependencies = [
+ "glob",
+ "once_cell",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "termcolor",
+ "toml",
+]
+
+[[package]]
 name = "tt-call"
 version = "1.0.8"
 source = "registry+https://github.com/rust-lang/crates.io-index"
modifiedcrates/evm-coder/Cargo.tomldiffbeforeafterboth
--- a/crates/evm-coder/Cargo.toml
+++ b/crates/evm-coder/Cargo.toml
@@ -29,6 +29,7 @@
 hex-literal = "0.3.4"
 similar-asserts = "1.4.2"
 concat-idents = "1.1.3"
+trybuild = "1.0"
 
 [features]
 default = ["std"]
modifiedcrates/evm-coder/src/custom_signature.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/custom_signature.rs
+++ b/crates/evm-coder/src/custom_signature.rs
@@ -423,15 +423,6 @@
 		assert_eq!(<MaxSize>::name(), "!".repeat(SIGNATURE_SIZE_LIMIT));
 	}
 
-	// This test must NOT compile with "index out of bounds"!
-	// #[test]
-	// fn over_max_size() {
-	// 	assert_eq!(
-	// 		<Vec<MaxSize>>::name(),
-	// 		"!".repeat(SIGNATURE_SIZE_LIMIT) + "[]"
-	// 	);
-	// }
-
 	#[test]
 	fn make_func_without_args() {
 		const SIG: FunctionSignature = make_signature!(
@@ -498,4 +489,10 @@
 	fn shift() {
 		assert_eq!(<(u32,)>::name(), "(uint32)");
 	}
+
+	#[test]
+	fn over_max_size() {
+		let t = trybuild::TestCases::new();
+		t.compile_fail("tests/build_failed/custom_signature_over_max_size.rs");
+	}
 }
addedcrates/evm-coder/tests/build_failed/custom_signature_over_max_size.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/evm-coder/tests/build_failed/custom_signature_over_max_size.rs
@@ -0,0 +1,33 @@
+#![allow(dead_code)]
+use std::str::from_utf8;
+
+use evm_coder::{
+	make_signature,
+	custom_signature::{SignatureUnit, SIGNATURE_SIZE_LIMIT},
+};
+
+trait Name {
+	const SIGNATURE: SignatureUnit;
+
+	fn name() -> &'static str {
+		from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
+	}
+}
+
+impl<T: Name> Name for Vec<T> {
+	evm_coder::make_signature!(new nameof(T) fixed("[]"));
+}
+
+struct MaxSize();
+impl Name for MaxSize {
+	const SIGNATURE: SignatureUnit = SignatureUnit {
+		data: [b'!'; SIGNATURE_SIZE_LIMIT],
+		len: SIGNATURE_SIZE_LIMIT,
+	};
+}
+
+const NAME: SignatureUnit = <Vec<MaxSize>>::SIGNATURE;
+
+fn main() {
+	assert!(false);
+}
addedcrates/evm-coder/tests/build_failed/custom_signature_over_max_size.stderrdiffbeforeafterboth
--- /dev/null
+++ b/crates/evm-coder/tests/build_failed/custom_signature_over_max_size.stderr
@@ -0,0 +1,19 @@
+error: any use of this value will cause an error
+  --> tests/build_failed/custom_signature_over_max_size.rs:18:2
+   |
+18 |     evm_coder::make_signature!(new nameof(T) fixed("[]"));
+   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ index out of bounds: the length is 256 but the index is 256
+   |
+   = note: `#[deny(const_err)]` on by default
+   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
+   = note: for more information, see issue #71800 <https://github.com/rust-lang/rust/issues/71800>
+   = note: this error originates in the macro `make_signature` which comes from the expansion of the macro `evm_coder::make_signature` (in Nightly builds, run with -Z macro-backtrace for more info)
+
+error: any use of this value will cause an error
+  --> tests/build_failed/custom_signature_over_max_size.rs:29:29
+   |
+29 | const NAME: SignatureUnit = <Vec<MaxSize>>::SIGNATURE;
+   | -------------------------   ^^^^^^^^^^^^^^^^^^^^^^^^^ referenced constant has errors
+   |
+   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
+   = note: for more information, see issue #71800 <https://github.com/rust-lang/rust/issues/71800>
modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -35,10 +35,7 @@
 
 use crate::{
 	Pallet, CollectionHandle, Config, CollectionProperties, SelfWeightOf,
-	eth::{
-		convert_cross_account_to_uint256, convert_cross_account_to_tuple,
-		convert_tuple_to_cross_account,
-	},
+	eth::{convert_cross_account_to_uint256, convert_tuple_to_cross_account},
 	weights::WeightInfo,
 };
 
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 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);
after · 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 contract1819extern crate alloc;20use core::marker::PhantomData;21use evm_coder::{22	abi::AbiWriter,23	execution::Result,24	generate_stubgen, solidity_interface,25	types::*,26	ToLog,27	custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},28	make_signature,29};30use pallet_evm::{31	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,32	account::CrossAccountId,33};34use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};35use pallet_evm_transaction_payment::CallContext;36use sp_core::{H160, U256};37use up_data_structs::SponsorshipState;38use crate::{39	AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringFeeLimit,40	SponsoringRateLimit, SponsoringModeT, Sponsoring,41};42use frame_support::traits::Get;43use up_sponsorship::SponsorshipHandler;44use sp_std::vec::Vec;4546/// Pallet events.47#[derive(ToLog)]48pub enum ContractHelpersEvents {49	/// Contract sponsor was set.50	ContractSponsorSet {51		/// Contract address of the affected collection.52		#[indexed]53		contract_address: address,54		/// New sponsor address.55		sponsor: address,56	},5758	/// New sponsor was confirm.59	ContractSponsorshipConfirmed {60		/// Contract address of the affected collection.61		#[indexed]62		contract_address: address,63		/// New sponsor address.64		sponsor: address,65	},6667	/// Collection sponsor was removed.68	ContractSponsorRemoved {69		/// Contract address of the affected collection.70		#[indexed]71		contract_address: address,72	},73}7475/// See [`ContractHelpersCall`]76pub struct ContractHelpers<T: Config>(SubstrateRecorder<T>);77impl<T: Config> WithRecorder<T> for ContractHelpers<T> {78	fn recorder(&self) -> &SubstrateRecorder<T> {79		&self.080	}8182	fn into_recorder(self) -> SubstrateRecorder<T> {83		self.084	}85}8687/// @title Magic contract, which allows users to reconfigure other contracts88#[solidity_interface(name = ContractHelpers, events(ContractHelpersEvents))]89impl<T: Config> ContractHelpers<T>90where91	T::AccountId: AsRef<[u8; 32]>,92{93	/// Get user, which deployed specified contract94	/// @dev May return zero address in case if contract is deployed95	///  using uniquenetwork evm-migration pallet, or using other terms not96	///  intended by pallet-evm97	/// @dev Returns zero address if contract does not exists98	/// @param contractAddress Contract to get owner of99	/// @return address Owner of contract100	fn contract_owner(&self, contract_address: address) -> Result<address> {101		Ok(<Owner<T>>::get(contract_address))102	}103104	/// Set sponsor.105	/// @param contractAddress Contract for which a sponsor is being established.106	/// @param sponsor User address who set as pending sponsor.107	fn set_sponsor(108		&mut self,109		caller: caller,110		contract_address: address,111		sponsor: address,112	) -> Result<void> {113		self.recorder().consume_sload()?;114		self.recorder().consume_sstore()?;115116		Pallet::<T>::set_sponsor(117			&T::CrossAccountId::from_eth(caller),118			contract_address,119			&T::CrossAccountId::from_eth(sponsor),120		)121		.map_err(dispatch_to_evm::<T>)?;122123		Ok(())124	}125126	/// Set contract as self sponsored.127	///128	/// @param contractAddress Contract for which a self sponsoring is being enabled.129	fn self_sponsored_enable(&mut self, caller: caller, contract_address: address) -> Result<void> {130		self.recorder().consume_sload()?;131		self.recorder().consume_sstore()?;132133		let caller = T::CrossAccountId::from_eth(caller);134135		Pallet::<T>::ensure_owner(contract_address, *caller.as_eth())136			.map_err(dispatch_to_evm::<T>)?;137138		Pallet::<T>::force_set_sponsor(139			contract_address,140			&T::CrossAccountId::from_eth(contract_address),141		)142		.map_err(dispatch_to_evm::<T>)?;143144		Ok(())145	}146147	/// Remove sponsor.148	///149	/// @param contractAddress Contract for which a sponsorship is being removed.150	fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {151		self.recorder().consume_sload()?;152		self.recorder().consume_sstore()?;153154		Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)155			.map_err(dispatch_to_evm::<T>)?;156157		Ok(())158	}159160	/// Confirm sponsorship.161	///162	/// @dev Caller must be same that set via [`setSponsor`].163	///164	/// @param contractAddress Сontract for which need to confirm sponsorship.165	fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {166		self.recorder().consume_sload()?;167		self.recorder().consume_sstore()?;168169		Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)170			.map_err(dispatch_to_evm::<T>)?;171172		Ok(())173	}174175	/// Get current sponsor.176	///177	/// @param contractAddress The contract for which a sponsor is requested.178	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.179	fn sponsor(&self, contract_address: address) -> Result<(address, uint256)> {180		let sponsor =181			Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;182		Ok(pallet_common::eth::convert_cross_account_to_tuple::<T>(183			&sponsor,184		))185	}186187	/// Check tat contract has confirmed sponsor.188	///189	/// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.190	/// @return **true** if contract has confirmed sponsor.191	fn has_sponsor(&self, contract_address: address) -> Result<bool> {192		Ok(Pallet::<T>::get_sponsor(contract_address).is_some())193	}194195	/// Check tat contract has pending sponsor.196	///197	/// @param contractAddress The contract for which the presence of a pending sponsor is checked.198	/// @return **true** if contract has pending sponsor.199	fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {200		Ok(match Sponsoring::<T>::get(contract_address) {201			SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,202			SponsorshipState::Unconfirmed(_) => true,203		})204	}205206	fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {207		Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)208	}209210	fn set_sponsoring_mode(211		&mut self,212		caller: caller,213		contract_address: address,214		// TODO: implement support for enums in evm-coder215		mode: uint8,216	) -> Result<void> {217		self.recorder().consume_sload()?;218		self.recorder().consume_sstore()?;219220		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;221		let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;222		<Pallet<T>>::set_sponsoring_mode(contract_address, mode);223224		Ok(())225	}226227	/// Get current contract sponsoring rate limit228	/// @param contractAddress Contract to get sponsoring rate limit of229	/// @return uint32 Amount of blocks between two sponsored transactions230	fn sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {231		self.recorder().consume_sload()?;232233		Ok(<SponsoringRateLimit<T>>::get(contract_address)234			.try_into()235			.map_err(|_| "rate limit > u32::MAX")?)236	}237238	/// Set contract sponsoring rate limit239	/// @dev Sponsoring rate limit - is a minimum amount of blocks that should240	///  pass between two sponsored transactions241	/// @param contractAddress Contract to change sponsoring rate limit of242	/// @param rateLimit Target rate limit243	/// @dev Only contract owner can change this setting244	fn set_sponsoring_rate_limit(245		&mut self,246		caller: caller,247		contract_address: address,248		rate_limit: uint32,249	) -> Result<void> {250		self.recorder().consume_sload()?;251		self.recorder().consume_sstore()?;252253		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;254		<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());255		Ok(())256	}257258	/// Set contract sponsoring fee limit259	/// @dev Sponsoring fee limit - is maximum fee that could be spent by260	///  single transaction261	/// @param contractAddress Contract to change sponsoring fee limit of262	/// @param feeLimit Fee limit263	/// @dev Only contract owner can change this setting264	fn set_sponsoring_fee_limit(265		&mut self,266		caller: caller,267		contract_address: address,268		fee_limit: uint256,269	) -> Result<void> {270		self.recorder().consume_sload()?;271		self.recorder().consume_sstore()?;272273		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;274		<Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())275			.map_err(dispatch_to_evm::<T>)?;276		Ok(())277	}278279	/// Get current contract sponsoring fee limit280	/// @param contractAddress Contract to get sponsoring fee limit of281	/// @return uint256 Maximum amount of fee that could be spent by single282	///  transaction283	fn sponsoring_fee_limit(&self, contract_address: address) -> Result<uint256> {284		self.recorder().consume_sload()?;285286		Ok(get_sponsoring_fee_limit::<T>(contract_address))287	}288289	/// Is specified user present in contract allow list290	/// @dev Contract owner always implicitly included291	/// @param contractAddress Contract to check allowlist of292	/// @param user User to check293	/// @return bool Is specified users exists in contract allowlist294	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {295		self.0.consume_sload()?;296		Ok(<Pallet<T>>::allowed(contract_address, user))297	}298299	/// Toggle user presence in contract allowlist300	/// @param contractAddress Contract to change allowlist of301	/// @param user Which user presence should be toggled302	/// @param isAllowed `true` if user should be allowed to be sponsored303	///  or call this contract, `false` otherwise304	/// @dev Only contract owner can change this setting305	fn toggle_allowed(306		&mut self,307		caller: caller,308		contract_address: address,309		user: address,310		is_allowed: bool,311	) -> Result<void> {312		self.recorder().consume_sload()?;313		self.recorder().consume_sstore()?;314315		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;316		<Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);317318		Ok(())319	}320321	/// Is this contract has allowlist access enabled322	/// @dev Allowlist always can have users, and it is used for two purposes:323	///  in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist324	///  in case of allowlist access enabled, only users from allowlist may call this contract325	/// @param contractAddress Contract to get allowlist access of326	/// @return bool Is specified contract has allowlist access enabled327	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {328		Ok(<AllowlistEnabled<T>>::get(contract_address))329	}330331	/// Toggle contract allowlist access332	/// @param contractAddress Contract to change allowlist access of333	/// @param enabled Should allowlist access to be enabled?334	fn toggle_allowlist(335		&mut self,336		caller: caller,337		contract_address: address,338		enabled: bool,339	) -> Result<void> {340		self.recorder().consume_sload()?;341		self.recorder().consume_sstore()?;342343		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;344		<Pallet<T>>::toggle_allowlist(contract_address, enabled);345		Ok(())346	}347}348349/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]350pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);351impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>352where353	T::AccountId: AsRef<[u8; 32]>,354{355	fn is_reserved(contract: &sp_core::H160) -> bool {356		contract == &T::ContractAddress::get()357	}358359	fn is_used(contract: &sp_core::H160) -> bool {360		contract == &T::ContractAddress::get()361	}362363	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {364		// TODO: Extract to another OnMethodCall handler365		if <AllowlistEnabled<T>>::get(handle.code_address())366			&& !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)367		{368			return Some(Err(PrecompileFailure::Revert {369				exit_status: ExitRevert::Reverted,370				output: {371					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));372					writer.string("Target contract is allowlisted");373					writer.finish()374				},375			}));376		}377378		if handle.code_address() != T::ContractAddress::get() {379			return None;380		}381382		let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));383		pallet_evm_coder_substrate::call(handle, helpers)384	}385386	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {387		(contract == &T::ContractAddress::get())388			.then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())389	}390}391392/// Hooks into contract creation, storing owner of newly deployed contract393pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);394impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {395	fn on_create(owner: H160, contract: H160) {396		<Owner<T>>::insert(contract, owner);397	}398}399400/// Bridge to pallet-sponsoring401pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);402impl<T: Config> SponsorshipHandler<T::CrossAccountId, CallContext>403	for HelpersContractSponsoring<T>404{405	fn get_sponsor(406		who: &T::CrossAccountId,407		call_context: &CallContext,408	) -> Option<T::CrossAccountId> {409		let contract_address = call_context.contract_address;410		let mode = <Pallet<T>>::sponsoring_mode(contract_address);411		if mode == SponsoringModeT::Disabled {412			return None;413		}414415		let sponsor = match <Pallet<T>>::get_sponsor(contract_address) {416			Some(sponsor) => sponsor,417			None => return None,418		};419420		if mode == SponsoringModeT::Allowlisted421			&& !<Pallet<T>>::allowed(contract_address, *who.as_eth())422		{423			return None;424		}425		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;426427		if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {428			let limit = <SponsoringRateLimit<T>>::get(contract_address);429430			let timeout = last_tx_block + limit;431			if block_number < timeout {432				return None;433			}434		}435436		let sponsored_fee_limit = get_sponsoring_fee_limit::<T>(contract_address);437438		if call_context.max_fee > sponsored_fee_limit {439			return None;440		}441442		<SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);443444		Some(sponsor)445	}446}447448fn get_sponsoring_fee_limit<T: Config>(contract_address: address) -> uint256 {449	<SponsoringFeeLimit<T>>::get(contract_address)450		.get(&0xffffffff)451		.cloned()452		.unwrap_or(U256::MAX)453}454455generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);456generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -28,7 +28,6 @@
 	custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
 	make_signature,
 };
-use pallet_common::eth::convert_tuple_to_cross_account;
 use up_data_structs::CollectionMode;
 use pallet_common::erc::{CommonEvmHandler, PrecompileResult};
 use sp_std::vec::Vec;
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -21,7 +21,6 @@
 
 extern crate alloc;
 
-use alloc::string::ToString;
 use core::{
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,
@@ -39,7 +38,6 @@
 use pallet_common::{
 	CollectionHandle, CollectionPropertyPermissions,
 	erc::{CommonEvmHandler, CollectionCall, static_property::key},
-	eth::convert_tuple_to_cross_account,
 };
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
 use pallet_evm_coder_substrate::{call, dispatch_to_evm};
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -42,10 +42,7 @@
 	CreateCollectionData,
 };
 
-use crate::{
-	weights::WeightInfo, Config, SelfWeightOf, NftTransferBasket, FungibleTransferBasket,
-	ReFungibleTransferBasket, NftApproveBasket, FungibleApproveBasket, RefungibleApproveBasket,
-};
+use crate::{weights::WeightInfo, Config, SelfWeightOf};
 
 use alloc::format;
 use sp_std::vec::Vec;
modifiedruntime/common/config/pallets/scheduler.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/scheduler.rs
+++ b/runtime/common/config/pallets/scheduler.rs
@@ -25,7 +25,7 @@
 use codec::Decode;
 use crate::{
 	runtime_common::{scheduler::SchedulerPaymentExecutor, config::substrate::RuntimeBlockWeights},
-	Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, OriginCaller, Balances,
+	Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, OriginCaller,
 };
 use pallet_unique_scheduler_v2::ScheduledEnsureOriginSuccess;
 use up_common::types::AccountId;
modifiedruntime/common/scheduler.rsdiffbeforeafterboth
--- a/runtime/common/scheduler.rs
+++ b/runtime/common/scheduler.rs
@@ -14,19 +14,16 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-use frame_support::{
-	traits::NamedReservableCurrency,
-	dispatch::{GetDispatchInfo, PostDispatchInfo, DispatchInfo},
-};
+use frame_support::dispatch::{GetDispatchInfo, PostDispatchInfo, DispatchInfo};
 use sp_runtime::{
 	traits::{Dispatchable, Applyable, Member},
 	generic::Era,
 	transaction_validity::TransactionValidityError,
-	DispatchErrorWithPostInfo, DispatchError,
+	DispatchErrorWithPostInfo,
 };
 use codec::Encode;
-use crate::{Runtime, RuntimeCall, RuntimeOrigin, Balances};
-use up_common::types::{AccountId, Balance};
+use crate::{Runtime, RuntimeCall, RuntimeOrigin};
+use up_common::types::AccountId;
 use fp_self_contained::SelfContainedCall;
 use pallet_unique_scheduler_v2::DispatchCall;
 use pallet_transaction_payment::ChargeTransactionPayment;