tempo-chainspec 1.8.2

Tempo hardfork configuration and chain specification helpers
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
//! Tempo-specific hardfork definitions and traits.
//!
//! This module provides the infrastructure for managing hardfork transitions in Tempo.
//!
//! ## Adding a New Hardfork
//!
//! When a new hardfork is needed (e.g., `Vivace`):
//!
//! ### In `hardfork.rs`:
//! 1. Append a `Vivace` variant to `tempo_hardfork!` — automatically:
//!    * defines the enum variant via [`hardfork!`]
//!    * implements trait `TempoHardforks` by adding `is_vivace()`, `is_vivace_active_at_timestamp()`,
//!      and updating `tempo_hardfork_at()`
//!    * adds tests for each of the `TempoHardfork` methods
//! 2. Update `From<TempoHardfork> for SpecId` if the hardfork requires a different Ethereum `SpecId`
//!
//! ### In `spec.rs`:
//! 3. Add `vivace_time: Option<u64>` field to `TempoGenesisInfo`
//! 4. Add `TempoHardfork::Vivace => self.vivace_time` arm to `TempoGenesisInfo::fork_time()`
//!
//! ### In genesis files and generator:
//! 5. Add `"vivaceTime": 0` to `genesis/dev.json`
//! 6. Add `vivace_time: Option<u64>` arg to `xtask/src/genesis_args.rs`
//! 7. Add insertion of `"vivaceTime"` to chain_config.extra_fields

use crate::constants::gas;
use alloy_eips::eip7825::MAX_TX_GAS_LIMIT_OSAKA;
#[cfg(feature = "evm")]
use alloy_evm::revm::primitives::hardfork::SpecId;
use alloy_hardforks::hardfork;

/// Single-source hardfork definition macro. Append a new variant and everything else is generated:
///
/// * Defines the `TempoHardfork` enum via [`hardfork!`] (including `Display`, `FromStr`,
///   `Hardfork` trait impl, and `VARIANTS` const)
/// * Generates `is_<fork>()` inherent methods on `TempoHardfork` — returns `true` when
///   `*self >= Self::<Fork>`
/// * Generates the `TempoHardforks` trait with:
///   - `tempo_fork_activation()` (required — the only method implementors provide)
///   - `tempo_hardfork_at()` — walks `VARIANTS` in reverse to find the latest active fork
///   - `is_<fork>_active_at_timestamp()` — per-fork convenience helpers
///   - `general_gas_limit_at()` — gas limit lookup by timestamp
/// * Generates a `#[cfg(test)] mod tests` with activation, naming, trait, and serde tests
///
/// `Genesis` (first variant) is treated as the baseline and does not get `is_*()` methods.
///  All subsequent variants are considered post-Genesis hardforks.
macro_rules! tempo_hardfork {
    (
        $(#[$enum_meta:meta])*
        TempoHardfork {
            $(#[$genesis_meta:meta])* Genesis,
            $( $(#[$meta:meta])* $variant:ident ),* $(,)?
        }
    ) => {

        // delegate to alloy's `hardfork!` macro
        hardfork!(
            $(#[$enum_meta])*
            TempoHardfork {
                $(#[$genesis_meta])* Genesis,
                $( $(#[$meta])* $variant ),*
            }
        );

        impl TempoHardfork {
            paste::paste! {
                $(
                    #[doc = concat!("Returns true if this hardfork is ", stringify!($variant), " or later.")]
                    pub const fn [<is_ $variant:lower>](&self) -> bool {
                        *self as u64 >= Self::$variant as u64
                    }
                )*
            }
        }

        /// Trait for querying Tempo-specific hardfork activations.
        #[cfg(feature = "reth")]
        pub trait TempoHardforks: reth_chainspec::EthereumHardforks {
            /// Retrieves activation condition for a Tempo-specific hardfork.
            fn tempo_fork_activation(&self, fork: TempoHardfork) -> reth_chainspec::ForkCondition;

            /// Retrieves the Tempo hardfork active at a given timestamp.
            fn tempo_hardfork_at(&self, timestamp: u64) -> TempoHardfork {
                for &fork in TempoHardfork::VARIANTS.iter().rev() {
                    if self.tempo_fork_activation(fork).active_at_timestamp(timestamp) {
                        return fork;
                    }
                }
                TempoHardfork::Genesis
            }

            paste::paste! {
                $(
                    #[doc = concat!("Returns true if ", stringify!($variant), " is active at the given timestamp.")]
                    fn [<is_ $variant:lower _active_at_timestamp>](&self, timestamp: u64) -> bool {
                        self.tempo_fork_activation(TempoHardfork::$variant)
                            .active_at_timestamp(timestamp)
                    }
                )*
            }

            /// Returns the general (non-payment) gas limit for the given timestamp and block.
            /// - T1+: fixed at 30M gas
            /// - Pre-T1: calculated as (gas_limit - shared_gas_limit) / 2
            fn general_gas_limit_at(&self, timestamp: u64, gas_limit: u64, shared_gas_limit: u64) -> u64 {
                self.tempo_hardfork_at(timestamp)
                    .general_gas_limit()
                    .unwrap_or_else(|| (gas_limit - shared_gas_limit) / 2)
            }

            /// Returns the shared gas limit for the given timestamp and block.
            /// - T4+: 0 gas
            /// - Pre-T4: block_gas_limit / 10
            fn shared_gas_limit_at(&self, timestamp: u64, gas_limit: u64) -> u64 {
                self.tempo_hardfork_at(timestamp)
                    .shared_gas_limit(gas_limit)
            }
        }

        #[cfg(all(test, feature = "reth"))]
        mod tests {
            use super::*;
            use TempoHardfork::*;
            use reth_chainspec::Hardfork;

            #[test]
            fn test_hardfork_name() {
                assert_eq!(Genesis.name(), "Genesis");
                $(assert_eq!($variant.name(), stringify!($variant));)*
            }

            #[test]
            fn test_hardfork_trait_implementation() {
                for fork in TempoHardfork::VARIANTS {
                    let _name: &str = Hardfork::name(fork);
                }
            }

            #[test]
            fn test_variant_index_roundtrip() {
                for fork in TempoHardfork::VARIANTS {
                    assert_eq!(
                        TempoHardfork::from_variant_index(fork.variant_index()),
                        Some(*fork)
                    );
                }
                assert_eq!(
                    TempoHardfork::from_variant_index(TempoHardfork::VARIANTS.len() as u8),
                    None
                );
            }

            #[test]
            #[cfg(feature = "serde")]
            fn test_tempo_hardfork_serde() {
                for fork in TempoHardfork::VARIANTS {
                    let json = serde_json::to_string(fork).expect("serialize");
                    let deserialized: TempoHardfork = serde_json::from_str(&json).expect("deserialize");
                    assert_eq!(deserialized, *fork);
                }
            }

            paste::paste! {
                $(
                    #[test]
                    fn [<test_is_ $variant:lower>]() {
                        let idx = TempoHardfork::VARIANTS.iter().position(|v| *v == $variant)
                            .expect(concat!(stringify!($variant), " missing from VARIANTS"));
                        for (i, fork) in TempoHardfork::VARIANTS.iter().enumerate() {
                            let active = TempoHardfork::[<is_ $variant:lower>](fork);
                            if i >= idx {
                                assert!(active, "{fork:?} should satisfy is_{}", stringify!([<$variant:lower>]));
                            } else {
                                assert!(!active, "{fork:?} should not satisfy is_{}", stringify!([<$variant:lower>]));
                            }
                        }
                    }
                )*
            }
        }
    };
}

// -------------------------------------------------------------------------------------
// Tempo hardfork definitions — append new variants here.
// -------------------------------------------------------------------------------------
tempo_hardfork! (
    /// Tempo-specific hardforks for network upgrades.
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    #[derive(Default)]
    TempoHardfork {
        /// Genesis hardfork
        Genesis,
        #[default]
        /// T0 hardfork (default until T1 activates on mainnet)
        T0,
        /// T1 hardfork - adds expiring nonce transactions
        T1,
        /// T1.A hardfork - removes EIP-7825 per-transaction gas limit
        T1A,
        /// T1.B hardfork
        T1B,
        /// T1.C hardfork
        T1C,
        /// T2 hardfork - adds compound transfer policies ([TIP-1015])
        ///
        /// [TIP-1015]: <https://docs.tempo.xyz/protocol/tips/tip-1015>
        T2,
        /// T3 hardfork
        T3,
        /// T4 hardfork
        T4,
        /// T5 hardfork
        T5,
        /// T6 hardfork
        T6,
        /// T7 hardfork
        T7,
        /// T8 hardfork
        T8,
    }
);

impl TempoHardfork {
    /// Returns the position of this hardfork in [`Self::VARIANTS`].
    ///
    /// Useful for storing the hardfork in an atomic, see [`Self::from_variant_index`].
    pub const fn variant_index(&self) -> u8 {
        *self as u8
    }

    /// Returns the hardfork at the given [`Self::VARIANTS`] position, see
    /// [`Self::variant_index`].
    ///
    /// Returns `None` if the index is out of bounds.
    pub const fn from_variant_index(index: u8) -> Option<Self> {
        if (index as usize) < Self::VARIANTS.len() {
            Some(Self::VARIANTS[index as usize])
        } else {
            None
        }
    }

    /// Returns the fixed general gas limit for T1+, or None for pre-T1.
    /// - Pre-T1: None
    /// - T1+: 30M gas (fixed)
    pub const fn general_gas_limit(&self) -> Option<u64> {
        if self.is_t1() {
            return Some(gas::TEMPO_T1_GENERAL_GAS_LIMIT);
        }
        None
    }

    /// Returns the shared gas limit for the given block gas limit.
    /// - T4+: 0 gas
    /// - Pre-T4: block_gas_limit / 10
    pub const fn shared_gas_limit(&self, block_gas_limit: u64) -> u64 {
        if self.is_t4() {
            0
        } else {
            block_gas_limit / 10
        }
    }

    /// Returns the per-transaction gas limit cap.
    /// - Pre-T1A: EIP-7825 Osaka limit (16,777,216 gas)
    /// - T1A+: 30M gas (allows maximum-sized contract deployments under [TIP-1000] state creation)
    ///
    /// [TIP-1000]: <https://docs.tempo.xyz/protocol/tips/tip-1000>
    pub const fn tx_gas_limit_cap(&self) -> Option<u64> {
        if self.is_t1a() {
            return Some(gas::TEMPO_T1_TX_GAS_LIMIT_CAP);
        }
        Some(MAX_TX_GAS_LIMIT_OSAKA)
    }

    /// Gas cost for using an existing 2D nonce key
    pub const fn gas_existing_nonce_key(&self) -> u64 {
        if self.is_t2() {
            return gas::TEMPO_T2_EXISTING_NONCE_KEY_GAS;
        }
        gas::TEMPO_T1_EXISTING_NONCE_KEY_GAS
    }

    /// Gas cost for using a new 2D nonce key
    pub const fn gas_new_nonce_key(&self) -> u64 {
        if self.is_t2() {
            return gas::TEMPO_T2_NEW_NONCE_KEY_GAS;
        }
        gas::TEMPO_T1_NEW_NONCE_KEY_GAS
    }

    /// Returns the active hardfork at the given timestamp for the specified chain.
    ///
    /// Returns `None` if the chain ID is not a known Tempo chain.
    pub const fn from_chain_and_timestamp(chain_id: u64, timestamp: u64) -> Option<Self> {
        // Walk variants in reverse to find the latest active fork, mirroring
        // `TempoHardforks::tempo_hardfork_at` but without needing a chainspec instance.
        let variants = Self::VARIANTS;
        let mut i = variants.len();
        while i > 0 {
            i -= 1;
            let activation = match chain_id {
                4217 => variants[i].mainnet_activation_timestamp(),
                42431 => variants[i].moderato_activation_timestamp(),
                _ => return None,
            };
            if let Some(ts) = activation
                && timestamp >= ts
            {
                return Some(variants[i]);
            }
        }
        Some(Self::Genesis)
    }

    /// Retrieves the activation block for this hardfork on mainnet.
    pub const fn mainnet_activation_block(&self) -> Option<u64> {
        use crate::constants::mainnet::*;
        match self {
            Self::Genesis => Some(MAINNET_GENESIS_BLOCK),
            Self::T0 => Some(MAINNET_T0_BLOCK),
            Self::T1 => Some(MAINNET_T1_BLOCK),
            Self::T1A => Some(MAINNET_T1A_BLOCK),
            Self::T1B => Some(MAINNET_T1B_BLOCK),
            Self::T1C => Some(MAINNET_T1C_BLOCK),
            Self::T2 => Some(MAINNET_T2_BLOCK),
            Self::T3 => None, // not yet known
            Self::T4 => None,
            Self::T5 => None,
            Self::T6 => None,
            Self::T7 => None,
            Self::T8 => None,
        }
    }

    /// Retrieves the activation timestamp for this hardfork on mainnet.
    pub const fn mainnet_activation_timestamp(&self) -> Option<u64> {
        use crate::constants::mainnet::*;
        match self {
            Self::Genesis => Some(MAINNET_GENESIS_TIMESTAMP),
            Self::T0 => Some(MAINNET_T0_TIMESTAMP),
            Self::T1 => Some(MAINNET_T1_TIMESTAMP),
            Self::T1A => Some(MAINNET_T1A_TIMESTAMP),
            Self::T1B => Some(MAINNET_T1B_TIMESTAMP),
            Self::T1C => Some(MAINNET_T1C_TIMESTAMP),
            Self::T2 => Some(MAINNET_T2_TIMESTAMP),
            Self::T3 => Some(MAINNET_T3_TIMESTAMP),
            Self::T4 => Some(MAINNET_T4_TIMESTAMP),
            Self::T5 => Some(MAINNET_T5_TIMESTAMP),
            Self::T6 => Some(MAINNET_T6_TIMESTAMP),
            Self::T7 => None,
            Self::T8 => None,
        }
    }

    /// Retrieves the activation block for this hardfork on moderato testnet.
    pub const fn moderato_activation_block(&self) -> Option<u64> {
        use crate::constants::moderato::*;
        match self {
            Self::Genesis => Some(MODERATO_GENESIS_BLOCK),
            Self::T0 => Some(MODERATO_T0_BLOCK),
            Self::T1 => Some(MODERATO_T1_BLOCK),
            Self::T1A => Some(MODERATO_T1A_BLOCK),
            Self::T1B => Some(MODERATO_T1B_BLOCK),
            Self::T1C => Some(MODERATO_T1C_BLOCK),
            Self::T2 => Some(MODERATO_T2_BLOCK),
            Self::T3 => None, // not yet known
            Self::T4 => None,
            Self::T5 => None,
            Self::T6 => None,
            Self::T7 => None,
            Self::T8 => None,
        }
    }

    /// Retrieves the activation timestamp for this hardfork on moderato testnet.
    pub const fn moderato_activation_timestamp(&self) -> Option<u64> {
        use crate::constants::moderato::*;
        match self {
            Self::Genesis => Some(MODERATO_GENESIS_TIMESTAMP),
            Self::T0 => Some(MODERATO_T0_TIMESTAMP),
            Self::T1 => Some(MODERATO_T1_TIMESTAMP),
            Self::T1A => Some(MODERATO_T1A_TIMESTAMP),
            Self::T1B => Some(MODERATO_T1B_TIMESTAMP),
            Self::T1C => Some(MODERATO_T1C_TIMESTAMP),
            Self::T2 => Some(MODERATO_T2_TIMESTAMP),
            Self::T3 => Some(MODERATO_T3_TIMESTAMP),
            Self::T4 => Some(MODERATO_T4_TIMESTAMP),
            Self::T5 => Some(MODERATO_T5_TIMESTAMP),
            Self::T6 => Some(MODERATO_T6_TIMESTAMP),
            Self::T7 => None,
            Self::T8 => None,
        }
    }
}

#[cfg(feature = "evm")]
impl From<TempoHardfork> for SpecId {
    fn from(_value: TempoHardfork) -> Self {
        Self::OSAKA
    }
}

#[cfg(feature = "evm")]
impl From<&TempoHardfork> for SpecId {
    fn from(value: &TempoHardfork) -> Self {
        Self::from(*value)
    }
}

#[cfg(feature = "evm")]
impl From<SpecId> for TempoHardfork {
    fn from(_spec: SpecId) -> Self {
        // All Tempo hardforks map to SpecId::OSAKA, so we cannot derive the hardfork from SpecId.
        // Default to the default hardfork when converting from SpecId.
        // The actual hardfork should be passed explicitly where needed.
        Self::default()
    }
}