-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathInvestmentManager.sol
764 lines (649 loc) · 36.6 KB
/
InvestmentManager.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
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.21;
import {Auth} from "./util/Auth.sol";
import {MathLib} from "./util/MathLib.sol";
import {SafeTransferLib} from "./util/SafeTransferLib.sol";
interface GatewayLike {
function increaseInvestOrder(uint64 poolId, bytes16 trancheId, address investor, uint128 currency, uint128 amount)
external;
function decreaseInvestOrder(uint64 poolId, bytes16 trancheId, address investor, uint128 currency, uint128 amount)
external;
function increaseRedeemOrder(uint64 poolId, bytes16 trancheId, address investor, uint128 currency, uint128 amount)
external;
function decreaseRedeemOrder(uint64 poolId, bytes16 trancheId, address investor, uint128 currency, uint128 amount)
external;
function collectInvest(uint64 poolId, bytes16 trancheId, address investor, uint128 currency) external;
function collectRedeem(uint64 poolId, bytes16 trancheId, address investor, uint128 currency) external;
function cancelInvestOrder(uint64 poolId, bytes16 trancheId, address investor, uint128 currency) external;
function cancelRedeemOrder(uint64 poolId, bytes16 trancheId, address investor, uint128 currency) external;
}
interface ERC20Like {
function approve(address token, address spender, uint256 value) external;
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function decimals() external view returns (uint8);
function mint(address, uint256) external;
function burn(address, uint256) external;
}
interface LiquidityPoolLike is ERC20Like {
function poolId() external returns (uint64);
function trancheId() external returns (bytes16);
function asset() external view returns (address);
function hasMember(address) external returns (bool);
function updatePrice(uint128 price) external;
function checkTransferRestriction(address from, address to, uint256 value) external view returns (bool);
function latestPrice() external view returns (uint128);
}
interface PoolManagerLike {
function currencyIdToAddress(uint128 currencyId) external view returns (address);
function currencyAddressToId(address addr) external view returns (uint128);
function getTrancheToken(uint64 poolId, bytes16 trancheId) external view returns (address);
function getLiquidityPool(uint64 poolId, bytes16 trancheId, address currency) external view returns (address);
function isAllowedAsPoolCurrency(uint64 poolId, address currencyAddress) external view returns (bool);
}
interface EscrowLike {
function approve(address token, address spender, uint256 value) external;
}
interface UserEscrowLike {
function transferIn(address token, address source, address destination, uint256 amount) external;
function transferOut(address token, address owner, address destination, uint256 amount) external;
}
/// @dev Liquidity Pool orders and investment/redemption limits per user
struct LPValues {
uint128 maxDeposit; // denominated in currency
uint128 maxMint; // denominated in tranche tokens
uint128 maxWithdraw; // denominated in currency
uint128 maxRedeem; // denominated in tranche tokens
uint128 remainingInvestOrder; // denominated in currency
uint128 remainingRedeemOrder; // denominated in tranche tokens
}
/// @title Investment Manager
/// @notice This is the main contract LiquidityPools interact with for
/// both incoming and outgoing investment transactions.
contract InvestmentManager is Auth {
using MathLib for uint256;
using MathLib for uint128;
/// @dev Prices are fixed-point integers with 18 decimals
uint8 internal constant PRICE_DECIMALS = 18;
EscrowLike public immutable escrow;
UserEscrowLike public immutable userEscrow;
GatewayLike public gateway;
PoolManagerLike public poolManager;
mapping(address investor => mapping(address liquidityPool => LPValues)) public orderbook;
// --- Events ---
event File(bytes32 indexed what, address data);
event ProcessDeposit(
address indexed liquidityPool, address indexed user, uint128 currencyAmount, uint128 trancheTokenAmount
);
event ProcessRedeem(
address indexed liquidityPool, address indexed user, uint128 currencyAmount, uint128 trancheTokenAmount
);
event ExecutedCollectInvest(
uint64 indexed poolId,
bytes16 indexed trancheId,
address recipient,
uint128 currency,
uint128 currencyPayout,
uint128 trancheTokensPayout
);
event ExecutedCollectRedeem(
uint64 indexed poolId,
bytes16 indexed trancheId,
address recipient,
uint128 currency,
uint128 currencyPayout,
uint128 trancheTokensPayout
);
event ExecutedDecreaseInvestOrder(
uint64 indexed poolId, bytes16 indexed trancheId, address user, uint128 currency, uint128 currencyPayout
);
event ExecutedDecreaseRedeemOrder(
uint64 indexed poolId, bytes16 indexed trancheId, address user, uint128 currency, uint128 trancheTokensPayout
);
constructor(address escrow_, address userEscrow_) {
escrow = EscrowLike(escrow_);
userEscrow = UserEscrowLike(userEscrow_);
wards[msg.sender] = 1;
emit Rely(msg.sender);
}
/// @dev Gateway must be msg.sender for incoming messages
modifier onlyGateway() {
require(msg.sender == address(gateway), "InvestmentManager/not-the-gateway");
_;
}
// --- Administration ---
function file(bytes32 what, address data) external auth {
if (what == "gateway") gateway = GatewayLike(data);
else if (what == "poolManager") poolManager = PoolManagerLike(data);
else revert("InvestmentManager/file-unrecognized-param");
emit File(what, data);
}
// --- Outgoing message handling ---
/// @notice Request deposit. Liquidity pools have to request investments from Centrifuge before actual tranche tokens can be minted.
/// The deposit requests are added to the order book on Centrifuge. Once the next epoch is executed on Centrifuge,
/// liquidity pools can proceed with tranche token payouts in case their orders got fulfilled.
/// If an amount of 0 is passed, this triggers cancelling outstanding deposit orders.
/// @dev The user currency amount required to fulfill the deposit request have to be locked,
/// even though the tranche token payout can only happen after epoch execution.
function requestDeposit(address liquidityPool, uint256 currencyAmount, address user) public auth {
LiquidityPoolLike lPool = LiquidityPoolLike(liquidityPool);
uint128 _currencyAmount = _toUint128(currencyAmount);
require(_currencyAmount != 0, "InvestmentManager/zero-amount-not-allowed");
uint64 poolId = lPool.poolId();
bytes16 trancheId = lPool.trancheId();
address currency = lPool.asset();
uint128 currencyId = poolManager.currencyAddressToId(currency);
poolManager.isAllowedAsPoolCurrency(poolId, currency);
require(
lPool.checkTransferRestriction(address(0), user, convertToShares(liquidityPool, currencyAmount)),
"InvestmentManager/transfer-not-allowed"
);
// Transfer the currency amount from user to escrow (lock currency in escrow)
SafeTransferLib.safeTransferFrom(currency, user, address(escrow), _currencyAmount);
LPValues storage lpValues = orderbook[user][liquidityPool];
lpValues.remainingInvestOrder = lpValues.remainingInvestOrder + _currencyAmount;
gateway.increaseInvestOrder(poolId, trancheId, user, currencyId, _currencyAmount);
}
/// @notice Request tranche token redemption. Liquidity pools have to request redemptions from Centrifuge before actual currency payouts can be done.
/// The redemption requests are added to the order book on Centrifuge. Once the next epoch is executed on Centrifuge,
/// liquidity pools can proceed with currency payouts in case their orders got fulfilled.
/// If an amount of 0 is passed, this triggers cancelling outstanding redemption orders.
/// @dev The user tranche tokens required to fulfill the redemption request have to be locked, even though the currency payout can only happen after epoch execution.
function requestRedeem(address liquidityPool, uint256 trancheTokenAmount, address user) public auth {
LiquidityPoolLike lPool = LiquidityPoolLike(liquidityPool);
uint128 _trancheTokenAmount = _toUint128(trancheTokenAmount);
require(_trancheTokenAmount != 0, "InvestmentManager/zero-amount-not-allowed");
uint64 poolId = lPool.poolId();
bytes16 trancheId = lPool.trancheId();
address currency = lPool.asset();
uint128 currencyId = poolManager.currencyAddressToId(currency);
poolManager.isAllowedAsPoolCurrency(poolId, currency);
// Transfer the tranche token amount from user to escrow (lock tranche tokens in escrow)
lPool.transferFrom(user, address(escrow), _trancheTokenAmount);
LPValues storage lpValues = orderbook[user][liquidityPool];
lpValues.remainingRedeemOrder = lpValues.remainingRedeemOrder + _trancheTokenAmount;
gateway.increaseRedeemOrder(poolId, trancheId, user, currencyId, _trancheTokenAmount);
}
function decreaseDepositRequest(address liquidityPool, uint256 _currencyAmount, address user) public auth {
uint128 currencyAmount = _toUint128(_currencyAmount);
LiquidityPoolLike _liquidityPool = LiquidityPoolLike(msg.sender);
gateway.decreaseInvestOrder(
_liquidityPool.poolId(),
_liquidityPool.trancheId(),
user,
poolManager.currencyAddressToId(_liquidityPool.asset()),
currencyAmount
);
}
function decreaseRedeemRequest(address liquidityPool, uint256 _trancheTokenAmount, address user) public auth {
uint128 trancheTokenAmount = _toUint128(_trancheTokenAmount);
LiquidityPoolLike _liquidityPool = LiquidityPoolLike(msg.sender);
require(
_liquidityPool.checkTransferRestriction(address(0), user, _trancheTokenAmount),
"InvestmentManager/transfer-not-allowed"
);
gateway.decreaseRedeemOrder(
_liquidityPool.poolId(),
_liquidityPool.trancheId(),
user,
poolManager.currencyAddressToId(_liquidityPool.asset()),
trancheTokenAmount
);
}
function cancelDepositRequest(address liquidityPool, address user) public auth {
LiquidityPoolLike _liquidityPool = LiquidityPoolLike(msg.sender);
gateway.cancelInvestOrder(
_liquidityPool.poolId(),
_liquidityPool.trancheId(),
user,
poolManager.currencyAddressToId(_liquidityPool.asset())
);
}
function cancelRedeemRequest(address liquidityPool, address user) public auth {
LiquidityPoolLike _liquidityPool = LiquidityPoolLike(msg.sender);
uint256 approximateTrancheTokenPayout = userRedeemRequest(liquidityPool, user);
require(
_liquidityPool.checkTransferRestriction(address(0), user, approximateTrancheTokenPayout),
"InvestmentManager/transfer-not-allowed"
);
gateway.cancelRedeemOrder(
_liquidityPool.poolId(),
_liquidityPool.trancheId(),
user,
poolManager.currencyAddressToId(_liquidityPool.asset())
);
}
function collectDeposit(address liquidityPool, address user) public auth {
LiquidityPoolLike _liquidityPool = LiquidityPoolLike(msg.sender);
uint256 approximateMaxTrancheTokenPayout =
convertToShares(liquidityPool, userDepositRequest(liquidityPool, user));
require(
_liquidityPool.checkTransferRestriction(address(escrow), user, approximateMaxTrancheTokenPayout),
"InvestmentManager/transfer-not-allowed"
);
gateway.collectInvest(
_liquidityPool.poolId(),
_liquidityPool.trancheId(),
user,
poolManager.currencyAddressToId(_liquidityPool.asset())
);
}
function collectRedeem(address liquidityPool, address user) public auth {
LiquidityPoolLike _liquidityPool = LiquidityPoolLike(msg.sender);
gateway.collectRedeem(
_liquidityPool.poolId(),
_liquidityPool.trancheId(),
user,
poolManager.currencyAddressToId(_liquidityPool.asset())
);
}
// --- Incoming message handling ---
function updateTrancheTokenPrice(uint64 poolId, bytes16 trancheId, uint128 currencyId, uint128 price)
public
onlyGateway
{
address currency = poolManager.currencyIdToAddress(currencyId);
address liquidityPool = poolManager.getLiquidityPool(poolId, trancheId, currency);
require(liquidityPool != address(0), "InvestmentManager/tranche-does-not-exist");
LiquidityPoolLike(liquidityPool).updatePrice(price);
}
function handleExecutedCollectInvest(
uint64 poolId,
bytes16 trancheId,
address recipient,
uint128 currency,
uint128 currencyPayout,
uint128 trancheTokensPayout,
uint128 remainingInvestOrder
) public onlyGateway {
require(currencyPayout != 0, "InvestmentManager/zero-invest");
address _currency = poolManager.currencyIdToAddress(currency);
address liquidityPool = poolManager.getLiquidityPool(poolId, trancheId, _currency);
require(liquidityPool != address(0), "InvestmentManager/tranche-does-not-exist");
LPValues storage lpValues = orderbook[recipient][liquidityPool];
lpValues.maxDeposit = lpValues.maxDeposit + currencyPayout;
lpValues.maxMint = lpValues.maxMint + trancheTokensPayout;
lpValues.remainingInvestOrder = remainingInvestOrder;
LiquidityPoolLike(liquidityPool).mint(address(escrow), trancheTokensPayout); // mint to escrow. Recipient can claim by calling withdraw / redeem
_updateLiquidityPoolPrice(liquidityPool, currencyPayout, trancheTokensPayout);
emit ExecutedCollectInvest(poolId, trancheId, recipient, currency, currencyPayout, trancheTokensPayout);
}
function handleExecutedCollectRedeem(
uint64 poolId,
bytes16 trancheId,
address recipient,
uint128 currency,
uint128 currencyPayout,
uint128 trancheTokensPayout,
uint128 remainingRedeemOrder
) public onlyGateway {
require(trancheTokensPayout != 0, "InvestmentManager/zero-redeem");
address _currency = poolManager.currencyIdToAddress(currency);
address liquidityPool = poolManager.getLiquidityPool(poolId, trancheId, _currency);
require(liquidityPool != address(0), "InvestmentManager/tranche-does-not-exist");
LPValues storage lpValues = orderbook[recipient][liquidityPool];
lpValues.maxWithdraw = lpValues.maxWithdraw + currencyPayout;
lpValues.maxRedeem = lpValues.maxRedeem + trancheTokensPayout;
lpValues.remainingRedeemOrder = remainingRedeemOrder;
userEscrow.transferIn(_currency, address(escrow), recipient, currencyPayout);
LiquidityPoolLike(liquidityPool).burn(address(escrow), trancheTokensPayout); // burned redeemed tokens from escrow
_updateLiquidityPoolPrice(liquidityPool, currencyPayout, trancheTokensPayout);
emit ExecutedCollectRedeem(poolId, trancheId, recipient, currency, currencyPayout, trancheTokensPayout);
}
function handleExecutedDecreaseInvestOrder(
uint64 poolId,
bytes16 trancheId,
address user,
uint128 currency,
uint128 currencyPayout,
uint128 remainingInvestOrder
) public onlyGateway {
require(currencyPayout != 0, "InvestmentManager/zero-payout");
address _currency = poolManager.currencyIdToAddress(currency);
address liquidityPool = poolManager.getLiquidityPool(poolId, trancheId, _currency);
require(liquidityPool != address(0), "InvestmentManager/tranche-does-not-exist");
require(_currency == LiquidityPoolLike(liquidityPool).asset(), "InvestmentManager/not-tranche-currency");
// Transfer currency amount to userEscrow
userEscrow.transferIn(_currency, address(escrow), user, currencyPayout);
LPValues storage lpValues = orderbook[user][liquidityPool];
lpValues.remainingInvestOrder = remainingInvestOrder;
// Increasing maxRedeem and maxWithdraw with the currencyPayout,
// leads to an effective redeem price of 1.0 and thus the user actually receiving
// exactly currencyPayout on both redeem() and withdraw()
lpValues.maxRedeem = lpValues.maxRedeem + currencyPayout;
lpValues.maxWithdraw = lpValues.maxWithdraw + currencyPayout;
emit ExecutedDecreaseInvestOrder(poolId, trancheId, user, currency, currencyPayout);
}
/// @dev Compared to handleExecutedDecreaseInvestOrder, there is no
/// transfer of currency in this function because they
/// can stay in the Escrow, ready to be claimed on deposit/mint.
function handleExecutedDecreaseRedeemOrder(
uint64 poolId,
bytes16 trancheId,
address user,
uint128 currency,
uint128 trancheTokenPayout,
uint128 remainingRedeemOrder
) public onlyGateway {
require(trancheTokenPayout != 0, "InvestmentManager/zero-payout");
address _currency = poolManager.currencyIdToAddress(currency);
address liquidityPool = poolManager.getLiquidityPool(poolId, trancheId, _currency);
require(address(liquidityPool) != address(0), "InvestmentManager/tranche-does-not-exist");
LPValues storage lpValues = orderbook[user][liquidityPool];
lpValues.remainingRedeemOrder = remainingRedeemOrder;
// Increasing maxMint and maxDeposit with the trancheTokensPayout
// leads to an effective redeem price of 1.0 and thus the user actually receiving
// exactly trancheTokensPayout on both deposit() and mint()
lpValues.maxDeposit = lpValues.maxDeposit + trancheTokenPayout;
lpValues.maxMint = lpValues.maxMint + trancheTokenPayout;
emit ExecutedDecreaseRedeemOrder(poolId, trancheId, user, currency, trancheTokenPayout);
}
// --- View functions ---
function totalAssets(address liquidityPool, uint256 totalSupply) public view returns (uint256 _totalAssets) {
_totalAssets = convertToAssets(liquidityPool, totalSupply);
}
/// @dev Calculates the amount of shares / tranche tokens that any user would get for the amount of currency / assets provided.
/// The calculation is based on the tranche token price from the most recent epoch retrieved from Centrifuge.
function convertToShares(address liquidityPool, uint256 _assets) public view auth returns (uint256 shares) {
uint128 latestPrice = LiquidityPoolLike(liquidityPool).latestPrice();
if (latestPrice == 0) {
// If the price is not set, we assume it is 1.00
latestPrice = uint128(1 * 10 ** PRICE_DECIMALS);
}
(uint8 currencyDecimals, uint8 trancheTokenDecimals) = _getPoolDecimals(liquidityPool);
uint128 assets = _toUint128(_assets);
shares = assets.mulDiv(
10 ** (PRICE_DECIMALS + trancheTokenDecimals - currencyDecimals), latestPrice, MathLib.Rounding.Down
);
}
/// @dev Calculates the asset value for an amount of shares / tranche tokens provided.
/// The calculation is based on the tranche token price from the most recent epoch retrieved from Centrifuge.
function convertToAssets(address liquidityPool, uint256 _shares) public view auth returns (uint256 assets) {
uint128 latestPrice = LiquidityPoolLike(liquidityPool).latestPrice();
if (latestPrice == 0) {
// If the price is not set, we assume it is 1.00
latestPrice = uint128(1 * 10 ** PRICE_DECIMALS);
}
(uint8 currencyDecimals, uint8 trancheTokenDecimals) = _getPoolDecimals(liquidityPool);
uint128 shares = _toUint128(_shares);
assets = shares.mulDiv(
latestPrice, 10 ** (PRICE_DECIMALS + trancheTokenDecimals - currencyDecimals), MathLib.Rounding.Down
);
}
/// @return currencyAmount is type of uint256 to support the EIP4626 Liquidity Pool interface
function maxDeposit(address liquidityPool, address user) public view returns (uint256 currencyAmount) {
currencyAmount = uint256(orderbook[user][liquidityPool].maxDeposit);
}
/// @return trancheTokenAmount type of uint256 to support the EIP4626 Liquidity Pool interface
function maxMint(address liquidityPool, address user) public view returns (uint256 trancheTokenAmount) {
trancheTokenAmount = uint256(orderbook[user][liquidityPool].maxMint);
}
/// @return currencyAmount type of uint256 to support the EIP4626 Liquidity Pool interface
function maxWithdraw(address liquidityPool, address user) public view returns (uint256 currencyAmount) {
currencyAmount = uint256(orderbook[user][liquidityPool].maxWithdraw);
}
/// @return trancheTokenAmount type of uint256 to support the EIP4626 Liquidity Pool interface
function maxRedeem(address liquidityPool, address user) public view returns (uint256 trancheTokenAmount) {
trancheTokenAmount = uint256(orderbook[user][liquidityPool].maxRedeem);
}
/// @return trancheTokenAmount is type of uint256 to support the EIP4626 Liquidity Pool interface
function previewDeposit(address liquidityPool, address user, uint256 _currencyAmount)
public
view
returns (uint256 trancheTokenAmount)
{
uint128 currencyAmount = _toUint128(_currencyAmount);
uint256 depositPrice = calculateDepositPrice(user, liquidityPool);
if (depositPrice == 0) return 0;
trancheTokenAmount = uint256(_calculateTrancheTokenAmount(currencyAmount, liquidityPool, depositPrice));
}
/// @return currencyAmount is type of uint256 to support the EIP4626 Liquidity Pool interface
function previewMint(address liquidityPool, address user, uint256 _trancheTokenAmount)
public
view
returns (uint256 currencyAmount)
{
uint128 trancheTokenAmount = _toUint128(_trancheTokenAmount);
uint256 depositPrice = calculateDepositPrice(user, liquidityPool);
if (depositPrice == 0) return 0;
currencyAmount = uint256(_calculateCurrencyAmount(trancheTokenAmount, liquidityPool, depositPrice));
}
/// @return trancheTokenAmount is type of uint256 to support the EIP4626 Liquidity Pool interface
function previewWithdraw(address liquidityPool, address user, uint256 _currencyAmount)
public
view
returns (uint256 trancheTokenAmount)
{
uint128 currencyAmount = _toUint128(_currencyAmount);
uint256 redeemPrice = calculateRedeemPrice(user, liquidityPool);
if (redeemPrice == 0) return 0;
trancheTokenAmount = uint256(_calculateTrancheTokenAmount(currencyAmount, liquidityPool, redeemPrice));
}
/// @return currencyAmount is type of uint256 to support the EIP4626 Liquidity Pool interface
function previewRedeem(address liquidityPool, address user, uint256 _trancheTokenAmount)
public
view
returns (uint256 currencyAmount)
{
uint128 trancheTokenAmount = _toUint128(_trancheTokenAmount);
uint256 redeemPrice = calculateRedeemPrice(user, liquidityPool);
if (redeemPrice == 0) return 0;
currencyAmount = uint256(_calculateCurrencyAmount(trancheTokenAmount, liquidityPool, redeemPrice));
}
function userDepositRequest(address liquidityPool, address user) public view returns (uint256 currencyAmount) {
currencyAmount = uint256(orderbook[user][liquidityPool].remainingInvestOrder);
}
function userRedeemRequest(address liquidityPool, address user) public view returns (uint256 trancheTokenAmount) {
trancheTokenAmount = uint256(orderbook[user][liquidityPool].remainingRedeemOrder);
}
// --- Liquidity Pool processing functions ---
/// @notice Processes owner's currency deposit / investment after the epoch has been executed on Centrifuge.
/// In case owner's invest order was fulfilled (partially or in full) on Centrifuge during epoch execution MaxDeposit and MaxMint are increased and tranche tokens can be transferred to user's wallet on calling processDeposit.
/// Note: The currency required to fulfill the invest order is already locked in escrow upon calling requestDeposit.
/// @dev trancheTokenAmount return value is type of uint256 to be compliant with EIP4626 LiquidityPool interface
/// @return trancheTokenAmount the amount of tranche tokens transferred to the user's wallet after successful deposit.
function processDeposit(address liquidityPool, uint256 currencyAmount, address receiver, address owner)
public
auth
returns (uint256 trancheTokenAmount)
{
uint128 _currencyAmount = _toUint128(currencyAmount);
require(
(_currencyAmount <= orderbook[owner][liquidityPool].maxDeposit && _currencyAmount != 0),
"InvestmentManager/amount-exceeds-deposit-limits"
);
uint256 depositPrice = calculateDepositPrice(owner, liquidityPool);
require(depositPrice != 0, "LiquidityPool/deposit-token-price-0");
uint128 _trancheTokenAmount = _calculateTrancheTokenAmount(_currencyAmount, liquidityPool, depositPrice);
_deposit(_trancheTokenAmount, _currencyAmount, liquidityPool, receiver, owner);
trancheTokenAmount = uint256(_trancheTokenAmount);
}
/// @notice Processes owner's currency deposit / investment after the epoch has been executed on Centrifuge.
/// In case owner's invest order was fulfilled on Centrifuge during epoch execution MaxDeposit and MaxMint are increased
/// and trancheTokens can be transferred to owner's wallet on calling processDeposit or processMint.
/// Note: The currency amount required to fulfill the invest order is already locked in escrow upon calling requestDeposit.
/// Note: The tranche tokens are already minted on collectInvest and are deposited to the escrow account until the owner calls mint, or deposit.
/// Note: The tranche tokens are transferred to the receivers wallet.
/// @dev currencyAmount return value is type of uint256 to be compliant with EIP4626 LiquidityPool interface
/// @return currencyAmount the amount of liquidityPool assets invested and locked in escrow in order
/// for the amount of tranche tokens received after successful investment into the pool.
function processMint(address liquidityPool, uint256 trancheTokenAmount, address receiver, address owner)
public
auth
returns (uint256 currencyAmount)
{
uint128 _trancheTokenAmount = _toUint128(trancheTokenAmount);
require(
(_trancheTokenAmount <= orderbook[owner][liquidityPool].maxMint && _trancheTokenAmount != 0),
"InvestmentManager/amount-exceeds-mint-limits"
);
uint256 depositPrice = calculateDepositPrice(owner, liquidityPool);
require(depositPrice != 0, "LiquidityPool/deposit-token-price-0");
uint128 _currencyAmount = _calculateCurrencyAmount(_trancheTokenAmount, liquidityPool, depositPrice);
_deposit(_trancheTokenAmount, _currencyAmount, liquidityPool, receiver, owner);
currencyAmount = uint256(_currencyAmount);
}
function _deposit(
uint128 trancheTokenAmount,
uint128 currencyAmount,
address liquidityPool,
address receiver,
address owner
) internal {
LiquidityPoolLike lPool = LiquidityPoolLike(liquidityPool);
// Decrease the deposit limits
LPValues storage lpValues = orderbook[owner][liquidityPool];
lpValues.maxDeposit = lpValues.maxDeposit < currencyAmount ? 0 : lpValues.maxDeposit - currencyAmount;
lpValues.maxMint = lpValues.maxMint < trancheTokenAmount ? 0 : lpValues.maxMint - trancheTokenAmount;
// Transfer the tranche tokens to the user
require(
lPool.transferFrom(address(escrow), receiver, trancheTokenAmount),
"InvestmentManager/tranche-tokens-transfer-failed"
);
emit ProcessDeposit(liquidityPool, owner, currencyAmount, trancheTokenAmount);
}
/// @dev Processes owner's tranche Token redemption after the epoch has been executed on Centrifuge.
/// In case owner's redemption order was fulfilled on Centrifuge during epoch execution MaxRedeem and MaxWithdraw
/// are increased and LiquidityPool currency can be transferred to owner's wallet on calling processRedeem or processWithdraw.
/// Note: The trancheTokenAmount required to fulfill the redemption order was already locked in escrow
/// upon calling requestRedeem and burned upon collectRedeem.
/// @notice currencyAmount return value is type of uint256 to be compliant with EIP4626 LiquidityPool interface
/// @return currencyAmount the amount of liquidityPool assets received for the amount of redeemed/burned tranche tokens.
function processRedeem(address liquidityPool, uint256 trancheTokenAmount, address receiver, address owner)
public
auth
returns (uint256 currencyAmount)
{
uint128 _trancheTokenAmount = _toUint128(trancheTokenAmount);
require(
_trancheTokenAmount <= orderbook[owner][liquidityPool].maxRedeem && _trancheTokenAmount != 0,
"InvestmentManager/amount-exceeds-redeem-limits"
);
uint256 redeemPrice = calculateRedeemPrice(owner, liquidityPool);
require(redeemPrice != 0, "LiquidityPool/redeem-token-price-0");
uint128 _currencyAmount = _calculateCurrencyAmount(_trancheTokenAmount, liquidityPool, redeemPrice);
_redeem(_trancheTokenAmount, _currencyAmount, liquidityPool, receiver, owner);
currencyAmount = uint256(_currencyAmount);
}
/// @dev Processes owner's tranche token redemption after the epoch has been executed on Centrifuge.
/// In case owner's redemption order was fulfilled on Centrifuge during epoch execution MaxRedeem and MaxWithdraw
/// are increased and LiquidityPool currency can be transferred to owner's wallet on calling processRedeem or processWithdraw.
/// Note: The trancheTokenAmount required to fulfill the redemption order was already locked in escrow upon calling requestRedeem and burned upon collectRedeem.
/// @notice trancheTokenAmount return value is type of uint256 to be compliant with EIP4626 LiquidityPool interface
/// @return trancheTokenAmount the amount of trancheTokens redeemed/burned required to receive the currencyAmount payout/withdrawal.
function processWithdraw(address liquidityPool, uint256 currencyAmount, address receiver, address owner)
public
auth
returns (uint256 trancheTokenAmount)
{
uint128 _currencyAmount = _toUint128(currencyAmount);
require(
(_currencyAmount <= orderbook[owner][liquidityPool].maxWithdraw && _currencyAmount != 0),
"InvestmentManager/amount-exceeds-withdraw-limits"
);
uint256 redeemPrice = calculateRedeemPrice(owner, liquidityPool);
require(redeemPrice != 0, "LiquidityPool/redeem-token-price-0");
uint128 _trancheTokenAmount = _calculateTrancheTokenAmount(_currencyAmount, liquidityPool, redeemPrice);
_redeem(_trancheTokenAmount, _currencyAmount, liquidityPool, receiver, owner);
trancheTokenAmount = uint256(_trancheTokenAmount);
}
function _redeem(
uint128 trancheTokenAmount,
uint128 currencyAmount,
address liquidityPool,
address receiver,
address owner
) internal {
LiquidityPoolLike lPool = LiquidityPoolLike(liquidityPool);
// Decrease the redemption limits
LPValues storage lpValues = orderbook[owner][liquidityPool];
lpValues.maxWithdraw = lpValues.maxWithdraw < currencyAmount ? 0 : lpValues.maxWithdraw - currencyAmount;
lpValues.maxRedeem = lpValues.maxRedeem < trancheTokenAmount ? 0 : lpValues.maxRedeem - trancheTokenAmount;
// Transfer the currency to the user
userEscrow.transferOut(lPool.asset(), owner, receiver, currencyAmount);
emit ProcessRedeem(liquidityPool, owner, currencyAmount, trancheTokenAmount);
}
// --- Helpers ---
function calculateDepositPrice(address user, address liquidityPool) public view returns (uint256 depositPrice) {
LPValues storage lpValues = orderbook[user][liquidityPool];
if (lpValues.maxMint == 0) {
return 0;
}
depositPrice = _calculatePrice(lpValues.maxDeposit, lpValues.maxMint, liquidityPool);
}
function calculateRedeemPrice(address user, address liquidityPool) public view returns (uint256 redeemPrice) {
LPValues storage lpValues = orderbook[user][liquidityPool];
if (lpValues.maxRedeem == 0) {
return 0;
}
redeemPrice = _calculatePrice(lpValues.maxWithdraw, lpValues.maxRedeem, liquidityPool);
}
function _calculatePrice(uint128 currencyAmount, uint128 trancheTokenAmount, address liquidityPool)
public
view
returns (uint256 depositPrice)
{
(uint8 currencyDecimals, uint8 trancheTokenDecimals) = _getPoolDecimals(liquidityPool);
uint256 currencyAmountInPriceDecimals = _toPriceDecimals(currencyAmount, currencyDecimals);
uint256 trancheTokenAmountInPriceDecimals = _toPriceDecimals(trancheTokenAmount, trancheTokenDecimals);
depositPrice = currencyAmountInPriceDecimals.mulDiv(
10 ** PRICE_DECIMALS, trancheTokenAmountInPriceDecimals, MathLib.Rounding.Down
);
}
function _updateLiquidityPoolPrice(address liquidityPool, uint128 currencyPayout, uint128 trancheTokensPayout)
internal
{
uint128 price = _toUint128(_calculatePrice(currencyPayout, trancheTokensPayout, liquidityPool));
LiquidityPoolLike(liquidityPool).updatePrice(price);
}
function _calculateTrancheTokenAmount(uint128 currencyAmount, address liquidityPool, uint256 price)
internal
view
returns (uint128 trancheTokenAmount)
{
(uint8 currencyDecimals, uint8 trancheTokenDecimals) = _getPoolDecimals(liquidityPool);
uint256 currencyAmountInPriceDecimals = _toPriceDecimals(currencyAmount, currencyDecimals).mulDiv(
10 ** PRICE_DECIMALS, price, MathLib.Rounding.Down
);
trancheTokenAmount = _fromPriceDecimals(currencyAmountInPriceDecimals, trancheTokenDecimals);
}
function _calculateCurrencyAmount(uint128 trancheTokenAmount, address liquidityPool, uint256 price)
internal
view
returns (uint128 currencyAmount)
{
(uint8 currencyDecimals, uint8 trancheTokenDecimals) = _getPoolDecimals(liquidityPool);
uint256 currencyAmountInPriceDecimals = _toPriceDecimals(trancheTokenAmount, trancheTokenDecimals).mulDiv(
price, 10 ** PRICE_DECIMALS, MathLib.Rounding.Down
);
currencyAmount = _fromPriceDecimals(currencyAmountInPriceDecimals, currencyDecimals);
}
/// @dev Safe type conversion from uint256 to uint128. Revert if value is too big to be stored with uint128. Avoid data loss.
/// @return value - safely converted without data loss
function _toUint128(uint256 _value) internal pure returns (uint128 value) {
if (_value > type(uint128).max) {
revert("InvestmentManager/uint128-overflow");
} else {
value = uint128(_value);
}
}
/// @dev When converting currency to tranche token amounts using the price,
/// all values are normalized to PRICE_DECIMALS
function _toPriceDecimals(uint128 _value, uint8 decimals) internal pure returns (uint256 value) {
if (PRICE_DECIMALS == decimals) return uint256(_value);
value = uint256(_value) * 10 ** (PRICE_DECIMALS - decimals);
}
/// @dev Convert decimals of the value from the price decimals back to the intended decimals
function _fromPriceDecimals(uint256 _value, uint8 decimals) internal pure returns (uint128 value) {
if (PRICE_DECIMALS == decimals) return _toUint128(_value);
value = _toUint128(_value / 10 ** (PRICE_DECIMALS - decimals));
}
/// @dev Return the currency decimals and the tranche token decimals for a given liquidityPool
function _getPoolDecimals(address liquidityPool)
internal
view
returns (uint8 currencyDecimals, uint8 trancheTokenDecimals)
{
currencyDecimals = ERC20Like(LiquidityPoolLike(liquidityPool).asset()).decimals();
trancheTokenDecimals = LiquidityPoolLike(liquidityPool).decimals();
}
}