@drift-labs/sdk 0.2.0-master.21 → 0.2.0-master.24

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 (88) hide show
  1. package/lib/accounts/types.d.ts +1 -0
  2. package/lib/addresses/pda.d.ts +3 -0
  3. package/lib/addresses/pda.js +23 -1
  4. package/lib/admin.d.ts +3 -0
  5. package/lib/admin.js +31 -0
  6. package/lib/clearingHouse.d.ts +9 -2
  7. package/lib/clearingHouse.js +132 -4
  8. package/lib/clearingHouseUser.js +5 -5
  9. package/lib/config.js +1 -1
  10. package/lib/constants/banks.d.ts +2 -0
  11. package/lib/constants/banks.js +9 -0
  12. package/lib/constants/numericConstants.d.ts +2 -0
  13. package/lib/constants/numericConstants.js +4 -1
  14. package/lib/events/sort.js +7 -10
  15. package/lib/events/types.d.ts +2 -1
  16. package/lib/events/types.js +1 -0
  17. package/lib/idl/clearing_house.json +1008 -147
  18. package/lib/index.d.ts +1 -0
  19. package/lib/index.js +1 -0
  20. package/lib/math/amm.js +2 -2
  21. package/lib/math/insurance.d.ts +4 -0
  22. package/lib/math/insurance.js +27 -0
  23. package/lib/math/margin.d.ts +1 -1
  24. package/lib/math/margin.js +5 -7
  25. package/lib/math/position.js +1 -1
  26. package/lib/types.d.ts +56 -20
  27. package/lib/types.js +0 -3
  28. package/package.json +1 -1
  29. package/src/addresses/marketAddresses.js +26 -0
  30. package/src/addresses/pda.ts +47 -0
  31. package/src/admin.ts +65 -0
  32. package/src/assert/assert.js +9 -0
  33. package/src/clearingHouse.ts +217 -9
  34. package/src/clearingHouseUser.ts +10 -6
  35. package/src/config.ts +1 -1
  36. package/src/constants/banks.js +42 -0
  37. package/src/constants/banks.ts +16 -0
  38. package/src/constants/markets.js +42 -0
  39. package/src/constants/numericConstants.js +41 -0
  40. package/src/constants/numericConstants.ts +4 -0
  41. package/src/events/eventList.js +77 -0
  42. package/src/events/sort.ts +10 -14
  43. package/src/events/txEventCache.js +71 -0
  44. package/src/events/types.ts +3 -0
  45. package/src/examples/makeTradeExample.js +80 -0
  46. package/src/factory/bigNum.js +390 -0
  47. package/src/factory/oracleClient.js +20 -0
  48. package/src/idl/clearing_house.json +1008 -147
  49. package/src/index.ts +1 -0
  50. package/src/math/amm.ts +2 -2
  51. package/src/math/auction.js +42 -0
  52. package/src/math/conversion.js +11 -0
  53. package/src/math/funding.js +248 -0
  54. package/src/math/insurance.ts +35 -0
  55. package/src/math/margin.ts +3 -10
  56. package/src/math/oracles.js +26 -0
  57. package/src/math/position.ts +2 -2
  58. package/src/math/repeg.js +128 -0
  59. package/src/math/state.js +15 -0
  60. package/src/math/trade.js +253 -0
  61. package/src/math/utils.js +26 -0
  62. package/src/math/utils.js.map +1 -0
  63. package/src/oracles/oracleClientCache.js +19 -0
  64. package/src/oracles/pythClient.js +46 -0
  65. package/src/oracles/quoteAssetOracleClient.js +32 -0
  66. package/src/oracles/switchboardClient.js +69 -0
  67. package/src/oracles/types.js +2 -0
  68. package/src/orderParams.js +20 -0
  69. package/src/slot/SlotSubscriber.js +39 -0
  70. package/src/token/index.js +38 -0
  71. package/src/tokenFaucet.js +189 -0
  72. package/src/tx/types.js +2 -0
  73. package/src/tx/utils.js +17 -0
  74. package/src/types.ts +64 -20
  75. package/src/userName.js +20 -0
  76. package/src/util/computeUnits.js +27 -0
  77. package/src/util/getTokenAddress.js +9 -0
  78. package/src/util/promiseTimeout.js +14 -0
  79. package/src/util/tps.js +27 -0
  80. package/src/wallet.js +35 -0
  81. package/my-script/.env +0 -7
  82. package/my-script/getUserStats.ts +0 -124
  83. package/my-script/multiConnections.ts +0 -137
  84. package/my-script/test-regex.ts +0 -11
  85. package/my-script/utils.ts +0 -52
  86. package/my-script/ww18NdhuLSQPCrHSx7V68eZJpe2y311heWeXJfSmP3Q.json +0 -1
  87. package/my-script/ww2z7N9TG1PLLUQGQF2VKzCFaPtQ5FBhRfeEAuy6c5C.json +0 -1
  88. package/my-script/ww3StJtTubhwssqAhvSSAc5ifCgKjzmF8hz7Gt2DmSa.json +0 -1
package/src/index.ts CHANGED
@@ -41,6 +41,7 @@ export * from './math/trade';
41
41
  export * from './math/orders';
42
42
  export * from './math/repeg';
43
43
  export * from './math/margin';
44
+ export * from './math/insurance';
44
45
  export * from './orderParams';
45
46
  export * from './slot/SlotSubscriber';
46
47
  export * from './wallet';
package/src/math/amm.ts CHANGED
@@ -635,12 +635,12 @@ export function calculateMaxBaseAssetAmountFillable(
635
635
  if (isVariant(orderDirection, 'long')) {
636
636
  maxBaseAssetAmountOnSide = BN.max(
637
637
  ZERO,
638
- amm.maxBaseAssetReserve.sub(amm.baseAssetReserve)
638
+ amm.baseAssetReserve.sub(amm.minBaseAssetReserve)
639
639
  );
640
640
  } else {
641
641
  maxBaseAssetAmountOnSide = BN.max(
642
642
  ZERO,
643
- amm.baseAssetReserve.sub(amm.minBaseAssetReserve)
643
+ amm.maxBaseAssetReserve.sub(amm.baseAssetReserve)
644
644
  );
645
645
  }
646
646
 
@@ -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;
@@ -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,35 @@
1
+ import { ONE, ZERO } from '../constants/numericConstants';
2
+ import { BN } from '../index';
3
+
4
+ export function stakeAmountToShares(
5
+ amount: BN,
6
+ totalIfShares: BN,
7
+ insuranceFundVaultBalance: BN
8
+ ): BN {
9
+ let nShares: BN;
10
+ if (insuranceFundVaultBalance.gt(ZERO)) {
11
+ nShares = amount.mul(totalIfShares).div(insuranceFundVaultBalance);
12
+ } else {
13
+ nShares = amount;
14
+ }
15
+
16
+ return nShares;
17
+ }
18
+
19
+ export function unstakeSharesToAmount(
20
+ nShares: BN,
21
+ totalIfShares: BN,
22
+ insuranceFundVaultBalance: BN
23
+ ): BN {
24
+ let amount: BN;
25
+ if (totalIfShares.gt(ZERO)) {
26
+ amount = BN.max(
27
+ ZERO,
28
+ nShares.mul(insuranceFundVaultBalance).div(totalIfShares).sub(ONE)
29
+ );
30
+ } else {
31
+ amount = ZERO;
32
+ }
33
+
34
+ return amount;
35
+ }
@@ -92,22 +92,15 @@ export function calculateOraclePriceForPerpMargin(
92
92
  return marginPrice;
93
93
  }
94
94
 
95
- export function calculateMarginBaseAssetValue(
95
+ export function calculateBaseAssetValueWithOracle(
96
96
  market: MarketAccount,
97
97
  marketPosition: UserPosition,
98
98
  oraclePriceData: OraclePriceData
99
99
  ): BN {
100
- const marginPrice = calculateOraclePriceForPerpMargin(
101
- marketPosition,
102
- market,
103
- oraclePriceData
104
- );
105
- const baseAssetValue = marketPosition.baseAssetAmount
100
+ return marketPosition.baseAssetAmount
106
101
  .abs()
107
- .mul(marginPrice)
102
+ .mul(oraclePriceData.price)
108
103
  .div(AMM_TO_QUOTE_PRECISION_RATIO.mul(MARK_PRICE_PRECISION));
109
-
110
- return baseAssetValue;
111
104
  }
112
105
 
113
106
  export function calculateWorstCaseBaseAssetAmount(
@@ -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;
@@ -18,7 +18,7 @@ import {
18
18
  getSwapDirection,
19
19
  } from './amm';
20
20
 
21
- import { calculateMarginBaseAssetValue } from './margin';
21
+ import { calculateBaseAssetValueWithOracle } from './margin';
22
22
 
23
23
  /**
24
24
  * calculateBaseAssetValue
@@ -99,7 +99,7 @@ export function calculatePositionPNL(
99
99
  return marketPosition.quoteAssetAmount;
100
100
  }
101
101
 
102
- const baseAssetValue = calculateMarginBaseAssetValue(
102
+ const baseAssetValue = calculateBaseAssetValueWithOracle(
103
103
  market,
104
104
  marketPosition,
105
105
  oraclePriceData
@@ -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;