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
/
DecreasePositionCollateralUtils.sol
485 lines (424 loc) · 21.3 KB
/
DecreasePositionCollateralUtils.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
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "../utils/Precision.sol";
import "../error/ErrorUtils.sol";
import "../data/DataStore.sol";
import "../event/EventEmitter.sol";
import "../oracle/Oracle.sol";
import "../pricing/PositionPricingUtils.sol";
import "./Position.sol";
import "./PositionEventUtils.sol";
import "./PositionStoreUtils.sol";
import "./PositionUtils.sol";
import "../order/BaseOrderUtils.sol";
import "../order/OrderEventUtils.sol";
import "../swap/SwapUtils.sol";
// @title DecreasePositionCollateralUtils
// @dev Library for functions to help with the calculations when decreasing a position
library DecreasePositionCollateralUtils {
using SafeCast for uint256;
using SafeCast for int256;
using Position for Position.Props;
using Order for Order.Props;
using Price for Price.Props;
using EventUtils for EventUtils.AddressItems;
using EventUtils for EventUtils.UintItems;
using EventUtils for EventUtils.IntItems;
using EventUtils for EventUtils.BoolItems;
using EventUtils for EventUtils.Bytes32Items;
using EventUtils for EventUtils.BytesItems;
using EventUtils for EventUtils.StringItems;
struct ProcessCollateralCache {
int256 adjustedPositionPnlUsd;
uint256 adjustedPriceImpactDiffUsd;
uint256 adjustedPriceImpactDiffAmount;
uint256 pnlDiffAmount;
}
// @dev handle the collateral changes of the position
// @param params PositionUtils.UpdatePositionParams
// @param cache DecreasePositionCache
// @return (PositionUtils.DecreasePositionCollateralValues, PositionPricingUtils.PositionFees)
function processCollateral(
PositionUtils.UpdatePositionParams memory params,
PositionUtils.DecreasePositionCache memory cache
) external returns (
PositionUtils.DecreasePositionCollateralValues memory,
PositionPricingUtils.PositionFees memory
) {
ProcessCollateralCache memory collateralCache;
PositionUtils.DecreasePositionCollateralValues memory values;
values.remainingCollateralAmount = cache.initialCollateralAmount.toInt256();
Price.Props memory collateralTokenPrice = MarketUtils.getCachedTokenPrice(params.order.initialCollateralToken(), params.market, cache.prices);
(values.executionPrice, values.priceImpactAmount, values.priceImpactDiffUsd) = getExecutionPrice(params, cache.prices, params.order.sizeDeltaUsd());
(values.positionPnlUsd, values.sizeDeltaInTokens) = PositionUtils.getPositionPnlUsd(
params.contracts.dataStore,
params.market,
cache.prices,
params.position,
values.executionPrice,
params.order.sizeDeltaUsd()
);
collateralCache.adjustedPositionPnlUsd = values.positionPnlUsd;
collateralCache.adjustedPriceImpactDiffUsd = values.priceImpactDiffUsd;
if (values.positionPnlUsd > 0 && values.priceImpactDiffUsd > 0) {
if (values.positionPnlUsd > values.priceImpactDiffUsd.toInt256()) {
collateralCache.adjustedPositionPnlUsd = values.positionPnlUsd - values.priceImpactDiffUsd.toInt256();
collateralCache.adjustedPriceImpactDiffUsd = 0;
} else {
collateralCache.adjustedPositionPnlUsd = 0;
collateralCache.adjustedPriceImpactDiffUsd = values.priceImpactDiffUsd - values.positionPnlUsd.toUint256();
}
}
collateralCache.adjustedPriceImpactDiffAmount = collateralCache.adjustedPriceImpactDiffUsd / collateralTokenPrice.max;
if (collateralCache.adjustedPriceImpactDiffUsd > 0 && params.order.initialCollateralDeltaAmount() > 0) {
uint256 initialCollateralDeltaAmount = params.order.initialCollateralDeltaAmount();
if (collateralCache.adjustedPriceImpactDiffAmount > params.order.initialCollateralDeltaAmount()) {
params.order.setInitialCollateralDeltaAmount(0);
} else {
params.order.setInitialCollateralDeltaAmount(params.order.initialCollateralDeltaAmount() - collateralCache.adjustedPriceImpactDiffAmount);
}
OrderEventUtils.emitOrderCollateralDeltaAmountAutoUpdated(
params.contracts.eventEmitter,
params.orderKey,
initialCollateralDeltaAmount,
params.order.initialCollateralDeltaAmount()
);
}
values.remainingCollateralAmount -= params.order.initialCollateralDeltaAmount().toInt256();
values.output.outputToken = params.position.collateralToken();
values.output.outputAmount = params.order.initialCollateralDeltaAmount();
values.output.secondaryOutputToken = cache.pnlToken;
if (collateralCache.adjustedPositionPnlUsd < 0) {
// position realizes a loss
// deduct collateral from user, transfer it to the pool
values.pnlTokenForPool = params.position.collateralToken();
values.pnlAmountForPool = -values.positionPnlUsd / collateralTokenPrice.min.toInt256();
values.remainingCollateralAmount -= values.pnlAmountForPool;
} else {
// position realizes a profit
// deduct the pnl from the pool
values.pnlTokenForPool = cache.pnlToken;
values.pnlAmountForPool = -values.positionPnlUsd / cache.pnlTokenPrice.max.toInt256();
values.pnlAmountForUser = collateralCache.adjustedPositionPnlUsd.toUint256() / cache.pnlTokenPrice.max;
// if the price impact was capped send the difference to a holding area
collateralCache.pnlDiffAmount = (-values.pnlAmountForPool - values.pnlAmountForUser.toInt256()).toUint256();
if (collateralCache.pnlDiffAmount > 0) {
MarketUtils.incrementClaimableCollateralAmount(
params.contracts.dataStore,
params.contracts.eventEmitter,
params.market.marketToken,
cache.pnlToken,
params.order.receiver(),
collateralCache.pnlDiffAmount
);
}
// swap profit to the collateral token here so that the profit can be used
// to pay for the totalNetCostAmount from the fees
(bool wasSwapped, uint256 swapOutputAmount) = swapProfitToCollateralToken(
params,
cache.pnlToken,
values.pnlAmountForUser,
values.pnlAmountForPool
);
if (wasSwapped) {
values.output.outputAmount += swapOutputAmount;
} else {
if (params.position.collateralToken() == cache.pnlToken) {
values.output.outputAmount += values.pnlAmountForUser;
} else {
// store the pnlAmountForUser separately as it differs from the collateralToken
values.output.secondaryOutputAmount = values.pnlAmountForUser;
}
}
}
PositionPricingUtils.GetPositionFeesParams memory getPositionFeesParams = PositionPricingUtils.GetPositionFeesParams(
params.contracts.dataStore,
params.contracts.referralStorage,
params.position,
collateralTokenPrice,
params.market.longToken,
params.market.shortToken,
params.order.sizeDeltaUsd(),
params.order.uiFeeReceiver()
);
PositionPricingUtils.PositionFees memory fees = PositionPricingUtils.getPositionFees(
getPositionFeesParams
);
// if there is a positive outputAmount, use the outputAmount to pay for fees and price impact
// the values.output.outputToken should be the same as the position.collateralToken at this point
if (values.output.outputToken == params.position.collateralToken() && values.output.outputAmount > 0) {
if (values.output.outputAmount > fees.totalNetCostAmount) {
values.output.outputAmount -= fees.totalNetCostAmount;
fees.collateralCostAmount = 0;
} else {
fees.collateralCostAmount -= values.output.outputAmount;
values.output.outputAmount = 0;
}
}
// deduct remaining fees from the position's collateral
values.remainingCollateralAmount -= fees.collateralCostAmount.toInt256();
// if there is insufficient collateral remaining then prioritize using the collateral to pay
// funding fees, the rest of the collateral is sent to the pool
// paying of closing fees should be safe to skip
// any difference in the paying of borrowing fees should be accounted for
// from the transfer of collateral to the pool and by the update of the
// pending borrowing fees
// any difference in pending negative PnL should similarly be accounted for
// through the transfer fo collateral to the pool and by the update of the
// pending pnl
// paying of price impact should also be safe to skip, it would be the same as
// closing the position with zero price impact, just that if there were any collateral that could
// partially pay for negative price impact, it would be sent to the pool instead
if (BaseOrderUtils.isLiquidationOrder(params.order.orderType()) && values.remainingCollateralAmount < 0) {
PositionEventUtils.emitPositionFeesInfo(
params.contracts.eventEmitter,
params.orderKey,
params.market.marketToken,
params.position.collateralToken(),
params.order.sizeDeltaUsd(),
false,
fees
);
PositionEventUtils.emitLiquidationInfo(
params.contracts.eventEmitter,
params.orderKey,
params.position.collateralAmount(),
values.positionPnlUsd,
values.remainingCollateralAmount
);
return getLiquidationValues(params, values, fees);
}
if (values.remainingCollateralAmount < 0) {
revert Errors.InsufficientCollateral(values.remainingCollateralAmount);
}
// if there is a positive impact, the impact pool amount should be reduced
// if there is a negative impact, the impact pool amount should be increased
MarketUtils.applyDeltaToPositionImpactPool(
params.contracts.dataStore,
params.contracts.eventEmitter,
params.market.marketToken,
-values.priceImpactAmount
);
// if the price impact was capped, deduct the difference from the collateral
// and send it to a holding area
if (collateralCache.adjustedPriceImpactDiffAmount > 0) {
if (values.remainingCollateralAmount.toUint256() < collateralCache.adjustedPriceImpactDiffAmount) {
collateralCache.adjustedPriceImpactDiffAmount = values.remainingCollateralAmount.toUint256();
}
values.remainingCollateralAmount -= collateralCache.adjustedPriceImpactDiffAmount.toInt256();
// the order.receiver is meant to allow the output of an order to be
// received by an address that is different from the position.account
// address
// for claimable collateral, the funds are still credited to the owner
// of the position indicated by order.account
MarketUtils.incrementClaimableCollateralAmount(
params.contracts.dataStore,
params.contracts.eventEmitter,
params.market.marketToken,
params.position.collateralToken(),
params.order.account(),
collateralCache.adjustedPriceImpactDiffAmount
);
}
FeeUtils.incrementClaimableFeeAmount(
params.contracts.dataStore,
params.contracts.eventEmitter,
params.market.marketToken,
params.position.collateralToken(),
fees.feeReceiverAmount,
Keys.POSITION_FEE
);
FeeUtils.incrementClaimableUiFeeAmount(
params.contracts.dataStore,
params.contracts.eventEmitter,
params.order.uiFeeReceiver(),
params.market.marketToken,
params.position.collateralToken(),
fees.ui.uiFeeAmount,
Keys.UI_POSITION_FEE
);
return (values, fees);
}
function getExecutionPrice(
PositionUtils.UpdatePositionParams memory params,
MarketUtils.MarketPrices memory prices,
uint256 sizeDeltaUsd
) internal view returns (uint256, int256, uint256) {
int256 priceImpactUsd = PositionPricingUtils.getPriceImpactUsd(
PositionPricingUtils.GetPriceImpactUsdParams(
params.contracts.dataStore,
params.market,
-sizeDeltaUsd.toInt256(),
params.order.isLong()
)
);
priceImpactUsd = MarketUtils.getCappedPositionImpactUsd(
params.contracts.dataStore,
params.market.marketToken,
prices.indexTokenPrice,
priceImpactUsd,
sizeDeltaUsd
);
uint256 priceImpactDiffUsd;
if (priceImpactUsd < 0) {
uint256 maxPriceImpactFactor = MarketUtils.getMaxPositionImpactFactor(
params.contracts.dataStore,
params.market.marketToken,
false
);
// convert the max price impact to the min negative value
int256 minPriceImpactUsd = -Precision.applyFactor(sizeDeltaUsd, maxPriceImpactFactor).toInt256();
if (priceImpactUsd < minPriceImpactUsd) {
priceImpactDiffUsd = (minPriceImpactUsd - priceImpactUsd).toUint256();
priceImpactUsd = minPriceImpactUsd;
}
}
uint256 executionPrice = BaseOrderUtils.getExecutionPrice(
params.contracts.oracle.getCustomPrice(params.market.indexToken),
sizeDeltaUsd,
priceImpactUsd,
params.order.acceptablePrice(),
params.position.isLong(),
false
);
int256 priceImpactAmount = PositionPricingUtils.getPriceImpactAmount(
sizeDeltaUsd,
executionPrice,
prices.indexTokenPrice,
params.position.isLong(),
false
);
return (executionPrice, priceImpactAmount, priceImpactDiffUsd);
}
// for simplicity all fee values are set to zero in case there is insufficient
// collateral to cover all fees
function getLiquidationValues(
PositionUtils.UpdatePositionParams memory params,
PositionUtils.DecreasePositionCollateralValues memory values,
PositionPricingUtils.PositionFees memory fees
) internal returns (
PositionUtils.DecreasePositionCollateralValues memory,
PositionPricingUtils.PositionFees memory
) {
if (fees.funding.fundingFeeAmount > params.position.collateralAmount()) {
values.pnlAmountForPool = 0;
// the case where this is insufficient collateral to pay funding fees
// should be rare, and the difference should be small
// in case it happens, the pool should be topped up with the required amount using
// an insurance fund or similar mechanism
PositionEventUtils.emitInsufficientFundingFeePayment(
params.contracts.eventEmitter,
params.market.marketToken,
params.position.collateralToken(),
fees.funding.fundingFeeAmount,
params.position.collateralAmount()
);
} else {
values.pnlTokenForPool = params.position.collateralToken();
values.pnlAmountForPool = (params.position.collateralAmount() - fees.funding.fundingFeeAmount).toInt256();
}
PositionUtils.DecreasePositionCollateralValues memory _values = PositionUtils.DecreasePositionCollateralValues(
values.pnlTokenForPool, // pnlTokenForPool
values.executionPrice, // executionPrice
0, // remainingCollateralAmount
values.positionPnlUsd, // positionPnlUsd
values.pnlAmountForPool, // pnlAmountForPool
0, // pnlAmountForUser
values.sizeDeltaInTokens, // sizeDeltaInTokens
values.priceImpactAmount, // priceImpactAmount
0, // priceImpactDiffUsd
0, // priceImpactDiffAmount
PositionUtils.DecreasePositionCollateralValuesOutput(
address(0),
0,
address(0),
0
)
);
PositionPricingUtils.PositionFees memory _fees;
// allow the accumulated funding fees to still be claimable
_fees.funding.claimableLongTokenAmount = fees.funding.claimableLongTokenAmount;
_fees.funding.claimableShortTokenAmount = fees.funding.claimableShortTokenAmount;
return (_values, _fees);
}
// swap the withdrawn collateral from collateralToken to pnlToken if needed
function swapWithdrawnCollateralToPnlToken(
PositionUtils.UpdatePositionParams memory params,
PositionUtils.DecreasePositionCollateralValues memory values
) external returns (PositionUtils.DecreasePositionCollateralValues memory) {
if (params.order.decreasePositionSwapType() == Order.DecreasePositionSwapType.SwapCollateralTokenToPnlToken) {
Market.Props[] memory swapPathMarkets = new Market.Props[](1);
swapPathMarkets[0] = params.market;
try params.contracts.swapHandler.swap(
SwapUtils.SwapParams(
params.contracts.dataStore,
params.contracts.eventEmitter,
params.contracts.oracle,
Bank(payable(params.market.marketToken)),
params.orderKey,
params.position.collateralToken(), // tokenIn
values.output.outputAmount, // amountIn
swapPathMarkets, // markets
0, // minOutputAmount
params.market.marketToken, // receiver
params.order.uiFeeReceiver(), // uiFeeReceiver
false // shouldUnwrapNativeToken
)
) returns (address tokenOut, uint256 swapOutputAmount) {
if (tokenOut != values.output.secondaryOutputToken) {
revert Errors.InvalidOutputToken(tokenOut, values.output.secondaryOutputToken);
}
// combine the values into outputToken and outputAmount
values.output.outputToken = tokenOut;
values.output.outputAmount = values.output.secondaryOutputAmount + swapOutputAmount;
values.output.secondaryOutputAmount = 0;
} catch Error(string memory reason) {
emit SwapUtils.SwapReverted(reason, "");
} catch (bytes memory reasonBytes) {
(string memory reason, /* bool hasRevertMessage */) = ErrorUtils.getRevertMessage(reasonBytes);
emit SwapUtils.SwapReverted(reason, reasonBytes);
}
}
return values;
}
// swap the realized profit from the pnlToken to the collateralToken if needed
function swapProfitToCollateralToken(
PositionUtils.UpdatePositionParams memory params,
address pnlToken,
uint256 profitAmount,
int256 poolAmountDelta
) internal returns (bool, uint256) {
if (params.order.decreasePositionSwapType() == Order.DecreasePositionSwapType.SwapPnlTokenToCollateralToken) {
Market.Props[] memory swapPathMarkets = new Market.Props[](1);
swapPathMarkets[0] = params.market;
// adjust the pool amount by the poolAmountDelta so that the price impact of the swap will be
// more accurately calculated
params.contracts.dataStore.setInt(Keys.poolAmountAdjustmentKey(params.market.marketToken, pnlToken), poolAmountDelta);
try params.contracts.swapHandler.swap(
SwapUtils.SwapParams(
params.contracts.dataStore,
params.contracts.eventEmitter,
params.contracts.oracle,
Bank(payable(params.market.marketToken)),
params.orderKey,
pnlToken, // tokenIn
profitAmount, // amountIn
swapPathMarkets, // markets
0, // minOutputAmount
params.market.marketToken, // receiver
params.order.uiFeeReceiver(), // uiFeeReceiver
false // shouldUnwrapNativeToken
)
) returns (address /* tokenOut */, uint256 swapOutputAmount) {
return (true, swapOutputAmount);
} catch Error(string memory reason) {
emit SwapUtils.SwapReverted(reason, "");
} catch (bytes memory reasonBytes) {
(string memory reason, /* bool hasRevertMessage */) = ErrorUtils.getRevertMessage(reasonBytes);
emit SwapUtils.SwapReverted(reason, reasonBytes);
}
params.contracts.dataStore.setInt(Keys.poolAmountAdjustmentKey(params.market.marketToken, pnlToken), 0);
}
return (false, 0);
}
}