-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathPool.sol
1184 lines (1026 loc) · 38.8 KB
/
Pool.sol
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: BUSL-1.1
pragma solidity 0.8.25;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/Multicall.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./filters/CollateralFilter.sol";
import "./rates/InterestRateModel.sol";
import "./tokenization/DepositToken.sol";
import "./LoanReceipt.sol";
import "./LiquidityLogic.sol";
import "./DepositLogic.sol";
import "./BorrowLogic.sol";
import "./oracle/PriceOracle.sol";
import "./interfaces/IPool.sol";
import "./interfaces/ILiquidity.sol";
import "./interfaces/ICollateralWrapper.sol";
import "./interfaces/ICollateralLiquidator.sol";
import "./interfaces/ICollateralLiquidationReceiver.sol";
/**
* @title Pool
* @author MetaStreet Labs
*/
abstract contract Pool is
ERC165,
ReentrancyGuard,
Multicall,
CollateralFilter,
InterestRateModel,
DepositToken,
PriceOracle,
IPool,
ILiquidity,
ICollateralLiquidationReceiver
{
using SafeCast for uint256;
using SafeERC20 for IERC20;
using LiquidityLogic for LiquidityLogic.Liquidity;
/**************************************************************************/
/* Constants */
/**************************************************************************/
/**
* @notice Tick spacing basis points for absolute type
*/
uint256 public constant ABSOLUTE_TICK_LIMIT_SPACING_BASIS_POINTS =
LiquidityLogic.ABSOLUTE_TICK_LIMIT_SPACING_BASIS_POINTS;
/**
* @notice Tick spacing basis points for ratio type
*/
uint256 public constant RATIO_TICK_LIMIT_SPACING_BASIS_POINTS =
LiquidityLogic.RATIO_TICK_LIMIT_SPACING_BASIS_POINTS;
/**************************************************************************/
/* Structures */
/**************************************************************************/
/**
* @notice Redemption
* @param pending Redemption shares pending
* @param index Redemption queue index
* @param target Redemption queue target
*/
struct Redemption {
uint128 pending;
uint128 index;
uint128 target;
}
/**
* @notice Deposit
* @param shares Shares
* @param redemptionId Next Redemption ID
* @param redemptions Mapping of redemption ID to redemption
*/
struct Deposit {
uint128 shares;
uint128 redemptionId;
mapping(uint128 => Redemption) redemptions;
}
/**
* @notice Delegate
* @param version Delegate version
* @param to Delegate address
*/
struct Delegate {
DelegateVersion version;
address to;
}
/**
* @custom:storage-location erc7201:pool.delegateStorage
* @param delegates Mapping of collateralToken to token ID to Delegate
*/
struct DelegateStorage {
mapping(address => mapping(uint256 => Delegate)) delegates;
}
/**
* @custom:storage-location pool.feeShareStorage
* @param recipient Fee share recipient
* @param split Fee share split of admin fee in basis points
*/
struct FeeShareStorage {
address recipient;
uint16 split;
}
/**
* @notice Loan status
*/
enum LoanStatus {
Uninitialized,
Active,
Repaid,
Liquidated,
CollateralLiquidated
}
/**
* @notice Borrow function options
*/
enum BorrowOptions {
None,
CollateralWrapperContext,
CollateralFilterContext,
DelegateCashV1,
DelegateCashV2,
OracleContext
}
/**
* @notice Delegate version
*/
enum DelegateVersion {
None,
DelegateCashV1,
DelegateCashV2
}
/**************************************************************************/
/* Immutable State */
/**************************************************************************/
/**
* @notice Collateral wrappers (max 3)
*/
address internal immutable _collateralWrapper1;
address internal immutable _collateralWrapper2;
address internal immutable _collateralWrapper3;
/**
* @notice Collateral liquidator
*/
ICollateralLiquidator internal immutable _collateralLiquidator;
/**
* @notice Delegate registry v1 contract
*/
address internal immutable _delegateRegistryV1;
/**
* @notice Delegate registry v2 contract
*/
address internal immutable _delegateRegistryV2;
/**
* @notice Delegate cash storage slot
* @dev keccak256(abi.encode(uint256(keccak256("erc7201:pool.delegateStorage")) - 1)) & ~bytes32(uint256(0xff));
* @dev Erroneous inclusion of "erc7201" in the above namespace ID. No intention to fix.
*/
bytes32 internal constant DELEGATE_STORAGE_LOCATION =
0xf0e5094ebd597f2042580340ce53d1b15e5b64e0d8be717ecde51dd37c619300;
/**
* @notice Fee share storage slot
* @dev keccak256(abi.encode(uint256(keccak256("pool.feeShareStorage")) - 1)) & ~bytes32(uint256(0xff));
*/
bytes32 internal constant FEE_SHARE_STORAGE_LOCATION =
0x1004a5c92d0898c7512a97f012b3e1b4d5140998c1fd26690d21ba53eace8b00;
/**************************************************************************/
/* State */
/**************************************************************************/
/**
* @notice Pool Storage
* @param currencyToken Currency token contract
* @param adminFeeRate Admin fee rate in basis points
* @param durations Durations
* @param rates Rates
* @param admin Admin
* @param adminFeeBalance Admin fee balance
* @param liquidity Liquidity
* @param deposits Mapping of account to tick to deposit
* @param loans Mapping of loan receipt hash to loan status
*/
struct PoolStorage {
IERC20 currencyToken;
uint32 adminFeeRate;
uint64[] durations;
uint64[] rates;
address admin;
uint256 adminFeeBalance;
LiquidityLogic.Liquidity liquidity;
mapping(address => mapping(uint128 => Deposit)) deposits;
mapping(bytes32 => LoanStatus) loans;
}
/**
* @notice Pool state
*/
PoolStorage internal _storage;
/**************************************************************************/
/* Constructor */
/**************************************************************************/
/**
* @notice Pool constructor
* @param collateralLiquidator_ Collateral liquidator
* @param delegateRegistryV1_ Delegate registry v1 contract
* @param delegateRegistryV2_ Delegate registry v2 contract
* @param collateralWrappers_ Collateral wrappers
*/
constructor(
address collateralLiquidator_,
address delegateRegistryV1_,
address delegateRegistryV2_,
address[] memory collateralWrappers_
) {
if (collateralWrappers_.length > 3) revert InvalidParameters();
_collateralLiquidator = ICollateralLiquidator(collateralLiquidator_);
_delegateRegistryV1 = delegateRegistryV1_;
_delegateRegistryV2 = delegateRegistryV2_;
_collateralWrapper1 = (collateralWrappers_.length > 0) ? collateralWrappers_[0] : address(0);
_collateralWrapper2 = (collateralWrappers_.length > 1) ? collateralWrappers_[1] : address(0);
_collateralWrapper3 = (collateralWrappers_.length > 2) ? collateralWrappers_[2] : address(0);
}
/**************************************************************************/
/* Initializer */
/**************************************************************************/
/**
* @notice Pool initializer
* @dev Fee-on-transfer currency tokens are not supported
* @param currencyToken_ Currency token contract
* @param durations_ Duration tiers
* @param rates_ Interest rate tiers
*/
function _initialize(address currencyToken_, uint64[] memory durations_, uint64[] memory rates_) internal {
if (IERC20Metadata(currencyToken_).decimals() > 18) revert InvalidParameters();
_storage.currencyToken = IERC20(currencyToken_);
_storage.admin = msg.sender;
/* Assign durations */
if (durations_.length > Tick.MAX_NUM_DURATIONS) revert InvalidParameters();
for (uint256 i; i < durations_.length; i++) {
/* Check duration is monotonic */
if (i != 0 && durations_[i] >= durations_[i - 1]) revert InvalidParameters();
_storage.durations.push(durations_[i]);
}
/* Assign rates */
if (rates_.length > Tick.MAX_NUM_RATES) revert InvalidParameters();
for (uint256 i; i < rates_.length; i++) {
/* Check rate is monotonic */
if (i != 0 && rates_[i] <= rates_[i - 1]) revert InvalidParameters();
_storage.rates.push(rates_[i]);
}
/* Initialize liquidity */
_storage.liquidity.initialize();
}
/**************************************************************************/
/* Getters */
/**************************************************************************/
/**
* @notice Get implementation name
* @return Implementation name
*/
function IMPLEMENTATION_NAME() external pure virtual returns (string memory);
/**
* @notice Get implementation version
* @return Implementation version
*/
function IMPLEMENTATION_VERSION() external pure returns (string memory) {
return "2.15";
}
/**
* @inheritdoc IPool
*/
function currencyToken() external view returns (address) {
return address(_storage.currencyToken);
}
/**
* @inheritdoc IPool
*/
function durations() external view returns (uint64[] memory) {
return _storage.durations;
}
/**
* @inheritdoc IPool
*/
function rates() external view returns (uint64[] memory) {
return _storage.rates;
}
/**
* @inheritdoc IPool
*/
function admin() external view returns (address) {
return _storage.admin;
}
/**
* @inheritdoc IPool
*/
function adminFeeRate() external view returns (uint32) {
return _storage.adminFeeRate;
}
/**
* @inheritdoc IPool
*/
function adminFeeBalance() external view returns (uint256) {
return _unscale(_storage.adminFeeBalance, false);
}
/**
* @notice Get fee share
* @return recipient Fee share recipient
* @return split Fee share split of admin fee in basis points
*/
function feeShare() external view returns (address recipient, uint16 split) {
return (_getFeeShareStorage().recipient, _getFeeShareStorage().split);
}
/**
* @inheritdoc IPool
*/
function collateralWrappers() external view returns (address[] memory) {
address[] memory collateralWrappers_ = new address[](3);
collateralWrappers_[0] = _collateralWrapper1;
collateralWrappers_[1] = _collateralWrapper2;
collateralWrappers_[2] = _collateralWrapper3;
return collateralWrappers_;
}
/**
* @inheritdoc IPool
*/
function collateralLiquidator() external view returns (address) {
return address(_collateralLiquidator);
}
/**
* @inheritdoc IPool
*/
function delegationRegistry() external view returns (address) {
return address(_delegateRegistryV1);
}
/**
* @inheritdoc IPool
*/
function delegationRegistryV2() external view returns (address) {
return address(_delegateRegistryV2);
}
/**
* @notice Get deposit
* @param account Account
* @param tick Tick
* @return shares Shares
* @return redemptionId Redemption ID
*/
function deposits(address account, uint128 tick) external view returns (uint128 shares, uint128 redemptionId) {
shares = _storage.deposits[account][tick].shares;
redemptionId = _storage.deposits[account][tick].redemptionId;
}
/**
* @notice Get redemption
* @param account Account
* @param tick Tick
* @param redemptionId Redemption ID
* @return pending Redemption quantity pending
* @return index Redemption index
* @return target Redemption quantity target
*/
function redemptions(
address account,
uint128 tick,
uint128 redemptionId
) external view returns (uint128 pending, uint128 index, uint128 target) {
return (
_storage.deposits[account][tick].redemptions[redemptionId].pending,
_storage.deposits[account][tick].redemptions[redemptionId].index,
_storage.deposits[account][tick].redemptions[redemptionId].target
);
}
/**
* @notice Get loan status
* @param receiptHash Loan receipt hash
* @return Loan status
*/
function loans(bytes32 receiptHash) external view returns (LoanStatus) {
return _storage.loans[receiptHash];
}
/**
* @inheritdoc ILiquidity
*/
function liquidityNodes(uint128 startTick, uint128 endTick) external view returns (NodeInfo[] memory) {
return _storage.liquidity.liquidityNodes(startTick, endTick);
}
/**
* @inheritdoc ILiquidity
*/
function liquidityNode(uint128 tick) external view returns (NodeInfo memory) {
return _storage.liquidity.liquidityNode(tick);
}
/**
* @inheritdoc ILiquidity
*/
function liquidityNodeWithAccrual(uint128 tick) external view returns (NodeInfo memory, AccrualInfo memory) {
return _storage.liquidity.liquidityNodeWithAccrual(tick);
}
/**
* @inheritdoc ILiquidity
*/
function depositSharePrice(uint128 tick) external view returns (uint256) {
return _unscale(_storage.liquidity.depositSharePrice(tick), false);
}
/**
* @inheritdoc ILiquidity
*/
function redemptionSharePrice(uint128 tick) external view returns (uint256) {
return _unscale(_storage.liquidity.redemptionSharePrice(tick), false);
}
/**************************************************************************/
/* Loan Receipt External Helpers */
/**************************************************************************/
/**
* @notice Decode loan receipt
* @param loanReceipt Loan receipt
* @return Decoded loan receipt
*/
function decodeLoanReceipt(bytes calldata loanReceipt) external pure returns (LoanReceipt.LoanReceiptV2 memory) {
return BorrowLogic._decodeLoanReceipt(loanReceipt);
}
/**************************************************************************/
/* Helper Functions */
/**************************************************************************/
/**
* @notice Helper function that returns underlying collateral in (address,
* uint256[], uint256) shape
* @param collateralToken Collateral token, either underlying token or collateral wrapper
* @param collateralTokenId Collateral token ID
* @param collateralWrapperContext Collateral wrapper context
* @return token Underlying collateral token
* @return tokenIds Underlying collateral token IDs (unique)
* @return tokenIdQuantities Underlying collateral token ID quantities
* @return tokenCount Underlying total token count
*/
function _getUnderlyingCollateral(
address collateralToken,
uint256 collateralTokenId,
bytes memory collateralWrapperContext
)
internal
view
returns (address token, uint256[] memory tokenIds, uint256[] memory tokenIdQuantities, uint256 tokenCount)
{
/* Enumerate if collateral token is a collateral wrapper */
if (
collateralToken == _collateralWrapper1 ||
collateralToken == _collateralWrapper2 ||
collateralToken == _collateralWrapper3
) {
(token, tokenIds, tokenIdQuantities) = ICollateralWrapper(collateralToken).enumerateWithQuantities(
collateralTokenId,
collateralWrapperContext
);
tokenCount = ICollateralWrapper(collateralToken).count(collateralTokenId, collateralWrapperContext);
return (token, tokenIds, tokenIdQuantities, tokenCount);
}
/* If single asset, convert to length one token ID array */
token = collateralToken;
tokenIds = new uint256[](1);
tokenIds[0] = collateralTokenId;
tokenIdQuantities = new uint256[](1);
tokenIdQuantities[0] = 1;
tokenCount = 1;
}
/**
* @notice Get reference to ERC-7201 delegate storage
* @return $ Reference to delegate storage
*/
function _getDelegateStorage() private pure returns (DelegateStorage storage $) {
assembly {
$.slot := DELEGATE_STORAGE_LOCATION
}
}
/**
* @notice Get reference to ERC-7201 fee share storage
* @return $ Reference to fee share storage
*/
function _getFeeShareStorage() private pure returns (FeeShareStorage storage $) {
assembly {
$.slot := FEE_SHARE_STORAGE_LOCATION
}
}
/**
* @dev Helper function to quote a loan
* @param principal Principal amount in currency tokens
* @param duration Duration in seconds
* @param collateralToken_ Collateral token address
* @param collateralTokenId Collateral token ID
* @param ticks Liquidity node ticks
* @param collateralWrapperContext Collateral wrapper context
* @param collateralFilterContext Collateral filter context
* @param oracleContext Oracle context
* @param isRefinance True if called by refinance()
* @return Repayment amount in currency tokens, admin fee in currency
* tokens, liquidity nodes, liquidity node count
*/
function _quote(
uint256 principal,
uint64 duration,
address collateralToken_,
uint256 collateralTokenId,
uint128[] calldata ticks,
bytes memory collateralWrapperContext,
bytes calldata collateralFilterContext,
bytes calldata oracleContext,
bool isRefinance
) internal view returns (uint256, uint256, LiquidityLogic.NodeSource[] memory, uint16) {
/* Get underlying collateral */
(
address underlyingCollateralToken,
uint256[] memory underlyingCollateralTokenIds,
uint256[] memory underlyingQuantities,
uint256 underlyingCollateralTokenCount
) = _getUnderlyingCollateral(collateralToken_, collateralTokenId, collateralWrapperContext);
/* Verify collateral is supported */
if (!isRefinance) {
for (uint256 i; i < underlyingCollateralTokenIds.length; i++) {
if (
!_collateralSupported(
underlyingCollateralToken,
underlyingCollateralTokenIds[i],
i,
collateralFilterContext
)
) revert UnsupportedCollateral(i);
}
}
/* Cache durations */
uint64[] memory durations_ = _storage.durations;
/* Validate duration */
if (duration > durations_[0]) revert UnsupportedLoanDuration();
/* Lookup duration index */
uint256 durationIndex = durations_.length - 1;
for (; durationIndex != 0; durationIndex--) {
if (duration <= durations_[durationIndex]) break;
}
/* Get oracle price if price oracle exists, else 0 */
uint256 oraclePrice = price(
collateralToken(),
address(_storage.currencyToken),
underlyingCollateralTokenIds,
underlyingQuantities,
oracleContext
);
/* Source liquidity nodes */
(LiquidityLogic.NodeSource[] memory nodes, uint16 count) = _storage.liquidity.source(
principal,
ticks,
underlyingCollateralTokenCount,
durationIndex,
_scale(oraclePrice)
);
/* Price interest for liquidity nodes */
(uint256 repayment, uint256 adminFee) = _price(
principal,
duration,
nodes,
count,
_storage.rates,
_storage.adminFeeRate
);
return (repayment, adminFee, nodes, count);
}
/**
* @dev Helper function to transfer collateral
* @param from From
* @param to To
* @param collateralToken Collateral token
* @param collateralTokenId Collateral token ID
*/
function _transferCollateral(
address from,
address to,
address collateralToken,
uint256 collateralTokenId
) internal virtual {
IERC721(collateralToken).transferFrom(from, to, collateralTokenId);
}
/**
* @dev Helper function to liquidate collateral
* @param collateralToken Collateral token
* @param collateralTokenId Collateral token ID
* @param collateralWrapperContext Collateral wrapper context
* @param encodedLoanReceipt Encoded loan receipt
*/
function _liquidateCollateral(
address collateralToken,
uint256 collateralTokenId,
bytes memory collateralWrapperContext,
bytes calldata encodedLoanReceipt
) internal virtual {
/* Approve collateral for transfer to _collateralLiquidator */
IERC721(collateralToken).approve(address(_collateralLiquidator), collateralTokenId);
/* Start liquidation with collateral liquidator */
_collateralLiquidator.liquidate(
address(_storage.currencyToken),
collateralToken,
collateralTokenId,
collateralWrapperContext,
encodedLoanReceipt
);
}
/**
* @dev Helper function to transfer fee share
* @param feeShareRecipient Fee share recipient
* @param feeShareAmount Fee share amount
*/
function _transferFeeShare(address feeShareRecipient, uint256 feeShareAmount) internal {
/* Transfer currency token to fee share recipient */
uint256 unscaledFeeShareAmount = _unscale(feeShareAmount, false);
_storage.currencyToken.safeTransfer(feeShareRecipient, unscaledFeeShareAmount);
/* Emit Admin Fee Share Transferred */
emit AdminFeeShareTransferred(feeShareRecipient, unscaledFeeShareAmount);
}
/**
* @dev Helper function to get currency token scaling factor
* @return Factor
*/
function _scaleFactor() internal view returns (uint256) {
return 10 ** (18 - IERC20Metadata(address(_storage.currencyToken)).decimals());
}
/**
* @dev Helper function to scale up a value
* @param value Value
* @return Scaled value
*/
function _scale(uint256 value) internal view returns (uint256) {
return value * _scaleFactor();
}
/**
* @dev Helper function to scale down a value
* @param value Value
* @param isRoundUp Round up if true
* @return Unscaled value
*/
function _unscale(uint256 value, bool isRoundUp) internal view returns (uint256) {
uint256 factor = _scaleFactor();
return (value % factor == 0 || !isRoundUp) ? value / factor : value / factor + 1;
}
/**************************************************************************/
/* Lend API */
/**************************************************************************/
/**
* @inheritdoc IPool
*/
function quote(
uint256 principal,
uint64 duration,
address collateralToken,
uint256 collateralTokenId,
uint128[] calldata ticks,
bytes calldata options
) external view returns (uint256) {
/* Quote repayment */
(uint256 repayment, , , ) = _quote(
_scale(principal),
duration,
collateralToken,
collateralTokenId,
ticks,
BorrowLogic._getOptionsData(options, BorrowOptions.CollateralWrapperContext),
BorrowLogic._getOptionsData(options, BorrowOptions.CollateralFilterContext),
BorrowLogic._getOptionsData(options, BorrowOptions.OracleContext),
false
);
return _unscale(repayment, true);
}
/**
* @inheritdoc IPool
*/
function borrow(
uint256 principal,
uint64 duration,
address collateralToken,
uint256 collateralTokenId,
uint256 maxRepayment,
uint128[] calldata ticks,
bytes calldata options
) external nonReentrant returns (uint256) {
uint256 scaledPrincipal = _scale(principal);
/* Quote repayment, admin fee, and liquidity nodes */
(uint256 repayment, uint256 adminFee, LiquidityLogic.NodeSource[] memory nodes, uint16 count) = _quote(
scaledPrincipal,
duration,
collateralToken,
collateralTokenId,
ticks,
BorrowLogic._getOptionsData(options, BorrowOptions.CollateralWrapperContext),
BorrowLogic._getOptionsData(options, BorrowOptions.CollateralFilterContext),
BorrowLogic._getOptionsData(options, BorrowOptions.OracleContext),
false
);
/* Handle borrow accounting */
(bytes memory encodedLoanReceipt, bytes32 loanReceiptHash) = BorrowLogic._borrow(
_storage,
scaledPrincipal,
duration,
collateralToken,
collateralTokenId,
repayment,
_scale(maxRepayment),
adminFee,
nodes,
count,
BorrowLogic._getOptionsData(options, BorrowOptions.CollateralWrapperContext)
);
/* Handle delegate.cash option */
BorrowLogic._optionDelegateCash(
_getDelegateStorage(),
collateralToken,
collateralTokenId,
_delegateRegistryV1,
_delegateRegistryV2,
options
);
/* Transfer collateral from borrower to pool */
_transferCollateral(msg.sender, address(this), collateralToken, collateralTokenId);
/* Transfer principal from pool to borrower */
_storage.currencyToken.safeTransfer(msg.sender, principal);
/* Emit LoanOriginated */
emit LoanOriginated(loanReceiptHash, encodedLoanReceipt);
return _unscale(repayment, true);
}
/**
* @inheritdoc IPool
*/
function repay(bytes calldata encodedLoanReceipt) external nonReentrant returns (uint256) {
/* Handle repay accounting */
(
uint256 repayment,
uint256 feeShareAmount,
LoanReceipt.LoanReceiptV2 memory loanReceipt,
bytes32 loanReceiptHash
) = BorrowLogic._repay(_storage, _getFeeShareStorage(), encodedLoanReceipt);
uint256 unscaledRepayment = _unscale(repayment, true);
/* Revoke delegates */
BorrowLogic._revokeDelegates(
_getDelegateStorage(),
loanReceipt.collateralToken,
loanReceipt.collateralTokenId,
_delegateRegistryV1,
_delegateRegistryV2
);
/* Transfer repayment from borrower to pool */
_storage.currencyToken.safeTransferFrom(loanReceipt.borrower, address(this), unscaledRepayment);
/* Transfer collateral from pool to borrower */
_transferCollateral(
address(this),
loanReceipt.borrower,
loanReceipt.collateralToken,
loanReceipt.collateralTokenId
);
/* Transfer currency token to fee share recipient */
if (feeShareAmount != 0) _transferFeeShare(_getFeeShareStorage().recipient, feeShareAmount);
/* Emit Loan Repaid */
emit LoanRepaid(loanReceiptHash, unscaledRepayment);
return unscaledRepayment;
}
/**
* @inheritdoc IPool
*/
function refinance(
bytes calldata encodedLoanReceipt,
uint256 principal,
uint64 duration,
uint256 maxRepayment,
uint128[] calldata ticks,
bytes calldata options
) external nonReentrant returns (uint256) {
uint256 scaledPrincipal = _scale(principal);
/* Handle repay accounting */
(
uint256 repayment,
uint256 feeShareAmount,
LoanReceipt.LoanReceiptV2 memory loanReceipt,
bytes32 loanReceiptHash
) = BorrowLogic._repay(_storage, _getFeeShareStorage(), encodedLoanReceipt);
uint256 unscaledRepayment = _unscale(repayment, true);
/* Quote new repayment, admin fee, and liquidity nodes */
(uint256 newRepayment, uint256 adminFee, LiquidityLogic.NodeSource[] memory nodes, uint16 count) = _quote(
scaledPrincipal,
duration,
loanReceipt.collateralToken,
loanReceipt.collateralTokenId,
ticks,
loanReceipt.collateralWrapperContext,
encodedLoanReceipt[0:0],
BorrowLogic._getOptionsData(options, BorrowOptions.OracleContext),
true
);
/* Handle borrow accounting */
(bytes memory newEncodedLoanReceipt, bytes32 newLoanReceiptHash) = BorrowLogic._borrow(
_storage,
scaledPrincipal,
duration,
loanReceipt.collateralToken,
loanReceipt.collateralTokenId,
newRepayment,
_scale(maxRepayment),
adminFee,
nodes,
count,
loanReceipt.collateralWrapperContext
);
/* Determine transfer direction */
if (principal < unscaledRepayment) {
/* Transfer prorated repayment less principal from borrower to pool */
_storage.currencyToken.safeTransferFrom(loanReceipt.borrower, address(this), unscaledRepayment - principal);
} else {
/* Transfer principal less prorated repayment from pool to borrower */
_storage.currencyToken.safeTransfer(msg.sender, principal - unscaledRepayment);
}
/* Transfer currency token to fee share recipient */
if (feeShareAmount != 0) _transferFeeShare(_getFeeShareStorage().recipient, feeShareAmount);
/* Emit Loan Repaid */
emit LoanRepaid(loanReceiptHash, unscaledRepayment);
/* Emit LoanOriginated */
emit LoanOriginated(newLoanReceiptHash, newEncodedLoanReceipt);
return _unscale(newRepayment, true);
}
/**
* @inheritdoc IPool
*/
function liquidate(bytes calldata encodedLoanReceipt) external nonReentrant {
/* Handle liquidate accounting */
(LoanReceipt.LoanReceiptV2 memory loanReceipt, bytes32 loanReceiptHash) = BorrowLogic._liquidate(
_storage,
encodedLoanReceipt
);
/* Revoke delegates */
BorrowLogic._revokeDelegates(
_getDelegateStorage(),
loanReceipt.collateralToken,
loanReceipt.collateralTokenId,
_delegateRegistryV1,
_delegateRegistryV2
);
/* Liquidate collateral */
_liquidateCollateral(
loanReceipt.collateralToken,
loanReceipt.collateralTokenId,
loanReceipt.collateralWrapperContext,
encodedLoanReceipt
);
/* Emit Loan Liquidated */
emit LoanLiquidated(loanReceiptHash);
}
/**************************************************************************/
/* Callbacks */
/**************************************************************************/
/**
* @inheritdoc ICollateralLiquidationReceiver
*/
function onCollateralLiquidated(bytes calldata encodedLoanReceipt, uint256 proceeds) external nonReentrant {
/* Validate caller is collateral liquidator */
if (msg.sender != address(_collateralLiquidator)) revert InvalidCaller();
/* Handle collateral liquidation accounting */
(uint256 borrowerSurplus, LoanReceipt.LoanReceiptV2 memory loanReceipt, bytes32 loanReceiptHash) = BorrowLogic
._onCollateralLiquidated(_storage, encodedLoanReceipt, _scale(proceeds));
uint256 unscaledBorrowerSurplus = _unscale(borrowerSurplus, false);
/* Transfer surplus to borrower */
if (unscaledBorrowerSurplus != 0)
IERC20(_storage.currencyToken).safeTransfer(loanReceipt.borrower, unscaledBorrowerSurplus);
/* Emit Collateral Liquidated */
emit CollateralLiquidated(loanReceiptHash, proceeds, unscaledBorrowerSurplus);
}
/**************************************************************************/
/* Deposit API */
/**************************************************************************/
/**
* @inheritdoc IPool
*/
function deposit(uint128 tick, uint256 amount, uint256 minShares) external nonReentrant returns (uint256) {
/* Handle deposit accounting and compute shares */
uint128 shares = DepositLogic._deposit(_storage, tick, _scale(amount).toUint128(), minShares.toUint128());
/* Call token hook */
_onExternalTransfer(address(0), msg.sender, tick, shares);