1use futures_util::StreamExt;
9use serde_json::{json, Value};
10
11use crate::subscription::{graphql_ws_url, run_subscription, SubscriptionError, SubscriptionItem};
12use crate::IndexerError;
13
14pub const CONTRACT_EVENT_FIELDS: &str = r"
17 __typename
18 id
19 raw
20 maxId
21 protocolVersion
22 version
23 contractAddress
24 transactionId
25 ... on ShieldedSpendEvent { nullifier }
26 ... on ShieldedReceiveEvent { commitment ciphertext receivingContractAddress }
27 ... on ShieldedMintEvent { commitment domainSep amount }
28 ... on ShieldedBurnEvent { nullifier amount }
29 ... on UnshieldedSpendEvent {
30 sender { kind userAddress contractAddress } domainSep tokenType amount
31 }
32 ... on UnshieldedReceiveEvent {
33 recipient { kind userAddress contractAddress } domainSep tokenType amount
34 }
35 ... on UnshieldedMintEvent { domainSep tokenType amount }
36 ... on UnshieldedBurnEvent { sender { kind userAddress contractAddress } tokenType amount }
37";
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub enum ContractEventType {
42 ShieldedSpend,
43 ShieldedReceive,
44 ShieldedMint,
45 ShieldedBurn,
46 UnshieldedSpend,
47 UnshieldedReceive,
48 UnshieldedMint,
49 UnshieldedBurn,
50 Paused,
51 Unpaused,
52 Misc,
53}
54
55impl ContractEventType {
56 #[must_use]
58 pub const fn as_graphql(self) -> &'static str {
59 match self {
60 Self::ShieldedSpend => "SHIELDED_SPEND",
61 Self::ShieldedReceive => "SHIELDED_RECEIVE",
62 Self::ShieldedMint => "SHIELDED_MINT",
63 Self::ShieldedBurn => "SHIELDED_BURN",
64 Self::UnshieldedSpend => "UNSHIELDED_SPEND",
65 Self::UnshieldedReceive => "UNSHIELDED_RECEIVE",
66 Self::UnshieldedMint => "UNSHIELDED_MINT",
67 Self::UnshieldedBurn => "UNSHIELDED_BURN",
68 Self::Paused => "PAUSED",
69 Self::Unpaused => "UNPAUSED",
70 Self::Misc => "MISC",
71 }
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum EventAddress {
78 User(String),
79 Contract(String),
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum ContractEventKind {
87 ShieldedSpend {
88 nullifier: String,
89 },
90 ShieldedReceive {
91 commitment: String,
92 ciphertext: Option<String>,
93 receiving_contract_address: Option<String>,
94 },
95 ShieldedMint {
96 commitment: String,
97 domain_sep: String,
98 amount: Option<String>,
99 },
100 ShieldedBurn {
101 nullifier: String,
102 amount: Option<String>,
103 },
104 UnshieldedSpend {
105 sender: EventAddress,
106 domain_sep: String,
107 token_type: String,
108 amount: String,
109 },
110 UnshieldedReceive {
111 recipient: EventAddress,
112 domain_sep: String,
113 token_type: String,
114 amount: String,
115 },
116 UnshieldedMint {
117 domain_sep: String,
118 token_type: String,
119 amount: String,
120 },
121 UnshieldedBurn {
122 sender: EventAddress,
123 token_type: String,
124 amount: String,
125 },
126 Paused,
127 Unpaused,
128 Misc,
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct ContractEvent {
135 pub id: u64,
137 pub max_id: u64,
139 pub payload_version: u32,
141 pub protocol_version: u32,
142 pub contract_address: String,
143 pub transaction_id: u64,
144 pub raw: String,
146 pub kind: ContractEventKind,
147}
148
149#[derive(Debug, Clone, Default, PartialEq, Eq)]
152pub struct ContractEventFilter {
153 pub contract_address: String,
154 pub types: Option<Vec<ContractEventType>>,
156 pub field_prefixes: Vec<(String, String)>,
160 pub from_block: Option<u64>,
161 pub to_block: Option<u64>,
164 pub transaction_hash: Option<String>,
165}
166
167impl ContractEventFilter {
168 #[must_use]
170 pub fn to_graphql(&self) -> Value {
171 let mut filter = json!({ "contractAddress": self.contract_address });
172 if let Some(types) = &self.types {
173 filter["types"] = types.iter().map(|t| t.as_graphql()).collect();
174 }
175 if !self.field_prefixes.is_empty() {
176 filter["fieldPrefixes"] = self
177 .field_prefixes
178 .iter()
179 .map(|(field, prefix)| json!({ "fieldName": field, "prefix": prefix }))
180 .collect();
181 }
182 if let Some(h) = self.from_block {
183 filter["fromBlock"] = json!(h);
184 }
185 if let Some(h) = self.to_block {
186 filter["toBlock"] = json!(h);
187 }
188 if let Some(hash) = &self.transaction_hash {
189 filter["transactionHash"] = json!(hash);
190 }
191 filter
192 }
193}
194
195fn shape(msg: impl Into<String>) -> IndexerError {
196 IndexerError::InvalidResponse(msg.into())
197}
198
199fn text(v: &Value, field: &str) -> Result<String, IndexerError> {
200 v.get(field)
201 .and_then(Value::as_str)
202 .map(ToOwned::to_owned)
203 .ok_or_else(|| {
204 shape(format!(
205 "contract event field `{field}` missing or not a string"
206 ))
207 })
208}
209
210fn optional_text(v: &Value, field: &str) -> Option<String> {
211 v.get(field).and_then(Value::as_str).map(ToOwned::to_owned)
212}
213
214fn number(v: &Value, field: &str) -> Result<u64, IndexerError> {
215 v.get(field).and_then(Value::as_u64).ok_or_else(|| {
216 shape(format!(
217 "contract event field `{field}` missing or not a count"
218 ))
219 })
220}
221
222fn address(v: &Value, field: &str) -> Result<EventAddress, IndexerError> {
223 let a = v
224 .get(field)
225 .ok_or_else(|| shape(format!("contract event field `{field}` missing")))?;
226 match a.get("kind").and_then(Value::as_str) {
227 Some("USER") => Ok(EventAddress::User(text(a, "userAddress")?)),
228 Some("CONTRACT") => Ok(EventAddress::Contract(text(a, "contractAddress")?)),
229 other => Err(shape(format!("contract event `{field}.kind` is {other:?}"))),
230 }
231}
232
233pub fn parse_contract_event(v: &Value) -> Result<ContractEvent, IndexerError> {
235 let kind = match v.get("__typename").and_then(Value::as_str) {
236 Some("ShieldedSpendEvent") => ContractEventKind::ShieldedSpend {
237 nullifier: text(v, "nullifier")?,
238 },
239 Some("ShieldedReceiveEvent") => ContractEventKind::ShieldedReceive {
240 commitment: text(v, "commitment")?,
241 ciphertext: optional_text(v, "ciphertext"),
242 receiving_contract_address: optional_text(v, "receivingContractAddress"),
243 },
244 Some("ShieldedMintEvent") => ContractEventKind::ShieldedMint {
245 commitment: text(v, "commitment")?,
246 domain_sep: text(v, "domainSep")?,
247 amount: optional_text(v, "amount"),
248 },
249 Some("ShieldedBurnEvent") => ContractEventKind::ShieldedBurn {
250 nullifier: text(v, "nullifier")?,
251 amount: optional_text(v, "amount"),
252 },
253 Some("UnshieldedSpendEvent") => ContractEventKind::UnshieldedSpend {
254 sender: address(v, "sender")?,
255 domain_sep: text(v, "domainSep")?,
256 token_type: text(v, "tokenType")?,
257 amount: text(v, "amount")?,
258 },
259 Some("UnshieldedReceiveEvent") => ContractEventKind::UnshieldedReceive {
260 recipient: address(v, "recipient")?,
261 domain_sep: text(v, "domainSep")?,
262 token_type: text(v, "tokenType")?,
263 amount: text(v, "amount")?,
264 },
265 Some("UnshieldedMintEvent") => ContractEventKind::UnshieldedMint {
266 domain_sep: text(v, "domainSep")?,
267 token_type: text(v, "tokenType")?,
268 amount: text(v, "amount")?,
269 },
270 Some("UnshieldedBurnEvent") => ContractEventKind::UnshieldedBurn {
271 sender: address(v, "sender")?,
272 token_type: text(v, "tokenType")?,
273 amount: text(v, "amount")?,
274 },
275 Some("PausedEvent") => ContractEventKind::Paused,
276 Some("UnpausedEvent") => ContractEventKind::Unpaused,
277 Some("MiscContractEvent") => ContractEventKind::Misc,
278 other => return Err(shape(format!("unknown contract event type {other:?}"))),
279 };
280 Ok(ContractEvent {
281 id: number(v, "id")?,
282 max_id: number(v, "maxId")?,
283 payload_version: u32::try_from(number(v, "version")?)
284 .map_err(|_| shape("contract event `version` out of range"))?,
285 protocol_version: u32::try_from(number(v, "protocolVersion")?)
286 .map_err(|_| shape("contract event `protocolVersion` out of range"))?,
287 contract_address: text(v, "contractAddress")?,
288 transaction_id: number(v, "transactionId")?,
289 raw: text(v, "raw")?,
290 kind,
291 })
292}
293
294#[must_use]
296pub fn contract_events_query() -> String {
297 format!(
298 "query ContractEvents($filter: ContractEventFilter!, $limit: Int, $offset: Int) {{
299 contractEvents(filter: $filter, limit: $limit, offset: $offset) {{ {CONTRACT_EVENT_FIELDS} }}
300 }}"
301 )
302}
303
304pub async fn subscribe_contract_events(
308 http_url: &str,
309 filter: &ContractEventFilter,
310 after_id: Option<u64>,
311) -> Result<
312 impl futures_util::Stream<Item = Result<ContractEvent, SubscriptionError>>
313 + moonproof_utils::rt::MaybeSend
314 + use<>,
315 SubscriptionError,
316> {
317 let query = format!(
318 "subscription ContractEventsSub($filter: ContractEventFilter!, $id: Int) {{
319 contractEvents(filter: $filter, id: $id) {{ {CONTRACT_EVENT_FIELDS} }}
320 }}"
321 );
322 let variables = json!({ "filter": filter.to_graphql(), "id": after_id });
323 let inner = run_subscription(&graphql_ws_url(http_url), &query, variables).await?;
324 Ok(inner.filter_map(|item| async move {
325 match item {
326 Ok(SubscriptionItem::Next(data)) => Some(
327 data.get("contractEvents")
328 .ok_or_else(|| {
329 SubscriptionError::MalformedMessage("next without `contractEvents`".into())
330 })
331 .and_then(|e| {
332 parse_contract_event(e)
333 .map_err(|err| SubscriptionError::MalformedMessage(err.to_string()))
334 }),
335 ),
336 Ok(SubscriptionItem::Complete) => None,
337 Err(e) => Some(Err(e)),
338 }
339 }))
340}
341
342#[cfg(test)]
343mod tests {
344 use super::*;
345
346 fn base(typename: &str) -> Value {
347 json!({
348 "__typename": typename, "id": 7, "maxId": 9, "raw": "ab", "version": 1,
349 "protocolVersion": 2_001_100, "contractAddress": "cc", "transactionId": 3,
350 })
351 }
352
353 #[test]
354 fn parses_an_unshielded_receive() {
355 let mut v = base("UnshieldedReceiveEvent");
356 v["recipient"] = json!({ "kind": "USER", "userAddress": "aa", "contractAddress": null });
357 v["domainSep"] = json!("d0");
358 v["tokenType"] = json!("00");
359 v["amount"] = json!("340282366920938463463374607431768211455");
360 let e = parse_contract_event(&v).unwrap();
361 assert_eq!(e.id, 7);
362 assert_eq!(e.protocol_version, 2_001_100);
363 assert_eq!(
364 e.kind,
365 ContractEventKind::UnshieldedReceive {
366 recipient: EventAddress::User("aa".into()),
367 domain_sep: "d0".into(),
368 token_type: "00".into(),
369 amount: "340282366920938463463374607431768211455".into(),
370 }
371 );
372 }
373
374 #[test]
375 fn parses_the_payload_free_events() {
376 assert_eq!(
377 parse_contract_event(&base("PausedEvent")).unwrap().kind,
378 ContractEventKind::Paused
379 );
380 assert_eq!(
381 parse_contract_event(&base("MiscContractEvent"))
382 .unwrap()
383 .kind,
384 ContractEventKind::Misc
385 );
386 }
387
388 #[test]
389 fn refuses_an_unknown_type_and_a_missing_field() {
390 assert!(parse_contract_event(&base("FutureEvent")).is_err());
391 assert!(parse_contract_event(&base("ShieldedSpendEvent")).is_err());
392 }
393
394 #[test]
395 fn filter_renders_only_what_is_set() {
396 let f = ContractEventFilter {
397 contract_address: "cc".into(),
398 types: Some(vec![ContractEventType::Paused, ContractEventType::Misc]),
399 to_block: Some(10),
400 ..ContractEventFilter::default()
401 };
402 assert_eq!(
403 f.to_graphql(),
404 json!({ "contractAddress": "cc", "types": ["PAUSED", "MISC"], "toBlock": 10 })
405 );
406 }
407}