1use 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
32const GAS_ESTIMATE_BUFFER_NUM: u64 = 13;
37const GAS_ESTIMATE_BUFFER_DEN: u64 = 10;
38
39#[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#[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 pub fn new(http: reqwest::Client, url: impl Into<String>) -> Self {
92 Self {
93 http,
94 url: url.into(),
95 }
96 }
97
98 pub fn with_default_client(url: impl Into<String>) -> Self {
100 Self::new(reqwest::Client::new(), url)
101 }
102
103 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 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 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 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 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 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 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 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 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 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 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 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
342pub 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
360pub 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
392pub 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
403pub 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
429const MAX_RPC_RETRIES: u32 = 5;
432
433const MAX_RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(30);
436
437fn 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
443fn 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"))) .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 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 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"))) .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"))) .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"))) .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 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 assert!(
738 raw[0] >= 0xc0,
739 "legacy tx must be an RLP list, got first byte {:#x}",
740 raw[0]
741 );
742
743 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}