-
Notifications
You must be signed in to change notification settings - Fork 12
/
Morpho.sol
365 lines (319 loc) · 17.1 KB
/
Morpho.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
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.17;
import {IMorpho} from "./interfaces/IMorpho.sol";
import {IPositionsManager} from "./interfaces/IPositionsManager.sol";
import {IPool, IPoolAddressesProvider} from "@aave-v3-core/interfaces/IPool.sol";
import {IRewardsController} from "@aave-v3-periphery/rewards/interfaces/IRewardsController.sol";
import {Types} from "./libraries/Types.sol";
import {Events} from "./libraries/Events.sol";
import {Errors} from "./libraries/Errors.sol";
import {Constants} from "./libraries/Constants.sol";
import {DelegateCall} from "@morpho-utils/DelegateCall.sol";
import {ERC20, SafeTransferLib} from "@solmate/utils/SafeTransferLib.sol";
import {ERC20 as ERC20Permit2, Permit2Lib} from "@permit2/libraries/Permit2Lib.sol";
import {MorphoStorage} from "./MorphoStorage.sol";
import {MorphoGetters} from "./MorphoGetters.sol";
import {MorphoSetters} from "./MorphoSetters.sol";
/// @title Morpho
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice The main Morpho contract exposing all user entry points.
contract Morpho is IMorpho, MorphoGetters, MorphoSetters {
using DelegateCall for address;
using SafeTransferLib for ERC20;
using Permit2Lib for ERC20Permit2;
/* INITIALIZER */
/// @notice Initializes the contract.
/// @param addressesProvider The address of the pool addresses provider.
/// @param eModeCategoryId The e-mode category of the deployed Morpho. 0 for the general mode.
/// @param positionsManager The address of the `_positionsManager` to set.
/// @param defaultIterations The `_defaultIterations` to set.
function initialize(
address addressesProvider,
uint8 eModeCategoryId,
address positionsManager,
Types.Iterations memory defaultIterations
) external initializer {
__Ownable_init_unchained();
_addressesProvider = IPoolAddressesProvider(addressesProvider);
_pool = IPool(_addressesProvider.getPool());
_positionsManager = positionsManager;
_defaultIterations = defaultIterations;
emit Events.DefaultIterationsSet(defaultIterations.repay, defaultIterations.withdraw);
emit Events.PositionsManagerSet(positionsManager);
_eModeCategoryId = eModeCategoryId;
_pool.setUserEMode(_eModeCategoryId);
}
/* EXTERNAL */
/// @notice Supplies `amount` of `underlying` on behalf of `onBehalf`.
/// The supplied amount cannot be used as collateral but is eligible for the peer-to-peer matching.
/// @param underlying The address of the underlying asset to supply.
/// @param amount The amount of `underlying` to supply.
/// @param onBehalf The address that will receive the supply position.
/// @param maxIterations The maximum number of iterations allowed during the matching process. Using 4 was shown to be efficient in Morpho Labs' simulations.
/// @return The amount supplied (in underlying).
function supply(address underlying, uint256 amount, address onBehalf, uint256 maxIterations)
external
returns (uint256)
{
return _supply(underlying, amount, msg.sender, onBehalf, maxIterations);
}
/// @notice Supplies `amount` of `underlying` of `onBehalf` using permit2 in a single tx.
/// The supplied amount cannot be used as collateral but is eligible for the peer-to-peer matching.
/// @param underlying The address of the `underlying` asset to supply.
/// @param amount The amount of `underlying` to supply.
/// @param onBehalf The address that will receive the supply position.
/// @param maxIterations The maximum number of iterations allowed during the matching process.
/// @param deadline The deadline for the permit2 signature.
/// @param signature The permit2 signature.
/// @return The amount supplied (in underlying).
function supplyWithPermit(
address underlying,
uint256 amount,
address onBehalf,
uint256 maxIterations,
uint256 deadline,
Types.Signature calldata signature
) external returns (uint256) {
ERC20Permit2(underlying).simplePermit2(
msg.sender, address(this), amount, deadline, signature.v, signature.r, signature.s
);
return _supply(underlying, amount, msg.sender, onBehalf, maxIterations);
}
/// @notice Supplies `amount` of `underlying` collateral to the pool on behalf of `onBehalf`.
/// The supplied amount cannot be matched peer-to-peer but can be used as collateral.
/// @param underlying The address of the underlying asset to supply.
/// @param amount The amount of `underlying` to supply.
/// @param onBehalf The address that will receive the collateral position.
/// @return The collateral amount supplied (in underlying).
function supplyCollateral(address underlying, uint256 amount, address onBehalf) external returns (uint256) {
return _supplyCollateral(underlying, amount, msg.sender, onBehalf);
}
/// @notice Supplies `amount` of `underlying` collateral to the pool on behalf of `onBehalf` using permit2 in a single tx.
/// The supplied amount cannot be matched peer-to-peer but can be used as collateral.
/// @param underlying The address of the underlying asset to supply.
/// @param amount The amount of `underlying` to supply.
/// @param onBehalf The address that will receive the collateral position.
/// @param deadline The deadline for the permit2 signature.
/// @param signature The permit2 signature.
/// @return The collateral amount supplied (in underlying).
function supplyCollateralWithPermit(
address underlying,
uint256 amount,
address onBehalf,
uint256 deadline,
Types.Signature calldata signature
) external returns (uint256) {
ERC20Permit2(underlying).simplePermit2(
msg.sender, address(this), amount, deadline, signature.v, signature.r, signature.s
);
return _supplyCollateral(underlying, amount, msg.sender, onBehalf);
}
/// @notice Borrows `amount` of `underlying` on behalf of `onBehalf`.
/// If sender is not `onBehalf`, sender must have previously been approved by `onBehalf` using `approveManager`.
/// @param underlying The address of the underlying asset to borrow.
/// @param amount The amount of `underlying` to borrow.
/// @param onBehalf The address that will receive the debt position.
/// @param receiver The address that will receive the borrowed funds.
/// @param maxIterations The maximum number of iterations allowed during the matching process. Using 4 was shown to be efficient in Morpho Labs' simulations.
/// @return The amount borrowed (in underlying).
function borrow(address underlying, uint256 amount, address onBehalf, address receiver, uint256 maxIterations)
external
returns (uint256)
{
return _borrow(underlying, amount, onBehalf, receiver, maxIterations);
}
/// @notice Repays `amount` of `underlying` on behalf of `onBehalf`.
/// @param underlying The address of the underlying asset to borrow.
/// @param amount The amount of `underlying` to repay.
/// @param onBehalf The address whose position will be repaid.
/// @return The amount repaid (in underlying).
function repay(address underlying, uint256 amount, address onBehalf) external returns (uint256) {
return _repay(underlying, amount, msg.sender, onBehalf);
}
/// @notice Repays `amount` of `underlying` on behalf of `onBehalf` using permit2 in a single tx.
/// @dev When repaying all, one should pass `type(uint160).max` as `amount` because Permit2 does not support approvals larger than 160 bits.
/// @param underlying The address of the underlying asset to borrow.
/// @param amount The amount of `underlying` to repay.
/// @param onBehalf The address whose position will be repaid.
/// @param deadline The deadline for the permit2 signature.
/// @param signature The permit2 signature.
/// @return The amount repaid (in underlying).
function repayWithPermit(
address underlying,
uint256 amount,
address onBehalf,
uint256 deadline,
Types.Signature calldata signature
) external returns (uint256) {
ERC20Permit2(underlying).simplePermit2(
msg.sender, address(this), amount, deadline, signature.v, signature.r, signature.s
);
return _repay(underlying, amount, msg.sender, onBehalf);
}
/// @notice Withdraws `amount` of `underlying` on behalf of `onBehalf`.
/// If sender is not `onBehalf`, sender must have previously been approved by `onBehalf` using `approveManager`.
/// @param underlying The address of the underlying asset to withdraw.
/// @param amount The amount of `underlying` to withdraw.
/// @param onBehalf The address whose position will be withdrawn.
/// @param receiver The address that will receive the withdrawn funds.
/// @param maxIterations The maximum number of iterations allowed during the matching process.
/// If it is less than `_defaultIterations.withdraw`, the latter will be used.
/// Pass 0 to fallback to the `_defaultIterations.withdraw`.
/// @return The amount withdrawn.
function withdraw(address underlying, uint256 amount, address onBehalf, address receiver, uint256 maxIterations)
external
returns (uint256)
{
return _withdraw(underlying, amount, onBehalf, receiver, maxIterations);
}
/// @notice Withdraws `amount` of `underlying` collateral on behalf of `onBehalf`.
/// If sender is not `onBehalf`, sender must have previously been approved by `onBehalf` using `approveManager`.
/// @param underlying The address of the underlying asset to withdraw.
/// @param amount The amount of `underlying` to withdraw.
/// @param onBehalf The address whose position will be withdrawn.
/// @param receiver The address that will receive the withdrawn funds.
/// @return The collateral amount withdrawn (in underlying).
function withdrawCollateral(address underlying, uint256 amount, address onBehalf, address receiver)
external
returns (uint256)
{
return _withdrawCollateral(underlying, amount, onBehalf, receiver);
}
/// @notice Liquidates `user`.
/// @param underlyingBorrowed The address of the underlying borrowed to repay.
/// @param underlyingCollateral The address of the underlying collateral to seize.
/// @param user The address of the user to liquidate.
/// @param amount The amount of `underlyingBorrowed` to repay.
/// @return The `underlyingBorrowed` amount repaid (in underlying) and the `underlyingCollateral` amount seized (in underlying).
function liquidate(address underlyingBorrowed, address underlyingCollateral, address user, uint256 amount)
external
returns (uint256, uint256)
{
return _liquidate(underlyingBorrowed, underlyingCollateral, amount, user, msg.sender);
}
/// @notice Approves a `manager` to borrow/withdraw on behalf of the sender.
/// @param manager The address of the manager.
/// @param isAllowed Whether `manager` is allowed to manage `msg.sender`'s position or not.
function approveManager(address manager, bool isAllowed) external {
_approveManager(msg.sender, manager, isAllowed);
}
/// @notice Approves a `manager` to manage the position of `msg.sender` using EIP712 signature in a single tx.
/// @param delegator The address of the delegator.
/// @param manager The address of the manager.
/// @param isAllowed Whether `manager` is allowed to manage `msg.sender`'s position or not.
/// @param nonce The nonce of the signed message.
/// @param deadline The deadline of the signed message.
/// @param signature The signature of the message.
function approveManagerWithSig(
address delegator,
address manager,
bool isAllowed,
uint256 nonce,
uint256 deadline,
Types.Signature calldata signature
) external {
if (uint256(signature.s) > Constants.MAX_VALID_ECDSA_S) revert Errors.InvalidValueS();
// v ∈ {27, 28} (source: https://ethereum.github.io/yellowpaper/paper.pdf #308)
if (signature.v != 27 && signature.v != 28) revert Errors.InvalidValueV();
bytes32 structHash = keccak256(
abi.encode(Constants.EIP712_AUTHORIZATION_TYPEHASH, delegator, manager, isAllowed, nonce, deadline)
);
bytes32 digest = _hashEIP712TypedData(structHash);
address signatory = ecrecover(digest, signature.v, signature.r, signature.s);
if (signatory == address(0) || delegator != signatory) revert Errors.InvalidSignatory();
if (block.timestamp >= deadline) revert Errors.SignatureExpired();
uint256 usedNonce = _userNonce[signatory]++;
if (nonce != usedNonce) revert Errors.InvalidNonce();
emit Events.UserNonceIncremented(msg.sender, signatory, usedNonce);
_approveManager(signatory, manager, isAllowed);
}
/// @notice Claims rewards for the given assets.
/// @param assets The assets to claim rewards from (aToken or variable debt token).
/// @param onBehalf The address for which rewards are claimed and sent to.
/// @return rewardTokens The addresses of each reward token.
/// @return claimedAmounts The amount of rewards claimed (in reward tokens).
function claimRewards(address[] calldata assets, address onBehalf)
external
returns (address[] memory rewardTokens, uint256[] memory claimedAmounts)
{
if (address(_rewardsManager) == address(0)) revert Errors.AddressIsZero();
if (_isClaimRewardsPaused) revert Errors.ClaimRewardsPaused();
(rewardTokens, claimedAmounts) = _rewardsManager.claimRewards(assets, onBehalf);
IRewardsController(_rewardsManager.REWARDS_CONTROLLER()).claimAllRewardsToSelf(assets);
for (uint256 i; i < rewardTokens.length; ++i) {
uint256 claimedAmount = claimedAmounts[i];
if (claimedAmount > 0) {
ERC20(rewardTokens[i]).safeTransfer(onBehalf, claimedAmount);
emit Events.RewardsClaimed(msg.sender, onBehalf, rewardTokens[i], claimedAmount);
}
}
}
/* INTERNAL */
function _supply(address underlying, uint256 amount, address from, address onBehalf, uint256 maxIterations)
internal
returns (uint256)
{
bytes memory returnData = _positionsManager.functionDelegateCall(
abi.encodeCall(IPositionsManager.supplyLogic, (underlying, amount, from, onBehalf, maxIterations))
);
return (abi.decode(returnData, (uint256)));
}
function _supplyCollateral(address underlying, uint256 amount, address from, address onBehalf)
internal
returns (uint256)
{
bytes memory returnData = _positionsManager.functionDelegateCall(
abi.encodeCall(IPositionsManager.supplyCollateralLogic, (underlying, amount, from, onBehalf))
);
return (abi.decode(returnData, (uint256)));
}
function _borrow(address underlying, uint256 amount, address onBehalf, address receiver, uint256 maxIterations)
internal
returns (uint256)
{
bytes memory returnData = _positionsManager.functionDelegateCall(
abi.encodeCall(IPositionsManager.borrowLogic, (underlying, amount, onBehalf, receiver, maxIterations))
);
return (abi.decode(returnData, (uint256)));
}
function _repay(address underlying, uint256 amount, address from, address onBehalf) internal returns (uint256) {
bytes memory returnData = _positionsManager.functionDelegateCall(
abi.encodeCall(IPositionsManager.repayLogic, (underlying, amount, from, onBehalf))
);
return (abi.decode(returnData, (uint256)));
}
function _withdraw(address underlying, uint256 amount, address onBehalf, address receiver, uint256 maxIterations)
internal
returns (uint256)
{
bytes memory returnData = _positionsManager.functionDelegateCall(
abi.encodeCall(IPositionsManager.withdrawLogic, (underlying, amount, onBehalf, receiver, maxIterations))
);
return (abi.decode(returnData, (uint256)));
}
function _withdrawCollateral(address underlying, uint256 amount, address onBehalf, address receiver)
internal
returns (uint256)
{
bytes memory returnData = _positionsManager.functionDelegateCall(
abi.encodeCall(IPositionsManager.withdrawCollateralLogic, (underlying, amount, onBehalf, receiver))
);
return (abi.decode(returnData, (uint256)));
}
function _liquidate(
address underlyingBorrowed,
address underlyingCollateral,
uint256 amount,
address borrower,
address liquidator
) internal returns (uint256 repaid, uint256 seized) {
bytes memory returnData = _positionsManager.functionDelegateCall(
abi.encodeCall(
IPositionsManager.liquidateLogic,
(underlyingBorrowed, underlyingCollateral, amount, borrower, liquidator)
)
);
return (abi.decode(returnData, (uint256, uint256)));
}
}