-
Notifications
You must be signed in to change notification settings - Fork 2k
/
processor.rs
2035 lines (1831 loc) · 82.8 KB
/
processor.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
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
//! Program state processor
use crate::{
error::LendingError,
instruction::LendingInstruction,
math::{Decimal, Rate, TryAdd, TryDiv, TryMul},
pyth,
state::{
CalculateBorrowResult, CalculateLiquidationResult, CalculateRepayResult,
InitLendingMarketParams, InitObligationParams, InitReserveParams, LendingMarket,
NewReserveCollateralParams, NewReserveLiquidityParams, Obligation, Reserve,
ReserveCollateral, ReserveConfig, ReserveLiquidity,
},
};
use num_traits::FromPrimitive;
use solana_program::{
account_info::{next_account_info, AccountInfo},
decode_error::DecodeError,
entrypoint::ProgramResult,
instruction::Instruction,
msg,
program::{invoke, invoke_signed},
program_error::{PrintProgramError, ProgramError},
program_pack::{IsInitialized, Pack},
pubkey::Pubkey,
sysvar::{clock::Clock, rent::Rent, Sysvar},
};
use spl_token::solana_program::instruction::AccountMeta;
use spl_token::state::{Account, Mint};
use std::convert::TryInto;
/// Processes an instruction
pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
input: &[u8],
) -> ProgramResult {
let instruction = LendingInstruction::unpack(input)?;
match instruction {
LendingInstruction::InitLendingMarket {
owner,
quote_currency,
} => {
msg!("Instruction: Init Lending Market");
process_init_lending_market(program_id, owner, quote_currency, accounts)
}
LendingInstruction::SetLendingMarketOwner { new_owner } => {
msg!("Instruction: Set Lending Market Owner");
process_set_lending_market_owner(program_id, new_owner, accounts)
}
LendingInstruction::InitReserve {
liquidity_amount,
config,
} => {
msg!("Instruction: Init Reserve");
process_init_reserve(program_id, liquidity_amount, config, accounts)
}
LendingInstruction::RefreshReserve => {
msg!("Instruction: Refresh Reserve");
process_refresh_reserve(program_id, accounts)
}
LendingInstruction::DepositReserveLiquidity { liquidity_amount } => {
msg!("Instruction: Deposit Reserve Liquidity");
process_deposit_reserve_liquidity(program_id, liquidity_amount, accounts)
}
LendingInstruction::RedeemReserveCollateral { collateral_amount } => {
msg!("Instruction: Redeem Reserve Collateral");
process_redeem_reserve_collateral(program_id, collateral_amount, accounts)
}
LendingInstruction::InitObligation => {
msg!("Instruction: Init Obligation");
process_init_obligation(program_id, accounts)
}
LendingInstruction::RefreshObligation => {
msg!("Instruction: Refresh Obligation");
process_refresh_obligation(program_id, accounts)
}
LendingInstruction::DepositObligationCollateral { collateral_amount } => {
msg!("Instruction: Deposit Obligation Collateral");
process_deposit_obligation_collateral(program_id, collateral_amount, accounts)
}
LendingInstruction::WithdrawObligationCollateral { collateral_amount } => {
msg!("Instruction: Withdraw Obligation Collateral");
process_withdraw_obligation_collateral(program_id, collateral_amount, accounts)
}
LendingInstruction::BorrowObligationLiquidity {
liquidity_amount,
slippage_limit,
} => {
msg!("Instruction: Borrow Obligation Liquidity");
process_borrow_obligation_liquidity(
program_id,
liquidity_amount,
slippage_limit,
accounts,
)
}
LendingInstruction::RepayObligationLiquidity { liquidity_amount } => {
msg!("Instruction: Repay Obligation Liquidity");
process_repay_obligation_liquidity(program_id, liquidity_amount, accounts)
}
LendingInstruction::LiquidateObligation { liquidity_amount } => {
msg!("Instruction: Liquidate Obligation");
process_liquidate_obligation(program_id, liquidity_amount, accounts)
}
LendingInstruction::FlashLoan { amount } => {
msg!("Instruction: Flash Loan");
process_flash_loan(program_id, amount, accounts)
}
LendingInstruction::ModifyReserveConfig { new_config } => {
msg!("Instruction: Modify Reserve Config");
process_modify_reserve_config(program_id, new_config, accounts)
}
}
}
fn process_init_lending_market(
program_id: &Pubkey,
owner: Pubkey,
quote_currency: [u8; 32],
accounts: &[AccountInfo],
) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
let lending_market_info = next_account_info(account_info_iter)?;
let rent = &Rent::from_account_info(next_account_info(account_info_iter)?)?;
let token_program_id = next_account_info(account_info_iter)?;
let oracle_program_id = next_account_info(account_info_iter)?;
assert_rent_exempt(rent, lending_market_info)?;
let mut lending_market = assert_uninitialized::<LendingMarket>(lending_market_info)?;
if lending_market_info.owner != program_id {
msg!("Lending market provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
lending_market.init(InitLendingMarketParams {
bump_seed: Pubkey::find_program_address(&[lending_market_info.key.as_ref()], program_id).1,
owner,
quote_currency,
token_program_id: *token_program_id.key,
oracle_program_id: *oracle_program_id.key,
});
LendingMarket::pack(lending_market, &mut lending_market_info.data.borrow_mut())?;
Ok(())
}
#[inline(never)] // avoid stack frame limit
fn process_set_lending_market_owner(
program_id: &Pubkey,
new_owner: Pubkey,
accounts: &[AccountInfo],
) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
let lending_market_info = next_account_info(account_info_iter)?;
let lending_market_owner_info = next_account_info(account_info_iter)?;
let mut lending_market = LendingMarket::unpack(&lending_market_info.data.borrow())?;
if lending_market_info.owner != program_id {
msg!("Lending market provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &lending_market.owner != lending_market_owner_info.key {
msg!("Lending market owner does not match the lending market owner provided");
return Err(LendingError::InvalidMarketOwner.into());
}
if !lending_market_owner_info.is_signer {
msg!("Lending market owner provided must be a signer");
return Err(LendingError::InvalidSigner.into());
}
lending_market.owner = new_owner;
LendingMarket::pack(lending_market, &mut lending_market_info.data.borrow_mut())?;
Ok(())
}
fn process_init_reserve(
program_id: &Pubkey,
liquidity_amount: u64,
config: ReserveConfig,
accounts: &[AccountInfo],
) -> ProgramResult {
if liquidity_amount == 0 {
msg!("Reserve must be initialized with liquidity");
return Err(LendingError::InvalidAmount.into());
}
config.validate()?;
let account_info_iter = &mut accounts.iter().peekable();
let source_liquidity_info = next_account_info(account_info_iter)?;
let destination_collateral_info = next_account_info(account_info_iter)?;
let reserve_info = next_account_info(account_info_iter)?;
let reserve_liquidity_mint_info = next_account_info(account_info_iter)?;
let reserve_liquidity_supply_info = next_account_info(account_info_iter)?;
let reserve_liquidity_fee_receiver_info = next_account_info(account_info_iter)?;
let reserve_collateral_mint_info = next_account_info(account_info_iter)?;
let reserve_collateral_supply_info = next_account_info(account_info_iter)?;
let pyth_product_info = next_account_info(account_info_iter)?;
let pyth_price_info = next_account_info(account_info_iter)?;
let lending_market_info = next_account_info(account_info_iter)?;
let lending_market_authority_info = next_account_info(account_info_iter)?;
let lending_market_owner_info = next_account_info(account_info_iter)?;
let user_transfer_authority_info = next_account_info(account_info_iter)?;
let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;
let rent_info = next_account_info(account_info_iter)?;
let rent = &Rent::from_account_info(rent_info)?;
let token_program_id = next_account_info(account_info_iter)?;
assert_rent_exempt(rent, reserve_info)?;
let mut reserve = assert_uninitialized::<Reserve>(reserve_info)?;
if reserve_info.owner != program_id {
msg!("Reserve provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if reserve_liquidity_supply_info.key == source_liquidity_info.key {
msg!("Reserve liquidity supply cannot be used as the source liquidity provided");
return Err(LendingError::InvalidAccountInput.into());
}
let lending_market = LendingMarket::unpack(&lending_market_info.data.borrow())?;
if lending_market_info.owner != program_id {
msg!("Lending market provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &lending_market.token_program_id != token_program_id.key {
msg!("Lending market token program does not match the token program provided");
return Err(LendingError::InvalidTokenProgram.into());
}
if &lending_market.owner != lending_market_owner_info.key {
msg!("Lending market owner does not match the lending market owner provided");
return Err(LendingError::InvalidMarketOwner.into());
}
if !lending_market_owner_info.is_signer {
msg!("Lending market owner provided must be a signer");
return Err(LendingError::InvalidSigner.into());
}
if &lending_market.oracle_program_id != pyth_product_info.owner {
msg!("Pyth product account provided is not owned by the lending market oracle program");
return Err(LendingError::InvalidOracleConfig.into());
}
if &lending_market.oracle_program_id != pyth_price_info.owner {
msg!("Pyth price account provided is not owned by the lending market oracle program");
return Err(LendingError::InvalidOracleConfig.into());
}
let pyth_product_data = pyth_product_info.try_borrow_data()?;
let pyth_product = pyth::load::<pyth::Product>(&pyth_product_data)
.map_err(|_| ProgramError::InvalidAccountData)?;
if pyth_product.magic != pyth::MAGIC {
msg!("Pyth product account provided is not a valid Pyth account");
return Err(LendingError::InvalidOracleConfig.into());
}
if pyth_product.ver != pyth::VERSION_2 {
msg!("Pyth product account provided has a different version than expected");
return Err(LendingError::InvalidOracleConfig.into());
}
if pyth_product.atype != pyth::AccountType::Product as u32 {
msg!("Pyth product account provided is not a valid Pyth product account");
return Err(LendingError::InvalidOracleConfig.into());
}
let pyth_price_pubkey_bytes: &[u8; 32] = pyth_price_info
.key
.as_ref()
.try_into()
.map_err(|_| LendingError::InvalidAccountInput)?;
if &pyth_product.px_acc.val != pyth_price_pubkey_bytes {
msg!("Pyth product price account does not match the Pyth price provided");
return Err(LendingError::InvalidOracleConfig.into());
}
let quote_currency = get_pyth_product_quote_currency(pyth_product)?;
if lending_market.quote_currency != quote_currency {
msg!("Lending market quote currency does not match the oracle quote currency");
return Err(LendingError::InvalidOracleConfig.into());
}
let market_price = get_pyth_price(pyth_price_info, clock)?;
let authority_signer_seeds = &[
lending_market_info.key.as_ref(),
&[lending_market.bump_seed],
];
let lending_market_authority_pubkey =
Pubkey::create_program_address(authority_signer_seeds, program_id)?;
if &lending_market_authority_pubkey != lending_market_authority_info.key {
msg!(
"Derived lending market authority does not match the lending market authority provided"
);
return Err(LendingError::InvalidMarketAuthority.into());
}
let reserve_liquidity_mint = unpack_mint(&reserve_liquidity_mint_info.data.borrow())?;
if reserve_liquidity_mint_info.owner != token_program_id.key {
msg!("Reserve liquidity mint is not owned by the token program provided");
return Err(LendingError::InvalidTokenOwner.into());
}
reserve.init(InitReserveParams {
current_slot: clock.slot,
lending_market: *lending_market_info.key,
liquidity: ReserveLiquidity::new(NewReserveLiquidityParams {
mint_pubkey: *reserve_liquidity_mint_info.key,
mint_decimals: reserve_liquidity_mint.decimals,
supply_pubkey: *reserve_liquidity_supply_info.key,
fee_receiver: *reserve_liquidity_fee_receiver_info.key,
oracle_pubkey: *pyth_price_info.key,
market_price,
}),
collateral: ReserveCollateral::new(NewReserveCollateralParams {
mint_pubkey: *reserve_collateral_mint_info.key,
supply_pubkey: *reserve_collateral_supply_info.key,
}),
config,
});
let collateral_amount = reserve.deposit_liquidity(liquidity_amount)?;
Reserve::pack(reserve, &mut reserve_info.data.borrow_mut())?;
spl_token_init_account(TokenInitializeAccountParams {
account: reserve_liquidity_supply_info.clone(),
mint: reserve_liquidity_mint_info.clone(),
owner: lending_market_authority_info.clone(),
rent: rent_info.clone(),
token_program: token_program_id.clone(),
})?;
spl_token_init_account(TokenInitializeAccountParams {
account: reserve_liquidity_fee_receiver_info.clone(),
mint: reserve_liquidity_mint_info.clone(),
owner: lending_market_authority_info.clone(),
rent: rent_info.clone(),
token_program: token_program_id.clone(),
})?;
spl_token_init_mint(TokenInitializeMintParams {
mint: reserve_collateral_mint_info.clone(),
authority: lending_market_authority_info.key,
rent: rent_info.clone(),
decimals: reserve_liquidity_mint.decimals,
token_program: token_program_id.clone(),
})?;
spl_token_init_account(TokenInitializeAccountParams {
account: reserve_collateral_supply_info.clone(),
mint: reserve_collateral_mint_info.clone(),
owner: lending_market_authority_info.clone(),
rent: rent_info.clone(),
token_program: token_program_id.clone(),
})?;
spl_token_init_account(TokenInitializeAccountParams {
account: destination_collateral_info.clone(),
mint: reserve_collateral_mint_info.clone(),
owner: user_transfer_authority_info.clone(),
rent: rent_info.clone(),
token_program: token_program_id.clone(),
})?;
spl_token_transfer(TokenTransferParams {
source: source_liquidity_info.clone(),
destination: reserve_liquidity_supply_info.clone(),
amount: liquidity_amount,
authority: user_transfer_authority_info.clone(),
authority_signer_seeds: &[],
token_program: token_program_id.clone(),
})?;
spl_token_mint_to(TokenMintToParams {
mint: reserve_collateral_mint_info.clone(),
destination: destination_collateral_info.clone(),
amount: collateral_amount,
authority: lending_market_authority_info.clone(),
authority_signer_seeds,
token_program: token_program_id.clone(),
})?;
Ok(())
}
fn process_refresh_reserve(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult {
let account_info_iter = &mut accounts.iter().peekable();
let reserve_info = next_account_info(account_info_iter)?;
let reserve_liquidity_oracle_info = next_account_info(account_info_iter)?;
let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;
let mut reserve = Reserve::unpack(&reserve_info.data.borrow())?;
if reserve_info.owner != program_id {
msg!("Reserve provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &reserve.liquidity.oracle_pubkey != reserve_liquidity_oracle_info.key {
msg!("Reserve liquidity oracle does not match the reserve liquidity oracle provided");
return Err(LendingError::InvalidAccountInput.into());
}
reserve.liquidity.market_price = get_pyth_price(reserve_liquidity_oracle_info, clock)?;
reserve.accrue_interest(clock.slot)?;
reserve.last_update.update_slot(clock.slot);
Reserve::pack(reserve, &mut reserve_info.data.borrow_mut())?;
Ok(())
}
fn process_deposit_reserve_liquidity(
program_id: &Pubkey,
liquidity_amount: u64,
accounts: &[AccountInfo],
) -> ProgramResult {
if liquidity_amount == 0 {
msg!("Liquidity amount provided cannot be zero");
return Err(LendingError::InvalidAmount.into());
}
let account_info_iter = &mut accounts.iter();
let source_liquidity_info = next_account_info(account_info_iter)?;
let destination_collateral_info = next_account_info(account_info_iter)?;
let reserve_info = next_account_info(account_info_iter)?;
let reserve_liquidity_supply_info = next_account_info(account_info_iter)?;
let reserve_collateral_mint_info = next_account_info(account_info_iter)?;
let lending_market_info = next_account_info(account_info_iter)?;
let lending_market_authority_info = next_account_info(account_info_iter)?;
let user_transfer_authority_info = next_account_info(account_info_iter)?;
let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;
let token_program_id = next_account_info(account_info_iter)?;
let lending_market = LendingMarket::unpack(&lending_market_info.data.borrow())?;
if lending_market_info.owner != program_id {
msg!("Lending market provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &lending_market.token_program_id != token_program_id.key {
msg!("Lending market token program does not match the token program provided");
return Err(LendingError::InvalidTokenProgram.into());
}
let mut reserve = Reserve::unpack(&reserve_info.data.borrow())?;
if reserve_info.owner != program_id {
msg!("Reserve provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &reserve.lending_market != lending_market_info.key {
msg!("Reserve lending market does not match the lending market provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &reserve.liquidity.supply_pubkey != reserve_liquidity_supply_info.key {
msg!("Reserve liquidity supply does not match the reserve liquidity supply provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &reserve.collateral.mint_pubkey != reserve_collateral_mint_info.key {
msg!("Reserve collateral mint does not match the reserve collateral mint provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &reserve.liquidity.supply_pubkey == source_liquidity_info.key {
msg!("Reserve liquidity supply cannot be used as the source liquidity provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &reserve.collateral.supply_pubkey == destination_collateral_info.key {
msg!("Reserve collateral supply cannot be used as the destination collateral provided");
return Err(LendingError::InvalidAccountInput.into());
}
if reserve.last_update.is_stale(clock.slot)? {
msg!("Reserve is stale and must be refreshed in the current slot");
return Err(LendingError::ReserveStale.into());
}
let authority_signer_seeds = &[
lending_market_info.key.as_ref(),
&[lending_market.bump_seed],
];
let lending_market_authority_pubkey =
Pubkey::create_program_address(authority_signer_seeds, program_id)?;
if &lending_market_authority_pubkey != lending_market_authority_info.key {
msg!(
"Derived lending market authority {} does not match the lending market authority provided {}",
&lending_market_authority_pubkey.to_string(),
&lending_market_authority_info.key.to_string(),
);
return Err(LendingError::InvalidMarketAuthority.into());
}
let collateral_amount = reserve.deposit_liquidity(liquidity_amount)?;
reserve.last_update.mark_stale();
Reserve::pack(reserve, &mut reserve_info.data.borrow_mut())?;
spl_token_transfer(TokenTransferParams {
source: source_liquidity_info.clone(),
destination: reserve_liquidity_supply_info.clone(),
amount: liquidity_amount,
authority: user_transfer_authority_info.clone(),
authority_signer_seeds: &[],
token_program: token_program_id.clone(),
})?;
spl_token_mint_to(TokenMintToParams {
mint: reserve_collateral_mint_info.clone(),
destination: destination_collateral_info.clone(),
amount: collateral_amount,
authority: lending_market_authority_info.clone(),
authority_signer_seeds,
token_program: token_program_id.clone(),
})?;
Ok(())
}
fn process_redeem_reserve_collateral(
program_id: &Pubkey,
collateral_amount: u64,
accounts: &[AccountInfo],
) -> ProgramResult {
if collateral_amount == 0 {
msg!("Collateral amount provided cannot be zero");
return Err(LendingError::InvalidAmount.into());
}
let account_info_iter = &mut accounts.iter();
let source_collateral_info = next_account_info(account_info_iter)?;
let destination_liquidity_info = next_account_info(account_info_iter)?;
let reserve_info = next_account_info(account_info_iter)?;
let reserve_collateral_mint_info = next_account_info(account_info_iter)?;
let reserve_liquidity_supply_info = next_account_info(account_info_iter)?;
let lending_market_info = next_account_info(account_info_iter)?;
let lending_market_authority_info = next_account_info(account_info_iter)?;
let user_transfer_authority_info = next_account_info(account_info_iter)?;
let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;
let token_program_id = next_account_info(account_info_iter)?;
let lending_market = LendingMarket::unpack(&lending_market_info.data.borrow())?;
if lending_market_info.owner != program_id {
msg!("Lending market provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &lending_market.token_program_id != token_program_id.key {
msg!("Lending market token program does not match the token program provided");
return Err(LendingError::InvalidTokenProgram.into());
}
let mut reserve = Reserve::unpack(&reserve_info.data.borrow())?;
if reserve_info.owner != program_id {
msg!("Reserve provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &reserve.lending_market != lending_market_info.key {
msg!("Reserve lending market does not match the lending market provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &reserve.collateral.mint_pubkey != reserve_collateral_mint_info.key {
msg!("Reserve collateral mint does not match the reserve collateral mint provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &reserve.collateral.supply_pubkey == source_collateral_info.key {
msg!("Reserve collateral supply cannot be used as the source collateral provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &reserve.liquidity.supply_pubkey != reserve_liquidity_supply_info.key {
msg!("Reserve liquidity supply does not match the reserve liquidity supply provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &reserve.liquidity.supply_pubkey == destination_liquidity_info.key {
msg!("Reserve liquidity supply cannot be used as the destination liquidity provided");
return Err(LendingError::InvalidAccountInput.into());
}
if reserve.last_update.is_stale(clock.slot)? {
msg!("Reserve is stale and must be refreshed in the current slot");
return Err(LendingError::ReserveStale.into());
}
let authority_signer_seeds = &[
lending_market_info.key.as_ref(),
&[lending_market.bump_seed],
];
let lending_market_authority_pubkey =
Pubkey::create_program_address(authority_signer_seeds, program_id)?;
if &lending_market_authority_pubkey != lending_market_authority_info.key {
msg!(
"Derived lending market authority does not match the lending market authority provided"
);
return Err(LendingError::InvalidMarketAuthority.into());
}
let liquidity_amount = reserve.redeem_collateral(collateral_amount)?;
reserve.last_update.mark_stale();
Reserve::pack(reserve, &mut reserve_info.data.borrow_mut())?;
spl_token_burn(TokenBurnParams {
mint: reserve_collateral_mint_info.clone(),
source: source_collateral_info.clone(),
amount: collateral_amount,
authority: user_transfer_authority_info.clone(),
authority_signer_seeds: &[],
token_program: token_program_id.clone(),
})?;
spl_token_transfer(TokenTransferParams {
source: reserve_liquidity_supply_info.clone(),
destination: destination_liquidity_info.clone(),
amount: liquidity_amount,
authority: lending_market_authority_info.clone(),
authority_signer_seeds,
token_program: token_program_id.clone(),
})?;
Ok(())
}
#[inline(never)] // avoid stack frame limit
fn process_init_obligation(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
let obligation_info = next_account_info(account_info_iter)?;
let lending_market_info = next_account_info(account_info_iter)?;
let obligation_owner_info = next_account_info(account_info_iter)?;
let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;
let rent = &Rent::from_account_info(next_account_info(account_info_iter)?)?;
let token_program_id = next_account_info(account_info_iter)?;
assert_rent_exempt(rent, obligation_info)?;
let mut obligation = assert_uninitialized::<Obligation>(obligation_info)?;
if obligation_info.owner != program_id {
msg!("Obligation provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
let lending_market = LendingMarket::unpack(&lending_market_info.data.borrow())?;
if lending_market_info.owner != program_id {
msg!("Lending market provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &lending_market.token_program_id != token_program_id.key {
msg!("Lending market token program does not match the token program provided");
return Err(LendingError::InvalidTokenProgram.into());
}
if !obligation_owner_info.is_signer {
msg!("Obligation owner provided must be a signer");
return Err(LendingError::InvalidSigner.into());
}
obligation.init(InitObligationParams {
current_slot: clock.slot,
lending_market: *lending_market_info.key,
owner: *obligation_owner_info.key,
deposits: vec![],
borrows: vec![],
});
Obligation::pack(obligation, &mut obligation_info.data.borrow_mut())?;
Ok(())
}
fn process_refresh_obligation(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult {
let account_info_iter = &mut accounts.iter().peekable();
let obligation_info = next_account_info(account_info_iter)?;
let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;
let mut obligation = Obligation::unpack(&obligation_info.data.borrow())?;
if obligation_info.owner != program_id {
msg!("Obligation provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
let mut deposited_value = Decimal::zero();
let mut borrowed_value = Decimal::zero();
let mut allowed_borrow_value = Decimal::zero();
let mut unhealthy_borrow_value = Decimal::zero();
for (index, collateral) in obligation.deposits.iter_mut().enumerate() {
let deposit_reserve_info = next_account_info(account_info_iter)?;
if deposit_reserve_info.owner != program_id {
msg!(
"Deposit reserve provided for collateral {} is not owned by the lending program",
index
);
return Err(LendingError::InvalidAccountOwner.into());
}
if collateral.deposit_reserve != *deposit_reserve_info.key {
msg!(
"Deposit reserve of collateral {} does not match the deposit reserve provided",
index
);
return Err(LendingError::InvalidAccountInput.into());
}
let deposit_reserve = Reserve::unpack(&deposit_reserve_info.data.borrow())?;
if deposit_reserve.last_update.is_stale(clock.slot)? {
msg!(
"Deposit reserve provided for collateral {} is stale and must be refreshed in the current slot",
index
);
return Err(LendingError::ReserveStale.into());
}
// @TODO: add lookup table https://git.io/JOCYq
let decimals = 10u64
.checked_pow(deposit_reserve.liquidity.mint_decimals as u32)
.ok_or(LendingError::MathOverflow)?;
let market_value = deposit_reserve
.collateral_exchange_rate()?
.decimal_collateral_to_liquidity(collateral.deposited_amount.into())?
.try_mul(deposit_reserve.liquidity.market_price)?
.try_div(decimals)?;
collateral.market_value = market_value;
let loan_to_value_rate = Rate::from_percent(deposit_reserve.config.loan_to_value_ratio);
let liquidation_threshold_rate =
Rate::from_percent(deposit_reserve.config.liquidation_threshold);
deposited_value = deposited_value.try_add(market_value)?;
allowed_borrow_value =
allowed_borrow_value.try_add(market_value.try_mul(loan_to_value_rate)?)?;
unhealthy_borrow_value =
unhealthy_borrow_value.try_add(market_value.try_mul(liquidation_threshold_rate)?)?;
}
for (index, liquidity) in obligation.borrows.iter_mut().enumerate() {
let borrow_reserve_info = next_account_info(account_info_iter)?;
if borrow_reserve_info.owner != program_id {
msg!(
"Borrow reserve provided for liquidity {} is not owned by the lending program",
index
);
return Err(LendingError::InvalidAccountOwner.into());
}
if liquidity.borrow_reserve != *borrow_reserve_info.key {
msg!(
"Borrow reserve of liquidity {} does not match the borrow reserve provided",
index
);
return Err(LendingError::InvalidAccountInput.into());
}
let borrow_reserve = Reserve::unpack(&borrow_reserve_info.data.borrow())?;
if borrow_reserve.last_update.is_stale(clock.slot)? {
msg!(
"Borrow reserve provided for liquidity {} is stale and must be refreshed in the current slot",
index
);
return Err(LendingError::ReserveStale.into());
}
liquidity.accrue_interest(borrow_reserve.liquidity.cumulative_borrow_rate_wads)?;
// @TODO: add lookup table https://git.io/JOCYq
let decimals = 10u64
.checked_pow(borrow_reserve.liquidity.mint_decimals as u32)
.ok_or(LendingError::MathOverflow)?;
let market_value = liquidity
.borrowed_amount_wads
.try_mul(borrow_reserve.liquidity.market_price)?
.try_div(decimals)?;
liquidity.market_value = market_value;
borrowed_value = borrowed_value.try_add(market_value)?;
}
if account_info_iter.peek().is_some() {
msg!("Too many obligation deposit or borrow reserves provided");
return Err(LendingError::InvalidAccountInput.into());
}
obligation.deposited_value = deposited_value;
obligation.borrowed_value = borrowed_value;
obligation.allowed_borrow_value = allowed_borrow_value;
obligation.unhealthy_borrow_value = unhealthy_borrow_value;
obligation.last_update.update_slot(clock.slot);
Obligation::pack(obligation, &mut obligation_info.data.borrow_mut())?;
Ok(())
}
#[inline(never)] // avoid stack frame limit
fn process_deposit_obligation_collateral(
program_id: &Pubkey,
collateral_amount: u64,
accounts: &[AccountInfo],
) -> ProgramResult {
if collateral_amount == 0 {
msg!("Collateral amount provided cannot be zero");
return Err(LendingError::InvalidAmount.into());
}
let account_info_iter = &mut accounts.iter();
let source_collateral_info = next_account_info(account_info_iter)?;
let destination_collateral_info = next_account_info(account_info_iter)?;
let deposit_reserve_info = next_account_info(account_info_iter)?;
let obligation_info = next_account_info(account_info_iter)?;
let lending_market_info = next_account_info(account_info_iter)?;
let obligation_owner_info = next_account_info(account_info_iter)?;
let user_transfer_authority_info = next_account_info(account_info_iter)?;
let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;
let token_program_id = next_account_info(account_info_iter)?;
let lending_market = LendingMarket::unpack(&lending_market_info.data.borrow())?;
if lending_market_info.owner != program_id {
msg!("Lending market provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &lending_market.token_program_id != token_program_id.key {
msg!("Lending market token program does not match the token program provided");
return Err(LendingError::InvalidTokenProgram.into());
}
let deposit_reserve = Reserve::unpack(&deposit_reserve_info.data.borrow())?;
if deposit_reserve_info.owner != program_id {
msg!("Deposit reserve provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &deposit_reserve.lending_market != lending_market_info.key {
msg!("Deposit reserve lending market does not match the lending market provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &deposit_reserve.collateral.supply_pubkey == source_collateral_info.key {
msg!("Deposit reserve collateral supply cannot be used as the source collateral provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &deposit_reserve.collateral.supply_pubkey != destination_collateral_info.key {
msg!(
"Deposit reserve collateral supply must be used as the destination collateral provided"
);
return Err(LendingError::InvalidAccountInput.into());
}
if deposit_reserve.last_update.is_stale(clock.slot)? {
msg!("Deposit reserve is stale and must be refreshed in the current slot");
return Err(LendingError::ReserveStale.into());
}
if deposit_reserve.config.loan_to_value_ratio == 0 {
msg!("Deposit reserve has collateral disabled for borrowing");
return Err(LendingError::ReserveCollateralDisabled.into());
}
let mut obligation = Obligation::unpack(&obligation_info.data.borrow())?;
if obligation_info.owner != program_id {
msg!("Obligation provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &obligation.lending_market != lending_market_info.key {
msg!("Obligation lending market does not match the lending market provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &obligation.owner != obligation_owner_info.key {
msg!("Obligation owner does not match the obligation owner provided");
return Err(LendingError::InvalidObligationOwner.into());
}
if !obligation_owner_info.is_signer {
msg!("Obligation owner provided must be a signer");
return Err(LendingError::InvalidSigner.into());
}
obligation
.find_or_add_collateral_to_deposits(*deposit_reserve_info.key)?
.deposit(collateral_amount)?;
obligation.last_update.mark_stale();
Obligation::pack(obligation, &mut obligation_info.data.borrow_mut())?;
spl_token_transfer(TokenTransferParams {
source: source_collateral_info.clone(),
destination: destination_collateral_info.clone(),
amount: collateral_amount,
authority: user_transfer_authority_info.clone(),
authority_signer_seeds: &[],
token_program: token_program_id.clone(),
})?;
Ok(())
}
#[inline(never)] // avoid stack frame limit
fn process_withdraw_obligation_collateral(
program_id: &Pubkey,
collateral_amount: u64,
accounts: &[AccountInfo],
) -> ProgramResult {
if collateral_amount == 0 {
msg!("Collateral amount provided cannot be zero");
return Err(LendingError::InvalidAmount.into());
}
let account_info_iter = &mut accounts.iter();
let source_collateral_info = next_account_info(account_info_iter)?;
let destination_collateral_info = next_account_info(account_info_iter)?;
let withdraw_reserve_info = next_account_info(account_info_iter)?;
let obligation_info = next_account_info(account_info_iter)?;
let lending_market_info = next_account_info(account_info_iter)?;
let lending_market_authority_info = next_account_info(account_info_iter)?;
let obligation_owner_info = next_account_info(account_info_iter)?;
let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;
let token_program_id = next_account_info(account_info_iter)?;
let lending_market = LendingMarket::unpack(&lending_market_info.data.borrow())?;
if lending_market_info.owner != program_id {
msg!("Lending market provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &lending_market.token_program_id != token_program_id.key {
msg!("Lending market token program does not match the token program provided");
return Err(LendingError::InvalidTokenProgram.into());
}
let withdraw_reserve = Reserve::unpack(&withdraw_reserve_info.data.borrow())?;
if withdraw_reserve_info.owner != program_id {
msg!("Withdraw reserve provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &withdraw_reserve.lending_market != lending_market_info.key {
msg!("Withdraw reserve lending market does not match the lending market provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &withdraw_reserve.collateral.supply_pubkey != source_collateral_info.key {
msg!("Withdraw reserve collateral supply must be used as the source collateral provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &withdraw_reserve.collateral.supply_pubkey == destination_collateral_info.key {
msg!("Withdraw reserve collateral supply cannot be used as the destination collateral provided");
return Err(LendingError::InvalidAccountInput.into());
}
if withdraw_reserve.last_update.is_stale(clock.slot)? {
msg!("Withdraw reserve is stale and must be refreshed in the current slot");
return Err(LendingError::ReserveStale.into());
}
let mut obligation = Obligation::unpack(&obligation_info.data.borrow())?;
if obligation_info.owner != program_id {
msg!("Obligation provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
}
if &obligation.lending_market != lending_market_info.key {
msg!("Obligation lending market does not match the lending market provided");
return Err(LendingError::InvalidAccountInput.into());
}
if &obligation.owner != obligation_owner_info.key {
msg!("Obligation owner does not match the obligation owner provided");
return Err(LendingError::InvalidObligationOwner.into());
}
if !obligation_owner_info.is_signer {
msg!("Obligation owner provided must be a signer");
return Err(LendingError::InvalidSigner.into());
}
if obligation.last_update.is_stale(clock.slot)? {
msg!("Obligation is stale and must be refreshed in the current slot");
return Err(LendingError::ObligationStale.into());
}
let (collateral, collateral_index) =
obligation.find_collateral_in_deposits(*withdraw_reserve_info.key)?;
if collateral.deposited_amount == 0 {
msg!("Collateral deposited amount is zero");
return Err(LendingError::ObligationCollateralEmpty.into());
}
let authority_signer_seeds = &[
lending_market_info.key.as_ref(),
&[lending_market.bump_seed],
];
let lending_market_authority_pubkey =
Pubkey::create_program_address(authority_signer_seeds, program_id)?;
if &lending_market_authority_pubkey != lending_market_authority_info.key {
msg!(
"Derived lending market authority does not match the lending market authority provided"
);
return Err(LendingError::InvalidMarketAuthority.into());
}
let withdraw_amount = if obligation.borrows.is_empty() {
if collateral_amount == u64::MAX {
collateral.deposited_amount
} else {
collateral.deposited_amount.min(collateral_amount)
}
} else if obligation.deposited_value == Decimal::zero() {
msg!("Obligation deposited value is zero");
return Err(LendingError::ObligationDepositsZero.into());
} else {
let max_withdraw_value = obligation.max_withdraw_value(Rate::from_percent(
withdraw_reserve.config.loan_to_value_ratio,
))?;
if max_withdraw_value == Decimal::zero() {
msg!("Maximum withdraw value is zero");
return Err(LendingError::WithdrawTooLarge.into());
}
let withdraw_amount = if collateral_amount == u64::MAX {
let withdraw_value = max_withdraw_value.min(collateral.market_value);
let withdraw_pct = withdraw_value.try_div(collateral.market_value)?;
withdraw_pct
.try_mul(collateral.deposited_amount)?
.try_floor_u64()?
.min(collateral.deposited_amount)
} else {
let withdraw_amount = collateral_amount.min(collateral.deposited_amount);
let withdraw_pct =
Decimal::from(withdraw_amount).try_div(collateral.deposited_amount)?;
let withdraw_value = collateral.market_value.try_mul(withdraw_pct)?;