reth_transaction_pool/test_utils/
mock.rs

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
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
//! Mock types.

use crate::{
    identifier::{SenderIdentifiers, TransactionId},
    pool::txpool::TxPool,
    traits::TransactionOrigin,
    CoinbaseTipOrdering, EthBlobTransactionSidecar, EthPoolTransaction, PoolTransaction,
    ValidPoolTransaction,
};
use alloy_consensus::{
    constants::{
        EIP1559_TX_TYPE_ID, EIP2930_TX_TYPE_ID, EIP4844_TX_TYPE_ID, EIP7702_TX_TYPE_ID,
        LEGACY_TX_TYPE_ID,
    },
    TxEip1559, TxEip2930, TxEip4844, TxEip7702, TxLegacy, Typed2718,
};
use alloy_eips::{
    eip1559::MIN_PROTOCOL_BASE_FEE,
    eip2930::AccessList,
    eip4844::{BlobTransactionSidecar, BlobTransactionValidationError, DATA_GAS_PER_BLOB},
    eip7702::SignedAuthorization,
};
use alloy_primitives::{
    Address, Bytes, ChainId, PrimitiveSignature as Signature, TxHash, TxKind, B256, U256,
};
use paste::paste;
use rand::{
    distributions::{Uniform, WeightedIndex},
    prelude::Distribution,
};
use reth_primitives::{
    transaction::{SignedTransactionIntoRecoveredExt, TryFromRecoveredTransactionError},
    PooledTransaction, PooledTransactionsElementEcRecovered, RecoveredTx, Transaction,
    TransactionSigned, TxType,
};
use reth_primitives_traits::InMemorySize;
use std::{ops::Range, sync::Arc, time::Instant, vec::IntoIter};

/// A transaction pool implementation using [`MockOrdering`] for transaction ordering.
///
/// This type is an alias for [`TxPool<MockOrdering>`].
pub type MockTxPool = TxPool<MockOrdering>;

/// A validated transaction in the transaction pool, using [`MockTransaction`] as the transaction
/// type.
///
/// This type is an alias for [`ValidPoolTransaction<MockTransaction>`].
pub type MockValidTx = ValidPoolTransaction<MockTransaction>;

/// Create an empty `TxPool`
pub fn mock_tx_pool() -> MockTxPool {
    MockTxPool::new(Default::default(), Default::default())
}

/// Sets the value for the field
macro_rules! set_value {
    ($this:ident => $field:ident) => {
        let new_value = $field;
        match $this {
            MockTransaction::Legacy { ref mut $field, .. } |
            MockTransaction::Eip1559 { ref mut $field, .. } |
            MockTransaction::Eip4844 { ref mut $field, .. } |
            MockTransaction::Eip2930 { ref mut $field, .. } |
            MockTransaction::Eip7702 { ref mut $field, .. } => {
                *$field = new_value;
            }
        }
        // Ensure the tx cost is always correct after each mutation.
        $this.update_cost();
    };
}

/// Gets the value for the field
macro_rules! get_value {
    ($this:tt => $field:ident) => {
        match $this {
            MockTransaction::Legacy { $field, .. } |
            MockTransaction::Eip1559 { $field, .. } |
            MockTransaction::Eip4844 { $field, .. } |
            MockTransaction::Eip2930 { $field, .. } |
            MockTransaction::Eip7702 { $field, .. } => $field,
        }
    };
}

// Generates all setters and getters
macro_rules! make_setters_getters {
    ($($name:ident => $t:ty);*) => {
        paste! {$(
            /// Sets the value of the specified field.
            pub fn [<set_ $name>](&mut self, $name: $t) -> &mut Self {
                set_value!(self => $name);
                self
            }

            /// Sets the value of the specified field using a fluent interface.
            pub fn [<with_ $name>](mut self, $name: $t) -> Self {
                set_value!(self => $name);
                self
            }

            /// Gets the value of the specified field.
            pub const fn [<get_ $name>](&self) -> &$t {
                get_value!(self => $name)
            }
        )*}
    };
}

/// A Bare transaction type used for testing.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum MockTransaction {
    /// Legacy transaction type.
    Legacy {
        /// The chain id of the transaction.
        chain_id: Option<ChainId>,
        /// The hash of the transaction.
        hash: B256,
        /// The sender's address.
        sender: Address,
        /// The transaction nonce.
        nonce: u64,
        /// The gas price for the transaction.
        gas_price: u128,
        /// The gas limit for the transaction.
        gas_limit: u64,
        /// The transaction's destination.
        to: TxKind,
        /// The value of the transaction.
        value: U256,
        /// The transaction input data.
        input: Bytes,
        /// The size of the transaction, returned in the implementation of [`PoolTransaction`].
        size: usize,
        /// The cost of the transaction, returned in the implementation of [`PoolTransaction`].
        cost: U256,
    },
    /// EIP-2930 transaction type.
    Eip2930 {
        /// The chain id of the transaction.
        chain_id: ChainId,
        /// The hash of the transaction.
        hash: B256,
        /// The sender's address.
        sender: Address,
        /// The transaction nonce.
        nonce: u64,
        /// The transaction's destination.
        to: TxKind,
        /// The gas limit for the transaction.
        gas_limit: u64,
        /// The transaction input data.
        input: Bytes,
        /// The value of the transaction.
        value: U256,
        /// The gas price for the transaction.
        gas_price: u128,
        /// The access list associated with the transaction.
        access_list: AccessList,
        /// The size of the transaction, returned in the implementation of [`PoolTransaction`].
        size: usize,
        /// The cost of the transaction, returned in the implementation of [`PoolTransaction`].
        cost: U256,
    },
    /// EIP-1559 transaction type.
    Eip1559 {
        /// The chain id of the transaction.
        chain_id: ChainId,
        /// The hash of the transaction.
        hash: B256,
        /// The sender's address.
        sender: Address,
        /// The transaction nonce.
        nonce: u64,
        /// The maximum fee per gas for the transaction.
        max_fee_per_gas: u128,
        /// The maximum priority fee per gas for the transaction.
        max_priority_fee_per_gas: u128,
        /// The gas limit for the transaction.
        gas_limit: u64,
        /// The transaction's destination.
        to: TxKind,
        /// The value of the transaction.
        value: U256,
        /// The access list associated with the transaction.
        access_list: AccessList,
        /// The transaction input data.
        input: Bytes,
        /// The size of the transaction, returned in the implementation of [`PoolTransaction`].
        size: usize,
        /// The cost of the transaction, returned in the implementation of [`PoolTransaction`].
        cost: U256,
    },
    /// EIP-4844 transaction type.
    Eip4844 {
        /// The chain id of the transaction.
        chain_id: ChainId,
        /// The hash of the transaction.
        hash: B256,
        /// The sender's address.
        sender: Address,
        /// The transaction nonce.
        nonce: u64,
        /// The maximum fee per gas for the transaction.
        max_fee_per_gas: u128,
        /// The maximum priority fee per gas for the transaction.
        max_priority_fee_per_gas: u128,
        /// The maximum fee per blob gas for the transaction.
        max_fee_per_blob_gas: u128,
        /// The gas limit for the transaction.
        gas_limit: u64,
        /// The transaction's destination.
        to: Address,
        /// The value of the transaction.
        value: U256,
        /// The access list associated with the transaction.
        access_list: AccessList,
        /// The transaction input data.
        input: Bytes,
        /// The sidecar information for the transaction.
        sidecar: BlobTransactionSidecar,
        /// The size of the transaction, returned in the implementation of [`PoolTransaction`].
        size: usize,
        /// The cost of the transaction, returned in the implementation of [`PoolTransaction`].
        cost: U256,
    },
    /// EIP-7702 transaction type.
    Eip7702 {
        /// The chain id of the transaction.
        chain_id: ChainId,
        /// The hash of the transaction.
        hash: B256,
        /// The sender's address.
        sender: Address,
        /// The transaction nonce.
        nonce: u64,
        /// The maximum fee per gas for the transaction.
        max_fee_per_gas: u128,
        /// The maximum priority fee per gas for the transaction.
        max_priority_fee_per_gas: u128,
        /// The gas limit for the transaction.
        gas_limit: u64,
        /// The transaction's destination.
        to: Address,
        /// The value of the transaction.
        value: U256,
        /// The access list associated with the transaction.
        access_list: AccessList,
        /// The authorization list associated with the transaction.
        authorization_list: Vec<SignedAuthorization>,
        /// The transaction input data.
        input: Bytes,
        /// The size of the transaction, returned in the implementation of [`PoolTransaction`].
        size: usize,
        /// The cost of the transaction, returned in the implementation of [`PoolTransaction`].
        cost: U256,
    },
}

// === impl MockTransaction ===

impl MockTransaction {
    make_setters_getters! {
        nonce => u64;
        hash => B256;
        sender => Address;
        gas_limit => u64;
        value => U256;
        input => Bytes;
        size => usize
    }

    /// Returns a new legacy transaction with random address and hash and empty values
    pub fn legacy() -> Self {
        Self::Legacy {
            chain_id: Some(1),
            hash: B256::random(),
            sender: Address::random(),
            nonce: 0,
            gas_price: 0,
            gas_limit: 0,
            to: Address::random().into(),
            value: Default::default(),
            input: Default::default(),
            size: Default::default(),
            cost: U256::ZERO,
        }
    }

    /// Returns a new EIP2930 transaction with random address and hash and empty values
    pub fn eip2930() -> Self {
        Self::Eip2930 {
            chain_id: 1,
            hash: B256::random(),
            sender: Address::random(),
            nonce: 0,
            to: Address::random().into(),
            gas_limit: 0,
            input: Bytes::new(),
            value: Default::default(),
            gas_price: 0,
            access_list: Default::default(),
            size: Default::default(),
            cost: U256::ZERO,
        }
    }

    /// Returns a new EIP1559 transaction with random address and hash and empty values
    pub fn eip1559() -> Self {
        Self::Eip1559 {
            chain_id: 1,
            hash: B256::random(),
            sender: Address::random(),
            nonce: 0,
            max_fee_per_gas: MIN_PROTOCOL_BASE_FEE as u128,
            max_priority_fee_per_gas: MIN_PROTOCOL_BASE_FEE as u128,
            gas_limit: 0,
            to: Address::random().into(),
            value: Default::default(),
            input: Bytes::new(),
            access_list: Default::default(),
            size: Default::default(),
            cost: U256::ZERO,
        }
    }

    /// Returns a new EIP7702 transaction with random address and hash and empty values
    pub fn eip7702() -> Self {
        Self::Eip7702 {
            chain_id: 1,
            hash: B256::random(),
            sender: Address::random(),
            nonce: 0,
            max_fee_per_gas: MIN_PROTOCOL_BASE_FEE as u128,
            max_priority_fee_per_gas: MIN_PROTOCOL_BASE_FEE as u128,
            gas_limit: 0,
            to: Address::random(),
            value: Default::default(),
            input: Bytes::new(),
            access_list: Default::default(),
            authorization_list: vec![],
            size: Default::default(),
            cost: U256::ZERO,
        }
    }

    /// Returns a new EIP4844 transaction with random address and hash and empty values
    pub fn eip4844() -> Self {
        Self::Eip4844 {
            chain_id: 1,
            hash: B256::random(),
            sender: Address::random(),
            nonce: 0,
            max_fee_per_gas: MIN_PROTOCOL_BASE_FEE as u128,
            max_priority_fee_per_gas: MIN_PROTOCOL_BASE_FEE as u128,
            max_fee_per_blob_gas: DATA_GAS_PER_BLOB as u128,
            gas_limit: 0,
            to: Address::random(),
            value: Default::default(),
            input: Bytes::new(),
            access_list: Default::default(),
            sidecar: Default::default(),
            size: Default::default(),
            cost: U256::ZERO,
        }
    }

    /// Returns a new EIP4844 transaction with a provided sidecar
    pub fn eip4844_with_sidecar(sidecar: BlobTransactionSidecar) -> Self {
        let mut transaction = Self::eip4844();
        if let Self::Eip4844 { sidecar: ref mut existing_sidecar, .. } = &mut transaction {
            *existing_sidecar = sidecar;
        }
        transaction
    }

    /// Creates a new transaction with the given [`TxType`].
    ///
    /// See the default constructors for each of the transaction types:
    ///
    /// * [`MockTransaction::legacy`]
    /// * [`MockTransaction::eip2930`]
    /// * [`MockTransaction::eip1559`]
    /// * [`MockTransaction::eip4844`]
    pub fn new_from_type(tx_type: TxType) -> Self {
        #[allow(unreachable_patterns)]
        match tx_type {
            TxType::Legacy => Self::legacy(),
            TxType::Eip2930 => Self::eip2930(),
            TxType::Eip1559 => Self::eip1559(),
            TxType::Eip4844 => Self::eip4844(),
            TxType::Eip7702 => Self::eip7702(),

            _ => unreachable!("Invalid transaction type"),
        }
    }

    /// Sets the max fee per blob gas for EIP-4844 transactions,
    pub fn with_blob_fee(mut self, val: u128) -> Self {
        self.set_blob_fee(val);
        self
    }

    /// Sets the max fee per blob gas for EIP-4844 transactions,
    pub fn set_blob_fee(&mut self, val: u128) -> &mut Self {
        if let Self::Eip4844 { max_fee_per_blob_gas, .. } = self {
            *max_fee_per_blob_gas = val;
        }
        self
    }

    /// Sets the priority fee for dynamic fee transactions (EIP-1559 and EIP-4844)
    pub fn set_priority_fee(&mut self, val: u128) -> &mut Self {
        if let Self::Eip1559 { max_priority_fee_per_gas, .. } |
        Self::Eip4844 { max_priority_fee_per_gas, .. } = self
        {
            *max_priority_fee_per_gas = val;
        }
        self
    }

    /// Sets the priority fee for dynamic fee transactions (EIP-1559 and EIP-4844)
    pub fn with_priority_fee(mut self, val: u128) -> Self {
        self.set_priority_fee(val);
        self
    }

    /// Gets the priority fee for dynamic fee transactions (EIP-1559 and EIP-4844)
    pub const fn get_priority_fee(&self) -> Option<u128> {
        match self {
            Self::Eip1559 { max_priority_fee_per_gas, .. } |
            Self::Eip4844 { max_priority_fee_per_gas, .. } |
            Self::Eip7702 { max_priority_fee_per_gas, .. } => Some(*max_priority_fee_per_gas),
            _ => None,
        }
    }

    /// Sets the max fee for dynamic fee transactions (EIP-1559 and EIP-4844)
    pub fn set_max_fee(&mut self, val: u128) -> &mut Self {
        if let Self::Eip1559 { max_fee_per_gas, .. } |
        Self::Eip4844 { max_fee_per_gas, .. } |
        Self::Eip7702 { max_fee_per_gas, .. } = self
        {
            *max_fee_per_gas = val;
        }
        self
    }

    /// Sets the max fee for dynamic fee transactions (EIP-1559 and EIP-4844)
    pub fn with_max_fee(mut self, val: u128) -> Self {
        self.set_max_fee(val);
        self
    }

    /// Gets the max fee for dynamic fee transactions (EIP-1559 and EIP-4844)
    pub const fn get_max_fee(&self) -> Option<u128> {
        match self {
            Self::Eip1559 { max_fee_per_gas, .. } |
            Self::Eip4844 { max_fee_per_gas, .. } |
            Self::Eip7702 { max_fee_per_gas, .. } => Some(*max_fee_per_gas),
            _ => None,
        }
    }

    /// Sets the access list for transactions supporting EIP-1559, EIP-4844, and EIP-2930.
    pub fn set_accesslist(&mut self, list: AccessList) -> &mut Self {
        match self {
            Self::Legacy { .. } => {}
            Self::Eip1559 { access_list: accesslist, .. } |
            Self::Eip4844 { access_list: accesslist, .. } |
            Self::Eip2930 { access_list: accesslist, .. } |
            Self::Eip7702 { access_list: accesslist, .. } => {
                *accesslist = list;
            }
        }
        self
    }

    /// Sets the gas price for the transaction.
    pub fn set_gas_price(&mut self, val: u128) -> &mut Self {
        match self {
            Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => {
                *gas_price = val;
            }
            Self::Eip1559 { max_fee_per_gas, max_priority_fee_per_gas, .. } |
            Self::Eip4844 { max_fee_per_gas, max_priority_fee_per_gas, .. } |
            Self::Eip7702 { max_fee_per_gas, max_priority_fee_per_gas, .. } => {
                *max_fee_per_gas = val;
                *max_priority_fee_per_gas = val;
            }
        }
        self
    }

    /// Sets the gas price for the transaction.
    pub fn with_gas_price(mut self, val: u128) -> Self {
        match self {
            Self::Legacy { ref mut gas_price, .. } | Self::Eip2930 { ref mut gas_price, .. } => {
                *gas_price = val;
            }
            Self::Eip1559 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } |
            Self::Eip4844 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } |
            Self::Eip7702 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } => {
                *max_fee_per_gas = val;
                *max_priority_fee_per_gas = val;
            }
        }
        self
    }

    /// Gets the gas price for the transaction.
    pub const fn get_gas_price(&self) -> u128 {
        match self {
            Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => *gas_price,
            Self::Eip1559 { max_fee_per_gas, .. } |
            Self::Eip4844 { max_fee_per_gas, .. } |
            Self::Eip7702 { max_fee_per_gas, .. } => *max_fee_per_gas,
        }
    }

    /// Returns a clone with a decreased nonce
    pub fn prev(&self) -> Self {
        self.clone().with_hash(B256::random()).with_nonce(self.get_nonce() - 1)
    }

    /// Returns a clone with an increased nonce
    pub fn next(&self) -> Self {
        self.clone().with_hash(B256::random()).with_nonce(self.get_nonce() + 1)
    }

    /// Returns a clone with an increased nonce
    pub fn skip(&self, skip: u64) -> Self {
        self.clone().with_hash(B256::random()).with_nonce(self.get_nonce() + skip + 1)
    }

    /// Returns a clone with incremented nonce
    pub fn inc_nonce(self) -> Self {
        let nonce = self.get_nonce() + 1;
        self.with_nonce(nonce)
    }

    /// Sets a new random hash
    pub fn rng_hash(self) -> Self {
        self.with_hash(B256::random())
    }

    /// Returns a new transaction with a higher gas price +1
    pub fn inc_price(&self) -> Self {
        self.inc_price_by(1)
    }

    /// Returns a new transaction with a higher gas price
    pub fn inc_price_by(&self, value: u128) -> Self {
        self.clone().with_gas_price(self.get_gas_price().checked_add(value).unwrap())
    }

    /// Returns a new transaction with a lower gas price -1
    pub fn decr_price(&self) -> Self {
        self.decr_price_by(1)
    }

    /// Returns a new transaction with a lower gas price
    pub fn decr_price_by(&self, value: u128) -> Self {
        self.clone().with_gas_price(self.get_gas_price().checked_sub(value).unwrap())
    }

    /// Returns a new transaction with a higher value
    pub fn inc_value(&self) -> Self {
        self.clone().with_value(self.get_value().checked_add(U256::from(1)).unwrap())
    }

    /// Returns a new transaction with a higher gas limit
    pub fn inc_limit(&self) -> Self {
        self.clone().with_gas_limit(self.get_gas_limit() + 1)
    }

    /// Returns a new transaction with a higher blob fee +1
    ///
    /// If it's an EIP-4844 transaction.
    pub fn inc_blob_fee(&self) -> Self {
        self.inc_blob_fee_by(1)
    }

    /// Returns a new transaction with a higher blob fee
    ///
    /// If it's an EIP-4844 transaction.
    pub fn inc_blob_fee_by(&self, value: u128) -> Self {
        let mut this = self.clone();
        if let Self::Eip4844 { max_fee_per_blob_gas, .. } = &mut this {
            *max_fee_per_blob_gas = max_fee_per_blob_gas.checked_add(value).unwrap();
        }
        this
    }

    /// Returns a new transaction with a lower blob fee -1
    ///
    /// If it's an EIP-4844 transaction.
    pub fn decr_blob_fee(&self) -> Self {
        self.decr_price_by(1)
    }

    /// Returns a new transaction with a lower blob fee
    ///
    /// If it's an EIP-4844 transaction.
    pub fn decr_blob_fee_by(&self, value: u128) -> Self {
        let mut this = self.clone();
        if let Self::Eip4844 { max_fee_per_blob_gas, .. } = &mut this {
            *max_fee_per_blob_gas = max_fee_per_blob_gas.checked_sub(value).unwrap();
        }
        this
    }

    /// Returns the transaction type identifier associated with the current [`MockTransaction`].
    pub const fn tx_type(&self) -> u8 {
        match self {
            Self::Legacy { .. } => LEGACY_TX_TYPE_ID,
            Self::Eip1559 { .. } => EIP1559_TX_TYPE_ID,
            Self::Eip4844 { .. } => EIP4844_TX_TYPE_ID,
            Self::Eip2930 { .. } => EIP2930_TX_TYPE_ID,
            Self::Eip7702 { .. } => EIP7702_TX_TYPE_ID,
        }
    }

    /// Checks if the transaction is of the legacy type.
    pub const fn is_legacy(&self) -> bool {
        matches!(self, Self::Legacy { .. })
    }

    /// Checks if the transaction is of the EIP-1559 type.
    pub const fn is_eip1559(&self) -> bool {
        matches!(self, Self::Eip1559 { .. })
    }

    /// Checks if the transaction is of the EIP-4844 type.
    pub const fn is_eip4844(&self) -> bool {
        matches!(self, Self::Eip4844 { .. })
    }

    /// Checks if the transaction is of the EIP-2930 type.
    pub const fn is_eip2930(&self) -> bool {
        matches!(self, Self::Eip2930 { .. })
    }

    /// Checks if the transaction is of the EIP-2930 type.
    pub const fn is_eip7702(&self) -> bool {
        matches!(self, Self::Eip7702 { .. })
    }

    fn update_cost(&mut self) {
        match self {
            Self::Legacy { cost, gas_limit, gas_price, value, .. } |
            Self::Eip2930 { cost, gas_limit, gas_price, value, .. } => {
                *cost = U256::from(*gas_limit) * U256::from(*gas_price) + *value
            }
            Self::Eip1559 { cost, gas_limit, max_fee_per_gas, value, .. } |
            Self::Eip4844 { cost, gas_limit, max_fee_per_gas, value, .. } |
            Self::Eip7702 { cost, gas_limit, max_fee_per_gas, value, .. } => {
                *cost = U256::from(*gas_limit) * U256::from(*max_fee_per_gas) + *value
            }
        };
    }
}

impl PoolTransaction for MockTransaction {
    type TryFromConsensusError = TryFromRecoveredTransactionError;

    type Consensus = TransactionSigned;

    type Pooled = PooledTransaction;

    fn try_from_consensus(
        tx: RecoveredTx<Self::Consensus>,
    ) -> Result<Self, Self::TryFromConsensusError> {
        tx.try_into()
    }

    fn into_consensus(self) -> RecoveredTx<Self::Consensus> {
        self.into()
    }

    fn from_pooled(pooled: RecoveredTx<Self::Pooled>) -> Self {
        pooled.into()
    }

    fn try_consensus_into_pooled(
        tx: RecoveredTx<Self::Consensus>,
    ) -> Result<RecoveredTx<Self::Pooled>, Self::TryFromConsensusError> {
        let (tx, signer) = tx.to_components();
        Self::Pooled::try_from(tx)
            .map(|tx| tx.with_signer(signer))
            .map_err(|_| TryFromRecoveredTransactionError::BlobSidecarMissing)
    }

    fn hash(&self) -> &TxHash {
        self.get_hash()
    }

    fn sender(&self) -> Address {
        *self.get_sender()
    }

    fn sender_ref(&self) -> &Address {
        self.get_sender()
    }

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

    // Having `get_cost` from `make_setters_getters` would be cleaner but we didn't
    // want to also generate the error-prone cost setters. For now cost should be
    // correct at construction and auto-updated per field update via `update_cost`,
    // not to be manually set.
    fn cost(&self) -> &U256 {
        match self {
            Self::Legacy { cost, .. } |
            Self::Eip2930 { cost, .. } |
            Self::Eip1559 { cost, .. } |
            Self::Eip4844 { cost, .. } |
            Self::Eip7702 { cost, .. } => cost,
        }
    }

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

    fn max_fee_per_gas(&self) -> u128 {
        match self {
            Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => *gas_price,
            Self::Eip1559 { max_fee_per_gas, .. } |
            Self::Eip4844 { max_fee_per_gas, .. } |
            Self::Eip7702 { max_fee_per_gas, .. } => *max_fee_per_gas,
        }
    }

    fn access_list(&self) -> Option<&AccessList> {
        match self {
            Self::Legacy { .. } => None,
            Self::Eip1559 { access_list: accesslist, .. } |
            Self::Eip4844 { access_list: accesslist, .. } |
            Self::Eip2930 { access_list: accesslist, .. } |
            Self::Eip7702 { access_list: accesslist, .. } => Some(accesslist),
        }
    }

    fn max_priority_fee_per_gas(&self) -> Option<u128> {
        match self {
            Self::Legacy { .. } | Self::Eip2930 { .. } => None,
            Self::Eip1559 { max_priority_fee_per_gas, .. } |
            Self::Eip4844 { max_priority_fee_per_gas, .. } |
            Self::Eip7702 { max_priority_fee_per_gas, .. } => Some(*max_priority_fee_per_gas),
        }
    }

    fn max_fee_per_blob_gas(&self) -> Option<u128> {
        match self {
            Self::Eip4844 { max_fee_per_blob_gas, .. } => Some(*max_fee_per_blob_gas),
            _ => None,
        }
    }

    /// Calculates the effective tip per gas given a base fee.
    fn effective_tip_per_gas(&self, base_fee: u64) -> Option<u128> {
        // Convert base_fee to u128 for precision in calculations
        let base_fee = base_fee as u128;

        // Retrieve the maximum fee per gas
        let max_fee_per_gas = self.max_fee_per_gas();

        // If the maximum fee per gas is less than the base fee, return None
        if max_fee_per_gas < base_fee {
            return None
        }

        // Calculate the fee by subtracting the base fee from the maximum fee per gas
        let fee = max_fee_per_gas - base_fee;

        // If the maximum priority fee per gas is available, return the minimum of fee and priority
        // fee
        if let Some(priority_fee) = self.max_priority_fee_per_gas() {
            return Some(fee.min(priority_fee))
        }

        // Otherwise, return the calculated fee
        Some(fee)
    }

    /// Returns the priority fee or gas price based on the transaction type.
    fn priority_fee_or_price(&self) -> u128 {
        match self {
            Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => *gas_price,
            Self::Eip1559 { max_priority_fee_per_gas, .. } |
            Self::Eip4844 { max_priority_fee_per_gas, .. } |
            Self::Eip7702 { max_priority_fee_per_gas, .. } => *max_priority_fee_per_gas,
        }
    }

    /// Returns the transaction kind associated with the transaction.
    fn kind(&self) -> TxKind {
        match self {
            Self::Legacy { to, .. } | Self::Eip1559 { to, .. } | Self::Eip2930 { to, .. } => *to,
            Self::Eip4844 { to, .. } | Self::Eip7702 { to, .. } => TxKind::Call(*to),
        }
    }

    /// Returns true if the transaction is a contract creation.
    fn is_create(&self) -> bool {
        match self {
            Self::Legacy { to, .. } | Self::Eip1559 { to, .. } | Self::Eip2930 { to, .. } => {
                to.is_create()
            }
            Self::Eip4844 { .. } | Self::Eip7702 { .. } => false,
        }
    }

    /// Returns the input data associated with the transaction.
    fn input(&self) -> &[u8] {
        self.get_input()
    }

    /// Returns the size of the transaction.
    fn size(&self) -> usize {
        *self.get_size()
    }

    /// Returns the transaction type as a byte identifier.
    fn tx_type(&self) -> u8 {
        match self {
            Self::Legacy { .. } => TxType::Legacy.into(),
            Self::Eip1559 { .. } => TxType::Eip1559.into(),
            Self::Eip4844 { .. } => TxType::Eip4844.into(),
            Self::Eip2930 { .. } => TxType::Eip2930.into(),
            Self::Eip7702 { .. } => TxType::Eip7702.into(),
        }
    }

    /// Returns the encoded length of the transaction.
    fn encoded_length(&self) -> usize {
        self.size()
    }

    /// Returns the chain ID associated with the transaction.
    fn chain_id(&self) -> Option<u64> {
        match self {
            Self::Legacy { chain_id, .. } => *chain_id,
            Self::Eip1559 { chain_id, .. } |
            Self::Eip4844 { chain_id, .. } |
            Self::Eip2930 { chain_id, .. } |
            Self::Eip7702 { chain_id, .. } => Some(*chain_id),
        }
    }
}

impl EthPoolTransaction for MockTransaction {
    fn take_blob(&mut self) -> EthBlobTransactionSidecar {
        match self {
            Self::Eip4844 { sidecar, .. } => EthBlobTransactionSidecar::Present(sidecar.clone()),
            _ => EthBlobTransactionSidecar::None,
        }
    }

    fn blob_count(&self) -> usize {
        match self {
            Self::Eip4844 { sidecar, .. } => sidecar.blobs.len(),
            _ => 0,
        }
    }

    fn try_into_pooled_eip4844(
        self,
        sidecar: Arc<BlobTransactionSidecar>,
    ) -> Option<RecoveredTx<Self::Pooled>> {
        let (tx, signer) = self.into_consensus().to_components();
        tx.try_into_pooled_eip4844(Arc::unwrap_or_clone(sidecar))
            .map(|tx| tx.with_signer(signer))
            .ok()
    }

    fn try_from_eip4844(
        tx: RecoveredTx<Self::Consensus>,
        sidecar: BlobTransactionSidecar,
    ) -> Option<Self> {
        let (tx, signer) = tx.to_components();
        tx.try_into_pooled_eip4844(sidecar)
            .map(|tx| tx.with_signer(signer))
            .ok()
            .map(Self::from_pooled)
    }

    fn validate_blob(
        &self,
        _blob: &BlobTransactionSidecar,
        _settings: &reth_primitives::kzg::KzgSettings,
    ) -> Result<(), alloy_eips::eip4844::BlobTransactionValidationError> {
        match &self {
            Self::Eip4844 { .. } => Ok(()),
            _ => Err(BlobTransactionValidationError::NotBlobTransaction(self.tx_type())),
        }
    }

    fn authorization_count(&self) -> usize {
        0
    }
}

impl TryFrom<RecoveredTx> for MockTransaction {
    type Error = TryFromRecoveredTransactionError;

    fn try_from(tx: RecoveredTx) -> Result<Self, Self::Error> {
        let sender = tx.signer();
        let transaction = tx.into_signed();
        let hash = transaction.hash();
        let size = transaction.size();

        #[allow(unreachable_patterns)]
        match transaction.transaction {
            Transaction::Legacy(TxLegacy {
                chain_id,
                nonce,
                gas_price,
                gas_limit,
                to,
                value,
                input,
            }) => Ok(Self::Legacy {
                chain_id,
                hash,
                sender,
                nonce,
                gas_price,
                gas_limit,
                to,
                value,
                input,
                size,
                cost: U256::from(gas_limit) * U256::from(gas_price) + value,
            }),
            Transaction::Eip2930(TxEip2930 {
                chain_id,
                nonce,
                gas_price,
                gas_limit,
                to,
                value,
                input,
                access_list,
            }) => Ok(Self::Eip2930 {
                chain_id,
                hash,
                sender,
                nonce,
                gas_price,
                gas_limit,
                to,
                value,
                input,
                access_list,
                size,
                cost: U256::from(gas_limit) * U256::from(gas_price) + value,
            }),
            Transaction::Eip1559(TxEip1559 {
                chain_id,
                nonce,
                gas_limit,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                to,
                value,
                input,
                access_list,
            }) => Ok(Self::Eip1559 {
                chain_id,
                hash,
                sender,
                nonce,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                gas_limit,
                to,
                value,
                input,
                access_list,
                size,
                cost: U256::from(gas_limit) * U256::from(max_fee_per_gas) + value,
            }),
            Transaction::Eip4844(TxEip4844 {
                chain_id,
                nonce,
                gas_limit,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                to,
                value,
                input,
                access_list,
                blob_versioned_hashes: _,
                max_fee_per_blob_gas,
            }) => Ok(Self::Eip4844 {
                chain_id,
                hash,
                sender,
                nonce,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                max_fee_per_blob_gas,
                gas_limit,
                to,
                value,
                input,
                access_list,
                sidecar: BlobTransactionSidecar::default(),
                size,
                cost: U256::from(gas_limit) * U256::from(max_fee_per_gas) + value,
            }),
            Transaction::Eip7702(TxEip7702 {
                chain_id,
                nonce,
                gas_limit,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                to,
                value,
                access_list,
                authorization_list,
                input,
            }) => Ok(Self::Eip7702 {
                chain_id,
                hash,
                sender,
                nonce,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                gas_limit,
                to,
                value,
                input,
                access_list,
                authorization_list,
                size,
                cost: U256::from(gas_limit) * U256::from(max_fee_per_gas) + value,
            }),
            tx => Err(TryFromRecoveredTransactionError::UnsupportedTransactionType(tx.ty())),
        }
    }
}

impl From<PooledTransactionsElementEcRecovered> for MockTransaction {
    fn from(tx: PooledTransactionsElementEcRecovered) -> Self {
        tx.into_ecrecovered_transaction().try_into().expect(
            "Failed to convert from PooledTransactionsElementEcRecovered to MockTransaction",
        )
    }
}

impl From<MockTransaction> for RecoveredTx {
    fn from(tx: MockTransaction) -> Self {
        let signed_tx =
            TransactionSigned::new(tx.clone().into(), Signature::test_signature(), *tx.hash());

        Self::from_signed_transaction(signed_tx, tx.sender())
    }
}

impl From<MockTransaction> for Transaction {
    fn from(mock: MockTransaction) -> Self {
        match mock {
            MockTransaction::Legacy {
                chain_id,
                nonce,
                gas_price,
                gas_limit,
                to,
                value,
                input,
                ..
            } => Self::Legacy(TxLegacy { chain_id, nonce, gas_price, gas_limit, to, value, input }),
            MockTransaction::Eip2930 {
                chain_id,
                nonce,
                gas_price,
                gas_limit,
                to,
                value,
                access_list,
                input,
                ..
            } => Self::Eip2930(TxEip2930 {
                chain_id,
                nonce,
                gas_price,
                gas_limit,
                to,
                value,
                access_list,
                input,
            }),
            MockTransaction::Eip1559 {
                chain_id,
                nonce,
                gas_limit,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                to,
                value,
                access_list,
                input,
                ..
            } => Self::Eip1559(TxEip1559 {
                chain_id,
                nonce,
                gas_limit,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                to,
                value,
                access_list,
                input,
            }),
            MockTransaction::Eip4844 {
                chain_id,
                nonce,
                gas_limit,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                to,
                value,
                access_list,
                sidecar,
                max_fee_per_blob_gas,
                input,
                ..
            } => Self::Eip4844(TxEip4844 {
                chain_id,
                nonce,
                gas_limit,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                to,
                value,
                access_list,
                blob_versioned_hashes: sidecar.versioned_hashes().collect(),
                max_fee_per_blob_gas,
                input,
            }),
            MockTransaction::Eip7702 {
                chain_id,
                nonce,
                gas_limit,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                to,
                value,
                access_list,
                input,
                authorization_list,
                ..
            } => Self::Eip7702(TxEip7702 {
                chain_id,
                nonce,
                gas_limit,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                to,
                value,
                access_list,
                authorization_list,
                input,
            }),
        }
    }
}

#[cfg(any(test, feature = "arbitrary"))]
impl proptest::arbitrary::Arbitrary for MockTransaction {
    type Parameters = ();
    fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
        use proptest::prelude::Strategy;
        use proptest_arbitrary_interop::arb;

        arb::<(TransactionSigned, Address)>()
            .prop_map(|(signed_transaction, signer)| {
                RecoveredTx::from_signed_transaction(signed_transaction, signer)
                    .try_into()
                    .expect("Failed to create an Arbitrary MockTransaction via RecoveredTx")
            })
            .boxed()
    }

    type Strategy = proptest::strategy::BoxedStrategy<Self>;
}

/// A factory for creating and managing various types of mock transactions.
#[derive(Debug, Default)]
pub struct MockTransactionFactory {
    pub(crate) ids: SenderIdentifiers,
}

// === impl MockTransactionFactory ===

impl MockTransactionFactory {
    /// Generates a transaction ID for the given [`MockTransaction`].
    pub fn tx_id(&mut self, tx: &MockTransaction) -> TransactionId {
        let sender = self.ids.sender_id_or_create(tx.sender());
        TransactionId::new(sender, tx.nonce())
    }

    /// Validates a [`MockTransaction`] and returns a [`MockValidTx`].
    pub fn validated(&mut self, transaction: MockTransaction) -> MockValidTx {
        self.validated_with_origin(TransactionOrigin::External, transaction)
    }

    /// Validates a [`MockTransaction`] and returns a shared [`Arc<MockValidTx>`].
    pub fn validated_arc(&mut self, transaction: MockTransaction) -> Arc<MockValidTx> {
        Arc::new(self.validated(transaction))
    }

    /// Converts the transaction into a validated transaction with a specified origin.
    pub fn validated_with_origin(
        &mut self,
        origin: TransactionOrigin,
        transaction: MockTransaction,
    ) -> MockValidTx {
        MockValidTx {
            propagate: false,
            transaction_id: self.tx_id(&transaction),
            transaction,
            timestamp: Instant::now(),
            origin,
        }
    }

    /// Creates a validated legacy [`MockTransaction`].
    pub fn create_legacy(&mut self) -> MockValidTx {
        self.validated(MockTransaction::legacy())
    }

    /// Creates a validated EIP-1559 [`MockTransaction`].
    pub fn create_eip1559(&mut self) -> MockValidTx {
        self.validated(MockTransaction::eip1559())
    }

    /// Creates a validated EIP-4844 [`MockTransaction`].
    pub fn create_eip4844(&mut self) -> MockValidTx {
        self.validated(MockTransaction::eip4844())
    }
}

/// `MockOrdering` is just a `CoinbaseTipOrdering` with `MockTransaction`
pub type MockOrdering = CoinbaseTipOrdering<MockTransaction>;

/// A ratio of each of the configured transaction types. The percentages sum up to 100, this is
/// enforced in [`MockTransactionRatio::new`] by an assert.
#[derive(Debug, Clone)]
pub struct MockTransactionRatio {
    /// Percent of transactions that are legacy transactions
    pub legacy_pct: u32,
    /// Percent of transactions that are access list transactions
    pub access_list_pct: u32,
    /// Percent of transactions that are EIP-1559 transactions
    pub dynamic_fee_pct: u32,
    /// Percent of transactions that are EIP-4844 transactions
    pub blob_pct: u32,
}

impl MockTransactionRatio {
    /// Creates a new [`MockTransactionRatio`] with the given percentages.
    ///
    /// Each argument is treated as a full percent, for example `30u32` is `30%`.
    ///
    /// The percentages must sum up to 100 exactly, or this method will panic.
    pub fn new(legacy_pct: u32, access_list_pct: u32, dynamic_fee_pct: u32, blob_pct: u32) -> Self {
        let total = legacy_pct + access_list_pct + dynamic_fee_pct + blob_pct;
        assert_eq!(
            total,
            100,
            "percentages must sum up to 100, instead got legacy: {legacy_pct}, access_list: {access_list_pct}, dynamic_fee: {dynamic_fee_pct}, blob: {blob_pct}, total: {total}",
        );

        Self { legacy_pct, access_list_pct, dynamic_fee_pct, blob_pct }
    }

    /// Create a [`WeightedIndex`] from this transaction ratio.
    ///
    /// This index will sample in the following order:
    /// * Legacy transaction => 0
    /// * EIP-2930 transaction => 1
    /// * EIP-1559 transaction => 2
    /// * EIP-4844 transaction => 3
    pub fn weighted_index(&self) -> WeightedIndex<u32> {
        WeightedIndex::new([
            self.legacy_pct,
            self.access_list_pct,
            self.dynamic_fee_pct,
            self.blob_pct,
        ])
        .unwrap()
    }
}

/// The range of each type of fee, for the different transaction types
#[derive(Debug, Clone)]
pub struct MockFeeRange {
    /// The range of `gas_price` or legacy and access list transactions
    pub gas_price: Uniform<u128>,
    /// The range of priority fees for EIP-1559 and EIP-4844 transactions
    pub priority_fee: Uniform<u128>,
    /// The range of max fees for EIP-1559 and EIP-4844 transactions
    pub max_fee: Uniform<u128>,
    /// The range of max fees per blob gas for EIP-4844 transactions
    pub max_fee_blob: Uniform<u128>,
}

impl MockFeeRange {
    /// Creates a new [`MockFeeRange`] with the given ranges.
    ///
    /// Expects the bottom of the `priority_fee_range` to be greater than the top of the
    /// `max_fee_range`.
    pub fn new(
        gas_price: Range<u128>,
        priority_fee: Range<u128>,
        max_fee: Range<u128>,
        max_fee_blob: Range<u128>,
    ) -> Self {
        assert!(
            max_fee.start <= priority_fee.end,
            "max_fee_range should be strictly below the priority fee range"
        );
        Self {
            gas_price: gas_price.into(),
            priority_fee: priority_fee.into(),
            max_fee: max_fee.into(),
            max_fee_blob: max_fee_blob.into(),
        }
    }

    /// Returns a sample of `gas_price` for legacy and access list transactions with the given
    /// [Rng](rand::Rng).
    pub fn sample_gas_price(&self, rng: &mut impl rand::Rng) -> u128 {
        self.gas_price.sample(rng)
    }

    /// Returns a sample of `max_priority_fee_per_gas` for EIP-1559 and EIP-4844 transactions with
    /// the given [Rng](rand::Rng).
    pub fn sample_priority_fee(&self, rng: &mut impl rand::Rng) -> u128 {
        self.priority_fee.sample(rng)
    }

    /// Returns a sample of `max_fee_per_gas` for EIP-1559 and EIP-4844 transactions with the given
    /// [Rng](rand::Rng).
    pub fn sample_max_fee(&self, rng: &mut impl rand::Rng) -> u128 {
        self.max_fee.sample(rng)
    }

    /// Returns a sample of `max_fee_per_blob_gas` for EIP-4844 transactions with the given
    /// [Rng](rand::Rng).
    pub fn sample_max_fee_blob(&self, rng: &mut impl rand::Rng) -> u128 {
        self.max_fee_blob.sample(rng)
    }
}

/// A configured distribution that can generate transactions
#[derive(Debug, Clone)]
pub struct MockTransactionDistribution {
    /// ratio of each transaction type to generate
    transaction_ratio: MockTransactionRatio,
    /// generates the gas limit
    gas_limit_range: Uniform<u64>,
    /// generates the transaction's fake size
    size_range: Uniform<usize>,
    /// generates fees for the given transaction types
    fee_ranges: MockFeeRange,
}

impl MockTransactionDistribution {
    /// Creates a new generator distribution.
    pub fn new(
        transaction_ratio: MockTransactionRatio,
        fee_ranges: MockFeeRange,
        gas_limit_range: Range<u64>,
        size_range: Range<usize>,
    ) -> Self {
        Self {
            transaction_ratio,
            gas_limit_range: gas_limit_range.into(),
            fee_ranges,
            size_range: size_range.into(),
        }
    }

    /// Generates a new transaction
    pub fn tx(&self, nonce: u64, rng: &mut impl rand::Rng) -> MockTransaction {
        let transaction_sample = self.transaction_ratio.weighted_index().sample(rng);
        let tx = match transaction_sample {
            0 => MockTransaction::legacy().with_gas_price(self.fee_ranges.sample_gas_price(rng)),
            1 => MockTransaction::eip2930().with_gas_price(self.fee_ranges.sample_gas_price(rng)),
            2 => MockTransaction::eip1559()
                .with_priority_fee(self.fee_ranges.sample_priority_fee(rng))
                .with_max_fee(self.fee_ranges.sample_max_fee(rng)),
            3 => MockTransaction::eip4844()
                .with_priority_fee(self.fee_ranges.sample_priority_fee(rng))
                .with_max_fee(self.fee_ranges.sample_max_fee(rng))
                .with_blob_fee(self.fee_ranges.sample_max_fee_blob(rng)),
            _ => unreachable!("unknown transaction type returned by the weighted index"),
        };

        let size = self.size_range.sample(rng);

        tx.with_nonce(nonce).with_gas_limit(self.gas_limit_range.sample(rng)).with_size(size)
    }

    /// Generates a new transaction set for the given sender.
    ///
    /// The nonce range defines which nonces to set, and how many transactions to generate.
    pub fn tx_set(
        &self,
        sender: Address,
        nonce_range: Range<u64>,
        rng: &mut impl rand::Rng,
    ) -> MockTransactionSet {
        let txs =
            nonce_range.map(|nonce| self.tx(nonce, rng).with_sender(sender)).collect::<Vec<_>>();
        MockTransactionSet::new(txs)
    }

    /// Generates a transaction set that ensures that blob txs are not mixed with other transaction
    /// types.
    ///
    /// This is done by taking the existing distribution, and using the first transaction to
    /// determine whether or not the sender should generate entirely blob transactions.
    pub fn tx_set_non_conflicting_types(
        &self,
        sender: Address,
        nonce_range: Range<u64>,
        rng: &mut impl rand::Rng,
    ) -> NonConflictingSetOutcome {
        // This will create a modified distribution that will only generate blob transactions
        // for the given sender, if the blob transaction is the first transaction in the set.
        //
        // Otherwise, it will modify the transaction distribution to only generate legacy, eip2930,
        // and eip1559 transactions.
        //
        // The new distribution should still have the same relative amount of transaction types.
        let mut modified_distribution = self.clone();
        let first_tx = self.tx(nonce_range.start, rng);

        // now we can check and modify the distribution, preserving potentially uneven ratios
        // between transaction types
        if first_tx.is_eip4844() {
            modified_distribution.transaction_ratio = MockTransactionRatio {
                legacy_pct: 0,
                access_list_pct: 0,
                dynamic_fee_pct: 0,
                blob_pct: 100,
            };

            // finally generate the transaction set
            NonConflictingSetOutcome::BlobsOnly(modified_distribution.tx_set(
                sender,
                nonce_range,
                rng,
            ))
        } else {
            let MockTransactionRatio { legacy_pct, access_list_pct, dynamic_fee_pct, .. } =
                modified_distribution.transaction_ratio;

            // Calculate the total weight of non-blob transactions
            let total_non_blob_weight: u32 = legacy_pct + access_list_pct + dynamic_fee_pct;

            // Calculate new weights, preserving the ratio between non-blob transaction types
            let new_weights: Vec<u32> = [legacy_pct, access_list_pct, dynamic_fee_pct]
                .into_iter()
                .map(|weight| weight * 100 / total_non_blob_weight)
                .collect();

            let new_ratio = MockTransactionRatio {
                legacy_pct: new_weights[0],
                access_list_pct: new_weights[1],
                dynamic_fee_pct: new_weights[2],
                blob_pct: 0,
            };

            // Set the new transaction ratio excluding blob transactions and preserving the relative
            // ratios
            modified_distribution.transaction_ratio = new_ratio;

            // finally generate the transaction set
            NonConflictingSetOutcome::Mixed(modified_distribution.tx_set(sender, nonce_range, rng))
        }
    }
}

/// Indicates whether or not the non-conflicting transaction set generated includes only blobs, or
/// a mix of transaction types.
#[derive(Debug, Clone)]
pub enum NonConflictingSetOutcome {
    /// The transaction set includes only blob transactions
    BlobsOnly(MockTransactionSet),
    /// The transaction set includes a mix of transaction types
    Mixed(MockTransactionSet),
}

impl NonConflictingSetOutcome {
    /// Returns the inner [`MockTransactionSet`]
    pub fn into_inner(self) -> MockTransactionSet {
        match self {
            Self::BlobsOnly(set) | Self::Mixed(set) => set,
        }
    }

    /// Introduces artificial nonce gaps into the transaction set, at random, with a range of gap
    /// sizes.
    ///
    /// If this is a [`NonConflictingSetOutcome::BlobsOnly`], then nonce gaps will not be
    /// introduced. Otherwise, the nonce gaps will be introduced to the mixed transaction set.
    ///
    /// See [`MockTransactionSet::with_nonce_gaps`] for more information on the generation process.
    pub fn with_nonce_gaps(
        &mut self,
        gap_pct: u32,
        gap_range: Range<u64>,
        rng: &mut impl rand::Rng,
    ) {
        match self {
            Self::BlobsOnly(_) => {}
            Self::Mixed(set) => set.with_nonce_gaps(gap_pct, gap_range, rng),
        }
    }
}

/// A set of [`MockTransaction`]s that can be modified at once
#[derive(Debug, Clone)]
pub struct MockTransactionSet {
    pub(crate) transactions: Vec<MockTransaction>,
}

impl MockTransactionSet {
    /// Create a new [`MockTransactionSet`] from a list of transactions
    const fn new(transactions: Vec<MockTransaction>) -> Self {
        Self { transactions }
    }

    /// Creates a series of dependent transactions for a given sender and nonce.
    ///
    /// This method generates a sequence of transactions starting from the provided nonce
    /// for the given sender.
    ///
    /// The number of transactions created is determined by `tx_count`.
    pub fn dependent(sender: Address, from_nonce: u64, tx_count: usize, tx_type: TxType) -> Self {
        let mut txs = Vec::with_capacity(tx_count);
        let mut curr_tx =
            MockTransaction::new_from_type(tx_type).with_nonce(from_nonce).with_sender(sender);
        for _ in 0..tx_count {
            txs.push(curr_tx.clone());
            curr_tx = curr_tx.next();
        }

        Self::new(txs)
    }

    /// Creates a chain of transactions for a given sender with a specified count.
    ///
    /// This method generates a sequence of transactions starting from the specified sender
    /// and creates a chain of transactions based on the `tx_count`.
    pub fn sequential_transactions_by_sender(
        sender: Address,
        tx_count: usize,
        tx_type: TxType,
    ) -> Self {
        Self::dependent(sender, 0, tx_count, tx_type)
    }

    /// Introduces artificial nonce gaps into the transaction set, at random, with a range of gap
    /// sizes.
    ///
    /// This assumes that the `gap_pct` is between 0 and 100, and the `gap_range` has a lower bound
    /// of at least one. This is enforced with assertions.
    ///
    /// The `gap_pct` is the percent chance that the next transaction in the set will introduce a
    /// nonce gap.
    ///
    /// Let an example transaction set be `[(tx1, 1), (tx2, 2)]`, where the first element of the
    /// tuple is a transaction, and the second element is the nonce. If the `gap_pct` is 50, and
    /// the `gap_range` is `1..=1`, then the resulting transaction set could would be either
    /// `[(tx1, 1), (tx2, 2)]` or `[(tx1, 1), (tx2, 3)]`, with a 50% chance of either.
    pub fn with_nonce_gaps(
        &mut self,
        gap_pct: u32,
        gap_range: Range<u64>,
        rng: &mut impl rand::Rng,
    ) {
        assert!(gap_pct <= 100, "gap_pct must be between 0 and 100");
        assert!(gap_range.start >= 1, "gap_range must have a lower bound of at least one");

        let mut prev_nonce = 0;
        for tx in &mut self.transactions {
            if rng.gen_bool(gap_pct as f64 / 100.0) {
                prev_nonce += gap_range.start;
            } else {
                prev_nonce += 1;
            }
            tx.set_nonce(prev_nonce);
        }
    }

    /// Add transactions to the [`MockTransactionSet`]
    pub fn extend<T: IntoIterator<Item = MockTransaction>>(&mut self, txs: T) {
        self.transactions.extend(txs);
    }

    /// Extract the inner [Vec] of [`MockTransaction`]s
    pub fn into_vec(self) -> Vec<MockTransaction> {
        self.transactions
    }

    /// Returns an iterator over the contained transactions in the set
    pub fn iter(&self) -> impl Iterator<Item = &MockTransaction> {
        self.transactions.iter()
    }

    /// Returns a mutable iterator over the contained transactions in the set.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut MockTransaction> {
        self.transactions.iter_mut()
    }
}

impl IntoIterator for MockTransactionSet {
    type Item = MockTransaction;
    type IntoIter = IntoIter<MockTransaction>;

    fn into_iter(self) -> Self::IntoIter {
        self.transactions.into_iter()
    }
}

#[test]
fn test_mock_priority() {
    use crate::TransactionOrdering;

    let o = MockOrdering::default();
    let lo = MockTransaction::eip1559().with_gas_limit(100_000);
    let hi = lo.next().inc_price();
    assert!(o.priority(&hi, 0) > o.priority(&lo, 0));
}