@drift-labs/sdk 0.2.0-master.3 → 0.2.0-master.31

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 (208) hide show
  1. package/README.md +13 -13
  2. package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
  3. package/lib/accounts/bulkUserStatsSubscription.js +21 -0
  4. package/lib/accounts/bulkUserSubscription.js +0 -1
  5. package/lib/accounts/fetch.d.ts +2 -1
  6. package/lib/accounts/fetch.js +9 -1
  7. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +16 -16
  8. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +31 -28
  9. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  10. package/lib/accounts/pollingUserStatsAccountSubscriber.js +113 -0
  11. package/lib/accounts/types.d.ts +22 -11
  12. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +17 -17
  13. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +37 -35
  14. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  15. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  16. package/lib/addresses/marketAddresses.d.ts +1 -3
  17. package/lib/addresses/pda.d.ts +10 -4
  18. package/lib/addresses/pda.js +51 -14
  19. package/lib/admin.d.ts +42 -26
  20. package/lib/admin.js +228 -81
  21. package/lib/clearingHouse.d.ts +130 -49
  22. package/lib/clearingHouse.js +1256 -367
  23. package/lib/clearingHouseConfig.d.ts +4 -4
  24. package/lib/clearingHouseUser.d.ts +51 -39
  25. package/lib/clearingHouseUser.js +408 -191
  26. package/lib/clearingHouseUserStats.d.ts +18 -0
  27. package/lib/clearingHouseUserStats.js +49 -0
  28. package/lib/clearingHouseUserStatsConfig.d.ts +14 -0
  29. package/lib/clearingHouseUserStatsConfig.js +2 -0
  30. package/lib/config.d.ts +7 -9
  31. package/lib/config.js +21 -21
  32. package/lib/constants/numericConstants.d.ts +25 -12
  33. package/lib/constants/numericConstants.js +35 -21
  34. package/lib/constants/perpMarkets.d.ts +18 -0
  35. package/lib/constants/{markets.js → perpMarkets.js} +7 -7
  36. package/lib/constants/spotMarkets.d.ts +19 -0
  37. package/lib/constants/spotMarkets.js +53 -0
  38. package/lib/dlob/DLOB.d.ts +74 -0
  39. package/lib/dlob/DLOB.js +595 -0
  40. package/lib/dlob/DLOBNode.d.ts +54 -0
  41. package/lib/dlob/DLOBNode.js +85 -0
  42. package/lib/dlob/NodeList.d.ts +26 -0
  43. package/lib/dlob/NodeList.js +139 -0
  44. package/lib/events/eventList.js +3 -0
  45. package/lib/events/eventSubscriber.d.ts +4 -2
  46. package/lib/events/eventSubscriber.js +16 -9
  47. package/lib/events/fetchLogs.d.ts +10 -1
  48. package/lib/events/fetchLogs.js +27 -7
  49. package/lib/events/pollingLogProvider.d.ts +2 -1
  50. package/lib/events/pollingLogProvider.js +6 -2
  51. package/lib/events/sort.js +8 -11
  52. package/lib/events/types.d.ts +8 -2
  53. package/lib/events/types.js +6 -0
  54. package/lib/examples/makeTradeExample.js +20 -8
  55. package/lib/factory/bigNum.d.ts +2 -0
  56. package/lib/factory/bigNum.js +48 -10
  57. package/lib/idl/clearing_house.json +4889 -1529
  58. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  59. package/lib/index.d.ts +21 -6
  60. package/lib/index.js +25 -6
  61. package/lib/math/amm.d.ts +9 -6
  62. package/lib/math/amm.js +91 -66
  63. package/lib/math/auction.js +4 -1
  64. package/lib/math/conversion.js +1 -1
  65. package/lib/math/funding.d.ts +6 -6
  66. package/lib/math/funding.js +11 -10
  67. package/lib/math/insurance.d.ts +4 -0
  68. package/lib/math/insurance.js +27 -0
  69. package/lib/math/margin.d.ts +11 -0
  70. package/lib/math/margin.js +77 -0
  71. package/lib/math/market.d.ts +14 -9
  72. package/lib/math/market.js +72 -10
  73. package/lib/math/oracles.d.ts +4 -0
  74. package/lib/math/oracles.js +36 -8
  75. package/lib/math/orders.d.ts +6 -2
  76. package/lib/math/orders.js +78 -3
  77. package/lib/math/position.d.ts +21 -13
  78. package/lib/math/position.js +76 -36
  79. package/lib/math/repeg.js +14 -5
  80. package/lib/math/spotBalance.d.ts +22 -0
  81. package/lib/math/spotBalance.js +192 -0
  82. package/lib/math/spotMarket.d.ts +4 -0
  83. package/lib/math/spotMarket.js +8 -0
  84. package/lib/math/spotPosition.d.ts +6 -0
  85. package/lib/math/spotPosition.js +23 -0
  86. package/lib/math/trade.d.ts +10 -10
  87. package/lib/math/trade.js +32 -39
  88. package/lib/oracles/pythClient.js +1 -1
  89. package/lib/oracles/quoteAssetOracleClient.js +1 -1
  90. package/lib/oracles/switchboardClient.js +1 -1
  91. package/lib/orderParams.d.ts +14 -5
  92. package/lib/orderParams.js +12 -92
  93. package/lib/serum/serumSubscriber.d.ts +23 -0
  94. package/lib/serum/serumSubscriber.js +41 -0
  95. package/lib/serum/types.d.ts +11 -0
  96. package/lib/serum/types.js +2 -0
  97. package/lib/slot/SlotSubscriber.d.ts +7 -0
  98. package/lib/slot/SlotSubscriber.js +3 -0
  99. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  100. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  101. package/lib/tx/retryTxSender.d.ts +1 -1
  102. package/lib/tx/retryTxSender.js +13 -4
  103. package/lib/tx/types.d.ts +1 -1
  104. package/lib/tx/utils.js +1 -1
  105. package/lib/types.d.ts +566 -138
  106. package/lib/types.js +129 -5
  107. package/lib/userMap/userMap.d.ts +25 -0
  108. package/lib/userMap/userMap.js +73 -0
  109. package/lib/userMap/userStatsMap.d.ts +19 -0
  110. package/lib/userMap/userStatsMap.js +68 -0
  111. package/lib/util/computeUnits.js +1 -1
  112. package/lib/util/getTokenAddress.d.ts +2 -0
  113. package/lib/util/getTokenAddress.js +9 -0
  114. package/package.json +12 -6
  115. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  116. package/src/accounts/bulkUserSubscription.ts +0 -1
  117. package/src/accounts/fetch.ts +27 -2
  118. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +46 -42
  119. package/src/accounts/pollingUserStatsAccountSubscriber.ts +172 -0
  120. package/src/accounts/types.ts +31 -11
  121. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +64 -59
  122. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  123. package/src/addresses/marketAddresses.ts +1 -2
  124. package/src/addresses/pda.ts +88 -14
  125. package/src/admin.ts +452 -147
  126. package/src/assert/assert.js +9 -0
  127. package/src/clearingHouse.ts +2066 -467
  128. package/src/clearingHouseConfig.ts +4 -3
  129. package/src/clearingHouseUser.ts +747 -294
  130. package/src/clearingHouseUserStats.ts +75 -0
  131. package/src/clearingHouseUserStatsConfig.ts +18 -0
  132. package/src/config.ts +30 -31
  133. package/src/constants/numericConstants.ts +48 -25
  134. package/src/constants/{markets.ts → perpMarkets.ts} +10 -10
  135. package/src/constants/spotMarkets.ts +73 -0
  136. package/src/dlob/DLOB.ts +953 -0
  137. package/src/dlob/DLOBNode.ts +167 -0
  138. package/src/dlob/NodeList.ts +189 -0
  139. package/src/events/eventList.js +77 -0
  140. package/src/events/eventList.ts +3 -0
  141. package/src/events/eventSubscriber.ts +20 -12
  142. package/src/events/fetchLogs.ts +35 -8
  143. package/src/events/pollingLogProvider.ts +10 -2
  144. package/src/events/sort.ts +11 -15
  145. package/src/events/types.ts +19 -1
  146. package/src/examples/makeTradeExample.js +157 -0
  147. package/src/examples/makeTradeExample.ts +32 -14
  148. package/src/factory/bigNum.ts +65 -13
  149. package/src/idl/clearing_house.json +4889 -1529
  150. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  151. package/src/index.ts +21 -6
  152. package/src/math/amm.ts +171 -88
  153. package/src/math/auction.ts +5 -1
  154. package/src/math/conversion.ts +2 -2
  155. package/src/math/funding.ts +20 -18
  156. package/src/math/insurance.ts +35 -0
  157. package/src/math/margin.ts +127 -0
  158. package/src/math/market.ts +145 -14
  159. package/src/math/oracles.ts +63 -9
  160. package/src/math/orders.ts +138 -4
  161. package/src/math/position.ts +119 -58
  162. package/src/math/repeg.ts +16 -6
  163. package/src/math/spotBalance.ts +319 -0
  164. package/src/math/spotMarket.ts +9 -0
  165. package/src/math/spotPosition.ts +47 -0
  166. package/src/math/trade.ts +53 -59
  167. package/src/oracles/pythClient.ts +2 -2
  168. package/src/oracles/quoteAssetOracleClient.ts +2 -2
  169. package/src/oracles/switchboardClient.ts +2 -2
  170. package/src/orderParams.ts +24 -137
  171. package/src/serum/serumSubscriber.ts +80 -0
  172. package/src/serum/types.ts +13 -0
  173. package/src/slot/SlotSubscriber.ts +11 -1
  174. package/src/token/index.js +38 -0
  175. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  176. package/src/tx/retryTxSender.ts +16 -5
  177. package/src/tx/types.js +2 -0
  178. package/src/tx/types.ts +2 -1
  179. package/src/tx/utils.js +17 -0
  180. package/src/tx/utils.ts +1 -1
  181. package/src/types.ts +533 -140
  182. package/src/userMap/userMap.ts +100 -0
  183. package/src/userMap/userStatsMap.ts +110 -0
  184. package/src/util/computeUnits.js +21 -11
  185. package/src/util/computeUnits.ts +1 -1
  186. package/src/util/getTokenAddress.js +9 -0
  187. package/src/util/getTokenAddress.ts +18 -0
  188. package/src/util/promiseTimeout.js +14 -0
  189. package/src/util/tps.js +27 -0
  190. package/tests/bn/test.ts +24 -10
  191. package/tests/dlob/helpers.ts +397 -0
  192. package/tests/dlob/test.ts +3688 -0
  193. package/lib/constants/banks.d.ts +0 -16
  194. package/lib/constants/banks.js +0 -34
  195. package/lib/constants/markets.d.ts +0 -19
  196. package/lib/math/bankBalance.d.ts +0 -9
  197. package/lib/math/bankBalance.js +0 -75
  198. package/lib/math/state.d.ts +0 -8
  199. package/lib/math/state.js +0 -15
  200. package/lib/orders.d.ts +0 -8
  201. package/lib/orders.js +0 -134
  202. package/src/constants/banks.ts +0 -43
  203. package/src/math/bankBalance.ts +0 -112
  204. package/src/math/state.ts +0 -14
  205. package/src/math/utils.js +0 -27
  206. package/src/math/utils.js.map +0 -1
  207. package/src/orders.ts +0 -244
  208. package/src/util/computeUnits.js.map +0 -1
package/lib/math/trade.js CHANGED
@@ -19,13 +19,13 @@ const MAXPCT = new anchor_1.BN(1000); //percentage units are [0,1000] => [0,1]
19
19
  * @param useSpread whether to consider spread with calculating slippage
20
20
  * @return [pctAvgSlippage, pctMaxSlippage, entryPrice, newPrice]
21
21
  *
22
- * 'pctAvgSlippage' => the percentage change to entryPrice (average est slippage in execution) : Precision MARK_PRICE_PRECISION
22
+ * 'pctAvgSlippage' => the percentage change to entryPrice (average est slippage in execution) : Precision PRICE_PRECISION
23
23
  *
24
- * 'pctMaxSlippage' => the percentage change to maxPrice (highest est slippage in execution) : Precision MARK_PRICE_PRECISION
24
+ * 'pctMaxSlippage' => the percentage change to maxPrice (highest est slippage in execution) : Precision PRICE_PRECISION
25
25
  *
26
- * 'entryPrice' => the average price of the trade : Precision MARK_PRICE_PRECISION
26
+ * 'entryPrice' => the average price of the trade : Precision PRICE_PRECISION
27
27
  *
28
- * 'newPrice' => the price of the asset after the trade : Precision MARK_PRICE_PRECISION
28
+ * 'newPrice' => the price of the asset after the trade : Precision PRICE_PRECISION
29
29
  */
30
30
  function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quote', oraclePriceData, useSpread = true) {
31
31
  let oldPrice;
@@ -38,20 +38,16 @@ function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quo
38
38
  }
39
39
  }
40
40
  else {
41
- oldPrice = (0, market_1.calculateMarkPrice)(market, oraclePriceData);
41
+ oldPrice = (0, market_1.calculateReservePrice)(market, oraclePriceData);
42
42
  }
43
43
  if (amount.eq(numericConstants_1.ZERO)) {
44
44
  return [numericConstants_1.ZERO, numericConstants_1.ZERO, oldPrice, oldPrice];
45
45
  }
46
- const [acquiredBase, acquiredQuote] = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType, oraclePriceData, useSpread);
47
- const swapDirection = (0, types_2.isVariant)(direction, 'long')
48
- ? types_1.SwapDirection.REMOVE
49
- : types_1.SwapDirection.ADD;
50
- const quoteAssetAmountAcquired = (0, amm_1.calculateQuoteAssetAmountSwapped)(acquiredQuote.abs(), market.amm.pegMultiplier, swapDirection);
51
- const entryPrice = quoteAssetAmountAcquired
46
+ const [acquiredBaseReserve, acquiredQuoteReserve, acquiredQuoteAssetAmount] = calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType, oraclePriceData, useSpread);
47
+ const entryPrice = acquiredQuoteAssetAmount
52
48
  .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
53
- .mul(numericConstants_1.MARK_PRICE_PRECISION)
54
- .div(acquiredBase.abs());
49
+ .mul(numericConstants_1.PRICE_PRECISION)
50
+ .div(acquiredBaseReserve.abs());
55
51
  let amm;
56
52
  if (useSpread && market.amm.baseSpread > 0) {
57
53
  const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = (0, amm_1.calculateUpdatedAMMSpreadReserves)(market.amm, direction, oraclePriceData);
@@ -65,7 +61,7 @@ function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quo
65
61
  else {
66
62
  amm = market.amm;
67
63
  }
68
- const newPrice = (0, amm_1.calculatePrice)(amm.baseAssetReserve.sub(acquiredBase), amm.quoteAssetReserve.sub(acquiredQuote), amm.pegMultiplier);
64
+ const newPrice = (0, amm_1.calculatePrice)(amm.baseAssetReserve.sub(acquiredBaseReserve), amm.quoteAssetReserve.sub(acquiredQuoteReserve), amm.pegMultiplier);
69
65
  if (direction == types_1.PositionDirection.SHORT) {
70
66
  (0, assert_1.assert)(newPrice.lte(oldPrice));
71
67
  }
@@ -74,12 +70,12 @@ function calculateTradeSlippage(direction, amount, market, inputAssetType = 'quo
74
70
  }
75
71
  const pctMaxSlippage = newPrice
76
72
  .sub(oldPrice)
77
- .mul(numericConstants_1.MARK_PRICE_PRECISION)
73
+ .mul(numericConstants_1.PRICE_PRECISION)
78
74
  .div(oldPrice)
79
75
  .abs();
80
76
  const pctAvgSlippage = entryPrice
81
77
  .sub(oldPrice)
82
- .mul(numericConstants_1.MARK_PRICE_PRECISION)
78
+ .mul(numericConstants_1.PRICE_PRECISION)
83
79
  .div(oldPrice)
84
80
  .abs();
85
81
  return [pctAvgSlippage, pctMaxSlippage, entryPrice, newPrice];
@@ -98,7 +94,7 @@ exports.calculateTradeSlippage = calculateTradeSlippage;
98
94
  */
99
95
  function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType = 'quote', oraclePriceData, useSpread = true) {
100
96
  if (amount.eq(numericConstants_1.ZERO)) {
101
- return [numericConstants_1.ZERO, numericConstants_1.ZERO];
97
+ return [numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO];
102
98
  }
103
99
  const swapDirection = (0, amm_1.getSwapDirection)(inputAssetType, direction);
104
100
  let amm;
@@ -117,7 +113,8 @@ function calculateTradeAcquiredAmounts(direction, amount, market, inputAssetType
117
113
  const [newQuoteAssetReserve, newBaseAssetReserve] = (0, amm_1.calculateAmmReservesAfterSwap)(amm, inputAssetType, amount, swapDirection);
118
114
  const acquiredBase = amm.baseAssetReserve.sub(newBaseAssetReserve);
119
115
  const acquiredQuote = amm.quoteAssetReserve.sub(newQuoteAssetReserve);
120
- return [acquiredBase, acquiredQuote];
116
+ const acquiredQuoteAssetAmount = (0, amm_1.calculateQuoteAssetAmountSwapped)(acquiredQuote.abs(), amm.pegMultiplier, swapDirection);
117
+ return [acquiredBase, acquiredQuote, acquiredQuoteAssetAmount];
121
118
  }
122
119
  exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
123
120
  /**
@@ -133,28 +130,28 @@ exports.calculateTradeAcquiredAmounts = calculateTradeAcquiredAmounts;
133
130
  * [
134
131
  * direction => direction of trade required, PositionDirection
135
132
  * tradeSize => size of trade required, TODO-PRECISION
136
- * entryPrice => the entry price for the trade, MARK_PRICE_PRECISION
137
- * targetPrice => the target price MARK_PRICE_PRECISION
133
+ * entryPrice => the entry price for the trade, PRICE_PRECISION
134
+ * targetPrice => the target price PRICE_PRECISION
138
135
  * ]
139
136
  */
140
137
  function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAssetType = 'quote', oraclePriceData, useSpread = true) {
141
138
  (0, assert_1.assert)(market.amm.baseAssetReserve.gt(numericConstants_1.ZERO));
142
139
  (0, assert_1.assert)(targetPrice.gt(numericConstants_1.ZERO));
143
140
  (0, assert_1.assert)(pct.lte(MAXPCT) && pct.gt(numericConstants_1.ZERO));
144
- const markPriceBefore = (0, market_1.calculateMarkPrice)(market, oraclePriceData);
141
+ const reservePriceBefore = (0, market_1.calculateReservePrice)(market, oraclePriceData);
145
142
  const bidPriceBefore = (0, market_1.calculateBidPrice)(market, oraclePriceData);
146
143
  const askPriceBefore = (0, market_1.calculateAskPrice)(market, oraclePriceData);
147
144
  let direction;
148
- if (targetPrice.gt(markPriceBefore)) {
149
- const priceGap = targetPrice.sub(markPriceBefore);
145
+ if (targetPrice.gt(reservePriceBefore)) {
146
+ const priceGap = targetPrice.sub(reservePriceBefore);
150
147
  const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
151
- targetPrice = markPriceBefore.add(priceGapScaled);
148
+ targetPrice = reservePriceBefore.add(priceGapScaled);
152
149
  direction = types_1.PositionDirection.LONG;
153
150
  }
154
151
  else {
155
- const priceGap = markPriceBefore.sub(targetPrice);
152
+ const priceGap = reservePriceBefore.sub(targetPrice);
156
153
  const priceGapScaled = priceGap.mul(pct).div(MAXPCT);
157
- targetPrice = markPriceBefore.sub(priceGapScaled);
154
+ targetPrice = reservePriceBefore.sub(priceGapScaled);
158
155
  direction = types_1.PositionDirection.SHORT;
159
156
  }
160
157
  let tradeSize;
@@ -173,7 +170,7 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
173
170
  quoteAssetReserveBefore = market.amm.quoteAssetReserve;
174
171
  }
175
172
  const invariant = market.amm.sqrtK.mul(market.amm.sqrtK);
176
- const k = invariant.mul(numericConstants_1.MARK_PRICE_PRECISION);
173
+ const k = invariant.mul(numericConstants_1.PRICE_PRECISION);
177
174
  let baseAssetReserveAfter;
178
175
  let quoteAssetReserveAfter;
179
176
  const biasModifier = new anchor_1.BN(1);
@@ -182,7 +179,7 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
182
179
  targetPrice.lt(askPriceBefore) &&
183
180
  targetPrice.gt(bidPriceBefore)) {
184
181
  // no trade, market is at target
185
- if (markPriceBefore.gt(targetPrice)) {
182
+ if (reservePriceBefore.gt(targetPrice)) {
186
183
  direction = types_1.PositionDirection.SHORT;
187
184
  }
188
185
  else {
@@ -191,12 +188,10 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
191
188
  tradeSize = numericConstants_1.ZERO;
192
189
  return [direction, tradeSize, targetPrice, targetPrice];
193
190
  }
194
- else if (markPriceBefore.gt(targetPrice)) {
191
+ else if (reservePriceBefore.gt(targetPrice)) {
195
192
  // overestimate y2
196
193
  baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).sub(biasModifier)).sub(new anchor_1.BN(1));
197
- quoteAssetReserveAfter = k
198
- .div(numericConstants_1.MARK_PRICE_PRECISION)
199
- .div(baseAssetReserveAfter);
194
+ quoteAssetReserveAfter = k.div(numericConstants_1.PRICE_PRECISION).div(baseAssetReserveAfter);
200
195
  markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
201
196
  direction = types_1.PositionDirection.SHORT;
202
197
  tradeSize = quoteAssetReserveBefore
@@ -206,12 +201,10 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
206
201
  .div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
207
202
  baseSize = baseAssetReserveAfter.sub(baseAssetReserveBefore);
208
203
  }
209
- else if (markPriceBefore.lt(targetPrice)) {
204
+ else if (reservePriceBefore.lt(targetPrice)) {
210
205
  // underestimate y2
211
206
  baseAssetReserveAfter = (0, utils_1.squareRootBN)(k.div(targetPrice).mul(peg).div(numericConstants_1.PEG_PRECISION).add(biasModifier)).add(new anchor_1.BN(1));
212
- quoteAssetReserveAfter = k
213
- .div(numericConstants_1.MARK_PRICE_PRECISION)
214
- .div(baseAssetReserveAfter);
207
+ quoteAssetReserveAfter = k.div(numericConstants_1.PRICE_PRECISION).div(baseAssetReserveAfter);
215
208
  markPriceAfter = (0, amm_1.calculatePrice)(baseAssetReserveAfter, quoteAssetReserveAfter, peg);
216
209
  direction = types_1.PositionDirection.LONG;
217
210
  tradeSize = quoteAssetReserveAfter
@@ -229,15 +222,15 @@ function calculateTargetPriceTrade(market, targetPrice, pct = MAXPCT, outputAsse
229
222
  }
230
223
  let tp1 = targetPrice;
231
224
  let tp2 = markPriceAfter;
232
- let originalDiff = targetPrice.sub(markPriceBefore);
225
+ let originalDiff = targetPrice.sub(reservePriceBefore);
233
226
  if (direction == types_1.PositionDirection.SHORT) {
234
227
  tp1 = markPriceAfter;
235
228
  tp2 = targetPrice;
236
- originalDiff = markPriceBefore.sub(targetPrice);
229
+ originalDiff = reservePriceBefore.sub(targetPrice);
237
230
  }
238
231
  const entryPrice = tradeSize
239
232
  .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
240
- .mul(numericConstants_1.MARK_PRICE_PRECISION)
233
+ .mul(numericConstants_1.PRICE_PRECISION)
241
234
  .div(baseSize.abs());
242
235
  (0, assert_1.assert)(tp1.sub(tp2).lte(originalDiff), 'Target Price Calculation incorrect');
243
236
  (0, assert_1.assert)(tp2.lte(tp1) || tp2.sub(tp1).abs() < 100000, 'Target Price Calculation incorrect' +
@@ -29,7 +29,7 @@ function convertPythPrice(price, exponent) {
29
29
  exponent = Math.abs(exponent);
30
30
  const pythPrecision = numericConstants_1.TEN.pow(new anchor_1.BN(exponent).abs());
31
31
  return new anchor_1.BN(price * Math.pow(10, exponent))
32
- .mul(numericConstants_1.MARK_PRICE_PRECISION)
32
+ .mul(numericConstants_1.PRICE_PRECISION)
33
33
  .div(pythPrecision);
34
34
  }
35
35
  exports.convertPythPrice = convertPythPrice;
@@ -4,7 +4,7 @@ exports.QuoteAssetOracleClient = exports.QUOTE_ORACLE_PRICE_DATA = void 0;
4
4
  const anchor_1 = require("@project-serum/anchor");
5
5
  const numericConstants_1 = require("../constants/numericConstants");
6
6
  exports.QUOTE_ORACLE_PRICE_DATA = {
7
- price: numericConstants_1.MARK_PRICE_PRECISION,
7
+ price: numericConstants_1.PRICE_PRECISION,
8
8
  slot: new anchor_1.BN(0),
9
9
  confidence: new anchor_1.BN(1),
10
10
  hasSufficientNumberOfDataPoints: true,
@@ -53,6 +53,6 @@ function getSwitchboardProgram(connection) {
53
53
  function convertSwitchboardDecimal(switchboardDecimal) {
54
54
  const switchboardPrecision = numericConstants_1.TEN.pow(new anchor_1.BN(switchboardDecimal.scale));
55
55
  return switchboardDecimal.mantissa
56
- .mul(numericConstants_1.MARK_PRICE_PRECISION)
56
+ .mul(numericConstants_1.PRICE_PRECISION)
57
57
  .div(switchboardPrecision);
58
58
  }
@@ -1,7 +1,16 @@
1
1
  /// <reference types="bn.js" />
2
- import { OrderParams, OrderTriggerCondition, PositionDirection } from './types';
2
+ import { OptionalOrderParams, OrderTriggerCondition } from './types';
3
3
  import { BN } from '@project-serum/anchor';
4
- export declare function getLimitOrderParams(marketIndex: BN, direction: PositionDirection, baseAssetAmount: BN, price: BN, reduceOnly: boolean, discountToken?: boolean, referrer?: boolean, userOrderId?: number, postOnly?: boolean, oraclePriceOffset?: BN, immediateOrCancel?: boolean): OrderParams;
5
- export declare function getTriggerMarketOrderParams(marketIndex: BN, direction: PositionDirection, baseAssetAmount: BN, triggerPrice: BN, triggerCondition: OrderTriggerCondition, reduceOnly: boolean, discountToken?: boolean, referrer?: boolean, userOrderId?: number): OrderParams;
6
- export declare function getTriggerLimitOrderParams(marketIndex: BN, direction: PositionDirection, baseAssetAmount: BN, price: BN, triggerPrice: BN, triggerCondition: OrderTriggerCondition, reduceOnly: boolean, discountToken?: boolean, referrer?: boolean, userOrderId?: number): OrderParams;
7
- export declare function getMarketOrderParams(marketIndex: BN, direction: PositionDirection, quoteAssetAmount: BN, baseAssetAmount: BN, reduceOnly: boolean, price?: BN, discountToken?: boolean, referrer?: boolean): OrderParams;
4
+ export declare function getLimitOrderParams(params: Omit<OptionalOrderParams, 'orderType' | 'marketType'> & {
5
+ price: BN;
6
+ }): OptionalOrderParams;
7
+ export declare function getTriggerMarketOrderParams(params: Omit<OptionalOrderParams, 'orderType' | 'marketType'> & {
8
+ triggerCondition: OrderTriggerCondition;
9
+ triggerPrice: BN;
10
+ }): OptionalOrderParams;
11
+ export declare function getTriggerLimitOrderParams(params: Omit<OptionalOrderParams, 'orderType' | 'marketType'> & {
12
+ triggerCondition: OrderTriggerCondition;
13
+ triggerPrice: BN;
14
+ price: BN;
15
+ }): OptionalOrderParams;
16
+ export declare function getMarketOrderParams(params: Omit<OptionalOrderParams, 'orderType' | 'marketType'>): OptionalOrderParams;
@@ -2,107 +2,27 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getMarketOrderParams = exports.getTriggerLimitOrderParams = exports.getTriggerMarketOrderParams = exports.getLimitOrderParams = void 0;
4
4
  const types_1 = require("./types");
5
- const numericConstants_1 = require("./constants/numericConstants");
6
- function getLimitOrderParams(marketIndex, direction, baseAssetAmount, price, reduceOnly, discountToken = false, referrer = false, userOrderId = 0, postOnly = false, oraclePriceOffset = numericConstants_1.ZERO, immediateOrCancel = false) {
7
- return {
5
+ function getLimitOrderParams(params) {
6
+ return Object.assign({}, params, {
8
7
  orderType: types_1.OrderType.LIMIT,
9
- userOrderId,
10
- marketIndex,
11
- direction,
12
- quoteAssetAmount: numericConstants_1.ZERO,
13
- baseAssetAmount,
14
- price,
15
- reduceOnly,
16
- postOnly,
17
- immediateOrCancel,
18
- positionLimit: numericConstants_1.ZERO,
19
- padding0: true,
20
- padding1: numericConstants_1.ZERO,
21
- optionalAccounts: {
22
- discountToken,
23
- referrer,
24
- },
25
- triggerCondition: types_1.OrderTriggerCondition.ABOVE,
26
- triggerPrice: numericConstants_1.ZERO,
27
- oraclePriceOffset,
28
- };
8
+ });
29
9
  }
30
10
  exports.getLimitOrderParams = getLimitOrderParams;
31
- function getTriggerMarketOrderParams(marketIndex, direction, baseAssetAmount, triggerPrice, triggerCondition, reduceOnly, discountToken = false, referrer = false, userOrderId = 0) {
32
- return {
11
+ function getTriggerMarketOrderParams(params) {
12
+ return Object.assign({}, params, {
33
13
  orderType: types_1.OrderType.TRIGGER_MARKET,
34
- userOrderId,
35
- marketIndex,
36
- direction,
37
- quoteAssetAmount: numericConstants_1.ZERO,
38
- baseAssetAmount,
39
- price: numericConstants_1.ZERO,
40
- reduceOnly,
41
- postOnly: false,
42
- immediateOrCancel: false,
43
- positionLimit: numericConstants_1.ZERO,
44
- padding0: true,
45
- padding1: numericConstants_1.ZERO,
46
- optionalAccounts: {
47
- discountToken,
48
- referrer,
49
- },
50
- triggerCondition,
51
- triggerPrice,
52
- oraclePriceOffset: numericConstants_1.ZERO,
53
- };
14
+ });
54
15
  }
55
16
  exports.getTriggerMarketOrderParams = getTriggerMarketOrderParams;
56
- function getTriggerLimitOrderParams(marketIndex, direction, baseAssetAmount, price, triggerPrice, triggerCondition, reduceOnly, discountToken = false, referrer = false, userOrderId = 0) {
57
- return {
17
+ function getTriggerLimitOrderParams(params) {
18
+ return Object.assign({}, params, {
58
19
  orderType: types_1.OrderType.TRIGGER_LIMIT,
59
- userOrderId,
60
- marketIndex,
61
- direction,
62
- quoteAssetAmount: numericConstants_1.ZERO,
63
- baseAssetAmount,
64
- price,
65
- reduceOnly,
66
- postOnly: false,
67
- immediateOrCancel: false,
68
- positionLimit: numericConstants_1.ZERO,
69
- padding0: true,
70
- padding1: numericConstants_1.ZERO,
71
- optionalAccounts: {
72
- discountToken,
73
- referrer,
74
- },
75
- triggerCondition,
76
- triggerPrice,
77
- oraclePriceOffset: numericConstants_1.ZERO,
78
- };
20
+ });
79
21
  }
80
22
  exports.getTriggerLimitOrderParams = getTriggerLimitOrderParams;
81
- function getMarketOrderParams(marketIndex, direction, quoteAssetAmount, baseAssetAmount, reduceOnly, price = numericConstants_1.ZERO, discountToken = false, referrer = false) {
82
- if (baseAssetAmount.eq(numericConstants_1.ZERO) && quoteAssetAmount.eq(numericConstants_1.ZERO)) {
83
- throw Error('baseAssetAmount or quoteAssetAmount must be zero');
84
- }
85
- return {
23
+ function getMarketOrderParams(params) {
24
+ return Object.assign({}, params, {
86
25
  orderType: types_1.OrderType.MARKET,
87
- userOrderId: 0,
88
- marketIndex,
89
- direction,
90
- quoteAssetAmount,
91
- baseAssetAmount,
92
- price,
93
- reduceOnly,
94
- postOnly: false,
95
- immediateOrCancel: false,
96
- positionLimit: numericConstants_1.ZERO,
97
- padding0: true,
98
- padding1: numericConstants_1.ZERO,
99
- optionalAccounts: {
100
- discountToken,
101
- referrer,
102
- },
103
- triggerCondition: types_1.OrderTriggerCondition.ABOVE,
104
- triggerPrice: numericConstants_1.ZERO,
105
- oraclePriceOffset: numericConstants_1.ZERO,
106
- };
26
+ });
107
27
  }
108
28
  exports.getMarketOrderParams = getMarketOrderParams;
@@ -0,0 +1,23 @@
1
+ import { Connection, PublicKey } from '@solana/web3.js';
2
+ import { BulkAccountLoader } from '../accounts/bulkAccountLoader';
3
+ import { Market, Orderbook } from '@project-serum/serum';
4
+ import { SerumMarketSubscriberConfig } from './types';
5
+ export declare class SerumSubscriber {
6
+ connection: Connection;
7
+ programId: PublicKey;
8
+ marketAddress: PublicKey;
9
+ accountLoader: BulkAccountLoader;
10
+ market: Market;
11
+ subscribed: boolean;
12
+ asksAddress: PublicKey;
13
+ asks: Orderbook;
14
+ asksCallbackId: string;
15
+ lastAsksSlot: number;
16
+ bidsAddress: PublicKey;
17
+ bids: Orderbook;
18
+ bidsCallbackId: string;
19
+ lastBidsSlot: number;
20
+ constructor(config: SerumMarketSubscriberConfig);
21
+ subscribe(): Promise<void>;
22
+ unsubscribe(): Promise<void>;
23
+ }
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SerumSubscriber = void 0;
4
+ const serum_1 = require("@project-serum/serum");
5
+ class SerumSubscriber {
6
+ constructor(config) {
7
+ this.connection = config.connection;
8
+ this.programId = config.programId;
9
+ this.marketAddress = config.marketAddress;
10
+ this.accountLoader = config.accountSubscription.accountLoader;
11
+ }
12
+ async subscribe() {
13
+ if (this.subscribed) {
14
+ return;
15
+ }
16
+ this.market = await serum_1.Market.load(this.connection, this.marketAddress, undefined, this.programId);
17
+ this.asksAddress = this.market.asksAddress;
18
+ this.asks = await this.market.loadAsks(this.connection);
19
+ this.asksCallbackId = this.accountLoader.addAccount(this.asksAddress, (buffer, slot) => {
20
+ this.lastAsksSlot = slot;
21
+ this.asks = serum_1.Orderbook.decode(this.market, buffer);
22
+ console.log(this.asks.getL2(3));
23
+ });
24
+ this.bidsAddress = this.market.bidsAddress;
25
+ this.bids = await this.market.loadBids(this.connection);
26
+ this.bidsCallbackId = this.accountLoader.addAccount(this.bidsAddress, (buffer, slot) => {
27
+ this.lastBidsSlot = slot;
28
+ this.bids = serum_1.Orderbook.decode(this.market, buffer);
29
+ });
30
+ this.subscribed = true;
31
+ }
32
+ async unsubscribe() {
33
+ if (!this.subscribed) {
34
+ return;
35
+ }
36
+ this.accountLoader.removeAccount(this.asksAddress, this.asksCallbackId);
37
+ this.accountLoader.removeAccount(this.bidsAddress, this.bidsCallbackId);
38
+ this.subscribed = false;
39
+ }
40
+ }
41
+ exports.SerumSubscriber = SerumSubscriber;
@@ -0,0 +1,11 @@
1
+ import { Connection, PublicKey } from '@solana/web3.js';
2
+ import { BulkAccountLoader } from '../accounts/bulkAccountLoader';
3
+ export declare type SerumMarketSubscriberConfig = {
4
+ connection: Connection;
5
+ programId: PublicKey;
6
+ marketAddress: PublicKey;
7
+ accountSubscription: {
8
+ type: 'polling';
9
+ accountLoader: BulkAccountLoader;
10
+ };
11
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,9 +1,16 @@
1
+ /// <reference types="node" />
1
2
  import { Connection } from '@solana/web3.js';
3
+ import { EventEmitter } from 'events';
4
+ import StrictEventEmitter from 'strict-event-emitter-types/types/src';
2
5
  declare type SlotSubscriberConfig = {};
6
+ export interface SlotSubscriberEvents {
7
+ newSlot: (newSlot: number) => void;
8
+ }
3
9
  export declare class SlotSubscriber {
4
10
  private connection;
5
11
  currentSlot: number;
6
12
  subscriptionId: number;
13
+ eventEmitter: StrictEventEmitter<EventEmitter, SlotSubscriberEvents>;
7
14
  constructor(connection: Connection, _config?: SlotSubscriberConfig);
8
15
  subscribe(): Promise<void>;
9
16
  getSlot(): number;
@@ -1,14 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SlotSubscriber = void 0;
4
+ const events_1 = require("events");
4
5
  class SlotSubscriber {
5
6
  constructor(connection, _config) {
6
7
  this.connection = connection;
8
+ this.eventEmitter = new events_1.EventEmitter();
7
9
  }
8
10
  async subscribe() {
9
11
  this.currentSlot = await this.connection.getSlot('confirmed');
10
12
  this.subscriptionId = this.connection.onSlotChange((slotInfo) => {
11
13
  this.currentSlot = slotInfo.slot;
14
+ this.eventEmitter.emit('newSlot', slotInfo.slot);
12
15
  });
13
16
  }
14
17
  getSlot() {
@@ -5,22 +5,25 @@ import { AccountInfo } from '@solana/spl-token';
5
5
  import { ConfirmOptions, Connection, PublicKey, TransactionInstruction, TransactionSignature } from '@solana/web3.js';
6
6
  import { BN } from '.';
7
7
  import { IWallet } from './types';
8
- export declare class MockUSDCFaucet {
8
+ export declare class TokenFaucet {
9
9
  connection: Connection;
10
10
  wallet: IWallet;
11
11
  program: Program;
12
12
  provider: AnchorProvider;
13
+ mint: PublicKey;
13
14
  opts?: ConfirmOptions;
14
- constructor(connection: Connection, wallet: IWallet, programId: PublicKey, opts?: ConfirmOptions);
15
- getMockUSDCFaucetStatePublicKeyAndNonce(): Promise<[
15
+ constructor(connection: Connection, wallet: IWallet, programId: PublicKey, mint: PublicKey, opts?: ConfirmOptions);
16
+ getFaucetConfigPublicKeyAndNonce(): Promise<[
16
17
  PublicKey,
17
18
  number
18
19
  ]>;
19
- mockUSDCFaucetStatePublicKey?: PublicKey;
20
- getMockUSDCFaucetStatePublicKey(): Promise<PublicKey>;
20
+ getMintAuthority(): Promise<PublicKey>;
21
+ getFaucetConfigPublicKey(): Promise<PublicKey>;
21
22
  initialize(): Promise<TransactionSignature>;
22
23
  fetchState(): Promise<any>;
24
+ private mintToUserIx;
23
25
  mintToUser(userTokenAccount: PublicKey, amount: BN): Promise<TransactionSignature>;
26
+ transferMintAuthority(): Promise<TransactionSignature>;
24
27
  createAssociatedTokenAccountAndMintTo(userPublicKey: PublicKey, amount: BN): Promise<[PublicKey, TransactionSignature]>;
25
28
  createAssociatedTokenAccountAndMintToInstructions(userPublicKey: PublicKey, amount: BN): Promise<[PublicKey, TransactionInstruction, TransactionInstruction]>;
26
29
  getAssosciatedMockUSDMintAddress(props: {