forked from agglayer/vault-bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVaultBridgeToken.sol
More file actions
1152 lines (954 loc) · 50.6 KB
/
VaultBridgeToken.sol
File metadata and controls
1152 lines (954 loc) · 50.6 KB
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: LicenseRef-PolygonLabs-Open-Attribution OR LicenseRef-PolygonLabs-Source-Available
pragma solidity 0.8.29;
// @remind UPDATE DOCUMENTATION.
// Main functionality.
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {ERC20PermitUpgradeable} from
"@openzeppelin-contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol";
import {IVaultBridgeTokenInitializer} from "./etc/IVaultBridgeTokenInitializer.sol";
// Other functionality.
import {Initializable} from "@openzeppelin-contracts-upgradeable/proxy/utils/Initializable.sol";
import {AccessControlUpgradeable} from "@openzeppelin-contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin-contracts-upgradeable/utils/PausableUpgradeable.sol";
import {ReentrancyGuardTransientUpgradeable} from
"@openzeppelin-contracts-upgradeable/utils/ReentrancyGuardTransientUpgradeable.sol";
import {ERC20PermitUser} from "./etc/ERC20PermitUser.sol";
import {IVersioned} from "./etc/IVersioned.sol";
// Libraries.
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
// External contracts.
import {ILxLyBridge} from "./etc/ILxLyBridge.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// Other.
import {ERC20Upgradeable} from "@openzeppelin-contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/// @title Vault Bridge Token
/// @author See https://github.com/agglayer/vault-bridge
/// @notice A vbToken is an ERC-20 token, ERC-4626 vault, and LxLy Bridge extension, enabling deposits and bridging of select assets, such as WBTC, WETH, USDT, USDC, and USDS, while producing yield.
/// @dev A base contract used to create vault bridge tokens.
/// @dev @note IMPORTANT: In order to not drive the complexity of the Vault Bridge protocol up, vbToken MUST NOT have transfer, deposit, or withdrawal fees. The underlying token on Layer X MUST NOT have a transfer fee; the contract will revert if a transfer fee is detected. The underlying token and Custom Token on Layer Ys MAY have transfer fees. The yield vault SHOULD NOT have deposit and/or withdrawal fees, and the price of its shares MUST NOT decrease (e.g., the vault does not realize bad debt); still, this contract implements solvency checks for protection. Additionally, the underlying token MUST NOT be a rebasing token, and MUST NOT have transfer hooks (i.e., the token does not enable reentrancy/cross-entrancy).
/// @dev It is expected that generated yield will offset any costs incurred when depositing to and withdrawing from the yield vault for the purpose of generating yield or rebalancing the internal reserve.
abstract contract VaultBridgeToken is
Initializable,
AccessControlUpgradeable,
PausableUpgradeable,
ReentrancyGuardTransientUpgradeable,
IERC4626,
ERC20PermitUpgradeable,
ERC20PermitUser,
IVersioned
{
// Libraries.
using SafeERC20 for IERC20;
/// @dev Storage of Vault Bridge Token contract.
/// @dev It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions when using with upgradeable contracts.
/// @custom:storage-location erc7201:agglayer.vault-bridge.VaultBridgeToken.storage
struct VaultBridgeTokenStorage {
IERC20 underlyingToken;
uint8 decimals;
uint256 minimumReservePercentage;
uint256 reservedAssets;
IERC4626 yieldVault;
address yieldRecipient;
uint256 _netCollectedYield;
uint32 lxlyId;
ILxLyBridge lxlyBridge;
uint256 migrationFeesFund;
uint256 minimumYieldVaultDeposit;
address migrationManager;
uint256 yieldVaultMaximumSlippagePercentage;
address _vaultBridgeTokenPart2;
}
/// @remind Document.
/// @dev Used for initializing the contract.
/// @dev @note (ATTENTION) `decimals` will match the underlying token. Defaults to 18 decimals if the underlying token reverts.
/// @param minimumReservePercentage_ 1e18 is 100%.
/// @param yieldVault_ An external, ERC-4246 compatible vault into which the underlying token is deposited to generate yield.
/// @param yieldRecipient_ The address that receives yield generated by the yield vault. The yield collector collects generated yield, while the yield recipient receives it.
/// @param minimumYieldVaultDeposit_ @remind Document.
/// @param transferFeeCalculator_ @remind Redocument. A dedicated fee calculator for covering the underlying token's transfer fees if the underlying token has a transfer fee. If the underlying token does not have a transfer fee, set to address(0).
struct InitializationParameters {
address owner;
string name;
string symbol;
address underlyingToken;
uint256 minimumReservePercentage;
address yieldVault;
address yieldRecipient;
address lxlyBridge;
uint256 minimumYieldVaultDeposit;
address migrationManager;
uint256 yieldVaultMaximumSlippagePercentage;
address vaultBridgeTokenPart2;
}
// Basic roles.
bytes32 public constant REBALANCER_ROLE = keccak256("REBALANCER_ROLE");
bytes32 public constant YIELD_COLLECTOR_ROLE = keccak256("YIELD_COLLECTOR_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/// @dev The storage slot at which Vault Bridge Token storage starts, following the EIP-7201 standard.
/// @dev Calculated as `keccak256(abi.encode(uint256(keccak256("agglayer.vault-bridge.VaultBridgeToken.storage")) - 1)) & ~bytes32(uint256(0xff))`.
bytes32 private constant _VAULT_BRIDGE_TOKEN_STORAGE =
hex"f082fbc4cfb4d172ba00d34227e208a31ceb0982bc189440d519185302e44700";
// Errors.
error Unauthorized();
error InvalidInitializer();
error InvalidOwner();
error InvalidName();
error InvalidSymbol();
error InvalidUnderlyingToken();
error InvalidMinimumReservePercentage();
error InvalidYieldVault();
error InvalidYieldRecipient();
error InvalidLxLyBridge();
error InvalidMigrationManager();
error InvalidYieldVaultMaximumSlippagePercentage();
error InvalidVaultBridgeTokenPart2();
error InvalidAssets();
error InvalidDestinationNetworkId();
error InvalidReceiver();
error InvalidPermitData();
error InvalidShares();
error IncorrectAmountOfSharesMinted(uint256 mintedShares, uint256 requiredShares);
error AssetsTooLarge(uint256 availableAssets, uint256 requestedAssets);
error IncorrectAmountOfSharesRedeemed(uint256 redeemedShares, uint256 requiredShares);
error CannotRebalanceReserve();
error NoNeedToRebalanceReserve();
error NoYield();
error InvalidOriginNetwork();
error CannotCompleteMigration(uint256 requiredAssets, uint256 receivedAssets, uint256 assetsInMigrationFund);
error YieldVaultRedemptionFailed(uint256 sharesToRedeem, uint256 redemptionLimit);
error MinimumYieldVaultDepositNotMet(uint256 assetsToDeposit, uint256 minimumYieldVaultDeposit);
error YieldVaultDepositFailed(uint256 assetsToDeposit, uint256 depositLimit);
error InsufficientYieldVaultSharesMinted(uint256 depositedAssets, uint256 mintedShares);
error UnknownError(bytes data);
error YieldVaultWithdrawalFailed(uint256 assetsToWithdraw, uint256 withdrawalLimit);
error ExcessiveYieldVaultSharesBurned(uint256 burnedShares, uint256 withdrawnAssets);
error InsufficientUnderlyingTokenReceived(uint256 receivedAssets, uint256 requestedAssets);
error UnknownFunction(bytes4 functionSelector);
// Events.
event ReserveRebalanced(uint256 oldReservedAssets, uint256 newReservedAssets, uint256 reservePercentage);
event YieldCollected(address indexed yieldRecipient, uint256 vbTokenAmount);
event Burned(uint256 vbTokenAmount);
event DonatedAsYield(address indexed who, uint256 assets);
event DonatedForCompletingMigration(address indexed who, uint256 assets);
event MigrationCompleted(
uint32 indexed originNetwork,
uint256 indexed shares,
uint256 indexed assets,
uint256 migrationFeesFundUtilization
);
event YieldRecipientSet(address indexed yieldRecipient);
event TransferFeeCalculatorSet(address transferFeeCalculator);
event MinimumReservePercentageSet(uint256 minimumReservePercentage);
event YieldVaultDrained(uint256 redeemedShares, uint256 receivedAssets);
event YieldVaultSet(address yieldVault);
event YieldVaultMaximumSlippagePercentageSet(uint256 slippagePercentage);
// -----================= ::: MODIFIERS ::: =================-----
/// @dev Checks if the sender is the yield recipient.
modifier onlyYieldRecipient() {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
require(msg.sender == $.yieldRecipient, Unauthorized());
_;
}
/// @dev Checks if the sender is LxLy Bridge.
modifier onlyLxLyBridge() {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
require(msg.sender == address($.lxlyBridge), Unauthorized());
_;
}
/// @dev Checks if the sender is Migration Manager.
modifier onlyMigrationManager() {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
require(msg.sender == $.migrationManager, Unauthorized());
_;
}
/// @dev Checks if the sender is the vbToken itself.
modifier onlySelf() {
require(msg.sender == address(this), Unauthorized());
_;
}
// -----================= ::: SETUP ::: =================-----
// @remind Document.
/// @param initParams Please refer to `InitializationParameters` for more information.
function __VaultBridgeToken_init(address initializer_, InitializationParameters calldata initParams)
internal
onlyInitializing
{
// Check the input.
require(initializer_ != address(0), InvalidInitializer());
// Initialize the contract using the external initializer.
(bool ok, bytes memory data) =
initializer_.delegatecall(abi.encodeCall(IVaultBridgeTokenInitializer.initialize, (initParams)));
if (!ok) {
assembly ("memory-safe") {
revert(add(32, data), mload(data))
}
}
}
// -----================= ::: SOLIDITY ::: =================-----
// @remind Document.
receive() external payable {}
// @remind Document (the entire function).
fallback() external payable virtual {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
address vaultBridgeTokenPart2 = $._vaultBridgeTokenPart2;
assembly {
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), vaultBridgeTokenPart2, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch success
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
// -----================= ::: STORAGE ::: =================-----
/// @notice The underlying token that backs vbToken.
function underlyingToken() public view returns (IERC20) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.underlyingToken;
}
/// @notice The number of decimals of the vault bridge token.
/// @notice The number of decimals is the same as that of the underlying token, or 18 if the underlying token reverted (e.g., does not implement `decimals`).
function decimals() public view override(ERC20Upgradeable, IERC20Metadata) returns (uint8) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.decimals;
}
/// @notice Vault bridge tokens have an internal reserve of the underlying token from which withdrawals are served first.
/// @notice The owner can rebalance the reserve by calling `rebalanceReserve` when it is below or above the `minimumReservePercentage`.
/// @return 1e18 is 100%.
function minimumReservePercentage() public view returns (uint256) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.minimumReservePercentage;
}
/// @notice Vault bridge tokens have an internal reserve of the underlying token from which withdrawals are served first.
/// @notice The owner can rebalance the reserve by calling `rebalanceReserve` when it is below or above the `minimumReservePercentage`.
function reservedAssets() public view returns (uint256) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.reservedAssets;
}
/// @notice An external, ERC-4246 compatible vault into which the underlying token is deposited to generate yield.
function yieldVault() public view returns (IERC4626) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.yieldVault;
}
/// @notice The address that receives yield generated by the yield vault.
/// @notice The owner collects generated yield, while the yield recipient receives it.
function yieldRecipient() public view returns (address) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.yieldRecipient;
}
/// @notice The LxLy ID of this network.
function lxlyId() public view returns (uint32) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.lxlyId;
}
/// @notice LxLy Bridge, which connects AggLayer networks.
function lxlyBridge() public view returns (ILxLyBridge) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.lxlyBridge;
}
/// @notice A dedicated fund for covering the underlying token's transfer fees during a migration from a Layer Y. Please refer to `_completeMigration` for more information.
function migrationFeesFund() public view returns (uint256) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.migrationFeesFund;
}
/// @notice The minimum deposit amount for triggering a yield vault deposit.
/// @notice Amounts below this value will be reserved regardless of the reserve percentage, in order to save gas for the user.
/// @notice The limit does not apply when rebalancing the reserve.
function minimumYieldVaultDeposit() public view returns (uint256) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.minimumYieldVaultDeposit;
}
// @remind Document.
function migrationManager() public view returns (address) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.migrationManager;
}
// @remind Document.
function yieldVaultMaximumSlippagePercentage() public view returns (uint256) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.yieldVaultMaximumSlippagePercentage;
}
/// @dev Returns a pointer to the ERC-7201 storage namespace.
function _getVaultBridgeTokenStorage() internal pure returns (VaultBridgeTokenStorage storage $) {
assembly {
$.slot := _VAULT_BRIDGE_TOKEN_STORAGE
}
}
// -----================= ::: ERC-4626 ::: =================-----
/// @notice The underlying token that backs vbToken.
function asset() public view returns (address assetTokenAddress) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return address($.underlyingToken);
}
/// @notice The real-time total backing of vbToken in the underlying token.
function totalAssets() public view returns (uint256 totalManagedAssets) {
return stakedAssets() + reservedAssets();
}
/// @notice Tells how much a specific amount of underlying token is worth in vbToken.
/// @dev The underlying token backs vbToken 1:1.
function convertToShares(uint256 assets) public pure returns (uint256 shares) {
// @note CAUTION! Changing this function will affect the conversion rate for the entire contract, and may introduce bugs.
shares = assets;
}
/// @notice Tells how much a specific amount of vbToken is worth in the underlying token.
/// @dev vbToken is backed by the underlying token 1:1.
function convertToAssets(uint256 shares) public pure returns (uint256 assets) {
// @note CAUTION! Changing this function will affect the conversion rate for the entire contract, and may introduce bugs.
assets = shares;
}
/// @notice How much underlying token can deposited for a specific user right now. (Depositing the underlying token mints vbToken).
function maxDeposit(address) external view returns (uint256 maxAssets) {
return paused() ? 0 : type(uint256).max;
}
/// @notice How much vbToken would be minted if a specific amount of the underlying token were deposited right now.
function previewDeposit(uint256 assets) external view whenNotPaused returns (uint256 shares) {
// Check the input.
require(assets > 0, InvalidAssets());
return convertToShares(assets);
}
/// @notice Deposit a specific amount of the underlying token and mint vbToken.
function deposit(uint256 assets, address receiver) external whenNotPaused nonReentrant returns (uint256 shares) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
(shares,) = _deposit(assets, $.lxlyId, receiver, false, 0);
}
/// @notice Deposit a specific amount of the underlying token, and bridge minted vbToken to another network.
/// @dev If vbToken is custom mapped on LxLy Bridge on the other network, the user will receive Custom Token. Otherwise, they will receive wrapped vbToken.
/// @dev The `receiver` in the ERC-4626 `Deposit` event will be this contract.
function depositAndBridge(
uint256 assets,
address receiver,
uint32 destinationNetworkId,
bool forceUpdateGlobalExitRoot
) external whenNotPaused nonReentrant returns (uint256 shares) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
// Check the input.
require(destinationNetworkId != $.lxlyId, InvalidDestinationNetworkId());
(shares,) = _deposit(assets, destinationNetworkId, receiver, forceUpdateGlobalExitRoot, 0);
}
// @remind Document (the entire function).
function _deposit(
uint256 assets,
uint32 destinationNetworkId,
address receiver,
bool forceUpdateGlobalExitRoot,
uint256 maxShares
) internal returns (uint256 shares, uint256 spentAssets) {
return _depositUsingCustomReceivingFunction(
_receiveUnderlyingToken, assets, destinationNetworkId, receiver, forceUpdateGlobalExitRoot, maxShares
);
}
/// @notice Locks the underlying token, mints vbToken, and optionally bridges it to another network.
/// @param maxShares Caps the amount of vbToken that is minted. Unused underlying token will be refunded to the sender. Set to `0` to disable.
/// @param receiveUnderlyingToken @remind Document.
/// @dev If bridging to another network, the `receiver` in the ERC-4626 `Deposit` event will be this contract.
function _depositUsingCustomReceivingFunction(
function(address, uint256) internal receiveUnderlyingToken,
uint256 assets,
uint32 destinationNetworkId,
address receiver,
bool forceUpdateGlobalExitRoot,
uint256 maxShares
) internal returns (uint256 shares, uint256 spentAssets) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
// Check the inputs.
require(assets > 0, InvalidAssets());
require(receiver != address(0), InvalidReceiver());
require(receiver != address(this), InvalidReceiver());
// Transfer the underlying token from the sender to self.
receiveUnderlyingToken(msg.sender, assets);
// Check for a refund.
if (maxShares > 0) {
// Calculate the required amount of the underlying token.
uint256 requiredAssets = convertToAssets(maxShares);
if (assets > requiredAssets) {
// Calculate the difference.
uint256 refund = assets - requiredAssets;
// Refund the difference.
_sendUnderlyingToken(msg.sender, refund);
// Update the `assets`.
assets = requiredAssets;
}
}
// Set the return values.
shares = convertToShares(assets);
spentAssets = assets;
// Calculate the amount to reserve.
uint256 assetsToReserve = _calculateAmountToReserve(assets, shares);
// Calculate the amount to try to deposit into the yield vault.
uint256 assetsToDeposit = assets - assetsToReserve;
// Try to deposit into the yield vault.
if (assetsToDeposit > 0) {
// Deposit, and update the amount to reserve if necessary.
assetsToReserve += _depositIntoYieldVault(assetsToDeposit, false);
}
// Update the reserve.
$.reservedAssets += assetsToReserve;
// Mint vbToken.
if (destinationNetworkId != $.lxlyId) {
// Mint to self.
_mint(address(this), shares);
// Bridge to the receiver.
$.lxlyBridge.bridgeAsset(
destinationNetworkId, receiver, shares, address(this), forceUpdateGlobalExitRoot, ""
);
// Update the receiver.
receiver = address(this);
} else {
// Mint to the receiver.
_mint(receiver, shares);
}
// Emit the ERC-4626 event.
emit IERC4626.Deposit(msg.sender, receiver, assets, shares);
// @remind Document.
uint256 reservePercentage_ = reservePercentage();
// @remind Document.
if (
$.minimumReservePercentage < 1e18 && reservePercentage_ > 3 * $.minimumReservePercentage
&& reservePercentage_ > 0.1e18
) {
_rebalanceReserve(false, true);
}
}
/// @notice Deposit a specific amount of the underlying token and mint vbToken.
/// @dev Uses EIP-2612 permit to transfer the underlying token from the sender to self.
function depositWithPermit(uint256 assets, address receiver, bytes calldata permitData)
external
whenNotPaused
nonReentrant
returns (uint256 shares)
{
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
(shares,) = _depositWithPermit(assets, permitData, $.lxlyId, receiver, false, 0);
}
/// @notice Deposit a specific amount of the underlying token, and bridge minted vbToken to another network.
/// @dev If vbToken is custom mapped on LxLy Bridge on the other network, the user will receive Custom Token. Otherwise, they will receive wrapped vbToken.
/// @dev Uses EIP-2612 permit to transfer the underlying token from the sender to self.
/// @dev The `receiver` in the ERC-4626 `Deposit` event will be this contract.
function depositWithPermitAndBridge(
uint256 assets,
address receiver,
uint32 destinationNetworkId,
bool forceUpdateGlobalExitRoot,
bytes calldata permitData
) external whenNotPaused nonReentrant returns (uint256 shares) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
// Check the input.
require(destinationNetworkId != $.lxlyId, InvalidDestinationNetworkId());
(shares,) = _depositWithPermit(assets, permitData, destinationNetworkId, receiver, forceUpdateGlobalExitRoot, 0);
}
/// @notice Locks the underlying token, mints vbToken, and optionally bridges it to another network.
/// @param maxShares Caps the amount of vbToken that is minted. Unused underlying token will be refunded to the sender. Set to `0` to disable.
/// @dev Uses EIP-2612 permit to transfer the underlying token from the sender to self.
function _depositWithPermit(
uint256 assets,
bytes calldata permitData,
uint32 destinationNetworkId,
address receiver,
bool forceUpdateGlobalExitRoot,
uint256 maxShares
) internal returns (uint256 shares, uint256 spentAssets) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
// Check the input.
require(permitData.length > 0, InvalidPermitData());
// Use the permit.
_permit(address($.underlyingToken), assets, permitData);
return _deposit(assets, destinationNetworkId, receiver, forceUpdateGlobalExitRoot, maxShares);
}
/// @notice How much vbToken can be minted to a specific user right now. (Minting vbToken locks the underlying token).
function maxMint(address) external view returns (uint256 maxShares) {
return paused() ? 0 : type(uint256).max;
}
/// @notice How much underlying token would be required to mint a specific amount of vbToken right now.
function previewMint(uint256 shares) external view whenNotPaused returns (uint256 assets) {
// Check the input.
require(shares > 0, InvalidShares());
return convertToAssets(shares);
}
/// @notice Mint a specific amount of vbToken by locking the required amount of the underlying token.
function mint(uint256 shares, address receiver) external whenNotPaused nonReentrant returns (uint256 assets) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
// Check the input.
require(shares > 0, InvalidShares());
// Mint vbToken to the receiver.
uint256 mintedShares;
(mintedShares, assets) = _deposit(convertToAssets(shares), $.lxlyId, receiver, false, shares);
// Check the output.
require(mintedShares == shares, IncorrectAmountOfSharesMinted(mintedShares, shares));
}
/// @notice How much underlying token can be withdrawn from a specific user right now. (Withdrawing the underlying token burns vbToken).
function maxWithdraw(address owner) external view returns (uint256 maxAssets) {
// Return zero if the contract is paused.
if (paused()) return 0;
// Return zero if the balance is zero.
uint256 shares = balanceOf(owner);
if (shares == 0) return 0;
// Return the maximum amount that can be withdrawn.
return _simulateWithdraw(convertToAssets(shares), false);
}
/// @notice How much vbToken would be burned if a specific amount of the underlying token were withdrawn right now.
function previewWithdraw(uint256 assets) external view whenNotPaused returns (uint256 shares) {
return convertToShares(_simulateWithdraw(assets, true));
}
/// @dev Calculates the amount of the underlying token that could be withdrawn right now.
/// @dev This function is used for estimation purposes only.
/// @dev @note IMPORTANT: `reservedAssets` must be up-to-date before using this function.
/// @param assets The maximum amount of the underlying token to simulate a withdrawal for.
/// @param force Whether to revert if the all of the `assets` would not be withdrawn.
function _simulateWithdraw(uint256 assets, bool force) internal view returns (uint256 withdrawnAssets) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
// Check the input.
require(assets > 0, InvalidAssets());
// The amount that cannot be withdrawn at the moment.
uint256 remainingAssets = assets;
// Simulate withdrawal from the reserve.
if ($.reservedAssets >= remainingAssets) return assets;
remainingAssets -= $.reservedAssets;
// Simulate withdrawal from the yield vault.
uint256 maxWithdraw_ = $.yieldVault.maxWithdraw(address(this));
maxWithdraw_ = remainingAssets > maxWithdraw_ ? maxWithdraw_ : remainingAssets;
uint256 burnedYieldVaultShares;
try $.yieldVault.previewWithdraw(maxWithdraw_) returns (uint256 shares) {
burnedYieldVaultShares = shares;
} catch (bytes memory data) {
if (force) {
assembly ("memory-safe") {
revert(add(32, data), mload(data))
}
} else {
return $.reservedAssets;
}
}
// @remind Document.
bool solvencyCheckPassed = Math.mulDiv(
convertToAssets(totalSupply() + yield()) - reservedAssets(), burnedYieldVaultShares, maxWithdraw_
) <= Math.mulDiv($.yieldVault.balanceOf(address(this)), 1e18 + $.yieldVaultMaximumSlippagePercentage, 1e18);
// @remind Document.
if (!solvencyCheckPassed) {
if (force) revert ExcessiveYieldVaultSharesBurned(burnedYieldVaultShares, maxWithdraw_);
return $.reservedAssets;
}
// @remind Document.
if (remainingAssets == maxWithdraw_) return assets;
remainingAssets -= maxWithdraw_;
// Set the return value (the amount of the underlying token that can be withdrawn right now).
withdrawnAssets = assets - remainingAssets;
// Revert if all of the `assets` must have been withdrawn and there is a remaining amount.
if (force) require(remainingAssets == 0, AssetsTooLarge(withdrawnAssets, assets));
}
/// @notice Withdraw a specific amount of the underlying token by burning the required amount of vbToken.
function withdraw(uint256 assets, address receiver, address owner)
external
whenNotPaused
nonReentrant
returns (uint256 shares)
{
return _withdraw(assets, receiver, owner);
}
/// @notice Withdraw a specific amount of the underlying token by burning the required amount of vbToken.
function _withdraw(uint256 assets, address receiver, address owner) internal returns (uint256 shares) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
// Check the inputs.
require(assets > 0, InvalidAssets());
require(receiver != address(0), InvalidReceiver());
require(owner != address(0), InvalidOwner());
// Cache the total supply, uncollected yield, and reserved assets.
uint256 originalTotalSupply = totalSupply();
uint256 originalUncollectedYield = yield();
uint256 originalReservedAssets = $.reservedAssets;
// Set the return value.
shares = convertToShares(assets);
// Check the input.
if (msg.sender != owner) _spendAllowance(owner, msg.sender, shares);
// The amount that cannot be withdrawn at the moment.
uint256 remainingAssets = assets;
// Calculate the amount to withdraw from the reserve.
uint256 amountToWithdraw = originalReservedAssets > remainingAssets ? remainingAssets : originalReservedAssets;
// Withdraw the underlying token from the reserve.
if (amountToWithdraw > 0) {
// Update the reserve.
$.reservedAssets -= amountToWithdraw;
// Update the remaining assets.
remainingAssets -= amountToWithdraw;
}
uint256 receivedAssets;
if (remainingAssets != 0) {
// Calculate the amount to withdraw from the yield vault.
uint256 maxWithdraw_ = $.yieldVault.maxWithdraw(address(this));
// Withdraw the underlying token from the yield vault.
if (maxWithdraw_ >= remainingAssets) {
// Withdraw to this contract.
(, receivedAssets) = _withdrawFromYieldVault(
remainingAssets,
true,
address(this),
originalTotalSupply,
originalUncollectedYield,
originalReservedAssets
);
} else {
// Update the remaining assets.
remainingAssets -= maxWithdraw_;
// Revert because all of the `assets` could not be withdrawn.
revert AssetsTooLarge(assets - remainingAssets, assets);
}
}
// Burn vbToken.
_burn(owner, shares);
// Send the underlying token to the receiver.
_sendUnderlyingToken(receiver, amountToWithdraw + receivedAssets);
// Emit the ERC-4626 event.
emit IERC4626.Withdraw(msg.sender, receiver, owner, assets, shares);
// @remind Document.
if ($.minimumReservePercentage < 1e18 && reservePercentage() <= 0.01e18 && $.minimumReservePercentage >= 0.1e18)
{
_rebalanceReserve(false, false);
}
}
/// @notice How much vbToken can be redeemed for a specific user. (Redeeming vbToken burns it and unlocks the underlying token).
function maxRedeem(address owner) external view returns (uint256 maxShares) {
// Return zero if the contract is paused.
if (paused()) return 0;
// Return zero if the balance is zero.
uint256 shares = balanceOf(owner);
if (shares == 0) return 0;
// Return the maximum amount that can be redeemed.
return convertToShares(_simulateWithdraw(convertToAssets(shares), false));
}
/// @notice How much underlying token would be unlocked if a specific amount of vbToken were redeemed and burned right now.
function previewRedeem(uint256 shares) external view whenNotPaused returns (uint256 assets) {
// Check the input.
require(shares > 0, InvalidShares());
return _simulateWithdraw(convertToAssets(shares), true);
}
/// @notice Burn a specific amount of vbToken and unlock the respective amount of the underlying token.
function redeem(uint256 shares, address receiver, address owner)
external
whenNotPaused
nonReentrant
returns (uint256 assets)
{
// Check the input.
require(shares > 0, InvalidShares());
// Set the return value.
assets = convertToAssets(shares);
// Burn vbToken and unlock the underlying token.
uint256 redeemedShares = _withdraw(assets, receiver, owner);
// Check the output.
require(redeemedShares == shares, IncorrectAmountOfSharesRedeemed(redeemedShares, shares));
}
/// @notice Claim vbToken from LxLy Bridge and redeem it.
function claimAndRedeem(
bytes32[32] calldata smtProofLocalExitRoot,
bytes32[32] calldata smtProofRollupExitRoot,
uint256 globalIndex,
bytes32 mainnetExitRoot,
bytes32 rollupExitRoot,
address destinationAddress,
uint256 amount,
address receiver,
bytes calldata metadata
) external whenNotPaused nonReentrant returns (uint256 assets) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
// Claim vbToken from LxLy Bridge.
$.lxlyBridge.claimAsset(
smtProofLocalExitRoot,
smtProofRollupExitRoot,
globalIndex,
mainnetExitRoot,
rollupExitRoot,
$.lxlyId,
address(this),
$.lxlyId,
destinationAddress,
amount,
metadata
);
// Set the return value.
assets = convertToAssets(amount);
// Burn vbToken and unlock the underlying token.
uint256 redeemedShares = _withdraw(assets, receiver, destinationAddress);
// Check the output.
require(redeemedShares == amount, IncorrectAmountOfSharesRedeemed(redeemedShares, amount));
}
// -----================= ::: ERC-20 ::: =================-----
/// @dev Pausable ERC-20 `transfer` function.
function transfer(address to, uint256 value)
public
virtual
override(ERC20Upgradeable, IERC20)
whenNotPaused
returns (bool)
{
return ERC20Upgradeable.transfer(to, value);
}
/// @dev Pausable ERC-20 `transferFrom` function.
function transferFrom(address from, address to, uint256 value)
public
virtual
override(ERC20Upgradeable, IERC20)
whenNotPaused
returns (bool)
{
return ERC20Upgradeable.transferFrom(from, to, value);
}
/// @dev Pausable ERC-20 `approve` function.
function approve(address spender, uint256 value)
public
virtual
override(ERC20Upgradeable, IERC20)
whenNotPaused
returns (bool)
{
return ERC20Upgradeable.approve(spender, value);
}
/// @dev Pausable ERC-20 Permit `permit` function.
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
public
virtual
override
whenNotPaused
{
super.permit(owner, spender, value, deadline, v, r, s);
}
// -----================= ::: VAULT BRIDGE TOKEN ::: =================-----
/// @notice The real-time amount of the underlying token in the yield vault, as reported by the yield vault.
function stakedAssets() public view returns (uint256) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
return $.yieldVault.convertToAssets($.yieldVault.balanceOf(address(this)));
}
/// @notice The real-time reserve percentage.
/// @notice The reserve is based on the total supply of vbToken, and does not account for uncompleted migrations of backing from Layer Ys to Layer X. Please refer to `completeMigration` for more information.
function reservePercentage() public view returns (uint256) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
// Return zero if the total supply is zero.
if (totalSupply() == 0) return 0;
// Calculate the reserve percentage.
return Math.mulDiv($.reservedAssets, 1e18, convertToAssets(totalSupply()));
}
/// @notice The real-time amount of yield available for collection.
function yield() public view returns (uint256) {
// The formula for calculating yield is:
// yield = assets reported by yield vault + reserved assets - vbToken total supply in assets
(bool positive, uint256 difference) = backingDifference();
// Returns zero if the backing is negative.
return positive ? convertToShares(difference) : 0;
}
/// @notice The real-time difference between the total assets and the minimum assets required to back the total supply of vbToken.
function backingDifference() public view returns (bool positive, uint256 difference) {
// Get the state.
uint256 totalAssets_ = totalAssets();
uint256 minimumAssets = convertToAssets(totalSupply());
// Calculate the difference.
return
totalAssets_ >= minimumAssets ? (true, totalAssets_ - minimumAssets) : (false, minimumAssets - totalAssets_);
}
/// @notice Rebalances the internal reserve by withdrawing the underlying token from, or depositing the underlying token into, the yield vault.
/// @param force Whether to revert if the reserve cannot be rebalanced.
/// @param allowRebalanceDown Whether to allow the reserve to be rebalanced down (by depositing into the yield vault).
function _rebalanceReserve(bool force, bool allowRebalanceDown) internal {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
// Cache the reserved assets, total supply, and uncollected yield.
uint256 originalReservedAssets = $.reservedAssets;
uint256 originalTotalSupply = totalSupply();
uint256 originalUncollectedYield = yield();
// Calculate the minimum reserve amount.
uint256 minimumReserve = convertToAssets(Math.mulDiv(originalTotalSupply, $.minimumReservePercentage, 1e18));
// Check if the reserve is below, above, or at the minimum threshold.
/* Below. */
if (originalReservedAssets < minimumReserve) {
// Calculate the amount to try to withdraw from the yield vault.
uint256 shortfall = minimumReserve - originalReservedAssets;
// Try to withdraw from the yield vault.
(uint256 nonWithdrawnAssets, uint256 receivedAssets) = _withdrawFromYieldVault(
shortfall, false, address(this), originalTotalSupply, originalUncollectedYield, originalReservedAssets
);
// @remind Document.
if (force && nonWithdrawnAssets == shortfall) revert CannotRebalanceReserve();
// Update the reserve.
$.reservedAssets += receivedAssets;
// Emit the event.
emit ReserveRebalanced(originalReservedAssets, $.reservedAssets, reservePercentage());
}
/* Above */
else if (originalReservedAssets > minimumReserve && allowRebalanceDown) {
// Calculate the amount to try to deposit into the yield vault.
uint256 excess = originalReservedAssets - minimumReserve;
// Try to deposit into the yield vault.
uint256 nonDepositedAssets = _depositIntoYieldVault(excess, false);
// @remind Document.
if (force && nonDepositedAssets == excess) revert CannotRebalanceReserve();
// Update the reserve.
$.reservedAssets -= (excess - nonDepositedAssets);
// Emit the event.
emit ReserveRebalanced(originalReservedAssets, $.reservedAssets, reservePercentage());
}
/* At. */
else if (force) {
revert NoNeedToRebalanceReserve();
}
}
/// @notice Calculates the amount of assets to reserve (as opposed to depositing into the yield vault) based on the current reserve and minimum reserve percentage.
/// @dev @note (ATTENTION) Make any necessary changes to the reserve prior to using this function.
/// @param assets The amount of the underlying token being deposited.
/// @param nonMintedShares The amount of vbToken that will be minted after using this function, as a result of the deposit.
function _calculateAmountToReserve(uint256 assets, uint256 nonMintedShares)
internal
view
returns (uint256 assetsToReserve)
{
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
// Calculate the minimum reserve.
uint256 minimumReserve =
convertToAssets(Math.mulDiv(totalSupply() + nonMintedShares, $.minimumReservePercentage, 1e18));
// Calculate the amount to reserve.
assetsToReserve = $.reservedAssets < minimumReserve ? minimumReserve - $.reservedAssets : 0;
return assetsToReserve <= assets ? assetsToReserve : assets;
}
// @remind Redocument.
/// @notice Deposit a specific amount of the underlying token into the yield vault.
/// @param assets The amount of the underlying token to deposit into the yield vault.
/// @param exact @remind Document.
/// @return nonDepositedAssets The amount of the underlying token that could not be deposited into the yield vault. The value will be zero if `exact` is set to `true`.
function _depositIntoYieldVault(uint256 assets, bool exact) internal returns (uint256 nonDepositedAssets) {
VaultBridgeTokenStorage storage $ = _getVaultBridgeTokenStorage();
// Check whether to skip depositing into the yield vault.
if (assets < $.minimumYieldVaultDeposit) {
if (exact) revert MinimumYieldVaultDepositNotMet(assets, $.minimumYieldVaultDeposit);
return assets;
}
// @remind Document.
uint256 originalAssets = assets;
// Get the yield vault's deposit limit.
uint256 maxDeposit_ = $.yieldVault.maxDeposit(address(this));
// @remind Document.
if (exact) require(assets <= maxDeposit_, YieldVaultDepositFailed(assets, maxDeposit_));
// Set the return value.
nonDepositedAssets = assets > maxDeposit_ ? assets - maxDeposit_ : 0;
// Calculate the amount to deposit into the yield vault.
assets = assets > maxDeposit_ ? maxDeposit_ : assets;