1234567891011121314151617#![doc = include_str!("../README.md")]18#![cfg_attr(not(feature = "std"), no_std)]19#![deny(missing_docs)]2021use core::marker::PhantomData;2223use fp_evm::{CheckEvmTransaction, FeeCalculator, TransactionValidationError, WithdrawReason};24use frame_support::{25 storage::with_transaction,26 traits::{Currency, Imbalance, IsSubType, OnUnbalanced},27};28pub use pallet::*;29use pallet_evm::{30 account::CrossAccountId, EnsureAddressOrigin, NegativeImbalanceOf, OnChargeEVMTransaction,31 OnCheckEvmTransaction,32};33use sp_core::{H160, U256};34use sp_runtime::{traits::UniqueSaturatedInto, DispatchError, TransactionOutcome};35use up_sponsorship::SponsorshipHandler;3637#[frame_support::pallet]38pub mod pallet {39 use sp_std::vec::Vec;4041 use super::*;4243 44 pub struct CallContext {45 46 pub contract_address: H160,47 48 pub input: Vec<u8>,49 50 pub max_fee: U256,51 }5253 #[pallet::config]54 pub trait Config: frame_system::Config + pallet_evm::Config {55 56 type EvmSponsorshipHandler: SponsorshipHandler<Self::CrossAccountId, CallContext>;57 }5859 #[pallet::pallet]60 pub struct Pallet<T>(_);61}626364pub struct TransactionValidityHack<T: Config>(PhantomData<*const T>);65impl<T: Config> fp_evm::TransactionValidityHack<T::CrossAccountId> for TransactionValidityHack<T> {66 fn who_pays_fee(67 origin: H160,68 max_fee: U256,69 reason: &WithdrawReason,70 ) -> Option<T::CrossAccountId> {71 match reason {72 WithdrawReason::Call { target, input } => {73 let origin_sub = T::CrossAccountId::from_eth(origin);74 let call_context = CallContext {75 contract_address: *target,76 input: input.clone(),77 max_fee,78 };79 T::EvmSponsorshipHandler::get_sponsor(&origin_sub, &call_context)80 }81 _ => None,82 }83 }84}858687pub struct BridgeSponsorshipHandler<T>(PhantomData<T>);88impl<T, C> SponsorshipHandler<T::AccountId, C> for BridgeSponsorshipHandler<T>89where90 T: Config + pallet_evm::Config,91 C: IsSubType<pallet_evm::Call<T>>,92{93 fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {94 match call.is_sub_type()? {95 pallet_evm::Call::call {96 source,97 target,98 input,99 gas_limit,100 max_fee_per_gas,101 ..102 } => {103 let _ = T::CallOrigin::ensure_address_origin(104 source,105 <frame_system::RawOrigin<T::AccountId>>::Signed(who.clone()).into(),106 )107 .ok()?;108 let who = T::CrossAccountId::from_sub(who.clone());109 let max_fee = max_fee_per_gas.saturating_mul((*gas_limit).into());110 let call_context = CallContext {111 contract_address: *target,112 input: input.clone(),113 max_fee,114 };115 116 117 let sponsor = frame_support::storage::with_transaction(|| {118 TransactionOutcome::Rollback(Ok::<_, DispatchError>(119 T::EvmSponsorshipHandler::get_sponsor(&who, &call_context),120 ))121 })122 123 .ok()??;124 Some(sponsor.as_sub().clone())125 }126 _ => None,127 }128 }129}