This repository has been archived by the owner on Dec 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ExecuteDepositUtils.sol
422 lines (365 loc) · 14.8 KB
/
ExecuteDepositUtils.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
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "../adl/AdlUtils.sol";
import "../data/DataStore.sol";
import "../event/EventEmitter.sol";
import "./DepositVault.sol";
import "./DepositStoreUtils.sol";
import "./DepositEventUtils.sol";
import "../pricing/SwapPricingUtils.sol";
import "../oracle/Oracle.sol";
import "../oracle/OracleUtils.sol";
import "../gas/GasUtils.sol";
import "../callback/CallbackUtils.sol";
import "../utils/Array.sol";
import "../error/ErrorUtils.sol";
// @title DepositUtils
// @dev Library for deposit functions, to help with the depositing of liquidity
// into a market in return for market tokens
library ExecuteDepositUtils {
using SafeCast for uint256;
using SafeCast for int256;
using Array for uint256[];
using Price for Price.Props;
using Deposit for Deposit.Props;
// @dev ExecuteDepositParams struct used in executeDeposit to avoid stack
// too deep errors
//
// @param dataStore DataStore
// @param eventEmitter EventEmitter
// @param oracle Oracle
// @param key the key of the deposit to execute
// @param oracleBlockNumbers the oracle block numbers for the prices in oracle
// @param keeper the address of the keeper executing the deposit
// @param startingGas the starting amount of gas
struct ExecuteDepositParams {
DataStore dataStore;
EventEmitter eventEmitter;
DepositVault depositVault;
Oracle oracle;
bytes32 key;
uint256[] minOracleBlockNumbers;
uint256[] maxOracleBlockNumbers;
address keeper;
uint256 startingGas;
}
// @dev _ExecuteDepositParams struct used in executeDeposit to avoid stack
// too deep errors
//
// @param market the market to deposit into
// @param account the depositing account
// @param receiver the account to send the market tokens to
// @param uiFeeReceiver the ui fee receiver account
// @param tokenIn the token to deposit, either the market.longToken or
// market.shortToken
// @param tokenOut the other token, if tokenIn is market.longToken then
// tokenOut is market.shortToken and vice versa
// @param tokenInPrice price of tokenIn
// @param tokenOutPrice price of tokenOut
// @param amount amount of tokenIn
// @param priceImpactUsd price impact in USD
struct _ExecuteDepositParams {
Market.Props market;
address account;
address receiver;
address uiFeeReceiver;
address tokenIn;
address tokenOut;
Price.Props tokenInPrice;
Price.Props tokenOutPrice;
uint256 amount;
int256 priceImpactUsd;
}
struct ExecuteDepositCache {
uint256 longTokenAmount;
uint256 shortTokenAmount;
uint256 longTokenUsd;
uint256 shortTokenUsd;
uint256 receivedMarketTokens;
int256 priceImpactUsd;
}
// @dev executes a deposit
// @param params ExecuteDepositParams
function executeDeposit(ExecuteDepositParams memory params) external {
Deposit.Props memory deposit = DepositStoreUtils.get(params.dataStore, params.key);
ExecuteDepositCache memory cache;
if (deposit.account() == address(0)) {
revert Errors.EmptyDeposit();
}
OracleUtils.validateBlockNumberWithinRange(
params.minOracleBlockNumbers,
params.maxOracleBlockNumbers,
deposit.updatedAtBlock()
);
Market.Props memory market = MarketUtils.getEnabledMarket(params.dataStore, deposit.market());
MarketUtils.MarketPrices memory prices = MarketUtils.getMarketPrices(params.oracle, market);
// deposits should improve the pool state but it should be checked if
// the max pnl factor for deposits is exceeded as this would lead to the
// price of the market token decreasing below a target minimum percentage
// due to pnl
// note that this is just a validation for deposits, there is no actual
// minimum price for a market token
MarketUtils.validateMaxPnl(
params.dataStore,
market,
prices,
Keys.MAX_PNL_FACTOR_FOR_DEPOSITS,
Keys.MAX_PNL_FACTOR_FOR_DEPOSITS
);
cache.longTokenAmount = swap(
params,
deposit.longTokenSwapPath(),
deposit.initialLongToken(),
deposit.initialLongTokenAmount(),
market.marketToken,
market.longToken,
deposit.uiFeeReceiver()
);
cache.shortTokenAmount = swap(
params,
deposit.shortTokenSwapPath(),
deposit.initialShortToken(),
deposit.initialShortTokenAmount(),
market.marketToken,
market.shortToken,
deposit.uiFeeReceiver()
);
if (cache.longTokenAmount == 0 && cache.shortTokenAmount == 0) {
revert Errors.EmptyDepositAmountsAfterSwap();
}
cache.longTokenUsd = cache.longTokenAmount * prices.longTokenPrice.midPrice();
cache.shortTokenUsd = cache.shortTokenAmount * prices.shortTokenPrice.midPrice();
cache.priceImpactUsd = SwapPricingUtils.getPriceImpactUsd(
SwapPricingUtils.GetPriceImpactUsdParams(
params.dataStore,
market,
market.longToken,
market.shortToken,
prices.longTokenPrice.midPrice(),
prices.shortTokenPrice.midPrice(),
(cache.longTokenAmount * prices.longTokenPrice.midPrice()).toInt256(),
(cache.shortTokenAmount * prices.shortTokenPrice.midPrice()).toInt256()
)
);
if (cache.longTokenAmount > 0) {
_ExecuteDepositParams memory _params = _ExecuteDepositParams(
market,
deposit.account(),
deposit.receiver(),
deposit.uiFeeReceiver(),
market.longToken,
market.shortToken,
prices.longTokenPrice,
prices.shortTokenPrice,
cache.longTokenAmount,
cache.priceImpactUsd * cache.longTokenUsd.toInt256() / (cache.longTokenUsd + cache.shortTokenUsd).toInt256()
);
cache.receivedMarketTokens += _executeDeposit(params, _params);
}
if (cache.shortTokenAmount > 0) {
_ExecuteDepositParams memory _params = _ExecuteDepositParams(
market,
deposit.account(),
deposit.receiver(),
deposit.uiFeeReceiver(),
market.shortToken,
market.longToken,
prices.shortTokenPrice,
prices.longTokenPrice,
cache.shortTokenAmount,
cache.priceImpactUsd * cache.shortTokenUsd.toInt256() / (cache.longTokenUsd + cache.shortTokenUsd).toInt256()
);
cache.receivedMarketTokens += _executeDeposit(params, _params);
}
if (cache.receivedMarketTokens < deposit.minMarketTokens()) {
revert Errors.MinMarketTokens(cache.receivedMarketTokens, deposit.minMarketTokens());
}
DepositStoreUtils.remove(params.dataStore, params.key, deposit.account());
// validate that internal state changes are correct before calling
// external callbacks
MarketUtils.validateMarketTokenBalance(params.dataStore, market);
DepositEventUtils.emitDepositExecuted(
params.eventEmitter,
params.key,
cache.longTokenAmount,
cache.shortTokenAmount,
cache.receivedMarketTokens
);
CallbackUtils.afterDepositExecution(params.key, deposit);
GasUtils.payExecutionFee(
params.dataStore,
params.eventEmitter,
params.depositVault,
deposit.executionFee(),
params.startingGas,
params.keeper,
deposit.account()
);
}
// @dev executes a deposit
// @param params ExecuteDepositParams
// @param _params _ExecuteDepositParams
function _executeDeposit(ExecuteDepositParams memory params, _ExecuteDepositParams memory _params) internal returns (uint256) {
SwapPricingUtils.SwapFees memory fees = SwapPricingUtils.getSwapFees(
params.dataStore,
_params.market.marketToken,
_params.amount,
_params.uiFeeReceiver
);
FeeUtils.incrementClaimableFeeAmount(
params.dataStore,
params.eventEmitter,
_params.market.marketToken,
_params.tokenIn,
fees.feeReceiverAmount,
Keys.DEPOSIT_FEE
);
FeeUtils.incrementClaimableUiFeeAmount(
params.dataStore,
params.eventEmitter,
_params.uiFeeReceiver,
_params.market.marketToken,
_params.tokenIn,
fees.uiFeeAmount,
Keys.UI_DEPOSIT_FEE
);
SwapPricingUtils.emitSwapFeesCollected(
params.eventEmitter,
_params.market.marketToken,
_params.tokenIn,
_params.tokenInPrice.min,
"deposit",
fees
);
uint256 mintAmount;
MarketPoolValueInfo.Props memory poolValueInfo = MarketUtils.getPoolValueInfo(
params.dataStore,
_params.market,
params.oracle.getPrimaryPrice(_params.market.indexToken),
_params.tokenIn == _params.market.longToken ? _params.tokenInPrice : _params.tokenOutPrice,
_params.tokenIn == _params.market.shortToken ? _params.tokenInPrice : _params.tokenOutPrice,
Keys.MAX_PNL_FACTOR_FOR_DEPOSITS,
true
);
if (poolValueInfo.poolValue < 0) {
revert Errors.InvalidPoolValueForDeposit(poolValueInfo.poolValue);
}
uint256 poolValue = poolValueInfo.poolValue.toUint256();
uint256 marketTokensSupply = MarketUtils.getMarketTokenSupply(MarketToken(payable(_params.market.marketToken)));
MarketEventUtils.emitMarketPoolValueInfo(
params.eventEmitter,
_params.market.marketToken,
poolValueInfo,
marketTokensSupply
);
if (_params.priceImpactUsd > 0) {
// when there is a positive price impact factor,
// tokens from the swap impact pool are used to mint additional market tokens for the user
// for example, if 50,000 USDC is deposited and there is a positive price impact
// an additional 0.005 ETH may be used to mint market tokens
// the swap impact pool is decreased by the used amount
//
// priceImpactUsd is calculated based on pricing assuming only depositAmount of tokenIn
// was added to the pool
// since impactAmount of tokenOut is added to the pool here, the calculation of
// the tokenInPrice would not be entirely accurate
int256 positiveImpactAmount = MarketUtils.applySwapImpactWithCap(
params.dataStore,
params.eventEmitter,
_params.market.marketToken,
_params.tokenOut,
_params.tokenOutPrice,
_params.priceImpactUsd
);
// calculate the usd amount using positiveImpactAmount since it may
// be capped by the max available amount in the impact pool
mintAmount += MarketUtils.usdToMarketTokenAmount(
positiveImpactAmount.toUint256() * _params.tokenOutPrice.min,
poolValue,
marketTokensSupply
);
// deposit the token out, that was withdrawn from the impact pool, to mint market tokens
MarketUtils.applyDeltaToPoolAmount(
params.dataStore,
params.eventEmitter,
_params.market.marketToken,
_params.tokenOut,
positiveImpactAmount
);
MarketUtils.validatePoolAmount(
params.dataStore,
_params.market,
_params.tokenOut
);
} else {
// when there is a negative price impact factor,
// less of the deposit amount is used to mint market tokens
// for example, if 10 ETH is deposited and there is a negative price impact
// only 9.995 ETH may be used to mint market tokens
// the remaining 0.005 ETH will be stored in the swap impact pool
int256 negativeImpactAmount = MarketUtils.applySwapImpactWithCap(
params.dataStore,
params.eventEmitter,
_params.market.marketToken,
_params.tokenIn,
_params.tokenInPrice,
_params.priceImpactUsd
);
fees.amountAfterFees -= (-negativeImpactAmount).toUint256();
}
mintAmount += MarketUtils.usdToMarketTokenAmount(
fees.amountAfterFees * _params.tokenInPrice.min,
poolValue,
marketTokensSupply
);
MarketUtils.applyDeltaToPoolAmount(
params.dataStore,
params.eventEmitter,
_params.market.marketToken,
_params.tokenIn,
(fees.amountAfterFees + fees.feeAmountForPool).toInt256()
);
MarketUtils.validatePoolAmount(
params.dataStore,
_params.market,
_params.tokenIn
);
MarketToken(payable(_params.market.marketToken)).mint(_params.receiver, mintAmount);
return mintAmount;
}
function swap(
ExecuteDepositParams memory params,
address[] memory swapPath,
address initialToken,
uint256 inputAmount,
address market,
address expectedOutputToken,
address uiFeeReceiver
) internal returns (uint256) {
Market.Props[] memory swapPathMarkets = MarketUtils.getEnabledMarkets(
params.dataStore,
swapPath
);
(address outputToken, uint256 outputAmount) = SwapUtils.swap(
SwapUtils.SwapParams(
params.dataStore, // dataStore
params.eventEmitter, // eventEmitter
params.oracle, // oracle
params.depositVault, // bank
params.key, // key
initialToken, // tokenIn
inputAmount, // amountIn
swapPathMarkets, // swapPathMarkets
0, // minOutputAmount
market, // receiver
uiFeeReceiver, // uiFeeReceiver
false // shouldUnwrapNativeToken
)
);
if (outputToken != expectedOutputToken) {
revert Errors.InvalidSwapOutputToken(outputToken, expectedOutputToken);
}
MarketUtils.validateMarketTokenBalance(params.dataStore, swapPathMarkets);
return outputAmount;
}
}