op_alloy_genesis/
system.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
//! System Config Type

use crate::RollupConfig;
use alloy_consensus::{Eip658Value, Receipt};
use alloy_primitives::{address, b256, Address, Log, B256, B64, U256, U64};
use alloy_sol_types::{sol, SolType};

/// `keccak256("ConfigUpdate(uint256,uint8,bytes)")`
pub const CONFIG_UPDATE_TOPIC: B256 =
    b256!("1d2b0bda21d56b8bd12d4f94ebacffdfb35f5e226f84b461103bb8beab6353be");

/// The initial version of the system config event log.
pub const CONFIG_UPDATE_EVENT_VERSION_0: B256 = B256::ZERO;

/// System configuration.
#[derive(Debug, Copy, Clone, Default, Hash, Eq, PartialEq)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct SystemConfig {
    /// Batcher address
    #[cfg_attr(feature = "serde", serde(rename = "batcherAddr"))]
    pub batcher_address: Address,
    /// Fee overhead value
    pub overhead: U256,
    /// Fee scalar value
    pub scalar: U256,
    /// Gas limit value
    pub gas_limit: u64,
    /// Base fee scalar value
    pub base_fee_scalar: Option<u64>,
    /// Blob base fee scalar value
    pub blob_base_fee_scalar: Option<u64>,
    /// EIP-1559 denominator
    pub eip1559_denominator: Option<u32>,
    /// EIP-1559 elasticity
    pub eip1559_elasticity: Option<u32>,
}

/// Represents type of update to the system config.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
#[repr(u64)]
pub enum SystemConfigUpdateType {
    /// Batcher update type
    Batcher = 0,
    /// Gas config update type
    GasConfig = 1,
    /// Gas limit update type
    GasLimit = 2,
    /// Unsafe block signer update type
    UnsafeBlockSigner = 3,
    /// EIP-1559 parameters update type
    Eip1559 = 4,
}

impl TryFrom<u64> for SystemConfigUpdateType {
    type Error = SystemConfigUpdateError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(Self::Batcher),
            1 => Ok(Self::GasConfig),
            2 => Ok(Self::GasLimit),
            3 => Ok(Self::UnsafeBlockSigner),
            4 => Ok(Self::Eip1559),
            _ => Err(SystemConfigUpdateError::LogProcessing(
                LogProcessingError::InvalidSystemConfigUpdateType(value),
            )),
        }
    }
}

impl SystemConfig {
    /// Filters all L1 receipts to find config updates and applies the config updates.
    pub fn update_with_receipts(
        &mut self,
        receipts: &[Receipt],
        l1_system_config_address: Address,
        ecotone_active: bool,
    ) -> Result<(), SystemConfigUpdateError> {
        for receipt in receipts {
            if Eip658Value::Eip658(false) == receipt.status {
                continue;
            }

            receipt.logs.iter().try_for_each(|log| {
                let topics = log.topics();
                if log.address == l1_system_config_address
                    && !topics.is_empty()
                    && topics[0] == CONFIG_UPDATE_TOPIC
                {
                    // Safety: Error is bubbled up by the trailing `?`
                    self.process_config_update_log(log, ecotone_active)?;
                }
                Ok(())
            })?;
        }
        Ok(())
    }

    /// Returns the eip1559 parameters from a [SystemConfig] encoded as a [B64].
    pub fn eip_1559_params(
        &self,
        rollup_config: &RollupConfig,
        parent_timestamp: u64,
        next_timestamp: u64,
    ) -> Option<B64> {
        let is_holocene = rollup_config.is_holocene_active(next_timestamp);

        // For the first holocene block, a zero'd out B64 is returned to signal the
        // execution layer to use the canyon base fee parameters. Else, the system
        // config's eip1559 parameters are encoded as a B64.
        if is_holocene && !rollup_config.is_holocene_active(parent_timestamp) {
            Some(B64::ZERO)
        } else {
            is_holocene.then_some(B64::from_slice(
                &[
                    self.eip1559_denominator.unwrap_or_default().to_be_bytes(),
                    self.eip1559_elasticity.unwrap_or_default().to_be_bytes(),
                ]
                .concat(),
            ))
        }
    }

    /// Decodes an EVM log entry emitted by the system config contract and applies it as a
    /// [SystemConfig] change.
    ///
    /// Parse log data for:
    ///
    /// ```text
    /// event ConfigUpdate(
    ///    uint256 indexed version,
    ///    UpdateType indexed updateType,
    ///    bytes data
    /// );
    /// ```
    fn process_config_update_log(
        &mut self,
        log: &Log,
        ecotone_active: bool,
    ) -> Result<SystemConfigUpdateType, SystemConfigUpdateError> {
        // Validate the log
        if log.topics().len() < 3 {
            return Err(SystemConfigUpdateError::LogProcessing(
                LogProcessingError::InvalidTopicLen(log.topics().len()),
            ));
        }
        if log.topics()[0] != CONFIG_UPDATE_TOPIC {
            return Err(SystemConfigUpdateError::LogProcessing(LogProcessingError::InvalidTopic));
        }

        // Parse the config update log
        let version = log.topics()[1];
        if version != CONFIG_UPDATE_EVENT_VERSION_0 {
            return Err(SystemConfigUpdateError::LogProcessing(
                LogProcessingError::UnsupportedVersion(version),
            ));
        }
        let Ok(topic_bytes) = <&[u8; 8]>::try_from(&log.topics()[2].as_slice()[24..]) else {
            return Err(SystemConfigUpdateError::LogProcessing(
                LogProcessingError::UpdateTypeDecodingError,
            ));
        };
        let update_type = u64::from_be_bytes(*topic_bytes);
        let log_data = log.data.data.as_ref();

        // Apply the update
        match update_type.try_into()? {
            SystemConfigUpdateType::Batcher => {
                self.update_batcher_address(log_data).map_err(SystemConfigUpdateError::Batcher)
            }
            SystemConfigUpdateType::GasConfig => self
                .update_gas_config(log_data, ecotone_active)
                .map_err(SystemConfigUpdateError::GasConfig),
            SystemConfigUpdateType::GasLimit => {
                self.update_gas_limit(log_data).map_err(SystemConfigUpdateError::GasLimit)
            }
            SystemConfigUpdateType::Eip1559 => {
                self.update_eip1559_params(log_data).map_err(SystemConfigUpdateError::Eip1559)
            }
            // Ignored in derivation
            SystemConfigUpdateType::UnsafeBlockSigner => {
                Ok(SystemConfigUpdateType::UnsafeBlockSigner)
            }
        }
    }

    /// Updates the batcher address in the [SystemConfig] given the log data.
    fn update_batcher_address(
        &mut self,
        log_data: &[u8],
    ) -> Result<SystemConfigUpdateType, BatcherUpdateError> {
        if log_data.len() != 96 {
            return Err(BatcherUpdateError::InvalidDataLen(log_data.len()));
        }

        let Ok(pointer) = <sol!(uint64)>::abi_decode(&log_data[0..32], true) else {
            return Err(BatcherUpdateError::PointerDecodingError);
        };
        if pointer != 32 {
            return Err(BatcherUpdateError::InvalidDataPointer(pointer));
        }
        let Ok(length) = <sol!(uint64)>::abi_decode(&log_data[32..64], true) else {
            return Err(BatcherUpdateError::LengthDecodingError);
        };
        if length != 32 {
            return Err(BatcherUpdateError::InvalidDataLength(length));
        }

        let Ok(batcher_address) = <sol!(address)>::abi_decode(&log_data[64..], true) else {
            return Err(BatcherUpdateError::BatcherAddressDecodingError);
        };
        self.batcher_address = batcher_address;
        Ok(SystemConfigUpdateType::Batcher)
    }

    /// Updates the [SystemConfig] gas config - both the overhead and scalar values
    /// given the log data and rollup config.
    fn update_gas_config(
        &mut self,
        log_data: &[u8],
        ecotone_active: bool,
    ) -> Result<SystemConfigUpdateType, GasConfigUpdateError> {
        if log_data.len() != 128 {
            return Err(GasConfigUpdateError::InvalidDataLen(log_data.len()));
        }

        let Ok(pointer) = <sol!(uint64)>::abi_decode(&log_data[0..32], true) else {
            return Err(GasConfigUpdateError::PointerDecodingError);
        };
        if pointer != 32 {
            return Err(GasConfigUpdateError::InvalidDataPointer(pointer));
        }
        let Ok(length) = <sol!(uint64)>::abi_decode(&log_data[32..64], true) else {
            return Err(GasConfigUpdateError::LengthDecodingError);
        };
        if length != 64 {
            return Err(GasConfigUpdateError::InvalidDataLength(length));
        }

        let Ok(overhead) = <sol!(uint256)>::abi_decode(&log_data[64..96], true) else {
            return Err(GasConfigUpdateError::OverheadDecodingError);
        };
        let Ok(scalar) = <sol!(uint256)>::abi_decode(&log_data[96..], true) else {
            return Err(GasConfigUpdateError::ScalarDecodingError);
        };

        if ecotone_active
            && RollupConfig::check_ecotone_l1_system_config_scalar(scalar.to_be_bytes()).is_err()
        {
            // ignore invalid scalars, retain the old system-config scalar
            return Ok(SystemConfigUpdateType::GasConfig);
        }

        // Retain the scalar data in encoded form.
        self.scalar = scalar;

        // If ecotone is active, set the overhead to zero, otherwise set to the decoded value.
        self.overhead = if ecotone_active { U256::ZERO } else { overhead };

        Ok(SystemConfigUpdateType::GasConfig)
    }

    /// Updates the gas limit of the [SystemConfig] given the log data.
    fn update_gas_limit(
        &mut self,
        log_data: &[u8],
    ) -> Result<SystemConfigUpdateType, GasLimitUpdateError> {
        if log_data.len() != 96 {
            return Err(GasLimitUpdateError::InvalidDataLen(log_data.len()));
        }

        let Ok(pointer) = <sol!(uint64)>::abi_decode(&log_data[0..32], true) else {
            return Err(GasLimitUpdateError::PointerDecodingError);
        };
        if pointer != 32 {
            return Err(GasLimitUpdateError::InvalidDataPointer(pointer));
        }
        let Ok(length) = <sol!(uint64)>::abi_decode(&log_data[32..64], true) else {
            return Err(GasLimitUpdateError::LengthDecodingError);
        };
        if length != 32 {
            return Err(GasLimitUpdateError::InvalidDataLength(length));
        }

        let Ok(gas_limit) = <sol!(uint256)>::abi_decode(&log_data[64..], true) else {
            return Err(GasLimitUpdateError::GasLimitDecodingError);
        };
        self.gas_limit = U64::from(gas_limit).saturating_to::<u64>();
        Ok(SystemConfigUpdateType::GasLimit)
    }

    /// Updates the EIP-1559 parameters of the [SystemConfig] given the log data.
    fn update_eip1559_params(
        &mut self,
        log_data: &[u8],
    ) -> Result<SystemConfigUpdateType, EIP1559UpdateError> {
        if log_data.len() != 96 {
            return Err(EIP1559UpdateError::InvalidDataLen(log_data.len()));
        }

        let Ok(pointer) = <sol!(uint64)>::abi_decode(&log_data[0..32], true) else {
            return Err(EIP1559UpdateError::PointerDecodingError);
        };
        if pointer != 32 {
            return Err(EIP1559UpdateError::InvalidDataPointer(pointer));
        }
        let Ok(length) = <sol!(uint64)>::abi_decode(&log_data[32..64], true) else {
            return Err(EIP1559UpdateError::LengthDecodingError);
        };
        if length != 32 {
            return Err(EIP1559UpdateError::InvalidDataLength(length));
        }

        let Ok(eip1559_params) = <sol!(uint64)>::abi_decode(&log_data[64..], true) else {
            return Err(EIP1559UpdateError::EIP1559DecodingError);
        };

        self.eip1559_denominator = Some((eip1559_params >> 32) as u32);
        self.eip1559_elasticity = Some(eip1559_params as u32);

        Ok(SystemConfigUpdateType::Eip1559)
    }
}

/// An error for processing the [SystemConfig] update log.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SystemConfigUpdateError {
    /// An error occurred while processing the update log.
    LogProcessing(LogProcessingError),
    /// A batcher update error.
    Batcher(BatcherUpdateError),
    /// A gas config update error.
    GasConfig(GasConfigUpdateError),
    /// A gas limit update error.
    GasLimit(GasLimitUpdateError),
    /// An EIP-1559 parameter update error.
    Eip1559(EIP1559UpdateError),
}

impl core::fmt::Display for SystemConfigUpdateError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::LogProcessing(err) => write!(f, "Log processing error: {}", err),
            Self::Batcher(err) => write!(f, "Batcher update error: {}", err),
            Self::GasConfig(err) => write!(f, "Gas config update error: {}", err),
            Self::GasLimit(err) => write!(f, "Gas limit update error: {}", err),
            Self::Eip1559(err) => write!(f, "EIP-1559 parameter update error: {}", err),
        }
    }
}

/// An error occurred while processing the update log.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LogProcessingError {
    /// Received an incorrect number of log topics.
    InvalidTopicLen(usize),
    /// The log topic is invalid.
    InvalidTopic,
    /// The config update log version is unsupported.
    UnsupportedVersion(B256),
    /// Failed to decode the update type from the config update log.
    UpdateTypeDecodingError,
    /// An invalid system config update type.
    InvalidSystemConfigUpdateType(u64),
}

impl core::fmt::Display for LogProcessingError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InvalidTopicLen(len) => {
                write!(f, "Invalid config update log: invalid topic length: {}", len)
            }
            Self::InvalidTopic => write!(f, "Invalid config update log: invalid topic"),
            Self::UnsupportedVersion(version) => {
                write!(f, "Invalid config update log: unsupported version: {}", version)
            }
            Self::UpdateTypeDecodingError => {
                write!(f, "Failed to decode config update log: update type")
            }
            Self::InvalidSystemConfigUpdateType(value) => {
                write!(f, "Invalid system config update type: {}", value)
            }
        }
    }
}

/// An error for updating the batcher address on the [SystemConfig].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BatcherUpdateError {
    /// Invalid data length.
    InvalidDataLen(usize),
    /// Failed to decode the data pointer argument from the batcher update log.
    PointerDecodingError,
    /// The data pointer is invalid.
    InvalidDataPointer(u64),
    /// Failed to decode the data length argument from the batcher update log.
    LengthDecodingError,
    /// The data length is invalid.
    InvalidDataLength(u64),
    /// Failed to decode the batcher address argument from the batcher update log.
    BatcherAddressDecodingError,
}

impl core::fmt::Display for BatcherUpdateError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InvalidDataLen(len) => {
                write!(f, "Invalid config update log: invalid data length: {}", len)
            }
            Self::PointerDecodingError => {
                write!(f, "Failed to decode batcher update log: data pointer")
            }
            Self::InvalidDataPointer(pointer) => {
                write!(f, "Invalid config update log: invalid data pointer: {}", pointer)
            }
            Self::LengthDecodingError => {
                write!(f, "Failed to decode batcher update log: data length")
            }
            Self::InvalidDataLength(length) => {
                write!(f, "Invalid config update log: invalid data length: {}", length)
            }
            Self::BatcherAddressDecodingError => {
                write!(f, "Failed to decode batcher update log: batcher address")
            }
        }
    }
}

/// An error for updating the gas config on the [SystemConfig].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum GasConfigUpdateError {
    /// Invalid data length.
    InvalidDataLen(usize),
    /// Failed to decode the data pointer argument from the gas config update log.
    PointerDecodingError,
    /// The data pointer is invalid.
    InvalidDataPointer(u64),
    /// Failed to decode the data length argument from the gas config update log.
    LengthDecodingError,
    /// The data length is invalid.
    InvalidDataLength(u64),
    /// Failed to decode the overhead argument from the gas config update log.
    OverheadDecodingError,
    /// Failed to decode the scalar argument from the gas config update log.
    ScalarDecodingError,
}

impl core::fmt::Display for GasConfigUpdateError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InvalidDataLen(len) => {
                write!(f, "Invalid config update log: invalid data length: {}", len)
            }
            Self::PointerDecodingError => {
                write!(f, "Failed to decode gas config update log: data pointer")
            }
            Self::InvalidDataPointer(pointer) => {
                write!(f, "Invalid config update log: invalid data pointer: {}", pointer)
            }
            Self::LengthDecodingError => {
                write!(f, "Failed to decode gas config update log: data length")
            }
            Self::InvalidDataLength(length) => {
                write!(f, "Invalid config update log: invalid data length: {}", length)
            }
            Self::OverheadDecodingError => {
                write!(f, "Failed to decode gas config update log: overhead")
            }
            Self::ScalarDecodingError => {
                write!(f, "Failed to decode gas config update log: scalar")
            }
        }
    }
}

/// An error for updating the gas limit on the [SystemConfig].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum GasLimitUpdateError {
    /// Invalid data length.
    InvalidDataLen(usize),
    /// Failed to decode the data pointer argument from the gas limit update log.
    PointerDecodingError,
    /// The data pointer is invalid.
    InvalidDataPointer(u64),
    /// Failed to decode the data length argument from the gas limit update log.
    LengthDecodingError,
    /// The data length is invalid.
    InvalidDataLength(u64),
    /// Failed to decode the gas limit argument from the gas limit update log.
    GasLimitDecodingError,
}

impl core::fmt::Display for GasLimitUpdateError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InvalidDataLen(len) => {
                write!(f, "Invalid config update log: invalid data length: {}", len)
            }
            Self::PointerDecodingError => {
                write!(f, "Failed to decode gas limit update log: data pointer")
            }
            Self::InvalidDataPointer(pointer) => {
                write!(f, "Invalid config update log: invalid data pointer: {}", pointer)
            }
            Self::LengthDecodingError => {
                write!(f, "Failed to decode gas limit update log: data length")
            }
            Self::InvalidDataLength(length) => {
                write!(f, "Invalid config update log: invalid data length: {}", length)
            }
            Self::GasLimitDecodingError => {
                write!(f, "Failed to decode gas limit update log: gas limit")
            }
        }
    }
}

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

/// An error for updating the EIP-1559 parameters on the [SystemConfig].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum EIP1559UpdateError {
    /// Invalid data length.
    InvalidDataLen(usize),
    /// Failed to decode the data pointer argument from the eip 1559 update log.
    PointerDecodingError,
    /// The data pointer is invalid.
    InvalidDataPointer(u64),
    /// Failed to decode the data length argument from the eip 1559 update log.
    LengthDecodingError,
    /// The data length is invalid.
    InvalidDataLength(u64),
    /// Failed to decode the eip1559 params argument from the eip 1559 update log.
    EIP1559DecodingError,
}

impl core::fmt::Display for EIP1559UpdateError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::InvalidDataLen(len) => {
                write!(f, "Invalid config update log: invalid data length: {}", len)
            }
            Self::PointerDecodingError => {
                write!(f, "Failed to decode eip1559 parameter update log: data pointer")
            }
            Self::InvalidDataPointer(pointer) => {
                write!(f, "Invalid config update log: invalid data pointer: {}", pointer)
            }
            Self::LengthDecodingError => {
                write!(f, "Failed to decode eip1559 parameter update log: data length")
            }
            Self::InvalidDataLength(length) => {
                write!(f, "Invalid config update log: invalid data length: {}", length)
            }
            Self::EIP1559DecodingError => {
                write!(
                    f,
                    "Failed to decode eip1559 parameter update log: eip1559 parameters invalid"
                )
            }
        }
    }
}

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

/// System accounts
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SystemAccounts {
    /// The address that can deposit attributes
    pub attributes_depositor: Address,
    /// The address of the attributes predeploy
    pub attributes_predeploy: Address,
    /// The address of the fee vault
    pub fee_vault: Address,
}

impl Default for SystemAccounts {
    fn default() -> Self {
        Self {
            attributes_depositor: address!("deaddeaddeaddeaddeaddeaddeaddeaddead0001"),
            attributes_predeploy: address!("4200000000000000000000000000000000000015"),
            fee_vault: address!("4200000000000000000000000000000000000011"),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use alloc::vec;
    use alloy_primitives::{b256, hex, LogData, B256};
    use arbitrary::Arbitrary;
    use rand::Rng;

    #[test]
    fn test_arbitrary_system_config() {
        let mut bytes = [0u8; 1024];
        rand::thread_rng().fill(bytes.as_mut_slice());
        SystemConfig::arbitrary(&mut arbitrary::Unstructured::new(&bytes)).unwrap();
    }

    #[test]
    fn test_eip_1559_params_from_system_config_none() {
        let rollup_config = RollupConfig::default();
        let sys_config = SystemConfig::default();
        assert_eq!(sys_config.eip_1559_params(&rollup_config, 0, 0), None);
    }

    #[test]
    fn test_eip_1559_params_from_system_config_some() {
        let rollup_config = RollupConfig { holocene_time: Some(0), ..Default::default() };
        let sys_config = SystemConfig {
            eip1559_denominator: Some(1),
            eip1559_elasticity: None,
            ..Default::default()
        };
        let expected = Some(B64::from_slice(&[1u32.to_be_bytes(), 0u32.to_be_bytes()].concat()));
        assert_eq!(sys_config.eip_1559_params(&rollup_config, 0, 0), expected);
    }

    #[test]
    fn test_eip_1559_params_from_system_config() {
        let rollup_config = RollupConfig { holocene_time: Some(0), ..Default::default() };
        let sys_config = SystemConfig {
            eip1559_denominator: Some(1),
            eip1559_elasticity: Some(2),
            ..Default::default()
        };
        let expected = Some(B64::from_slice(&[1u32.to_be_bytes(), 2u32.to_be_bytes()].concat()));
        assert_eq!(sys_config.eip_1559_params(&rollup_config, 0, 0), expected);
    }

    #[test]
    fn test_default_eip_1559_params_from_system_config() {
        let rollup_config = RollupConfig { holocene_time: Some(0), ..Default::default() };
        let sys_config = SystemConfig {
            eip1559_denominator: None,
            eip1559_elasticity: None,
            ..Default::default()
        };
        let expected = Some(B64::ZERO);
        assert_eq!(sys_config.eip_1559_params(&rollup_config, 0, 0), expected);
    }

    #[test]
    fn test_default_eip_1559_params_from_system_config_pre_holocene() {
        let rollup_config = RollupConfig::default();
        let sys_config = SystemConfig {
            eip1559_denominator: Some(1),
            eip1559_elasticity: Some(2),
            ..Default::default()
        };
        assert_eq!(sys_config.eip_1559_params(&rollup_config, 0, 0), None);
    }

    #[test]
    fn test_default_eip_1559_params_first_block_holocene() {
        let rollup_config = RollupConfig { holocene_time: Some(2), ..Default::default() };
        let sys_config = SystemConfig {
            eip1559_denominator: Some(1),
            eip1559_elasticity: Some(2),
            ..Default::default()
        };
        assert_eq!(sys_config.eip_1559_params(&rollup_config, 0, 2), Some(B64::ZERO));
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_system_config_serde() {
        let sc_str = r#"{
          "batcherAddr": "0x6887246668a3b87F54DeB3b94Ba47a6f63F32985",
          "overhead": "0x00000000000000000000000000000000000000000000000000000000000000bc",
          "scalar": "0x00000000000000000000000000000000000000000000000000000000000a6fe0",
          "gasLimit": 30000000
        }"#;
        let system_config: SystemConfig = serde_json::from_str(sc_str).unwrap();
        assert_eq!(
            system_config.batcher_address,
            address!("6887246668a3b87F54DeB3b94Ba47a6f63F32985")
        );
        assert_eq!(system_config.overhead, U256::from(0xbc));
        assert_eq!(system_config.scalar, U256::from(0xa6fe0));
        assert_eq!(system_config.gas_limit, 30000000);
    }

    #[test]
    fn test_system_config_update_with_receipts_unchanged() {
        let mut system_config = SystemConfig::default();
        let receipts = vec![];
        let l1_system_config_address = Address::ZERO;
        let ecotone_active = false;

        system_config
            .update_with_receipts(&receipts, l1_system_config_address, ecotone_active)
            .unwrap();

        assert_eq!(system_config, SystemConfig::default());
    }

    #[test]
    fn test_system_config_update_with_receipts_batcher_address() {
        const UPDATE_TYPE: B256 =
            b256!("0000000000000000000000000000000000000000000000000000000000000000");
        let mut system_config = SystemConfig::default();
        let l1_system_config_address = Address::ZERO;
        let ecotone_active = false;

        let update_log = Log {
            address: Address::ZERO,
            data: LogData::new_unchecked(
                vec![
                    CONFIG_UPDATE_TOPIC,
                    CONFIG_UPDATE_EVENT_VERSION_0,
                    UPDATE_TYPE,
                ],
                hex!("00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000beef").into()
            )
        };

        let receipt = Receipt {
            logs: vec![update_log],
            status: Eip658Value::Eip658(true),
            cumulative_gas_used: 0u128,
        };

        system_config
            .update_with_receipts(&[receipt], l1_system_config_address, ecotone_active)
            .unwrap();

        assert_eq!(
            system_config.batcher_address,
            address!("000000000000000000000000000000000000bEEF"),
        );
    }

    #[test]
    fn test_system_config_update_batcher_log() {
        const UPDATE_TYPE: B256 =
            b256!("0000000000000000000000000000000000000000000000000000000000000000");

        let mut system_config = SystemConfig::default();

        let update_log = Log {
            address: Address::ZERO,
            data: LogData::new_unchecked(
                vec![
                    CONFIG_UPDATE_TOPIC,
                    CONFIG_UPDATE_EVENT_VERSION_0,
                    UPDATE_TYPE,
                ],
                hex!("00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000beef").into()
            )
        };

        // Update the batcher address.
        system_config.process_config_update_log(&update_log, false).unwrap();

        assert_eq!(
            system_config.batcher_address,
            address!("000000000000000000000000000000000000bEEF")
        );
    }

    #[test]
    fn test_system_config_update_gas_config_log() {
        const UPDATE_TYPE: B256 =
            b256!("0000000000000000000000000000000000000000000000000000000000000001");

        let mut system_config = SystemConfig::default();

        let update_log = Log {
            address: Address::ZERO,
            data: LogData::new_unchecked(
                vec![
                    CONFIG_UPDATE_TOPIC,
                    CONFIG_UPDATE_EVENT_VERSION_0,
                    UPDATE_TYPE,
                ],
                hex!("00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000babe000000000000000000000000000000000000000000000000000000000000beef").into()
            )
        };

        // Update the batcher address.
        system_config.process_config_update_log(&update_log, false).unwrap();

        assert_eq!(system_config.overhead, U256::from(0xbabe));
        assert_eq!(system_config.scalar, U256::from(0xbeef));
    }

    #[test]
    fn test_system_config_update_gas_config_log_ecotone() {
        const UPDATE_TYPE: B256 =
            b256!("0000000000000000000000000000000000000000000000000000000000000001");

        let mut system_config = SystemConfig::default();

        let update_log = Log {
            address: Address::ZERO,
            data: LogData::new_unchecked(
                vec![
                    CONFIG_UPDATE_TOPIC,
                    CONFIG_UPDATE_EVENT_VERSION_0,
                    UPDATE_TYPE,
                ],
                hex!("00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000babe000000000000000000000000000000000000000000000000000000000000beef").into()
            )
        };

        // Update the gas limit.
        system_config.process_config_update_log(&update_log, true).unwrap();

        assert_eq!(system_config.overhead, U256::from(0));
        assert_eq!(system_config.scalar, U256::from(0xbeef));
    }

    #[test]
    fn test_system_config_update_gas_limit_log() {
        const UPDATE_TYPE: B256 =
            b256!("0000000000000000000000000000000000000000000000000000000000000002");

        let mut system_config = SystemConfig::default();

        let update_log = Log {
            address: Address::ZERO,
            data: LogData::new_unchecked(
                vec![
                    CONFIG_UPDATE_TOPIC,
                    CONFIG_UPDATE_EVENT_VERSION_0,
                    UPDATE_TYPE,
                ],
                hex!("00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000beef").into()
            )
        };

        // Update the gas limit.
        system_config.process_config_update_log(&update_log, false).unwrap();

        assert_eq!(system_config.gas_limit, 0xbeef_u64);
    }

    #[test]
    fn test_system_config_update_eip1559_params_log() {
        const UPDATE_TYPE: B256 =
            b256!("0000000000000000000000000000000000000000000000000000000000000004");

        let mut system_config = SystemConfig::default();
        let update_log = Log {
            address: Address::ZERO,
            data: LogData::new_unchecked(
                vec![
                    CONFIG_UPDATE_TOPIC,
                    CONFIG_UPDATE_EVENT_VERSION_0,
                    UPDATE_TYPE,
                ],
                hex!("000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000babe0000beef").into()
            )
        };

        // Update the EIP-1559 parameters.
        system_config.process_config_update_log(&update_log, false).unwrap();

        assert_eq!(system_config.eip1559_denominator, Some(0xbabe_u32));
        assert_eq!(system_config.eip1559_elasticity, Some(0xbeef_u32));
    }
}