@drift-labs/sdk 0.2.0-temp.0 → 0.2.0-temp.1

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 (115) hide show
  1. package/lib/admin.d.ts +7 -5
  2. package/lib/admin.js +34 -11
  3. package/lib/clearingHouse.d.ts +23 -9
  4. package/lib/clearingHouse.js +335 -95
  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 +1 -0
  10. package/lib/constants/numericConstants.js +2 -1
  11. package/lib/idl/clearing_house.json +689 -153
  12. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  13. package/lib/index.d.ts +3 -2
  14. package/lib/index.js +7 -2
  15. package/lib/math/amm.js +7 -35
  16. package/lib/math/auction.js +4 -1
  17. package/lib/math/orders.d.ts +2 -2
  18. package/lib/math/orders.js +19 -2
  19. package/lib/math/position.js +3 -1
  20. package/lib/math/trade.d.ts +1 -1
  21. package/lib/math/trade.js +7 -10
  22. package/lib/orderParams.d.ts +14 -5
  23. package/lib/orderParams.js +8 -96
  24. package/lib/orders.js +1 -1
  25. package/lib/slot/SlotSubscriber.d.ts +7 -0
  26. package/lib/slot/SlotSubscriber.js +3 -0
  27. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +7 -5
  28. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +41 -40
  29. package/lib/tx/utils.js +1 -1
  30. package/lib/types.d.ts +132 -14
  31. package/lib/types.js +52 -1
  32. package/lib/util/computeUnits.js +1 -1
  33. package/package.json +3 -3
  34. package/src/accounts/bulkAccountLoader.js +197 -0
  35. package/src/accounts/bulkUserSubscription.js +33 -0
  36. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  37. package/src/accounts/pollingOracleSubscriber.js +93 -0
  38. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  39. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  40. package/src/accounts/types.js +10 -0
  41. package/src/accounts/utils.js +7 -0
  42. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  43. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  44. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  45. package/src/addresses/marketAddresses.js +26 -0
  46. package/src/admin.js +517 -0
  47. package/src/admin.ts +53 -14
  48. package/src/assert/assert.js +9 -0
  49. package/src/clearingHouse.ts +510 -131
  50. package/src/clearingHouseConfig.js +2 -0
  51. package/src/clearingHouseUser.ts +12 -23
  52. package/src/clearingHouseUserConfig.js +2 -0
  53. package/src/config.js +67 -0
  54. package/src/config.ts +1 -1
  55. package/src/constants/banks.js +42 -0
  56. package/src/constants/banks.ts +9 -2
  57. package/src/constants/markets.js +42 -0
  58. package/src/constants/numericConstants.js +41 -0
  59. package/src/constants/numericConstants.ts +1 -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 +390 -0
  70. package/src/factory/oracleClient.js +20 -0
  71. package/src/idl/clearing_house.json +689 -153
  72. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  73. package/src/index.js +69 -0
  74. package/src/index.ts +3 -2
  75. package/src/math/amm.js +369 -0
  76. package/src/math/amm.ts +19 -49
  77. package/src/math/auction.js +42 -0
  78. package/src/math/auction.ts +5 -1
  79. package/src/math/conversion.js +11 -0
  80. package/src/math/funding.js +248 -0
  81. package/src/math/oracles.js +26 -0
  82. package/src/math/orders.ts +17 -3
  83. package/src/math/position.ts +5 -1
  84. package/src/math/repeg.js +128 -0
  85. package/src/math/state.js +15 -0
  86. package/src/math/trade.js +253 -0
  87. package/src/math/trade.ts +23 -25
  88. package/src/math/utils.js +0 -1
  89. package/src/mockUSDCFaucet.js +280 -0
  90. package/src/oracles/oracleClientCache.js +19 -0
  91. package/src/oracles/pythClient.js +46 -0
  92. package/src/oracles/quoteAssetOracleClient.js +32 -0
  93. package/src/oracles/switchboardClient.js +69 -0
  94. package/src/oracles/types.js +2 -0
  95. package/src/orderParams.js +20 -0
  96. package/src/orderParams.ts +20 -141
  97. package/src/orders.ts +2 -1
  98. package/src/slot/SlotSubscriber.js +39 -0
  99. package/src/slot/SlotSubscriber.ts +11 -1
  100. package/src/token/index.js +38 -0
  101. package/src/tokenFaucet.js +189 -0
  102. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +48 -59
  103. package/src/tx/types.js +2 -0
  104. package/src/tx/utils.js +17 -0
  105. package/src/tx/utils.ts +1 -1
  106. package/src/types.js +125 -0
  107. package/src/types.ts +128 -15
  108. package/src/userName.js +20 -0
  109. package/src/util/computeUnits.js +21 -11
  110. package/src/util/computeUnits.ts +1 -1
  111. package/src/util/getTokenAddress.js +9 -0
  112. package/src/util/promiseTimeout.js +14 -0
  113. package/src/util/tps.js +27 -0
  114. package/src/wallet.js +35 -0
  115. package/src/util/computeUnits.js.map +0 -1
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getAuctionPrice = exports.isAuctionComplete = void 0;
4
+ const types_1 = require("../types");
5
+ const _1 = require("../.");
6
+ function isAuctionComplete(order, slot) {
7
+ if (order.auctionDuration === 0) {
8
+ return true;
9
+ }
10
+ return new _1.BN(slot).sub(order.slot).gt(new _1.BN(order.auctionDuration));
11
+ }
12
+ exports.isAuctionComplete = isAuctionComplete;
13
+ function getAuctionPrice(order, slot) {
14
+ const slotsElapsed = new _1.BN(slot).sub(order.slot);
15
+ const deltaDenominator = new _1.BN(order.auctionDuration);
16
+ const deltaNumerator = _1.BN.min(slotsElapsed, deltaDenominator);
17
+ if (deltaDenominator.eq(_1.ZERO)) {
18
+ return order.auctionEndPrice;
19
+ }
20
+ let priceDelta;
21
+ if (types_1.isVariant(order.direction, 'long')) {
22
+ priceDelta = order.auctionEndPrice
23
+ .sub(order.auctionStartPrice)
24
+ .mul(deltaNumerator)
25
+ .div(deltaDenominator);
26
+ }
27
+ else {
28
+ priceDelta = order.auctionStartPrice
29
+ .sub(order.auctionEndPrice)
30
+ .mul(deltaNumerator)
31
+ .div(deltaDenominator);
32
+ }
33
+ let price;
34
+ if (types_1.isVariant(order.direction, 'long')) {
35
+ price = order.auctionStartPrice.add(priceDelta);
36
+ }
37
+ else {
38
+ price = order.auctionStartPrice.sub(priceDelta);
39
+ }
40
+ return price;
41
+ }
42
+ exports.getAuctionPrice = getAuctionPrice;
@@ -2,7 +2,11 @@ import { isVariant, Order } from '../types';
2
2
  import { BN, ZERO } from '../.';
3
3
 
4
4
  export function isAuctionComplete(order: Order, slot: number): boolean {
5
- return new BN(slot).sub(order.slot).gte(new BN(order.auctionDuration));
5
+ if (order.auctionDuration === 0) {
6
+ return true;
7
+ }
8
+
9
+ return new BN(slot).sub(order.slot).gt(new BN(order.auctionDuration));
6
10
  }
7
11
 
8
12
  export function getAuctionPrice(order: Order, slot: number): BN {
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.convertToNumber = void 0;
4
+ const numericConstants_1 = require("../constants/numericConstants");
5
+ const convertToNumber = (bigNumber, precision = numericConstants_1.MARK_PRICE_PRECISION) => {
6
+ if (!bigNumber)
7
+ return 0;
8
+ return (bigNumber.div(precision).toNumber() +
9
+ bigNumber.mod(precision).toNumber() / precision.toNumber());
10
+ };
11
+ exports.convertToNumber = convertToNumber;
@@ -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,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;
@@ -1,9 +1,10 @@
1
1
  import { ClearingHouseUser } from '../clearingHouseUser';
2
- import { isOneOfVariant, 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,6 +121,7 @@ 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 {
@@ -127,7 +129,19 @@ export function getLimitPrice(
127
129
  if (!order.oraclePriceOffset.eq(ZERO)) {
128
130
  limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
129
131
  } else if (isOneOfVariant(order.orderType, ['market', 'triggerMarket'])) {
130
- limitPrice = getAuctionPrice(order, slot);
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);
140
+ } else {
141
+ const bidPrice = calculateBidPrice(market, oraclePriceData);
142
+ const delta = bidPrice.div(new BN(market.amm.maxSlippageRatio));
143
+ limitPrice = bidPrice.sub(delta);
144
+ }
131
145
  } else {
132
146
  limitPrice = order.price;
133
147
  }
@@ -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
  /**
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.calculateBudgetedPeg = exports.calculateBudgetedK = exports.calculateBudgetedKBN = exports.calculateRepegCost = exports.calculateAdjustKCost = void 0;
4
+ const anchor_1 = require("@project-serum/anchor");
5
+ const assert_1 = require("../assert/assert");
6
+ const numericConstants_1 = require("../constants/numericConstants");
7
+ /**
8
+ * Helper function calculating adjust k cost
9
+ * @param amm
10
+ * @param numerator
11
+ * @param denomenator
12
+ * @returns cost : Precision QUOTE_ASSET_PRECISION
13
+ */
14
+ function calculateAdjustKCost(amm, numerator, denomenator) {
15
+ // const k = market.amm.sqrtK.mul(market.amm.sqrtK);
16
+ const x = amm.baseAssetReserve;
17
+ const y = amm.quoteAssetReserve;
18
+ const d = amm.netBaseAssetAmount;
19
+ const Q = amm.pegMultiplier;
20
+ const quoteScale = y.mul(d).mul(Q); //.div(AMM_RESERVE_PRECISION);
21
+ const p = numerator.mul(numericConstants_1.MARK_PRICE_PRECISION).div(denomenator);
22
+ const cost = quoteScale
23
+ .div(x.add(d))
24
+ .sub(quoteScale
25
+ .mul(p)
26
+ .div(numericConstants_1.MARK_PRICE_PRECISION)
27
+ .div(x.mul(p).div(numericConstants_1.MARK_PRICE_PRECISION).add(d)))
28
+ .div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
29
+ .div(numericConstants_1.PEG_PRECISION);
30
+ return cost.mul(new anchor_1.BN(-1));
31
+ }
32
+ exports.calculateAdjustKCost = calculateAdjustKCost;
33
+ /**
34
+ * Helper function calculating adjust pegMultiplier (repeg) cost
35
+ *
36
+ * @param amm
37
+ * @param newPeg
38
+ * @returns cost : Precision QUOTE_ASSET_PRECISION
39
+ */
40
+ function calculateRepegCost(amm, newPeg) {
41
+ const dqar = amm.quoteAssetReserve.sub(amm.terminalQuoteAssetReserve);
42
+ const cost = dqar
43
+ .mul(newPeg.sub(amm.pegMultiplier))
44
+ .div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
45
+ .div(numericConstants_1.PEG_PRECISION);
46
+ return cost;
47
+ }
48
+ exports.calculateRepegCost = calculateRepegCost;
49
+ function calculateBudgetedKBN(x, y, budget, Q, d) {
50
+ assert_1.assert(Q.gt(new anchor_1.BN(0)));
51
+ const C = budget.mul(new anchor_1.BN(-1));
52
+ let dSign = new anchor_1.BN(1);
53
+ if (d.lt(new anchor_1.BN(0))) {
54
+ dSign = new anchor_1.BN(-1);
55
+ }
56
+ const pegged_y_d_d = y
57
+ .mul(d)
58
+ .mul(d)
59
+ .mul(Q)
60
+ .div(numericConstants_1.AMM_RESERVE_PRECISION)
61
+ .div(numericConstants_1.AMM_RESERVE_PRECISION)
62
+ .div(numericConstants_1.PEG_PRECISION);
63
+ const numer1 = pegged_y_d_d;
64
+ const numer2 = C.mul(d)
65
+ .div(numericConstants_1.QUOTE_PRECISION)
66
+ .mul(x.add(d))
67
+ .div(numericConstants_1.AMM_RESERVE_PRECISION)
68
+ .mul(dSign);
69
+ const denom1 = C.mul(x)
70
+ .mul(x.add(d))
71
+ .div(numericConstants_1.AMM_RESERVE_PRECISION)
72
+ .div(numericConstants_1.QUOTE_PRECISION);
73
+ const denom2 = pegged_y_d_d;
74
+ const numerator = numer1.sub(numer2).div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
75
+ const denominator = denom1.add(denom2).div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
76
+ return [numerator, denominator];
77
+ }
78
+ exports.calculateBudgetedKBN = calculateBudgetedKBN;
79
+ function calculateBudgetedK(amm, cost) {
80
+ // wolframalpha.com
81
+ // (1/(x+d) - p/(x*p+d))*y*d*Q = C solve for p
82
+ // p = (d(y*d*Q - C(x+d))) / (C*x(x+d) + y*d*d*Q)
83
+ // numer
84
+ // = y*d*d*Q - Cxd - Cdd
85
+ // = y/x*Q*d*d - Cd - Cd/x
86
+ // = mark - C/d - C/(x)
87
+ // = mark/C - 1/d - 1/x
88
+ // denom
89
+ // = C*x*x + C*x*d + y*d*d*Q
90
+ // = x/d**2 + 1 / d + mark/C
91
+ // todo: assumes k = x * y
92
+ // otherwise use: (y(1-p) + (kp^2/(x*p+d)) - k/(x+d)) * Q = C solve for p
93
+ const x = amm.baseAssetReserve;
94
+ const y = amm.quoteAssetReserve;
95
+ const d = amm.netBaseAssetAmount;
96
+ const Q = amm.pegMultiplier;
97
+ const [numerator, denominator] = calculateBudgetedKBN(x, y, cost, Q, d);
98
+ return [numerator, denominator];
99
+ }
100
+ exports.calculateBudgetedK = calculateBudgetedK;
101
+ function calculateBudgetedPeg(amm, cost, targetPrice) {
102
+ // wolframalpha.com
103
+ // (1/(x+d) - p/(x*p+d))*y*d*Q = C solve for p
104
+ // p = (d(y*d*Q - C(x+d))) / (C*x(x+d) + y*y*d*Q)
105
+ // todo: assumes k = x * y
106
+ // otherwise use: (y(1-p) + (kp^2/(x*p+d)) - k/(x+d)) * Q = C solve for p
107
+ const targetPeg = targetPrice
108
+ .mul(amm.baseAssetReserve)
109
+ .div(amm.quoteAssetReserve)
110
+ .div(numericConstants_1.PRICE_DIV_PEG);
111
+ const k = amm.sqrtK.mul(amm.sqrtK);
112
+ const x = amm.baseAssetReserve;
113
+ const y = amm.quoteAssetReserve;
114
+ const d = amm.netBaseAssetAmount;
115
+ const Q = amm.pegMultiplier;
116
+ const C = cost.mul(new anchor_1.BN(-1));
117
+ const deltaQuoteAssetReserves = y.sub(k.div(x.add(d)));
118
+ const pegChangeDirection = targetPeg.sub(Q);
119
+ const useTargetPeg = (deltaQuoteAssetReserves.lt(numericConstants_1.ZERO) && pegChangeDirection.gt(numericConstants_1.ZERO)) ||
120
+ (deltaQuoteAssetReserves.gt(numericConstants_1.ZERO) && pegChangeDirection.lt(numericConstants_1.ZERO));
121
+ if (deltaQuoteAssetReserves.eq(numericConstants_1.ZERO) || useTargetPeg) {
122
+ return targetPeg;
123
+ }
124
+ const deltaPegMultiplier = C.mul(numericConstants_1.MARK_PRICE_PRECISION).div(deltaQuoteAssetReserves.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO));
125
+ const newPeg = Q.sub(deltaPegMultiplier.mul(numericConstants_1.PEG_PRECISION).div(numericConstants_1.MARK_PRICE_PRECISION));
126
+ return newPeg;
127
+ }
128
+ exports.calculateBudgetedPeg = calculateBudgetedPeg;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getExchangeFee = void 0;
4
+ /**
5
+ * Get the clearing house percent fee charged on notional of taking trades
6
+ *
7
+ * @param state
8
+ * @returns Precision : basis points (bps)
9
+ */
10
+ function getExchangeFee(state) {
11
+ const exchangeFee = state.feeStructure.feeNumerator.toNumber() /
12
+ state.feeStructure.feeDenominator.toNumber();
13
+ return exchangeFee;
14
+ }
15
+ exports.getExchangeFee = getExchangeFee;