use futures_util::StreamExt;
use serde_json::{json, Value};
use crate::subscription::{graphql_ws_url, run_subscription, SubscriptionError, SubscriptionItem};
use crate::IndexerError;
pub const CONTRACT_EVENT_FIELDS: &str = r"
__typename
id
raw
maxId
protocolVersion
version
contractAddress
transactionId
... on ShieldedSpendEvent { nullifier }
... on ShieldedReceiveEvent { commitment ciphertext receivingContractAddress }
... on ShieldedMintEvent { commitment domainSep amount }
... on ShieldedBurnEvent { nullifier amount }
... on UnshieldedSpendEvent {
sender { kind userAddress contractAddress } domainSep tokenType amount
}
... on UnshieldedReceiveEvent {
recipient { kind userAddress contractAddress } domainSep tokenType amount
}
... on UnshieldedMintEvent { domainSep tokenType amount }
... on UnshieldedBurnEvent { sender { kind userAddress contractAddress } tokenType amount }
";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ContractEventType {
ShieldedSpend,
ShieldedReceive,
ShieldedMint,
ShieldedBurn,
UnshieldedSpend,
UnshieldedReceive,
UnshieldedMint,
UnshieldedBurn,
Paused,
Unpaused,
Misc,
}
impl ContractEventType {
#[must_use]
pub const fn as_graphql(self) -> &'static str {
match self {
Self::ShieldedSpend => "SHIELDED_SPEND",
Self::ShieldedReceive => "SHIELDED_RECEIVE",
Self::ShieldedMint => "SHIELDED_MINT",
Self::ShieldedBurn => "SHIELDED_BURN",
Self::UnshieldedSpend => "UNSHIELDED_SPEND",
Self::UnshieldedReceive => "UNSHIELDED_RECEIVE",
Self::UnshieldedMint => "UNSHIELDED_MINT",
Self::UnshieldedBurn => "UNSHIELDED_BURN",
Self::Paused => "PAUSED",
Self::Unpaused => "UNPAUSED",
Self::Misc => "MISC",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventAddress {
User(String),
Contract(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContractEventKind {
ShieldedSpend {
nullifier: String,
},
ShieldedReceive {
commitment: String,
ciphertext: Option<String>,
receiving_contract_address: Option<String>,
},
ShieldedMint {
commitment: String,
domain_sep: String,
amount: Option<String>,
},
ShieldedBurn {
nullifier: String,
amount: Option<String>,
},
UnshieldedSpend {
sender: EventAddress,
domain_sep: String,
token_type: String,
amount: String,
},
UnshieldedReceive {
recipient: EventAddress,
domain_sep: String,
token_type: String,
amount: String,
},
UnshieldedMint {
domain_sep: String,
token_type: String,
amount: String,
},
UnshieldedBurn {
sender: EventAddress,
token_type: String,
amount: String,
},
Paused,
Unpaused,
Misc,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContractEvent {
pub id: u64,
pub max_id: u64,
pub payload_version: u32,
pub protocol_version: u32,
pub contract_address: String,
pub transaction_id: u64,
pub raw: String,
pub kind: ContractEventKind,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ContractEventFilter {
pub contract_address: String,
pub types: Option<Vec<ContractEventType>>,
pub field_prefixes: Vec<(String, String)>,
pub from_block: Option<u64>,
pub to_block: Option<u64>,
pub transaction_hash: Option<String>,
}
impl ContractEventFilter {
#[must_use]
pub fn to_graphql(&self) -> Value {
let mut filter = json!({ "contractAddress": self.contract_address });
if let Some(types) = &self.types {
filter["types"] = types.iter().map(|t| t.as_graphql()).collect();
}
if !self.field_prefixes.is_empty() {
filter["fieldPrefixes"] = self
.field_prefixes
.iter()
.map(|(field, prefix)| json!({ "fieldName": field, "prefix": prefix }))
.collect();
}
if let Some(h) = self.from_block {
filter["fromBlock"] = json!(h);
}
if let Some(h) = self.to_block {
filter["toBlock"] = json!(h);
}
if let Some(hash) = &self.transaction_hash {
filter["transactionHash"] = json!(hash);
}
filter
}
}
fn shape(msg: impl Into<String>) -> IndexerError {
IndexerError::InvalidResponse(msg.into())
}
fn text(v: &Value, field: &str) -> Result<String, IndexerError> {
v.get(field)
.and_then(Value::as_str)
.map(ToOwned::to_owned)
.ok_or_else(|| {
shape(format!(
"contract event field `{field}` missing or not a string"
))
})
}
fn optional_text(v: &Value, field: &str) -> Option<String> {
v.get(field).and_then(Value::as_str).map(ToOwned::to_owned)
}
fn number(v: &Value, field: &str) -> Result<u64, IndexerError> {
v.get(field).and_then(Value::as_u64).ok_or_else(|| {
shape(format!(
"contract event field `{field}` missing or not a count"
))
})
}
fn address(v: &Value, field: &str) -> Result<EventAddress, IndexerError> {
let a = v
.get(field)
.ok_or_else(|| shape(format!("contract event field `{field}` missing")))?;
match a.get("kind").and_then(Value::as_str) {
Some("USER") => Ok(EventAddress::User(text(a, "userAddress")?)),
Some("CONTRACT") => Ok(EventAddress::Contract(text(a, "contractAddress")?)),
other => Err(shape(format!("contract event `{field}.kind` is {other:?}"))),
}
}
pub fn parse_contract_event(v: &Value) -> Result<ContractEvent, IndexerError> {
let kind = match v.get("__typename").and_then(Value::as_str) {
Some("ShieldedSpendEvent") => ContractEventKind::ShieldedSpend {
nullifier: text(v, "nullifier")?,
},
Some("ShieldedReceiveEvent") => ContractEventKind::ShieldedReceive {
commitment: text(v, "commitment")?,
ciphertext: optional_text(v, "ciphertext"),
receiving_contract_address: optional_text(v, "receivingContractAddress"),
},
Some("ShieldedMintEvent") => ContractEventKind::ShieldedMint {
commitment: text(v, "commitment")?,
domain_sep: text(v, "domainSep")?,
amount: optional_text(v, "amount"),
},
Some("ShieldedBurnEvent") => ContractEventKind::ShieldedBurn {
nullifier: text(v, "nullifier")?,
amount: optional_text(v, "amount"),
},
Some("UnshieldedSpendEvent") => ContractEventKind::UnshieldedSpend {
sender: address(v, "sender")?,
domain_sep: text(v, "domainSep")?,
token_type: text(v, "tokenType")?,
amount: text(v, "amount")?,
},
Some("UnshieldedReceiveEvent") => ContractEventKind::UnshieldedReceive {
recipient: address(v, "recipient")?,
domain_sep: text(v, "domainSep")?,
token_type: text(v, "tokenType")?,
amount: text(v, "amount")?,
},
Some("UnshieldedMintEvent") => ContractEventKind::UnshieldedMint {
domain_sep: text(v, "domainSep")?,
token_type: text(v, "tokenType")?,
amount: text(v, "amount")?,
},
Some("UnshieldedBurnEvent") => ContractEventKind::UnshieldedBurn {
sender: address(v, "sender")?,
token_type: text(v, "tokenType")?,
amount: text(v, "amount")?,
},
Some("PausedEvent") => ContractEventKind::Paused,
Some("UnpausedEvent") => ContractEventKind::Unpaused,
Some("MiscContractEvent") => ContractEventKind::Misc,
other => return Err(shape(format!("unknown contract event type {other:?}"))),
};
Ok(ContractEvent {
id: number(v, "id")?,
max_id: number(v, "maxId")?,
payload_version: u32::try_from(number(v, "version")?)
.map_err(|_| shape("contract event `version` out of range"))?,
protocol_version: u32::try_from(number(v, "protocolVersion")?)
.map_err(|_| shape("contract event `protocolVersion` out of range"))?,
contract_address: text(v, "contractAddress")?,
transaction_id: number(v, "transactionId")?,
raw: text(v, "raw")?,
kind,
})
}
#[must_use]
pub fn contract_events_query() -> String {
format!(
"query ContractEvents($filter: ContractEventFilter!, $limit: Int, $offset: Int) {{
contractEvents(filter: $filter, limit: $limit, offset: $offset) {{ {CONTRACT_EVENT_FIELDS} }}
}}"
)
}
pub async fn subscribe_contract_events(
http_url: &str,
filter: &ContractEventFilter,
after_id: Option<u64>,
) -> Result<
impl futures_util::Stream<Item = Result<ContractEvent, SubscriptionError>>
+ moonproof_utils::rt::MaybeSend
+ use<>,
SubscriptionError,
> {
let query = format!(
"subscription ContractEventsSub($filter: ContractEventFilter!, $id: Int) {{
contractEvents(filter: $filter, id: $id) {{ {CONTRACT_EVENT_FIELDS} }}
}}"
);
let variables = json!({ "filter": filter.to_graphql(), "id": after_id });
let inner = run_subscription(&graphql_ws_url(http_url), &query, variables).await?;
Ok(inner.filter_map(|item| async move {
match item {
Ok(SubscriptionItem::Next(data)) => Some(
data.get("contractEvents")
.ok_or_else(|| {
SubscriptionError::MalformedMessage("next without `contractEvents`".into())
})
.and_then(|e| {
parse_contract_event(e)
.map_err(|err| SubscriptionError::MalformedMessage(err.to_string()))
}),
),
Ok(SubscriptionItem::Complete) => None,
Err(e) => Some(Err(e)),
}
}))
}
#[cfg(test)]
mod tests {
use super::*;
fn base(typename: &str) -> Value {
json!({
"__typename": typename, "id": 7, "maxId": 9, "raw": "ab", "version": 1,
"protocolVersion": 2_001_100, "contractAddress": "cc", "transactionId": 3,
})
}
#[test]
fn parses_an_unshielded_receive() {
let mut v = base("UnshieldedReceiveEvent");
v["recipient"] = json!({ "kind": "USER", "userAddress": "aa", "contractAddress": null });
v["domainSep"] = json!("d0");
v["tokenType"] = json!("00");
v["amount"] = json!("340282366920938463463374607431768211455");
let e = parse_contract_event(&v).unwrap();
assert_eq!(e.id, 7);
assert_eq!(e.protocol_version, 2_001_100);
assert_eq!(
e.kind,
ContractEventKind::UnshieldedReceive {
recipient: EventAddress::User("aa".into()),
domain_sep: "d0".into(),
token_type: "00".into(),
amount: "340282366920938463463374607431768211455".into(),
}
);
}
#[test]
fn parses_the_payload_free_events() {
assert_eq!(
parse_contract_event(&base("PausedEvent")).unwrap().kind,
ContractEventKind::Paused
);
assert_eq!(
parse_contract_event(&base("MiscContractEvent"))
.unwrap()
.kind,
ContractEventKind::Misc
);
}
#[test]
fn refuses_an_unknown_type_and_a_missing_field() {
assert!(parse_contract_event(&base("FutureEvent")).is_err());
assert!(parse_contract_event(&base("ShieldedSpendEvent")).is_err());
}
#[test]
fn filter_renders_only_what_is_set() {
let f = ContractEventFilter {
contract_address: "cc".into(),
types: Some(vec![ContractEventType::Paused, ContractEventType::Misc]),
to_block: Some(10),
..ContractEventFilter::default()
};
assert_eq!(
f.to_graphql(),
json!({ "contractAddress": "cc", "types": ["PAUSED", "MISC"], "toBlock": 10 })
);
}
}