1use crate::{
19 evm::{
20 api::{GenericTransaction, TransactionSigned},
21 create_call,
22 fees::InfoT,
23 },
24 AccountIdOf, AddressMapper, BalanceOf, CallOf, Config, Pallet, Zero, LOG_TARGET,
25};
26use codec::{Decode, DecodeWithMemTracking, Encode};
27use frame_support::{
28 dispatch::{DispatchInfo, GetDispatchInfo},
29 traits::{
30 fungible::Balanced,
31 tokens::{Fortitude, Precision, Preservation},
32 InherentBuilder, IsSubType, SignedTransactionBuilder,
33 },
34};
35use pallet_transaction_payment::Config as TxConfig;
36use scale_info::{StaticTypeInfo, TypeInfo};
37use sp_core::U256;
38use sp_runtime::{
39 generic::{self, CheckedExtrinsic, ExtrinsicFormat},
40 traits::{
41 Checkable, ExtrinsicCall, ExtrinsicLike, ExtrinsicMetadata, LazyExtrinsic,
42 TransactionExtension,
43 },
44 transaction_validity::{InvalidTransaction, TransactionValidityError},
45 OpaqueExtrinsic, RuntimeDebug, Weight,
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, RuntimeDebug)]
59pub struct UncheckedExtrinsic<Address, Signature, E: EthExtra>(
60 pub generic::UncheckedExtrinsic<Address, CallOf<E::Config>, Signature, E::Extension>,
61);
62
63impl<Address, Signature, E: EthExtra> TypeInfo for UncheckedExtrinsic<Address, Signature, E>
64where
65 Address: StaticTypeInfo,
66 Signature: StaticTypeInfo,
67 E::Extension: StaticTypeInfo,
68{
69 type Identity =
70 generic::UncheckedExtrinsic<Address, CallOf<E::Config>, Signature, E::Extension>;
71 fn type_info() -> scale_info::Type {
72 generic::UncheckedExtrinsic::<Address, CallOf<E::Config>, Signature, E::Extension>::type_info()
73 }
74}
75
76impl<Address, Signature, E: EthExtra>
77 From<generic::UncheckedExtrinsic<Address, CallOf<E::Config>, Signature, E::Extension>>
78 for UncheckedExtrinsic<Address, Signature, E>
79{
80 fn from(
81 utx: generic::UncheckedExtrinsic<Address, CallOf<E::Config>, Signature, E::Extension>,
82 ) -> Self {
83 Self(utx)
84 }
85}
86
87impl<Address: TypeInfo, Signature: TypeInfo, E: EthExtra> ExtrinsicLike
88 for UncheckedExtrinsic<Address, Signature, E>
89{
90 fn is_bare(&self) -> bool {
91 ExtrinsicLike::is_bare(&self.0)
92 }
93}
94
95impl<Address, Signature, E: EthExtra> ExtrinsicMetadata
96 for UncheckedExtrinsic<Address, Signature, E>
97{
98 const VERSIONS: &'static [u8] = generic::UncheckedExtrinsic::<
99 Address,
100 CallOf<E::Config>,
101 Signature,
102 E::Extension,
103 >::VERSIONS;
104 type TransactionExtensions = E::Extension;
105}
106
107impl<Address: TypeInfo, Signature: TypeInfo, E: EthExtra> ExtrinsicCall
108 for UncheckedExtrinsic<Address, Signature, E>
109{
110 type Call = CallOf<E::Config>;
111
112 fn call(&self) -> &Self::Call {
113 self.0.call()
114 }
115
116 fn into_call(self) -> Self::Call {
117 self.0.into_call()
118 }
119}
120
121impl<LookupSource, Signature, E, Lookup> Checkable<Lookup>
122 for UncheckedExtrinsic<LookupSource, Signature, E>
123where
124 E: EthExtra,
125 Self: Encode,
126 <E::Config as frame_system::Config>::Nonce: TryFrom<U256>,
127 CallOf<E::Config>: SetWeightLimit,
128 generic::UncheckedExtrinsic<LookupSource, CallOf<E::Config>, Signature, E::Extension>:
130 Checkable<
131 Lookup,
132 Checked = CheckedExtrinsic<AccountIdOf<E::Config>, CallOf<E::Config>, E::Extension>,
133 >,
134{
135 type Checked = CheckedExtrinsic<AccountIdOf<E::Config>, CallOf<E::Config>, E::Extension>;
136
137 fn check(self, lookup: &Lookup) -> Result<Self::Checked, TransactionValidityError> {
138 if !self.0.is_signed() {
139 if let Some(crate::Call::eth_transact { payload }) = self.0.function.is_sub_type() {
140 let checked = E::try_into_checked_extrinsic(payload, self.encoded_size())?;
141 return Ok(checked)
142 };
143 }
144 self.0.check(lookup)
145 }
146
147 #[cfg(feature = "try-runtime")]
148 fn unchecked_into_checked_i_know_what_i_am_doing(
149 self,
150 lookup: &Lookup,
151 ) -> Result<Self::Checked, TransactionValidityError> {
152 self.0.unchecked_into_checked_i_know_what_i_am_doing(lookup)
153 }
154}
155
156impl<Address, Signature, E: EthExtra> GetDispatchInfo
157 for UncheckedExtrinsic<Address, Signature, E>
158{
159 fn get_dispatch_info(&self) -> DispatchInfo {
160 self.0.get_dispatch_info()
161 }
162}
163
164impl<Address: Encode, Signature: Encode, E: EthExtra> serde::Serialize
165 for UncheckedExtrinsic<Address, Signature, E>
166{
167 fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error>
168 where
169 S: ::serde::Serializer,
170 {
171 self.0.serialize(seq)
172 }
173}
174
175impl<'a, Address: Decode, Signature: Decode, E: EthExtra> serde::Deserialize<'a>
176 for UncheckedExtrinsic<Address, Signature, E>
177{
178 fn deserialize<D>(de: D) -> Result<Self, D::Error>
179 where
180 D: serde::Deserializer<'a>,
181 {
182 let r = sp_core::bytes::deserialize(de)?;
183 Decode::decode(&mut &r[..])
184 .map_err(|e| serde::de::Error::custom(alloc::format!("Decode error: {}", e)))
185 }
186}
187
188impl<Address, Signature, E: EthExtra> SignedTransactionBuilder
189 for UncheckedExtrinsic<Address, Signature, E>
190where
191 Address: TypeInfo,
192 Signature: TypeInfo,
193 E::Extension: TypeInfo,
194{
195 type Address = Address;
196 type Signature = Signature;
197 type Extension = E::Extension;
198
199 fn new_signed_transaction(
200 call: Self::Call,
201 signed: Address,
202 signature: Signature,
203 tx_ext: E::Extension,
204 ) -> Self {
205 generic::UncheckedExtrinsic::new_signed(call, signed, signature, tx_ext).into()
206 }
207}
208
209impl<Address, Signature, E: EthExtra> InherentBuilder for UncheckedExtrinsic<Address, Signature, E>
210where
211 Address: TypeInfo,
212 Signature: TypeInfo,
213 E::Extension: TypeInfo,
214{
215 fn new_inherent(call: Self::Call) -> Self {
216 generic::UncheckedExtrinsic::new_bare(call).into()
217 }
218}
219
220impl<Address, Signature, E: EthExtra> From<UncheckedExtrinsic<Address, Signature, E>>
221 for OpaqueExtrinsic
222where
223 Address: Encode,
224 Signature: Encode,
225 E::Extension: Encode,
226{
227 fn from(extrinsic: UncheckedExtrinsic<Address, Signature, E>) -> Self {
228 extrinsic.0.into()
229 }
230}
231
232impl<Address, Signature, E: EthExtra> LazyExtrinsic for UncheckedExtrinsic<Address, Signature, E>
233where
234 generic::UncheckedExtrinsic<Address, CallOf<E::Config>, Signature, E::Extension>: LazyExtrinsic,
235{
236 fn decode_unprefixed(data: &[u8]) -> Result<Self, codec::Error> {
237 Ok(Self(LazyExtrinsic::decode_unprefixed(data)?))
238 }
239}
240
241pub trait EthExtra {
243 type Config: Config + TxConfig;
245
246 type Extension: TransactionExtension<CallOf<Self::Config>>;
251
252 fn get_eth_extension(
259 nonce: <Self::Config as frame_system::Config>::Nonce,
260 tip: BalanceOf<Self::Config>,
261 ) -> Self::Extension;
262
263 fn try_into_checked_extrinsic(
271 payload: &[u8],
272 encoded_len: usize,
273 ) -> Result<
274 CheckedExtrinsic<AccountIdOf<Self::Config>, CallOf<Self::Config>, Self::Extension>,
275 InvalidTransaction,
276 >
277 where
278 <Self::Config as frame_system::Config>::Nonce: TryFrom<U256>,
279 CallOf<Self::Config>: SetWeightLimit,
280 {
281 let tx = TransactionSigned::decode(&payload).map_err(|err| {
282 log::debug!(target: LOG_TARGET, "Failed to decode transaction: {err:?}");
283 InvalidTransaction::Call
284 })?;
285
286 match &tx {
288 crate::evm::api::TransactionSigned::Transaction1559Signed(_) |
289 crate::evm::api::TransactionSigned::Transaction2930Signed(_) |
290 crate::evm::api::TransactionSigned::TransactionLegacySigned(_) => {
291 },
293 crate::evm::api::TransactionSigned::Transaction7702Signed(_) => {
294 log::debug!(target: LOG_TARGET, "EIP-7702 transactions are not supported");
295 return Err(InvalidTransaction::Call);
296 },
297 crate::evm::api::TransactionSigned::Transaction4844Signed(_) => {
298 log::debug!(target: LOG_TARGET, "EIP-4844 transactions are not supported");
299 return Err(InvalidTransaction::Call);
300 },
301 }
302
303 let signer_addr = tx.recover_eth_address().map_err(|err| {
304 log::debug!(target: LOG_TARGET, "Failed to recover signer: {err:?}");
305 InvalidTransaction::BadProof
306 })?;
307
308 let signer = <Self::Config as Config>::AddressMapper::to_fallback_account_id(&signer_addr);
309 let base_fee = <Pallet<Self::Config>>::evm_base_fee();
310 let tx = GenericTransaction::from_signed(tx, base_fee, None);
311 let nonce = tx.nonce.unwrap_or_default().try_into().map_err(|_| {
312 log::debug!(target: LOG_TARGET, "Failed to convert nonce");
313 InvalidTransaction::Call
314 })?;
315
316 log::trace!(target: LOG_TARGET, "Decoded Ethereum transaction with signer: {signer_addr:?} nonce: {nonce:?}");
317 let call_info =
318 create_call::<Self::Config>(tx, Some((encoded_len as u32, payload.to_vec())), true)?;
319 let storage_credit = <Self::Config as Config>::Currency::withdraw(
320 &signer,
321 call_info.storage_deposit,
322 Precision::Exact,
323 Preservation::Preserve,
324 Fortitude::Polite,
325 ).map_err(|_| {
326 log::debug!(target: LOG_TARGET, "Not enough balance to hold additional storage deposit of {:?}", call_info.storage_deposit);
327 InvalidTransaction::Payment
328 })?;
329 <Self::Config as Config>::FeeInfo::deposit_txfee(storage_credit);
330
331 crate::tracing::if_tracing(|tracer| {
332 tracer.watch_address(&Pallet::<Self::Config>::block_author());
333 tracer.watch_address(&signer_addr);
334 });
335
336 log::debug!(target: LOG_TARGET, "\
337 Created checked Ethereum transaction with: \
338 from={signer_addr:?} \
339 eth_gas={} \
340 encoded_len={encoded_len} \
341 tx_fee={:?} \
342 storage_deposit={:?} \
343 weight_limit={} \
344 nonce={nonce:?}\
345 ",
346 call_info.gas,
347 call_info.tx_fee,
348 call_info.storage_deposit,
349 call_info.weight_limit,
350 );
351
352 Ok(CheckedExtrinsic {
355 format: ExtrinsicFormat::Signed(
356 signer.into(),
357 Self::get_eth_extension(nonce, Zero::zero()),
358 ),
359 function: call_info.call,
360 })
361 }
362}
363
364#[cfg(test)]
365mod test {
366 use super::*;
367 use crate::{
368 evm::*,
369 test_utils::*,
370 tests::{
371 Address, ExtBuilder, RuntimeCall, RuntimeOrigin, SignedExtra, Test, UncheckedExtrinsic,
372 },
373 EthTransactInfo, Weight, RUNTIME_PALLETS_ADDR,
374 };
375 use frame_support::{error::LookupError, traits::fungible::Mutate};
376 use pallet_revive_fixtures::compile_module;
377 use sp_runtime::traits::{self, Checkable, DispatchTransaction};
378
379 type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
380
381 struct TestContext;
382
383 impl traits::Lookup for TestContext {
384 type Source = Address;
385 type Target = AccountIdOf<Test>;
386 fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError> {
387 match s {
388 Self::Source::Id(id) => Ok(id),
389 _ => Err(LookupError),
390 }
391 }
392 }
393
394 #[derive(Clone)]
396 struct UncheckedExtrinsicBuilder {
397 tx: GenericTransaction,
398 before_validate: Option<std::sync::Arc<dyn Fn() + Send + Sync>>,
399 dry_run: Option<EthTransactInfo<BalanceOf<Test>>>,
400 }
401
402 impl UncheckedExtrinsicBuilder {
403 fn new() -> Self {
405 Self {
406 tx: GenericTransaction {
407 from: Some(Account::default().address()),
408 chain_id: Some(<Test as Config>::ChainId::get().into()),
409 ..Default::default()
410 },
411 before_validate: None,
412 dry_run: None,
413 }
414 }
415
416 fn data(mut self, data: Vec<u8>) -> Self {
417 self.tx.input = Bytes(data).into();
418 self
419 }
420
421 fn fund_account(account: &Account) {
422 let _ = <Test as Config>::Currency::set_balance(
423 &account.substrate_account(),
424 100_000_000_000_000,
425 );
426 }
427
428 fn estimate_gas(&mut self) {
429 let account = Account::default();
430 Self::fund_account(&account);
431
432 let dry_run =
433 crate::Pallet::<Test>::dry_run_eth_transact(self.tx.clone(), Default::default());
434 self.tx.gas_price = Some(<Pallet<Test>>::evm_base_fee());
435
436 match dry_run {
437 Ok(dry_run) => {
438 self.tx.gas = Some(dry_run.eth_gas);
439 self.dry_run = Some(dry_run);
440 },
441 Err(err) => {
442 log::debug!(target: LOG_TARGET, "Failed to estimate gas: {:?}", err);
443 },
444 }
445 }
446
447 fn call_with(dest: H160) -> Self {
449 let mut builder = Self::new();
450 builder.tx.to = Some(dest);
451 builder
452 }
453
454 fn instantiate_with(code: Vec<u8>, data: Vec<u8>) -> Self {
456 let mut builder = Self::new();
457 builder.tx.input = Bytes(code.into_iter().chain(data.into_iter()).collect()).into();
458 builder
459 }
460
461 fn before_validate(mut self, f: impl Fn() + Send + Sync + 'static) -> Self {
463 self.before_validate = Some(std::sync::Arc::new(f));
464 self
465 }
466
467 fn check(
468 self,
469 ) -> Result<
470 (u32, RuntimeCall, SignedExtra, GenericTransaction, Weight, TransactionSigned),
471 TransactionValidityError,
472 > {
473 self.mutate_estimate_and_check(Box::new(|_| ()))
474 }
475
476 fn mutate_estimate_and_check(
478 mut self,
479 f: Box<dyn FnOnce(&mut GenericTransaction) -> ()>,
480 ) -> Result<
481 (u32, RuntimeCall, SignedExtra, GenericTransaction, Weight, TransactionSigned),
482 TransactionValidityError,
483 > {
484 ExtBuilder::default().build().execute_with(|| self.estimate_gas());
485 ExtBuilder::default().build().execute_with(|| {
486 f(&mut self.tx);
487 let UncheckedExtrinsicBuilder { tx, before_validate, .. } = self.clone();
488
489 let account = Account::default();
491 Self::fund_account(&account);
492
493 let signed_transaction =
494 account.sign_transaction(tx.clone().try_into_unsigned().unwrap());
495 let call = RuntimeCall::Contracts(crate::Call::eth_transact {
496 payload: signed_transaction.signed_payload().clone(),
497 });
498
499 let uxt: UncheckedExtrinsic = generic::UncheckedExtrinsic::new_bare(call).into();
500 let encoded_len = uxt.encoded_size();
501 let result: CheckedExtrinsic<_, _, _> = uxt.check(&TestContext {})?;
502 let (account_id, extra): (AccountId32, SignedExtra) = match result.format {
503 ExtrinsicFormat::Signed(signer, extra) => (signer, extra),
504 _ => unreachable!(),
505 };
506
507 before_validate.map(|f| f());
508 extra.clone().validate_and_prepare(
509 RuntimeOrigin::signed(account_id),
510 &result.function,
511 &result.function.get_dispatch_info(),
512 encoded_len,
513 0,
514 )?;
515
516 Ok((
517 encoded_len as u32,
518 result.function,
519 extra,
520 tx,
521 self.dry_run.unwrap().gas_required,
522 signed_transaction,
523 ))
524 })
525 }
526 }
527
528 #[test]
529 fn check_eth_transact_call_works() {
530 let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]));
531 let (expected_encoded_len, call, _, tx, gas_required, signed_transaction) =
532 builder.check().unwrap();
533 let expected_effective_gas_price =
534 ExtBuilder::default().build().execute_with(|| Pallet::<Test>::evm_base_fee());
535
536 match call {
537 RuntimeCall::Contracts(crate::Call::eth_call::<Test> {
538 dest,
539 value,
540 data,
541 gas_limit,
542 transaction_encoded,
543 effective_gas_price,
544 encoded_len,
545 }) if dest == tx.to.unwrap() &&
546 value == tx.value.unwrap_or_default().as_u64().into() &&
547 data == tx.input.to_vec() &&
548 transaction_encoded == signed_transaction.signed_payload() &&
549 effective_gas_price == expected_effective_gas_price =>
550 {
551 assert_eq!(encoded_len, expected_encoded_len);
552 assert!(
553 gas_limit.all_gte(gas_required),
554 "Assert failed: gas_limit={gas_limit:?} >= gas_required={gas_required:?}"
555 );
556 },
557 _ => panic!("Call does not match."),
558 }
559 }
560
561 #[test]
562 fn check_eth_transact_instantiate_works() {
563 let (expected_code, _) = compile_module("dummy").unwrap();
564 let expected_data = vec![];
565 let builder = UncheckedExtrinsicBuilder::instantiate_with(
566 expected_code.clone(),
567 expected_data.clone(),
568 );
569 let (expected_encoded_len, call, _, tx, gas_required, signed_transaction) =
570 builder.check().unwrap();
571 let expected_effective_gas_price =
572 ExtBuilder::default().build().execute_with(|| Pallet::<Test>::evm_base_fee());
573 let expected_value = tx.value.unwrap_or_default().as_u64().into();
574
575 match call {
576 RuntimeCall::Contracts(crate::Call::eth_instantiate_with_code::<Test> {
577 value,
578 code,
579 data,
580 gas_limit,
581 transaction_encoded,
582 effective_gas_price,
583 encoded_len,
584 }) if value == expected_value &&
585 code == expected_code &&
586 data == expected_data &&
587 transaction_encoded == signed_transaction.signed_payload() &&
588 effective_gas_price == expected_effective_gas_price =>
589 {
590 assert_eq!(encoded_len, expected_encoded_len);
591 assert!(
592 gas_limit.all_gte(gas_required),
593 "Assert failed: gas_limit={gas_limit:?} >= gas_required={gas_required:?}"
594 );
595 },
596 _ => panic!("Call does not match."),
597 }
598 }
599
600 #[test]
601 fn check_eth_transact_nonce_works() {
602 let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]));
603
604 assert_eq!(
605 builder.mutate_estimate_and_check(Box::new(|tx| tx.nonce = Some(1u32.into()))),
606 Err(TransactionValidityError::Invalid(InvalidTransaction::Future))
607 );
608
609 let builder =
610 UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])).before_validate(|| {
611 <crate::System<Test>>::inc_account_nonce(Account::default().substrate_account());
612 });
613
614 assert_eq!(
615 builder.check(),
616 Err(TransactionValidityError::Invalid(InvalidTransaction::Stale))
617 );
618 }
619
620 #[test]
621 fn check_eth_transact_chain_id_works() {
622 let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]));
623
624 assert_eq!(
625 builder.mutate_estimate_and_check(Box::new(|tx| tx.chain_id = Some(42.into()))),
626 Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
627 );
628 }
629
630 #[test]
631 fn check_instantiate_data() {
632 let code: Vec<u8> = polkavm_common::program::BLOB_MAGIC
633 .into_iter()
634 .chain(b"invalid code".iter().cloned())
635 .collect();
636 let data = vec![1];
637
638 let builder = UncheckedExtrinsicBuilder::instantiate_with(code.clone(), data.clone());
639
640 assert_eq!(
642 builder.check(),
643 Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
644 );
645 }
646
647 #[test]
648 fn check_transaction_fees() {
649 let scenarios: Vec<(_, Box<dyn FnOnce(&mut GenericTransaction)>, _)> = vec![
650 (
651 "Eth fees too low",
652 Box::new(|tx| {
653 tx.gas_price = Some(100u64.into());
654 }),
655 InvalidTransaction::Payment,
656 ),
657 (
658 "Gas fees too low",
659 Box::new(|tx| {
660 tx.gas = Some(tx.gas.unwrap() / 2);
661 }),
662 InvalidTransaction::Payment,
663 ),
664 ];
665
666 for (msg, update_tx, err) in scenarios {
667 let res = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20]))
668 .mutate_estimate_and_check(update_tx);
669
670 assert_eq!(res, Err(TransactionValidityError::Invalid(err)), "{}", msg);
671 }
672 }
673
674 #[test]
675 fn check_transaction_tip() {
676 let (code, _) = compile_module("dummy").unwrap();
677 let data = vec![42u8; crate::limits::CALLDATA_BYTES as usize];
679 let (_, _, extra, _tx, _gas_required, _) =
680 UncheckedExtrinsicBuilder::instantiate_with(code.clone(), data.clone())
681 .mutate_estimate_and_check(Box::new(|tx| {
682 tx.gas_price = Some(tx.gas_price.unwrap() * 103 / 100);
683 log::debug!(target: LOG_TARGET, "Gas price: {:?}", tx.gas_price);
684 }))
685 .unwrap();
686
687 assert_eq!(U256::from(extra.1.tip()), 0u32.into());
688 }
689
690 #[test]
691 fn check_runtime_pallets_addr_works() {
692 let remark: CallOf<Test> =
693 frame_system::Call::remark { remark: b"Hello, world!".to_vec() }.into();
694
695 let builder =
696 UncheckedExtrinsicBuilder::call_with(RUNTIME_PALLETS_ADDR).data(remark.encode());
697 let (_, call, _, _, _, _) = builder.check().unwrap();
698
699 match call {
700 RuntimeCall::Contracts(crate::Call::eth_substrate_call {
701 call: inner_call, ..
702 }) => {
703 assert_eq!(*inner_call, remark);
704 },
705 _ => panic!("Expected the RuntimeCall::Contracts variant, got: {:?}", call),
706 }
707 }
708}