off-grid-primitives 0.1.0

Core data structures and logic for the Off-Grid exchange: spot market (L1/L2/L3), order books, matching engine, and account balances
Documentation
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
// core_events/src/lib.rs
use once_cell::sync::OnceCell;
use std::sync::{mpsc, Mutex};
use std::thread;
use std::fmt;
use serde::{Serialize, Deserialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SpotEvent {
    /// New market price event in Spot
    SpotNewMarketPrice {
        /// client id
        /// multiple client ids can be provided for the same event
        client_ids: Vec<Vec<u8>>,
        /// pair id
        #[serde(with = "serde_bytes")]
        pair_id: Vec<u8>,
        /// base asset id
        #[serde(with = "serde_bytes")]
        base_asset_id: Vec<u8>,
        /// quote asset id
        #[serde(with = "serde_bytes")]
        quote_asset_id: Vec<u8>,
        /// price
        price: u64,
        /// timestamp in milliseconds
        /// i64 is chosen because of js type compatibility
        timestamp: i64,
    },
    /// Spot pair rebate happened when maker fee bps is lower than 0
    SpotPairRebate {
        /// pair id
        #[serde(with = "serde_bytes")]
        pair_id: Vec<u8>,
        /// base asset id
        #[serde(with = "serde_bytes")]
        base_asset_id: Vec<u8>,
        /// quote asset id
        #[serde(with = "serde_bytes")]
        quote_asset_id: Vec<u8>,
        /// price 
        price: u64,
        /// is bid
        is_bid: bool,
        /// account id
        #[serde(with = "serde_bytes")]
        account_id: Vec<u8>,
        /// happened on maker/taker side
        is_maker: bool,
        /// fee bps
        fee_bps: i16,
        /// asset volume
        base_volume: u64,
        /// quote volume
        quote_volume: u64,
        /// timestamp
        timestamp: i64,
    },
    /// Spot pair client account changed
    SpotPairClientAccountChanged {
        /// pair id
        #[serde(with = "serde_bytes")]
        pair_id: Vec<u8>,
        /// client id
        #[serde(with = "serde_bytes")]
        cid: Option<Vec<u8>>,
        /// admin account id
        #[serde(with = "serde_bytes")]
        admin_account_id: Option<Vec<u8>>,
        /// fee account id
        #[serde(with = "serde_bytes")]
        fee_account_id: Option<Vec<u8>>,
        /// timestamp
        /// i64 is chosen because of js type compatibility
        timestamp: i64,
    },
    /// Pair added to the matching engine
    SpotPairAdded {
        /// client id
        #[serde(with = "serde_bytes")]
        cid: Vec<u8>,
        /// pair id
        #[serde(with = "serde_bytes")]
        pair_id: Vec<u8>,
        /// timestamp
        /// i64 is chosen because of js type compatibility
        timestamp: i64,
    },
    /// Transfer event from an account to another account
    Transfer {
        /// client id 
        #[serde(with = "serde_bytes")]
        cid: Vec<u8>,
        /// from account id
        #[serde(with = "serde_bytes")]
        from: Vec<u8>,
        /// to account id
        #[serde(with = "serde_bytes")]
        to: Vec<u8>,
        /// asset id
        #[serde(with = "serde_bytes")]
        asset: Vec<u8>,
        /// amount
        amnt: u64,
        /// timestamp
        timestamp: i64,
    },
    /// Spot order block changed in the orderbook
    SpotPriceLevelChanged {
        /// pair id
        #[serde(with = "serde_bytes")]
        pair_id: Vec<u8>,
        /// is bid
        is_bid: bool,
        /// price
        price: u64,
        /// public quantity
        pqty: u64,
        /// current quantity
        cqty: u64,
        /// timestamp
        timestamp: i64,
    },
    /// Spot order placed in the orderbook being a maker
    SpotOrderPlaced { 
        /// client id
        #[serde(with = "serde_bytes")]
        cid: Vec<u8>,
        /// pair id
        #[serde(with = "serde_bytes")]
        pair_id: Vec<u8>,
        /// base asset id
        #[serde(with = "serde_bytes")]
        base_asset_id: Vec<u8>,
        /// quote asset id
        #[serde(with = "serde_bytes")]
        quote_asset_id: Vec<u8>,
        /// order id
        #[serde(with = "serde_bytes")]
        order_id: Vec<u8>, 
        /// maker account id
        #[serde(with = "serde_bytes")]
        maker_account_id: Vec<u8>, 
        /// maker order is bid
        is_bid: bool, 
        /// price
        price: u64, 
        /// whole amount
        amnt: u64,
        /// iceberg quantity
        iqty: u64, 
        /// current quantity
        cqty: u64, 
        /// public quantity
        pqty: u64,
        /// timestamp, i64 is chosen because of js type compatibility
        timestamp: i64, 
        /// expires at timestamp, i64 is chosen because of js type compatibility
        expires_at: i64 
    },
    /// Spot order partially filled in the orderbook being a taker for taker spot order history
    SpotOrderPartiallyFilled { 
        /// whether the event is for a taker order
        is_taker_event: bool,
        /// taker client id
        #[serde(with = "serde_bytes")]
        taker_cid: Vec<u8>,
        /// maker client id
        #[serde(with = "serde_bytes")]
        maker_cid: Vec<u8>,
        /// taker order id
        #[serde(with = "serde_bytes")]
        taker_order_id: Vec<u8>,
        /// maker order id
        #[serde(with = "serde_bytes")]
        maker_order_id: Vec<u8>,
        /// maker account id
        #[serde(with = "serde_bytes")]
        taker_account_id: Vec<u8>, 
        /// taker account id
        #[serde(with = "serde_bytes")]
        maker_account_id: Vec<u8>, 
        /// taker order is bid
        taker_order_is_bid: bool, 
        /// maker order is bid
        maker_order_is_bid: bool, 
        /// price
        price: u64, 
        /// pair id
        #[serde(with = "serde_bytes")]
        pair_id: Vec<u8>,
        /// base asset id
        #[serde(with = "serde_bytes")]
        base_asset_id: Vec<u8>,
        /// quote asset id
        #[serde(with = "serde_bytes")]
        quote_asset_id: Vec<u8>,
        /// base volume
        base_volume: u64,
        /// quote volume
        quote_volume: u64,
        /// base fee
        base_fee: u64,
        /// quote fee
        quote_fee: u64,
        /// maker fee bps
        maker_fee_bps: i16,
        /// taker fee bps
        taker_fee_bps: i16,
        /// whole amount
        amnt: u64,
        /// iceberg quantity
        iqty: u64, 
        /// public quantity
        pqty: u64,
        /// current quantity
        cqty: u64, 
        /// timestamp, i64 is chosen because of js type compatibility
        timestamp: i64, 
        /// expires at timestamp, i64 is chosen because of js type compatibility
        expires_at: i64 
    },
    /// Spot order fully filled in the orderbook being a taker for taker spot order history
    SpotOrderFullyFilled { 
        /// whether the event is for a taker order
        is_taker_event: bool,
        /// taker client id
        #[serde(with = "serde_bytes")]
        taker_cid: Vec<u8>,
        /// maker client id
        #[serde(with = "serde_bytes")]
        maker_cid: Vec<u8>,
        /// taker order id
        #[serde(with = "serde_bytes")]
        taker_order_id: Vec<u8>,
        /// maker order id
        #[serde(with = "serde_bytes")]
        maker_order_id: Vec<u8>,
        /// maker account id
        #[serde(with = "serde_bytes")]
        maker_account_id: Vec<u8>, 
        /// taker account id
        #[serde(with = "serde_bytes")]
        taker_account_id: Vec<u8>, 
        /// taker order is bid
        taker_order_is_bid: bool, 
        /// maker order is bid
        maker_order_is_bid: bool, 
        /// price
        price: u64, 
        /// pair id
        #[serde(with = "serde_bytes")]
        pair_id: Vec<u8>,
        /// base asset id
        #[serde(with = "serde_bytes")]
        base_asset_id: Vec<u8>,
        /// quote asset id
        #[serde(with = "serde_bytes")]
        quote_asset_id: Vec<u8>,
        /// base volume 
        base_volume: u64,
        /// quote volume
        quote_volume: u64,
        /// base fee
        base_fee: u64,
        /// quote fee
        quote_fee: u64,
        /// maker fee bps
        maker_fee_bps: i16,
        /// taker fee bps
        taker_fee_bps: i16,
        /// whole amount
        amnt: u64,
        /// iceberg quantity
        iqty: u64,
        /// public quantity
        pqty: u64, 
        /// current quantity
        cqty: u64, 
        /// timestamp, i64 is chosen because of js type compatibility
        timestamp: i64, 
        /// expires at timestamp, i64 is chosen because of js type compatibility
        expires_at: i64 
    },
    /// Spot order cancelled in the orderbook regardless of being a maker or taker
    SpotOrderCancelled { 
        /// client id
        #[serde(with = "serde_bytes")]
        cid: Vec<u8>,
        /// order id
        #[serde(with = "serde_bytes")]
        order_id: Vec<u8>, 
        /// maker account id
        #[serde(with = "serde_bytes")]
        maker_account_id: Vec<u8>, 
        /// is bid
        is_bid: bool, 
        /// price
        price: u64, 
        /// whole amount
        amnt: u64,
        /// iceberg quantity
        iqty: u64, 
        /// public quantity
        pqty: u64,
        /// current quantity
        cqty: u64, 
        /// timestamp, i64 is chosen because of js type compatibility
        timestamp: i64, 
        /// expires at timestamp, i64 is chosen because of js type compatibility
        expires_at: i64 
    },
    /// Spot order expired in the orderbook regardless of being a maker
    SpotOrderExpired { 
        /// client id
        #[serde(with = "serde_bytes")]
        cid: Vec<u8>,
        /// order id
        #[serde(with = "serde_bytes")]
        order_id: Vec<u8>, 
        /// maker account id
        #[serde(with = "serde_bytes")]
        maker_account_id: Vec<u8>, 
        /// is bid
        is_bid: bool, 
        /// price
        price: u64, 
        /// whole amount
        amnt: u64,
        /// iceberg quantity
        iqty: u64, 
        /// public quantity
        pqty: u64,
        /// current quantity
        cqty: u64, 
        /// timestamp, i64 is chosen because of js type compatibility
        timestamp: i64, 
        /// expires at timestamp, i64 is chosen because of js type compatibility
        expires_at: i64 
    },
    SpotOrderIcebergQuantityChanged { 
        /// client id
        #[serde(with = "serde_bytes")]
        cid: Vec<u8>,
        /// order id
        #[serde(with = "serde_bytes")]
        order_id: Vec<u8>, 
        /// whole initial amount
        amnt: u64,
        /// iceberg quantity
        iqty: u64, 
        /// public quantity
        pqty: u64,
        /// current quantity
        cqty: u64, 
        /// timestamp, i64 is chosen because of js type compatibility
        timestamp: i64, 
        /// expires at timestamp, i64 is chosen because of js type compatibility
        expires_at: i64 
    }
}

/// A queue of events that can be formatted and displayed.
/// This is a newtype wrapper around `Vec<SpotEvent>` that provides better formatting support.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct EventQueue(pub Vec<SpotEvent>);

impl EventQueue {
    /// Create a new empty event queue
    pub fn new() -> Self {
        EventQueue(Vec::new())
    }

    /// Create an event queue from a vector of events
    pub fn from_vec(events: Vec<SpotEvent>) -> Self {
        EventQueue(events)
    }

    /// Get a reference to the underlying vector
    pub fn as_vec(&self) -> &Vec<SpotEvent> {
        &self.0
    }

    /// Consume the wrapper and return the underlying vector
    pub fn into_vec(self) -> Vec<SpotEvent> {
        self.0
    }

    /// Check if the queue is empty
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Get the number of events in the queue
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Log all events in this queue using `println!`.
    ///
    /// This is primarily intended for debugging or tests. In production code,
    /// prefer sending events to a structured logging backend.
    pub fn log(&self, prefix: &str) {
        if self.0.is_empty() {
            println!("{prefix}[]");
            return;
        }

        for (i, event) in self.0.iter().enumerate() {
            println!("{prefix}[{i}]: {:?}", event);
        }
    }
}

impl Default for EventQueue {
    fn default() -> Self {
        EventQueue::new()
    }
}

impl From<Vec<SpotEvent>> for EventQueue {
    fn from(events: Vec<SpotEvent>) -> Self {
        EventQueue(events)
    }
}

impl From<EventQueue> for Vec<SpotEvent> {
    fn from(queue: EventQueue) -> Self {
        queue.0
    }
}

impl fmt::Display for EventQueue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.0.is_empty() {
            return write!(f, "[]");
        }
        
        write!(f, "[")?;
        for (i, event) in self.0.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{:?}", event)?;
        }
        write!(f, "]")
    }
}

impl std::ops::Deref for EventQueue {
    type Target = Vec<SpotEvent>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for EventQueue {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

pub trait EventBackend: Send + 'static {
    fn handle_event(&mut self, event: SpotEvent);
}

// Sender into the dispatcher
static DISPATCH_TX: OnceCell<mpsc::Sender<SpotEvent>> = OnceCell::new();

// List of per-backend senders
static BACKEND_TXS: OnceCell<Mutex<Vec<mpsc::Sender<SpotEvent>>>> = OnceCell::new();

// In-memory event queue that stores events before they are published
static EVENT_QUEUE: OnceCell<Mutex<Vec<SpotEvent>>> = OnceCell::new();

fn backend_txs() -> &'static Mutex<Vec<mpsc::Sender<SpotEvent>>> {
    BACKEND_TXS.get_or_init(|| Mutex::new(Vec::new()))
}

fn event_queue() -> &'static Mutex<Vec<SpotEvent>> {
    EVENT_QUEUE.get_or_init(|| Mutex::new(Vec::new()))
}

/// Call once at process startup to create the dispatcher thread.
pub fn init_event_bus() {
    let (tx, rx) = mpsc::channel::<SpotEvent>();
    DISPATCH_TX.set(tx).ok(); // ignore if already set

    // Dispatcher thread: fan out every event to all registered backends.
    thread::spawn(move || {
        while let Ok(event) = rx.recv() {
            // clone once per backend
            let backends = backend_txs().lock().unwrap();
            for backend_tx in backends.iter() {
                // Ignore send errors (backend might have shut down)
                let _ = backend_tx.send(event.clone());
            }
        }
    });
}

/// Called from anywhere (engine, core logic) to emit an event.
/// This stores the event in the event queue. Use `publish_events()` to actually send them.
pub fn emit_event(event: SpotEvent) {
    let mut queue = event_queue().lock().unwrap();
    queue.push(event);
}

/// Publishes all events from the global queue to the event bus (if initialized).
/// After publishing, the queue is drained and cleared.
pub fn publish_events() {
    // Drain all events from the queue
    let events: Vec<SpotEvent> = {
        let mut queue = event_queue().lock().unwrap();
        let drained = queue.clone();
        queue.clear();
        drained
    };

    // Send each event to the dispatcher if it's initialized
    if let Some(tx) = DISPATCH_TX.get() {
        for event in events {
            // ignore error if dispatcher is down
            let _ = tx.send(event);
        }
    }
}

/// Publishes an EventQueue to the event bus (if initialized).
/// This is useful when you have an EventQueue returned from an operation.
pub fn publish_event_queue(events: EventQueue) {
    // Send each event to the dispatcher if it's initialized
    if let Some(tx) = DISPATCH_TX.get() {
        for event in events.into_vec() {
            // ignore error if dispatcher is down
            let _ = tx.send(event);
        }
    }
}

/// Register a backend; returns an `mpsc::Receiver<SpotEvent>` that you
/// can consume from a dedicated thread.
pub fn register_backend() -> mpsc::Receiver<SpotEvent> {
    let (tx, rx) = mpsc::channel::<SpotEvent>();

    {
        let mut list = backend_txs().lock().unwrap();
        list.push(tx);
    }

    rx
}

/// Drains all events from the event queue and returns them.
/// This clears the queue after draining.
/// Useful for retrieving events after operations complete.
pub fn drain_events() -> EventQueue {
    let mut queue = event_queue().lock().unwrap();
    let drained = queue.clone();
    queue.clear();
    EventQueue(drained)
}

/// Clears all events from the event queue without returning them.
pub fn clear_events() {
    let mut queue = event_queue().lock().unwrap();
    queue.clear();
}