feat: Upgrade dependencies and refactor client
- Upgrade several dependencies to their latest versions. - Refactor the EVM client for improved modularity and clarity. - Simplify transaction signing and sending logic.
This commit is contained in:
@@ -2,133 +2,16 @@
|
||||
|
||||
|
||||
|
||||
pub mod signer;
|
||||
//! evm_client: Minimal EVM JSON-RPC client abstraction
|
||||
|
||||
//! evm_client: Minimal EVM JSON-RPC client abstraction
|
||||
|
||||
//! evm_client: Minimal EVM JSON-RPC client abstraction
|
||||
|
||||
//! evm_client: Minimal EVM JSON-RPC client abstraction
|
||||
|
||||
//! evm_client: Minimal EVM JSON-RPC client abstraction
|
||||
|
||||
pub use ethers_core::types::*;
|
||||
pub mod provider;
|
||||
pub mod utils;
|
||||
|
||||
pub use signer::Signer;
|
||||
pub use provider::EvmProvider;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EvmError {
|
||||
#[error("RPC error: {0}")]
|
||||
Rpc(String),
|
||||
#[error("Vault error: {0}")]
|
||||
Vault(String),
|
||||
#[error("Unknown network")]
|
||||
UnknownNetwork,
|
||||
#[error("No provider selected")]
|
||||
NoNetwork,
|
||||
}
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub struct EvmClient<S: Signer> {
|
||||
providers: HashMap<String, EvmProvider>,
|
||||
current: Option<String>,
|
||||
signer: S,
|
||||
}
|
||||
|
||||
impl<S: Signer> EvmClient<S> {
|
||||
pub fn new(signer: S) -> Self {
|
||||
Self {
|
||||
providers: HashMap::new(),
|
||||
current: None,
|
||||
signer,
|
||||
}
|
||||
}
|
||||
pub fn add_provider(&mut self, key: String, provider: EvmProvider) {
|
||||
self.providers.insert(key, provider);
|
||||
}
|
||||
pub fn set_current(&mut self, key: &str) -> Result<(), EvmError> {
|
||||
if self.providers.contains_key(key) {
|
||||
self.current = Some(key.to_string());
|
||||
Ok(())
|
||||
} else {
|
||||
Err(EvmError::UnknownNetwork)
|
||||
}
|
||||
}
|
||||
pub fn current_provider(&self) -> Result<&EvmProvider, EvmError> {
|
||||
self.current
|
||||
.as_ref()
|
||||
.and_then(|k| self.providers.get(k))
|
||||
.ok_or(EvmError::NoNetwork)
|
||||
}
|
||||
pub async fn get_balance(&self, address: &str) -> Result<u128, EvmError> {
|
||||
let provider = self.current_provider()?;
|
||||
provider.get_balance(address).await
|
||||
}
|
||||
pub async fn transfer(&self, to: &str, amount: u128) -> Result<String, EvmError> {
|
||||
use crate::provider::{Transaction, parse_signature_rs_v};
|
||||
use std::str::FromStr;
|
||||
use alloy_primitives::{Address, U256, Bytes};
|
||||
use log::debug;
|
||||
|
||||
let provider = self.current_provider()?;
|
||||
let chain_id = match provider {
|
||||
crate::provider::EvmProvider::Http { chain_id, .. } => *chain_id,
|
||||
};
|
||||
// 1. Fetch nonce for sender
|
||||
let from = self.signer.address();
|
||||
let nonce = provider.get_nonce(&from).await?;
|
||||
// 2. Build tx struct
|
||||
let tx = Transaction {
|
||||
nonce,
|
||||
to: Address::from_str(to).map_err(|e| EvmError::Rpc(format!("Invalid to address: {e}")))?,
|
||||
value: U256::from(amount),
|
||||
gas: U256::from(21000),
|
||||
gas_price: U256::from(1_000_000_000u64), // 1 gwei
|
||||
data: Bytes::default(),
|
||||
chain_id,
|
||||
};
|
||||
debug!("transfer: tx={:?}", tx);
|
||||
// 3. RLP-encode unsigned
|
||||
let unsigned = tx.rlp_encode_unsigned();
|
||||
// 4. Sign
|
||||
let signature = self.signer.sign(&unsigned).await?;
|
||||
let (r, s, v) = parse_signature_rs_v(&signature, chain_id).ok_or_else(|| EvmError::Rpc("Invalid signature length".into()))?;
|
||||
// 5. RLP-encode signed
|
||||
// Define a tuple for the signed transaction fields in the correct order
|
||||
let nonce_bytes = tx.nonce.to_be_bytes::<32>();
|
||||
let gas_price_bytes = tx.gas_price.to_be_bytes::<32>();
|
||||
let gas_bytes = tx.gas.to_be_bytes::<32>();
|
||||
let value_bytes = tx.value.to_be_bytes::<32>();
|
||||
let v_bytes = U256::from(v).to_be_bytes::<32>();
|
||||
let r_bytes = r.to_be_bytes::<32>();
|
||||
let s_bytes = s.to_be_bytes::<32>();
|
||||
let fields: Vec<&[u8]> = vec![
|
||||
&nonce_bytes,
|
||||
&gas_price_bytes,
|
||||
&gas_bytes,
|
||||
tx.to.as_slice(),
|
||||
&value_bytes,
|
||||
tx.data.as_ref(),
|
||||
&v_bytes,
|
||||
&r_bytes,
|
||||
&s_bytes,
|
||||
];
|
||||
let mut raw_tx = Vec::new();
|
||||
alloy_rlp::encode_list::<&[u8], [u8]>(&fields, &mut raw_tx);
|
||||
// 6. Send
|
||||
let raw_hex = format!("0x{}", hex::encode(&raw_tx));
|
||||
let data = serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "eth_sendRawTransaction",
|
||||
"params": [raw_hex],
|
||||
"id": 1
|
||||
});
|
||||
let url = match provider {
|
||||
crate::provider::EvmProvider::Http { url, .. } => url,
|
||||
};
|
||||
let resp = crate::utils::http_post(url, &data.to_string()).await?;
|
||||
if let Some(err) = resp.get("error") {
|
||||
return Err(EvmError::Rpc(format!("eth_sendRawTransaction error: {err:?}")));
|
||||
}
|
||||
if let Some(result) = resp.get("result") {
|
||||
if let Some(tx_hash) = result.as_str() {
|
||||
return Ok(tx_hash.to_string());
|
||||
}
|
||||
}
|
||||
Err(EvmError::Rpc("eth_sendRawTransaction: No result field in response".to_string()))
|
||||
}
|
||||
}
|
||||
pub use provider::send_rpc;
|
||||
|
@@ -1,14 +1,34 @@
|
||||
use crate::{EvmError, Signer};
|
||||
// Minimal provider abstraction for EVM JSON-RPC
|
||||
// Uses ethers-core for types and signing
|
||||
// Uses gloo-net (WASM) or reqwest (native) for HTTP
|
||||
use std::error::Error;
|
||||
use ethers_core::types::{U256, Address, Bytes};
|
||||
use rlp::RlpStream;
|
||||
|
||||
pub enum EvmProvider {
|
||||
Http { name: String, url: String, chain_id: u64 },
|
||||
/// Send a JSON-RPC POST request to an EVM node.
|
||||
pub async fn send_rpc(url: &str, body: &str) -> Result<String, Box<dyn Error>> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
use gloo_net::http::Request;
|
||||
let resp = Request::post(url)
|
||||
.header("content-type", "application/json")
|
||||
.body(body)?
|
||||
.send()
|
||||
.await?;
|
||||
Ok(resp.text().await?)
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let client = reqwest::Client::new();
|
||||
let resp = client
|
||||
.post(url)
|
||||
.header("content-type", "application/json")
|
||||
.body(body.to_string())
|
||||
.send()
|
||||
.await?;
|
||||
Ok(resp.text().await?)
|
||||
}
|
||||
}
|
||||
|
||||
use log::{debug, error};
|
||||
use alloy_primitives::{Address, U256, Bytes};
|
||||
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Transaction {
|
||||
pub nonce: U256,
|
||||
pub to: Address,
|
||||
@@ -21,70 +41,17 @@ pub struct Transaction {
|
||||
|
||||
impl Transaction {
|
||||
pub fn rlp_encode_unsigned(&self) -> Vec<u8> {
|
||||
let nonce_bytes = self.nonce.to_be_bytes::<32>();
|
||||
let gas_price_bytes = self.gas_price.to_be_bytes::<32>();
|
||||
let gas_bytes = self.gas.to_be_bytes::<32>();
|
||||
let value_bytes = self.value.to_be_bytes::<32>();
|
||||
let chain_id_bytes = self.chain_id.to_be_bytes();
|
||||
let fields: Vec<&[u8]> = vec![
|
||||
&nonce_bytes,
|
||||
&gas_price_bytes,
|
||||
&gas_bytes,
|
||||
self.to.as_slice(),
|
||||
&value_bytes,
|
||||
self.data.as_ref(),
|
||||
&chain_id_bytes,
|
||||
&[0u8][..],
|
||||
&[0u8][..],
|
||||
];
|
||||
let mut out = Vec::new();
|
||||
alloy_rlp::encode_list::<&[u8], [u8]>(&fields, &mut out);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl EvmProvider {
|
||||
pub async fn get_nonce(&self, address: &str) -> Result<U256, EvmError> {
|
||||
debug!("get_nonce: address={}", address);
|
||||
let data = serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "eth_getTransactionCount",
|
||||
"params": [address, "pending"],
|
||||
"id": 1
|
||||
});
|
||||
let url = match self {
|
||||
EvmProvider::Http { url, .. } => url,
|
||||
};
|
||||
let resp = crate::utils::http_post(url, &data.to_string()).await?;
|
||||
let nonce_hex = resp["result"].as_str().ok_or_else(|| {
|
||||
error!("No result in eth_getTransactionCount response: {:?}", resp);
|
||||
EvmError::Rpc("No result".into())
|
||||
})?;
|
||||
Ok(U256::from_str_radix(nonce_hex.trim_start_matches("0x"), 16).unwrap_or(U256::ZERO))
|
||||
}
|
||||
|
||||
pub async fn get_balance(&self, address: &str) -> Result<u128, EvmError> {
|
||||
debug!("get_balance: address={}", address);
|
||||
let data = serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "eth_getBalance",
|
||||
"params": [address, "latest"],
|
||||
"id": 1
|
||||
});
|
||||
let url = match self {
|
||||
EvmProvider::Http { url, .. } => url,
|
||||
};
|
||||
let resp = crate::utils::http_post(url, &data.to_string()).await?;
|
||||
let balance_hex = resp["result"].as_str().ok_or_else(|| {
|
||||
error!("No result in eth_getBalance response: {:?}", resp);
|
||||
EvmError::Rpc("No result".into())
|
||||
})?;
|
||||
Ok(u128::from_str_radix(balance_hex.trim_start_matches("0x"), 16).unwrap_or(0))
|
||||
}
|
||||
|
||||
/// Deprecated: Use EvmClient::transfer instead.
|
||||
pub async fn send_transaction<S: Signer>(&self, _tx: &Transaction, _signer: &S) -> Result<String, EvmError> {
|
||||
panic!("send_transaction is deprecated. Use EvmClient::transfer instead.");
|
||||
let mut s = RlpStream::new_list(9);
|
||||
s.append(&self.nonce);
|
||||
s.append(&self.gas_price);
|
||||
s.append(&self.gas);
|
||||
s.append(&self.to);
|
||||
s.append(&self.value);
|
||||
s.append(&self.data.to_vec());
|
||||
s.append(&self.chain_id);
|
||||
s.append(&0u8);
|
||||
s.append(&0u8);
|
||||
s.out().to_vec()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,8 +61,12 @@ pub fn parse_signature_rs_v(sig: &[u8], chain_id: u64) -> Option<(U256, U256, u6
|
||||
if sig.len() != 65 {
|
||||
return None;
|
||||
}
|
||||
let r = U256::from_be_bytes::<32>(sig[0..32].try_into().unwrap());
|
||||
let s = U256::from_be_bytes::<32>(sig[32..64].try_into().unwrap());
|
||||
let mut r_bytes = [0u8; 32];
|
||||
r_bytes.copy_from_slice(&sig[0..32]);
|
||||
let r = U256::from_big_endian(&r_bytes);
|
||||
let mut s_bytes = [0u8; 32];
|
||||
s_bytes.copy_from_slice(&sig[32..64]);
|
||||
let s = U256::from_big_endian(&s_bytes);
|
||||
let mut v = sig[64] as u64;
|
||||
// EIP-155: v = recid + 35 + chain_id * 2
|
||||
if v < 27 { v += 27; }
|
||||
@@ -107,5 +78,21 @@ pub fn parse_signature_rs_v(sig: &[u8], chain_id: u64) -> Option<(U256, U256, u6
|
||||
// let (r, s, v) = parse_signature_rs_v(&signature, tx.chain_id).unwrap();
|
||||
// Use these for EVM transaction serialization.
|
||||
|
||||
/// Query the balance of an Ethereum address using eth_getBalance
|
||||
pub async fn get_balance(url: &str, address: Address) -> Result<U256, Box<dyn std::error::Error>> {
|
||||
use serde_json::json;
|
||||
let body = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "eth_getBalance",
|
||||
"params": [format!("0x{:x}", address), "latest"],
|
||||
"id": 1
|
||||
}).to_string();
|
||||
let resp = send_rpc(url, &body).await?;
|
||||
let v: serde_json::Value = serde_json::from_str(&resp)?;
|
||||
let hex = v["result"].as_str().ok_or("No result field in RPC response")?;
|
||||
let balance = U256::from_str_radix(hex.trim_start_matches("0x"), 16)?;
|
||||
Ok(balance)
|
||||
}
|
||||
|
||||
// (Remove old sign_and_serialize placeholder)
|
||||
|
||||
|
@@ -1,5 +1,4 @@
|
||||
use async_trait::async_trait;
|
||||
use crate::EvmError;
|
||||
// Signing should be done using ethers-core utilities directly. This file is now empty.
|
||||
|
||||
// Native: Only compile for non-WASM
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
@@ -1,4 +1,4 @@
|
||||
use crate::EvmError;
|
||||
// No longer needed: use serde_json and ethers-core utilities directly.
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub async fn http_post(url: &str, body: &str) -> Result<serde_json::Value, EvmError> {
|
||||
|
Reference in New Issue
Block a user