revm-context-interface 18.0.0

Revm context interface 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
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
//! Gas table for dynamic gas constants.

use crate::{
    cfg::gas::{self, get_tokens_in_calldata, InitialAndFloorGas},
    context::SStoreResult,
};
use core::hash::{Hash, Hasher};
use primitives::{
    eip7702, eip8037,
    hardfork::SpecId::{self},
    OnceLock, U256,
};
use std::sync::Arc;

/// Gas table for dynamic gas constants.
#[derive(Clone)]
pub struct GasParams {
    /// Table of gas costs for operations
    table: Arc<[u64; 256]>,
}

impl PartialEq<GasParams> for GasParams {
    fn eq(&self, other: &GasParams) -> bool {
        self.table == other.table
    }
}

impl Hash for GasParams {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.table.hash(hasher);
    }
}

impl core::fmt::Debug for GasParams {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "GasParams {{ table: {:?} }}", self.table)
    }
}

/// Returns number of words what would fit to provided number of bytes,
/// i.e. it rounds up the number bytes to number of words.
#[inline]
pub const fn num_words(len: usize) -> usize {
    len.div_ceil(32)
}

impl Eq for GasParams {}
#[cfg(feature = "serde")]
mod serde {
    use super::{Arc, GasParams};
    use std::vec::Vec;

    #[derive(serde::Serialize, serde::Deserialize)]
    struct GasParamsSerde {
        table: Vec<u64>,
    }

    #[cfg(feature = "serde")]
    impl serde::Serialize for GasParams {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: serde::Serializer,
        {
            GasParamsSerde {
                table: self.table.to_vec(),
            }
            .serialize(serializer)
        }
    }

    impl<'de> serde::Deserialize<'de> for GasParams {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            let table = GasParamsSerde::deserialize(deserializer)?;
            if table.table.len() != 256 {
                return Err(serde::de::Error::custom("Invalid gas params length"));
            }
            Ok(Self::new(Arc::new(table.table.try_into().unwrap())))
        }
    }
}

impl Default for GasParams {
    #[inline]
    fn default() -> Self {
        Self::new_spec(SpecId::default())
    }
}

impl GasParams {
    /// Creates a new `GasParams` with the given table.
    #[inline]
    pub const fn new(table: Arc<[u64; 256]>) -> Self {
        Self { table }
    }

    /// Overrides the gas cost for the given gas id.
    ///
    /// It will clone underlying table and override the values.
    ///
    /// Use to override default gas cost
    ///
    /// ```rust
    /// use revm_context_interface::cfg::gas_params::{GasParams, GasId};
    /// use primitives::hardfork::SpecId;
    ///
    /// let mut gas_table = GasParams::new_spec(SpecId::default());
    /// gas_table.override_gas([(GasId::memory_linear_cost(), 2), (GasId::memory_quadratic_reduction(), 512)].into_iter());
    /// assert_eq!(gas_table.get(GasId::memory_linear_cost()), 2);
    /// assert_eq!(gas_table.get(GasId::memory_quadratic_reduction()), 512);
    /// ```
    pub fn override_gas(&mut self, values: impl IntoIterator<Item = (GasId, u64)>) {
        let mut table = *self.table.clone();
        for (id, value) in values.into_iter() {
            table[id.as_usize()] = value;
        }
        *self = Self::new(Arc::new(table));
    }

    /// Returns the table.
    #[inline]
    pub fn table(&self) -> &[u64; 256] {
        &self.table
    }

    /// Creates a new `GasParams` for the given spec.
    #[inline(never)]
    pub fn new_spec(spec: SpecId) -> Self {
        use SpecId::*;
        let gas_params = match spec {
            FRONTIER => {
                static TABLE: OnceLock<GasParams> = OnceLock::new();
                TABLE.get_or_init(|| Self::new_spec_inner(spec))
            }
            // Transaction creation cost was added in homestead fork.
            HOMESTEAD => {
                static TABLE: OnceLock<GasParams> = OnceLock::new();
                TABLE.get_or_init(|| Self::new_spec_inner(spec))
            }
            // New account cost for selfdestruct was added in tangerine fork.
            TANGERINE => {
                static TABLE: OnceLock<GasParams> = OnceLock::new();
                TABLE.get_or_init(|| Self::new_spec_inner(spec))
            }
            // EXP cost was increased in spurious dragon fork.
            SPURIOUS_DRAGON | BYZANTIUM | PETERSBURG => {
                static TABLE: OnceLock<GasParams> = OnceLock::new();
                TABLE.get_or_init(|| Self::new_spec_inner(spec))
            }
            // SSTORE gas calculation changed in istanbul fork.
            ISTANBUL => {
                static TABLE: OnceLock<GasParams> = OnceLock::new();
                TABLE.get_or_init(|| Self::new_spec_inner(spec))
            }
            // Warm/cold state access
            BERLIN => {
                static TABLE: OnceLock<GasParams> = OnceLock::new();
                TABLE.get_or_init(|| Self::new_spec_inner(spec))
            }
            // Refund reduction in london fork.
            LONDON | MERGE => {
                static TABLE: OnceLock<GasParams> = OnceLock::new();
                TABLE.get_or_init(|| Self::new_spec_inner(spec))
            }
            // Transaction initcode cost was introduced in shanghai fork.
            SHANGHAI | CANCUN => {
                static TABLE: OnceLock<GasParams> = OnceLock::new();
                TABLE.get_or_init(|| Self::new_spec_inner(spec))
            }
            // EIP-7702 was introduced in prague fork.
            PRAGUE | OSAKA => {
                static TABLE: OnceLock<GasParams> = OnceLock::new();
                TABLE.get_or_init(|| Self::new_spec_inner(spec))
            }
            // New fork.
            SpecId::AMSTERDAM => {
                static TABLE: OnceLock<GasParams> = OnceLock::new();
                TABLE.get_or_init(|| Self::new_spec_inner(spec))
            }
        };
        gas_params.clone()
    }

    /// Creates a new `GasParams` for the given spec.
    #[inline]
    fn new_spec_inner(spec: SpecId) -> Self {
        let mut table = [0; 256];

        table[GasId::exp_byte_gas().as_usize()] = 10;
        table[GasId::logdata().as_usize()] = gas::LOGDATA;
        table[GasId::logtopic().as_usize()] = gas::LOGTOPIC;
        table[GasId::copy_per_word().as_usize()] = gas::COPY;
        table[GasId::extcodecopy_per_word().as_usize()] = gas::COPY;
        table[GasId::mcopy_per_word().as_usize()] = gas::COPY;
        table[GasId::keccak256_per_word().as_usize()] = gas::KECCAK256WORD;
        table[GasId::memory_linear_cost().as_usize()] = gas::MEMORY;
        table[GasId::memory_quadratic_reduction().as_usize()] = 512;
        table[GasId::initcode_per_word().as_usize()] = gas::INITCODE_WORD_COST;
        table[GasId::create().as_usize()] = gas::CREATE;
        table[GasId::call_stipend_reduction().as_usize()] = 64;
        table[GasId::transfer_value_cost().as_usize()] = gas::CALLVALUE;
        table[GasId::cold_account_additional_cost().as_usize()] = 0;
        table[GasId::new_account_cost().as_usize()] = gas::NEWACCOUNT;
        table[GasId::warm_storage_read_cost().as_usize()] = 0;
        // Frontiers had fixed 5k cost.
        table[GasId::sstore_static().as_usize()] = gas::SSTORE_RESET;
        // SSTORE SET
        table[GasId::sstore_set_without_load_cost().as_usize()] =
            gas::SSTORE_SET - gas::SSTORE_RESET;
        // SSTORE RESET Is covered in SSTORE_STATIC.
        table[GasId::sstore_reset_without_cold_load_cost().as_usize()] = 0;
        // SSTORE SET REFUND (same as sstore_set_without_load_cost but used only in sstore_refund)
        table[GasId::sstore_set_refund().as_usize()] =
            table[GasId::sstore_set_without_load_cost().as_usize()];
        // SSTORE RESET REFUND (same as sstore_reset_without_cold_load_cost but used only in sstore_refund)
        table[GasId::sstore_reset_refund().as_usize()] =
            table[GasId::sstore_reset_without_cold_load_cost().as_usize()];
        // SSTORE CLEARING SLOT REFUND
        table[GasId::sstore_clearing_slot_refund().as_usize()] = 15000;
        table[GasId::selfdestruct_refund().as_usize()] = 24000;
        table[GasId::call_stipend().as_usize()] = gas::CALL_STIPEND;
        table[GasId::cold_storage_additional_cost().as_usize()] = 0;
        table[GasId::cold_storage_cost().as_usize()] = 0;
        table[GasId::new_account_cost_for_selfdestruct().as_usize()] = 0;
        table[GasId::code_deposit_cost().as_usize()] = gas::CODEDEPOSIT;
        table[GasId::tx_token_non_zero_byte_multiplier().as_usize()] =
            gas::NON_ZERO_BYTE_MULTIPLIER;
        table[GasId::tx_token_cost().as_usize()] = gas::STANDARD_TOKEN_COST;
        table[GasId::tx_base_stipend().as_usize()] = 21000;

        if spec.is_enabled_in(SpecId::HOMESTEAD) {
            table[GasId::tx_create_cost().as_usize()] = gas::CREATE;
        }

        if spec.is_enabled_in(SpecId::TANGERINE) {
            table[GasId::new_account_cost_for_selfdestruct().as_usize()] = gas::NEWACCOUNT;
        }

        if spec.is_enabled_in(SpecId::SPURIOUS_DRAGON) {
            table[GasId::exp_byte_gas().as_usize()] = 50;
        }

        if spec.is_enabled_in(SpecId::ISTANBUL) {
            table[GasId::sstore_static().as_usize()] = gas::ISTANBUL_SLOAD_GAS;
            table[GasId::sstore_set_without_load_cost().as_usize()] =
                gas::SSTORE_SET - gas::ISTANBUL_SLOAD_GAS;
            table[GasId::sstore_reset_without_cold_load_cost().as_usize()] =
                gas::SSTORE_RESET - gas::ISTANBUL_SLOAD_GAS;
            table[GasId::sstore_set_refund().as_usize()] =
                table[GasId::sstore_set_without_load_cost().as_usize()];
            table[GasId::sstore_reset_refund().as_usize()] =
                table[GasId::sstore_reset_without_cold_load_cost().as_usize()];
            table[GasId::tx_token_non_zero_byte_multiplier().as_usize()] =
                gas::NON_ZERO_BYTE_MULTIPLIER_ISTANBUL;
        }

        if spec.is_enabled_in(SpecId::BERLIN) {
            table[GasId::sstore_static().as_usize()] = gas::WARM_STORAGE_READ_COST;
            table[GasId::cold_account_additional_cost().as_usize()] =
                gas::COLD_ACCOUNT_ACCESS_COST_ADDITIONAL;
            table[GasId::cold_storage_additional_cost().as_usize()] =
                gas::COLD_SLOAD_COST - gas::WARM_STORAGE_READ_COST;
            table[GasId::cold_storage_cost().as_usize()] = gas::COLD_SLOAD_COST;
            table[GasId::warm_storage_read_cost().as_usize()] = gas::WARM_STORAGE_READ_COST;

            table[GasId::sstore_reset_without_cold_load_cost().as_usize()] =
                gas::WARM_SSTORE_RESET - gas::WARM_STORAGE_READ_COST;
            table[GasId::sstore_set_without_load_cost().as_usize()] =
                gas::SSTORE_SET - gas::WARM_STORAGE_READ_COST;
            table[GasId::sstore_set_refund().as_usize()] =
                table[GasId::sstore_set_without_load_cost().as_usize()];
            table[GasId::sstore_reset_refund().as_usize()] =
                table[GasId::sstore_reset_without_cold_load_cost().as_usize()];

            table[GasId::tx_access_list_address_cost().as_usize()] = gas::ACCESS_LIST_ADDRESS;
            table[GasId::tx_access_list_storage_key_cost().as_usize()] =
                gas::ACCESS_LIST_STORAGE_KEY;
        }

        if spec.is_enabled_in(SpecId::LONDON) {
            // EIP-3529: Reduction in refunds

            // Replace SSTORE_CLEARS_SCHEDULE (as defined in EIP-2200) with
            // SSTORE_RESET_GAS + ACCESS_LIST_STORAGE_KEY_COST (4,800 gas as of EIP-2929 + EIP-2930)
            table[GasId::sstore_clearing_slot_refund().as_usize()] =
                gas::WARM_SSTORE_RESET + gas::ACCESS_LIST_STORAGE_KEY;

            table[GasId::selfdestruct_refund().as_usize()] = 0;
        }

        if spec.is_enabled_in(SpecId::SHANGHAI) {
            table[GasId::tx_initcode_cost().as_usize()] = gas::INITCODE_WORD_COST;
        }

        if spec.is_enabled_in(SpecId::PRAGUE) {
            table[GasId::tx_eip7702_per_empty_account_cost().as_usize()] =
                eip7702::PER_EMPTY_ACCOUNT_COST;

            // EIP-7702 authorization refund for existing accounts
            table[GasId::tx_eip7702_auth_refund().as_usize()] =
                eip7702::PER_EMPTY_ACCOUNT_COST - eip7702::PER_AUTH_BASE_COST;

            table[GasId::tx_floor_cost_per_token().as_usize()] = gas::TOTAL_COST_FLOOR_PER_TOKEN;
            table[GasId::tx_floor_cost_base_gas().as_usize()] = 21000;
            // EIP-7623 floor tokens reuse `tokens_in_calldata`, i.e. zero bytes count as
            // one token each.
            table[GasId::tx_floor_token_zero_byte_multiplier().as_usize()] = 1;
        }

        // EIP-8037: State creation gas cost increase.
        // State-gas entries store *byte counts* here; the helper methods multiply
        // by the current `cost_per_state_byte` (CPSB), which is derived from the
        // block gas limit at charge time via `Cfg::cpsb`.
        if spec.is_enabled_in(SpecId::AMSTERDAM) {
            // Regular gas changes
            table[GasId::create().as_usize()] = 9000;
            table[GasId::tx_create_cost().as_usize()] = 9000;
            table[GasId::code_deposit_cost().as_usize()] = 0;
            table[GasId::new_account_cost().as_usize()] = 0;
            table[GasId::new_account_cost_for_selfdestruct().as_usize()] = 0;
            // GAS_STORAGE_SET regular = GAS_STORAGE_UPDATE - GAS_COLD_SLOAD = 5000 - 2100 = 2900
            // sstore_set_without_load_cost = 2900 - WARM_STORAGE_READ_COST(100) = 2800
            table[GasId::sstore_set_without_load_cost().as_usize()] = 2800;

            // State gas byte counts (multiplied by CPSB at charge time).
            table[GasId::sstore_set_state_gas().as_usize()] = eip8037::SSTORE_SET_BYTES;
            table[GasId::new_account_state_gas().as_usize()] = eip8037::NEW_ACCOUNT_BYTES;
            table[GasId::code_deposit_state_gas().as_usize()] = eip8037::CODE_DEPOSIT_PER_BYTE;
            table[GasId::create_state_gas().as_usize()] = eip8037::NEW_ACCOUNT_BYTES;
            table[GasId::tx_eip7702_state_gas_bytecode().as_usize()] = eip8037::AUTH_BASE_BYTES;

            // SSTORE refund for 0→X→0 restoration: regular gas only.
            // The state-gas portion (SSTORE_SET_BYTES × CPSB) is restored directly
            // to the reservoir via `GasParams::sstore_state_gas_refill`.
            table[GasId::sstore_set_refund().as_usize()] = 2800;

            // EIP-7702 under EIP-8037: only the regular-gas slots live here.
            // The state-gas portions are sourced from `new_account_state_gas`
            // (per-account) and `tx_eip7702_state_gas_bytecode` (per-bytecode);
            // helpers in `GasParams` combine them with the current CPSB.
            //   regular per-auth cost: 7500 (state bytes added pessimistically in `initial_tx_gas`)
            //   regular refund:        0   (per-auth refund is entirely state gas)
            table[GasId::tx_eip7702_per_empty_account_cost().as_usize()] =
                eip8037::EIP7702_PER_EMPTY_ACCOUNT_REGULAR;
            table[GasId::tx_eip7702_auth_refund().as_usize()] = 0;

            // EIP-7976: Increase calldata floor cost from 10/40 to 64/64 gas per byte
            // (zero/nonzero). The per-token constant bumps from 10 to 16, and
            // `floor_tokens_in_calldata` switches from `zero + nonzero * 4` to
            // `(zero + nonzero) * 4`, i.e. every byte now costs 16 * 4 = 64 gas in the floor.
            table[GasId::tx_floor_cost_per_token().as_usize()] = 16;
            table[GasId::tx_floor_token_zero_byte_multiplier().as_usize()] =
                table[GasId::tx_token_non_zero_byte_multiplier().as_usize()];

            // EIP-7981: Charge access list data at 64 gas per byte, matching
            // calldata floor pricing. Per-item costs bake in the data charge:
            //   address: 2400 + 20 * 64 = 3680
            //   key:     1900 + 32 * 64 = 3948
            // And every access-list byte contributes 4 floor tokens (16 * 4 = 64 gas).
            table[GasId::tx_access_list_address_cost().as_usize()] =
                gas::ACCESS_LIST_ADDRESS + 20 * 64;
            table[GasId::tx_access_list_storage_key_cost().as_usize()] =
                gas::ACCESS_LIST_STORAGE_KEY + 32 * 64;
            table[GasId::tx_access_list_floor_byte_multiplier().as_usize()] = 4;
        }

        Self::new(Arc::new(table))
    }

    /// Gets the gas cost for the given gas id.
    #[inline]
    pub fn get(&self, id: GasId) -> u64 {
        self.table[id.as_usize()]
    }

    /// `EXP` opcode cost calculation.
    #[inline]
    pub fn exp_cost(&self, power: U256) -> u64 {
        if power.is_zero() {
            return 0;
        }
        // EIP-160: EXP cost increase
        self.get(GasId::exp_byte_gas())
            .saturating_mul(log2floor(power) / 8 + 1)
    }

    /// Selfdestruct refund.
    #[inline]
    pub fn selfdestruct_refund(&self) -> i64 {
        self.get(GasId::selfdestruct_refund()) as i64
    }

    /// Selfdestruct cold cost is calculated differently from other cold costs.
    /// and it contains both cold and warm costs.
    #[inline]
    pub fn selfdestruct_cold_cost(&self) -> u64 {
        self.cold_account_additional_cost() + self.warm_storage_read_cost()
    }

    /// Selfdestruct cost.
    #[inline]
    pub fn selfdestruct_cost(&self, should_charge_topup: bool, is_cold: bool) -> u64 {
        let mut gas = 0;

        // EIP-150: Gas cost changes for IO-heavy operations
        if should_charge_topup {
            gas += self.new_account_cost_for_selfdestruct();
        }

        if is_cold {
            // Note: SELFDESTRUCT does not charge a WARM_STORAGE_READ_COST in case the recipient is already warm,
            // which differs from how the other call-variants work. The reasoning behind this is to keep
            // the changes small, a SELFDESTRUCT already costs 5K and is a no-op if invoked more than once.
            //
            // For GasParams both values are zero before BERLIN fork.
            gas += self.selfdestruct_cold_cost();
        }
        gas
    }

    /// EXTCODECOPY gas cost
    #[inline]
    pub fn extcodecopy(&self, len: usize) -> u64 {
        self.get(GasId::extcodecopy_per_word())
            .saturating_mul(num_words(len) as u64)
    }

    /// MCOPY gas cost
    #[inline]
    pub fn mcopy_cost(&self, len: usize) -> u64 {
        self.get(GasId::mcopy_per_word())
            .saturating_mul(num_words(len) as u64)
    }

    /// Static gas cost for SSTORE opcode
    #[inline]
    pub fn sstore_static_gas(&self) -> u64 {
        self.get(GasId::sstore_static())
    }

    /// SSTORE set cost
    #[inline]
    pub fn sstore_set_without_load_cost(&self) -> u64 {
        self.get(GasId::sstore_set_without_load_cost())
    }

    /// SSTORE reset cost
    #[inline]
    pub fn sstore_reset_without_cold_load_cost(&self) -> u64 {
        self.get(GasId::sstore_reset_without_cold_load_cost())
    }

    /// SSTORE clearing slot refund
    #[inline]
    pub fn sstore_clearing_slot_refund(&self) -> u64 {
        self.get(GasId::sstore_clearing_slot_refund())
    }

    /// SSTORE set refund. Used in sstore_refund for SSTORE_SET_GAS - SLOAD_GAS.
    #[inline]
    pub fn sstore_set_refund(&self) -> u64 {
        self.get(GasId::sstore_set_refund())
    }

    /// SSTORE reset refund. Used in sstore_refund for SSTORE_RESET_GAS - SLOAD_GAS.
    #[inline]
    pub fn sstore_reset_refund(&self) -> u64 {
        self.get(GasId::sstore_reset_refund())
    }

    /// Dynamic gas cost for SSTORE opcode.
    ///
    /// Dynamic gas cost is gas that needs input from SSTORE operation to be calculated.
    #[inline]
    pub fn sstore_dynamic_gas(&self, is_istanbul: bool, vals: &SStoreResult, is_cold: bool) -> u64 {
        // frontier logic gets charged for every SSTORE operation if original value is zero.
        // this behaviour is fixed in istanbul fork.
        if !is_istanbul {
            if vals.is_present_zero() && !vals.is_new_zero() {
                return self.sstore_set_without_load_cost();
            } else {
                return self.sstore_reset_without_cold_load_cost();
            }
        }

        let mut gas = 0;

        // this will be zero before berlin fork.
        if is_cold {
            gas += self.cold_storage_cost();
        }

        // if new values changed present value and present value is unchanged from original.
        if vals.new_values_changes_present() && vals.is_original_eq_present() {
            gas += if vals.is_original_zero() {
                // set cost for creating storage slot (Zero slot means it is not existing).
                // and previous condition says present is same as original.
                self.sstore_set_without_load_cost()
            } else {
                // if new value is not zero, this means we are setting some value to it.
                self.sstore_reset_without_cold_load_cost()
            };
        }
        gas
    }

    /// SSTORE refund calculation.
    #[inline]
    pub fn sstore_refund(&self, is_istanbul: bool, vals: &SStoreResult) -> i64 {
        // EIP-3529: Reduction in refunds
        let sstore_clearing_slot_refund = self.sstore_clearing_slot_refund() as i64;

        if !is_istanbul {
            // // before istanbul fork, refund was always awarded without checking original state.
            if !vals.is_present_zero() && vals.is_new_zero() {
                return sstore_clearing_slot_refund;
            }
            return 0;
        }

        // If current value equals new value (this is a no-op)
        if vals.is_new_eq_present() {
            return 0;
        }

        // refund for the clearing of storage slot.
        // As new is not equal to present, new values zero means that original and present values are not zero
        if vals.is_original_eq_present() && vals.is_new_zero() {
            return sstore_clearing_slot_refund;
        }

        let mut refund = 0;
        // If original value is not 0
        if !vals.is_original_zero() {
            // If current value is 0 (also means that new value is not 0),
            if vals.is_present_zero() {
                // remove SSTORE_CLEARS_SCHEDULE gas from refund counter.
                refund -= sstore_clearing_slot_refund;
            // If new value is 0 (also means that current value is not 0),
            } else if vals.is_new_zero() {
                // add SSTORE_CLEARS_SCHEDULE gas to refund counter.
                refund += sstore_clearing_slot_refund;
            }
        }

        // If original value equals new value (this storage slot is reset)
        if vals.is_original_eq_new() {
            // If original value is 0
            if vals.is_original_zero() {
                // add SSTORE_SET_GAS - SLOAD_GAS to refund counter.
                refund += self.sstore_set_refund() as i64;
            // Otherwise
            } else {
                // add SSTORE_RESET_GAS - SLOAD_GAS gas to refund counter.
                refund += self.sstore_reset_refund() as i64;
            }
        }
        refund
    }

    /// `LOG` opcode cost calculation.
    #[inline]
    pub fn log_cost(&self, n: u8, len: u64) -> u64 {
        self.get(GasId::logdata())
            .saturating_mul(len)
            .saturating_add(self.get(GasId::logtopic()) * n as u64)
    }

    /// KECCAK256 gas cost per word
    #[inline]
    pub fn keccak256_cost(&self, len: usize) -> u64 {
        self.get(GasId::keccak256_per_word())
            .saturating_mul(num_words(len) as u64)
    }

    /// Memory gas cost
    #[inline]
    pub fn memory_cost(&self, len: usize) -> u64 {
        let len = len as u64;
        self.get(GasId::memory_linear_cost())
            .saturating_mul(len)
            .saturating_add(
                (len.saturating_mul(len))
                    .saturating_div(self.get(GasId::memory_quadratic_reduction())),
            )
    }

    /// Initcode word cost
    #[inline]
    pub fn initcode_cost(&self, len: usize) -> u64 {
        self.get(GasId::initcode_per_word())
            .saturating_mul(num_words(len) as u64)
    }

    /// Create gas cost
    #[inline]
    pub fn create_cost(&self) -> u64 {
        self.get(GasId::create())
    }

    /// Create2 gas cost.
    #[inline]
    pub fn create2_cost(&self, len: usize) -> u64 {
        self.get(GasId::create()).saturating_add(
            self.get(GasId::keccak256_per_word())
                .saturating_mul(num_words(len) as u64),
        )
    }

    /// Call stipend.
    #[inline]
    pub fn call_stipend(&self) -> u64 {
        self.get(GasId::call_stipend())
    }

    /// Call stipend reduction. Call stipend is reduced by 1/64 of the gas limit.
    #[inline]
    pub fn call_stipend_reduction(&self, gas_limit: u64) -> u64 {
        gas_limit - gas_limit / self.get(GasId::call_stipend_reduction())
    }

    /// Transfer value cost
    #[inline]
    pub fn transfer_value_cost(&self) -> u64 {
        self.get(GasId::transfer_value_cost())
    }

    /// Additional cold cost. Additional cold cost is added to the gas cost if the account is cold loaded.
    #[inline]
    pub fn cold_account_additional_cost(&self) -> u64 {
        self.get(GasId::cold_account_additional_cost())
    }

    /// Cold storage additional cost.
    #[inline]
    pub fn cold_storage_additional_cost(&self) -> u64 {
        self.get(GasId::cold_storage_additional_cost())
    }

    /// Cold storage cost.
    #[inline]
    pub fn cold_storage_cost(&self) -> u64 {
        self.get(GasId::cold_storage_cost())
    }

    /// New account cost. New account cost is added to the gas cost if the account is empty.
    #[inline]
    pub fn new_account_cost(&self, is_spurious_dragon: bool, transfers_value: bool) -> u64 {
        // EIP-161: State trie clearing (invariant-preserving alternative)
        // Pre-Spurious Dragon: always charge for new account
        // Post-Spurious Dragon: only charge if value is transferred
        if !is_spurious_dragon || transfers_value {
            return self.get(GasId::new_account_cost());
        }
        0
    }

    /// New account cost for selfdestruct.
    #[inline]
    pub fn new_account_cost_for_selfdestruct(&self) -> u64 {
        self.get(GasId::new_account_cost_for_selfdestruct())
    }

    /// Warm storage read cost. Warm storage read cost is added to the gas cost if the account is warm loaded.
    #[inline]
    pub fn warm_storage_read_cost(&self) -> u64 {
        self.get(GasId::warm_storage_read_cost())
    }

    /// Copy cost
    #[inline]
    pub fn copy_cost(&self, len: usize) -> u64 {
        self.copy_per_word_cost(num_words(len))
    }

    /// Copy per word cost
    #[inline]
    pub fn copy_per_word_cost(&self, word_num: usize) -> u64 {
        self.get(GasId::copy_per_word())
            .saturating_mul(word_num as u64)
    }

    /// Code deposit cost, calculated per byte as len * code_deposit_cost.
    #[inline]
    pub fn code_deposit_cost(&self, len: usize) -> u64 {
        self.get(GasId::code_deposit_cost())
            .saturating_mul(len as u64)
    }

    /// State gas for SSTORE: charges for new slot creation (zero → non-zero).
    #[inline]
    pub fn sstore_state_gas(&self, vals: &SStoreResult, cpsb: u64) -> u64 {
        if vals.new_values_changes_present()
            && vals.is_original_eq_present()
            && vals.is_original_zero()
        {
            self.get(GasId::sstore_set_state_gas()).saturating_mul(cpsb)
        } else {
            0
        }
    }

    /// State gas to refill the reservoir on 0→x→0 storage restoration (EIP-8037).
    ///
    /// When a storage slot is restored to its original zero value within the
    /// same transaction, the state gas originally charged for the 0→x
    /// transition is returned directly to the reservoir (not via the capped
    /// refund counter). Returns 0 in any other case.
    ///
    /// `cpsb` is the current `cost_per_state_byte` (see [`super::Cfg::cpsb`]).
    #[inline]
    pub fn sstore_state_gas_refill(&self, vals: &SStoreResult, cpsb: u64) -> u64 {
        if !vals.is_new_eq_present() && vals.is_original_eq_new() && vals.is_original_zero() {
            self.get(GasId::sstore_set_state_gas()).saturating_mul(cpsb)
        } else {
            0
        }
    }

    /// State gas for new account creation.
    #[inline]
    pub fn new_account_state_gas(&self, cpsb: u64) -> u64 {
        self.get(GasId::new_account_state_gas())
            .saturating_mul(cpsb)
    }

    /// State gas for code deposit of `len` bytes.
    #[inline]
    pub fn code_deposit_state_gas(&self, len: usize, cpsb: u64) -> u64 {
        self.get(GasId::code_deposit_state_gas())
            .saturating_mul(len as u64)
            .saturating_mul(cpsb)
    }

    /// State gas for contract metadata creation.
    #[inline]
    pub fn create_state_gas(&self, cpsb: u64) -> u64 {
        self.get(GasId::create_state_gas()).saturating_mul(cpsb)
    }

    /// Used in [GasParams::initial_tx_gas] to calculate the eip7702 per-auth cost.
    ///
    /// Under EIP-8037 this combines a regular portion with a state-bytes portion
    /// (new-account + bytecode) multiplied by `cpsb`. Pre-EIP-8037 the state-bytes
    /// portion is zero so this returns the legacy `PER_EMPTY_ACCOUNT_COST`.
    #[inline]
    pub fn tx_eip7702_per_empty_account_cost(&self, cpsb: u64) -> u64 {
        let regular = self.get(GasId::tx_eip7702_per_empty_account_cost());
        let state = self.tx_eip7702_state_gas(cpsb);
        regular.saturating_add(state)
    }

    /// EIP-7702 authorization refund per existing account.
    ///
    /// Pre-Amsterdam this is a fixed regular-gas refund (`PER_EMPTY_ACCOUNT_COST - PER_AUTH_BASE_COST`).
    /// Under EIP-8037 the refund is fully state gas, equal to the per-account
    /// state-gas portion (`NEW_ACCOUNT_BYTES * cpsb`).
    #[inline]
    pub fn tx_eip7702_auth_refund(&self, cpsb: u64) -> u64 {
        let regular = self.get(GasId::tx_eip7702_auth_refund());
        let state = self.new_account_state_gas(cpsb);
        regular.saturating_add(state)
    }

    /// EIP-8037: State gas per EIP-7702 authorization (pessimistic).
    ///
    /// Sums the new-account and bytecode state-bytes portions and multiplies by
    /// `cpsb`. Used for `initial_state_gas` tracking. Zero before AMSTERDAM.
    #[inline]
    pub fn tx_eip7702_state_gas(&self, cpsb: u64) -> u64 {
        let new_account = self.get(GasId::new_account_state_gas());
        let bytecode = self.get(GasId::tx_eip7702_state_gas_bytecode());
        new_account.saturating_add(bytecode).saturating_mul(cpsb)
    }

    /// EIP-7702 total state-gas refund for a transaction.
    ///
    /// Combines the per-account refund (`NEW_ACCOUNT_BYTES * cpsb` per refunded
    /// account, when the authorization targets an account that already exists)
    /// with the per-bytecode refund (`AUTH_BASE_BYTES * cpsb` per refunded
    /// bytecode, when the delegation target is already deployed). Returns zero
    /// before AMSTERDAM.
    #[inline]
    pub fn tx_eip7702_state_refund(
        &self,
        refunded_accounts: u64,
        refunded_bytecodes: u64,
        cpsb: u64,
    ) -> u64 {
        let per_account = self
            .get(GasId::new_account_state_gas())
            .saturating_mul(refunded_accounts);
        let per_bytecode = self
            .get(GasId::tx_eip7702_state_gas_bytecode())
            .saturating_mul(refunded_bytecodes);
        per_account
            .saturating_add(per_bytecode)
            .saturating_mul(cpsb)
    }

    /// EIP-7702 per-auth refund: regular-gas portion only.
    ///
    /// Pre-Amsterdam this is `PER_EMPTY_ACCOUNT_COST - PER_AUTH_BASE_COST` (12500).
    /// Under EIP-8037 it is zero — the refund is entirely state gas.
    #[inline]
    pub fn tx_eip7702_auth_refund_regular(&self) -> u64 {
        self.get(GasId::tx_eip7702_auth_refund())
    }

    /// Used in [GasParams::initial_tx_gas] to calculate the token non zero byte multiplier.
    #[inline]
    pub fn tx_token_non_zero_byte_multiplier(&self) -> u64 {
        self.get(GasId::tx_token_non_zero_byte_multiplier())
    }

    /// Used in [GasParams::initial_tx_gas] to calculate the token cost for input data.
    #[inline]
    pub fn tx_token_cost(&self) -> u64 {
        self.get(GasId::tx_token_cost())
    }

    /// Used in [GasParams::initial_tx_gas] to calculate the floor gas per token.
    pub fn tx_floor_cost_per_token(&self) -> u64 {
        self.get(GasId::tx_floor_cost_per_token())
    }

    /// Multiplier for a zero byte in the floor tokens calculation.
    ///
    /// Under EIP-7623 this is `1` (zero bytes count as one token), so the floor
    /// reuses `tokens_in_calldata`. Under [EIP-7976](https://eips.ethereum.org/EIPS/eip-7976)
    /// it is raised to [`tx_token_non_zero_byte_multiplier`](Self::tx_token_non_zero_byte_multiplier)
    /// so every calldata byte contributes the same amount (`floor_tokens_in_calldata =
    /// (zero + nonzero) * 4`).
    pub fn tx_floor_token_zero_byte_multiplier(&self) -> u64 {
        self.get(GasId::tx_floor_token_zero_byte_multiplier())
    }

    /// Floor gas cost for a transaction with the given calldata.
    ///
    /// Introduced by EIP-7623 and further updated by EIP-7976. Computes
    /// `tx_floor_cost_per_token * floor_tokens_in_calldata + tx_floor_cost_base_gas`,
    /// where
    /// `floor_tokens_in_calldata = zero * tx_floor_token_zero_byte_multiplier + nonzero * tx_token_non_zero_byte_multiplier`.
    /// When the two multipliers match (EIP-7976), every byte contributes the
    /// same amount, so the zero/nonzero split is skipped and `input.len()` is
    /// used directly; otherwise (EIP-7623 path, zero multiplier = 1) the result
    /// matches `get_tokens_in_calldata(input, nonzero)`.
    #[inline]
    pub fn tx_floor_cost(&self, input: &[u8]) -> u64 {
        let zero_multiplier = self.tx_floor_token_zero_byte_multiplier();
        let non_zero_multiplier = self.tx_token_non_zero_byte_multiplier();
        let floor_tokens = if zero_multiplier == non_zero_multiplier {
            input.len() as u64 * non_zero_multiplier
        } else {
            get_tokens_in_calldata(input, non_zero_multiplier)
        };
        self.tx_floor_cost_with_tokens(floor_tokens)
    }

    /// Calculate the floor gas cost for a transaction with the given number of tokens.
    #[inline]
    pub fn tx_floor_cost_with_tokens(&self, tokens: u64) -> u64 {
        self.tx_floor_cost_per_token() * tokens + self.tx_floor_cost_base_gas()
    }

    /// Used in [GasParams::initial_tx_gas] to calculate the floor gas base gas.
    pub fn tx_floor_cost_base_gas(&self) -> u64 {
        self.get(GasId::tx_floor_cost_base_gas())
    }

    /// Used in [GasParams::initial_tx_gas] to calculate the access list address cost.
    pub fn tx_access_list_address_cost(&self) -> u64 {
        self.get(GasId::tx_access_list_address_cost())
    }

    /// Used in [GasParams::initial_tx_gas] to calculate the access list storage key cost.
    pub fn tx_access_list_storage_key_cost(&self) -> u64 {
        self.get(GasId::tx_access_list_storage_key_cost())
    }

    /// Calculate the total gas cost for an access list.
    ///
    /// This is a helper method that calculates the combined cost of:
    /// - `accounts` addresses in the access list
    /// - `storages` storage keys in the access list
    ///
    /// # Examples
    ///
    /// ```
    /// use revm_context_interface::cfg::gas_params::GasParams;
    /// use primitives::hardfork::SpecId;
    ///
    /// let gas_params = GasParams::new_spec(SpecId::BERLIN);
    /// // Calculate cost for 2 addresses and 5 storage keys
    /// let cost = gas_params.tx_access_list_cost(2, 5);
    /// assert_eq!(cost, 2 * 2400 + 5 * 1900); // 2 * ACCESS_LIST_ADDRESS + 5 * ACCESS_LIST_STORAGE_KEY
    /// ```
    #[inline]
    pub fn tx_access_list_cost(&self, accounts: u64, storages: u64) -> u64 {
        accounts
            .saturating_mul(self.tx_access_list_address_cost())
            .saturating_add(storages.saturating_mul(self.tx_access_list_storage_key_cost()))
    }

    /// Floor tokens contributed per access-list byte ([EIP-7981]).
    ///
    /// Zero before AMSTERDAM. From AMSTERDAM onward this is `4`, so each
    /// access-list byte contributes the same 64 gas to the floor as a calldata
    /// byte under EIP-7976.
    ///
    /// [EIP-7981]: https://eips.ethereum.org/EIPS/eip-7981
    #[inline]
    pub fn tx_access_list_floor_byte_multiplier(&self) -> u64 {
        self.get(GasId::tx_access_list_floor_byte_multiplier())
    }

    /// Floor tokens contributed by an access list with the given address and
    /// storage-key counts (EIP-7981). Each address is 20 bytes, each storage
    /// key is 32 bytes; tokens per byte come from
    /// [`tx_access_list_floor_byte_multiplier`](Self::tx_access_list_floor_byte_multiplier).
    #[inline]
    pub fn tx_floor_tokens_in_access_list(&self, accounts: u64, storages: u64) -> u64 {
        let bytes = accounts
            .saturating_mul(20)
            .saturating_add(storages.saturating_mul(32));
        bytes.saturating_mul(self.tx_access_list_floor_byte_multiplier())
    }

    /// Used in [GasParams::initial_tx_gas] to calculate the base transaction stipend.
    pub fn tx_base_stipend(&self) -> u64 {
        self.get(GasId::tx_base_stipend())
    }

    /// Used in [GasParams::initial_tx_gas] to calculate the create cost.
    ///
    /// Similar to the [`Self::create_cost`] method but it got activated in different fork,
    #[inline]
    pub fn tx_create_cost(&self) -> u64 {
        self.get(GasId::tx_create_cost())
    }

    /// Used in [GasParams::initial_tx_gas] to calculate the initcode cost per word of len.
    #[inline]
    pub fn tx_initcode_cost(&self, len: usize) -> u64 {
        self.get(GasId::tx_initcode_cost())
            .saturating_mul(num_words(len) as u64)
    }

    /// Initial gas that is deducted for transaction to be included.
    /// Initial gas contains initial stipend gas, gas for access list and input data.
    ///
    /// Under EIP-8037, state gas is tracked separately in `initial_state_gas`,
    /// while regular intrinsic gas accumulates in `initial_regular_gas`. The state
    /// gas components are:
    /// - EIP-7702 auth list state gas (per-auth account creation + metadata costs)
    /// - For CREATE transactions: `create_state_gas` (account creation + contract metadata)
    ///
    /// Note: `code_deposit_state_gas` is not included since deployed code size is unknown at validation time.
    ///
    /// # Returns
    ///
    /// - Intrinsic gas (including state gas for CREATE)
    /// - Number of tokens in calldata
    pub fn initial_tx_gas(
        &self,
        input: &[u8],
        is_create: bool,
        access_list_accounts: u64,
        access_list_storages: u64,
        authorization_list_num: u64,
        cpsb: u64,
    ) -> InitialAndFloorGas {
        // Initdate stipend
        let tokens_in_calldata =
            get_tokens_in_calldata(input, self.tx_token_non_zero_byte_multiplier());

        // EIP-7702: Compute auth list costs.
        // Under EIP-8037, tx_eip7702_per_empty_account_cost bundles regular + state gas.
        // We split them: regular goes in initial_regular_gas, state goes in initial_state_gas.
        let auth_total_cost = authorization_list_num * self.tx_eip7702_per_empty_account_cost(cpsb);
        let auth_state_gas = authorization_list_num * self.tx_eip7702_state_gas(cpsb);

        let auth_regular_cost = auth_total_cost - auth_state_gas;

        let mut initial_regular_gas = tokens_in_calldata * self.tx_token_cost()
            // before berlin tx_access_list_address_cost will be zero
            + access_list_accounts * self.tx_access_list_address_cost()
            // before berlin tx_access_list_storage_key_cost will be zero
            + access_list_storages * self.tx_access_list_storage_key_cost()
            + self.tx_base_stipend()
            // EIP-7702: Only the regular portion of auth list cost
            + auth_regular_cost;

        // EIP-8037: Track auth list state gas separately for reservoir handling.
        let mut initial_state_gas = auth_state_gas;

        if is_create {
            // EIP-2: Homestead Hard-fork Changes
            initial_regular_gas += self.tx_create_cost();

            // EIP-3860: Limit and meter initcode
            initial_regular_gas += self.tx_initcode_cost(input.len());

            // EIP-8037: State gas for CREATE transactions.
            // create_state_gas covers both account creation and contract metadata.
            initial_state_gas += self.create_state_gas(cpsb);
        }

        // Calculate gas floor. Introduced by EIP-7623, updated by EIP-7976, and
        // extended by EIP-7981 to include access-list data alongside calldata.
        let access_list_floor_tokens =
            self.tx_floor_tokens_in_access_list(access_list_accounts, access_list_storages);
        let floor_gas =
            self.tx_floor_cost(input) + access_list_floor_tokens * self.tx_floor_cost_per_token();

        InitialAndFloorGas::default()
            .with_initial_regular_gas(initial_regular_gas)
            .with_initial_state_gas(initial_state_gas)
            .with_floor_gas(floor_gas)
    }
}

#[inline]
pub(crate) const fn log2floor(value: U256) -> u64 {
    255u64.saturating_sub(value.leading_zeros() as u64)
}

/// Gas identifier that maps onto index in gas table.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GasId(u8);

impl GasId {
    /// Creates a new `GasId` with the given id.
    #[inline]
    pub const fn new(id: u8) -> Self {
        Self(id)
    }

    /// Returns the id of the gas.
    #[inline]
    pub const fn as_u8(&self) -> u8 {
        self.0
    }

    /// Returns the id of the gas as a usize.
    #[inline]
    pub const fn as_usize(&self) -> usize {
        self.0 as usize
    }

    /// Returns the name of the gas identifier as a string.
    ///
    /// # Examples
    ///
    /// ```
    /// use revm_context_interface::cfg::gas_params::GasId;
    ///
    /// assert_eq!(GasId::exp_byte_gas().name(), "exp_byte_gas");
    /// assert_eq!(GasId::memory_linear_cost().name(), "memory_linear_cost");
    /// assert_eq!(GasId::sstore_static().name(), "sstore_static");
    /// ```
    pub const fn name(&self) -> &'static str {
        match self.0 {
            x if x == Self::exp_byte_gas().as_u8() => "exp_byte_gas",
            x if x == Self::extcodecopy_per_word().as_u8() => "extcodecopy_per_word",
            x if x == Self::copy_per_word().as_u8() => "copy_per_word",
            x if x == Self::logdata().as_u8() => "logdata",
            x if x == Self::logtopic().as_u8() => "logtopic",
            x if x == Self::mcopy_per_word().as_u8() => "mcopy_per_word",
            x if x == Self::keccak256_per_word().as_u8() => "keccak256_per_word",
            x if x == Self::memory_linear_cost().as_u8() => "memory_linear_cost",
            x if x == Self::memory_quadratic_reduction().as_u8() => "memory_quadratic_reduction",
            x if x == Self::initcode_per_word().as_u8() => "initcode_per_word",
            x if x == Self::create().as_u8() => "create",
            x if x == Self::call_stipend_reduction().as_u8() => "call_stipend_reduction",
            x if x == Self::transfer_value_cost().as_u8() => "transfer_value_cost",
            x if x == Self::cold_account_additional_cost().as_u8() => {
                "cold_account_additional_cost"
            }
            x if x == Self::new_account_cost().as_u8() => "new_account_cost",
            x if x == Self::warm_storage_read_cost().as_u8() => "warm_storage_read_cost",
            x if x == Self::sstore_static().as_u8() => "sstore_static",
            x if x == Self::sstore_set_without_load_cost().as_u8() => {
                "sstore_set_without_load_cost"
            }
            x if x == Self::sstore_reset_without_cold_load_cost().as_u8() => {
                "sstore_reset_without_cold_load_cost"
            }
            x if x == Self::sstore_clearing_slot_refund().as_u8() => "sstore_clearing_slot_refund",
            x if x == Self::selfdestruct_refund().as_u8() => "selfdestruct_refund",
            x if x == Self::call_stipend().as_u8() => "call_stipend",
            x if x == Self::cold_storage_additional_cost().as_u8() => {
                "cold_storage_additional_cost"
            }
            x if x == Self::cold_storage_cost().as_u8() => "cold_storage_cost",
            x if x == Self::new_account_cost_for_selfdestruct().as_u8() => {
                "new_account_cost_for_selfdestruct"
            }
            x if x == Self::code_deposit_cost().as_u8() => "code_deposit_cost",
            x if x == Self::tx_eip7702_per_empty_account_cost().as_u8() => {
                "tx_eip7702_per_empty_account_cost"
            }
            x if x == Self::tx_token_non_zero_byte_multiplier().as_u8() => {
                "tx_token_non_zero_byte_multiplier"
            }
            x if x == Self::tx_token_cost().as_u8() => "tx_token_cost",
            x if x == Self::tx_floor_cost_per_token().as_u8() => "tx_floor_cost_per_token",
            x if x == Self::tx_floor_cost_base_gas().as_u8() => "tx_floor_cost_base_gas",
            x if x == Self::tx_access_list_address_cost().as_u8() => "tx_access_list_address_cost",
            x if x == Self::tx_access_list_storage_key_cost().as_u8() => {
                "tx_access_list_storage_key_cost"
            }
            x if x == Self::tx_base_stipend().as_u8() => "tx_base_stipend",
            x if x == Self::tx_create_cost().as_u8() => "tx_create_cost",
            x if x == Self::tx_initcode_cost().as_u8() => "tx_initcode_cost",
            x if x == Self::sstore_set_refund().as_u8() => "sstore_set_refund",
            x if x == Self::sstore_reset_refund().as_u8() => "sstore_reset_refund",
            x if x == Self::tx_eip7702_auth_refund().as_u8() => "tx_eip7702_auth_refund",
            x if x == Self::sstore_set_state_gas().as_u8() => "sstore_set_state_gas",
            x if x == Self::new_account_state_gas().as_u8() => "new_account_state_gas",
            x if x == Self::code_deposit_state_gas().as_u8() => "code_deposit_state_gas",
            x if x == Self::create_state_gas().as_u8() => "create_state_gas",
            x if x == Self::tx_eip7702_state_gas_bytecode().as_u8() => {
                "tx_eip7702_state_gas_bytecode"
            }
            x if x == Self::tx_floor_token_zero_byte_multiplier().as_u8() => {
                "tx_floor_token_zero_byte_multiplier"
            }
            x if x == Self::tx_access_list_floor_byte_multiplier().as_u8() => {
                "tx_access_list_floor_byte_multiplier"
            }
            _ => "unknown",
        }
    }

    /// Converts a string to a `GasId`.
    ///
    /// Returns `None` if the string does not match any known gas identifier.
    ///
    /// # Examples
    ///
    /// ```
    /// use revm_context_interface::cfg::gas_params::GasId;
    ///
    /// assert_eq!(GasId::from_name("exp_byte_gas"), Some(GasId::exp_byte_gas()));
    /// assert_eq!(GasId::from_name("memory_linear_cost"), Some(GasId::memory_linear_cost()));
    /// assert_eq!(GasId::from_name("invalid_name"), None);
    /// ```
    pub fn from_name(s: &str) -> Option<GasId> {
        match s {
            "exp_byte_gas" => Some(Self::exp_byte_gas()),
            "extcodecopy_per_word" => Some(Self::extcodecopy_per_word()),
            "copy_per_word" => Some(Self::copy_per_word()),
            "logdata" => Some(Self::logdata()),
            "logtopic" => Some(Self::logtopic()),
            "mcopy_per_word" => Some(Self::mcopy_per_word()),
            "keccak256_per_word" => Some(Self::keccak256_per_word()),
            "memory_linear_cost" => Some(Self::memory_linear_cost()),
            "memory_quadratic_reduction" => Some(Self::memory_quadratic_reduction()),
            "initcode_per_word" => Some(Self::initcode_per_word()),
            "create" => Some(Self::create()),
            "call_stipend_reduction" => Some(Self::call_stipend_reduction()),
            "transfer_value_cost" => Some(Self::transfer_value_cost()),
            "cold_account_additional_cost" => Some(Self::cold_account_additional_cost()),
            "new_account_cost" => Some(Self::new_account_cost()),
            "warm_storage_read_cost" => Some(Self::warm_storage_read_cost()),
            "sstore_static" => Some(Self::sstore_static()),
            "sstore_set_without_load_cost" => Some(Self::sstore_set_without_load_cost()),
            "sstore_reset_without_cold_load_cost" => {
                Some(Self::sstore_reset_without_cold_load_cost())
            }
            "sstore_clearing_slot_refund" => Some(Self::sstore_clearing_slot_refund()),
            "selfdestruct_refund" => Some(Self::selfdestruct_refund()),
            "call_stipend" => Some(Self::call_stipend()),
            "cold_storage_additional_cost" => Some(Self::cold_storage_additional_cost()),
            "cold_storage_cost" => Some(Self::cold_storage_cost()),
            "new_account_cost_for_selfdestruct" => Some(Self::new_account_cost_for_selfdestruct()),
            "code_deposit_cost" => Some(Self::code_deposit_cost()),
            "tx_eip7702_per_empty_account_cost" => Some(Self::tx_eip7702_per_empty_account_cost()),
            "tx_token_non_zero_byte_multiplier" => Some(Self::tx_token_non_zero_byte_multiplier()),
            "tx_token_cost" => Some(Self::tx_token_cost()),
            "tx_floor_cost_per_token" => Some(Self::tx_floor_cost_per_token()),
            "tx_floor_cost_base_gas" => Some(Self::tx_floor_cost_base_gas()),
            "tx_access_list_address_cost" => Some(Self::tx_access_list_address_cost()),
            "tx_access_list_storage_key_cost" => Some(Self::tx_access_list_storage_key_cost()),
            "tx_base_stipend" => Some(Self::tx_base_stipend()),
            "tx_create_cost" => Some(Self::tx_create_cost()),
            "tx_initcode_cost" => Some(Self::tx_initcode_cost()),
            "sstore_set_refund" => Some(Self::sstore_set_refund()),
            "sstore_reset_refund" => Some(Self::sstore_reset_refund()),
            "tx_eip7702_auth_refund" => Some(Self::tx_eip7702_auth_refund()),
            "sstore_set_state_gas" => Some(Self::sstore_set_state_gas()),
            "new_account_state_gas" => Some(Self::new_account_state_gas()),
            "code_deposit_state_gas" => Some(Self::code_deposit_state_gas()),
            "create_state_gas" => Some(Self::create_state_gas()),
            "tx_eip7702_state_gas_bytecode" => Some(Self::tx_eip7702_state_gas_bytecode()),
            "tx_floor_token_zero_byte_multiplier" => {
                Some(Self::tx_floor_token_zero_byte_multiplier())
            }
            "tx_access_list_floor_byte_multiplier" => {
                Some(Self::tx_access_list_floor_byte_multiplier())
            }
            _ => None,
        }
    }

    /// EXP gas cost per byte
    pub const fn exp_byte_gas() -> GasId {
        Self::new(1)
    }

    /// EXTCODECOPY gas cost per word
    pub const fn extcodecopy_per_word() -> GasId {
        Self::new(2)
    }

    /// Copy copy per word
    pub const fn copy_per_word() -> GasId {
        Self::new(3)
    }

    /// Log data gas cost per byte
    pub const fn logdata() -> GasId {
        Self::new(4)
    }

    /// Log topic gas cost per topic
    pub const fn logtopic() -> GasId {
        Self::new(5)
    }

    /// MCOPY gas cost per word
    pub const fn mcopy_per_word() -> GasId {
        Self::new(6)
    }

    /// KECCAK256 gas cost per word
    pub const fn keccak256_per_word() -> GasId {
        Self::new(7)
    }

    /// Memory linear cost. Memory is additionally added as n*linear_cost.
    pub const fn memory_linear_cost() -> GasId {
        Self::new(8)
    }

    /// Memory quadratic reduction. Memory is additionally added as n*n/quadratic_reduction.
    pub const fn memory_quadratic_reduction() -> GasId {
        Self::new(9)
    }

    /// Initcode word cost
    pub const fn initcode_per_word() -> GasId {
        Self::new(10)
    }

    /// Create gas cost
    pub const fn create() -> GasId {
        Self::new(11)
    }

    /// Call stipend reduction. Call stipend is reduced by 1/64 of the gas limit.
    pub const fn call_stipend_reduction() -> GasId {
        Self::new(12)
    }

    /// Transfer value cost
    pub const fn transfer_value_cost() -> GasId {
        Self::new(13)
    }

    /// Additional cold cost. Additional cold cost is added to the gas cost if the account is cold loaded.
    pub const fn cold_account_additional_cost() -> GasId {
        Self::new(14)
    }

    /// New account cost. New account cost is added to the gas cost if the account is empty.
    pub const fn new_account_cost() -> GasId {
        Self::new(15)
    }

    /// Warm storage read cost. Warm storage read cost is added to the gas cost if the account is warm loaded.
    ///
    /// Used in delegated account access to specify delegated account warm gas cost.
    pub const fn warm_storage_read_cost() -> GasId {
        Self::new(16)
    }

    /// Static gas cost for SSTORE opcode. This gas in comparison with other gas const needs
    /// to be deducted after check for minimal stipend gas cost. This is a reason why it is here.
    pub const fn sstore_static() -> GasId {
        Self::new(17)
    }

    /// SSTORE set cost additional amount after SSTORE_RESET is added.
    pub const fn sstore_set_without_load_cost() -> GasId {
        Self::new(18)
    }

    /// SSTORE reset cost
    pub const fn sstore_reset_without_cold_load_cost() -> GasId {
        Self::new(19)
    }

    /// SSTORE clearing slot refund
    pub const fn sstore_clearing_slot_refund() -> GasId {
        Self::new(20)
    }

    /// Selfdestruct refund.
    pub const fn selfdestruct_refund() -> GasId {
        Self::new(21)
    }

    /// Call stipend checked in sstore.
    pub const fn call_stipend() -> GasId {
        Self::new(22)
    }

    /// Cold storage additional cost.
    pub const fn cold_storage_additional_cost() -> GasId {
        Self::new(23)
    }

    /// Cold storage cost
    pub const fn cold_storage_cost() -> GasId {
        Self::new(24)
    }

    /// New account cost for selfdestruct.
    pub const fn new_account_cost_for_selfdestruct() -> GasId {
        Self::new(25)
    }

    /// Code deposit cost. Calculated as len * code_deposit_cost.
    pub const fn code_deposit_cost() -> GasId {
        Self::new(26)
    }

    /// EIP-7702 PER_EMPTY_ACCOUNT_COST gas
    pub const fn tx_eip7702_per_empty_account_cost() -> GasId {
        Self::new(27)
    }

    /// Initial tx gas token non zero byte multiplier.
    pub const fn tx_token_non_zero_byte_multiplier() -> GasId {
        Self::new(28)
    }

    /// Initial tx gas token cost.
    pub const fn tx_token_cost() -> GasId {
        Self::new(29)
    }

    /// Initial tx gas floor cost per token.
    pub const fn tx_floor_cost_per_token() -> GasId {
        Self::new(30)
    }

    /// Initial tx gas floor cost base gas.
    pub const fn tx_floor_cost_base_gas() -> GasId {
        Self::new(31)
    }

    /// Initial tx gas access list address cost.
    pub const fn tx_access_list_address_cost() -> GasId {
        Self::new(32)
    }

    /// Initial tx gas access list storage key cost.
    pub const fn tx_access_list_storage_key_cost() -> GasId {
        Self::new(33)
    }

    /// Initial tx gas base stipend.
    pub const fn tx_base_stipend() -> GasId {
        Self::new(34)
    }

    /// Initial tx gas create cost.
    pub const fn tx_create_cost() -> GasId {
        Self::new(35)
    }

    /// Initial tx gas initcode cost per word.
    pub const fn tx_initcode_cost() -> GasId {
        Self::new(36)
    }

    /// SSTORE set refund. Used in sstore_refund for SSTORE_SET_GAS - SLOAD_GAS refund calculation.
    pub const fn sstore_set_refund() -> GasId {
        Self::new(37)
    }

    /// SSTORE reset refund. Used in sstore_refund for SSTORE_RESET_GAS - SLOAD_GAS refund calculation.
    pub const fn sstore_reset_refund() -> GasId {
        Self::new(38)
    }

    /// EIP-7702 authorization refund per existing account.
    /// This is the refund given when an authorization is applied to an already existing account.
    /// Calculated as PER_EMPTY_ACCOUNT_COST - PER_AUTH_BASE_COST (25000 - 12500 = 12500).
    pub const fn tx_eip7702_auth_refund() -> GasId {
        Self::new(39)
    }

    /// State gas for new storage slot creation (SSTORE zero → non-zero).
    pub const fn sstore_set_state_gas() -> GasId {
        Self::new(40)
    }

    /// State gas for new account creation.
    pub const fn new_account_state_gas() -> GasId {
        Self::new(41)
    }

    /// State gas per byte for code deposit.
    pub const fn code_deposit_state_gas() -> GasId {
        Self::new(42)
    }

    /// State gas for contract metadata creation.
    pub const fn create_state_gas() -> GasId {
        Self::new(43)
    }

    /// EIP-8037: State bytes for the bytecode (delegation) portion of an EIP-7702 authorization.
    /// Equals `eip8037::AUTH_BASE_BYTES`. Multiplied by CPSB at charge time.
    /// Zero before AMSTERDAM.
    pub const fn tx_eip7702_state_gas_bytecode() -> GasId {
        Self::new(44)
    }

    /// Multiplier for a zero byte in `floor_tokens_in_calldata`.
    ///
    /// `1` under [EIP-7623](https://eips.ethereum.org/EIPS/eip-7623) and raised
    /// to [`tx_token_non_zero_byte_multiplier`](Self::tx_token_non_zero_byte_multiplier)
    /// under [EIP-7976](https://eips.ethereum.org/EIPS/eip-7976), which makes the
    /// floor cost uniform across zero and nonzero calldata bytes. Zero before PRAGUE.
    pub const fn tx_floor_token_zero_byte_multiplier() -> GasId {
        Self::new(45)
    }

    /// Floor tokens contributed per byte of access-list data (EIP-7981).
    ///
    /// Zero before AMSTERDAM. From AMSTERDAM onward, set to `4` so every
    /// access-list byte contributes the same 16 × 4 = 64 gas as a calldata byte
    /// under EIP-7976.
    pub const fn tx_access_list_floor_byte_multiplier() -> GasId {
        Self::new(46)
    }
}

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

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

        #[test]
        fn test_log2floor_edge_cases() {
            // Test zero
            assert_eq!(log2floor(U256::ZERO), 0);

            // Test powers of 2
            assert_eq!(log2floor(U256::from(1u64)), 0); // log2(1) = 0
            assert_eq!(log2floor(U256::from(2u64)), 1); // log2(2) = 1
            assert_eq!(log2floor(U256::from(4u64)), 2); // log2(4) = 2
            assert_eq!(log2floor(U256::from(8u64)), 3); // log2(8) = 3
            assert_eq!(log2floor(U256::from(256u64)), 8); // log2(256) = 8

            // Test non-powers of 2
            assert_eq!(log2floor(U256::from(3u64)), 1); // log2(3) = 1.58... -> floor = 1
            assert_eq!(log2floor(U256::from(5u64)), 2); // log2(5) = 2.32... -> floor = 2
            assert_eq!(log2floor(U256::from(255u64)), 7); // log2(255) = 7.99... -> floor = 7

            // Test large values
            assert_eq!(log2floor(U256::from(u64::MAX)), 63);
            assert_eq!(log2floor(U256::from(u64::MAX) + U256::from(1u64)), 64);
            assert_eq!(log2floor(U256::MAX), 255);
        }
    }

    #[test]
    fn test_gas_id_name_and_from_str_coverage() {
        let mut unique_names = HashSet::new();
        let mut known_gas_ids = 0;

        // Iterate over all possible GasId values (0..256)
        for i in 0..=255 {
            let gas_id = GasId::new(i);
            let name = gas_id.name();

            // Count unique names (excluding "unknown")
            if name != "unknown" {
                unique_names.insert(name);
            }
        }

        // Now test from_str for each unique name
        for name in &unique_names {
            if let Some(gas_id) = GasId::from_name(name) {
                known_gas_ids += 1;
                // Verify round-trip: name -> GasId -> name should be consistent
                assert_eq!(gas_id.name(), *name, "Round-trip failed for {}", name);
            }
        }

        println!("Total unique named GasIds: {}", unique_names.len());
        println!("GasIds resolvable via from_str: {}", known_gas_ids);

        // All unique names should be resolvable via from_str
        assert_eq!(
            unique_names.len(),
            known_gas_ids,
            "Not all unique names are resolvable via from_str"
        );

        // We should have exactly 46 known GasIds (based on the indices 1-46 used)
        assert_eq!(
            unique_names.len(),
            46,
            "Expected 46 unique GasIds, found {}",
            unique_names.len()
        );
    }

    #[test]
    fn test_tx_access_list_cost() {
        use crate::cfg::gas;

        // Test with Berlin spec (when access list was introduced)
        let gas_params = GasParams::new_spec(SpecId::BERLIN);

        // Test with 0 accounts and 0 storages
        assert_eq!(gas_params.tx_access_list_cost(0, 0), 0);

        // Test with 1 account and 0 storages
        assert_eq!(
            gas_params.tx_access_list_cost(1, 0),
            gas::ACCESS_LIST_ADDRESS
        );

        // Test with 0 accounts and 1 storage
        assert_eq!(
            gas_params.tx_access_list_cost(0, 1),
            gas::ACCESS_LIST_STORAGE_KEY
        );

        // Test with 2 accounts and 5 storages
        assert_eq!(
            gas_params.tx_access_list_cost(2, 5),
            2 * gas::ACCESS_LIST_ADDRESS + 5 * gas::ACCESS_LIST_STORAGE_KEY
        );

        // Test with large numbers to ensure no overflow
        assert_eq!(
            gas_params.tx_access_list_cost(100, 200),
            100 * gas::ACCESS_LIST_ADDRESS + 200 * gas::ACCESS_LIST_STORAGE_KEY
        );

        // Test with pre-Berlin spec (should return 0)
        let gas_params_pre_berlin = GasParams::new_spec(SpecId::ISTANBUL);
        assert_eq!(gas_params_pre_berlin.tx_access_list_cost(10, 20), 0);
    }

    #[test]
    fn test_initial_state_gas_for_create() {
        // Use AMSTERDAM spec since EIP-8037 state gas is only enabled starting from Amsterdam.
        let gas_params = GasParams::new_spec(SpecId::AMSTERDAM);
        let cpsb = eip8037::CPSB_GLAMSTERDAM;

        // Test CREATE transaction (is_create = true)
        let create_gas = gas_params.initial_tx_gas(b"", true, 0, 0, 0, cpsb);
        let expected_state_gas = gas_params.create_state_gas(cpsb);

        assert_eq!(create_gas.initial_state_gas_final(), expected_state_gas);
        assert_eq!(
            create_gas.initial_state_gas_final(),
            eip8037::NEW_ACCOUNT_BYTES * eip8037::CPSB_GLAMSTERDAM
        );

        // initial_total_gas() returns both regular and state gas combined
        let create_cost = gas_params.tx_create_cost();
        let initcode_cost = gas_params.tx_initcode_cost(0);
        assert_eq!(
            create_gas.initial_total_gas(),
            gas_params.tx_base_stipend() + create_cost + initcode_cost + expected_state_gas
        );

        // Test CALL transaction (is_create = false)
        let call_gas = gas_params.initial_tx_gas(b"", false, 0, 0, 0, cpsb);
        assert_eq!(call_gas.initial_state_gas_final(), 0);
        // initial_gas should be unchanged for calls
        assert_eq!(call_gas.initial_total_gas(), gas_params.tx_base_stipend());
    }

    #[test]
    fn test_eip7981_access_list_cost_amsterdam() {
        // EIP-7981 folds a 64 gas/byte data charge into the per-item access-list cost
        // and adds 4 floor tokens per access-list byte on top of the EIP-7976 floor.
        let params = GasParams::new_spec(SpecId::AMSTERDAM);

        // Per-item intrinsic cost: base + bytes * 64
        assert_eq!(params.tx_access_list_address_cost(), 2400 + 20 * 64);
        assert_eq!(params.tx_access_list_storage_key_cost(), 1900 + 32 * 64);
        assert_eq!(params.tx_access_list_cost(1, 0), 2400 + 20 * 64);
        assert_eq!(params.tx_access_list_cost(0, 1), 1900 + 32 * 64);

        // Floor multiplier activates at AMSTERDAM.
        assert_eq!(params.tx_access_list_floor_byte_multiplier(), 4);
        // 2 addresses (40 bytes) + 3 keys (96 bytes) = 136 bytes => 544 floor tokens.
        assert_eq!(params.tx_floor_tokens_in_access_list(2, 3), (40 + 96) * 4);

        // Floor gas includes both calldata (empty here) and access-list contribution.
        let gas = params.initial_tx_gas(b"", false, 2, 3, 0, 0);
        let expected_al_floor = (40 + 96) * 4 * params.tx_floor_cost_per_token();
        assert_eq!(
            gas.floor_gas(),
            params.tx_floor_cost_base_gas() + expected_al_floor,
        );

        // Pre-AMSTERDAM the access-list floor contribution is zero.
        let prague = GasParams::new_spec(SpecId::PRAGUE);
        assert_eq!(prague.tx_access_list_floor_byte_multiplier(), 0);
        assert_eq!(prague.tx_floor_tokens_in_access_list(2, 3), 0);
        let prague_gas = prague.initial_tx_gas(b"", false, 2, 3, 0, 0);
        assert_eq!(prague_gas.floor_gas(), prague.tx_floor_cost_base_gas());
    }
}