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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
use anyhow::anyhow;
use anyhow::Result;
use ellipsis_client::EllipsisClient;
use phoenix::program::dispatch_market::*;
use phoenix::program::EvictEvent;
use phoenix::program::ExpiredOrderEvent;
use phoenix::program::FeeEvent;
use phoenix::program::FillEvent;
use phoenix::program::FillSummaryEvent;
use phoenix::program::MarketHeader;
use phoenix::program::PhoenixMarketEvent;
use phoenix::program::PlaceEvent;
use phoenix::program::ReduceEvent;
use phoenix::program::TimeInForceEvent;
use phoenix::state::enums::*;
use phoenix::state::markets::*;
use phoenix::state::TraderState;
use phoenix_sdk_core::market_event::TimeInForce;
use phoenix_sdk_core::sdk_client_core::MarketState;
pub use phoenix_sdk_core::{
    market_event::{Evict, Fill, FillSummary, MarketEventDetails, PhoenixEvent, Place, Reduce},
    sdk_client_core::{get_decimal_string, MarketMetadata, PhoenixOrder, SDKClientCore},
};
use serde::{Deserialize, Serialize};
use solana_client::client_error::reqwest;
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_sdk::{
    commitment_config::CommitmentConfig,
    program_pack::Pack,
    pubkey::Pubkey,
    signature::{Signature, Signer},
    signer::keypair::Keypair,
};
use std::collections::HashMap;
use std::ops::Deref;
use std::str::FromStr;
use std::{collections::BTreeMap, mem::size_of, ops::DerefMut};

use crate::orderbook::Orderbook;

#[derive(Debug, Serialize, Deserialize)]
pub struct JsonMarketConfig {
    pub markets: Vec<String>,
}

pub struct SDKClient {
    pub client: EllipsisClient,
    pub core: SDKClientCore,
}

impl Deref for SDKClient {
    type Target = SDKClientCore;

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

impl DerefMut for SDKClient {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.core
    }
}

impl SDKClient {
    /// Create a new SDKClient from an EllipsisClient.
    /// This does not have any markets added to it. You must call `add_market` or `add_all_markets` to
    /// add markets to the SDKClient.
    pub async fn new_from_ellipsis_client(client: EllipsisClient) -> Result<Self> {
        let markets = BTreeMap::new();

        let core = SDKClientCore {
            markets,
            trader: client.payer.pubkey(),
        };
        Ok(SDKClient { client, core })
    }

    /// Create a new SDKClient from an EllipsisClient.
    /// This does not have any markets added to it. You must call `add_market` or `add_all_markets` to
    /// add markets to the SDKClient.
    pub fn new_from_ellipsis_client_sync(client: EllipsisClient) -> Result<Self> {
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(Self::new_from_ellipsis_client(client))
    }

    /// Recommended way to create a new SDKClient from an EllipsisClient.
    /// This will use a list of markets from a pre-defined config file to add all known markets to the SDKClient.
    pub async fn new_from_ellipsis_client_with_all_markets(client: EllipsisClient) -> Result<Self> {
        let markets = BTreeMap::new();

        let core = SDKClientCore {
            markets,
            trader: client.payer.pubkey(),
        };
        println!("Creating SDKClient with all markets");
        let mut sdk = SDKClient { client, core };
        sdk.add_all_markets().await?;
        Ok(sdk)
    }

    /// Recommended way to create a new SDKClient from an EllipsisClient.
    /// This will use a list of markets from a pre-defined config file to add all known markets to the SDKClient.
    pub fn new_from_ellipsis_client_with_all_markets_sync(client: EllipsisClient) -> Result<Self> {
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(Self::new_from_ellipsis_client_with_all_markets(client))
    }

    /// Create a new SDKClient from an EllipsisClient.
    /// Pass in a list of market keys to add to the SDKClient.
    pub async fn new_from_ellipsis_client_with_market_keys(
        market_keys: Vec<&Pubkey>,
        client: EllipsisClient,
    ) -> Result<Self> {
        let mut markets = BTreeMap::new();
        for market_key in market_keys {
            let market_metadata = Self::get_market_metadata(&client, market_key).await?;
            markets.insert(*market_key, market_metadata);
        }
        let core = SDKClientCore {
            markets,
            trader: client.payer.pubkey(),
        };
        Ok(SDKClient { client, core })
    }

    /// Create a new SDKClient from an EllipsisClient.
    /// Pass in a list of market keys to add to the SDKClient.
    pub fn new_from_ellipsis_client_sync_with_market_keys(
        market_keys: Vec<&Pubkey>,
        client: EllipsisClient,
    ) -> Result<Self> {
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(Self::new_from_ellipsis_client_with_market_keys(
            market_keys,
            client,
        ))
    }

    /// Create a new SDKClient.
    /// This does not have any markets added to it. You must call `add_market` or `add_all_markets` to
    /// add markets to the SDKClient.
    pub async fn new(payer: &Keypair, url: &str) -> Result<Self> {
        let rpc = RpcClient::new_with_commitment(url.to_string(), CommitmentConfig::confirmed());
        let client = EllipsisClient::from_rpc(rpc, payer)?;

        SDKClient::new_from_ellipsis_client(client).await
    }

    /// Create a new SDKClient.
    /// This does not have any markets added to it. You must call `add_market` or `add_all_markets` to
    /// add markets to the SDKClient.
    pub fn new_sync(payer: &Keypair, url: &str) -> Result<Self> {
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(Self::new(payer, url))
    }

    /// Recommended way to create a new SDKClient.
    /// This will use a list of markets from a pre-defined config file to add all known markets to the SDKClient.
    pub async fn new_with_all_markets(payer: &Keypair, url: &str) -> Result<Self> {
        let rpc = RpcClient::new_with_commitment(url.to_string(), CommitmentConfig::confirmed());
        let client = EllipsisClient::from_rpc(rpc, payer)?;

        SDKClient::new_from_ellipsis_client_with_all_markets(client).await
    }

    /// Recommended way to create a new SDKClient.
    /// This will use a list of markets from a pre-defined config file to add all known markets to the SDKClient.
    pub fn new_with_all_markets_sync(payer: &Keypair, url: &str) -> Result<Self> {
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(Self::new_with_all_markets(payer, url))
    }

    /// Create a new SDKClient.
    /// Pass in a list of market keys to add to the SDKClient.
    pub async fn new_with_market_keys(
        market_keys: Vec<&Pubkey>,
        payer: &Keypair,
        url: &str,
    ) -> Result<Self> {
        let rpc = RpcClient::new_with_commitment(url.to_string(), CommitmentConfig::confirmed());
        let client = EllipsisClient::from_rpc(rpc, payer)?;

        SDKClient::new_from_ellipsis_client_with_market_keys(market_keys, client).await
    }

    /// Create a new SDKClient.
    /// Pass in a list of market keys to add to the SDKClient.
    pub fn new_with_market_keys_sync(
        market_keys: Vec<&Pubkey>,
        payer: &Keypair,
        url: &str,
    ) -> Result<Self> {
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(Self::new_with_market_keys(market_keys, payer, url))
    }

    /// Load in all known markets from a pre-defined config file located in the SDK github.
    pub async fn add_all_markets(&mut self) -> Result<()> {
        let config_url = "https://raw.githubusercontent.com/Ellipsis-Labs/phoenix-sdk/master/typescript/phoenix-sdk/config.json";

        let genesis = self.client.get_genesis_hash().await?;

        //hardcoded in the genesis hashes for mainnet and devnet
        let cluster = match genesis.to_string().as_str() {
            "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d" => "mainnet-beta",
            "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG" => "devnet",
            _ => "localhost",
        };

        let response = reqwest::get(config_url)
            .await
            .map_err(|e| anyhow!("Failed to get config file: {}", e))?
            .json::<HashMap<String, JsonMarketConfig>>()
            .await
            .map_err(|e| anyhow!("Failed to parse config file: {}", e))?;

        let market_details = response
            .get(cluster)
            .ok_or_else(|| anyhow!("Failed to find cluster {} in config file", cluster))?;

        for market_key in market_details.markets.iter() {
            let market_key = Pubkey::from_str(market_key).map_err(|e| anyhow!(e))?;
            if self.markets.get(&market_key).is_some() {
                continue;
            }
            self.add_market(&market_key).await.map_err(|e| anyhow!(e))?;
        }

        Ok(())
    }

    pub fn add_all_markets_sync(&mut self) -> Result<()> {
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(self.add_all_markets())
    }

    pub async fn add_market(&mut self, market_key: &Pubkey) -> anyhow::Result<()> {
        let market_metadata = Self::get_market_metadata(&self.client, market_key).await?;
        self.markets.insert(*market_key, market_metadata);

        Ok(())
    }

    pub fn set_payer(&mut self, payer: Keypair) {
        self.trader = payer.pubkey();
        self.client.payer = payer;
    }

    pub fn set_trader(&mut self, trader: Pubkey) {
        self.trader = trader;
    }

    pub fn get_trader(&self) -> Pubkey {
        self.trader
    }

    pub async fn get_market_ladder(&self, market_key: &Pubkey, levels: u64) -> Result<Ladder> {
        let market_account_data = (self.client.get_account_data(market_key))
            .await
            .map_err(|_| anyhow!("Failed to get market account data"))?;
        let (header_bytes, bytes) = market_account_data.split_at(size_of::<MarketHeader>());
        let header: &MarketHeader =
            bytemuck::try_from_bytes(header_bytes).expect("Failed to deserialize market header");
        let market = load_with_dispatch(&header.market_size_params, bytes)
            .map_err(|_| anyhow!("Market configuration not found"))?
            .inner;

        Ok(market.get_ladder(levels))
    }

    pub fn get_market_ladder_sync(&self, market_key: &Pubkey, levels: u64) -> Result<Ladder> {
        let rt = tokio::runtime::Runtime::new()?; //fix error handling instead of panic
        rt.block_on(self.get_market_ladder(market_key, levels))
    }

    pub async fn get_market_orderbook(
        &self,
        market_key: &Pubkey,
    ) -> Result<Orderbook<FIFOOrderId, PhoenixOrder>> {
        let market_account_data = (self.client.get_account_data(market_key))
            .await
            .unwrap_or_default();
        let default = Orderbook::<FIFOOrderId, PhoenixOrder> {
            size_mult: 0.0,
            price_mult: 0.0,
            bids: BTreeMap::new(),
            asks: BTreeMap::new(),
        };
        if market_account_data.is_empty() {
            return Ok(default);
        }
        let (header_bytes, bytes) = market_account_data.split_at(size_of::<MarketHeader>());
        let base_lots_multiplier = self.base_lots_to_base_units_multiplier(market_key)?;
        let ticks_multiplier = self.ticks_to_float_price_multiplier(market_key)?;
        Ok(bytemuck::try_from_bytes::<MarketHeader>(header_bytes)
            .ok()
            .map(|header| {
                load_with_dispatch(&header.market_size_params, bytes)
                    .map(|market| {
                        Orderbook::from_market(market.inner, base_lots_multiplier, ticks_multiplier)
                    })
                    .unwrap_or_else(|_| default.clone())
            })
            .unwrap_or(default))
    }

    pub async fn get_market_orderbook_sync(
        &self,
        market_key: &Pubkey,
    ) -> Result<Orderbook<FIFOOrderId, PhoenixOrder>> {
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(self.get_market_orderbook(market_key))
    }

    pub async fn get_traders_with_market_key(
        &self,
        market_key: &Pubkey,
    ) -> Result<BTreeMap<Pubkey, TraderState>> {
        let market_account_data = match (self.client.get_account_data(market_key)).await {
            Ok(data) => data,
            Err(_) => return Ok(BTreeMap::new()),
        };
        let (header_bytes, bytes) = market_account_data.split_at(size_of::<MarketHeader>());
        let header = bytemuck::try_from_bytes::<MarketHeader>(header_bytes)
            .map_err(|_| anyhow!("Failed to deserialize market header"))?;
        let market = load_with_dispatch(&header.market_size_params, bytes)
            .map_err(|_| anyhow!("Market configuration not found"))?
            .inner;

        Ok(market
            .get_registered_traders()
            .iter()
            .map(|(k, v)| (*k, *v))
            .collect())
    }

    pub fn get_traders_with_market_key_sync(
        &self,
        market_key: &Pubkey,
    ) -> Result<BTreeMap<Pubkey, TraderState>> {
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(self.get_traders_with_market_key(market_key))
    }

    pub async fn get_market_state(&self, market_key: &Pubkey) -> Result<MarketState> {
        let market_account_data = match (self.client.get_account_data(market_key)).await {
            Ok(data) => data,
            Err(_) => {
                return Ok(MarketState {
                    orderbook: Orderbook {
                        size_mult: 0.0,
                        price_mult: 0.0,
                        bids: BTreeMap::new(),
                        asks: BTreeMap::new(),
                    },
                    traders: BTreeMap::new(),
                })
            }
        };
        let (header_bytes, bytes) = market_account_data.split_at(size_of::<MarketHeader>());
        let header = bytemuck::try_from_bytes::<MarketHeader>(header_bytes)
            .expect("Failed to deserialize market header");
        let market = load_with_dispatch(&header.market_size_params, bytes)
            .expect("Market configuration not found")
            .inner;

        let orderbook = Orderbook::from_market(
            market,
            self.base_lots_to_base_units_multiplier(market_key)?,
            self.ticks_to_float_price_multiplier(market_key)?,
        );

        let traders = market
            .get_registered_traders()
            .iter()
            .map(|(k, v)| (*k, *v))
            .collect();

        Ok(MarketState { orderbook, traders })
    }

    #[allow(clippy::useless_conversion)]
    async fn get_market_metadata(
        client: &EllipsisClient,
        market_key: &Pubkey,
    ) -> Result<MarketMetadata> {
        let market_account_data = (client.get_account_data(market_key))
            .await
            .map_err(|_| anyhow!("Failed to find market account"))?;
        let (header_bytes, bytes) = market_account_data.split_at(size_of::<MarketHeader>());
        let header = bytemuck::try_from_bytes::<MarketHeader>(header_bytes)
            .map_err(|_| anyhow!("Failed to deserialize market header"))?;
        let market = load_with_dispatch(&header.market_size_params, bytes)
            .map_err(|_| anyhow!("Market configuration not found"))?
            .inner;

        let base_mint_acct = spl_token::state::Mint::unpack(
            &client
                .get_account_data(&header.base_params.mint_key)
                .await
                .map_err(|_| anyhow!("Failed to find base mint account"))?,
        )
        .map_err(|_| anyhow!("Failed to deserialize base mint account"))?;
        let quote_mint_acct = spl_token::state::Mint::unpack(
            &client
                .get_account_data(&header.quote_params.mint_key)
                .await
                .map_err(|_| anyhow!("Failed to find quote mint account"))?,
        )
        .map_err(|_| anyhow!("Failed to deserialize quote mint account"))?;

        let quote_lot_size = header.get_quote_lot_size().into();
        let base_lot_size = header.get_base_lot_size().into();
        let quote_multiplier = 10u64.pow(quote_mint_acct.decimals as u32);
        let base_multiplier = 10u64.pow(base_mint_acct.decimals as u32);
        let base_mint = header.base_params.mint_key;
        let quote_mint = header.quote_params.mint_key;
        let tick_size_in_quote_atoms_per_base_unit =
            header.get_tick_size_in_quote_atoms_per_base_unit().into();
        let num_base_lots_per_base_unit = market.get_base_lots_per_base_unit().into();
        // max(1) is only relevant for old markets where the raw_base_units_per_base_unit was not set
        let raw_base_units_per_base_unit = header.raw_base_units_per_base_unit.max(1);

        Ok(MarketMetadata {
            base_mint,
            quote_mint,
            base_decimals: base_mint_acct.decimals as u32,
            quote_decimals: quote_mint_acct.decimals as u32,
            base_multiplier,
            quote_multiplier,
            tick_size_in_quote_atoms_per_base_unit,
            quote_lot_size,
            base_lot_size,
            num_base_lots_per_base_unit,
            raw_base_units_per_base_unit,
        })
    }

    pub async fn parse_events_from_transaction(
        &self,
        sig: &Signature,
    ) -> Option<Vec<PhoenixEvent>> {
        let tx = self.client.get_transaction(sig).await.ok()?;
        if tx.is_err {
            return None;
        }
        let raw_phoenix_events = self.core.parse_events_from_transaction(sig, &tx)?;
        let mut trade_direction = None;
        let mut market_events = vec![];
        let mut cached_metadata = self.markets.clone();
        for raw_phoenix_event in raw_phoenix_events {
            let header = raw_phoenix_event.header;
            if !cached_metadata.contains_key(&header.market) {
                cached_metadata.insert(
                    header.market.clone(),
                    Self::get_market_metadata(&self.client, &header.market)
                        .await
                        .ok()?,
                )?;
            }
            let meta = cached_metadata.get(&header.market)?;

            for phoenix_event in raw_phoenix_event.batch {
                match phoenix_event {
                    PhoenixMarketEvent::Fill(FillEvent {
                        index,
                        maker_id,
                        order_sequence_number,
                        price_in_ticks,
                        base_lots_filled,
                        base_lots_remaining,
                    }) => {
                        let side_filled = Side::from_order_sequence_number(order_sequence_number);
                        market_events.push(PhoenixEvent {
                            market: header.market,
                            sequence_number: header.sequence_number,
                            slot: header.slot,
                            timestamp: header.timestamp,
                            signature: *sig,
                            signer: header.signer,
                            event_index: index as u64,
                            details: MarketEventDetails::Fill(Fill {
                                order_sequence_number,
                                maker: maker_id,
                                taker: header.signer,
                                price_in_ticks,
                                base_lots_filled,
                                base_lots_remaining,
                                side_filled: Side::from_order_sequence_number(
                                    order_sequence_number,
                                ),
                                is_full_fill: base_lots_remaining == 0,
                            }),
                        });
                        if trade_direction.is_none() {
                            trade_direction = match side_filled {
                                Side::Bid => Some(-1),
                                Side::Ask => Some(1),
                            }
                        }
                    }
                    PhoenixMarketEvent::Reduce(ReduceEvent {
                        index,
                        order_sequence_number,
                        price_in_ticks,
                        base_lots_removed,
                        base_lots_remaining,
                    }) => market_events.push(PhoenixEvent {
                        market: header.market,
                        sequence_number: header.sequence_number,
                        slot: header.slot,
                        timestamp: header.timestamp,
                        signature: *sig,
                        signer: header.signer,
                        event_index: index as u64,
                        details: MarketEventDetails::Reduce(Reduce {
                            order_sequence_number,
                            maker: header.signer,
                            price_in_ticks,
                            base_lots_removed,
                            base_lots_remaining,
                            is_full_cancel: base_lots_remaining == 0,
                        }),
                    }),

                    PhoenixMarketEvent::Place(PlaceEvent {
                        index,
                        order_sequence_number,
                        client_order_id,
                        price_in_ticks,
                        base_lots_placed,
                    }) => market_events.push(PhoenixEvent {
                        market: header.market,
                        sequence_number: header.sequence_number,
                        slot: header.slot,
                        timestamp: header.timestamp,
                        signature: *sig,
                        signer: header.signer,
                        event_index: index as u64,
                        details: MarketEventDetails::Place(Place {
                            order_sequence_number,
                            client_order_id,
                            maker: header.signer,
                            price_in_ticks,
                            base_lots_placed,
                        }),
                    }),
                    PhoenixMarketEvent::Evict(EvictEvent {
                        index,
                        maker_id,
                        order_sequence_number,
                        price_in_ticks,
                        base_lots_evicted,
                    }) => market_events.push(PhoenixEvent {
                        market: header.market,
                        sequence_number: header.sequence_number,
                        slot: header.slot,
                        timestamp: header.timestamp,
                        signature: *sig,
                        signer: header.signer,
                        event_index: index as u64,
                        details: MarketEventDetails::Evict(Evict {
                            order_sequence_number,
                            maker: maker_id,
                            price_in_ticks,
                            base_lots_evicted,
                        }),
                    }),
                    PhoenixMarketEvent::FillSummary(FillSummaryEvent {
                        index,
                        client_order_id,
                        total_base_lots_filled,
                        total_quote_lots_filled,
                        total_fee_in_quote_lots,
                    }) => market_events.push(PhoenixEvent {
                        market: header.market,
                        sequence_number: header.sequence_number,
                        slot: header.slot,
                        timestamp: header.timestamp,
                        signature: *sig,
                        signer: header.signer,
                        event_index: index as u64,
                        details: MarketEventDetails::FillSummary(FillSummary {
                            client_order_id,
                            total_base_filled: total_base_lots_filled * meta.base_lot_size,
                            total_quote_filled_including_fees: total_quote_lots_filled
                                * meta.quote_lot_size,
                            total_quote_fees: total_fee_in_quote_lots * meta.quote_lot_size,
                            trade_direction: trade_direction.unwrap_or(0),
                        }),
                    }),
                    PhoenixMarketEvent::Fee(FeeEvent {
                        index,
                        fees_collected_in_quote_lots,
                    }) => market_events.push(PhoenixEvent {
                        market: header.market,
                        sequence_number: header.sequence_number,
                        slot: header.slot,
                        timestamp: header.timestamp,
                        signature: *sig,
                        signer: header.signer,
                        event_index: index as u64,
                        details: MarketEventDetails::Fee(
                            fees_collected_in_quote_lots * meta.quote_lot_size,
                        ),
                    }),
                    PhoenixMarketEvent::TimeInForce(TimeInForceEvent {
                        index,
                        order_sequence_number,
                        last_valid_slot,
                        last_valid_unix_timestamp_in_seconds,
                    }) => market_events.push(PhoenixEvent {
                        market: header.market,
                        sequence_number: header.sequence_number,
                        slot: header.slot,
                        timestamp: header.timestamp,
                        signature: *sig,
                        signer: header.signer,
                        event_index: index as u64,
                        details: MarketEventDetails::TimeInForce(TimeInForce {
                            order_sequence_number,
                            last_valid_slot,
                            last_valid_unix_timestamp_in_seconds,
                        }),
                    }),
                    PhoenixMarketEvent::ExpiredOrder(ExpiredOrderEvent {
                        index,
                        maker_id,
                        order_sequence_number,
                        price_in_ticks,
                        base_lots_removed,
                    }) => market_events.push(PhoenixEvent {
                        market: header.market,
                        sequence_number: header.sequence_number,
                        slot: header.slot,
                        timestamp: header.timestamp,
                        signature: *sig,
                        signer: header.signer,
                        event_index: index as u64,
                        details: MarketEventDetails::Reduce(Reduce {
                            order_sequence_number,
                            maker: maker_id,
                            price_in_ticks,
                            base_lots_removed,
                            base_lots_remaining: 0,
                            is_full_cancel: true,
                        }),
                    }),
                    _ => {
                        println!("Unknown event: {:?}", phoenix_event);
                    }
                }
            }
        }
        Some(market_events)
    }

    pub async fn parse_places(&self, signature: &Signature) -> Vec<PhoenixEvent> {
        let events = self
            .parse_events_from_transaction(signature)
            .await
            .unwrap_or_default();
        events
            .iter()
            .filter_map(|&event| match event.details {
                MarketEventDetails::Place(..) => Some(event),
                _ => None,
            })
            .collect::<Vec<PhoenixEvent>>()
    }

    pub async fn parse_cancels(&self, signature: &Signature) -> Vec<PhoenixEvent> {
        let events = self
            .parse_events_from_transaction(signature)
            .await
            .unwrap_or_default();
        events
            .iter()
            .filter_map(|&event| match event.details {
                MarketEventDetails::Reduce(..) => Some(event),
                _ => None,
            })
            .collect::<Vec<PhoenixEvent>>()
    }

    pub async fn parse_fills(&self, signature: &Signature) -> Vec<PhoenixEvent> {
        let events = self
            .parse_events_from_transaction(signature)
            .await
            .unwrap_or_default();
        events
            .iter()
            .filter_map(|&event| match event.details {
                MarketEventDetails::Fill(..) => Some(event),
                _ => None,
            })
            .collect::<Vec<PhoenixEvent>>()
    }

    pub async fn parse_fills_and_places(
        &self,
        signature: &Signature,
    ) -> (Vec<PhoenixEvent>, Vec<PhoenixEvent>) {
        let events = self
            .parse_events_from_transaction(signature)
            .await
            .unwrap_or_default();
        let fills = events
            .iter()
            .filter_map(|&event| match event.details {
                MarketEventDetails::Fill(..) => Some(event),
                _ => None,
            })
            .collect::<Vec<PhoenixEvent>>();
        let places = events
            .iter()
            .filter_map(|&event| match event.details {
                MarketEventDetails::Place(..) => Some(event),
                _ => None,
            })
            .collect::<Vec<PhoenixEvent>>();

        (fills, places)
    }

    pub async fn send_ioc(
        &self,
        market_key: &Pubkey,
        price: u64,
        side: Side,
        size: u64,
    ) -> Option<(Signature, Vec<PhoenixEvent>)> {
        let new_order_ix = self.get_ioc_ix(market_key, price, side, size).ok()?;
        let signature = self
            .client
            .sign_send_instructions(vec![new_order_ix], vec![])
            .await
            .ok()?;
        let fills = self.parse_fills(&signature).await;
        Some((signature, fills))
    }

    pub async fn send_fok_buy(
        &self,
        market_key: &Pubkey,
        price: u64,
        size_in_quote_lots: u64,
    ) -> Option<(Signature, Vec<PhoenixEvent>)> {
        let new_order_ix = self
            .get_fok_buy_ix(market_key, price, size_in_quote_lots)
            .ok()?;

        let signature = self
            .client
            .sign_send_instructions(vec![new_order_ix], vec![])
            .await
            .ok()?;
        let fills = self.parse_fills(&signature).await;
        Some((signature, fills))
    }

    pub async fn send_fok_sell(
        &self,
        market_key: &Pubkey,
        price: u64,
        size_in_base_lots: u64,
    ) -> Option<(Signature, Vec<PhoenixEvent>)> {
        let new_order_ix = self
            .get_fok_sell_ix(market_key, price, size_in_base_lots)
            .ok()?;

        let signature = self
            .client
            .sign_send_instructions(vec![new_order_ix], vec![])
            .await
            .ok()?;
        let fills = self.parse_fills(&signature).await;
        Some((signature, fills))
    }

    pub async fn send_ioc_with_slippage(
        &self,
        market_key: &Pubkey,
        lots_in: u64,
        min_lots_out: u64,
        side: Side,
    ) -> Option<(Signature, Vec<PhoenixEvent>)> {
        let new_order_ix = self
            .get_ioc_with_slippage_ix(market_key, lots_in, min_lots_out, side)
            .ok()?;
        let signature = self
            .client
            .sign_send_instructions(vec![new_order_ix], vec![])
            .await
            .ok()?;
        let fills = self.parse_fills(&signature).await;
        Some((signature, fills))
    }

    pub async fn send_post_only(
        &self,
        market_key: &Pubkey,
        price: u64,
        side: Side,
        size: u64,
    ) -> Option<(Signature, Vec<PhoenixEvent>)> {
        let new_order_ix = self.get_post_only_ix(market_key, price, side, size).ok()?;
        let signature = self
            .client
            .sign_send_instructions(vec![new_order_ix], vec![])
            .await
            .ok()?;
        let fills = self.parse_fills(&signature).await;
        Some((signature, fills))
    }

    pub async fn send_limit_order(
        &self,
        market_key: &Pubkey,
        price: u64,
        side: Side,
        size: u64,
    ) -> Option<(Signature, Vec<PhoenixEvent>, Vec<PhoenixEvent>)> {
        let new_order_ix = self
            .get_limit_order_ix(market_key, price, side, size)
            .ok()?;
        let signature = self
            .client
            .sign_send_instructions(vec![new_order_ix], vec![])
            .await
            .ok()?;
        let (fills, places) = self.parse_fills_and_places(&signature).await;
        Some((signature, places, fills))
    }

    pub async fn send_cancel_ids(
        &self,
        market_key: &Pubkey,
        ids: Vec<FIFOOrderId>,
    ) -> Option<(Signature, Vec<PhoenixEvent>)> {
        let cancel_ix = self.get_cancel_ids_ix(market_key, ids).ok()?;
        let signature = self
            .client
            .sign_send_instructions(vec![cancel_ix], vec![])
            .await
            .ok()?;

        let cancels = self.parse_cancels(&signature).await;
        Some((signature, cancels))
    }

    pub async fn send_cancel_up_to(
        &self,
        market_key: &Pubkey,
        tick_limit: Option<u64>,
        side: Side,
    ) -> Option<(Signature, Vec<PhoenixEvent>)> {
        let cancel_ix = self
            .get_cancel_up_to_ix(market_key, tick_limit, side)
            .ok()?;
        let signature = self
            .client
            .sign_send_instructions(vec![cancel_ix], vec![])
            .await
            .ok()?;

        let cancels = self.parse_cancels(&signature).await;
        Some((signature, cancels))
    }

    pub async fn send_cancel_all(
        &self,
        market_key: &Pubkey,
    ) -> Option<(Signature, Vec<PhoenixEvent>)> {
        let cancel_all_ix = self.get_cancel_all_ix(market_key).ok()?;
        let signature = self
            .client
            .sign_send_instructions(vec![cancel_all_ix], vec![])
            .await
            .ok()?;

        let cancels = self.parse_cancels(&signature).await;
        Some((signature, cancels))
    }
}