use std::time::Duration;
use futures_util::{stream::Stream, StreamExt};
use moonproof_utils::rt::timeout;
use serde::Deserialize;
use serde_json::{json, Value};
use crate::ws::{self, Incoming};
const WS_PROTOCOL: &str = "graphql-transport-ws";
const WS_PROTOCOL_DEFLATE: &str = "graphql-transport-ws+deflate";
pub const MAX_INFLATED_BYTES: u64 = 16 * 1024 * 1024;
const CONNECTION_INIT_TIMEOUT: Duration = Duration::from_secs(10);
const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
#[derive(Debug, thiserror::Error)]
pub enum SubscriptionError {
#[error("websocket error: {0}")]
WebSocket(String),
#[error("invalid subscription URL: {0}")]
InvalidUrl(String),
#[error("connection_init timed out")]
ConnectionInitTimeout,
#[error("server returned error: {0}")]
ServerError(String),
#[error("unexpected server message before connection_ack: {0}")]
UnexpectedFirstMessage(String),
#[error("malformed server message: {0}")]
MalformedMessage(String),
#[error("inflated subscription message exceeds {MAX_INFLATED_BYTES} bytes")]
PayloadTooLarge,
#[error("indexer connection went silent: no reply to a keepalive ping within {0:?}")]
KeepaliveTimeout(Duration),
}
#[derive(Debug, Clone)]
pub enum SubscriptionItem {
Next(Value),
Complete,
}
#[cfg(not(target_arch = "wasm32"))]
pub type SubscriptionStream =
Box<dyn Stream<Item = Result<SubscriptionItem, SubscriptionError>> + Unpin + Send>;
#[cfg(target_arch = "wasm32")]
pub type SubscriptionStream =
Box<dyn Stream<Item = Result<SubscriptionItem, SubscriptionError>> + Unpin>;
pub async fn run_subscription(
ws_url: &str,
query: &str,
variables: Value,
) -> Result<SubscriptionStream, SubscriptionError> {
run_subscription_with_keepalive(ws_url, query, variables, KEEPALIVE_INTERVAL).await
}
async fn run_subscription_with_keepalive(
ws_url: &str,
query: &str,
variables: Value,
keepalive: Duration,
) -> Result<SubscriptionStream, SubscriptionError> {
let mut ws = ws::connect(ws_url, &[WS_PROTOCOL_DEFLATE, WS_PROTOCOL]).await?;
ws.send_text(json!({ "type": "connection_init", "payload": {} }).to_string())
.await?;
let ack_msg = timeout(CONNECTION_INIT_TIMEOUT, ws.next())
.await
.map_err(|_| SubscriptionError::ConnectionInitTimeout)?
.ok_or_else(|| {
SubscriptionError::UnexpectedFirstMessage("stream closed before ack".to_owned())
})??;
let deflate = ws.protocol().as_deref() == Some(WS_PROTOCOL_DEFLATE);
expect_connection_ack(&ack_msg, deflate)?;
let sub_id = "1";
ws.send_text(
json!({
"id": sub_id,
"type": "subscribe",
"payload": { "query": query, "variables": variables },
})
.to_string(),
)
.await?;
let stream = futures_util::stream::unfold(Some(ws), move |state| async move {
next_subscription_item(state?, keepalive, deflate).await
});
let pinned: SubscriptionStream = Box::new(Box::pin(stream));
Ok(pinned)
}
async fn next_subscription_item(
mut ws: ws::Socket,
keepalive: Duration,
deflate: bool,
) -> Option<(
Result<SubscriptionItem, SubscriptionError>,
Option<ws::Socket>,
)> {
let mut pinged = false;
loop {
let msg = match timeout(keepalive, ws.next()).await {
Ok(Some(Ok(m))) => m,
Ok(Some(Err(e))) => return Some((Err(e), None)),
Ok(None) => return None, Err(_) if pinged => {
return Some((Err(SubscriptionError::KeepaliveTimeout(keepalive)), None));
}
Err(_) => {
if let Err(e) = ws.send_text(json!({ "type": "ping" }).to_string()).await {
return Some((Err(e), None));
}
pinged = true;
continue;
}
};
pinged = false;
let text = match frame_text(msg, deflate) {
Ok(Frame::Text(text)) => text,
Ok(Frame::Control) => continue,
Ok(Frame::Closed) => return None,
Err(e) => return Some((Err(e), None)),
};
match parse_server_message(&text) {
Ok(ServerMessage::Next { id, data }) if id == "1" => {
return Some((Ok(SubscriptionItem::Next(data)), Some(ws)));
}
Ok(ServerMessage::Complete { id }) if id == "1" => {
return Some((Ok(SubscriptionItem::Complete), None));
}
Ok(ServerMessage::Error { id, payload }) if id == "1" => {
return Some((
Err(SubscriptionError::ServerError(payload.to_string())),
None,
));
}
Ok(ServerMessage::Ping) => {
if let Err(e) = ws.send_text(json!({ "type": "pong" }).to_string()).await {
return Some((Err(e), None));
}
}
Ok(
ServerMessage::Pong
| ServerMessage::Other
| ServerMessage::Next { .. }
| ServerMessage::Complete { .. }
| ServerMessage::Error { .. },
) => {
}
Err(e) => return Some((Err(e), None)),
}
}
}
enum Frame {
Text(String),
Control,
Closed,
}
fn frame_text(msg: Incoming, deflate: bool) -> Result<Frame, SubscriptionError> {
match msg {
Incoming::Text(text) => Ok(Frame::Text(text)),
Incoming::Binary(bytes) if deflate => inflate_message(&bytes).map(Frame::Text),
Incoming::Closed => Ok(Frame::Closed),
Incoming::Binary(_) | Incoming::Control => Ok(Frame::Control),
}
}
fn inflate_message(compressed: &[u8]) -> Result<String, SubscriptionError> {
use std::io::Read;
let mut out = Vec::new();
flate2::read::ZlibDecoder::new(compressed)
.take(MAX_INFLATED_BYTES + 1)
.read_to_end(&mut out)
.map_err(|e| SubscriptionError::MalformedMessage(format!("inflate: {e}")))?;
if out.len() as u64 > MAX_INFLATED_BYTES {
return Err(SubscriptionError::PayloadTooLarge);
}
String::from_utf8(out).map_err(|e| {
SubscriptionError::MalformedMessage(format!("inflated message is not UTF-8: {e}"))
})
}
fn expect_connection_ack(msg: &Incoming, deflate: bool) -> Result<(), SubscriptionError> {
let text = match frame_text(msg.clone(), deflate)? {
Frame::Text(t) => t,
Frame::Control | Frame::Closed => {
return Err(SubscriptionError::UnexpectedFirstMessage(format!(
"non-text first message: {msg:?}"
)));
}
};
let v: Value = serde_json::from_str(&text)
.map_err(|e| SubscriptionError::MalformedMessage(format!("ack json: {e}")))?;
match v.get("type").and_then(|t| t.as_str()) {
Some("connection_ack") => Ok(()),
Some(other) => Err(SubscriptionError::UnexpectedFirstMessage(other.to_owned())),
None => Err(SubscriptionError::MalformedMessage(
"ack message has no `type` field".to_owned(),
)),
}
}
#[derive(Debug)]
enum ServerMessage {
Next {
id: String,
data: Value,
},
Complete {
id: String,
},
Error {
id: String,
payload: Value,
},
Ping,
Pong,
Other,
}
#[derive(Deserialize)]
struct RawMessage {
#[serde(rename = "type")]
ty: String,
#[serde(default)]
id: Option<String>,
#[serde(default)]
payload: Option<Value>,
}
fn parse_server_message(text: &str) -> Result<ServerMessage, SubscriptionError> {
let raw: RawMessage = serde_json::from_str(text)
.map_err(|e| SubscriptionError::MalformedMessage(format!("server message: {e}")))?;
Ok(match raw.ty.as_str() {
"next" => {
let id = raw
.id
.ok_or_else(|| SubscriptionError::MalformedMessage("next missing id".to_owned()))?;
let payload = raw.payload.ok_or_else(|| {
SubscriptionError::MalformedMessage("next missing payload".to_owned())
})?;
if let Some(errors) = payload.get("errors").filter(|e| !e.is_null()) {
return Err(SubscriptionError::ServerError(errors.to_string()));
}
let data = payload.get("data").cloned().unwrap_or(Value::Null);
ServerMessage::Next { id, data }
}
"complete" => {
let id = raw.id.ok_or_else(|| {
SubscriptionError::MalformedMessage("complete missing id".to_owned())
})?;
ServerMessage::Complete { id }
}
"error" => {
let id = raw.id.ok_or_else(|| {
SubscriptionError::MalformedMessage("error missing id".to_owned())
})?;
let payload = raw.payload.unwrap_or(Value::Null);
ServerMessage::Error { id, payload }
}
"ping" => ServerMessage::Ping,
"pong" => ServerMessage::Pong,
_ => ServerMessage::Other,
})
}
#[must_use]
pub fn graphql_ws_url(http_url: &str) -> String {
let Ok(mut url) = url::Url::parse(http_url) else {
return http_url.to_owned();
};
let ws_scheme = match url.scheme() {
"https" => Some("wss"),
"http" => Some("ws"),
_ => None,
};
if let Some(scheme) = ws_scheme {
if url.set_scheme(scheme).is_err() {
return http_url.to_owned();
}
}
if url.path().is_empty() || url.path() == "/" {
url.set_path(crate::endpoint::DEFAULT_GRAPHQL_PATH);
}
let path = url.path().trim_end_matches('/').to_owned();
if !path.ends_with("/ws") {
url.set_path(&format!("{path}/ws"));
}
url.to_string()
}
const DUST_PROBE_TIMEOUT: Duration = Duration::from_secs(15);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DustEventPosition {
pub id: i64,
pub protocol_version: u32,
pub max_id: i64,
}
pub async fn first_dust_event_from(
http_url: &str,
id: Option<i64>,
) -> Result<DustEventPosition, SubscriptionError> {
const QUERY: &str = r"
subscription DustEventPosition($id: Int) {
dustLedgerEvents(id: $id) { id maxId protocolVersion }
}
";
let mut stream =
run_subscription(&graphql_ws_url(http_url), QUERY, json!({ "id": id })).await?;
let first = timeout(DUST_PROBE_TIMEOUT, stream.next())
.await
.map_err(|_| {
SubscriptionError::MalformedMessage("no dust event within the probe timeout".into())
})?;
let data = match first {
Some(Ok(SubscriptionItem::Next(data))) => data,
Some(Ok(SubscriptionItem::Complete)) | None => {
return Err(SubscriptionError::MalformedMessage(
"the dust event stream closed".into(),
));
}
Some(Err(e)) => return Err(e),
};
let event = &data["dustLedgerEvents"];
let field = |name: &str| {
event[name].as_i64().ok_or_else(|| {
SubscriptionError::MalformedMessage(format!("dust event `{name}` missing"))
})
};
Ok(DustEventPosition {
id: field("id")?,
protocol_version: u32::try_from(field("protocolVersion")?).map_err(|_| {
SubscriptionError::MalformedMessage("protocolVersion out of range".into())
})?,
max_id: field("maxId")?,
})
}
pub async fn find_dust_timeline_start(
http_url: &str,
boundary: u32,
) -> Result<Option<i64>, SubscriptionError> {
search_dust_boundary(boundary, |id| first_dust_event_from(http_url, id)).await
}
async fn search_dust_boundary<F, Fut>(
boundary: u32,
mut probe: F,
) -> Result<Option<i64>, SubscriptionError>
where
F: FnMut(Option<i64>) -> Fut,
Fut: std::future::Future<Output = Result<DustEventPosition, SubscriptionError>>,
{
let first = probe(None).await?;
let last = probe(Some(first.max_id)).await?;
if first.protocol_version >= boundary || last.protocol_version < boundary {
return Ok(None);
}
let mut best = last.id;
let (mut low, mut high) = (first.id + 1, last.id - 1);
while low <= high {
let middle = low + (high - low) / 2;
let probed = probe(Some(middle)).await?;
if probed.id > high {
high = middle - 1;
} else if probed.protocol_version >= boundary {
best = probed.id;
high = middle - 1;
} else {
low = probed.id + 1;
}
}
Ok(Some(best))
}
pub async fn subscribe_dust_ledger_events(
http_url: &str,
start_id: Option<i64>,
) -> Result<DustLedgerEventStream, SubscriptionError> {
const QUERY: &str = r"
subscription DustLedgerEventsSub($id: Int) {
dustLedgerEvents(id: $id) {
__typename
id
raw
maxId
}
}
";
let ws_url = graphql_ws_url(http_url);
let variables = match start_id {
Some(id) => json!({ "id": id }),
None => json!({ "id": null }),
};
let inner = run_subscription(&ws_url, QUERY, variables).await?;
Ok(DustLedgerEventStream { inner })
}
pub struct DustLedgerEventStream {
inner: SubscriptionStream,
}
impl Stream for DustLedgerEventStream {
type Item = Result<crate::DustLedgerEventRaw, SubscriptionError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use std::task::Poll;
let item = match std::pin::Pin::new(&mut self.inner).poll_next(cx) {
Poll::Ready(Some(Ok(item))) => item,
Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
Poll::Ready(None) => return Poll::Ready(None),
Poll::Pending => return Poll::Pending,
};
match item {
SubscriptionItem::Complete => Poll::Ready(None),
SubscriptionItem::Next(data) => Poll::Ready(Some(parse_dust_ledger_event(&data))),
}
}
}
pub async fn subscribe_unshielded_transactions(
http_url: &str,
address: &str,
start_id: Option<i64>,
) -> Result<UnshieldedTxStream, SubscriptionError> {
const QUERY: &str = r"
subscription UnshieldedTransactionsSub($address: UnshieldedAddress!, $id: Int) {
unshieldedTransactions(address: $address, transactionId: $id) {
__typename
... on UnshieldedTransaction {
createdUtxos {
owner
tokenType
value
intentHash
outputIndex
ctime
initialNonce
registeredForDustGeneration
}
spentUtxos {
owner
tokenType
value
intentHash
outputIndex
ctime
initialNonce
registeredForDustGeneration
}
transaction {
__typename
id
hash
block {
hash
height
timestamp
}
... on RegularTransaction {
transactionResult {
status
}
}
}
}
... on UnshieldedTransactionsProgress {
highestTransactionId
}
}
}
";
let ws_url = graphql_ws_url(http_url);
let variables = match start_id {
Some(id) => json!({ "address": address, "id": id }),
None => json!({ "address": address, "id": null }),
};
let inner = run_subscription(&ws_url, QUERY, variables).await?;
Ok(UnshieldedTxStream { inner })
}
pub struct UnshieldedTxStream {
inner: SubscriptionStream,
}
impl Stream for UnshieldedTxStream {
type Item = Result<crate::UnshieldedTxRaw, SubscriptionError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use std::task::Poll;
let item = match std::pin::Pin::new(&mut self.inner).poll_next(cx) {
Poll::Ready(Some(Ok(item))) => item,
Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
Poll::Ready(None) => return Poll::Ready(None),
Poll::Pending => return Poll::Pending,
};
match item {
SubscriptionItem::Complete => Poll::Ready(None),
SubscriptionItem::Next(data) => Poll::Ready(Some(parse_unshielded_tx_event(&data))),
}
}
}
fn parse_unshielded_tx_event(data: &Value) -> Result<crate::UnshieldedTxRaw, SubscriptionError> {
let ev = data.get("unshieldedTransactions").ok_or_else(|| {
SubscriptionError::MalformedMessage(
"next payload missing `unshieldedTransactions` field".to_owned(),
)
})?;
let kind = ev
.get("__typename")
.and_then(|v| v.as_str())
.unwrap_or("UnknownUnshieldedTransactionsEvent")
.to_owned();
if kind == "UnshieldedTransactionsProgress" {
let highest = ev
.get("highestTransactionId")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| {
SubscriptionError::MalformedMessage(
"progress event missing highestTransactionId".to_owned(),
)
})?;
return Ok(crate::UnshieldedTxRaw {
kind,
status: None,
transaction_id: None,
transaction_hash: None,
block: None,
block_time_secs: None,
created_utxos: Vec::new(),
spent_utxos: Vec::new(),
highest_transaction_id: Some(highest),
});
}
let created = ev
.get("createdUtxos")
.and_then(|v| v.as_array())
.ok_or_else(|| {
SubscriptionError::MalformedMessage(
"unshielded tx missing createdUtxos array".to_owned(),
)
})?
.iter()
.map(parse_unshielded_utxo)
.collect::<Result<Vec<_>, _>>()?;
let spent = ev
.get("spentUtxos")
.and_then(|v| v.as_array())
.ok_or_else(|| {
SubscriptionError::MalformedMessage("unshielded tx missing spentUtxos array".to_owned())
})?
.iter()
.map(parse_unshielded_utxo)
.collect::<Result<Vec<_>, _>>()?;
let tx_obj = ev.get("transaction").ok_or_else(|| {
SubscriptionError::MalformedMessage("unshielded tx missing `transaction` object".to_owned())
})?;
let tx_typename = tx_obj
.get("__typename")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_owned();
let transaction_id = tx_obj.get("id").and_then(serde_json::Value::as_i64);
let transaction_hash = tx_obj
.get("hash")
.and_then(|v| v.as_str())
.map(ToOwned::to_owned);
let (block, block_time_secs) =
parse_tx_block(tx_obj, "unshielded tx's `transaction` missing `block`")?;
let status = if tx_typename == "SystemTransaction" {
Some("SUCCESS".to_owned())
} else {
tx_obj
.get("transactionResult")
.and_then(|r| r.get("status"))
.and_then(|s| s.as_str())
.map(ToOwned::to_owned)
};
Ok(crate::UnshieldedTxRaw {
kind,
status,
transaction_id,
transaction_hash,
block: Some(block),
block_time_secs: Some(block_time_secs),
created_utxos: created,
spent_utxos: spent,
highest_transaction_id: None,
})
}
fn parse_tx_block(
tx_obj: &Value,
missing_block: &str,
) -> Result<(crate::types::BlockRef, i64), SubscriptionError> {
let block_obj = tx_obj
.get("block")
.ok_or_else(|| SubscriptionError::MalformedMessage(missing_block.to_owned()))?;
let block_hash = block_obj
.get("hash")
.and_then(|v| v.as_str())
.ok_or_else(|| SubscriptionError::MalformedMessage("block missing hash".to_owned()))?
.to_owned();
let block_height = block_obj
.get("height")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| SubscriptionError::MalformedMessage("block missing height".to_owned()))?;
let block_ts_ms = block_obj
.get("timestamp")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| SubscriptionError::MalformedMessage("block missing timestamp".to_owned()))?;
let block_time_secs = block_ts_ms / 1000;
let block = crate::types::BlockRef {
hash: block_hash,
height: block_height,
};
Ok((block, block_time_secs))
}
fn parse_unshielded_utxo(v: &Value) -> Result<crate::UnshieldedUtxoRaw, SubscriptionError> {
let owner = v
.get("owner")
.and_then(|x| x.as_str())
.ok_or_else(|| SubscriptionError::MalformedMessage("utxo missing owner".to_owned()))?
.to_owned();
let token_type = v
.get("tokenType")
.and_then(|x| x.as_str())
.ok_or_else(|| SubscriptionError::MalformedMessage("utxo missing tokenType".to_owned()))?
.to_owned();
let value = v
.get("value")
.and_then(|x| x.as_str())
.ok_or_else(|| SubscriptionError::MalformedMessage("utxo missing value".to_owned()))?
.to_owned();
let intent_hash = v
.get("intentHash")
.and_then(|x| x.as_str())
.ok_or_else(|| SubscriptionError::MalformedMessage("utxo missing intentHash".to_owned()))?
.to_owned();
let output_index = v
.get("outputIndex")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| {
SubscriptionError::MalformedMessage("utxo missing outputIndex".to_owned())
})?;
let ctime = v.get("ctime").and_then(serde_json::Value::as_i64);
let initial_nonce = v
.get("initialNonce")
.and_then(|x| x.as_str())
.ok_or_else(|| SubscriptionError::MalformedMessage("utxo missing initialNonce".to_owned()))?
.to_owned();
let registered_for_dust_generation = v
.get("registeredForDustGeneration")
.and_then(serde_json::Value::as_bool)
.ok_or_else(|| {
SubscriptionError::MalformedMessage(
"utxo missing registeredForDustGeneration".to_owned(),
)
})?;
Ok(crate::UnshieldedUtxoRaw {
owner,
token_type,
value,
intent_hash,
output_index,
ctime,
initial_nonce,
registered_for_dust_generation,
})
}
pub async fn subscribe_shielded_transactions(
http_url: &str,
session_id: &str,
start_index: Option<i64>,
) -> Result<ShieldedTxStream, SubscriptionError> {
const QUERY: &str = r"
subscription ShieldedTransactionsSub($sessionId: HexEncoded!, $index: Int) {
shieldedTransactions(sessionId: $sessionId, index: $index) {
__typename
... on RelevantTransaction {
transaction {
id
hash
endIndex
transactionResult {
status
}
block {
hash
height
timestamp
}
zswapLedgerEvents {
id
raw
maxId
}
}
collapsedMerkleTree {
startIndex
endIndex
update
protocolVersion
}
}
... on ShieldedTransactionsProgress {
highestEndIndex
highestCheckedEndIndex
highestRelevantEndIndex
}
}
}
";
let ws_url = graphql_ws_url(http_url);
let variables = match start_index {
Some(i) => json!({ "sessionId": session_id, "index": i }),
None => json!({ "sessionId": session_id, "index": null }),
};
let inner = run_subscription(&ws_url, QUERY, variables).await?;
Ok(ShieldedTxStream { inner })
}
pub struct ShieldedTxStream {
inner: SubscriptionStream,
}
impl Stream for ShieldedTxStream {
type Item = Result<crate::ShieldedTxRaw, SubscriptionError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use std::task::Poll;
let item = match std::pin::Pin::new(&mut self.inner).poll_next(cx) {
Poll::Ready(Some(Ok(item))) => item,
Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
Poll::Ready(None) => return Poll::Ready(None),
Poll::Pending => return Poll::Pending,
};
match item {
SubscriptionItem::Complete => Poll::Ready(None),
SubscriptionItem::Next(data) => Poll::Ready(Some(parse_shielded_tx_event(&data))),
}
}
}
fn parse_shielded_tx_event(data: &Value) -> Result<crate::ShieldedTxRaw, SubscriptionError> {
let ev = data.get("shieldedTransactions").ok_or_else(|| {
SubscriptionError::MalformedMessage(
"next payload missing `shieldedTransactions` field".to_owned(),
)
})?;
let kind = ev
.get("__typename")
.and_then(|v| v.as_str())
.unwrap_or("UnknownShieldedTransactionsEvent")
.to_owned();
if kind == "ShieldedTransactionsProgress" {
return parse_shielded_progress(ev, kind);
}
let tx_obj = ev.get("transaction").ok_or_else(|| {
SubscriptionError::MalformedMessage(
"relevant-transaction event missing `transaction` object".to_owned(),
)
})?;
let transaction_id = tx_obj
.get("id")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| SubscriptionError::MalformedMessage("transaction missing id".to_owned()))?;
let transaction_hash = tx_obj
.get("hash")
.and_then(|v| v.as_str())
.ok_or_else(|| SubscriptionError::MalformedMessage("transaction missing hash".to_owned()))?
.to_owned();
let zswap_end_index = tx_obj
.get("endIndex")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| {
SubscriptionError::MalformedMessage("transaction missing zswapEndIndex".to_owned())
})?;
let status = tx_obj
.get("transactionResult")
.and_then(|r| r.get("status"))
.and_then(|s| s.as_str())
.map(ToOwned::to_owned);
let (block, block_time_secs) = parse_tx_block(tx_obj, "transaction missing block")?;
let zswap_ledger_events = parse_tx_zswap_ledger_events(tx_obj)?;
let zswap_collapsed_update = ev
.get("collapsedMerkleTree")
.filter(|v| !v.is_null())
.map(parse_collapsed_update)
.transpose()?;
Ok(crate::ShieldedTxRaw {
kind,
status,
transaction_id: Some(transaction_id),
transaction_hash: Some(transaction_hash),
block: Some(block),
block_time_secs: Some(block_time_secs),
zswap_end_index: Some(zswap_end_index),
zswap_ledger_events,
zswap_collapsed_update,
highest_zswap_end_index: None,
highest_checked_zswap_end_index: None,
highest_relevant_zswap_end_index: None,
})
}
fn parse_shielded_progress(
ev: &Value,
kind: String,
) -> Result<crate::ShieldedTxRaw, SubscriptionError> {
let highest = ev
.get("highestEndIndex")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| {
SubscriptionError::MalformedMessage("progress event missing highestEndIndex".to_owned())
})?;
let highest_checked = ev
.get("highestCheckedEndIndex")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| {
SubscriptionError::MalformedMessage(
"progress event missing highestCheckedEndIndex".to_owned(),
)
})?;
let highest_relevant = ev
.get("highestRelevantEndIndex")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| {
SubscriptionError::MalformedMessage(
"progress event missing highestRelevantEndIndex".to_owned(),
)
})?;
Ok(crate::ShieldedTxRaw {
kind,
status: None,
transaction_id: None,
transaction_hash: None,
block: None,
block_time_secs: None,
zswap_end_index: None,
zswap_ledger_events: Vec::new(),
zswap_collapsed_update: None,
highest_zswap_end_index: Some(highest),
highest_checked_zswap_end_index: Some(highest_checked),
highest_relevant_zswap_end_index: Some(highest_relevant),
})
}
fn parse_tx_zswap_ledger_events(
tx_obj: &Value,
) -> Result<Vec<crate::ZswapLedgerEventRaw>, SubscriptionError> {
let mut zswap_ledger_events = Vec::new();
if let Some(evts) = tx_obj.get("zswapLedgerEvents").and_then(|v| v.as_array()) {
for evt in evts {
let id = evt
.get("id")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| {
SubscriptionError::MalformedMessage("zswap ledger event missing id".to_owned())
})?;
let raw = evt
.get("raw")
.and_then(|v| v.as_str())
.ok_or_else(|| {
SubscriptionError::MalformedMessage("zswap ledger event missing raw".to_owned())
})?
.to_owned();
let max_id = evt
.get("maxId")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| {
SubscriptionError::MalformedMessage(
"zswap ledger event missing maxId".to_owned(),
)
})?;
zswap_ledger_events.push(crate::ZswapLedgerEventRaw { id, raw, max_id });
}
}
Ok(zswap_ledger_events)
}
fn parse_collapsed_update(
v: &Value,
) -> Result<crate::MerkleTreeCollapsedUpdate, SubscriptionError> {
let start_index = v
.get("startIndex")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| {
SubscriptionError::MalformedMessage(
"zswap collapsed update missing startIndex".to_owned(),
)
})?;
let end_index = v
.get("endIndex")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| {
SubscriptionError::MalformedMessage(
"zswap collapsed update missing endIndex".to_owned(),
)
})?;
let update = v
.get("update")
.and_then(|x| x.as_str())
.ok_or_else(|| {
SubscriptionError::MalformedMessage("zswap collapsed update missing update".to_owned())
})?
.to_owned();
let protocol_version = v
.get("protocolVersion")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| {
SubscriptionError::MalformedMessage(
"zswap collapsed update missing protocolVersion".to_owned(),
)
})?;
Ok(crate::MerkleTreeCollapsedUpdate {
start_index,
end_index,
update,
protocol_version,
})
}
pub async fn subscribe_blocks(
http_url: &str,
start_offset: Option<crate::BlockOffset>,
) -> Result<BlockStream, SubscriptionError> {
const QUERY: &str = r"
subscription BlocksSub($offset: BlockOffset) {
blocks(offset: $offset) {
hash
height
protocolVersion
timestamp
author
zswapMerkleTreeRoot
ledgerParameters
parent { hash height }
transactions {
__typename
... on RegularTransaction { id hash }
... on SystemTransaction { id hash }
}
}
}
";
let ws_url = graphql_ws_url(http_url);
let variables = match start_offset {
None => json!({ "offset": null }),
Some(crate::BlockOffset::Hash(h)) => json!({ "offset": { "hash": h } }),
Some(crate::BlockOffset::Height(h)) => json!({ "offset": { "height": h } }),
};
let inner = run_subscription(&ws_url, QUERY, variables).await?;
Ok(BlockStream { inner })
}
pub struct BlockStream {
inner: SubscriptionStream,
}
impl Stream for BlockStream {
type Item = Result<crate::BlockTickRaw, SubscriptionError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use std::task::Poll;
let item = match std::pin::Pin::new(&mut self.inner).poll_next(cx) {
Poll::Ready(Some(Ok(item))) => item,
Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
Poll::Ready(None) => return Poll::Ready(None),
Poll::Pending => return Poll::Pending,
};
match item {
SubscriptionItem::Complete => Poll::Ready(None),
SubscriptionItem::Next(data) => Poll::Ready(Some(parse_block_tick(&data))),
}
}
}
fn parse_block_tick(data: &Value) -> Result<crate::BlockTickRaw, SubscriptionError> {
let b = data.get("blocks").ok_or_else(|| {
SubscriptionError::MalformedMessage("next payload missing `blocks` field".to_owned())
})?;
let hash = required_str(b, "hash")?;
let height = required_i64(b, "height")?;
let protocol_version = required_i64(b, "protocolVersion")?;
let timestamp_ms = required_i64(b, "timestamp")?;
let author = b
.get("author")
.and_then(|v| v.as_str())
.map(ToOwned::to_owned);
let zswap_merkle_tree_root = required_str(b, "zswapMerkleTreeRoot")?;
let ledger_parameters = required_str(b, "ledgerParameters")?;
let (parent_hash, parent_height) = match b.get("parent") {
None | Some(Value::Null) => (None, None),
Some(parent) => (
Some(required_str(parent, "hash")?),
Some(required_i64(parent, "height")?),
),
};
let mut transactions = Vec::new();
if let Some(arr) = b.get("transactions").and_then(|v| v.as_array()) {
for tx in arr {
let typename = tx
.get("__typename")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_owned();
let kind = if typename == "SystemTransaction" {
crate::TransactionKind::System
} else {
crate::TransactionKind::Regular
};
transactions.push(crate::BlockTickTransactionRef {
kind,
id: required_i64(tx, "id")?,
hash: required_str(tx, "hash")?,
});
}
}
Ok(crate::BlockTickRaw {
hash,
height,
protocol_version,
timestamp_ms,
author,
zswap_merkle_tree_root,
ledger_parameters,
parent_hash,
parent_height,
transactions,
})
}
pub async fn subscribe_contract_actions(
http_url: &str,
address: &str,
start_offset: Option<crate::BlockOffset>,
) -> Result<ContractActionStream, SubscriptionError> {
const QUERY: &str = r"
subscription ContractActionsSub($address: HexEncoded!, $offset: BlockOffset) {
contractActions(address: $address, offset: $offset) {
__typename
address
state
zswapState
unshieldedBalances { tokenType amount }
... on ContractCall { entryPoint }
transaction {
__typename
id
hash
block { hash height timestamp }
}
}
}
";
let ws_url = graphql_ws_url(http_url);
let variables = match start_offset {
None => json!({ "address": address, "offset": null }),
Some(crate::BlockOffset::Hash(h)) => {
json!({ "address": address, "offset": { "hash": h } })
}
Some(crate::BlockOffset::Height(h)) => {
json!({ "address": address, "offset": { "height": h } })
}
};
let inner = run_subscription(&ws_url, QUERY, variables).await?;
Ok(ContractActionStream { inner })
}
pub struct ContractActionStream {
inner: SubscriptionStream,
}
impl Stream for ContractActionStream {
type Item = Result<crate::ContractActionTickRaw, SubscriptionError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use std::task::Poll;
let item = match std::pin::Pin::new(&mut self.inner).poll_next(cx) {
Poll::Ready(Some(Ok(item))) => item,
Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
Poll::Ready(None) => return Poll::Ready(None),
Poll::Pending => return Poll::Pending,
};
match item {
SubscriptionItem::Complete => Poll::Ready(None),
SubscriptionItem::Next(data) => Poll::Ready(Some(parse_contract_action_tick(&data))),
}
}
}
fn parse_contract_action_tick(
data: &Value,
) -> Result<crate::ContractActionTickRaw, SubscriptionError> {
let a = data.get("contractActions").ok_or_else(|| {
SubscriptionError::MalformedMessage(
"next payload missing `contractActions` field".to_owned(),
)
})?;
let typename = a
.get("__typename")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_owned();
let kind = match typename.as_str() {
"ContractDeploy" => crate::ContractActionKind::Deploy,
"ContractCall" => crate::ContractActionKind::Call,
"ContractUpdate" => crate::ContractActionKind::Update,
other => {
return Err(SubscriptionError::MalformedMessage(format!(
"unknown contract action __typename `{other}`"
)));
}
};
let address = required_str(a, "address")?;
let state = required_str(a, "state")?;
let zswap_state = required_str(a, "zswapState")?;
let mut unshielded_balances = Vec::new();
if let Some(arr) = a.get("unshieldedBalances").and_then(|v| v.as_array()) {
for b in arr {
unshielded_balances.push(crate::ContractBalance {
token_type: required_str(b, "tokenType")?,
amount: required_str(b, "amount")?,
});
}
}
let entry_point = a
.get("entryPoint")
.and_then(|v| v.as_str())
.map(ToOwned::to_owned);
let tx = a.get("transaction").ok_or_else(|| {
SubscriptionError::MalformedMessage("action missing transaction".to_owned())
})?;
let transaction_id = required_i64(tx, "id")?;
let transaction_hash = required_str(tx, "hash")?;
let block_obj = tx.get("block").ok_or_else(|| {
SubscriptionError::MalformedMessage("transaction missing block".to_owned())
})?;
let block = crate::BlockRef {
hash: required_str(block_obj, "hash")?,
height: required_i64(block_obj, "height")?,
};
Ok(crate::ContractActionTickRaw {
kind,
address,
state,
zswap_state,
unshielded_balances,
entry_point,
transaction_id,
transaction_hash,
block,
})
}
pub async fn subscribe_zswap_ledger_events(
http_url: &str,
start_id: Option<i64>,
) -> Result<ZswapLedgerEventStream, SubscriptionError> {
const QUERY: &str = r"
subscription ZswapLedgerEventsSub($id: Int) {
zswapLedgerEvents(id: $id) {
id
raw
maxId
}
}
";
let ws_url = graphql_ws_url(http_url);
let variables = match start_id {
Some(id) => json!({ "id": id }),
None => json!({ "id": null }),
};
let inner = run_subscription(&ws_url, QUERY, variables).await?;
Ok(ZswapLedgerEventStream { inner })
}
pub struct ZswapLedgerEventStream {
inner: SubscriptionStream,
}
impl Stream for ZswapLedgerEventStream {
type Item = Result<crate::ZswapLedgerEventRaw, SubscriptionError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use std::task::Poll;
let item = match std::pin::Pin::new(&mut self.inner).poll_next(cx) {
Poll::Ready(Some(Ok(item))) => item,
Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
Poll::Ready(None) => return Poll::Ready(None),
Poll::Pending => return Poll::Pending,
};
match item {
SubscriptionItem::Complete => Poll::Ready(None),
SubscriptionItem::Next(data) => Poll::Ready(Some(parse_zswap_ledger_event(&data))),
}
}
}
fn parse_zswap_ledger_event(data: &Value) -> Result<crate::ZswapLedgerEventRaw, SubscriptionError> {
let ev = data.get("zswapLedgerEvents").ok_or_else(|| {
SubscriptionError::MalformedMessage(
"next payload missing `zswapLedgerEvents` field".to_owned(),
)
})?;
let id = required_i64(ev, "id")?;
let raw = required_str(ev, "raw")?;
let max_id = required_i64(ev, "maxId")?;
Ok(crate::ZswapLedgerEventRaw { id, raw, max_id })
}
pub async fn subscribe_dust_generations(
http_url: &str,
dust_address_hex: &str,
block_hash_hex: &str,
dtime_cutoff_height: i64,
) -> Result<DustGenerationsStream, SubscriptionError> {
const QUERY: &str = r"
subscription DustGenerationsSub($dustAddress: DustAddress!, $blockHash: HexEncoded!, $dtimeCutoffHeight: Int!) {
dustGenerations(dustAddress: $dustAddress, blockHash: $blockHash, dtimeCutoffHeight: $dtimeCutoffHeight) {
__typename
... on DustGenerationsItem {
commitmentMtIndex
generationMtIndex
owner
value
initialValue
backingNight
ctime
transactionId
transactionHash
collapsedMerkleTree {
startIndex
endIndex
update
protocolVersion
}
}
... on DustGenerationsProgress {
highestIndex
collapsedMerkleTree {
startIndex
endIndex
update
protocolVersion
}
}
... on DustGenerationDtimeUpdateItem {
generationMtIndex
owner
nightUtxoHash
newDtime
transactionId
transactionHash
treeInsertionPath
}
}
}
";
let ws_url = graphql_ws_url(http_url);
let variables = json!({
"dustAddress": dust_address_hex,
"blockHash": block_hash_hex,
"dtimeCutoffHeight": dtime_cutoff_height,
});
let inner = run_subscription(&ws_url, QUERY, variables).await?;
Ok(DustGenerationsStream { inner })
}
pub struct DustGenerationsStream {
inner: SubscriptionStream,
}
impl Stream for DustGenerationsStream {
type Item = Result<crate::DustGenerationsTickRaw, SubscriptionError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use std::task::Poll;
let item = match std::pin::Pin::new(&mut self.inner).poll_next(cx) {
Poll::Ready(Some(Ok(item))) => item,
Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
Poll::Ready(None) => return Poll::Ready(None),
Poll::Pending => return Poll::Pending,
};
match item {
SubscriptionItem::Complete => Poll::Ready(None),
SubscriptionItem::Next(data) => Poll::Ready(Some(parse_dust_generations_tick(&data))),
}
}
}
fn parse_dust_generations_tick(
data: &Value,
) -> Result<crate::DustGenerationsTickRaw, SubscriptionError> {
let g = data.get("dustGenerations").ok_or_else(|| {
SubscriptionError::MalformedMessage(
"next payload missing `dustGenerations` field".to_owned(),
)
})?;
let kind = g
.get("__typename")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_owned();
if kind == "DustGenerationsProgress" {
let highest_index = required_i64(g, "highestIndex")?;
let collapsed = optional_collapsed_update(g, "collapsedMerkleTree")?;
return Ok(crate::DustGenerationsTickRaw {
kind,
item: None,
dtime_update: None,
progress: Some(crate::DustGenerationsProgressRaw {
highest_index,
collapsed_merkle_tree: collapsed,
}),
});
}
if kind == "DustGenerationsItem" {
let item = crate::DustGenerationsItemRaw {
commitment_mt_index: required_i64(g, "commitmentMtIndex")?,
generation_mt_index: required_i64(g, "generationMtIndex")?,
owner: required_str(g, "owner")?,
value: required_str(g, "value")?,
initial_value: required_str(g, "initialValue")?,
backing_night: required_str(g, "backingNight")?,
ctime: required_i64(g, "ctime")?,
transaction_id: required_i64(g, "transactionId")?,
transaction_hash: required_str(g, "transactionHash")?,
collapsed_merkle_tree: optional_collapsed_update(g, "collapsedMerkleTree")?,
};
return Ok(crate::DustGenerationsTickRaw {
kind,
item: Some(item),
dtime_update: None,
progress: None,
});
}
if kind == "DustGenerationDtimeUpdateItem" {
let dtime_update = crate::DustGenerationDtimeUpdateRaw {
generation_mt_index: required_i64(g, "generationMtIndex")?,
owner: required_str(g, "owner")?,
night_utxo_hash: required_str(g, "nightUtxoHash")?,
new_dtime: required_i64(g, "newDtime")?,
transaction_id: required_i64(g, "transactionId")?,
transaction_hash: required_str(g, "transactionHash")?,
tree_insertion_path: required_str(g, "treeInsertionPath")?,
};
return Ok(crate::DustGenerationsTickRaw {
kind,
item: None,
dtime_update: Some(dtime_update),
progress: None,
});
}
Err(SubscriptionError::MalformedMessage(format!(
"unknown dustGenerations __typename `{kind}`"
)))
}
pub async fn subscribe_dust_nullifier_transactions(
http_url: &str,
nullifier_prefixes_hex: &[String],
from_block: Option<i64>,
to_block: Option<i64>,
) -> Result<DustNullifierStream, SubscriptionError> {
const QUERY: &str = r"
subscription DustNullifierTxSub(
$prefixes: [HexEncoded!]!, $from: Int, $to: Int
) {
dustNullifierTransactions(
nullifierLeBytesPrefixes: $prefixes, fromBlock: $from, toBlock: $to
) {
nullifierLeBytes
commitmentLeBytes
transactionId
transactionHash
blockHeight
blockHash
}
}
";
let ws_url = graphql_ws_url(http_url);
let variables = json!({
"prefixes": nullifier_prefixes_hex,
"from": from_block,
"to": to_block,
});
let inner = run_subscription(&ws_url, QUERY, variables).await?;
Ok(DustNullifierStream { inner })
}
pub struct DustNullifierStream {
inner: SubscriptionStream,
}
impl Stream for DustNullifierStream {
type Item = Result<crate::DustNullifierMatchRaw, SubscriptionError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use std::task::Poll;
let item = match std::pin::Pin::new(&mut self.inner).poll_next(cx) {
Poll::Ready(Some(Ok(item))) => item,
Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
Poll::Ready(None) => return Poll::Ready(None),
Poll::Pending => return Poll::Pending,
};
match item {
SubscriptionItem::Complete => Poll::Ready(None),
SubscriptionItem::Next(data) => Poll::Ready(Some(parse_dust_nullifier_match(&data))),
}
}
}
fn parse_dust_nullifier_match(
data: &Value,
) -> Result<crate::DustNullifierMatchRaw, SubscriptionError> {
let m = data.get("dustNullifierTransactions").ok_or_else(|| {
SubscriptionError::MalformedMessage(
"next payload missing `dustNullifierTransactions` field".to_owned(),
)
})?;
Ok(crate::DustNullifierMatchRaw {
nullifier_le_bytes: required_str(m, "nullifierLeBytes")?,
commitment_le_bytes: required_str(m, "commitmentLeBytes")?,
transaction_id: required_i64(m, "transactionId")?,
transaction_hash: required_str(m, "transactionHash")?,
block_hash: required_str(m, "blockHash")?,
block_height: required_i64(m, "blockHeight")?,
})
}
pub async fn subscribe_shielded_nullifier_transactions(
http_url: &str,
nullifier_prefixes_hex: &[String],
from_block: Option<i64>,
to_block: Option<i64>,
) -> Result<ShieldedNullifierStream, SubscriptionError> {
const QUERY: &str = r"
subscription ShieldedNullifierTxSub(
$prefixes: [HexEncoded!]!, $from: Int, $to: Int
) {
shieldedNullifierTransactions(
nullifierPrefixes: $prefixes, fromBlock: $from, toBlock: $to
) {
nullifier
transactionId
blockHeight
blockHash
}
}
";
let ws_url = graphql_ws_url(http_url);
let variables = json!({
"prefixes": nullifier_prefixes_hex,
"from": from_block,
"to": to_block,
});
let inner = run_subscription(&ws_url, QUERY, variables).await?;
Ok(ShieldedNullifierStream { inner })
}
pub struct ShieldedNullifierStream {
inner: SubscriptionStream,
}
impl Stream for ShieldedNullifierStream {
type Item = Result<crate::ShieldedNullifierMatchRaw, SubscriptionError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use std::task::Poll;
let item = match std::pin::Pin::new(&mut self.inner).poll_next(cx) {
Poll::Ready(Some(Ok(item))) => item,
Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
Poll::Ready(None) => return Poll::Ready(None),
Poll::Pending => return Poll::Pending,
};
match item {
SubscriptionItem::Complete => Poll::Ready(None),
SubscriptionItem::Next(data) => {
Poll::Ready(Some(parse_shielded_nullifier_match(&data)))
}
}
}
}
fn parse_shielded_nullifier_match(
data: &Value,
) -> Result<crate::ShieldedNullifierMatchRaw, SubscriptionError> {
let m = data.get("shieldedNullifierTransactions").ok_or_else(|| {
SubscriptionError::MalformedMessage(
"next payload missing `shieldedNullifierTransactions` field".to_owned(),
)
})?;
Ok(crate::ShieldedNullifierMatchRaw {
nullifier: required_str(m, "nullifier")?,
transaction_id: required_i64(m, "transactionId")?,
block_hash: required_str(m, "blockHash")?,
block_height: required_i64(m, "blockHeight")?,
})
}
fn required_str(obj: &Value, field: &str) -> Result<String, SubscriptionError> {
obj.get(field)
.and_then(|v| v.as_str())
.map(ToOwned::to_owned)
.ok_or_else(|| {
SubscriptionError::MalformedMessage(format!("missing string field `{field}`"))
})
}
fn required_i64(obj: &Value, field: &str) -> Result<i64, SubscriptionError> {
obj.get(field)
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| SubscriptionError::MalformedMessage(format!("missing i64 field `{field}`")))
}
fn optional_collapsed_update(
obj: &Value,
field: &str,
) -> Result<Option<crate::MerkleTreeCollapsedUpdate>, SubscriptionError> {
match obj.get(field) {
None | Some(Value::Null) => Ok(None),
Some(v) => Ok(Some(parse_collapsed_update(v)?)),
}
}
fn parse_dust_ledger_event(data: &Value) -> Result<crate::DustLedgerEventRaw, SubscriptionError> {
let ev = data.get("dustLedgerEvents").ok_or_else(|| {
SubscriptionError::MalformedMessage(
"next payload missing `dustLedgerEvents` field".to_owned(),
)
})?;
let kind = ev
.get("__typename")
.and_then(|v| v.as_str())
.unwrap_or("UnknownDustLedgerEvent")
.to_owned();
let id = ev
.get("id")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| SubscriptionError::MalformedMessage("event missing id".to_owned()))?;
let raw = ev
.get("raw")
.and_then(|v| v.as_str())
.ok_or_else(|| SubscriptionError::MalformedMessage("event missing raw".to_owned()))?
.to_owned();
let max_id = ev
.get("maxId")
.and_then(serde_json::Value::as_i64)
.ok_or_else(|| SubscriptionError::MalformedMessage("event missing maxId".to_owned()))?;
Ok(crate::DustLedgerEventRaw {
kind,
id,
raw,
max_id,
})
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use futures_util::SinkExt;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::tungstenite::protocol::Message;
use super::*;
struct SelectsGraphqlTransportWs;
impl tokio_tungstenite::tungstenite::handshake::server::Callback for SelectsGraphqlTransportWs {
fn on_request(
self,
_: &tokio_tungstenite::tungstenite::handshake::server::Request,
mut response: tokio_tungstenite::tungstenite::handshake::server::Response,
) -> Result<
tokio_tungstenite::tungstenite::handshake::server::Response,
tokio_tungstenite::tungstenite::handshake::server::ErrorResponse,
> {
response.headers_mut().insert(
"Sec-WebSocket-Protocol",
HeaderValue::from_static(WS_PROTOCOL),
);
Ok(response)
}
}
async fn quiet_server(answer_pings: bool) -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
let (tcp, _) = listener.accept().await.unwrap();
let mut ws = tokio_tungstenite::accept_hdr_async(tcp, SelectsGraphqlTransportWs)
.await
.unwrap();
while let Some(Ok(msg)) = ws.next().await {
let Message::Text(text) = msg else { continue };
let kind = serde_json::from_str::<Value>(&text).unwrap()["type"].clone();
let reply = match kind.as_str() {
Some("connection_init") => json!({ "type": "connection_ack" }),
Some("ping") if answer_pings => json!({ "type": "pong" }),
_ => continue,
};
ws.send(Message::Text(reply.to_string().into()))
.await
.unwrap();
}
});
format!("ws://{addr}")
}
#[tokio::test]
async fn a_silent_connection_fails_after_an_unanswered_ping() {
let url = quiet_server(false).await;
let keepalive = Duration::from_millis(100);
let mut stream =
run_subscription_with_keepalive(&url, "subscription { x }", json!({}), keepalive)
.await
.unwrap();
let next = tokio::time::timeout(Duration::from_secs(5), stream.next())
.await
.unwrap();
assert!(
matches!(next, Some(Err(SubscriptionError::KeepaliveTimeout(_)))),
"{next:?}"
);
}
#[tokio::test]
async fn an_answered_ping_keeps_a_quiet_subscription_open() {
let url = quiet_server(true).await;
let keepalive = Duration::from_millis(100);
let mut stream =
run_subscription_with_keepalive(&url, "subscription { x }", json!({}), keepalive)
.await
.unwrap();
let next = tokio::time::timeout(Duration::from_millis(800), stream.next()).await;
assert!(
next.is_err(),
"the stream stayed open with nothing to deliver: {next:?}"
);
}
fn timeline() -> Vec<(i64, u32)> {
let mut events: Vec<(i64, u32)> = (0..40).step_by(3).map(|id| (id, 1_000_400)).collect();
events.extend((40..90).step_by(7).map(|id| (id, 2_001_100)));
events
}
fn probe_on(
events: &[(i64, u32)],
) -> impl FnMut(Option<i64>) -> std::future::Ready<Result<DustEventPosition, SubscriptionError>> + '_
{
let max_id = events.last().unwrap().0;
move |from| {
let from = from.unwrap_or(0);
let found =
events
.iter()
.find(|(id, _)| *id >= from)
.map(|&(id, pv)| DustEventPosition {
id,
protocol_version: pv,
max_id,
});
std::future::ready(
found.ok_or_else(|| SubscriptionError::MalformedMessage("past the end".into())),
)
}
}
#[tokio::test]
async fn the_boundary_is_the_first_event_past_it() {
let events = timeline();
let start = search_dust_boundary(2_000_000, probe_on(&events))
.await
.unwrap();
assert_eq!(start, Some(40));
}
#[tokio::test]
async fn a_chain_born_past_the_boundary_starts_at_the_beginning() {
let events: Vec<(i64, u32)> = (0..20).map(|id| (id, 2_001_100)).collect();
assert_eq!(
search_dust_boundary(2_000_000, probe_on(&events))
.await
.unwrap(),
None
);
}
#[tokio::test]
async fn a_chain_not_yet_past_the_boundary_has_no_start() {
let events: Vec<(i64, u32)> = (0..20).map(|id| (id, 1_000_400)).collect();
assert_eq!(
search_dust_boundary(2_000_000, probe_on(&events))
.await
.unwrap(),
None
);
}
#[tokio::test]
async fn every_crossing_point_is_found() {
for cross in 1..30 {
let events: Vec<(i64, u32)> = (0..30)
.map(|id| (id * 2, if id >= cross { 2_001_100 } else { 1_000_400 }))
.collect();
let start = search_dust_boundary(2_000_000, probe_on(&events))
.await
.unwrap();
assert_eq!(start, Some(cross * 2), "crossing at event {cross}");
}
}
fn zlib(bytes: &[u8]) -> Vec<u8> {
use std::io::Write;
let mut enc = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
enc.write_all(bytes).unwrap();
enc.finish().unwrap()
}
#[test]
fn a_binary_frame_inflates_under_deflate() {
let json = r#"{"type":"next","id":"1","payload":{"data":{}}}"#;
let msg = Incoming::Binary(zlib(json.as_bytes()));
match frame_text(msg, true).unwrap() {
Frame::Text(t) => assert_eq!(t, json),
_ => panic!("expected a text message"),
}
}
#[test]
fn a_binary_frame_is_ignored_without_deflate() {
let msg = Incoming::Binary(zlib(b"{}"));
assert!(matches!(frame_text(msg, false).unwrap(), Frame::Control));
}
#[test]
fn small_messages_stay_text_under_deflate() {
let msg = Incoming::Text(r#"{"type":"ping"}"#.to_owned());
assert!(matches!(frame_text(msg, true).unwrap(), Frame::Text(_)));
}
#[test]
fn an_inflation_past_the_cap_is_refused() {
let bomb = zlib(&vec![
b' ';
usize::try_from(MAX_INFLATED_BYTES).unwrap() + 1
]);
assert!(matches!(
inflate_message(&bomb),
Err(SubscriptionError::PayloadTooLarge)
));
}
#[test]
fn garbage_is_a_malformed_message() {
assert!(matches!(
inflate_message(b"not zlib"),
Err(SubscriptionError::MalformedMessage(_))
));
}
#[test]
fn http_to_ws_url_keeps_path() {
assert_eq!(
graphql_ws_url("http://127.0.0.1:8088/api/v4/graphql"),
"ws://127.0.0.1:8088/api/v4/graphql/ws"
);
assert_eq!(
graphql_ws_url("https://indexer.example.com/api/v4/graphql"),
"wss://indexer.example.com/api/v4/graphql/ws"
);
}
#[test]
fn blockfrost_url_keeps_its_project_id() {
assert_eq!(
graphql_ws_url(
"https://midnight-preprod.blockfrost.io/api/v0?project_id=nightpreprodX"
),
"wss://midnight-preprod.blockfrost.io/api/v0/ws?project_id=nightpreprodX"
);
}
#[test]
fn a_bare_host_gets_the_self_hosted_path() {
assert_eq!(
graphql_ws_url("http://127.0.0.1:8088"),
"ws://127.0.0.1:8088/api/v4/graphql/ws"
);
}
#[test]
fn trailing_slash_does_not_double() {
assert_eq!(
graphql_ws_url("http://127.0.0.1:8088/api/v4/graphql/"),
"ws://127.0.0.1:8088/api/v4/graphql/ws"
);
}
#[test]
fn already_ws_url_round_trips() {
let u = "ws://127.0.0.1:8088/api/v4/graphql/ws";
assert_eq!(graphql_ws_url(u), u);
}
#[test]
fn parse_next_extracts_data() {
let m = parse_server_message(r#"{"id":"1","type":"next","payload":{"data":{"x":42}}}"#)
.unwrap();
match m {
ServerMessage::Next { id, data } => {
assert_eq!(id, "1");
assert_eq!(data["x"], 42);
}
other => panic!("wrong variant: {other:?}"),
}
}
#[test]
fn parse_next_promotes_errors_inside_payload() {
let err = parse_server_message(
r#"{"id":"1","type":"next","payload":{"errors":[{"message":"oops"}]}}"#,
)
.unwrap_err();
assert!(matches!(err, SubscriptionError::ServerError(_)));
}
#[test]
fn parse_ping_and_pong() {
assert!(matches!(
parse_server_message(r#"{"type":"ping"}"#).unwrap(),
ServerMessage::Ping
));
assert!(matches!(
parse_server_message(r#"{"type":"pong"}"#).unwrap(),
ServerMessage::Pong
));
}
#[test]
fn parse_unknown_type_is_other() {
assert!(matches!(
parse_server_message(r#"{"type":"vendor-extension"}"#).unwrap(),
ServerMessage::Other
));
}
#[test]
fn parse_unshielded_progress_event() {
let data: Value = serde_json::from_str(
r#"{"unshieldedTransactions":{
"__typename":"UnshieldedTransactionsProgress",
"highestTransactionId":42
}}"#,
)
.unwrap();
let ev = parse_unshielded_tx_event(&data).unwrap();
assert!(ev.is_progress());
assert_eq!(ev.highest_transaction_id, Some(42));
assert_eq!(ev.created_utxos, Vec::<crate::UnshieldedUtxoRaw>::new());
assert_eq!(ev.spent_utxos, Vec::<crate::UnshieldedUtxoRaw>::new());
assert!(ev.transaction_id.is_none());
}
#[test]
fn parse_unshielded_transaction_event_regular_success() {
let data: Value = serde_json::from_str(
r#"{"unshieldedTransactions":{
"__typename":"UnshieldedTransaction",
"createdUtxos":[{
"owner":"mn_addr_undeployed1x",
"tokenType":"0000000000000000000000000000000000000000000000000000000000000000",
"value":"1000",
"intentHash":"aabb",
"outputIndex":0,
"ctime":1700000000,
"initialNonce":"cc",
"registeredForDustGeneration":false
}],
"spentUtxos":[],
"transaction":{
"__typename":"RegularTransaction",
"id":99,
"hash":"deadbeef",
"block":{"hash":"01","height":7,"timestamp":1700000000000},
"transactionResult":{"status":"SUCCESS"}
}
}}"#,
)
.unwrap();
let ev = parse_unshielded_tx_event(&data).unwrap();
assert!(ev.is_transaction());
assert_eq!(ev.transaction_id, Some(99));
assert_eq!(ev.transaction_hash.as_deref(), Some("deadbeef"));
assert_eq!(ev.status.as_deref(), Some("SUCCESS"));
assert_eq!(ev.block.as_ref().unwrap().height, 7);
assert_eq!(ev.block_time_secs, Some(1_700_000_000));
assert_eq!(ev.created_utxos.len(), 1);
assert_eq!(ev.created_utxos[0].value, "1000");
assert_eq!(ev.created_utxos[0].output_index, 0);
}
#[test]
fn parse_unshielded_transaction_event_system_tx_defaults_to_success() {
let data: Value = serde_json::from_str(
r#"{"unshieldedTransactions":{
"__typename":"UnshieldedTransaction",
"createdUtxos":[],
"spentUtxos":[],
"transaction":{
"__typename":"SystemTransaction",
"id":1,
"hash":"00",
"block":{"hash":"0a","height":0,"timestamp":0}
}
}}"#,
)
.unwrap();
let ev = parse_unshielded_tx_event(&data).unwrap();
assert_eq!(ev.status.as_deref(), Some("SUCCESS"));
}
#[test]
fn parse_unshielded_transaction_event_regular_failure() {
let data: Value = serde_json::from_str(
r#"{"unshieldedTransactions":{
"__typename":"UnshieldedTransaction",
"createdUtxos":[],
"spentUtxos":[{
"owner":"mn_addr_undeployed1x",
"tokenType":"00",
"value":"1",
"intentHash":"ab",
"outputIndex":0,
"ctime":null,
"initialNonce":"cd",
"registeredForDustGeneration":true
}],
"transaction":{
"__typename":"RegularTransaction",
"id":3,
"hash":"ff",
"block":{"hash":"0b","height":1,"timestamp":1000},
"transactionResult":{"status":"FAILURE"}
}
}}"#,
)
.unwrap();
let ev = parse_unshielded_tx_event(&data).unwrap();
assert_eq!(ev.status.as_deref(), Some("FAILURE"));
assert_eq!(ev.spent_utxos.len(), 1);
assert!(ev.spent_utxos[0].ctime.is_none());
assert!(ev.spent_utxos[0].registered_for_dust_generation);
}
#[test]
fn parse_shielded_progress_event() {
let data: Value = serde_json::from_str(
r#"{"shieldedTransactions":{
"__typename":"ShieldedTransactionsProgress",
"highestEndIndex":100,
"highestCheckedEndIndex":90,
"highestRelevantEndIndex":42
}}"#,
)
.unwrap();
let ev = parse_shielded_tx_event(&data).unwrap();
assert!(ev.is_progress());
assert_eq!(ev.highest_zswap_end_index, Some(100));
assert_eq!(ev.highest_checked_zswap_end_index, Some(90));
assert_eq!(ev.highest_relevant_zswap_end_index, Some(42));
assert_eq!(
ev.zswap_ledger_events,
Vec::<crate::ZswapLedgerEventRaw>::new()
);
assert!(ev.transaction_id.is_none());
}
#[test]
fn parse_shielded_relevant_transaction_event() {
let data: Value = serde_json::from_str(
r#"{"shieldedTransactions":{
"__typename":"RelevantTransaction",
"transaction":{
"id":5,
"hash":"aabb",
"endIndex":17,
"transactionResult":{"status":"SUCCESS"},
"block":{"hash":"0a","height":1,"timestamp":1700000000000},
"zswapLedgerEvents":[
{"id":1,"raw":"deadbeef","maxId":1},
{"id":2,"raw":"cafe","maxId":2}
]
},
"collapsedMerkleTree":null
}}"#,
)
.unwrap();
let ev = parse_shielded_tx_event(&data).unwrap();
assert!(ev.is_transaction());
assert_eq!(ev.transaction_id, Some(5));
assert_eq!(ev.transaction_hash.as_deref(), Some("aabb"));
assert_eq!(ev.status.as_deref(), Some("SUCCESS"));
assert_eq!(ev.zswap_end_index, Some(17));
assert_eq!(ev.block.as_ref().unwrap().height, 1);
assert_eq!(ev.block_time_secs, Some(1_700_000_000));
assert_eq!(ev.zswap_ledger_events.len(), 2);
assert_eq!(ev.zswap_ledger_events[0].raw, "deadbeef");
assert!(ev.zswap_collapsed_update.is_none());
}
#[test]
fn parse_shielded_relevant_tx_with_collapsed_update() {
let data: Value = serde_json::from_str(
r#"{"shieldedTransactions":{
"__typename":"RelevantTransaction",
"transaction":{
"id":10,
"hash":"ff",
"endIndex":50,
"transactionResult":{"status":"SUCCESS"},
"block":{"hash":"0b","height":2,"timestamp":1000},
"zswapLedgerEvents":[]
},
"collapsedMerkleTree":{
"startIndex":40,
"endIndex":48,
"update":"c0ffee",
"protocolVersion":1
}
}}"#,
)
.unwrap();
let ev = parse_shielded_tx_event(&data).unwrap();
let upd = ev.zswap_collapsed_update.expect("collapsed update present");
assert_eq!(upd.start_index, 40);
assert_eq!(upd.end_index, 48);
assert_eq!(upd.update, "c0ffee");
assert_eq!(upd.protocol_version, 1);
}
#[test]
fn parse_shielded_relevant_tx_with_failure_status() {
let data: Value = serde_json::from_str(
r#"{"shieldedTransactions":{
"__typename":"RelevantTransaction",
"transaction":{
"id":11,
"hash":"99",
"endIndex":60,
"transactionResult":{"status":"FAILURE"},
"block":{"hash":"0c","height":3,"timestamp":2000},
"zswapLedgerEvents":[]
}
}}"#,
)
.unwrap();
let ev = parse_shielded_tx_event(&data).unwrap();
assert_eq!(ev.status.as_deref(), Some("FAILURE"));
}
#[test]
fn parse_shielded_malformed_missing_zswap_end_index() {
let data: Value = serde_json::from_str(
r#"{"shieldedTransactions":{
"__typename":"RelevantTransaction",
"transaction":{
"id":1,
"hash":"00",
"transactionResult":{"status":"SUCCESS"},
"block":{"hash":"00","height":0,"timestamp":0},
"zswapLedgerEvents":[]
}
}}"#,
)
.unwrap();
let err = parse_shielded_tx_event(&data).unwrap_err();
assert!(matches!(err, SubscriptionError::MalformedMessage(_)));
}
#[test]
fn parse_unshielded_malformed_missing_field_errors() {
let data: Value = serde_json::from_str(
r#"{"unshieldedTransactions":{
"__typename":"UnshieldedTransaction"
}}"#,
)
.unwrap();
let err = parse_unshielded_tx_event(&data).unwrap_err();
assert!(matches!(err, SubscriptionError::MalformedMessage(_)));
}
#[test]
fn parse_block_tick_round_trips() {
let data: Value = serde_json::from_str(
r#"{"blocks":{
"hash":"aabb",
"height":12,
"protocolVersion":3,
"timestamp":1700000000000,
"author":"cafe",
"zswapMerkleTreeRoot":"0011",
"ledgerParameters":"2233",
"parent":{"hash":"dead","height":11},
"transactions":[
{"__typename":"RegularTransaction","id":1,"hash":"ee"},
{"__typename":"SystemTransaction","id":2,"hash":"ff"}
]
}}"#,
)
.unwrap();
let ev = parse_block_tick(&data).unwrap();
assert_eq!(ev.hash, "aabb");
assert_eq!(ev.height, 12);
assert_eq!(ev.protocol_version, 3);
assert_eq!(ev.timestamp_ms, 1_700_000_000_000);
assert_eq!(ev.author.as_deref(), Some("cafe"));
assert_eq!(ev.parent_hash.as_deref(), Some("dead"));
assert_eq!(ev.parent_height, Some(11));
assert_eq!(ev.transactions.len(), 2);
assert!(matches!(
ev.transactions[0].kind,
crate::TransactionKind::Regular
));
assert!(matches!(
ev.transactions[1].kind,
crate::TransactionKind::System
));
}
#[test]
fn parse_block_tick_tolerates_null_parent_and_author() {
let data: Value = serde_json::from_str(
r#"{"blocks":{
"hash":"00",
"height":0,
"protocolVersion":1,
"timestamp":0,
"author":null,
"zswapMerkleTreeRoot":"",
"ledgerParameters":"",
"parent":null,
"transactions":[]
}}"#,
)
.unwrap();
let ev = parse_block_tick(&data).unwrap();
assert!(ev.author.is_none());
assert!(ev.parent_hash.is_none());
assert!(ev.parent_height.is_none());
assert_eq!(
ev.transactions,
Vec::<crate::BlockTickTransactionRef>::new()
);
}
#[test]
fn parse_block_tick_malformed_missing_hash_errors() {
let data: Value = serde_json::from_str(
r#"{"blocks":{"height":1,"protocolVersion":1,"timestamp":0,
"zswapMerkleTreeRoot":"","ledgerParameters":""}}"#,
)
.unwrap();
let err = parse_block_tick(&data).unwrap_err();
assert!(matches!(err, SubscriptionError::MalformedMessage(_)));
}
#[test]
fn parse_contract_deploy_action() {
let data: Value = serde_json::from_str(
r#"{"contractActions":{
"__typename":"ContractDeploy",
"address":"deadbeef",
"state":"01",
"zswapState":"02",
"unshieldedBalances":[],
"transaction":{
"__typename":"RegularTransaction",
"id":7,
"hash":"aa",
"block":{"hash":"bb","height":3,"timestamp":0}
}
}}"#,
)
.unwrap();
let ev = parse_contract_action_tick(&data).unwrap();
assert!(matches!(ev.kind, crate::ContractActionKind::Deploy));
assert_eq!(ev.address, "deadbeef");
assert!(ev.entry_point.is_none());
assert_eq!(ev.transaction_id, 7);
assert_eq!(ev.block.height, 3);
}
#[test]
fn parse_contract_call_action_carries_entry_point() {
let data: Value = serde_json::from_str(
r#"{"contractActions":{
"__typename":"ContractCall",
"address":"dd",
"state":"01",
"zswapState":"02",
"entryPoint":"transfer",
"unshieldedBalances":[
{"tokenType":"ab","amount":"100"}
],
"transaction":{
"__typename":"RegularTransaction",
"id":9,
"hash":"ff",
"block":{"hash":"cc","height":4,"timestamp":0}
}
}}"#,
)
.unwrap();
let ev = parse_contract_action_tick(&data).unwrap();
assert!(matches!(ev.kind, crate::ContractActionKind::Call));
assert_eq!(ev.entry_point.as_deref(), Some("transfer"));
assert_eq!(ev.unshielded_balances.len(), 1);
assert_eq!(ev.unshielded_balances[0].amount, "100");
}
#[test]
fn parse_contract_action_unknown_typename_errors() {
let data: Value = serde_json::from_str(
r#"{"contractActions":{
"__typename":"NotARealVariant",
"address":"aa",
"state":"01",
"zswapState":"02",
"unshieldedBalances":[],
"transaction":{
"__typename":"RegularTransaction",
"id":1,"hash":"aa","block":{"hash":"bb","height":0,"timestamp":0}
}
}}"#,
)
.unwrap();
let err = parse_contract_action_tick(&data).unwrap_err();
assert!(matches!(err, SubscriptionError::MalformedMessage(_)));
}
#[test]
fn parse_zswap_ledger_event_round_trips() {
let data: Value = serde_json::from_str(
r#"{"zswapLedgerEvents":{
"id":42,
"raw":"aabb",
"maxId":100
}}"#,
)
.unwrap();
let ev = parse_zswap_ledger_event(&data).unwrap();
assert_eq!(ev.id, 42);
assert_eq!(ev.raw, "aabb");
assert_eq!(ev.max_id, 100);
}
#[test]
fn parse_zswap_ledger_event_malformed_errors() {
let data: Value = serde_json::from_str(r#"{"zswapLedgerEvents":{"id":1}}"#).unwrap();
let err = parse_zswap_ledger_event(&data).unwrap_err();
assert!(matches!(err, SubscriptionError::MalformedMessage(_)));
}
#[test]
fn parse_dust_generations_item() {
let data: Value = serde_json::from_str(
r#"{"dustGenerations":{
"__typename":"DustGenerationsItem",
"commitmentMtIndex":5,
"generationMtIndex":7,
"owner":"aabb",
"value":"1000",
"initialValue":"500",
"backingNight":"cc",
"ctime":1700000000,
"transactionId":99,
"transactionHash":"ee",
"collapsedMerkleTree":{
"startIndex":0,"endIndex":5,"update":"dd","protocolVersion":3
}
}}"#,
)
.unwrap();
let ev = parse_dust_generations_tick(&data).unwrap();
assert!(ev.is_item());
assert!(!ev.is_progress());
let item = ev.item.unwrap();
assert_eq!(item.commitment_mt_index, 5);
assert_eq!(item.generation_mt_index, 7);
assert_eq!(item.value, "1000");
assert_eq!(item.transaction_id, 99);
assert_eq!(item.transaction_hash, "ee");
let cu = item.collapsed_merkle_tree.unwrap();
assert_eq!(cu.start_index, 0);
assert_eq!(cu.end_index, 5);
}
#[test]
fn parse_dust_generations_progress_no_collapsed_update() {
let data: Value = serde_json::from_str(
r#"{"dustGenerations":{
"__typename":"DustGenerationsProgress",
"highestIndex":17,
"collapsedMerkleTree":null
}}"#,
)
.unwrap();
let ev = parse_dust_generations_tick(&data).unwrap();
assert!(ev.is_progress());
let p = ev.progress.unwrap();
assert_eq!(p.highest_index, 17);
assert!(p.collapsed_merkle_tree.is_none());
}
#[test]
fn parse_dust_generations_unknown_typename_errors() {
let data: Value =
serde_json::from_str(r#"{"dustGenerations":{"__typename":"SomethingElse"}}"#).unwrap();
let err = parse_dust_generations_tick(&data).unwrap_err();
assert!(matches!(err, SubscriptionError::MalformedMessage(_)));
}
#[test]
fn parse_dust_nullifier_match_round_trips() {
let data: Value = serde_json::from_str(
r#"{"dustNullifierTransactions":{
"nullifierLeBytes":"aa",
"commitmentLeBytes":"bb",
"transactionId":33,
"transactionHash":"dd",
"blockHeight":5,
"blockHash":"cc"
}}"#,
)
.unwrap();
let ev = parse_dust_nullifier_match(&data).unwrap();
assert_eq!(ev.nullifier_le_bytes, "aa");
assert_eq!(ev.commitment_le_bytes, "bb");
assert_eq!(ev.transaction_id, 33);
assert_eq!(ev.transaction_hash, "dd");
assert_eq!(ev.block_height, 5);
assert_eq!(ev.block_hash, "cc");
}
#[test]
fn parse_shielded_nullifier_match_round_trips() {
let data: Value = serde_json::from_str(
r#"{"shieldedNullifierTransactions":{
"nullifier":"aa",
"transactionId":7,
"blockHeight":9,
"blockHash":"cc"
}}"#,
)
.unwrap();
let ev = parse_shielded_nullifier_match(&data).unwrap();
assert_eq!(ev.nullifier, "aa");
assert_eq!(ev.transaction_id, 7);
assert_eq!(ev.block_height, 9);
assert_eq!(ev.block_hash, "cc");
}
}