taskfast-agent 0.22.0

Orchestration library for TaskFast agents: bootstrap, wallet, webhooks, events, signing, keystore.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
// SPDX-License-Identifier: MIT
//! Minimal Tempo JSON-RPC client for the submission-fee voucher flow.
//!
//! `taskfast post` needs to:
//!   1. turn the server-emitted ERC-20 transfer calldata into a signed,
//!      broadcast tx whose hash can be submitted as a voucher, or
//!   2. hand the server a raw RLP-encoded signed tx it can broadcast.
//!
//! Both paths need `eth_chainId` + `eth_getTransactionCount` + `eth_gasPrice`
//! + `eth_estimateGas` to build a replay-safe legacy tx with a correctly
//! sized gas limit. Path (1) additionally needs `eth_sendRawTransaction`.
//! That's it. `alloy-provider` would cover this plus subscription,
//! middleware, and batching we don't want — so this module wraps those
//! five methods over `reqwest` directly.
//!
//! # Why legacy (not EIP-1559) txs
//!
//! Tempo is a stable-fee chain fork — `eth_gasPrice` is authoritative and
//! `eth_feeHistory` isn't guaranteed to exist on every node. A legacy tx
//! with `chain_id` set (EIP-155 replay protection) is the widest-compat
//! shape and keeps the RPC surface to 4 read methods + 1 write.

use alloy_consensus::{SignableTransaction, TxEnvelope, TxLegacy};
use alloy_eips::eip2718::Encodable2718;
use alloy_primitives::{Address, Bytes, TxHash, TxKind, U256};
use alloy_signer::SignerSync;
use alloy_signer_local::PrivateKeySigner;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use thiserror::Error as ThisError;

/// Buffer applied to `eth_estimateGas` output, as numerator/denominator.
/// 13/10 = +30%. State drift between estimate and execution (cold SLOAD,
/// new storage slot, balance flip) can push actual gas above the estimate;
/// 30% matches the conservative end of the ethers/alloy-ecosystem default.
const GAS_ESTIMATE_BUFFER_NUM: u64 = 13;
const GAS_ESTIMATE_BUFFER_DEN: u64 = 10;

/// Errors surfaced by [`TempoRpcClient`] and [`sign_and_broadcast_erc20_transfer`].
#[derive(Debug, ThisError)]
pub enum RpcError {
    #[error("rpc transport: {0}")]
    Transport(#[from] reqwest::Error),
    #[error("rpc returned non-2xx {status}: {body}")]
    Http { status: u16, body: String },
    #[error("rpc error {code}: {message}")]
    Rpc { code: i64, message: String },
    #[error("rpc response shape invalid: {0}")]
    Decode(String),
    #[error("hex decode: {0}")]
    Hex(String),
    #[error("signing failed: {0}")]
    Sign(String),
}

/// Thin JSON-RPC client over reqwest. One instance = one RPC endpoint.
#[derive(Debug, Clone)]
pub struct TempoRpcClient {
    http: reqwest::Client,
    url: String,
}

#[derive(Serialize)]
struct RpcRequest<'a, P: Serialize> {
    jsonrpc: &'static str,
    id: u64,
    method: &'a str,
    params: P,
}

#[derive(Deserialize)]
struct RpcResponse {
    #[serde(default)]
    result: Option<Value>,
    #[serde(default)]
    error: Option<RpcErrorBody>,
}

#[derive(Deserialize)]
struct RpcErrorBody {
    code: i64,
    #[serde(default)]
    message: String,
    #[serde(default)]
    data: Option<serde_json::Value>,
}

impl TempoRpcClient {
    /// Build from an existing reqwest client (share connection pool with the
    /// TaskFast API client) plus the Tempo RPC URL.
    pub fn new(http: reqwest::Client, url: impl Into<String>) -> Self {
        Self {
            http,
            url: url.into(),
        }
    }

    /// Convenience: build with a fresh reqwest client. Tests use this.
    pub fn with_default_client(url: impl Into<String>) -> Self {
        Self::new(reqwest::Client::new(), url)
    }

    /// `eth_chainId` → u64. Hex-prefixed-hex decode.
    pub async fn chain_id(&self) -> Result<u64, RpcError> {
        let raw: String = self.call("eth_chainId", json!([])).await?;
        parse_hex_u64(&raw)
    }

    /// `eth_getTransactionCount(address, "pending")` → nonce.
    ///
    /// Uses `pending` not `latest` so a second tx from the same signer doesn't
    /// collide on nonce if the first hasn't been mined yet.
    pub async fn pending_nonce(&self, addr: Address) -> Result<u64, RpcError> {
        let raw: String = self
            .call(
                "eth_getTransactionCount",
                json!([format!("{addr:#x}"), "pending"]),
            )
            .await?;
        parse_hex_u64(&raw)
    }

    /// `eth_gasPrice` → u128. Wei.
    pub async fn gas_price(&self) -> Result<u128, RpcError> {
        let raw: String = self.call("eth_gasPrice", json!([])).await?;
        parse_hex_u128(&raw)
    }

    /// `eth_estimateGas({from, to, data})` → gas units.
    ///
    /// Called before every ERC-20 transfer so we size `gas_limit` to actual
    /// chain state (Tempo testnet's canonical USDC `transfer` lands around
    /// 307k; a different token or recipient-with-no-prior-balance can push
    /// higher). A revert here means the tx would fail on-chain — callers
    /// should surface the error rather than broadcast a doomed tx.
    pub async fn estimate_gas(
        &self,
        from: Address,
        to: Address,
        data: &Bytes,
    ) -> Result<u64, RpcError> {
        let raw: String = self
            .call(
                "eth_estimateGas",
                json!([{
                    "from": format!("{from:#x}"),
                    "to": format!("{to:#x}"),
                    "data": format!("0x{}", hex::encode(data)),
                }]),
            )
            .await?;
        parse_hex_u64(&raw)
    }

    /// `eth_call({to, data}, "latest")` → returned bytes.
    ///
    /// Used for view-only calls (ERC-20 `allowance` / `balanceOf`, etc.) where
    /// we need to read chain state without broadcasting a tx.
    pub async fn eth_call(&self, to: Address, data: &Bytes) -> Result<Vec<u8>, RpcError> {
        let raw: String = self
            .call(
                "eth_call",
                json!([
                    {
                        "to": format!("{to:#x}"),
                        "data": format!("0x{}", hex::encode(data)),
                    },
                    "latest",
                ]),
            )
            .await?;
        decode_0x(&raw)
    }

    /// `eth_call({from, to, data}, "latest")` → returned bytes.
    ///
    /// Like [`Self::eth_call`] but with an explicit sender. Tempo Zone TIP-20s
    /// enforce balance privacy — `balanceOf(X)`/`allowance(X, …)` revert
    /// `Unauthorized` unless `msg.sender` is a party — so self-reads must
    /// impersonate the queried address (needs no signature; a no-op on L1).
    pub async fn eth_call_from(
        &self,
        from: Address,
        to: Address,
        data: &Bytes,
    ) -> Result<Vec<u8>, RpcError> {
        let raw: String = self
            .call(
                "eth_call",
                json!([
                    {
                        "from": format!("{from:#x}"),
                        "to": format!("{to:#x}"),
                        "data": format!("0x{}", hex::encode(data)),
                    },
                    "latest",
                ]),
            )
            .await?;
        decode_0x(&raw)
    }

    /// `eth_getTransactionReceipt(tx_hash)` → `Some(status_ok)` once mined,
    /// `None` if still pending.
    ///
    /// Returns `Ok(Some(true))` when the receipt's `status` field is `0x1`,
    /// `Ok(Some(false))` on `0x0` (reverted), `Ok(None)` if the receipt is
    /// not yet available.
    pub async fn transaction_receipt_status(
        &self,
        tx_hash: TxHash,
    ) -> Result<Option<bool>, RpcError> {
        let hash_hex = format!("{tx_hash:#x}");
        let value: Value = match self
            .call("eth_getTransactionReceipt", json!([hash_hex]))
            .await
        {
            Ok(v) => v,
            // Moderato public RPC occasionally returns {"jsonrpc":"2.0","id":1}
            // with neither `result` nor `error`. Treat identically to
            // `result: null` (pending) so `wait_for_receipt` keeps polling.
            Err(RpcError::Decode(ref m)) if m.contains("missing both result and error") => {
                return Ok(None);
            }
            Err(e) => return Err(e),
        };
        if value.is_null() {
            return Ok(None);
        }
        let status = value
            .get("status")
            .and_then(Value::as_str)
            .ok_or_else(|| RpcError::Decode("receipt missing status field".into()))?;
        let ok = parse_hex_u64(status)? == 1;
        Ok(Some(ok))
    }

    /// Poll `eth_getTransactionReceipt` until mined or `timeout` elapses.
    ///
    /// Returns `Ok(true)` on `status == 0x1`, `Ok(false)` on revert, and
    /// `Err(RpcError::Decode)` on timeout. Caller maps the timeout to the
    /// command-level error variant (poster path wants `CmdError::Server`).
    pub async fn wait_for_receipt(
        &self,
        tx_hash: TxHash,
        timeout: std::time::Duration,
        interval: std::time::Duration,
    ) -> Result<bool, RpcError> {
        let deadline = std::time::Instant::now() + timeout;
        loop {
            if let Some(ok) = self.transaction_receipt_status(tx_hash).await? {
                return Ok(ok);
            }
            if std::time::Instant::now() >= deadline {
                return Err(RpcError::Decode(format!(
                    "receipt for {tx_hash:#x} not mined within {:?}",
                    timeout
                )));
            }
            tokio::time::sleep(interval).await;
        }
    }

    /// `eth_sendRawTransaction(0x<rlp>)` → tx hash.
    pub async fn send_raw_transaction(&self, raw_tx: &[u8]) -> Result<TxHash, RpcError> {
        let hex_str = format!("0x{}", hex::encode(raw_tx));
        let raw: String = self
            .call("eth_sendRawTransaction", json!([hex_str]))
            .await?;
        let bytes = decode_0x(&raw)?;
        if bytes.len() != 32 {
            return Err(RpcError::Decode(format!(
                "tx hash must be 32 bytes, got {}",
                bytes.len()
            )));
        }
        Ok(TxHash::from_slice(&bytes))
    }

    /// Raw JSON-RPC passthrough: `method` + `params` in, untyped `result` out.
    ///
    /// Backs `taskfast cast rpc` (gh#101) — arbitrary methods (`tempo_*`
    /// faucets, debug namespaces) that the typed wrappers above don't cover.
    /// Deliberately non-generic so the public surface stays a single stable
    /// signature; typed decoding remains internal via the private `call`.
    pub async fn raw_call(&self, method: &str, params: Value) -> Result<Value, RpcError> {
        self.call(method, params).await
    }

    async fn call<R>(&self, method: &str, params: Value) -> Result<R, RpcError>
    where
        R: for<'de> Deserialize<'de>,
    {
        let req = RpcRequest {
            jsonrpc: "2.0",
            id: 1,
            method,
            params,
        };
        // Public RPC endpoints throttle shared callers with 429. Retry a few
        // times with exponential backoff — honoring `Retry-After` — before
        // surfacing the error, so a rate limit doesn't fail an otherwise-healthy
        // call. Every other non-2xx (incl. 5xx) surfaces immediately.
        let mut attempt: u32 = 0;
        let parsed: RpcResponse = loop {
            let resp = self.http.post(&self.url).json(&req).send().await?;
            let status = resp.status();
            if status.is_success() {
                break resp.json().await?;
            }
            if status.as_u16() == 429 && attempt < MAX_RPC_RETRIES {
                let delay = retry_after(&resp)
                    .map_or_else(|| rpc_backoff(attempt), |d| d.min(MAX_RETRY_AFTER));
                tracing::debug!(attempt = %(attempt + 1), ?delay, "rpc throttled (429); retrying");
                attempt += 1;
                tokio::time::sleep(delay).await;
                continue;
            }
            let body = resp.text().await.unwrap_or_default();
            return Err(RpcError::Http {
                status: status.as_u16(),
                body,
            });
        };
        if let Some(err) = parsed.error {
            let message = match err.data {
                Some(d) => format!("{} (data: {})", err.message, d),
                None => err.message,
            };
            return Err(RpcError::Rpc {
                code: err.code,
                message,
            });
        }
        let result = parsed
            .result
            .ok_or_else(|| RpcError::Decode("rpc response missing both result and error".into()))?;
        serde_json::from_value(result).map_err(|e| RpcError::Decode(e.to_string()))
    }
}

/// Sign `calldata` as a legacy tx targeting `to`, broadcast it, return tx hash.
///
/// Generalization of `sign_and_broadcast_erc20_transfer`: used by the poster's
/// `taskfast escrow sign` flow for both `IERC20.approve` (target = token) and
/// `TaskEscrow.open(...)` (target = escrow contract).
///
/// Fetches chain_id + nonce + gas_price + gas_limit (`eth_estimateGas` with a
/// 30% buffer) from the RPC.
pub async fn sign_and_broadcast_tx(
    rpc: &TempoRpcClient,
    signer: &PrivateKeySigner,
    to: Address,
    calldata: Bytes,
) -> Result<TxHash, RpcError> {
    let raw = sign_tx(rpc, signer, to, calldata).await?;
    rpc.send_raw_transaction(&raw).await
}

/// Build + sign a legacy tx targeting `to` without broadcasting. Returns the
/// raw RLP-encoded signed tx — suitable for dry-runs or server-broadcast flows.
pub async fn sign_tx(
    rpc: &TempoRpcClient,
    signer: &PrivateKeySigner,
    to: Address,
    calldata: Bytes,
) -> Result<Vec<u8>, RpcError> {
    let chain_id = rpc.chain_id().await?;
    let nonce = rpc.pending_nonce(signer.address()).await?;
    let gas_price = rpc.gas_price().await?;
    let estimate = rpc.estimate_gas(signer.address(), to, &calldata).await?;
    let gas_limit = estimate.saturating_mul(GAS_ESTIMATE_BUFFER_NUM) / GAS_ESTIMATE_BUFFER_DEN;

    let tx = TxLegacy {
        chain_id: Some(chain_id),
        nonce,
        gas_price,
        gas_limit,
        to: TxKind::Call(to),
        value: U256::ZERO,
        input: calldata,
    };
    let sig_hash = tx.signature_hash();
    let sig = signer
        .sign_hash_sync(&sig_hash)
        .map_err(|e| RpcError::Sign(e.to_string()))?;
    let signed = tx.into_signed(sig);
    let envelope = TxEnvelope::Legacy(signed);
    Ok(envelope.encoded_2718())
}

/// Thin ERC-20 wrapper around [`sign_and_broadcast_tx`]. The returned hash is
/// the `submission_fee_voucher` for `POST /task_drafts/{id}/submit`.
pub async fn sign_and_broadcast_erc20_transfer(
    rpc: &TempoRpcClient,
    signer: &PrivateKeySigner,
    token_address: Address,
    calldata: Bytes,
) -> Result<TxHash, RpcError> {
    sign_and_broadcast_tx(rpc, signer, token_address, calldata).await
}

/// Thin ERC-20 wrapper around [`sign_tx`]. Returns raw RLP bytes for the
/// "raw-signed-tx" voucher form.
pub async fn sign_erc20_transfer(
    rpc: &TempoRpcClient,
    signer: &PrivateKeySigner,
    token_address: Address,
    calldata: Bytes,
) -> Result<Vec<u8>, RpcError> {
    sign_tx(rpc, signer, token_address, calldata).await
}

fn parse_hex_u64(s: &str) -> Result<u64, RpcError> {
    let stripped = s.strip_prefix("0x").unwrap_or(s);
    u64::from_str_radix(stripped, 16).map_err(|e| RpcError::Hex(format!("u64 from {s}: {e}")))
}

fn parse_hex_u128(s: &str) -> Result<u128, RpcError> {
    let stripped = s.strip_prefix("0x").unwrap_or(s);
    u128::from_str_radix(stripped, 16).map_err(|e| RpcError::Hex(format!("u128 from {s}: {e}")))
}

fn decode_0x(s: &str) -> Result<Vec<u8>, RpcError> {
    let stripped = s.strip_prefix("0x").unwrap_or(s);
    hex::decode(stripped).map_err(|e| RpcError::Hex(e.to_string()))
}

/// Max retries for a throttled RPC endpoint (429 only; every other non-2xx,
/// incl. 5xx, surfaces immediately).
const MAX_RPC_RETRIES: u32 = 5;

/// Cap on a server-supplied `Retry-After` so a broken or malicious endpoint
/// can't park the CLI for hours.
const MAX_RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(30);

/// Exponential backoff, capped: 250ms, 500ms, 1s, 2s, 4s, 4s…
fn rpc_backoff(attempt: u32) -> std::time::Duration {
    let ms = 250u64.saturating_mul(1u64 << attempt.min(4));
    std::time::Duration::from_millis(ms.min(4_000))
}

/// Honor a numeric `Retry-After: <seconds>` header when the endpoint sends one.
fn retry_after(resp: &reqwest::Response) -> Option<std::time::Duration> {
    resp.headers()
        .get(reqwest::header::RETRY_AFTER)?
        .to_str()
        .ok()?
        .trim()
        .parse::<u64>()
        .ok()
        .map(std::time::Duration::from_secs)
}

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{body_partial_json, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn rpc_ok(result: Value) -> ResponseTemplate {
        ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0",
            "id": 1,
            "result": result,
        }))
    }

    #[tokio::test]
    async fn chain_id_decodes_hex() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/"))
            .and(body_partial_json(json!({"method": "eth_chainId"})))
            .respond_with(rpc_ok(json!("0xa5bf")))
            .mount(&server)
            .await;
        let rpc = TempoRpcClient::with_default_client(server.uri());
        assert_eq!(rpc.chain_id().await.unwrap(), 42_431);
    }

    #[tokio::test]
    async fn nonce_sends_pending_tag() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/"))
            .and(body_partial_json(json!({
                "method": "eth_getTransactionCount",
                "params": ["0x0000000000000000000000000000000000000001", "pending"],
            })))
            .respond_with(rpc_ok(json!("0x7")))
            .mount(&server)
            .await;
        let rpc = TempoRpcClient::with_default_client(server.uri());
        let addr: Address = "0x0000000000000000000000000000000000000001"
            .parse()
            .unwrap();
        assert_eq!(rpc.pending_nonce(addr).await.unwrap(), 7);
    }

    #[tokio::test]
    async fn gas_price_decodes_u128() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/"))
            .and(body_partial_json(json!({"method": "eth_gasPrice"})))
            .respond_with(rpc_ok(json!("0x3b9aca00"))) // 1 gwei
            .mount(&server)
            .await;
        let rpc = TempoRpcClient::with_default_client(server.uri());
        assert_eq!(rpc.gas_price().await.unwrap(), 1_000_000_000u128);
    }

    #[tokio::test]
    async fn send_raw_transaction_returns_tx_hash() {
        let server = MockServer::start().await;
        let hash_hex = format!("0x{}", "aa".repeat(32));
        Mock::given(method("POST"))
            .and(path("/"))
            .and(body_partial_json(
                json!({"method": "eth_sendRawTransaction"}),
            ))
            .respond_with(rpc_ok(json!(hash_hex.clone())))
            .mount(&server)
            .await;
        let rpc = TempoRpcClient::with_default_client(server.uri());
        let h = rpc.send_raw_transaction(&[1u8, 2, 3]).await.unwrap();
        assert_eq!(format!("{h:#x}"), hash_hex);
    }

    #[tokio::test]
    async fn raw_call_passes_method_params_and_returns_untyped_result() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/"))
            .and(body_partial_json(json!({
                "method": "tempo_fundAddress",
                "params": ["0x0000000000000000000000000000000000000001"],
            })))
            .respond_with(rpc_ok(json!({"funded": true})))
            .mount(&server)
            .await;
        let rpc = TempoRpcClient::with_default_client(server.uri());
        let out = rpc
            .raw_call(
                "tempo_fundAddress",
                json!(["0x0000000000000000000000000000000000000001"]),
            )
            .await
            .unwrap();
        assert_eq!(out, json!({"funded": true}));
    }

    #[tokio::test]
    async fn rpc_error_body_surfaces_as_rpc_variant() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "jsonrpc": "2.0",
                "id": 1,
                "error": { "code": -32000, "message": "nonce too low" },
            })))
            .mount(&server)
            .await;
        let rpc = TempoRpcClient::with_default_client(server.uri());
        let err = rpc.gas_price().await.expect_err("must fail");
        match err {
            RpcError::Rpc { code, message } => {
                assert_eq!(code, -32000);
                assert!(message.contains("nonce too low"));
            }
            other => panic!("expected Rpc, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn http_5xx_surfaces_as_http_variant() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(502).set_body_string("upstream"))
            .mount(&server)
            .await;
        let rpc = TempoRpcClient::with_default_client(server.uri());
        let err = rpc.chain_id().await.expect_err("must fail");
        assert!(
            matches!(err, RpcError::Http { status: 502, .. }),
            "got {err:?}"
        );
    }

    #[tokio::test]
    async fn eth_call_from_sets_the_sender() {
        // Zone TIP-20 balance privacy: the self-read must carry `from` == owner.
        let server = MockServer::start().await;
        let from: Address = "0x00000000000000000000000000000000000000aa"
            .parse()
            .unwrap();
        Mock::given(method("POST"))
            .and(path("/"))
            .and(body_partial_json(json!({
                "method": "eth_call",
                "params": [{ "from": format!("{from:#x}") }, "latest"],
            })))
            .respond_with(rpc_ok(json!("0x1234")))
            .mount(&server)
            .await;
        let rpc = TempoRpcClient::with_default_client(server.uri());
        let to: Address = "0x00000000000000000000000000000000000000bb"
            .parse()
            .unwrap();
        let out = rpc
            .eth_call_from(from, to, &Bytes::from(vec![0xab]))
            .await
            .unwrap();
        assert_eq!(out, vec![0x12, 0x34]);
    }

    #[tokio::test]
    async fn rpc_retries_on_429_then_succeeds() {
        let server = MockServer::start().await;
        // First response 429 (throttled), then a normal 200.
        Mock::given(method("POST"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(429))
            .up_to_n_times(1)
            .with_priority(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/"))
            .respond_with(rpc_ok(json!("0xa5bf")))
            .with_priority(2)
            .mount(&server)
            .await;
        let rpc = TempoRpcClient::with_default_client(server.uri());
        assert_eq!(rpc.chain_id().await.unwrap(), 42_431);
    }

    #[tokio::test]
    async fn estimate_gas_parses_hex_u64() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/"))
            .and(body_partial_json(json!({"method": "eth_estimateGas"})))
            .respond_with(rpc_ok(json!("0x4b094"))) // 307_348 — observed Tempo testnet USDC transfer
            .mount(&server)
            .await;
        let rpc = TempoRpcClient::with_default_client(server.uri());
        let from: Address = "0x0000000000000000000000000000000000000001"
            .parse()
            .unwrap();
        let to: Address = "0x0000000000000000000000000000000000000002"
            .parse()
            .unwrap();
        let gas = rpc
            .estimate_gas(from, to, &Bytes::from_static(&[0xa9u8, 0x05, 0x9c, 0xbb]))
            .await
            .unwrap();
        assert_eq!(gas, 307_348);
    }

    #[tokio::test]
    async fn estimate_gas_rpc_error_propagates() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/"))
            .and(body_partial_json(json!({"method": "eth_estimateGas"})))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "jsonrpc": "2.0",
                "id": 1,
                "error": { "code": 3, "message": "execution reverted: ERC20: insufficient balance" },
            })))
            .mount(&server)
            .await;
        let rpc = TempoRpcClient::with_default_client(server.uri());
        let from: Address = "0x0000000000000000000000000000000000000001"
            .parse()
            .unwrap();
        let to: Address = "0x0000000000000000000000000000000000000002"
            .parse()
            .unwrap();
        let err = rpc
            .estimate_gas(from, to, &Bytes::new())
            .await
            .expect_err("revert must propagate");
        assert!(
            matches!(err, RpcError::Rpc { code: 3, .. }),
            "expected Rpc variant, got {err:?}"
        );
    }

    #[tokio::test]
    async fn sign_erc20_transfer_roundtrips_through_rpc() {
        use alloy_eips::eip2718::Decodable2718;

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(body_partial_json(json!({"method": "eth_chainId"})))
            .respond_with(rpc_ok(json!("0xa5bf"))) // 42431 testnet
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(body_partial_json(
                json!({"method": "eth_getTransactionCount"}),
            ))
            .respond_with(rpc_ok(json!("0x0")))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(body_partial_json(json!({"method": "eth_gasPrice"})))
            .respond_with(rpc_ok(json!("0x3b9aca00")))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(body_partial_json(json!({"method": "eth_estimateGas"})))
            .respond_with(rpc_ok(json!("0x4b094"))) // 307_348
            .mount(&server)
            .await;
        let signer = PrivateKeySigner::random();
        let rpc = TempoRpcClient::with_default_client(server.uri());
        let token: Address = "0x00000000000000000000000000000000000000aa"
            .parse()
            .unwrap();
        // Real-looking ERC-20 transfer calldata: selector 0xa9059cbb + 32b addr + 32b amount.
        let calldata = Bytes::from_iter(
            [0xa9u8, 0x05, 0x9c, 0xbb]
                .into_iter()
                .chain(vec![0u8; 32 + 32]),
        );
        let raw = sign_erc20_transfer(&rpc, &signer, token, calldata)
            .await
            .expect("sign");
        assert!(!raw.is_empty(), "raw tx must encode to non-empty bytes");
        // Legacy tx RLP starts with list prefix 0xc0..0xf7 or 0xf8..0xff.
        assert!(
            raw[0] >= 0xc0,
            "legacy tx must be an RLP list, got first byte {:#x}",
            raw[0]
        );

        // Decode the signed envelope and assert the buffered gas limit:
        // floor(307_348 * 13 / 10) = 399_552.
        let envelope = TxEnvelope::decode_2718(&mut raw.as_slice()).expect("decode envelope");
        let TxEnvelope::Legacy(signed) = envelope else {
            panic!("expected legacy envelope");
        };
        assert_eq!(signed.tx().gas_limit, 399_552);
    }
}