@drift-labs/sdk 0.1.36-master.7 → 0.2.0-master.10

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 (254) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +6 -6
  2. package/lib/accounts/bulkAccountLoader.js +81 -95
  3. package/lib/accounts/bulkUserSubscription.js +13 -57
  4. package/lib/accounts/fetch.d.ts +4 -0
  5. package/lib/accounts/fetch.js +18 -0
  6. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +34 -38
  7. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +224 -224
  8. package/lib/accounts/pollingOracleSubscriber.d.ts +3 -3
  9. package/lib/accounts/pollingOracleSubscriber.js +37 -49
  10. package/lib/accounts/pollingTokenAccountSubscriber.d.ts +3 -3
  11. package/lib/accounts/pollingTokenAccountSubscriber.js +35 -50
  12. package/lib/accounts/pollingUserAccountSubscriber.d.ts +7 -13
  13. package/lib/accounts/pollingUserAccountSubscriber.js +71 -134
  14. package/lib/accounts/types.d.ts +34 -41
  15. package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -4
  16. package/lib/accounts/webSocketAccountSubscriber.js +39 -35
  17. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +33 -28
  18. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +153 -185
  19. package/lib/accounts/webSocketUserAccountSubscriber.d.ts +5 -11
  20. package/lib/accounts/webSocketUserAccountSubscriber.js +22 -67
  21. package/lib/addresses/marketAddresses.d.ts +4 -0
  22. package/lib/addresses/marketAddresses.js +15 -0
  23. package/lib/addresses/pda.d.ts +12 -0
  24. package/lib/addresses/pda.js +83 -0
  25. package/lib/admin.d.ts +12 -18
  26. package/lib/admin.js +398 -558
  27. package/lib/clearingHouse.d.ts +83 -109
  28. package/lib/clearingHouse.js +832 -893
  29. package/lib/clearingHouseConfig.d.ts +34 -0
  30. package/lib/clearingHouseConfig.js +2 -0
  31. package/lib/clearingHouseUser.d.ts +19 -22
  32. package/lib/clearingHouseUser.js +155 -141
  33. package/lib/clearingHouseUserConfig.d.ts +14 -0
  34. package/lib/clearingHouseUserConfig.js +2 -0
  35. package/lib/config.d.ts +12 -0
  36. package/lib/config.js +35 -4
  37. package/lib/constants/banks.d.ts +16 -0
  38. package/lib/constants/banks.js +41 -0
  39. package/lib/constants/markets.d.ts +8 -3
  40. package/lib/constants/markets.js +13 -206
  41. package/lib/constants/numericConstants.d.ts +17 -0
  42. package/lib/constants/numericConstants.js +23 -6
  43. package/lib/events/eventList.d.ts +22 -0
  44. package/lib/events/eventList.js +77 -0
  45. package/lib/events/eventSubscriber.d.ts +34 -0
  46. package/lib/events/eventSubscriber.js +126 -0
  47. package/lib/events/fetchLogs.d.ts +13 -0
  48. package/lib/events/fetchLogs.js +39 -0
  49. package/lib/events/pollingLogProvider.d.ts +15 -0
  50. package/lib/events/pollingLogProvider.js +53 -0
  51. package/lib/events/sort.d.ts +2 -0
  52. package/lib/events/sort.js +44 -0
  53. package/lib/events/txEventCache.d.ts +24 -0
  54. package/lib/events/txEventCache.js +71 -0
  55. package/lib/events/types.d.ts +49 -0
  56. package/lib/events/types.js +20 -0
  57. package/lib/events/webSocketLogProvider.d.ts +12 -0
  58. package/lib/events/webSocketLogProvider.js +30 -0
  59. package/lib/examples/makeTradeExample.js +26 -27
  60. package/lib/factory/bigNum.d.ts +118 -0
  61. package/lib/factory/bigNum.js +364 -0
  62. package/lib/factory/oracleClient.d.ts +1 -2
  63. package/lib/factory/oracleClient.js +6 -2
  64. package/lib/idl/clearing_house.json +2258 -2774
  65. package/lib/index.d.ts +14 -5
  66. package/lib/index.js +18 -5
  67. package/lib/math/amm.d.ts +24 -29
  68. package/lib/math/amm.js +209 -176
  69. package/lib/math/auction.d.ts +5 -0
  70. package/lib/math/auction.js +42 -0
  71. package/lib/math/bankBalance.d.ts +9 -0
  72. package/lib/math/bankBalance.js +75 -0
  73. package/lib/math/conversion.d.ts +0 -1
  74. package/lib/math/conversion.js +1 -5
  75. package/lib/math/funding.d.ts +6 -6
  76. package/lib/math/funding.js +158 -175
  77. package/lib/math/market.d.ts +6 -6
  78. package/lib/math/market.js +10 -9
  79. package/lib/math/orders.d.ts +6 -1
  80. package/lib/math/orders.js +38 -1
  81. package/lib/math/position.d.ts +7 -5
  82. package/lib/math/position.js +29 -27
  83. package/lib/math/repeg.d.ts +22 -0
  84. package/lib/math/repeg.js +128 -0
  85. package/lib/math/trade.d.ts +5 -4
  86. package/lib/math/trade.js +29 -24
  87. package/lib/mockUSDCFaucet.js +87 -116
  88. package/lib/oracles/oracleClientCache.d.ts +8 -0
  89. package/lib/oracles/oracleClientCache.js +19 -0
  90. package/lib/oracles/pythClient.d.ts +3 -5
  91. package/lib/oracles/pythClient.js +12 -31
  92. package/lib/oracles/quoteAssetOracleClient.d.ts +9 -0
  93. package/lib/oracles/quoteAssetOracleClient.js +21 -0
  94. package/lib/oracles/switchboardClient.d.ts +3 -5
  95. package/lib/oracles/switchboardClient.js +29 -50
  96. package/lib/oracles/types.d.ts +6 -1
  97. package/lib/orderParams.d.ts +14 -5
  98. package/lib/orderParams.js +8 -96
  99. package/lib/orders.d.ts +6 -7
  100. package/lib/orders.js +11 -89
  101. package/lib/slot/SlotSubscriber.d.ts +19 -0
  102. package/lib/slot/SlotSubscriber.js +26 -0
  103. package/lib/tx/retryTxSender.d.ts +2 -2
  104. package/lib/tx/retryTxSender.js +108 -123
  105. package/lib/tx/types.d.ts +5 -1
  106. package/lib/tx/utils.d.ts +1 -1
  107. package/lib/tx/utils.js +11 -2
  108. package/lib/types.d.ts +180 -110
  109. package/lib/types.js +54 -1
  110. package/lib/userName.d.ts +4 -0
  111. package/lib/userName.js +20 -0
  112. package/lib/util/computeUnits.js +10 -21
  113. package/lib/util/tps.js +11 -22
  114. package/lib/wallet.js +7 -20
  115. package/package.json +11 -4
  116. package/src/accounts/bulkAccountLoader.js +197 -0
  117. package/src/accounts/bulkAccountLoader.ts +21 -15
  118. package/src/accounts/bulkUserSubscription.js +33 -0
  119. package/src/accounts/bulkUserSubscription.ts +1 -45
  120. package/src/accounts/fetch.js +29 -0
  121. package/src/accounts/fetch.ts +33 -0
  122. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  123. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +249 -214
  124. package/src/accounts/pollingOracleSubscriber.js +93 -0
  125. package/src/accounts/pollingOracleSubscriber.ts +16 -8
  126. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  127. package/src/accounts/pollingTokenAccountSubscriber.ts +11 -8
  128. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  129. package/src/accounts/pollingUserAccountSubscriber.ts +21 -86
  130. package/src/accounts/types.js +10 -0
  131. package/src/accounts/types.ts +41 -70
  132. package/src/accounts/utils.js +7 -0
  133. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  134. package/src/accounts/webSocketAccountSubscriber.ts +33 -16
  135. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  136. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +190 -240
  137. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  138. package/src/accounts/webSocketUserAccountSubscriber.ts +11 -71
  139. package/src/addresses/marketAddresses.js +26 -0
  140. package/src/addresses/marketAddresses.ts +18 -0
  141. package/{lib/addresses.js → src/addresses/pda.js} +45 -34
  142. package/src/addresses/pda.ts +118 -0
  143. package/src/admin.ts +247 -336
  144. package/src/assert/assert.js +9 -0
  145. package/src/clearingHouse.ts +1023 -1026
  146. package/src/clearingHouseConfig.ts +37 -0
  147. package/src/clearingHouseUser.ts +275 -185
  148. package/src/clearingHouseUserConfig.ts +18 -0
  149. package/src/config.ts +54 -1
  150. package/src/constants/banks.ts +50 -0
  151. package/src/constants/markets.ts +16 -207
  152. package/src/constants/numericConstants.ts +34 -5
  153. package/src/events/eventList.js +77 -0
  154. package/src/events/eventList.ts +94 -0
  155. package/src/events/eventSubscriber.js +139 -0
  156. package/src/events/eventSubscriber.ts +194 -0
  157. package/src/events/fetchLogs.js +50 -0
  158. package/src/events/fetchLogs.ts +80 -0
  159. package/src/events/pollingLogProvider.js +64 -0
  160. package/src/events/pollingLogProvider.ts +79 -0
  161. package/src/events/sort.js +44 -0
  162. package/src/events/sort.ts +65 -0
  163. package/src/events/txEventCache.js +71 -0
  164. package/src/events/txEventCache.ts +74 -0
  165. package/src/events/types.js +20 -0
  166. package/src/events/types.ts +98 -0
  167. package/src/events/webSocketLogProvider.js +41 -0
  168. package/src/events/webSocketLogProvider.ts +38 -0
  169. package/src/examples/makeTradeExample.js +80 -0
  170. package/src/examples/makeTradeExample.ts +20 -11
  171. package/src/factory/bigNum.js +364 -0
  172. package/src/factory/bigNum.ts +524 -0
  173. package/src/factory/oracleClient.js +20 -0
  174. package/src/factory/oracleClient.ts +7 -4
  175. package/src/idl/clearing_house.json +2258 -2774
  176. package/src/index.js +69 -0
  177. package/src/index.ts +14 -5
  178. package/src/math/amm.js +369 -0
  179. package/src/math/amm.ts +382 -243
  180. package/src/math/auction.js +42 -0
  181. package/src/math/auction.ts +43 -0
  182. package/src/math/bankBalance.js +75 -0
  183. package/src/math/bankBalance.ts +112 -0
  184. package/src/math/conversion.js +11 -0
  185. package/src/math/conversion.ts +1 -11
  186. package/src/math/funding.js +248 -0
  187. package/src/math/funding.ts +12 -9
  188. package/src/math/market.js +57 -0
  189. package/src/math/market.ts +37 -30
  190. package/src/math/oracles.js +26 -0
  191. package/src/math/orders.js +110 -0
  192. package/src/math/orders.ts +43 -1
  193. package/src/math/position.js +140 -0
  194. package/src/math/position.ts +52 -35
  195. package/src/math/repeg.js +128 -0
  196. package/src/math/repeg.ts +176 -0
  197. package/src/math/state.js +15 -0
  198. package/src/math/trade.js +253 -0
  199. package/src/math/trade.ts +55 -47
  200. package/src/math/utils.js +26 -0
  201. package/src/math/utils.js.map +1 -0
  202. package/src/mockUSDCFaucet.js +171 -0
  203. package/src/oracles/oracleClientCache.js +19 -0
  204. package/src/oracles/oracleClientCache.ts +20 -0
  205. package/src/oracles/pythClient.js +46 -0
  206. package/src/oracles/pythClient.ts +4 -11
  207. package/src/oracles/quoteAssetOracleClient.js +32 -0
  208. package/src/oracles/quoteAssetOracleClient.ts +25 -0
  209. package/src/oracles/switchboardClient.js +69 -0
  210. package/src/oracles/switchboardClient.ts +11 -24
  211. package/src/oracles/types.js +2 -0
  212. package/src/oracles/types.ts +7 -1
  213. package/src/orderParams.js +20 -0
  214. package/src/orderParams.ts +20 -141
  215. package/src/orders.js +134 -0
  216. package/src/orders.ts +25 -134
  217. package/src/slot/SlotSubscriber.js +39 -0
  218. package/src/slot/SlotSubscriber.ts +42 -0
  219. package/src/token/index.js +38 -0
  220. package/src/tx/retryTxSender.js +188 -0
  221. package/src/tx/retryTxSender.ts +6 -4
  222. package/src/tx/types.js +2 -0
  223. package/src/tx/types.ts +6 -1
  224. package/src/tx/utils.js +17 -0
  225. package/src/tx/utils.ts +22 -3
  226. package/src/types.js +114 -0
  227. package/src/types.ts +176 -124
  228. package/src/userName.js +20 -0
  229. package/src/userName.ts +20 -0
  230. package/src/util/promiseTimeout.js +14 -0
  231. package/src/util/tps.js +27 -0
  232. package/src/wallet.js +35 -0
  233. package/tests/bn/test.ts +255 -0
  234. package/tsconfig.json +12 -12
  235. package/lib/addresses.d.ts +0 -10
  236. package/lib/constants/accounts.d.ts +0 -15
  237. package/lib/constants/accounts.js +0 -18
  238. package/lib/factory/clearingHouse.d.ts +0 -35
  239. package/lib/factory/clearingHouse.js +0 -81
  240. package/lib/factory/clearingHouseUser.d.ts +0 -19
  241. package/lib/factory/clearingHouseUser.js +0 -34
  242. package/lib/math/insuranceFund.d.ts +0 -15
  243. package/lib/math/insuranceFund.js +0 -33
  244. package/lib/settlement.d.ts +0 -4
  245. package/lib/settlement.js +0 -10
  246. package/lib/tx/defaultTxSender.d.ts +0 -8
  247. package/lib/tx/defaultTxSender.js +0 -12
  248. package/src/addresses.ts +0 -82
  249. package/src/constants/accounts.ts +0 -26
  250. package/src/factory/clearingHouse.ts +0 -173
  251. package/src/factory/clearingHouseUser.ts +0 -73
  252. package/src/math/insuranceFund.ts +0 -29
  253. package/src/settlement.ts +0 -9
  254. package/src/tx/defaultTxSender.ts +0 -24
@@ -2,107 +2,19 @@
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 {
8
- 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
- };
5
+ function getLimitOrderParams(params) {
6
+ return Object.assign({}, params, { orderType: types_1.OrderType.LIMIT });
29
7
  }
30
8
  exports.getLimitOrderParams = getLimitOrderParams;
31
- function getTriggerMarketOrderParams(marketIndex, direction, baseAssetAmount, triggerPrice, triggerCondition, reduceOnly, discountToken = false, referrer = false, userOrderId = 0) {
32
- return {
33
- 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
- };
9
+ function getTriggerMarketOrderParams(params) {
10
+ return Object.assign({}, params, { orderType: types_1.OrderType.TRIGGER_MARKET });
54
11
  }
55
12
  exports.getTriggerMarketOrderParams = getTriggerMarketOrderParams;
56
- function getTriggerLimitOrderParams(marketIndex, direction, baseAssetAmount, price, triggerPrice, triggerCondition, reduceOnly, discountToken = false, referrer = false, userOrderId = 0) {
57
- return {
58
- 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
- };
13
+ function getTriggerLimitOrderParams(params) {
14
+ return Object.assign({}, params, { orderType: types_1.OrderType.TRIGGER_LIMIT });
79
15
  }
80
16
  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 {
86
- 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
- };
17
+ function getMarketOrderParams(params) {
18
+ return Object.assign({}, params, { orderType: types_1.OrderType.MARKET });
107
19
  }
108
20
  exports.getMarketOrderParams = getMarketOrderParams;
package/lib/orders.d.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  /// <reference types="bn.js" />
2
- import { Market, Order, UserAccount, UserPosition } from './types';
3
- import { BN, ClearingHouseUser } from '.';
2
+ import { MarketAccount, Order, UserAccount, UserPosition } from './types';
3
+ import { BN } from '.';
4
4
  import { OraclePriceData } from '.';
5
- export declare function calculateNewStateAfterOrder(userAccount: UserAccount, userPosition: UserPosition, market: Market, order: Order): [UserAccount, UserPosition, Market] | null;
6
- export declare function calculateBaseAssetAmountMarketCanExecute(market: Market, order: Order, oraclePriceData?: OraclePriceData): BN;
7
- export declare function calculateAmountToTradeForLimit(market: Market, order: Order, oraclePriceData?: OraclePriceData): BN;
8
- export declare function calculateAmountToTradeForTriggerLimit(market: Market, order: Order): BN;
9
- export declare function calculateBaseAssetAmountUserCanExecute(market: Market, order: Order, user: ClearingHouseUser): BN;
5
+ export declare function calculateNewStateAfterOrder(userAccount: UserAccount, userPosition: UserPosition, market: MarketAccount, order: Order): [UserAccount, UserPosition, MarketAccount] | null;
6
+ export declare function calculateBaseAssetAmountMarketCanExecute(market: MarketAccount, order: Order, oraclePriceData?: OraclePriceData): BN;
7
+ export declare function calculateAmountToTradeForLimit(market: MarketAccount, order: Order, oraclePriceData?: OraclePriceData): BN;
8
+ export declare function calculateAmountToTradeForTriggerLimit(market: MarketAccount, order: Order): BN;
package/lib/orders.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateBaseAssetAmountUserCanExecute = exports.calculateAmountToTradeForTriggerLimit = exports.calculateAmountToTradeForLimit = exports.calculateBaseAssetAmountMarketCanExecute = exports.calculateNewStateAfterOrder = void 0;
3
+ exports.calculateAmountToTradeForTriggerLimit = exports.calculateAmountToTradeForLimit = exports.calculateBaseAssetAmountMarketCanExecute = exports.calculateNewStateAfterOrder = void 0;
4
4
  const types_1 = require("./types");
5
5
  const _1 = require(".");
6
6
  const market_1 = require("./math/market");
@@ -12,7 +12,7 @@ function calculateNewStateAfterOrder(userAccount, userPosition, market, order) {
12
12
  return null;
13
13
  }
14
14
  const baseAssetAmountToTrade = calculateBaseAssetAmountMarketCanExecute(market, order);
15
- if (baseAssetAmountToTrade.lt(market.amm.minimumBaseAssetTradeSize)) {
15
+ if (baseAssetAmountToTrade.lt(market.amm.baseAssetAmountStepSize)) {
16
16
  return null;
17
17
  }
18
18
  const userAccountAfter = Object.assign({}, userAccount);
@@ -88,7 +88,6 @@ function calculateBaseAssetAmountMarketCanExecute(market, order, oraclePriceData
88
88
  return calculateAmountToTradeForTriggerLimit(market, order);
89
89
  }
90
90
  else if ((0, types_1.isVariant)(order.orderType, 'market')) {
91
- // should never be a market order queued
92
91
  return numericConstants_1.ZERO;
93
92
  }
94
93
  else {
@@ -102,33 +101,23 @@ function calculateAmountToTradeForLimit(market, order, oraclePriceData) {
102
101
  if (!oraclePriceData) {
103
102
  throw Error('Cant calculate limit price for oracle offset oracle without OraclePriceData');
104
103
  }
105
- const floatingPrice = oraclePriceData.price.add(order.oraclePriceOffset);
106
- if (order.postOnly) {
107
- limitPrice = (0, types_1.isVariant)(order.direction, 'long')
108
- ? _1.BN.min(order.price, floatingPrice)
109
- : _1.BN.max(order.price, floatingPrice);
110
- }
111
- else {
112
- limitPrice = floatingPrice;
113
- }
104
+ limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
114
105
  }
115
- const [maxAmountToTrade, direction] = (0, amm_1.calculateMaxBaseAssetAmountToTrade)(market.amm, limitPrice, order.direction, !order.postOnly);
106
+ const [maxAmountToTrade, direction] = (0, amm_1.calculateMaxBaseAssetAmountToTrade)(market.amm, limitPrice, order.direction);
107
+ const baseAssetAmount = (0, _1.standardizeBaseAssetAmount)(maxAmountToTrade, market.amm.baseAssetAmountStepSize);
116
108
  // Check that directions are the same
117
109
  const sameDirection = isSameDirection(direction, order.direction);
118
110
  if (!sameDirection) {
119
111
  return numericConstants_1.ZERO;
120
112
  }
121
- return maxAmountToTrade.gt(order.baseAssetAmount)
113
+ return baseAssetAmount.gt(order.baseAssetAmount)
122
114
  ? order.baseAssetAmount
123
- : maxAmountToTrade;
115
+ : baseAssetAmount;
124
116
  }
125
117
  exports.calculateAmountToTradeForLimit = calculateAmountToTradeForLimit;
126
118
  function calculateAmountToTradeForTriggerLimit(market, order) {
127
- if (order.baseAssetAmountFilled.eq(numericConstants_1.ZERO)) {
128
- const baseAssetAmount = calculateAmountToTradeForTriggerMarket(market, order);
129
- if (baseAssetAmount.eq(numericConstants_1.ZERO)) {
130
- return numericConstants_1.ZERO;
131
- }
119
+ if (!order.triggered) {
120
+ return numericConstants_1.ZERO;
132
121
  }
133
122
  return calculateAmountToTradeForLimit(market, order);
134
123
  }
@@ -138,75 +127,8 @@ function isSameDirection(firstDirection, secondDirection) {
138
127
  ((0, types_1.isVariant)(firstDirection, 'short') && (0, types_1.isVariant)(secondDirection, 'short')));
139
128
  }
140
129
  function calculateAmountToTradeForTriggerMarket(market, order) {
141
- return isTriggerConditionSatisfied(market, order)
142
- ? order.baseAssetAmount
143
- : numericConstants_1.ZERO;
144
- }
145
- function isTriggerConditionSatisfied(market, order) {
146
- const markPrice = (0, market_1.calculateMarkPrice)(market);
147
- if ((0, types_1.isVariant)(order.triggerCondition, 'above')) {
148
- return markPrice.gt(order.triggerPrice);
149
- }
150
- else {
151
- return markPrice.lt(order.triggerPrice);
152
- }
153
- }
154
- function calculateBaseAssetAmountUserCanExecute(market, order, user) {
155
- const maxLeverage = user.getMaxLeverage(order.marketIndex, 'Initial');
156
- const freeCollateral = user.getFreeCollateral();
157
- let quoteAssetAmount;
158
- if ((0, _1.isOrderRiskIncreasingInSameDirection)(user, order)) {
159
- quoteAssetAmount = freeCollateral.mul(maxLeverage).div(_1.TEN_THOUSAND);
160
- }
161
- else {
162
- const position = user.getUserPosition(order.marketIndex) ||
163
- user.getEmptyPosition(order.marketIndex);
164
- const positionValue = (0, _1.calculateBaseAssetValue)(market, position);
165
- quoteAssetAmount = freeCollateral
166
- .mul(maxLeverage)
167
- .div(_1.TEN_THOUSAND)
168
- .add(positionValue.mul(numericConstants_1.TWO));
169
- }
170
- if (quoteAssetAmount.lte(numericConstants_1.ZERO)) {
130
+ if (!order.triggered) {
171
131
  return numericConstants_1.ZERO;
172
132
  }
173
- const swapDirection = (0, types_1.isVariant)(order.direction, 'long')
174
- ? types_1.SwapDirection.ADD
175
- : types_1.SwapDirection.REMOVE;
176
- const useSpread = !order.postOnly;
177
- let amm;
178
- if (useSpread) {
179
- const { baseAssetReserve, quoteAssetReserve } = (0, _1.calculateSpreadReserves)(market.amm, order.direction);
180
- amm = {
181
- baseAssetReserve,
182
- quoteAssetReserve,
183
- sqrtK: market.amm.sqrtK,
184
- pegMultiplier: market.amm.pegMultiplier,
185
- };
186
- }
187
- else {
188
- amm = market.amm;
189
- }
190
- const baseAssetReservesBefore = amm.baseAssetReserve;
191
- const [_, baseAssetReservesAfter] = (0, _1.calculateAmmReservesAfterSwap)(amm, 'quote', quoteAssetAmount, swapDirection);
192
- let baseAssetAmount = baseAssetReservesBefore
193
- .sub(baseAssetReservesAfter)
194
- .abs();
195
- if (order.reduceOnly) {
196
- const position = user.getUserPosition(order.marketIndex) ||
197
- user.getEmptyPosition(order.marketIndex);
198
- if ((0, types_1.isVariant)(order.direction, 'long') &&
199
- position.baseAssetAmount.gte(numericConstants_1.ZERO)) {
200
- baseAssetAmount = numericConstants_1.ZERO;
201
- }
202
- else if ((0, types_1.isVariant)(order.direction, 'short') &&
203
- position.baseAssetAmount.lte(numericConstants_1.ZERO)) {
204
- baseAssetAmount = numericConstants_1.ZERO;
205
- }
206
- else {
207
- _1.BN.min(baseAssetAmount, position.baseAssetAmount.abs());
208
- }
209
- }
210
- return baseAssetAmount;
133
+ return order.baseAssetAmount;
211
134
  }
212
- exports.calculateBaseAssetAmountUserCanExecute = calculateBaseAssetAmountUserCanExecute;
@@ -0,0 +1,19 @@
1
+ /// <reference types="node" />
2
+ import { Connection } from '@solana/web3.js';
3
+ import { EventEmitter } from 'events';
4
+ import StrictEventEmitter from 'strict-event-emitter-types/types/src';
5
+ declare type SlotSubscriberConfig = {};
6
+ export interface SlotSubscriberEvents {
7
+ newSlot: (newSlot: number) => void;
8
+ }
9
+ export declare class SlotSubscriber {
10
+ private connection;
11
+ currentSlot: number;
12
+ subscriptionId: number;
13
+ eventEmitter: StrictEventEmitter<EventEmitter, SlotSubscriberEvents>;
14
+ constructor(connection: Connection, _config?: SlotSubscriberConfig);
15
+ subscribe(): Promise<void>;
16
+ getSlot(): number;
17
+ unsubscribe(): Promise<void>;
18
+ }
19
+ export {};
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SlotSubscriber = void 0;
4
+ const events_1 = require("events");
5
+ class SlotSubscriber {
6
+ constructor(connection, _config) {
7
+ this.connection = connection;
8
+ this.eventEmitter = new events_1.EventEmitter();
9
+ }
10
+ async subscribe() {
11
+ this.currentSlot = await this.connection.getSlot('confirmed');
12
+ this.subscriptionId = this.connection.onSlotChange((slotInfo) => {
13
+ this.currentSlot = slotInfo.slot;
14
+ this.eventEmitter.emit('newSlot', slotInfo.slot);
15
+ });
16
+ }
17
+ getSlot() {
18
+ return this.currentSlot;
19
+ }
20
+ async unsubscribe() {
21
+ if (this.subscriptionId) {
22
+ await this.connection.removeSlotChangeListener(this.subscriptionId);
23
+ }
24
+ }
25
+ }
26
+ exports.SlotSubscriber = SlotSubscriber;
@@ -1,5 +1,5 @@
1
1
  /// <reference types="node" />
2
- import { TxSender } from './types';
2
+ import { TxSender, TxSigAndSlot } from './types';
3
3
  import { Commitment, ConfirmOptions, RpcResponseAndContext, Signer, SignatureResult, Transaction, TransactionSignature, Connection } from '@solana/web3.js';
4
4
  import { AnchorProvider } from '@project-serum/anchor';
5
5
  declare type ResolveReference = {
@@ -11,7 +11,7 @@ export declare class RetryTxSender implements TxSender {
11
11
  retrySleep: number;
12
12
  additionalConnections: Connection[];
13
13
  constructor(provider: AnchorProvider, timeout?: number, retrySleep?: number, additionalConnections?: Connection[]);
14
- send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions): Promise<TransactionSignature>;
14
+ send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions): Promise<TxSigAndSlot>;
15
15
  prepareTx(tx: Transaction, additionalSigners: Array<Signer>, opts: ConfirmOptions): Promise<Transaction>;
16
16
  confirmTransaction(signature: TransactionSignature, commitment?: Commitment): Promise<RpcResponseAndContext<SignatureResult>>;
17
17
  getTimestamp(): number;
@@ -1,13 +1,4 @@
1
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
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -24,133 +15,127 @@ class RetryTxSender {
24
15
  this.retrySleep = retrySleep !== null && retrySleep !== void 0 ? retrySleep : DEFAULT_RETRY;
25
16
  this.additionalConnections = additionalConnections;
26
17
  }
27
- send(tx, additionalSigners, opts) {
28
- return __awaiter(this, void 0, void 0, function* () {
29
- if (additionalSigners === undefined) {
30
- additionalSigners = [];
31
- }
32
- if (opts === undefined) {
33
- opts = this.provider.opts;
18
+ async send(tx, additionalSigners, opts) {
19
+ if (additionalSigners === undefined) {
20
+ additionalSigners = [];
21
+ }
22
+ if (opts === undefined) {
23
+ opts = this.provider.opts;
24
+ }
25
+ await this.prepareTx(tx, additionalSigners, opts);
26
+ const rawTransaction = tx.serialize();
27
+ const startTime = this.getTimestamp();
28
+ const txid = await this.provider.connection.sendRawTransaction(rawTransaction, opts);
29
+ this.sendToAdditionalConnections(rawTransaction, opts);
30
+ let done = false;
31
+ const resolveReference = {
32
+ resolve: undefined,
33
+ };
34
+ const stopWaiting = () => {
35
+ done = true;
36
+ if (resolveReference.resolve) {
37
+ resolveReference.resolve();
34
38
  }
35
- yield this.prepareTx(tx, additionalSigners, opts);
36
- const rawTransaction = tx.serialize();
37
- const startTime = this.getTimestamp();
38
- const txid = yield this.provider.connection.sendRawTransaction(rawTransaction, opts);
39
- this.sendToAdditionalConnections(rawTransaction, opts);
40
- let done = false;
41
- const resolveReference = {
42
- resolve: undefined,
43
- };
44
- const stopWaiting = () => {
45
- done = true;
46
- if (resolveReference.resolve) {
47
- resolveReference.resolve();
39
+ };
40
+ (async () => {
41
+ while (!done && this.getTimestamp() - startTime < this.timeout) {
42
+ await this.sleep(resolveReference);
43
+ if (!done) {
44
+ this.provider.connection
45
+ .sendRawTransaction(rawTransaction, opts)
46
+ .catch((e) => {
47
+ console.error(e);
48
+ stopWaiting();
49
+ });
50
+ this.sendToAdditionalConnections(rawTransaction, opts);
48
51
  }
49
- };
50
- (() => __awaiter(this, void 0, void 0, function* () {
51
- while (!done && this.getTimestamp() - startTime < this.timeout) {
52
- yield this.sleep(resolveReference);
53
- if (!done) {
54
- this.provider.connection
55
- .sendRawTransaction(rawTransaction, opts)
56
- .catch((e) => {
57
- console.error(e);
58
- stopWaiting();
59
- });
60
- this.sendToAdditionalConnections(rawTransaction, opts);
61
- }
62
- }
63
- }))();
64
- try {
65
- yield this.confirmTransaction(txid, opts.commitment);
66
- }
67
- catch (e) {
68
- console.error(e);
69
- throw e;
70
52
  }
71
- finally {
72
- stopWaiting();
73
- }
74
- return txid;
75
- });
53
+ })();
54
+ let slot;
55
+ try {
56
+ const result = await this.confirmTransaction(txid, opts.commitment);
57
+ slot = result.context.slot;
58
+ }
59
+ catch (e) {
60
+ console.error(e);
61
+ throw e;
62
+ }
63
+ finally {
64
+ stopWaiting();
65
+ }
66
+ return { txSig: txid, slot };
76
67
  }
77
- prepareTx(tx, additionalSigners, opts) {
78
- return __awaiter(this, void 0, void 0, function* () {
79
- tx.feePayer = this.provider.wallet.publicKey;
80
- tx.recentBlockhash = (yield this.provider.connection.getRecentBlockhash(opts.preflightCommitment)).blockhash;
81
- yield this.provider.wallet.signTransaction(tx);
82
- additionalSigners
83
- .filter((s) => s !== undefined)
84
- .forEach((kp) => {
85
- tx.partialSign(kp);
86
- });
87
- return tx;
68
+ async prepareTx(tx, additionalSigners, opts) {
69
+ tx.feePayer = this.provider.wallet.publicKey;
70
+ tx.recentBlockhash = (await this.provider.connection.getRecentBlockhash(opts.preflightCommitment)).blockhash;
71
+ await this.provider.wallet.signTransaction(tx);
72
+ additionalSigners
73
+ .filter((s) => s !== undefined)
74
+ .forEach((kp) => {
75
+ tx.partialSign(kp);
88
76
  });
77
+ return tx;
89
78
  }
90
- confirmTransaction(signature, commitment) {
91
- return __awaiter(this, void 0, void 0, function* () {
92
- let decodedSignature;
93
- try {
94
- decodedSignature = bs58_1.default.decode(signature);
95
- }
96
- catch (err) {
97
- throw new Error('signature must be base58 encoded: ' + signature);
98
- }
99
- (0, assert_1.default)(decodedSignature.length === 64, 'signature has invalid length');
100
- const start = Date.now();
101
- const subscriptionCommitment = commitment || this.provider.opts.commitment;
102
- const subscriptionIds = new Array();
103
- const connections = [
104
- this.provider.connection,
105
- ...this.additionalConnections,
106
- ];
107
- let response = null;
108
- const promises = connections.map((connection, i) => {
109
- let subscriptionId;
110
- const confirmPromise = new Promise((resolve, reject) => {
111
- try {
112
- subscriptionId = connection.onSignature(signature, (result, context) => {
113
- subscriptionIds[i] = undefined;
114
- response = {
115
- context,
116
- value: result,
117
- };
118
- resolve(null);
119
- }, subscriptionCommitment);
120
- }
121
- catch (err) {
122
- reject(err);
123
- }
124
- });
125
- subscriptionIds.push(subscriptionId);
126
- return confirmPromise;
79
+ async confirmTransaction(signature, commitment) {
80
+ let decodedSignature;
81
+ try {
82
+ decodedSignature = bs58_1.default.decode(signature);
83
+ }
84
+ catch (err) {
85
+ throw new Error('signature must be base58 encoded: ' + signature);
86
+ }
87
+ (0, assert_1.default)(decodedSignature.length === 64, 'signature has invalid length');
88
+ const start = Date.now();
89
+ const subscriptionCommitment = commitment || this.provider.opts.commitment;
90
+ const subscriptionIds = new Array();
91
+ const connections = [
92
+ this.provider.connection,
93
+ ...this.additionalConnections,
94
+ ];
95
+ let response = null;
96
+ const promises = connections.map((connection, i) => {
97
+ let subscriptionId;
98
+ const confirmPromise = new Promise((resolve, reject) => {
99
+ try {
100
+ subscriptionId = connection.onSignature(signature, (result, context) => {
101
+ subscriptionIds[i] = undefined;
102
+ response = {
103
+ context,
104
+ value: result,
105
+ };
106
+ resolve(null);
107
+ }, subscriptionCommitment);
108
+ }
109
+ catch (err) {
110
+ reject(err);
111
+ }
127
112
  });
128
- try {
129
- yield this.promiseTimeout(promises, this.timeout);
130
- }
131
- finally {
132
- for (const [i, subscriptionId] of subscriptionIds.entries()) {
133
- if (subscriptionId) {
134
- connections[i].removeSignatureListener(subscriptionId);
135
- }
113
+ subscriptionIds.push(subscriptionId);
114
+ return confirmPromise;
115
+ });
116
+ try {
117
+ await this.promiseTimeout(promises, this.timeout);
118
+ }
119
+ finally {
120
+ for (const [i, subscriptionId] of subscriptionIds.entries()) {
121
+ if (subscriptionId) {
122
+ connections[i].removeSignatureListener(subscriptionId);
136
123
  }
137
124
  }
138
- if (response === null) {
139
- const duration = (Date.now() - start) / 1000;
140
- throw new Error(`Transaction was not confirmed in ${duration.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${signature} using the Solana Explorer or CLI tools.`);
141
- }
142
- return response;
143
- });
125
+ }
126
+ if (response === null) {
127
+ const duration = (Date.now() - start) / 1000;
128
+ throw new Error(`Transaction was not confirmed in ${duration.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${signature} using the Solana Explorer or CLI tools.`);
129
+ }
130
+ return response;
144
131
  }
145
132
  getTimestamp() {
146
133
  return new Date().getTime();
147
134
  }
148
- sleep(reference) {
149
- return __awaiter(this, void 0, void 0, function* () {
150
- return new Promise((resolve) => {
151
- reference.resolve = resolve;
152
- setTimeout(resolve, this.retrySleep);
153
- });
135
+ async sleep(reference) {
136
+ return new Promise((resolve) => {
137
+ reference.resolve = resolve;
138
+ setTimeout(resolve, this.retrySleep);
154
139
  });
155
140
  }
156
141
  promiseTimeout(promises, timeoutMs) {
package/lib/tx/types.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import { Provider } from '@project-serum/anchor';
2
2
  import { ConfirmOptions, Signer, Transaction, TransactionSignature } from '@solana/web3.js';
3
+ export declare type TxSigAndSlot = {
4
+ txSig: TransactionSignature;
5
+ slot: number;
6
+ };
3
7
  export interface TxSender {
4
8
  provider: Provider;
5
- send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions): Promise<TransactionSignature>;
9
+ send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions): Promise<TxSigAndSlot>;
6
10
  }
package/lib/tx/utils.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  import { Transaction, TransactionInstruction } from '@solana/web3.js';
2
- export declare function wrapInTx(instruction: TransactionInstruction): Transaction;
2
+ export declare function wrapInTx(instruction: TransactionInstruction, computeUnits?: number): Transaction;
package/lib/tx/utils.js CHANGED
@@ -2,7 +2,16 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.wrapInTx = void 0;
4
4
  const web3_js_1 = require("@solana/web3.js");
5
- function wrapInTx(instruction) {
6
- return new web3_js_1.Transaction().add(instruction);
5
+ const COMPUTE_UNITS_DEFAULT = 200000;
6
+ function wrapInTx(instruction, computeUnits = 600000 // TODO, requires less code change
7
+ ) {
8
+ const tx = new web3_js_1.Transaction();
9
+ if (computeUnits != COMPUTE_UNITS_DEFAULT) {
10
+ tx.add(web3_js_1.ComputeBudgetProgram.requestUnits({
11
+ units: computeUnits,
12
+ additionalFee: 0,
13
+ }));
14
+ }
15
+ return tx.add(instruction);
7
16
  }
8
17
  exports.wrapInTx = wrapInTx;