revm-context 16.0.0

Revm context crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
//! This module contains [`TxEnv`] struct and implements [`Transaction`] trait for it.
use crate::TransactionType;
use context_interface::{
    either::Either,
    transaction::{
        AccessList, AccessListItem, Authorization, RecoveredAuthority, RecoveredAuthorization,
        SignedAuthorization, Transaction,
    },
};
use core::fmt::Debug;
use database_interface::{BENCH_CALLER, BENCH_TARGET};
use primitives::{eip7825, Address, Bytes, TxKind, B256, U256};
use std::{vec, vec::Vec};

/// The Transaction Environment is a struct that contains all fields that can be found in all Ethereum transaction,
/// including EIP-4844, EIP-7702, EIP-7873, etc.  It implements the [`Transaction`] trait, which is used inside the EVM to execute a transaction.
///
/// [`TxEnvBuilder`] builder is recommended way to create a new [`TxEnv`] as it will automatically
/// set the transaction type based on the fields set.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TxEnv {
    /// Transaction type
    pub tx_type: u8,
    /// Caller aka Author aka transaction signer
    pub caller: Address,
    /// The gas limit of the transaction.
    pub gas_limit: u64,
    /// The gas price of the transaction.
    ///
    /// For EIP-1559 transaction this represent max_gas_fee.
    pub gas_price: u128,
    /// The destination of the transaction
    pub kind: TxKind,
    /// The value sent to `transact_to`
    pub value: U256,
    /// The data of the transaction
    pub data: Bytes,

    /// The nonce of the transaction
    pub nonce: u64,

    /// The chain ID of the transaction
    ///
    /// Incorporated as part of the Spurious Dragon upgrade via [EIP-155].
    ///
    /// [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
    pub chain_id: Option<u64>,

    /// A list of addresses and storage keys that the transaction plans to access
    ///
    /// Added in [EIP-2930].
    ///
    /// [EIP-2930]: https://eips.ethereum.org/EIPS/eip-2930
    pub access_list: AccessList,

    /// The priority fee per gas
    ///
    /// Incorporated as part of the London upgrade via [EIP-1559].
    ///
    /// [EIP-1559]: https://eips.ethereum.org/EIPS/eip-1559
    pub gas_priority_fee: Option<u128>,

    /// The list of blob versioned hashes
    ///
    /// Per EIP there should be at least one blob present if [`max_fee_per_blob_gas`][Self::max_fee_per_blob_gas] is [`Some`].
    ///
    /// Incorporated as part of the Cancun upgrade via [EIP-4844].
    ///
    /// [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
    pub blob_hashes: Vec<B256>,

    /// The max fee per blob gas
    ///
    /// Incorporated as part of the Cancun upgrade via [EIP-4844].
    ///
    /// [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
    pub max_fee_per_blob_gas: u128,

    /// List of authorizations
    ///
    /// `authorization_list` contains the signature that authorizes this
    /// caller to place the code to signer account.
    ///
    /// Set EOA account code for one transaction via [EIP-7702].
    ///
    /// [EIP-7702]: https://eips.ethereum.org/EIPS/eip-7702
    pub authorization_list: Vec<Either<SignedAuthorization, RecoveredAuthorization>>,
}

impl Default for TxEnv {
    fn default() -> Self {
        Self::builder().build().unwrap()
    }
}

/// Error type for deriving transaction type used as error in [`TxEnv::derive_tx_type`] function.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DeriveTxTypeError {
    /// Missing target for EIP-4844
    MissingTargetForEip4844,
    /// Missing target for EIP-7702
    MissingTargetForEip7702,
    /// Missing target for EIP-7873
    MissingTargetForEip7873,
}

impl core::fmt::Display for DeriveTxTypeError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let s = match self {
            Self::MissingTargetForEip4844 => "missing target for EIP-4844",
            Self::MissingTargetForEip7702 => "missing target for EIP-7702",
            Self::MissingTargetForEip7873 => "missing target for EIP-7873",
        };
        f.write_str(s)
    }
}

impl core::error::Error for DeriveTxTypeError {}

impl TxEnv {
    /// Creates a new TxEnv with benchmark-specific values.
    pub fn new_bench() -> Self {
        Self {
            caller: BENCH_CALLER,
            kind: TxKind::Call(BENCH_TARGET),
            gas_limit: 1_000_000_000,
            ..Default::default()
        }
    }

    /// Derives tx type from transaction fields and sets it to `tx_type`.
    /// Returns error in case some fields were not set correctly.
    pub fn derive_tx_type(&mut self) -> Result<(), DeriveTxTypeError> {
        if !self.access_list.0.is_empty() {
            self.tx_type = TransactionType::Eip2930 as u8;
        }

        if self.gas_priority_fee.is_some() {
            self.tx_type = TransactionType::Eip1559 as u8;
        }

        if !self.blob_hashes.is_empty() || self.max_fee_per_blob_gas > 0 {
            if let TxKind::Call(_) = self.kind {
                self.tx_type = TransactionType::Eip4844 as u8;
                return Ok(());
            } else {
                return Err(DeriveTxTypeError::MissingTargetForEip4844);
            }
        }

        if !self.authorization_list.is_empty() {
            if let TxKind::Call(_) = self.kind {
                self.tx_type = TransactionType::Eip7702 as u8;
                return Ok(());
            } else {
                return Err(DeriveTxTypeError::MissingTargetForEip7702);
            }
        }
        Ok(())
    }

    /// Insert a list of signed authorizations into the authorization list.
    pub fn set_signed_authorization(&mut self, auth: Vec<SignedAuthorization>) {
        self.authorization_list = auth.into_iter().map(Either::Left).collect();
    }

    /// Insert a list of recovered authorizations into the authorization list.
    pub fn set_recovered_authorization(&mut self, auth: Vec<RecoveredAuthorization>) {
        self.authorization_list = auth.into_iter().map(Either::Right).collect();
    }
}

impl Transaction for TxEnv {
    type AccessListItem<'a> = &'a AccessListItem;
    type Authorization<'a> = &'a Either<SignedAuthorization, RecoveredAuthorization>;

    fn tx_type(&self) -> u8 {
        self.tx_type
    }

    fn kind(&self) -> TxKind {
        self.kind
    }

    fn caller(&self) -> Address {
        self.caller
    }

    fn gas_limit(&self) -> u64 {
        self.gas_limit
    }

    fn gas_price(&self) -> u128 {
        self.gas_price
    }

    fn value(&self) -> U256 {
        self.value
    }

    fn nonce(&self) -> u64 {
        self.nonce
    }

    fn chain_id(&self) -> Option<u64> {
        self.chain_id
    }

    fn access_list(&self) -> Option<impl Iterator<Item = Self::AccessListItem<'_>>> {
        Some(self.access_list.0.iter())
    }

    fn max_fee_per_gas(&self) -> u128 {
        self.gas_price
    }

    fn max_fee_per_blob_gas(&self) -> u128 {
        self.max_fee_per_blob_gas
    }

    fn authorization_list_len(&self) -> usize {
        self.authorization_list.len()
    }

    fn authorization_list(&self) -> impl Iterator<Item = Self::Authorization<'_>> {
        self.authorization_list.iter()
    }

    fn input(&self) -> &Bytes {
        &self.data
    }

    fn blob_versioned_hashes(&self) -> &[B256] {
        &self.blob_hashes
    }

    fn max_priority_fee_per_gas(&self) -> Option<u128> {
        self.gas_priority_fee
    }
}

/// Builder for constructing [`TxEnv`] instances
#[derive(Default, Debug)]
pub struct TxEnvBuilder {
    tx_type: Option<u8>,
    caller: Address,
    gas_limit: u64,
    gas_price: u128,
    kind: TxKind,
    value: U256,
    data: Bytes,
    nonce: u64,
    chain_id: Option<u64>,
    access_list: AccessList,
    gas_priority_fee: Option<u128>,
    blob_hashes: Vec<B256>,
    max_fee_per_blob_gas: u128,
    authorization_list: Vec<Either<SignedAuthorization, RecoveredAuthorization>>,
}

impl TxEnvBuilder {
    /// Create a new builder with default values
    pub fn new() -> Self {
        Self {
            tx_type: None,
            caller: Address::default(),
            gas_limit: eip7825::TX_GAS_LIMIT_CAP,
            gas_price: 0,
            kind: TxKind::Call(Address::default()),
            value: U256::ZERO,
            data: Bytes::default(),
            nonce: 0,
            chain_id: Some(1), // Mainnet chain ID is 1
            access_list: Default::default(),
            gas_priority_fee: None,
            blob_hashes: Vec::new(),
            max_fee_per_blob_gas: 0,
            authorization_list: Vec::new(),
        }
    }

    /// Set the transaction type
    pub fn tx_type(mut self, tx_type: Option<u8>) -> Self {
        self.tx_type = tx_type;
        self
    }

    /// Get the transaction type
    pub fn get_tx_type(&self) -> Option<u8> {
        self.tx_type
    }

    /// Set the caller address
    pub fn caller(mut self, caller: Address) -> Self {
        self.caller = caller;
        self
    }

    /// Set the gas limit
    pub fn gas_limit(mut self, gas_limit: u64) -> Self {
        self.gas_limit = gas_limit;
        self
    }

    /// Set the max fee per gas.
    pub fn max_fee_per_gas(mut self, max_fee_per_gas: u128) -> Self {
        self.gas_price = max_fee_per_gas;
        self
    }

    /// Set the gas price
    pub fn gas_price(mut self, gas_price: u128) -> Self {
        self.gas_price = gas_price;
        self
    }

    /// Set the transaction kind
    pub fn kind(mut self, kind: TxKind) -> Self {
        self.kind = kind;
        self
    }

    /// Set the transaction kind to call
    pub fn call(mut self, target: Address) -> Self {
        self.kind = TxKind::Call(target);
        self
    }

    /// Set the transaction kind to create
    pub fn create(mut self) -> Self {
        self.kind = TxKind::Create;
        self
    }

    /// Set the transaction kind to create
    pub fn to(self, target: Address) -> Self {
        self.call(target)
    }

    /// Set the transaction value
    pub fn value(mut self, value: U256) -> Self {
        self.value = value;
        self
    }

    /// Set the transaction data
    pub fn data(mut self, data: Bytes) -> Self {
        self.data = data;
        self
    }

    /// Set the transaction nonce
    pub fn nonce(mut self, nonce: u64) -> Self {
        self.nonce = nonce;
        self
    }

    /// Set the chain ID
    pub fn chain_id(mut self, chain_id: Option<u64>) -> Self {
        self.chain_id = chain_id;
        self
    }

    /// Set the access list
    pub fn access_list(mut self, access_list: AccessList) -> Self {
        self.access_list = access_list;
        self
    }

    /// Set the gas priority fee
    pub fn gas_priority_fee(mut self, gas_priority_fee: Option<u128>) -> Self {
        self.gas_priority_fee = gas_priority_fee;
        self
    }

    /// Set the blob hashes
    pub fn blob_hashes(mut self, blob_hashes: Vec<B256>) -> Self {
        self.blob_hashes = blob_hashes;
        self
    }

    /// Set the max fee per blob gas
    pub fn max_fee_per_blob_gas(mut self, max_fee_per_blob_gas: u128) -> Self {
        self.max_fee_per_blob_gas = max_fee_per_blob_gas;
        self
    }

    /// Set the authorization list
    pub fn authorization_list(
        mut self,
        authorization_list: Vec<Either<SignedAuthorization, RecoveredAuthorization>>,
    ) -> Self {
        self.authorization_list = authorization_list;
        self
    }

    /// Insert a list of signed authorizations into the authorization list.
    pub fn authorization_list_signed(mut self, auth: Vec<SignedAuthorization>) -> Self {
        self.authorization_list = auth.into_iter().map(Either::Left).collect();
        self
    }

    /// Insert a list of recovered authorizations into the authorization list.
    pub fn authorization_list_recovered(mut self, auth: Vec<RecoveredAuthorization>) -> Self {
        self.authorization_list = auth.into_iter().map(Either::Right).collect();
        self
    }

    /// Build the final [`TxEnv`] with default values for missing fields.
    pub fn build_fill(mut self) -> TxEnv {
        if let Some(tx_type) = self.tx_type {
            match TransactionType::from(tx_type) {
                TransactionType::Legacy => {
                    // do nothing
                }
                TransactionType::Eip2930 => {
                    // do nothing, all fields are set. Access list can be empty.
                }
                TransactionType::Eip1559 => {
                    // gas priority fee is required
                    if self.gas_priority_fee.is_none() {
                        self.gas_priority_fee = Some(0);
                    }
                }
                TransactionType::Eip4844 => {
                    // gas priority fee is required
                    if self.gas_priority_fee.is_none() {
                        self.gas_priority_fee = Some(0);
                    }

                    // blob hashes can be empty
                    if self.blob_hashes.is_empty() {
                        self.blob_hashes = vec![B256::default()];
                    }

                    // target is required
                    if !self.kind.is_call() {
                        self.kind = TxKind::Call(Address::default());
                    }
                }
                TransactionType::Eip7702 => {
                    // gas priority fee is required
                    if self.gas_priority_fee.is_none() {
                        self.gas_priority_fee = Some(0);
                    }

                    // authorization list can be empty
                    if self.authorization_list.is_empty() {
                        // add dummy authorization
                        self.authorization_list =
                            vec![Either::Right(RecoveredAuthorization::new_unchecked(
                                Authorization {
                                    chain_id: U256::from(self.chain_id.unwrap_or(1)),
                                    address: self.caller,
                                    nonce: self.nonce,
                                },
                                RecoveredAuthority::Invalid,
                            ))];
                    }

                    // target is required
                    if !self.kind.is_call() {
                        self.kind = TxKind::Call(Address::default());
                    }
                }
                TransactionType::Custom => {
                    // do nothing
                }
            }
        }

        let mut tx = TxEnv {
            tx_type: self.tx_type.unwrap_or(0),
            caller: self.caller,
            gas_limit: self.gas_limit,
            gas_price: self.gas_price,
            kind: self.kind,
            value: self.value,
            data: self.data,
            nonce: self.nonce,
            chain_id: self.chain_id,
            access_list: self.access_list,
            gas_priority_fee: self.gas_priority_fee,
            blob_hashes: self.blob_hashes,
            max_fee_per_blob_gas: self.max_fee_per_blob_gas,
            authorization_list: self.authorization_list,
        };

        // if tx_type is not set, derive it from fields and fix errors.
        if self.tx_type.is_none() {
            match tx.derive_tx_type() {
                Ok(_) => {}
                Err(DeriveTxTypeError::MissingTargetForEip4844) => {
                    tx.kind = TxKind::Call(Address::default());
                }
                Err(DeriveTxTypeError::MissingTargetForEip7702) => {
                    tx.kind = TxKind::Call(Address::default());
                }
                Err(DeriveTxTypeError::MissingTargetForEip7873) => {
                    tx.kind = TxKind::Call(Address::default());
                }
            }
        }

        tx
    }

    /// Build the final [`TxEnv`], returns error if some fields are wrongly set.
    /// If it is fine to fill missing fields with default values, use [`TxEnvBuilder::build_fill`] instead.
    pub fn build(self) -> Result<TxEnv, TxEnvBuildError> {
        // if tx_type is set, check if all needed fields are set correctly.
        if let Some(tx_type) = self.tx_type {
            match TransactionType::from(tx_type) {
                TransactionType::Legacy => {
                    // do nothing
                }
                TransactionType::Eip2930 => {
                    // do nothing, all fields are set. Access list can be empty.
                }
                TransactionType::Eip1559 => {
                    // gas priority fee is required
                    if self.gas_priority_fee.is_none() {
                        return Err(TxEnvBuildError::MissingGasPriorityFeeForEip1559);
                    }
                }
                TransactionType::Eip4844 => {
                    // gas priority fee is required
                    if self.gas_priority_fee.is_none() {
                        return Err(TxEnvBuildError::MissingGasPriorityFeeForEip1559);
                    }

                    // blob hashes can be empty
                    if self.blob_hashes.is_empty() {
                        return Err(TxEnvBuildError::MissingBlobHashesForEip4844);
                    }

                    // target is required
                    if !self.kind.is_call() {
                        return Err(TxEnvBuildError::MissingTargetForEip4844);
                    }
                }
                TransactionType::Eip7702 => {
                    // gas priority fee is required
                    if self.gas_priority_fee.is_none() {
                        return Err(TxEnvBuildError::MissingGasPriorityFeeForEip1559);
                    }

                    // authorization list can be empty
                    if self.authorization_list.is_empty() {
                        return Err(TxEnvBuildError::MissingAuthorizationListForEip7702);
                    }

                    // target is required
                    if !self.kind.is_call() {
                        return Err(DeriveTxTypeError::MissingTargetForEip7702.into());
                    }
                }
                TransactionType::Custom => {
                    // do nothing, custom transaction type is handled by the caller.
                }
            }
        }

        let mut tx = TxEnv {
            tx_type: self.tx_type.unwrap_or(0),
            caller: self.caller,
            gas_limit: self.gas_limit,
            gas_price: self.gas_price,
            kind: self.kind,
            value: self.value,
            data: self.data,
            nonce: self.nonce,
            chain_id: self.chain_id,
            access_list: self.access_list,
            gas_priority_fee: self.gas_priority_fee,
            blob_hashes: self.blob_hashes,
            max_fee_per_blob_gas: self.max_fee_per_blob_gas,
            authorization_list: self.authorization_list,
        };

        // Derive tx type from fields, if some fields are wrongly set it will return an error.
        if self.tx_type.is_none() {
            tx.derive_tx_type()?;
        }

        Ok(tx)
    }
}

/// Error type for building [`TxEnv`]
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TxEnvBuildError {
    /// Derive tx type error
    DeriveErr(DeriveTxTypeError),
    /// Missing priority fee for EIP-1559
    MissingGasPriorityFeeForEip1559,
    /// Missing blob hashes for EIP-4844
    MissingBlobHashesForEip4844,
    /// Missing authorization list for EIP-7702
    MissingAuthorizationListForEip7702,
    /// Missing target for EIP-4844
    MissingTargetForEip4844,
}

impl core::fmt::Display for TxEnvBuildError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::DeriveErr(err) => write!(f, "derive tx type error: {err}"),
            Self::MissingGasPriorityFeeForEip1559 => {
                f.write_str("missing gas priority fee for EIP-1559")
            }
            Self::MissingBlobHashesForEip4844 => f.write_str("missing blob hashes for EIP-4844"),
            Self::MissingAuthorizationListForEip7702 => {
                f.write_str("missing authorization list for EIP-7702")
            }
            Self::MissingTargetForEip4844 => f.write_str("missing target for EIP-4844"),
        }
    }
}

impl core::error::Error for TxEnvBuildError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::DeriveErr(err) => Some(err),
            _ => None,
        }
    }
}

impl From<DeriveTxTypeError> for TxEnvBuildError {
    fn from(error: DeriveTxTypeError) -> Self {
        TxEnvBuildError::DeriveErr(error)
    }
}

impl TxEnv {
    /// Create a new builder for constructing a [`TxEnv`]
    pub fn builder() -> TxEnvBuilder {
        TxEnvBuilder::new()
    }

    /// Create a new builder for constructing a [`TxEnv`] with benchmark-specific values.
    pub fn builder_for_bench() -> TxEnvBuilder {
        TxEnv::new_bench().modify()
    }

    /// Modify the [`TxEnv`] by using builder pattern.
    pub fn modify(self) -> TxEnvBuilder {
        let TxEnv {
            tx_type,
            caller,
            gas_limit,
            gas_price,
            kind,
            value,
            data,
            nonce,
            chain_id,
            access_list,
            gas_priority_fee,
            blob_hashes,
            max_fee_per_blob_gas,
            authorization_list,
        } = self;

        TxEnvBuilder::new()
            .tx_type(Some(tx_type))
            .caller(caller)
            .gas_limit(gas_limit)
            .gas_price(gas_price)
            .kind(kind)
            .value(value)
            .data(data)
            .nonce(nonce)
            .chain_id(chain_id)
            .access_list(access_list)
            .gas_priority_fee(gas_priority_fee)
            .blob_hashes(blob_hashes)
            .max_fee_per_blob_gas(max_fee_per_blob_gas)
            .authorization_list(authorization_list)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn effective_gas_setup(
        tx_type: TransactionType,
        gas_price: u128,
        gas_priority_fee: Option<u128>,
    ) -> u128 {
        let tx = TxEnv {
            tx_type: tx_type as u8,
            gas_price,
            gas_priority_fee,
            ..Default::default()
        };
        let base_fee = 100;
        tx.effective_gas_price(base_fee)
    }

    #[test]
    fn test_tx_env_builder_build_valid_legacy() {
        // Legacy transaction
        let tx = TxEnvBuilder::new()
            .tx_type(Some(0))
            .caller(Address::from([1u8; 20]))
            .gas_limit(21000)
            .gas_price(20)
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .value(U256::from(100))
            .data(Bytes::from(vec![0x01, 0x02]))
            .nonce(5)
            .chain_id(Some(1))
            .build()
            .unwrap();

        assert_eq!(tx.kind, TxKind::Call(Address::from([2u8; 20])));
        assert_eq!(tx.caller, Address::from([1u8; 20]));
        assert_eq!(tx.gas_limit, 21000);
        assert_eq!(tx.gas_price, 20);
        assert_eq!(tx.value, U256::from(100));
        assert_eq!(tx.data, Bytes::from(vec![0x01, 0x02]));
        assert_eq!(tx.nonce, 5);
        assert_eq!(tx.chain_id, Some(1));
        assert_eq!(tx.tx_type, TransactionType::Legacy);
    }

    #[test]
    fn test_tx_env_builder_build_valid_eip2930() {
        // EIP-2930 transaction with access list
        let access_list = AccessList(vec![AccessListItem {
            address: Address::from([3u8; 20]),
            storage_keys: vec![B256::from([4u8; 32])],
        }]);
        let tx = TxEnvBuilder::new()
            .tx_type(Some(1))
            .caller(Address::from([1u8; 20]))
            .gas_limit(50000)
            .gas_price(25)
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .access_list(access_list.clone())
            .build()
            .unwrap();

        assert_eq!(tx.tx_type, TransactionType::Eip2930);
        assert_eq!(tx.access_list, access_list);
    }

    #[test]
    fn test_tx_env_builder_build_valid_eip1559() {
        // EIP-1559 transaction
        let tx = TxEnvBuilder::new()
            .tx_type(Some(2))
            .caller(Address::from([1u8; 20]))
            .gas_limit(50000)
            .gas_price(30)
            .gas_priority_fee(Some(10))
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .build()
            .unwrap();

        assert_eq!(tx.tx_type, TransactionType::Eip1559);
        assert_eq!(tx.gas_priority_fee, Some(10));
    }

    #[test]
    fn test_tx_env_builder_build_valid_eip4844() {
        // EIP-4844 blob transaction
        let blob_hashes = vec![B256::from([5u8; 32]), B256::from([6u8; 32])];
        let tx = TxEnvBuilder::new()
            .tx_type(Some(3))
            .caller(Address::from([1u8; 20]))
            .gas_limit(50000)
            .gas_price(30)
            .gas_priority_fee(Some(10))
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .blob_hashes(blob_hashes.clone())
            .max_fee_per_blob_gas(100)
            .build()
            .unwrap();

        assert_eq!(tx.tx_type, TransactionType::Eip4844);
        assert_eq!(tx.blob_hashes, blob_hashes);
        assert_eq!(tx.max_fee_per_blob_gas, 100);
    }

    #[test]
    fn test_tx_env_builder_build_valid_eip7702() {
        // EIP-7702 EOA code transaction
        let auth = RecoveredAuthorization::new_unchecked(
            Authorization {
                chain_id: U256::from(1),
                nonce: 0,
                address: Address::default(),
            },
            RecoveredAuthority::Valid(Address::default()),
        );
        let auth_list = vec![Either::Right(auth)];

        let tx = TxEnvBuilder::new()
            .tx_type(Some(4))
            .caller(Address::from([1u8; 20]))
            .gas_limit(50000)
            .gas_price(30)
            .gas_priority_fee(Some(10))
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .authorization_list(auth_list.clone())
            .build()
            .unwrap();

        assert_eq!(tx.tx_type, TransactionType::Eip7702);
        assert_eq!(tx.authorization_list.len(), 1);
    }

    #[test]
    fn test_tx_env_builder_build_create_transaction() {
        // Contract creation transaction
        let bytecode = Bytes::from(vec![0x60, 0x80, 0x60, 0x40]);
        let tx = TxEnvBuilder::new()
            .kind(TxKind::Create)
            .data(bytecode.clone())
            .gas_limit(100000)
            .gas_price(20)
            .build()
            .unwrap();

        assert_eq!(tx.kind, TxKind::Create);
        assert_eq!(tx.data, bytecode);
    }

    #[test]
    fn test_tx_env_builder_build_errors_eip1559_missing_priority_fee() {
        // EIP-1559 without gas_priority_fee should fail
        let result = TxEnvBuilder::new()
            .tx_type(Some(2))
            .caller(Address::from([1u8; 20]))
            .gas_limit(50000)
            .gas_price(30)
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .build();

        assert!(matches!(
            result,
            Err(TxEnvBuildError::MissingGasPriorityFeeForEip1559)
        ));
    }

    #[test]
    fn test_tx_env_builder_build_errors_eip4844_missing_blob_hashes() {
        // EIP-4844 without blob hashes should fail
        let result = TxEnvBuilder::new()
            .tx_type(Some(3))
            .gas_priority_fee(Some(10))
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .build();

        assert!(matches!(
            result,
            Err(TxEnvBuildError::MissingBlobHashesForEip4844)
        ));
    }

    #[test]
    fn test_tx_env_builder_build_errors_eip4844_not_call() {
        // EIP-4844 with Create should fail
        let result = TxEnvBuilder::new()
            .tx_type(Some(3))
            .gas_priority_fee(Some(10))
            .blob_hashes(vec![B256::from([5u8; 32])])
            .kind(TxKind::Create)
            .build();

        assert!(matches!(
            result,
            Err(TxEnvBuildError::MissingTargetForEip4844)
        ));
    }

    #[test]
    fn test_tx_env_builder_build_errors_eip7702_missing_auth_list() {
        // EIP-7702 without authorization list should fail
        let result = TxEnvBuilder::new()
            .tx_type(Some(4))
            .gas_priority_fee(Some(10))
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .build();

        assert!(matches!(
            result,
            Err(TxEnvBuildError::MissingAuthorizationListForEip7702)
        ));
    }

    #[test]
    fn test_tx_env_builder_build_errors_eip7702_not_call() {
        // EIP-7702 with Create should fail
        let auth = RecoveredAuthorization::new_unchecked(
            Authorization {
                chain_id: U256::from(1),
                nonce: 0,
                address: Address::default(),
            },
            RecoveredAuthority::Valid(Address::default()),
        );
        let result = TxEnvBuilder::new()
            .tx_type(Some(4))
            .gas_priority_fee(Some(10))
            .authorization_list(vec![Either::Right(auth)])
            .kind(TxKind::Create)
            .build();

        assert!(matches!(result, Err(TxEnvBuildError::DeriveErr(_))));
    }

    #[test]
    fn test_tx_env_builder_build_fill_legacy() {
        // Legacy transaction with build_fill
        let tx = TxEnvBuilder::new()
            .caller(Address::from([1u8; 20]))
            .gas_limit(21000)
            .gas_price(20)
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .build_fill();

        assert_eq!(tx.tx_type, TransactionType::Legacy);
        assert_eq!(tx.gas_priority_fee, None);
    }

    #[test]
    fn test_tx_env_builder_build_fill_eip1559_missing_priority_fee() {
        // EIP-1559 without gas_priority_fee should be filled with 0
        let tx = TxEnvBuilder::new()
            .tx_type(Some(2))
            .caller(Address::from([1u8; 20]))
            .gas_limit(50000)
            .gas_price(30)
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .build_fill();

        assert_eq!(tx.tx_type, TransactionType::Eip1559);
        assert_eq!(tx.gas_priority_fee, Some(0));
    }

    #[test]
    fn test_tx_env_builder_build_fill_eip4844_missing_blob_hashes() {
        // EIP-4844 without blob hashes should add default blob hash
        let tx = TxEnvBuilder::new()
            .tx_type(Some(3))
            .gas_priority_fee(Some(10))
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .build_fill();

        assert_eq!(tx.tx_type, TransactionType::Eip4844);
        assert_eq!(tx.blob_hashes.len(), 1);
        assert_eq!(tx.blob_hashes[0], B256::default());
    }

    #[test]
    fn test_tx_env_builder_build_fill_eip4844_create_to_call() {
        // EIP-4844 with Create should be converted to Call
        let tx = TxEnvBuilder::new()
            .tx_type(Some(3))
            .gas_priority_fee(Some(10))
            .blob_hashes(vec![B256::from([5u8; 32])])
            .kind(TxKind::Create)
            .build_fill();

        assert_eq!(tx.tx_type, TransactionType::Eip4844);
        assert_eq!(tx.kind, TxKind::Call(Address::default()));
    }

    #[test]
    fn test_tx_env_builder_build_fill_eip7702_missing_auth_list() {
        // EIP-7702 without authorization list should add dummy auth
        let tx = TxEnvBuilder::new()
            .tx_type(Some(4))
            .gas_priority_fee(Some(10))
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .build_fill();

        assert_eq!(tx.tx_type, TransactionType::Eip7702);
        assert_eq!(tx.authorization_list.len(), 1);
    }

    #[test]
    fn test_tx_env_builder_build_fill_eip7702_create_to_call() {
        // EIP-7702 with Create should be converted to Call
        let auth = RecoveredAuthorization::new_unchecked(
            Authorization {
                chain_id: U256::from(1),
                nonce: 0,
                address: Address::default(),
            },
            RecoveredAuthority::Valid(Address::default()),
        );
        let tx = TxEnvBuilder::new()
            .tx_type(Some(4))
            .gas_priority_fee(Some(10))
            .authorization_list(vec![Either::Right(auth)])
            .kind(TxKind::Create)
            .build_fill();

        assert_eq!(tx.tx_type, TransactionType::Eip7702);
        assert_eq!(tx.kind, TxKind::Call(Address::default()));
    }

    #[test]
    fn test_tx_env_builder_derive_tx_type_legacy() {
        // No special fields, should derive Legacy
        let tx = TxEnvBuilder::new()
            .caller(Address::from([1u8; 20]))
            .gas_limit(21000)
            .gas_price(20)
            .build()
            .unwrap();

        assert_eq!(tx.tx_type, TransactionType::Legacy);
    }

    #[test]
    fn test_tx_env_builder_derive_tx_type_eip2930() {
        // Access list present, should derive EIP-2930
        let access_list = AccessList(vec![AccessListItem {
            address: Address::from([3u8; 20]),
            storage_keys: vec![B256::from([4u8; 32])],
        }]);
        let tx = TxEnvBuilder::new()
            .caller(Address::from([1u8; 20]))
            .access_list(access_list)
            .build()
            .unwrap();

        assert_eq!(tx.tx_type, TransactionType::Eip2930);
    }

    #[test]
    fn test_tx_env_builder_derive_tx_type_eip1559() {
        // Gas priority fee present, should derive EIP-1559
        let tx = TxEnvBuilder::new()
            .caller(Address::from([1u8; 20]))
            .gas_priority_fee(Some(10))
            .build()
            .unwrap();

        assert_eq!(tx.tx_type, TransactionType::Eip1559);
    }

    #[test]
    fn test_tx_env_builder_derive_tx_type_eip4844() {
        // Blob hashes present, should derive EIP-4844
        let tx = TxEnvBuilder::new()
            .caller(Address::from([1u8; 20]))
            .gas_priority_fee(Some(10))
            .blob_hashes(vec![B256::from([5u8; 32])])
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .build()
            .unwrap();

        assert_eq!(tx.tx_type, TransactionType::Eip4844);
    }

    #[test]
    fn test_tx_env_builder_derive_tx_type_eip7702() {
        // Authorization list present, should derive EIP-7702
        let auth = RecoveredAuthorization::new_unchecked(
            Authorization {
                chain_id: U256::from(1),
                nonce: 0,
                address: Address::default(),
            },
            RecoveredAuthority::Valid(Address::default()),
        );
        let tx = TxEnvBuilder::new()
            .caller(Address::from([1u8; 20]))
            .gas_priority_fee(Some(10))
            .authorization_list(vec![Either::Right(auth)])
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .build()
            .unwrap();

        assert_eq!(tx.tx_type, TransactionType::Eip7702);
    }

    #[test]
    fn test_tx_env_builder_custom_tx_type() {
        // Custom transaction type (0xFF)
        let tx = TxEnvBuilder::new()
            .tx_type(Some(0xFF))
            .caller(Address::from([1u8; 20]))
            .build()
            .unwrap();

        assert_eq!(tx.tx_type, TransactionType::Custom);
    }

    #[test]
    fn test_tx_env_builder_chain_methods() {
        // Test method chaining
        let tx = TxEnvBuilder::new()
            .caller(Address::from([1u8; 20]))
            .gas_limit(50000)
            .gas_price(25)
            .kind(TxKind::Call(Address::from([2u8; 20])))
            .value(U256::from(1000))
            .data(Bytes::from(vec![0x12, 0x34]))
            .nonce(10)
            .chain_id(Some(5))
            .access_list(AccessList(vec![AccessListItem {
                address: Address::from([3u8; 20]),
                storage_keys: vec![],
            }]))
            .gas_priority_fee(Some(5))
            .blob_hashes(vec![B256::from([7u8; 32])])
            .max_fee_per_blob_gas(200)
            .build_fill();

        assert_eq!(tx.caller, Address::from([1u8; 20]));
        assert_eq!(tx.gas_limit, 50000);
        assert_eq!(tx.gas_price, 25);
        assert_eq!(tx.kind, TxKind::Call(Address::from([2u8; 20])));
        assert_eq!(tx.value, U256::from(1000));
        assert_eq!(tx.data, Bytes::from(vec![0x12, 0x34]));
        assert_eq!(tx.nonce, 10);
        assert_eq!(tx.chain_id, Some(5));
        assert_eq!(tx.access_list.len(), 1);
        assert_eq!(tx.gas_priority_fee, Some(5));
        assert_eq!(tx.blob_hashes.len(), 1);
        assert_eq!(tx.max_fee_per_blob_gas, 200);
    }

    #[test]
    fn test_effective_gas_price() {
        assert_eq!(90, effective_gas_setup(TransactionType::Legacy, 90, None));
        assert_eq!(
            90,
            effective_gas_setup(TransactionType::Legacy, 90, Some(0))
        );
        assert_eq!(
            90,
            effective_gas_setup(TransactionType::Legacy, 90, Some(10))
        );
        assert_eq!(
            120,
            effective_gas_setup(TransactionType::Legacy, 120, Some(10))
        );
        assert_eq!(90, effective_gas_setup(TransactionType::Eip2930, 90, None));
        assert_eq!(
            90,
            effective_gas_setup(TransactionType::Eip2930, 90, Some(0))
        );
        assert_eq!(
            90,
            effective_gas_setup(TransactionType::Eip2930, 90, Some(10))
        );
        assert_eq!(
            120,
            effective_gas_setup(TransactionType::Eip2930, 120, Some(10))
        );
        assert_eq!(90, effective_gas_setup(TransactionType::Eip1559, 90, None));
        assert_eq!(
            90,
            effective_gas_setup(TransactionType::Eip1559, 90, Some(0))
        );
        assert_eq!(
            90,
            effective_gas_setup(TransactionType::Eip1559, 90, Some(10))
        );
        assert_eq!(
            110,
            effective_gas_setup(TransactionType::Eip1559, 120, Some(10))
        );
        assert_eq!(90, effective_gas_setup(TransactionType::Eip4844, 90, None));
        assert_eq!(
            90,
            effective_gas_setup(TransactionType::Eip4844, 90, Some(0))
        );
        assert_eq!(
            90,
            effective_gas_setup(TransactionType::Eip4844, 90, Some(10))
        );
        assert_eq!(
            110,
            effective_gas_setup(TransactionType::Eip4844, 120, Some(10))
        );
        assert_eq!(90, effective_gas_setup(TransactionType::Eip7702, 90, None));
        assert_eq!(
            90,
            effective_gas_setup(TransactionType::Eip7702, 90, Some(0))
        );
        assert_eq!(
            90,
            effective_gas_setup(TransactionType::Eip7702, 90, Some(10))
        );
        assert_eq!(
            110,
            effective_gas_setup(TransactionType::Eip7702, 120, Some(10))
        );
    }
}