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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
#![cfg_attr(not(feature = "program"), allow(unused))]
use crate::error::DexError;
use crate::matching::{OrderType, Side};
use bytemuck::cast;
use serde::{Deserialize, Serialize};
use solana_program::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
sysvar::rent,
};
use std::convert::TryInto;
use arrayref::{array_ref, array_refs};
use num_enum::{IntoPrimitive, TryFromPrimitive};
use std::num::NonZeroU64;
#[cfg(test)]
use proptest::prelude::*;
#[cfg(test)]
use proptest_derive::Arbitrary;
pub mod srm_token {
use solana_program::declare_id;
declare_id!("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt");
}
pub mod msrm_token {
use solana_program::declare_id;
declare_id!("MSRMcoVyrFxnSgo5uXwone5SKcGhT1KEJMFEkMEWf9L");
}
pub mod disable_authority {
use solana_program::declare_id;
declare_id!("5ZVJgwWxMsqXxRMYHXqMwH2hd4myX5Ef4Au2iUsuNQ7V");
}
pub mod fee_sweeper {
use solana_program::declare_id;
declare_id!("DeqYsmBd9BnrbgUwQjVH4sQWK71dEgE6eoZFw3Rp4ftE");
}
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(test, derive(Arbitrary))]
#[cfg_attr(test, proptest(no_params))]
#[cfg_attr(feature = "fuzz", derive(arbitrary::Arbitrary))]
pub struct InitializeMarketInstruction {
pub coin_lot_size: u64,
pub pc_lot_size: u64,
pub fee_rate_bps: u16,
pub vault_signer_nonce: u64,
pub pc_dust_threshold: u64,
}
#[derive(
PartialEq, Eq, Copy, Clone, Debug, TryFromPrimitive, IntoPrimitive, Serialize, Deserialize,
)]
#[cfg_attr(test, derive(Arbitrary))]
#[cfg_attr(feature = "fuzz", derive(arbitrary::Arbitrary))]
#[repr(u8)]
pub enum SelfTradeBehavior {
DecrementTake = 0,
CancelProvide = 1,
AbortTransaction = 2,
}
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(test, derive(Arbitrary))]
pub struct SendTakeInstruction {
pub side: Side,
#[cfg_attr(
test,
proptest(strategy = "(1u64..=std::u64::MAX).prop_map(|x| NonZeroU64::new(x).unwrap())")
)]
pub limit_price: NonZeroU64,
#[cfg_attr(
test,
proptest(strategy = "(1u64..=std::u64::MAX).prop_map(|x| NonZeroU64::new(x).unwrap())")
)]
pub max_coin_qty: NonZeroU64,
#[cfg_attr(
test,
proptest(strategy = "(1u64..=std::u64::MAX).prop_map(|x| NonZeroU64::new(x).unwrap())")
)]
pub max_native_pc_qty_including_fees: NonZeroU64,
pub min_coin_qty: u64,
pub min_native_pc_qty: u64,
pub limit: u16,
}
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(test, derive(Arbitrary))]
pub struct NewOrderInstructionV3 {
pub side: Side,
#[cfg_attr(
test,
proptest(strategy = "(1u64..=std::u64::MAX).prop_map(|x| NonZeroU64::new(x).unwrap())")
)]
pub limit_price: NonZeroU64,
#[cfg_attr(
test,
proptest(strategy = "(1u64..=std::u64::MAX).prop_map(|x| NonZeroU64::new(x).unwrap())")
)]
pub max_coin_qty: NonZeroU64,
#[cfg_attr(
test,
proptest(strategy = "(1u64..=std::u64::MAX).prop_map(|x| NonZeroU64::new(x).unwrap())")
)]
pub max_native_pc_qty_including_fees: NonZeroU64,
pub self_trade_behavior: SelfTradeBehavior,
pub order_type: OrderType,
pub client_order_id: u64,
pub limit: u16,
}
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(test, derive(Arbitrary))]
pub struct NewOrderInstructionV2 {
pub side: Side,
#[cfg_attr(
test,
proptest(strategy = "(1u64..=std::u64::MAX).prop_map(|x| NonZeroU64::new(x).unwrap())")
)]
pub limit_price: NonZeroU64,
#[cfg_attr(
test,
proptest(strategy = "(1u64..=std::u64::MAX).prop_map(|x| NonZeroU64::new(x).unwrap())")
)]
pub max_qty: NonZeroU64,
pub order_type: OrderType,
pub client_id: u64,
pub self_trade_behavior: SelfTradeBehavior,
}
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(test, derive(Arbitrary))]
pub struct NewOrderInstructionV1 {
pub side: Side,
#[cfg_attr(
test,
proptest(strategy = "(1u64..=std::u64::MAX).prop_map(|x| NonZeroU64::new(x).unwrap())")
)]
pub limit_price: NonZeroU64,
#[cfg_attr(
test,
proptest(strategy = "(1u64..=std::u64::MAX).prop_map(|x| NonZeroU64::new(x).unwrap())")
)]
pub max_qty: NonZeroU64,
pub order_type: OrderType,
pub client_id: u64,
}
impl NewOrderInstructionV1 {
pub fn add_self_trade_behavior(
self,
self_trade_behavior: SelfTradeBehavior,
) -> NewOrderInstructionV2 {
let NewOrderInstructionV1 {
side,
limit_price,
max_qty,
order_type,
client_id,
} = self;
NewOrderInstructionV2 {
side,
limit_price,
max_qty,
order_type,
client_id,
self_trade_behavior,
}
}
}
impl SendTakeInstruction {
fn unpack(data: &[u8; 46]) -> Option<Self> {
let (
&side_arr,
&price_arr,
&max_coin_qty_arr,
&max_native_pc_qty_arr,
&min_coin_qty_arr,
&min_native_pc_qty_arr,
&limit_arr,
) = array_refs![data, 4, 8, 8, 8, 8, 8, 2];
let side = Side::try_from_primitive(u32::from_le_bytes(side_arr).try_into().ok()?).ok()?;
let limit_price = NonZeroU64::new(u64::from_le_bytes(price_arr))?;
let max_coin_qty = NonZeroU64::new(u64::from_le_bytes(max_coin_qty_arr))?;
let max_native_pc_qty_including_fees =
NonZeroU64::new(u64::from_le_bytes(max_native_pc_qty_arr))?;
let min_coin_qty = u64::from_le_bytes(min_coin_qty_arr);
let min_native_pc_qty = u64::from_le_bytes(min_native_pc_qty_arr);
let limit = u16::from_le_bytes(limit_arr);
Some(SendTakeInstruction {
side,
limit_price,
max_coin_qty,
max_native_pc_qty_including_fees,
min_coin_qty,
min_native_pc_qty,
limit,
})
}
}
impl NewOrderInstructionV3 {
fn unpack(data: &[u8; 46]) -> Option<Self> {
let (
&side_arr,
&price_arr,
&max_coin_qty_arr,
&max_native_pc_qty_arr,
&self_trade_behavior_arr,
&otype_arr,
&client_order_id_bytes,
&limit_arr,
) = array_refs![data, 4, 8, 8, 8, 4, 4, 8, 2];
let side = Side::try_from_primitive(u32::from_le_bytes(side_arr).try_into().ok()?).ok()?;
let limit_price = NonZeroU64::new(u64::from_le_bytes(price_arr))?;
let max_coin_qty = NonZeroU64::new(u64::from_le_bytes(max_coin_qty_arr))?;
let max_native_pc_qty_including_fees =
NonZeroU64::new(u64::from_le_bytes(max_native_pc_qty_arr))?;
let self_trade_behavior = SelfTradeBehavior::try_from_primitive(
u32::from_le_bytes(self_trade_behavior_arr)
.try_into()
.ok()?,
)
.ok()?;
let order_type =
OrderType::try_from_primitive(u32::from_le_bytes(otype_arr).try_into().ok()?).ok()?;
let client_order_id = u64::from_le_bytes(client_order_id_bytes);
let limit = u16::from_le_bytes(limit_arr);
Some(NewOrderInstructionV3 {
side,
limit_price,
max_coin_qty,
max_native_pc_qty_including_fees,
self_trade_behavior,
order_type,
client_order_id,
limit,
})
}
}
impl NewOrderInstructionV1 {
fn unpack(data: &[u8; 32]) -> Option<Self> {
let (&side_arr, &price_arr, &max_qty_arr, &otype_arr, &client_id_bytes) =
array_refs![data, 4, 8, 8, 4, 8];
let client_id = u64::from_le_bytes(client_id_bytes);
let side = match u32::from_le_bytes(side_arr) {
0 => Side::Bid,
1 => Side::Ask,
_ => return None,
};
let limit_price = NonZeroU64::new(u64::from_le_bytes(price_arr))?;
let max_qty = NonZeroU64::new(u64::from_le_bytes(max_qty_arr))?;
let order_type = match u32::from_le_bytes(otype_arr) {
0 => OrderType::Limit,
1 => OrderType::ImmediateOrCancel,
2 => OrderType::PostOnly,
_ => return None,
};
Some(NewOrderInstructionV1 {
side,
limit_price,
max_qty,
order_type,
client_id,
})
}
}
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(test, derive(Arbitrary))]
#[cfg_attr(feature = "fuzz", derive(arbitrary::Arbitrary))]
pub struct CancelOrderInstructionV2 {
pub side: Side,
pub order_id: u128,
}
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(test, derive(Arbitrary))]
#[cfg_attr(feature = "fuzz", derive(arbitrary::Arbitrary))]
pub struct CancelOrderInstruction {
pub side: Side,
pub order_id: u128,
pub owner: [u64; 4],
pub owner_slot: u8,
}
impl CancelOrderInstructionV2 {
fn unpack(data: &[u8; 20]) -> Option<Self> {
let (&side_arr, &oid_arr) = array_refs![data, 4, 16];
let side = Side::try_from_primitive(u32::from_le_bytes(side_arr).try_into().ok()?).ok()?;
let order_id = u128::from_le_bytes(oid_arr);
Some(CancelOrderInstructionV2 { side, order_id })
}
}
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(test, derive(Arbitrary))]
#[cfg_attr(feature = "fuzz", derive(arbitrary::Arbitrary))]
pub enum MarketInstruction {
InitializeMarket(InitializeMarketInstruction),
NewOrder(NewOrderInstructionV1),
MatchOrders(u16),
ConsumeEvents(u16),
CancelOrder(CancelOrderInstruction),
SettleFunds,
CancelOrderByClientId(u64),
DisableMarket,
SweepFees,
NewOrderV2(NewOrderInstructionV2),
NewOrderV3(NewOrderInstructionV3),
CancelOrderV2(CancelOrderInstructionV2),
CancelOrderByClientIdV2(u64),
SendTake(SendTakeInstruction),
CloseOpenOrders,
InitOpenOrders,
Prune(u16),
ConsumeEventsPermissioned(u16),
}
impl MarketInstruction {
pub fn pack(&self) -> Vec<u8> {
bincode::serialize(&(0u8, self)).unwrap()
}
pub fn unpack(versioned_bytes: &[u8]) -> Option<Self> {
if versioned_bytes.len() < 5 || versioned_bytes.len() > 58 {
return None;
}
let (&[version], &discrim, data) = array_refs![versioned_bytes, 1, 4; ..;];
if version != 0 {
return None;
}
let discrim = u32::from_le_bytes(discrim);
Some(match (discrim, data.len()) {
(0, 34) => MarketInstruction::InitializeMarket({
let data_array = array_ref![data, 0, 34];
let fields = array_refs![data_array, 8, 8, 2, 8, 8];
InitializeMarketInstruction {
coin_lot_size: u64::from_le_bytes(*fields.0),
pc_lot_size: u64::from_le_bytes(*fields.1),
fee_rate_bps: u16::from_le_bytes(*fields.2),
vault_signer_nonce: u64::from_le_bytes(*fields.3),
pc_dust_threshold: u64::from_le_bytes(*fields.4),
}
}),
(1, 32) => MarketInstruction::NewOrder({
let data_arr = array_ref![data, 0, 32];
NewOrderInstructionV1::unpack(data_arr)?
}),
(2, 2) => {
let limit = array_ref![data, 0, 2];
MarketInstruction::MatchOrders(u16::from_le_bytes(*limit))
}
(3, 2) => {
let limit = array_ref![data, 0, 2];
MarketInstruction::ConsumeEvents(u16::from_le_bytes(*limit))
}
(4, 53) => MarketInstruction::CancelOrder({
let data_array = array_ref![data, 0, 53];
let fields = array_refs![data_array, 4, 16, 32, 1];
let side = match u32::from_le_bytes(*fields.0) {
0 => Side::Bid,
1 => Side::Ask,
_ => return None,
};
let order_id = u128::from_le_bytes(*fields.1);
let owner = cast(*fields.2);
let &[owner_slot] = fields.3;
CancelOrderInstruction {
side,
order_id,
owner,
owner_slot,
}
}),
(5, 0) => MarketInstruction::SettleFunds,
(6, 8) => {
let client_id = array_ref![data, 0, 8];
MarketInstruction::CancelOrderByClientId(u64::from_le_bytes(*client_id))
}
(7, 0) => MarketInstruction::DisableMarket,
(8, 0) => MarketInstruction::SweepFees,
(9, 36) => MarketInstruction::NewOrderV2({
let data_arr = array_ref![data, 0, 36];
let (v1_data_arr, v2_data_arr) = array_refs![data_arr, 32, 4];
let v1_instr = NewOrderInstructionV1::unpack(v1_data_arr)?;
let self_trade_behavior = SelfTradeBehavior::try_from_primitive(
u32::from_le_bytes(*v2_data_arr).try_into().ok()?,
)
.ok()?;
v1_instr.add_self_trade_behavior(self_trade_behavior)
}),
(10, 46) => MarketInstruction::NewOrderV3({
let data_arr = array_ref![data, 0, 46];
NewOrderInstructionV3::unpack(data_arr)?
}),
(11, 20) => MarketInstruction::CancelOrderV2({
let data_arr = array_ref![data, 0, 20];
CancelOrderInstructionV2::unpack(data_arr)?
}),
(12, 8) => {
let client_id = array_ref![data, 0, 8];
MarketInstruction::CancelOrderByClientIdV2(u64::from_le_bytes(*client_id))
}
(13, 46) => MarketInstruction::SendTake({
let data_arr = array_ref![data, 0, 46];
SendTakeInstruction::unpack(data_arr)?
}),
(14, 0) => MarketInstruction::CloseOpenOrders,
(15, 0) => MarketInstruction::InitOpenOrders,
(16, 2) => {
let limit = array_ref![data, 0, 2];
MarketInstruction::Prune(u16::from_le_bytes(*limit))
}
(17, 2) => {
let limit = array_ref![data, 0, 2];
MarketInstruction::ConsumeEventsPermissioned(u16::from_le_bytes(*limit))
}
_ => return None,
})
}
#[cfg(test)]
#[inline]
pub fn unpack_serde(data: &[u8]) -> Result<Self, ()> {
match data.split_first() {
None => Err(()),
Some((&0u8, rest)) => bincode::deserialize(rest).map_err(|_| ()),
Some((_, _rest)) => Err(()),
}
}
}
pub fn initialize_market(
market: &Pubkey,
program_id: &Pubkey,
coin_mint_pk: &Pubkey,
pc_mint_pk: &Pubkey,
coin_vault_pk: &Pubkey,
pc_vault_pk: &Pubkey,
authority_pk: Option<&Pubkey>,
prune_authority_pk: Option<&Pubkey>,
consume_events_authority_pk: Option<&Pubkey>,
bids_pk: &Pubkey,
asks_pk: &Pubkey,
req_q_pk: &Pubkey,
event_q_pk: &Pubkey,
coin_lot_size: u64,
pc_lot_size: u64,
vault_signer_nonce: u64,
pc_dust_threshold: u64,
) -> Result<solana_program::instruction::Instruction, DexError> {
let data = MarketInstruction::InitializeMarket(InitializeMarketInstruction {
coin_lot_size,
pc_lot_size,
fee_rate_bps: 0,
vault_signer_nonce,
pc_dust_threshold,
})
.pack();
let market_account = AccountMeta::new(*market, false);
let bids = AccountMeta::new(*bids_pk, false);
let asks = AccountMeta::new(*asks_pk, false);
let req_q = AccountMeta::new(*req_q_pk, false);
let event_q = AccountMeta::new(*event_q_pk, false);
let coin_vault = AccountMeta::new(*coin_vault_pk, false);
let pc_vault = AccountMeta::new(*pc_vault_pk, false);
let coin_mint = AccountMeta::new_readonly(*coin_mint_pk, false);
let pc_mint = AccountMeta::new_readonly(*pc_mint_pk, false);
let rent_sysvar = AccountMeta::new_readonly(solana_program::sysvar::rent::ID, false);
let mut accounts = vec![
market_account,
req_q,
event_q,
bids,
asks,
coin_vault,
pc_vault,
coin_mint,
pc_mint,
rent_sysvar,
];
if let Some(auth) = authority_pk {
let authority = AccountMeta::new_readonly(*auth, false);
accounts.push(authority);
if let Some(prune_auth) = prune_authority_pk {
let authority = AccountMeta::new_readonly(*prune_auth, false);
accounts.push(authority);
if let Some(consume_events_auth) = consume_events_authority_pk {
let authority = AccountMeta::new_readonly(*consume_events_auth, false);
accounts.push(authority);
}
}
}
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
pub fn new_order(
market: &Pubkey,
open_orders_account: &Pubkey,
request_queue: &Pubkey,
event_queue: &Pubkey,
market_bids: &Pubkey,
market_asks: &Pubkey,
order_payer: &Pubkey,
open_orders_account_owner: &Pubkey,
coin_vault: &Pubkey,
pc_vault: &Pubkey,
spl_token_program_id: &Pubkey,
rent_sysvar_id: &Pubkey,
srm_account_referral: Option<&Pubkey>,
program_id: &Pubkey,
side: Side,
limit_price: NonZeroU64,
max_coin_qty: NonZeroU64,
order_type: OrderType,
client_order_id: u64,
self_trade_behavior: SelfTradeBehavior,
limit: u16,
max_native_pc_qty_including_fees: NonZeroU64,
) -> Result<Instruction, DexError> {
let data = MarketInstruction::NewOrderV3(NewOrderInstructionV3 {
side,
limit_price,
max_coin_qty,
order_type,
client_order_id,
self_trade_behavior,
limit,
max_native_pc_qty_including_fees,
})
.pack();
let mut accounts = vec![
AccountMeta::new(*market, false),
AccountMeta::new(*open_orders_account, false),
AccountMeta::new(*request_queue, false),
AccountMeta::new(*event_queue, false),
AccountMeta::new(*market_bids, false),
AccountMeta::new(*market_asks, false),
AccountMeta::new(*order_payer, false),
AccountMeta::new_readonly(*open_orders_account_owner, true),
AccountMeta::new(*coin_vault, false),
AccountMeta::new(*pc_vault, false),
AccountMeta::new_readonly(*spl_token_program_id, false),
AccountMeta::new_readonly(*rent_sysvar_id, false),
];
if let Some(key) = srm_account_referral {
accounts.push(AccountMeta::new_readonly(*key, false))
}
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
pub fn match_orders(
program_id: &Pubkey,
market: &Pubkey,
request_queue: &Pubkey,
bids: &Pubkey,
asks: &Pubkey,
event_queue: &Pubkey,
coin_fee_receivable_account: &Pubkey,
pc_fee_receivable_account: &Pubkey,
limit: u16,
) -> Result<Instruction, DexError> {
let data = MarketInstruction::MatchOrders(limit).pack();
let accounts: Vec<AccountMeta> = vec![
AccountMeta::new(*market, false),
AccountMeta::new(*request_queue, false),
AccountMeta::new(*event_queue, false),
AccountMeta::new(*bids, false),
AccountMeta::new(*asks, false),
AccountMeta::new(*coin_fee_receivable_account, false),
AccountMeta::new(*pc_fee_receivable_account, false),
];
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
pub fn consume_events(
program_id: &Pubkey,
open_orders_accounts: Vec<&Pubkey>,
market: &Pubkey,
event_queue: &Pubkey,
coin_fee_receivable_account: &Pubkey,
pc_fee_receivable_account: &Pubkey,
limit: u16,
) -> Result<Instruction, DexError> {
let data = MarketInstruction::ConsumeEvents(limit).pack();
let mut accounts: Vec<AccountMeta> = open_orders_accounts
.iter()
.map(|key| AccountMeta::new(**key, false))
.collect();
accounts.append(&mut vec![
AccountMeta::new(*market, false),
AccountMeta::new(*event_queue, false),
AccountMeta::new(*coin_fee_receivable_account, false),
AccountMeta::new(*pc_fee_receivable_account, false),
]);
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
pub fn consume_events_permissioned(
program_id: &Pubkey,
open_orders_accounts: Vec<&Pubkey>,
market: &Pubkey,
event_queue: &Pubkey,
consume_events_authority: &Pubkey,
limit: u16,
) -> Result<Instruction, DexError> {
let data = MarketInstruction::ConsumeEventsPermissioned(limit).pack();
let mut accounts: Vec<AccountMeta> = open_orders_accounts
.iter()
.map(|key| AccountMeta::new(**key, false))
.collect();
accounts.append(&mut vec![
AccountMeta::new(*market, false),
AccountMeta::new(*event_queue, false),
AccountMeta::new_readonly(*consume_events_authority, true),
]);
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
pub fn cancel_order(
program_id: &Pubkey,
market: &Pubkey,
market_bids: &Pubkey,
market_asks: &Pubkey,
open_orders_account: &Pubkey,
open_orders_account_owner: &Pubkey,
event_queue: &Pubkey,
side: Side,
order_id: u128,
) -> Result<Instruction, DexError> {
let data = MarketInstruction::CancelOrderV2(CancelOrderInstructionV2 { side, order_id }).pack();
let accounts: Vec<AccountMeta> = vec![
AccountMeta::new(*market, false),
AccountMeta::new(*market_bids, false),
AccountMeta::new(*market_asks, false),
AccountMeta::new(*open_orders_account, false),
AccountMeta::new_readonly(*open_orders_account_owner, true),
AccountMeta::new(*event_queue, false),
];
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
pub fn settle_funds(
program_id: &Pubkey,
market: &Pubkey,
spl_token_program_id: &Pubkey,
open_orders_account: &Pubkey,
open_orders_account_owner: &Pubkey,
coin_vault: &Pubkey,
coin_wallet: &Pubkey,
pc_vault: &Pubkey,
pc_wallet: &Pubkey,
referrer_pc_wallet: Option<&Pubkey>,
vault_signer: &Pubkey,
) -> Result<Instruction, DexError> {
let data = MarketInstruction::SettleFunds.pack();
let mut accounts: Vec<AccountMeta> = vec![
AccountMeta::new(*market, false),
AccountMeta::new(*open_orders_account, false),
AccountMeta::new_readonly(*open_orders_account_owner, true),
AccountMeta::new(*coin_vault, false),
AccountMeta::new(*pc_vault, false),
AccountMeta::new(*coin_wallet, false),
AccountMeta::new(*pc_wallet, false),
AccountMeta::new_readonly(*vault_signer, false),
AccountMeta::new_readonly(*spl_token_program_id, false),
];
if let Some(key) = referrer_pc_wallet {
accounts.push(AccountMeta::new(*key, false))
}
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
pub fn cancel_order_by_client_order_id(
program_id: &Pubkey,
market: &Pubkey,
market_bids: &Pubkey,
market_asks: &Pubkey,
open_orders_account: &Pubkey,
open_orders_account_owner: &Pubkey,
event_queue: &Pubkey,
client_order_id: u64,
) -> Result<Instruction, DexError> {
let data = MarketInstruction::CancelOrderByClientIdV2(client_order_id).pack();
let accounts: Vec<AccountMeta> = vec![
AccountMeta::new(*market, false),
AccountMeta::new(*market_bids, false),
AccountMeta::new(*market_asks, false),
AccountMeta::new(*open_orders_account, false),
AccountMeta::new_readonly(*open_orders_account_owner, true),
AccountMeta::new(*event_queue, false),
];
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
pub fn disable_market(
program_id: &Pubkey,
market: &Pubkey,
disable_authority_key: &Pubkey,
) -> Result<Instruction, DexError> {
let data = MarketInstruction::DisableMarket.pack();
let accounts: Vec<AccountMeta> = vec![
AccountMeta::new(*market, false),
AccountMeta::new_readonly(*disable_authority_key, true),
];
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
pub fn sweep_fees(
program_id: &Pubkey,
market: &Pubkey,
pc_vault: &Pubkey,
fee_sweeping_authority: &Pubkey,
fee_receivable_account: &Pubkey,
vault_signer: &Pubkey,
spl_token_program_id: &Pubkey,
) -> Result<Instruction, DexError> {
let data = MarketInstruction::SweepFees.pack();
let accounts: Vec<AccountMeta> = vec![
AccountMeta::new(*market, false),
AccountMeta::new(*pc_vault, false),
AccountMeta::new_readonly(*fee_sweeping_authority, true),
AccountMeta::new(*fee_receivable_account, false),
AccountMeta::new_readonly(*vault_signer, false),
AccountMeta::new_readonly(*spl_token_program_id, false),
];
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
pub fn close_open_orders(
program_id: &Pubkey,
open_orders: &Pubkey,
owner: &Pubkey,
destination: &Pubkey,
market: &Pubkey,
) -> Result<Instruction, DexError> {
let data = MarketInstruction::CloseOpenOrders.pack();
let accounts: Vec<AccountMeta> = vec![
AccountMeta::new(*open_orders, false),
AccountMeta::new_readonly(*owner, true),
AccountMeta::new(*destination, false),
AccountMeta::new_readonly(*market, false),
];
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
pub fn init_open_orders(
program_id: &Pubkey,
open_orders: &Pubkey,
owner: &Pubkey,
market: &Pubkey,
market_authority: Option<&Pubkey>,
) -> Result<Instruction, DexError> {
let data = MarketInstruction::InitOpenOrders.pack();
let mut accounts: Vec<AccountMeta> = vec![
AccountMeta::new(*open_orders, false),
AccountMeta::new_readonly(*owner, true),
AccountMeta::new_readonly(*market, false),
AccountMeta::new_readonly(rent::ID, false),
];
if let Some(market_authority) = market_authority {
accounts.push(AccountMeta::new_readonly(*market_authority, true));
}
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
pub fn prune(
program_id: &Pubkey,
market: &Pubkey,
bids: &Pubkey,
asks: &Pubkey,
prune_authority: &Pubkey,
open_orders: &Pubkey,
open_orders_owner: &Pubkey,
event_q: &Pubkey,
limit: u16,
) -> Result<Instruction, DexError> {
let data = MarketInstruction::Prune(limit).pack();
let accounts: Vec<AccountMeta> = vec![
AccountMeta::new(*market, false),
AccountMeta::new(*bids, false),
AccountMeta::new(*asks, false),
AccountMeta::new_readonly(*prune_authority, true),
AccountMeta::new(*open_orders, false),
AccountMeta::new_readonly(*open_orders_owner, false),
AccountMeta::new(*event_q, false),
];
Ok(Instruction {
program_id: *program_id,
data,
accounts,
})
}
#[cfg(test)]
mod tests {
use super::*;
proptest! {
#[test]
fn test_pack_unpack_roundtrip(inst: MarketInstruction) {
let serialized = inst.pack();
let unpack_serde_result = MarketInstruction::unpack_serde(&serialized).ok();
let unpack_result = MarketInstruction::unpack(&serialized);
assert_eq!(unpack_result, Some(inst));
assert!(unpack_serde_result == unpack_result,
"Serialized:\n{:?}\nLeft:\n{:#?}\nRight:\n{:#?}",
serialized, unpack_serde_result, unpack_result
);
}
}
}
#[cfg(feature = "fuzz")]
mod fuzzing {
use super::*;
use crate::matching::{OrderType, Side};
use arbitrary::Unstructured;
use std::convert::{TryFrom, TryInto};
#[derive(arbitrary::Arbitrary)]
struct NewOrderInstructionU64 {
pub side: Side,
pub limit_price: u64,
pub max_qty: u64,
pub order_type: OrderType,
pub client_id: u64,
pub self_trade_behavior: SelfTradeBehavior,
}
#[derive(arbitrary::Arbitrary)]
struct NewOrderInstructionV3U64 {
pub side: Side,
pub limit_price: u64,
pub max_coin_qty: u64,
pub max_native_pc_qty_including_fees: u64,
pub self_trade_behavior: SelfTradeBehavior,
pub order_type: OrderType,
pub client_order_id: u64,
pub limit: u16,
}
#[derive(arbitrary::Arbitrary)]
struct SendTakeInstructionU64 {
pub side: Side,
pub limit_price: u64,
pub max_coin_qty: u64,
pub max_native_pc_qty_including_fees: u64,
pub min_coin_qty: u64,
pub min_native_pc_qty: u64,
pub limit: u16,
}
impl TryFrom<SendTakeInstructionU64> for SendTakeInstruction {
type Error = std::num::TryFromIntError;
fn try_from(value: SendTakeInstructionU64) -> Result<Self, Self::Error> {
Ok(Self {
side: value.side,
limit_price: value.limit_price.try_into()?,
max_coin_qty: value.max_coin_qty.try_into()?,
max_native_pc_qty_including_fees: value
.max_native_pc_qty_including_fees
.try_into()?,
min_coin_qty: value.min_coin_qty,
min_native_pc_qty: value.min_native_pc_qty,
limit: value.limit,
})
}
}
impl TryFrom<NewOrderInstructionV3U64> for NewOrderInstructionV3 {
type Error = std::num::TryFromIntError;
fn try_from(value: NewOrderInstructionV3U64) -> Result<Self, Self::Error> {
Ok(Self {
side: value.side,
limit_price: value.limit_price.try_into()?,
max_coin_qty: value.max_coin_qty.try_into()?,
max_native_pc_qty_including_fees: value
.max_native_pc_qty_including_fees
.try_into()?,
order_type: value.order_type,
client_order_id: value.client_order_id,
self_trade_behavior: value.self_trade_behavior,
limit: value.limit,
})
}
}
impl TryFrom<NewOrderInstructionU64> for NewOrderInstructionV2 {
type Error = std::num::TryFromIntError;
fn try_from(value: NewOrderInstructionU64) -> Result<Self, Self::Error> {
Ok(Self {
side: value.side,
limit_price: value.limit_price.try_into()?,
max_qty: value.max_qty.try_into()?,
order_type: value.order_type,
client_id: value.client_id,
self_trade_behavior: value.self_trade_behavior,
})
}
}
impl TryFrom<NewOrderInstructionU64> for NewOrderInstructionV1 {
type Error = std::num::TryFromIntError;
fn try_from(value: NewOrderInstructionU64) -> Result<Self, Self::Error> {
Ok(Self {
side: value.side,
limit_price: value.limit_price.try_into()?,
max_qty: value.max_qty.try_into()?,
order_type: value.order_type,
client_id: value.client_id,
})
}
}
impl From<&SendTakeInstruction> for SendTakeInstructionU64 {
fn from(value: &SendTakeInstruction) -> Self {
Self {
side: value.side,
limit_price: value.limit_price.into(),
max_coin_qty: value.max_coin_qty.into(),
max_native_pc_qty_including_fees: value.max_native_pc_qty_including_fees.into(),
min_coin_qty: value.min_coin_qty,
min_native_pc_qty: value.min_native_pc_qty,
limit: value.limit,
}
}
}
impl From<&NewOrderInstructionV3> for NewOrderInstructionV3U64 {
fn from(value: &NewOrderInstructionV3) -> Self {
Self {
side: value.side,
limit_price: value.limit_price.get(),
max_coin_qty: value.max_coin_qty.get(),
max_native_pc_qty_including_fees: value.max_native_pc_qty_including_fees.get(),
self_trade_behavior: value.self_trade_behavior,
order_type: value.order_type,
client_order_id: value.client_order_id,
limit: value.limit,
}
}
}
impl From<&NewOrderInstructionV2> for NewOrderInstructionU64 {
fn from(value: &NewOrderInstructionV2) -> Self {
Self {
side: value.side,
limit_price: value.limit_price.get(),
max_qty: value.max_qty.get(),
order_type: value.order_type,
client_id: value.client_id,
self_trade_behavior: value.self_trade_behavior,
}
}
}
impl From<&NewOrderInstructionV1> for NewOrderInstructionU64 {
fn from(value: &NewOrderInstructionV1) -> Self {
Self {
side: value.side,
limit_price: value.limit_price.get(),
max_qty: value.max_qty.get(),
order_type: value.order_type,
client_id: value.client_id,
self_trade_behavior: SelfTradeBehavior::DecrementTake,
}
}
}
macro_rules! arbitrary_impl {
($T:ident, $TU64:ident) => {
impl arbitrary::Arbitrary for $T {
fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self, arbitrary::Error> {
<$TU64 as arbitrary::Arbitrary>::arbitrary(u)?
.try_into()
.map_err(|_| arbitrary::Error::IncorrectFormat)
}
fn size_hint(depth: usize) -> (usize, Option<usize>) {
<$TU64 as arbitrary::Arbitrary>::size_hint(depth)
}
fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
let x: $TU64 = self.into();
Box::new(x.shrink().map($TU64::try_into).filter_map(Result::ok))
}
}
};
}
arbitrary_impl!(SendTakeInstruction, SendTakeInstructionU64);
arbitrary_impl!(NewOrderInstructionV3, NewOrderInstructionV3U64);
arbitrary_impl!(NewOrderInstructionV2, NewOrderInstructionU64);
arbitrary_impl!(NewOrderInstructionV1, NewOrderInstructionU64);
}