@drift-labs/sdk 0.2.0-master.4 → 0.2.0-master.40

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 (234) hide show
  1. package/README.md +27 -27
  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/pollingUserStatsAccountSubscriber.d.ts +27 -0
  15. package/lib/accounts/pollingUserStatsAccountSubscriber.js +113 -0
  16. package/lib/accounts/types.d.ts +26 -15
  17. package/lib/accounts/webSocketDriftClientAccountSubscriber.d.ts +49 -0
  18. package/lib/accounts/{webSocketClearingHouseAccountSubscriber.js → webSocketDriftClientAccountSubscriber.js} +47 -45
  19. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  20. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  21. package/lib/addresses/marketAddresses.d.ts +1 -3
  22. package/lib/addresses/marketAddresses.js +1 -1
  23. package/lib/addresses/pda.d.ts +15 -9
  24. package/lib/addresses/pda.js +73 -35
  25. package/lib/adminClient.d.ts +65 -0
  26. package/lib/adminClient.js +637 -0
  27. package/lib/config.d.ts +9 -9
  28. package/lib/config.js +25 -21
  29. package/lib/constants/numericConstants.d.ts +30 -12
  30. package/lib/constants/numericConstants.js +41 -21
  31. package/lib/constants/perpMarkets.d.ts +18 -0
  32. package/lib/constants/{markets.js → perpMarkets.js} +7 -7
  33. package/lib/constants/spotMarkets.d.ts +19 -0
  34. package/lib/constants/spotMarkets.js +53 -0
  35. package/lib/dlob/DLOB.d.ts +82 -0
  36. package/lib/dlob/DLOB.js +696 -0
  37. package/lib/dlob/DLOBNode.d.ts +54 -0
  38. package/lib/dlob/DLOBNode.js +77 -0
  39. package/lib/dlob/NodeList.d.ts +27 -0
  40. package/lib/dlob/NodeList.js +144 -0
  41. package/lib/driftClient.d.ts +233 -0
  42. package/lib/driftClient.js +2096 -0
  43. package/lib/{clearingHouseConfig.d.ts → driftClientConfig.d.ts} +9 -9
  44. package/lib/{clearingHouseConfig.js → driftClientConfig.js} +0 -0
  45. package/lib/events/eventList.js +3 -0
  46. package/lib/events/eventSubscriber.d.ts +5 -2
  47. package/lib/events/eventSubscriber.js +25 -11
  48. package/lib/events/fetchLogs.d.ts +13 -2
  49. package/lib/events/fetchLogs.js +40 -12
  50. package/lib/events/pollingLogProvider.d.ts +2 -1
  51. package/lib/events/pollingLogProvider.js +7 -3
  52. package/lib/events/sort.js +8 -11
  53. package/lib/events/types.d.ts +9 -3
  54. package/lib/events/types.js +6 -0
  55. package/lib/events/webSocketLogProvider.js +1 -1
  56. package/lib/examples/makeTradeExample.js +30 -18
  57. package/lib/factory/bigNum.d.ts +8 -4
  58. package/lib/factory/bigNum.js +109 -19
  59. package/lib/idl/drift.json +8250 -0
  60. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  61. package/lib/index.d.ts +30 -13
  62. package/lib/index.js +30 -13
  63. package/lib/math/amm.d.ts +9 -6
  64. package/lib/math/amm.js +91 -38
  65. package/lib/math/conversion.js +1 -1
  66. package/lib/math/exchangeStatus.d.ts +4 -0
  67. package/lib/math/exchangeStatus.js +18 -0
  68. package/lib/math/funding.d.ts +6 -6
  69. package/lib/math/funding.js +23 -21
  70. package/lib/math/insurance.d.ts +4 -0
  71. package/lib/math/insurance.js +27 -0
  72. package/lib/math/margin.d.ts +11 -0
  73. package/lib/math/margin.js +82 -0
  74. package/lib/math/market.d.ts +14 -9
  75. package/lib/math/market.js +70 -10
  76. package/lib/math/oracles.d.ts +4 -0
  77. package/lib/math/oracles.js +36 -8
  78. package/lib/math/orders.d.ts +14 -6
  79. package/lib/math/orders.js +90 -17
  80. package/lib/math/position.d.ts +27 -13
  81. package/lib/math/position.js +92 -36
  82. package/lib/math/repeg.js +17 -8
  83. package/lib/math/spotBalance.d.ts +22 -0
  84. package/lib/math/spotBalance.js +192 -0
  85. package/lib/math/spotMarket.d.ts +4 -0
  86. package/lib/math/spotMarket.js +8 -0
  87. package/lib/math/spotPosition.d.ts +6 -0
  88. package/lib/math/spotPosition.js +23 -0
  89. package/lib/math/trade.d.ts +10 -10
  90. package/lib/math/trade.js +27 -31
  91. package/lib/oracles/pythClient.js +1 -1
  92. package/lib/oracles/quoteAssetOracleClient.js +1 -1
  93. package/lib/oracles/switchboardClient.js +1 -1
  94. package/lib/orderParams.d.ts +4 -4
  95. package/lib/orderParams.js +12 -4
  96. package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
  97. package/lib/serum/serumFulfillmentConfigMap.js +17 -0
  98. package/lib/serum/serumSubscriber.d.ts +27 -0
  99. package/lib/serum/serumSubscriber.js +56 -0
  100. package/lib/serum/types.d.ts +11 -0
  101. package/lib/{clearingHouseUserConfig.js → serum/types.js} +0 -0
  102. package/lib/slot/SlotSubscriber.d.ts +7 -0
  103. package/lib/slot/SlotSubscriber.js +3 -0
  104. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  105. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  106. package/lib/tx/retryTxSender.d.ts +1 -1
  107. package/lib/tx/retryTxSender.js +13 -4
  108. package/lib/tx/types.d.ts +1 -1
  109. package/lib/tx/utils.js +1 -1
  110. package/lib/types.d.ts +589 -196
  111. package/lib/types.js +108 -17
  112. package/lib/user.d.ts +226 -0
  113. package/lib/user.js +949 -0
  114. package/lib/userConfig.d.ts +14 -0
  115. package/lib/userConfig.js +2 -0
  116. package/lib/userMap/userMap.d.ts +41 -0
  117. package/lib/userMap/userMap.js +85 -0
  118. package/lib/userMap/userStatsMap.d.ts +19 -0
  119. package/lib/userMap/userStatsMap.js +68 -0
  120. package/lib/userName.d.ts +1 -0
  121. package/lib/userName.js +3 -2
  122. package/lib/userStats.d.ts +18 -0
  123. package/lib/userStats.js +49 -0
  124. package/lib/userStatsConfig.d.ts +14 -0
  125. package/lib/userStatsConfig.js +2 -0
  126. package/lib/util/computeUnits.js +1 -1
  127. package/lib/util/getTokenAddress.d.ts +2 -0
  128. package/lib/util/getTokenAddress.js +9 -0
  129. package/package.json +10 -3
  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/pollingUserStatsAccountSubscriber.ts +172 -0
  137. package/src/accounts/types.ts +35 -15
  138. package/src/accounts/{webSocketClearingHouseAccountSubscriber.ts → webSocketDriftClientAccountSubscriber.ts} +78 -73
  139. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  140. package/src/addresses/marketAddresses.ts +3 -4
  141. package/src/addresses/pda.ts +105 -33
  142. package/src/adminClient.ts +1207 -0
  143. package/src/config.ts +37 -31
  144. package/src/constants/numericConstants.ts +58 -24
  145. package/src/constants/{markets.ts → perpMarkets.ts} +10 -10
  146. package/src/constants/spotMarkets.ts +73 -0
  147. package/src/dlob/DLOB.ts +1123 -0
  148. package/src/dlob/DLOBNode.ts +155 -0
  149. package/src/dlob/NodeList.ts +195 -0
  150. package/src/driftClient.ts +3564 -0
  151. package/src/{clearingHouseConfig.ts → driftClientConfig.ts} +9 -8
  152. package/src/events/eventList.ts +3 -0
  153. package/src/events/eventSubscriber.ts +36 -14
  154. package/src/events/fetchLogs.ts +55 -13
  155. package/src/events/pollingLogProvider.ts +11 -3
  156. package/src/events/sort.ts +11 -15
  157. package/src/events/types.ts +21 -2
  158. package/src/events/webSocketLogProvider.ts +1 -1
  159. package/src/examples/makeTradeExample.ts +44 -28
  160. package/src/factory/bigNum.ts +150 -22
  161. package/src/idl/drift.json +8250 -0
  162. package/src/idl/pyth.json +98 -2
  163. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  164. package/src/index.ts +30 -13
  165. package/src/math/amm.ts +161 -48
  166. package/src/math/conversion.ts +2 -2
  167. package/src/math/exchangeStatus.ts +31 -0
  168. package/src/math/funding.ts +41 -31
  169. package/src/math/insurance.ts +35 -0
  170. package/src/math/margin.ts +133 -0
  171. package/src/math/market.ts +143 -14
  172. package/src/math/oracles.ts +63 -9
  173. package/src/math/orders.ts +163 -26
  174. package/src/math/position.ts +136 -58
  175. package/src/math/repeg.ts +19 -9
  176. package/src/math/spotBalance.ts +319 -0
  177. package/src/math/spotMarket.ts +9 -0
  178. package/src/math/spotPosition.ts +47 -0
  179. package/src/math/trade.ts +33 -37
  180. package/src/oracles/pythClient.ts +2 -2
  181. package/src/oracles/quoteAssetOracleClient.ts +2 -2
  182. package/src/oracles/switchboardClient.ts +2 -2
  183. package/src/orderParams.ts +16 -8
  184. package/src/serum/serumFulfillmentConfigMap.ts +26 -0
  185. package/src/serum/serumSubscriber.ts +99 -0
  186. package/src/serum/types.ts +13 -0
  187. package/src/slot/SlotSubscriber.ts +11 -1
  188. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  189. package/src/tx/retryTxSender.ts +16 -5
  190. package/src/tx/types.ts +2 -1
  191. package/src/tx/utils.ts +1 -1
  192. package/src/types.ts +572 -178
  193. package/src/user.ts +1582 -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/computeUnits.ts +1 -1
  201. package/src/util/getTokenAddress.ts +18 -0
  202. package/tests/bn/test.ts +46 -11
  203. package/tests/dlob/helpers.ts +611 -0
  204. package/tests/dlob/test.ts +4588 -0
  205. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +0 -49
  206. package/lib/admin.d.ts +0 -44
  207. package/lib/admin.js +0 -433
  208. package/lib/clearingHouse.d.ts +0 -133
  209. package/lib/clearingHouse.js +0 -931
  210. package/lib/clearingHouseUser.d.ts +0 -187
  211. package/lib/clearingHouseUser.js +0 -643
  212. package/lib/clearingHouseUserConfig.d.ts +0 -14
  213. package/lib/constants/banks.d.ts +0 -16
  214. package/lib/constants/banks.js +0 -34
  215. package/lib/constants/markets.d.ts +0 -19
  216. package/lib/idl/clearing_house.json +0 -3998
  217. package/lib/math/bankBalance.d.ts +0 -9
  218. package/lib/math/bankBalance.js +0 -75
  219. package/lib/math/state.d.ts +0 -8
  220. package/lib/math/state.js +0 -15
  221. package/lib/orders.d.ts +0 -8
  222. package/lib/orders.js +0 -134
  223. package/src/admin.ts +0 -722
  224. package/src/clearingHouse.ts +0 -1451
  225. package/src/clearingHouseUser.ts +0 -989
  226. package/src/constants/banks.ts +0 -43
  227. package/src/idl/clearing_house.json +0 -3998
  228. package/src/math/bankBalance.ts +0 -112
  229. package/src/math/state.ts +0 -14
  230. package/src/math/utils.js +0 -27
  231. package/src/math/utils.js.map +0 -1
  232. package/src/orders.ts +0 -244
  233. package/src/util/computeUnits.js +0 -17
  234. package/src/util/computeUnits.js.map +0 -1
@@ -0,0 +1,696 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DLOB = void 0;
4
+ const NodeList_1 = require("./NodeList");
5
+ const __1 = require("..");
6
+ const exchangeStatus_1 = require("../math/exchangeStatus");
7
+ class DLOB {
8
+ /**
9
+ *
10
+ * @param perpMarkets The perp markets to maintain a DLOB for
11
+ * @param spotMarkets The spot markets to maintain a DLOB for
12
+ * @param userMap map of all users
13
+ * @param silent set to true to prevent logging on inserts and removals
14
+ */
15
+ constructor(perpMarkets, spotMarkets, stateAccount, userMap, silent) {
16
+ this.openOrders = new Map();
17
+ this.orderLists = new Map();
18
+ this.marketIndexToAccount = new Map();
19
+ this.silent = false;
20
+ this.initialized = false;
21
+ this.stateAccount = stateAccount;
22
+ this.userMap = userMap;
23
+ this.silent = silent;
24
+ this.openOrders.set('perp', new Set());
25
+ this.openOrders.set('spot', new Set());
26
+ this.orderLists.set('perp', new Map());
27
+ this.orderLists.set('spot', new Map());
28
+ this.marketIndexToAccount.set('perp', new Map());
29
+ this.marketIndexToAccount.set('spot', new Map());
30
+ for (const market of perpMarkets) {
31
+ const marketIndex = market.marketIndex;
32
+ this.marketIndexToAccount.get('perp').set(marketIndex, market);
33
+ this.orderLists.get('perp').set(marketIndex, {
34
+ limit: {
35
+ ask: new NodeList_1.NodeList('limit', 'asc'),
36
+ bid: new NodeList_1.NodeList('limit', 'desc'),
37
+ },
38
+ floatingLimit: {
39
+ ask: new NodeList_1.NodeList('floatingLimit', 'asc'),
40
+ bid: new NodeList_1.NodeList('floatingLimit', 'desc'),
41
+ },
42
+ market: {
43
+ ask: new NodeList_1.NodeList('market', 'asc'),
44
+ bid: new NodeList_1.NodeList('market', 'asc'), // always sort ascending for market orders
45
+ },
46
+ trigger: {
47
+ above: new NodeList_1.NodeList('trigger', 'asc'),
48
+ below: new NodeList_1.NodeList('trigger', 'desc'),
49
+ },
50
+ });
51
+ }
52
+ for (const market of spotMarkets) {
53
+ const marketIndex = market.marketIndex;
54
+ this.marketIndexToAccount.get('spot').set(marketIndex, market);
55
+ this.orderLists.get('spot').set(marketIndex, {
56
+ limit: {
57
+ ask: new NodeList_1.NodeList('limit', 'asc'),
58
+ bid: new NodeList_1.NodeList('limit', 'desc'),
59
+ },
60
+ floatingLimit: {
61
+ ask: new NodeList_1.NodeList('floatingLimit', 'asc'),
62
+ bid: new NodeList_1.NodeList('floatingLimit', 'desc'),
63
+ },
64
+ market: {
65
+ ask: new NodeList_1.NodeList('market', 'asc'),
66
+ bid: new NodeList_1.NodeList('market', 'asc'), // always sort ascending for market orders
67
+ },
68
+ trigger: {
69
+ above: new NodeList_1.NodeList('trigger', 'asc'),
70
+ below: new NodeList_1.NodeList('trigger', 'desc'),
71
+ },
72
+ });
73
+ }
74
+ }
75
+ clear() {
76
+ for (const marketType of this.openOrders.keys()) {
77
+ this.openOrders.get(marketType).clear();
78
+ }
79
+ this.openOrders.clear();
80
+ for (const marketType of this.orderLists.keys()) {
81
+ for (const marketIndex of this.orderLists.get(marketType).keys()) {
82
+ const marketNodeLists = this.orderLists
83
+ .get(marketType)
84
+ .get(marketIndex);
85
+ for (const side of Object.keys(marketNodeLists)) {
86
+ for (const orderType of Object.keys(marketNodeLists[side])) {
87
+ marketNodeLists[side][orderType].clear();
88
+ }
89
+ }
90
+ }
91
+ }
92
+ this.orderLists.clear();
93
+ for (const marketType of this.marketIndexToAccount.keys()) {
94
+ this.marketIndexToAccount.get(marketType).clear();
95
+ }
96
+ this.marketIndexToAccount.clear();
97
+ }
98
+ /**
99
+ * initializes a new DLOB instance
100
+ *
101
+ * @returns a promise that resolves when the DLOB is initialized
102
+ */
103
+ async init() {
104
+ if (this.initialized) {
105
+ return false;
106
+ }
107
+ // initialize the dlob with the user map (prevents hitting getProgramAccounts)
108
+ for (const user of this.userMap.values()) {
109
+ const userAccount = user.getUserAccount();
110
+ const userAccountPubkey = user.getUserAccountPublicKey();
111
+ for (const order of userAccount.orders) {
112
+ this.insertOrder(order, userAccountPubkey);
113
+ }
114
+ }
115
+ this.initialized = true;
116
+ return true;
117
+ }
118
+ insertOrder(order, userAccount, onInsert) {
119
+ var _a;
120
+ if ((0, __1.isVariant)(order.status, 'init')) {
121
+ return;
122
+ }
123
+ const marketType = (0, __1.getVariant)(order.marketType);
124
+ if ((0, __1.isVariant)(order.status, 'open')) {
125
+ this.openOrders
126
+ .get(marketType)
127
+ .add((0, NodeList_1.getOrderSignature)(order.orderId, userAccount));
128
+ }
129
+ (_a = this.getListForOrder(order)) === null || _a === void 0 ? void 0 : _a.insert(order, marketType, this.marketIndexToAccount.get(marketType).get(order.marketIndex), userAccount);
130
+ if (onInsert) {
131
+ onInsert();
132
+ }
133
+ }
134
+ trigger(order, userAccount, onTrigger) {
135
+ var _a;
136
+ if ((0, __1.isVariant)(order.status, 'init')) {
137
+ return;
138
+ }
139
+ const marketType = (0, __1.getVariant)(order.marketType);
140
+ const triggerList = this.orderLists.get(marketType).get(order.marketIndex)
141
+ .trigger[(0, __1.isVariant)(order.triggerCondition, 'above') ? 'above' : 'below'];
142
+ triggerList.remove(order, userAccount);
143
+ (_a = this.getListForOrder(order)) === null || _a === void 0 ? void 0 : _a.insert(order, marketType, this.marketIndexToAccount.get(marketType).get(order.marketIndex), userAccount);
144
+ if (onTrigger) {
145
+ onTrigger();
146
+ }
147
+ }
148
+ getListForOrder(order) {
149
+ const isInactiveTriggerOrder = (0, __1.isOneOfVariant)(order.orderType, ['triggerMarket', 'triggerLimit']) &&
150
+ !order.triggered;
151
+ let type;
152
+ if (isInactiveTriggerOrder) {
153
+ type = 'trigger';
154
+ }
155
+ else if ((0, __1.isOneOfVariant)(order.orderType, ['market', 'triggerMarket'])) {
156
+ type = 'market';
157
+ }
158
+ else if (order.oraclePriceOffset !== 0) {
159
+ type = 'floatingLimit';
160
+ }
161
+ else {
162
+ type = 'limit';
163
+ }
164
+ let subType;
165
+ if (isInactiveTriggerOrder) {
166
+ subType = (0, __1.isVariant)(order.triggerCondition, 'above') ? 'above' : 'below';
167
+ }
168
+ else {
169
+ subType = (0, __1.isVariant)(order.direction, 'long') ? 'bid' : 'ask';
170
+ }
171
+ const marketType = (0, __1.getVariant)(order.marketType);
172
+ if (!this.orderLists.has(marketType)) {
173
+ return undefined;
174
+ }
175
+ return this.orderLists.get(marketType).get(order.marketIndex)[type][subType];
176
+ }
177
+ findNodesToFill(marketIndex, fallbackBid, fallbackAsk, slot, ts, marketType, oraclePriceData) {
178
+ const marketAccount = this.marketIndexToAccount
179
+ .get((0, __1.getVariant)(marketType))
180
+ .get(marketIndex);
181
+ if ((0, exchangeStatus_1.fillPaused)(this.stateAccount, marketAccount)) {
182
+ return [];
183
+ }
184
+ // Find all the crossing nodes
185
+ const crossingNodesToFill = this.findCrossingNodesToFill(marketIndex, slot, marketType, oraclePriceData);
186
+ let fallbackCrossingNodesToFill = new Array();
187
+ if (!(0, exchangeStatus_1.ammPaused)(this.stateAccount, marketAccount)) {
188
+ fallbackCrossingNodesToFill = this.findFallbackCrossingNodesToFill(marketIndex, fallbackBid, fallbackAsk, slot, marketType, oraclePriceData);
189
+ }
190
+ // get expired market nodes
191
+ const expiredNodesToFill = this.findExpiredNodesToFill(marketIndex, ts, marketType);
192
+ return crossingNodesToFill.concat(fallbackCrossingNodesToFill, expiredNodesToFill);
193
+ }
194
+ findCrossingNodesToFill(marketIndex, slot, marketType, oraclePriceData) {
195
+ const nodesToFill = new Array();
196
+ const askGenerator = this.getAsks(marketIndex, undefined, // dont include vask
197
+ slot, marketType, oraclePriceData);
198
+ const bidGenerator = this.getBids(marketIndex, undefined, // dont include vbid
199
+ slot, marketType, oraclePriceData);
200
+ let nextAsk = askGenerator.next();
201
+ let nextBid = bidGenerator.next();
202
+ // First try to find orders that cross
203
+ while (!nextAsk.done && !nextBid.done) {
204
+ const { crossingNodes, exhaustedSide } = this.findCrossingOrders(nextAsk.value, nextBid.value, oraclePriceData, slot);
205
+ if (exhaustedSide === 'bid') {
206
+ nextBid = bidGenerator.next();
207
+ }
208
+ else if (exhaustedSide === 'ask') {
209
+ nextAsk = askGenerator.next();
210
+ }
211
+ else if (exhaustedSide === 'both') {
212
+ nextBid = bidGenerator.next();
213
+ nextAsk = askGenerator.next();
214
+ }
215
+ else if (exhaustedSide === 'nocross') {
216
+ break;
217
+ }
218
+ else {
219
+ console.error(`invalid exhaustedSide: ${exhaustedSide}`);
220
+ break;
221
+ }
222
+ for (const crossingNode of crossingNodes) {
223
+ nodesToFill.push(crossingNode);
224
+ }
225
+ }
226
+ return nodesToFill;
227
+ }
228
+ findFallbackCrossingNodesToFill(marketIndex, fallbackBid, fallbackAsk, slot, marketType, oraclePriceData) {
229
+ var _a, _b;
230
+ const nodesToFill = new Array();
231
+ const askGenerator = this.getAsks(marketIndex, undefined, // dont include vask
232
+ slot, marketType, oraclePriceData);
233
+ const bidGenerator = this.getBids(marketIndex, undefined, // dont include vbid
234
+ slot, marketType, oraclePriceData);
235
+ let nextAsk = askGenerator.next();
236
+ let nextBid = bidGenerator.next();
237
+ // check for asks that cross fallbackBid
238
+ while (!nextAsk.done && fallbackBid !== undefined) {
239
+ const askNode = nextAsk.value;
240
+ if ((0, __1.isVariant)(marketType, 'spot') && ((_a = askNode.order) === null || _a === void 0 ? void 0 : _a.postOnly)) {
241
+ nextAsk = askGenerator.next();
242
+ continue;
243
+ }
244
+ const askLimitPrice = (0, __1.getOptionalLimitPrice)(askNode.order, oraclePriceData, slot);
245
+ // order crosses if there is no limit price or it crosses fallback price
246
+ const crosses = askLimitPrice === undefined || askLimitPrice.lte(fallbackBid);
247
+ // fallback is available if auction is complete or it's a spot order
248
+ const fallbackAvailable = (0, __1.isVariant)(marketType, 'spot') || (0, __1.isAuctionComplete)(askNode.order, slot);
249
+ if (crosses && fallbackAvailable) {
250
+ nodesToFill.push({
251
+ node: askNode,
252
+ makerNode: undefined, // filled by fallback
253
+ });
254
+ }
255
+ nextAsk = askGenerator.next();
256
+ }
257
+ // check for bids that cross fallbackAsk
258
+ while (!nextBid.done && fallbackAsk !== undefined) {
259
+ const bidNode = nextBid.value;
260
+ if ((0, __1.isVariant)(marketType, 'spot') && ((_b = bidNode.order) === null || _b === void 0 ? void 0 : _b.postOnly)) {
261
+ nextBid = bidGenerator.next();
262
+ continue;
263
+ }
264
+ const bidLimitPrice = (0, __1.getOptionalLimitPrice)(bidNode.order, oraclePriceData, slot);
265
+ // order crosses if there is no limit price or it crosses fallback price
266
+ const crosses = bidLimitPrice === undefined || bidLimitPrice.gte(fallbackAsk);
267
+ // fallback is available if auction is complete or it's a spot order
268
+ const fallbackAvailable = (0, __1.isVariant)(marketType, 'spot') || (0, __1.isAuctionComplete)(bidNode.order, slot);
269
+ if (crosses && fallbackAvailable) {
270
+ nodesToFill.push({
271
+ node: bidNode,
272
+ makerNode: undefined, // filled by fallback
273
+ });
274
+ }
275
+ nextBid = bidGenerator.next();
276
+ }
277
+ return nodesToFill;
278
+ }
279
+ findExpiredNodesToFill(marketIndex, ts, marketType) {
280
+ const nodesToFill = new Array();
281
+ const marketTypeStr = (0, __1.getVariant)(marketType);
282
+ const nodeLists = this.orderLists.get(marketTypeStr).get(marketIndex);
283
+ // All bids/asks that can expire
284
+ const bidGenerators = [
285
+ nodeLists.limit.bid.getGenerator(),
286
+ nodeLists.floatingLimit.bid.getGenerator(),
287
+ nodeLists.market.bid.getGenerator(),
288
+ ];
289
+ const askGenerators = [
290
+ nodeLists.limit.ask.getGenerator(),
291
+ nodeLists.floatingLimit.ask.getGenerator(),
292
+ nodeLists.market.ask.getGenerator(),
293
+ ];
294
+ for (const bidGenerator of bidGenerators) {
295
+ for (const bid of bidGenerator) {
296
+ if ((0, __1.isOrderExpired)(bid.order, ts)) {
297
+ nodesToFill.push({
298
+ node: bid,
299
+ });
300
+ }
301
+ }
302
+ }
303
+ for (const askGenerator of askGenerators) {
304
+ for (const ask of askGenerator) {
305
+ if ((0, __1.isOrderExpired)(ask.order, ts)) {
306
+ nodesToFill.push({
307
+ node: ask,
308
+ });
309
+ }
310
+ }
311
+ }
312
+ return nodesToFill;
313
+ }
314
+ findJitAuctionNodesToFill(marketIndex, slot, marketType) {
315
+ const nodesToFill = new Array();
316
+ // Then see if there are orders still in JIT auction
317
+ for (const marketBid of this.getMarketBids(marketIndex, marketType)) {
318
+ if (!(0, __1.isAuctionComplete)(marketBid.order, slot)) {
319
+ nodesToFill.push({
320
+ node: marketBid,
321
+ });
322
+ }
323
+ }
324
+ for (const marketAsk of this.getMarketAsks(marketIndex, marketType)) {
325
+ if (!(0, __1.isAuctionComplete)(marketAsk.order, slot)) {
326
+ nodesToFill.push({
327
+ node: marketAsk,
328
+ });
329
+ }
330
+ }
331
+ return nodesToFill;
332
+ }
333
+ getMarketBids(marketIndex, marketType) {
334
+ const marketTypeStr = (0, __1.getVariant)(marketType);
335
+ return this.orderLists
336
+ .get(marketTypeStr)
337
+ .get(marketIndex)
338
+ .market.bid.getGenerator();
339
+ }
340
+ getMarketAsks(marketIndex, marketType) {
341
+ const marketTypeStr = (0, __1.getVariant)(marketType);
342
+ return this.orderLists
343
+ .get(marketTypeStr)
344
+ .get(marketIndex)
345
+ .market.ask.getGenerator();
346
+ }
347
+ *getAsks(marketIndex, fallbackAsk, slot, marketType, oraclePriceData) {
348
+ if ((0, __1.isVariant)(marketType, 'spot') && !oraclePriceData) {
349
+ throw new Error('Must provide OraclePriceData to get spot asks');
350
+ }
351
+ const marketTypeStr = (0, __1.getVariant)(marketType);
352
+ const nodeLists = this.orderLists.get(marketTypeStr).get(marketIndex);
353
+ const generatorList = [
354
+ nodeLists.limit.ask.getGenerator(),
355
+ nodeLists.floatingLimit.ask.getGenerator(),
356
+ nodeLists.market.ask.getGenerator(),
357
+ ];
358
+ if (marketTypeStr === 'perp' && fallbackAsk) {
359
+ generatorList.push((0, NodeList_1.getVammNodeGenerator)(fallbackAsk));
360
+ }
361
+ if (generatorList.length === 0) {
362
+ throw new Error('No ask generators found');
363
+ }
364
+ const askGenerators = generatorList.map((generator) => {
365
+ return {
366
+ next: generator.next(),
367
+ generator,
368
+ };
369
+ });
370
+ let asksExhausted = false;
371
+ while (!asksExhausted) {
372
+ const bestGenerator = askGenerators.reduce((bestGenerator, currentGenerator) => {
373
+ if (currentGenerator.next.done) {
374
+ return bestGenerator;
375
+ }
376
+ if (bestGenerator.next.done) {
377
+ return currentGenerator;
378
+ }
379
+ const bestAskPrice = bestGenerator.next.value.getPrice(oraclePriceData, slot);
380
+ const currentAskPrice = currentGenerator.next.value.getPrice(oraclePriceData, slot);
381
+ return bestAskPrice.lt(currentAskPrice)
382
+ ? bestGenerator
383
+ : currentGenerator;
384
+ });
385
+ if (!bestGenerator.next.done) {
386
+ // skip this node if it's already completely filled
387
+ if (bestGenerator.next.value.isBaseFilled()) {
388
+ bestGenerator.next = bestGenerator.generator.next();
389
+ continue;
390
+ }
391
+ // skip order if user is being liquidated/bankrupt
392
+ if (bestGenerator.next.value.userAccount !== undefined) {
393
+ const user = this.userMap.get(bestGenerator.next.value.userAccount.toString());
394
+ if ((user === null || user === void 0 ? void 0 : user.getUserAccount().isBeingLiquidated) ||
395
+ (user === null || user === void 0 ? void 0 : user.getUserAccount().isBankrupt)) {
396
+ bestGenerator.next = bestGenerator.generator.next();
397
+ continue;
398
+ }
399
+ }
400
+ yield bestGenerator.next.value;
401
+ bestGenerator.next = bestGenerator.generator.next();
402
+ }
403
+ else {
404
+ asksExhausted = true;
405
+ }
406
+ }
407
+ }
408
+ *getBids(marketIndex, fallbackBid, slot, marketType, oraclePriceData) {
409
+ if ((0, __1.isVariant)(marketType, 'spot') && !oraclePriceData) {
410
+ throw new Error('Must provide OraclePriceData to get spot bids');
411
+ }
412
+ const marketTypeStr = (0, __1.getVariant)(marketType);
413
+ const nodeLists = this.orderLists.get(marketTypeStr).get(marketIndex);
414
+ const generatorList = [
415
+ nodeLists.limit.bid.getGenerator(),
416
+ nodeLists.floatingLimit.bid.getGenerator(),
417
+ nodeLists.market.bid.getGenerator(),
418
+ ];
419
+ if (marketTypeStr === 'perp' && fallbackBid) {
420
+ generatorList.push((0, NodeList_1.getVammNodeGenerator)(fallbackBid));
421
+ }
422
+ if (generatorList.length === 0) {
423
+ throw new Error('No bid generators found');
424
+ }
425
+ const bidGenerators = generatorList.map((generator) => {
426
+ return {
427
+ next: generator.next(),
428
+ generator,
429
+ };
430
+ });
431
+ let bidsExhausted = false; // there will always be the fallbackBid
432
+ while (!bidsExhausted) {
433
+ const bestGenerator = bidGenerators.reduce((bestGenerator, currentGenerator) => {
434
+ if (currentGenerator.next.done) {
435
+ return bestGenerator;
436
+ }
437
+ if (bestGenerator.next.done) {
438
+ return currentGenerator;
439
+ }
440
+ const bestBidPrice = bestGenerator.next.value.getPrice(oraclePriceData, slot);
441
+ const currentBidPrice = currentGenerator.next.value.getPrice(oraclePriceData, slot);
442
+ return bestBidPrice.gt(currentBidPrice)
443
+ ? bestGenerator
444
+ : currentGenerator;
445
+ });
446
+ if (!bestGenerator.next.done) {
447
+ // skip this node if it's already completely filled
448
+ if (bestGenerator.next.value.isBaseFilled()) {
449
+ bestGenerator.next = bestGenerator.generator.next();
450
+ continue;
451
+ }
452
+ // skip order if user is being liquidated/bankrupt
453
+ if (bestGenerator.next.value.userAccount !== undefined) {
454
+ const user = this.userMap.get(bestGenerator.next.value.userAccount.toString());
455
+ if ((user === null || user === void 0 ? void 0 : user.getUserAccount().isBeingLiquidated) ||
456
+ (user === null || user === void 0 ? void 0 : user.getUserAccount().isBankrupt)) {
457
+ bestGenerator.next = bestGenerator.generator.next();
458
+ continue;
459
+ }
460
+ }
461
+ yield bestGenerator.next.value;
462
+ bestGenerator.next = bestGenerator.generator.next();
463
+ }
464
+ else {
465
+ bidsExhausted = true;
466
+ }
467
+ }
468
+ }
469
+ findCrossingOrders(askNode, bidNode, oraclePriceData, slot) {
470
+ const bidPrice = bidNode.getPrice(oraclePriceData, slot);
471
+ const askPrice = askNode.getPrice(oraclePriceData, slot);
472
+ // orders don't cross - we're done walkin gup the book
473
+ if (bidPrice.lt(askPrice)) {
474
+ return {
475
+ crossingNodes: [],
476
+ exhaustedSide: 'nocross',
477
+ };
478
+ }
479
+ const bidOrder = bidNode.order;
480
+ const askOrder = askNode.order;
481
+ const bidUserAuthority = this.userMap.getUserAuthority(bidNode.userAccount.toString());
482
+ const askUserAuthority = this.userMap.getUserAuthority(askNode.userAccount.toString());
483
+ // Can't match orders from the same authority
484
+ const sameAuthority = bidUserAuthority.equals(askUserAuthority);
485
+ if (sameAuthority || (bidOrder.postOnly && askOrder.postOnly)) {
486
+ // don't have a principle way to pick which one to exhaust,
487
+ // exhaust each one 50% of the time so we can try each one against other orders
488
+ const exhaustedSide = Math.random() < 0.5 ? 'bid' : 'ask';
489
+ return {
490
+ crossingNodes: [],
491
+ exhaustedSide,
492
+ };
493
+ }
494
+ const { takerNode, makerNode, makerSide } = this.determineMakerAndTaker(askNode, bidNode);
495
+ // If order doesn't have limit price, cant be maker
496
+ if (!(0, __1.hasLimitPrice)(makerNode.order, slot)) {
497
+ return {
498
+ crossingNodes: [],
499
+ exhaustedSide: makerSide,
500
+ };
501
+ }
502
+ const bidBaseRemaining = bidOrder.baseAssetAmount.sub(bidOrder.baseAssetAmountFilled);
503
+ const askBaseRemaining = askOrder.baseAssetAmount.sub(askOrder.baseAssetAmountFilled);
504
+ let exhaustedSide;
505
+ if (bidBaseRemaining.eq(askBaseRemaining)) {
506
+ exhaustedSide = 'both';
507
+ }
508
+ else if (bidBaseRemaining.gt(askBaseRemaining)) {
509
+ exhaustedSide = 'ask';
510
+ }
511
+ else {
512
+ exhaustedSide = 'bid';
513
+ }
514
+ // update the orders on DLOB as if they were fill - so we don't try to match them on the next iteration
515
+ // NOTE: if something goes wrong during the actual fill (transaction fails, i.e. due to orders already being filled)
516
+ // then we risk having a mismatch between this local DLOB and the actual DLOB state on the blockchain. This isn't
517
+ // a problem in the current implementation because we construct a new DLOB from the blockchain state every time, rather
518
+ // than updating the existing DLOB based on events.
519
+ if (exhaustedSide === 'ask') {
520
+ // bid partially filled
521
+ const newBidOrder = { ...bidOrder };
522
+ newBidOrder.baseAssetAmountFilled =
523
+ bidOrder.baseAssetAmountFilled.add(askBaseRemaining);
524
+ this.getListForOrder(newBidOrder).update(newBidOrder, bidNode.userAccount);
525
+ // ask completely filled
526
+ const newAskOrder = { ...askOrder };
527
+ newAskOrder.baseAssetAmountFilled = askOrder.baseAssetAmount;
528
+ this.getListForOrder(newAskOrder).update(newAskOrder, askNode.userAccount);
529
+ }
530
+ else if (exhaustedSide === 'bid') {
531
+ // ask partially filled
532
+ const newAskOrder = { ...askOrder };
533
+ newAskOrder.baseAssetAmountFilled =
534
+ askOrder.baseAssetAmountFilled.add(bidBaseRemaining);
535
+ this.getListForOrder(newAskOrder).update(newAskOrder, askNode.userAccount);
536
+ // bid completely filled
537
+ const newBidOrder = { ...bidOrder };
538
+ newBidOrder.baseAssetAmountFilled = bidOrder.baseAssetAmount;
539
+ this.getListForOrder(newBidOrder).update(newBidOrder, bidNode.userAccount);
540
+ }
541
+ else {
542
+ // both completely filled
543
+ const newBidOrder = { ...bidOrder };
544
+ newBidOrder.baseAssetAmountFilled = bidOrder.baseAssetAmount;
545
+ this.getListForOrder(newBidOrder).update(newBidOrder, bidNode.userAccount);
546
+ const newAskOrder = { ...askOrder };
547
+ newAskOrder.baseAssetAmountFilled = askOrder.baseAssetAmount;
548
+ this.getListForOrder(newAskOrder).update(newAskOrder, askNode.userAccount);
549
+ }
550
+ return {
551
+ crossingNodes: [
552
+ {
553
+ node: takerNode,
554
+ makerNode: makerNode,
555
+ },
556
+ ],
557
+ exhaustedSide,
558
+ };
559
+ }
560
+ determineMakerAndTaker(askNode, bidNode) {
561
+ if (bidNode.order.postOnly) {
562
+ return {
563
+ takerNode: askNode,
564
+ makerNode: bidNode,
565
+ makerSide: 'bid',
566
+ };
567
+ }
568
+ else if (askNode.order.postOnly) {
569
+ return {
570
+ takerNode: bidNode,
571
+ makerNode: askNode,
572
+ makerSide: 'ask',
573
+ };
574
+ }
575
+ else if ((0, __1.isMarketOrder)(bidNode.order) && (0, __1.isLimitOrder)(askNode.order)) {
576
+ return {
577
+ takerNode: bidNode,
578
+ makerNode: askNode,
579
+ makerSide: 'ask',
580
+ };
581
+ }
582
+ else if ((0, __1.isMarketOrder)(askNode.order) && (0, __1.isLimitOrder)(bidNode.order)) {
583
+ return {
584
+ takerNode: askNode,
585
+ makerNode: bidNode,
586
+ makerSide: 'bid',
587
+ };
588
+ }
589
+ else if (askNode.order.slot.lt(bidNode.order.slot)) {
590
+ return {
591
+ takerNode: bidNode,
592
+ makerNode: askNode,
593
+ makerSide: 'ask',
594
+ };
595
+ }
596
+ else {
597
+ return {
598
+ takerNode: askNode,
599
+ makerNode: bidNode,
600
+ makerSide: 'bid',
601
+ };
602
+ }
603
+ }
604
+ getBestAsk(marketIndex, fallbackAsk, slot, marketType, oraclePriceData) {
605
+ return this.getAsks(marketIndex, fallbackAsk, slot, marketType, oraclePriceData)
606
+ .next()
607
+ .value.getPrice(oraclePriceData, slot);
608
+ }
609
+ getBestBid(marketIndex, fallbackBid, slot, marketType, oraclePriceData) {
610
+ return this.getBids(marketIndex, fallbackBid, slot, marketType, oraclePriceData)
611
+ .next()
612
+ .value.getPrice(oraclePriceData, slot);
613
+ }
614
+ findNodesToTrigger(marketIndex, slot, oraclePrice, marketType) {
615
+ if ((0, exchangeStatus_1.exchangePaused)(this.stateAccount)) {
616
+ return [];
617
+ }
618
+ const nodesToTrigger = [];
619
+ const marketTypeStr = (0, __1.getVariant)(marketType);
620
+ for (const node of this.orderLists
621
+ .get(marketTypeStr)
622
+ .get(marketIndex)
623
+ .trigger.above.getGenerator()) {
624
+ if (oraclePrice.gt(node.order.triggerPrice)) {
625
+ if ((0, __1.isAuctionComplete)(node.order, slot)) {
626
+ nodesToTrigger.push({
627
+ node: node,
628
+ });
629
+ }
630
+ }
631
+ else {
632
+ break;
633
+ }
634
+ }
635
+ for (const node of this.orderLists
636
+ .get(marketTypeStr)
637
+ .get(marketIndex)
638
+ .trigger.below.getGenerator()) {
639
+ if (oraclePrice.lt(node.order.triggerPrice)) {
640
+ if ((0, __1.isAuctionComplete)(node.order, slot)) {
641
+ nodesToTrigger.push({
642
+ node: node,
643
+ });
644
+ }
645
+ }
646
+ else {
647
+ break;
648
+ }
649
+ }
650
+ return nodesToTrigger;
651
+ }
652
+ printTopOfOrderLists(sdkConfig, driftClient, slotSubscriber, marketIndex, marketType) {
653
+ if ((0, __1.isVariant)(marketType, 'perp')) {
654
+ const market = driftClient.getPerpMarketAccount(marketIndex);
655
+ const slot = slotSubscriber.getSlot();
656
+ const oraclePriceData = driftClient.getOracleDataForPerpMarket(marketIndex);
657
+ const fallbackAsk = (0, __1.calculateAskPrice)(market, oraclePriceData);
658
+ const fallbackBid = (0, __1.calculateBidPrice)(market, oraclePriceData);
659
+ const bestAsk = this.getBestAsk(marketIndex, fallbackAsk, slot, marketType, oraclePriceData);
660
+ const bestBid = this.getBestBid(marketIndex, fallbackBid, slot, marketType, oraclePriceData);
661
+ const mid = bestAsk.add(bestBid).div(new __1.BN(2));
662
+ const bidSpread = ((0, __1.convertToNumber)(bestBid, __1.PRICE_PRECISION) /
663
+ (0, __1.convertToNumber)(oraclePriceData.price, __1.PRICE_PRECISION) -
664
+ 1) *
665
+ 100.0;
666
+ const askSpread = ((0, __1.convertToNumber)(bestAsk, __1.PRICE_PRECISION) /
667
+ (0, __1.convertToNumber)(oraclePriceData.price, __1.PRICE_PRECISION) -
668
+ 1) *
669
+ 100.0;
670
+ console.log(`Market ${sdkConfig.MARKETS[marketIndex].symbol} Orders`);
671
+ console.log(` Ask`, (0, __1.convertToNumber)(bestAsk, __1.PRICE_PRECISION).toFixed(3), `(${askSpread.toFixed(4)}%)`);
672
+ console.log(` Mid`, (0, __1.convertToNumber)(mid, __1.PRICE_PRECISION).toFixed(3));
673
+ console.log(` Bid`, (0, __1.convertToNumber)(bestBid, __1.PRICE_PRECISION).toFixed(3), `(${bidSpread.toFixed(4)}%)`);
674
+ }
675
+ else if ((0, __1.isVariant)(marketType, 'spot')) {
676
+ const slot = slotSubscriber.getSlot();
677
+ const oraclePriceData = driftClient.getOracleDataForPerpMarket(marketIndex);
678
+ const bestAsk = this.getBestAsk(marketIndex, undefined, slot, marketType, oraclePriceData);
679
+ const bestBid = this.getBestBid(marketIndex, undefined, slot, marketType, oraclePriceData);
680
+ const mid = bestAsk.add(bestBid).div(new __1.BN(2));
681
+ const bidSpread = ((0, __1.convertToNumber)(bestBid, __1.PRICE_PRECISION) /
682
+ (0, __1.convertToNumber)(oraclePriceData.price, __1.PRICE_PRECISION) -
683
+ 1) *
684
+ 100.0;
685
+ const askSpread = ((0, __1.convertToNumber)(bestAsk, __1.PRICE_PRECISION) /
686
+ (0, __1.convertToNumber)(oraclePriceData.price, __1.PRICE_PRECISION) -
687
+ 1) *
688
+ 100.0;
689
+ console.log(`Market ${sdkConfig.MARKETS[marketIndex].symbol} Orders`);
690
+ console.log(` Ask`, (0, __1.convertToNumber)(bestAsk, __1.PRICE_PRECISION).toFixed(3), `(${askSpread.toFixed(4)}%)`);
691
+ console.log(` Mid`, (0, __1.convertToNumber)(mid, __1.PRICE_PRECISION).toFixed(3));
692
+ console.log(` Bid`, (0, __1.convertToNumber)(bestBid, __1.PRICE_PRECISION).toFixed(3), `(${bidSpread.toFixed(4)}%)`);
693
+ }
694
+ }
695
+ }
696
+ exports.DLOB = DLOB;