Skip to main content

taskfast_agent/
tempo_rpc.rs

1// SPDX-License-Identifier: MIT
2//! Minimal Tempo JSON-RPC client for the submission-fee voucher flow.
3//!
4//! `taskfast post` needs to:
5//!   1. turn the server-emitted ERC-20 transfer calldata into a signed,
6//!      broadcast tx whose hash can be submitted as a voucher, or
7//!   2. hand the server a raw RLP-encoded signed tx it can broadcast.
8//!
9//! Both paths need `eth_chainId` + `eth_getTransactionCount` + `eth_gasPrice`
10//! + `eth_estimateGas` to build a replay-safe legacy tx with a correctly
11//! sized gas limit. Path (1) additionally needs `eth_sendRawTransaction`.
12//! That's it. `alloy-provider` would cover this plus subscription,
13//! middleware, and batching we don't want — so this module wraps those
14//! five methods over `reqwest` directly.
15//!
16//! # Why legacy (not EIP-1559) txs
17//!
18//! Tempo is a stable-fee chain fork — `eth_gasPrice` is authoritative and
19//! `eth_feeHistory` isn't guaranteed to exist on every node. A legacy tx
20//! with `chain_id` set (EIP-155 replay protection) is the widest-compat
21//! shape and keeps the RPC surface to 4 read methods + 1 write.
22
23use alloy_consensus::{SignableTransaction, TxEnvelope, TxLegacy};
24use alloy_eips::eip2718::Encodable2718;
25use alloy_primitives::{Address, Bytes, TxHash, TxKind, U256};
26use alloy_signer::SignerSync;
27use alloy_signer_local::PrivateKeySigner;
28use serde::{Deserialize, Serialize};
29use serde_json::{json, Value};
30use thiserror::Error as ThisError;
31
32/// Buffer applied to `eth_estimateGas` output, as numerator/denominator.
33/// 13/10 = +30%. State drift between estimate and execution (cold SLOAD,
34/// new storage slot, balance flip) can push actual gas above the estimate;
35/// 30% matches the conservative end of the ethers/alloy-ecosystem default.
36const GAS_ESTIMATE_BUFFER_NUM: u64 = 13;
37const GAS_ESTIMATE_BUFFER_DEN: u64 = 10;
38
39/// Errors surfaced by [`TempoRpcClient`] and [`sign_and_broadcast_erc20_transfer`].
40#[derive(Debug, ThisError)]
41pub enum RpcError {
42    #[error("rpc transport: {0}")]
43    Transport(#[from] reqwest::Error),
44    #[error("rpc returned non-2xx {status}: {body}")]
45    Http { status: u16, body: String },
46    #[error("rpc error {code}: {message}")]
47    Rpc { code: i64, message: String },
48    #[error("rpc response shape invalid: {0}")]
49    Decode(String),
50    #[error("hex decode: {0}")]
51    Hex(String),
52    #[error("signing failed: {0}")]
53    Sign(String),
54}
55
56/// Thin JSON-RPC client over reqwest. One instance = one RPC endpoint.
57#[derive(Debug, Clone)]
58pub struct TempoRpcClient {
59    http: reqwest::Client,
60    url: String,
61}
62
63#[derive(Serialize)]
64struct RpcRequest<'a, P: Serialize> {
65    jsonrpc: &'static str,
66    id: u64,
67    method: &'a str,
68    params: P,
69}
70
71#[derive(Deserialize)]
72struct RpcResponse {
73    #[serde(default)]
74    result: Option<Value>,
75    #[serde(default)]
76    error: Option<RpcErrorBody>,
77}
78
79#[derive(Deserialize)]
80struct RpcErrorBody {
81    code: i64,
82    #[serde(default)]
83    message: String,
84    #[serde(default)]
85    data: Option<serde_json::Value>,
86}
87
88impl TempoRpcClient {
89    /// Build from an existing reqwest client (share connection pool with the
90    /// TaskFast API client) plus the Tempo RPC URL.
91    pub fn new(http: reqwest::Client, url: impl Into<String>) -> Self {
92        Self {
93            http,
94            url: url.into(),
95        }
96    }
97
98    /// Convenience: build with a fresh reqwest client. Tests use this.
99    pub fn with_default_client(url: impl Into<String>) -> Self {
100        Self::new(reqwest::Client::new(), url)
101    }
102
103    /// `eth_chainId` → u64. Hex-prefixed-hex decode.
104    pub async fn chain_id(&self) -> Result<u64, RpcError> {
105        let raw: String = self.call("eth_chainId", json!([])).await?;
106        parse_hex_u64(&raw)
107    }
108
109    /// `eth_getTransactionCount(address, "pending")` → nonce.
110    ///
111    /// Uses `pending` not `latest` so a second tx from the same signer doesn't
112    /// collide on nonce if the first hasn't been mined yet.
113    pub async fn pending_nonce(&self, addr: Address) -> Result<u64, RpcError> {
114        let raw: String = self
115            .call(
116                "eth_getTransactionCount",
117                json!([format!("{addr:#x}"), "pending"]),
118            )
119            .await?;
120        parse_hex_u64(&raw)
121    }
122
123    /// `eth_gasPrice` → u128. Wei.
124    pub async fn gas_price(&self) -> Result<u128, RpcError> {
125        let raw: String = self.call("eth_gasPrice", json!([])).await?;
126        parse_hex_u128(&raw)
127    }
128
129    /// `eth_estimateGas({from, to, data})` → gas units.
130    ///
131    /// Called before every ERC-20 transfer so we size `gas_limit` to actual
132    /// chain state (Tempo testnet's canonical USDC `transfer` lands around
133    /// 307k; a different token or recipient-with-no-prior-balance can push
134    /// higher). A revert here means the tx would fail on-chain — callers
135    /// should surface the error rather than broadcast a doomed tx.
136    pub async fn estimate_gas(
137        &self,
138        from: Address,
139        to: Address,
140        data: &Bytes,
141    ) -> Result<u64, RpcError> {
142        let raw: String = self
143            .call(
144                "eth_estimateGas",
145                json!([{
146                    "from": format!("{from:#x}"),
147                    "to": format!("{to:#x}"),
148                    "data": format!("0x{}", hex::encode(data)),
149                }]),
150            )
151            .await?;
152        parse_hex_u64(&raw)
153    }
154
155    /// `eth_call({to, data}, "latest")` → returned bytes.
156    ///
157    /// Used for view-only calls (ERC-20 `allowance` / `balanceOf`, etc.) where
158    /// we need to read chain state without broadcasting a tx.
159    pub async fn eth_call(&self, to: Address, data: &Bytes) -> Result<Vec<u8>, RpcError> {
160        let raw: String = self
161            .call(
162                "eth_call",
163                json!([
164                    {
165                        "to": format!("{to:#x}"),
166                        "data": format!("0x{}", hex::encode(data)),
167                    },
168                    "latest",
169                ]),
170            )
171            .await?;
172        decode_0x(&raw)
173    }
174
175    /// `eth_call({from, to, data}, "latest")` → returned bytes.
176    ///
177    /// Like [`Self::eth_call`] but with an explicit sender. Tempo Zone TIP-20s
178    /// enforce balance privacy — `balanceOf(X)`/`allowance(X, …)` revert
179    /// `Unauthorized` unless `msg.sender` is a party — so self-reads must
180    /// impersonate the queried address (needs no signature; a no-op on L1).
181    pub async fn eth_call_from(
182        &self,
183        from: Address,
184        to: Address,
185        data: &Bytes,
186    ) -> Result<Vec<u8>, RpcError> {
187        let raw: String = self
188            .call(
189                "eth_call",
190                json!([
191                    {
192                        "from": format!("{from:#x}"),
193                        "to": format!("{to:#x}"),
194                        "data": format!("0x{}", hex::encode(data)),
195                    },
196                    "latest",
197                ]),
198            )
199            .await?;
200        decode_0x(&raw)
201    }
202
203    /// `eth_getTransactionReceipt(tx_hash)` → `Some(status_ok)` once mined,
204    /// `None` if still pending.
205    ///
206    /// Returns `Ok(Some(true))` when the receipt's `status` field is `0x1`,
207    /// `Ok(Some(false))` on `0x0` (reverted), `Ok(None)` if the receipt is
208    /// not yet available.
209    pub async fn transaction_receipt_status(
210        &self,
211        tx_hash: TxHash,
212    ) -> Result<Option<bool>, RpcError> {
213        let hash_hex = format!("{tx_hash:#x}");
214        let value: Value = match self
215            .call("eth_getTransactionReceipt", json!([hash_hex]))
216            .await
217        {
218            Ok(v) => v,
219            // Moderato public RPC occasionally returns {"jsonrpc":"2.0","id":1}
220            // with neither `result` nor `error`. Treat identically to
221            // `result: null` (pending) so `wait_for_receipt` keeps polling.
222            Err(RpcError::Decode(ref m)) if m.contains("missing both result and error") => {
223                return Ok(None);
224            }
225            Err(e) => return Err(e),
226        };
227        if value.is_null() {
228            return Ok(None);
229        }
230        let status = value
231            .get("status")
232            .and_then(Value::as_str)
233            .ok_or_else(|| RpcError::Decode("receipt missing status field".into()))?;
234        let ok = parse_hex_u64(status)? == 1;
235        Ok(Some(ok))
236    }
237
238    /// Poll `eth_getTransactionReceipt` until mined or `timeout` elapses.
239    ///
240    /// Returns `Ok(true)` on `status == 0x1`, `Ok(false)` on revert, and
241    /// `Err(RpcError::Decode)` on timeout. Caller maps the timeout to the
242    /// command-level error variant (poster path wants `CmdError::Server`).
243    pub async fn wait_for_receipt(
244        &self,
245        tx_hash: TxHash,
246        timeout: std::time::Duration,
247        interval: std::time::Duration,
248    ) -> Result<bool, RpcError> {
249        let deadline = std::time::Instant::now() + timeout;
250        loop {
251            if let Some(ok) = self.transaction_receipt_status(tx_hash).await? {
252                return Ok(ok);
253            }
254            if std::time::Instant::now() >= deadline {
255                return Err(RpcError::Decode(format!(
256                    "receipt for {tx_hash:#x} not mined within {:?}",
257                    timeout
258                )));
259            }
260            tokio::time::sleep(interval).await;
261        }
262    }
263
264    /// `eth_sendRawTransaction(0x<rlp>)` → tx hash.
265    pub async fn send_raw_transaction(&self, raw_tx: &[u8]) -> Result<TxHash, RpcError> {
266        let hex_str = format!("0x{}", hex::encode(raw_tx));
267        let raw: String = self
268            .call("eth_sendRawTransaction", json!([hex_str]))
269            .await?;
270        let bytes = decode_0x(&raw)?;
271        if bytes.len() != 32 {
272            return Err(RpcError::Decode(format!(
273                "tx hash must be 32 bytes, got {}",
274                bytes.len()
275            )));
276        }
277        Ok(TxHash::from_slice(&bytes))
278    }
279
280    /// Raw JSON-RPC passthrough: `method` + `params` in, untyped `result` out.
281    ///
282    /// Backs `taskfast cast rpc` (gh#101) — arbitrary methods (`tempo_*`
283    /// faucets, debug namespaces) that the typed wrappers above don't cover.
284    /// Deliberately non-generic so the public surface stays a single stable
285    /// signature; typed decoding remains internal via the private `call`.
286    pub async fn raw_call(&self, method: &str, params: Value) -> Result<Value, RpcError> {
287        self.call(method, params).await
288    }
289
290    async fn call<R>(&self, method: &str, params: Value) -> Result<R, RpcError>
291    where
292        R: for<'de> Deserialize<'de>,
293    {
294        let req = RpcRequest {
295            jsonrpc: "2.0",
296            id: 1,
297            method,
298            params,
299        };
300        // Public RPC endpoints throttle shared callers with 429. Retry a few
301        // times with exponential backoff — honoring `Retry-After` — before
302        // surfacing the error, so a rate limit doesn't fail an otherwise-healthy
303        // call. Every other non-2xx (incl. 5xx) surfaces immediately.
304        let mut attempt: u32 = 0;
305        let parsed: RpcResponse = loop {
306            let resp = self.http.post(&self.url).json(&req).send().await?;
307            let status = resp.status();
308            if status.is_success() {
309                break resp.json().await?;
310            }
311            if status.as_u16() == 429 && attempt < MAX_RPC_RETRIES {
312                let delay = retry_after(&resp)
313                    .map_or_else(|| rpc_backoff(attempt), |d| d.min(MAX_RETRY_AFTER));
314                tracing::debug!(attempt = %(attempt + 1), ?delay, "rpc throttled (429); retrying");
315                attempt += 1;
316                tokio::time::sleep(delay).await;
317                continue;
318            }
319            let body = resp.text().await.unwrap_or_default();
320            return Err(RpcError::Http {
321                status: status.as_u16(),
322                body,
323            });
324        };
325        if let Some(err) = parsed.error {
326            let message = match err.data {
327                Some(d) => format!("{} (data: {})", err.message, d),
328                None => err.message,
329            };
330            return Err(RpcError::Rpc {
331                code: err.code,
332                message,
333            });
334        }
335        let result = parsed
336            .result
337            .ok_or_else(|| RpcError::Decode("rpc response missing both result and error".into()))?;
338        serde_json::from_value(result).map_err(|e| RpcError::Decode(e.to_string()))
339    }
340}
341
342/// Sign `calldata` as a legacy tx targeting `to`, broadcast it, return tx hash.
343///
344/// Generalization of `sign_and_broadcast_erc20_transfer`: used by the poster's
345/// `taskfast escrow sign` flow for both `IERC20.approve` (target = token) and
346/// `TaskEscrow.open(...)` (target = escrow contract).
347///
348/// Fetches chain_id + nonce + gas_price + gas_limit (`eth_estimateGas` with a
349/// 30% buffer) from the RPC.
350pub async fn sign_and_broadcast_tx(
351    rpc: &TempoRpcClient,
352    signer: &PrivateKeySigner,
353    to: Address,
354    calldata: Bytes,
355) -> Result<TxHash, RpcError> {
356    let raw = sign_tx(rpc, signer, to, calldata).await?;
357    rpc.send_raw_transaction(&raw).await
358}
359
360/// Build + sign a legacy tx targeting `to` without broadcasting. Returns the
361/// raw RLP-encoded signed tx — suitable for dry-runs or server-broadcast flows.
362pub async fn sign_tx(
363    rpc: &TempoRpcClient,
364    signer: &PrivateKeySigner,
365    to: Address,
366    calldata: Bytes,
367) -> Result<Vec<u8>, RpcError> {
368    let chain_id = rpc.chain_id().await?;
369    let nonce = rpc.pending_nonce(signer.address()).await?;
370    let gas_price = rpc.gas_price().await?;
371    let estimate = rpc.estimate_gas(signer.address(), to, &calldata).await?;
372    let gas_limit = estimate.saturating_mul(GAS_ESTIMATE_BUFFER_NUM) / GAS_ESTIMATE_BUFFER_DEN;
373
374    let tx = TxLegacy {
375        chain_id: Some(chain_id),
376        nonce,
377        gas_price,
378        gas_limit,
379        to: TxKind::Call(to),
380        value: U256::ZERO,
381        input: calldata,
382    };
383    let sig_hash = tx.signature_hash();
384    let sig = signer
385        .sign_hash_sync(&sig_hash)
386        .map_err(|e| RpcError::Sign(e.to_string()))?;
387    let signed = tx.into_signed(sig);
388    let envelope = TxEnvelope::Legacy(signed);
389    Ok(envelope.encoded_2718())
390}
391
392/// Thin ERC-20 wrapper around [`sign_and_broadcast_tx`]. The returned hash is
393/// the `submission_fee_voucher` for `POST /task_drafts/{id}/submit`.
394pub async fn sign_and_broadcast_erc20_transfer(
395    rpc: &TempoRpcClient,
396    signer: &PrivateKeySigner,
397    token_address: Address,
398    calldata: Bytes,
399) -> Result<TxHash, RpcError> {
400    sign_and_broadcast_tx(rpc, signer, token_address, calldata).await
401}
402
403/// Thin ERC-20 wrapper around [`sign_tx`]. Returns raw RLP bytes for the
404/// "raw-signed-tx" voucher form.
405pub async fn sign_erc20_transfer(
406    rpc: &TempoRpcClient,
407    signer: &PrivateKeySigner,
408    token_address: Address,
409    calldata: Bytes,
410) -> Result<Vec<u8>, RpcError> {
411    sign_tx(rpc, signer, token_address, calldata).await
412}
413
414fn parse_hex_u64(s: &str) -> Result<u64, RpcError> {
415    let stripped = s.strip_prefix("0x").unwrap_or(s);
416    u64::from_str_radix(stripped, 16).map_err(|e| RpcError::Hex(format!("u64 from {s}: {e}")))
417}
418
419fn parse_hex_u128(s: &str) -> Result<u128, RpcError> {
420    let stripped = s.strip_prefix("0x").unwrap_or(s);
421    u128::from_str_radix(stripped, 16).map_err(|e| RpcError::Hex(format!("u128 from {s}: {e}")))
422}
423
424fn decode_0x(s: &str) -> Result<Vec<u8>, RpcError> {
425    let stripped = s.strip_prefix("0x").unwrap_or(s);
426    hex::decode(stripped).map_err(|e| RpcError::Hex(e.to_string()))
427}
428
429/// Max retries for a throttled RPC endpoint (429 only; every other non-2xx,
430/// incl. 5xx, surfaces immediately).
431const MAX_RPC_RETRIES: u32 = 5;
432
433/// Cap on a server-supplied `Retry-After` so a broken or malicious endpoint
434/// can't park the CLI for hours.
435const MAX_RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(30);
436
437/// Exponential backoff, capped: 250ms, 500ms, 1s, 2s, 4s, 4s…
438fn rpc_backoff(attempt: u32) -> std::time::Duration {
439    let ms = 250u64.saturating_mul(1u64 << attempt.min(4));
440    std::time::Duration::from_millis(ms.min(4_000))
441}
442
443/// Honor a numeric `Retry-After: <seconds>` header when the endpoint sends one.
444fn retry_after(resp: &reqwest::Response) -> Option<std::time::Duration> {
445    resp.headers()
446        .get(reqwest::header::RETRY_AFTER)?
447        .to_str()
448        .ok()?
449        .trim()
450        .parse::<u64>()
451        .ok()
452        .map(std::time::Duration::from_secs)
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458    use wiremock::matchers::{body_partial_json, method, path};
459    use wiremock::{Mock, MockServer, ResponseTemplate};
460
461    fn rpc_ok(result: Value) -> ResponseTemplate {
462        ResponseTemplate::new(200).set_body_json(json!({
463            "jsonrpc": "2.0",
464            "id": 1,
465            "result": result,
466        }))
467    }
468
469    #[tokio::test]
470    async fn chain_id_decodes_hex() {
471        let server = MockServer::start().await;
472        Mock::given(method("POST"))
473            .and(path("/"))
474            .and(body_partial_json(json!({"method": "eth_chainId"})))
475            .respond_with(rpc_ok(json!("0xa5bf")))
476            .mount(&server)
477            .await;
478        let rpc = TempoRpcClient::with_default_client(server.uri());
479        assert_eq!(rpc.chain_id().await.unwrap(), 42_431);
480    }
481
482    #[tokio::test]
483    async fn nonce_sends_pending_tag() {
484        let server = MockServer::start().await;
485        Mock::given(method("POST"))
486            .and(path("/"))
487            .and(body_partial_json(json!({
488                "method": "eth_getTransactionCount",
489                "params": ["0x0000000000000000000000000000000000000001", "pending"],
490            })))
491            .respond_with(rpc_ok(json!("0x7")))
492            .mount(&server)
493            .await;
494        let rpc = TempoRpcClient::with_default_client(server.uri());
495        let addr: Address = "0x0000000000000000000000000000000000000001"
496            .parse()
497            .unwrap();
498        assert_eq!(rpc.pending_nonce(addr).await.unwrap(), 7);
499    }
500
501    #[tokio::test]
502    async fn gas_price_decodes_u128() {
503        let server = MockServer::start().await;
504        Mock::given(method("POST"))
505            .and(path("/"))
506            .and(body_partial_json(json!({"method": "eth_gasPrice"})))
507            .respond_with(rpc_ok(json!("0x3b9aca00"))) // 1 gwei
508            .mount(&server)
509            .await;
510        let rpc = TempoRpcClient::with_default_client(server.uri());
511        assert_eq!(rpc.gas_price().await.unwrap(), 1_000_000_000u128);
512    }
513
514    #[tokio::test]
515    async fn send_raw_transaction_returns_tx_hash() {
516        let server = MockServer::start().await;
517        let hash_hex = format!("0x{}", "aa".repeat(32));
518        Mock::given(method("POST"))
519            .and(path("/"))
520            .and(body_partial_json(
521                json!({"method": "eth_sendRawTransaction"}),
522            ))
523            .respond_with(rpc_ok(json!(hash_hex.clone())))
524            .mount(&server)
525            .await;
526        let rpc = TempoRpcClient::with_default_client(server.uri());
527        let h = rpc.send_raw_transaction(&[1u8, 2, 3]).await.unwrap();
528        assert_eq!(format!("{h:#x}"), hash_hex);
529    }
530
531    #[tokio::test]
532    async fn raw_call_passes_method_params_and_returns_untyped_result() {
533        let server = MockServer::start().await;
534        Mock::given(method("POST"))
535            .and(path("/"))
536            .and(body_partial_json(json!({
537                "method": "tempo_fundAddress",
538                "params": ["0x0000000000000000000000000000000000000001"],
539            })))
540            .respond_with(rpc_ok(json!({"funded": true})))
541            .mount(&server)
542            .await;
543        let rpc = TempoRpcClient::with_default_client(server.uri());
544        let out = rpc
545            .raw_call(
546                "tempo_fundAddress",
547                json!(["0x0000000000000000000000000000000000000001"]),
548            )
549            .await
550            .unwrap();
551        assert_eq!(out, json!({"funded": true}));
552    }
553
554    #[tokio::test]
555    async fn rpc_error_body_surfaces_as_rpc_variant() {
556        let server = MockServer::start().await;
557        Mock::given(method("POST"))
558            .and(path("/"))
559            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
560                "jsonrpc": "2.0",
561                "id": 1,
562                "error": { "code": -32000, "message": "nonce too low" },
563            })))
564            .mount(&server)
565            .await;
566        let rpc = TempoRpcClient::with_default_client(server.uri());
567        let err = rpc.gas_price().await.expect_err("must fail");
568        match err {
569            RpcError::Rpc { code, message } => {
570                assert_eq!(code, -32000);
571                assert!(message.contains("nonce too low"));
572            }
573            other => panic!("expected Rpc, got {other:?}"),
574        }
575    }
576
577    #[tokio::test]
578    async fn http_5xx_surfaces_as_http_variant() {
579        let server = MockServer::start().await;
580        Mock::given(method("POST"))
581            .and(path("/"))
582            .respond_with(ResponseTemplate::new(502).set_body_string("upstream"))
583            .mount(&server)
584            .await;
585        let rpc = TempoRpcClient::with_default_client(server.uri());
586        let err = rpc.chain_id().await.expect_err("must fail");
587        assert!(
588            matches!(err, RpcError::Http { status: 502, .. }),
589            "got {err:?}"
590        );
591    }
592
593    #[tokio::test]
594    async fn eth_call_from_sets_the_sender() {
595        // Zone TIP-20 balance privacy: the self-read must carry `from` == owner.
596        let server = MockServer::start().await;
597        let from: Address = "0x00000000000000000000000000000000000000aa"
598            .parse()
599            .unwrap();
600        Mock::given(method("POST"))
601            .and(path("/"))
602            .and(body_partial_json(json!({
603                "method": "eth_call",
604                "params": [{ "from": format!("{from:#x}") }, "latest"],
605            })))
606            .respond_with(rpc_ok(json!("0x1234")))
607            .mount(&server)
608            .await;
609        let rpc = TempoRpcClient::with_default_client(server.uri());
610        let to: Address = "0x00000000000000000000000000000000000000bb"
611            .parse()
612            .unwrap();
613        let out = rpc
614            .eth_call_from(from, to, &Bytes::from(vec![0xab]))
615            .await
616            .unwrap();
617        assert_eq!(out, vec![0x12, 0x34]);
618    }
619
620    #[tokio::test]
621    async fn rpc_retries_on_429_then_succeeds() {
622        let server = MockServer::start().await;
623        // First response 429 (throttled), then a normal 200.
624        Mock::given(method("POST"))
625            .and(path("/"))
626            .respond_with(ResponseTemplate::new(429))
627            .up_to_n_times(1)
628            .with_priority(1)
629            .mount(&server)
630            .await;
631        Mock::given(method("POST"))
632            .and(path("/"))
633            .respond_with(rpc_ok(json!("0xa5bf")))
634            .with_priority(2)
635            .mount(&server)
636            .await;
637        let rpc = TempoRpcClient::with_default_client(server.uri());
638        assert_eq!(rpc.chain_id().await.unwrap(), 42_431);
639    }
640
641    #[tokio::test]
642    async fn estimate_gas_parses_hex_u64() {
643        let server = MockServer::start().await;
644        Mock::given(method("POST"))
645            .and(path("/"))
646            .and(body_partial_json(json!({"method": "eth_estimateGas"})))
647            .respond_with(rpc_ok(json!("0x4b094"))) // 307_348 — observed Tempo testnet USDC transfer
648            .mount(&server)
649            .await;
650        let rpc = TempoRpcClient::with_default_client(server.uri());
651        let from: Address = "0x0000000000000000000000000000000000000001"
652            .parse()
653            .unwrap();
654        let to: Address = "0x0000000000000000000000000000000000000002"
655            .parse()
656            .unwrap();
657        let gas = rpc
658            .estimate_gas(from, to, &Bytes::from_static(&[0xa9u8, 0x05, 0x9c, 0xbb]))
659            .await
660            .unwrap();
661        assert_eq!(gas, 307_348);
662    }
663
664    #[tokio::test]
665    async fn estimate_gas_rpc_error_propagates() {
666        let server = MockServer::start().await;
667        Mock::given(method("POST"))
668            .and(path("/"))
669            .and(body_partial_json(json!({"method": "eth_estimateGas"})))
670            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
671                "jsonrpc": "2.0",
672                "id": 1,
673                "error": { "code": 3, "message": "execution reverted: ERC20: insufficient balance" },
674            })))
675            .mount(&server)
676            .await;
677        let rpc = TempoRpcClient::with_default_client(server.uri());
678        let from: Address = "0x0000000000000000000000000000000000000001"
679            .parse()
680            .unwrap();
681        let to: Address = "0x0000000000000000000000000000000000000002"
682            .parse()
683            .unwrap();
684        let err = rpc
685            .estimate_gas(from, to, &Bytes::new())
686            .await
687            .expect_err("revert must propagate");
688        assert!(
689            matches!(err, RpcError::Rpc { code: 3, .. }),
690            "expected Rpc variant, got {err:?}"
691        );
692    }
693
694    #[tokio::test]
695    async fn sign_erc20_transfer_roundtrips_through_rpc() {
696        use alloy_eips::eip2718::Decodable2718;
697
698        let server = MockServer::start().await;
699        Mock::given(method("POST"))
700            .and(body_partial_json(json!({"method": "eth_chainId"})))
701            .respond_with(rpc_ok(json!("0xa5bf"))) // 42431 testnet
702            .mount(&server)
703            .await;
704        Mock::given(method("POST"))
705            .and(body_partial_json(
706                json!({"method": "eth_getTransactionCount"}),
707            ))
708            .respond_with(rpc_ok(json!("0x0")))
709            .mount(&server)
710            .await;
711        Mock::given(method("POST"))
712            .and(body_partial_json(json!({"method": "eth_gasPrice"})))
713            .respond_with(rpc_ok(json!("0x3b9aca00")))
714            .mount(&server)
715            .await;
716        Mock::given(method("POST"))
717            .and(body_partial_json(json!({"method": "eth_estimateGas"})))
718            .respond_with(rpc_ok(json!("0x4b094"))) // 307_348
719            .mount(&server)
720            .await;
721        let signer = PrivateKeySigner::random();
722        let rpc = TempoRpcClient::with_default_client(server.uri());
723        let token: Address = "0x00000000000000000000000000000000000000aa"
724            .parse()
725            .unwrap();
726        // Real-looking ERC-20 transfer calldata: selector 0xa9059cbb + 32b addr + 32b amount.
727        let calldata = Bytes::from_iter(
728            [0xa9u8, 0x05, 0x9c, 0xbb]
729                .into_iter()
730                .chain(vec![0u8; 32 + 32]),
731        );
732        let raw = sign_erc20_transfer(&rpc, &signer, token, calldata)
733            .await
734            .expect("sign");
735        assert!(!raw.is_empty(), "raw tx must encode to non-empty bytes");
736        // Legacy tx RLP starts with list prefix 0xc0..0xf7 or 0xf8..0xff.
737        assert!(
738            raw[0] >= 0xc0,
739            "legacy tx must be an RLP list, got first byte {:#x}",
740            raw[0]
741        );
742
743        // Decode the signed envelope and assert the buffered gas limit:
744        // floor(307_348 * 13 / 10) = 399_552.
745        let envelope = TxEnvelope::decode_2718(&mut raw.as_slice()).expect("decode envelope");
746        let TxEnvelope::Legacy(signed) = envelope else {
747            panic!("expected legacy envelope");
748        };
749        assert_eq!(signed.tx().gas_limit, 399_552);
750    }
751}