-
Notifications
You must be signed in to change notification settings - Fork 9
/
ControllerPeggedAssetV2.sol
399 lines (326 loc) · 13.7 KB
/
ControllerPeggedAssetV2.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
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import {IVaultFactoryV2} from "../interfaces/IVaultFactoryV2.sol";
import {IVaultV2} from "../interfaces/IVaultV2.sol";
import "@chainlink/interfaces/AggregatorV3Interface.sol";
import "@chainlink/interfaces/AggregatorV2V3Interface.sol";
import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol";
/// @author Y2K Finance Team
contract ControllerPeggedAssetV2 {
using FixedPointMathLib for uint256;
IVaultFactoryV2 public immutable vaultFactory;
AggregatorV2V3Interface internal sequencerUptimeFeed;
uint16 private constant GRACE_PERIOD_TIME = 3600;
address public immutable treasury;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/** @notice Contract constructor
* @param _factory VaultFactory address
* @param _l2Sequencer Arbitrum sequencer address
* @param _treasury Treasury address
*/
constructor(
address _factory,
address _l2Sequencer,
address _treasury
) {
if (_factory == address(0)) revert ZeroAddress();
if (_l2Sequencer == address(0)) revert ZeroAddress();
vaultFactory = IVaultFactoryV2(_factory);
sequencerUptimeFeed = AggregatorV2V3Interface(_l2Sequencer);
treasury = _treasury;
}
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/** @notice Trigger depeg event
* @param _marketId Target market index
* @param _epochId End of epoch set for market
*/
function triggerDepeg(uint256 _marketId, uint256 _epochId) public {
address[2] memory vaults = vaultFactory.getVaults(_marketId);
if (vaults[0] == address(0) || vaults[1] == address(0))
revert MarketDoesNotExist(_marketId);
IVaultV2 premiumVault = IVaultV2(vaults[0]);
IVaultV2 collateralVault = IVaultV2(vaults[1]);
if (premiumVault.epochExists(_epochId) == false) revert EpochNotExist();
int256 price = getLatestPrice(premiumVault.token());
if (int256(premiumVault.strike()) <= price)
revert PriceNotAtStrikePrice(price);
(uint40 epochStart, uint40 epochEnd, ) = premiumVault.getEpochConfig(
_epochId
);
if (uint256(epochStart) > block.timestamp) revert EpochNotStarted();
if (block.timestamp > uint256(epochEnd)) revert EpochExpired();
//require this function cannot be called twice in the same epoch for the same vault
if (premiumVault.epochResolved(_epochId)) revert EpochFinishedAlready();
if (collateralVault.epochResolved(_epochId))
revert EpochFinishedAlready();
// check if epoch qualifies for null epoch
if (
premiumVault.totalAssets(_epochId) == 0 ||
collateralVault.totalAssets(_epochId) == 0
) {
revert VaultZeroTVL();
}
premiumVault.resolveEpoch(_epochId);
collateralVault.resolveEpoch(_epochId);
uint256 epochFee = vaultFactory.getEpochFee(_epochId);
uint256 premiumTVL = premiumVault.finalTVL(_epochId);
uint256 collateralTVL = collateralVault.finalTVL(_epochId);
uint256 premiumFee = calculateWithdrawalFeeValue(premiumTVL, epochFee);
uint256 collateralFee = calculateWithdrawalFeeValue(
collateralTVL,
epochFee
);
// avoid stack too deep error by avoiding local variables
// uint256 premiumTVLAfterFee = premiumTVL - premiumFee;
// uint256 collateralTVLAfterFee = collateralTVL - collateralFee;
premiumVault.setClaimTVL(_epochId, collateralTVL - collateralFee);
collateralVault.setClaimTVL(_epochId, premiumTVL - premiumFee);
// send fees to treasury and remaining TVL to respective counterparty vault
// strike price reached so premium is entitled to collateralTVL - collateralFee
premiumVault.sendTokens(_epochId, premiumFee, treasury);
premiumVault.sendTokens(
_epochId,
premiumTVL - premiumFee,
address(collateralVault)
);
// strike price is reached so collateral is still entitled to premiumTVL - premiumFee but looses collateralTVL
collateralVault.sendTokens(_epochId, collateralFee, treasury);
collateralVault.sendTokens(
_epochId,
collateralTVL - collateralFee,
address(premiumVault)
);
emit EpochResolved(
_epochId,
_marketId,
VaultTVL(
premiumTVL - premiumFee,
collateralTVL,
collateralTVL - collateralFee,
premiumTVL
),
true,
block.timestamp,
price
);
}
/** @notice Trigger epoch end without depeg event
* @param _marketId Target market index
* @param _epochId End of epoch set for market
*/
function triggerEndEpoch(uint256 _marketId, uint256 _epochId) public {
address[2] memory vaults = vaultFactory.getVaults(_marketId);
if (vaults[0] == address(0) || vaults[1] == address(0))
revert MarketDoesNotExist(_marketId);
IVaultV2 premiumVault = IVaultV2(vaults[0]);
IVaultV2 collateralVault = IVaultV2(vaults[1]);
if (
premiumVault.epochExists(_epochId) == false ||
collateralVault.epochExists(_epochId) == false
) revert EpochNotExist();
(, uint40 epochEnd, ) = premiumVault.getEpochConfig(_epochId);
if (block.timestamp <= uint256(epochEnd)) revert EpochNotExpired();
//require this function cannot be called twice in the same epoch for the same vault
if (premiumVault.epochResolved(_epochId)) revert EpochFinishedAlready();
if (collateralVault.epochResolved(_epochId))
revert EpochFinishedAlready();
premiumVault.resolveEpoch(_epochId);
collateralVault.resolveEpoch(_epochId);
uint256 epochFee = vaultFactory.getEpochFee(_epochId);
uint256 premiumTVL = premiumVault.finalTVL(_epochId);
uint256 collateralTVL = collateralVault.finalTVL(_epochId);
uint256 premiumFee = calculateWithdrawalFeeValue(premiumTVL, epochFee);
uint256 premiumTVLAfterFee = premiumTVL - premiumFee;
uint256 collateralTVLAfterFee = collateralTVL + premiumTVLAfterFee;
// strike price is not reached so premium is entiled to 0
premiumVault.setClaimTVL(_epochId, 0);
// strike price is not reached so collateral is entitled to collateralTVL + premiumTVLAfterFee
collateralVault.setClaimTVL(_epochId, collateralTVLAfterFee);
// send premium fees to treasury and remaining TVL to collateral vault
premiumVault.sendTokens(_epochId, premiumFee, treasury);
// strike price reached so collateral is entitled to collateralTVLAfterFee
premiumVault.sendTokens(
_epochId,
premiumTVLAfterFee,
address(collateralVault)
);
emit EpochResolved(
_epochId,
_marketId,
VaultTVL(collateralTVLAfterFee, collateralTVL, 0, premiumTVL),
false,
block.timestamp,
0
);
}
/** @notice Trigger epoch invalid when one vault has 0 TVL
* @param _marketId Target market index
* @param _epochId End of epoch set for market
*/
function triggerNullEpoch(uint256 _marketId, uint256 _epochId) public {
address[2] memory vaults = vaultFactory.getVaults(_marketId);
if (vaults[0] == address(0) || vaults[1] == address(0))
revert MarketDoesNotExist(_marketId);
IVaultV2 premiumVault = IVaultV2(vaults[0]);
IVaultV2 collateralVault = IVaultV2(vaults[1]);
if (
premiumVault.epochExists(_epochId) == false ||
collateralVault.epochExists(_epochId) == false
) revert EpochNotExist();
(uint40 epochStart, , ) = premiumVault.getEpochConfig(_epochId);
if (block.timestamp < uint256(epochStart)) revert EpochNotStarted();
//require this function cannot be called twice in the same epoch for the same vault
if (premiumVault.epochResolved(_epochId)) revert EpochFinishedAlready();
if (collateralVault.epochResolved(_epochId))
revert EpochFinishedAlready();
//set claim TVL to final TVL if total assets are 0
if (premiumVault.totalAssets(_epochId) == 0) {
premiumVault.resolveEpoch(_epochId);
collateralVault.resolveEpoch(_epochId);
premiumVault.setClaimTVL(_epochId, 0);
collateralVault.setClaimTVL(
_epochId,
collateralVault.finalTVL(_epochId)
);
collateralVault.setEpochNull(_epochId);
} else if (collateralVault.totalAssets(_epochId) == 0) {
premiumVault.resolveEpoch(_epochId);
collateralVault.resolveEpoch(_epochId);
premiumVault.setClaimTVL(_epochId, premiumVault.finalTVL(_epochId));
collateralVault.setClaimTVL(_epochId, 0);
premiumVault.setEpochNull(_epochId);
} else revert VaultNotZeroTVL();
emit NullEpoch(
_epochId,
_marketId,
VaultTVL(
collateralVault.claimTVL(_epochId),
collateralVault.finalTVL(_epochId),
premiumVault.claimTVL(_epochId),
premiumVault.finalTVL(_epochId)
),
block.timestamp
);
}
/*//////////////////////////////////////////////////////////////
GETTERS
//////////////////////////////////////////////////////////////*/
/** @notice Lookup token price
* @param _token Target token address
* @return nowPrice Current token price
*/
function getLatestPrice(address _token) public view returns (int256) {
(
,
/*uint80 roundId*/
int256 answer,
uint256 startedAt, /*uint256 updatedAt*/ /*uint80 answeredInRound*/
,
) = sequencerUptimeFeed.latestRoundData();
// Answer == 0: Sequencer is up
// Answer == 1: Sequencer is down
bool isSequencerUp = answer == 0;
if (!isSequencerUp) {
revert SequencerDown();
}
// Make sure the grace period has passed after the sequencer is back up.
uint256 timeSinceUp = block.timestamp - startedAt;
if (timeSinceUp <= GRACE_PERIOD_TIME) {
revert GracePeriodNotOver();
}
AggregatorV3Interface priceFeed = AggregatorV3Interface(
vaultFactory.tokenToOracle(_token)
);
(uint80 roundID, int256 price, , , uint80 answeredInRound) = priceFeed
.latestRoundData();
uint256 decimals = priceFeed.decimals();
if (decimals < 18) {
decimals = 10**(18 - (decimals));
price = price * int256(decimals);
} else if (decimals == 18) {
price = price;
} else {
decimals = 10**((decimals - 18));
price = price / int256(decimals);
}
if (price <= 0) revert OraclePriceZero();
if (answeredInRound < roundID) revert RoundIDOutdated();
return price;
}
/** @notice Lookup target VaultFactory address
* @dev need to find way to express typecasts in NatSpec
*/
function getVaultFactory() external view returns (address) {
return address(vaultFactory);
}
/** @notice Calculate amount to withdraw after subtracting protocol fee
* @param amount Amount of tokens to withdraw
* @param fee Fee to be applied
*/
function calculateWithdrawalFeeValue(uint256 amount, uint256 fee)
public
pure
returns (uint256 feeValue)
{
// 0.5% = multiply by 10000 then divide by 50
return amount.mulDivDown(fee, 10000);
}
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
error MarketDoesNotExist(uint256 marketId);
error SequencerDown();
error GracePeriodNotOver();
error ZeroAddress();
error EpochFinishedAlready();
error PriceNotAtStrikePrice(int256 price);
error EpochNotStarted();
error EpochExpired();
error OraclePriceZero();
error RoundIDOutdated();
error EpochNotExist();
error EpochNotExpired();
error VaultNotZeroTVL();
error VaultZeroTVL();
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/** @notice Resolves epoch when event is emitted
* @param epochId market epoch ID
* @param marketId market ID
* @param tvl TVL
* @param strikeMet Flag if event isDisaster
* @param time time
* @param depegPrice Price that triggered depeg
*/
event EpochResolved(
uint256 indexed epochId,
uint256 indexed marketId,
VaultTVL tvl,
bool strikeMet,
uint256 time,
int256 depegPrice
);
/** @notice Sets epoch to null when event is emitted
* @param epochId market epoch ID
* @param marketId market ID
* @param tvl TVL
* @param time timestamp
*/
event NullEpoch(
uint256 indexed epochId,
uint256 indexed marketId,
VaultTVL tvl,
uint256 time
);
struct VaultTVL {
uint256 COLLAT_claimTVL;
uint256 COLLAT_finalTVL;
uint256 PREM_claimTVL;
uint256 PREM_finalTVL;
}
}