openzeppelin_monitor/services/filter/
filter_match.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! Match handling and processing logic.
//!
//! This module implements the processing of matched transactions and events:
//! - Converts blockchain data to trigger-friendly format
//! - Prepares notification payloads by converting blockchain-specific data into a generic format
//! - Handles match execution through configured triggers
//! - Manages the transformation of complex blockchain data into template variables

use std::collections::HashMap;

use alloy::primitives::Address;
use serde_json::{json, Value as JsonValue};

use crate::{
	models::{MonitorMatch, ScriptLanguage},
	services::{
		filter::{
			evm_helpers::{b256_to_string, h160_to_string},
			FilterError,
		},
		trigger::TriggerExecutionServiceTrait,
	},
};

/// Process a monitor match by executing associated triggers.
///
/// Takes a matched monitor event and processes it through the appropriate trigger service.
/// Converts blockchain-specific data into a standardized format that can be used in trigger
/// templates.
///
/// # Arguments
/// * `matching_monitor` - The matched monitor event containing transaction and trigger information
/// * `trigger_service` - Service responsible for executing triggers
/// * `trigger_scripts` - Scripts to be executed for each trigger
///
/// # Returns
/// Result indicating success or failure of trigger execution
///
/// # Example
/// The function converts blockchain data into template variables like:
/// ```text
/// "monitor.name": "Transfer USDT Token"
/// "transaction.hash": "0x99139c8f64b9b939678e261e1553660b502d9fd01c2ab1516e699ee6c8cc5791"
/// "transaction.from": "0xf401346fd255e034a2e43151efe1d68c1e0f8ca5"
/// "transaction.to": "0x0000000000001ff3684f28c67538d4d072c22734"
/// "transaction.value": "24504000000000000"
/// "events.0.signature": "Transfer(address,address,uint256)"
/// "events.0.args.to": "0x70bf6634ee8cb27d04478f184b9b8bb13e5f4710"
/// "events.0.args.from": "0x2e8135be71230c6b1b4045696d41c09db0414226"
/// "events.0.args.value": "88248701"
/// ```
pub async fn handle_match<T: TriggerExecutionServiceTrait>(
	matching_monitor: MonitorMatch,
	trigger_service: &T,
	trigger_scripts: &HashMap<String, (ScriptLanguage, String)>,
) -> Result<(), FilterError> {
	match &matching_monitor {
		MonitorMatch::EVM(evm_monitor_match) => {
			let transaction = evm_monitor_match.transaction.clone();
			// If sender does not exist, we replace with 0x0000000000000000000000000000000000000000
			let sender = transaction.sender().unwrap_or(&Address::ZERO);

			// Create structured JSON data
			let mut data_json = json!({
				"monitor": {
					"name": evm_monitor_match.monitor.name.clone(),
				},
				"transaction": {
					"hash": b256_to_string(*transaction.hash()),
					"from": h160_to_string(*sender),
					"value": transaction.value().to_string(),
				},
				"functions": [],
				"events": []
			});

			// Add 'to' address if present
			if let Some(to) = transaction.to() {
				data_json["transaction"]["to"] = json!(h160_to_string(*to));
			}

			// Process matched functions
			let functions = data_json["functions"].as_array_mut().unwrap();
			for func in evm_monitor_match.matched_on.functions.iter() {
				let mut function_data = json!({
					"signature": func.signature.clone(),
					"args": {}
				});

				// Add function arguments if present
				if let Some(args) = &evm_monitor_match.matched_on_args {
					if let Some(func_args) = &args.functions {
						for func_arg in func_args {
							if func_arg.signature == func.signature {
								if let Some(arg_entries) = &func_arg.args {
									let args_obj = function_data["args"].as_object_mut().unwrap();
									for arg in arg_entries {
										args_obj.insert(arg.name.clone(), json!(arg.value.clone()));
									}
								}
							}
						}
					}
				}

				functions.push(function_data);
			}

			// Process matched events
			let events = data_json["events"].as_array_mut().unwrap();
			for event in evm_monitor_match.matched_on.events.iter() {
				let mut event_data = json!({
					"signature": event.signature.clone(),
					"args": {}
				});

				// Add event arguments if present
				if let Some(args) = &evm_monitor_match.matched_on_args {
					if let Some(event_args) = &args.events {
						for event_arg in event_args {
							if event_arg.signature == event.signature {
								if let Some(arg_entries) = &event_arg.args {
									let args_obj = event_data["args"].as_object_mut().unwrap();
									for arg in arg_entries {
										args_obj.insert(arg.name.clone(), json!(arg.value.clone()));
									}
								}
							}
						}
					}
				}

				events.push(event_data);
			}

			// Swallow any errors since it's logged in the trigger service and we want to continue
			// processing other matches
			let _ = trigger_service
				.execute(
					&evm_monitor_match
						.monitor
						.triggers
						.iter()
						.map(|s| s.to_string())
						.collect::<Vec<_>>(),
					json_to_hashmap(&data_json),
					&matching_monitor,
					trigger_scripts,
				)
				.await;
		}
		MonitorMatch::Stellar(stellar_monitor_match) => {
			let transaction = stellar_monitor_match.transaction.clone();

			// Create structured JSON data
			let mut data_json = json!({
				"monitor": {
					"name": stellar_monitor_match.monitor.name.clone(),
				},
				"transaction": {
					"hash": transaction.hash().to_string(),
				},
				"functions": [],
				"events": []
			});

			// Process matched functions
			let functions = data_json["functions"].as_array_mut().unwrap();
			for func in stellar_monitor_match.matched_on.functions.iter() {
				let mut function_data = json!({
					"signature": func.signature.clone(),
					"args": {}
				});

				// Add function arguments if present
				if let Some(args) = &stellar_monitor_match.matched_on_args {
					if let Some(func_args) = &args.functions {
						for func_arg in func_args {
							if func_arg.signature == func.signature {
								if let Some(arg_entries) = &func_arg.args {
									let args_obj = function_data["args"].as_object_mut().unwrap();
									for arg in arg_entries {
										args_obj.insert(arg.name.clone(), json!(arg.value.clone()));
									}
								}
							}
						}
					}
				}

				functions.push(function_data);
			}

			// Process matched events
			let events = data_json["events"].as_array_mut().unwrap();
			for event in stellar_monitor_match.matched_on.events.iter() {
				let mut event_data = json!({
					"signature": event.signature.clone(),
					"args": {}
				});

				// Add event arguments if present
				if let Some(args) = &stellar_monitor_match.matched_on_args {
					if let Some(event_args) = &args.events {
						for event_arg in event_args {
							if event_arg.signature == event.signature {
								if let Some(arg_entries) = &event_arg.args {
									let args_obj = event_data["args"].as_object_mut().unwrap();
									for arg in arg_entries {
										args_obj.insert(arg.name.clone(), json!(arg.value.clone()));
									}
								}
							}
						}
					}
				}

				events.push(event_data);
			}

			// Swallow any errors since it's logged in the trigger service and we want to continue
			// processing other matches
			let _ = trigger_service
				.execute(
					&stellar_monitor_match
						.monitor
						.triggers
						.iter()
						.map(|s| s.to_string())
						.collect::<Vec<_>>(),
					json_to_hashmap(&data_json),
					&matching_monitor,
					trigger_scripts,
				)
				.await;
		}
	}
	Ok(())
}

/// Converts a JsonValue to a flattened HashMap with dotted path notation
fn json_to_hashmap(json: &JsonValue) -> HashMap<String, String> {
	let mut result = HashMap::new();
	flatten_json_path(json, "", &mut result);
	result
}

/// Flattens a JsonValue into a HashMap with dotted path notation
fn flatten_json_path(value: &JsonValue, prefix: &str, result: &mut HashMap<String, String>) {
	match value {
		JsonValue::Object(obj) => {
			for (key, val) in obj {
				let new_prefix = if prefix.is_empty() {
					key.clone()
				} else {
					format!("{}.{}", prefix, key)
				};
				flatten_json_path(val, &new_prefix, result);
			}
		}
		JsonValue::Array(arr) => {
			for (idx, val) in arr.iter().enumerate() {
				let new_prefix = format!("{}.{}", prefix, idx);
				flatten_json_path(val, &new_prefix, result);
			}
		}
		JsonValue::String(s) => insert_primitive(prefix, result, s),
		JsonValue::Number(n) => insert_primitive(prefix, result, n.to_string()),
		JsonValue::Bool(b) => insert_primitive(prefix, result, b.to_string()),
		JsonValue::Null => insert_primitive(prefix, result, "null".to_string()),
	}
}

/// Helper function to insert primitive values with consistent key handling
fn insert_primitive<T: ToString>(prefix: &str, result: &mut HashMap<String, String>, value: T) {
	let key = if prefix.is_empty() {
		"value".to_string()
	} else {
		prefix.to_string()
	};
	result.insert(key, value.to_string());
}

#[cfg(test)]
mod tests {
	use super::*;
	use serde_json::json;

	#[test]
	fn test_json_to_hashmap() {
		let json = json!({
			"monitor": {
				"name": "Test Monitor",
			},
			"transaction": {
				"hash": "0x1234567890abcdef",
			},
		});

		let hashmap = json_to_hashmap(&json);
		assert_eq!(hashmap["monitor.name"], "Test Monitor");
		assert_eq!(hashmap["transaction.hash"], "0x1234567890abcdef");
	}

	#[test]
	fn test_json_to_hashmap_with_functions() {
		let json = json!({
			"monitor": {
				"name": "Test Monitor",
			},
			"functions": [
				{
					"signature": "function1(uint256)",
					"args": {
						"arg1": "100",
					},
				},
			],
		});

		let hashmap = json_to_hashmap(&json);
		assert_eq!(hashmap["monitor.name"], "Test Monitor");
		assert_eq!(hashmap["functions.0.signature"], "function1(uint256)");
		assert_eq!(hashmap["functions.0.args.arg1"], "100");
	}

	#[test]
	fn test_json_to_hashmap_with_events() {
		let json = json!({
			"monitor": {
				"name": "Test Monitor",
			},
			"events": [
				{
					"signature": "event1(uint256)",
					"args": {
						"arg1": "100",
					},
				},
			],
		});

		let hashmap = json_to_hashmap(&json);
		assert_eq!(hashmap["monitor.name"], "Test Monitor");
		assert_eq!(hashmap["events.0.signature"], "event1(uint256)");
		assert_eq!(hashmap["events.0.args.arg1"], "100");
	}

	// Add tests for flatten_json_path
	#[test]
	fn test_flatten_json_path_object() {
		let json = json!({
			"monitor": {
				"name": "Test Monitor",
			},
		});

		let mut result = HashMap::new();
		flatten_json_path(&json, "", &mut result);
		assert_eq!(result["monitor.name"], "Test Monitor");
	}

	#[test]
	fn test_flatten_json_path_array() {
		let json = json!({
			"monitor": {
				"name": "Test Monitor",
			},
		});

		let mut result = HashMap::new();
		flatten_json_path(&json, "", &mut result);
		assert_eq!(result["monitor.name"], "Test Monitor");
	}

	#[test]
	fn test_flatten_json_path_string() {
		let json = json!("Test String");
		let mut result = HashMap::new();
		flatten_json_path(&json, "test_prefix", &mut result);
		assert_eq!(result["test_prefix"], "Test String");

		let mut result2 = HashMap::new();
		flatten_json_path(&json, "", &mut result2);
		assert_eq!(result2["value"], "Test String");
	}

	#[test]
	fn test_flatten_json_path_number() {
		let json = json!(123);
		let mut result = HashMap::new();
		flatten_json_path(&json, "test_prefix", &mut result);
		assert_eq!(result["test_prefix"], "123");

		let mut result2 = HashMap::new();
		flatten_json_path(&json, "", &mut result2);
		assert_eq!(result2["value"], "123");
	}

	#[test]
	fn test_flatten_json_path_boolean() {
		let json = json!(true);
		let mut result = HashMap::new();
		flatten_json_path(&json, "test_prefix", &mut result);
		assert_eq!(result["test_prefix"], "true");

		// Test with empty prefix
		let mut result2 = HashMap::new();
		flatten_json_path(&json, "", &mut result2);
		assert_eq!(result2["value"], "true");
	}

	#[test]
	fn test_flatten_json_path_null() {
		let json = json!(null);
		let mut result = HashMap::new();
		flatten_json_path(&json, "test_prefix", &mut result);
		assert_eq!(result["test_prefix"], "null");

		let mut result2 = HashMap::new();
		flatten_json_path(&json, "", &mut result2);
		assert_eq!(result2["value"], "null");
	}

	#[test]
	fn test_flatten_json_path_nested_object() {
		let json = json!({
			"monitor": {
				"name": "Test Monitor",
				"nested": {
					"key": "value",
				},
			},
		});

		let mut result = HashMap::new();
		flatten_json_path(&json, "", &mut result);
		assert_eq!(result["monitor.nested.key"], "value");
	}

	#[test]
	fn test_flatten_json_path_nested_array() {
		let json = json!({
			"monitor": {
				"name": "Test Monitor",
				"nested": [
					{
						"key": "value1",
					},
					{
						"key": "value2",
					},
				],
			},
		});

		let mut result = HashMap::new();
		flatten_json_path(&json, "", &mut result);
		assert_eq!(result["monitor.nested.0.key"], "value1");
		assert_eq!(result["monitor.nested.1.key"], "value2");
	}

	#[test]
	fn test_flatten_json_path_with_prefix() {
		let json = json!({
			"monitor": {
				"name": "Test Monitor",
			},
		});

		let mut result = HashMap::new();
		flatten_json_path(&json, "prefix", &mut result);
		assert_eq!(result["prefix.monitor.name"], "Test Monitor");
	}

	#[test]
	fn test_json_to_hashmap_with_primitive_values() {
		// String
		let json_string = json!("Test String");
		let hashmap_string = json_to_hashmap(&json_string);
		assert_eq!(hashmap_string["value"], "Test String");

		// Number
		let json_number = json!(123);
		let hashmap_number = json_to_hashmap(&json_number);
		assert_eq!(hashmap_number["value"], "123");

		// Boolean
		let json_bool = json!(true);
		let hashmap_bool = json_to_hashmap(&json_bool);
		assert_eq!(hashmap_bool["value"], "true");

		// Null
		let json_null = json!(null);
		let hashmap_null = json_to_hashmap(&json_null);
		assert_eq!(hashmap_null["value"], "null");
	}

	#[test]
	fn test_insert_primitive() {
		let mut result = HashMap::new();
		insert_primitive("prefix", &mut result, "Test String");
		assert_eq!(result["prefix"], "Test String");

		let mut result2 = HashMap::new();
		insert_primitive("", &mut result2, "Test String");
		assert_eq!(result2["value"], "Test String");

		let mut result3 = HashMap::new();
		insert_primitive("prefix", &mut result3, 123);
		assert_eq!(result3["prefix"], "123");

		let mut result4 = HashMap::new();
		insert_primitive("", &mut result4, 123);
		assert_eq!(result4["value"], "123");

		let mut result5 = HashMap::new();
		insert_primitive("prefix", &mut result5, true);
		assert_eq!(result5["prefix"], "true");

		let mut result6 = HashMap::new();
		insert_primitive("", &mut result6, true);
		assert_eq!(result6["value"], "true");

		let mut result7 = HashMap::new();
		insert_primitive("prefix", &mut result7, JsonValue::Null);
		assert_eq!(result7["prefix"], "null");

		let mut result8 = HashMap::new();
		insert_primitive("", &mut result8, JsonValue::Null);
		assert_eq!(result8["value"], "null");
	}
}