fedimint_mintv2_client/
receive.rs1use fedimint_client::DynGlobalClientContext;
2use fedimint_client_module::module::ClientContext;
3use fedimint_client_module::sm::{ClientSMDatabaseTransaction, State, StateTransition};
4use fedimint_core::TransactionId;
5use fedimint_core::core::OperationId;
6use fedimint_core::encoding::{Decodable, Encodable};
7
8use crate::events::{ReceivePaymentStatus, ReceivePaymentUpdateEvent};
9use crate::{MintClientContext, MintClientModule};
10
11#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
12pub struct ReceiveStateMachine {
13 pub common: ReceiveSMCommon,
14 pub state: ReceiveSMState,
15}
16
17impl ReceiveStateMachine {
18 pub fn update(&self, state: ReceiveSMState) -> Self {
19 Self {
20 common: self.common.clone(),
21 state,
22 }
23 }
24}
25
26#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
27pub struct ReceiveSMCommon {
28 pub operation_id: OperationId,
29 pub txid: TransactionId,
30}
31
32#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
33pub enum ReceiveSMState {
34 Pending,
35 Success,
36 Rejected(String),
37}
38
39impl State for ReceiveStateMachine {
40 type ModuleContext = MintClientContext;
41
42 fn transitions(
43 &self,
44 context: &Self::ModuleContext,
45 global_context: &DynGlobalClientContext,
46 ) -> Vec<StateTransition<Self>> {
47 let client_ctx = context.client_ctx.clone();
48 let global_context = global_context.clone();
49
50 match &self.state {
51 ReceiveSMState::Pending => vec![StateTransition::new(
52 Self::await_tx_outcome(global_context.clone(), self.common.txid),
53 move |dbtx, result, old_state| {
54 Box::pin(Self::transition_tx_outcome(
55 client_ctx.clone(),
56 global_context.clone(),
57 dbtx,
58 result,
59 old_state,
60 ))
61 },
62 )],
63 ReceiveSMState::Success | ReceiveSMState::Rejected(..) => vec![],
64 }
65 }
66
67 fn operation_id(&self) -> OperationId {
68 self.common.operation_id
69 }
70}
71
72impl ReceiveStateMachine {
73 async fn await_tx_outcome(
74 global_context: DynGlobalClientContext,
75 txid: TransactionId,
76 ) -> Result<(), String> {
77 global_context.await_tx_accepted(txid).await
78 }
79
80 async fn transition_tx_outcome(
81 client_ctx: ClientContext<MintClientModule>,
82 global_context: DynGlobalClientContext,
83 dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
84 result: Result<(), String>,
85 old_state: ReceiveStateMachine,
86 ) -> ReceiveStateMachine {
87 let account = global_context.account(dbtx).await;
88
89 let (status, new_state) = match result {
90 Ok(()) => (ReceivePaymentStatus::Success, ReceiveSMState::Success),
91 Err(e) => (ReceivePaymentStatus::Rejected, ReceiveSMState::Rejected(e)),
92 };
93
94 client_ctx
95 .log_event(
96 &mut dbtx.module_tx(),
97 ReceivePaymentUpdateEvent {
98 operation_id: old_state.common.operation_id,
99 status,
100 account,
101 },
102 )
103 .await;
104
105 old_state.update(new_state)
106 }
107}