1use 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
48pub trait SetWeightLimit {
50 fn set_weight_limit(&mut self, weight_limit: Weight) -> Weight;
54}
55
56#[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 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
304pub trait EthExtra {
306 type Config: Config + TxConfig;
308
309 type ExtensionV0: TransactionExtension<CallOf<Self::Config>>;
314
315 type ExtensionOtherVersions: Pipeline<CallOf<Self::Config>>;
319
320 fn get_eth_extension(
327 nonce: <Self::Config as frame_system::Config>::Nonce,
328 tip: BalanceOf<Self::Config>,
329 ) -> Self::ExtensionV0;
330
331 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 match &tx {
366 crate::evm::api::TransactionSigned::Transaction1559Signed(_) |
367 crate::evm::api::TransactionSigned::Transaction2930Signed(_) |
368 crate::evm::api::TransactionSigned::TransactionLegacySigned(_) |
369 crate::evm::api::TransactionSigned::Transaction7702Signed(_) => {
370 },
372 crate::evm::api::TransactionSigned::Transaction4844Signed(_) => {
373 log::debug!(target: LOG_TARGET, "EIP-4844 transactions are not supported");
374 return Err(InvalidTransaction::Call);
375 },
376 }
377
378 let signer_addr = tx.recover_eth_address().map_err(|err| {
379 log::debug!(target: LOG_TARGET, "Failed to recover signer: {err:?}");
380 InvalidTransaction::BadProof
381 })?;
382
383 let signer = <Self::Config as Config>::AddressMapper::to_fallback_account_id(&signer_addr);
384 let base_fee = <Pallet<Self::Config>>::evm_base_fee();
385 let tx = GenericTransaction::from_signed(tx, base_fee, None);
386 let nonce = tx.nonce.unwrap_or_default().try_into().map_err(|_| {
387 log::debug!(target: LOG_TARGET, "Failed to convert nonce");
388 InvalidTransaction::Call
389 })?;
390
391 log::debug!(target: LOG_TARGET, "Decoded Ethereum transaction with signer: {signer_addr:?} nonce: {nonce:?}");
392 log::trace!(target: LOG_TARGET, "Decoded Ethereum transaction was: {tx:?}");
393 let call_info = tx.into_call::<Self::Config>(CreateCallMode::ExtrinsicExecution(
394 encoded_len as u32,
395 payload.to_vec(),
396 ))?;
397 let storage_credit = <Self::Config as Config>::Currency::withdraw(
398 &signer,
399 call_info.storage_deposit,
400 Precision::Exact,
401 Preservation::Preserve,
402 Fortitude::Polite,
403 ).map_err(|_| {
404 log::debug!(target: LOG_TARGET, "Not enough balance to hold additional storage deposit of {:?}", call_info.storage_deposit);
405 InvalidTransaction::Payment
406 })?;
407 <Self::Config as Config>::FeeInfo::deposit_txfee(storage_credit);
408
409 crate::tracing::if_tracing(|tracer| {
410 tracer.watch_address(&Pallet::<Self::Config>::block_author());
411 tracer.watch_address(&signer_addr);
412 });
413
414 log::debug!(target: LOG_TARGET, "\
415 Created checked Ethereum transaction with: \
416 from={signer_addr:?} \
417 eth_gas={} \
418 encoded_len={encoded_len} \
419 tx_fee={:?} \
420 storage_deposit={:?} \
421 weight_limit={} \
422 nonce={nonce:?}\
423 ",
424 call_info.eth_gas_limit,
425 call_info.tx_fee,
426 call_info.storage_deposit,
427 call_info.weight_limit,
428 );
429
430 Ok(CheckedExtrinsic {
433 format: ExtrinsicFormat::Signed(
434 signer.into(),
435 Self::get_eth_extension(nonce, Zero::zero()),
436 ),
437 function: call_info.call,
438 })
439 }
440}
441
442#[cfg(test)]
443mod test {
444 use super::*;
445 use crate::{
446 EthTransactInfo, RUNTIME_PALLETS_ADDR, Weight,
447 evm::*,
448 test_utils::*,
449 tests::{
450 Address, ExtBuilder, RuntimeCall, RuntimeOrigin, SignedExtra, Test, TestSigner,
451 UncheckedExtrinsic,
452 },
453 };
454 use frame_support::traits::fungible::Mutate;
455 use pallet_revive_fixtures::compile_module;
456 use sp_runtime::traits::{self, Checkable, DispatchTransaction, LookupError};
457
458 type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
459
460 struct TestContext;
461
462 impl traits::Lookup for TestContext {
463 type Source = Address;
464 type Target = AccountIdOf<Test>;
465 fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError> {
466 match s {
467 Self::Source::Id(id) => Ok(id),
468 _ => Err(LookupError),
469 }
470 }
471 }
472
473 #[derive(Clone)]
475 struct UncheckedExtrinsicBuilder {
476 tx: GenericTransaction,
477 before_validate: Option<std::sync::Arc<dyn Fn() + Send + Sync>>,
478 dry_run: Option<EthTransactInfo<BalanceOf<Test>>>,
479 }
480
481 impl UncheckedExtrinsicBuilder {
482 fn new() -> Self {
484 Self {
485 tx: GenericTransaction {
486 from: Some(Account::default().address()),
487 chain_id: Some(<Test as Config>::ChainId::get().into()),
488 ..Default::default()
489 },
490 before_validate: None,
491 dry_run: None,
492 }
493 }
494
495 fn data(mut self, data: Vec<u8>) -> Self {
496 self.tx.input = Bytes(data).into();
497 self
498 }
499
500 fn fund_account(account: &Account) {
501 let _ = <Test as Config>::Currency::set_balance(
502 &account.substrate_account(),
503 100_000_000_000_000,
504 );
505 }
506
507 fn estimate_gas(&mut self) {
508 let account = Account::default();
509 Self::fund_account(&account);
510
511 let dry_run =
512 crate::Pallet::<Test>::dry_run_eth_transact(self.tx.clone(), None, true, None);
513 let base_fee = <Pallet<Test>>::evm_base_fee();
514 self.tx.gas_price = Some(base_fee);
515 self.tx.max_fee_per_gas = Some(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 fn call_with(dest: H160) -> Self {
530 let mut builder = Self::new();
531 builder.tx.to = Some(dest);
532 builder
533 }
534
535 fn call_with_authorization(
537 dest: H160,
538 authorization_list: Vec<AuthorizationListEntry>,
539 ) -> Self {
540 let mut builder = Self::new();
541 builder.tx.to = Some(dest);
542 builder.tx.r#type = Some(TYPE_EIP7702.into());
543 builder.tx.authorization_list = authorization_list;
544 builder
545 }
546
547 fn instantiate_with(code: Vec<u8>, data: Vec<u8>) -> Self {
549 let mut builder = Self::new();
550 builder.tx.input = Bytes(code.into_iter().chain(data.into_iter()).collect()).into();
551 builder
552 }
553
554 fn before_validate(mut self, f: impl Fn() + Send + Sync + 'static) -> Self {
556 self.before_validate = Some(std::sync::Arc::new(f));
557 self
558 }
559
560 fn check(
561 self,
562 ) -> Result<
563 (u32, RuntimeCall, SignedExtra, GenericTransaction, Weight, TransactionSigned),
564 TransactionValidityError,
565 > {
566 self.mutate_estimate_and_check(Box::new(|_| ()))
567 }
568
569 fn mutate_estimate_and_check(
571 mut self,
572 f: Box<dyn FnOnce(&mut GenericTransaction) -> ()>,
573 ) -> Result<
574 (u32, RuntimeCall, SignedExtra, GenericTransaction, Weight, TransactionSigned),
575 TransactionValidityError,
576 > {
577 ExtBuilder::default().build().execute_with(|| self.estimate_gas());
578 ExtBuilder::default().build().execute_with(|| {
579 f(&mut self.tx);
580 let UncheckedExtrinsicBuilder { tx, before_validate, .. } = self.clone();
581
582 let account = Account::default();
584 Self::fund_account(&account);
585
586 let signed_transaction =
587 account.sign_transaction(tx.clone().try_into_unsigned().unwrap());
588 let call = RuntimeCall::Contracts(crate::Call::eth_transact {
589 payload: signed_transaction.signed_payload().clone(),
590 });
591
592 let uxt: UncheckedExtrinsic = generic::UncheckedExtrinsic::new_bare(call).into();
593 let encoded_len = uxt.encoded_size();
594 let result: CheckedExtrinsic<_, _, _> = uxt.check(&TestContext {})?;
595 let (account_id, extra): (AccountId32, SignedExtra) = match result.format {
596 ExtrinsicFormat::Signed(signer, extra) => (signer, extra),
597 _ => unreachable!(),
598 };
599
600 before_validate.map(|f| f());
601 extra.clone().validate_and_prepare(
602 RuntimeOrigin::signed(account_id),
603 &result.function,
604 &result.function.get_dispatch_info(),
605 encoded_len,
606 0,
607 )?;
608
609 Ok((
610 encoded_len as u32,
611 result.function,
612 extra,
613 tx,
614 self.dry_run.unwrap().weight_required,
615 signed_transaction,
616 ))
617 })
618 }
619 }
620
621 #[test]
622 fn check_eth_transact_call_works() {
623 let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]));
624 let (expected_encoded_len, call, _, tx, weight_required, signed_transaction) =
625 builder.check().unwrap();
626 let expected_effective_gas_price =
627 ExtBuilder::default().build().execute_with(|| Pallet::<Test>::evm_base_fee());
628
629 match call {
630 RuntimeCall::Contracts(crate::Call::eth_call::<Test> {
631 dest,
632 value,
633 weight_limit,
634 data,
635 transaction_encoded,
636 effective_gas_price,
637 encoded_len,
638 ..
639 }) if dest == tx.to.unwrap() &&
640 value == tx.value.unwrap_or_default().as_u64().into() &&
641 data == tx.input.to_vec() &&
642 transaction_encoded == signed_transaction.signed_payload() &&
643 effective_gas_price == expected_effective_gas_price =>
644 {
645 assert_eq!(encoded_len, expected_encoded_len);
646 assert!(
647 weight_limit.all_gte(weight_required),
648 "Assert failed: weight_limit={weight_limit:?} >= weight_required={weight_required:?}"
649 );
650 },
651 _ => panic!("Call does not match."),
652 }
653 }
654
655 #[test]
656 fn check_eth_transact_instantiate_works() {
657 let (expected_code, _) = compile_module("dummy").unwrap();
658 let expected_data = vec![];
659 let builder = UncheckedExtrinsicBuilder::instantiate_with(
660 expected_code.clone(),
661 expected_data.clone(),
662 );
663 let (expected_encoded_len, call, _, tx, weight_required, signed_transaction) =
664 builder.check().unwrap();
665 let expected_effective_gas_price =
666 ExtBuilder::default().build().execute_with(|| Pallet::<Test>::evm_base_fee());
667 let expected_value = tx.value.unwrap_or_default().as_u64().into();
668
669 match call {
670 RuntimeCall::Contracts(crate::Call::eth_instantiate_with_code::<Test> {
671 value,
672 weight_limit,
673 code,
674 data,
675 transaction_encoded,
676 effective_gas_price,
677 encoded_len,
678 ..
679 }) if value == expected_value &&
680 code == expected_code &&
681 data == expected_data &&
682 transaction_encoded == signed_transaction.signed_payload() &&
683 effective_gas_price == expected_effective_gas_price =>
684 {
685 assert_eq!(encoded_len, expected_encoded_len);
686 assert!(
687 weight_limit.all_gte(weight_required),
688 "Assert failed: weight_limit={weight_limit:?} >= weight_required={weight_required:?}"
689 );
690 },
691 _ => panic!("Call does not match."),
692 }
693 }
694
695 #[test]
696 fn check_eth_transact_nonce_works() {
697 let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]));
698
699 assert_eq!(
700 builder.mutate_estimate_and_check(Box::new(|tx| tx.nonce = Some(1u32.into()))),
701 Err(TransactionValidityError::Invalid(InvalidTransaction::Future))
702 );
703
704 let builder =
705 UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])).before_validate(|| {
706 <crate::System<Test>>::inc_account_nonce(Account::default().substrate_account());
707 });
708
709 assert_eq!(
710 builder.check(),
711 Err(TransactionValidityError::Invalid(InvalidTransaction::Stale))
712 );
713 }
714
715 #[test]
716 fn check_eth_transact_chain_id_works() {
717 let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]));
718
719 assert_eq!(
720 builder.mutate_estimate_and_check(Box::new(|tx| tx.chain_id = Some(42.into()))),
721 Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
722 );
723 }
724
725 #[test]
726 fn check_instantiate_data() {
727 let code: Vec<u8> = polkavm_common::program::BLOB_MAGIC
728 .into_iter()
729 .chain(b"invalid code".iter().cloned())
730 .collect();
731 let data = vec![1];
732
733 let builder = UncheckedExtrinsicBuilder::instantiate_with(code.clone(), data.clone());
734
735 assert_eq!(
737 builder.check(),
738 Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
739 );
740 }
741
742 #[test]
745 fn check_eth_transact_payload_size() {
746 let check = |len: u32| {
747 ExtBuilder::default().build().execute_with(|| {
748 let call = RuntimeCall::Contracts(crate::Call::eth_transact {
749 payload: vec![0u8; len as usize],
750 });
751 let uxt: UncheckedExtrinsic = generic::UncheckedExtrinsic::new_bare(call).into();
752 uxt.check(&TestContext {}).map(|_| ())
753 })
754 };
755 let limit = crate::limits::MAX_TRANSACTION_PAYLOAD_SIZE;
756
757 assert_eq!(
758 check(limit + 1),
759 Err(TransactionValidityError::Invalid(InvalidTransaction::ExhaustsResources))
760 );
761 assert_eq!(check(limit), Err(TransactionValidityError::Invalid(InvalidTransaction::Call)));
762 }
763
764 #[test]
767 fn dry_run_eth_transact_payload_size() {
768 ExtBuilder::default().build().execute_with(|| {
769 let exhausts_resources = |input_len: u32| {
770 let result = crate::Pallet::<Test>::dry_run_eth_transact(
771 GenericTransaction {
772 from: Some(ALICE_ADDR),
773 to: Some(BOB_ADDR),
774 input: vec![0u8; input_len as usize].into(),
775 ..Default::default()
776 },
777 None,
778 false,
779 None,
780 );
781 matches!(
782 result,
783 Err(crate::EthTransactError::Message(msg)) if msg.contains("ExhaustsResources")
784 )
785 };
786 let limit = crate::limits::MAX_TRANSACTION_PAYLOAD_SIZE;
787
788 assert!(exhausts_resources(limit));
789 assert!(!exhausts_resources(limit - 1024));
790 });
791 }
792
793 #[test]
794 fn check_transaction_fees() {
795 let scenarios: Vec<(_, Box<dyn FnOnce(&mut GenericTransaction)>, _)> = vec![
796 (
797 "Eth fees too low",
798 Box::new(|tx| {
799 tx.gas_price = Some(100u64.into());
800 }),
801 InvalidTransaction::Payment,
802 ),
803 (
804 "Gas fees too low",
805 Box::new(|tx| {
806 tx.gas = Some(tx.gas.unwrap() / 2);
807 }),
808 InvalidTransaction::Payment,
809 ),
810 ];
811
812 for (msg, update_tx, err) in scenarios {
813 let res = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]))
814 .mutate_estimate_and_check(update_tx);
815
816 assert_eq!(res, Err(TransactionValidityError::Invalid(err)), "{}", msg);
817 }
818 }
819
820 #[test]
821 fn eth_pre_dispatch_weight_matches_check_weight_booking() {
822 let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]));
823 let (encoded_len, call, _, _, _, signed_transaction) = builder.check().unwrap();
824
825 ExtBuilder::default().build().execute_with(|| {
826 let reported =
827 Pallet::<Test>::eth_pre_dispatch_weight(signed_transaction.signed_payload())
828 .unwrap();
829 let info = <Test as Config>::FeeInfo::dispatch_info(&call);
830 let expected = frame_system::calculate_consumed_extrinsic_weight::<CallOf<Test>>(
831 &<Test as frame_system::Config>::BlockWeights::get(),
832 &info,
833 encoded_len as usize,
834 );
835
836 assert_eq!(reported, expected);
837 });
838 }
839
840 #[test]
841 fn check_transaction_tip() {
842 let (code, _) = compile_module("dummy").unwrap();
843 let data = vec![42u8; crate::limits::CALLDATA_BYTES as usize];
845 let (_, _, extra, _tx, _gas_required, _) =
846 UncheckedExtrinsicBuilder::instantiate_with(code.clone(), data.clone())
847 .mutate_estimate_and_check(Box::new(|tx| {
848 tx.gas_price = Some(tx.gas_price.unwrap() * 103 / 100);
849 log::debug!(target: LOG_TARGET, "Gas price: {:?}", tx.gas_price);
850 }))
851 .unwrap();
852
853 assert_eq!(U256::from(extra.1.tip()), 0u32.into());
854 }
855
856 #[test]
857 fn check_runtime_pallets_addr_works() {
858 let remark: CallOf<Test> =
859 frame_system::Call::remark { remark: b"Hello, world!".to_vec() }.into();
860
861 let builder =
862 UncheckedExtrinsicBuilder::call_with(RUNTIME_PALLETS_ADDR).data(remark.encode());
863 let (_, call, _, _, _, _) = builder.check().unwrap();
864
865 match call {
866 RuntimeCall::Contracts(crate::Call::eth_substrate_call {
867 call: inner_call, ..
868 }) => {
869 assert_eq!(*inner_call, remark);
870 },
871 _ => panic!("Expected the RuntimeCall::Contracts variant, got: {:?}", call),
872 }
873 }
874
875 #[test]
885 fn contract_deployment_with_nick_method_works() {
886 let raw_transaction_bytes = alloy_core::hex!(
888 "0xf9016c8085174876e8008303c4d88080b90154608060405234801561001057600080fd5b50610134806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80634af63f0214602d575b600080fd5b60cf60048036036040811015604157600080fd5b810190602081018135640100000000811115605b57600080fd5b820183602082011115606c57600080fd5b80359060200191846001830284011164010000000083111715608d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550509135925060eb915050565b604080516001600160a01b039092168252519081900360200190f35b6000818351602085016000f5939250505056fea26469706673582212206b44f8a82cb6b156bfcc3dc6aadd6df4eefd204bc928a4397fd15dacf6d5320564736f6c634300060200331b83247000822470"
889 );
890
891 let mut signed_transaction = TransactionSigned::decode(raw_transaction_bytes.as_slice())
892 .expect("Invalid raw transaction bytes");
893 if let TransactionSigned::TransactionLegacySigned(ref mut legacy_transaction) =
894 signed_transaction
895 {
896 legacy_transaction.transaction_legacy_unsigned.gas =
897 U256::from_dec_str("3750815700000").unwrap();
898 }
899 let generic_transaction = GenericTransaction::from_signed(
900 signed_transaction.clone(),
901 ExtBuilder::default().build().execute_with(|| Pallet::<Test>::evm_base_fee()),
902 None,
903 );
904
905 let unchecked_extrinsic_builder = UncheckedExtrinsicBuilder {
906 tx: generic_transaction,
907 before_validate: None,
908 dry_run: None,
909 };
910
911 let eth_transact_result = unchecked_extrinsic_builder.check();
913
914 let (
916 _encoded_len,
917 _function,
918 _extra,
919 generic_transaction,
920 _gas_required,
921 _signed_transaction,
922 ) = eth_transact_result.expect("eth_transact failed");
923 assert!(
924 generic_transaction.chain_id.is_none(),
925 "Chain Id in the generic transaction is not None"
926 );
927 }
928
929 #[test]
930 fn check_eth_transact_7702_call_works() {
931 let chain_id = U256::from(<Test as Config>::ChainId::get());
932 let signer = TestSigner::new(&[0xCC; 32]);
933 let auth = signer.sign_authorization(chain_id, H160::from([1u8; 20]), U256::zero());
934
935 let builder =
936 UncheckedExtrinsicBuilder::call_with_authorization(H160::from([1u8; 20]), vec![auth]);
937 let (expected_encoded_len, call, _, tx, weight_required, _) = builder.check().unwrap();
938
939 match call {
940 RuntimeCall::Contracts(crate::Call::eth_call::<Test> {
941 dest,
942 weight_limit,
943 encoded_len,
944 authorization_list,
945 ..
946 }) if dest == tx.to.unwrap() => {
947 assert_eq!(encoded_len, expected_encoded_len);
948 assert_eq!(authorization_list.len(), 1);
949 assert!(
950 weight_limit.all_gte(weight_required),
951 "weight_limit={weight_limit:?} >= weight_required={weight_required:?}"
952 );
953 },
954 _ => panic!("Call does not match."),
955 }
956 }
957
958 #[test]
959 fn check_eth_transact_7702_insufficient_gas() {
960 use crate::evm::fees::InfoT;
961
962 let chain_id = U256::from(<Test as Config>::ChainId::get());
963 let dest = H160::from([1u8; 20]);
964 let auths: Vec<_> = (0..3u8)
965 .map(|i| {
966 let mut seed = [0u8; 32];
967 seed[0] = 0xCC + i;
968 TestSigner::new(&seed).sign_authorization(chain_id, dest, U256::zero())
969 })
970 .collect();
971 let num_auths = auths.len() as u128;
972 let gas_scale = <Test as Config>::GasScale::get() as u128;
973 let auth_cost = Pallet::<Test>::worst_case_delegation_deposit().saturating_mul(num_auths);
974
975 UncheckedExtrinsicBuilder::call_with_authorization(dest, auths.clone())
977 .check()
978 .expect("estimated gas should pass validation");
979
980 UncheckedExtrinsicBuilder::call_with_authorization(dest, auths.clone())
982 .mutate_estimate_and_check(Box::new(move |tx| {
983 let mut call_info = tx
984 .clone()
985 .into_call::<Test>(CreateCallMode::DryRun)
986 .expect("dry run should succeed");
987 let base_info = <Test as Config>::FeeInfo::base_dispatch_info(&mut call_info.call);
988 let overhead = <Test as Config>::FeeInfo::fixed_fee(call_info.encoded_len as u32) +
989 <Test as Config>::FeeInfo::weight_to_fee(&base_info.total_weight());
990 let sufficient_gas = 1 + (auth_cost + overhead) / gas_scale;
991 tx.gas = Some(U256::from(sufficient_gas));
992 }))
993 .expect("gas covering auth deposits + overhead should pass");
994
995 let res = UncheckedExtrinsicBuilder::call_with_authorization(dest, auths)
997 .mutate_estimate_and_check(Box::new(move |tx| {
998 let insufficient_gas = auth_cost / gas_scale;
999 tx.gas = Some(U256::from(insufficient_gas));
1000 }));
1001
1002 assert_eq!(res, Err(TransactionValidityError::Invalid(InvalidTransaction::Payment)));
1003 }
1004
1005 #[test]
1008 fn check_eth_transact_7702_rejects_oversized_nonce() {
1009 let chain_id = U256::from(<Test as Config>::ChainId::get());
1010 let dest = H160::from([1u8; 20]);
1011 let signer = TestSigner::new(&[0xCC; 32]);
1012 let auth = signer.sign_authorization(chain_id, dest, U256::zero());
1013
1014 let oversized_nonce = U256::one() << 64;
1016 let bad_auth = crate::evm::AuthorizationListEntry { nonce: oversized_nonce, ..auth };
1017
1018 assert_eq!(
1019 UncheckedExtrinsicBuilder::call_with_authorization(dest, vec![bad_auth]).check(),
1020 Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
1021 );
1022 }
1023
1024 #[test]
1027 fn check_eth_transact_7702_rejects_oversized_y_parity() {
1028 let chain_id = U256::from(<Test as Config>::ChainId::get());
1029 let dest = H160::from([1u8; 20]);
1030 let signer = TestSigner::new(&[0xCC; 32]);
1031 let auth = signer.sign_authorization(chain_id, dest, U256::zero());
1032
1033 let bad_auth = crate::evm::AuthorizationListEntry { y_parity: U256::from(256u32), ..auth };
1035
1036 assert_eq!(
1037 UncheckedExtrinsicBuilder::call_with_authorization(dest, vec![bad_auth]).check(),
1038 Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
1039 );
1040 }
1041
1042 #[test]
1047 fn check_eth_transact_7702_rejects_empty_auth_list() {
1048 let dest = H160::from([1u8; 20]);
1049 assert_eq!(
1050 UncheckedExtrinsicBuilder::call_with_authorization(dest, vec![]).check(),
1051 Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
1052 );
1053 }
1054
1055 #[test]
1060 fn check_eth_transact_7702_rejects_runtime_pallets_addr() {
1061 let chain_id = U256::from(<Test as Config>::ChainId::get());
1062 let signer = TestSigner::new(&[0xCC; 32]);
1063 let auth = signer.sign_authorization(chain_id, H160::from([1u8; 20]), U256::zero());
1064
1065 let remark: CallOf<Test> =
1066 frame_system::Call::remark { remark: b"Hello, world!".to_vec() }.into();
1067
1068 assert_eq!(
1069 UncheckedExtrinsicBuilder::call_with_authorization(RUNTIME_PALLETS_ADDR, vec![auth])
1070 .data(remark.encode())
1071 .check(),
1072 Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
1073 );
1074 }
1075}