use std::sync::Arc;
use async_trait::async_trait;
use serde_json::{json, Value};
use crate::error::SdkError;
use crate::types::{
AccountInfo, Address, CallRequest, Event, EventFilter, FeeData, LogFilter, LogPage, NodeInfo,
Receipt, RecentWaveSummary, SimulationResult, Tx, TxHash,
};
use super::pending::PendingTx;
use super::transport::Transport;
#[async_trait]
pub trait Provider: Send + Sync {
async fn chain_id(&self) -> Result<u64, SdkError>;
async fn wave_id(&self) -> Result<u64, SdkError>;
async fn get_node_info(&self) -> Result<NodeInfo, SdkError>;
async fn get_metrics(&self) -> Result<Value, SdkError>;
async fn get_balance(&self, addr: &Address) -> Result<u128, SdkError>;
async fn get_nonce(&self, addr: &Address) -> Result<u64, SdkError>;
async fn get_account(&self, addr: &Address) -> Result<AccountInfo, SdkError>;
async fn get_contract_code(&self, addr: &Address) -> Result<Vec<u8>, SdkError>;
async fn get_storage_slot(&self, slot: &[u8; 32]) -> Result<Option<Vec<u8>>, SdkError>;
async fn resolve_name(&self, name: &str) -> Result<Option<Address>, SdkError>;
async fn send_raw_transaction(&self, tx: &Tx) -> Result<TxHash, SdkError>;
async fn call(&self, req: &CallRequest) -> Result<Vec<u8>, SdkError>;
async fn simulate_transaction(&self, tx: &Tx) -> Result<SimulationResult, SdkError>;
async fn get_transaction_receipt(&self, hash: &TxHash) -> Result<Option<Receipt>, SdkError>;
async fn get_receipt(&self, hash: &TxHash) -> Result<Option<Receipt>, SdkError>;
async fn get_tx(&self, hash: &TxHash) -> Result<Option<Tx>, SdkError>;
async fn get_wave(&self, wave_id: u64) -> Result<Option<Value>, SdkError>;
async fn get_wave_head(&self) -> Result<Option<Value>, SdkError>;
async fn get_fee_data(&self) -> Result<FeeData, SdkError>;
async fn get_hard_finality_cert(&self, wave_id: u64) -> Result<Option<Value>, SdkError>;
async fn get_events(&self, filter: &EventFilter) -> Result<Vec<Event>, SdkError>;
async fn get_logs(&self, filter: &LogFilter) -> Result<LogPage, SdkError>;
async fn get_validator(&self, addr: &Address) -> Result<Option<Value>, SdkError>;
async fn get_operator_validators(&self, operator: &Address) -> Result<Vec<Value>, SdkError>;
async fn get_snapshot(&self) -> Result<Value, SdkError>;
async fn get_snapshot_manifest(&self) -> Result<Value, SdkError>;
}
#[derive(Clone)]
pub struct RootProvider<T: Transport> {
transport: Arc<T>,
}
impl<T: Transport> RootProvider<T> {
#[must_use]
pub fn new(transport: T) -> Self {
Self {
transport: Arc::new(transport),
}
}
#[must_use]
pub fn transport(&self) -> &T {
&self.transport
}
}
impl<T: Transport + 'static> RootProvider<T> {
pub async fn send_transaction(self: &Arc<Self>, tx: &Tx) -> Result<PendingTx, SdkError> {
let hash = self.send_raw_transaction(tx).await?;
let provider: Arc<dyn Provider> = self.clone();
Ok(PendingTx::new(hash, provider))
}
}
impl<T: Transport> std::fmt::Debug for RootProvider<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RootProvider").finish_non_exhaustive()
}
}
#[async_trait]
impl<T: Transport + 'static> Provider for RootProvider<T> {
async fn chain_id(&self) -> Result<u64, SdkError> {
let v = self.transport.send("pyde_chainId", json!([])).await?;
decode_hex_u64(&v, "chain_id")
}
async fn wave_id(&self) -> Result<u64, SdkError> {
let v = self.transport.send("pyde_waveId", json!([])).await?;
decode_hex_u64(&v, "wave_id")
}
async fn get_node_info(&self) -> Result<NodeInfo, SdkError> {
let v = self.transport.send("pyde_getNodeInfo", json!([])).await?;
serde_json::from_value(v)
.map_err(|e| SdkError::InvalidResponse(format!("get_node_info: {e}")))
}
async fn get_metrics(&self) -> Result<Value, SdkError> {
self.transport.send("pyde_getMetrics", json!([])).await
}
async fn get_balance(&self, addr: &Address) -> Result<u128, SdkError> {
let v = self
.transport
.send("pyde_getBalance", json!([addr.to_hex()]))
.await?;
decode_hex_u128(&v, "balance")
}
async fn get_nonce(&self, addr: &Address) -> Result<u64, SdkError> {
let v = self
.transport
.send("pyde_getNonce", json!([addr.to_hex()]))
.await?;
decode_hex_u64(&v, "nonce")
}
async fn get_account(&self, addr: &Address) -> Result<AccountInfo, SdkError> {
let v = self
.transport
.send("pyde_getAccount", json!([addr.to_hex()]))
.await?;
serde_json::from_value(v)
.map_err(|e| SdkError::InvalidResponse(format!("get_account: {e}")))
}
async fn get_contract_code(&self, addr: &Address) -> Result<Vec<u8>, SdkError> {
let v = self
.transport
.send("pyde_getContractCode", json!([addr.to_hex()]))
.await?;
decode_hex_bytes(&v, "contract_code")
}
async fn get_storage_slot(&self, slot: &[u8; 32]) -> Result<Option<Vec<u8>>, SdkError> {
let slot_hex = format!("0x{}", hex::encode(slot));
let v = self
.transport
.send("pyde_getStorageSlot", json!([{"slot": slot_hex}]))
.await?;
if v.is_null() {
return Ok(None);
}
decode_hex_bytes(&v, "storage_slot").map(Some)
}
async fn resolve_name(&self, name: &str) -> Result<Option<Address>, SdkError> {
let v = self
.transport
.send("pyde_resolveName", json!([name]))
.await?;
if v.is_null() {
return Ok(None);
}
let s = v.as_str().ok_or_else(|| {
SdkError::InvalidResponse(format!("resolve_name: expected string, got {v}"))
})?;
Address::from_hex(s).map(Some)
}
async fn send_raw_transaction(&self, tx: &Tx) -> Result<TxHash, SdkError> {
let bytes = crate::tx::encode(tx)?;
let payload = format!("0x{}", hex::encode(&bytes));
let v = self
.transport
.send("pyde_sendRawTransaction", json!([payload]))
.await?;
decode_tx_hash_from_value(&v, "send_raw_transaction")
}
async fn call(&self, req: &CallRequest) -> Result<Vec<u8>, SdkError> {
let v = self.transport.send("pyde_call", json!([req])).await?;
decode_hex_bytes(&v, "call")
}
async fn simulate_transaction(&self, tx: &Tx) -> Result<SimulationResult, SdkError> {
let bytes = crate::tx::encode(tx)?;
let payload = format!("0x{}", hex::encode(&bytes));
let v = self
.transport
.send("pyde_simulateTransaction", json!([payload]))
.await?;
serde_json::from_value(v)
.map_err(|e| SdkError::InvalidResponse(format!("simulate_transaction: {e}")))
}
async fn get_transaction_receipt(&self, hash: &TxHash) -> Result<Option<Receipt>, SdkError> {
let hash_hex = format!("0x{}", hex::encode(hash.as_bytes()));
let v = self
.transport
.send("pyde_getTransactionReceipt", json!([hash_hex]))
.await?;
if v.is_null() {
return Ok(None);
}
serde_json::from_value(v)
.map(Some)
.map_err(|e| SdkError::InvalidResponse(format!("get_transaction_receipt: {e}")))
}
async fn get_receipt(&self, hash: &TxHash) -> Result<Option<Receipt>, SdkError> {
let hash_hex = format!("0x{}", hex::encode(hash.as_bytes()));
let v = self
.transport
.send("pyde_getReceipt", json!([hash_hex]))
.await?;
if v.is_null() {
return Ok(None);
}
serde_json::from_value(v)
.map(Some)
.map_err(|e| SdkError::InvalidResponse(format!("get_receipt: {e}")))
}
async fn get_tx(&self, hash: &TxHash) -> Result<Option<Tx>, SdkError> {
let hash_hex = format!("0x{}", hex::encode(hash.as_bytes()));
let v = self.transport.send("pyde_getTx", json!([hash_hex])).await?;
if v.is_null() {
return Ok(None);
}
serde_json::from_value(v)
.map(Some)
.map_err(|e| SdkError::InvalidResponse(format!("get_tx: {e}")))
}
async fn get_wave(&self, wave_id: u64) -> Result<Option<Value>, SdkError> {
let v = self
.transport
.send("pyde_getWave", json!([wave_id]))
.await?;
if v.is_null() {
return Ok(None);
}
Ok(Some(v))
}
async fn get_wave_head(&self) -> Result<Option<Value>, SdkError> {
let v = self.transport.send("pyde_getWave", json!([])).await?;
if v.is_null() {
return Ok(None);
}
Ok(Some(v))
}
async fn get_fee_data(&self) -> Result<FeeData, SdkError> {
let v = self.transport.send("pyde_getFeeData", json!([])).await?;
let obj = v.as_object().ok_or_else(|| {
SdkError::InvalidResponse(format!("get_fee_data: expected object, got {v}"))
})?;
let base_fee = decode_hex_u128(
obj.get("base_fee").ok_or_else(|| {
SdkError::InvalidResponse("get_fee_data: missing base_fee".into())
})?,
"base_fee",
)?;
let suggested_tip = decode_hex_u128(
obj.get("suggested_tip").ok_or_else(|| {
SdkError::InvalidResponse("get_fee_data: missing suggested_tip".into())
})?,
"suggested_tip",
)?;
let wave_id = decode_hex_u64(
obj.get("wave_id")
.ok_or_else(|| SdkError::InvalidResponse("get_fee_data: missing wave_id".into()))?,
"wave_id",
)?;
let recent_arr = obj
.get("recent_waves")
.and_then(|v| v.as_array())
.ok_or_else(|| {
SdkError::InvalidResponse("get_fee_data: missing recent_waves array".into())
})?;
let mut recent_waves = Vec::with_capacity(recent_arr.len());
for (i, entry) in recent_arr.iter().enumerate() {
let e = entry.as_object().ok_or_else(|| {
SdkError::InvalidResponse(format!("recent_waves[{i}]: not an object"))
})?;
let wave_id = decode_hex_u64(
e.get("wave_id").ok_or_else(|| {
SdkError::InvalidResponse(format!("recent_waves[{i}].wave_id missing"))
})?,
"recent_waves.wave_id",
)?;
let gas_used = decode_hex_u64(
e.get("gas_used").ok_or_else(|| {
SdkError::InvalidResponse(format!("recent_waves[{i}].gas_used missing"))
})?,
"recent_waves.gas_used",
)?;
let gas_limit = decode_hex_u64(
e.get("gas_limit").ok_or_else(|| {
SdkError::InvalidResponse(format!("recent_waves[{i}].gas_limit missing"))
})?,
"recent_waves.gas_limit",
)?;
let utilisation = e
.get("utilisation")
.and_then(|v| v.as_str())
.ok_or_else(|| {
SdkError::InvalidResponse(format!(
"recent_waves[{i}].utilisation missing or not a string"
))
})?
.parse::<f64>()
.map_err(|err| {
SdkError::InvalidResponse(format!("recent_waves[{i}].utilisation: {err}"))
})?;
recent_waves.push(RecentWaveSummary {
wave_id,
gas_used,
gas_limit,
utilisation,
});
}
Ok(FeeData {
base_fee,
suggested_tip,
wave_id,
recent_waves,
})
}
async fn get_hard_finality_cert(&self, wave_id: u64) -> Result<Option<Value>, SdkError> {
let v = self
.transport
.send("pyde_getHardFinalityCert", json!([wave_id]))
.await?;
if v.is_null() {
return Ok(None);
}
Ok(Some(v))
}
async fn get_events(&self, filter: &EventFilter) -> Result<Vec<Event>, SdkError> {
let v = self
.transport
.send("pyde_getEvents", json!([filter]))
.await?;
serde_json::from_value(v).map_err(|e| SdkError::InvalidResponse(format!("get_events: {e}")))
}
async fn get_logs(&self, filter: &LogFilter) -> Result<LogPage, SdkError> {
let v = self.transport.send("pyde_getLogs", json!([filter])).await?;
serde_json::from_value(v).map_err(|e| SdkError::InvalidResponse(format!("get_logs: {e}")))
}
async fn get_validator(&self, addr: &Address) -> Result<Option<Value>, SdkError> {
let v = self
.transport
.send("pyde_getValidator", json!([addr.to_hex()]))
.await?;
if v.is_null() {
return Ok(None);
}
Ok(Some(v))
}
async fn get_operator_validators(&self, operator: &Address) -> Result<Vec<Value>, SdkError> {
let v = self
.transport
.send("pyde_getOperatorValidators", json!([operator.to_hex()]))
.await?;
if v.is_null() {
return Ok(Vec::new());
}
serde_json::from_value(v)
.map_err(|e| SdkError::InvalidResponse(format!("get_operator_validators: {e}")))
}
async fn get_snapshot(&self) -> Result<Value, SdkError> {
self.transport.send("pyde_getSnapshot", json!([])).await
}
async fn get_snapshot_manifest(&self) -> Result<Value, SdkError> {
self.transport
.send("pyde_getSnapshotManifest", json!([]))
.await
}
}
fn decode_hex_u64(v: &Value, ctx: &str) -> Result<u64, SdkError> {
let s = v
.as_str()
.ok_or_else(|| SdkError::InvalidResponse(format!("{ctx}: expected hex string, got {v}")))?;
let stripped = s.trim_start_matches("0x");
u64::from_str_radix(stripped, 16)
.map_err(|e| SdkError::InvalidResponse(format!("{ctx}: bad hex u64 {s:?}: {e}")))
}
fn decode_hex_u128(v: &Value, ctx: &str) -> Result<u128, SdkError> {
let s = v
.as_str()
.ok_or_else(|| SdkError::InvalidResponse(format!("{ctx}: expected hex string, got {v}")))?;
let stripped = s.trim_start_matches("0x");
u128::from_str_radix(stripped, 16)
.map_err(|e| SdkError::InvalidResponse(format!("{ctx}: bad hex u128 {s:?}: {e}")))
}
fn decode_hex_bytes(v: &Value, ctx: &str) -> Result<Vec<u8>, SdkError> {
let s = v
.as_str()
.ok_or_else(|| SdkError::InvalidResponse(format!("{ctx}: expected hex string, got {v}")))?;
let stripped = s.trim_start_matches("0x");
hex::decode(stripped)
.map_err(|e| SdkError::InvalidResponse(format!("{ctx}: bad hex bytes: {e}")))
}
fn decode_tx_hash_from_value(v: &Value, ctx: &str) -> Result<TxHash, SdkError> {
let s = v
.as_str()
.ok_or_else(|| SdkError::InvalidResponse(format!("{ctx}: expected hex string, got {v}")))?;
let bytes = hex::decode(s.trim_start_matches("0x"))
.map_err(|e| SdkError::InvalidResponse(format!("{ctx}: tx_hash hex: {e}")))?;
if bytes.len() != 32 {
return Err(SdkError::InvalidResponse(format!(
"{ctx}: tx_hash expected 32 bytes, got {}",
bytes.len()
)));
}
let mut arr = [0u8; 32];
arr.copy_from_slice(&bytes);
Ok(TxHash::new(arr))
}