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 transaction_receipt_status(
182 &self,
183 tx_hash: TxHash,
184 ) -> Result<Option<bool>, RpcError> {
185 let hash_hex = format!("{tx_hash:#x}");
186 let value: Value = match self
187 .call("eth_getTransactionReceipt", json!([hash_hex]))
188 .await
189 {
190 Ok(v) => v,
191 Err(RpcError::Decode(ref m)) if m.contains("missing both result and error") => {
195 return Ok(None);
196 }
197 Err(e) => return Err(e),
198 };
199 if value.is_null() {
200 return Ok(None);
201 }
202 let status = value
203 .get("status")
204 .and_then(Value::as_str)
205 .ok_or_else(|| RpcError::Decode("receipt missing status field".into()))?;
206 let ok = parse_hex_u64(status)? == 1;
207 Ok(Some(ok))
208 }
209
210 pub async fn wait_for_receipt(
216 &self,
217 tx_hash: TxHash,
218 timeout: std::time::Duration,
219 interval: std::time::Duration,
220 ) -> Result<bool, RpcError> {
221 let deadline = std::time::Instant::now() + timeout;
222 loop {
223 if let Some(ok) = self.transaction_receipt_status(tx_hash).await? {
224 return Ok(ok);
225 }
226 if std::time::Instant::now() >= deadline {
227 return Err(RpcError::Decode(format!(
228 "receipt for {tx_hash:#x} not mined within {:?}",
229 timeout
230 )));
231 }
232 tokio::time::sleep(interval).await;
233 }
234 }
235
236 pub async fn send_raw_transaction(&self, raw_tx: &[u8]) -> Result<TxHash, RpcError> {
238 let hex_str = format!("0x{}", hex::encode(raw_tx));
239 let raw: String = self
240 .call("eth_sendRawTransaction", json!([hex_str]))
241 .await?;
242 let bytes = decode_0x(&raw)?;
243 if bytes.len() != 32 {
244 return Err(RpcError::Decode(format!(
245 "tx hash must be 32 bytes, got {}",
246 bytes.len()
247 )));
248 }
249 Ok(TxHash::from_slice(&bytes))
250 }
251
252 pub async fn raw_call(&self, method: &str, params: Value) -> Result<Value, RpcError> {
259 self.call(method, params).await
260 }
261
262 async fn call<R>(&self, method: &str, params: Value) -> Result<R, RpcError>
263 where
264 R: for<'de> Deserialize<'de>,
265 {
266 let req = RpcRequest {
267 jsonrpc: "2.0",
268 id: 1,
269 method,
270 params,
271 };
272 let resp = self.http.post(&self.url).json(&req).send().await?;
273 let status = resp.status();
274 if !status.is_success() {
275 let body = resp.text().await.unwrap_or_default();
276 return Err(RpcError::Http {
277 status: status.as_u16(),
278 body,
279 });
280 }
281 let parsed: RpcResponse = resp.json().await?;
282 if let Some(err) = parsed.error {
283 let message = match err.data {
284 Some(d) => format!("{} (data: {})", err.message, d),
285 None => err.message,
286 };
287 return Err(RpcError::Rpc {
288 code: err.code,
289 message,
290 });
291 }
292 let result = parsed
293 .result
294 .ok_or_else(|| RpcError::Decode("rpc response missing both result and error".into()))?;
295 serde_json::from_value(result).map_err(|e| RpcError::Decode(e.to_string()))
296 }
297}
298
299pub async fn sign_and_broadcast_tx(
308 rpc: &TempoRpcClient,
309 signer: &PrivateKeySigner,
310 to: Address,
311 calldata: Bytes,
312) -> Result<TxHash, RpcError> {
313 let raw = sign_tx(rpc, signer, to, calldata).await?;
314 rpc.send_raw_transaction(&raw).await
315}
316
317pub async fn sign_tx(
320 rpc: &TempoRpcClient,
321 signer: &PrivateKeySigner,
322 to: Address,
323 calldata: Bytes,
324) -> Result<Vec<u8>, RpcError> {
325 let chain_id = rpc.chain_id().await?;
326 let nonce = rpc.pending_nonce(signer.address()).await?;
327 let gas_price = rpc.gas_price().await?;
328 let estimate = rpc.estimate_gas(signer.address(), to, &calldata).await?;
329 let gas_limit = estimate.saturating_mul(GAS_ESTIMATE_BUFFER_NUM) / GAS_ESTIMATE_BUFFER_DEN;
330
331 let tx = TxLegacy {
332 chain_id: Some(chain_id),
333 nonce,
334 gas_price,
335 gas_limit,
336 to: TxKind::Call(to),
337 value: U256::ZERO,
338 input: calldata,
339 };
340 let sig_hash = tx.signature_hash();
341 let sig = signer
342 .sign_hash_sync(&sig_hash)
343 .map_err(|e| RpcError::Sign(e.to_string()))?;
344 let signed = tx.into_signed(sig);
345 let envelope = TxEnvelope::Legacy(signed);
346 Ok(envelope.encoded_2718())
347}
348
349pub async fn sign_and_broadcast_erc20_transfer(
352 rpc: &TempoRpcClient,
353 signer: &PrivateKeySigner,
354 token_address: Address,
355 calldata: Bytes,
356) -> Result<TxHash, RpcError> {
357 sign_and_broadcast_tx(rpc, signer, token_address, calldata).await
358}
359
360pub async fn sign_erc20_transfer(
363 rpc: &TempoRpcClient,
364 signer: &PrivateKeySigner,
365 token_address: Address,
366 calldata: Bytes,
367) -> Result<Vec<u8>, RpcError> {
368 sign_tx(rpc, signer, token_address, calldata).await
369}
370
371fn parse_hex_u64(s: &str) -> Result<u64, RpcError> {
372 let stripped = s.strip_prefix("0x").unwrap_or(s);
373 u64::from_str_radix(stripped, 16).map_err(|e| RpcError::Hex(format!("u64 from {s}: {e}")))
374}
375
376fn parse_hex_u128(s: &str) -> Result<u128, RpcError> {
377 let stripped = s.strip_prefix("0x").unwrap_or(s);
378 u128::from_str_radix(stripped, 16).map_err(|e| RpcError::Hex(format!("u128 from {s}: {e}")))
379}
380
381fn decode_0x(s: &str) -> Result<Vec<u8>, RpcError> {
382 let stripped = s.strip_prefix("0x").unwrap_or(s);
383 hex::decode(stripped).map_err(|e| RpcError::Hex(e.to_string()))
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389 use wiremock::matchers::{body_partial_json, method, path};
390 use wiremock::{Mock, MockServer, ResponseTemplate};
391
392 fn rpc_ok(result: Value) -> ResponseTemplate {
393 ResponseTemplate::new(200).set_body_json(json!({
394 "jsonrpc": "2.0",
395 "id": 1,
396 "result": result,
397 }))
398 }
399
400 #[tokio::test]
401 async fn chain_id_decodes_hex() {
402 let server = MockServer::start().await;
403 Mock::given(method("POST"))
404 .and(path("/"))
405 .and(body_partial_json(json!({"method": "eth_chainId"})))
406 .respond_with(rpc_ok(json!("0xa5bf")))
407 .mount(&server)
408 .await;
409 let rpc = TempoRpcClient::with_default_client(server.uri());
410 assert_eq!(rpc.chain_id().await.unwrap(), 42_431);
411 }
412
413 #[tokio::test]
414 async fn nonce_sends_pending_tag() {
415 let server = MockServer::start().await;
416 Mock::given(method("POST"))
417 .and(path("/"))
418 .and(body_partial_json(json!({
419 "method": "eth_getTransactionCount",
420 "params": ["0x0000000000000000000000000000000000000001", "pending"],
421 })))
422 .respond_with(rpc_ok(json!("0x7")))
423 .mount(&server)
424 .await;
425 let rpc = TempoRpcClient::with_default_client(server.uri());
426 let addr: Address = "0x0000000000000000000000000000000000000001"
427 .parse()
428 .unwrap();
429 assert_eq!(rpc.pending_nonce(addr).await.unwrap(), 7);
430 }
431
432 #[tokio::test]
433 async fn gas_price_decodes_u128() {
434 let server = MockServer::start().await;
435 Mock::given(method("POST"))
436 .and(path("/"))
437 .and(body_partial_json(json!({"method": "eth_gasPrice"})))
438 .respond_with(rpc_ok(json!("0x3b9aca00"))) .mount(&server)
440 .await;
441 let rpc = TempoRpcClient::with_default_client(server.uri());
442 assert_eq!(rpc.gas_price().await.unwrap(), 1_000_000_000u128);
443 }
444
445 #[tokio::test]
446 async fn send_raw_transaction_returns_tx_hash() {
447 let server = MockServer::start().await;
448 let hash_hex = format!("0x{}", "aa".repeat(32));
449 Mock::given(method("POST"))
450 .and(path("/"))
451 .and(body_partial_json(
452 json!({"method": "eth_sendRawTransaction"}),
453 ))
454 .respond_with(rpc_ok(json!(hash_hex.clone())))
455 .mount(&server)
456 .await;
457 let rpc = TempoRpcClient::with_default_client(server.uri());
458 let h = rpc.send_raw_transaction(&[1u8, 2, 3]).await.unwrap();
459 assert_eq!(format!("{h:#x}"), hash_hex);
460 }
461
462 #[tokio::test]
463 async fn raw_call_passes_method_params_and_returns_untyped_result() {
464 let server = MockServer::start().await;
465 Mock::given(method("POST"))
466 .and(path("/"))
467 .and(body_partial_json(json!({
468 "method": "tempo_fundAddress",
469 "params": ["0x0000000000000000000000000000000000000001"],
470 })))
471 .respond_with(rpc_ok(json!({"funded": true})))
472 .mount(&server)
473 .await;
474 let rpc = TempoRpcClient::with_default_client(server.uri());
475 let out = rpc
476 .raw_call(
477 "tempo_fundAddress",
478 json!(["0x0000000000000000000000000000000000000001"]),
479 )
480 .await
481 .unwrap();
482 assert_eq!(out, json!({"funded": true}));
483 }
484
485 #[tokio::test]
486 async fn rpc_error_body_surfaces_as_rpc_variant() {
487 let server = MockServer::start().await;
488 Mock::given(method("POST"))
489 .and(path("/"))
490 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
491 "jsonrpc": "2.0",
492 "id": 1,
493 "error": { "code": -32000, "message": "nonce too low" },
494 })))
495 .mount(&server)
496 .await;
497 let rpc = TempoRpcClient::with_default_client(server.uri());
498 let err = rpc.gas_price().await.expect_err("must fail");
499 match err {
500 RpcError::Rpc { code, message } => {
501 assert_eq!(code, -32000);
502 assert!(message.contains("nonce too low"));
503 }
504 other => panic!("expected Rpc, got {other:?}"),
505 }
506 }
507
508 #[tokio::test]
509 async fn http_5xx_surfaces_as_http_variant() {
510 let server = MockServer::start().await;
511 Mock::given(method("POST"))
512 .and(path("/"))
513 .respond_with(ResponseTemplate::new(502).set_body_string("upstream"))
514 .mount(&server)
515 .await;
516 let rpc = TempoRpcClient::with_default_client(server.uri());
517 let err = rpc.chain_id().await.expect_err("must fail");
518 assert!(
519 matches!(err, RpcError::Http { status: 502, .. }),
520 "got {err:?}"
521 );
522 }
523
524 #[tokio::test]
525 async fn estimate_gas_parses_hex_u64() {
526 let server = MockServer::start().await;
527 Mock::given(method("POST"))
528 .and(path("/"))
529 .and(body_partial_json(json!({"method": "eth_estimateGas"})))
530 .respond_with(rpc_ok(json!("0x4b094"))) .mount(&server)
532 .await;
533 let rpc = TempoRpcClient::with_default_client(server.uri());
534 let from: Address = "0x0000000000000000000000000000000000000001"
535 .parse()
536 .unwrap();
537 let to: Address = "0x0000000000000000000000000000000000000002"
538 .parse()
539 .unwrap();
540 let gas = rpc
541 .estimate_gas(from, to, &Bytes::from_static(&[0xa9u8, 0x05, 0x9c, 0xbb]))
542 .await
543 .unwrap();
544 assert_eq!(gas, 307_348);
545 }
546
547 #[tokio::test]
548 async fn estimate_gas_rpc_error_propagates() {
549 let server = MockServer::start().await;
550 Mock::given(method("POST"))
551 .and(path("/"))
552 .and(body_partial_json(json!({"method": "eth_estimateGas"})))
553 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
554 "jsonrpc": "2.0",
555 "id": 1,
556 "error": { "code": 3, "message": "execution reverted: ERC20: insufficient balance" },
557 })))
558 .mount(&server)
559 .await;
560 let rpc = TempoRpcClient::with_default_client(server.uri());
561 let from: Address = "0x0000000000000000000000000000000000000001"
562 .parse()
563 .unwrap();
564 let to: Address = "0x0000000000000000000000000000000000000002"
565 .parse()
566 .unwrap();
567 let err = rpc
568 .estimate_gas(from, to, &Bytes::new())
569 .await
570 .expect_err("revert must propagate");
571 assert!(
572 matches!(err, RpcError::Rpc { code: 3, .. }),
573 "expected Rpc variant, got {err:?}"
574 );
575 }
576
577 #[tokio::test]
578 async fn sign_erc20_transfer_roundtrips_through_rpc() {
579 use alloy_eips::eip2718::Decodable2718;
580
581 let server = MockServer::start().await;
582 Mock::given(method("POST"))
583 .and(body_partial_json(json!({"method": "eth_chainId"})))
584 .respond_with(rpc_ok(json!("0xa5bf"))) .mount(&server)
586 .await;
587 Mock::given(method("POST"))
588 .and(body_partial_json(
589 json!({"method": "eth_getTransactionCount"}),
590 ))
591 .respond_with(rpc_ok(json!("0x0")))
592 .mount(&server)
593 .await;
594 Mock::given(method("POST"))
595 .and(body_partial_json(json!({"method": "eth_gasPrice"})))
596 .respond_with(rpc_ok(json!("0x3b9aca00")))
597 .mount(&server)
598 .await;
599 Mock::given(method("POST"))
600 .and(body_partial_json(json!({"method": "eth_estimateGas"})))
601 .respond_with(rpc_ok(json!("0x4b094"))) .mount(&server)
603 .await;
604 let signer = PrivateKeySigner::random();
605 let rpc = TempoRpcClient::with_default_client(server.uri());
606 let token: Address = "0x00000000000000000000000000000000000000aa"
607 .parse()
608 .unwrap();
609 let calldata = Bytes::from_iter(
611 [0xa9u8, 0x05, 0x9c, 0xbb]
612 .into_iter()
613 .chain(vec![0u8; 32 + 32]),
614 );
615 let raw = sign_erc20_transfer(&rpc, &signer, token, calldata)
616 .await
617 .expect("sign");
618 assert!(!raw.is_empty(), "raw tx must encode to non-empty bytes");
619 assert!(
621 raw[0] >= 0xc0,
622 "legacy tx must be an RLP list, got first byte {:#x}",
623 raw[0]
624 );
625
626 let envelope = TxEnvelope::decode_2718(&mut raw.as_slice()).expect("decode envelope");
629 let TxEnvelope::Legacy(signed) = envelope else {
630 panic!("expected legacy envelope");
631 };
632 assert_eq!(signed.tx().gas_limit, 399_552);
633 }
634}