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

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 (193) hide show
  1. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +13 -13
  2. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +27 -27
  3. package/lib/accounts/types.d.ts +8 -9
  4. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +14 -14
  5. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +35 -34
  6. package/lib/addresses/pda.d.ts +8 -6
  7. package/lib/addresses/pda.js +35 -27
  8. package/lib/admin.d.ts +9 -6
  9. package/lib/admin.js +90 -54
  10. package/lib/clearingHouse.d.ts +71 -42
  11. package/lib/clearingHouse.js +765 -282
  12. package/lib/clearingHouseConfig.d.ts +2 -2
  13. package/lib/clearingHouseUser.d.ts +19 -17
  14. package/lib/clearingHouseUser.js +145 -123
  15. package/lib/config.d.ts +7 -7
  16. package/lib/config.js +21 -21
  17. package/lib/constants/numericConstants.d.ts +12 -12
  18. package/lib/constants/numericConstants.js +13 -13
  19. package/lib/constants/{markets.d.ts → perpMarkets.d.ts} +5 -5
  20. package/{src/constants/markets.js → lib/constants/perpMarkets.js} +4 -4
  21. package/lib/constants/{banks.d.ts → spotMarkets.d.ts} +6 -6
  22. package/lib/constants/{banks.js → spotMarkets.js} +16 -16
  23. package/lib/events/eventSubscriber.d.ts +4 -2
  24. package/lib/events/eventSubscriber.js +16 -9
  25. package/lib/events/fetchLogs.d.ts +10 -1
  26. package/lib/events/fetchLogs.js +27 -7
  27. package/lib/events/pollingLogProvider.d.ts +2 -1
  28. package/lib/events/pollingLogProvider.js +6 -2
  29. package/lib/events/types.d.ts +4 -2
  30. package/lib/events/types.js +2 -0
  31. package/lib/examples/makeTradeExample.js +18 -6
  32. package/lib/idl/clearing_house.json +1128 -347
  33. package/lib/index.d.ts +6 -3
  34. package/lib/index.js +6 -3
  35. package/lib/math/amm.d.ts +5 -3
  36. package/lib/math/amm.js +42 -4
  37. package/lib/math/funding.d.ts +6 -6
  38. package/lib/math/funding.js +2 -1
  39. package/lib/math/margin.d.ts +4 -4
  40. package/lib/math/margin.js +18 -11
  41. package/lib/math/market.d.ts +10 -9
  42. package/lib/math/market.js +29 -6
  43. package/lib/math/oracles.d.ts +2 -1
  44. package/lib/math/oracles.js +11 -1
  45. package/lib/math/orders.d.ts +5 -5
  46. package/lib/math/position.d.ts +13 -13
  47. package/lib/math/position.js +19 -19
  48. package/lib/math/spotBalance.d.ts +19 -0
  49. package/lib/math/spotBalance.js +176 -0
  50. package/lib/math/spotMarket.d.ts +4 -0
  51. package/lib/math/spotMarket.js +8 -0
  52. package/lib/math/spotPosition.d.ts +2 -0
  53. package/lib/math/spotPosition.js +8 -0
  54. package/lib/math/state.js +2 -2
  55. package/lib/math/trade.d.ts +4 -4
  56. package/lib/orderParams.d.ts +4 -4
  57. package/lib/orderParams.js +12 -4
  58. package/lib/serum/serumSubscriber.d.ts +23 -0
  59. package/lib/serum/serumSubscriber.js +41 -0
  60. package/lib/serum/types.d.ts +11 -0
  61. package/lib/serum/types.js +2 -0
  62. package/lib/tx/retryTxSender.d.ts +1 -1
  63. package/lib/tx/retryTxSender.js +4 -2
  64. package/lib/tx/types.d.ts +1 -1
  65. package/lib/types.d.ts +148 -39
  66. package/lib/types.js +37 -9
  67. package/my-script/.env +7 -0
  68. package/my-script/getUserStats.ts +106 -0
  69. package/my-script/multiConnections.ts +119 -0
  70. package/my-script/test-regex.ts +11 -0
  71. package/my-script/utils.ts +52 -0
  72. package/package.json +1 -1
  73. package/src/accounts/bulkAccountLoader.js +249 -0
  74. package/src/accounts/bulkUserStatsSubscription.js +75 -0
  75. package/src/accounts/bulkUserSubscription.js +75 -0
  76. package/src/accounts/fetch.js +92 -0
  77. package/src/accounts/pollingClearingHouseAccountSubscriber.js +465 -0
  78. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +38 -38
  79. package/src/accounts/pollingOracleSubscriber.js +156 -0
  80. package/src/accounts/pollingTokenAccountSubscriber.js +141 -0
  81. package/src/accounts/pollingUserAccountSubscriber.js +208 -0
  82. package/src/accounts/pollingUserStatsAccountSubscriber.js +208 -0
  83. package/src/accounts/types.js +28 -0
  84. package/src/accounts/types.ts +11 -9
  85. package/src/accounts/utils.js +7 -0
  86. package/src/accounts/webSocketAccountSubscriber.js +138 -0
  87. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +433 -0
  88. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +59 -52
  89. package/src/accounts/webSocketUserAccountSubscriber.js +113 -0
  90. package/src/accounts/webSocketUserStatsAccountSubsriber.js +113 -0
  91. package/src/addresses/pda.js +186 -0
  92. package/src/addresses/pda.ts +56 -42
  93. package/src/admin.js +1284 -0
  94. package/src/admin.ts +149 -75
  95. package/src/assert/assert.js +1 -1
  96. package/src/clearingHouse.js +3433 -0
  97. package/src/clearingHouse.ts +1097 -380
  98. package/src/clearingHouseConfig.js +2 -0
  99. package/src/clearingHouseConfig.ts +2 -2
  100. package/src/clearingHouseUser.js +874 -0
  101. package/src/clearingHouseUser.ts +237 -172
  102. package/src/clearingHouseUserConfig.js +2 -0
  103. package/src/clearingHouseUserStats.js +115 -0
  104. package/src/clearingHouseUserStatsConfig.js +2 -0
  105. package/src/config.js +80 -0
  106. package/src/config.ts +30 -30
  107. package/src/constants/numericConstants.js +18 -11
  108. package/src/constants/numericConstants.ts +17 -15
  109. package/{lib/constants/markets.js → src/constants/perpMarkets.js} +11 -11
  110. package/src/constants/{markets.ts → perpMarkets.ts} +5 -5
  111. package/src/constants/spotMarkets.js +51 -0
  112. package/src/constants/{banks.ts → spotMarkets.ts} +19 -19
  113. package/src/events/eventList.js +66 -23
  114. package/src/events/eventSubscriber.js +202 -0
  115. package/src/events/eventSubscriber.ts +20 -12
  116. package/src/events/fetchLogs.js +117 -0
  117. package/src/events/fetchLogs.ts +35 -8
  118. package/src/events/pollingLogProvider.js +113 -0
  119. package/src/events/pollingLogProvider.ts +10 -2
  120. package/src/events/sort.js +41 -0
  121. package/src/events/txEventCache.js +22 -19
  122. package/src/events/types.js +25 -0
  123. package/src/events/types.ts +7 -1
  124. package/src/events/webSocketLogProvider.js +76 -0
  125. package/src/examples/makeTradeExample.ts +27 -6
  126. package/src/factory/bigNum.js +183 -180
  127. package/src/factory/oracleClient.js +9 -9
  128. package/src/idl/clearing_house.json +1128 -347
  129. package/src/index.js +75 -0
  130. package/src/index.ts +6 -3
  131. package/src/math/amm.js +422 -0
  132. package/src/math/amm.ts +73 -5
  133. package/src/math/auction.js +10 -10
  134. package/src/math/conversion.js +4 -3
  135. package/src/math/funding.js +223 -175
  136. package/src/math/funding.ts +7 -7
  137. package/src/math/insurance.js +27 -0
  138. package/src/math/margin.js +77 -0
  139. package/src/math/margin.ts +34 -23
  140. package/src/math/market.js +105 -0
  141. package/src/math/market.ts +71 -19
  142. package/src/math/oracles.js +40 -10
  143. package/src/math/oracles.ts +18 -1
  144. package/src/math/orders.js +153 -0
  145. package/src/math/orders.ts +5 -5
  146. package/src/math/position.js +172 -0
  147. package/src/math/position.ts +31 -31
  148. package/src/math/repeg.js +40 -40
  149. package/src/math/spotBalance.js +176 -0
  150. package/src/math/spotBalance.ts +290 -0
  151. package/src/math/spotMarket.js +8 -0
  152. package/src/math/spotMarket.ts +9 -0
  153. package/src/math/spotPosition.js +8 -0
  154. package/src/math/spotPosition.ts +6 -0
  155. package/src/math/state.ts +2 -2
  156. package/src/math/trade.js +81 -74
  157. package/src/math/trade.ts +4 -4
  158. package/src/math/utils.js +8 -7
  159. package/src/oracles/oracleClientCache.js +10 -9
  160. package/src/oracles/pythClient.js +52 -17
  161. package/src/oracles/quoteAssetOracleClient.js +44 -13
  162. package/src/oracles/switchboardClient.js +69 -37
  163. package/src/oracles/types.js +1 -1
  164. package/src/orderParams.js +14 -6
  165. package/src/orderParams.ts +16 -8
  166. package/src/serum/serumSubscriber.js +102 -0
  167. package/src/serum/serumSubscriber.ts +80 -0
  168. package/src/serum/types.js +2 -0
  169. package/src/serum/types.ts +13 -0
  170. package/src/slot/SlotSubscriber.js +67 -20
  171. package/src/token/index.js +4 -4
  172. package/src/tokenFaucet.js +288 -154
  173. package/src/tx/retryTxSender.js +280 -0
  174. package/src/tx/retryTxSender.ts +5 -2
  175. package/src/tx/types.js +1 -1
  176. package/src/tx/types.ts +2 -1
  177. package/src/tx/utils.js +7 -6
  178. package/src/types.js +216 -0
  179. package/src/types.ts +131 -39
  180. package/src/userName.js +5 -5
  181. package/src/util/computeUnits.js +46 -11
  182. package/src/util/promiseTimeout.js +5 -5
  183. package/src/util/tps.js +46 -12
  184. package/src/wallet.js +55 -18
  185. package/lib/math/bankBalance.d.ts +0 -15
  186. package/lib/math/bankBalance.js +0 -150
  187. package/src/addresses/marketAddresses.js +0 -26
  188. package/src/constants/banks.js +0 -42
  189. package/src/examples/makeTradeExample.js +0 -80
  190. package/src/math/bankBalance.ts +0 -258
  191. package/src/math/state.js +0 -15
  192. package/src/math/utils.js.map +0 -1
  193. package/src/util/getTokenAddress.js +0 -9
package/src/math/trade.js CHANGED
@@ -1,15 +1,15 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+ exports.__esModule = true;
3
3
  exports.calculateTargetPriceTrade = exports.calculateTradeAcquiredAmounts = exports.calculateTradeSlippage = void 0;
4
- const types_1 = require("../types");
5
- const anchor_1 = require("@project-serum/anchor");
6
- const assert_1 = require("../assert/assert");
7
- const numericConstants_1 = require("../constants/numericConstants");
8
- const market_1 = require("./market");
9
- const amm_1 = require("./amm");
10
- const utils_1 = require("./utils");
11
- const types_2 = require("../types");
12
- const MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
4
+ var types_1 = require("../types");
5
+ var anchor_1 = require("@project-serum/anchor");
6
+ var assert_1 = require("../assert/assert");
7
+ var numericConstants_1 = require("../constants/numericConstants");
8
+ var market_1 = require("./market");
9
+ var amm_1 = require("./amm");
10
+ var utils_1 = require("./utils");
11
+ var types_2 = require("../types");
12
+ var MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
13
13
  /**
14
14
  * Calculates avg/max slippage (price impact) for candidate trade
15
15
  * @param direction
@@ -27,53 +27,55 @@ const MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
27
27
  *
28
28
  * 'newPrice' => the price of the asset after the trade : Precision MARK_PRICE_PRECISION
29
29
  */
30
- function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quote', oraclePriceData, useSpread = true) {
31
- let oldPrice;
30
+ function calculateTradeSlippage(direction, amount, market, inputAssetType, oraclePriceData, useSpread) {
31
+ if (inputAssetType === void 0) { inputAssetType = 'quote'; }
32
+ if (useSpread === void 0) { useSpread = true; }
33
+ var oldPrice;
32
34
  if (useSpread && market.amm.baseSpread > 0) {
33
- if (types_2.isVariant(direction, 'long')) {
34
- oldPrice = market_1.calculateAskPrice(market, oraclePriceData);
35
+ if ((0, types_2.isVariant)(direction, 'long')) {
36
+ oldPrice = (0, market_1.calculateAskPrice)(market, oraclePriceData);
35
37
  }
36
38
  else {
37
- oldPrice = market_1.calculateBidPrice(market, oraclePriceData);
39
+ oldPrice = (0, market_1.calculateBidPrice)(market, oraclePriceData);
38
40
  }
39
41
  }
40
42
  else {
41
- oldPrice = market_1.calculateMarkPrice(market, oraclePriceData);
43
+ oldPrice = (0, market_1.calculateMarkPrice)(market, oraclePriceData);
42
44
  }
43
45
  if (amount.eq(numericConstants_1.ZERO)) {
44
46
  return [numericConstants_1.ZERO, numericConstants_1.ZERO, oldPrice, oldPrice];
45
47
  }
46
- const [acquiredBaseReserve, acquiredQuoteReserve, acquiredQuoteAssetAmount] = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType, oraclePriceData, useSpread);
47
- const entryPrice = acquiredQuoteAssetAmount
48
+ var _a = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType, oraclePriceData, useSpread), acquiredBaseReserve = _a[0], acquiredQuoteReserve = _a[1], acquiredQuoteAssetAmount = _a[2];
49
+ var entryPrice = acquiredQuoteAssetAmount
48
50
  .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
49
51
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
50
52
  .div(acquiredBaseReserve.abs());
51
- let amm;
53
+ var amm;
52
54
  if (useSpread && market.amm.baseSpread > 0) {
53
- const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
55
+ var _b = (0, amm_1.calculateUpdatedAMMSpreadReserves)(market.amm, direction, oraclePriceData), baseAssetReserve = _b.baseAssetReserve, quoteAssetReserve = _b.quoteAssetReserve, sqrtK = _b.sqrtK, newPeg = _b.newPeg;
54
56
  amm = {
55
- baseAssetReserve,
56
- quoteAssetReserve,
57
+ baseAssetReserve: baseAssetReserve,
58
+ quoteAssetReserve: quoteAssetReserve,
57
59
  sqrtK: sqrtK,
58
- pegMultiplier: newPeg,
60
+ pegMultiplier: newPeg
59
61
  };
60
62
  }
61
63
  else {
62
64
  amm = market.amm;
63
65
  }
64
- const newPrice = amm_1.calculatePrice(amm.baseAssetReserve.sub(acquiredBaseReserve), amm.quoteAssetReserve.sub(acquiredQuoteReserve), amm.pegMultiplier);
66
+ var newPrice = (0, amm_1.calculatePrice)(amm.baseAssetReserve.sub(acquiredBaseReserve), amm.quoteAssetReserve.sub(acquiredQuoteReserve), amm.pegMultiplier);
65
67
  if (direction == types_1.PositionDirection.SHORT) {
66
- assert_1.assert(newPrice.lte(oldPrice));
68
+ (0, assert_1.assert)(newPrice.lte(oldPrice));
67
69
  }
68
70
  else {
69
- assert_1.assert(oldPrice.lte(newPrice));
71
+ (0, assert_1.assert)(oldPrice.lte(newPrice));
70
72
  }
71
- const pctMaxSlippage = newPrice
73
+ var pctMaxSlippage = newPrice
72
74
  .sub(oldPrice)
73
75
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
74
76
  .div(oldPrice)
75
77
  .abs();
76
- const pctAvgSlippage = entryPrice
78
+ var pctAvgSlippage = entryPrice
77
79
  .sub(oldPrice)
78
80
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
79
81
  .div(oldPrice)
@@ -92,29 +94,31 @@ exports.calculateTradeSlippage = calculateTradeSlippage;
92
94
  * | 'acquiredBase' => positive/negative change in user's base : BN AMM_RESERVE_PRECISION
93
95
  * | 'acquiredQuote' => positive/negative change in user's quote : BN TODO-PRECISION
94
96
  */
95
- function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType = 'quote', oraclePriceData, useSpread = true) {
97
+ function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType, oraclePriceData, useSpread) {
98
+ if (inputAssetType === void 0) { inputAssetType = 'quote'; }
99
+ if (useSpread === void 0) { useSpread = true; }
96
100
  if (amount.eq(numericConstants_1.ZERO)) {
97
101
  return [numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO];
98
102
  }
99
- const swapDirection = amm_1.getSwapDirection(inputAssetType, direction);
100
- let amm;
103
+ var swapDirection = (0, amm_1.getSwapDirection)(inputAssetType, direction);
104
+ var amm;
101
105
  if (useSpread && market.amm.baseSpread > 0) {
102
- const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
106
+ var _a = (0, amm_1.calculateUpdatedAMMSpreadReserves)(market.amm, direction, oraclePriceData), baseAssetReserve = _a.baseAssetReserve, quoteAssetReserve = _a.quoteAssetReserve, sqrtK = _a.sqrtK, newPeg = _a.newPeg;
103
107
  amm = {
104
- baseAssetReserve,
105
- quoteAssetReserve,
108
+ baseAssetReserve: baseAssetReserve,
109
+ quoteAssetReserve: quoteAssetReserve,
106
110
  sqrtK: sqrtK,
107
- pegMultiplier: newPeg,
111
+ pegMultiplier: newPeg
108
112
  };
109
113
  }
110
114
  else {
111
115
  amm = market.amm;
112
116
  }
113
- const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(amm, inputAssetType, amount, swapDirection);
114
- const acquiredBase = amm.baseAssetReserve.sub(newBaseAssetReserve);
115
- const acquiredQuote = amm.quoteAssetReserve.sub(newQuoteAssetReserve);
116
- const acquiredQuoteAssetamount = amm_1.calculateQuoteAssetAmountSwapped(acquiredQuote.abs(), amm.pegMultiplier, swapDirection);
117
- return [acquiredBase, acquiredQuote, acquiredQuoteAssetamount];
117
+ var _b = (0, amm_1.calculateAmmReservesAfterSwap)(amm, inputAssetType, amount, swapDirection), newQuoteAssetReserve = _b[0], newBaseAssetReserve = _b[1];
118
+ var acquiredBase = amm.baseAssetReserve.sub(newBaseAssetReserve);
119
+ var acquiredQuote = amm.quoteAssetReserve.sub(newQuoteAssetReserve);
120
+ var acquiredQuoteAssetAmount = (0, amm_1.calculateQuoteAssetAmountSwapped)(acquiredQuote.abs(), amm.pegMultiplier, swapDirection);
121
+ return [acquiredBase, acquiredQuote, acquiredQuoteAssetAmount];
118
122
  }
119
123
  exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
120
124
  /**
@@ -134,33 +138,36 @@ exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
134
138
  * targetPrice => the target price MARK_PRICE_PRECISION
135
139
  * ]
136
140
  */
137
- function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAssetType = 'quote', oraclePriceData, useSpread = true) {
138
- assert_1.assert(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
139
- assert_1.assert(targetPrice.gt(numericConstants_1.ZERO));
140
- assert_1.assert(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
141
- const markPriceBefore = market_1.calculateMarkPrice(market, oraclePriceData);
142
- const bidPriceBefore = market_1.calculateBidPrice(market, oraclePriceData);
143
- const askPriceBefore = market_1.calculateAskPrice(market, oraclePriceData);
144
- let direction;
141
+ function calculateTargetPriceTrade(market, targetPrice, pct, outputAssetType, oraclePriceData, useSpread) {
142
+ if (pct === void 0) { pct = MAXPCT; }
143
+ if (outputAssetType === void 0) { outputAssetType = 'quote'; }
144
+ if (useSpread === void 0) { useSpread = true; }
145
+ (0, assert_1.assert)(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
146
+ (0, assert_1.assert)(targetPrice.gt(numericConstants_1.ZERO));
147
+ (0, assert_1.assert)(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
148
+ var markPriceBefore = (0, market_1.calculateMarkPrice)(market, oraclePriceData);
149
+ var bidPriceBefore = (0, market_1.calculateBidPrice)(market, oraclePriceData);
150
+ var askPriceBefore = (0, market_1.calculateAskPrice)(market, oraclePriceData);
151
+ var direction;
145
152
  if (targetPrice.gt(markPriceBefore)) {
146
- const priceGap = targetPrice.sub(markPriceBefore);
147
- const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
153
+ var priceGap = targetPrice.sub(markPriceBefore);
154
+ var priceGapScaled = priceGap.mul(pct).div(MAXPCT);
148
155
  targetPrice = markPriceBefore.add(priceGapScaled);
149
156
  direction = types_1.PositionDirection.LONG;
150
157
  }
151
158
  else {
152
- const priceGap = markPriceBefore.sub(targetPrice);
153
- const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
159
+ var priceGap = markPriceBefore.sub(targetPrice);
160
+ var priceGapScaled = priceGap.mul(pct).div(MAXPCT);
154
161
  targetPrice = markPriceBefore.sub(priceGapScaled);
155
162
  direction = types_1.PositionDirection.SHORT;
156
163
  }
157
- let tradeSize;
158
- let baseSize;
159
- let baseAssetReserveBefore;
160
- let quoteAssetReserveBefore;
161
- let peg = market.amm.pegMultiplier;
164
+ var tradeSize;
165
+ var baseSize;
166
+ var baseAssetReserveBefore;
167
+ var quoteAssetReserveBefore;
168
+ var peg = market.amm.pegMultiplier;
162
169
  if (useSpread && market.amm.baseSpread > 0) {
163
- const { baseAssetReserve, quoteAssetReserve, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, direction, oraclePriceData);
170
+ var _a = (0, amm_1.calculateUpdatedAMMSpreadReserves)(market.amm, direction, oraclePriceData), baseAssetReserve = _a.baseAssetReserve, quoteAssetReserve = _a.quoteAssetReserve, newPeg = _a.newPeg;
164
171
  baseAssetReserveBefore = baseAssetReserve;
165
172
  quoteAssetReserveBefore = quoteAssetReserve;
166
173
  peg = newPeg;
@@ -169,12 +176,12 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
169
176
  baseAssetReserveBefore = market.amm.baseAssetReserve;
170
177
  quoteAssetReserveBefore = market.amm.quoteAssetReserve;
171
178
  }
172
- const invariant = market.amm.sqrtK.mul(market.amm.sqrtK);
173
- const k = invariant.mul(numericConstants_1.MARK_PRICE_PRECISION);
174
- let baseAssetReserveAfter;
175
- let quoteAssetReserveAfter;
176
- const biasModifier = new anchor_1.BN(1);
177
- let markPriceAfter;
179
+ var invariant = market.amm.sqrtK.mul(market.amm.sqrtK);
180
+ var k = invariant.mul(numericConstants_1.MARK_PRICE_PRECISION);
181
+ var baseAssetReserveAfter;
182
+ var quoteAssetReserveAfter;
183
+ var biasModifier = new anchor_1.BN(1);
184
+ var markPriceAfter;
178
185
  if (useSpread &&
179
186
  targetPrice.lt(askPriceBefore) &&
180
187
  targetPrice.gt(bidPriceBefore)) {
@@ -190,11 +197,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
190
197
  }
191
198
  else if (markPriceBefore.gt(targetPrice)) {
192
199
  // overestimate y2
193
- baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
200
+ baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
194
201
  quoteAssetReserveAfter = k
195
202
  .div(numericConstants_1.MARK_PRICE_PRECISION)
196
203
  .div(baseAssetReserveAfter);
197
- markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
204
+ markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
198
205
  direction = types_1.PositionDirection.SHORT;
199
206
  tradeSize = quoteAssetReserveBefore
200
207
  .sub(quoteAssetReserveAfter)
@@ -205,11 +212,11 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
205
212
  }
206
213
  else if (markPriceBefore.lt(targetPrice)) {
207
214
  // underestimate y2
208
- baseAssetReserveAfter = utils_1.squareRootBN(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
215
+ baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
209
216
  quoteAssetReserveAfter = k
210
217
  .div(numericConstants_1.MARK_PRICE_PRECISION)
211
218
  .div(baseAssetReserveAfter);
212
- markPriceAfter = amm_1.calculatePrice(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
219
+ markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
213
220
  direction = types_1.PositionDirection.LONG;
214
221
  tradeSize = quoteAssetReserveAfter
215
222
  .sub(quoteAssetReserveBefore)
@@ -224,20 +231,20 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
224
231
  tradeSize = numericConstants_1.ZERO;
225
232
  return [direction, tradeSize, targetPrice, targetPrice];
226
233
  }
227
- let tp1 = targetPrice;
228
- let tp2 = markPriceAfter;
229
- let originalDiff = targetPrice.sub(markPriceBefore);
234
+ var tp1 = targetPrice;
235
+ var tp2 = markPriceAfter;
236
+ var originalDiff = targetPrice.sub(markPriceBefore);
230
237
  if (direction == types_1.PositionDirection.SHORT) {
231
238
  tp1 = markPriceAfter;
232
239
  tp2 = targetPrice;
233
240
  originalDiff = markPriceBefore.sub(targetPrice);
234
241
  }
235
- const entryPrice = tradeSize
242
+ var entryPrice = tradeSize
236
243
  .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
237
244
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
238
245
  .div(baseSize.abs());
239
- assert_1.assert(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
240
- assert_1.assert(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
246
+ (0, assert_1.assert)(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
247
+ (0, assert_1.assert)(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
241
248
  tp2.toString() +
242
249
  '>=' +
243
250
  tp1.toString() +
package/src/math/trade.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { MarketAccount, PositionDirection } from '../types';
1
+ import { PerpMarketAccount, PositionDirection } from '../types';
2
2
  import { BN } from '@project-serum/anchor';
3
3
  import { assert } from '../assert/assert';
4
4
  import {
@@ -59,7 +59,7 @@ export type PriceImpactUnit =
59
59
  export function calculateTradeSlippage(
60
60
  direction: PositionDirection,
61
61
  amount: BN,
62
- market: MarketAccount,
62
+ market: PerpMarketAccount,
63
63
  inputAssetType: AssetType = 'quote',
64
64
  oraclePriceData?: OraclePriceData,
65
65
  useSpread = true
@@ -147,7 +147,7 @@ export function calculateTradeSlippage(
147
147
  export function calculateTradeAcquiredAmounts(
148
148
  direction: PositionDirection,
149
149
  amount: BN,
150
- market: MarketAccount,
150
+ market: PerpMarketAccount,
151
151
  inputAssetType: AssetType = 'quote',
152
152
  oraclePriceData: OraclePriceData,
153
153
  useSpread = true
@@ -204,7 +204,7 @@ export function calculateTradeAcquiredAmounts(
204
204
  * ]
205
205
  */
206
206
  export function calculateTargetPriceTrade(
207
- market: MarketAccount,
207
+ market: PerpMarketAccount,
208
208
  targetPrice: BN,
209
209
  pct: BN = MAXPCT,
210
210
  outputAssetType: AssetType = 'quote',
package/src/math/utils.js CHANGED
@@ -1,15 +1,16 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+ exports.__esModule = true;
3
3
  exports.squareRootBN = void 0;
4
- const __1 = require("../");
5
- const squareRootBN = (n, closeness = new __1.BN(1)) => {
4
+ var __1 = require("../");
5
+ var squareRootBN = function (n, closeness) {
6
+ if (closeness === void 0) { closeness = new __1.BN(1); }
6
7
  // Assuming the sqrt of n as n only
7
- let x = n;
8
+ var x = n;
8
9
  // The closed guess will be stored in the root
9
- let root;
10
+ var root;
10
11
  // To count the number of iterations
11
- let count = 0;
12
- const TWO = new __1.BN(2);
12
+ var count = 0;
13
+ var TWO = new __1.BN(2);
13
14
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
14
15
  while (count < Number.MAX_SAFE_INTEGER) {
15
16
  count++;
@@ -1,19 +1,20 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+ exports.__esModule = true;
3
3
  exports.OracleClientCache = void 0;
4
- const oracleClient_1 = require("../factory/oracleClient");
5
- class OracleClientCache {
6
- constructor() {
4
+ var oracleClient_1 = require("../factory/oracleClient");
5
+ var OracleClientCache = /** @class */ (function () {
6
+ function OracleClientCache() {
7
7
  this.cache = new Map();
8
8
  }
9
- get(oracleSource, connection) {
10
- const key = Object.keys(oracleSource)[0];
9
+ OracleClientCache.prototype.get = function (oracleSource, connection) {
10
+ var key = Object.keys(oracleSource)[0];
11
11
  if (this.cache.has(key)) {
12
12
  return this.cache.get(key);
13
13
  }
14
- const client = oracleClient_1.getOracleClient(oracleSource, connection);
14
+ var client = (0, oracleClient_1.getOracleClient)(oracleSource, connection);
15
15
  this.cache.set(key, client);
16
16
  return client;
17
- }
18
- }
17
+ };
18
+ return OracleClientCache;
19
+ }());
19
20
  exports.OracleClientCache = OracleClientCache;
@@ -8,37 +8,72 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- Object.defineProperty(exports, "__esModule", { value: true });
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ exports.__esModule = true;
12
39
  exports.convertPythPrice = exports.PythClient = void 0;
13
- const client_1 = require("@pythnetwork/client");
14
- const anchor_1 = require("@project-serum/anchor");
15
- const numericConstants_1 = require("../constants/numericConstants");
16
- class PythClient {
17
- constructor(connection) {
40
+ var client_1 = require("@pythnetwork/client");
41
+ var anchor_1 = require("@project-serum/anchor");
42
+ var numericConstants_1 = require("../constants/numericConstants");
43
+ var PythClient = /** @class */ (function () {
44
+ function PythClient(connection) {
18
45
  this.connection = connection;
19
46
  }
20
- getOraclePriceData(pricePublicKey) {
21
- return __awaiter(this, void 0, void 0, function* () {
22
- const accountInfo = yield this.connection.getAccountInfo(pricePublicKey);
23
- return this.getOraclePriceDataFromBuffer(accountInfo.data);
47
+ PythClient.prototype.getOraclePriceData = function (pricePublicKey) {
48
+ return __awaiter(this, void 0, void 0, function () {
49
+ var accountInfo;
50
+ return __generator(this, function (_a) {
51
+ switch (_a.label) {
52
+ case 0: return [4 /*yield*/, this.connection.getAccountInfo(pricePublicKey)];
53
+ case 1:
54
+ accountInfo = _a.sent();
55
+ return [2 /*return*/, this.getOraclePriceDataFromBuffer(accountInfo.data)];
56
+ }
57
+ });
24
58
  });
25
- }
26
- getOraclePriceDataFromBuffer(buffer) {
27
- const priceData = client_1.parsePriceData(buffer);
59
+ };
60
+ PythClient.prototype.getOraclePriceDataFromBuffer = function (buffer) {
61
+ var priceData = (0, client_1.parsePriceData)(buffer);
28
62
  return {
29
63
  price: convertPythPrice(priceData.aggregate.price, priceData.exponent),
30
64
  slot: new anchor_1.BN(priceData.lastSlot.toString()),
31
65
  confidence: convertPythPrice(priceData.confidence, priceData.exponent),
32
66
  twap: convertPythPrice(priceData.twap.value, priceData.exponent),
33
67
  twapConfidence: convertPythPrice(priceData.twac.value, priceData.exponent),
34
- hasSufficientNumberOfDataPoints: true,
68
+ hasSufficientNumberOfDataPoints: true
35
69
  };
36
- }
37
- }
70
+ };
71
+ return PythClient;
72
+ }());
38
73
  exports.PythClient = PythClient;
39
74
  function convertPythPrice(price, exponent) {
40
75
  exponent = Math.abs(exponent);
41
- const pythPrecision = numericConstants_1.TEN.pow(new anchor_1.BN(exponent).abs());
76
+ var pythPrecision = numericConstants_1.TEN.pow(new anchor_1.BN(exponent).abs());
42
77
  return new anchor_1.BN(price * Math.pow(10, exponent))
43
78
  .mul(numericConstants_1.MARK_PRICE_PRECISION)
44
79
  .div(pythPrecision);
@@ -8,25 +8,56 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- Object.defineProperty(exports, "__esModule", { value: true });
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ exports.__esModule = true;
12
39
  exports.QuoteAssetOracleClient = exports.QUOTE_ORACLE_PRICE_DATA = void 0;
13
- const anchor_1 = require("@project-serum/anchor");
14
- const numericConstants_1 = require("../constants/numericConstants");
40
+ var anchor_1 = require("@project-serum/anchor");
41
+ var numericConstants_1 = require("../constants/numericConstants");
15
42
  exports.QUOTE_ORACLE_PRICE_DATA = {
16
43
  price: numericConstants_1.MARK_PRICE_PRECISION,
17
44
  slot: new anchor_1.BN(0),
18
45
  confidence: new anchor_1.BN(1),
19
- hasSufficientNumberOfDataPoints: true,
46
+ hasSufficientNumberOfDataPoints: true
20
47
  };
21
- class QuoteAssetOracleClient {
22
- constructor() { }
23
- getOraclePriceData(_pricePublicKey) {
24
- return __awaiter(this, void 0, void 0, function* () {
25
- return Promise.resolve(exports.QUOTE_ORACLE_PRICE_DATA);
26
- });
48
+ var QuoteAssetOracleClient = /** @class */ (function () {
49
+ function QuoteAssetOracleClient() {
27
50
  }
28
- getOraclePriceDataFromBuffer(_buffer) {
51
+ QuoteAssetOracleClient.prototype.getOraclePriceData = function (_pricePublicKey) {
52
+ return __awaiter(this, void 0, void 0, function () {
53
+ return __generator(this, function (_a) {
54
+ return [2 /*return*/, Promise.resolve(exports.QUOTE_ORACLE_PRICE_DATA)];
55
+ });
56
+ });
57
+ };
58
+ QuoteAssetOracleClient.prototype.getOraclePriceDataFromBuffer = function (_buffer) {
29
59
  return exports.QUOTE_ORACLE_PRICE_DATA;
30
- }
31
- }
60
+ };
61
+ return QuoteAssetOracleClient;
62
+ }());
32
63
  exports.QuoteAssetOracleClient = QuoteAssetOracleClient;