Skip to main content

foundry_common/tempo/
hardfork.rs

1//! Tempo hardfork activation queries.
2
3use crate::{FoundryTransactionBuilder, provider::is_rpc_method_not_found};
4use alloy_network::{Network, TransactionBuilder};
5use alloy_provider::Provider;
6use alloy_transport::{TransportError, TransportErrorKind};
7use eyre::Result;
8use serde::Deserialize;
9use tempo_alloy::{chainspec::hardfork::TempoHardfork, rpc::ForkSchedule};
10use tempo_primitives::transaction::{FEE_PAYER_SIGNATURE_MARKER, TEMPO_EXPIRING_NONCE_KEY};
11
12#[derive(Debug, Deserialize)]
13#[serde(rename_all = "camelCase")]
14struct AnvilNodeInfo {
15    hard_fork: Option<String>,
16    network: Option<String>,
17}
18
19/// Returns whether `hardfork` is active at the head of the chain behind `provider`.
20///
21/// Queries `tempo_forkSchedule` and falls back to `anvil_nodeInfo` for Anvil nodes, which do not
22/// serve the fork schedule. Fails when neither source reports a hardfork known to this build.
23pub async fn is_tempo_hardfork_active<N: Network, P: Provider<N>>(
24    provider: &P,
25    hardfork: TempoHardfork,
26) -> Result<bool> {
27    Ok(active_tempo_hardfork(provider).await? >= hardfork)
28}
29
30/// Returns the Tempo hardfork active on the RPC, falling back to `anvil_nodeInfo` for nodes that
31/// do not serve the fork schedule.
32pub async fn active_tempo_hardfork<N: Network, P: Provider<N>>(
33    provider: &P,
34) -> Result<TempoHardfork> {
35    match fork_schedule_hardfork(provider).await {
36        Ok(hardfork) => Ok(hardfork),
37        Err(err) if is_rpc_method_not_found(&err) => match anvil_tempo_hardfork(provider).await {
38            Ok(Some(hardfork)) => Ok(hardfork),
39            _ => Err(err.into()),
40        },
41        Err(err) => Err(err.into()),
42    }
43}
44
45/// Fails when `tx` carries a non-zero expiring nonce and the chain is known to predate T12.
46///
47/// TIP-1106 turns the nonce of an expiring nonce transaction into an opaque discriminator from
48/// T12 on. Earlier hardforks reject any value other than zero. When the active hardfork cannot be
49/// determined the check is skipped and validation is left to the node.
50pub async fn ensure_expiring_nonce_discriminator_active<N: Network, P: Provider<N>>(
51    provider: &P,
52    tx: &N::TransactionRequest,
53) -> Result<()>
54where
55    N::TransactionRequest: FoundryTransactionBuilder<N>,
56{
57    if tx.nonce_key() == Some(TEMPO_EXPIRING_NONCE_KEY)
58        && let Some(nonce) = tx.nonce().filter(|nonce| *nonce != 0)
59        && matches!(is_tempo_hardfork_active(provider, TempoHardfork::T12).await, Ok(false))
60    {
61        eyre::bail!(
62            "expiring nonce transactions must use nonce 0 before the Tempo T12 hardfork, got nonce {nonce}; non-zero expiring nonce discriminators (TIP-1106) are not active on this chain"
63        );
64    }
65    Ok(())
66}
67
68/// Marks `request`, the gas estimation request of a transaction a fee payer will sponsor, as
69/// sponsored.
70///
71/// From T14 a fee payer signature costs one cold account access: the fee payer's account is read
72/// to check that its root key is not retired. The sponsor signs after estimation, because its
73/// signature commits to the gas limit, so the request carries [`FEE_PAYER_SIGNATURE_MARKER`] in its
74/// place, for which a Tempo node adds that access to the estimate. Before T14 nodes do not handle
75/// the marker, so the request is left unchanged there and when the hardfork is unknown.
76pub async fn mark_sponsored_gas_estimation<N: Network, P: Provider<N>>(
77    provider: &P,
78    request: &mut N::TransactionRequest,
79) where
80    N::TransactionRequest: FoundryTransactionBuilder<N>,
81{
82    if request.fee_payer_signature().is_none()
83        && matches!(is_tempo_hardfork_active(provider, TempoHardfork::T14).await, Ok(true))
84    {
85        request.set_fee_payer_signature(FEE_PAYER_SIGNATURE_MARKER);
86    }
87}
88
89async fn fork_schedule_hardfork<N: Network, P: Provider<N>>(
90    provider: &P,
91) -> Result<TempoHardfork, TransportError> {
92    let schedule = provider.raw_request::<_, ForkSchedule>("tempo_forkSchedule".into(), ()).await?;
93    schedule.active.parse::<TempoHardfork>().map_err(TransportErrorKind::custom)
94}
95
96async fn anvil_tempo_hardfork<N: Network, P: Provider<N>>(
97    provider: &P,
98) -> Result<Option<TempoHardfork>, TransportError> {
99    let info = provider.raw_request::<_, AnvilNodeInfo>("anvil_nodeInfo".into(), ()).await?;
100    Ok(hardfork_from_anvil_node_info(&info))
101}
102
103fn hardfork_from_anvil_node_info(info: &AnvilNodeInfo) -> Option<TempoHardfork> {
104    if info.network.as_deref() != Some("tempo") {
105        return None;
106    }
107    info.hard_fork.as_deref()?.parse().ok()
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    use alloy_json_rpc::ErrorPayload;
114    use alloy_primitives::U256;
115    use alloy_provider::{ProviderBuilder, mock::Asserter};
116    use tempo_alloy::{TempoNetwork, rpc::TempoTransactionRequest};
117
118    fn mocked_provider(asserter: Asserter) -> impl Provider<TempoNetwork> {
119        ProviderBuilder::new().network::<TempoNetwork>().connect_mocked_client(asserter)
120    }
121
122    #[tokio::test]
123    async fn tempo_fork_schedule_detects_t3_activation() {
124        for (active, expected) in [("T2", false), ("T3", true), ("T13", true), ("T14", true)] {
125            let asserter = Asserter::new();
126            asserter.push_success(&serde_json::json!({ "active": active, "schedule": [] }));
127            let provider = mocked_provider(asserter);
128            assert_eq!(
129                is_tempo_hardfork_active(&provider, TempoHardfork::T3).await.unwrap(),
130                expected
131            );
132        }
133    }
134
135    #[tokio::test]
136    async fn tempo_fork_schedule_rejects_unknown_hardfork() {
137        let asserter = Asserter::new();
138        asserter.push_success(&serde_json::json!({ "active": "FutureFork", "schedule": [] }));
139        let provider = mocked_provider(asserter);
140        assert!(is_tempo_hardfork_active(&provider, TempoHardfork::T3).await.is_err());
141    }
142
143    #[test]
144    fn hardfork_from_anvil_node_info_requires_tempo_network() {
145        let info = |network: &str, hard_fork: &str| AnvilNodeInfo {
146            network: Some(network.to_string()),
147            hard_fork: Some(hard_fork.to_string()),
148        };
149        assert_eq!(hardfork_from_anvil_node_info(&info("tempo", "T3")), Some(TempoHardfork::T3));
150        assert_eq!(hardfork_from_anvil_node_info(&info("tempo", "T11")), Some(TempoHardfork::T11));
151        assert_eq!(hardfork_from_anvil_node_info(&info("tempo", "FutureFork")), None);
152        assert_eq!(hardfork_from_anvil_node_info(&info("ethereum", "T3")), None);
153    }
154
155    #[tokio::test]
156    async fn anvil_node_info_fallback_detects_hardfork_activation() {
157        let asserter = Asserter::new();
158        for _ in 0..2 {
159            asserter.push_failure(ErrorPayload {
160                code: -32601,
161                message: "Method not found".into(),
162                data: None,
163            });
164            asserter.push_success(&serde_json::json!({ "network": "tempo", "hardFork": "T3" }));
165        }
166        let provider =
167            ProviderBuilder::new().network::<TempoNetwork>().connect_mocked_client(asserter);
168        assert!(is_tempo_hardfork_active(&provider, TempoHardfork::T3).await.unwrap());
169        assert!(!is_tempo_hardfork_active(&provider, TempoHardfork::T4).await.unwrap());
170    }
171
172    #[tokio::test]
173    async fn expiring_nonce_discriminator_requires_t12_when_hardfork_is_known() {
174        let request = |nonce_key, nonce| {
175            let mut tx = TempoTransactionRequest::default();
176            tx.set_nonce_key(nonce_key);
177            tx.set_nonce(nonce);
178            tx
179        };
180        let discriminator = request(TEMPO_EXPIRING_NONCE_KEY, 7);
181
182        // `None` leaves the mock without a response, so any hardfork query fails.
183        for (tx, active, accepted) in [
184            (&discriminator, Some("T11"), false),
185            (&discriminator, Some("T12"), true),
186            (&discriminator, Some("FutureFork"), true),
187            (&discriminator, None, true),
188            (&request(TEMPO_EXPIRING_NONCE_KEY, 0), None, true),
189            (&request(U256::from(1), 7), None, true),
190        ] {
191            let asserter = Asserter::new();
192            if let Some(active) = active {
193                asserter.push_success(&serde_json::json!({ "active": active, "schedule": [] }));
194            }
195            let provider = mocked_provider(asserter);
196            let result = ensure_expiring_nonce_discriminator_active(&provider, tx).await;
197            assert_eq!(
198                result.is_ok(),
199                accepted,
200                "nonce {:?} at {active:?}: {result:?}",
201                tx.nonce()
202            );
203        }
204    }
205}