difftreelog
refactor Chage Owner storage value type H160 -> CrossAccountId BREAKING CHANGE: changed `fn allowed` signature
in: master
2 files 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/>.1617use core::marker::PhantomData;18use evm_coder::{19 abi::AbiWriter,20 execution::{Result, Error},21 generate_stubgen, solidity_interface,22 types::*,23};24use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};25use pallet_evm::{26 ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,27 account::CrossAccountId,28};29use sp_core::H160;30use crate::{31 AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringRateLimit, SponsoringModeT,32};33use frame_support::traits::Get;34use up_sponsorship::SponsorshipHandler;35use sp_std::vec::Vec;3637struct ContractHelpers<T: Config>(SubstrateRecorder<T>);38impl<T: Config> WithRecorder<T> for ContractHelpers<T> {39 fn recorder(&self) -> &SubstrateRecorder<T> {40 &self.041 }4243 fn into_recorder(self) -> SubstrateRecorder<T> {44 self.045 }46}4748#[solidity_interface(name = "ContractHelpers")]49impl<T: Config> ContractHelpers<T> {50 fn contract_owner(&self, contract_address: address) -> Result<address> {51 Ok(<Pallet<T>>::contract_owner(contract_address)52 .map_err(dispatch_to_evm::<T>)?53 .as_eth()54 .clone())55 }5657 fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {58 Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)59 }6061 /// Deprecated62 fn toggle_sponsoring(63 &mut self,64 caller: caller,65 contract_address: address,66 enabled: bool,67 ) -> Result<void> {68 <Pallet<T>>::ensure_owner(contract_address, caller)?;69 <Pallet<T>>::toggle_sponsoring(contract_address, enabled);70 Ok(())71 }7273 fn set_sponsoring_mode(74 &mut self,75 caller: caller,76 contract_address: address,77 mode: uint8,78 ) -> Result<void> {79 <Pallet<T>>::ensure_owner(contract_address, caller)?;80 let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;81 <Pallet<T>>::set_sponsoring_mode(contract_address, mode);82 Ok(())83 }8485 fn sponsoring_mode(&self, contract_address: address) -> Result<uint8> {86 Ok(<Pallet<T>>::sponsoring_mode(contract_address).to_eth())87 }8889 fn set_sponsoring_rate_limit(90 &mut self,91 caller: caller,92 contract_address: address,93 rate_limit: uint32,94 ) -> Result<void> {95 <Pallet<T>>::ensure_owner(contract_address, caller)?;96 <Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());97 Ok(())98 }99100 fn get_sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {101 Ok(<SponsoringRateLimit<T>>::get(contract_address)102 .try_into()103 .map_err(|_| "rate limit > u32::MAX")?)104 }105106 fn allowed(&self, contract_address: address, user: address) -> Result<bool> {107 self.0.consume_sload()?;108 Ok(<Pallet<T>>::allowed(contract_address, T::CrossAccountId::from_eth(user)))109 }110111 fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {112 Ok(<AllowlistEnabled<T>>::get(contract_address))113 }114115 fn toggle_allowlist(116 &mut self,117 caller: caller,118 contract_address: address,119 enabled: bool,120 ) -> Result<void> {121 <Pallet<T>>::ensure_owner(contract_address, caller)?;122 <Pallet<T>>::toggle_allowlist(contract_address, enabled);123 Ok(())124 }125126 fn toggle_allowed(127 &mut self,128 caller: caller,129 contract_address: address,130 user: address,131 allowed: bool,132 ) -> Result<void> {133 <Pallet<T>>::ensure_owner(contract_address, caller)?;134 <Pallet<T>>::toggle_allowed(contract_address, user, allowed);135 Ok(())136 }137}138139pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);140impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T> {141 fn is_reserved(contract: &sp_core::H160) -> bool {142 contract == &T::ContractAddress::get()143 }144145 fn is_used(contract: &sp_core::H160) -> bool {146 contract == &T::ContractAddress::get()147 }148149 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {150 // TODO: Extract to another OnMethodCall handler151 if <AllowlistEnabled<T>>::get(handle.code_address())152 && !<Pallet<T>>::allowed(handle.code_address(), T::CrossAccountId::from_eth(handle.context().caller))153 {154 return Some(Err(PrecompileFailure::Revert {155 exit_status: ExitRevert::Reverted,156 output: {157 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));158 writer.string("Target contract is allowlisted");159 writer.finish()160 },161 }));162 }163164 if handle.code_address() != T::ContractAddress::get() {165 return None;166 }167168 let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));169 pallet_evm_coder_substrate::call(handle, helpers)170 }171172 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {173 (contract == &T::ContractAddress::get())174 .then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())175 }176}177178pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);179impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {180 fn on_create(owner: H160, contract: H160) {181 <Owner<T>>::insert(contract, T::CrossAccountId::from_eth(owner));182 }183}184185pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);186impl<T: Config> SponsorshipHandler<T::CrossAccountId, (H160, Vec<u8>)>187 for HelpersContractSponsoring<T>188{189 fn get_sponsor(who: &T::CrossAccountId, call: &(H160, Vec<u8>)) -> Option<T::CrossAccountId> {190 let mode = <Pallet<T>>::sponsoring_mode(call.0);191 if mode == SponsoringModeT::Disabled {192 return None;193 }194195 if mode == SponsoringModeT::Allowlisted && !<Pallet<T>>::allowed(call.0, who.clone()) {196 return None;197 }198 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;199200 if let Some(last_tx_block) = <SponsorBasket<T>>::get(&call.0, who.as_eth()) {201 let limit = <SponsoringRateLimit<T>>::get(&call.0);202203 let timeout = last_tx_block + limit;204 if block_number < timeout {205 return None;206 }207 }208209 <SponsorBasket<T>>::insert(&call.0, who.as_eth(), block_number);210211 let sponsor = T::CrossAccountId::from_eth(call.0);212 Some(sponsor)213 }214}215216generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);217generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);pallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -15,6 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
#![cfg_attr(not(feature = "std"), no_std)]
+#![feature(is_some_with)]
use codec::{Decode, Encode, MaxEncodedLen};
pub use pallet::*;
@@ -25,9 +26,10 @@
#[frame_support::pallet]
pub mod pallet {
pub use super::*;
- use evm_coder::execution::Result;
use frame_support::pallet_prelude::*;
use sp_core::H160;
+ use pallet_evm::account::CrossAccountId;
+ use frame_system::pallet_prelude::BlockNumberFor;
#[pallet::config]
pub trait Config:
@@ -39,17 +41,31 @@
#[pallet::error]
pub enum Error<T> {
- /// This method is only executable by owner
+ /// This method is only executable by owner.
NoPermission,
+
+ /// Contract has no owner.
+ NoContractOwner,
}
+ const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
+
#[pallet::pallet]
+ #[pallet::storage_version(STORAGE_VERSION)]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
+ /// Store owner for contract.
+ ///
+ /// * **Key** - contract address.
+ /// * **Value** - owner for contract.
#[pallet::storage]
- pub(super) type Owner<T: Config> =
- StorageMap<Hasher = Twox128, Key = H160, Value = H160, QueryKind = ValueQuery>;
+ pub(super) type Owner<T: Config> = StorageMap<
+ Hasher = Twox128,
+ Key = H160,
+ Value = T::CrossAccountId,
+ QueryKind = OptionQuery,
+ >;
#[pallet::storage]
#[deprecated]
@@ -57,10 +73,12 @@
StorageMap<Hasher = Twox128, Key = H160, Value = bool, QueryKind = ValueQuery>;
#[pallet::storage]
+ #[deprecated]
pub(super) type SponsoringMode<T: Config> =
StorageMap<Hasher = Twox128, Key = H160, Value = SponsoringModeT, QueryKind = OptionQuery>;
#[pallet::storage]
+ #[deprecated]
pub(super) type SponsoringRateLimit<T: Config> = StorageMap<
Hasher = Twox128,
Key = H160,
@@ -70,6 +88,7 @@
>;
#[pallet::storage]
+ #[deprecated]
pub(super) type SponsorBasket<T: Config> = StorageDoubleMap<
Hasher1 = Twox128,
Key1 = H160,
@@ -80,10 +99,12 @@
>;
#[pallet::storage]
+ #[deprecated]
pub(super) type AllowlistEnabled<T: Config> =
StorageMap<Hasher = Twox128, Key = H160, Value = bool, QueryKind = ValueQuery>;
#[pallet::storage]
+ #[deprecated]
pub(super) type Allowlist<T: Config> = StorageDoubleMap<
Hasher1 = Twox128,
Key1 = H160,
@@ -93,6 +114,18 @@
QueryKind = ValueQuery,
>;
+ #[pallet::hooks]
+ impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
+ fn on_runtime_upgrade() -> Weight {
+ let storage_version = StorageVersion::get::<Pallet<T>>();
+ if storage_version < StorageVersion::new(1) {
+ <Owner<T>>::translate_values::<H160, _>(|address| Some(T::CrossAccountId::from_eth(address)));
+ }
+
+ 0
+ }
+ }
+
impl<T: Config> Pallet<T> {
pub fn sponsoring_mode(contract: H160) -> SponsoringModeT {
<SponsoringMode<T>>::get(contract)
@@ -125,8 +158,9 @@
<SponsoringRateLimit<T>>::insert(contract, rate_limit);
}
- pub fn allowed(contract: H160, user: H160) -> bool {
- <Allowlist<T>>::get(&contract, &user) || <Owner<T>>::get(&contract) == user
+ pub fn allowed(contract: H160, user: T::CrossAccountId) -> bool {
+ <Allowlist<T>>::get(&contract, user.as_eth())
+ || Pallet::<T>::contract_owner(contract).is_ok_and(|owner| *owner == user)
}
pub fn toggle_allowlist(contract: H160, enabled: bool) {
@@ -137,11 +171,17 @@
<Allowlist<T>>::insert(contract, user, allowed);
}
- pub fn ensure_owner(contract: H160, user: H160) -> Result<()> {
- ensure!(<Owner<T>>::get(&contract) == user, "no permission");
+ pub fn ensure_owner(contract: H160, user: H160) -> evm_coder::execution::Result<()> {
+ ensure!(Pallet::<T>::contract_owner(contract).is_ok_and(|owner| *owner.as_eth() == user), "no permission");
Ok(())
}
}
+
+ impl<T: Config> Pallet<T> {
+ pub fn contract_owner(contract: H160) -> Result<T::CrossAccountId, DispatchError> {
+ Ok(<Owner<T>>::get(contract).ok_or::<Error<T>>(Error::NoContractOwner)?)
+ }
+ }
}
#[derive(Encode, Decode, PartialEq, TypeInfo, MaxEncodedLen)]