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
/
BaseOrderUtils.sol
432 lines (379 loc) · 17.9 KB
/
BaseOrderUtils.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
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./Order.sol";
import "../market/Market.sol";
import "../data/DataStore.sol";
import "../event/EventEmitter.sol";
import "../order/OrderVault.sol";
import "../oracle/Oracle.sol";
import "../swap/SwapHandler.sol";
// @title Order
// @dev Library for common order functions used in OrderUtils, IncreaseOrderUtils
// DecreaseOrderUtils, SwapOrderUtils
library BaseOrderUtils {
using SafeCast for int256;
using SafeCast for uint256;
using Order for Order.Props;
using Price for Price.Props;
// @dev CreateOrderParams struct used in createOrder to avoid stack
// too deep errors
//
// @param addresses address values
// @param numbers number values
// @param orderType for order.orderType
// @param decreasePositionSwapType for order.decreasePositionSwapType
// @param isLong for order.isLong
// @param shouldUnwrapNativeToken for order.shouldUnwrapNativeToken
struct CreateOrderParams {
CreateOrderParamsAddresses addresses;
CreateOrderParamsNumbers numbers;
Order.OrderType orderType;
Order.DecreasePositionSwapType decreasePositionSwapType;
bool isLong;
bool shouldUnwrapNativeToken;
bytes32 referralCode;
}
// @param receiver for order.receiver
// @param callbackContract for order.callbackContract
// @param market for order.market
// @param initialCollateralToken for order.initialCollateralToken
// @param swapPath for order.swapPath
struct CreateOrderParamsAddresses {
address receiver;
address callbackContract;
address uiFeeReceiver;
address market;
address initialCollateralToken;
address[] swapPath;
}
// @param sizeDeltaUsd for order.sizeDeltaUsd
// @param triggerPrice for order.triggerPrice
// @param acceptablePrice for order.acceptablePrice
// @param executionFee for order.executionFee
// @param callbackGasLimit for order.callbackGasLimit
// @param minOutputAmount for order.minOutputAmount
struct CreateOrderParamsNumbers {
uint256 sizeDeltaUsd;
uint256 initialCollateralDeltaAmount;
uint256 triggerPrice;
uint256 acceptablePrice;
uint256 executionFee;
uint256 callbackGasLimit;
uint256 minOutputAmount;
}
// @dev ExecuteOrderParams struct used in executeOrder to avoid stack
// too deep errors
//
// @param contracts ExecuteOrderParamsContracts
// @param key the key of the order to execute
// @param order the order to execute
// @param swapPathMarkets the market values of the markets in the swapPath
// @param minOracleBlockNumbers the min oracle block numbers
// @param maxOracleBlockNumbers the max oracle block numbers
// @param market market values of the trading market
// @param keeper the keeper sending the transaction
// @param startingGas the starting gas
// @param positionKey the key of the order's position
struct ExecuteOrderParams {
ExecuteOrderParamsContracts contracts;
bytes32 key;
Order.Props order;
Market.Props[] swapPathMarkets;
uint256[] minOracleBlockNumbers;
uint256[] maxOracleBlockNumbers;
Market.Props market;
address keeper;
uint256 startingGas;
bytes32 positionKey;
}
// @param dataStore DataStore
// @param eventEmitter EventEmitter
// @param orderVault OrderVault
// @param oracle Oracle
// @param swapHandler SwapHandler
// @param referralStorage IReferralStorage
struct ExecuteOrderParamsContracts {
DataStore dataStore;
EventEmitter eventEmitter;
OrderVault orderVault;
Oracle oracle;
SwapHandler swapHandler;
IReferralStorage referralStorage;
}
// @dev check if an orderType is a market order
// @param orderType the order type
// @return whether an orderType is a market order
function isMarketOrder(Order.OrderType orderType) internal pure returns (bool) {
return orderType == Order.OrderType.MarketSwap ||
orderType == Order.OrderType.MarketIncrease ||
orderType == Order.OrderType.MarketDecrease ||
orderType == Order.OrderType.Liquidation;
}
// @dev check if an orderType is a limit order
// @param orderType the order type
// @return whether an orderType is a limit order
function isLimitOrder(Order.OrderType orderType) internal pure returns (bool) {
return orderType == Order.OrderType.LimitSwap ||
orderType == Order.OrderType.LimitIncrease ||
orderType == Order.OrderType.LimitDecrease;
}
// @dev check if an orderType is a swap order
// @param orderType the order type
// @return whether an orderType is a swap order
function isSwapOrder(Order.OrderType orderType) internal pure returns (bool) {
return orderType == Order.OrderType.MarketSwap ||
orderType == Order.OrderType.LimitSwap;
}
// @dev check if an orderType is a position order
// @param orderType the order type
// @return whether an orderType is a position order
function isPositionOrder(Order.OrderType orderType) internal pure returns (bool) {
return isIncreaseOrder(orderType) || isDecreaseOrder(orderType);
}
// @dev check if an orderType is an increase order
// @param orderType the order type
// @return whether an orderType is an increase order
function isIncreaseOrder(Order.OrderType orderType) internal pure returns (bool) {
return orderType == Order.OrderType.MarketIncrease ||
orderType == Order.OrderType.LimitIncrease;
}
// @dev check if an orderType is a decrease order
// @param orderType the order type
// @return whether an orderType is a decrease order
function isDecreaseOrder(Order.OrderType orderType) internal pure returns (bool) {
return orderType == Order.OrderType.MarketDecrease ||
orderType == Order.OrderType.LimitDecrease ||
orderType == Order.OrderType.StopLossDecrease ||
orderType == Order.OrderType.Liquidation;
}
// @dev check if an orderType is a liquidation order
// @param orderType the order type
// @return whether an orderType is a liquidation order
function isLiquidationOrder(Order.OrderType orderType) internal pure returns (bool) {
return orderType == Order.OrderType.Liquidation;
}
// @dev set the price for increase / decrease position orders
//
// for market orders, set the min and max values of the customPrice for the indexToken
// to either primaryPrice.min or primaryPrice.max depending on whether the order
// is an increase or decrease and whether it is for a long or short
//
// customPrice.min and customPrice.max will be equal in this case
// this is because in getExecutionPrice the function will try to use the closest price which can fulfill
// the order, if customPrice.min is set to primaryPrice.min and customPrice.max is set to primaryPrice.max
// getExecutionPrice will pick a better price than what should be possible
//
// for limit orders, the the min and max value will be set to the triggerPrice
// and primaryPrice value, this represents the price that the user desired the order
// to be fulfilled at and the best oracle price that the order can be fulfilled at
//
// for stop-loss orders, the min and max value will be set to the triggerPrice value
// the primaryPrice and secondaryPrice are not used because the primaryPrice is a stale
// value and cannot be used as it would result in executing at a better price than what
// should be possible, the secondaryPrice is a worse price than the triggerPrice, so
// it should not need to be considered
//
// getExecutionPrice handles the logic for selecting the execution price to use
//
// @param oracle Oracle
// @param indexToken the index token
// @param orderType the order type
// @param triggerPrice the order's triggerPrice
// @param isLong whether the order is for a long or short
function setExactOrderPrice(
Oracle oracle,
address indexToken,
Order.OrderType orderType,
uint256 triggerPrice,
bool isLong
) internal {
if (isSwapOrder(orderType)) {
return;
}
bool isIncrease = isIncreaseOrder(orderType);
// increase order:
// - long: use the larger price
// - short: use the smaller price
// decrease order:
// - long: use the smaller price
// - short: use the larger price
bool shouldUseMaxPrice = isIncrease ? isLong : !isLong;
if (orderType == Order.OrderType.MarketIncrease ||
orderType == Order.OrderType.MarketDecrease ||
orderType == Order.OrderType.Liquidation) {
Price.Props memory price = oracle.getPrimaryPrice(indexToken);
oracle.setCustomPrice(indexToken, Price.Props(
price.pickPrice(shouldUseMaxPrice),
price.pickPrice(shouldUseMaxPrice)
));
return;
}
if (orderType == Order.OrderType.LimitIncrease ||
orderType == Order.OrderType.LimitDecrease
) {
uint256 primaryPrice = oracle.getPrimaryPrice(indexToken).pickPrice(shouldUseMaxPrice);
// for limit increase orders:
// - long: validate primaryPrice < triggerPrice
// - short: validate primaryPrice > triggerPrice
// for limit decrease orders:
// - long: validate primaryPrice > triggerPrice
// - short: validate primaryPrice < triggerPrice
bool shouldValidateSmallerPrimaryPrice = shouldUseMaxPrice;
bool ok = shouldValidateSmallerPrimaryPrice ? primaryPrice <= triggerPrice : primaryPrice >= triggerPrice;
if (!ok) {
revert Errors.InvalidLimitOrderPrices(primaryPrice, triggerPrice, shouldValidateSmallerPrimaryPrice);
}
if (shouldValidateSmallerPrimaryPrice) {
oracle.setCustomPrice(indexToken, Price.Props(
primaryPrice, // min price that order can be executed with
triggerPrice // max price that order can be executed with
));
} else {
oracle.setCustomPrice(indexToken, Price.Props(
triggerPrice, // min price that order can be executed with
primaryPrice // max price that order can be executed with
));
}
return;
}
if (orderType == Order.OrderType.StopLossDecrease) {
uint256 primaryPrice = oracle.getPrimaryPrice(indexToken).pickPrice(shouldUseMaxPrice);
uint256 secondaryPrice = oracle.getSecondaryPrice(indexToken).pickPrice(shouldUseMaxPrice);
// for stop-loss decrease orders:
// - long: validate descending price
// - short: validate ascending price
bool shouldValidateAscendingPrice = !isLong;
bool ok = shouldValidateAscendingPrice ?
(primaryPrice <= triggerPrice && triggerPrice <= secondaryPrice) :
(primaryPrice >= triggerPrice && triggerPrice >= secondaryPrice);
if (!ok) {
revert Errors.InvalidStopLossOrderPrices(primaryPrice, secondaryPrice, triggerPrice, shouldValidateAscendingPrice);
}
if (shouldValidateAscendingPrice) {
oracle.setCustomPrice(indexToken, Price.Props(
triggerPrice, // min price that order can be executed with
triggerPrice // max price that order can be executed with
));
} else {
oracle.setCustomPrice(indexToken, Price.Props(
triggerPrice, // min price that order can be executed with
triggerPrice // max price that order can be executed with
));
}
return;
}
revert Errors.UnsupportedOrderType();
}
// @dev get the execution price for an order
//
// see setExactOrderPrice for information on the customPrice values
//
// for limit / stop-loss orders, the triggerPrice is returned here if it can
// fulfill the acceptablePrice after factoring in price impact
//
// if the triggerPrice cannot fulfill the acceptablePrice, check if the acceptablePrice
// can be fulfilled using the best oracle price after factoring in price impact
// if it can be fulfilled, fulfill the order at the acceptablePrice
//
// @param customIndexTokenPrice the custom price of the index token
// @param sizeDeltaUsd the order.sizeDeltaUsd
// @param priceImpactUsd the price impact of the order
// @param acceptablePrice the order.acceptablePrice
// @param isLong whether this is for a long or short order
// @param isIncrease whether this is for an increase or decrease order
// @return the execution price
function getExecutionPrice(
Price.Props memory customIndexTokenPrice,
uint256 sizeDeltaUsd,
int256 priceImpactUsd,
uint256 acceptablePrice,
bool isLong,
bool isIncrease
) internal pure returns (uint256) {
// increase order:
// - long: use the larger price
// - short: use the smaller price
// decrease order:
// - long: use the smaller price
// - short: use the larger price
bool shouldUseMaxPrice = isIncrease ? isLong : !isLong;
// should price be smaller than acceptablePrice
// increase order:
// - long: price should be smaller than acceptablePrice
// - short: price should be larger than acceptablePrice
// decrease order:
// - long: price should be larger than acceptablePrice
// - short: price should be smaller than acceptablePrice
bool shouldPriceBeSmaller = isIncrease ? isLong : !isLong;
// for market orders, customIndexTokenPrice.min and customIndexTokenPrice.max should
// be equal, see setExactOrderPrice for more info
// for limit orders, customIndexTokenPrice contains the triggerPrice and the best oracle
// price, we first attempt to fulfill the order using the triggerPrice
uint256 price = customIndexTokenPrice.pickPrice(shouldUseMaxPrice);
// increase order:
// - long: lower price for positive impact, higher price for negative impact
// - short: higher price for positive impact, lower price for negative impact
// decrease order:
// - long: higher price for positive impact, lower price for negative impact
// - short: lower price for positive impact, higher price for negative impact
bool shouldFlipPriceImpactUsd = isIncrease ? isLong : !isLong;
int256 priceImpactUsdForPriceAdjustment = shouldFlipPriceImpactUsd ? -priceImpactUsd : priceImpactUsd;
if (priceImpactUsdForPriceAdjustment < 0 && (-priceImpactUsdForPriceAdjustment).toUint256() > sizeDeltaUsd) {
revert Errors.PriceImpactLargerThanOrderSize(priceImpactUsdForPriceAdjustment, sizeDeltaUsd);
}
// adjust price by price impact
if (sizeDeltaUsd > 0) {
price = price * Calc.sumReturnUint256(sizeDeltaUsd, priceImpactUsdForPriceAdjustment) / sizeDeltaUsd;
}
if (shouldPriceBeSmaller && price <= acceptablePrice) {
return price;
}
if (!shouldPriceBeSmaller && price >= acceptablePrice) {
return price;
}
// if the order could not be fulfilled using the triggerPrice
// check if the best oracle price can fulfill the order
price = customIndexTokenPrice.pickPrice(!shouldUseMaxPrice);
// adjust price by price impact
if (sizeDeltaUsd > 0) {
price = price * Calc.sumReturnUint256(sizeDeltaUsd, priceImpactUsdForPriceAdjustment) / sizeDeltaUsd;
}
if (shouldPriceBeSmaller && price <= acceptablePrice) {
return acceptablePrice;
}
if (!shouldPriceBeSmaller && price >= acceptablePrice) {
return acceptablePrice;
}
// the setExactOrderPrice function should have validated if the price fulfills
// the order's trigger price
//
// for decrease orders, the price impact should already be capped, so if the user
// had set an acceptable price within the range of the capped price impact, then
// the order should be fulfillable at the acceptable price
//
// for increase orders, the negative price impact is not capped
//
// for both increase and decrease orders, if it is due to price impact that the
// order cannot be fulfilled then the order should be frozen
//
// this is to prevent gaming by manipulation of the price impact value
//
// usually it should be costly to game the price impact value
// however, for certain cases, e.g. a user already has a large position opened
// the user may create limit orders that would only trigger after they close
// their position, this gives the user the option to cancel the pending order if
// prices do not move in their favour or to close their position and let the order
// execute if prices move in their favour
revert Errors.OrderNotFulfillableDueToPriceImpact(price, acceptablePrice);
}
// @dev validate that an order exists
// @param order the order to check
function validateNonEmptyOrder(Order.Props memory order) internal pure {
if (order.account() == address(0)) {
revert Errors.EmptyOrder();
}
if (order.sizeDeltaUsd() == 0 && order.initialCollateralDeltaAmount() == 0) {
revert Errors.EmptyOrder();
}
}
}