nym_contracts_common/events.rs
1// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
2// SPDX-License-Identifier: Apache-2.0
3
4use cosmwasm_std::Event;
5
6/// Looks up value of particular attribute in the provided event. If it fails to find it,
7/// the function panics.
8///
9/// # Arguments
10///
11/// * `event`: event to search through.
12/// * `key`: key associated with the particular attribute
13pub fn must_find_attribute(event: &Event, key: &str) -> String {
14 // due to how the function is supposed to work, the unwrap is fine in this instance
15 #[allow(clippy::unwrap_used)]
16 may_find_attribute(event, key).unwrap()
17}
18
19/// Looks up value of particular attribute in the provided event. Returns None if it does not exist.
20///
21/// # Arguments
22///
23/// * `event`: event to search through.
24/// * `key`: key associated with the particular attribute
25pub fn may_find_attribute(event: &Event, key: &str) -> Option<String> {
26 for attr in &event.attributes {
27 if attr.key == key {
28 return Some(attr.value.clone());
29 }
30 }
31 None
32}
33
34pub trait OptionallyAddAttribute {
35 fn add_optional_attribute(
36 self,
37 key: impl Into<String>,
38 value: Option<impl Into<String>>,
39 ) -> Self;
40}
41
42impl OptionallyAddAttribute for Event {
43 fn add_optional_attribute(
44 self,
45 key: impl Into<String>,
46 value: Option<impl Into<String>>,
47 ) -> Self {
48 if let Some(value) = value {
49 self.add_attribute(key, value)
50 } else {
51 // TODO: perhaps if value doesn't exist, we should emit explicit 'null'?
52 self
53 }
54 }
55}