use serde::{Deserialize, Serialize};
use super::Address;
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReceiptStatus {
Success,
Reverted,
OutOfGas,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RevertCategory {
EngineValidation,
Contract,
Vm,
#[serde(untagged)]
Other(String),
}
impl RevertCategory {
#[must_use]
pub fn is_known(&self) -> bool {
!matches!(self, Self::Other(_))
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct RevertReason {
pub category: RevertCategory,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Receipt {
pub tx_hash: String,
pub wave_id: String,
pub tx_index: String,
#[serde(default)]
pub nonce: String,
#[serde(default)]
pub commit_reveal: bool,
pub status: ReceiptStatus,
pub gas_used: String,
pub fee_paid: String,
#[serde(default)]
pub return_data: String,
#[serde(default)]
pub events: Vec<Event>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revert_reason: Option<RevertReason>,
}
fn strict_u64_from_hex(s: &str, field: &str) -> Result<u64, crate::SdkError> {
u64::from_str_radix(s.trim_start_matches("0x"), 16)
.map_err(|e| crate::SdkError::InvalidResponse(format!("{field}: {e}")))
}
fn strict_u128_from_hex(s: &str, field: &str) -> Result<u128, crate::SdkError> {
u128::from_str_radix(s.trim_start_matches("0x"), 16)
.map_err(|e| crate::SdkError::InvalidResponse(format!("{field}: {e}")))
}
fn strict_u32_from_hex(s: &str, field: &str) -> Result<u32, crate::SdkError> {
u32::from_str_radix(s.trim_start_matches("0x"), 16)
.map_err(|e| crate::SdkError::InvalidResponse(format!("{field}: {e}")))
}
fn strict_bytes_from_hex(s: &str, field: &str) -> Result<Vec<u8>, crate::SdkError> {
hex::decode(s.trim_start_matches("0x"))
.map_err(|e| crate::SdkError::InvalidResponse(format!("{field}: {e}")))
}
impl Receipt {
#[must_use]
pub fn is_success(&self) -> bool {
matches!(self.status, ReceiptStatus::Success)
}
#[must_use]
pub fn is_engine_validation_revert(&self) -> bool {
matches!(
&self.revert_reason,
Some(r) if matches!(r.category, RevertCategory::EngineValidation)
)
}
#[must_use]
pub fn is_contract_revert(&self) -> bool {
matches!(
&self.revert_reason,
Some(r) if matches!(r.category, RevertCategory::Contract)
)
}
#[must_use]
pub fn is_vm_trap(&self) -> bool {
matches!(
&self.revert_reason,
Some(r) if matches!(r.category, RevertCategory::Vm)
)
}
#[must_use]
pub fn gas(&self) -> u64 {
self.try_gas().unwrap_or(0)
}
pub fn try_gas(&self) -> Result<u64, crate::SdkError> {
strict_u64_from_hex(&self.gas_used, "gas_used")
}
#[must_use]
pub fn fee_paid_quanta(&self) -> u128 {
self.try_fee_paid_quanta().unwrap_or(0)
}
pub fn try_fee_paid_quanta(&self) -> Result<u128, crate::SdkError> {
strict_u128_from_hex(&self.fee_paid, "fee_paid")
}
#[must_use]
pub fn wave_id_u64(&self) -> u64 {
self.try_wave_id_u64().unwrap_or(0)
}
pub fn try_wave_id_u64(&self) -> Result<u64, crate::SdkError> {
strict_u64_from_hex(&self.wave_id, "wave_id")
}
#[must_use]
pub fn nonce_u64(&self) -> u64 {
self.try_nonce_u64().unwrap_or(0)
}
pub fn try_nonce_u64(&self) -> Result<u64, crate::SdkError> {
strict_u64_from_hex(&self.nonce, "nonce")
}
#[must_use]
pub fn tx_index_u32(&self) -> u32 {
self.try_tx_index_u32().unwrap_or(0)
}
pub fn try_tx_index_u32(&self) -> Result<u32, crate::SdkError> {
strict_u32_from_hex(&self.tx_index, "tx_index")
}
#[must_use]
pub fn return_bytes(&self) -> Vec<u8> {
self.try_return_bytes().unwrap_or_default()
}
pub fn try_return_bytes(&self) -> Result<Vec<u8>, crate::SdkError> {
strict_bytes_from_hex(&self.return_data, "return_data")
}
#[must_use]
pub fn contract_address(&self) -> Option<Address> {
let bytes = self.return_bytes();
if bytes.len() == 32 {
let mut addr = [0u8; 32];
addr.copy_from_slice(&bytes);
Some(Address(addr))
} else {
None
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
pub wave_id: String,
pub tx_index: String,
pub event_index: String,
pub contract_addr: String,
#[serde(default)]
pub topics: Vec<String>,
#[serde(default)]
pub data: String,
}
impl Event {
#[must_use]
pub fn wave_id_u64(&self) -> u64 {
u64::from_str_radix(self.wave_id.trim_start_matches("0x"), 16).unwrap_or(0)
}
#[must_use]
pub fn tx_index_u32(&self) -> u32 {
u32::from_str_radix(self.tx_index.trim_start_matches("0x"), 16).unwrap_or(0)
}
#[must_use]
pub fn event_index_u32(&self) -> u32 {
u32::from_str_radix(self.event_index.trim_start_matches("0x"), 16).unwrap_or(0)
}
#[must_use]
pub fn data_bytes(&self) -> Vec<u8> {
hex::decode(self.data.trim_start_matches("0x")).unwrap_or_default()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountInfo {
pub address: String,
pub account_type: String,
pub balance: String,
pub nonce: u64,
pub code_hash: String,
#[serde(default)]
pub storage_root: String,
}
impl AccountInfo {
#[must_use]
pub fn balance_quanta(&self) -> u128 {
u128::from_str_radix(self.balance.trim_start_matches("0x"), 16).unwrap_or(0)
}
#[must_use]
pub fn is_contract(&self) -> bool {
self.account_type == "contract"
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeInfo {
pub peer_id: String,
pub falcon_pubkey: String,
#[serde(default)]
pub listen_addrs: Vec<String>,
pub agent_version: String,
pub protocol_version: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CallRequest {
pub to: String,
pub data: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub from: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub gas: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimulationResult {
#[serde(default)]
pub receipt: Option<SimulationReceipt>,
pub access_list: SimulationAccessList,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimulationReceipt {
pub status: String,
pub gas_used: String,
pub fee_paid: String,
pub return_data: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimulationAccessList {
pub reads: Vec<SimulationRead>,
pub writes: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimulationRead {
pub slot: String,
#[serde(default)]
pub observed_version: Option<SimulationReadVersion>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimulationReadVersion {
pub tx_index: u32,
pub attempt: u32,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LogFilter {
#[serde(skip_serializing_if = "Option::is_none")]
pub from_wave: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub to_wave: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub contracts: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub topics: Vec<Option<Vec<String>>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cursor: Option<LogCursor>,
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogCursor {
pub wave_id: String,
pub tx_index: String,
pub event_index: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogPage {
#[serde(default)]
pub entries: Vec<Event>,
#[serde(default)]
pub next_cursor: Option<LogCursor>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EventFilter {
#[serde(skip_serializing_if = "Option::is_none")]
pub from_wave: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub to_wave: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub contract: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct CallOverrides {
pub from: Option<Address>,
pub value: Option<u128>,
pub gas_limit: Option<u64>,
}
#[derive(Debug, Clone)]
pub struct FeeData {
pub base_fee: u128,
pub suggested_tip: u128,
pub wave_id: u64,
pub recent_waves: Vec<RecentWaveSummary>,
}
#[derive(Debug, Clone, Copy)]
pub struct RecentWaveSummary {
pub wave_id: u64,
pub gas_used: u64,
pub gas_limit: u64,
pub utilisation: f64,
}
pub type Log = Event;
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn revert_category_decodes_engine_snake_case() {
let v: RevertCategory = serde_json::from_str(r#""engine_validation""#).unwrap();
assert_eq!(v, RevertCategory::EngineValidation);
assert!(v.is_known());
let v: RevertCategory = serde_json::from_str(r#""contract""#).unwrap();
assert_eq!(v, RevertCategory::Contract);
let v: RevertCategory = serde_json::from_str(r#""vm""#).unwrap();
assert_eq!(v, RevertCategory::Vm);
let v: RevertCategory = serde_json::from_str(r#""future_category""#).unwrap();
assert!(!v.is_known());
assert!(matches!(v, RevertCategory::Other(ref s) if s == "future_category"));
}
#[test]
fn receipt_decodes_engine_shape() {
let raw = r#"{
"tx_hash": "0xdead",
"wave_id": "0x5",
"tx_index": "0x2",
"status": "success",
"gas_used": "0x5208",
"fee_paid": "0x12345",
"return_data": "0x",
"events": []
}"#;
let r: Receipt = serde_json::from_str(raw).unwrap();
assert_eq!(r.gas(), 0x5208);
assert_eq!(r.fee_paid_quanta(), 0x12345);
assert_eq!(r.wave_id_u64(), 5);
assert_eq!(r.tx_index_u32(), 2);
assert!(r.is_success());
}
#[test]
fn receipt_handles_status_variants() {
let payload = |status: &str| {
format!(
r#"{{ "tx_hash": "0x00", "wave_id": "0x0", "tx_index": "0x0",
"status": "{status}", "gas_used": "0x0", "fee_paid": "0x0" }}"#
)
};
let s: Receipt = serde_json::from_str(&payload("success")).unwrap();
let r: Receipt = serde_json::from_str(&payload("reverted")).unwrap();
let o: Receipt = serde_json::from_str(&payload("out_of_gas")).unwrap();
assert_eq!(s.status, ReceiptStatus::Success);
assert_eq!(r.status, ReceiptStatus::Reverted);
assert_eq!(o.status, ReceiptStatus::OutOfGas);
}
#[test]
fn contract_address_extracts_from_32_byte_return() {
let bytes = [0xAB; 32];
let r = Receipt {
tx_hash: String::new(),
wave_id: "0x0".into(),
tx_index: "0x0".into(),
nonce: "0x0".into(),
commit_reveal: false,
status: ReceiptStatus::Success,
gas_used: String::new(),
fee_paid: String::new(),
return_data: format!("0x{}", hex::encode(bytes)),
events: vec![],
revert_reason: None,
};
let addr = r.contract_address().unwrap();
assert_eq!(addr.as_bytes(), &bytes);
}
#[test]
fn event_decodes_engine_shape() {
let raw = r#"{
"wave_id": "0x10",
"tx_index": "0x3",
"event_index": "0x1",
"contract_addr": "0xabcd",
"topics": ["0x1111", "0x2222"],
"data": "0xbeef"
}"#;
let e: Event = serde_json::from_str(raw).unwrap();
assert_eq!(e.wave_id_u64(), 0x10);
assert_eq!(e.tx_index_u32(), 3);
assert_eq!(e.event_index_u32(), 1);
assert_eq!(e.topics.len(), 2);
assert_eq!(e.data_bytes(), vec![0xBE, 0xEF]);
}
#[test]
fn account_info_decodes_engine_shape() {
let raw = r#"{
"address": "0xa1",
"account_type": "eoa",
"balance": "0x3b9aca00",
"nonce": 7,
"code_hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"storage_root": "0x0000000000000000000000000000000000000000000000000000000000000000",
"state_root": "0x0000000000000000000000000000000000000000000000000000000000000000"
}"#;
let a: AccountInfo = serde_json::from_str(raw).unwrap();
assert_eq!(a.balance_quanta(), 1_000_000_000);
assert_eq!(a.nonce, 7);
assert!(!a.is_contract());
assert_eq!(
a.storage_root,
"0x0000000000000000000000000000000000000000000000000000000000000000"
);
}
#[test]
fn log_filter_skips_empties() {
let f = LogFilter {
from_wave: Some("0x5".into()),
contracts: vec!["0xabcd".into()],
..Default::default()
};
let json = serde_json::to_string(&f).unwrap();
assert!(json.contains("from_wave"));
assert!(json.contains("contracts"));
assert!(!json.contains("to_wave"));
assert!(!json.contains("topics"));
assert!(!json.contains("cursor"));
assert!(!json.contains("limit"));
}
#[test]
fn simulation_result_round_trip() {
let raw = r#"{
"receipt": {
"status": "Success",
"gas_used": "0x5208",
"fee_paid": "0x12345",
"return_data": "0x"
},
"access_list": {
"reads": [
{ "slot": "0xaa", "observed_version": null }
],
"writes": ["0xbb"]
}
}"#;
let s: SimulationResult = serde_json::from_str(raw).unwrap();
let receipt = s.receipt.unwrap();
assert_eq!(receipt.status, "Success");
assert_eq!(s.access_list.reads.len(), 1);
assert_eq!(s.access_list.writes.len(), 1);
}
#[test]
fn event_filter_uses_camel_case() {
let f = EventFilter {
from_wave: Some("0x0".into()),
to_wave: Some("0xff".into()),
contract: None,
};
let json = serde_json::to_string(&f).unwrap();
assert!(json.contains("fromWave"));
assert!(json.contains("toWave"));
assert!(!json.contains("contract\""));
}
}