git.delta.rocks / unique-network / refs/commits / 60ea0ef4a6b1

difftreelog

feat evm contract helpers pallet

Yaroslav Bolyukin2021-07-27parent: #026f1bb.patch.diff
in: master

5 files changed

addedpallets/evm-contract-helpers/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/pallets/evm-contract-helpers/Cargo.toml
@@ -0,0 +1,36 @@
+[package]
+name = "pallet-evm-contract-helpers"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies]
+frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.8' }
+frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.8' }
+sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.8' }
+sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.8' }
+sp-core = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.8' }
+evm-coder = { default-features = false, path = '../../crates/evm-coder' }
+pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
+pallet-evm = { default-features = false, version = "5.0.0-dev", git = "https://github.com/uniquenetwork/frontier.git", branch = "injected-transactions-parachain" }
+up-sponsorship = { default-features = false, path = '../../primitives/sponsorship' }
+log = "0.4.14"
+
+[dependencies.codec]
+default-features = false
+features = ['derive']
+package = 'parity-scale-codec'
+version = '2.0.0'
+
+[features]
+default = ["std"]
+std = [
+    "frame-support/std",
+    "frame-system/std",
+    "sp-runtime/std",
+    "sp-std/std",
+    "sp-core/std",
+    "evm-coder/std",
+    "pallet-evm-coder-substrate/std",
+    "pallet-evm/std",
+    "up-sponsorship/std",
+]
addedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
after · pallets/evm-contract-helpers/src/eth.rs
1use core::marker::PhantomData;2use evm_coder::{abi::AbiWriter, execution::Result, solidity_interface, types::*};3use pallet_evm_coder_substrate::SubstrateRecorder;4use pallet_evm::{ExitReason, ExitRevert, OnCreate, OnMethodCall, PrecompileOutput};5use sp_core::H160;6use crate::{7	AllowlistEnabled, Config, Owner, Pallet, SelfSponsoring, SponsorBasket, SponsoringRateLimit,8};9use frame_support::traits::Get;10use up_sponsorship::SponsorshipHandler;11use sp_std::vec::Vec;1213struct ContractHelpers<T: Config>(SubstrateRecorder<T>);1415#[solidity_interface(name = "ContractHelpers")]16impl<T: Config> ContractHelpers<T> {17	fn contract_owner(&self, contract: address) -> Result<address> {18		self.0.consume_sload()?;19		Ok(<Owner<T>>::get(contract))20	}2122	fn sponsoring_enabled(&self, contract: address) -> Result<bool> {23		self.0.consume_sload()?;24		Ok(<SelfSponsoring<T>>::get(contract))25	}2627	fn toggle_sponsoring(28		&mut self,29		caller: caller,30		contract: address,31		enabled: bool,32	) -> Result<void> {33		self.0.consume_sload()?;34		<Pallet<T>>::ensure_owner(contract, caller)?;35		self.0.consume_sstore()?;36		<Pallet<T>>::toggle_sponsoring(contract, enabled);37		Ok(())38	}3940	fn allowed(&self, contract: address, user: address) -> Result<bool> {41		self.0.consume_sload()?;42		Ok(<Pallet<T>>::allowed(contract, user))43	}4445	fn allowlist_enabled(&self, contract: address) -> Result<bool> {46		self.0.consume_sload()?;47		Ok(<AllowlistEnabled<T>>::get(contract))48	}4950	fn toggle_allowlist(51		&mut self,52		caller: caller,53		contract: address,54		enabled: bool,55	) -> Result<void> {56		self.0.consume_sload()?;57		<Pallet<T>>::ensure_owner(contract, caller)?;58		self.0.consume_sstore()?;59		<Pallet<T>>::toggle_allowlist(contract, enabled);60		Ok(())61	}6263	fn toggle_allowed(64		&mut self,65		caller: caller,66		contract: address,67		user: address,68		allowed: bool,69	) -> Result<void> {70		self.0.consume_sload()?;71		<Pallet<T>>::ensure_owner(contract, caller)?;72		self.0.consume_sstore()?;73		<Pallet<T>>::toggle_allowed(contract, user, allowed);74		Ok(())75	}76}7778pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);79impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T> {80	fn is_reserved(contract: &sp_core::H160) -> bool {81		contract == &T::ContractAddress::get()82	}8384	fn is_used(contract: &sp_core::H160) -> bool {85		contract == &T::ContractAddress::get()86	}8788	fn call(89		source: &sp_core::H160,90		target: &sp_core::H160,91		gas_left: u64,92		input: &[u8],93		value: sp_core::U256,94	) -> Option<PrecompileOutput> {95		// TODO: Extract to another OnMethodCall handler96		if !<Pallet<T>>::allowed(*target, *source) {97			return Some(PrecompileOutput {98				exit_status: ExitReason::Revert(ExitRevert::Reverted),99				cost: 0,100				output: {101					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));102					writer.string("Target contract is allowlisted");103					writer.finish()104				},105				logs: sp_std::vec![],106			});107		}108109		if target != &T::ContractAddress::get() {110			return None;111		}112113		let mut helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(*target, gas_left));114		let result = pallet_evm_coder_substrate::call_internal(*source, &mut helpers, value, input);115		helpers.0.evm_to_precompile_output(result)116	}117118	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {119		(contract == &T::ContractAddress::get())120			.then(|| include_bytes!("./stubs/ContractHelpers.bin").to_vec())121	}122}123124pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);125impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {126	fn on_create(owner: H160, contract: H160) {127		<Owner<T>>::insert(contract, owner);128	}129}130131pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);132impl<T: Config> SponsorshipHandler<H160, (H160, Vec<u8>)> for HelpersContractSponsoring<T> {133	fn get_sponsor(who: &H160, call: &(H160, Vec<u8>)) -> Option<H160> {134		if <SelfSponsoring<T>>::get(&call.0) {135			let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;136			let limit = <SponsoringRateLimit<T>>::get(&call.0);137			if let Some(last_tx_block) = <SponsorBasket<T>>::get(&call.0, who) {138				<SponsorBasket<T>>::insert(&call.0, who, block_number);139				let limit_time = last_tx_block + limit.into();140				if block_number > limit_time {141					return Some(call.0);142				}143			} else {144				<SponsorBasket<T>>::insert(&call.0, who, block_number);145				return Some(call.0);146			}147		}148		None149	}150}
addedpallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -0,0 +1,92 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+pub use pallet::*;
+pub use eth::*;
+pub mod eth;
+
+#[frame_support::pallet]
+pub mod pallet {
+	use evm_coder::execution::Result;
+	use frame_support::pallet_prelude::*;
+	use pallet_evm::RawEvent;
+	use sp_core::H160;
+
+	#[pallet::config]
+	pub trait Config: frame_system::Config + pallet_evm_coder_substrate::Config {
+		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
+
+		type ContractAddress: Get<H160>;
+	}
+
+	#[pallet::error]
+	pub enum Error<T> {
+		/// This method is only executable by owner
+		NoPermission,
+	}
+
+	#[pallet::pallet]
+	#[pallet::generate_store(pub(super) trait Store)]
+	pub struct Pallet<T>(_);
+
+	#[pallet::storage]
+	pub(super) type Owner<T: Config> =
+		StorageMap<Hasher = Twox128, Key = H160, Value = H160, QueryKind = ValueQuery>;
+
+	#[pallet::storage]
+	pub(super) type SelfSponsoring<T: Config> =
+		StorageMap<Hasher = Twox128, Key = H160, Value = bool, QueryKind = ValueQuery>;
+
+	#[pallet::storage]
+	pub(super) type SponsoringRateLimit<T: Config> =
+		StorageMap<Hasher = Twox128, Key = H160, Value = T::BlockNumber, QueryKind = ValueQuery>;
+
+	#[pallet::storage]
+	pub(super) type SponsorBasket<T: Config> = StorageDoubleMap<
+		Hasher1 = Twox128,
+		Key1 = H160,
+		Hasher2 = Twox128,
+		Key2 = H160,
+		Value = T::BlockNumber,
+		QueryKind = OptionQuery,
+	>;
+
+	#[pallet::storage]
+	pub(super) type AllowlistEnabled<T: Config> =
+		StorageMap<Hasher = Twox128, Key = H160, Value = bool, QueryKind = ValueQuery>;
+
+	#[pallet::storage]
+	pub(super) type Allowlist<T: Config> = StorageDoubleMap<
+		Hasher1 = Twox128,
+		Key1 = H160,
+		Hasher2 = Twox128,
+		Key2 = H160,
+		Value = bool,
+		QueryKind = ValueQuery,
+	>;
+
+	impl<T: Config> Pallet<T> {
+		pub fn toggle_sponsoring(contract: H160, enabled: bool) {
+			<SelfSponsoring<T>>::insert(contract, enabled);
+		}
+
+		pub fn allowed(contract: H160, user: H160) -> bool {
+			if !<AllowlistEnabled<T>>::get(contract) {
+				return true;
+			}
+			<Allowlist<T>>::get(&contract, &user) || <Owner<T>>::get(&contract) == user
+		}
+
+		pub fn toggle_allowlist(contract: H160, enabled: bool) {
+			<AllowlistEnabled<T>>::insert(contract, enabled)
+		}
+
+		pub fn toggle_allowed(contract: H160, user: H160, allowed: bool) {
+			<Allowlist<T>>::insert(contract, user, allowed);
+		}
+
+		pub fn ensure_owner(contract: H160, user: H160) -> Result<()> {
+			ensure!(<Owner<T>>::get(&contract) == user, "no permission");
+			Ok(())
+		}
+	}
+}
addedpallets/evm-contract-helpers/src/stubs/ContractHelpers.bindiffbeforeafterboth

binary blob — no preview

addedpallets/evm-contract-helpers/src/stubs/ContractHelpers.soldiffbeforeafterboth
--- /dev/null
+++ b/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
@@ -0,0 +1,40 @@
+contract ContractHelpers {
+    uint8 _dummmy = 0;
+    address _dummy_addr = 0x0000000000000000000000000000000000000000;
+	string stub_error = "this contract does not exists, contract helpers are implemented on substrate chain side";
+
+    function contractOwner(address contract_address) public view returns (address) {
+        require(false, stub_error);
+        contract_address;
+        return _dummy_addr;
+    }
+    
+    function sponsoringEnabled(address contract_address) public view returns (bool) {
+        require(false, stub_error);
+        contract_address;
+        _dummmy;
+        return false;
+    }
+    
+    function toggleSponsoring(address contract_address, bool enabled) public {
+        require(false, stub_error);
+        contract_address;
+        enabled;
+        _dummmy = 0;
+    }
+    
+    function toggleAllowlist(address contract_address, bool enabled) public {
+        require(false, stub_error);
+        contract_address;
+        enabled;
+        _dummmy = 0;
+    }
+    
+    function toggleAllowed(address contract_address, address user, bool allowed) public {
+        require(false, stub_error);
+        contract_address;
+        user;
+        allowed;
+        _dummmy = 0;
+    }
+}
\ No newline at end of file