@drift-labs/sdk 0.2.0-temp.2 → 2.0.1

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 (278) hide show
  1. package/README.md +27 -29
  2. package/lib/accounts/bulkAccountLoader.d.ts +2 -0
  3. package/lib/accounts/bulkAccountLoader.js +36 -29
  4. package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
  5. package/lib/accounts/bulkUserStatsSubscription.js +21 -0
  6. package/lib/accounts/bulkUserSubscription.d.ts +2 -2
  7. package/lib/accounts/bulkUserSubscription.js +0 -1
  8. package/lib/accounts/fetch.d.ts +2 -1
  9. package/lib/accounts/fetch.js +9 -1
  10. package/lib/accounts/{pollingClearingHouseAccountSubscriber.d.ts → pollingDriftClientAccountSubscriber.d.ts} +20 -25
  11. package/lib/accounts/{pollingClearingHouseAccountSubscriber.js → pollingDriftClientAccountSubscriber.js} +45 -49
  12. package/lib/accounts/{pollingOracleSubscriber.d.ts → pollingOracleAccountSubscriber.d.ts} +2 -2
  13. package/lib/accounts/{pollingOracleSubscriber.js → pollingOracleAccountSubscriber.js} +3 -3
  14. package/lib/accounts/pollingUserAccountSubscriber.d.ts +1 -1
  15. package/lib/accounts/pollingUserAccountSubscriber.js +5 -11
  16. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  17. package/lib/accounts/pollingUserStatsAccountSubscriber.js +107 -0
  18. package/lib/accounts/types.d.ts +26 -15
  19. package/lib/accounts/webSocketDriftClientAccountSubscriber.d.ts +49 -0
  20. package/lib/accounts/{webSocketClearingHouseAccountSubscriber.js → webSocketDriftClientAccountSubscriber.js} +47 -45
  21. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  22. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  23. package/lib/addresses/marketAddresses.d.ts +1 -3
  24. package/lib/addresses/marketAddresses.js +1 -1
  25. package/lib/addresses/pda.d.ts +15 -9
  26. package/lib/addresses/pda.js +73 -35
  27. package/lib/adminClient.d.ts +65 -0
  28. package/lib/adminClient.js +637 -0
  29. package/lib/config.d.ts +10 -10
  30. package/lib/config.js +26 -22
  31. package/lib/constants/numericConstants.d.ts +29 -12
  32. package/lib/constants/numericConstants.js +40 -21
  33. package/lib/constants/perpMarkets.d.ts +18 -0
  34. package/lib/constants/{markets.js → perpMarkets.js} +20 -9
  35. package/lib/constants/spotMarkets.d.ts +19 -0
  36. package/lib/constants/spotMarkets.js +63 -0
  37. package/lib/dlob/DLOB.d.ts +82 -0
  38. package/lib/dlob/DLOB.js +694 -0
  39. package/lib/dlob/DLOBNode.d.ts +54 -0
  40. package/lib/dlob/DLOBNode.js +77 -0
  41. package/lib/dlob/NodeList.d.ts +27 -0
  42. package/lib/dlob/NodeList.js +144 -0
  43. package/lib/driftClient.d.ts +234 -0
  44. package/lib/driftClient.js +2108 -0
  45. package/lib/{clearingHouseConfig.d.ts → driftClientConfig.d.ts} +9 -9
  46. package/lib/{clearingHouseConfig.js → driftClientConfig.js} +0 -0
  47. package/lib/events/eventList.d.ts +0 -1
  48. package/lib/events/eventList.js +0 -7
  49. package/lib/events/eventSubscriber.d.ts +5 -2
  50. package/lib/events/eventSubscriber.js +25 -11
  51. package/lib/events/fetchLogs.d.ts +13 -2
  52. package/lib/events/fetchLogs.js +45 -14
  53. package/lib/events/pollingLogProvider.d.ts +2 -1
  54. package/lib/events/pollingLogProvider.js +7 -3
  55. package/lib/events/sort.js +8 -11
  56. package/lib/events/txEventCache.d.ts +0 -2
  57. package/lib/events/txEventCache.js +0 -14
  58. package/lib/events/types.d.ts +11 -3
  59. package/lib/events/types.js +8 -0
  60. package/lib/events/webSocketLogProvider.js +1 -1
  61. package/lib/examples/makeTradeExample.js +30 -18
  62. package/lib/factory/bigNum.d.ts +8 -4
  63. package/lib/factory/bigNum.js +109 -19
  64. package/lib/idl/drift.json +8392 -0
  65. package/lib/index.d.ts +29 -12
  66. package/lib/index.js +29 -12
  67. package/lib/math/amm.d.ts +9 -6
  68. package/lib/math/amm.js +91 -38
  69. package/lib/math/conversion.js +1 -1
  70. package/lib/math/exchangeStatus.d.ts +4 -0
  71. package/lib/math/exchangeStatus.js +18 -0
  72. package/lib/math/funding.d.ts +6 -6
  73. package/lib/math/funding.js +23 -21
  74. package/lib/math/insurance.d.ts +4 -0
  75. package/lib/math/insurance.js +27 -0
  76. package/lib/math/margin.d.ts +11 -0
  77. package/lib/math/margin.js +82 -0
  78. package/lib/math/market.d.ts +14 -9
  79. package/lib/math/market.js +70 -10
  80. package/lib/math/oracles.d.ts +4 -0
  81. package/lib/math/oracles.js +36 -8
  82. package/lib/math/orders.d.ts +16 -6
  83. package/lib/math/orders.js +97 -17
  84. package/lib/math/position.d.ts +27 -13
  85. package/lib/math/position.js +91 -37
  86. package/lib/math/repeg.js +17 -8
  87. package/lib/math/spotBalance.d.ts +22 -0
  88. package/lib/math/spotBalance.js +192 -0
  89. package/lib/math/spotMarket.d.ts +4 -0
  90. package/lib/math/spotMarket.js +8 -0
  91. package/lib/math/spotPosition.d.ts +6 -0
  92. package/lib/math/spotPosition.js +23 -0
  93. package/lib/math/trade.d.ts +10 -10
  94. package/lib/math/trade.js +27 -31
  95. package/lib/oracles/pythClient.js +1 -1
  96. package/lib/oracles/quoteAssetOracleClient.js +1 -1
  97. package/lib/oracles/switchboardClient.js +1 -1
  98. package/lib/orderParams.d.ts +4 -4
  99. package/lib/orderParams.js +12 -4
  100. package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
  101. package/lib/serum/serumFulfillmentConfigMap.js +17 -0
  102. package/lib/serum/serumSubscriber.d.ts +27 -0
  103. package/lib/serum/serumSubscriber.js +56 -0
  104. package/lib/serum/types.d.ts +11 -0
  105. package/{src/oracles → lib/serum}/types.js +0 -0
  106. package/lib/tokenFaucet.d.ts +1 -0
  107. package/lib/tokenFaucet.js +23 -12
  108. package/lib/tx/retryTxSender.d.ts +1 -1
  109. package/lib/tx/retryTxSender.js +13 -4
  110. package/lib/tx/types.d.ts +1 -1
  111. package/lib/types.d.ts +631 -222
  112. package/lib/types.js +137 -24
  113. package/lib/user.d.ts +228 -0
  114. package/lib/user.js +959 -0
  115. package/lib/userConfig.d.ts +14 -0
  116. package/lib/{clearingHouseUserConfig.js → userConfig.js} +0 -0
  117. package/lib/userMap/userMap.d.ts +41 -0
  118. package/lib/userMap/userMap.js +85 -0
  119. package/lib/userMap/userStatsMap.d.ts +19 -0
  120. package/lib/userMap/userStatsMap.js +68 -0
  121. package/lib/userName.d.ts +1 -0
  122. package/lib/userName.js +3 -2
  123. package/lib/userStats.d.ts +18 -0
  124. package/lib/userStats.js +49 -0
  125. package/lib/userStatsConfig.d.ts +14 -0
  126. package/{src/clearingHouseConfig.js → lib/userStatsConfig.js} +0 -0
  127. package/lib/util/getTokenAddress.d.ts +2 -0
  128. package/lib/util/getTokenAddress.js +9 -0
  129. package/package.json +12 -5
  130. package/src/accounts/bulkAccountLoader.ts +44 -34
  131. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  132. package/src/accounts/bulkUserSubscription.ts +2 -3
  133. package/src/accounts/fetch.ts +27 -2
  134. package/src/accounts/{pollingClearingHouseAccountSubscriber.ts → pollingDriftClientAccountSubscriber.ts} +65 -75
  135. package/src/accounts/{pollingOracleSubscriber.ts → pollingOracleAccountSubscriber.ts} +2 -2
  136. package/src/accounts/pollingUserAccountSubscriber.ts +5 -12
  137. package/src/accounts/pollingUserStatsAccountSubscriber.ts +166 -0
  138. package/src/accounts/types.ts +35 -15
  139. package/src/accounts/{webSocketClearingHouseAccountSubscriber.ts → webSocketDriftClientAccountSubscriber.ts} +78 -73
  140. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  141. package/src/addresses/marketAddresses.ts +3 -4
  142. package/src/addresses/pda.ts +105 -33
  143. package/src/adminClient.ts +1207 -0
  144. package/src/config.ts +41 -34
  145. package/src/constants/numericConstants.ts +59 -26
  146. package/src/constants/{markets.ts → perpMarkets.ts} +22 -11
  147. package/src/constants/spotMarkets.ts +83 -0
  148. package/src/dlob/DLOB.ts +1120 -0
  149. package/src/dlob/DLOBNode.ts +155 -0
  150. package/src/dlob/NodeList.ts +195 -0
  151. package/src/driftClient.ts +3594 -0
  152. package/src/{clearingHouseConfig.ts → driftClientConfig.ts} +9 -8
  153. package/src/events/eventList.ts +1 -8
  154. package/src/events/eventSubscriber.ts +36 -14
  155. package/src/events/fetchLogs.ts +60 -15
  156. package/src/events/pollingLogProvider.ts +11 -3
  157. package/src/events/sort.ts +11 -15
  158. package/src/events/txEventCache.ts +0 -16
  159. package/src/events/types.ts +27 -2
  160. package/src/events/webSocketLogProvider.ts +1 -1
  161. package/src/examples/makeTradeExample.js +152 -75
  162. package/src/examples/makeTradeExample.ts +44 -28
  163. package/src/factory/bigNum.ts +150 -22
  164. package/src/idl/drift.json +8392 -0
  165. package/src/idl/pyth.json +98 -2
  166. package/src/index.ts +29 -12
  167. package/src/math/amm.ts +161 -48
  168. package/src/math/conversion.ts +2 -2
  169. package/src/math/exchangeStatus.ts +31 -0
  170. package/src/math/funding.ts +41 -31
  171. package/src/math/insurance.ts +35 -0
  172. package/src/math/margin.ts +133 -0
  173. package/src/math/market.ts +143 -14
  174. package/src/math/oracles.ts +63 -9
  175. package/src/math/orders.ts +168 -26
  176. package/src/math/position.ts +133 -59
  177. package/src/math/repeg.ts +19 -9
  178. package/src/math/spotBalance.ts +319 -0
  179. package/src/math/spotMarket.ts +9 -0
  180. package/src/math/spotPosition.ts +47 -0
  181. package/src/math/trade.ts +33 -37
  182. package/src/oracles/pythClient.ts +2 -2
  183. package/src/oracles/quoteAssetOracleClient.ts +2 -2
  184. package/src/oracles/switchboardClient.ts +2 -2
  185. package/src/orderParams.ts +16 -8
  186. package/src/serum/serumFulfillmentConfigMap.ts +26 -0
  187. package/src/serum/serumSubscriber.ts +99 -0
  188. package/src/serum/types.ts +13 -0
  189. package/src/tokenFaucet.ts +38 -15
  190. package/src/tx/retryTxSender.ts +16 -5
  191. package/src/tx/types.ts +2 -1
  192. package/src/types.ts +594 -195
  193. package/src/user.ts +1599 -0
  194. package/src/{clearingHouseUserConfig.ts → userConfig.ts} +5 -5
  195. package/src/userMap/userMap.ts +124 -0
  196. package/src/userMap/userStatsMap.ts +108 -0
  197. package/src/userName.ts +2 -1
  198. package/src/userStats.ts +75 -0
  199. package/src/userStatsConfig.ts +18 -0
  200. package/src/util/getTokenAddress.ts +18 -0
  201. package/tests/bn/test.ts +46 -11
  202. package/tests/dlob/helpers.ts +619 -0
  203. package/tests/dlob/test.ts +4586 -0
  204. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +0 -49
  205. package/lib/admin.d.ts +0 -44
  206. package/lib/admin.js +0 -438
  207. package/lib/clearingHouse.d.ts +0 -146
  208. package/lib/clearingHouse.js +0 -1154
  209. package/lib/clearingHouseUser.d.ts +0 -187
  210. package/lib/clearingHouseUser.js +0 -634
  211. package/lib/clearingHouseUserConfig.d.ts +0 -14
  212. package/lib/constants/banks.d.ts +0 -16
  213. package/lib/constants/banks.js +0 -41
  214. package/lib/constants/markets.d.ts +0 -19
  215. package/lib/idl/clearing_house.json +0 -4464
  216. package/lib/math/bankBalance.d.ts +0 -9
  217. package/lib/math/bankBalance.js +0 -75
  218. package/lib/math/state.d.ts +0 -8
  219. package/lib/math/state.js +0 -15
  220. package/lib/orders.d.ts +0 -8
  221. package/lib/orders.js +0 -134
  222. package/src/accounts/bulkAccountLoader.js +0 -197
  223. package/src/accounts/bulkUserSubscription.js +0 -33
  224. package/src/accounts/pollingClearingHouseAccountSubscriber.js +0 -311
  225. package/src/accounts/pollingOracleSubscriber.js +0 -93
  226. package/src/accounts/pollingTokenAccountSubscriber.js +0 -90
  227. package/src/accounts/pollingUserAccountSubscriber.js +0 -132
  228. package/src/accounts/types.js +0 -10
  229. package/src/accounts/utils.js +0 -7
  230. package/src/accounts/webSocketAccountSubscriber.js +0 -93
  231. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +0 -233
  232. package/src/accounts/webSocketUserAccountSubscriber.js +0 -62
  233. package/src/addresses/marketAddresses.js +0 -26
  234. package/src/admin.js +0 -517
  235. package/src/admin.ts +0 -730
  236. package/src/clearingHouse.ts +0 -1828
  237. package/src/clearingHouseUser.ts +0 -978
  238. package/src/clearingHouseUserConfig.js +0 -2
  239. package/src/config.js +0 -67
  240. package/src/constants/banks.js +0 -42
  241. package/src/constants/banks.ts +0 -50
  242. package/src/constants/markets.js +0 -42
  243. package/src/constants/numericConstants.js +0 -41
  244. package/src/events/eventSubscriber.js +0 -139
  245. package/src/events/fetchLogs.js +0 -50
  246. package/src/events/pollingLogProvider.js +0 -64
  247. package/src/events/sort.js +0 -44
  248. package/src/events/txEventCache.js +0 -71
  249. package/src/events/types.js +0 -20
  250. package/src/events/webSocketLogProvider.js +0 -41
  251. package/src/factory/bigNum.js +0 -390
  252. package/src/factory/oracleClient.js +0 -20
  253. package/src/idl/clearing_house.json +0 -4464
  254. package/src/index.js +0 -69
  255. package/src/math/amm.js +0 -369
  256. package/src/math/auction.js +0 -42
  257. package/src/math/bankBalance.ts +0 -112
  258. package/src/math/conversion.js +0 -11
  259. package/src/math/funding.js +0 -248
  260. package/src/math/oracles.js +0 -26
  261. package/src/math/repeg.js +0 -128
  262. package/src/math/state.js +0 -15
  263. package/src/math/state.ts +0 -14
  264. package/src/math/trade.js +0 -253
  265. package/src/math/utils.js +0 -26
  266. package/src/math/utils.js.map +0 -1
  267. package/src/mockUSDCFaucet.js +0 -280
  268. package/src/oracles/oracleClientCache.js +0 -19
  269. package/src/oracles/pythClient.js +0 -46
  270. package/src/oracles/quoteAssetOracleClient.js +0 -32
  271. package/src/oracles/switchboardClient.js +0 -69
  272. package/src/orderParams.js +0 -20
  273. package/src/orders.ts +0 -245
  274. package/src/slot/SlotSubscriber.js +0 -39
  275. package/src/tokenFaucet.js +0 -189
  276. package/src/types.js +0 -125
  277. package/src/userName.js +0 -20
  278. package/src/wallet.js +0 -35
package/src/orders.ts DELETED
@@ -1,245 +0,0 @@
1
- import {
2
- isVariant,
3
- MarketAccount,
4
- Order,
5
- PositionDirection,
6
- UserAccount,
7
- UserPosition,
8
- } from './types';
9
- import { BN, standardizeBaseAssetAmount } from '.';
10
- import { calculateNewMarketAfterTrade } from './math/market';
11
- import {
12
- AMM_TO_QUOTE_PRECISION_RATIO,
13
- PEG_PRECISION,
14
- ZERO,
15
- } from './constants/numericConstants';
16
- import { calculateMaxBaseAssetAmountToTrade } from './math/amm';
17
- import {
18
- findDirectionToClose,
19
- positionCurrentDirection,
20
- } from './math/position';
21
- import { OraclePriceData } from '.';
22
-
23
- export function calculateNewStateAfterOrder(
24
- userAccount: UserAccount,
25
- userPosition: UserPosition,
26
- market: MarketAccount,
27
- order: Order
28
- ): [UserAccount, UserPosition, MarketAccount] | null {
29
- if (isVariant(order.status, 'init')) {
30
- return null;
31
- }
32
-
33
- const baseAssetAmountToTrade = calculateBaseAssetAmountMarketCanExecute(
34
- market,
35
- order
36
- );
37
- if (baseAssetAmountToTrade.lt(market.amm.baseAssetAmountStepSize)) {
38
- return null;
39
- }
40
-
41
- const userAccountAfter = Object.assign({}, userAccount);
42
- const userPositionAfter = Object.assign({}, userPosition);
43
-
44
- const currentPositionDirection = positionCurrentDirection(userPosition);
45
- const increasePosition =
46
- userPosition.baseAssetAmount.eq(ZERO) ||
47
- isSameDirection(order.direction, currentPositionDirection);
48
-
49
- if (increasePosition) {
50
- const marketAfter = calculateNewMarketAfterTrade(
51
- baseAssetAmountToTrade,
52
- order.direction,
53
- market
54
- );
55
-
56
- const { quoteAssetAmountSwapped, baseAssetAmountSwapped } =
57
- calculateAmountSwapped(market, marketAfter);
58
-
59
- userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(
60
- baseAssetAmountSwapped
61
- );
62
- userPositionAfter.quoteAssetAmount = userPositionAfter.quoteAssetAmount.add(
63
- quoteAssetAmountSwapped
64
- );
65
-
66
- return [userAccountAfter, userPositionAfter, marketAfter];
67
- } else {
68
- const reversePosition = baseAssetAmountToTrade.gt(
69
- userPosition.baseAssetAmount.abs()
70
- );
71
-
72
- if (reversePosition) {
73
- const intermediateMarket = calculateNewMarketAfterTrade(
74
- userPosition.baseAssetAmount,
75
- findDirectionToClose(userPosition),
76
- market
77
- );
78
-
79
- const { quoteAssetAmountSwapped: baseAssetValue } =
80
- calculateAmountSwapped(market, intermediateMarket);
81
-
82
- let pnl;
83
- if (isVariant(currentPositionDirection, 'long')) {
84
- pnl = baseAssetValue.sub(userPosition.quoteAssetAmount);
85
- } else {
86
- pnl = userPosition.quoteAssetAmount.sub(baseAssetValue);
87
- }
88
-
89
- userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
90
-
91
- const baseAssetAmountLeft = baseAssetAmountToTrade.sub(
92
- userPosition.baseAssetAmount.abs()
93
- );
94
-
95
- const marketAfter = calculateNewMarketAfterTrade(
96
- baseAssetAmountLeft,
97
- order.direction,
98
- intermediateMarket
99
- );
100
-
101
- const { quoteAssetAmountSwapped, baseAssetAmountSwapped } =
102
- calculateAmountSwapped(intermediateMarket, marketAfter);
103
-
104
- userPositionAfter.quoteAssetAmount = quoteAssetAmountSwapped;
105
- userPositionAfter.baseAssetAmount = baseAssetAmountSwapped;
106
-
107
- return [userAccountAfter, userPositionAfter, marketAfter];
108
- } else {
109
- const marketAfter = calculateNewMarketAfterTrade(
110
- baseAssetAmountToTrade,
111
- order.direction,
112
- market
113
- );
114
-
115
- const {
116
- quoteAssetAmountSwapped: baseAssetValue,
117
- baseAssetAmountSwapped,
118
- } = calculateAmountSwapped(market, marketAfter);
119
-
120
- const costBasisRealized = userPosition.quoteAssetAmount
121
- .mul(baseAssetAmountSwapped.abs())
122
- .div(userPosition.baseAssetAmount.abs());
123
-
124
- let pnl;
125
- if (isVariant(currentPositionDirection, 'long')) {
126
- pnl = baseAssetValue.sub(costBasisRealized);
127
- } else {
128
- pnl = costBasisRealized.sub(baseAssetValue);
129
- }
130
-
131
- userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
132
-
133
- userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(
134
- baseAssetAmountSwapped
135
- );
136
- userPositionAfter.quoteAssetAmount =
137
- userPositionAfter.quoteAssetAmount.sub(costBasisRealized);
138
-
139
- return [userAccountAfter, userPositionAfter, marketAfter];
140
- }
141
- }
142
- }
143
-
144
- function calculateAmountSwapped(
145
- marketBefore: MarketAccount,
146
- marketAfter: MarketAccount
147
- ): { quoteAssetAmountSwapped: BN; baseAssetAmountSwapped: BN } {
148
- return {
149
- quoteAssetAmountSwapped: marketBefore.amm.quoteAssetReserve
150
- .sub(marketAfter.amm.quoteAssetReserve)
151
- .abs()
152
- .mul(marketBefore.amm.pegMultiplier)
153
- .div(PEG_PRECISION)
154
- .div(AMM_TO_QUOTE_PRECISION_RATIO),
155
- baseAssetAmountSwapped: marketBefore.amm.baseAssetReserve.sub(
156
- marketAfter.amm.baseAssetReserve
157
- ),
158
- };
159
- }
160
-
161
- export function calculateBaseAssetAmountMarketCanExecute(
162
- market: MarketAccount,
163
- order: Order,
164
- oraclePriceData?: OraclePriceData
165
- ): BN {
166
- if (isVariant(order.orderType, 'limit')) {
167
- return calculateAmountToTradeForLimit(market, order, oraclePriceData);
168
- } else if (isVariant(order.orderType, 'triggerLimit')) {
169
- return calculateAmountToTradeForTriggerLimit(market, order);
170
- } else if (isVariant(order.orderType, 'market')) {
171
- return ZERO;
172
- } else {
173
- return calculateAmountToTradeForTriggerMarket(market, order);
174
- }
175
- }
176
-
177
- export function calculateAmountToTradeForLimit(
178
- market: MarketAccount,
179
- order: Order,
180
- oraclePriceData?: OraclePriceData
181
- ): BN {
182
- let limitPrice = order.price;
183
- if (!order.oraclePriceOffset.eq(ZERO)) {
184
- if (!oraclePriceData) {
185
- throw Error(
186
- 'Cant calculate limit price for oracle offset oracle without OraclePriceData'
187
- );
188
- }
189
- limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
190
- }
191
-
192
- const [maxAmountToTrade, direction] = calculateMaxBaseAssetAmountToTrade(
193
- market.amm,
194
- limitPrice,
195
- order.direction,
196
- oraclePriceData
197
- );
198
-
199
- const baseAssetAmount = standardizeBaseAssetAmount(
200
- maxAmountToTrade,
201
- market.amm.baseAssetAmountStepSize
202
- );
203
-
204
- // Check that directions are the same
205
- const sameDirection = isSameDirection(direction, order.direction);
206
- if (!sameDirection) {
207
- return ZERO;
208
- }
209
-
210
- return baseAssetAmount.gt(order.baseAssetAmount)
211
- ? order.baseAssetAmount
212
- : baseAssetAmount;
213
- }
214
-
215
- export function calculateAmountToTradeForTriggerLimit(
216
- market: MarketAccount,
217
- order: Order
218
- ): BN {
219
- if (!order.triggered) {
220
- return ZERO;
221
- }
222
-
223
- return calculateAmountToTradeForLimit(market, order);
224
- }
225
-
226
- function isSameDirection(
227
- firstDirection: PositionDirection,
228
- secondDirection: PositionDirection
229
- ): boolean {
230
- return (
231
- (isVariant(firstDirection, 'long') && isVariant(secondDirection, 'long')) ||
232
- (isVariant(firstDirection, 'short') && isVariant(secondDirection, 'short'))
233
- );
234
- }
235
-
236
- function calculateAmountToTradeForTriggerMarket(
237
- market: MarketAccount,
238
- order: Order
239
- ): BN {
240
- if (!order.triggered) {
241
- return ZERO;
242
- }
243
-
244
- return order.baseAssetAmount;
245
- }
@@ -1,39 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.SlotSubscriber = void 0;
13
- const events_1 = require("events");
14
- class SlotSubscriber {
15
- constructor(connection, _config) {
16
- this.connection = connection;
17
- this.eventEmitter = new events_1.EventEmitter();
18
- }
19
- subscribe() {
20
- return __awaiter(this, void 0, void 0, function* () {
21
- this.currentSlot = yield this.connection.getSlot('confirmed');
22
- this.subscriptionId = this.connection.onSlotChange((slotInfo) => {
23
- this.currentSlot = slotInfo.slot;
24
- this.eventEmitter.emit('newSlot', slotInfo.slot);
25
- });
26
- });
27
- }
28
- getSlot() {
29
- return this.currentSlot;
30
- }
31
- unsubscribe() {
32
- return __awaiter(this, void 0, void 0, function* () {
33
- if (this.subscriptionId) {
34
- yield this.connection.removeSlotChangeListener(this.subscriptionId);
35
- }
36
- });
37
- }
38
- }
39
- exports.SlotSubscriber = SlotSubscriber;
@@ -1,189 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
- Object.defineProperty(o, "default", { enumerable: true, value: v });
11
- }) : function(o, v) {
12
- o["default"] = v;
13
- });
14
- var __importStar = (this && this.__importStar) || function (mod) {
15
- if (mod && mod.__esModule) return mod;
16
- var result = {};
17
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
- __setModuleDefault(result, mod);
19
- return result;
20
- };
21
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
22
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23
- return new (P || (P = Promise))(function (resolve, reject) {
24
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27
- step((generator = generator.apply(thisArg, _arguments || [])).next());
28
- });
29
- };
30
- var __importDefault = (this && this.__importDefault) || function (mod) {
31
- return (mod && mod.__esModule) ? mod : { "default": mod };
32
- };
33
- Object.defineProperty(exports, "__esModule", { value: true });
34
- exports.TokenFaucet = void 0;
35
- const anchor = __importStar(require("@project-serum/anchor"));
36
- const anchor_1 = require("@project-serum/anchor");
37
- const spl_token_1 = require("@solana/spl-token");
38
- const web3_js_1 = require("@solana/web3.js");
39
- const token_faucet_json_1 = __importDefault(require("./idl/token_faucet.json"));
40
- class TokenFaucet {
41
- constructor(connection, wallet, programId, mint, opts) {
42
- this.connection = connection;
43
- this.wallet = wallet;
44
- this.opts = opts || anchor_1.AnchorProvider.defaultOptions();
45
- const provider = new anchor_1.AnchorProvider(connection, wallet, this.opts);
46
- this.provider = provider;
47
- this.program = new anchor_1.Program(token_faucet_json_1.default, programId, provider);
48
- this.mint = mint;
49
- }
50
- getFaucetConfigPublicKeyAndNonce() {
51
- return __awaiter(this, void 0, void 0, function* () {
52
- return anchor.web3.PublicKey.findProgramAddress([
53
- Buffer.from(anchor.utils.bytes.utf8.encode('faucet_config')),
54
- this.mint.toBuffer(),
55
- ], this.program.programId);
56
- });
57
- }
58
- getMintAuthority() {
59
- return __awaiter(this, void 0, void 0, function* () {
60
- return (yield anchor.web3.PublicKey.findProgramAddress([
61
- Buffer.from(anchor.utils.bytes.utf8.encode('mint_authority')),
62
- this.mint.toBuffer(),
63
- ], this.program.programId))[0];
64
- });
65
- }
66
- getFaucetConfigPublicKey() {
67
- return __awaiter(this, void 0, void 0, function* () {
68
- return (yield this.getFaucetConfigPublicKeyAndNonce())[0];
69
- });
70
- }
71
- initialize() {
72
- return __awaiter(this, void 0, void 0, function* () {
73
- const [faucetConfigPublicKey] = yield this.getFaucetConfigPublicKeyAndNonce();
74
- return yield this.program.rpc.initialize({
75
- accounts: {
76
- faucetConfig: faucetConfigPublicKey,
77
- admin: this.wallet.publicKey,
78
- mintAccount: this.mint,
79
- rent: web3_js_1.SYSVAR_RENT_PUBKEY,
80
- systemProgram: anchor.web3.SystemProgram.programId,
81
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
82
- },
83
- });
84
- });
85
- }
86
- fetchState() {
87
- return __awaiter(this, void 0, void 0, function* () {
88
- return yield this.program.account.faucetConfig.fetch(yield this.getFaucetConfigPublicKey());
89
- });
90
- }
91
- mintToUserIx(userTokenAccount, amount) {
92
- return __awaiter(this, void 0, void 0, function* () {
93
- return this.program.instruction.mintToUser(amount, {
94
- accounts: {
95
- faucetConfig: yield this.getFaucetConfigPublicKey(),
96
- mintAccount: this.mint,
97
- userTokenAccount,
98
- mintAuthority: yield this.getMintAuthority(),
99
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
100
- },
101
- });
102
- });
103
- }
104
- mintToUser(userTokenAccount, amount) {
105
- return __awaiter(this, void 0, void 0, function* () {
106
- const mintIx = yield this.mintToUserIx(userTokenAccount, amount);
107
- const tx = new web3_js_1.Transaction().add(mintIx);
108
- const txSig = yield this.program.provider.sendAndConfirm(tx, [], this.opts);
109
- return txSig;
110
- });
111
- }
112
- transferMintAuthority() {
113
- return __awaiter(this, void 0, void 0, function* () {
114
- return yield this.program.rpc.transferMintAuthority({
115
- accounts: {
116
- faucetConfig: yield this.getFaucetConfigPublicKey(),
117
- mintAccount: this.mint,
118
- mintAuthority: yield this.getMintAuthority(),
119
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
120
- admin: this.wallet.publicKey,
121
- },
122
- });
123
- });
124
- }
125
- createAssociatedTokenAccountAndMintTo(userPublicKey, amount) {
126
- return __awaiter(this, void 0, void 0, function* () {
127
- const tx = new web3_js_1.Transaction();
128
- const [associatedTokenPublicKey, createAssociatedAccountIx, mintToTx] = yield this.createAssociatedTokenAccountAndMintToInstructions(userPublicKey, amount);
129
- let associatedTokenAccountExists = false;
130
- try {
131
- const assosciatedTokenAccount = yield this.connection.getAccountInfo(associatedTokenPublicKey);
132
- associatedTokenAccountExists = !!assosciatedTokenAccount;
133
- }
134
- catch (e) {
135
- // token account doesn't exist
136
- associatedTokenAccountExists = false;
137
- }
138
- const skipAccountCreation = associatedTokenAccountExists;
139
- if (!skipAccountCreation)
140
- tx.add(createAssociatedAccountIx);
141
- tx.add(mintToTx);
142
- const txSig = yield this.program.provider.sendAndConfirm(tx, [], this.opts);
143
- return [associatedTokenPublicKey, txSig];
144
- });
145
- }
146
- createAssociatedTokenAccountAndMintToInstructions(userPublicKey, amount) {
147
- return __awaiter(this, void 0, void 0, function* () {
148
- const state = yield this.fetchState();
149
- const associateTokenPublicKey = yield this.getAssosciatedMockUSDMintAddress({ userPubKey: userPublicKey });
150
- const createAssociatedAccountIx = spl_token_1.Token.createAssociatedTokenAccountInstruction(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, state.mint, associateTokenPublicKey, userPublicKey, this.wallet.publicKey);
151
- const mintToIx = yield this.mintToUserIx(associateTokenPublicKey, amount);
152
- return [associateTokenPublicKey, createAssociatedAccountIx, mintToIx];
153
- });
154
- }
155
- getAssosciatedMockUSDMintAddress(props) {
156
- return __awaiter(this, void 0, void 0, function* () {
157
- const state = yield this.fetchState();
158
- return spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, state.mint, props.userPubKey);
159
- });
160
- }
161
- getTokenAccountInfo(props) {
162
- return __awaiter(this, void 0, void 0, function* () {
163
- const assosciatedKey = yield this.getAssosciatedMockUSDMintAddress(props);
164
- const state = yield this.fetchState();
165
- const token = new spl_token_1.Token(this.connection, state.mint, spl_token_1.TOKEN_PROGRAM_ID,
166
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
167
- // @ts-ignore
168
- this.provider.payer);
169
- return yield token.getAccountInfo(assosciatedKey);
170
- });
171
- }
172
- subscribeToTokenAccount(props) {
173
- return __awaiter(this, void 0, void 0, function* () {
174
- try {
175
- const tokenAccountKey = yield this.getAssosciatedMockUSDMintAddress(props);
176
- props.callback(yield this.getTokenAccountInfo(props));
177
- // Couldn't find a way to do it using anchor framework subscription, someone on serum discord recommended this way
178
- this.connection.onAccountChange(tokenAccountKey, (_accountInfo /* accountInfo is a buffer which we don't know how to deserialize */) => __awaiter(this, void 0, void 0, function* () {
179
- props.callback(yield this.getTokenAccountInfo(props));
180
- }));
181
- return true;
182
- }
183
- catch (e) {
184
- return false;
185
- }
186
- });
187
- }
188
- }
189
- exports.TokenFaucet = TokenFaucet;
package/src/types.js DELETED
@@ -1,125 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DefaultOrderParams = exports.LiquidationType = exports.TradeSide = exports.isOneOfVariant = exports.isVariant = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderDiscountTier = exports.OrderStatus = exports.OrderType = exports.OracleSource = exports.DepositDirection = exports.PositionDirection = exports.BankBalanceType = exports.SwapDirection = void 0;
4
- const _1 = require(".");
5
- // # Utility Types / Enums / Constants
6
- class SwapDirection {
7
- }
8
- exports.SwapDirection = SwapDirection;
9
- SwapDirection.ADD = { add: {} };
10
- SwapDirection.REMOVE = { remove: {} };
11
- class BankBalanceType {
12
- }
13
- exports.BankBalanceType = BankBalanceType;
14
- BankBalanceType.DEPOSIT = { deposit: {} };
15
- BankBalanceType.BORROW = { borrow: {} };
16
- class PositionDirection {
17
- }
18
- exports.PositionDirection = PositionDirection;
19
- PositionDirection.LONG = { long: {} };
20
- PositionDirection.SHORT = { short: {} };
21
- class DepositDirection {
22
- }
23
- exports.DepositDirection = DepositDirection;
24
- DepositDirection.DEPOSIT = { deposit: {} };
25
- DepositDirection.WITHDRAW = { withdraw: {} };
26
- class OracleSource {
27
- }
28
- exports.OracleSource = OracleSource;
29
- OracleSource.PYTH = { pyth: {} };
30
- OracleSource.SWITCHBOARD = { switchboard: {} };
31
- OracleSource.QUOTE_ASSET = { quoteAsset: {} };
32
- class OrderType {
33
- }
34
- exports.OrderType = OrderType;
35
- OrderType.LIMIT = { limit: {} };
36
- OrderType.TRIGGER_MARKET = { triggerMarket: {} };
37
- OrderType.TRIGGER_LIMIT = { triggerLimit: {} };
38
- OrderType.MARKET = { market: {} };
39
- class OrderStatus {
40
- }
41
- exports.OrderStatus = OrderStatus;
42
- OrderStatus.INIT = { init: {} };
43
- OrderStatus.OPEN = { open: {} };
44
- class OrderDiscountTier {
45
- }
46
- exports.OrderDiscountTier = OrderDiscountTier;
47
- OrderDiscountTier.NONE = { none: {} };
48
- OrderDiscountTier.FIRST = { first: {} };
49
- OrderDiscountTier.SECOND = { second: {} };
50
- OrderDiscountTier.THIRD = { third: {} };
51
- OrderDiscountTier.FOURTH = { fourth: {} };
52
- class OrderAction {
53
- }
54
- exports.OrderAction = OrderAction;
55
- OrderAction.PLACE = { place: {} };
56
- OrderAction.CANCEL = { cancel: {} };
57
- OrderAction.EXPIRE = { expire: {} };
58
- OrderAction.FILL = { fill: {} };
59
- OrderAction.TRIGGER = { trigger: {} };
60
- class OrderActionExplanation {
61
- }
62
- exports.OrderActionExplanation = OrderActionExplanation;
63
- OrderActionExplanation.NONE = { none: {} };
64
- OrderActionExplanation.BREACHED_MARGIN_REQUIREMENT = {
65
- breachedMarginRequirement: {},
66
- };
67
- OrderActionExplanation.ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
68
- oraclePriceBreachedLimitPrice: {},
69
- };
70
- OrderActionExplanation.MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
71
- marketOrderFilledToLimitPrice: {},
72
- };
73
- class OrderTriggerCondition {
74
- }
75
- exports.OrderTriggerCondition = OrderTriggerCondition;
76
- OrderTriggerCondition.ABOVE = { above: {} };
77
- OrderTriggerCondition.BELOW = { below: {} };
78
- function isVariant(object, type) {
79
- return object.hasOwnProperty(type);
80
- }
81
- exports.isVariant = isVariant;
82
- function isOneOfVariant(object, types) {
83
- return types.reduce((result, type) => {
84
- return result || object.hasOwnProperty(type);
85
- }, false);
86
- }
87
- exports.isOneOfVariant = isOneOfVariant;
88
- var TradeSide;
89
- (function (TradeSide) {
90
- TradeSide[TradeSide["None"] = 0] = "None";
91
- TradeSide[TradeSide["Buy"] = 1] = "Buy";
92
- TradeSide[TradeSide["Sell"] = 2] = "Sell";
93
- })(TradeSide = exports.TradeSide || (exports.TradeSide = {}));
94
- class LiquidationType {
95
- }
96
- exports.LiquidationType = LiquidationType;
97
- LiquidationType.LIQUIDATE_PERP = { liquidatePerp: {} };
98
- LiquidationType.LIQUIDATE_BORROW = { liquidateBorrow: {} };
99
- LiquidationType.LIQUIDATE_BORROW_FOR_PERP_PNL = {
100
- liquidateBorrowForPerpPnl: {},
101
- };
102
- LiquidationType.LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
103
- liquidatePerpPnlForDeposit: {},
104
- };
105
- exports.DefaultOrderParams = {
106
- orderType: OrderType.MARKET,
107
- userOrderId: 0,
108
- direction: PositionDirection.LONG,
109
- baseAssetAmount: _1.ZERO,
110
- price: _1.ZERO,
111
- marketIndex: _1.ZERO,
112
- reduceOnly: false,
113
- postOnly: false,
114
- immediateOrCancel: false,
115
- triggerPrice: _1.ZERO,
116
- triggerCondition: OrderTriggerCondition.ABOVE,
117
- positionLimit: _1.ZERO,
118
- oraclePriceOffset: _1.ZERO,
119
- padding0: _1.ZERO,
120
- padding1: _1.ZERO,
121
- optionalAccounts: {
122
- discountToken: false,
123
- referrer: false,
124
- },
125
- };
package/src/userName.js DELETED
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decodeName = exports.encodeName = exports.DEFAULT_USER_NAME = exports.MAX_NAME_LENGTH = void 0;
4
- exports.MAX_NAME_LENGTH = 32;
5
- exports.DEFAULT_USER_NAME = 'Main Account';
6
- function encodeName(name) {
7
- if (name.length > exports.MAX_NAME_LENGTH) {
8
- throw Error(`User name (${name}) longer than 32 characters`);
9
- }
10
- const buffer = Buffer.alloc(32);
11
- buffer.fill(name);
12
- buffer.fill(' ', name.length);
13
- return Array(...buffer);
14
- }
15
- exports.encodeName = encodeName;
16
- function decodeName(bytes) {
17
- const buffer = Buffer.from(bytes);
18
- return buffer.toString('utf8').trim();
19
- }
20
- exports.decodeName = decodeName;
package/src/wallet.js DELETED
@@ -1,35 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.Wallet = void 0;
13
- class Wallet {
14
- constructor(payer) {
15
- this.payer = payer;
16
- }
17
- signTransaction(tx) {
18
- return __awaiter(this, void 0, void 0, function* () {
19
- tx.partialSign(this.payer);
20
- return tx;
21
- });
22
- }
23
- signAllTransactions(txs) {
24
- return __awaiter(this, void 0, void 0, function* () {
25
- return txs.map((t) => {
26
- t.partialSign(this.payer);
27
- return t;
28
- });
29
- });
30
- }
31
- get publicKey() {
32
- return this.payer.publicKey;
33
- }
34
- }
35
- exports.Wallet = Wallet;