@drift-labs/sdk 0.2.0-master.0 → 0.2.0-master.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/lib/admin.d.ts +8 -5
  2. package/lib/admin.js +43 -11
  3. package/lib/clearingHouse.d.ts +28 -18
  4. package/lib/clearingHouse.js +366 -143
  5. package/lib/clearingHouseUser.d.ts +2 -2
  6. package/lib/clearingHouseUser.js +8 -17
  7. package/lib/config.js +1 -1
  8. package/lib/constants/banks.js +9 -2
  9. package/lib/constants/numericConstants.d.ts +2 -0
  10. package/lib/constants/numericConstants.js +3 -1
  11. package/lib/factory/bigNum.d.ts +8 -2
  12. package/lib/factory/bigNum.js +14 -6
  13. package/lib/idl/clearing_house.json +805 -202
  14. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  15. package/lib/index.d.ts +3 -2
  16. package/lib/index.js +7 -2
  17. package/lib/math/amm.d.ts +6 -1
  18. package/lib/math/amm.js +124 -41
  19. package/lib/math/auction.js +4 -1
  20. package/lib/math/orders.d.ts +2 -2
  21. package/lib/math/orders.js +18 -11
  22. package/lib/math/position.js +3 -1
  23. package/lib/math/repeg.js +1 -1
  24. package/lib/math/trade.d.ts +1 -1
  25. package/lib/math/trade.js +7 -10
  26. package/lib/orderParams.d.ts +14 -5
  27. package/lib/orderParams.js +8 -96
  28. package/lib/orders.d.ts +1 -2
  29. package/lib/orders.js +6 -85
  30. package/lib/slot/SlotSubscriber.d.ts +7 -0
  31. package/lib/slot/SlotSubscriber.js +3 -0
  32. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +7 -5
  33. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +41 -40
  34. package/lib/tx/utils.js +1 -1
  35. package/lib/types.d.ts +137 -14
  36. package/lib/types.js +53 -1
  37. package/lib/util/computeUnits.js +1 -1
  38. package/package.json +3 -3
  39. package/src/accounts/bulkAccountLoader.js +197 -0
  40. package/src/accounts/bulkUserSubscription.js +33 -0
  41. package/src/accounts/fetch.js +29 -0
  42. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  43. package/src/accounts/pollingOracleSubscriber.js +93 -0
  44. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  45. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  46. package/src/accounts/types.js +10 -0
  47. package/src/accounts/utils.js +7 -0
  48. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  49. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  50. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  51. package/src/addresses/marketAddresses.js +26 -0
  52. package/src/addresses/pda.js +104 -0
  53. package/src/admin.ts +66 -14
  54. package/src/assert/assert.js +9 -0
  55. package/src/clearingHouse.ts +558 -230
  56. package/src/clearingHouseUser.ts +12 -23
  57. package/src/config.ts +1 -1
  58. package/src/constants/banks.ts +9 -2
  59. package/src/constants/numericConstants.ts +2 -0
  60. package/src/events/eventList.js +77 -0
  61. package/src/events/eventSubscriber.js +139 -0
  62. package/src/events/fetchLogs.js +50 -0
  63. package/src/events/pollingLogProvider.js +64 -0
  64. package/src/events/sort.js +44 -0
  65. package/src/events/txEventCache.js +71 -0
  66. package/src/events/types.js +20 -0
  67. package/src/events/webSocketLogProvider.js +41 -0
  68. package/src/examples/makeTradeExample.js +80 -0
  69. package/src/factory/bigNum.js +364 -0
  70. package/src/factory/bigNum.ts +26 -9
  71. package/src/factory/oracleClient.js +20 -0
  72. package/src/idl/clearing_house.json +805 -202
  73. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  74. package/src/index.js +100 -0
  75. package/src/index.ts +3 -2
  76. package/src/math/amm.js +369 -0
  77. package/src/math/amm.ts +207 -52
  78. package/src/math/auction.js +42 -0
  79. package/src/math/auction.ts +5 -1
  80. package/src/math/bankBalance.js +75 -0
  81. package/src/math/conversion.js +11 -0
  82. package/src/math/funding.js +248 -0
  83. package/src/math/market.js +57 -0
  84. package/src/math/oracles.js +26 -0
  85. package/src/math/orders.js +110 -0
  86. package/src/math/orders.ts +17 -13
  87. package/src/math/position.js +140 -0
  88. package/src/math/position.ts +5 -1
  89. package/src/math/repeg.js +128 -0
  90. package/src/math/repeg.ts +2 -1
  91. package/src/math/state.js +15 -0
  92. package/src/math/trade.js +253 -0
  93. package/src/math/trade.ts +23 -25
  94. package/src/math/utils.js +0 -1
  95. package/src/mockUSDCFaucet.js +280 -0
  96. package/src/oracles/oracleClientCache.js +19 -0
  97. package/src/oracles/pythClient.js +46 -0
  98. package/src/oracles/quoteAssetOracleClient.js +32 -0
  99. package/src/oracles/switchboardClient.js +69 -0
  100. package/src/oracles/types.js +2 -0
  101. package/src/orderParams.js +20 -0
  102. package/src/orderParams.ts +20 -141
  103. package/src/orders.js +134 -0
  104. package/src/orders.ts +7 -131
  105. package/src/slot/SlotSubscriber.js +39 -0
  106. package/src/slot/SlotSubscriber.ts +11 -1
  107. package/src/token/index.js +38 -0
  108. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +48 -59
  109. package/src/tx/retryTxSender.js +188 -0
  110. package/src/tx/types.js +2 -0
  111. package/src/tx/utils.js +17 -0
  112. package/src/tx/utils.ts +1 -1
  113. package/src/types.js +114 -0
  114. package/src/types.ts +132 -16
  115. package/src/userName.js +20 -0
  116. package/src/util/computeUnits.ts +1 -1
  117. package/src/util/promiseTimeout.js +14 -0
  118. package/src/util/tps.js +27 -0
  119. package/src/wallet.js +35 -0
  120. package/src/util/computeUnits.js +0 -17
  121. package/src/util/computeUnits.js.map +0 -1
@@ -0,0 +1,248 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.calculateFundingPool = exports.calculateLongShortFundingRateAndLiveTwaps = exports.calculateLongShortFundingRate = exports.calculateEstimatedFundingRate = exports.calculateAllEstimatedFundingRate = void 0;
13
+ const anchor_1 = require("@project-serum/anchor");
14
+ const numericConstants_1 = require("../constants/numericConstants");
15
+ const market_1 = require("./market");
16
+ /**
17
+ *
18
+ * @param market
19
+ * @param oraclePriceData
20
+ * @param periodAdjustment
21
+ * @returns Estimated funding rate. : Precision //TODO-PRECISION
22
+ */
23
+ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ // periodAdjustment
26
+ // 1: hourly
27
+ // 24: daily
28
+ // 24 * 365.25: annualized
29
+ const secondsInHour = new anchor_1.BN(3600);
30
+ const hoursInDay = new anchor_1.BN(24);
31
+ const ONE = new anchor_1.BN(1);
32
+ if (!market.initialized) {
33
+ return [numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO];
34
+ }
35
+ const payFreq = new anchor_1.BN(market.amm.fundingPeriod);
36
+ // todo: sufficiently differs from blockchain timestamp?
37
+ const now = new anchor_1.BN((Date.now() / 1000).toFixed(0));
38
+ const timeSinceLastUpdate = now.sub(market.amm.lastFundingRateTs);
39
+ // calculate real-time mark twap
40
+ const lastMarkTwapWithMantissa = market.amm.lastMarkPriceTwap;
41
+ const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
42
+ const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
43
+ const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, anchor_1.BN.max(numericConstants_1.ZERO, secondsInHour.sub(timeSinceLastMarkChange)));
44
+ const baseAssetPriceWithMantissa = market_1.calculateMarkPrice(market, oraclePriceData);
45
+ const markTwapWithMantissa = markTwapTimeSinceLastUpdate
46
+ .mul(lastMarkTwapWithMantissa)
47
+ .add(timeSinceLastMarkChange.mul(baseAssetPriceWithMantissa))
48
+ .div(timeSinceLastMarkChange.add(markTwapTimeSinceLastUpdate));
49
+ // calculate real-time (predicted) oracle twap
50
+ // note: oracle twap depends on `when the chord is struck` (market is trade)
51
+ const lastOracleTwapWithMantissa = market.amm.lastOraclePriceTwap;
52
+ const lastOraclePriceTwapTs = market.amm.lastOraclePriceTwapTs;
53
+ const oracleInvalidDuration = anchor_1.BN.max(numericConstants_1.ZERO, lastMarkPriceTwapTs.sub(lastOraclePriceTwapTs));
54
+ const timeSinceLastOracleTwapUpdate = now.sub(lastOraclePriceTwapTs);
55
+ const oracleTwapTimeSinceLastUpdate = anchor_1.BN.max(ONE, anchor_1.BN.min(secondsInHour, anchor_1.BN.max(ONE, secondsInHour.sub(timeSinceLastOracleTwapUpdate))));
56
+ let oracleTwapWithMantissa = lastOracleTwapWithMantissa;
57
+ // if passing live oracle data, improve predicted calc estimate
58
+ if (oraclePriceData) {
59
+ const oraclePrice = oraclePriceData.price;
60
+ const oracleLiveVsTwap = oraclePrice
61
+ .sub(lastOracleTwapWithMantissa)
62
+ .abs()
63
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
64
+ .mul(new anchor_1.BN(100))
65
+ .div(lastOracleTwapWithMantissa);
66
+ // verify pyth live input is within 10% of last twap for live update
67
+ if (oracleLiveVsTwap.lte(numericConstants_1.MARK_PRICE_PRECISION.mul(new anchor_1.BN(10)))) {
68
+ oracleTwapWithMantissa = oracleTwapTimeSinceLastUpdate
69
+ .mul(lastOracleTwapWithMantissa)
70
+ .add(timeSinceLastMarkChange.mul(oraclePrice))
71
+ .div(timeSinceLastMarkChange.add(oracleTwapTimeSinceLastUpdate));
72
+ }
73
+ }
74
+ const shrunkLastOracleTwapwithMantissa = oracleTwapTimeSinceLastUpdate
75
+ .mul(lastOracleTwapWithMantissa)
76
+ .add(oracleInvalidDuration.mul(lastMarkTwapWithMantissa))
77
+ .div(oracleTwapTimeSinceLastUpdate.add(oracleInvalidDuration));
78
+ const twapSpread = lastMarkTwapWithMantissa.sub(shrunkLastOracleTwapwithMantissa);
79
+ const twapSpreadPct = twapSpread
80
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
81
+ .mul(new anchor_1.BN(100))
82
+ .div(shrunkLastOracleTwapwithMantissa);
83
+ const lowerboundEst = twapSpreadPct
84
+ .mul(payFreq)
85
+ .mul(anchor_1.BN.min(secondsInHour, timeSinceLastUpdate))
86
+ .mul(periodAdjustment)
87
+ .div(secondsInHour)
88
+ .div(secondsInHour)
89
+ .div(hoursInDay);
90
+ const interpEst = twapSpreadPct.mul(periodAdjustment).div(hoursInDay);
91
+ const interpRateQuote = twapSpreadPct
92
+ .mul(periodAdjustment)
93
+ .div(hoursInDay)
94
+ .div(numericConstants_1.MARK_PRICE_PRECISION.div(numericConstants_1.QUOTE_PRECISION));
95
+ let feePoolSize = calculateFundingPool(market);
96
+ if (interpRateQuote.lt(new anchor_1.BN(0))) {
97
+ feePoolSize = feePoolSize.mul(new anchor_1.BN(-1));
98
+ }
99
+ let cappedAltEst;
100
+ let largerSide;
101
+ let smallerSide;
102
+ if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort.abs())) {
103
+ largerSide = market.baseAssetAmountLong.abs();
104
+ smallerSide = market.baseAssetAmountShort.abs();
105
+ if (twapSpread.gt(new anchor_1.BN(0))) {
106
+ return [
107
+ markTwapWithMantissa,
108
+ oracleTwapWithMantissa,
109
+ lowerboundEst,
110
+ interpEst,
111
+ interpEst,
112
+ ];
113
+ }
114
+ }
115
+ else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort.abs())) {
116
+ largerSide = market.baseAssetAmountShort.abs();
117
+ smallerSide = market.baseAssetAmountLong.abs();
118
+ if (twapSpread.lt(new anchor_1.BN(0))) {
119
+ return [
120
+ markTwapWithMantissa,
121
+ oracleTwapWithMantissa,
122
+ lowerboundEst,
123
+ interpEst,
124
+ interpEst,
125
+ ];
126
+ }
127
+ }
128
+ else {
129
+ return [
130
+ markTwapWithMantissa,
131
+ oracleTwapWithMantissa,
132
+ lowerboundEst,
133
+ interpEst,
134
+ interpEst,
135
+ ];
136
+ }
137
+ if (largerSide.gt(numericConstants_1.ZERO)) {
138
+ // funding smaller flow
139
+ cappedAltEst = smallerSide.mul(twapSpread).div(hoursInDay);
140
+ const feePoolTopOff = feePoolSize
141
+ .mul(numericConstants_1.MARK_PRICE_PRECISION.div(numericConstants_1.QUOTE_PRECISION))
142
+ .mul(numericConstants_1.AMM_RESERVE_PRECISION);
143
+ cappedAltEst = cappedAltEst.add(feePoolTopOff).div(largerSide);
144
+ cappedAltEst = cappedAltEst
145
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
146
+ .mul(new anchor_1.BN(100))
147
+ .div(oracleTwapWithMantissa)
148
+ .mul(periodAdjustment);
149
+ if (cappedAltEst.abs().gte(interpEst.abs())) {
150
+ cappedAltEst = interpEst;
151
+ }
152
+ }
153
+ else {
154
+ cappedAltEst = interpEst;
155
+ }
156
+ return [
157
+ markTwapWithMantissa,
158
+ oracleTwapWithMantissa,
159
+ lowerboundEst,
160
+ cappedAltEst,
161
+ interpEst,
162
+ ];
163
+ });
164
+ }
165
+ exports.calculateAllEstimatedFundingRate = calculateAllEstimatedFundingRate;
166
+ /**
167
+ *
168
+ * @param market
169
+ * @param oraclePriceData
170
+ * @param periodAdjustment
171
+ * @param estimationMethod
172
+ * @returns Estimated funding rate. : Precision //TODO-PRECISION
173
+ */
174
+ function calculateEstimatedFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1), estimationMethod) {
175
+ return __awaiter(this, void 0, void 0, function* () {
176
+ const [_1, _2, lowerboundEst, cappedAltEst, interpEst] = yield calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
177
+ if (estimationMethod == 'lowerbound') {
178
+ //assuming remaining funding period has no gap
179
+ return lowerboundEst;
180
+ }
181
+ else if (estimationMethod == 'capped') {
182
+ return cappedAltEst;
183
+ }
184
+ else {
185
+ return interpEst;
186
+ }
187
+ });
188
+ }
189
+ exports.calculateEstimatedFundingRate = calculateEstimatedFundingRate;
190
+ /**
191
+ *
192
+ * @param market
193
+ * @param oraclePriceData
194
+ * @param periodAdjustment
195
+ * @returns Estimated funding rate. : Precision //TODO-PRECISION
196
+ */
197
+ function calculateLongShortFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
198
+ return __awaiter(this, void 0, void 0, function* () {
199
+ const [_1, _2, _, cappedAltEst, interpEst] = yield calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
200
+ if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort)) {
201
+ return [cappedAltEst, interpEst];
202
+ }
203
+ else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort)) {
204
+ return [interpEst, cappedAltEst];
205
+ }
206
+ else {
207
+ return [interpEst, interpEst];
208
+ }
209
+ });
210
+ }
211
+ exports.calculateLongShortFundingRate = calculateLongShortFundingRate;
212
+ /**
213
+ *
214
+ * @param market
215
+ * @param oraclePriceData
216
+ * @param periodAdjustment
217
+ * @returns Estimated funding rate. : Precision //TODO-PRECISION
218
+ */
219
+ function calculateLongShortFundingRateAndLiveTwaps(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
220
+ return __awaiter(this, void 0, void 0, function* () {
221
+ const [markTwapLive, oracleTwapLive, _2, cappedAltEst, interpEst] = yield calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustment);
222
+ if (market.baseAssetAmountLong.gt(market.baseAssetAmountShort.abs())) {
223
+ return [markTwapLive, oracleTwapLive, cappedAltEst, interpEst];
224
+ }
225
+ else if (market.baseAssetAmountLong.lt(market.baseAssetAmountShort.abs())) {
226
+ return [markTwapLive, oracleTwapLive, interpEst, cappedAltEst];
227
+ }
228
+ else {
229
+ return [markTwapLive, oracleTwapLive, interpEst, interpEst];
230
+ }
231
+ });
232
+ }
233
+ exports.calculateLongShortFundingRateAndLiveTwaps = calculateLongShortFundingRateAndLiveTwaps;
234
+ /**
235
+ *
236
+ * @param market
237
+ * @returns Estimated fee pool size
238
+ */
239
+ function calculateFundingPool(market) {
240
+ // todo
241
+ const totalFeeLB = market.amm.totalExchangeFee.div(new anchor_1.BN(2));
242
+ const feePool = anchor_1.BN.max(numericConstants_1.ZERO, market.amm.totalFeeMinusDistributions
243
+ .sub(totalFeeLB)
244
+ .mul(new anchor_1.BN(1))
245
+ .div(new anchor_1.BN(3)));
246
+ return feePool;
247
+ }
248
+ exports.calculateFundingPool = calculateFundingPool;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.calculateOracleSpread = exports.calculateMarkOracleSpread = exports.calculateNewMarketAfterTrade = exports.calculateAskPrice = exports.calculateBidPrice = exports.calculateMarkPrice = void 0;
4
+ const types_1 = require("../types");
5
+ const amm_1 = require("./amm");
6
+ /**
7
+ * Calculates market mark price
8
+ *
9
+ * @param market
10
+ * @return markPrice : Precision MARK_PRICE_PRECISION
11
+ */
12
+ function calculateMarkPrice(market, oraclePriceData) {
13
+ const newAmm = amm_1.calculateUpdatedAMM(market.amm, oraclePriceData);
14
+ return amm_1.calculatePrice(newAmm.baseAssetReserve, newAmm.quoteAssetReserve, newAmm.pegMultiplier);
15
+ }
16
+ exports.calculateMarkPrice = calculateMarkPrice;
17
+ /**
18
+ * Calculates market bid price
19
+ *
20
+ * @param market
21
+ * @return bidPrice : Precision MARK_PRICE_PRECISION
22
+ */
23
+ function calculateBidPrice(market, oraclePriceData) {
24
+ const { baseAssetReserve, quoteAssetReserve, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, types_1.PositionDirection.SHORT, oraclePriceData);
25
+ return amm_1.calculatePrice(baseAssetReserve, quoteAssetReserve, newPeg);
26
+ }
27
+ exports.calculateBidPrice = calculateBidPrice;
28
+ /**
29
+ * Calculates market ask price
30
+ *
31
+ * @param market
32
+ * @return bidPrice : Precision MARK_PRICE_PRECISION
33
+ */
34
+ function calculateAskPrice(market, oraclePriceData) {
35
+ const { baseAssetReserve, quoteAssetReserve, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, types_1.PositionDirection.LONG, oraclePriceData);
36
+ return amm_1.calculatePrice(baseAssetReserve, quoteAssetReserve, newPeg);
37
+ }
38
+ exports.calculateAskPrice = calculateAskPrice;
39
+ function calculateNewMarketAfterTrade(baseAssetAmount, direction, market) {
40
+ const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', baseAssetAmount.abs(), amm_1.getSwapDirection('base', direction));
41
+ const newAmm = Object.assign({}, market.amm);
42
+ const newMarket = Object.assign({}, market);
43
+ newMarket.amm = newAmm;
44
+ newMarket.amm.quoteAssetReserve = newQuoteAssetReserve;
45
+ newMarket.amm.baseAssetReserve = newBaseAssetReserve;
46
+ return newMarket;
47
+ }
48
+ exports.calculateNewMarketAfterTrade = calculateNewMarketAfterTrade;
49
+ function calculateMarkOracleSpread(market, oraclePriceData) {
50
+ const markPrice = calculateMarkPrice(market, oraclePriceData);
51
+ return calculateOracleSpread(markPrice, oraclePriceData);
52
+ }
53
+ exports.calculateMarkOracleSpread = calculateMarkOracleSpread;
54
+ function calculateOracleSpread(price, oraclePriceData) {
55
+ return price.sub(oraclePriceData.price);
56
+ }
57
+ exports.calculateOracleSpread = calculateOracleSpread;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isOracleValid = void 0;
4
+ const numericConstants_1 = require("../constants/numericConstants");
5
+ const index_1 = require("../index");
6
+ function isOracleValid(amm, oraclePriceData, oracleGuardRails, slot) {
7
+ const isOraclePriceNonPositive = oraclePriceData.price.lt(numericConstants_1.ZERO);
8
+ const isOraclePriceTooVolatile = oraclePriceData.price
9
+ .div(index_1.BN.max(numericConstants_1.ONE, amm.lastOraclePriceTwap))
10
+ .gt(oracleGuardRails.validity.tooVolatileRatio) ||
11
+ amm.lastOraclePriceTwap
12
+ .div(index_1.BN.max(numericConstants_1.ONE, oraclePriceData.price))
13
+ .gt(oracleGuardRails.validity.tooVolatileRatio);
14
+ const isConfidenceTooLarge = oraclePriceData.price
15
+ .div(index_1.BN.max(numericConstants_1.ONE, oraclePriceData.confidence))
16
+ .lt(oracleGuardRails.validity.confidenceIntervalMaxSize);
17
+ const oracleIsStale = oraclePriceData.slot
18
+ .sub(new index_1.BN(slot))
19
+ .gt(oracleGuardRails.validity.slotsBeforeStale);
20
+ return !(!oraclePriceData.hasSufficientNumberOfDataPoints ||
21
+ oracleIsStale ||
22
+ isOraclePriceNonPositive ||
23
+ isOraclePriceTooVolatile ||
24
+ isConfidenceTooLarge);
25
+ }
26
+ exports.isOracleValid = isOracleValid;
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getLimitPrice = exports.standardizeBaseAssetAmount = exports.isOrderReduceOnly = exports.isOrderRiskIncreasingInSameDirection = exports.isOrderRiskIncreasing = void 0;
4
+ const types_1 = require("../types");
5
+ const numericConstants_1 = require("../constants/numericConstants");
6
+ const anchor_1 = require("@project-serum/anchor");
7
+ const auction_1 = require("./auction");
8
+ const market_1 = require("./market");
9
+ function isOrderRiskIncreasing(user, order) {
10
+ if (types_1.isVariant(order.status, 'init')) {
11
+ return false;
12
+ }
13
+ const position = user.getUserPosition(order.marketIndex) ||
14
+ user.getEmptyPosition(order.marketIndex);
15
+ // if no position exists, it's risk increasing
16
+ if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
17
+ return true;
18
+ }
19
+ // if position is long and order is long
20
+ if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && types_1.isVariant(order.direction, 'long')) {
21
+ return true;
22
+ }
23
+ // if position is short and order is short
24
+ if (position.baseAssetAmount.lt(numericConstants_1.ZERO) &&
25
+ types_1.isVariant(order.direction, 'short')) {
26
+ return true;
27
+ }
28
+ const baseAssetAmountToFill = order.baseAssetAmount.sub(order.baseAssetAmountFilled);
29
+ // if order will flip position
30
+ if (baseAssetAmountToFill.gt(position.baseAssetAmount.abs().mul(numericConstants_1.TWO))) {
31
+ return true;
32
+ }
33
+ return false;
34
+ }
35
+ exports.isOrderRiskIncreasing = isOrderRiskIncreasing;
36
+ function isOrderRiskIncreasingInSameDirection(user, order) {
37
+ if (types_1.isVariant(order.status, 'init')) {
38
+ return false;
39
+ }
40
+ const position = user.getUserPosition(order.marketIndex) ||
41
+ user.getEmptyPosition(order.marketIndex);
42
+ // if no position exists, it's risk increasing
43
+ if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
44
+ return true;
45
+ }
46
+ // if position is long and order is long
47
+ if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && types_1.isVariant(order.direction, 'long')) {
48
+ return true;
49
+ }
50
+ // if position is short and order is short
51
+ if (position.baseAssetAmount.lt(numericConstants_1.ZERO) &&
52
+ types_1.isVariant(order.direction, 'short')) {
53
+ return true;
54
+ }
55
+ return false;
56
+ }
57
+ exports.isOrderRiskIncreasingInSameDirection = isOrderRiskIncreasingInSameDirection;
58
+ function isOrderReduceOnly(user, order) {
59
+ if (types_1.isVariant(order.status, 'init')) {
60
+ return false;
61
+ }
62
+ const position = user.getUserPosition(order.marketIndex) ||
63
+ user.getEmptyPosition(order.marketIndex);
64
+ // if position is long and order is long
65
+ if (position.baseAssetAmount.gte(numericConstants_1.ZERO) &&
66
+ types_1.isVariant(order.direction, 'long')) {
67
+ return false;
68
+ }
69
+ // if position is short and order is short
70
+ if (position.baseAssetAmount.lte(numericConstants_1.ZERO) &&
71
+ types_1.isVariant(order.direction, 'short')) {
72
+ return false;
73
+ }
74
+ return true;
75
+ }
76
+ exports.isOrderReduceOnly = isOrderReduceOnly;
77
+ function standardizeBaseAssetAmount(baseAssetAmount, stepSize) {
78
+ const remainder = baseAssetAmount.mod(stepSize);
79
+ return baseAssetAmount.sub(remainder);
80
+ }
81
+ exports.standardizeBaseAssetAmount = standardizeBaseAssetAmount;
82
+ function getLimitPrice(order, market, oraclePriceData, slot) {
83
+ let limitPrice;
84
+ if (!order.oraclePriceOffset.eq(numericConstants_1.ZERO)) {
85
+ limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
86
+ }
87
+ else if (types_1.isOneOfVariant(order.orderType, ['market', 'triggerMarket'])) {
88
+ if (auction_1.isAuctionComplete(order, slot)) {
89
+ limitPrice = auction_1.getAuctionPrice(order, slot);
90
+ }
91
+ else if (!order.price.eq(numericConstants_1.ZERO)) {
92
+ limitPrice = order.price;
93
+ }
94
+ else if (types_1.isVariant(order.direction, 'long')) {
95
+ const askPrice = market_1.calculateAskPrice(market, oraclePriceData);
96
+ const delta = askPrice.div(new anchor_1.BN(market.amm.maxSlippageRatio));
97
+ limitPrice = askPrice.add(delta);
98
+ }
99
+ else {
100
+ const bidPrice = market_1.calculateBidPrice(market, oraclePriceData);
101
+ const delta = bidPrice.div(new anchor_1.BN(market.amm.maxSlippageRatio));
102
+ limitPrice = bidPrice.sub(delta);
103
+ }
104
+ }
105
+ else {
106
+ limitPrice = order.price;
107
+ }
108
+ return limitPrice;
109
+ }
110
+ exports.getLimitPrice = getLimitPrice;
@@ -1,9 +1,10 @@
1
1
  import { ClearingHouseUser } from '../clearingHouseUser';
2
- import { isVariant, Order } from '../types';
2
+ import { isOneOfVariant, isVariant, MarketAccount, Order } from '../types';
3
3
  import { ZERO, TWO } from '../constants/numericConstants';
4
4
  import { BN } from '@project-serum/anchor';
5
5
  import { OraclePriceData } from '../oracles/types';
6
- import { getAuctionPrice } from './auction';
6
+ import { getAuctionPrice, isAuctionComplete } from './auction';
7
+ import { calculateAskPrice, calculateBidPrice } from './market';
7
8
 
8
9
  export function isOrderRiskIncreasing(
9
10
  user: ClearingHouseUser,
@@ -120,24 +121,27 @@ export function standardizeBaseAssetAmount(
120
121
 
121
122
  export function getLimitPrice(
122
123
  order: Order,
124
+ market: MarketAccount,
123
125
  oraclePriceData: OraclePriceData,
124
126
  slot: number
125
127
  ): BN {
126
128
  let limitPrice;
127
129
  if (!order.oraclePriceOffset.eq(ZERO)) {
128
- const floatingPrice = oraclePriceData.price.add(order.oraclePriceOffset);
129
- if (order.postOnly) {
130
- limitPrice = isVariant(order.direction, 'long')
131
- ? BN.min(order.price, floatingPrice)
132
- : BN.max(order.price, floatingPrice);
130
+ limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
131
+ } else if (isOneOfVariant(order.orderType, ['market', 'triggerMarket'])) {
132
+ if (isAuctionComplete(order, slot)) {
133
+ limitPrice = getAuctionPrice(order, slot);
134
+ } else if (!order.price.eq(ZERO)) {
135
+ limitPrice = order.price;
136
+ } else if (isVariant(order.direction, 'long')) {
137
+ const askPrice = calculateAskPrice(market, oraclePriceData);
138
+ const delta = askPrice.div(new BN(market.amm.maxSlippageRatio));
139
+ limitPrice = askPrice.add(delta);
133
140
  } else {
134
- limitPrice = floatingPrice;
141
+ const bidPrice = calculateBidPrice(market, oraclePriceData);
142
+ const delta = bidPrice.div(new BN(market.amm.maxSlippageRatio));
143
+ limitPrice = bidPrice.sub(delta);
135
144
  }
136
- } else if (
137
- isVariant(order.orderType, 'market') ||
138
- isVariant(order.orderType, 'triggerMarket')
139
- ) {
140
- limitPrice = getAuctionPrice(order, slot);
141
145
  } else {
142
146
  limitPrice = order.price;
143
147
  }
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isEmptyPosition = exports.positionCurrentDirection = exports.findDirectionToClose = exports.calculateEntryPrice = exports.positionIsAvailable = exports.calculatePositionFundingPNL = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
4
+ const __1 = require("../");
5
+ const numericConstants_1 = require("../constants/numericConstants");
6
+ const types_1 = require("../types");
7
+ const amm_1 = require("./amm");
8
+ /**
9
+ * calculateBaseAssetValue
10
+ * = market value of closing entire position
11
+ * @param market
12
+ * @param userPosition
13
+ * @param oraclePriceData
14
+ * @returns Base Asset Value. : Precision QUOTE_PRECISION
15
+ */
16
+ function calculateBaseAssetValue(market, userPosition, oraclePriceData) {
17
+ if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
18
+ return numericConstants_1.ZERO;
19
+ }
20
+ const directionToClose = findDirectionToClose(userPosition);
21
+ let prepegAmm;
22
+ if (market.amm.baseSpread > 0) {
23
+ const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, directionToClose, oraclePriceData);
24
+ prepegAmm = {
25
+ baseAssetReserve,
26
+ quoteAssetReserve,
27
+ sqrtK: sqrtK,
28
+ pegMultiplier: newPeg,
29
+ };
30
+ }
31
+ else {
32
+ prepegAmm = amm_1.calculateUpdatedAMM(market.amm, oraclePriceData);
33
+ }
34
+ const [newQuoteAssetReserve, _] = amm_1.calculateAmmReservesAfterSwap(prepegAmm, 'base', userPosition.baseAssetAmount.abs(), amm_1.getSwapDirection('base', directionToClose));
35
+ switch (directionToClose) {
36
+ case types_1.PositionDirection.SHORT:
37
+ return prepegAmm.quoteAssetReserve
38
+ .sub(newQuoteAssetReserve)
39
+ .mul(prepegAmm.pegMultiplier)
40
+ .div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
41
+ case types_1.PositionDirection.LONG:
42
+ return newQuoteAssetReserve
43
+ .sub(prepegAmm.quoteAssetReserve)
44
+ .mul(prepegAmm.pegMultiplier)
45
+ .div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
46
+ .add(numericConstants_1.ONE);
47
+ }
48
+ }
49
+ exports.calculateBaseAssetValue = calculateBaseAssetValue;
50
+ /**
51
+ * calculatePositionPNL
52
+ * = BaseAssetAmount * (Avg Exit Price - Avg Entry Price)
53
+ * @param market
54
+ * @param marketPosition
55
+ * @param withFunding (adds unrealized funding payment pnl to result)
56
+ * @returns BaseAssetAmount : Precision QUOTE_PRECISION
57
+ */
58
+ function calculatePositionPNL(market, marketPosition, withFunding = false, oraclePriceData) {
59
+ if (marketPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
60
+ return numericConstants_1.ZERO;
61
+ }
62
+ const baseAssetValue = calculateBaseAssetValue(market, marketPosition, oraclePriceData);
63
+ let pnl;
64
+ if (marketPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
65
+ pnl = baseAssetValue.sub(marketPosition.quoteAssetAmount);
66
+ }
67
+ else {
68
+ pnl = marketPosition.quoteAssetAmount.sub(baseAssetValue);
69
+ }
70
+ if (withFunding) {
71
+ const fundingRatePnL = calculatePositionFundingPNL(market, marketPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION);
72
+ pnl = pnl.add(fundingRatePnL);
73
+ }
74
+ return pnl;
75
+ }
76
+ exports.calculatePositionPNL = calculatePositionPNL;
77
+ /**
78
+ *
79
+ * @param market
80
+ * @param marketPosition
81
+ * @returns // TODO-PRECISION
82
+ */
83
+ function calculatePositionFundingPNL(market, marketPosition) {
84
+ if (marketPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
85
+ return numericConstants_1.ZERO;
86
+ }
87
+ let ammCumulativeFundingRate;
88
+ if (marketPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
89
+ ammCumulativeFundingRate = market.amm.cumulativeFundingRateLong;
90
+ }
91
+ else {
92
+ ammCumulativeFundingRate = market.amm.cumulativeFundingRateShort;
93
+ }
94
+ const perPositionFundingRate = ammCumulativeFundingRate
95
+ .sub(marketPosition.lastCumulativeFundingRate)
96
+ .mul(marketPosition.baseAssetAmount)
97
+ .div(numericConstants_1.AMM_RESERVE_PRECISION)
98
+ .div(numericConstants_1.FUNDING_PAYMENT_PRECISION)
99
+ .mul(new __1.BN(-1));
100
+ return perPositionFundingRate;
101
+ }
102
+ exports.calculatePositionFundingPNL = calculatePositionFundingPNL;
103
+ function positionIsAvailable(position) {
104
+ return (position.baseAssetAmount.eq(numericConstants_1.ZERO) &&
105
+ position.openOrders.eq(numericConstants_1.ZERO) &&
106
+ position.unsettledPnl.eq(numericConstants_1.ZERO));
107
+ }
108
+ exports.positionIsAvailable = positionIsAvailable;
109
+ /**
110
+ *
111
+ * @param userPosition
112
+ * @returns Precision: MARK_PRICE_PRECISION (10^10)
113
+ */
114
+ function calculateEntryPrice(userPosition) {
115
+ if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
116
+ return numericConstants_1.ZERO;
117
+ }
118
+ return userPosition.quoteAssetAmount
119
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
120
+ .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
121
+ .div(userPosition.baseAssetAmount)
122
+ .abs();
123
+ }
124
+ exports.calculateEntryPrice = calculateEntryPrice;
125
+ function findDirectionToClose(userPosition) {
126
+ return userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
127
+ ? types_1.PositionDirection.SHORT
128
+ : types_1.PositionDirection.LONG;
129
+ }
130
+ exports.findDirectionToClose = findDirectionToClose;
131
+ function positionCurrentDirection(userPosition) {
132
+ return userPosition.baseAssetAmount.gte(numericConstants_1.ZERO)
133
+ ? types_1.PositionDirection.LONG
134
+ : types_1.PositionDirection.SHORT;
135
+ }
136
+ exports.positionCurrentDirection = positionCurrentDirection;
137
+ function isEmptyPosition(userPosition) {
138
+ return (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) && userPosition.openOrders.eq(numericConstants_1.ZERO));
139
+ }
140
+ exports.isEmptyPosition = isEmptyPosition;
@@ -153,7 +153,11 @@ export function calculatePositionFundingPNL(
153
153
  }
154
154
 
155
155
  export function positionIsAvailable(position: UserPosition): boolean {
156
- return position.baseAssetAmount.eq(ZERO) && position.openOrders.eq(ZERO);
156
+ return (
157
+ position.baseAssetAmount.eq(ZERO) &&
158
+ position.openOrders.eq(ZERO) &&
159
+ position.unsettledPnl.eq(ZERO)
160
+ );
157
161
  }
158
162
 
159
163
  /**