af_iperps/event_ext/
apply.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
//! Helpers for updating off-chain data with event content
use af_move_type::otw::Otw;
use af_utilities::types::IFixed;

use crate::account::Account;
use crate::clearing_house::{ClearingHouse, Vault};
use crate::events;
use crate::orderbook::Order;
use crate::position::Position;

/// Intended for defining how to update off-chain data with event information.
pub trait Apply<T> {
    /// Use the contents of `self` to (possibly) mutate data in `target`.
    fn apply(&self, target: &mut T);
}

/// Convenience tool for implementing [`Apply`] for events that contain the values of attributes to
/// set in an object.
///
/// The implementations here don't handle how to fetch each object, that is up to the application.
///
/// For instance, one database might store only a single [`Position`] and ignore the `ch_id` and
/// `account_id` fields of the relevant events because those are already filtered for in the
/// WebSocket event subscriber.
///
/// On the other hand, another database might store several positions in a `HashMap` and use the
/// `account_id` field of the relevant events to fetch the [`Position`] from the map before passing
/// it to `.apply()`.
macro_rules! set_fields {
    (
        $(
            $event_type:ty {
                $(
                    $object_type:ty {
                        $(
                            $event_field:ident => $($object_field:ident).+
                        ),+ $(,)?
                    }
                )+
            }
        )*
    ) => {
        $(
            $(
                impl Apply<$object_type> for $event_type {
                    fn apply(&self, target: &mut $object_type) {
                        let Self {
                            $($event_field,)+
                            ..
                        } = self;
                        $(
                            target.$($object_field).+ = $event_field.clone();
                        )+
                    }
                }
            )+
        )*
    };
}

set_fields! {
    events::DepositedCollateral<Otw> {
        Account<Otw> {
            account_collateral_after => collateral.value
        }
    }

    events::AllocatedCollateral {
        Position {
            position_collateral_after => collateral
        }
        Account<Otw> {
            account_collateral_after => collateral.value
        }
        Vault<Otw> {
            vault_balance_after => collateral_balance.value
        }
    }

    events::WithdrewCollateral<Otw> {
        Account<Otw> {
            account_collateral_after => collateral.value
        }
    }

    events::DeallocatedCollateral {
        Account<Otw> {
            account_collateral_after => collateral.value
        }
        Position {
            position_collateral_after => collateral
        }
        Vault<Otw> {
            vault_balance_after => collateral_balance.value
        }
    }

    events::UpdatedPremiumTwap {
        ClearingHouse<Otw> {
            premium_twap => market_state.premium_twap,
            premium_twap_last_upd_ms => market_state.premium_twap_last_upd_ms,
        }
    }

    events::UpdatedSpreadTwap {
        ClearingHouse<Otw> {
            spread_twap => market_state.spread_twap,
            spread_twap_last_upd_ms => market_state.spread_twap_last_upd_ms,
        }
    }

    events::UpdatedFunding {
        ClearingHouse<Otw> {
            cum_funding_rate_long => market_state.cum_funding_rate_long,
            cum_funding_rate_short => market_state.cum_funding_rate_short,
            funding_last_upd_ms => market_state.funding_last_upd_ms,
        }
    }

    events::UpdatedOpenInterestAndFeesAccrued {
        ClearingHouse<Otw> {
            open_interest => market_state.open_interest,
            fees_accrued => market_state.fees_accrued,
        }
    }

    events::SettledFunding {
        Position {
            collateral_after => collateral,
            mkt_funding_rate_long => cum_funding_rate_long,
            mkt_funding_rate_short => cum_funding_rate_short,
        }
    }

    events::FilledMakerOrder {
        Position {
            maker_collateral => collateral,
            maker_base_amount => base_asset_amount,
            maker_quote_amount => quote_asset_notional_amount,
            maker_pending_asks_quantity => asks_quantity,
            maker_pending_bids_quantity => bids_quantity,
        }
    }

    events::FilledTakerOrder {
        Position {
            taker_collateral => collateral,
            taker_base_amount => base_asset_amount,
            taker_quote_amount => quote_asset_notional_amount,
        }
    }

    events::PostedOrder {
        Position {
            pending_asks => asks_quantity,
            pending_bids => bids_quantity,
            pending_orders => pending_orders,
        }
    }

    events::CanceledOrders {
        Position {
            asks_quantity => asks_quantity,
            bids_quantity => bids_quantity,
            pending_orders => pending_orders,
        }
    }

    events::UpdatedCumFundings {
        ClearingHouse<Otw> {
            cum_funding_rate_long => market_state.cum_funding_rate_long,
            cum_funding_rate_short => market_state.cum_funding_rate_short,
        }
    }

    events::UpdatedMarginRatios {
        ClearingHouse<Otw> {
            margin_ratio_initial => market_params.margin_ratio_initial,
            margin_ratio_maintenance => market_params.margin_ratio_maintenance,
        }
    }

    events::AcceptedPositionFeesProposal {
        Position {
            maker_fee => maker_fee,
            taker_fee => taker_fee,
        }
    }

    events::UpdatedFees {
        ClearingHouse<Otw> {
            maker_fee => market_params.maker_fee,
            taker_fee => market_params.taker_fee,
            liquidation_fee => market_params.liquidation_fee,
            force_cancel_fee => market_params.force_cancel_fee,
            insurance_fund_fee => market_params.insurance_fund_fee,
        }
    }

    events::UpdatedFundingParameters {
        ClearingHouse<Otw> {
            funding_frequency_ms => market_params.funding_frequency_ms,
            funding_period_ms => market_params.funding_period_ms,
            premium_twap_frequency_ms => market_params.premium_twap_frequency_ms,
            premium_twap_period_ms => market_params.premium_twap_period_ms,
        }
    }

    events::UpdatedSpreadTwapParameters {
        ClearingHouse<Otw> {
            spread_twap_frequency_ms => market_params.spread_twap_frequency_ms,
            spread_twap_period_ms => market_params.spread_twap_period_ms,
        }
    }

    events::UpdatedMinOrderUsdValue {
        ClearingHouse<Otw> {
            min_order_usd_value => market_params.min_order_usd_value,
        }
    }

    events::UpdatedLiquidationTolerance {
        ClearingHouse<Otw> {
            liquidation_tolerance => market_params.liquidation_tolerance,
        }
    }

    events::UpdatedBaseOracleTolerance {
        ClearingHouse<Otw> {
            oracle_tolerance => market_params.base_oracle_tolerance,
        }
    }

    events::UpdatedCollateralOracleTolerance {
        ClearingHouse<Otw> {
            oracle_tolerance => market_params.collateral_oracle_tolerance,
        }
    }

    events::UpdatedMaxPendingOrders {
        ClearingHouse<Otw> {
            max_pending_orders => market_params.max_pending_orders,
        }
    }

    events::DonatedToInsuranceFund {
        Vault<Otw> {
            new_balance => insurance_fund_balance.value,
        }
    }

    events::WithdrewFees {
        Vault<Otw> {
            vault_balance_after => collateral_balance.value,
        }
    }

    events::WithdrewInsuranceFund {
        Vault<Otw> {
            insurance_fund_balance_after => insurance_fund_balance.value,
        }
    }
}

impl Apply<ClearingHouse<Otw>> for events::WithdrewFees {
    fn apply(&self, target: &mut ClearingHouse<Otw>) {
        target.market_state.fees_accrued = IFixed::zero();
    }
}

// When you reset fees you set at a constant value which is used as a "null" value. It's in the
// constants module of the contracts.
impl Apply<Position> for events::ResettedPositionFees {
    fn apply(&self, target: &mut Position) {
        target.maker_fee = 1.into();
        target.taker_fee = 1.into();
    }
}

impl Apply<Position> for events::LiquidatedPosition {
    fn apply(&self, target: &mut Position) {
        let Self {
            liqee_collateral,
            liqee_base_amount,
            liqee_quote_amount,
            ..
        } = *self;
        target.collateral = liqee_collateral;
        target.base_asset_amount = liqee_base_amount;
        target.quote_asset_notional_amount = liqee_quote_amount;
        // All pending orders are force canceled upon liquidation
        target.asks_quantity = IFixed::zero();
        target.bids_quantity = IFixed::zero();
        target.pending_orders = 0;
    }
}

/// General interface to help apply orderbook-related events to a database.
///
/// The methods here don't have to be used as an interface for other applications, they're only
/// defined for conveniently calling `event.apply(&mut database)` on whatever the `database` type
/// is.
pub trait Orderbook {
    /// To use with `OrderbookPostReceipt` event.
    fn insert_order(&mut self, order_id: u128, order: Order);

    /// To use with `CanceledOrder` or `FilledMakerOrder`
    /// in which maker order was fully filled.
    fn remove_order(&mut self, order_id: u128);

    /// To use with `FilledMakerOrder` in which
    /// maker order was not fully filled.
    fn reduce_order_size(&mut self, order_id: u128, size_to_sub: u64);
}

impl<T: Orderbook> Apply<T> for events::OrderbookPostReceipt {
    fn apply(&self, target: &mut T) {
        let Self {
            order_id,
            order_size: size,
            account_id,
            ..
        } = *self;
        let order = Order { account_id, size };
        target.insert_order(order_id, order);
    }
}

impl<T: Orderbook> Apply<T> for events::CanceledOrder {
    fn apply(&self, target: &mut T) {
        let Self { order_id, .. } = *self;
        target.remove_order(order_id);
    }
}

impl<T: Orderbook> Apply<T> for events::FilledMakerOrder {
    fn apply(&self, target: &mut T) {
        let Self {
            order_id,
            maker_size,
            maker_final_size,
            ..
        } = *self;
        if maker_final_size > 0 {
            target.reduce_order_size(order_id, maker_size)
        } else {
            target.remove_order(order_id);
        }
    }
}