@drift-labs/sdk 0.2.0-master.25 → 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 (184) 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 +7 -6
  7. package/lib/addresses/pda.js +31 -27
  8. package/lib/admin.d.ts +9 -6
  9. package/lib/admin.js +83 -42
  10. package/lib/clearingHouse.d.ts +69 -42
  11. package/lib/clearingHouse.js +753 -277
  12. package/lib/clearingHouseConfig.d.ts +2 -2
  13. package/lib/clearingHouseUser.d.ts +16 -16
  14. package/lib/clearingHouseUser.js +139 -119
  15. package/lib/config.d.ts +7 -7
  16. package/lib/config.js +20 -20
  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/types.d.ts +2 -1
  24. package/lib/events/types.js +1 -0
  25. package/lib/examples/makeTradeExample.js +7 -7
  26. package/lib/idl/clearing_house.json +1008 -279
  27. package/lib/index.d.ts +5 -3
  28. package/lib/index.js +5 -3
  29. package/lib/math/amm.d.ts +2 -2
  30. package/lib/math/amm.js +1 -1
  31. package/lib/math/funding.d.ts +6 -6
  32. package/lib/math/funding.js +2 -1
  33. package/lib/math/margin.d.ts +4 -4
  34. package/lib/math/margin.js +18 -11
  35. package/lib/math/market.d.ts +10 -9
  36. package/lib/math/market.js +29 -6
  37. package/lib/math/oracles.d.ts +2 -1
  38. package/lib/math/oracles.js +11 -1
  39. package/lib/math/orders.d.ts +5 -5
  40. package/lib/math/position.d.ts +13 -13
  41. package/lib/math/position.js +19 -19
  42. package/lib/math/spotBalance.d.ts +19 -0
  43. package/lib/math/spotBalance.js +176 -0
  44. package/lib/math/spotMarket.d.ts +4 -0
  45. package/lib/math/spotMarket.js +8 -0
  46. package/lib/math/spotPosition.d.ts +2 -0
  47. package/lib/math/spotPosition.js +8 -0
  48. package/lib/math/state.js +2 -2
  49. package/lib/math/trade.d.ts +4 -4
  50. package/lib/orderParams.d.ts +4 -4
  51. package/lib/orderParams.js +12 -4
  52. package/lib/serum/serumSubscriber.d.ts +23 -0
  53. package/lib/serum/serumSubscriber.js +41 -0
  54. package/lib/serum/types.d.ts +11 -0
  55. package/lib/serum/types.js +2 -0
  56. package/lib/tx/retryTxSender.d.ts +1 -1
  57. package/lib/tx/retryTxSender.js +4 -2
  58. package/lib/tx/types.d.ts +1 -1
  59. package/lib/types.d.ts +123 -33
  60. package/lib/types.js +31 -9
  61. package/my-script/.env +7 -0
  62. package/my-script/getUserStats.ts +106 -0
  63. package/my-script/multiConnections.ts +119 -0
  64. package/my-script/test-regex.ts +11 -0
  65. package/my-script/utils.ts +52 -0
  66. package/package.json +1 -1
  67. package/src/accounts/bulkAccountLoader.js +249 -0
  68. package/src/accounts/bulkUserStatsSubscription.js +75 -0
  69. package/src/accounts/bulkUserSubscription.js +75 -0
  70. package/src/accounts/fetch.js +92 -0
  71. package/src/accounts/pollingClearingHouseAccountSubscriber.js +465 -0
  72. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +38 -38
  73. package/src/accounts/pollingOracleSubscriber.js +156 -0
  74. package/src/accounts/pollingTokenAccountSubscriber.js +141 -0
  75. package/src/accounts/pollingUserAccountSubscriber.js +208 -0
  76. package/src/accounts/pollingUserStatsAccountSubscriber.js +208 -0
  77. package/src/accounts/types.js +28 -0
  78. package/src/accounts/types.ts +11 -9
  79. package/src/accounts/utils.js +7 -0
  80. package/src/accounts/webSocketAccountSubscriber.js +138 -0
  81. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +433 -0
  82. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +59 -52
  83. package/src/accounts/webSocketUserAccountSubscriber.js +113 -0
  84. package/src/accounts/webSocketUserStatsAccountSubsriber.js +113 -0
  85. package/src/addresses/pda.js +186 -0
  86. package/src/addresses/pda.ts +49 -44
  87. package/src/admin.js +1284 -0
  88. package/src/admin.ts +140 -47
  89. package/src/assert/assert.js +1 -1
  90. package/src/clearingHouse.js +3433 -0
  91. package/src/clearingHouse.ts +1083 -378
  92. package/src/clearingHouseConfig.js +2 -0
  93. package/src/clearingHouseConfig.ts +2 -2
  94. package/src/clearingHouseUser.js +874 -0
  95. package/src/clearingHouseUser.ts +232 -168
  96. package/src/clearingHouseUserConfig.js +2 -0
  97. package/src/clearingHouseUserStats.js +115 -0
  98. package/src/clearingHouseUserStatsConfig.js +2 -0
  99. package/src/config.js +80 -0
  100. package/src/config.ts +29 -29
  101. package/src/constants/numericConstants.js +18 -11
  102. package/src/constants/numericConstants.ts +17 -15
  103. package/{lib/constants/markets.js → src/constants/perpMarkets.js} +11 -11
  104. package/src/constants/{markets.ts → perpMarkets.ts} +5 -5
  105. package/src/constants/spotMarkets.js +51 -0
  106. package/src/constants/{banks.ts → spotMarkets.ts} +19 -19
  107. package/src/events/eventList.js +66 -23
  108. package/src/events/eventSubscriber.js +202 -0
  109. package/src/events/fetchLogs.js +117 -0
  110. package/src/events/pollingLogProvider.js +113 -0
  111. package/src/events/sort.js +41 -0
  112. package/src/events/txEventCache.js +22 -19
  113. package/src/events/types.js +25 -0
  114. package/src/events/types.ts +3 -0
  115. package/src/events/webSocketLogProvider.js +76 -0
  116. package/src/examples/makeTradeExample.ts +10 -8
  117. package/src/factory/bigNum.js +183 -180
  118. package/src/factory/oracleClient.js +9 -9
  119. package/src/idl/clearing_house.json +1008 -279
  120. package/src/index.js +75 -0
  121. package/src/index.ts +5 -3
  122. package/src/math/amm.js +422 -0
  123. package/src/math/amm.ts +6 -3
  124. package/src/math/auction.js +10 -10
  125. package/src/math/conversion.js +4 -3
  126. package/src/math/funding.js +223 -175
  127. package/src/math/funding.ts +7 -7
  128. package/src/math/insurance.js +27 -0
  129. package/src/math/margin.js +77 -0
  130. package/src/math/margin.ts +34 -23
  131. package/src/math/market.js +105 -0
  132. package/src/math/market.ts +71 -19
  133. package/src/math/oracles.js +40 -10
  134. package/src/math/oracles.ts +18 -1
  135. package/src/math/orders.js +153 -0
  136. package/src/math/orders.ts +5 -5
  137. package/src/math/position.js +172 -0
  138. package/src/math/position.ts +31 -31
  139. package/src/math/repeg.js +40 -40
  140. package/src/math/spotBalance.js +176 -0
  141. package/src/math/spotBalance.ts +290 -0
  142. package/src/math/spotMarket.js +8 -0
  143. package/src/math/spotMarket.ts +9 -0
  144. package/src/math/spotPosition.js +8 -0
  145. package/src/math/spotPosition.ts +6 -0
  146. package/src/math/state.ts +2 -2
  147. package/src/math/trade.js +81 -74
  148. package/src/math/trade.ts +4 -4
  149. package/src/math/utils.js +8 -7
  150. package/src/oracles/oracleClientCache.js +10 -9
  151. package/src/oracles/pythClient.js +52 -17
  152. package/src/oracles/quoteAssetOracleClient.js +44 -13
  153. package/src/oracles/switchboardClient.js +69 -37
  154. package/src/oracles/types.js +1 -1
  155. package/src/orderParams.js +14 -6
  156. package/src/orderParams.ts +16 -8
  157. package/src/serum/serumSubscriber.js +102 -0
  158. package/src/serum/serumSubscriber.ts +80 -0
  159. package/src/serum/types.js +2 -0
  160. package/src/serum/types.ts +13 -0
  161. package/src/slot/SlotSubscriber.js +67 -20
  162. package/src/token/index.js +4 -4
  163. package/src/tokenFaucet.js +288 -154
  164. package/src/tx/retryTxSender.js +280 -0
  165. package/src/tx/retryTxSender.ts +5 -2
  166. package/src/tx/types.js +1 -1
  167. package/src/tx/types.ts +2 -1
  168. package/src/tx/utils.js +7 -6
  169. package/src/types.js +216 -0
  170. package/src/types.ts +110 -33
  171. package/src/userName.js +5 -5
  172. package/src/util/computeUnits.js +46 -11
  173. package/src/util/promiseTimeout.js +5 -5
  174. package/src/util/tps.js +46 -12
  175. package/src/wallet.js +55 -18
  176. package/lib/math/bankBalance.d.ts +0 -15
  177. package/lib/math/bankBalance.js +0 -150
  178. package/src/addresses/marketAddresses.js +0 -26
  179. package/src/constants/banks.js +0 -42
  180. package/src/examples/makeTradeExample.js +0 -80
  181. package/src/math/bankBalance.ts +0 -258
  182. package/src/math/state.js +0 -15
  183. package/src/math/utils.js.map +0 -1
  184. 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);
@@ -169,27 +174,30 @@ class ClearingHouse {
169
174
  getStateAccount() {
170
175
  return this.accountSubscriber.getStateAccountAndSlot().data;
171
176
  }
172
- getMarketAccount(marketIndex) {
177
+ getPerpMarketAccount(marketIndex) {
173
178
  var _a;
174
179
  marketIndex = marketIndex instanceof anchor_1.BN ? marketIndex : new anchor_1.BN(marketIndex);
175
180
  return (_a = this.accountSubscriber.getMarketAccountAndSlot(marketIndex)) === null || _a === void 0 ? void 0 : _a.data;
176
181
  }
177
- getMarketAccounts() {
182
+ getPerpMarketAccounts() {
178
183
  return this.accountSubscriber
179
184
  .getMarketAccountsAndSlots()
180
185
  .map((value) => value.data);
181
186
  }
182
- getBankAccount(bankIndex) {
183
- bankIndex = bankIndex instanceof anchor_1.BN ? bankIndex : new anchor_1.BN(bankIndex);
184
- 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;
185
190
  }
186
- getQuoteAssetBankAccount() {
187
- return this.accountSubscriber.getBankAccountAndSlot(numericConstants_1.QUOTE_ASSET_BANK_INDEX)
188
- .data;
191
+ getQuoteSpotMarketAccount() {
192
+ return this.accountSubscriber.getSpotMarketAccountAndSlot(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).data;
189
193
  }
190
194
  getOraclePriceDataAndSlot(oraclePublicKey) {
191
195
  return this.accountSubscriber.getOraclePriceDataAndSlot(oraclePublicKey);
192
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
+ }
193
201
  /**
194
202
  * Update the wallet to use for clearing house transactions and linked user account
195
203
  * @param newWallet
@@ -279,6 +287,15 @@ class ClearingHouse {
279
287
  },
280
288
  });
281
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
+ }
282
299
  getUser(userId) {
283
300
  userId = userId !== null && userId !== void 0 ? userId : this.activeUserId;
284
301
  if (!this.users.has(userId)) {
@@ -308,14 +325,14 @@ class ClearingHouse {
308
325
  getUserAccountAndSlot(userId) {
309
326
  return this.getUser(userId).getUserAccountAndSlot();
310
327
  }
311
- getUserBankBalance(bankIndex) {
312
- const bankIndexBN = bankIndex instanceof anchor_1.BN ? bankIndex : new anchor_1.BN(bankIndex);
313
- 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));
314
331
  }
315
332
  getQuoteAssetTokenAmount() {
316
- const bank = this.getBankAccount(numericConstants_1.QUOTE_ASSET_BANK_INDEX);
317
- const userBankBalance = this.getUserBankBalance(numericConstants_1.QUOTE_ASSET_BANK_INDEX);
318
- 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);
319
336
  }
320
337
  getRemainingAccounts(params) {
321
338
  const userAccountAndSlot = this.getUserAccountAndSlot();
@@ -324,14 +341,14 @@ class ClearingHouse {
324
341
  }
325
342
  const { data: userAccount, slot: lastUserPositionsSlot } = userAccountAndSlot;
326
343
  const oracleAccountMap = new Map();
327
- const bankAccountMap = new Map();
328
- const marketAccountMap = new Map();
344
+ const spotMarketAccountMap = new Map();
345
+ const perpMarketAccountMap = new Map();
329
346
  for (const [marketIndexNum, slot] of this.marketLastSlotCache.entries()) {
330
347
  // if cache has more recent slot than user positions account slot, add market to remaining accounts
331
348
  // otherwise remove from slot
332
349
  if (slot > lastUserPositionsSlot) {
333
- const marketAccount = this.getMarketAccount(marketIndexNum);
334
- marketAccountMap.set(marketIndexNum, {
350
+ const marketAccount = this.getPerpMarketAccount(marketIndexNum);
351
+ perpMarketAccountMap.set(marketIndexNum, {
335
352
  pubkey: marketAccount.pubkey,
336
353
  isSigner: false,
337
354
  isWritable: false,
@@ -346,11 +363,11 @@ class ClearingHouse {
346
363
  this.marketLastSlotCache.delete(marketIndexNum);
347
364
  }
348
365
  }
349
- for (const position of userAccount.positions) {
366
+ for (const position of userAccount.perpPositions) {
350
367
  if (!(0, position_1.positionIsAvailable)(position)) {
351
368
  const marketIndexNum = position.marketIndex.toNumber();
352
- const marketAccount = this.getMarketAccount(marketIndexNum);
353
- marketAccountMap.set(marketIndexNum, {
369
+ const marketAccount = this.getPerpMarketAccount(marketIndexNum);
370
+ perpMarketAccountMap.set(marketIndexNum, {
354
371
  pubkey: marketAccount.pubkey,
355
372
  isSigner: false,
356
373
  isWritable: false,
@@ -362,9 +379,9 @@ class ClearingHouse {
362
379
  });
363
380
  }
364
381
  }
365
- if (params.readableMarketIndex) {
366
- const marketAccount = this.getMarketAccount(params.readableMarketIndex.toNumber());
367
- marketAccountMap.set(params.readableMarketIndex.toNumber(), {
382
+ if (params.readablePerpMarketIndex) {
383
+ const marketAccount = this.getPerpMarketAccount(params.readablePerpMarketIndex.toNumber());
384
+ perpMarketAccountMap.set(params.readablePerpMarketIndex.toNumber(), {
368
385
  pubkey: marketAccount.pubkey,
369
386
  isSigner: false,
370
387
  isWritable: true,
@@ -375,9 +392,9 @@ class ClearingHouse {
375
392
  isWritable: false,
376
393
  });
377
394
  }
378
- if (params.writableMarketIndex) {
379
- const marketAccount = this.getMarketAccount(params.writableMarketIndex.toNumber());
380
- marketAccountMap.set(params.writableMarketIndex.toNumber(), {
395
+ if (params.writablePerpMarketIndex) {
396
+ const marketAccount = this.getPerpMarketAccount(params.writablePerpMarketIndex.toNumber());
397
+ perpMarketAccountMap.set(params.writablePerpMarketIndex.toNumber(), {
381
398
  pubkey: marketAccount.pubkey,
382
399
  isSigner: false,
383
400
  isWritable: true,
@@ -388,33 +405,48 @@ class ClearingHouse {
388
405
  isWritable: false,
389
406
  });
390
407
  }
391
- for (const userBankBalance of userAccount.bankBalances) {
392
- if (!userBankBalance.balance.eq(numericConstants_1.ZERO)) {
393
- const bankAccount = this.getBankAccount(userBankBalance.bankIndex);
394
- bankAccountMap.set(userBankBalance.bankIndex.toNumber(), {
395
- 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,
396
413
  isSigner: false,
397
414
  isWritable: false,
398
415
  });
399
- if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
400
- oracleAccountMap.set(bankAccount.oracle.toString(), {
401
- pubkey: bankAccount.oracle,
416
+ if (!spotMarketAccount.marketIndex.eq(numericConstants_1.ZERO)) {
417
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
418
+ pubkey: spotMarketAccount.oracle,
402
419
  isSigner: false,
403
420
  isWritable: false,
404
421
  });
405
422
  }
406
423
  }
407
424
  }
408
- if (params.writableBankIndex) {
409
- const bankAccount = this.getBankAccount(params.writableBankIndex);
410
- bankAccountMap.set(params.writableBankIndex.toNumber(), {
411
- 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,
412
444
  isSigner: false,
413
445
  isWritable: true,
414
446
  });
415
- if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
416
- oracleAccountMap.set(bankAccount.oracle.toString(), {
417
- pubkey: bankAccount.oracle,
447
+ if (!spotMarketAccount.marketIndex.eq(numericConstants_1.ZERO)) {
448
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
449
+ pubkey: spotMarketAccount.oracle,
418
450
  isSigner: false,
419
451
  isWritable: false,
420
452
  });
@@ -422,8 +454,8 @@ class ClearingHouse {
422
454
  }
423
455
  return [
424
456
  ...oracleAccountMap.values(),
425
- ...bankAccountMap.values(),
426
- ...marketAccountMap.values(),
457
+ ...spotMarketAccountMap.values(),
458
+ ...perpMarketAccountMap.values(),
427
459
  ];
428
460
  }
429
461
  getOrder(orderId) {
@@ -435,13 +467,13 @@ class ClearingHouse {
435
467
  var _a;
436
468
  return (_a = this.getUserAccount()) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.userOrderId === userOrderId);
437
469
  }
438
- async deposit(amount, bankIndex, collateralAccountPublicKey, userId, reduceOnly = false) {
470
+ async deposit(amount, marketIndex, collateralAccountPublicKey, userId, reduceOnly = false) {
439
471
  const tx = new web3_js_1.Transaction();
440
472
  const additionalSigners = [];
441
- const bank = this.getBankAccount(bankIndex);
442
- 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);
443
475
  const authority = this.wallet.publicKey;
444
- const createWSOLTokenAccount = isSolBank && collateralAccountPublicKey.equals(authority);
476
+ const createWSOLTokenAccount = isSolMarket && collateralAccountPublicKey.equals(authority);
445
477
  if (createWSOLTokenAccount) {
446
478
  const { ixs, signers, pubkey } = await this.getWrappedSolAccountCreationIxs(amount);
447
479
  collateralAccountPublicKey = pubkey;
@@ -450,7 +482,7 @@ class ClearingHouse {
450
482
  });
451
483
  signers.forEach((signer) => additionalSigners.push(signer));
452
484
  }
453
- const depositCollateralIx = await this.getDepositInstruction(amount, bankIndex, collateralAccountPublicKey, userId, reduceOnly, true);
485
+ const depositCollateralIx = await this.getDepositInstruction(amount, marketIndex, collateralAccountPublicKey, userId, reduceOnly, true);
454
486
  tx.add(depositCollateralIx);
455
487
  // Close the wrapped sol account at the end of the transaction
456
488
  if (createWSOLTokenAccount) {
@@ -459,37 +491,37 @@ class ClearingHouse {
459
491
  const { txSig } = await this.txSender.send(tx, additionalSigners, this.opts);
460
492
  return txSig;
461
493
  }
462
- async getDepositInstruction(amount, bankIndex, userTokenAccount, userId, reduceOnly = false, userInitialized = true) {
494
+ async getDepositInstruction(amount, marketIndex, userTokenAccount, userId, reduceOnly = false, userInitialized = true) {
463
495
  const userAccountPublicKey = userId
464
496
  ? await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, userId)
465
497
  : await this.getUserAccountPublicKey();
466
498
  let remainingAccounts = [];
467
499
  if (userInitialized) {
468
500
  remainingAccounts = this.getRemainingAccounts({
469
- writableBankIndex: bankIndex,
501
+ writableSpotMarketIndex: marketIndex,
470
502
  });
471
503
  }
472
504
  else {
473
- const bankAccount = this.getBankAccount(bankIndex);
474
- 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)) {
475
507
  remainingAccounts.push({
476
- pubkey: bankAccount.oracle,
508
+ pubkey: spotMarketAccount.oracle,
477
509
  isSigner: false,
478
510
  isWritable: false,
479
511
  });
480
512
  }
481
513
  remainingAccounts.push({
482
- pubkey: bankAccount.pubkey,
514
+ pubkey: spotMarketAccount.pubkey,
483
515
  isSigner: false,
484
516
  isWritable: true,
485
517
  });
486
518
  }
487
- const bank = this.getBankAccount(bankIndex);
488
- 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, {
489
521
  accounts: {
490
522
  state: await this.getStatePublicKey(),
491
- bank: bank.pubkey,
492
- bankVault: bank.vault,
523
+ spotMarket: spotMarketAccount.pubkey,
524
+ spotMarketVault: spotMarketAccount.vault,
493
525
  user: userAccountPublicKey,
494
526
  userStats: this.getUserStatsAccountPublicKey(),
495
527
  userTokenAccount: userTokenAccount,
@@ -509,7 +541,7 @@ class ClearingHouse {
509
541
  return false;
510
542
  }
511
543
  }
512
- async getSolWithdrawalIxs(bankIndex, amount) {
544
+ async getSolWithdrawalIxs(marketIndex, amount) {
513
545
  const result = {
514
546
  ixs: [],
515
547
  signers: [],
@@ -525,7 +557,7 @@ class ClearingHouse {
525
557
  signers.forEach((ix) => {
526
558
  result.signers.push(ix);
527
559
  });
528
- const withdrawIx = await this.getWithdrawIx(amount, bankIndex, pubkey, true);
560
+ const withdrawIx = await this.getWithdrawIx(amount, marketIndex, pubkey, true);
529
561
  result.ixs.push(withdrawIx);
530
562
  result.ixs.push(spl_token_1.Token.createCloseAccountInstruction(spl_token_1.TOKEN_PROGRAM_ID, pubkey, authority, authority, []));
531
563
  return result;
@@ -547,7 +579,7 @@ class ClearingHouse {
547
579
  space: 165,
548
580
  programId: spl_token_1.TOKEN_PROGRAM_ID,
549
581
  }));
550
- 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));
551
583
  result.signers.push(wrappedSolAccount);
552
584
  return result;
553
585
  }
@@ -555,20 +587,20 @@ class ClearingHouse {
555
587
  * Creates the Clearing House User account for a user, and deposits some initial collateral
556
588
  * @param amount
557
589
  * @param userTokenAccount
558
- * @param bankIndex
590
+ * @param marketIndex
559
591
  * @param userId
560
592
  * @param name
561
593
  * @param fromUserId
562
594
  * @returns
563
595
  */
564
- 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) {
565
597
  const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(userId, name, referrerInfo);
566
598
  const additionalSigners = [];
567
- const bank = this.getBankAccount(bankIndex);
568
- 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);
569
601
  const tx = new web3_js_1.Transaction();
570
602
  const authority = this.wallet.publicKey;
571
- const createWSOLTokenAccount = isSolBank && userTokenAccount.equals(authority);
603
+ const createWSOLTokenAccount = isSolMarket && userTokenAccount.equals(authority);
572
604
  if (createWSOLTokenAccount) {
573
605
  const { ixs: startIxs, signers, pubkey, } = await this.getWrappedSolAccountCreationIxs(amount);
574
606
  userTokenAccount = pubkey;
@@ -578,8 +610,8 @@ class ClearingHouse {
578
610
  signers.forEach((signer) => additionalSigners.push(signer));
579
611
  }
580
612
  const depositCollateralIx = fromUserId != null
581
- ? await this.getTransferDepositIx(amount, bankIndex, fromUserId, userId)
582
- : 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);
583
615
  if (userId === 0) {
584
616
  tx.add(await this.getInitializeUserStatsIx());
585
617
  }
@@ -591,10 +623,10 @@ class ClearingHouse {
591
623
  const { txSig } = await this.txSender.send(tx, additionalSigners, this.opts);
592
624
  return [txSig, userAccountPublicKey];
593
625
  }
594
- 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) {
595
627
  const [associateTokenPublicKey, createAssociatedAccountIx, mintToIx] = await tokenFaucet.createAssociatedTokenAccountAndMintToInstructions(this.wallet.publicKey, amount);
596
628
  const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(userId, name, referrerInfo);
597
- const depositCollateralIx = await this.getDepositInstruction(amount, bankIndex, associateTokenPublicKey, userId, false, false);
629
+ const depositCollateralIx = await this.getDepositInstruction(amount, marketIndex, associateTokenPublicKey, userId, false, false);
598
630
  const tx = new web3_js_1.Transaction().add(createAssociatedAccountIx).add(mintToIx);
599
631
  if (userId === 0) {
600
632
  tx.add(await this.getInitializeUserStatsIx());
@@ -603,13 +635,13 @@ class ClearingHouse {
603
635
  const txSig = await this.program.provider.sendAndConfirm(tx, []);
604
636
  return [txSig, userAccountPublicKey];
605
637
  }
606
- async withdraw(amount, bankIndex, userTokenAccount, reduceOnly = false) {
638
+ async withdraw(amount, marketIndex, userTokenAccount, reduceOnly = false) {
607
639
  const tx = new web3_js_1.Transaction();
608
640
  const additionalSigners = [];
609
- const bank = this.getBankAccount(bankIndex);
610
- 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);
611
643
  const authority = this.wallet.publicKey;
612
- const createWSOLTokenAccount = isSolBank && userTokenAccount.equals(authority);
644
+ const createWSOLTokenAccount = isSolMarket && userTokenAccount.equals(authority);
613
645
  if (createWSOLTokenAccount) {
614
646
  const { ixs, signers, pubkey } = await this.getWrappedSolAccountCreationIxs(amount);
615
647
  userTokenAccount = pubkey;
@@ -618,7 +650,7 @@ class ClearingHouse {
618
650
  });
619
651
  signers.forEach((signer) => additionalSigners.push(signer));
620
652
  }
621
- const withdrawCollateral = await this.getWithdrawIx(amount, bank.bankIndex, userTokenAccount, reduceOnly);
653
+ const withdrawCollateral = await this.getWithdrawIx(amount, spotMarketAccount.marketIndex, userTokenAccount, reduceOnly);
622
654
  tx.add(withdrawCollateral);
623
655
  // Close the wrapped sol account at the end of the transaction
624
656
  if (createWSOLTokenAccount) {
@@ -627,17 +659,17 @@ class ClearingHouse {
627
659
  const { txSig } = await this.txSender.send(tx, additionalSigners, this.opts);
628
660
  return txSig;
629
661
  }
630
- async getWithdrawIx(amount, bankIndex, userTokenAccount, reduceOnly = false) {
662
+ async getWithdrawIx(amount, marketIndex, userTokenAccount, reduceOnly = false) {
631
663
  const userAccountPublicKey = await this.getUserAccountPublicKey();
632
664
  const remainingAccounts = this.getRemainingAccounts({
633
- writableBankIndex: bankIndex,
665
+ writableSpotMarketIndex: marketIndex,
634
666
  });
635
- const bank = this.getBankAccount(bankIndex);
636
- 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, {
637
669
  accounts: {
638
670
  state: await this.getStatePublicKey(),
639
- bank: bank.pubkey,
640
- bankVault: bank.vault,
671
+ spotMarket: spotMarketAccount.pubkey,
672
+ spotMarketVault: spotMarketAccount.vault,
641
673
  clearingHouseSigner: this.getSignerPublicKey(),
642
674
  user: userAccountPublicKey,
643
675
  userStats: this.getUserStatsAccountPublicKey(),
@@ -648,17 +680,17 @@ class ClearingHouse {
648
680
  remainingAccounts,
649
681
  });
650
682
  }
651
- async transferDeposit(amount, bankIndex, fromUserId, toUserId) {
652
- 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);
653
685
  return txSig;
654
686
  }
655
- async getTransferDepositIx(amount, bankIndex, fromUserId, toUserId) {
687
+ async getTransferDepositIx(amount, marketIndex, fromUserId, toUserId) {
656
688
  const fromUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, fromUserId);
657
689
  const toUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, toUserId);
658
690
  const remainingAccounts = this.getRemainingAccounts({
659
- writableBankIndex: bankIndex,
691
+ writableSpotMarketIndex: marketIndex,
660
692
  });
661
- return await this.program.instruction.transferDeposit(bankIndex, amount, {
693
+ return await this.program.instruction.transferDeposit(marketIndex, amount, {
662
694
  accounts: {
663
695
  authority: this.wallet.publicKey,
664
696
  fromUser,
@@ -669,15 +701,15 @@ class ClearingHouse {
669
701
  remainingAccounts,
670
702
  });
671
703
  }
672
- async updateBankCumulativeInterest(bankIndex) {
673
- 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);
674
706
  return txSig;
675
707
  }
676
- async updateBankCumulativeInterestIx(bankIndex) {
677
- const bank = this.getBankAccount(bankIndex);
678
- return await this.program.instruction.updateBankCumulativeInterest({
708
+ async updateSpotMarketCumulativeInterestIx(marketIndex) {
709
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
710
+ return await this.program.instruction.updateSpotMarketCumulativeInterest({
679
711
  accounts: {
680
- bank: bank.pubkey,
712
+ spotMarket: spotMarket.pubkey,
681
713
  },
682
714
  });
683
715
  }
@@ -687,7 +719,7 @@ class ClearingHouse {
687
719
  }
688
720
  async settleLPIx(settleeUserAccountPublicKey, marketIndex) {
689
721
  const settleeUserAccount = (await this.program.account.user.fetch(settleeUserAccountPublicKey));
690
- const userPositions = settleeUserAccount.positions;
722
+ const userPositions = settleeUserAccount.perpPositions;
691
723
  const remainingAccounts = [];
692
724
  let foundMarket = false;
693
725
  for (const position of userPositions) {
@@ -721,12 +753,12 @@ class ClearingHouse {
721
753
  async getRemoveLiquidityIx(marketIndex, sharesToBurn) {
722
754
  const userAccountPublicKey = await this.getUserAccountPublicKey();
723
755
  const remainingAccounts = this.getRemainingAccounts({
724
- writableMarketIndex: marketIndex,
756
+ writablePerpMarketIndex: marketIndex,
725
757
  });
726
758
  if (sharesToBurn == undefined) {
727
759
  const userAccount = this.getUserAccount();
728
- const marketPosition = userAccount.positions.filter((position) => position.marketIndex.eq(marketIndex))[0];
729
- sharesToBurn = marketPosition.lpShares;
760
+ const perpPosition = userAccount.perpPositions.filter((position) => position.marketIndex.eq(marketIndex))[0];
761
+ sharesToBurn = perpPosition.lpShares;
730
762
  console.log('burning lp shares:', sharesToBurn.toString());
731
763
  }
732
764
  return this.program.instruction.removeLiquidity(sharesToBurn, marketIndex, {
@@ -746,7 +778,7 @@ class ClearingHouse {
746
778
  async getAddLiquidityIx(amount, marketIndex) {
747
779
  const userAccountPublicKey = await this.getUserAccountPublicKey();
748
780
  const remainingAccounts = this.getRemainingAccounts({
749
- writableMarketIndex: marketIndex,
781
+ writablePerpMarketIndex: marketIndex,
750
782
  });
751
783
  return this.program.instruction.addLiquidity(amount, marketIndex, {
752
784
  accounts: {
@@ -766,19 +798,51 @@ class ClearingHouse {
766
798
  price: limitPrice,
767
799
  });
768
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
+ }
769
831
  async placeOrder(orderParams) {
770
832
  const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceOrderIx(orderParams)), [], this.opts);
771
833
  this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
772
834
  return txSig;
773
835
  }
774
- getOrderParams(optionalOrderParams) {
775
- return Object.assign({}, types_1.DefaultOrderParams, optionalOrderParams);
836
+ getOrderParams(optionalOrderParams, marketType) {
837
+ return Object.assign({}, types_1.DefaultOrderParams, optionalOrderParams, {
838
+ marketType,
839
+ });
776
840
  }
777
841
  async getPlaceOrderIx(orderParams) {
778
- orderParams = this.getOrderParams(orderParams);
842
+ orderParams = this.getOrderParams(orderParams, types_1.MarketType.PERP);
779
843
  const userAccountPublicKey = await this.getUserAccountPublicKey();
780
844
  const remainingAccounts = this.getRemainingAccounts({
781
- readableMarketIndex: orderParams.marketIndex,
845
+ readablePerpMarketIndex: orderParams.marketIndex,
782
846
  });
783
847
  return await this.program.instruction.placeOrder(orderParams, {
784
848
  accounts: {
@@ -802,7 +866,7 @@ class ClearingHouse {
802
866
  const oracleAccountInfos = [];
803
867
  for (const marketIndex of marketIndexes) {
804
868
  if (!marketIndex.eq(new anchor_1.BN(100))) {
805
- const market = this.getMarketAccount(marketIndex);
869
+ const market = this.getPerpMarketAccount(marketIndex);
806
870
  marketAccountInfos.push({
807
871
  pubkey: market.pubkey,
808
872
  isWritable: true,
@@ -824,6 +888,41 @@ class ClearingHouse {
824
888
  remainingAccounts,
825
889
  });
826
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
+ }
827
926
  async cancelOrder(orderId) {
828
927
  const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getCancelOrderIx(orderId)), [], this.opts);
829
928
  return txSig;
@@ -847,7 +946,7 @@ class ClearingHouse {
847
946
  async getCancelOrderByUserIdIx(userOrderId) {
848
947
  const userAccountPublicKey = await this.getUserAccountPublicKey();
849
948
  const order = this.getOrderByUserId(userOrderId);
850
- const oracle = this.getMarketAccount(order.marketIndex).amm.oracle;
949
+ const oracle = this.getPerpMarketAccount(order.marketIndex).amm.oracle;
851
950
  const remainingAccounts = this.getRemainingAccounts({});
852
951
  return await this.program.instruction.cancelOrderByUserId(userOrderId, {
853
952
  accounts: {
@@ -870,32 +969,32 @@ class ClearingHouse {
870
969
  const marketIndex = order
871
970
  ? order.marketIndex
872
971
  : userAccount.orders.find((order) => order.orderId.eq(userAccount.nextOrderId.sub(numericConstants_1.ONE))).marketIndex;
873
- const marketAccount = this.getMarketAccount(marketIndex);
972
+ const marketAccount = this.getPerpMarketAccount(marketIndex);
874
973
  const oracleAccountMap = new Map();
875
- const bankAccountMap = new Map();
876
- const marketAccountMap = new Map();
877
- for (const bankBalance of userAccount.bankBalances) {
878
- if (!bankBalance.balance.eq(numericConstants_1.ZERO)) {
879
- const bankAccount = this.getBankAccount(bankBalance.bankIndex);
880
- bankAccountMap.set(bankBalance.bankIndex.toNumber(), {
881
- 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,
882
981
  isSigner: false,
883
982
  isWritable: false,
884
983
  });
885
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
886
- oracleAccountMap.set(bankAccount.oracle.toString(), {
887
- pubkey: bankAccount.oracle,
984
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
985
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
986
+ pubkey: spotMarketAccount.oracle,
888
987
  isSigner: false,
889
988
  isWritable: false,
890
989
  });
891
990
  }
892
991
  }
893
992
  }
894
- for (const position of userAccount.positions) {
993
+ for (const position of userAccount.perpPositions) {
895
994
  if (!(0, position_1.positionIsAvailable)(position) &&
896
995
  !position.marketIndex.eq(order.marketIndex)) {
897
- const market = this.getMarketAccount(position.marketIndex);
898
- marketAccountMap.set(position.marketIndex.toNumber(), {
996
+ const market = this.getPerpMarketAccount(position.marketIndex);
997
+ perpMarketAccountMap.set(position.marketIndex.toNumber(), {
899
998
  pubkey: market.pubkey,
900
999
  isWritable: false,
901
1000
  isSigner: false,
@@ -907,7 +1006,7 @@ class ClearingHouse {
907
1006
  });
908
1007
  }
909
1008
  }
910
- marketAccountMap.set(marketIndex.toNumber(), {
1009
+ perpMarketAccountMap.set(marketIndex.toNumber(), {
911
1010
  pubkey: marketAccount.pubkey,
912
1011
  isWritable: true,
913
1012
  isSigner: false,
@@ -919,8 +1018,8 @@ class ClearingHouse {
919
1018
  });
920
1019
  const remainingAccounts = [
921
1020
  ...oracleAccountMap.values(),
922
- ...bankAccountMap.values(),
923
- ...marketAccountMap.values(),
1021
+ ...spotMarketAccountMap.values(),
1022
+ ...perpMarketAccountMap.values(),
924
1023
  ];
925
1024
  if (makerInfo) {
926
1025
  remainingAccounts.push({
@@ -960,6 +1059,212 @@ class ClearingHouse {
960
1059
  remainingAccounts,
961
1060
  });
962
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
+ }
963
1268
  async triggerOrder(userAccountPublicKey, user, order) {
964
1269
  const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getTriggerOrderIx(userAccountPublicKey, user, order)), [], this.opts);
965
1270
  return txSig;
@@ -967,32 +1272,32 @@ class ClearingHouse {
967
1272
  async getTriggerOrderIx(userAccountPublicKey, userAccount, order) {
968
1273
  const fillerPublicKey = await this.getUserAccountPublicKey();
969
1274
  const marketIndex = order.marketIndex;
970
- const marketAccount = this.getMarketAccount(marketIndex);
1275
+ const marketAccount = this.getPerpMarketAccount(marketIndex);
971
1276
  const oracleAccountMap = new Map();
972
- const bankAccountMap = new Map();
973
- const marketAccountMap = new Map();
974
- for (const bankBalance of userAccount.bankBalances) {
975
- if (!bankBalance.balance.eq(numericConstants_1.ZERO)) {
976
- const bankAccount = this.getBankAccount(bankBalance.bankIndex);
977
- bankAccountMap.set(bankBalance.bankIndex.toNumber(), {
978
- 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,
979
1284
  isSigner: false,
980
1285
  isWritable: false,
981
1286
  });
982
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
983
- oracleAccountMap.set(bankAccount.oracle.toString(), {
984
- pubkey: bankAccount.oracle,
1287
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1288
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1289
+ pubkey: spotMarketAccount.oracle,
985
1290
  isSigner: false,
986
1291
  isWritable: false,
987
1292
  });
988
1293
  }
989
1294
  }
990
1295
  }
991
- for (const position of userAccount.positions) {
1296
+ for (const position of userAccount.perpPositions) {
992
1297
  if (!(0, position_1.positionIsAvailable)(position) &&
993
1298
  !position.marketIndex.eq(order.marketIndex)) {
994
- const market = this.getMarketAccount(position.marketIndex);
995
- marketAccountMap.set(position.marketIndex.toNumber(), {
1299
+ const market = this.getPerpMarketAccount(position.marketIndex);
1300
+ perpMarketAccountMap.set(position.marketIndex.toNumber(), {
996
1301
  pubkey: market.pubkey,
997
1302
  isWritable: false,
998
1303
  isSigner: false,
@@ -1004,7 +1309,7 @@ class ClearingHouse {
1004
1309
  });
1005
1310
  }
1006
1311
  }
1007
- marketAccountMap.set(marketIndex.toNumber(), {
1312
+ perpMarketAccountMap.set(marketIndex.toNumber(), {
1008
1313
  pubkey: marketAccount.pubkey,
1009
1314
  isWritable: true,
1010
1315
  isSigner: false,
@@ -1016,8 +1321,8 @@ class ClearingHouse {
1016
1321
  });
1017
1322
  const remainingAccounts = [
1018
1323
  ...oracleAccountMap.values(),
1019
- ...bankAccountMap.values(),
1020
- ...marketAccountMap.values(),
1324
+ ...spotMarketAccountMap.values(),
1325
+ ...perpMarketAccountMap.values(),
1021
1326
  ];
1022
1327
  const orderId = order.orderId;
1023
1328
  return await this.program.instruction.triggerOrder(orderId, {
@@ -1030,18 +1335,94 @@ class ClearingHouse {
1030
1335
  remainingAccounts,
1031
1336
  });
1032
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
+ }
1033
1414
  async placeAndTake(orderParams, makerInfo, referrerInfo) {
1034
1415
  const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceAndTakeIx(orderParams, makerInfo, referrerInfo)), [], this.opts);
1035
1416
  this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
1036
1417
  return txSig;
1037
1418
  }
1038
1419
  async getPlaceAndTakeIx(orderParams, makerInfo, referrerInfo) {
1039
- orderParams = this.getOrderParams(orderParams);
1420
+ orderParams = this.getOrderParams(orderParams, types_1.MarketType.PERP);
1040
1421
  const userStatsPublicKey = await this.getUserStatsAccountPublicKey();
1041
1422
  const userAccountPublicKey = await this.getUserAccountPublicKey();
1042
1423
  const remainingAccounts = this.getRemainingAccounts({
1043
- writableMarketIndex: orderParams.marketIndex,
1044
- writableBankIndex: numericConstants_1.QUOTE_ASSET_BANK_INDEX,
1424
+ writablePerpMarketIndex: orderParams.marketIndex,
1425
+ writableSpotMarketIndex: numericConstants_1.QUOTE_SPOT_MARKET_INDEX,
1045
1426
  });
1046
1427
  let makerOrderId = null;
1047
1428
  if (makerInfo) {
@@ -1085,13 +1466,13 @@ class ClearingHouse {
1085
1466
  return txSig;
1086
1467
  }
1087
1468
  async getPlaceAndMakeIx(orderParams, takerInfo, referrerInfo) {
1088
- orderParams = this.getOrderParams(orderParams);
1469
+ orderParams = this.getOrderParams(orderParams, types_1.MarketType.PERP);
1089
1470
  const userStatsPublicKey = this.getUserStatsAccountPublicKey();
1090
1471
  const userAccountPublicKey = await this.getUserAccountPublicKey();
1091
1472
  // todo merge this with getRemainingAccounts
1092
1473
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1093
1474
  counterPartyUserAccount: takerInfo.takerUserAccount,
1094
- writableMarketIndex: orderParams.marketIndex,
1475
+ writablePerpMarketIndex: orderParams.marketIndex,
1095
1476
  });
1096
1477
  if (referrerInfo) {
1097
1478
  remainingAccounts.push({
@@ -1156,12 +1537,82 @@ class ClearingHouse {
1156
1537
  return txSig;
1157
1538
  }
1158
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) {
1159
1610
  const marketAccountMap = new Map();
1160
1611
  const oracleAccountMap = new Map();
1161
- const bankAccountMap = new Map();
1162
- for (const position of settleeUserAccount.positions) {
1612
+ const spotMarketAccountMap = new Map();
1613
+ for (const position of settleeUserAccount.perpPositions) {
1163
1614
  if (!(0, position_1.positionIsAvailable)(position)) {
1164
- const market = this.getMarketAccount(position.marketIndex);
1615
+ const market = this.getPerpMarketAccount(position.marketIndex);
1165
1616
  marketAccountMap.set(position.marketIndex.toNumber(), {
1166
1617
  pubkey: market.pubkey,
1167
1618
  isWritable: false,
@@ -1174,15 +1625,15 @@ class ClearingHouse {
1174
1625
  });
1175
1626
  }
1176
1627
  }
1177
- for (const userBankBalance of settleeUserAccount.bankBalances) {
1178
- if (!userBankBalance.balance.eq(numericConstants_1.QUOTE_ASSET_BANK_INDEX)) {
1179
- const bankAccount = this.getBankAccount(userBankBalance.bankIndex);
1180
- 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(), {
1181
1632
  pubkey: bankAccount.pubkey,
1182
1633
  isSigner: false,
1183
1634
  isWritable: false,
1184
1635
  });
1185
- if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
1636
+ if (!bankAccount.marketIndex.eq(numericConstants_1.ZERO)) {
1186
1637
  oracleAccountMap.set(bankAccount.oracle.toString(), {
1187
1638
  pubkey: bankAccount.oracle,
1188
1639
  isSigner: false,
@@ -1191,7 +1642,7 @@ class ClearingHouse {
1191
1642
  }
1192
1643
  }
1193
1644
  }
1194
- const marketAccount = this.getMarketAccount(marketIndex.toNumber());
1645
+ const marketAccount = this.getPerpMarketAccount(marketIndex.toNumber());
1195
1646
  marketAccountMap.set(marketIndex.toNumber(), {
1196
1647
  pubkey: marketAccount.pubkey,
1197
1648
  isSigner: false,
@@ -1202,17 +1653,17 @@ class ClearingHouse {
1202
1653
  isSigner: false,
1203
1654
  isWritable: false,
1204
1655
  });
1205
- bankAccountMap.set(numericConstants_1.QUOTE_ASSET_BANK_INDEX.toNumber(), {
1206
- 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,
1207
1658
  isSigner: false,
1208
1659
  isWritable: true,
1209
1660
  });
1210
1661
  const remainingAccounts = [
1211
1662
  ...oracleAccountMap.values(),
1212
- ...bankAccountMap.values(),
1663
+ ...spotMarketAccountMap.values(),
1213
1664
  ...marketAccountMap.values(),
1214
1665
  ];
1215
- return await this.program.instruction.settlePnl(marketIndex, {
1666
+ return await this.program.instruction.settleExpiredPosition(marketIndex, {
1216
1667
  accounts: {
1217
1668
  state: await this.getStatePublicKey(),
1218
1669
  authority: this.wallet.publicKey,
@@ -1222,7 +1673,8 @@ class ClearingHouse {
1222
1673
  });
1223
1674
  }
1224
1675
  async liquidatePerp(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount) {
1225
- 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);
1226
1678
  return txSig;
1227
1679
  }
1228
1680
  async getLiquidatePerpIx(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount) {
@@ -1230,7 +1682,7 @@ class ClearingHouse {
1230
1682
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1231
1683
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
1232
1684
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1233
- writableMarketIndex: marketIndex,
1685
+ writablePerpMarketIndex: marketIndex,
1234
1686
  counterPartyUserAccount: userAccount,
1235
1687
  });
1236
1688
  return await this.program.instruction.liquidatePerp(marketIndex, maxBaseAssetAmount, {
@@ -1245,17 +1697,17 @@ class ClearingHouse {
1245
1697
  remainingAccounts: remainingAccounts,
1246
1698
  });
1247
1699
  }
1248
- async liquidateBorrow(userAccountPublicKey, userAccount, assetBankIndex, liabilityBankIndex, maxLiabilityTransfer) {
1249
- 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);
1250
1702
  return txSig;
1251
1703
  }
1252
- async getLiquidateBorrowIx(userAccountPublicKey, userAccount, assetBankIndex, liabilityBankIndex, maxLiabilityTransfer) {
1704
+ async getLiquidateBorrowIx(userAccountPublicKey, userAccount, assetmarketIndex, liabilitymarketIndex, maxLiabilityTransfer) {
1253
1705
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1254
1706
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1255
1707
  counterPartyUserAccount: userAccount,
1256
- writableBankIndexes: [liabilityBankIndex, assetBankIndex],
1708
+ writableSpotMarketIndexes: [liabilitymarketIndex, assetmarketIndex],
1257
1709
  });
1258
- return await this.program.instruction.liquidateBorrow(assetBankIndex, liabilityBankIndex, maxLiabilityTransfer, {
1710
+ return await this.program.instruction.liquidateBorrow(assetmarketIndex, liabilitymarketIndex, maxLiabilityTransfer, {
1259
1711
  accounts: {
1260
1712
  state: await this.getStatePublicKey(),
1261
1713
  authority: this.wallet.publicKey,
@@ -1265,18 +1717,19 @@ class ClearingHouse {
1265
1717
  remainingAccounts: remainingAccounts,
1266
1718
  });
1267
1719
  }
1268
- async liquidateBorrowForPerpPnl(userAccountPublicKey, userAccount, perpMarketIndex, liabilityBankIndex, maxLiabilityTransfer) {
1269
- 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);
1270
1723
  return txSig;
1271
1724
  }
1272
- async getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilityBankIndex, maxLiabilityTransfer) {
1725
+ async getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilitymarketIndex, maxLiabilityTransfer) {
1273
1726
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1274
1727
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1275
1728
  counterPartyUserAccount: userAccount,
1276
- writableMarketIndex: perpMarketIndex,
1277
- writableBankIndexes: [liabilityBankIndex],
1729
+ writablePerpMarketIndex: perpMarketIndex,
1730
+ writableSpotMarketIndexes: [liabilitymarketIndex],
1278
1731
  });
1279
- return await this.program.instruction.liquidateBorrowForPerpPnl(perpMarketIndex, liabilityBankIndex, maxLiabilityTransfer, {
1732
+ return await this.program.instruction.liquidateBorrowForPerpPnl(perpMarketIndex, liabilitymarketIndex, maxLiabilityTransfer, {
1280
1733
  accounts: {
1281
1734
  state: await this.getStatePublicKey(),
1282
1735
  authority: this.wallet.publicKey,
@@ -1286,18 +1739,19 @@ class ClearingHouse {
1286
1739
  remainingAccounts: remainingAccounts,
1287
1740
  });
1288
1741
  }
1289
- async liquidatePerpPnlForDeposit(userAccountPublicKey, userAccount, perpMarketIndex, assetBankIndex, maxPnlTransfer) {
1290
- 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);
1291
1745
  return txSig;
1292
1746
  }
1293
- async getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetBankIndex, maxPnlTransfer) {
1747
+ async getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer) {
1294
1748
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1295
1749
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1296
1750
  counterPartyUserAccount: userAccount,
1297
- writableMarketIndex: perpMarketIndex,
1298
- writableBankIndexes: [assetBankIndex],
1751
+ writablePerpMarketIndex: perpMarketIndex,
1752
+ writableSpotMarketIndexes: [assetMarketIndex],
1299
1753
  });
1300
- return await this.program.instruction.liquidatePerpPnlForDeposit(perpMarketIndex, assetBankIndex, maxPnlTransfer, {
1754
+ return await this.program.instruction.liquidatePerpPnlForDeposit(perpMarketIndex, assetMarketIndex, maxPnlTransfer, {
1301
1755
  accounts: {
1302
1756
  state: await this.getStatePublicKey(),
1303
1757
  authority: this.wallet.publicKey,
@@ -1307,51 +1761,51 @@ class ClearingHouse {
1307
1761
  remainingAccounts: remainingAccounts,
1308
1762
  });
1309
1763
  }
1310
- async resolvePerpBankruptcy(userAccountPublicKey, userAccount, bankIndex, marketIndex) {
1311
- 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);
1312
1766
  return txSig;
1313
1767
  }
1314
- async getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, bankIndex, marketIndex) {
1768
+ async getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, marketIndex) {
1315
1769
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1316
1770
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1317
- writableMarketIndex: marketIndex,
1318
- writableBankIndexes: [bankIndex],
1771
+ writablePerpMarketIndex: marketIndex,
1772
+ writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
1319
1773
  counterPartyUserAccount: userAccount,
1320
1774
  });
1321
- const bank = this.getBankAccount(bankIndex);
1322
- 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, {
1323
1777
  accounts: {
1324
1778
  state: await this.getStatePublicKey(),
1325
1779
  authority: this.wallet.publicKey,
1326
1780
  user: userAccountPublicKey,
1327
1781
  liquidator: liquidatorPublicKey,
1328
- bankVault: bank.vault,
1329
- insuranceFundVault: bank.insuranceFundVault,
1782
+ spotMarketVault: spotMarket.vault,
1783
+ insuranceFundVault: spotMarket.insuranceFundVault,
1330
1784
  clearingHouseSigner: this.getSignerPublicKey(),
1331
1785
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1332
1786
  },
1333
1787
  remainingAccounts: remainingAccounts,
1334
1788
  });
1335
1789
  }
1336
- async resolveBorrowBankruptcy(userAccountPublicKey, userAccount, bankIndex) {
1337
- 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);
1338
1792
  return txSig;
1339
1793
  }
1340
- async getResolveBorrowBankruptcyIx(userAccountPublicKey, userAccount, bankIndex) {
1794
+ async getResolveBorrowBankruptcyIx(userAccountPublicKey, userAccount, marketIndex) {
1341
1795
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1342
1796
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1343
- writableBankIndexes: [bankIndex],
1797
+ writableSpotMarketIndexes: [marketIndex],
1344
1798
  counterPartyUserAccount: userAccount,
1345
1799
  });
1346
- const bank = this.getBankAccount(bankIndex);
1347
- return await this.program.instruction.resolveBorrowBankruptcy(bankIndex, {
1800
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
1801
+ return await this.program.instruction.resolveBorrowBankruptcy(marketIndex, {
1348
1802
  accounts: {
1349
1803
  state: await this.getStatePublicKey(),
1350
1804
  authority: this.wallet.publicKey,
1351
1805
  user: userAccountPublicKey,
1352
1806
  liquidator: liquidatorPublicKey,
1353
- bankVault: bank.vault,
1354
- insuranceFundVault: bank.insuranceFundVault,
1807
+ spotMarketVault: spotMarket.vault,
1808
+ insuranceFundVault: spotMarket.insuranceFundVault,
1355
1809
  clearingHouseSigner: this.getSignerPublicKey(),
1356
1810
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1357
1811
  },
@@ -1361,28 +1815,28 @@ class ClearingHouse {
1361
1815
  getRemainingAccountsWithCounterparty(params) {
1362
1816
  const counterPartyUserAccount = params.counterPartyUserAccount;
1363
1817
  const oracleAccountMap = new Map();
1364
- const bankAccountMap = new Map();
1818
+ const spotMarketAccountMap = new Map();
1365
1819
  const marketAccountMap = new Map();
1366
- for (const bankBalance of counterPartyUserAccount.bankBalances) {
1367
- if (!bankBalance.balance.eq(numericConstants_1.ZERO)) {
1368
- const bankAccount = this.getBankAccount(bankBalance.bankIndex);
1369
- bankAccountMap.set(bankBalance.bankIndex.toNumber(), {
1370
- 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,
1371
1825
  isSigner: false,
1372
1826
  isWritable: false,
1373
1827
  });
1374
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1375
- oracleAccountMap.set(bankAccount.oracle.toString(), {
1376
- pubkey: bankAccount.oracle,
1828
+ if (!spotMarket.oracle.equals(web3_js_1.PublicKey.default)) {
1829
+ oracleAccountMap.set(spotMarket.oracle.toString(), {
1830
+ pubkey: spotMarket.oracle,
1377
1831
  isSigner: false,
1378
1832
  isWritable: false,
1379
1833
  });
1380
1834
  }
1381
1835
  }
1382
1836
  }
1383
- for (const position of counterPartyUserAccount.positions) {
1837
+ for (const position of counterPartyUserAccount.perpPositions) {
1384
1838
  if (!(0, position_1.positionIsAvailable)(position)) {
1385
- const market = this.getMarketAccount(position.marketIndex);
1839
+ const market = this.getPerpMarketAccount(position.marketIndex);
1386
1840
  marketAccountMap.set(position.marketIndex.toNumber(), {
1387
1841
  pubkey: market.pubkey,
1388
1842
  isWritable: false,
@@ -1404,7 +1858,7 @@ class ClearingHouse {
1404
1858
  // if cache has more recent slot than user positions account slot, add market to remaining accounts
1405
1859
  // otherwise remove from slot
1406
1860
  if (slot > lastUserPositionsSlot) {
1407
- const marketAccount = this.getMarketAccount(marketIndexNum);
1861
+ const marketAccount = this.getPerpMarketAccount(marketIndexNum);
1408
1862
  marketAccountMap.set(marketIndexNum, {
1409
1863
  pubkey: marketAccount.pubkey,
1410
1864
  isSigner: false,
@@ -1420,26 +1874,26 @@ class ClearingHouse {
1420
1874
  this.marketLastSlotCache.delete(marketIndexNum);
1421
1875
  }
1422
1876
  }
1423
- for (const bankBalance of userAccount.bankBalances) {
1424
- if (!bankBalance.balance.eq(numericConstants_1.ZERO)) {
1425
- const bankAccount = this.getBankAccount(bankBalance.bankIndex);
1426
- bankAccountMap.set(bankBalance.bankIndex.toNumber(), {
1427
- 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,
1428
1882
  isSigner: false,
1429
1883
  isWritable: false,
1430
1884
  });
1431
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1432
- oracleAccountMap.set(bankAccount.oracle.toString(), {
1433
- pubkey: bankAccount.oracle,
1885
+ if (!spotMarket.oracle.equals(web3_js_1.PublicKey.default)) {
1886
+ oracleAccountMap.set(spotMarket.oracle.toString(), {
1887
+ pubkey: spotMarket.oracle,
1434
1888
  isSigner: false,
1435
1889
  isWritable: false,
1436
1890
  });
1437
1891
  }
1438
1892
  }
1439
1893
  }
1440
- for (const position of userAccount.positions) {
1894
+ for (const position of userAccount.perpPositions) {
1441
1895
  if (!(0, position_1.positionIsAvailable)(position)) {
1442
- const market = this.getMarketAccount(position.marketIndex);
1896
+ const market = this.getPerpMarketAccount(position.marketIndex);
1443
1897
  marketAccountMap.set(position.marketIndex.toNumber(), {
1444
1898
  pubkey: market.pubkey,
1445
1899
  isWritable: false,
@@ -1452,8 +1906,8 @@ class ClearingHouse {
1452
1906
  });
1453
1907
  }
1454
1908
  }
1455
- if (params.writableMarketIndex) {
1456
- const market = this.getMarketAccount(params.writableMarketIndex);
1909
+ if (params.writablePerpMarketIndex) {
1910
+ const market = this.getPerpMarketAccount(params.writablePerpMarketIndex);
1457
1911
  marketAccountMap.set(market.marketIndex.toNumber(), {
1458
1912
  pubkey: market.pubkey,
1459
1913
  isSigner: false,
@@ -1465,17 +1919,17 @@ class ClearingHouse {
1465
1919
  isWritable: false,
1466
1920
  });
1467
1921
  }
1468
- if (params.writableBankIndexes) {
1469
- for (const writableBankIndex of params.writableBankIndexes) {
1470
- const bank = this.getBankAccount(writableBankIndex);
1471
- bankAccountMap.set(bank.bankIndex.toNumber(), {
1472
- 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,
1473
1927
  isSigner: false,
1474
1928
  isWritable: true,
1475
1929
  });
1476
- if (!bank.oracle.equals(web3_js_1.PublicKey.default)) {
1477
- oracleAccountMap.set(bank.oracle.toString(), {
1478
- pubkey: bank.oracle,
1930
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1931
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1932
+ pubkey: spotMarketAccount.oracle,
1479
1933
  isSigner: false,
1480
1934
  isWritable: false,
1481
1935
  });
@@ -1484,7 +1938,7 @@ class ClearingHouse {
1484
1938
  }
1485
1939
  return [
1486
1940
  ...oracleAccountMap.values(),
1487
- ...bankAccountMap.values(),
1941
+ ...spotMarketAccountMap.values(),
1488
1942
  ...marketAccountMap.values(),
1489
1943
  ];
1490
1944
  }
@@ -1507,7 +1961,7 @@ class ClearingHouse {
1507
1961
  }
1508
1962
  async getSettleFundingPaymentIx(userAccount) {
1509
1963
  const user = (await this.program.account.user.fetch(userAccount));
1510
- const userPositions = user.positions;
1964
+ const userPositions = user.perpPositions;
1511
1965
  const remainingAccounts = [];
1512
1966
  for (const position of userPositions) {
1513
1967
  if (!(0, position_1.positionIsAvailable)(position)) {
@@ -1531,20 +1985,20 @@ class ClearingHouse {
1531
1985
  this.eventEmitter.emit(eventName, data);
1532
1986
  }
1533
1987
  getOracleDataForMarket(marketIndex) {
1534
- const oracleKey = this.getMarketAccount(marketIndex).amm.oracle;
1988
+ const oracleKey = this.getPerpMarketAccount(marketIndex).amm.oracle;
1535
1989
  const oracleData = this.getOraclePriceDataAndSlot(oracleKey).data;
1536
1990
  return oracleData;
1537
1991
  }
1538
- async initializeInsuranceFundStake(bankIndex) {
1539
- 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);
1540
1994
  return txSig;
1541
1995
  }
1542
- async getInitializeInsuranceFundStakeIx(bankIndex) {
1543
- const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, bankIndex);
1544
- 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, {
1545
1999
  accounts: {
1546
2000
  insuranceFundStake: ifStakeAccountPublicKey,
1547
- bank: this.getBankAccount(bankIndex).pubkey,
2001
+ spotMarket: this.getSpotMarketAccount(marketIndex).pubkey,
1548
2002
  userStats: this.getUserStatsAccountPublicKey(),
1549
2003
  authority: this.wallet.publicKey,
1550
2004
  payer: this.wallet.publicKey,
@@ -1554,80 +2008,80 @@ class ClearingHouse {
1554
2008
  },
1555
2009
  });
1556
2010
  }
1557
- async addInsuranceFundStake(bankIndex, amount, collateralAccountPublicKey) {
1558
- const bank = this.getBankAccount(bankIndex);
1559
- 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);
1560
2014
  const remainingAccounts = this.getRemainingAccounts({
1561
- writableBankIndex: bankIndex,
2015
+ writableSpotMarketIndex: marketIndex,
1562
2016
  });
1563
- return await this.program.rpc.addInsuranceFundStake(bankIndex, amount, {
2017
+ return await this.program.rpc.addInsuranceFundStake(marketIndex, amount, {
1564
2018
  accounts: {
1565
2019
  state: await this.getStatePublicKey(),
1566
- bank: bank.pubkey,
2020
+ spotMarket: spotMarket.pubkey,
1567
2021
  insuranceFundStake: ifStakeAccountPublicKey,
1568
2022
  userStats: this.getUserStatsAccountPublicKey(),
1569
2023
  authority: this.wallet.publicKey,
1570
- insuranceFundVault: bank.insuranceFundVault,
2024
+ insuranceFundVault: spotMarket.insuranceFundVault,
1571
2025
  userTokenAccount: collateralAccountPublicKey,
1572
2026
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1573
2027
  },
1574
2028
  remainingAccounts,
1575
2029
  });
1576
2030
  }
1577
- async requestRemoveInsuranceFundStake(bankIndex, amount) {
1578
- const bank = this.getBankAccount(bankIndex);
1579
- 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);
1580
2034
  const remainingAccounts = this.getRemainingAccounts({
1581
- writableBankIndex: bankIndex,
2035
+ writableSpotMarketIndex: marketIndex,
1582
2036
  });
1583
- return await this.program.rpc.requestRemoveInsuranceFundStake(bankIndex, amount, {
2037
+ return await this.program.rpc.requestRemoveInsuranceFundStake(marketIndex, amount, {
1584
2038
  accounts: {
1585
2039
  state: await this.getStatePublicKey(),
1586
- bank: bank.pubkey,
2040
+ spotMarket: spotMarketAccount.pubkey,
1587
2041
  insuranceFundStake: ifStakeAccountPublicKey,
1588
2042
  userStats: this.getUserStatsAccountPublicKey(),
1589
2043
  authority: this.wallet.publicKey,
1590
- insuranceFundVault: bank.insuranceFundVault,
2044
+ insuranceFundVault: spotMarketAccount.insuranceFundVault,
1591
2045
  // userTokenAccount: collateralAccountPublicKey,
1592
2046
  // tokenProgram: TOKEN_PROGRAM_ID,
1593
2047
  },
1594
2048
  remainingAccounts,
1595
2049
  });
1596
2050
  }
1597
- async cancelRequestRemoveInsuranceFundStake(bankIndex) {
1598
- const bank = this.getBankAccount(bankIndex);
1599
- 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);
1600
2054
  const remainingAccounts = this.getRemainingAccounts({
1601
- writableBankIndex: bankIndex,
2055
+ writableSpotMarketIndex: marketIndex,
1602
2056
  });
1603
- return await this.program.rpc.cancelRequestRemoveInsuranceFundStake(bankIndex, {
2057
+ return await this.program.rpc.cancelRequestRemoveInsuranceFundStake(marketIndex, {
1604
2058
  accounts: {
1605
2059
  state: await this.getStatePublicKey(),
1606
- bank: bank.pubkey,
2060
+ spotMarket: spotMarketAccount.pubkey,
1607
2061
  insuranceFundStake: ifStakeAccountPublicKey,
1608
2062
  userStats: this.getUserStatsAccountPublicKey(),
1609
2063
  authority: this.wallet.publicKey,
1610
- insuranceFundVault: bank.insuranceFundVault,
2064
+ insuranceFundVault: spotMarketAccount.insuranceFundVault,
1611
2065
  // userTokenAccount: collateralAccountPublicKey,
1612
2066
  // tokenProgram: TOKEN_PROGRAM_ID,
1613
2067
  },
1614
2068
  remainingAccounts,
1615
2069
  });
1616
2070
  }
1617
- async removeInsuranceFundStake(bankIndex, collateralAccountPublicKey) {
1618
- const bank = this.getBankAccount(bankIndex);
1619
- 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);
1620
2074
  const remainingAccounts = this.getRemainingAccounts({
1621
- writableBankIndex: bankIndex,
2075
+ writableSpotMarketIndex: marketIndex,
1622
2076
  });
1623
- return await this.program.rpc.removeInsuranceFundStake(bankIndex, {
2077
+ return await this.program.rpc.removeInsuranceFundStake(marketIndex, {
1624
2078
  accounts: {
1625
2079
  state: await this.getStatePublicKey(),
1626
- bank: bank.pubkey,
2080
+ spotMarket: spotMarketAccount.pubkey,
1627
2081
  insuranceFundStake: ifStakeAccountPublicKey,
1628
2082
  userStats: this.getUserStatsAccountPublicKey(),
1629
2083
  authority: this.wallet.publicKey,
1630
- insuranceFundVault: bank.insuranceFundVault,
2084
+ insuranceFundVault: spotMarketAccount.insuranceFundVault,
1631
2085
  clearingHouseSigner: this.getSignerPublicKey(),
1632
2086
  userTokenAccount: collateralAccountPublicKey,
1633
2087
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
@@ -1635,22 +2089,44 @@ class ClearingHouse {
1635
2089
  remainingAccounts,
1636
2090
  });
1637
2091
  }
1638
- async settleRevenueToInsuranceFund(bankIndex) {
1639
- const bank = this.getBankAccount(bankIndex);
2092
+ async settleRevenueToInsuranceFund(marketIndex) {
2093
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1640
2094
  const remainingAccounts = this.getRemainingAccounts({
1641
- writableBankIndex: bankIndex,
2095
+ writableSpotMarketIndex: marketIndex,
1642
2096
  });
1643
- return await this.program.rpc.settleRevenueToInsuranceFund(bankIndex, {
2097
+ return await this.program.rpc.settleRevenueToInsuranceFund(marketIndex, {
1644
2098
  accounts: {
1645
2099
  state: await this.getStatePublicKey(),
1646
- bank: bank.pubkey,
1647
- bankVault: bank.vault,
2100
+ spotMarket: spotMarketAccount.pubkey,
2101
+ spotMarketVault: spotMarketAccount.vault,
1648
2102
  clearingHouseSigner: this.getSignerPublicKey(),
1649
- insuranceFundVault: bank.insuranceFundVault,
2103
+ insuranceFundVault: spotMarketAccount.insuranceFundVault,
1650
2104
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1651
2105
  },
1652
2106
  remainingAccounts,
1653
2107
  });
1654
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
+ }
1655
2131
  }
1656
2132
  exports.ClearingHouse = ClearingHouse;