-
Notifications
You must be signed in to change notification settings - Fork 19
/
main.sw
2282 lines (2004 loc) · 85.3 KB
/
main.sw
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
// SPDX-License-Identifier: MIT
contract;
//
// @title Swaylend's Market Contract
// @notice An efficient monolithic money market protocol
// @author Reserve Labs LTD
//
mod events;
use events::*;
use pyth_interface::{data_structures::price::{Price, PriceFeedId}, PythCore};
use market_abi::{Market, structs::*,};
use std::asset::{mint_to, transfer};
use std::auth::{AuthError, msg_sender};
use std::call_frames::msg_asset_id;
use std::contract_id::ContractId;
use std::context::{msg_amount, this_balance};
use std::hash::{Hash, sha256};
use std::logging::log;
use std::revert::require;
use std::storage::storage_vec::*;
use std::u128::U128;
use std::vec::Vec;
use std::bytes::Bytes;
use std::convert::TryFrom;
use sway_libs::reentrancy::reentrancy_guard;
use standards::src5::{SRC5, State};
use sway_libs::ownership::*;
use sway_libs::signed_integers::i256::I256;
// version of the smart contract
const VERSION: u8 = 1_u8;
// pyth oracle configuration params
const ORACLE_MAX_STALENESS: u64 = 30; // 30 seconds
const ORACLE_MAX_AHEADNESS: u64 = 60; // 60 seconds
const ORACLE_MAX_CONF_WIDTH: u256 = 100; // 100 / 10000 = 1.0 %
// This is set during deployment of the contract
configurable {
DEBUG_STEP: u64 = 0,
}
storage {
// market configuration
market_configuration: MarketConfiguration = MarketConfiguration::default(),
// configuration for collateral assets (can add, pause ...)
collateral_configurations: StorageMap<AssetId, CollateralConfiguration> = StorageMap {},
// list of asset ids of collateral assets
collateral_configurations_keys: StorageVec<AssetId> = StorageVec {},
// booleans to pause certain functionalities
pause_config: PauseConfiguration = PauseConfiguration::default(),
// total collateral for each asset
totals_collateral: StorageMap<AssetId, u64> = StorageMap {},
// how much collateral user provided (separate for each asset)
user_collateral: StorageMap<(Identity, AssetId), u64> = StorageMap {},
// holds information about the users details in the market
user_basic: StorageMap<Identity, UserBasic> = StorageMap {},
// information about the whole market (total supply, total borrow, etc.)
market_basic: MarketBasics = MarketBasics::default(),
// debug timestamp (for testing purposes)
debug_timestamp: u64 = 0,
// pyth contract id
pyth_contract_id: ContractId = ContractId::zero(),
}
// Market contract implementation
impl Market for Contract {
/// Get version of the smart contract
/// # Returns
/// * [u8] - The version number of the smart contract.
fn get_version() -> u8 {
VERSION
}
// ## 0. Activate contract
/// # Arguments
/// * `market_configuration`: [MarketConfiguration] - The configuration settings for the market.
/// * `owner`: [Identity] - The identity of the owner of the contract.
///
/// # Reverts
/// * When the contract is already active, indicated by a non-zero last accrual time.
///
/// # Number of Storage Accesses
/// * Writes: `4`
/// * Reads: `2`
#[storage(write)]
fn activate_contract(market_configuration: MarketConfiguration, owner: Identity) {
require(
storage
.market_basic
.last_accrual_time
.read() == 0,
Error::AlreadyActive,
);
// Set owner
initialize_ownership(owner);
// Set market configuration
storage.market_configuration.write(market_configuration);
// Set last_accrual_time to current timestamp
storage
.market_basic
.last_accrual_time
.write(timestamp().into());
let market_basic = storage.market_basic.read();
let pause_config = PauseConfiguration {
supply_paused: false,
withdraw_paused: false,
absorb_paused: false,
buy_paused: false,
};
// Un-pause the contract
storage.pause_config.write(pause_config);
// Emit pause configuration updated event
log(PauseConfigurationEvent { pause_config });
// Emit market configuration event
log(MarketConfigurationEvent {
market_config: market_configuration,
});
// Emit market basic event
log(MarketBasicEvent { market_basic });
}
// ## 1. Debug functionality (for testing purposes)
// ## 1.1 Manually increment timestamp
/// This function is useful for testing purposes, allowing developers to simulate time progression during debugging.
///
/// # Reverts
/// * When `DEBUG_STEP` is not greater than zero, indicating that debugging is disabled.
///
/// # Number of Storage Accesses
/// * Writes: `1`
/// * Reads: `1`
#[storage(write)]
fn debug_increment_timestamp() {
require(DEBUG_STEP > 0, Error::DebuggingDisabled);
storage
.debug_timestamp
.write(storage.debug_timestamp.read() + DEBUG_STEP);
}
// ## 2. Collateral asset management
// ## 2.1 Add new collateral asset
/// # Arguments
/// * `configuration`: [CollateralConfiguration] - The collateral configuration to be added.
///
/// # Reverts
/// * When the caller is not the owner.
/// * When the asset already exists, indicated by a non-`None` value in the storage.
///
/// # Number of Storage Accesses
/// * Writes: `2`
/// * Reads: `1`
#[storage(write)]
fn add_collateral_asset(configuration: CollateralConfiguration) {
// Only owner can add new collateral asset
only_owner();
// Check if asset already exists
require(
storage
.collateral_configurations
.get(configuration.asset_id)
.try_read()
.is_none(),
Error::UnknownAsset,
);
storage
.collateral_configurations
.insert(configuration.asset_id, configuration);
storage
.collateral_configurations_keys
.push(configuration.asset_id);
log(CollateralAssetAdded {
asset_id: configuration.asset_id,
configuration,
});
}
// ## 2.2 Pause an existing collateral asset
/// # Arguments
/// * `asset_id`: [AssetId] - The asset ID of the collateral asset to be paused.
///
/// # Reverts
/// * When the caller is not the owner.
///
/// # Number of Storage Accesses
/// * Writes: `1`
/// * Reads: `1`
#[storage(write)]
fn pause_collateral_asset(asset_id: AssetId) {
// Only owner can pause collateral asset
only_owner();
let mut configuration = storage.collateral_configurations.get(asset_id).read();
configuration.paused = true;
storage
.collateral_configurations
.insert(asset_id, configuration);
log(CollateralAssetPaused {
asset_id: configuration.asset_id,
});
}
// ## 2.3 Resume a paused collateral asset
/// # Arguments
/// * `asset_id`: [AssetId] - The asset ID of the collateral asset to be resumed.
///
/// # Reverts
/// * When the caller is not the owner.
///
/// # Number of Storage Accesses
/// * Writes: `1`
/// * Reads: `1`
#[storage(write)]
fn resume_collateral_asset(asset_id: AssetId) {
// Only owner can resume collateral asset
only_owner();
let mut configuration = storage.collateral_configurations.get(asset_id).read();
configuration.paused = false;
storage
.collateral_configurations
.insert(asset_id, configuration);
log(CollateralAssetResumed {
asset_id: configuration.asset_id,
});
}
// ## 2.4 Update an existing collateral asset configuration
/// # Arguments
/// * `asset_id`: [AssetId] - The asset ID of the collateral asset to be updated.
/// * `configuration`: [CollateralConfiguration] - The new collateral configuration.
///
/// # Reverts
/// * When the caller is not the owner.
/// * When the asset does not exist, indicated by a non-`Some` value in the storage.
///
/// # Number of Storage Accesses
/// * Writes: `1`
/// * Reads: `1`
#[storage(write)]
fn update_collateral_asset(asset_id: AssetId, configuration: CollateralConfiguration) {
// Only owner can update collateral asset
only_owner();
// Check if asset exists
require(
storage
.collateral_configurations
.get(asset_id)
.try_read()
.is_some(),
Error::UnknownAsset,
);
storage
.collateral_configurations
.insert(asset_id, configuration);
log(CollateralAssetUpdated {
asset_id,
configuration,
});
}
// ## 2.5 Get all collateral asset configurations
/// This function retrieves all collateral asset configurations in the market.
///
/// # Returns
/// * [Vec<CollateralConfiguration>]: A list of collateral configurations
///
/// # Number of Storage Accesses
/// * Reads: `1 + storage.collateral_configurations_keys.len()`
#[storage(read)]
fn get_collateral_configurations() -> Vec<CollateralConfiguration> {
let mut result = Vec::new();
let mut index = 0;
let len = storage.collateral_configurations_keys.len();
while index < len {
let collateral_configuration = storage.collateral_configurations.get(storage.collateral_configurations_keys.get(index).unwrap().read()).read();
result.push(collateral_configuration);
index += 1;
}
result
}
// ## 3. Collateral asset management (Supply and Withdrawal)
// ## 3.1 Supply Collateral
/// This function ensures that the supplied collateral adheres to the market's rules and limits.
///
/// # Reverts
/// * When the supply is paused.
/// * When the supplied amount is less than or equal to zero.
/// * When the collateral asset is paused.
/// * When the total collateral exceeds the supply cap.
///
/// # Number of Storage Accesses
/// * Writes: `2`
/// * Reads: `4`
#[payable, storage(write)]
fn supply_collateral() {
// Only allow supplying collateral if paused flag is not set
require(!storage.pause_config.supply_paused.read(), Error::Paused);
// Check that the amount is greater than 0
let amount = msg_amount();
require(amount > 0, Error::InvalidPayment);
// Get the asset ID of the collateral asset being supplied and check that it is not paused
let asset_id: AssetId = msg_asset_id();
let collateral_configuration = storage.collateral_configurations.get(asset_id).read();
require(!collateral_configuration.paused, Error::Paused);
// Check that the new total collateral does not exceed the supply cap
let total_collateral = storage.totals_collateral.get(asset_id).try_read().unwrap_or(0) + amount;
require(
collateral_configuration
.supply_cap >= total_collateral,
Error::SupplyCapExceeded,
);
// Get the caller's account and calculate the new user collateral
let caller = msg_sender().unwrap();
let user_collateral = storage.user_collateral.get((caller, asset_id)).try_read().unwrap_or(0) + amount;
// Update the storage values (total collateral, user collateral)
storage.totals_collateral.insert(asset_id, total_collateral);
storage
.user_collateral
.insert((caller, asset_id), user_collateral);
// Log user supply collateral event
log(UserSupplyCollateralEvent {
account: caller,
asset_id,
amount,
});
}
// ## 3.2 Withdraw Collateral
/// This function ensures that the withdrawal adheres to the market's rules and checks for collateralization.
/// # Arguments
/// * `asset_id`: [AssetId] - The asset ID of the collateral asset to be withdrawn.
/// * `amount`: [u64] - The amount of collateral to be withdrawn.
/// * `price_data_update`: [PriceDataUpdate] - The price data update struct to be used for updating the price feeds.
///
/// # Reverts
/// * When the user is not collateralized.
///
/// # Number of Storage Accesses
/// * Writes: `2`
/// * Reads: `4`
#[payable, storage(write)]
fn withdraw_collateral(
asset_id: AssetId,
amount: u64,
price_data_update: PriceDataUpdate,
) {
reentrancy_guard();
// Only allow withdrawing collateral if paused flag is not set
require(!storage.pause_config.withdraw_paused.read(), Error::Paused);
// Get the caller's account and calculate the new user and total collateral
let caller = msg_sender().unwrap();
let user_collateral = storage.user_collateral.get((caller, asset_id)).try_read().unwrap_or(0) - amount;
let total_collateral = storage.totals_collateral.get(asset_id).try_read().unwrap_or(0) - amount;
// Update the storage values (total collateral, user collateral)
storage.totals_collateral.insert(asset_id, total_collateral);
storage
.user_collateral
.insert((caller, asset_id), user_collateral);
// Update price data
update_price_feeds_if_necessary_internal(price_data_update);
// Note: no accrue interest, BorrowCollateralFactor < LiquidationCollateralFactor covers small changes
// Check if the user is borrow collateralized
require(is_borrow_collateralized(caller), Error::NotCollateralized);
transfer(caller, asset_id, amount);
// Log user withdraw collateral event
log(UserWithdrawCollateralEvent {
account: caller,
asset_id,
amount,
});
}
// ## 3.3 Get User Collateral
/// This function retrieves the amount of collateral a user has supplied for a specific asset.
/// # Arguments
/// * `account`: [Identity] - The account of the user.
/// * `asset_id`: [AssetId] - The asset ID of the collateral asset.
///
/// # Returns
/// * [u64] - The amount of collateral the user has supplied for the specified asset.
///
/// # Number of Storage Accesses
/// * Writes: `1`
#[storage(read)]
fn get_user_collateral(account: Identity, asset_id: AssetId) -> u64 {
storage.user_collateral.get((account, asset_id)).try_read().unwrap_or(0)
}
// ## 3.4 Get all of User's Collateral assets
/// This function retrieves all collateral assets that a user has supplied, along with their respective amounts.
/// # Arguments
/// * `account`: [Identity] - The account of the user.
///
/// # Returns
/// * [Vec<(AssetId, u64)>] - A list of tuples containing the asset ID and total collateral for each collateral asset.
///
/// # Number of Storage Accesses
/// * Writes: `storage.collateral_configurations_keys.len()`
/// * Reads: `1 + storage.collateral_configurations_keys.len() * 3`
#[storage(read)]
fn get_all_user_collateral(account: Identity) -> Vec<(AssetId, u64)> {
let mut result = Vec::new();
let mut index = 0;
let len = storage.collateral_configurations_keys.len();
while index < len {
let collateral_configuration = storage.collateral_configurations.get(storage.collateral_configurations_keys.get(index).unwrap().read()).read();
let collateral_amount = storage.user_collateral.get((account, collateral_configuration.asset_id)).try_read().unwrap_or(0);
result.push((collateral_configuration.asset_id, collateral_amount));
index += 1;
}
result
}
// ## 3.5 Get Total Collateral
/// This function retrieves the total collateral amount for a specific asset.
///
/// # Arguments
/// * `asset_id`: [AssetId] - The asset ID of the collateral asset.
///
/// # Returns
/// * [u64] - The total collateral ammount.
/// # Number of Storage Accesses
/// * Writes: `1`
#[storage(read)]
fn totals_collateral(asset_id: AssetId) -> u64 {
storage.totals_collateral.get(asset_id).try_read().unwrap_or(0)
}
// ## 3.6 Get Total Collateral for all collateral assets
/// This function retrieves the total collateral amount for all collateral assets in the market.
///
/// # Returns
/// * [`Vec<(AssetId, u64)>`]: A list of tuples containing the asset ID and total collateral for each collateral asset
///
/// # Number of Storage Accesses
/// * Reads: `1 + storage.collateral_configurations_keys.len() * 2`
#[storage(read)]
fn get_all_totals_collateral() -> Vec<(AssetId, u64)> {
let mut result = Vec::new();
let mut index = 0;
let len = storage.collateral_configurations_keys.len();
while index < len {
let asset_id = storage.collateral_configurations_keys.get(index).unwrap().read();
result.push((asset_id, storage.totals_collateral.get(asset_id).try_read().unwrap_or(0)));
index += 1;
}
result
}
// ## 4. Base asset management (Supply and Withdrawal)
// ## 4.1 Supply Base
/// This function allows users to supply base assets to the market, updating their balance and the market's total supply.
///
/// # Arguments
/// This function does not take any parameters directly, as it uses the message context to retrieve the amount and asset ID.
///
/// # Reverts
/// * When the supply is paused.
/// * When the supplied amount is less than or equal to zero.
/// * When the supplied asset is not the base asset.
///
/// # Number of Storage Accesses
/// * Writes: `2`
/// * Reads: `4`
#[payable, storage(write)]
fn supply_base() {
// Only allow supplying if paused flag is not set
require(!storage.pause_config.supply_paused.read(), Error::Paused);
// Check that the amount is greater than 0 and that supplied asset is the base asset
let amount = msg_amount();
let base_asset_id = storage.market_configuration.read().base_token;
require(
amount > 0 && msg_asset_id() == base_asset_id,
Error::InvalidPayment,
);
// Accrue interest
accrue_internal();
// Get caller's user basic state
let caller = msg_sender().unwrap();
let user_basic = storage.user_basic.get(caller).try_read().unwrap_or(UserBasic::default());
let user_principal = user_basic.principal;
// Calculate new balance and principal value
let user_balance = present_value(user_principal) + I256::try_from(u256::from(amount)).unwrap();
let user_principal_new = principal_value(user_balance);
// Calculate repay and supply amounts
let (repay_amount, supply_amount) = repay_and_supply_amount(user_principal, user_principal_new);
// Read and update market basic information
let mut market_basic = storage.market_basic.read();
market_basic.total_supply_base += supply_amount;
market_basic.total_borrow_base -= repay_amount;
// Write to storage (market_basic)
storage.market_basic.write(market_basic);
// Update and write principal to storage
update_base_principal(caller, user_basic, user_principal_new);
if user_balance < I256::zero() {
// Check that the borrow amount is greater than the minimum allowed
require(
u256::try_from(user_balance.wrapping_neg())
.unwrap() >= storage
.market_configuration
.read()
.base_borrow_min,
Error::BorrowTooSmall,
);
}
// Emit user supply base event
log(UserSupplyBaseEvent {
account: caller,
supply_amount,
repay_amount,
});
// Emit market basic event
log(MarketBasicEvent { market_basic });
}
// ## 4.2 Withdraw base (borrowing if possible/necessary)
/// This function allows users to withdraw a specified amount of base assets, potentially borrowing if necessary.
///
/// # Arguments
/// * `amount`: [u64] - The amount of base asset to be withdrawn.
/// * `price_data_update`: [PriceDataUpdate] - The price data update struct to be used for updating the price feeds.
///
/// # Reverts
/// * When the user is not collateralized.
///
/// # Number of Storage Accesses
/// * Writes: `3`
/// * Reads: `5`
#[payable, storage(write)]
fn withdraw_base(amount: u64, price_data_update: PriceDataUpdate) {
reentrancy_guard();
// Only allow withdrawing if paused flag is not set
require(!storage.pause_config.withdraw_paused.read(), Error::Paused);
// Check that the amount is greater than 0
require(amount > 0, Error::InvalidPayment);
// Accrue interest
accrue_internal();
// Get caller's user basic state
let caller = msg_sender().unwrap();
let user_basic = storage.user_basic.get(caller).try_read().unwrap_or(UserBasic::default());
let user_principal = user_basic.principal;
// Calculate new balance and principal value
let user_balance = present_value(user_principal) - I256::try_from(u256::from(amount)).unwrap();
let user_principal_new = principal_value(user_balance);
// Calculate withdraw and borrow amounts
let (withdraw_amount, borrow_amount) = withdraw_and_borrow_amount(user_principal, user_principal_new);
log(UserWithdrawBaseEvent {
account: caller,
withdraw_amount,
borrow_amount,
});
// Read and update market basic information
let mut market_basic = storage.market_basic.read();
market_basic.total_supply_base -= withdraw_amount;
market_basic.total_borrow_base += borrow_amount;
// Write to storage (market_basic)
storage.market_basic.write(market_basic);
// Emit market basic event
log(MarketBasicEvent { market_basic });
// Update and write principal to storage
update_base_principal(caller, user_basic, user_principal_new);
if user_balance < I256::zero() {
// Check that the borrow amount is greater than the minimum allowed
require(
u256::try_from(user_balance.wrapping_neg())
.unwrap() >= storage
.market_configuration
.read()
.base_borrow_min,
Error::BorrowTooSmall,
);
// Update price data
update_price_feeds_if_necessary_internal(price_data_update);
// Check that the user is borrow collateralized
require(is_borrow_collateralized(caller), Error::NotCollateralized);
}
// Transfer base asset to the caller
transfer(
caller,
storage
.market_configuration
.read()
.base_token,
amount,
);
}
// ## 4.3 Get user supply and borrow
/// This function retrieves the amount of base asset supplied and borrowed by a specific user.
///
/// # Arguments
/// * `account`: [Identity] - The account of the user.
///
/// # Returns
/// * [u256] - The amount of base asset supplied by the user.
/// * [u256] - The amount of base asset borrowed by the user.
///
/// # Number of Storage Accesses
/// * Reads: `3`
#[storage(read)]
fn get_user_supply_borrow(account: Identity) -> (u256, u256) {
get_user_supply_borrow_internal(account)
}
// ## 4.4 Get how much user can borrow
/// This function calculates the amount of base asset a user can borrow based on their collateral and current borrow position.
///
/// # Arguments
/// * `account`: [Identity] - The account of the user.
///
/// # Returns
/// * [u256] - The amount of base asset the user can borrow.
///
/// # Number of Storage Accesses
/// * Reads: `4 + storage.collateral_configurations_keys.len() * 5`
#[storage(read)]
fn available_to_borrow(account: Identity) -> u256 {
// Get user's supply and borrow
let (_, borrow) = get_user_supply_borrow_internal(account);
let mut borrow_limit: u256 = 0;
// Calculate borrow limit for each collateral asset the user has
let mut index = 0;
let len = storage.collateral_configurations_keys.len();
let market_configuration = storage.market_configuration.read();
while index < len {
let collateral_configuration = storage.collateral_configurations.get(storage.collateral_configurations_keys.get(index).unwrap().read()).read();
let balance: u256 = storage.user_collateral.get((account, collateral_configuration.asset_id)).try_read().unwrap_or(0).into();
if balance == 0 {
index += 1;
continue;
}
let price = get_price_internal(collateral_configuration.price_feed_id, PricePosition::LowerBound); // decimals: price.exponent
let price_exponent = price.exponent;
let price = u256::from(price.price); // decimals: price.exponent
let amount = balance * collateral_configuration.borrow_collateral_factor / FACTOR_SCALE_18; // decimals: collateral_configuration.decimals
let scale = u256::from(10_u64).pow(
collateral_configuration.decimals + price_exponent - market_configuration.base_token_decimals,
);
borrow_limit += amount * price / scale; // decimals: base_token_decimals
index += 1;
};
// Get the base token price
let base_price = get_price_internal(market_configuration.base_token_price_feed_id, PricePosition::Middle); // decimals: base_price.exponent
let base_price_scale = u256::from(10_u64).pow(base_price.exponent);
let base_price = u256::from(base_price.price); // decimals: base_price.exponent
let borrow_limit = borrow_limit * base_price_scale / base_price; // decimals: base_token_decimals
if borrow_limit < borrow {
u256::zero()
} else {
// Returns how much the user can borrow
borrow_limit - borrow
}
}
// # 5. Liquidation management
// ## 5.1 Absorb
/// This function absorbs a list of underwater accounts onto the protocol balance sheet.
///
/// # Arguments
/// * `accounts`: [Vec<Identity>] - The list of underwater accounts to be absorbed.
/// * `price_data_update`: [PriceDataUpdate] - The price data update struct to be used for updating the price feeds.
///
/// # Number of Storage Accesses
/// * Writes: `2 + accounts.len() * 4`
/// * Reads: `5 + accounts.len() * 5`
#[payable, storage(write)]
fn absorb(accounts: Vec<Identity>, price_data_update: PriceDataUpdate) {
reentrancy_guard();
// Check that the pause flag is not set
require(!storage.pause_config.absorb_paused.read(), Error::Paused);
// Accrue interest
accrue_internal();
// Update price data
update_price_feeds_if_necessary_internal(price_data_update);
let mut index = 0;
// Loop and absorb each account
while index < accounts.len() {
absorb_internal(accounts.get(index).unwrap());
index += 1;
}
}
// ## 5.2 Is liquidatable
/// This function checks if an account is liquidatable.
///
/// # Arguments
/// * account: [Identity] - The account to be checked.
///
/// # Returns
/// * [bool] - True if the account is liquidatable, False otherwise.
///
/// # Number of Storage Accesses
/// * Reads: 1
#[storage(read)]
fn is_liquidatable(account: Identity) -> bool {
let present = get_user_balance_with_interest_internal(account);
is_liquidatable_internal(account, present)
}
// # 6. Protocol collateral management
// ## 6.1 Buying collateral
/// This function allows buying collateral from the protocol. Prices are not updated here as the caller is expected to update them in the same transaction using a multicall handler.
///
/// # Arguments
/// * `asset_id`: [AssetId] - The asset ID of the collateral asset to be bought.
/// * `min_amount`: [u64] - The minimum amount of collateral to be bought.
/// * `recipient`: [Identity] - The account of the recipient of the collateral.
///
/// # Reverts
/// * When the buy operation is paused.
/// * When payment is not in the base token or the amount is zero.
/// * When reserves are sufficient or not less than target reserves.
/// * When the quoted collateral amount is less than the minimum requested.
/// * When collateral reserves are insufficient.
///
/// # Number of Storage Accesses
/// * Reads: `8`
#[payable, storage(read)]
fn buy_collateral(asset_id: AssetId, min_amount: u64, recipient: Identity) {
reentrancy_guard();
// Only allow buying collateral if paused flag is not set
require(!storage.pause_config.buy_paused.read(), Error::Paused);
let payment_amount = msg_amount();
// Only allow payment in the base token and check that the payment amount is greater than 0
require(
msg_asset_id() == storage
.market_configuration
.read()
.base_token && payment_amount > 0,
Error::InvalidPayment,
);
let reserves = get_reserves_internal() - I256::try_from(u256::from(payment_amount)).unwrap();
// Only allow purchases if reserves are negative or if the reserves are less than the target reserves
require(
reserves < I256::zero() || reserves < I256::try_from(storage.market_configuration.read().target_reserves)
.unwrap(),
Error::NotForSale,
);
let reserves = get_collateral_reserves_internal(asset_id);
// Calculate the quote for a collateral asset in exchange for an amount of the base asset
let collateral_amount = quote_collateral_internal(asset_id, payment_amount);
// Check that the quote is greater than or equal to the minimum requested amount
require(collateral_amount >= min_amount, Error::TooMuchSlippage);
// Check that the quote is less than or equal to the reserves
require(
I256::try_from(u256::from(collateral_amount))
.unwrap() <= reserves,
Error::InsufficientReserves,
);
let caller = msg_sender().unwrap();
// Emit buy collateral event
log(BuyCollateralEvent {
caller,
recipient,
asset_id,
amount: collateral_amount,
price: payment_amount,
});
// Transfer the collateral asset to the recipient
transfer(recipient, asset_id, collateral_amount);
}
/// This function calculates the base asset value for selling a collateral asset.
///
/// # Arguments
/// * `asset_id`: [AssetId] - The asset ID of the collateral asset.
/// * `collateral_amount`: [u64] - The amount of the collateral asset.
///
/// # Returns
/// * [u64] - The value of the collateral asset in base asset.
///
/// # Number of Storage Accesses
/// * Reads: `5`
#[storage(read)]
fn collateral_value_to_sell(asset_id: AssetId, collateral_amount: u64) -> u64 { // decimals: base_token_decimals
let collateral_configuration = storage.collateral_configurations.get(asset_id).read();
let market_configuration = storage.market_configuration.read();
// Get the collateral asset price
let asset_price = get_price_internal(collateral_configuration.price_feed_id, PricePosition::UpperBound); // decimals: asset_price.exponent
let asset_price_scale = u256::from(10_u64).pow(asset_price.exponent);
let asset_price = u256::from(asset_price.price); // decimals: asset_price.exponent
let discount_factor: u256 = market_configuration.store_front_price_factor * (FACTOR_SCALE_18 - collateral_configuration.liquidation_penalty) / FACTOR_SCALE_18; // decimals: 18
let asset_price_discounted: u256 = asset_price * (FACTOR_SCALE_18 - discount_factor) / FACTOR_SCALE_18; // decimals: asset_price.exponent
// Get the base token price
let base_price = get_price_internal(market_configuration.base_token_price_feed_id, PricePosition::Middle); // decimals: base_price.exponent
let base_price_scale = u256::from(10_u64).pow(base_price.exponent);
let base_price = u256::from(base_price.price); // decimals: base_price.exponent
let scale = u256::from(10_u64).pow(
collateral_configuration
.decimals - storage
.market_configuration
.read()
.base_token_decimals,
);
let collateral_value = asset_price_discounted * collateral_amount.into() * base_price_scale / asset_price_scale / base_price / scale;
// Native assets are in u64
<u64 as TryFrom<u256>>::try_from(collateral_value).unwrap()
}
// ## 6.3 Get collateral quote for an amount of base asset
/// This function calculates the quote for collateral by considering the asset price, base price, and discount factors based on the collateral configuration.
///
/// # Arguments
/// * `asset_id`: [AssetId] - The asset ID of the collateral asset.
/// * `base_amount`: [u64] - The amount of base asset for which the quote is requested.
///
/// # Returns
/// * [u64] - The quote for the collateral asset in exchange for the base asset.
///
/// # Reverts
/// * When the conversion from `u256` to `u64` fails due to overflow.
///
/// # Number of Storage Accesses
/// * Reads: `2`
#[storage(read)]
fn quote_collateral(asset_id: AssetId, base_amount: u64) -> u64 {
quote_collateral_internal(asset_id, base_amount)
}
// ## 7. Reserves management
// ## 7.1 Get reserves
/// This function calculates and returns the total amount of protocol reserves of the base asset.
///
/// # Returns
/// * [I256] - The reserves of the base asset, expressed in base token decimals.
///
/// # Number of Storage Accesses
/// * Reads: `3` (Reads market basic, market configuration, and current balance of the base token.)
#[storage(read)]
fn get_reserves() -> I256 {
get_reserves_internal()
}
// ## 7.2 Withdraw reserves
/// This function allows the owner to withdraw a specified amount of reserves from the contract.
///
/// # Arguments
/// * `to`: [Identity] - The account to which the reserves will be sent.
/// * `amount`: [u64] - The amount of reserves to be withdrawn.
///
/// # Reverts
/// * When the caller is not the owner.
/// * When the amount requested exceeds the available reserves.
///
/// # Number of Storage Accesses
/// * Reads: `4`
#[storage(read)]
fn withdraw_reserves(to: Identity, amount: u64) {
// Only owner can withdraw reserves
only_owner();
let caller = msg_sender().unwrap();
let reserves = get_reserves_internal();
// Check that the amount is less than or equal to the reserves
require(
reserves >= I256::try_from(u256::from(amount))
.unwrap(),
Error::InsufficientReserves,
);
// Emit reserves withdrawn event
log(ReservesWithdrawnEvent {
caller,
to,
amount,
});
// Transfer the reserves to the recipient
transfer(to, storage.market_configuration.read().base_token, amount)
}
// ## 7.3 Get the collateral reserves of an asset
/// This function retrieves the reserves of a specified collateral asset.
///
/// # Arguments
/// * `asset_id`: [AssetId] - The asset ID of the collateral asset.
///
/// # Returns
/// * [I256] - The reserves (in asset decimals).
///
/// # Number of Storage Accesses
/// * Reads: `1`
#[storage(read)]
fn get_collateral_reserves(asset_id: AssetId) -> I256 {
get_collateral_reserves_internal(asset_id)
}
// ## 8. Pause management