Skip to main content

pallet_revive/evm/
runtime.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17//! Runtime types for integrating `pallet-revive` with the EVM.
18use crate::{
19	AccountIdOf, AddressMapper, BalanceOf, CallOf, Config, LOG_TARGET, Pallet, Zero,
20	evm::{
21		CreateCallMode,
22		api::{GenericTransaction, TransactionSigned},
23		fees::InfoT,
24	},
25};
26use codec::{Decode, DecodeWithMemTracking, Encode};
27use frame_support::{
28	dispatch::{DispatchInfo, GetDispatchInfo},
29	traits::{
30		InherentBuilder, IsSubType, SignedTransactionBuilder,
31		fungible::Balanced,
32		tokens::{Fortitude, Precision, Preservation},
33	},
34};
35use pallet_transaction_payment::Config as TxConfig;
36use scale_info::{StaticTypeInfo, TypeInfo};
37use sp_core::U256;
38use sp_runtime::{
39	Debug, OpaqueExtrinsic, Weight,
40	generic::{self, CheckedExtrinsic, ExtrinsicFormat},
41	traits::{
42		Checkable, ExtrinsicCall, ExtrinsicLike, ExtrinsicMetadata, LazyExtrinsic, Pipeline,
43		TransactionExtension,
44	},
45	transaction_validity::{InvalidTransaction, TransactionValidityError},
46};
47
48/// Used to set the weight limit argument of a `eth_call` or `eth_instantiate_with_code` call.
49pub trait SetWeightLimit {
50	/// Set the weight limit of this call.
51	///
52	/// Returns the replaced weight.
53	fn set_weight_limit(&mut self, weight_limit: Weight) -> Weight;
54}
55
56/// Wraps [`generic::UncheckedExtrinsic`] to support checking unsigned
57/// [`crate::Call::eth_transact`] extrinsic.
58#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug)]
59pub struct UncheckedExtrinsic<Address, Signature, E: EthExtra>(
60	pub  generic::UncheckedExtrinsic<
61		Address,
62		CallOf<E::Config>,
63		Signature,
64		E::ExtensionV0,
65		E::ExtensionOtherVersions,
66	>,
67);
68
69impl<Address, Signature, E: EthExtra> TypeInfo for UncheckedExtrinsic<Address, Signature, E>
70where
71	Address: StaticTypeInfo,
72	Signature: StaticTypeInfo,
73	E::ExtensionV0: StaticTypeInfo,
74{
75	type Identity = generic::UncheckedExtrinsic<
76		Address,
77		CallOf<E::Config>,
78		Signature,
79		E::ExtensionV0,
80		E::ExtensionOtherVersions,
81	>;
82	fn type_info() -> scale_info::Type {
83		generic::UncheckedExtrinsic::<
84			Address,
85			CallOf<E::Config>,
86			Signature,
87			E::ExtensionV0,
88			E::ExtensionOtherVersions,
89		>::type_info()
90	}
91}
92
93impl<Address, Signature, E: EthExtra>
94	From<
95		generic::UncheckedExtrinsic<
96			Address,
97			CallOf<E::Config>,
98			Signature,
99			E::ExtensionV0,
100			E::ExtensionOtherVersions,
101		>,
102	> for UncheckedExtrinsic<Address, Signature, E>
103{
104	fn from(
105		utx: generic::UncheckedExtrinsic<
106			Address,
107			CallOf<E::Config>,
108			Signature,
109			E::ExtensionV0,
110			E::ExtensionOtherVersions,
111		>,
112	) -> Self {
113		Self(utx)
114	}
115}
116
117impl<Address: TypeInfo, Signature: TypeInfo, E: EthExtra> ExtrinsicLike
118	for UncheckedExtrinsic<Address, Signature, E>
119{
120	fn is_bare(&self) -> bool {
121		ExtrinsicLike::is_bare(&self.0)
122	}
123}
124
125impl<Address, Signature, E: EthExtra> ExtrinsicMetadata
126	for UncheckedExtrinsic<Address, Signature, E>
127{
128	const VERSIONS: &'static [u8] = generic::UncheckedExtrinsic::<
129		Address,
130		CallOf<E::Config>,
131		Signature,
132		E::ExtensionV0,
133		E::ExtensionOtherVersions,
134	>::VERSIONS;
135	type TransactionExtensionPipelines = <generic::UncheckedExtrinsic<
136		Address,
137		CallOf<E::Config>,
138		Signature,
139		E::ExtensionV0,
140		E::ExtensionOtherVersions,
141	> as ExtrinsicMetadata>::TransactionExtensionPipelines;
142}
143
144impl<Address: TypeInfo, Signature: TypeInfo, E: EthExtra> ExtrinsicCall
145	for UncheckedExtrinsic<Address, Signature, E>
146{
147	type Call = CallOf<E::Config>;
148
149	fn call(&self) -> &Self::Call {
150		self.0.call()
151	}
152
153	fn into_call(self) -> Self::Call {
154		self.0.into_call()
155	}
156}
157
158impl<LookupSource, Signature, E, Lookup> Checkable<Lookup>
159	for UncheckedExtrinsic<LookupSource, Signature, E>
160where
161	E: EthExtra,
162	Self: Encode,
163	<E::Config as frame_system::Config>::Nonce: TryFrom<U256>,
164	CallOf<E::Config>: SetWeightLimit,
165	// required by Checkable for `generic::UncheckedExtrinsic`
166	generic::UncheckedExtrinsic<
167		LookupSource,
168		CallOf<E::Config>,
169		Signature,
170		E::ExtensionV0,
171		E::ExtensionOtherVersions,
172	>: Checkable<
173			Lookup,
174			Checked = CheckedExtrinsic<
175				AccountIdOf<E::Config>,
176				CallOf<E::Config>,
177				E::ExtensionV0,
178				E::ExtensionOtherVersions,
179			>,
180		>,
181{
182	type Checked = CheckedExtrinsic<
183		AccountIdOf<E::Config>,
184		CallOf<E::Config>,
185		E::ExtensionV0,
186		E::ExtensionOtherVersions,
187	>;
188
189	fn check(self, lookup: &Lookup) -> Result<Self::Checked, TransactionValidityError> {
190		if !self.0.is_signed() {
191			if let Some(crate::Call::eth_transact { payload }) = self.0.function.is_sub_type() {
192				log::trace!(
193					target: LOG_TARGET,
194					"eth_transact substrate tx hash: 0x{}",
195					sp_core::hexdisplay::HexDisplay::from(&sp_crypto_hashing::blake2_256(&self.encode())),
196				);
197				let checked = E::try_into_checked_extrinsic(payload, self.encoded_size())?;
198				return Ok(checked);
199			};
200		}
201		self.0.check(lookup)
202	}
203
204	#[cfg(feature = "try-runtime")]
205	fn unchecked_into_checked_i_know_what_i_am_doing(
206		self,
207		lookup: &Lookup,
208	) -> Result<Self::Checked, TransactionValidityError> {
209		self.0.unchecked_into_checked_i_know_what_i_am_doing(lookup)
210	}
211}
212
213impl<Address, Signature, E: EthExtra> GetDispatchInfo
214	for UncheckedExtrinsic<Address, Signature, E>
215{
216	fn get_dispatch_info(&self) -> DispatchInfo {
217		self.0.get_dispatch_info()
218	}
219}
220
221impl<Address: Encode, Signature: Encode, E: EthExtra> serde::Serialize
222	for UncheckedExtrinsic<Address, Signature, E>
223{
224	fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error>
225	where
226		S: ::serde::Serializer,
227	{
228		self.0.serialize(seq)
229	}
230}
231
232impl<'a, Address: DecodeWithMemTracking, Signature: DecodeWithMemTracking, E: EthExtra>
233	serde::Deserialize<'a> for UncheckedExtrinsic<Address, Signature, E>
234{
235	fn deserialize<D>(de: D) -> Result<Self, D::Error>
236	where
237		D: serde::Deserializer<'a>,
238	{
239		let r = sp_core::bytes::deserialize(de)?;
240		Decode::decode(&mut &r[..])
241			.map_err(|e| serde::de::Error::custom(alloc::format!("Decode error: {}", e)))
242	}
243}
244
245impl<Address, Signature, E: EthExtra> SignedTransactionBuilder
246	for UncheckedExtrinsic<Address, Signature, E>
247where
248	Address: TypeInfo,
249	Signature: TypeInfo,
250	E::ExtensionV0: TypeInfo,
251{
252	type Address = Address;
253	type Signature = Signature;
254	type Extension = E::ExtensionV0;
255
256	fn new_signed_transaction(
257		call: Self::Call,
258		signed: Address,
259		signature: Signature,
260		tx_ext: E::ExtensionV0,
261	) -> Self {
262		generic::UncheckedExtrinsic::new_signed(call, signed, signature, tx_ext).into()
263	}
264}
265
266impl<Address, Signature, E: EthExtra> InherentBuilder for UncheckedExtrinsic<Address, Signature, E>
267where
268	Address: TypeInfo,
269	Signature: TypeInfo,
270	E::ExtensionV0: TypeInfo,
271{
272	fn new_inherent(call: Self::Call) -> Self {
273		generic::UncheckedExtrinsic::new_bare(call).into()
274	}
275}
276
277impl<Address, Signature, E: EthExtra> From<UncheckedExtrinsic<Address, Signature, E>>
278	for OpaqueExtrinsic
279where
280	Address: Encode,
281	Signature: Encode,
282	E::ExtensionV0: Encode,
283{
284	fn from(extrinsic: UncheckedExtrinsic<Address, Signature, E>) -> Self {
285		extrinsic.0.into()
286	}
287}
288
289impl<Address, Signature, E: EthExtra> LazyExtrinsic for UncheckedExtrinsic<Address, Signature, E>
290where
291	generic::UncheckedExtrinsic<
292		Address,
293		CallOf<E::Config>,
294		Signature,
295		E::ExtensionV0,
296		E::ExtensionOtherVersions,
297	>: LazyExtrinsic,
298{
299	fn decode_unprefixed(data: &[u8]) -> Result<Self, codec::Error> {
300		Ok(Self(LazyExtrinsic::decode_unprefixed(data)?))
301	}
302}
303
304/// EthExtra convert an unsigned [`crate::Call::eth_transact`] into a [`CheckedExtrinsic`].
305pub trait EthExtra {
306	/// The Runtime configuration.
307	type Config: Config + TxConfig;
308
309	/// The Runtime's transaction extension version 0.
310	/// It should include at least:
311	/// - [`frame_system::CheckNonce`] to ensure that the nonce from the Ethereum transaction is
312	///   correct.
313	type ExtensionV0: TransactionExtension<CallOf<Self::Config>>;
314
315	/// The Runtime's transaction extension versions other than 0.
316	///
317	/// Use [`sp_runtime::traits::InvalidVersion`] if no other versions should be supported.
318	type ExtensionOtherVersions: Pipeline<CallOf<Self::Config>>;
319
320	/// Get the transaction extension to apply to an unsigned [`crate::Call::eth_transact`]
321	/// extrinsic.
322	///
323	/// # Parameters
324	/// - `nonce`: The nonce extracted from the Ethereum transaction.
325	/// - `tip`: The transaction tip calculated from the Ethereum transaction.
326	fn get_eth_extension(
327		nonce: <Self::Config as frame_system::Config>::Nonce,
328		tip: BalanceOf<Self::Config>,
329	) -> Self::ExtensionV0;
330
331	/// Convert the unsigned [`crate::Call::eth_transact`] into a [`CheckedExtrinsic`].
332	/// and ensure that the fees from the Ethereum transaction correspond to the fees computed from
333	/// the encoded_len and the injected weight_limit.
334	///
335	/// A payload larger than [`crate::limits::MAX_TRANSACTION_PAYLOAD_SIZE`] is rejected with
336	/// [`InvalidTransaction::ExhaustsResources`], as is a dry run of such a transaction.
337	///
338	/// # Parameters
339	/// - `payload`: The RLP-encoded Ethereum transaction.
340	/// - `encoded_len`: The encoded length of the extrinsic.
341	fn try_into_checked_extrinsic(
342		payload: &[u8],
343		encoded_len: usize,
344	) -> Result<
345		CheckedExtrinsic<
346			AccountIdOf<Self::Config>,
347			CallOf<Self::Config>,
348			Self::ExtensionV0,
349			Self::ExtensionOtherVersions,
350		>,
351		InvalidTransaction,
352	>
353	where
354		<Self::Config as frame_system::Config>::Nonce: TryFrom<U256>,
355		CallOf<Self::Config>: SetWeightLimit,
356	{
357		crate::evm::ensure_transaction_payload_size(payload)?;
358
359		let tx = TransactionSigned::decode(&payload).map_err(|err| {
360			log::debug!(target: LOG_TARGET, "Failed to decode transaction: {err:?}");
361			InvalidTransaction::Call
362		})?;
363
364		// Check transaction type and reject unsupported transaction types
365		match &tx {
366			crate::evm::api::TransactionSigned::Transaction1559Signed(_) |
367			crate::evm::api::TransactionSigned::Transaction2930Signed(_) |
368			crate::evm::api::TransactionSigned::TransactionLegacySigned(_) => {
369				// Supported transaction types, continue processing
370			},
371			crate::evm::api::TransactionSigned::Transaction7702Signed(_) => {
372				log::debug!(target: LOG_TARGET, "EIP-7702 transactions are not supported");
373				return Err(InvalidTransaction::Call);
374			},
375			crate::evm::api::TransactionSigned::Transaction4844Signed(_) => {
376				log::debug!(target: LOG_TARGET, "EIP-4844 transactions are not supported");
377				return Err(InvalidTransaction::Call);
378			},
379		}
380
381		let signer_addr = tx.recover_eth_address().map_err(|err| {
382			log::debug!(target: LOG_TARGET, "Failed to recover signer: {err:?}");
383			InvalidTransaction::BadProof
384		})?;
385
386		let signer = <Self::Config as Config>::AddressMapper::to_fallback_account_id(&signer_addr);
387		let base_fee = <Pallet<Self::Config>>::evm_base_fee();
388		let tx = GenericTransaction::from_signed(tx, base_fee, None);
389		let nonce = tx.nonce.unwrap_or_default().try_into().map_err(|_| {
390			log::debug!(target: LOG_TARGET, "Failed to convert nonce");
391			InvalidTransaction::Call
392		})?;
393
394		log::debug!(target: LOG_TARGET, "Decoded Ethereum transaction with signer: {signer_addr:?} nonce: {nonce:?}");
395		log::trace!(target: LOG_TARGET, "Decoded Ethereum transaction was: {tx:?}");
396		let call_info = tx.into_call::<Self::Config>(CreateCallMode::ExtrinsicExecution(
397			encoded_len as u32,
398			payload.to_vec(),
399		))?;
400		let storage_credit = <Self::Config as Config>::Currency::withdraw(
401			&signer,
402			call_info.storage_deposit,
403			Precision::Exact,
404			Preservation::Preserve,
405			Fortitude::Polite,
406		).map_err(|_| {
407			log::debug!(target: LOG_TARGET, "Not enough balance to hold additional storage deposit of {:?}", call_info.storage_deposit);
408			InvalidTransaction::Payment
409		})?;
410		<Self::Config as Config>::FeeInfo::deposit_txfee(storage_credit);
411
412		crate::tracing::if_tracing(|tracer| {
413			tracer.watch_address(&Pallet::<Self::Config>::block_author());
414			tracer.watch_address(&signer_addr);
415		});
416
417		log::debug!(target: LOG_TARGET, "\
418			Created checked Ethereum transaction with: \
419			from={signer_addr:?} \
420			eth_gas={} \
421			encoded_len={encoded_len} \
422			tx_fee={:?} \
423			storage_deposit={:?} \
424			weight_limit={} \
425			nonce={nonce:?}\
426			",
427			call_info.eth_gas_limit,
428			call_info.tx_fee,
429			call_info.storage_deposit,
430			call_info.weight_limit,
431		);
432
433		// We can't calculate a tip because it needs to be based on the actual gas used which we
434		// cannot know pre-dispatch. Hence we never supply a tip here or it would be way too high.
435		Ok(CheckedExtrinsic {
436			format: ExtrinsicFormat::Signed(
437				signer.into(),
438				Self::get_eth_extension(nonce, Zero::zero()),
439			),
440			function: call_info.call,
441		})
442	}
443}
444
445#[cfg(test)]
446mod test {
447	use super::*;
448	use crate::{
449		EthTransactInfo, RUNTIME_PALLETS_ADDR, Weight,
450		evm::*,
451		test_utils::*,
452		tests::{
453			Address, ExtBuilder, RuntimeCall, RuntimeOrigin, SignedExtra, Test, UncheckedExtrinsic,
454		},
455	};
456	use frame_support::traits::fungible::Mutate;
457	use pallet_revive_fixtures::compile_module;
458	use sp_runtime::traits::{self, Checkable, DispatchTransaction, LookupError};
459
460	type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
461
462	struct TestContext;
463
464	impl traits::Lookup for TestContext {
465		type Source = Address;
466		type Target = AccountIdOf<Test>;
467		fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError> {
468			match s {
469				Self::Source::Id(id) => Ok(id),
470				_ => Err(LookupError),
471			}
472		}
473	}
474
475	/// A builder for creating an unchecked extrinsic, and test that the check function works.
476	#[derive(Clone)]
477	struct UncheckedExtrinsicBuilder {
478		tx: GenericTransaction,
479		before_validate: Option<std::sync::Arc<dyn Fn() + Send + Sync>>,
480		dry_run: Option<EthTransactInfo<BalanceOf<Test>>>,
481	}
482
483	impl UncheckedExtrinsicBuilder {
484		/// Create a new builder with default values.
485		fn new() -> Self {
486			Self {
487				tx: GenericTransaction {
488					from: Some(Account::default().address()),
489					chain_id: Some(<Test as Config>::ChainId::get().into()),
490					..Default::default()
491				},
492				before_validate: None,
493				dry_run: None,
494			}
495		}
496
497		fn data(mut self, data: Vec<u8>) -> Self {
498			self.tx.input = Bytes(data).into();
499			self
500		}
501
502		fn fund_account(account: &Account) {
503			let _ = <Test as Config>::Currency::set_balance(
504				&account.substrate_account(),
505				100_000_000_000_000,
506			);
507		}
508
509		fn estimate_gas(&mut self) {
510			let account = Account::default();
511			Self::fund_account(&account);
512
513			let dry_run =
514				crate::Pallet::<Test>::dry_run_eth_transact(self.tx.clone(), None, true, None);
515			self.tx.gas_price = Some(<Pallet<Test>>::evm_base_fee());
516
517			match dry_run {
518				Ok(dry_run) => {
519					self.tx.gas = Some(dry_run.eth_gas);
520					self.dry_run = Some(dry_run);
521				},
522				Err(err) => {
523					log::debug!(target: LOG_TARGET, "Failed to estimate gas: {:?}", err);
524				},
525			}
526		}
527
528		/// Create a new builder with a call to the given address.
529		fn call_with(dest: H160) -> Self {
530			let mut builder = Self::new();
531			builder.tx.to = Some(dest);
532			builder
533		}
534
535		/// Create a new builder with an instantiate call.
536		fn instantiate_with(code: Vec<u8>, data: Vec<u8>) -> Self {
537			let mut builder = Self::new();
538			builder.tx.input = Bytes(code.into_iter().chain(data.into_iter()).collect()).into();
539			builder
540		}
541
542		/// Set before_validate function.
543		fn before_validate(mut self, f: impl Fn() + Send + Sync + 'static) -> Self {
544			self.before_validate = Some(std::sync::Arc::new(f));
545			self
546		}
547
548		fn check(
549			self,
550		) -> Result<
551			(u32, RuntimeCall, SignedExtra, GenericTransaction, Weight, TransactionSigned),
552			TransactionValidityError,
553		> {
554			self.mutate_estimate_and_check(Box::new(|_| ()))
555		}
556
557		/// Call `check` on the unchecked extrinsic, and `pre_dispatch` on the signed extension.
558		fn mutate_estimate_and_check(
559			mut self,
560			f: Box<dyn FnOnce(&mut GenericTransaction) -> ()>,
561		) -> Result<
562			(u32, RuntimeCall, SignedExtra, GenericTransaction, Weight, TransactionSigned),
563			TransactionValidityError,
564		> {
565			ExtBuilder::default().build().execute_with(|| self.estimate_gas());
566			ExtBuilder::default().build().execute_with(|| {
567				f(&mut self.tx);
568				let UncheckedExtrinsicBuilder { tx, before_validate, .. } = self.clone();
569
570				// Fund the account.
571				let account = Account::default();
572				Self::fund_account(&account);
573
574				let signed_transaction =
575					account.sign_transaction(tx.clone().try_into_unsigned().unwrap());
576				let call = RuntimeCall::Contracts(crate::Call::eth_transact {
577					payload: signed_transaction.signed_payload().clone(),
578				});
579
580				let uxt: UncheckedExtrinsic = generic::UncheckedExtrinsic::new_bare(call).into();
581				let encoded_len = uxt.encoded_size();
582				let result: CheckedExtrinsic<_, _, _> = uxt.check(&TestContext {})?;
583				let (account_id, extra): (AccountId32, SignedExtra) = match result.format {
584					ExtrinsicFormat::Signed(signer, extra) => (signer, extra),
585					_ => unreachable!(),
586				};
587
588				before_validate.map(|f| f());
589				extra.clone().validate_and_prepare(
590					RuntimeOrigin::signed(account_id),
591					&result.function,
592					&result.function.get_dispatch_info(),
593					encoded_len,
594					0,
595				)?;
596
597				Ok((
598					encoded_len as u32,
599					result.function,
600					extra,
601					tx,
602					self.dry_run.unwrap().weight_required,
603					signed_transaction,
604				))
605			})
606		}
607	}
608
609	#[test]
610	fn check_eth_transact_call_works() {
611		let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]));
612		let (expected_encoded_len, call, _, tx, weight_required, signed_transaction) =
613			builder.check().unwrap();
614		let expected_effective_gas_price =
615			ExtBuilder::default().build().execute_with(|| Pallet::<Test>::evm_base_fee());
616
617		match call {
618			RuntimeCall::Contracts(crate::Call::eth_call::<Test> {
619				dest,
620				value,
621				weight_limit,
622				data,
623				transaction_encoded,
624				effective_gas_price,
625				encoded_len,
626				..
627			}) if dest == tx.to.unwrap() &&
628				value == tx.value.unwrap_or_default().as_u64().into() &&
629				data == tx.input.to_vec() &&
630				transaction_encoded == signed_transaction.signed_payload() &&
631				effective_gas_price == expected_effective_gas_price =>
632			{
633				assert_eq!(encoded_len, expected_encoded_len);
634				assert!(
635					weight_limit.all_gte(weight_required),
636					"Assert failed: weight_limit={weight_limit:?} >= weight_required={weight_required:?}"
637				);
638			},
639			_ => panic!("Call does not match."),
640		}
641	}
642
643	#[test]
644	fn check_eth_transact_instantiate_works() {
645		let (expected_code, _) = compile_module("dummy").unwrap();
646		let expected_data = vec![];
647		let builder = UncheckedExtrinsicBuilder::instantiate_with(
648			expected_code.clone(),
649			expected_data.clone(),
650		);
651		let (expected_encoded_len, call, _, tx, weight_required, signed_transaction) =
652			builder.check().unwrap();
653		let expected_effective_gas_price =
654			ExtBuilder::default().build().execute_with(|| Pallet::<Test>::evm_base_fee());
655		let expected_value = tx.value.unwrap_or_default().as_u64().into();
656
657		match call {
658			RuntimeCall::Contracts(crate::Call::eth_instantiate_with_code::<Test> {
659				value,
660				weight_limit,
661				code,
662				data,
663				transaction_encoded,
664				effective_gas_price,
665				encoded_len,
666				..
667			}) if value == expected_value &&
668				code == expected_code &&
669				data == expected_data &&
670				transaction_encoded == signed_transaction.signed_payload() &&
671				effective_gas_price == expected_effective_gas_price =>
672			{
673				assert_eq!(encoded_len, expected_encoded_len);
674				assert!(
675					weight_limit.all_gte(weight_required),
676					"Assert failed: weight_limit={weight_limit:?} >= weight_required={weight_required:?}"
677				);
678			},
679			_ => panic!("Call does not match."),
680		}
681	}
682
683	#[test]
684	fn check_eth_transact_nonce_works() {
685		let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]));
686
687		assert_eq!(
688			builder.mutate_estimate_and_check(Box::new(|tx| tx.nonce = Some(1u32.into()))),
689			Err(TransactionValidityError::Invalid(InvalidTransaction::Future))
690		);
691
692		let builder =
693			UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])).before_validate(|| {
694				<crate::System<Test>>::inc_account_nonce(Account::default().substrate_account());
695			});
696
697		assert_eq!(
698			builder.check(),
699			Err(TransactionValidityError::Invalid(InvalidTransaction::Stale))
700		);
701	}
702
703	#[test]
704	fn check_eth_transact_chain_id_works() {
705		let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]));
706
707		assert_eq!(
708			builder.mutate_estimate_and_check(Box::new(|tx| tx.chain_id = Some(42.into()))),
709			Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
710		);
711	}
712
713	#[test]
714	fn check_instantiate_data() {
715		let code: Vec<u8> = polkavm_common::program::BLOB_MAGIC
716			.into_iter()
717			.chain(b"invalid code".iter().cloned())
718			.collect();
719		let data = vec![1];
720
721		let builder = UncheckedExtrinsicBuilder::instantiate_with(code.clone(), data.clone());
722
723		// Fail because the tx input fail to get the blob length
724		assert_eq!(
725			builder.check(),
726			Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
727		);
728	}
729
730	/// An `eth_transact` whose payload is larger than `MAX_TRANSACTION_PAYLOAD_SIZE` is invalid
731	/// before its payload is decoded. A payload at the limit passes the size check and is decoded.
732	#[test]
733	fn check_eth_transact_payload_size() {
734		let check = |len: u32| {
735			ExtBuilder::default().build().execute_with(|| {
736				let call = RuntimeCall::Contracts(crate::Call::eth_transact {
737					payload: vec![0u8; len as usize],
738				});
739				let uxt: UncheckedExtrinsic = generic::UncheckedExtrinsic::new_bare(call).into();
740				uxt.check(&TestContext {}).map(|_| ())
741			})
742		};
743		let limit = crate::limits::MAX_TRANSACTION_PAYLOAD_SIZE;
744
745		assert_eq!(
746			check(limit + 1),
747			Err(TransactionValidityError::Invalid(InvalidTransaction::ExhaustsResources))
748		);
749		assert_eq!(check(limit), Err(TransactionValidityError::Invalid(InvalidTransaction::Call)));
750	}
751
752	/// A dry run of a transaction whose payload is larger than `MAX_TRANSACTION_PAYLOAD_SIZE`
753	/// fails with the error its submission is rejected with.
754	#[test]
755	fn dry_run_eth_transact_payload_size() {
756		ExtBuilder::default().build().execute_with(|| {
757			let exhausts_resources = |input_len: u32| {
758				let result = crate::Pallet::<Test>::dry_run_eth_transact(
759					GenericTransaction {
760						from: Some(ALICE_ADDR),
761						to: Some(BOB_ADDR),
762						input: vec![0u8; input_len as usize].into(),
763						..Default::default()
764					},
765					None,
766					false,
767					None,
768				);
769				matches!(
770					result,
771					Err(crate::EthTransactError::Message(msg)) if msg.contains("ExhaustsResources")
772				)
773			};
774			let limit = crate::limits::MAX_TRANSACTION_PAYLOAD_SIZE;
775
776			assert!(exhausts_resources(limit));
777			assert!(!exhausts_resources(limit - 1024));
778		});
779	}
780
781	#[test]
782	fn check_transaction_fees() {
783		let scenarios: Vec<(_, Box<dyn FnOnce(&mut GenericTransaction)>, _)> = vec![
784			(
785				"Eth fees too low",
786				Box::new(|tx| {
787					tx.gas_price = Some(100u64.into());
788				}),
789				InvalidTransaction::Payment,
790			),
791			(
792				"Gas fees too low",
793				Box::new(|tx| {
794					tx.gas = Some(tx.gas.unwrap() / 2);
795				}),
796				InvalidTransaction::Payment,
797			),
798		];
799
800		for (msg, update_tx, err) in scenarios {
801			let res = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]))
802				.mutate_estimate_and_check(update_tx);
803
804			assert_eq!(res, Err(TransactionValidityError::Invalid(err)), "{}", msg);
805		}
806	}
807
808	#[test]
809	fn eth_pre_dispatch_weight_matches_check_weight_booking() {
810		let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]));
811		let (encoded_len, call, _, _, _, signed_transaction) = builder.check().unwrap();
812
813		ExtBuilder::default().build().execute_with(|| {
814			let reported =
815				Pallet::<Test>::eth_pre_dispatch_weight(signed_transaction.signed_payload())
816					.unwrap();
817			let info = <Test as Config>::FeeInfo::dispatch_info(&call);
818			let expected = frame_system::calculate_consumed_extrinsic_weight::<CallOf<Test>>(
819				&<Test as frame_system::Config>::BlockWeights::get(),
820				&info,
821				encoded_len as usize,
822			);
823
824			assert_eq!(reported, expected);
825		});
826	}
827
828	#[test]
829	fn check_transaction_tip() {
830		let (code, _) = compile_module("dummy").unwrap();
831		// create some dummy data to increase the gas fee
832		let data = vec![42u8; crate::limits::CALLDATA_BYTES as usize];
833		let (_, _, extra, _tx, _gas_required, _) =
834			UncheckedExtrinsicBuilder::instantiate_with(code.clone(), data.clone())
835				.mutate_estimate_and_check(Box::new(|tx| {
836					tx.gas_price = Some(tx.gas_price.unwrap() * 103 / 100);
837					log::debug!(target: LOG_TARGET, "Gas price: {:?}", tx.gas_price);
838				}))
839				.unwrap();
840
841		assert_eq!(U256::from(extra.1.tip()), 0u32.into());
842	}
843
844	#[test]
845	fn check_runtime_pallets_addr_works() {
846		let remark: CallOf<Test> =
847			frame_system::Call::remark { remark: b"Hello, world!".to_vec() }.into();
848
849		let builder =
850			UncheckedExtrinsicBuilder::call_with(RUNTIME_PALLETS_ADDR).data(remark.encode());
851		let (_, call, _, _, _, _) = builder.check().unwrap();
852
853		match call {
854			RuntimeCall::Contracts(crate::Call::eth_substrate_call {
855				call: inner_call, ..
856			}) => {
857				assert_eq!(*inner_call, remark);
858			},
859			_ => panic!("Expected the RuntimeCall::Contracts variant, got: {:?}", call),
860		}
861	}
862
863	/// The raw bytes seen in this test is of a deployment transaction from [eip-2470] which publish
864	/// a contract at a predicable address on any chain that it's run on. We use these bytes to test
865	/// that if we were to run this transaction on pallet-revive that it would run and also produce
866	/// a contract at the address described in the EIP.
867	///
868	/// Note: the linked EIP is not an EIP for Nick's method, it's just an EIP that makes use of
869	/// Nick's method.
870	///
871	/// [eip-2470]: https://eips.ethereum.org/EIPS/eip-2470
872	#[test]
873	fn contract_deployment_with_nick_method_works() {
874		// Arrange
875		let raw_transaction_bytes = alloy_core::hex!(
876			"0xf9016c8085174876e8008303c4d88080b90154608060405234801561001057600080fd5b50610134806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80634af63f0214602d575b600080fd5b60cf60048036036040811015604157600080fd5b810190602081018135640100000000811115605b57600080fd5b820183602082011115606c57600080fd5b80359060200191846001830284011164010000000083111715608d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550509135925060eb915050565b604080516001600160a01b039092168252519081900360200190f35b6000818351602085016000f5939250505056fea26469706673582212206b44f8a82cb6b156bfcc3dc6aadd6df4eefd204bc928a4397fd15dacf6d5320564736f6c634300060200331b83247000822470"
877		);
878
879		let mut signed_transaction = TransactionSigned::decode(raw_transaction_bytes.as_slice())
880			.expect("Invalid raw transaction bytes");
881		if let TransactionSigned::TransactionLegacySigned(ref mut legacy_transaction) =
882			signed_transaction
883		{
884			legacy_transaction.transaction_legacy_unsigned.gas =
885				U256::from_dec_str("3750815700000").unwrap();
886		}
887		let generic_transaction = GenericTransaction::from_signed(
888			signed_transaction.clone(),
889			ExtBuilder::default().build().execute_with(|| Pallet::<Test>::evm_base_fee()),
890			None,
891		);
892
893		let unchecked_extrinsic_builder = UncheckedExtrinsicBuilder {
894			tx: generic_transaction,
895			before_validate: None,
896			dry_run: None,
897		};
898
899		// Act
900		let eth_transact_result = unchecked_extrinsic_builder.check();
901
902		// Assert
903		let (
904			_encoded_len,
905			_function,
906			_extra,
907			generic_transaction,
908			_gas_required,
909			_signed_transaction,
910		) = eth_transact_result.expect("eth_transact failed");
911		assert!(
912			generic_transaction.chain_id.is_none(),
913			"Chain Id in the generic transaction is not None"
914		);
915	}
916}