fedimint_wallet_client/
withdraw.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
use bitcoin::Txid;
use fedimint_api_client::api::{deserialize_outcome, FederationApiExt};
use fedimint_client::sm::{ClientSMDatabaseTransaction, State, StateTransition};
use fedimint_client::DynGlobalClientContext;
use fedimint_core::core::OperationId;
use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::endpoint_constants::AWAIT_OUTPUT_OUTCOME_ENDPOINT;
use fedimint_core::module::ApiRequestErased;
use fedimint_core::OutPoint;
use fedimint_wallet_common::WalletOutputOutcome;
use futures::future::pending;
use tracing::warn;

use crate::events::WithdrawRequest;
use crate::WalletClientContext;

// TODO: track tx confirmations
#[aquamarine::aquamarine]
/// graph LR
///     Created --> Success
///     Created --> Aborted
#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct WithdrawStateMachine {
    pub(crate) operation_id: OperationId,
    pub(crate) state: WithdrawStates,
}

impl State for WithdrawStateMachine {
    type ModuleContext = WalletClientContext;

    fn transitions(
        &self,
        context: &Self::ModuleContext,
        global_context: &DynGlobalClientContext,
    ) -> Vec<StateTransition<Self>> {
        let wallet_context = context.clone();
        match &self.state {
            WithdrawStates::Created(created) => {
                vec![StateTransition::new(
                    await_withdraw_processed(
                        global_context.clone(),
                        context.clone(),
                        created.clone(),
                    ),
                    move |dbtx, res, old_state| {
                        Box::pin(transition_withdraw_processed(
                            res,
                            old_state,
                            wallet_context.clone(),
                            dbtx,
                        ))
                    },
                )]
            }
            WithdrawStates::Success(_) | WithdrawStates::Aborted(_) => {
                vec![]
            }
        }
    }

    fn operation_id(&self) -> OperationId {
        self.operation_id
    }
}

async fn await_withdraw_processed(
    global_context: DynGlobalClientContext,
    context: WalletClientContext,
    created: CreatedWithdrawState,
) -> Result<Txid, String> {
    global_context
        .await_tx_accepted(created.fm_outpoint.txid)
        .await?;

    let outcome = global_context
        .api()
        .request_current_consensus_retry(
            AWAIT_OUTPUT_OUTCOME_ENDPOINT.to_owned(),
            ApiRequestErased::new(created.fm_outpoint),
        )
        .await;

    match deserialize_outcome::<WalletOutputOutcome>(&outcome, &context.wallet_decoder)
        .map_err(|e| e.to_string())
        .and_then(|outcome| {
            outcome
                .ensure_v0_ref()
                .map(|outcome| outcome.0)
                .map_err(|e| e.to_string())
        }) {
        Ok(txid) => Ok(txid),
        Err(e) => {
            warn!("Failed to process wallet output outcome: {e}");

            pending().await
        }
    }
}

async fn transition_withdraw_processed(
    res: Result<Txid, String>,
    old_state: WithdrawStateMachine,
    client_ctx: WalletClientContext,
    dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
) -> WithdrawStateMachine {
    assert!(
        matches!(old_state.state, WithdrawStates::Created(_)),
        "Unexpected old state: got {:?}, expected Created",
        old_state.state
    );

    let new_state = match res {
        Ok(txid) => {
            client_ctx
                .client_ctx
                .log_event(&mut dbtx.module_tx(), WithdrawRequest { txid })
                .await;
            WithdrawStates::Success(SuccessWithdrawState { txid })
        }
        Err(error) => WithdrawStates::Aborted(AbortedWithdrawState { error }),
    };

    WithdrawStateMachine {
        operation_id: old_state.operation_id,
        state: new_state,
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub enum WithdrawStates {
    Created(CreatedWithdrawState),
    Success(SuccessWithdrawState),
    Aborted(AbortedWithdrawState),
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct CreatedWithdrawState {
    pub(crate) fm_outpoint: OutPoint,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct SuccessWithdrawState {
    pub(crate) txid: Txid,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
pub struct AbortedWithdrawState {
    pub(crate) error: String,
}