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 async fn call<R>(&self, method: &str, params: Value) -> Result<R, RpcError>
253 where
254 R: for<'de> Deserialize<'de>,
255 {
256 let req = RpcRequest {
257 jsonrpc: "2.0",
258 id: 1,
259 method,
260 params,
261 };
262 let resp = self.http.post(&self.url).json(&req).send().await?;
263 let status = resp.status();
264 if !status.is_success() {
265 let body = resp.text().await.unwrap_or_default();
266 return Err(RpcError::Http {
267 status: status.as_u16(),
268 body,
269 });
270 }
271 let parsed: RpcResponse = resp.json().await?;
272 if let Some(err) = parsed.error {
273 let message = match err.data {
274 Some(d) => format!("{} (data: {})", err.message, d),
275 None => err.message,
276 };
277 return Err(RpcError::Rpc {
278 code: err.code,
279 message,
280 });
281 }
282 let result = parsed
283 .result
284 .ok_or_else(|| RpcError::Decode("rpc response missing both result and error".into()))?;
285 serde_json::from_value(result).map_err(|e| RpcError::Decode(e.to_string()))
286 }
287}
288
289pub async fn sign_and_broadcast_tx(
298 rpc: &TempoRpcClient,
299 signer: &PrivateKeySigner,
300 to: Address,
301 calldata: Bytes,
302) -> Result<TxHash, RpcError> {
303 let raw = sign_tx(rpc, signer, to, calldata).await?;
304 rpc.send_raw_transaction(&raw).await
305}
306
307pub async fn sign_tx(
310 rpc: &TempoRpcClient,
311 signer: &PrivateKeySigner,
312 to: Address,
313 calldata: Bytes,
314) -> Result<Vec<u8>, RpcError> {
315 let chain_id = rpc.chain_id().await?;
316 let nonce = rpc.pending_nonce(signer.address()).await?;
317 let gas_price = rpc.gas_price().await?;
318 let estimate = rpc.estimate_gas(signer.address(), to, &calldata).await?;
319 let gas_limit = estimate.saturating_mul(GAS_ESTIMATE_BUFFER_NUM) / GAS_ESTIMATE_BUFFER_DEN;
320
321 let tx = TxLegacy {
322 chain_id: Some(chain_id),
323 nonce,
324 gas_price,
325 gas_limit,
326 to: TxKind::Call(to),
327 value: U256::ZERO,
328 input: calldata,
329 };
330 let sig_hash = tx.signature_hash();
331 let sig = signer
332 .sign_hash_sync(&sig_hash)
333 .map_err(|e| RpcError::Sign(e.to_string()))?;
334 let signed = tx.into_signed(sig);
335 let envelope = TxEnvelope::Legacy(signed);
336 Ok(envelope.encoded_2718())
337}
338
339pub async fn sign_and_broadcast_erc20_transfer(
342 rpc: &TempoRpcClient,
343 signer: &PrivateKeySigner,
344 token_address: Address,
345 calldata: Bytes,
346) -> Result<TxHash, RpcError> {
347 sign_and_broadcast_tx(rpc, signer, token_address, calldata).await
348}
349
350pub async fn sign_erc20_transfer(
353 rpc: &TempoRpcClient,
354 signer: &PrivateKeySigner,
355 token_address: Address,
356 calldata: Bytes,
357) -> Result<Vec<u8>, RpcError> {
358 sign_tx(rpc, signer, token_address, calldata).await
359}
360
361fn parse_hex_u64(s: &str) -> Result<u64, RpcError> {
362 let stripped = s.strip_prefix("0x").unwrap_or(s);
363 u64::from_str_radix(stripped, 16).map_err(|e| RpcError::Hex(format!("u64 from {s}: {e}")))
364}
365
366fn parse_hex_u128(s: &str) -> Result<u128, RpcError> {
367 let stripped = s.strip_prefix("0x").unwrap_or(s);
368 u128::from_str_radix(stripped, 16).map_err(|e| RpcError::Hex(format!("u128 from {s}: {e}")))
369}
370
371fn decode_0x(s: &str) -> Result<Vec<u8>, RpcError> {
372 let stripped = s.strip_prefix("0x").unwrap_or(s);
373 hex::decode(stripped).map_err(|e| RpcError::Hex(e.to_string()))
374}
375
376#[cfg(test)]
377mod tests {
378 use super::*;
379 use wiremock::matchers::{body_partial_json, method, path};
380 use wiremock::{Mock, MockServer, ResponseTemplate};
381
382 fn rpc_ok(result: Value) -> ResponseTemplate {
383 ResponseTemplate::new(200).set_body_json(json!({
384 "jsonrpc": "2.0",
385 "id": 1,
386 "result": result,
387 }))
388 }
389
390 #[tokio::test]
391 async fn chain_id_decodes_hex() {
392 let server = MockServer::start().await;
393 Mock::given(method("POST"))
394 .and(path("/"))
395 .and(body_partial_json(json!({"method": "eth_chainId"})))
396 .respond_with(rpc_ok(json!("0xa5bf")))
397 .mount(&server)
398 .await;
399 let rpc = TempoRpcClient::with_default_client(server.uri());
400 assert_eq!(rpc.chain_id().await.unwrap(), 42_431);
401 }
402
403 #[tokio::test]
404 async fn nonce_sends_pending_tag() {
405 let server = MockServer::start().await;
406 Mock::given(method("POST"))
407 .and(path("/"))
408 .and(body_partial_json(json!({
409 "method": "eth_getTransactionCount",
410 "params": ["0x0000000000000000000000000000000000000001", "pending"],
411 })))
412 .respond_with(rpc_ok(json!("0x7")))
413 .mount(&server)
414 .await;
415 let rpc = TempoRpcClient::with_default_client(server.uri());
416 let addr: Address = "0x0000000000000000000000000000000000000001"
417 .parse()
418 .unwrap();
419 assert_eq!(rpc.pending_nonce(addr).await.unwrap(), 7);
420 }
421
422 #[tokio::test]
423 async fn gas_price_decodes_u128() {
424 let server = MockServer::start().await;
425 Mock::given(method("POST"))
426 .and(path("/"))
427 .and(body_partial_json(json!({"method": "eth_gasPrice"})))
428 .respond_with(rpc_ok(json!("0x3b9aca00"))) .mount(&server)
430 .await;
431 let rpc = TempoRpcClient::with_default_client(server.uri());
432 assert_eq!(rpc.gas_price().await.unwrap(), 1_000_000_000u128);
433 }
434
435 #[tokio::test]
436 async fn send_raw_transaction_returns_tx_hash() {
437 let server = MockServer::start().await;
438 let hash_hex = format!("0x{}", "aa".repeat(32));
439 Mock::given(method("POST"))
440 .and(path("/"))
441 .and(body_partial_json(
442 json!({"method": "eth_sendRawTransaction"}),
443 ))
444 .respond_with(rpc_ok(json!(hash_hex.clone())))
445 .mount(&server)
446 .await;
447 let rpc = TempoRpcClient::with_default_client(server.uri());
448 let h = rpc.send_raw_transaction(&[1u8, 2, 3]).await.unwrap();
449 assert_eq!(format!("{h:#x}"), hash_hex);
450 }
451
452 #[tokio::test]
453 async fn rpc_error_body_surfaces_as_rpc_variant() {
454 let server = MockServer::start().await;
455 Mock::given(method("POST"))
456 .and(path("/"))
457 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
458 "jsonrpc": "2.0",
459 "id": 1,
460 "error": { "code": -32000, "message": "nonce too low" },
461 })))
462 .mount(&server)
463 .await;
464 let rpc = TempoRpcClient::with_default_client(server.uri());
465 let err = rpc.gas_price().await.expect_err("must fail");
466 match err {
467 RpcError::Rpc { code, message } => {
468 assert_eq!(code, -32000);
469 assert!(message.contains("nonce too low"));
470 }
471 other => panic!("expected Rpc, got {other:?}"),
472 }
473 }
474
475 #[tokio::test]
476 async fn http_5xx_surfaces_as_http_variant() {
477 let server = MockServer::start().await;
478 Mock::given(method("POST"))
479 .and(path("/"))
480 .respond_with(ResponseTemplate::new(502).set_body_string("upstream"))
481 .mount(&server)
482 .await;
483 let rpc = TempoRpcClient::with_default_client(server.uri());
484 let err = rpc.chain_id().await.expect_err("must fail");
485 assert!(
486 matches!(err, RpcError::Http { status: 502, .. }),
487 "got {err:?}"
488 );
489 }
490
491 #[tokio::test]
492 async fn estimate_gas_parses_hex_u64() {
493 let server = MockServer::start().await;
494 Mock::given(method("POST"))
495 .and(path("/"))
496 .and(body_partial_json(json!({"method": "eth_estimateGas"})))
497 .respond_with(rpc_ok(json!("0x4b094"))) .mount(&server)
499 .await;
500 let rpc = TempoRpcClient::with_default_client(server.uri());
501 let from: Address = "0x0000000000000000000000000000000000000001"
502 .parse()
503 .unwrap();
504 let to: Address = "0x0000000000000000000000000000000000000002"
505 .parse()
506 .unwrap();
507 let gas = rpc
508 .estimate_gas(from, to, &Bytes::from_static(&[0xa9u8, 0x05, 0x9c, 0xbb]))
509 .await
510 .unwrap();
511 assert_eq!(gas, 307_348);
512 }
513
514 #[tokio::test]
515 async fn estimate_gas_rpc_error_propagates() {
516 let server = MockServer::start().await;
517 Mock::given(method("POST"))
518 .and(path("/"))
519 .and(body_partial_json(json!({"method": "eth_estimateGas"})))
520 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
521 "jsonrpc": "2.0",
522 "id": 1,
523 "error": { "code": 3, "message": "execution reverted: ERC20: insufficient balance" },
524 })))
525 .mount(&server)
526 .await;
527 let rpc = TempoRpcClient::with_default_client(server.uri());
528 let from: Address = "0x0000000000000000000000000000000000000001"
529 .parse()
530 .unwrap();
531 let to: Address = "0x0000000000000000000000000000000000000002"
532 .parse()
533 .unwrap();
534 let err = rpc
535 .estimate_gas(from, to, &Bytes::new())
536 .await
537 .expect_err("revert must propagate");
538 assert!(
539 matches!(err, RpcError::Rpc { code: 3, .. }),
540 "expected Rpc variant, got {err:?}"
541 );
542 }
543
544 #[tokio::test]
545 async fn sign_erc20_transfer_roundtrips_through_rpc() {
546 use alloy_eips::eip2718::Decodable2718;
547
548 let server = MockServer::start().await;
549 Mock::given(method("POST"))
550 .and(body_partial_json(json!({"method": "eth_chainId"})))
551 .respond_with(rpc_ok(json!("0xa5bf"))) .mount(&server)
553 .await;
554 Mock::given(method("POST"))
555 .and(body_partial_json(
556 json!({"method": "eth_getTransactionCount"}),
557 ))
558 .respond_with(rpc_ok(json!("0x0")))
559 .mount(&server)
560 .await;
561 Mock::given(method("POST"))
562 .and(body_partial_json(json!({"method": "eth_gasPrice"})))
563 .respond_with(rpc_ok(json!("0x3b9aca00")))
564 .mount(&server)
565 .await;
566 Mock::given(method("POST"))
567 .and(body_partial_json(json!({"method": "eth_estimateGas"})))
568 .respond_with(rpc_ok(json!("0x4b094"))) .mount(&server)
570 .await;
571 let signer = PrivateKeySigner::random();
572 let rpc = TempoRpcClient::with_default_client(server.uri());
573 let token: Address = "0x00000000000000000000000000000000000000aa"
574 .parse()
575 .unwrap();
576 let calldata = Bytes::from_iter(
578 [0xa9u8, 0x05, 0x9c, 0xbb]
579 .into_iter()
580 .chain(vec![0u8; 32 + 32]),
581 );
582 let raw = sign_erc20_transfer(&rpc, &signer, token, calldata)
583 .await
584 .expect("sign");
585 assert!(!raw.is_empty(), "raw tx must encode to non-empty bytes");
586 assert!(
588 raw[0] >= 0xc0,
589 "legacy tx must be an RLP list, got first byte {:#x}",
590 raw[0]
591 );
592
593 let envelope = TxEnvelope::decode_2718(&mut raw.as_slice()).expect("decode envelope");
596 let TxEnvelope::Legacy(signed) = envelope else {
597 panic!("expected legacy envelope");
598 };
599 assert_eq!(signed.tx().gas_limit, 399_552);
600 }
601}