@drift-labs/sdk 0.1.13 → 0.1.17-master.0

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 (68) hide show
  1. package/README.md +2 -2
  2. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts +1 -0
  3. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts.map +1 -1
  4. package/lib/accounts/defaultClearingHouseAccountSubscriber.js +18 -1
  5. package/lib/accounts/defaultUserAccountSubscriber.d.ts +2 -0
  6. package/lib/accounts/defaultUserAccountSubscriber.d.ts.map +1 -1
  7. package/lib/accounts/defaultUserAccountSubscriber.js +17 -1
  8. package/lib/accounts/types.d.ts +3 -0
  9. package/lib/accounts/types.d.ts.map +1 -1
  10. package/lib/accounts/webSocketAccountSubscriber.d.ts +2 -0
  11. package/lib/accounts/webSocketAccountSubscriber.d.ts.map +1 -1
  12. package/lib/accounts/webSocketAccountSubscriber.js +13 -3
  13. package/lib/admin.js +3 -3
  14. package/lib/clearingHouse.d.ts +4 -0
  15. package/lib/clearingHouse.d.ts.map +1 -1
  16. package/lib/clearingHouse.js +17 -9
  17. package/lib/clearingHouseUser.d.ts +4 -0
  18. package/lib/clearingHouseUser.d.ts.map +1 -1
  19. package/lib/clearingHouseUser.js +33 -13
  20. package/lib/constants/markets.d.ts.map +1 -1
  21. package/lib/constants/markets.js +14 -0
  22. package/lib/examples/makeTradeExample.js +10 -11
  23. package/lib/index.d.ts +2 -0
  24. package/lib/index.d.ts.map +1 -1
  25. package/lib/index.js +2 -0
  26. package/lib/math/amm.d.ts.map +1 -1
  27. package/lib/math/amm.js +9 -8
  28. package/lib/math/conversion.js +1 -1
  29. package/lib/math/funding.d.ts +2 -4
  30. package/lib/math/funding.d.ts.map +1 -1
  31. package/lib/math/funding.js +5 -7
  32. package/lib/math/insuranceFund.d.ts +4 -3
  33. package/lib/math/insuranceFund.d.ts.map +1 -1
  34. package/lib/math/insuranceFund.js +1 -0
  35. package/lib/math/market.js +1 -1
  36. package/lib/math/position.d.ts.map +1 -1
  37. package/lib/math/position.js +1 -1
  38. package/lib/math/trade.js +16 -16
  39. package/lib/pythClient.js +1 -1
  40. package/lib/util/computeUnits.d.ts +3 -0
  41. package/lib/util/computeUnits.d.ts.map +1 -0
  42. package/lib/util/computeUnits.js +27 -0
  43. package/lib/util/tps.d.ts +3 -0
  44. package/lib/util/tps.d.ts.map +1 -0
  45. package/lib/util/tps.js +27 -0
  46. package/lib/wallet.d.ts +2 -2
  47. package/lib/wallet.d.ts.map +1 -1
  48. package/package.json +2 -12
  49. package/src/accounts/defaultClearingHouseAccountSubscriber.ts +18 -0
  50. package/src/accounts/defaultUserAccountSubscriber.ts +18 -0
  51. package/src/accounts/types.ts +3 -1
  52. package/src/accounts/webSocketAccountSubscriber.ts +16 -6
  53. package/src/clearingHouse.ts +7 -1
  54. package/src/clearingHouseUser.ts +29 -4
  55. package/src/constants/markets.ts +14 -0
  56. package/src/constants/numericConstants.ts +0 -1
  57. package/src/examples/makeTradeExample.ts +6 -12
  58. package/src/index.ts +2 -0
  59. package/src/math/amm.ts +2 -2
  60. package/src/math/funding.ts +7 -6
  61. package/src/math/insuranceFund.ts +16 -9
  62. package/src/math/position.ts +6 -5
  63. package/src/util/computeUnits.ts +21 -0
  64. package/src/util/tps.ts +27 -0
  65. package/src/wallet.ts +17 -17
  66. package/.eslintrc.json +0 -36
  67. package/.prettierignore +0 -1
  68. package/.prettierrc.js +0 -9
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAE3C,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,qBAAqB,CAAC;AACpC,cAAc,kDAAkD,CAAC;AACjE,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC;AAC5B,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(require("./types"), exports);
35
35
  __exportStar(require("./math/utils"), exports);
36
36
  __exportStar(require("./config"), exports);
37
37
  __exportStar(require("./constants/numericConstants"), exports);
38
+ __exportStar(require("./util/computeUnits"), exports);
39
+ __exportStar(require("./util/tps"), exports);
@@ -1 +1 @@
1
- {"version":3,"file":"amm.d.ts","sourceRoot":"","sources":["../../src/math/amm.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAS3C,OAAO,EAAE,GAAG,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAIzE;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC7B,eAAe,EAAE,EAAE,EACnB,gBAAgB,EAAE,EAAE,EACpB,cAAc,EAAE,EAAE,GAChB,EAAE,CAUJ;AAED,oBAAY,SAAS,GAAG,OAAO,GAAG,MAAM,CAAC;AAEzC;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAC5C,GAAG,EAAE,GAAG,EACR,cAAc,EAAE,SAAS,EACzB,UAAU,EAAE,EAAE,EACd,aAAa,EAAE,aAAa,GAC1B,CAAC,EAAE,EAAE,EAAE,CAAC,CA0BV;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAClC,iBAAiB,EAAE,EAAE,EACrB,UAAU,EAAE,EAAE,EACd,aAAa,EAAE,aAAa,EAC5B,SAAS,EAAE,EAAE,GACX,CAAC,EAAE,EAAE,EAAE,CAAC,CASV;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC/B,cAAc,EAAE,SAAS,EACzB,iBAAiB,EAAE,iBAAiB,GAClC,aAAa,CAgBf;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CACnC,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,EAAE,EACf,SAAS,EAAE,EAAE,EACb,WAAW,EAAE,EAAE,GACb,EAAE,CA0BJ;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAC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E,MAAM,EACd,WAAW,EAAE,EAAE,EACf,MAAM,EAAE,EAAE,GACR,EAAE,CA2BJ;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,MAuBpD"}
package/lib/math/amm.js CHANGED
@@ -36,11 +36,12 @@ exports.calculatePrice = calculatePrice;
36
36
  * @returns quoteAssetReserve and baseAssetReserve after swap. : Precision AMM_RESERVE_PRECISION
37
37
  */
38
38
  function calculateAmmReservesAfterSwap(amm, inputAssetType, swapAmount, swapDirection) {
39
- assert_1.assert(swapAmount.gte(numericConstants_1.ZERO), 'swapAmount must be greater than 0');
39
+ (0, assert_1.assert)(swapAmount.gte(numericConstants_1.ZERO), 'swapAmount must be greater than 0');
40
40
  let newQuoteAssetReserve;
41
41
  let newBaseAssetReserve;
42
42
  if (inputAssetType === 'quote') {
43
- swapAmount = swapAmount.mul(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
43
+ swapAmount = swapAmount
44
+ .mul(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
44
45
  .div(amm.pegMultiplier);
45
46
  [newQuoteAssetReserve, newBaseAssetReserve] = calculateSwapOutput(amm.quoteAssetReserve, swapAmount, swapDirection, amm.sqrtK.mul(amm.sqrtK));
46
47
  }
@@ -104,7 +105,7 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
104
105
  marketIndex: new anchor_1.BN(marketIndex),
105
106
  quoteAssetAmount: new anchor_1.BN(0),
106
107
  };
107
- const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
108
+ const currentValue = (0, position_1.calculateBaseAssetValue)(market, netUserPosition);
108
109
  const marketNewK = Object.assign({}, market);
109
110
  marketNewK.amm = Object.assign({}, market.amm);
110
111
  marketNewK.amm.baseAssetReserve = market.amm.baseAssetReserve
@@ -115,7 +116,7 @@ function calculateAdjustKCost(market, marketIndex, numerator, denomenator) {
115
116
  .div(denomenator);
116
117
  marketNewK.amm.sqrtK = market.amm.sqrtK.mul(numerator).div(denomenator);
117
118
  netUserPosition.quoteAssetAmount = currentValue;
118
- const cost = __1.calculatePositionPNL(marketNewK, netUserPosition);
119
+ const cost = (0, __1.calculatePositionPNL)(marketNewK, netUserPosition);
119
120
  return cost;
120
121
  }
121
122
  exports.calculateAdjustKCost = calculateAdjustKCost;
@@ -134,15 +135,15 @@ function calculateRepegCost(market, marketIndex, newPeg) {
134
135
  marketIndex: new anchor_1.BN(marketIndex),
135
136
  quoteAssetAmount: new anchor_1.BN(0),
136
137
  };
137
- const currentValue = position_1.calculateBaseAssetValue(market, netUserPosition);
138
+ const currentValue = (0, position_1.calculateBaseAssetValue)(market, netUserPosition);
138
139
  netUserPosition.quoteAssetAmount = currentValue;
139
- const prevMarketPrice = __1.calculateMarkPrice(market);
140
+ const prevMarketPrice = (0, __1.calculateMarkPrice)(market);
140
141
  const marketNewPeg = Object.assign({}, market);
141
142
  marketNewPeg.amm = Object.assign({}, market.amm);
142
143
  // const marketNewPeg = JSON.parse(JSON.stringify(market));
143
144
  marketNewPeg.amm.pegMultiplier = newPeg;
144
- console.log('Price moves from', __1.convertToNumber(prevMarketPrice), 'to', __1.convertToNumber(__1.calculateMarkPrice(marketNewPeg)));
145
- const cost = __1.calculatePositionPNL(marketNewPeg, netUserPosition);
145
+ console.log('Price moves from', (0, __1.convertToNumber)(prevMarketPrice), 'to', (0, __1.convertToNumber)((0, __1.calculateMarkPrice)(marketNewPeg)));
146
+ const cost = (0, __1.calculatePositionPNL)(marketNewPeg, netUserPosition);
146
147
  return cost;
147
148
  }
148
149
  exports.calculateRepegCost = calculateRepegCost;
@@ -10,6 +10,6 @@ const convertToNumber = (bigNumber, precision = numericConstants_1.MARK_PRICE_PR
10
10
  };
11
11
  exports.convertToNumber = convertToNumber;
12
12
  const convertBaseAssetAmountToNumber = (baseAssetAmount) => {
13
- return exports.convertToNumber(baseAssetAmount, numericConstants_1.MARK_PRICE_PRECISION.mul(numericConstants_1.PEG_PRECISION));
13
+ return (0, exports.convertToNumber)(baseAssetAmount, numericConstants_1.MARK_PRICE_PRECISION.mul(numericConstants_1.PEG_PRECISION));
14
14
  };
15
15
  exports.convertBaseAssetAmountToNumber = convertBaseAssetAmountToNumber;
@@ -22,18 +22,16 @@ export declare function calculateEstimatedFundingRate(market: Market, oraclePric
22
22
  /**
23
23
  *
24
24
  * @param market
25
- * @param pythClient
25
+ * @param oraclePriceData
26
26
  * @param periodAdjustment
27
- * @param estimationMethod
28
27
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
29
28
  */
30
29
  export declare function calculateLongShortFundingRate(market: Market, oraclePriceData: PriceData, periodAdjustment?: BN): Promise<[BN, BN]>;
31
30
  /**
32
31
  *
33
32
  * @param market
34
- * @param pythClient
33
+ * @param oraclePriceData
35
34
  * @param periodAdjustment
36
- * @param estimationMethod
37
35
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
38
36
  */
39
37
  export declare function calculateLongShortFundingRateAndLiveTwaps(market: Market, oraclePriceData: PriceData, periodAdjustment?: BN): Promise<[BN, BN, BN, BN]>;
@@ -1 +1 @@
1
- {"version":3,"file":"funding.d.ts","sourceRoot":"","sources":["../../src/math/funding.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAOhD,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAGlC;;;;;;GAMG;AACH,wBAAsB,gCAAgC,CACrD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CA0K/B;AAED;;;;;;;GAOG;AACH,wBAAsB,6BAA6B,CAClD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,EAAE,EA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CAClD,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAenB;AAED;;;;;;GAMG;AACH,wBAAsB,yCAAyC,CAC9D,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,SAAS,EAC1B,gBAAgB,GAAE,EAAc,GAC9B,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAe3B;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,EAAE,CAQvD"}
@@ -40,7 +40,7 @@ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustm
40
40
  const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
41
41
  const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
42
42
  const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, secondsInHour.sub(timeSinceLastMarkChange));
43
- const baseAssetPriceWithMantissa = market_1.calculateMarkPrice(market);
43
+ const baseAssetPriceWithMantissa = (0, market_1.calculateMarkPrice)(market);
44
44
  const markTwapWithMantissa = markTwapTimeSinceLastUpdate
45
45
  .mul(lastMarkTwapWithMantissa)
46
46
  .add(timeSinceLastMarkChange.mul(baseAssetPriceWithMantissa))
@@ -78,7 +78,7 @@ function calculateAllEstimatedFundingRate(market, oraclePriceData, periodAdjustm
78
78
  .add(timeSinceLastMarkChange.mul(oraclePriceStableWithMantissa))
79
79
  .div(timeSinceLastOracleTwapUpdate.add(oracleTwapTimeSinceLastUpdate));
80
80
  }
81
- const twapSpread = markTwapWithMantissa.sub(oracleTwapWithMantissa);
81
+ const twapSpread = lastMarkTwapWithMantissa.sub(lastOracleTwapWithMantissa);
82
82
  const twapSpreadPct = twapSpread
83
83
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
84
84
  .mul(new anchor_1.BN(100))
@@ -193,9 +193,8 @@ exports.calculateEstimatedFundingRate = calculateEstimatedFundingRate;
193
193
  /**
194
194
  *
195
195
  * @param market
196
- * @param pythClient
196
+ * @param oraclePriceData
197
197
  * @param periodAdjustment
198
- * @param estimationMethod
199
198
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
200
199
  */
201
200
  function calculateLongShortFundingRate(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
@@ -216,9 +215,8 @@ exports.calculateLongShortFundingRate = calculateLongShortFundingRate;
216
215
  /**
217
216
  *
218
217
  * @param market
219
- * @param pythClient
218
+ * @param oraclePriceData
220
219
  * @param periodAdjustment
221
- * @param estimationMethod
222
220
  * @returns Estimated funding rate. : Precision //TODO-PRECISION
223
221
  */
224
222
  function calculateLongShortFundingRateAndLiveTwaps(market, oraclePriceData, periodAdjustment = new anchor_1.BN(1)) {
@@ -244,7 +242,7 @@ exports.calculateLongShortFundingRateAndLiveTwaps = calculateLongShortFundingRat
244
242
  function calculateFundingPool(market) {
245
243
  // todo
246
244
  const totalFeeLB = market.amm.totalFee.div(new anchor_1.BN(2));
247
- const feePool = market.amm.totalFeeMinusDistributions.sub(totalFeeLB);
245
+ const feePool = anchor_1.BN.max(numericConstants_1.ZERO, market.amm.totalFeeMinusDistributions.sub(totalFeeLB));
248
246
  return feePool;
249
247
  }
250
248
  exports.calculateFundingPool = calculateFundingPool;
@@ -1,6 +1,6 @@
1
- import { MarketsAccount, StateAccount } from "../types";
2
- import BN from "bn.js";
3
- import { Connection } from "@solana/web3.js";
1
+ import { MarketsAccount, StateAccount } from '../types';
2
+ import BN from 'bn.js';
3
+ import { Connection } from '@solana/web3.js';
4
4
  /**
5
5
  * In the case of a levered loss, the exchange first pays out undistributed fees and then the insurance fund.
6
6
  * Thus the de facto size of the insurance fund is the amount in the insurance vault plus the sum of each markets
@@ -9,6 +9,7 @@ import { Connection } from "@solana/web3.js";
9
9
  * @param connection
10
10
  * @param state
11
11
  * @param marketsAccount
12
+ * @returns Precision : QUOTE_ASSET_PRECISION
12
13
  */
13
14
  export declare function calculateInsuranceFundSize(connection: Connection, state: StateAccount, marketsAccount: MarketsAccount): Promise<BN>;
14
15
  //# sourceMappingURL=insuranceFund.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"insuranceFund.d.ts","sourceRoot":"","sources":["../../src/math/insuranceFund.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,cAAc,EAAE,YAAY,EAAC,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,MAAM,OAAO,CAAC;AACvB,OAAO,EAAC,UAAU,EAAC,MAAM,iBAAiB,CAAC;AAE3C;;;;;;;;GAQG;AACH,wBAAsB,0BAA0B,CAAC,UAAU,EAAE,UAAU,EAAE,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,cAAc,GAAI,OAAO,CAAC,EAAE,CAAC,CAQ1I"}
1
+ {"version":3,"file":"insuranceFund.d.ts","sourceRoot":"","sources":["../../src/math/insuranceFund.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,EAAE,MAAM,OAAO,CAAC;AACvB,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C;;;;;;;;;GASG;AACH,wBAAsB,0BAA0B,CAC/C,UAAU,EAAE,UAAU,EACtB,KAAK,EAAE,YAAY,EACnB,cAAc,EAAE,cAAc,GAC5B,OAAO,CAAC,EAAE,CAAC,CAUb"}
@@ -22,6 +22,7 @@ const bn_js_1 = __importDefault(require("bn.js"));
22
22
  * @param connection
23
23
  * @param state
24
24
  * @param marketsAccount
25
+ * @returns Precision : QUOTE_ASSET_PRECISION
25
26
  */
26
27
  function calculateInsuranceFundSize(connection, state, marketsAccount) {
27
28
  return __awaiter(this, void 0, void 0, function* () {
@@ -9,6 +9,6 @@ const amm_1 = require("./amm");
9
9
  * @return markPrice : Precision MARK_PRICE_PRECISION
10
10
  */
11
11
  function calculateMarkPrice(market) {
12
- return amm_1.calculatePrice(market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier);
12
+ return (0, amm_1.calculatePrice)(market.amm.baseAssetReserve, market.amm.quoteAssetReserve, market.amm.pegMultiplier);
13
13
  }
14
14
  exports.calculateMarkPrice = calculateMarkPrice;
@@ -1 +1 @@
1
- {"version":3,"file":"position.d.ts","sourceRoot":"","sources":["../../src/math/position.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,OAAO,CAAC;AAUvB,OAAO,EAAE,MAAM,EAAqB,YAAY,EAAE,MAAM,UAAU,CAAC;AAGnE;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACtC,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,YAAY,GACxB,EAAE,CA6BJ;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CACnC,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,YAAY,EAC5B,WAAW,UAAQ,GACjB,EAAE,CAwBJ;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAC1C,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,YAAY,GAC1B,EAAE,CAoBJ;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,YAAY,EAAE,YAAY,GAAG,EAAE,CAUlE"}
1
+ {"version":3,"file":"position.d.ts","sourceRoot":"","sources":["../../src/math/position.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,OAAO,CAAC;AAWvB,OAAO,EAAE,MAAM,EAAqB,YAAY,EAAE,MAAM,UAAU,CAAC;AAGnE;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACtC,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,YAAY,GACxB,EAAE,CA6BJ;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CACnC,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,YAAY,EAC5B,WAAW,UAAQ,GACjB,EAAE,CAwBJ;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAC1C,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,YAAY,GAC1B,EAAE,CAoBJ;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,YAAY,EAAE,YAAY,GAAG,EAAE,CAUlE"}
@@ -22,7 +22,7 @@ function calculateBaseAssetValue(market, userPosition) {
22
22
  const directionToClose = userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
23
23
  ? types_1.PositionDirection.SHORT
24
24
  : types_1.PositionDirection.LONG;
25
- const [newQuoteAssetReserve, _] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', userPosition.baseAssetAmount.abs(), amm_1.getSwapDirection('base', directionToClose));
25
+ const [newQuoteAssetReserve, _] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, 'base', userPosition.baseAssetAmount.abs(), (0, amm_1.getSwapDirection)('base', directionToClose));
26
26
  switch (directionToClose) {
27
27
  case types_1.PositionDirection.SHORT:
28
28
  return market.amm.quoteAssetReserve
package/lib/math/trade.js CHANGED
@@ -25,18 +25,18 @@ const MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
25
25
  * 'newPrice' => the price of the asset after the trade : Precision MARK_PRICE_PRECISION
26
26
  */
27
27
  function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quote') {
28
- const oldPrice = market_1.calculateMarkPrice(market);
28
+ const oldPrice = (0, market_1.calculateMarkPrice)(market);
29
29
  if (amount.eq(numericConstants_1.ZERO)) {
30
30
  return [numericConstants_1.ZERO, numericConstants_1.ZERO, oldPrice, oldPrice];
31
31
  }
32
32
  const [acquiredBase, acquiredQuote] = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType);
33
- const entryPrice = amm_1.calculatePrice(acquiredBase, acquiredQuote, market.amm.pegMultiplier).mul(new anchor_1.BN(-1));
34
- const newPrice = amm_1.calculatePrice(market.amm.baseAssetReserve.sub(acquiredBase), market.amm.quoteAssetReserve.sub(acquiredQuote), market.amm.pegMultiplier);
33
+ const entryPrice = (0, amm_1.calculatePrice)(acquiredBase, acquiredQuote, market.amm.pegMultiplier).mul(new anchor_1.BN(-1));
34
+ const newPrice = (0, amm_1.calculatePrice)(market.amm.baseAssetReserve.sub(acquiredBase), market.amm.quoteAssetReserve.sub(acquiredQuote), market.amm.pegMultiplier);
35
35
  if (direction == types_1.PositionDirection.SHORT) {
36
- assert_1.assert(newPrice.lt(oldPrice));
36
+ (0, assert_1.assert)(newPrice.lt(oldPrice));
37
37
  }
38
38
  else {
39
- assert_1.assert(oldPrice.lt(newPrice));
39
+ (0, assert_1.assert)(oldPrice.lt(newPrice));
40
40
  }
41
41
  const pctMaxSlippage = newPrice
42
42
  .sub(oldPrice)
@@ -64,7 +64,7 @@ function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType
64
64
  if (amount.eq(numericConstants_1.ZERO)) {
65
65
  return [numericConstants_1.ZERO, numericConstants_1.ZERO];
66
66
  }
67
- const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(market.amm, inputAssetType, amount, amm_1.getSwapDirection(inputAssetType, direction));
67
+ const [newQuoteAssetReserve, newBaseAssetReserve] = (0, amm_1.calculateAmmReservesAfterSwap)(market.amm, inputAssetType, amount, (0, amm_1.getSwapDirection)(inputAssetType, direction));
68
68
  const acquiredBase = market.amm.baseAssetReserve.sub(newBaseAssetReserve);
69
69
  const acquiredQuote = market.amm.quoteAssetReserve.sub(newQuoteAssetReserve);
70
70
  return [acquiredBase, acquiredQuote];
@@ -86,10 +86,10 @@ exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
86
86
  * ]
87
87
  */
88
88
  function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAssetType = 'quote') {
89
- assert_1.assert(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
90
- assert_1.assert(targetPrice.gt(numericConstants_1.ZERO));
91
- assert_1.assert(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
92
- const markPriceBefore = market_1.calculateMarkPrice(market);
89
+ (0, assert_1.assert)(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
90
+ (0, assert_1.assert)(targetPrice.gt(numericConstants_1.ZERO));
91
+ (0, assert_1.assert)(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
92
+ const markPriceBefore = (0, market_1.calculateMarkPrice)(market);
93
93
  if (targetPrice.gt(markPriceBefore)) {
94
94
  const priceGap = targetPrice.sub(markPriceBefore);
95
95
  const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
@@ -114,11 +114,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
114
114
  let markPriceAfter;
115
115
  if (markPriceBefore.gt(targetPrice)) {
116
116
  // overestimate y2
117
- baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
117
+ baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
118
118
  quoteAssetReserveAfter = k
119
119
  .div(numericConstants_1.MARK_PRICE_PRECISION)
120
120
  .div(baseAssetReserveAfter);
121
- markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
121
+ markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
122
122
  direction = types_1.PositionDirection.SHORT;
123
123
  tradeSize = quoteAssetReserveBefore
124
124
  .sub(quoteAssetReserveAfter)
@@ -129,11 +129,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
129
129
  }
130
130
  else if (markPriceBefore.lt(targetPrice)) {
131
131
  // underestimate y2
132
- baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
132
+ baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
133
133
  quoteAssetReserveAfter = k
134
134
  .div(numericConstants_1.MARK_PRICE_PRECISION)
135
135
  .div(baseAssetReserveAfter);
136
- markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
136
+ markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
137
137
  direction = types_1.PositionDirection.LONG;
138
138
  tradeSize = quoteAssetReserveAfter
139
139
  .sub(quoteAssetReserveBefore)
@@ -160,8 +160,8 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
160
160
  .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
161
161
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
162
162
  .div(baseSize.abs());
163
- assert_1.assert(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
164
- assert_1.assert(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
163
+ (0, assert_1.assert)(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
164
+ (0, assert_1.assert)(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
165
165
  tp2.toString() +
166
166
  '>=' +
167
167
  tp1.toString() +
package/lib/pythClient.js CHANGED
@@ -18,7 +18,7 @@ class PythClient {
18
18
  getPriceData(pricePublicKey) {
19
19
  return __awaiter(this, void 0, void 0, function* () {
20
20
  const account = yield this.connection.getAccountInfo(pricePublicKey);
21
- return client_1.parsePriceData(account.data);
21
+ return (0, client_1.parsePriceData)(account.data);
22
22
  });
23
23
  }
24
24
  }
@@ -0,0 +1,3 @@
1
+ import { Connection, Finality, PublicKey } from '@solana/web3.js';
2
+ export declare function findComputeUnitConsumption(programId: PublicKey, connection: Connection, txSignature: string, commitment?: Finality): Promise<number[]>;
3
+ //# sourceMappingURL=computeUnits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"computeUnits.d.ts","sourceRoot":"","sources":["../../src/util/computeUnits.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAElE,wBAAsB,0BAA0B,CAC/C,SAAS,EAAE,SAAS,EACpB,UAAU,EAAE,UAAU,EACtB,WAAW,EAAE,MAAM,EACnB,UAAU,GAAE,QAAsB,GAChC,OAAO,CAAC,MAAM,EAAE,CAAC,CAanB"}
@@ -0,0 +1,27 @@
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.findComputeUnitConsumption = void 0;
13
+ function findComputeUnitConsumption(programId, connection, txSignature, commitment = 'confirmed') {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ const tx = yield connection.getTransaction(txSignature, { commitment });
16
+ const computeUnits = [];
17
+ const regex = new RegExp(`Program ${programId.toString()} consumed ([0-9]{0,6}) of 200000 compute units`);
18
+ tx.meta.logMessages.forEach((logMessage) => {
19
+ const match = logMessage.match(regex);
20
+ if (match && match[1]) {
21
+ computeUnits.push(match[1]);
22
+ }
23
+ });
24
+ return computeUnits;
25
+ });
26
+ }
27
+ exports.findComputeUnitConsumption = findComputeUnitConsumption;
@@ -0,0 +1,3 @@
1
+ import { Connection, PublicKey } from '@solana/web3.js';
2
+ export declare function estimateTps(programId: PublicKey, connection: Connection, failed: boolean): Promise<number>;
3
+ //# sourceMappingURL=tps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tps.d.ts","sourceRoot":"","sources":["../../src/util/tps.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAExD,wBAAsB,WAAW,CAChC,SAAS,EAAE,SAAS,EACpB,UAAU,EAAE,UAAU,EACtB,MAAM,EAAE,OAAO,GACb,OAAO,CAAC,MAAM,CAAC,CAoBjB"}
@@ -0,0 +1,27 @@
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.estimateTps = void 0;
13
+ function estimateTps(programId, connection, failed) {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ let signatures = yield connection.getSignaturesForAddress(programId, undefined, 'finalized');
16
+ if (failed) {
17
+ signatures = signatures.filter((signature) => signature.err);
18
+ }
19
+ const numberOfSignatures = signatures.length;
20
+ if (numberOfSignatures === 0) {
21
+ return 0;
22
+ }
23
+ return (numberOfSignatures /
24
+ (signatures[0].blockTime - signatures[numberOfSignatures - 1].blockTime));
25
+ });
26
+ }
27
+ exports.estimateTps = estimateTps;
package/lib/wallet.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Keypair, PublicKey, Transaction } from "@solana/web3.js";
2
- import { IWallet } from "./types";
1
+ import { Keypair, PublicKey, Transaction } from '@solana/web3.js';
2
+ import { IWallet } from './types';
3
3
  export declare class Wallet implements IWallet {
4
4
  readonly payer: Keypair;
5
5
  constructor(payer: Keypair);
@@ -1 +1 @@
1
- {"version":3,"file":"wallet.d.ts","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,EAAE,SAAS,EAAE,WAAW,EAAC,MAAM,iBAAiB,CAAC;AAChE,OAAO,EAAC,OAAO,EAAC,MAAM,SAAS,CAAC;AAEhC,qBAAa,MAAO,YAAW,OAAO;IACtB,QAAQ,CAAC,KAAK,EAAE,OAAO;gBAAd,KAAK,EAAE,OAAO;IAE7B,eAAe,CAAC,EAAE,EAAE,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;IAKtD,mBAAmB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAOrE,IAAI,SAAS,IAAI,SAAS,CAEzB;CACJ"}
1
+ {"version":3,"file":"wallet.d.ts","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAClE,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC,qBAAa,MAAO,YAAW,OAAO;IACzB,QAAQ,CAAC,KAAK,EAAE,OAAO;gBAAd,KAAK,EAAE,OAAO;IAE7B,eAAe,CAAC,EAAE,EAAE,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;IAKtD,mBAAmB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAOrE,IAAI,SAAS,IAAI,SAAS,CAEzB;CACD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "0.1.13",
3
+ "version": "0.1.17-master.0",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
@@ -12,9 +12,7 @@
12
12
  "scripts": {
13
13
  "build": "yarn clean && tsc",
14
14
  "clean": "rm -rf lib",
15
- "patch-and-pub": "npm version patch --force && npm publish",
16
- "prettify": "prettier --write './src/**/*.{ts,tsx}'",
17
- "lint": "eslint . --ext ts --ext tsx --ext js --quiet"
15
+ "patch-and-pub": "npm version patch --force && npm publish"
18
16
  },
19
17
  "keywords": [
20
18
  "drift-labs",
@@ -36,14 +34,6 @@
36
34
  "@types/bn.js": "^5.1.0",
37
35
  "strict-event-emitter-types": "^2.0.0"
38
36
  },
39
- "devDependencies": {
40
- "@typescript-eslint/eslint-plugin": "^4.28.0",
41
- "@typescript-eslint/parser": "^4.28.0",
42
- "eslint": "^7.29.0",
43
- "eslint-config-prettier": "^8.3.0",
44
- "eslint-plugin-prettier": "^3.4.0",
45
- "prettier": "^2.4.1"
46
- },
47
37
  "description": "SDK for Drift Protocol v1",
48
38
  "engines": {
49
39
  "node": ">=12"
@@ -194,6 +194,24 @@ export class DefaultClearingHouseAccountSubscriber
194
194
  return true;
195
195
  }
196
196
 
197
+ public async fetch(): Promise<void> {
198
+ if (!this.isSubscribed) {
199
+ return;
200
+ }
201
+
202
+ const promises = this.optionalExtraSubscriptions
203
+ .map((optionalSubscription) => {
204
+ const subscriber = `${optionalSubscription}Subscriber`;
205
+ return this[subscriber].fetch();
206
+ })
207
+ .concat([
208
+ this.stateAccountSubscriber.fetch(),
209
+ this.marketsAccountSubscriber.fetch(),
210
+ ]);
211
+
212
+ await Promise.all(promises);
213
+ }
214
+
197
215
  public async unsubscribe(): Promise<void> {
198
216
  if (!this.isSubscribed) {
199
217
  return;
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  AccountSubscriber,
3
+ NotSubscribedError,
3
4
  UserAccountEvents,
4
5
  UserAccountSubscriber,
5
6
  } from './types';
@@ -65,6 +66,13 @@ export class DefaultUserAccountSubscriber implements UserAccountSubscriber {
65
66
  return true;
66
67
  }
67
68
 
69
+ async fetch(): Promise<void> {
70
+ await Promise.all([
71
+ this.userDataAccountSubscriber.fetch(),
72
+ this.userPositionsAccountSubscriber.fetch(),
73
+ ]);
74
+ }
75
+
68
76
  async unsubscribe(): Promise<void> {
69
77
  if (!this.isSubscribed) {
70
78
  return;
@@ -76,11 +84,21 @@ export class DefaultUserAccountSubscriber implements UserAccountSubscriber {
76
84
  this.isSubscribed = false;
77
85
  }
78
86
 
87
+ assertIsSubscribed(): void {
88
+ if (!this.isSubscribed) {
89
+ throw new NotSubscribedError(
90
+ 'You must call `subscribe` before using this function'
91
+ );
92
+ }
93
+ }
94
+
79
95
  public getUserAccount(): UserAccount {
96
+ this.assertIsSubscribed();
80
97
  return this.userDataAccountSubscriber.data;
81
98
  }
82
99
 
83
100
  public getUserPositionsAccount(): UserPositionsAccount {
101
+ this.assertIsSubscribed();
84
102
  return this.userPositionsAccountSubscriber.data;
85
103
  }
86
104
  }
@@ -16,6 +16,7 @@ import { EventEmitter } from 'events';
16
16
  export interface AccountSubscriber<T> {
17
17
  data?: T;
18
18
  subscribe(onChange: (data: T) => void): Promise<void>;
19
+ fetch(): Promise<void>;
19
20
  unsubscribe(): void;
20
21
  }
21
22
 
@@ -54,7 +55,7 @@ export interface ClearingHouseAccountSubscriber {
54
55
  subscribe(
55
56
  optionalSubscriptions?: ClearingHouseAccountTypes[]
56
57
  ): Promise<boolean>;
57
-
58
+ fetch(): Promise<void>;
58
59
  unsubscribe(): Promise<void>;
59
60
 
60
61
  getStateAccount(): StateAccount;
@@ -78,6 +79,7 @@ export interface UserAccountSubscriber {
78
79
  isSubscribed: boolean;
79
80
 
80
81
  subscribe(): Promise<boolean>;
82
+ fetch(): Promise<void>;
81
83
  unsubscribe(): Promise<void>;
82
84
 
83
85
  getUserAccount(): UserAccount;
@@ -7,6 +7,7 @@ export class WebSocketAccountSubscriber<T> implements AccountSubscriber<T> {
7
7
  accountName: string;
8
8
  program: Program;
9
9
  accountPublicKey: PublicKey;
10
+ onChange: (data: T) => void;
10
11
 
11
12
  public constructor(
12
13
  accountName: string,
@@ -19,20 +20,29 @@ export class WebSocketAccountSubscriber<T> implements AccountSubscriber<T> {
19
20
  }
20
21
 
21
22
  async subscribe(onChange: (data: T) => void): Promise<void> {
22
- this.data = (await this.program.account[this.accountName].fetch(
23
- this.accountPublicKey
24
- )) as T;
25
-
26
- onChange(this.data);
23
+ this.onChange = onChange;
24
+ await this.fetch();
27
25
 
28
26
  this.program.account[this.accountName]
29
27
  .subscribe(this.accountPublicKey, this.program.provider.opts.commitment)
30
28
  .on('change', async (data: T) => {
31
29
  this.data = data;
32
- onChange(data);
30
+ this.onChange(data);
33
31
  });
34
32
  }
35
33
 
34
+ async fetch(): Promise<void> {
35
+ const newData = (await this.program.account[this.accountName].fetch(
36
+ this.accountPublicKey
37
+ )) as T;
38
+
39
+ // if data has changed trigger update
40
+ if (JSON.stringify(newData) !== JSON.stringify(this.data)) {
41
+ this.data = newData;
42
+ this.onChange(this.data);
43
+ }
44
+ }
45
+
36
46
  unsubscribe(): Promise<void> {
37
47
  return this.program.account[this.accountName].unsubscribe(
38
48
  this.accountPublicKey
@@ -16,7 +16,6 @@ import {
16
16
  PositionDirection,
17
17
  TradeHistoryAccount,
18
18
  UserAccount,
19
- UserPositionsAccount,
20
19
  Market,
21
20
  } from './types';
22
21
  import * as anchor from '@project-serum/anchor';
@@ -140,6 +139,13 @@ export class ClearingHouse {
140
139
  ]);
141
140
  }
142
141
 
142
+ /**
143
+ * Forces the accountSubscriber to fetch account updates from rpc
144
+ */
145
+ public async fetchAccounts(): Promise<void> {
146
+ await this.accountSubscriber.fetch();
147
+ }
148
+
143
149
  /**
144
150
  * Unsubscribe from all currently subscribed state accounts
145
151
  */