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
use anchor_lang::prelude::*;
use anchor_spl::dex;
use anchor_spl::dex::serum_dex::instruction::SelfTradeBehavior;
use anchor_spl::dex::serum_dex::matching::{OrderType, Side as SerumSide};
use anchor_spl::dex::serum_dex::state::MarketState;
use anchor_spl::token;
use solana_program::declare_id;
use std::num::NonZeroU64;
declare_id!("22Y43yTVxuUkoRKdm9thyRhQ3SdgQS7c7kB6UNCiaczD");
#[program]
pub mod serum_swap {
use super::*;
pub fn init_account<'info>(ctx: Context<'_, '_, '_, 'info, InitAccount<'info>>) -> Result<()> {
let ctx = CpiContext::new(ctx.accounts.dex_program.clone(), ctx.accounts.into());
dex::init_open_orders(ctx)?;
Ok(())
}
pub fn close_account<'info>(
ctx: Context<'_, '_, '_, 'info, CloseAccount<'info>>,
) -> Result<()> {
let ctx = CpiContext::new(ctx.accounts.dex_program.clone(), ctx.accounts.into());
dex::close_open_orders(ctx)?;
Ok(())
}
#[access_control(is_valid_swap(&ctx))]
pub fn swap<'info>(
ctx: Context<'_, '_, '_, 'info, Swap<'info>>,
side: Side,
amount: u64,
min_exchange_rate: ExchangeRate,
) -> Result<()> {
let mut min_exchange_rate = min_exchange_rate;
min_exchange_rate.quote_decimals = 0;
let referral = ctx.remaining_accounts.iter().next().map(Clone::clone);
let (from_token, to_token) = match side {
Side::Bid => (&ctx.accounts.pc_wallet, &ctx.accounts.market.coin_wallet),
Side::Ask => (&ctx.accounts.market.coin_wallet, &ctx.accounts.pc_wallet),
};
let from_amount_before = token::accessor::amount(from_token)?;
let to_amount_before = token::accessor::amount(to_token)?;
let orderbook: OrderbookClient<'info> = (&*ctx.accounts).into();
match side {
Side::Bid => orderbook.buy(amount, None)?,
Side::Ask => orderbook.sell(amount, None)?,
};
orderbook.settle(referral)?;
let from_amount_after = token::accessor::amount(from_token)?;
let to_amount_after = token::accessor::amount(to_token)?;
let from_amount = from_amount_before.checked_sub(from_amount_after).unwrap();
let to_amount = to_amount_after.checked_sub(to_amount_before).unwrap();
apply_risk_checks(DidSwap {
authority: *ctx.accounts.authority.key,
given_amount: amount,
min_exchange_rate,
from_amount,
to_amount,
quote_amount: 0,
spill_amount: 0,
from_mint: token::accessor::mint(from_token)?,
to_mint: token::accessor::mint(to_token)?,
quote_mint: match side {
Side::Bid => token::accessor::mint(from_token)?,
Side::Ask => token::accessor::mint(to_token)?,
},
})?;
Ok(())
}
#[access_control(is_valid_swap_transitive(&ctx))]
pub fn swap_transitive<'info>(
ctx: Context<'_, '_, '_, 'info, SwapTransitive<'info>>,
amount: u64,
min_exchange_rate: ExchangeRate,
) -> Result<()> {
let referral = ctx.remaining_accounts.iter().next().map(Clone::clone);
let (from_amount, sell_proceeds) = {
let base_before = token::accessor::amount(&ctx.accounts.from.coin_wallet)?;
let quote_before = token::accessor::amount(&ctx.accounts.pc_wallet)?;
let orderbook = ctx.accounts.orderbook_from();
orderbook.sell(amount, None)?;
orderbook.settle(referral.clone())?;
let base_after = token::accessor::amount(&ctx.accounts.from.coin_wallet)?;
let quote_after = token::accessor::amount(&ctx.accounts.pc_wallet)?;
(
base_before.checked_sub(base_after).unwrap(),
quote_after.checked_sub(quote_before).unwrap(),
)
};
let (to_amount, buy_proceeds) = {
let base_before = token::accessor::amount(&ctx.accounts.to.coin_wallet)?;
let quote_before = token::accessor::amount(&ctx.accounts.pc_wallet)?;
let orderbook = ctx.accounts.orderbook_to();
orderbook.buy(sell_proceeds, None)?;
orderbook.settle(referral)?;
let base_after = token::accessor::amount(&ctx.accounts.to.coin_wallet)?;
let quote_after = token::accessor::amount(&ctx.accounts.pc_wallet)?;
(
base_after.checked_sub(base_before).unwrap(),
quote_before.checked_sub(quote_after).unwrap(),
)
};
let spill_amount = sell_proceeds.checked_sub(buy_proceeds).unwrap();
apply_risk_checks(DidSwap {
given_amount: amount,
min_exchange_rate,
from_amount,
to_amount,
quote_amount: sell_proceeds,
spill_amount,
from_mint: token::accessor::mint(&ctx.accounts.from.coin_wallet)?,
to_mint: token::accessor::mint(&ctx.accounts.to.coin_wallet)?,
quote_mint: token::accessor::mint(&ctx.accounts.pc_wallet)?,
authority: *ctx.accounts.authority.key,
})?;
Ok(())
}
}
fn apply_risk_checks(event: DidSwap) -> Result<()> {
emit!(event);
if event.to_amount == 0 {
return Err(ErrorCode::ZeroSwap.into());
}
let min_expected_amount = u128::from(
event.from_amount,
)
.checked_mul(
event.min_exchange_rate.rate.into(),
)
.unwrap()
.checked_mul(
10u128
.checked_pow(event.min_exchange_rate.quote_decimals.into())
.unwrap(),
)
.unwrap();
let effective_to_amount = {
let spill_surplus = match event.spill_amount == 0 || event.min_exchange_rate.strict {
true => 0,
false => u128::from(
event.to_amount,
)
.checked_mul(
event.spill_amount.into(),
)
.unwrap()
.checked_mul(
10u128
.checked_pow(event.min_exchange_rate.from_decimals.into())
.unwrap(),
)
.unwrap()
.checked_mul(
10u128
.checked_pow(event.min_exchange_rate.quote_decimals.into())
.unwrap(),
)
.unwrap()
.checked_div(
event
.quote_amount
.checked_sub(event.spill_amount)
.unwrap()
.into(),
)
.unwrap(),
};
let to_amount = u128::from(
event.to_amount,
)
.checked_mul(
10u128
.checked_pow(event.min_exchange_rate.from_decimals.into())
.unwrap(),
)
.unwrap()
.checked_mul(
10u128
.checked_pow(event.min_exchange_rate.quote_decimals.into())
.unwrap(),
)
.unwrap();
to_amount.checked_add(spill_surplus).unwrap()
};
if effective_to_amount < min_expected_amount {
msg!(
"effective_to_amount, min_expected_amount: {:?}, {:?}",
effective_to_amount,
min_expected_amount,
);
return Err(ErrorCode::SlippageExceeded.into());
}
Ok(())
}
#[derive(Accounts)]
pub struct InitAccount<'info> {
#[account(mut)]
open_orders: AccountInfo<'info>,
#[account(signer)]
authority: AccountInfo<'info>,
market: AccountInfo<'info>,
dex_program: AccountInfo<'info>,
rent: AccountInfo<'info>,
}
impl<'info> From<&mut InitAccount<'info>> for dex::InitOpenOrders<'info> {
fn from(accs: &mut InitAccount<'info>) -> dex::InitOpenOrders<'info> {
dex::InitOpenOrders {
open_orders: accs.open_orders.clone(),
authority: accs.authority.clone(),
market: accs.market.clone(),
rent: accs.rent.clone(),
}
}
}
#[derive(Accounts)]
pub struct CloseAccount<'info> {
#[account(mut)]
open_orders: AccountInfo<'info>,
#[account(signer)]
authority: AccountInfo<'info>,
#[account(mut)]
destination: AccountInfo<'info>,
market: AccountInfo<'info>,
dex_program: AccountInfo<'info>,
}
impl<'info> From<&mut CloseAccount<'info>> for dex::CloseOpenOrders<'info> {
fn from(accs: &mut CloseAccount<'info>) -> dex::CloseOpenOrders<'info> {
dex::CloseOpenOrders {
open_orders: accs.open_orders.clone(),
authority: accs.authority.clone(),
destination: accs.destination.clone(),
market: accs.market.clone(),
}
}
}
#[derive(Accounts)]
pub struct Swap<'info> {
pub market: MarketAccounts<'info>,
#[account(signer)]
pub authority: AccountInfo<'info>,
#[account(mut)]
pub pc_wallet: AccountInfo<'info>,
pub dex_program: AccountInfo<'info>,
pub token_program: AccountInfo<'info>,
pub rent: AccountInfo<'info>,
}
impl<'info> From<&Swap<'info>> for OrderbookClient<'info> {
fn from(accounts: &Swap<'info>) -> OrderbookClient<'info> {
OrderbookClient {
market: accounts.market.clone(),
authority: accounts.authority.clone(),
pc_wallet: accounts.pc_wallet.clone(),
dex_program: accounts.dex_program.clone(),
token_program: accounts.token_program.clone(),
rent: accounts.rent.clone(),
}
}
}
#[derive(Accounts)]
pub struct SwapTransitive<'info> {
pub from: MarketAccounts<'info>,
pub to: MarketAccounts<'info>,
#[account(signer)]
pub authority: AccountInfo<'info>,
#[account(mut)]
pub pc_wallet: AccountInfo<'info>,
pub dex_program: AccountInfo<'info>,
pub token_program: AccountInfo<'info>,
pub rent: AccountInfo<'info>,
}
impl<'info> SwapTransitive<'info> {
fn orderbook_from(&self) -> OrderbookClient<'info> {
OrderbookClient {
market: self.from.clone(),
authority: self.authority.clone(),
pc_wallet: self.pc_wallet.clone(),
dex_program: self.dex_program.clone(),
token_program: self.token_program.clone(),
rent: self.rent.clone(),
}
}
fn orderbook_to(&self) -> OrderbookClient<'info> {
OrderbookClient {
market: self.to.clone(),
authority: self.authority.clone(),
pc_wallet: self.pc_wallet.clone(),
dex_program: self.dex_program.clone(),
token_program: self.token_program.clone(),
rent: self.rent.clone(),
}
}
}
#[derive(Clone)]
struct OrderbookClient<'info> {
market: MarketAccounts<'info>,
authority: AccountInfo<'info>,
pc_wallet: AccountInfo<'info>,
dex_program: AccountInfo<'info>,
token_program: AccountInfo<'info>,
rent: AccountInfo<'info>,
}
impl<'info> OrderbookClient<'info> {
fn sell(
&self,
base_amount: u64,
srm_msrm_discount: Option<AccountInfo<'info>>,
) -> ProgramResult {
let limit_price = 1;
let max_coin_qty = {
let market = MarketState::load(&self.market.market, &dex::ID)?;
coin_lots(&market, base_amount)
};
let max_native_pc_qty = u64::MAX;
self.order_cpi(
limit_price,
max_coin_qty,
max_native_pc_qty,
Side::Ask,
srm_msrm_discount,
)
}
fn buy(
&self,
quote_amount: u64,
srm_msrm_discount: Option<AccountInfo<'info>>,
) -> ProgramResult {
let limit_price = u64::MAX;
let max_coin_qty = u64::MAX;
let max_native_pc_qty = quote_amount;
self.order_cpi(
limit_price,
max_coin_qty,
max_native_pc_qty,
Side::Bid,
srm_msrm_discount,
)
}
fn order_cpi(
&self,
limit_price: u64,
max_coin_qty: u64,
max_native_pc_qty: u64,
side: Side,
srm_msrm_discount: Option<AccountInfo<'info>>,
) -> ProgramResult {
let client_order_id = 0;
let limit = 65535;
let mut ctx = CpiContext::new(self.dex_program.clone(), self.clone().into());
if let Some(srm_msrm_discount) = srm_msrm_discount {
ctx = ctx.with_remaining_accounts(vec![srm_msrm_discount]);
}
dex::new_order_v3(
ctx,
side.into(),
NonZeroU64::new(limit_price).unwrap(),
NonZeroU64::new(max_coin_qty).unwrap(),
NonZeroU64::new(max_native_pc_qty).unwrap(),
SelfTradeBehavior::DecrementTake,
OrderType::ImmediateOrCancel,
client_order_id,
limit,
)
}
fn settle(&self, referral: Option<AccountInfo<'info>>) -> ProgramResult {
let settle_accs = dex::SettleFunds {
market: self.market.market.clone(),
open_orders: self.market.open_orders.clone(),
open_orders_authority: self.authority.clone(),
coin_vault: self.market.coin_vault.clone(),
pc_vault: self.market.pc_vault.clone(),
coin_wallet: self.market.coin_wallet.clone(),
pc_wallet: self.pc_wallet.clone(),
vault_signer: self.market.vault_signer.clone(),
token_program: self.token_program.clone(),
};
let mut ctx = CpiContext::new(self.dex_program.clone(), settle_accs);
if let Some(referral) = referral {
ctx = ctx.with_remaining_accounts(vec![referral]);
}
dex::settle_funds(ctx)
}
}
impl<'info> From<OrderbookClient<'info>> for dex::NewOrderV3<'info> {
fn from(c: OrderbookClient<'info>) -> dex::NewOrderV3<'info> {
dex::NewOrderV3 {
market: c.market.market.clone(),
open_orders: c.market.open_orders.clone(),
request_queue: c.market.request_queue.clone(),
event_queue: c.market.event_queue.clone(),
market_bids: c.market.bids.clone(),
market_asks: c.market.asks.clone(),
order_payer_token_account: c.market.order_payer_token_account.clone(),
open_orders_authority: c.authority.clone(),
coin_vault: c.market.coin_vault.clone(),
pc_vault: c.market.pc_vault.clone(),
token_program: c.token_program.clone(),
rent: c.rent.clone(),
}
}
}
fn coin_lots(market: &MarketState, size: u64) -> u64 {
size.checked_div(market.coin_lot_size).unwrap()
}
#[derive(Accounts, Clone)]
pub struct MarketAccounts<'info> {
#[account(mut)]
pub market: AccountInfo<'info>,
#[account(mut)]
pub open_orders: AccountInfo<'info>,
#[account(mut)]
pub request_queue: AccountInfo<'info>,
#[account(mut)]
pub event_queue: AccountInfo<'info>,
#[account(mut)]
pub bids: AccountInfo<'info>,
#[account(mut)]
pub asks: AccountInfo<'info>,
#[account(mut)]
pub order_payer_token_account: AccountInfo<'info>,
#[account(mut)]
pub coin_vault: AccountInfo<'info>,
#[account(mut)]
pub pc_vault: AccountInfo<'info>,
pub vault_signer: AccountInfo<'info>,
#[account(mut)]
pub coin_wallet: AccountInfo<'info>,
}
#[derive(AnchorSerialize, AnchorDeserialize)]
pub enum Side {
Bid,
Ask,
}
impl From<Side> for SerumSide {
fn from(side: Side) -> SerumSide {
match side {
Side::Bid => SerumSide::Bid,
Side::Ask => SerumSide::Ask,
}
}
}
fn is_valid_swap(ctx: &Context<Swap>) -> Result<()> {
_is_valid_swap(&ctx.accounts.market.coin_wallet, &ctx.accounts.pc_wallet)
}
fn is_valid_swap_transitive(ctx: &Context<SwapTransitive>) -> Result<()> {
_is_valid_swap(&ctx.accounts.from.coin_wallet, &ctx.accounts.to.coin_wallet)
}
fn _is_valid_swap<'info>(from: &AccountInfo<'info>, to: &AccountInfo<'info>) -> Result<()> {
let from_token_mint = token::accessor::mint(from)?;
let to_token_mint = token::accessor::mint(to)?;
if from_token_mint == to_token_mint {
return Err(ErrorCode::SwapTokensCannotMatch.into());
}
Ok(())
}
#[event]
pub struct DidSwap {
pub given_amount: u64,
pub min_exchange_rate: ExchangeRate,
pub from_amount: u64,
pub to_amount: u64,
pub quote_amount: u64,
pub spill_amount: u64,
pub from_mint: Pubkey,
pub to_mint: Pubkey,
pub quote_mint: Pubkey,
pub authority: Pubkey,
}
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct ExchangeRate {
pub rate: u64,
pub from_decimals: u8,
pub quote_decimals: u8,
pub strict: bool,
}
#[error]
pub enum ErrorCode {
#[msg("The tokens being swapped must have different mints")]
SwapTokensCannotMatch,
#[msg("Slippage tolerance exceeded")]
SlippageExceeded,
#[msg("No tokens received when swapping")]
ZeroSwap,
}