-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathERC4626FormImplementation.sol
495 lines (411 loc) · 19.7 KB
/
ERC4626FormImplementation.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
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
import { BaseForm } from "src/BaseForm.sol";
import { LiquidityHandler } from "src/crosschain-liquidity/LiquidityHandler.sol";
import { IBridgeValidator } from "src/interfaces/IBridgeValidator.sol";
import { Error } from "src/libraries/Error.sol";
import { DataLib } from "src/libraries/DataLib.sol";
import { InitSingleVaultData } from "src/types/DataTypes.sol";
import { IERC20 } from "openzeppelin-contracts/contracts/interfaces/IERC20.sol";
import { IERC20Metadata } from "openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC4626 } from "openzeppelin-contracts/contracts/interfaces/IERC4626.sol";
/// @title ERC4626FormImplementation
/// @dev Has common ERC4626 internal functions that can be re-used by implementations
/// @author Zeropoint Labs
abstract contract ERC4626FormImplementation is BaseForm, LiquidityHandler {
using SafeERC20 for IERC20;
using SafeERC20 for IERC4626;
using DataLib for uint256;
//////////////////////////////////////////////////////////////
// CONSTANTS //
//////////////////////////////////////////////////////////////
uint8 internal immutable STATE_REGISTRY_ID;
uint256 internal constant ENTIRE_SLIPPAGE = 10_000;
//////////////////////////////////////////////////////////////
// STRUCTS //
//////////////////////////////////////////////////////////////
struct DirectDepositLocalVars {
uint64 chainId;
address asset;
address bridgeValidator;
uint256 shares;
uint256 balanceBefore;
uint256 assetDifference;
uint256 nonce;
uint256 deadline;
uint256 inputAmount;
bytes signature;
}
struct DirectWithdrawLocalVars {
uint64 chainId;
address asset;
address bridgeValidator;
uint256 amount;
}
struct XChainWithdrawLocalVars {
uint64 dstChainId;
address asset;
address bridgeValidator;
uint256 balanceBefore;
uint256 balanceAfter;
uint256 amount;
}
//////////////////////////////////////////////////////////////
// CONSTRUCTOR //
//////////////////////////////////////////////////////////////
constructor(address superRegistry_, uint8 stateRegistryId_) BaseForm(superRegistry_) {
/// @dev check if state registry id is valid
superRegistry.getStateRegistry(stateRegistryId_);
STATE_REGISTRY_ID = stateRegistryId_;
}
//////////////////////////////////////////////////////////////
// EXTERNAL VIEW FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @inheritdoc BaseForm
function getVaultName() public view virtual override returns (string memory) {
return IERC4626(vault).name();
}
/// @inheritdoc BaseForm
function getVaultSymbol() public view virtual override returns (string memory) {
return IERC4626(vault).symbol();
}
/// @inheritdoc BaseForm
function getVaultDecimals() public view virtual override returns (uint256) {
return uint256(IERC4626(vault).decimals());
}
/// @inheritdoc BaseForm
function getPricePerVaultShare() public view virtual override returns (uint256) {
uint256 vaultDecimals = IERC4626(vault).decimals();
return IERC4626(vault).convertToAssets(10 ** vaultDecimals);
}
/// @inheritdoc BaseForm
function getVaultShareBalance() public view virtual override returns (uint256) {
return IERC4626(vault).balanceOf(address(this));
}
/// @inheritdoc BaseForm
function getTotalAssets() public view virtual override returns (uint256) {
return IERC4626(vault).totalAssets();
}
/// @inheritdoc BaseForm
function getTotalSupply() public view virtual override returns (uint256) {
return IERC4626(vault).totalSupply();
}
/// @inheritdoc BaseForm
function getPreviewPricePerVaultShare() public view virtual override returns (uint256) {
uint256 vaultDecimals = IERC4626(vault).decimals();
return IERC4626(vault).previewRedeem(10 ** vaultDecimals);
}
/// @inheritdoc BaseForm
function previewDepositTo(uint256 assets_) public view virtual override returns (uint256) {
return IERC4626(vault).convertToShares(assets_);
}
/// @inheritdoc BaseForm
function previewWithdrawFrom(uint256 assets_) public view virtual override returns (uint256) {
return IERC4626(vault).previewWithdraw(assets_);
}
/// @inheritdoc BaseForm
function previewRedeemFrom(uint256 shares_) public view virtual override returns (uint256) {
return IERC4626(vault).previewRedeem(shares_);
}
/// @inheritdoc BaseForm
function superformYieldTokenName() external view virtual override returns (string memory) {
return string(abi.encodePacked(IERC20Metadata(vault).name(), " SuperPosition"));
}
/// @inheritdoc BaseForm
function superformYieldTokenSymbol() external view virtual override returns (string memory) {
return string(abi.encodePacked("sp-", IERC20Metadata(vault).symbol()));
}
/// @inheritdoc BaseForm
function getStateRegistryId() external view override returns (uint8) {
return STATE_REGISTRY_ID;
}
//////////////////////////////////////////////////////////////
// INTERNAL FUNCTIONS //
//////////////////////////////////////////////////////////////
function _processDirectDeposit(InitSingleVaultData memory singleVaultData_) internal returns (uint256 shares) {
DirectDepositLocalVars memory vars;
IERC4626 v = IERC4626(vault);
vars.asset = address(asset);
vars.balanceBefore = IERC20(vars.asset).balanceOf(address(this));
IERC20 token = IERC20(singleVaultData_.liqData.token);
if (address(token) != NATIVE && singleVaultData_.liqData.txData.length == 0) {
/// @dev this is only valid if token == asset (no txData)
if (singleVaultData_.liqData.token != vars.asset) revert Error.DIFFERENT_TOKENS();
/// @dev handles the asset token transfers.
if (token.allowance(msg.sender, address(this)) < singleVaultData_.amount) {
revert Error.INSUFFICIENT_ALLOWANCE_FOR_DEPOSIT();
}
/// @dev transfers input token, which is the same as vault asset, to the form
token.safeTransferFrom(msg.sender, address(this), singleVaultData_.amount);
}
/// @dev non empty txData means there is a swap needed before depositing (input asset not the same as vault
/// asset)
if (singleVaultData_.liqData.txData.length != 0) {
vars.bridgeValidator = superRegistry.getBridgeValidator(singleVaultData_.liqData.bridgeId);
vars.chainId = CHAIN_ID;
vars.inputAmount =
IBridgeValidator(vars.bridgeValidator).decodeAmountIn(singleVaultData_.liqData.txData, false);
if (address(token) != NATIVE) {
/// @dev checks the allowance before transfer from router
if (token.allowance(msg.sender, address(this)) < vars.inputAmount) {
revert Error.INSUFFICIENT_ALLOWANCE_FOR_DEPOSIT();
}
/// @dev transfers input token, which is different from the vault asset, to the form
token.safeTransferFrom(msg.sender, address(this), vars.inputAmount);
}
IBridgeValidator(vars.bridgeValidator).validateTxData(
IBridgeValidator.ValidateTxDataArgs(
singleVaultData_.liqData.txData,
vars.chainId,
vars.chainId,
vars.chainId,
true,
address(this),
msg.sender,
address(token),
address(0)
)
);
_dispatchTokens(
superRegistry.getBridgeAddress(singleVaultData_.liqData.bridgeId),
singleVaultData_.liqData.txData,
address(token),
vars.inputAmount,
singleVaultData_.liqData.nativeAmount
);
if (
IBridgeValidator(vars.bridgeValidator).decodeSwapOutputToken(singleVaultData_.liqData.txData)
!= vars.asset
) {
revert Error.DIFFERENT_TOKENS();
}
}
vars.assetDifference = IERC20(vars.asset).balanceOf(address(this)) - vars.balanceBefore;
/// @dev the difference in vault tokens, ready to be deposited, is compared with the amount inscribed in the
/// superform data
if (
vars.assetDifference * ENTIRE_SLIPPAGE
< singleVaultData_.amount * (ENTIRE_SLIPPAGE - singleVaultData_.maxSlippage)
) {
revert Error.DIRECT_DEPOSIT_SWAP_FAILED();
}
/// @dev notice that vars.assetDifference is deposited regardless if txData exists or not
/// @dev this presumes no dust is left in the superform
IERC20(vars.asset).safeIncreaseAllowance(vault, vars.assetDifference);
/// @dev deposit assets for shares and add extra validation check to ensure intended ERC4626 behavior
shares = _depositAndValidate(singleVaultData_, v, vars.assetDifference);
}
function _processXChainDeposit(
InitSingleVaultData memory singleVaultData_,
uint64 srcChainId_
)
internal
returns (uint256 shares)
{
(,, uint64 dstChainId) = singleVaultData_.superformId.getSuperform();
address vaultLoc = vault;
IERC4626 v = IERC4626(vaultLoc);
if (IERC20(asset).allowance(msg.sender, address(this)) < singleVaultData_.amount) {
revert Error.INSUFFICIENT_ALLOWANCE_FOR_DEPOSIT();
}
/// @dev pulling from sender, to auto-send tokens back in case of failed deposits / reverts
IERC20(asset).safeTransferFrom(msg.sender, address(this), singleVaultData_.amount);
/// @dev allowance is modified inside of the IERC20.transferFrom() call
IERC20(asset).safeIncreaseAllowance(vaultLoc, singleVaultData_.amount);
/// @dev deposit assets for shares and add extra validation check to ensure intended ERC4626 behavior
shares = _depositAndValidate(singleVaultData_, v, singleVaultData_.amount);
emit Processed(srcChainId_, dstChainId, singleVaultData_.payloadId, singleVaultData_.amount, vaultLoc);
}
function _processDirectWithdraw(InitSingleVaultData memory singleVaultData_) internal returns (uint256 assets) {
DirectWithdrawLocalVars memory vars;
/// @dev if there is no txData, on withdraws the receiver is receiverAddress, otherwise it
/// is this contract (before swap)
IERC4626 v = IERC4626(vault);
IERC20 a = IERC20(asset);
if (!singleVaultData_.retain4626) {
vars.asset = address(asset);
/// @dev redeem shares for assets and add extra validation check to ensure intended ERC4626 behavior
assets = _withdrawAndValidate(singleVaultData_, v, a);
if (singleVaultData_.liqData.txData.length != 0) {
vars.bridgeValidator = superRegistry.getBridgeValidator(singleVaultData_.liqData.bridgeId);
vars.amount =
IBridgeValidator(vars.bridgeValidator).decodeAmountIn(singleVaultData_.liqData.txData, false);
/// @dev the amount inscribed in liqData must be less or equal than the amount redeemed from the vault
/// @dev if less it should be within the slippage limit specified by the user
/// @dev important to maintain so that the keeper cannot update with malicious data after successful
/// withdraw
if (_isWithdrawTxDataAmountInvalid(vars.amount, assets, singleVaultData_.maxSlippage)) {
revert Error.DIRECT_WITHDRAW_INVALID_LIQ_REQUEST();
}
vars.chainId = CHAIN_ID;
/// @dev validate and perform the swap to desired output token and send to beneficiary
IBridgeValidator(vars.bridgeValidator).validateTxData(
IBridgeValidator.ValidateTxDataArgs(
singleVaultData_.liqData.txData,
vars.chainId,
vars.chainId,
singleVaultData_.liqData.liqDstChainId,
false,
address(this),
singleVaultData_.receiverAddress,
vars.asset,
address(0)
)
);
_dispatchTokens(
superRegistry.getBridgeAddress(singleVaultData_.liqData.bridgeId),
singleVaultData_.liqData.txData,
vars.asset,
vars.amount,
singleVaultData_.liqData.nativeAmount
);
}
} else {
/// @dev transfer shares to user and do not redeem shares for assets
v.safeTransfer(singleVaultData_.receiverAddress, singleVaultData_.amount);
return 0;
}
}
function _processXChainWithdraw(
InitSingleVaultData memory singleVaultData_,
uint64 srcChainId_
)
internal
returns (uint256 assets)
{
XChainWithdrawLocalVars memory vars;
uint256 len = singleVaultData_.liqData.txData.length;
/// @dev a case where the withdraw req liqData has a valid token and tx data is not updated by the keeper
if (singleVaultData_.liqData.token != address(0) && len == 0) {
revert Error.WITHDRAW_TX_DATA_NOT_UPDATED();
} else if (singleVaultData_.liqData.token == address(0) && len != 0) {
revert Error.WITHDRAW_TOKEN_NOT_UPDATED();
}
(,, vars.dstChainId) = singleVaultData_.superformId.getSuperform();
IERC4626 v = IERC4626(vault);
IERC20 a = IERC20(asset);
if (!singleVaultData_.retain4626) {
vars.asset = address(asset);
/// @dev redeem shares for assets and add extra validation check to ensure intended ERC4626 behavior
assets = _withdrawAndValidate(singleVaultData_, v, a);
if (len != 0) {
vars.bridgeValidator = superRegistry.getBridgeValidator(singleVaultData_.liqData.bridgeId);
vars.amount =
IBridgeValidator(vars.bridgeValidator).decodeAmountIn(singleVaultData_.liqData.txData, false);
/// @dev the amount inscribed in liqData must be less or equal than the amount redeemed from the vault
/// @dev if less it should be within the slippage limit specified by the user
/// @dev important to maintain so that the keeper cannot update with malicious data after successful
/// withdraw
if (_isWithdrawTxDataAmountInvalid(vars.amount, assets, singleVaultData_.maxSlippage)) {
revert Error.XCHAIN_WITHDRAW_INVALID_LIQ_REQUEST();
}
/// @dev validate and perform the swap to desired output token and send to beneficiary
IBridgeValidator(vars.bridgeValidator).validateTxData(
IBridgeValidator.ValidateTxDataArgs(
singleVaultData_.liqData.txData,
vars.dstChainId,
srcChainId_,
singleVaultData_.liqData.liqDstChainId,
false,
address(this),
singleVaultData_.receiverAddress,
vars.asset,
address(0)
)
);
_dispatchTokens(
superRegistry.getBridgeAddress(singleVaultData_.liqData.bridgeId),
singleVaultData_.liqData.txData,
vars.asset,
vars.amount,
singleVaultData_.liqData.nativeAmount
);
}
} else {
/// @dev transfer shares to user and do not redeem shares for assets
v.safeTransfer(singleVaultData_.receiverAddress, singleVaultData_.amount);
return 0;
}
emit Processed(srcChainId_, vars.dstChainId, singleVaultData_.payloadId, singleVaultData_.amount, vault);
}
function _depositAndValidate(
InitSingleVaultData memory singleVaultData_,
IERC4626 v,
uint256 assetDifference
)
internal
returns (uint256 shares)
{
address sharesReceiver = singleVaultData_.retain4626 ? singleVaultData_.receiverAddress : address(this);
uint256 sharesBalanceBefore = v.balanceOf(sharesReceiver);
shares = v.deposit(assetDifference, sharesReceiver);
uint256 sharesBalanceAfter = v.balanceOf(sharesReceiver);
if (
(sharesBalanceAfter - sharesBalanceBefore != shares)
|| (
ENTIRE_SLIPPAGE * shares
< ((singleVaultData_.outputAmount * (ENTIRE_SLIPPAGE - singleVaultData_.maxSlippage)))
)
) {
revert Error.VAULT_IMPLEMENTATION_FAILED();
}
}
function _withdrawAndValidate(
InitSingleVaultData memory singleVaultData_,
IERC4626 v,
IERC20 a
)
internal
returns (uint256 assets)
{
address assetsReceiver =
singleVaultData_.liqData.txData.length == 0 ? singleVaultData_.receiverAddress : address(this);
uint256 assetsBalanceBefore = a.balanceOf(assetsReceiver);
assets = v.redeem(singleVaultData_.amount, assetsReceiver, address(this));
uint256 assetsBalanceAfter = a.balanceOf(assetsReceiver);
if (
(assetsBalanceAfter - assetsBalanceBefore != assets)
|| (
ENTIRE_SLIPPAGE * assets
< ((singleVaultData_.outputAmount * (ENTIRE_SLIPPAGE - singleVaultData_.maxSlippage)))
)
) {
revert Error.VAULT_IMPLEMENTATION_FAILED();
}
if (assets == 0) revert Error.WITHDRAW_ZERO_COLLATERAL();
}
function _isWithdrawTxDataAmountInvalid(
uint256 bridgeDecodedAmount_,
uint256 redeemedAmount_,
uint256 slippage_
)
internal
pure
returns (bool isInvalid)
{
if (
bridgeDecodedAmount_ > redeemedAmount_
|| ((bridgeDecodedAmount_ * ENTIRE_SLIPPAGE) < (redeemedAmount_ * (ENTIRE_SLIPPAGE - slippage_)))
) return true;
}
function _processEmergencyWithdraw(address receiverAddress_, uint256 amount_) internal {
IERC4626 v = IERC4626(vault);
if (receiverAddress_ == address(0)) revert Error.ZERO_ADDRESS();
if (v.balanceOf(address(this)) < amount_) {
revert Error.INSUFFICIENT_BALANCE();
}
v.safeTransfer(receiverAddress_, amount_);
emit EmergencyWithdrawalProcessed(receiverAddress_, amount_);
}
function _processForwardDustToPaymaster(address token_) internal {
if (token_ == address(0)) revert Error.ZERO_ADDRESS();
address paymaster = superRegistry.getAddress(keccak256("PAYMASTER"));
IERC20 token = IERC20(token_);
uint256 dust = token.balanceOf(address(this));
if (dust != 0) {
token.safeTransfer(paymaster, dust);
emit FormDustForwardedToPaymaster(token_, dust);
}
}
}