-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathMorphoMarketV1Adapter.sol
More file actions
220 lines (189 loc) · 9.79 KB
/
MorphoMarketV1Adapter.sol
File metadata and controls
220 lines (189 loc) · 9.79 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
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Morpho Association
pragma solidity 0.8.28;
import {IMorpho, MarketParams, Id} from "../../lib/morpho-blue/src/interfaces/IMorpho.sol";
import {MarketParamsLib} from "../../lib/morpho-blue/src/libraries/MarketParamsLib.sol";
import {SharesMathLib} from "../../lib/morpho-blue/src/libraries/SharesMathLib.sol";
import {IVaultV2} from "../interfaces/IVaultV2.sol";
import {IERC20} from "../interfaces/IERC20.sol";
import {IMorphoMarketV1Adapter} from "./interfaces/IMorphoMarketV1Adapter.sol";
import {SafeERC20Lib} from "../libraries/SafeERC20Lib.sol";
import {
AdaptiveCurveIrmLib
} from "../../lib/morpho-blue-irm/src/adaptive-curve-irm/libraries/periphery/AdaptiveCurveIrmLib.sol";
/// @dev Morpho Market V1 is also known as Morpho Blue.
/// @dev This adapter must be used with Morpho Market V1 that are protected against inflation attacks with an initial
/// supply. Following resource is relevant: https://docs.openzeppelin.com/contracts/5.x/erc4626#inflation-attack.
/// @dev Rounding error losses on supply/withdraw are realizable.
/// @dev If expectedSupplyAssets reverts for a market of the marketIds, realAssets will revert and the vault will not be
/// able to accrueInterest.
/// @dev Upon interest accrual, the vault calls realAssets(). If there are too many markets, it could cause issues such
/// as expensive interactions, even DOS, because of the gas.
/// @dev Shouldn't be used alongside another adapter that re-uses the last id (abi.encode("this/marketParams",
/// address(this), marketParams)).
/// @dev Markets get removed from the marketIds when the allocation is zero, but it doesn't mean that the adapter has
/// zero shares on the market.
/// @dev This adapter can only be used for markets with the adaptive curve irm.
/// @dev Before adding the adapter to the vault, its timelocks must be properly set.
contract MorphoMarketV1Adapter is IMorphoMarketV1Adapter {
using MarketParamsLib for MarketParams;
using SharesMathLib for uint256;
/* IMMUTABLES */
address public immutable factory;
address public immutable parentVault;
address public immutable asset;
address public immutable morpho;
bytes32 public immutable adapterId;
address public immutable adaptiveCurveIrm;
/* STORAGE */
address public skimRecipient;
bytes32[] public marketIds;
mapping(bytes32 marketId => uint256) public supplyShares;
mapping(bytes data => uint256) public executableAt;
function marketIdsLength() external view returns (uint256) {
return marketIds.length;
}
/* FUNCTIONS */
constructor(address _parentVault, address _morpho, address _adaptiveCurveIrm) {
factory = msg.sender;
parentVault = _parentVault;
morpho = _morpho;
asset = IVaultV2(_parentVault).asset();
adapterId = keccak256(abi.encode("this", address(this)));
adaptiveCurveIrm = _adaptiveCurveIrm;
SafeERC20Lib.safeApprove(asset, _morpho, type(uint256).max);
SafeERC20Lib.safeApprove(asset, _parentVault, type(uint256).max);
}
function submit(bytes calldata data) external {
require(msg.sender == IVaultV2(parentVault).curator(), Unauthorized());
require(executableAt[data] == 0, AlreadyPending());
bytes4 selector = bytes4(data);
executableAt[data] = block.timestamp + IVaultV2(parentVault).timelock(selector);
emit Submit(selector, data, executableAt[data]);
}
function timelocked() internal {
require(executableAt[msg.data] != 0, DataNotTimelocked());
require(block.timestamp >= executableAt[msg.data], TimelockNotExpired());
executableAt[msg.data] = 0;
emit Accept(bytes4(msg.data), msg.data);
}
function revoke(bytes calldata data) external {
require(
msg.sender == IVaultV2(parentVault).curator() || IVaultV2(parentVault).isSentinel(msg.sender),
Unauthorized()
);
require(executableAt[data] != 0, DataNotTimelocked());
executableAt[data] = 0;
emit Revoke(msg.sender, bytes4(data), data);
}
function setSkimRecipient(address newSkimRecipient) external {
timelocked();
skimRecipient = newSkimRecipient;
emit SetSkimRecipient(newSkimRecipient);
}
/// @dev Deallocate 0 from the vault after burning shares to update the allocation there.
function burnShares(bytes32 marketId) external {
timelocked();
uint256 supplySharesBefore = supplyShares[marketId];
supplyShares[marketId] = 0;
emit BurnShares(marketId, supplySharesBefore);
}
/// @dev Skims the adapter's balance of `token` and sends it to `skimRecipient`.
/// @dev This is useful to handle rewards that the adapter has earned.
function skim(address token) external {
require(msg.sender == skimRecipient, Unauthorized());
uint256 balance = IERC20(token).balanceOf(address(this));
SafeERC20Lib.safeTransfer(token, skimRecipient, balance);
emit Skim(token, balance);
}
/// @dev Does not log anything because the ids (logged in the parent vault) are enough.
/// @dev Returns the ids of the allocation and the change in allocation.
function allocate(bytes memory data, uint256 assets, bytes4, address) external returns (bytes32[] memory, int256) {
MarketParams memory marketParams = abi.decode(data, (MarketParams));
require(msg.sender == parentVault, Unauthorized());
require(marketParams.loanToken == asset, LoanAssetMismatch());
require(marketParams.irm == adaptiveCurveIrm, IrmMismatch());
bytes32 marketId = Id.unwrap(marketParams.id());
uint256 mintedShares;
if (assets > 0) {
(, mintedShares) = IMorpho(morpho).supply(marketParams, assets, 0, address(this), hex"");
require(mintedShares >= assets, SharePriceAboveOne());
supplyShares[marketId] += mintedShares;
}
uint256 oldAllocation = allocation(marketParams);
uint256 newAllocation = expectedSupplyAssets(marketId);
updateList(marketId, oldAllocation, newAllocation);
emit Allocate(marketId, newAllocation, mintedShares);
// Safe casts because Market V1 bounds the total supply of the underlying token, and allocation is less than the
// max total assets of the vault.
return (ids(marketParams), int256(newAllocation) - int256(oldAllocation));
}
/// @dev Does not log anything because the ids (logged in the parent vault) are enough.
/// @dev Returns the ids of the deallocation and the change in allocation.
function deallocate(bytes memory data, uint256 assets, bytes4, address)
external
returns (bytes32[] memory, int256)
{
MarketParams memory marketParams = abi.decode(data, (MarketParams));
require(msg.sender == parentVault, Unauthorized());
require(marketParams.loanToken == asset, LoanAssetMismatch());
require(marketParams.irm == adaptiveCurveIrm, IrmMismatch());
bytes32 marketId = Id.unwrap(marketParams.id());
uint256 burnedShares;
if (assets > 0) {
(, burnedShares) = IMorpho(morpho).withdraw(marketParams, assets, 0, address(this), address(this));
supplyShares[marketId] -= burnedShares;
}
uint256 oldAllocation = allocation(marketParams);
uint256 newAllocation = expectedSupplyAssets(marketId);
updateList(marketId, oldAllocation, newAllocation);
emit Deallocate(marketId, newAllocation, burnedShares);
// Safe casts because Market V1 bounds the total supply of the underlying token, and allocation is less than the
// max total assets of the vault.
return (ids(marketParams), int256(newAllocation) - int256(oldAllocation));
}
function updateList(bytes32 marketId, uint256 oldAllocation, uint256 newAllocation) internal {
if (oldAllocation > 0 && newAllocation == 0) {
for (uint256 i = 0; i < marketIds.length; i++) {
if (marketIds[i] == marketId) {
marketIds[i] = marketIds[marketIds.length - 1];
marketIds.pop();
break;
}
}
} else if (oldAllocation == 0 && newAllocation > 0) {
marketIds.push(marketId);
}
}
/* VIEW FUNCTIONS */
/// @dev Returns the expected supply assets of the market, taking into account the internal shares accounting.
function expectedSupplyAssets(bytes32 marketId) public view returns (uint256) {
uint256 _supplyShares = supplyShares[marketId];
if (_supplyShares == 0) {
return 0;
} else {
(uint256 totalSupplyAssets, uint256 totalSupplyShares,,) =
AdaptiveCurveIrmLib.expectedMarketBalances(morpho, marketId, adaptiveCurveIrm);
return _supplyShares.toAssetsDown(totalSupplyAssets, totalSupplyShares);
}
}
/// @dev Returns the Vault's allocation for this market.
function allocation(MarketParams memory marketParams) public view returns (uint256) {
return IVaultV2(parentVault).allocation(keccak256(abi.encode("this/marketParams", address(this), marketParams)));
}
/// @dev Returns adapter's ids.
function ids(MarketParams memory marketParams) public view returns (bytes32[] memory) {
bytes32[] memory ids_ = new bytes32[](3);
ids_[0] = adapterId;
ids_[1] = keccak256(abi.encode("collateralToken", marketParams.collateralToken));
ids_[2] = keccak256(abi.encode("this/marketParams", address(this), marketParams));
return ids_;
}
function realAssets() external view returns (uint256) {
uint256 _realAssets = 0;
for (uint256 i = 0; i < marketIds.length; i++) {
_realAssets += expectedSupplyAssets(marketIds[i]);
}
return _realAssets;
}
}