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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +13 -13
  2. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +27 -27
  3. package/lib/accounts/types.d.ts +8 -9
  4. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +14 -14
  5. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +35 -34
  6. package/lib/addresses/pda.d.ts +8 -6
  7. package/lib/addresses/pda.js +35 -27
  8. package/lib/admin.d.ts +9 -6
  9. package/lib/admin.js +90 -54
  10. package/lib/clearingHouse.d.ts +71 -42
  11. package/lib/clearingHouse.js +765 -282
  12. package/lib/clearingHouseConfig.d.ts +2 -2
  13. package/lib/clearingHouseUser.d.ts +19 -17
  14. package/lib/clearingHouseUser.js +145 -123
  15. package/lib/config.d.ts +7 -7
  16. package/lib/config.js +21 -21
  17. package/lib/constants/numericConstants.d.ts +12 -12
  18. package/lib/constants/numericConstants.js +13 -13
  19. package/lib/constants/{markets.d.ts → perpMarkets.d.ts} +5 -5
  20. package/{src/constants/markets.js → lib/constants/perpMarkets.js} +4 -4
  21. package/lib/constants/{banks.d.ts → spotMarkets.d.ts} +6 -6
  22. package/lib/constants/{banks.js → spotMarkets.js} +16 -16
  23. package/lib/events/eventSubscriber.d.ts +4 -2
  24. package/lib/events/eventSubscriber.js +16 -9
  25. package/lib/events/fetchLogs.d.ts +10 -1
  26. package/lib/events/fetchLogs.js +27 -7
  27. package/lib/events/pollingLogProvider.d.ts +2 -1
  28. package/lib/events/pollingLogProvider.js +6 -2
  29. package/lib/events/types.d.ts +4 -2
  30. package/lib/events/types.js +2 -0
  31. package/lib/examples/makeTradeExample.js +18 -6
  32. package/lib/idl/clearing_house.json +1128 -347
  33. package/lib/index.d.ts +6 -3
  34. package/lib/index.js +6 -3
  35. package/lib/math/amm.d.ts +5 -3
  36. package/lib/math/amm.js +42 -4
  37. package/lib/math/funding.d.ts +6 -6
  38. package/lib/math/funding.js +2 -1
  39. package/lib/math/margin.d.ts +4 -4
  40. package/lib/math/margin.js +18 -11
  41. package/lib/math/market.d.ts +10 -9
  42. package/lib/math/market.js +29 -6
  43. package/lib/math/oracles.d.ts +2 -1
  44. package/lib/math/oracles.js +11 -1
  45. package/lib/math/orders.d.ts +5 -5
  46. package/lib/math/position.d.ts +13 -13
  47. package/lib/math/position.js +19 -19
  48. package/lib/math/spotBalance.d.ts +19 -0
  49. package/lib/math/spotBalance.js +176 -0
  50. package/lib/math/spotMarket.d.ts +4 -0
  51. package/lib/math/spotMarket.js +8 -0
  52. package/lib/math/spotPosition.d.ts +2 -0
  53. package/lib/math/spotPosition.js +8 -0
  54. package/lib/math/state.js +2 -2
  55. package/lib/math/trade.d.ts +4 -4
  56. package/lib/orderParams.d.ts +4 -4
  57. package/lib/orderParams.js +12 -4
  58. package/lib/serum/serumSubscriber.d.ts +23 -0
  59. package/lib/serum/serumSubscriber.js +41 -0
  60. package/lib/serum/types.d.ts +11 -0
  61. package/lib/serum/types.js +2 -0
  62. package/lib/tx/retryTxSender.d.ts +1 -1
  63. package/lib/tx/retryTxSender.js +4 -2
  64. package/lib/tx/types.d.ts +1 -1
  65. package/lib/types.d.ts +148 -39
  66. package/lib/types.js +37 -9
  67. package/my-script/.env +7 -0
  68. package/my-script/getUserStats.ts +106 -0
  69. package/my-script/multiConnections.ts +119 -0
  70. package/my-script/test-regex.ts +11 -0
  71. package/my-script/utils.ts +52 -0
  72. package/package.json +1 -1
  73. package/src/accounts/bulkAccountLoader.js +249 -0
  74. package/src/accounts/bulkUserStatsSubscription.js +75 -0
  75. package/src/accounts/bulkUserSubscription.js +75 -0
  76. package/src/accounts/fetch.js +92 -0
  77. package/src/accounts/pollingClearingHouseAccountSubscriber.js +465 -0
  78. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +38 -38
  79. package/src/accounts/pollingOracleSubscriber.js +156 -0
  80. package/src/accounts/pollingTokenAccountSubscriber.js +141 -0
  81. package/src/accounts/pollingUserAccountSubscriber.js +208 -0
  82. package/src/accounts/pollingUserStatsAccountSubscriber.js +208 -0
  83. package/src/accounts/types.js +28 -0
  84. package/src/accounts/types.ts +11 -9
  85. package/src/accounts/utils.js +7 -0
  86. package/src/accounts/webSocketAccountSubscriber.js +138 -0
  87. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +433 -0
  88. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +59 -52
  89. package/src/accounts/webSocketUserAccountSubscriber.js +113 -0
  90. package/src/accounts/webSocketUserStatsAccountSubsriber.js +113 -0
  91. package/src/addresses/pda.js +186 -0
  92. package/src/addresses/pda.ts +56 -42
  93. package/src/admin.js +1284 -0
  94. package/src/admin.ts +149 -75
  95. package/src/assert/assert.js +1 -1
  96. package/src/clearingHouse.js +3433 -0
  97. package/src/clearingHouse.ts +1097 -380
  98. package/src/clearingHouseConfig.js +2 -0
  99. package/src/clearingHouseConfig.ts +2 -2
  100. package/src/clearingHouseUser.js +874 -0
  101. package/src/clearingHouseUser.ts +237 -172
  102. package/src/clearingHouseUserConfig.js +2 -0
  103. package/src/clearingHouseUserStats.js +115 -0
  104. package/src/clearingHouseUserStatsConfig.js +2 -0
  105. package/src/config.js +80 -0
  106. package/src/config.ts +30 -30
  107. package/src/constants/numericConstants.js +18 -11
  108. package/src/constants/numericConstants.ts +17 -15
  109. package/{lib/constants/markets.js → src/constants/perpMarkets.js} +11 -11
  110. package/src/constants/{markets.ts → perpMarkets.ts} +5 -5
  111. package/src/constants/spotMarkets.js +51 -0
  112. package/src/constants/{banks.ts → spotMarkets.ts} +19 -19
  113. package/src/events/eventList.js +66 -23
  114. package/src/events/eventSubscriber.js +202 -0
  115. package/src/events/eventSubscriber.ts +20 -12
  116. package/src/events/fetchLogs.js +117 -0
  117. package/src/events/fetchLogs.ts +35 -8
  118. package/src/events/pollingLogProvider.js +113 -0
  119. package/src/events/pollingLogProvider.ts +10 -2
  120. package/src/events/sort.js +41 -0
  121. package/src/events/txEventCache.js +22 -19
  122. package/src/events/types.js +25 -0
  123. package/src/events/types.ts +7 -1
  124. package/src/events/webSocketLogProvider.js +76 -0
  125. package/src/examples/makeTradeExample.ts +27 -6
  126. package/src/factory/bigNum.js +183 -180
  127. package/src/factory/oracleClient.js +9 -9
  128. package/src/idl/clearing_house.json +1128 -347
  129. package/src/index.js +75 -0
  130. package/src/index.ts +6 -3
  131. package/src/math/amm.js +422 -0
  132. package/src/math/amm.ts +73 -5
  133. package/src/math/auction.js +10 -10
  134. package/src/math/conversion.js +4 -3
  135. package/src/math/funding.js +223 -175
  136. package/src/math/funding.ts +7 -7
  137. package/src/math/insurance.js +27 -0
  138. package/src/math/margin.js +77 -0
  139. package/src/math/margin.ts +34 -23
  140. package/src/math/market.js +105 -0
  141. package/src/math/market.ts +71 -19
  142. package/src/math/oracles.js +40 -10
  143. package/src/math/oracles.ts +18 -1
  144. package/src/math/orders.js +153 -0
  145. package/src/math/orders.ts +5 -5
  146. package/src/math/position.js +172 -0
  147. package/src/math/position.ts +31 -31
  148. package/src/math/repeg.js +40 -40
  149. package/src/math/spotBalance.js +176 -0
  150. package/src/math/spotBalance.ts +290 -0
  151. package/src/math/spotMarket.js +8 -0
  152. package/src/math/spotMarket.ts +9 -0
  153. package/src/math/spotPosition.js +8 -0
  154. package/src/math/spotPosition.ts +6 -0
  155. package/src/math/state.ts +2 -2
  156. package/src/math/trade.js +81 -74
  157. package/src/math/trade.ts +4 -4
  158. package/src/math/utils.js +8 -7
  159. package/src/oracles/oracleClientCache.js +10 -9
  160. package/src/oracles/pythClient.js +52 -17
  161. package/src/oracles/quoteAssetOracleClient.js +44 -13
  162. package/src/oracles/switchboardClient.js +69 -37
  163. package/src/oracles/types.js +1 -1
  164. package/src/orderParams.js +14 -6
  165. package/src/orderParams.ts +16 -8
  166. package/src/serum/serumSubscriber.js +102 -0
  167. package/src/serum/serumSubscriber.ts +80 -0
  168. package/src/serum/types.js +2 -0
  169. package/src/serum/types.ts +13 -0
  170. package/src/slot/SlotSubscriber.js +67 -20
  171. package/src/token/index.js +4 -4
  172. package/src/tokenFaucet.js +288 -154
  173. package/src/tx/retryTxSender.js +280 -0
  174. package/src/tx/retryTxSender.ts +5 -2
  175. package/src/tx/types.js +1 -1
  176. package/src/tx/types.ts +2 -1
  177. package/src/tx/utils.js +7 -6
  178. package/src/types.js +216 -0
  179. package/src/types.ts +131 -39
  180. package/src/userName.js +5 -5
  181. package/src/util/computeUnits.js +46 -11
  182. package/src/util/promiseTimeout.js +5 -5
  183. package/src/util/tps.js +46 -12
  184. package/src/wallet.js +55 -18
  185. package/lib/math/bankBalance.d.ts +0 -15
  186. package/lib/math/bankBalance.js +0 -150
  187. package/src/addresses/marketAddresses.js +0 -26
  188. package/src/constants/banks.js +0 -42
  189. package/src/examples/makeTradeExample.js +0 -80
  190. package/src/math/bankBalance.ts +0 -258
  191. package/src/math/state.js +0 -15
  192. package/src/math/utils.js.map +0 -1
  193. package/src/util/getTokenAddress.js +0 -9
@@ -37,15 +37,16 @@ const pda_1 = require("./addresses/pda");
37
37
  const utils_1 = require("./tx/utils");
38
38
  const numericConstants_1 = require("./constants/numericConstants");
39
39
  const position_1 = require("./math/position");
40
- const bankBalance_1 = require("./math/bankBalance");
40
+ const spotBalance_1 = require("./math/spotBalance");
41
41
  const userName_1 = require("./userName");
42
42
  const pollingClearingHouseAccountSubscriber_1 = require("./accounts/pollingClearingHouseAccountSubscriber");
43
43
  const webSocketClearingHouseAccountSubscriber_1 = require("./accounts/webSocketClearingHouseAccountSubscriber");
44
44
  const retryTxSender_1 = require("./tx/retryTxSender");
45
45
  const clearingHouseUser_1 = require("./clearingHouseUser");
46
46
  const config_1 = require("./config");
47
- const banks_1 = require("./constants/banks");
47
+ const spotMarkets_1 = require("./constants/spotMarkets");
48
48
  const clearingHouseUserStats_1 = require("./clearingHouseUserStats");
49
+ const spotPosition_1 = require("./math/spotPosition");
49
50
  /**
50
51
  * # ClearingHouse
51
52
  * This class is the main way to interact with Drift Protocol. It allows you to subscribe to the various accounts where the Market's state is stored, as well as: opening positions, liquidating, settling funding, depositing & withdrawing, and more.
@@ -80,20 +81,24 @@ class ClearingHouse {
80
81
  accountSubscription: this.userAccountSubscriptionConfig,
81
82
  });
82
83
  }
83
- let marketIndexes = config.marketIndexes;
84
- let bankIndexes = config.bankIndexes;
84
+ let perpMarketIndexes = config.perpMarketIndexes;
85
+ let spotMarketIndexes = config.spotMarketIndexes;
85
86
  let oracleInfos = config.oracleInfos;
86
87
  if (config.env) {
87
- const { marketIndexes: envMarketIndexes, bankIndexes: envBankIndexes, oracleInfos: envOralceInfos, } = (0, config_1.getMarketsBanksAndOraclesForSubscription)(config.env);
88
- marketIndexes = marketIndexes ? marketIndexes : envMarketIndexes;
89
- bankIndexes = bankIndexes ? bankIndexes : envBankIndexes;
88
+ const { perpMarketIndexes: envPerpMarketIndexes, spotMarketIndexes: envSpotMarketIndexes, oracleInfos: envOralceInfos, } = (0, config_1.getMarketsAndOraclesForSubscription)(config.env);
89
+ perpMarketIndexes = perpMarketIndexes
90
+ ? perpMarketIndexes
91
+ : envPerpMarketIndexes;
92
+ spotMarketIndexes = spotMarketIndexes
93
+ ? spotMarketIndexes
94
+ : envSpotMarketIndexes;
90
95
  oracleInfos = oracleInfos ? oracleInfos : envOralceInfos;
91
96
  }
92
97
  if (((_d = config.accountSubscription) === null || _d === void 0 ? void 0 : _d.type) === 'polling') {
93
- this.accountSubscriber = new pollingClearingHouseAccountSubscriber_1.PollingClearingHouseAccountSubscriber(this.program, config.accountSubscription.accountLoader, marketIndexes !== null && marketIndexes !== void 0 ? marketIndexes : [], bankIndexes !== null && bankIndexes !== void 0 ? bankIndexes : [], oracleInfos !== null && oracleInfos !== void 0 ? oracleInfos : []);
98
+ this.accountSubscriber = new pollingClearingHouseAccountSubscriber_1.PollingClearingHouseAccountSubscriber(this.program, config.accountSubscription.accountLoader, perpMarketIndexes !== null && perpMarketIndexes !== void 0 ? perpMarketIndexes : [], spotMarketIndexes !== null && spotMarketIndexes !== void 0 ? spotMarketIndexes : [], oracleInfos !== null && oracleInfos !== void 0 ? oracleInfos : []);
94
99
  }
95
100
  else {
96
- this.accountSubscriber = new webSocketClearingHouseAccountSubscriber_1.WebSocketClearingHouseAccountSubscriber(this.program, (_e = config.marketIndexes) !== null && _e !== void 0 ? _e : [], (_f = config.bankIndexes) !== null && _f !== void 0 ? _f : [], (_g = config.oracleInfos) !== null && _g !== void 0 ? _g : []);
101
+ this.accountSubscriber = new webSocketClearingHouseAccountSubscriber_1.WebSocketClearingHouseAccountSubscriber(this.program, (_e = config.perpMarketIndexes) !== null && _e !== void 0 ? _e : [], (_f = config.spotMarketIndexes) !== null && _f !== void 0 ? _f : [], (_g = config.oracleInfos) !== null && _g !== void 0 ? _g : []);
97
102
  }
98
103
  this.eventEmitter = this.accountSubscriber.eventEmitter;
99
104
  this.txSender = new retryTxSender_1.RetryTxSender(this.provider, (_h = config.txSenderConfig) === null || _h === void 0 ? void 0 : _h.timeout, (_j = config.txSenderConfig) === null || _j === void 0 ? void 0 : _j.retrySleep, (_k = config.txSenderConfig) === null || _k === void 0 ? void 0 : _k.additionalConnections);
@@ -159,30 +164,40 @@ class ClearingHouse {
159
164
  this.statePublicKey = await (0, pda_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
160
165
  return this.statePublicKey;
161
166
  }
167
+ getSignerPublicKey() {
168
+ if (this.signerPublicKey) {
169
+ return this.signerPublicKey;
170
+ }
171
+ this.signerPublicKey = (0, pda_1.getClearingHouseSignerPublicKey)(this.program.programId);
172
+ return this.signerPublicKey;
173
+ }
162
174
  getStateAccount() {
163
175
  return this.accountSubscriber.getStateAccountAndSlot().data;
164
176
  }
165
- getMarketAccount(marketIndex) {
177
+ getPerpMarketAccount(marketIndex) {
166
178
  var _a;
167
179
  marketIndex = marketIndex instanceof anchor_1.BN ? marketIndex : new anchor_1.BN(marketIndex);
168
180
  return (_a = this.accountSubscriber.getMarketAccountAndSlot(marketIndex)) === null || _a === void 0 ? void 0 : _a.data;
169
181
  }
170
- getMarketAccounts() {
182
+ getPerpMarketAccounts() {
171
183
  return this.accountSubscriber
172
184
  .getMarketAccountsAndSlots()
173
185
  .map((value) => value.data);
174
186
  }
175
- getBankAccount(bankIndex) {
176
- bankIndex = bankIndex instanceof anchor_1.BN ? bankIndex : new anchor_1.BN(bankIndex);
177
- return this.accountSubscriber.getBankAccountAndSlot(bankIndex).data;
187
+ getSpotMarketAccount(marketIndex) {
188
+ marketIndex = marketIndex instanceof anchor_1.BN ? marketIndex : new anchor_1.BN(marketIndex);
189
+ return this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex).data;
178
190
  }
179
- getQuoteAssetBankAccount() {
180
- return this.accountSubscriber.getBankAccountAndSlot(numericConstants_1.QUOTE_ASSET_BANK_INDEX)
181
- .data;
191
+ getQuoteSpotMarketAccount() {
192
+ return this.accountSubscriber.getSpotMarketAccountAndSlot(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).data;
182
193
  }
183
194
  getOraclePriceDataAndSlot(oraclePublicKey) {
184
195
  return this.accountSubscriber.getOraclePriceDataAndSlot(oraclePublicKey);
185
196
  }
197
+ async getSerumV3FulfillmentConfig(serumMarket) {
198
+ const address = await (0, pda_1.getSerumFulfillmentConfigPublicKey)(this.program.programId, serumMarket);
199
+ return (await this.program.account.serumV3FulfillmentConfig.fetch(address));
200
+ }
186
201
  /**
187
202
  * Update the wallet to use for clearing house transactions and linked user account
188
203
  * @param newWallet
@@ -272,6 +287,15 @@ class ClearingHouse {
272
287
  },
273
288
  });
274
289
  }
290
+ async updateUserName(name, userId = 0) {
291
+ const nameBuffer = (0, userName_1.encodeName)(name);
292
+ return await this.program.rpc.updateUserName(userId, nameBuffer, {
293
+ accounts: {
294
+ user: await this.getUserAccountPublicKey(),
295
+ authority: this.wallet.publicKey,
296
+ },
297
+ });
298
+ }
275
299
  getUser(userId) {
276
300
  userId = userId !== null && userId !== void 0 ? userId : this.activeUserId;
277
301
  if (!this.users.has(userId)) {
@@ -301,14 +325,14 @@ class ClearingHouse {
301
325
  getUserAccountAndSlot(userId) {
302
326
  return this.getUser(userId).getUserAccountAndSlot();
303
327
  }
304
- getUserBankBalance(bankIndex) {
305
- const bankIndexBN = bankIndex instanceof anchor_1.BN ? bankIndex : new anchor_1.BN(bankIndex);
306
- return this.getUserAccount().bankBalances.find((bankBalance) => bankBalance.bankIndex.eq(bankIndexBN));
328
+ getSpotPosition(marketIndex) {
329
+ const marketIndexBN = marketIndex instanceof anchor_1.BN ? marketIndex : new anchor_1.BN(marketIndex);
330
+ return this.getUserAccount().spotPositions.find((spotPosition) => spotPosition.marketIndex.eq(marketIndexBN));
307
331
  }
308
332
  getQuoteAssetTokenAmount() {
309
- const bank = this.getBankAccount(numericConstants_1.QUOTE_ASSET_BANK_INDEX);
310
- const userBankBalance = this.getUserBankBalance(numericConstants_1.QUOTE_ASSET_BANK_INDEX);
311
- return (0, bankBalance_1.getTokenAmount)(userBankBalance.balance, bank, userBankBalance.balanceType);
333
+ const spotMarket = this.getSpotMarketAccount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
334
+ const spotPosition = this.getSpotPosition(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
335
+ return (0, spotBalance_1.getTokenAmount)(spotPosition.balance, spotMarket, spotPosition.balanceType);
312
336
  }
313
337
  getRemainingAccounts(params) {
314
338
  const userAccountAndSlot = this.getUserAccountAndSlot();
@@ -317,14 +341,14 @@ class ClearingHouse {
317
341
  }
318
342
  const { data: userAccount, slot: lastUserPositionsSlot } = userAccountAndSlot;
319
343
  const oracleAccountMap = new Map();
320
- const bankAccountMap = new Map();
321
- const marketAccountMap = new Map();
344
+ const spotMarketAccountMap = new Map();
345
+ const perpMarketAccountMap = new Map();
322
346
  for (const [marketIndexNum, slot] of this.marketLastSlotCache.entries()) {
323
347
  // if cache has more recent slot than user positions account slot, add market to remaining accounts
324
348
  // otherwise remove from slot
325
349
  if (slot > lastUserPositionsSlot) {
326
- const marketAccount = this.getMarketAccount(marketIndexNum);
327
- marketAccountMap.set(marketIndexNum, {
350
+ const marketAccount = this.getPerpMarketAccount(marketIndexNum);
351
+ perpMarketAccountMap.set(marketIndexNum, {
328
352
  pubkey: marketAccount.pubkey,
329
353
  isSigner: false,
330
354
  isWritable: false,
@@ -339,11 +363,11 @@ class ClearingHouse {
339
363
  this.marketLastSlotCache.delete(marketIndexNum);
340
364
  }
341
365
  }
342
- for (const position of userAccount.positions) {
366
+ for (const position of userAccount.perpPositions) {
343
367
  if (!(0, position_1.positionIsAvailable)(position)) {
344
368
  const marketIndexNum = position.marketIndex.toNumber();
345
- const marketAccount = this.getMarketAccount(marketIndexNum);
346
- marketAccountMap.set(marketIndexNum, {
369
+ const marketAccount = this.getPerpMarketAccount(marketIndexNum);
370
+ perpMarketAccountMap.set(marketIndexNum, {
347
371
  pubkey: marketAccount.pubkey,
348
372
  isSigner: false,
349
373
  isWritable: false,
@@ -355,9 +379,9 @@ class ClearingHouse {
355
379
  });
356
380
  }
357
381
  }
358
- if (params.readableMarketIndex) {
359
- const marketAccount = this.getMarketAccount(params.readableMarketIndex.toNumber());
360
- marketAccountMap.set(params.readableMarketIndex.toNumber(), {
382
+ if (params.readablePerpMarketIndex) {
383
+ const marketAccount = this.getPerpMarketAccount(params.readablePerpMarketIndex.toNumber());
384
+ perpMarketAccountMap.set(params.readablePerpMarketIndex.toNumber(), {
361
385
  pubkey: marketAccount.pubkey,
362
386
  isSigner: false,
363
387
  isWritable: true,
@@ -368,9 +392,9 @@ class ClearingHouse {
368
392
  isWritable: false,
369
393
  });
370
394
  }
371
- if (params.writableMarketIndex) {
372
- const marketAccount = this.getMarketAccount(params.writableMarketIndex.toNumber());
373
- marketAccountMap.set(params.writableMarketIndex.toNumber(), {
395
+ if (params.writablePerpMarketIndex) {
396
+ const marketAccount = this.getPerpMarketAccount(params.writablePerpMarketIndex.toNumber());
397
+ perpMarketAccountMap.set(params.writablePerpMarketIndex.toNumber(), {
374
398
  pubkey: marketAccount.pubkey,
375
399
  isSigner: false,
376
400
  isWritable: true,
@@ -381,33 +405,48 @@ class ClearingHouse {
381
405
  isWritable: false,
382
406
  });
383
407
  }
384
- for (const userBankBalance of userAccount.bankBalances) {
385
- if (!userBankBalance.balance.eq(numericConstants_1.ZERO)) {
386
- const bankAccount = this.getBankAccount(userBankBalance.bankIndex);
387
- bankAccountMap.set(userBankBalance.bankIndex.toNumber(), {
388
- pubkey: bankAccount.pubkey,
408
+ for (const spotPosition of userAccount.spotPositions) {
409
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
410
+ const spotMarketAccount = this.getSpotMarketAccount(spotPosition.marketIndex);
411
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
412
+ pubkey: spotMarketAccount.pubkey,
389
413
  isSigner: false,
390
414
  isWritable: false,
391
415
  });
392
- if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
393
- oracleAccountMap.set(bankAccount.oracle.toString(), {
394
- pubkey: bankAccount.oracle,
416
+ if (!spotMarketAccount.marketIndex.eq(numericConstants_1.ZERO)) {
417
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
418
+ pubkey: spotMarketAccount.oracle,
395
419
  isSigner: false,
396
420
  isWritable: false,
397
421
  });
398
422
  }
399
423
  }
400
424
  }
401
- if (params.writableBankIndex) {
402
- const bankAccount = this.getBankAccount(params.writableBankIndex);
403
- bankAccountMap.set(params.writableBankIndex.toNumber(), {
404
- pubkey: bankAccount.pubkey,
425
+ if (params.readableSpotMarketIndex) {
426
+ const spotMarketAccount = this.getSpotMarketAccount(params.readableSpotMarketIndex);
427
+ spotMarketAccountMap.set(params.readableSpotMarketIndex.toNumber(), {
428
+ pubkey: spotMarketAccount.pubkey,
429
+ isSigner: false,
430
+ isWritable: false,
431
+ });
432
+ if (!spotMarketAccount.marketIndex.eq(numericConstants_1.ZERO)) {
433
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
434
+ pubkey: spotMarketAccount.oracle,
435
+ isSigner: false,
436
+ isWritable: false,
437
+ });
438
+ }
439
+ }
440
+ if (params.writableSpotMarketIndex) {
441
+ const spotMarketAccount = this.getSpotMarketAccount(params.writableSpotMarketIndex);
442
+ spotMarketAccountMap.set(params.writableSpotMarketIndex.toNumber(), {
443
+ pubkey: spotMarketAccount.pubkey,
405
444
  isSigner: false,
406
445
  isWritable: true,
407
446
  });
408
- if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
409
- oracleAccountMap.set(bankAccount.oracle.toString(), {
410
- pubkey: bankAccount.oracle,
447
+ if (!spotMarketAccount.marketIndex.eq(numericConstants_1.ZERO)) {
448
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
449
+ pubkey: spotMarketAccount.oracle,
411
450
  isSigner: false,
412
451
  isWritable: false,
413
452
  });
@@ -415,8 +454,8 @@ class ClearingHouse {
415
454
  }
416
455
  return [
417
456
  ...oracleAccountMap.values(),
418
- ...bankAccountMap.values(),
419
- ...marketAccountMap.values(),
457
+ ...spotMarketAccountMap.values(),
458
+ ...perpMarketAccountMap.values(),
420
459
  ];
421
460
  }
422
461
  getOrder(orderId) {
@@ -428,13 +467,13 @@ class ClearingHouse {
428
467
  var _a;
429
468
  return (_a = this.getUserAccount()) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.userOrderId === userOrderId);
430
469
  }
431
- async deposit(amount, bankIndex, collateralAccountPublicKey, userId, reduceOnly = false) {
470
+ async deposit(amount, marketIndex, collateralAccountPublicKey, userId, reduceOnly = false) {
432
471
  const tx = new web3_js_1.Transaction();
433
472
  const additionalSigners = [];
434
- const bank = this.getBankAccount(bankIndex);
435
- const isSolBank = bank.mint.equals(banks_1.WRAPPED_SOL_MINT);
473
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
474
+ const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
436
475
  const authority = this.wallet.publicKey;
437
- const createWSOLTokenAccount = isSolBank && collateralAccountPublicKey.equals(authority);
476
+ const createWSOLTokenAccount = isSolMarket && collateralAccountPublicKey.equals(authority);
438
477
  if (createWSOLTokenAccount) {
439
478
  const { ixs, signers, pubkey } = await this.getWrappedSolAccountCreationIxs(amount);
440
479
  collateralAccountPublicKey = pubkey;
@@ -443,7 +482,7 @@ class ClearingHouse {
443
482
  });
444
483
  signers.forEach((signer) => additionalSigners.push(signer));
445
484
  }
446
- const depositCollateralIx = await this.getDepositInstruction(amount, bankIndex, collateralAccountPublicKey, userId, reduceOnly, true);
485
+ const depositCollateralIx = await this.getDepositInstruction(amount, marketIndex, collateralAccountPublicKey, userId, reduceOnly, true);
447
486
  tx.add(depositCollateralIx);
448
487
  // Close the wrapped sol account at the end of the transaction
449
488
  if (createWSOLTokenAccount) {
@@ -452,37 +491,37 @@ class ClearingHouse {
452
491
  const { txSig } = await this.txSender.send(tx, additionalSigners, this.opts);
453
492
  return txSig;
454
493
  }
455
- async getDepositInstruction(amount, bankIndex, userTokenAccount, userId, reduceOnly = false, userInitialized = true) {
494
+ async getDepositInstruction(amount, marketIndex, userTokenAccount, userId, reduceOnly = false, userInitialized = true) {
456
495
  const userAccountPublicKey = userId
457
496
  ? await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, userId)
458
497
  : await this.getUserAccountPublicKey();
459
498
  let remainingAccounts = [];
460
499
  if (userInitialized) {
461
500
  remainingAccounts = this.getRemainingAccounts({
462
- writableBankIndex: bankIndex,
501
+ writableSpotMarketIndex: marketIndex,
463
502
  });
464
503
  }
465
504
  else {
466
- const bankAccount = this.getBankAccount(bankIndex);
467
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
505
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
506
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
468
507
  remainingAccounts.push({
469
- pubkey: bankAccount.oracle,
508
+ pubkey: spotMarketAccount.oracle,
470
509
  isSigner: false,
471
510
  isWritable: false,
472
511
  });
473
512
  }
474
513
  remainingAccounts.push({
475
- pubkey: bankAccount.pubkey,
514
+ pubkey: spotMarketAccount.pubkey,
476
515
  isSigner: false,
477
516
  isWritable: true,
478
517
  });
479
518
  }
480
- const bank = this.getBankAccount(bankIndex);
481
- return await this.program.instruction.deposit(bankIndex, amount, reduceOnly, {
519
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
520
+ return await this.program.instruction.deposit(marketIndex, amount, reduceOnly, {
482
521
  accounts: {
483
522
  state: await this.getStatePublicKey(),
484
- bank: bank.pubkey,
485
- bankVault: bank.vault,
523
+ spotMarket: spotMarketAccount.pubkey,
524
+ spotMarketVault: spotMarketAccount.vault,
486
525
  user: userAccountPublicKey,
487
526
  userStats: this.getUserStatsAccountPublicKey(),
488
527
  userTokenAccount: userTokenAccount,
@@ -502,7 +541,7 @@ class ClearingHouse {
502
541
  return false;
503
542
  }
504
543
  }
505
- async getSolWithdrawalIxs(bankIndex, amount) {
544
+ async getSolWithdrawalIxs(marketIndex, amount) {
506
545
  const result = {
507
546
  ixs: [],
508
547
  signers: [],
@@ -518,7 +557,7 @@ class ClearingHouse {
518
557
  signers.forEach((ix) => {
519
558
  result.signers.push(ix);
520
559
  });
521
- const withdrawIx = await this.getWithdrawIx(amount, bankIndex, pubkey, true);
560
+ const withdrawIx = await this.getWithdrawIx(amount, marketIndex, pubkey, true);
522
561
  result.ixs.push(withdrawIx);
523
562
  result.ixs.push(spl_token_1.Token.createCloseAccountInstruction(spl_token_1.TOKEN_PROGRAM_ID, pubkey, authority, authority, []));
524
563
  return result;
@@ -540,7 +579,7 @@ class ClearingHouse {
540
579
  space: 165,
541
580
  programId: spl_token_1.TOKEN_PROGRAM_ID,
542
581
  }));
543
- result.ixs.push(spl_token_1.Token.createInitAccountInstruction(spl_token_1.TOKEN_PROGRAM_ID, banks_1.WRAPPED_SOL_MINT, wrappedSolAccount.publicKey, authority));
582
+ result.ixs.push(spl_token_1.Token.createInitAccountInstruction(spl_token_1.TOKEN_PROGRAM_ID, spotMarkets_1.WRAPPED_SOL_MINT, wrappedSolAccount.publicKey, authority));
544
583
  result.signers.push(wrappedSolAccount);
545
584
  return result;
546
585
  }
@@ -548,20 +587,20 @@ class ClearingHouse {
548
587
  * Creates the Clearing House User account for a user, and deposits some initial collateral
549
588
  * @param amount
550
589
  * @param userTokenAccount
551
- * @param bankIndex
590
+ * @param marketIndex
552
591
  * @param userId
553
592
  * @param name
554
593
  * @param fromUserId
555
594
  * @returns
556
595
  */
557
- async initializeUserAccountAndDepositCollateral(amount, userTokenAccount, bankIndex = new anchor_1.BN(0), userId = 0, name = userName_1.DEFAULT_USER_NAME, fromUserId, referrerInfo) {
596
+ async initializeUserAccountAndDepositCollateral(amount, userTokenAccount, marketIndex = new anchor_1.BN(0), userId = 0, name = userName_1.DEFAULT_USER_NAME, fromUserId, referrerInfo) {
558
597
  const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(userId, name, referrerInfo);
559
598
  const additionalSigners = [];
560
- const bank = this.getBankAccount(bankIndex);
561
- const isSolBank = bank.mint.equals(banks_1.WRAPPED_SOL_MINT);
599
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
600
+ const isSolMarket = spotMarket.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
562
601
  const tx = new web3_js_1.Transaction();
563
602
  const authority = this.wallet.publicKey;
564
- const createWSOLTokenAccount = isSolBank && userTokenAccount.equals(authority);
603
+ const createWSOLTokenAccount = isSolMarket && userTokenAccount.equals(authority);
565
604
  if (createWSOLTokenAccount) {
566
605
  const { ixs: startIxs, signers, pubkey, } = await this.getWrappedSolAccountCreationIxs(amount);
567
606
  userTokenAccount = pubkey;
@@ -571,8 +610,8 @@ class ClearingHouse {
571
610
  signers.forEach((signer) => additionalSigners.push(signer));
572
611
  }
573
612
  const depositCollateralIx = fromUserId != null
574
- ? await this.getTransferDepositIx(amount, bankIndex, fromUserId, userId)
575
- : await this.getDepositInstruction(amount, bankIndex, userTokenAccount, userId, false, false);
613
+ ? await this.getTransferDepositIx(amount, marketIndex, fromUserId, userId)
614
+ : await this.getDepositInstruction(amount, marketIndex, userTokenAccount, userId, false, false);
576
615
  if (userId === 0) {
577
616
  tx.add(await this.getInitializeUserStatsIx());
578
617
  }
@@ -584,10 +623,10 @@ class ClearingHouse {
584
623
  const { txSig } = await this.txSender.send(tx, additionalSigners, this.opts);
585
624
  return [txSig, userAccountPublicKey];
586
625
  }
587
- async initializeUserAccountForDevnet(userId = 0, name = userName_1.DEFAULT_USER_NAME, bankIndex, tokenFaucet, amount, referrerInfo) {
626
+ async initializeUserAccountForDevnet(userId = 0, name = userName_1.DEFAULT_USER_NAME, marketIndex, tokenFaucet, amount, referrerInfo) {
588
627
  const [associateTokenPublicKey, createAssociatedAccountIx, mintToIx] = await tokenFaucet.createAssociatedTokenAccountAndMintToInstructions(this.wallet.publicKey, amount);
589
628
  const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(userId, name, referrerInfo);
590
- const depositCollateralIx = await this.getDepositInstruction(amount, bankIndex, associateTokenPublicKey, userId, false, false);
629
+ const depositCollateralIx = await this.getDepositInstruction(amount, marketIndex, associateTokenPublicKey, userId, false, false);
591
630
  const tx = new web3_js_1.Transaction().add(createAssociatedAccountIx).add(mintToIx);
592
631
  if (userId === 0) {
593
632
  tx.add(await this.getInitializeUserStatsIx());
@@ -596,13 +635,13 @@ class ClearingHouse {
596
635
  const txSig = await this.program.provider.sendAndConfirm(tx, []);
597
636
  return [txSig, userAccountPublicKey];
598
637
  }
599
- async withdraw(amount, bankIndex, userTokenAccount, reduceOnly = false) {
638
+ async withdraw(amount, marketIndex, userTokenAccount, reduceOnly = false) {
600
639
  const tx = new web3_js_1.Transaction();
601
640
  const additionalSigners = [];
602
- const bank = this.getBankAccount(bankIndex);
603
- const isSolBank = bank.mint.equals(banks_1.WRAPPED_SOL_MINT);
641
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
642
+ const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
604
643
  const authority = this.wallet.publicKey;
605
- const createWSOLTokenAccount = isSolBank && userTokenAccount.equals(authority);
644
+ const createWSOLTokenAccount = isSolMarket && userTokenAccount.equals(authority);
606
645
  if (createWSOLTokenAccount) {
607
646
  const { ixs, signers, pubkey } = await this.getWrappedSolAccountCreationIxs(amount);
608
647
  userTokenAccount = pubkey;
@@ -611,7 +650,7 @@ class ClearingHouse {
611
650
  });
612
651
  signers.forEach((signer) => additionalSigners.push(signer));
613
652
  }
614
- const withdrawCollateral = await this.getWithdrawIx(amount, bank.bankIndex, userTokenAccount, reduceOnly);
653
+ const withdrawCollateral = await this.getWithdrawIx(amount, spotMarketAccount.marketIndex, userTokenAccount, reduceOnly);
615
654
  tx.add(withdrawCollateral);
616
655
  // Close the wrapped sol account at the end of the transaction
617
656
  if (createWSOLTokenAccount) {
@@ -620,18 +659,18 @@ class ClearingHouse {
620
659
  const { txSig } = await this.txSender.send(tx, additionalSigners, this.opts);
621
660
  return txSig;
622
661
  }
623
- async getWithdrawIx(amount, bankIndex, userTokenAccount, reduceOnly = false) {
662
+ async getWithdrawIx(amount, marketIndex, userTokenAccount, reduceOnly = false) {
624
663
  const userAccountPublicKey = await this.getUserAccountPublicKey();
625
664
  const remainingAccounts = this.getRemainingAccounts({
626
- writableBankIndex: bankIndex,
665
+ writableSpotMarketIndex: marketIndex,
627
666
  });
628
- const bank = this.getBankAccount(bankIndex);
629
- return await this.program.instruction.withdraw(bankIndex, amount, reduceOnly, {
667
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
668
+ return await this.program.instruction.withdraw(marketIndex, amount, reduceOnly, {
630
669
  accounts: {
631
670
  state: await this.getStatePublicKey(),
632
- bank: bank.pubkey,
633
- bankVault: bank.vault,
634
- bankVaultAuthority: bank.vaultAuthority,
671
+ spotMarket: spotMarketAccount.pubkey,
672
+ spotMarketVault: spotMarketAccount.vault,
673
+ clearingHouseSigner: this.getSignerPublicKey(),
635
674
  user: userAccountPublicKey,
636
675
  userStats: this.getUserStatsAccountPublicKey(),
637
676
  userTokenAccount: userTokenAccount,
@@ -641,17 +680,17 @@ class ClearingHouse {
641
680
  remainingAccounts,
642
681
  });
643
682
  }
644
- async transferDeposit(amount, bankIndex, fromUserId, toUserId) {
645
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getTransferDepositIx(amount, bankIndex, fromUserId, toUserId)), [], this.opts);
683
+ async transferDeposit(amount, marketIndex, fromUserId, toUserId) {
684
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getTransferDepositIx(amount, marketIndex, fromUserId, toUserId)), [], this.opts);
646
685
  return txSig;
647
686
  }
648
- async getTransferDepositIx(amount, bankIndex, fromUserId, toUserId) {
687
+ async getTransferDepositIx(amount, marketIndex, fromUserId, toUserId) {
649
688
  const fromUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, fromUserId);
650
689
  const toUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, toUserId);
651
690
  const remainingAccounts = this.getRemainingAccounts({
652
- writableBankIndex: bankIndex,
691
+ writableSpotMarketIndex: marketIndex,
653
692
  });
654
- return await this.program.instruction.transferDeposit(bankIndex, amount, {
693
+ return await this.program.instruction.transferDeposit(marketIndex, amount, {
655
694
  accounts: {
656
695
  authority: this.wallet.publicKey,
657
696
  fromUser,
@@ -662,15 +701,15 @@ class ClearingHouse {
662
701
  remainingAccounts,
663
702
  });
664
703
  }
665
- async updateBankCumulativeInterest(bankIndex) {
666
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.updateBankCumulativeInterestIx(bankIndex)), [], this.opts);
704
+ async updateSpotMarketCumulativeInterest(marketIndex) {
705
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.updateSpotMarketCumulativeInterestIx(marketIndex)), [], this.opts);
667
706
  return txSig;
668
707
  }
669
- async updateBankCumulativeInterestIx(bankIndex) {
670
- const bank = this.getBankAccount(bankIndex);
671
- return await this.program.instruction.updateBankCumulativeInterest({
708
+ async updateSpotMarketCumulativeInterestIx(marketIndex) {
709
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
710
+ return await this.program.instruction.updateSpotMarketCumulativeInterest({
672
711
  accounts: {
673
- bank: bank.pubkey,
712
+ spotMarket: spotMarket.pubkey,
674
713
  },
675
714
  });
676
715
  }
@@ -680,7 +719,7 @@ class ClearingHouse {
680
719
  }
681
720
  async settleLPIx(settleeUserAccountPublicKey, marketIndex) {
682
721
  const settleeUserAccount = (await this.program.account.user.fetch(settleeUserAccountPublicKey));
683
- const userPositions = settleeUserAccount.positions;
722
+ const userPositions = settleeUserAccount.perpPositions;
684
723
  const remainingAccounts = [];
685
724
  let foundMarket = false;
686
725
  for (const position of userPositions) {
@@ -714,12 +753,12 @@ class ClearingHouse {
714
753
  async getRemoveLiquidityIx(marketIndex, sharesToBurn) {
715
754
  const userAccountPublicKey = await this.getUserAccountPublicKey();
716
755
  const remainingAccounts = this.getRemainingAccounts({
717
- writableMarketIndex: marketIndex,
756
+ writablePerpMarketIndex: marketIndex,
718
757
  });
719
758
  if (sharesToBurn == undefined) {
720
759
  const userAccount = this.getUserAccount();
721
- const marketPosition = userAccount.positions.filter((position) => position.marketIndex.eq(marketIndex))[0];
722
- sharesToBurn = marketPosition.lpShares;
760
+ const perpPosition = userAccount.perpPositions.filter((position) => position.marketIndex.eq(marketIndex))[0];
761
+ sharesToBurn = perpPosition.lpShares;
723
762
  console.log('burning lp shares:', sharesToBurn.toString());
724
763
  }
725
764
  return this.program.instruction.removeLiquidity(sharesToBurn, marketIndex, {
@@ -739,7 +778,7 @@ class ClearingHouse {
739
778
  async getAddLiquidityIx(amount, marketIndex) {
740
779
  const userAccountPublicKey = await this.getUserAccountPublicKey();
741
780
  const remainingAccounts = this.getRemainingAccounts({
742
- writableMarketIndex: marketIndex,
781
+ writablePerpMarketIndex: marketIndex,
743
782
  });
744
783
  return this.program.instruction.addLiquidity(amount, marketIndex, {
745
784
  accounts: {
@@ -759,19 +798,51 @@ class ClearingHouse {
759
798
  price: limitPrice,
760
799
  });
761
800
  }
801
+ async sendSignedTx(tx) {
802
+ const { txSig } = await this.txSender.send(tx, undefined, this.opts, true);
803
+ return txSig;
804
+ }
805
+ /**
806
+ * Sends a market order and returns a signed tx which can fill the order against the vamm, which the caller can use to fill their own order if required.
807
+ * @param orderParams
808
+ * @param userAccountPublicKey
809
+ * @param userAccount
810
+ * @returns
811
+ */
812
+ async sendMarketOrderAndGetSignedFillTx(orderParams, userAccountPublicKey, userAccount) {
813
+ const marketIndex = orderParams.marketIndex;
814
+ const orderId = userAccount.nextOrderId;
815
+ const marketOrderTx = (0, utils_1.wrapInTx)(await this.getPlaceOrderIx(orderParams));
816
+ const fillTx = (0, utils_1.wrapInTx)(await this.getFillOrderIx(userAccountPublicKey, userAccount, {
817
+ orderId,
818
+ marketIndex,
819
+ }));
820
+ // Apply the latest blockhash to the txs so that we can sign before sending them
821
+ const currentBlockHash = (await this.connection.getLatestBlockhash('finalized')).blockhash;
822
+ marketOrderTx.recentBlockhash = currentBlockHash;
823
+ fillTx.recentBlockhash = currentBlockHash;
824
+ marketOrderTx.feePayer = userAccount.authority;
825
+ fillTx.feePayer = userAccount.authority;
826
+ const [signedMarketOrderTx, signedFillTx] = await this.provider.wallet.signAllTransactions([marketOrderTx, fillTx]);
827
+ const { txSig, slot } = await this.txSender.send(signedMarketOrderTx, [], this.opts, true);
828
+ this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
829
+ return { txSig, signedFillTx };
830
+ }
762
831
  async placeOrder(orderParams) {
763
832
  const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceOrderIx(orderParams)), [], this.opts);
764
833
  this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
765
834
  return txSig;
766
835
  }
767
- getOrderParams(optionalOrderParams) {
768
- return Object.assign({}, types_1.DefaultOrderParams, optionalOrderParams);
836
+ getOrderParams(optionalOrderParams, marketType) {
837
+ return Object.assign({}, types_1.DefaultOrderParams, optionalOrderParams, {
838
+ marketType,
839
+ });
769
840
  }
770
841
  async getPlaceOrderIx(orderParams) {
771
- orderParams = this.getOrderParams(orderParams);
842
+ orderParams = this.getOrderParams(orderParams, types_1.MarketType.PERP);
772
843
  const userAccountPublicKey = await this.getUserAccountPublicKey();
773
844
  const remainingAccounts = this.getRemainingAccounts({
774
- readableMarketIndex: orderParams.marketIndex,
845
+ readablePerpMarketIndex: orderParams.marketIndex,
775
846
  });
776
847
  return await this.program.instruction.placeOrder(orderParams, {
777
848
  accounts: {
@@ -795,7 +866,7 @@ class ClearingHouse {
795
866
  const oracleAccountInfos = [];
796
867
  for (const marketIndex of marketIndexes) {
797
868
  if (!marketIndex.eq(new anchor_1.BN(100))) {
798
- const market = this.getMarketAccount(marketIndex);
869
+ const market = this.getPerpMarketAccount(marketIndex);
799
870
  marketAccountInfos.push({
800
871
  pubkey: market.pubkey,
801
872
  isWritable: true,
@@ -817,6 +888,41 @@ class ClearingHouse {
817
888
  remainingAccounts,
818
889
  });
819
890
  }
891
+ async settleExpiredMarket(marketIndex) {
892
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getSettleExpiredMarketIx(marketIndex)), [], this.opts);
893
+ return txSig;
894
+ }
895
+ async getSettleExpiredMarketIx(marketIndex) {
896
+ const marketAccountInfos = [];
897
+ const oracleAccountInfos = [];
898
+ const spotMarketAccountInfos = [];
899
+ const market = this.getPerpMarketAccount(marketIndex);
900
+ marketAccountInfos.push({
901
+ pubkey: market.pubkey,
902
+ isWritable: true,
903
+ isSigner: false,
904
+ });
905
+ oracleAccountInfos.push({
906
+ pubkey: market.amm.oracle,
907
+ isWritable: false,
908
+ isSigner: false,
909
+ });
910
+ spotMarketAccountInfos.push({
911
+ pubkey: this.getSpotMarketAccount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).pubkey,
912
+ isSigner: false,
913
+ isWritable: true,
914
+ });
915
+ const remainingAccounts = oracleAccountInfos
916
+ .concat(spotMarketAccountInfos)
917
+ .concat(marketAccountInfos);
918
+ return await this.program.instruction.settleExpiredMarket(marketIndex, {
919
+ accounts: {
920
+ state: await this.getStatePublicKey(),
921
+ authority: this.wallet.publicKey,
922
+ },
923
+ remainingAccounts,
924
+ });
925
+ }
820
926
  async cancelOrder(orderId) {
821
927
  const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getCancelOrderIx(orderId)), [], this.opts);
822
928
  return txSig;
@@ -840,7 +946,7 @@ class ClearingHouse {
840
946
  async getCancelOrderByUserIdIx(userOrderId) {
841
947
  const userAccountPublicKey = await this.getUserAccountPublicKey();
842
948
  const order = this.getOrderByUserId(userOrderId);
843
- const oracle = this.getMarketAccount(order.marketIndex).amm.oracle;
949
+ const oracle = this.getPerpMarketAccount(order.marketIndex).amm.oracle;
844
950
  const remainingAccounts = this.getRemainingAccounts({});
845
951
  return await this.program.instruction.cancelOrderByUserId(userOrderId, {
846
952
  accounts: {
@@ -863,32 +969,32 @@ class ClearingHouse {
863
969
  const marketIndex = order
864
970
  ? order.marketIndex
865
971
  : userAccount.orders.find((order) => order.orderId.eq(userAccount.nextOrderId.sub(numericConstants_1.ONE))).marketIndex;
866
- const marketAccount = this.getMarketAccount(marketIndex);
972
+ const marketAccount = this.getPerpMarketAccount(marketIndex);
867
973
  const oracleAccountMap = new Map();
868
- const bankAccountMap = new Map();
869
- const marketAccountMap = new Map();
870
- for (const bankBalance of userAccount.bankBalances) {
871
- if (!bankBalance.balance.eq(numericConstants_1.ZERO)) {
872
- const bankAccount = this.getBankAccount(bankBalance.bankIndex);
873
- bankAccountMap.set(bankBalance.bankIndex.toNumber(), {
874
- pubkey: bankAccount.pubkey,
974
+ const spotMarketAccountMap = new Map();
975
+ const perpMarketAccountMap = new Map();
976
+ for (const spotPosition of userAccount.spotPositions) {
977
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
978
+ const spotMarketAccount = this.getSpotMarketAccount(spotPosition.marketIndex);
979
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
980
+ pubkey: spotMarketAccount.pubkey,
875
981
  isSigner: false,
876
982
  isWritable: false,
877
983
  });
878
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
879
- oracleAccountMap.set(bankAccount.oracle.toString(), {
880
- pubkey: bankAccount.oracle,
984
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
985
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
986
+ pubkey: spotMarketAccount.oracle,
881
987
  isSigner: false,
882
988
  isWritable: false,
883
989
  });
884
990
  }
885
991
  }
886
992
  }
887
- for (const position of userAccount.positions) {
993
+ for (const position of userAccount.perpPositions) {
888
994
  if (!(0, position_1.positionIsAvailable)(position) &&
889
995
  !position.marketIndex.eq(order.marketIndex)) {
890
- const market = this.getMarketAccount(position.marketIndex);
891
- marketAccountMap.set(position.marketIndex.toNumber(), {
996
+ const market = this.getPerpMarketAccount(position.marketIndex);
997
+ perpMarketAccountMap.set(position.marketIndex.toNumber(), {
892
998
  pubkey: market.pubkey,
893
999
  isWritable: false,
894
1000
  isSigner: false,
@@ -900,7 +1006,7 @@ class ClearingHouse {
900
1006
  });
901
1007
  }
902
1008
  }
903
- marketAccountMap.set(marketIndex.toNumber(), {
1009
+ perpMarketAccountMap.set(marketIndex.toNumber(), {
904
1010
  pubkey: marketAccount.pubkey,
905
1011
  isWritable: true,
906
1012
  isSigner: false,
@@ -912,8 +1018,8 @@ class ClearingHouse {
912
1018
  });
913
1019
  const remainingAccounts = [
914
1020
  ...oracleAccountMap.values(),
915
- ...bankAccountMap.values(),
916
- ...marketAccountMap.values(),
1021
+ ...spotMarketAccountMap.values(),
1022
+ ...perpMarketAccountMap.values(),
917
1023
  ];
918
1024
  if (makerInfo) {
919
1025
  remainingAccounts.push({
@@ -953,6 +1059,212 @@ class ClearingHouse {
953
1059
  remainingAccounts,
954
1060
  });
955
1061
  }
1062
+ async placeSpotOrder(orderParams) {
1063
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceSpotOrderIx(orderParams)), [], this.opts);
1064
+ return txSig;
1065
+ }
1066
+ async getPlaceSpotOrderIx(orderParams) {
1067
+ orderParams = this.getOrderParams(orderParams, types_1.MarketType.SPOT);
1068
+ const userAccountPublicKey = await this.getUserAccountPublicKey();
1069
+ const remainingAccounts = this.getRemainingAccounts({
1070
+ readableSpotMarketIndex: orderParams.marketIndex,
1071
+ });
1072
+ return await this.program.instruction.placeSpotOrder(orderParams, {
1073
+ accounts: {
1074
+ state: await this.getStatePublicKey(),
1075
+ user: userAccountPublicKey,
1076
+ userStats: this.getUserStatsAccountPublicKey(),
1077
+ authority: this.wallet.publicKey,
1078
+ },
1079
+ remainingAccounts,
1080
+ });
1081
+ }
1082
+ async fillSpotOrder(userAccountPublicKey, user, order, fulfillmentConfig, makerInfo, referrerInfo) {
1083
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getFillSpotOrderIx(userAccountPublicKey, user, order, fulfillmentConfig, makerInfo, referrerInfo)), [], this.opts);
1084
+ return txSig;
1085
+ }
1086
+ async getFillSpotOrderIx(userAccountPublicKey, userAccount, order, fulfillmentConfig, makerInfo, referrerInfo) {
1087
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
1088
+ const fillerPublicKey = await this.getUserAccountPublicKey();
1089
+ const fillerStatsPublicKey = this.getUserStatsAccountPublicKey();
1090
+ const marketIndex = order
1091
+ ? order.marketIndex
1092
+ : userAccount.orders.find((order) => order.orderId.eq(userAccount.nextOrderId.sub(numericConstants_1.ONE))).marketIndex;
1093
+ const oracleAccountMap = new Map();
1094
+ const spotMarketAccountMap = new Map();
1095
+ const perpMarketAccountMap = new Map();
1096
+ for (const spotPosition of userAccount.spotPositions) {
1097
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1098
+ const spotMarket = this.getSpotMarketAccount(spotPosition.marketIndex);
1099
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
1100
+ pubkey: spotMarket.pubkey,
1101
+ isSigner: false,
1102
+ isWritable: false,
1103
+ });
1104
+ if (!spotMarket.oracle.equals(web3_js_1.PublicKey.default)) {
1105
+ oracleAccountMap.set(spotMarket.oracle.toString(), {
1106
+ pubkey: spotMarket.oracle,
1107
+ isSigner: false,
1108
+ isWritable: false,
1109
+ });
1110
+ }
1111
+ }
1112
+ }
1113
+ for (const position of userAccount.perpPositions) {
1114
+ if (!(0, position_1.positionIsAvailable)(position) &&
1115
+ !position.marketIndex.eq(order.marketIndex)) {
1116
+ const market = this.getPerpMarketAccount(position.marketIndex);
1117
+ perpMarketAccountMap.set(position.marketIndex.toNumber(), {
1118
+ pubkey: market.pubkey,
1119
+ isWritable: false,
1120
+ isSigner: false,
1121
+ });
1122
+ oracleAccountMap.set(market.amm.oracle.toString(), {
1123
+ pubkey: market.amm.oracle,
1124
+ isWritable: false,
1125
+ isSigner: false,
1126
+ });
1127
+ }
1128
+ }
1129
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1130
+ spotMarketAccountMap.set(marketIndex.toNumber(), {
1131
+ pubkey: spotMarketAccount.pubkey,
1132
+ isWritable: true,
1133
+ isSigner: false,
1134
+ });
1135
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1136
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1137
+ pubkey: spotMarketAccount.oracle,
1138
+ isWritable: false,
1139
+ isSigner: false,
1140
+ });
1141
+ }
1142
+ const quoteMarketAccount = this.getQuoteSpotMarketAccount();
1143
+ spotMarketAccountMap.set(quoteMarketAccount.marketIndex.toNumber(), {
1144
+ pubkey: quoteMarketAccount.pubkey,
1145
+ isWritable: true,
1146
+ isSigner: false,
1147
+ });
1148
+ const remainingAccounts = [
1149
+ ...oracleAccountMap.values(),
1150
+ ...spotMarketAccountMap.values(),
1151
+ ...perpMarketAccountMap.values(),
1152
+ ];
1153
+ if (makerInfo) {
1154
+ remainingAccounts.push({
1155
+ pubkey: makerInfo.maker,
1156
+ isWritable: true,
1157
+ isSigner: false,
1158
+ });
1159
+ remainingAccounts.push({
1160
+ pubkey: makerInfo.makerStats,
1161
+ isWritable: true,
1162
+ isSigner: false,
1163
+ });
1164
+ }
1165
+ if (referrerInfo) {
1166
+ remainingAccounts.push({
1167
+ pubkey: referrerInfo.referrer,
1168
+ isWritable: true,
1169
+ isSigner: false,
1170
+ });
1171
+ remainingAccounts.push({
1172
+ pubkey: referrerInfo.referrerStats,
1173
+ isWritable: true,
1174
+ isSigner: false,
1175
+ });
1176
+ }
1177
+ const orderId = order.orderId;
1178
+ const makerOrderId = makerInfo ? makerInfo.order.orderId : null;
1179
+ if (fulfillmentConfig) {
1180
+ remainingAccounts.push({
1181
+ pubkey: fulfillmentConfig.pubkey,
1182
+ isWritable: false,
1183
+ isSigner: false,
1184
+ });
1185
+ remainingAccounts.push({
1186
+ pubkey: fulfillmentConfig.serumProgramId,
1187
+ isWritable: false,
1188
+ isSigner: false,
1189
+ });
1190
+ remainingAccounts.push({
1191
+ pubkey: fulfillmentConfig.serumMarket,
1192
+ isWritable: true,
1193
+ isSigner: false,
1194
+ });
1195
+ remainingAccounts.push({
1196
+ pubkey: fulfillmentConfig.serumRequestQueue,
1197
+ isWritable: true,
1198
+ isSigner: false,
1199
+ });
1200
+ remainingAccounts.push({
1201
+ pubkey: fulfillmentConfig.serumEventQueue,
1202
+ isWritable: true,
1203
+ isSigner: false,
1204
+ });
1205
+ remainingAccounts.push({
1206
+ pubkey: fulfillmentConfig.serumBids,
1207
+ isWritable: true,
1208
+ isSigner: false,
1209
+ });
1210
+ remainingAccounts.push({
1211
+ pubkey: fulfillmentConfig.serumAsks,
1212
+ isWritable: true,
1213
+ isSigner: false,
1214
+ });
1215
+ remainingAccounts.push({
1216
+ pubkey: fulfillmentConfig.serumBaseVault,
1217
+ isWritable: true,
1218
+ isSigner: false,
1219
+ });
1220
+ remainingAccounts.push({
1221
+ pubkey: fulfillmentConfig.serumQuoteVault,
1222
+ isWritable: true,
1223
+ isSigner: false,
1224
+ });
1225
+ remainingAccounts.push({
1226
+ pubkey: fulfillmentConfig.serumOpenOrders,
1227
+ isWritable: true,
1228
+ isSigner: false,
1229
+ });
1230
+ remainingAccounts.push({
1231
+ pubkey: (0, pda_1.getSerumSignerPublicKey)(fulfillmentConfig.serumProgramId, fulfillmentConfig.serumMarket, fulfillmentConfig.serumSignerNonce),
1232
+ isWritable: false,
1233
+ isSigner: false,
1234
+ });
1235
+ remainingAccounts.push({
1236
+ pubkey: this.getSignerPublicKey(),
1237
+ isWritable: false,
1238
+ isSigner: false,
1239
+ });
1240
+ remainingAccounts.push({
1241
+ pubkey: spl_token_1.TOKEN_PROGRAM_ID,
1242
+ isWritable: false,
1243
+ isSigner: false,
1244
+ });
1245
+ remainingAccounts.push({
1246
+ pubkey: spotMarketAccount.vault,
1247
+ isWritable: true,
1248
+ isSigner: false,
1249
+ });
1250
+ remainingAccounts.push({
1251
+ pubkey: quoteMarketAccount.vault,
1252
+ isWritable: true,
1253
+ isSigner: false,
1254
+ });
1255
+ }
1256
+ return await this.program.instruction.fillSpotOrder(orderId, fulfillmentConfig ? fulfillmentConfig.fulfillmentType : null, makerOrderId, {
1257
+ accounts: {
1258
+ state: await this.getStatePublicKey(),
1259
+ filler: fillerPublicKey,
1260
+ fillerStats: fillerStatsPublicKey,
1261
+ user: userAccountPublicKey,
1262
+ userStats: userStatsPublicKey,
1263
+ authority: this.wallet.publicKey,
1264
+ },
1265
+ remainingAccounts,
1266
+ });
1267
+ }
956
1268
  async triggerOrder(userAccountPublicKey, user, order) {
957
1269
  const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getTriggerOrderIx(userAccountPublicKey, user, order)), [], this.opts);
958
1270
  return txSig;
@@ -960,32 +1272,32 @@ class ClearingHouse {
960
1272
  async getTriggerOrderIx(userAccountPublicKey, userAccount, order) {
961
1273
  const fillerPublicKey = await this.getUserAccountPublicKey();
962
1274
  const marketIndex = order.marketIndex;
963
- const marketAccount = this.getMarketAccount(marketIndex);
1275
+ const marketAccount = this.getPerpMarketAccount(marketIndex);
964
1276
  const oracleAccountMap = new Map();
965
- const bankAccountMap = new Map();
966
- const marketAccountMap = new Map();
967
- for (const bankBalance of userAccount.bankBalances) {
968
- if (!bankBalance.balance.eq(numericConstants_1.ZERO)) {
969
- const bankAccount = this.getBankAccount(bankBalance.bankIndex);
970
- bankAccountMap.set(bankBalance.bankIndex.toNumber(), {
971
- pubkey: bankAccount.pubkey,
1277
+ const spotMarketAccountMap = new Map();
1278
+ const perpMarketAccountMap = new Map();
1279
+ for (const spotPosition of userAccount.spotPositions) {
1280
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1281
+ const spotMarketAccount = this.getSpotMarketAccount(spotPosition.marketIndex);
1282
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
1283
+ pubkey: spotMarketAccount.pubkey,
972
1284
  isSigner: false,
973
1285
  isWritable: false,
974
1286
  });
975
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
976
- oracleAccountMap.set(bankAccount.oracle.toString(), {
977
- pubkey: bankAccount.oracle,
1287
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1288
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1289
+ pubkey: spotMarketAccount.oracle,
978
1290
  isSigner: false,
979
1291
  isWritable: false,
980
1292
  });
981
1293
  }
982
1294
  }
983
1295
  }
984
- for (const position of userAccount.positions) {
1296
+ for (const position of userAccount.perpPositions) {
985
1297
  if (!(0, position_1.positionIsAvailable)(position) &&
986
1298
  !position.marketIndex.eq(order.marketIndex)) {
987
- const market = this.getMarketAccount(position.marketIndex);
988
- marketAccountMap.set(position.marketIndex.toNumber(), {
1299
+ const market = this.getPerpMarketAccount(position.marketIndex);
1300
+ perpMarketAccountMap.set(position.marketIndex.toNumber(), {
989
1301
  pubkey: market.pubkey,
990
1302
  isWritable: false,
991
1303
  isSigner: false,
@@ -997,7 +1309,7 @@ class ClearingHouse {
997
1309
  });
998
1310
  }
999
1311
  }
1000
- marketAccountMap.set(marketIndex.toNumber(), {
1312
+ perpMarketAccountMap.set(marketIndex.toNumber(), {
1001
1313
  pubkey: marketAccount.pubkey,
1002
1314
  isWritable: true,
1003
1315
  isSigner: false,
@@ -1009,8 +1321,8 @@ class ClearingHouse {
1009
1321
  });
1010
1322
  const remainingAccounts = [
1011
1323
  ...oracleAccountMap.values(),
1012
- ...bankAccountMap.values(),
1013
- ...marketAccountMap.values(),
1324
+ ...spotMarketAccountMap.values(),
1325
+ ...perpMarketAccountMap.values(),
1014
1326
  ];
1015
1327
  const orderId = order.orderId;
1016
1328
  return await this.program.instruction.triggerOrder(orderId, {
@@ -1023,18 +1335,94 @@ class ClearingHouse {
1023
1335
  remainingAccounts,
1024
1336
  });
1025
1337
  }
1338
+ async triggerSpotOrder(userAccountPublicKey, user, order) {
1339
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getTriggerSpotOrderIx(userAccountPublicKey, user, order)), [], this.opts);
1340
+ return txSig;
1341
+ }
1342
+ async getTriggerSpotOrderIx(userAccountPublicKey, userAccount, order) {
1343
+ const fillerPublicKey = await this.getUserAccountPublicKey();
1344
+ const marketIndex = order.marketIndex;
1345
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1346
+ const oracleAccountMap = new Map();
1347
+ const spotMarketAccountMap = new Map();
1348
+ const perpMarketAccountMap = new Map();
1349
+ for (const spotPosition of userAccount.spotPositions) {
1350
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1351
+ const spotMarketAccount = this.getSpotMarketAccount(spotPosition.marketIndex);
1352
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
1353
+ pubkey: spotMarketAccount.pubkey,
1354
+ isSigner: false,
1355
+ isWritable: false,
1356
+ });
1357
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1358
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1359
+ pubkey: spotMarketAccount.oracle,
1360
+ isSigner: false,
1361
+ isWritable: false,
1362
+ });
1363
+ }
1364
+ }
1365
+ }
1366
+ for (const position of userAccount.perpPositions) {
1367
+ if (!(0, position_1.positionIsAvailable)(position) &&
1368
+ !position.marketIndex.eq(order.marketIndex)) {
1369
+ const market = this.getPerpMarketAccount(position.marketIndex);
1370
+ perpMarketAccountMap.set(position.marketIndex.toNumber(), {
1371
+ pubkey: market.pubkey,
1372
+ isWritable: false,
1373
+ isSigner: false,
1374
+ });
1375
+ oracleAccountMap.set(market.amm.oracle.toString(), {
1376
+ pubkey: market.amm.oracle,
1377
+ isWritable: false,
1378
+ isSigner: false,
1379
+ });
1380
+ }
1381
+ }
1382
+ const quoteSpotMarket = this.getQuoteSpotMarketAccount();
1383
+ spotMarketAccountMap.set(quoteSpotMarket.marketIndex.toNumber(), {
1384
+ pubkey: quoteSpotMarket.pubkey,
1385
+ isWritable: true,
1386
+ isSigner: false,
1387
+ });
1388
+ spotMarketAccountMap.set(marketIndex.toNumber(), {
1389
+ pubkey: spotMarketAccount.pubkey,
1390
+ isWritable: false,
1391
+ isSigner: false,
1392
+ });
1393
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1394
+ pubkey: spotMarketAccount.oracle,
1395
+ isWritable: false,
1396
+ isSigner: false,
1397
+ });
1398
+ const remainingAccounts = [
1399
+ ...oracleAccountMap.values(),
1400
+ ...spotMarketAccountMap.values(),
1401
+ ...perpMarketAccountMap.values(),
1402
+ ];
1403
+ const orderId = order.orderId;
1404
+ return await this.program.instruction.triggerSpotOrder(orderId, {
1405
+ accounts: {
1406
+ state: await this.getStatePublicKey(),
1407
+ filler: fillerPublicKey,
1408
+ user: userAccountPublicKey,
1409
+ authority: this.wallet.publicKey,
1410
+ },
1411
+ remainingAccounts,
1412
+ });
1413
+ }
1026
1414
  async placeAndTake(orderParams, makerInfo, referrerInfo) {
1027
1415
  const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceAndTakeIx(orderParams, makerInfo, referrerInfo)), [], this.opts);
1028
1416
  this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
1029
1417
  return txSig;
1030
1418
  }
1031
1419
  async getPlaceAndTakeIx(orderParams, makerInfo, referrerInfo) {
1032
- orderParams = this.getOrderParams(orderParams);
1420
+ orderParams = this.getOrderParams(orderParams, types_1.MarketType.PERP);
1033
1421
  const userStatsPublicKey = await this.getUserStatsAccountPublicKey();
1034
1422
  const userAccountPublicKey = await this.getUserAccountPublicKey();
1035
1423
  const remainingAccounts = this.getRemainingAccounts({
1036
- writableMarketIndex: orderParams.marketIndex,
1037
- writableBankIndex: numericConstants_1.QUOTE_ASSET_BANK_INDEX,
1424
+ writablePerpMarketIndex: orderParams.marketIndex,
1425
+ writableSpotMarketIndex: numericConstants_1.QUOTE_SPOT_MARKET_INDEX,
1038
1426
  });
1039
1427
  let makerOrderId = null;
1040
1428
  if (makerInfo) {
@@ -1078,13 +1466,13 @@ class ClearingHouse {
1078
1466
  return txSig;
1079
1467
  }
1080
1468
  async getPlaceAndMakeIx(orderParams, takerInfo, referrerInfo) {
1081
- orderParams = this.getOrderParams(orderParams);
1469
+ orderParams = this.getOrderParams(orderParams, types_1.MarketType.PERP);
1082
1470
  const userStatsPublicKey = this.getUserStatsAccountPublicKey();
1083
1471
  const userAccountPublicKey = await this.getUserAccountPublicKey();
1084
1472
  // todo merge this with getRemainingAccounts
1085
1473
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1086
1474
  counterPartyUserAccount: takerInfo.takerUserAccount,
1087
- writableMarketIndex: orderParams.marketIndex,
1475
+ writablePerpMarketIndex: orderParams.marketIndex,
1088
1476
  });
1089
1477
  if (referrerInfo) {
1090
1478
  remainingAccounts.push({
@@ -1149,12 +1537,82 @@ class ClearingHouse {
1149
1537
  return txSig;
1150
1538
  }
1151
1539
  async settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
1540
+ const perpMarketAccountMap = new Map();
1541
+ const oracleAccountMap = new Map();
1542
+ const spotMarketAccountMap = new Map();
1543
+ for (const position of settleeUserAccount.perpPositions) {
1544
+ if (!(0, position_1.positionIsAvailable)(position)) {
1545
+ const market = this.getPerpMarketAccount(position.marketIndex);
1546
+ perpMarketAccountMap.set(position.marketIndex.toNumber(), {
1547
+ pubkey: market.pubkey,
1548
+ isWritable: false,
1549
+ isSigner: false,
1550
+ });
1551
+ oracleAccountMap.set(market.amm.oracle.toString(), {
1552
+ pubkey: market.amm.oracle,
1553
+ isWritable: false,
1554
+ isSigner: false,
1555
+ });
1556
+ }
1557
+ }
1558
+ for (const spotPosition of settleeUserAccount.spotPositions) {
1559
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1560
+ const spotMarketAccount = this.getSpotMarketAccount(spotPosition.marketIndex);
1561
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
1562
+ pubkey: spotMarketAccount.pubkey,
1563
+ isSigner: false,
1564
+ isWritable: false,
1565
+ });
1566
+ if (!spotMarketAccount.marketIndex.eq(numericConstants_1.ZERO)) {
1567
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1568
+ pubkey: spotMarketAccount.oracle,
1569
+ isSigner: false,
1570
+ isWritable: false,
1571
+ });
1572
+ }
1573
+ }
1574
+ }
1575
+ const marketAccount = this.getPerpMarketAccount(marketIndex.toNumber());
1576
+ perpMarketAccountMap.set(marketIndex.toNumber(), {
1577
+ pubkey: marketAccount.pubkey,
1578
+ isSigner: false,
1579
+ isWritable: true,
1580
+ });
1581
+ oracleAccountMap.set(marketAccount.amm.oracle.toString(), {
1582
+ pubkey: marketAccount.amm.oracle,
1583
+ isSigner: false,
1584
+ isWritable: false,
1585
+ });
1586
+ spotMarketAccountMap.set(numericConstants_1.QUOTE_SPOT_MARKET_INDEX.toNumber(), {
1587
+ pubkey: this.getSpotMarketAccount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).pubkey,
1588
+ isSigner: false,
1589
+ isWritable: true,
1590
+ });
1591
+ const remainingAccounts = [
1592
+ ...oracleAccountMap.values(),
1593
+ ...spotMarketAccountMap.values(),
1594
+ ...perpMarketAccountMap.values(),
1595
+ ];
1596
+ return await this.program.instruction.settlePnl(marketIndex, {
1597
+ accounts: {
1598
+ state: await this.getStatePublicKey(),
1599
+ authority: this.wallet.publicKey,
1600
+ user: settleeUserAccountPublicKey,
1601
+ },
1602
+ remainingAccounts: remainingAccounts,
1603
+ });
1604
+ }
1605
+ async settleExpiredPosition(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
1606
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getSettleExpiredPositionIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex)), [], this.opts);
1607
+ return txSig;
1608
+ }
1609
+ async getSettleExpiredPositionIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
1152
1610
  const marketAccountMap = new Map();
1153
1611
  const oracleAccountMap = new Map();
1154
- const bankAccountMap = new Map();
1155
- for (const position of settleeUserAccount.positions) {
1612
+ const spotMarketAccountMap = new Map();
1613
+ for (const position of settleeUserAccount.perpPositions) {
1156
1614
  if (!(0, position_1.positionIsAvailable)(position)) {
1157
- const market = this.getMarketAccount(position.marketIndex);
1615
+ const market = this.getPerpMarketAccount(position.marketIndex);
1158
1616
  marketAccountMap.set(position.marketIndex.toNumber(), {
1159
1617
  pubkey: market.pubkey,
1160
1618
  isWritable: false,
@@ -1167,15 +1625,15 @@ class ClearingHouse {
1167
1625
  });
1168
1626
  }
1169
1627
  }
1170
- for (const userBankBalance of settleeUserAccount.bankBalances) {
1171
- if (!userBankBalance.balance.eq(numericConstants_1.QUOTE_ASSET_BANK_INDEX)) {
1172
- const bankAccount = this.getBankAccount(userBankBalance.bankIndex);
1173
- bankAccountMap.set(userBankBalance.bankIndex.toNumber(), {
1628
+ for (const userBankBalance of settleeUserAccount.spotPositions) {
1629
+ if (!userBankBalance.balance.eq(numericConstants_1.ZERO)) {
1630
+ const bankAccount = this.getSpotMarketAccount(userBankBalance.marketIndex);
1631
+ spotMarketAccountMap.set(userBankBalance.marketIndex.toNumber(), {
1174
1632
  pubkey: bankAccount.pubkey,
1175
1633
  isSigner: false,
1176
1634
  isWritable: false,
1177
1635
  });
1178
- if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
1636
+ if (!bankAccount.marketIndex.eq(numericConstants_1.ZERO)) {
1179
1637
  oracleAccountMap.set(bankAccount.oracle.toString(), {
1180
1638
  pubkey: bankAccount.oracle,
1181
1639
  isSigner: false,
@@ -1184,7 +1642,7 @@ class ClearingHouse {
1184
1642
  }
1185
1643
  }
1186
1644
  }
1187
- const marketAccount = this.getMarketAccount(marketIndex.toNumber());
1645
+ const marketAccount = this.getPerpMarketAccount(marketIndex.toNumber());
1188
1646
  marketAccountMap.set(marketIndex.toNumber(), {
1189
1647
  pubkey: marketAccount.pubkey,
1190
1648
  isSigner: false,
@@ -1195,17 +1653,17 @@ class ClearingHouse {
1195
1653
  isSigner: false,
1196
1654
  isWritable: false,
1197
1655
  });
1198
- bankAccountMap.set(numericConstants_1.QUOTE_ASSET_BANK_INDEX.toNumber(), {
1199
- pubkey: this.getBankAccount(numericConstants_1.QUOTE_ASSET_BANK_INDEX).pubkey,
1656
+ spotMarketAccountMap.set(numericConstants_1.QUOTE_SPOT_MARKET_INDEX.toNumber(), {
1657
+ pubkey: this.getSpotMarketAccount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).pubkey,
1200
1658
  isSigner: false,
1201
1659
  isWritable: true,
1202
1660
  });
1203
1661
  const remainingAccounts = [
1204
1662
  ...oracleAccountMap.values(),
1205
- ...bankAccountMap.values(),
1663
+ ...spotMarketAccountMap.values(),
1206
1664
  ...marketAccountMap.values(),
1207
1665
  ];
1208
- return await this.program.instruction.settlePnl(marketIndex, {
1666
+ return await this.program.instruction.settleExpiredPosition(marketIndex, {
1209
1667
  accounts: {
1210
1668
  state: await this.getStatePublicKey(),
1211
1669
  authority: this.wallet.publicKey,
@@ -1215,7 +1673,8 @@ class ClearingHouse {
1215
1673
  });
1216
1674
  }
1217
1675
  async liquidatePerp(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount) {
1218
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidatePerpIx(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount)), [], this.opts);
1676
+ const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidatePerpIx(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount)), [], this.opts);
1677
+ this.marketLastSlotCache.set(marketIndex.toNumber(), slot);
1219
1678
  return txSig;
1220
1679
  }
1221
1680
  async getLiquidatePerpIx(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount) {
@@ -1223,7 +1682,7 @@ class ClearingHouse {
1223
1682
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1224
1683
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
1225
1684
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1226
- writableMarketIndex: marketIndex,
1685
+ writablePerpMarketIndex: marketIndex,
1227
1686
  counterPartyUserAccount: userAccount,
1228
1687
  });
1229
1688
  return await this.program.instruction.liquidatePerp(marketIndex, maxBaseAssetAmount, {
@@ -1238,17 +1697,17 @@ class ClearingHouse {
1238
1697
  remainingAccounts: remainingAccounts,
1239
1698
  });
1240
1699
  }
1241
- async liquidateBorrow(userAccountPublicKey, userAccount, assetBankIndex, liabilityBankIndex, maxLiabilityTransfer) {
1242
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidateBorrowIx(userAccountPublicKey, userAccount, assetBankIndex, liabilityBankIndex, maxLiabilityTransfer)), [], this.opts);
1700
+ async liquidateBorrow(userAccountPublicKey, userAccount, assetmarketIndex, liabilitymarketIndex, maxLiabilityTransfer) {
1701
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidateBorrowIx(userAccountPublicKey, userAccount, assetmarketIndex, liabilitymarketIndex, maxLiabilityTransfer)), [], this.opts);
1243
1702
  return txSig;
1244
1703
  }
1245
- async getLiquidateBorrowIx(userAccountPublicKey, userAccount, assetBankIndex, liabilityBankIndex, maxLiabilityTransfer) {
1704
+ async getLiquidateBorrowIx(userAccountPublicKey, userAccount, assetmarketIndex, liabilitymarketIndex, maxLiabilityTransfer) {
1246
1705
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1247
1706
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1248
1707
  counterPartyUserAccount: userAccount,
1249
- writableBankIndexes: [liabilityBankIndex, assetBankIndex],
1708
+ writableSpotMarketIndexes: [liabilitymarketIndex, assetmarketIndex],
1250
1709
  });
1251
- return await this.program.instruction.liquidateBorrow(assetBankIndex, liabilityBankIndex, maxLiabilityTransfer, {
1710
+ return await this.program.instruction.liquidateBorrow(assetmarketIndex, liabilitymarketIndex, maxLiabilityTransfer, {
1252
1711
  accounts: {
1253
1712
  state: await this.getStatePublicKey(),
1254
1713
  authority: this.wallet.publicKey,
@@ -1258,18 +1717,19 @@ class ClearingHouse {
1258
1717
  remainingAccounts: remainingAccounts,
1259
1718
  });
1260
1719
  }
1261
- async liquidateBorrowForPerpPnl(userAccountPublicKey, userAccount, perpMarketIndex, liabilityBankIndex, maxLiabilityTransfer) {
1262
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilityBankIndex, maxLiabilityTransfer)), [], this.opts);
1720
+ async liquidateBorrowForPerpPnl(userAccountPublicKey, userAccount, perpMarketIndex, liabilitymarketIndex, maxLiabilityTransfer) {
1721
+ const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilitymarketIndex, maxLiabilityTransfer)), [], this.opts);
1722
+ this.marketLastSlotCache.set(perpMarketIndex.toNumber(), slot);
1263
1723
  return txSig;
1264
1724
  }
1265
- async getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilityBankIndex, maxLiabilityTransfer) {
1725
+ async getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilitymarketIndex, maxLiabilityTransfer) {
1266
1726
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1267
1727
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1268
1728
  counterPartyUserAccount: userAccount,
1269
- writableMarketIndex: perpMarketIndex,
1270
- writableBankIndexes: [liabilityBankIndex],
1729
+ writablePerpMarketIndex: perpMarketIndex,
1730
+ writableSpotMarketIndexes: [liabilitymarketIndex],
1271
1731
  });
1272
- return await this.program.instruction.liquidateBorrowForPerpPnl(perpMarketIndex, liabilityBankIndex, maxLiabilityTransfer, {
1732
+ return await this.program.instruction.liquidateBorrowForPerpPnl(perpMarketIndex, liabilitymarketIndex, maxLiabilityTransfer, {
1273
1733
  accounts: {
1274
1734
  state: await this.getStatePublicKey(),
1275
1735
  authority: this.wallet.publicKey,
@@ -1279,18 +1739,19 @@ class ClearingHouse {
1279
1739
  remainingAccounts: remainingAccounts,
1280
1740
  });
1281
1741
  }
1282
- async liquidatePerpPnlForDeposit(userAccountPublicKey, userAccount, perpMarketIndex, assetBankIndex, maxPnlTransfer) {
1283
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetBankIndex, maxPnlTransfer)), [], this.opts);
1742
+ async liquidatePerpPnlForDeposit(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer) {
1743
+ const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer)), [], this.opts);
1744
+ this.marketLastSlotCache.set(perpMarketIndex.toNumber(), slot);
1284
1745
  return txSig;
1285
1746
  }
1286
- async getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetBankIndex, maxPnlTransfer) {
1747
+ async getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer) {
1287
1748
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1288
1749
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1289
1750
  counterPartyUserAccount: userAccount,
1290
- writableMarketIndex: perpMarketIndex,
1291
- writableBankIndexes: [assetBankIndex],
1751
+ writablePerpMarketIndex: perpMarketIndex,
1752
+ writableSpotMarketIndexes: [assetMarketIndex],
1292
1753
  });
1293
- return await this.program.instruction.liquidatePerpPnlForDeposit(perpMarketIndex, assetBankIndex, maxPnlTransfer, {
1754
+ return await this.program.instruction.liquidatePerpPnlForDeposit(perpMarketIndex, assetMarketIndex, maxPnlTransfer, {
1294
1755
  accounts: {
1295
1756
  state: await this.getStatePublicKey(),
1296
1757
  authority: this.wallet.publicKey,
@@ -1300,52 +1761,52 @@ class ClearingHouse {
1300
1761
  remainingAccounts: remainingAccounts,
1301
1762
  });
1302
1763
  }
1303
- async resolvePerpBankruptcy(userAccountPublicKey, userAccount, bankIndex, marketIndex) {
1304
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, bankIndex, marketIndex)), [], this.opts);
1764
+ async resolvePerpBankruptcy(userAccountPublicKey, userAccount, marketIndex) {
1765
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, marketIndex)), [], this.opts);
1305
1766
  return txSig;
1306
1767
  }
1307
- async getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, bankIndex, marketIndex) {
1768
+ async getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, marketIndex) {
1308
1769
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1309
1770
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1310
- writableMarketIndex: marketIndex,
1311
- writableBankIndexes: [bankIndex],
1771
+ writablePerpMarketIndex: marketIndex,
1772
+ writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
1312
1773
  counterPartyUserAccount: userAccount,
1313
1774
  });
1314
- const bank = this.getBankAccount(bankIndex);
1315
- return await this.program.instruction.resolvePerpBankruptcy(bankIndex, marketIndex, {
1775
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
1776
+ return await this.program.instruction.resolvePerpBankruptcy(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, marketIndex, {
1316
1777
  accounts: {
1317
1778
  state: await this.getStatePublicKey(),
1318
1779
  authority: this.wallet.publicKey,
1319
1780
  user: userAccountPublicKey,
1320
1781
  liquidator: liquidatorPublicKey,
1321
- bankVault: bank.vault,
1322
- insuranceFundVault: bank.insuranceFundVault,
1323
- insuranceFundVaultAuthority: bank.insuranceFundVaultAuthority,
1782
+ spotMarketVault: spotMarket.vault,
1783
+ insuranceFundVault: spotMarket.insuranceFundVault,
1784
+ clearingHouseSigner: this.getSignerPublicKey(),
1324
1785
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1325
1786
  },
1326
1787
  remainingAccounts: remainingAccounts,
1327
1788
  });
1328
1789
  }
1329
- async resolveBorrowBankruptcy(userAccountPublicKey, userAccount, bankIndex) {
1330
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getResolveBorrowBankruptcyIx(userAccountPublicKey, userAccount, bankIndex)), [], this.opts);
1790
+ async resolveBorrowBankruptcy(userAccountPublicKey, userAccount, marketIndex) {
1791
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getResolveBorrowBankruptcyIx(userAccountPublicKey, userAccount, marketIndex)), [], this.opts);
1331
1792
  return txSig;
1332
1793
  }
1333
- async getResolveBorrowBankruptcyIx(userAccountPublicKey, userAccount, bankIndex) {
1794
+ async getResolveBorrowBankruptcyIx(userAccountPublicKey, userAccount, marketIndex) {
1334
1795
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1335
1796
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1336
- writableBankIndexes: [bankIndex],
1797
+ writableSpotMarketIndexes: [marketIndex],
1337
1798
  counterPartyUserAccount: userAccount,
1338
1799
  });
1339
- const bank = this.getBankAccount(bankIndex);
1340
- return await this.program.instruction.resolveBorrowBankruptcy(bankIndex, {
1800
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
1801
+ return await this.program.instruction.resolveBorrowBankruptcy(marketIndex, {
1341
1802
  accounts: {
1342
1803
  state: await this.getStatePublicKey(),
1343
1804
  authority: this.wallet.publicKey,
1344
1805
  user: userAccountPublicKey,
1345
1806
  liquidator: liquidatorPublicKey,
1346
- bankVault: bank.vault,
1347
- insuranceFundVault: bank.insuranceFundVault,
1348
- insuranceFundVaultAuthority: bank.insuranceFundVaultAuthority,
1807
+ spotMarketVault: spotMarket.vault,
1808
+ insuranceFundVault: spotMarket.insuranceFundVault,
1809
+ clearingHouseSigner: this.getSignerPublicKey(),
1349
1810
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1350
1811
  },
1351
1812
  remainingAccounts: remainingAccounts,
@@ -1354,28 +1815,28 @@ class ClearingHouse {
1354
1815
  getRemainingAccountsWithCounterparty(params) {
1355
1816
  const counterPartyUserAccount = params.counterPartyUserAccount;
1356
1817
  const oracleAccountMap = new Map();
1357
- const bankAccountMap = new Map();
1818
+ const spotMarketAccountMap = new Map();
1358
1819
  const marketAccountMap = new Map();
1359
- for (const bankBalance of counterPartyUserAccount.bankBalances) {
1360
- if (!bankBalance.balance.eq(numericConstants_1.ZERO)) {
1361
- const bankAccount = this.getBankAccount(bankBalance.bankIndex);
1362
- bankAccountMap.set(bankBalance.bankIndex.toNumber(), {
1363
- pubkey: bankAccount.pubkey,
1820
+ for (const spotPosition of counterPartyUserAccount.spotPositions) {
1821
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1822
+ const spotMarket = this.getSpotMarketAccount(spotPosition.marketIndex);
1823
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
1824
+ pubkey: spotMarket.pubkey,
1364
1825
  isSigner: false,
1365
1826
  isWritable: false,
1366
1827
  });
1367
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1368
- oracleAccountMap.set(bankAccount.oracle.toString(), {
1369
- pubkey: bankAccount.oracle,
1828
+ if (!spotMarket.oracle.equals(web3_js_1.PublicKey.default)) {
1829
+ oracleAccountMap.set(spotMarket.oracle.toString(), {
1830
+ pubkey: spotMarket.oracle,
1370
1831
  isSigner: false,
1371
1832
  isWritable: false,
1372
1833
  });
1373
1834
  }
1374
1835
  }
1375
1836
  }
1376
- for (const position of counterPartyUserAccount.positions) {
1837
+ for (const position of counterPartyUserAccount.perpPositions) {
1377
1838
  if (!(0, position_1.positionIsAvailable)(position)) {
1378
- const market = this.getMarketAccount(position.marketIndex);
1839
+ const market = this.getPerpMarketAccount(position.marketIndex);
1379
1840
  marketAccountMap.set(position.marketIndex.toNumber(), {
1380
1841
  pubkey: market.pubkey,
1381
1842
  isWritable: false,
@@ -1397,7 +1858,7 @@ class ClearingHouse {
1397
1858
  // if cache has more recent slot than user positions account slot, add market to remaining accounts
1398
1859
  // otherwise remove from slot
1399
1860
  if (slot > lastUserPositionsSlot) {
1400
- const marketAccount = this.getMarketAccount(marketIndexNum);
1861
+ const marketAccount = this.getPerpMarketAccount(marketIndexNum);
1401
1862
  marketAccountMap.set(marketIndexNum, {
1402
1863
  pubkey: marketAccount.pubkey,
1403
1864
  isSigner: false,
@@ -1413,26 +1874,26 @@ class ClearingHouse {
1413
1874
  this.marketLastSlotCache.delete(marketIndexNum);
1414
1875
  }
1415
1876
  }
1416
- for (const bankBalance of userAccount.bankBalances) {
1417
- if (!bankBalance.balance.eq(numericConstants_1.ZERO)) {
1418
- const bankAccount = this.getBankAccount(bankBalance.bankIndex);
1419
- bankAccountMap.set(bankBalance.bankIndex.toNumber(), {
1420
- pubkey: bankAccount.pubkey,
1877
+ for (const spotPosition of userAccount.spotPositions) {
1878
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1879
+ const spotMarket = this.getSpotMarketAccount(spotPosition.marketIndex);
1880
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
1881
+ pubkey: spotMarket.pubkey,
1421
1882
  isSigner: false,
1422
1883
  isWritable: false,
1423
1884
  });
1424
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1425
- oracleAccountMap.set(bankAccount.oracle.toString(), {
1426
- pubkey: bankAccount.oracle,
1885
+ if (!spotMarket.oracle.equals(web3_js_1.PublicKey.default)) {
1886
+ oracleAccountMap.set(spotMarket.oracle.toString(), {
1887
+ pubkey: spotMarket.oracle,
1427
1888
  isSigner: false,
1428
1889
  isWritable: false,
1429
1890
  });
1430
1891
  }
1431
1892
  }
1432
1893
  }
1433
- for (const position of userAccount.positions) {
1894
+ for (const position of userAccount.perpPositions) {
1434
1895
  if (!(0, position_1.positionIsAvailable)(position)) {
1435
- const market = this.getMarketAccount(position.marketIndex);
1896
+ const market = this.getPerpMarketAccount(position.marketIndex);
1436
1897
  marketAccountMap.set(position.marketIndex.toNumber(), {
1437
1898
  pubkey: market.pubkey,
1438
1899
  isWritable: false,
@@ -1445,8 +1906,8 @@ class ClearingHouse {
1445
1906
  });
1446
1907
  }
1447
1908
  }
1448
- if (params.writableMarketIndex) {
1449
- const market = this.getMarketAccount(params.writableMarketIndex);
1909
+ if (params.writablePerpMarketIndex) {
1910
+ const market = this.getPerpMarketAccount(params.writablePerpMarketIndex);
1450
1911
  marketAccountMap.set(market.marketIndex.toNumber(), {
1451
1912
  pubkey: market.pubkey,
1452
1913
  isSigner: false,
@@ -1458,17 +1919,17 @@ class ClearingHouse {
1458
1919
  isWritable: false,
1459
1920
  });
1460
1921
  }
1461
- if (params.writableBankIndexes) {
1462
- for (const writableBankIndex of params.writableBankIndexes) {
1463
- const bank = this.getBankAccount(writableBankIndex);
1464
- bankAccountMap.set(bank.bankIndex.toNumber(), {
1465
- pubkey: bank.pubkey,
1922
+ if (params.writableSpotMarketIndexes) {
1923
+ for (const writableSpotMarketIndex of params.writableSpotMarketIndexes) {
1924
+ const spotMarketAccount = this.getSpotMarketAccount(writableSpotMarketIndex);
1925
+ spotMarketAccountMap.set(spotMarketAccount.marketIndex.toNumber(), {
1926
+ pubkey: spotMarketAccount.pubkey,
1466
1927
  isSigner: false,
1467
1928
  isWritable: true,
1468
1929
  });
1469
- if (!bank.oracle.equals(web3_js_1.PublicKey.default)) {
1470
- oracleAccountMap.set(bank.oracle.toString(), {
1471
- pubkey: bank.oracle,
1930
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1931
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1932
+ pubkey: spotMarketAccount.oracle,
1472
1933
  isSigner: false,
1473
1934
  isWritable: false,
1474
1935
  });
@@ -1477,7 +1938,7 @@ class ClearingHouse {
1477
1938
  }
1478
1939
  return [
1479
1940
  ...oracleAccountMap.values(),
1480
- ...bankAccountMap.values(),
1941
+ ...spotMarketAccountMap.values(),
1481
1942
  ...marketAccountMap.values(),
1482
1943
  ];
1483
1944
  }
@@ -1500,7 +1961,7 @@ class ClearingHouse {
1500
1961
  }
1501
1962
  async getSettleFundingPaymentIx(userAccount) {
1502
1963
  const user = (await this.program.account.user.fetch(userAccount));
1503
- const userPositions = user.positions;
1964
+ const userPositions = user.perpPositions;
1504
1965
  const remainingAccounts = [];
1505
1966
  for (const position of userPositions) {
1506
1967
  if (!(0, position_1.positionIsAvailable)(position)) {
@@ -1524,20 +1985,20 @@ class ClearingHouse {
1524
1985
  this.eventEmitter.emit(eventName, data);
1525
1986
  }
1526
1987
  getOracleDataForMarket(marketIndex) {
1527
- const oracleKey = this.getMarketAccount(marketIndex).amm.oracle;
1988
+ const oracleKey = this.getPerpMarketAccount(marketIndex).amm.oracle;
1528
1989
  const oracleData = this.getOraclePriceDataAndSlot(oracleKey).data;
1529
1990
  return oracleData;
1530
1991
  }
1531
- async initializeInsuranceFundStake(bankIndex) {
1532
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getInitializeInsuranceFundStakeIx(bankIndex)), [], this.opts);
1992
+ async initializeInsuranceFundStake(marketIndex) {
1993
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getInitializeInsuranceFundStakeIx(marketIndex)), [], this.opts);
1533
1994
  return txSig;
1534
1995
  }
1535
- async getInitializeInsuranceFundStakeIx(bankIndex) {
1536
- const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, bankIndex);
1537
- return await this.program.instruction.initializeInsuranceFundStake(bankIndex, {
1996
+ async getInitializeInsuranceFundStakeIx(marketIndex) {
1997
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
1998
+ return await this.program.instruction.initializeInsuranceFundStake(marketIndex, {
1538
1999
  accounts: {
1539
2000
  insuranceFundStake: ifStakeAccountPublicKey,
1540
- bank: this.getBankAccount(bankIndex).pubkey,
2001
+ spotMarket: this.getSpotMarketAccount(marketIndex).pubkey,
1541
2002
  userStats: this.getUserStatsAccountPublicKey(),
1542
2003
  authority: this.wallet.publicKey,
1543
2004
  payer: this.wallet.publicKey,
@@ -1547,103 +2008,125 @@ class ClearingHouse {
1547
2008
  },
1548
2009
  });
1549
2010
  }
1550
- async addInsuranceFundStake(bankIndex, amount, collateralAccountPublicKey) {
1551
- const bank = this.getBankAccount(bankIndex);
1552
- const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, bankIndex);
2011
+ async addInsuranceFundStake(marketIndex, amount, collateralAccountPublicKey) {
2012
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
2013
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
1553
2014
  const remainingAccounts = this.getRemainingAccounts({
1554
- writableBankIndex: bankIndex,
2015
+ writableSpotMarketIndex: marketIndex,
1555
2016
  });
1556
- return await this.program.rpc.addInsuranceFundStake(bankIndex, amount, {
2017
+ return await this.program.rpc.addInsuranceFundStake(marketIndex, amount, {
1557
2018
  accounts: {
1558
2019
  state: await this.getStatePublicKey(),
1559
- bank: bank.pubkey,
2020
+ spotMarket: spotMarket.pubkey,
1560
2021
  insuranceFundStake: ifStakeAccountPublicKey,
1561
2022
  userStats: this.getUserStatsAccountPublicKey(),
1562
2023
  authority: this.wallet.publicKey,
1563
- insuranceFundVault: bank.insuranceFundVault,
2024
+ insuranceFundVault: spotMarket.insuranceFundVault,
1564
2025
  userTokenAccount: collateralAccountPublicKey,
1565
2026
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1566
2027
  },
1567
2028
  remainingAccounts,
1568
2029
  });
1569
2030
  }
1570
- async requestRemoveInsuranceFundStake(bankIndex, amount) {
1571
- const bank = this.getBankAccount(bankIndex);
1572
- const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, bankIndex);
2031
+ async requestRemoveInsuranceFundStake(marketIndex, amount) {
2032
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
2033
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
1573
2034
  const remainingAccounts = this.getRemainingAccounts({
1574
- writableBankIndex: bankIndex,
2035
+ writableSpotMarketIndex: marketIndex,
1575
2036
  });
1576
- return await this.program.rpc.requestRemoveInsuranceFundStake(bankIndex, amount, {
2037
+ return await this.program.rpc.requestRemoveInsuranceFundStake(marketIndex, amount, {
1577
2038
  accounts: {
1578
2039
  state: await this.getStatePublicKey(),
1579
- bank: bank.pubkey,
2040
+ spotMarket: spotMarketAccount.pubkey,
1580
2041
  insuranceFundStake: ifStakeAccountPublicKey,
1581
2042
  userStats: this.getUserStatsAccountPublicKey(),
1582
2043
  authority: this.wallet.publicKey,
1583
- insuranceFundVault: bank.insuranceFundVault,
2044
+ insuranceFundVault: spotMarketAccount.insuranceFundVault,
1584
2045
  // userTokenAccount: collateralAccountPublicKey,
1585
2046
  // tokenProgram: TOKEN_PROGRAM_ID,
1586
2047
  },
1587
2048
  remainingAccounts,
1588
2049
  });
1589
2050
  }
1590
- async cancelRequestRemoveInsuranceFundStake(bankIndex) {
1591
- const bank = this.getBankAccount(bankIndex);
1592
- const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, bankIndex);
2051
+ async cancelRequestRemoveInsuranceFundStake(marketIndex) {
2052
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
2053
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
1593
2054
  const remainingAccounts = this.getRemainingAccounts({
1594
- writableBankIndex: bankIndex,
2055
+ writableSpotMarketIndex: marketIndex,
1595
2056
  });
1596
- return await this.program.rpc.cancelRequestRemoveInsuranceFundStake(bankIndex, {
2057
+ return await this.program.rpc.cancelRequestRemoveInsuranceFundStake(marketIndex, {
1597
2058
  accounts: {
1598
2059
  state: await this.getStatePublicKey(),
1599
- bank: bank.pubkey,
2060
+ spotMarket: spotMarketAccount.pubkey,
1600
2061
  insuranceFundStake: ifStakeAccountPublicKey,
1601
2062
  userStats: this.getUserStatsAccountPublicKey(),
1602
2063
  authority: this.wallet.publicKey,
1603
- insuranceFundVault: bank.insuranceFundVault,
2064
+ insuranceFundVault: spotMarketAccount.insuranceFundVault,
1604
2065
  // userTokenAccount: collateralAccountPublicKey,
1605
2066
  // tokenProgram: TOKEN_PROGRAM_ID,
1606
2067
  },
1607
2068
  remainingAccounts,
1608
2069
  });
1609
2070
  }
1610
- async removeInsuranceFundStake(bankIndex, collateralAccountPublicKey) {
1611
- const bank = this.getBankAccount(bankIndex);
1612
- const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, bankIndex);
2071
+ async removeInsuranceFundStake(marketIndex, collateralAccountPublicKey) {
2072
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
2073
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
1613
2074
  const remainingAccounts = this.getRemainingAccounts({
1614
- writableBankIndex: bankIndex,
2075
+ writableSpotMarketIndex: marketIndex,
1615
2076
  });
1616
- return await this.program.rpc.removeInsuranceFundStake(bankIndex, {
2077
+ return await this.program.rpc.removeInsuranceFundStake(marketIndex, {
1617
2078
  accounts: {
1618
2079
  state: await this.getStatePublicKey(),
1619
- bank: bank.pubkey,
2080
+ spotMarket: spotMarketAccount.pubkey,
1620
2081
  insuranceFundStake: ifStakeAccountPublicKey,
1621
2082
  userStats: this.getUserStatsAccountPublicKey(),
1622
2083
  authority: this.wallet.publicKey,
1623
- insuranceFundVault: bank.insuranceFundVault,
1624
- insuranceFundVaultAuthority: bank.insuranceFundVaultAuthority,
2084
+ insuranceFundVault: spotMarketAccount.insuranceFundVault,
2085
+ clearingHouseSigner: this.getSignerPublicKey(),
1625
2086
  userTokenAccount: collateralAccountPublicKey,
1626
2087
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1627
2088
  },
1628
2089
  remainingAccounts,
1629
2090
  });
1630
2091
  }
1631
- async settleRevenueToInsuranceFund(bankIndex) {
1632
- const bank = this.getBankAccount(bankIndex);
2092
+ async settleRevenueToInsuranceFund(marketIndex) {
2093
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1633
2094
  const remainingAccounts = this.getRemainingAccounts({
1634
- writableBankIndex: bankIndex,
2095
+ writableSpotMarketIndex: marketIndex,
1635
2096
  });
1636
- return await this.program.rpc.settleRevenueToInsuranceFund(bankIndex, {
2097
+ return await this.program.rpc.settleRevenueToInsuranceFund(marketIndex, {
1637
2098
  accounts: {
1638
2099
  state: await this.getStatePublicKey(),
1639
- bank: bank.pubkey,
1640
- bankVault: bank.vault,
1641
- bankVaultAuthority: bank.vaultAuthority,
1642
- insuranceFundVault: bank.insuranceFundVault,
2100
+ spotMarket: spotMarketAccount.pubkey,
2101
+ spotMarketVault: spotMarketAccount.vault,
2102
+ clearingHouseSigner: this.getSignerPublicKey(),
2103
+ insuranceFundVault: spotMarketAccount.insuranceFundVault,
1643
2104
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1644
2105
  },
1645
2106
  remainingAccounts,
1646
2107
  });
1647
2108
  }
2109
+ async resolvePerpPnlDeficit(spotMarketIndex, perpMarketIndex) {
2110
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getResolvePerpPnlDeficitIx(spotMarketIndex, perpMarketIndex)), [], this.opts);
2111
+ return txSig;
2112
+ }
2113
+ async getResolvePerpPnlDeficitIx(spotMarketIndex, perpMarketIndex) {
2114
+ const remainingAccounts = this.getRemainingAccounts({
2115
+ writablePerpMarketIndex: perpMarketIndex,
2116
+ writableSpotMarketIndex: spotMarketIndex,
2117
+ });
2118
+ const spotMarket = this.getSpotMarketAccount(spotMarketIndex);
2119
+ return await this.program.instruction.resolvePerpPnlDeficit(spotMarketIndex, perpMarketIndex, {
2120
+ accounts: {
2121
+ state: await this.getStatePublicKey(),
2122
+ authority: this.wallet.publicKey,
2123
+ spotMarketVault: spotMarket.vault,
2124
+ insuranceFundVault: spotMarket.insuranceFundVault,
2125
+ clearingHouseSigner: this.getSignerPublicKey(),
2126
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
2127
+ },
2128
+ remainingAccounts: remainingAccounts,
2129
+ });
2130
+ }
1648
2131
  }
1649
2132
  exports.ClearingHouse = ClearingHouse;