1use crate::currency::DecCoin;
5use crate::error::TypesError;
6use crate::pending_events::{PendingEpochEvent, PendingEpochEventData};
7use nym_mixnet_contract_common::{IdentityKey, NodeId};
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
12#[cfg_attr(
13 feature = "generate-ts",
14 ts(
15 export,
16 export_to = "ts-packages/types/src/types/rust/DelegationEventKind.ts"
17 )
18)]
19#[derive(Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, Debug)]
20pub enum DelegationEventKind {
21 Delegate,
22 Undelegate,
23}
24
25#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
26#[cfg_attr(
27 feature = "generate-ts",
28 ts(
29 export,
30 export_to = "ts-packages/types/src/types/rust/DelegationEvent.ts"
31 )
32)]
33#[derive(Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, Debug)]
34pub struct DelegationEvent {
35 pub kind: DelegationEventKind,
36 pub mix_id: NodeId,
37 pub address: String,
38 pub amount: Option<DecCoin>,
39 pub proxy: Option<String>,
40}
41
42#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
43#[cfg_attr(
44 feature = "generate-ts",
45 ts(
46 export,
47 export_to = "ts-packages/types/src/types/rust/WrappedDelegationEvent.ts"
48 )
49)]
50#[derive(Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, Debug)]
51pub struct WrappedDelegationEvent {
52 pub event: DelegationEvent,
53 pub node_identity: IdentityKey,
54}
55
56impl WrappedDelegationEvent {
57 pub fn new(event: DelegationEvent, node_identity: IdentityKey) -> Self {
58 Self {
59 event,
60 node_identity,
61 }
62 }
63}
64
65impl DelegationEvent {
66 pub fn address_matches(&self, address: &str) -> bool {
67 self.address == address
68 }
69}
70
71pub fn convert_to_delegation_events(epoch_events: Vec<PendingEpochEvent>) -> Vec<DelegationEvent> {
72 epoch_events
73 .into_iter()
74 .filter_map(|e| e.try_into().ok())
76 .collect()
77}
78
79impl TryFrom<PendingEpochEvent> for DelegationEvent {
80 type Error = TypesError;
81
82 fn try_from(value: PendingEpochEvent) -> Result<Self, Self::Error> {
83 value.event.try_into()
84 }
85}
86
87impl TryFrom<PendingEpochEventData> for DelegationEvent {
88 type Error = TypesError;
89
90 fn try_from(value: PendingEpochEventData) -> Result<Self, Self::Error> {
91 match value {
92 PendingEpochEventData::Delegate {
93 owner,
94 mix_id,
95 amount,
96 proxy,
97 } => Ok(DelegationEvent {
98 kind: DelegationEventKind::Delegate,
99 address: owner,
100 mix_id,
101 proxy,
102 amount: Some(amount),
103 }),
104 PendingEpochEventData::Undelegate {
105 owner,
106 mix_id,
107 proxy,
108 } => Ok(DelegationEvent {
109 kind: DelegationEventKind::Undelegate,
110 address: owner,
111 mix_id,
112 proxy,
113 amount: None,
114 }),
115 _ => Err(TypesError::NotADelegationEvent),
116 }
117 }
118}