@drift-labs/sdk 0.2.0-master.25 → 0.2.0-master.27

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 (124) hide show
  1. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +14 -13
  2. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +30 -27
  3. package/lib/accounts/types.d.ts +9 -9
  4. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +15 -14
  5. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +38 -34
  6. package/lib/addresses/pda.d.ts +7 -6
  7. package/lib/addresses/pda.js +31 -27
  8. package/lib/admin.d.ts +13 -7
  9. package/lib/admin.js +111 -44
  10. package/lib/clearingHouse.d.ts +71 -42
  11. package/lib/clearingHouse.js +767 -278
  12. package/lib/clearingHouseConfig.d.ts +2 -2
  13. package/lib/clearingHouseUser.d.ts +24 -22
  14. package/lib/clearingHouseUser.js +273 -177
  15. package/lib/config.d.ts +7 -7
  16. package/lib/config.js +21 -21
  17. package/lib/constants/numericConstants.d.ts +12 -12
  18. package/lib/constants/numericConstants.js +13 -13
  19. package/lib/constants/{markets.d.ts → perpMarkets.d.ts} +5 -5
  20. package/lib/constants/{markets.js → 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/dlob/DLOB.d.ts +73 -0
  24. package/lib/dlob/DLOB.js +557 -0
  25. package/lib/dlob/DLOBNode.d.ts +52 -0
  26. package/lib/dlob/DLOBNode.js +82 -0
  27. package/lib/dlob/NodeList.d.ts +26 -0
  28. package/lib/dlob/NodeList.js +138 -0
  29. package/lib/events/types.d.ts +2 -1
  30. package/lib/events/types.js +1 -0
  31. package/lib/examples/makeTradeExample.js +7 -7
  32. package/lib/idl/clearing_house.json +1152 -503
  33. package/lib/index.d.ts +10 -3
  34. package/lib/index.js +10 -3
  35. package/lib/math/amm.d.ts +2 -2
  36. package/lib/math/amm.js +1 -1
  37. package/lib/math/funding.d.ts +6 -6
  38. package/lib/math/funding.js +2 -1
  39. package/lib/math/margin.d.ts +4 -4
  40. package/lib/math/margin.js +18 -11
  41. package/lib/math/market.d.ts +11 -10
  42. package/lib/math/market.js +30 -7
  43. package/lib/math/oracles.d.ts +2 -1
  44. package/lib/math/oracles.js +11 -1
  45. package/lib/math/orders.d.ts +6 -6
  46. package/lib/math/orders.js +31 -16
  47. package/lib/math/position.d.ts +13 -13
  48. package/lib/math/position.js +19 -19
  49. package/lib/math/spotBalance.d.ts +22 -0
  50. package/lib/math/spotBalance.js +193 -0
  51. package/lib/math/spotMarket.d.ts +4 -0
  52. package/lib/math/spotMarket.js +8 -0
  53. package/lib/math/spotPosition.d.ts +6 -0
  54. package/lib/math/spotPosition.js +23 -0
  55. package/lib/math/state.js +2 -2
  56. package/lib/math/trade.d.ts +4 -4
  57. package/lib/orderParams.d.ts +4 -4
  58. package/lib/orderParams.js +12 -4
  59. package/lib/serum/serumSubscriber.d.ts +23 -0
  60. package/lib/serum/serumSubscriber.js +41 -0
  61. package/lib/serum/types.d.ts +11 -0
  62. package/lib/serum/types.js +2 -0
  63. package/lib/tx/retryTxSender.d.ts +1 -1
  64. package/lib/tx/retryTxSender.js +4 -2
  65. package/lib/tx/types.d.ts +1 -1
  66. package/lib/types.d.ts +148 -57
  67. package/lib/types.js +39 -11
  68. package/lib/userMap/userMap.d.ts +25 -0
  69. package/lib/userMap/userMap.js +73 -0
  70. package/lib/userMap/userStatsMap.d.ts +19 -0
  71. package/lib/userMap/userStatsMap.js +68 -0
  72. package/package.json +6 -3
  73. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +42 -38
  74. package/src/accounts/types.ts +12 -9
  75. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +65 -52
  76. package/src/addresses/pda.ts +49 -44
  77. package/src/admin.ts +190 -55
  78. package/src/clearingHouse.ts +1092 -365
  79. package/src/clearingHouseConfig.ts +2 -2
  80. package/src/clearingHouseUser.ts +518 -255
  81. package/src/config.ts +30 -30
  82. package/src/constants/numericConstants.ts +17 -15
  83. package/src/constants/{markets.ts → perpMarkets.ts} +5 -5
  84. package/src/constants/{banks.ts → spotMarkets.ts} +19 -19
  85. package/src/dlob/DLOB.ts +884 -0
  86. package/src/dlob/DLOBNode.ts +163 -0
  87. package/src/dlob/NodeList.ts +185 -0
  88. package/src/events/types.ts +3 -0
  89. package/src/examples/makeTradeExample.js +152 -75
  90. package/src/examples/makeTradeExample.ts +10 -8
  91. package/src/idl/clearing_house.json +1152 -503
  92. package/src/index.ts +10 -3
  93. package/src/math/amm.ts +6 -3
  94. package/src/math/funding.ts +7 -7
  95. package/src/math/margin.ts +34 -23
  96. package/src/math/market.ts +72 -20
  97. package/src/math/oracles.ts +18 -1
  98. package/src/math/orders.ts +33 -25
  99. package/src/math/position.ts +31 -31
  100. package/src/math/spotBalance.ts +316 -0
  101. package/src/math/spotMarket.ts +9 -0
  102. package/src/math/spotPosition.ts +47 -0
  103. package/src/math/state.ts +2 -2
  104. package/src/math/trade.ts +4 -4
  105. package/src/orderParams.ts +16 -8
  106. package/src/serum/serumSubscriber.ts +80 -0
  107. package/src/serum/types.ts +13 -0
  108. package/src/tx/retryTxSender.ts +5 -2
  109. package/src/tx/types.ts +2 -1
  110. package/src/types.ts +135 -56
  111. package/src/userMap/userMap.ts +100 -0
  112. package/src/userMap/userStatsMap.ts +110 -0
  113. package/tests/bn/test.ts +2 -3
  114. package/tests/dlob/helpers.ts +322 -0
  115. package/tests/dlob/test.ts +2865 -0
  116. package/lib/math/bankBalance.d.ts +0 -15
  117. package/lib/math/bankBalance.js +0 -150
  118. package/src/constants/numericConstants.js +0 -41
  119. package/src/math/bankBalance.ts +0 -258
  120. package/src/math/oracles.js +0 -26
  121. package/src/math/state.js +0 -15
  122. package/src/orderParams.js +0 -20
  123. package/src/slot/SlotSubscriber.js +0 -39
  124. package/src/tokenFaucet.js +0 -189
@@ -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,35 @@ 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;
190
+ }
191
+ getSpotMarketAccounts() {
192
+ return this.accountSubscriber
193
+ .getSpotMarketAccountsAndSlots()
194
+ .map((value) => value.data);
185
195
  }
186
- getQuoteAssetBankAccount() {
187
- return this.accountSubscriber.getBankAccountAndSlot(numericConstants_1.QUOTE_ASSET_BANK_INDEX)
188
- .data;
196
+ getQuoteSpotMarketAccount() {
197
+ return this.accountSubscriber.getSpotMarketAccountAndSlot(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).data;
189
198
  }
190
199
  getOraclePriceDataAndSlot(oraclePublicKey) {
191
200
  return this.accountSubscriber.getOraclePriceDataAndSlot(oraclePublicKey);
192
201
  }
202
+ async getSerumV3FulfillmentConfig(serumMarket) {
203
+ const address = await (0, pda_1.getSerumFulfillmentConfigPublicKey)(this.program.programId, serumMarket);
204
+ return (await this.program.account.serumV3FulfillmentConfig.fetch(address));
205
+ }
193
206
  /**
194
207
  * Update the wallet to use for clearing house transactions and linked user account
195
208
  * @param newWallet
@@ -279,6 +292,23 @@ class ClearingHouse {
279
292
  },
280
293
  });
281
294
  }
295
+ async updateUserName(name, userId = 0) {
296
+ const nameBuffer = (0, userName_1.encodeName)(name);
297
+ return await this.program.rpc.updateUserName(userId, nameBuffer, {
298
+ accounts: {
299
+ user: await this.getUserAccountPublicKey(),
300
+ authority: this.wallet.publicKey,
301
+ },
302
+ });
303
+ }
304
+ async updateUserCustomMarginRatio(marginRatio, userId = 0) {
305
+ return await this.program.rpc.updateUserCustomMarginRatio(userId, marginRatio, {
306
+ accounts: {
307
+ user: await this.getUserAccountPublicKey(),
308
+ authority: this.wallet.publicKey,
309
+ },
310
+ });
311
+ }
282
312
  getUser(userId) {
283
313
  userId = userId !== null && userId !== void 0 ? userId : this.activeUserId;
284
314
  if (!this.users.has(userId)) {
@@ -308,14 +338,14 @@ class ClearingHouse {
308
338
  getUserAccountAndSlot(userId) {
309
339
  return this.getUser(userId).getUserAccountAndSlot();
310
340
  }
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));
341
+ getSpotPosition(marketIndex) {
342
+ const marketIndexBN = marketIndex instanceof anchor_1.BN ? marketIndex : new anchor_1.BN(marketIndex);
343
+ return this.getUserAccount().spotPositions.find((spotPosition) => spotPosition.marketIndex.eq(marketIndexBN));
314
344
  }
315
345
  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);
346
+ const spotMarket = this.getSpotMarketAccount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
347
+ const spotPosition = this.getSpotPosition(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
348
+ return (0, spotBalance_1.getTokenAmount)(spotPosition.balance, spotMarket, spotPosition.balanceType);
319
349
  }
320
350
  getRemainingAccounts(params) {
321
351
  const userAccountAndSlot = this.getUserAccountAndSlot();
@@ -324,14 +354,14 @@ class ClearingHouse {
324
354
  }
325
355
  const { data: userAccount, slot: lastUserPositionsSlot } = userAccountAndSlot;
326
356
  const oracleAccountMap = new Map();
327
- const bankAccountMap = new Map();
328
- const marketAccountMap = new Map();
357
+ const spotMarketAccountMap = new Map();
358
+ const perpMarketAccountMap = new Map();
329
359
  for (const [marketIndexNum, slot] of this.marketLastSlotCache.entries()) {
330
360
  // if cache has more recent slot than user positions account slot, add market to remaining accounts
331
361
  // otherwise remove from slot
332
362
  if (slot > lastUserPositionsSlot) {
333
- const marketAccount = this.getMarketAccount(marketIndexNum);
334
- marketAccountMap.set(marketIndexNum, {
363
+ const marketAccount = this.getPerpMarketAccount(marketIndexNum);
364
+ perpMarketAccountMap.set(marketIndexNum, {
335
365
  pubkey: marketAccount.pubkey,
336
366
  isSigner: false,
337
367
  isWritable: false,
@@ -346,11 +376,11 @@ class ClearingHouse {
346
376
  this.marketLastSlotCache.delete(marketIndexNum);
347
377
  }
348
378
  }
349
- for (const position of userAccount.positions) {
379
+ for (const position of userAccount.perpPositions) {
350
380
  if (!(0, position_1.positionIsAvailable)(position)) {
351
381
  const marketIndexNum = position.marketIndex.toNumber();
352
- const marketAccount = this.getMarketAccount(marketIndexNum);
353
- marketAccountMap.set(marketIndexNum, {
382
+ const marketAccount = this.getPerpMarketAccount(marketIndexNum);
383
+ perpMarketAccountMap.set(marketIndexNum, {
354
384
  pubkey: marketAccount.pubkey,
355
385
  isSigner: false,
356
386
  isWritable: false,
@@ -362,12 +392,12 @@ class ClearingHouse {
362
392
  });
363
393
  }
364
394
  }
365
- if (params.readableMarketIndex) {
366
- const marketAccount = this.getMarketAccount(params.readableMarketIndex.toNumber());
367
- marketAccountMap.set(params.readableMarketIndex.toNumber(), {
395
+ if (params.readablePerpMarketIndex) {
396
+ const marketAccount = this.getPerpMarketAccount(params.readablePerpMarketIndex.toNumber());
397
+ perpMarketAccountMap.set(params.readablePerpMarketIndex.toNumber(), {
368
398
  pubkey: marketAccount.pubkey,
369
399
  isSigner: false,
370
- isWritable: true,
400
+ isWritable: false,
371
401
  });
372
402
  oracleAccountMap.set(marketAccount.amm.oracle.toString(), {
373
403
  pubkey: marketAccount.amm.oracle,
@@ -375,9 +405,9 @@ class ClearingHouse {
375
405
  isWritable: false,
376
406
  });
377
407
  }
378
- if (params.writableMarketIndex) {
379
- const marketAccount = this.getMarketAccount(params.writableMarketIndex.toNumber());
380
- marketAccountMap.set(params.writableMarketIndex.toNumber(), {
408
+ if (params.writablePerpMarketIndex) {
409
+ const marketAccount = this.getPerpMarketAccount(params.writablePerpMarketIndex.toNumber());
410
+ perpMarketAccountMap.set(params.writablePerpMarketIndex.toNumber(), {
381
411
  pubkey: marketAccount.pubkey,
382
412
  isSigner: false,
383
413
  isWritable: true,
@@ -388,33 +418,48 @@ class ClearingHouse {
388
418
  isWritable: false,
389
419
  });
390
420
  }
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,
421
+ for (const spotPosition of userAccount.spotPositions) {
422
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
423
+ const spotMarketAccount = this.getSpotMarketAccount(spotPosition.marketIndex);
424
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
425
+ pubkey: spotMarketAccount.pubkey,
396
426
  isSigner: false,
397
427
  isWritable: false,
398
428
  });
399
- if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
400
- oracleAccountMap.set(bankAccount.oracle.toString(), {
401
- pubkey: bankAccount.oracle,
429
+ if (!spotMarketAccount.marketIndex.eq(numericConstants_1.ZERO)) {
430
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
431
+ pubkey: spotMarketAccount.oracle,
402
432
  isSigner: false,
403
433
  isWritable: false,
404
434
  });
405
435
  }
406
436
  }
407
437
  }
408
- if (params.writableBankIndex) {
409
- const bankAccount = this.getBankAccount(params.writableBankIndex);
410
- bankAccountMap.set(params.writableBankIndex.toNumber(), {
411
- pubkey: bankAccount.pubkey,
438
+ if (params.readableSpotMarketIndex) {
439
+ const spotMarketAccount = this.getSpotMarketAccount(params.readableSpotMarketIndex);
440
+ spotMarketAccountMap.set(params.readableSpotMarketIndex.toNumber(), {
441
+ pubkey: spotMarketAccount.pubkey,
442
+ isSigner: false,
443
+ isWritable: false,
444
+ });
445
+ if (!spotMarketAccount.marketIndex.eq(numericConstants_1.ZERO)) {
446
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
447
+ pubkey: spotMarketAccount.oracle,
448
+ isSigner: false,
449
+ isWritable: false,
450
+ });
451
+ }
452
+ }
453
+ if (params.writableSpotMarketIndex) {
454
+ const spotMarketAccount = this.getSpotMarketAccount(params.writableSpotMarketIndex);
455
+ spotMarketAccountMap.set(params.writableSpotMarketIndex.toNumber(), {
456
+ pubkey: spotMarketAccount.pubkey,
412
457
  isSigner: false,
413
458
  isWritable: true,
414
459
  });
415
- if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
416
- oracleAccountMap.set(bankAccount.oracle.toString(), {
417
- pubkey: bankAccount.oracle,
460
+ if (!spotMarketAccount.marketIndex.eq(numericConstants_1.ZERO)) {
461
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
462
+ pubkey: spotMarketAccount.oracle,
418
463
  isSigner: false,
419
464
  isWritable: false,
420
465
  });
@@ -422,8 +467,8 @@ class ClearingHouse {
422
467
  }
423
468
  return [
424
469
  ...oracleAccountMap.values(),
425
- ...bankAccountMap.values(),
426
- ...marketAccountMap.values(),
470
+ ...spotMarketAccountMap.values(),
471
+ ...perpMarketAccountMap.values(),
427
472
  ];
428
473
  }
429
474
  getOrder(orderId) {
@@ -435,13 +480,13 @@ class ClearingHouse {
435
480
  var _a;
436
481
  return (_a = this.getUserAccount()) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.userOrderId === userOrderId);
437
482
  }
438
- async deposit(amount, bankIndex, collateralAccountPublicKey, userId, reduceOnly = false) {
483
+ async deposit(amount, marketIndex, collateralAccountPublicKey, userId, reduceOnly = false) {
439
484
  const tx = new web3_js_1.Transaction();
440
485
  const additionalSigners = [];
441
- const bank = this.getBankAccount(bankIndex);
442
- const isSolBank = bank.mint.equals(banks_1.WRAPPED_SOL_MINT);
486
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
487
+ const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
443
488
  const authority = this.wallet.publicKey;
444
- const createWSOLTokenAccount = isSolBank && collateralAccountPublicKey.equals(authority);
489
+ const createWSOLTokenAccount = isSolMarket && collateralAccountPublicKey.equals(authority);
445
490
  if (createWSOLTokenAccount) {
446
491
  const { ixs, signers, pubkey } = await this.getWrappedSolAccountCreationIxs(amount);
447
492
  collateralAccountPublicKey = pubkey;
@@ -450,7 +495,7 @@ class ClearingHouse {
450
495
  });
451
496
  signers.forEach((signer) => additionalSigners.push(signer));
452
497
  }
453
- const depositCollateralIx = await this.getDepositInstruction(amount, bankIndex, collateralAccountPublicKey, userId, reduceOnly, true);
498
+ const depositCollateralIx = await this.getDepositInstruction(amount, marketIndex, collateralAccountPublicKey, userId, reduceOnly, true);
454
499
  tx.add(depositCollateralIx);
455
500
  // Close the wrapped sol account at the end of the transaction
456
501
  if (createWSOLTokenAccount) {
@@ -459,37 +504,37 @@ class ClearingHouse {
459
504
  const { txSig } = await this.txSender.send(tx, additionalSigners, this.opts);
460
505
  return txSig;
461
506
  }
462
- async getDepositInstruction(amount, bankIndex, userTokenAccount, userId, reduceOnly = false, userInitialized = true) {
507
+ async getDepositInstruction(amount, marketIndex, userTokenAccount, userId, reduceOnly = false, userInitialized = true) {
463
508
  const userAccountPublicKey = userId
464
509
  ? await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, userId)
465
510
  : await this.getUserAccountPublicKey();
466
511
  let remainingAccounts = [];
467
512
  if (userInitialized) {
468
513
  remainingAccounts = this.getRemainingAccounts({
469
- writableBankIndex: bankIndex,
514
+ writableSpotMarketIndex: marketIndex,
470
515
  });
471
516
  }
472
517
  else {
473
- const bankAccount = this.getBankAccount(bankIndex);
474
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
518
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
519
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
475
520
  remainingAccounts.push({
476
- pubkey: bankAccount.oracle,
521
+ pubkey: spotMarketAccount.oracle,
477
522
  isSigner: false,
478
523
  isWritable: false,
479
524
  });
480
525
  }
481
526
  remainingAccounts.push({
482
- pubkey: bankAccount.pubkey,
527
+ pubkey: spotMarketAccount.pubkey,
483
528
  isSigner: false,
484
529
  isWritable: true,
485
530
  });
486
531
  }
487
- const bank = this.getBankAccount(bankIndex);
488
- return await this.program.instruction.deposit(bankIndex, amount, reduceOnly, {
532
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
533
+ return await this.program.instruction.deposit(marketIndex, amount, reduceOnly, {
489
534
  accounts: {
490
535
  state: await this.getStatePublicKey(),
491
- bank: bank.pubkey,
492
- bankVault: bank.vault,
536
+ spotMarket: spotMarketAccount.pubkey,
537
+ spotMarketVault: spotMarketAccount.vault,
493
538
  user: userAccountPublicKey,
494
539
  userStats: this.getUserStatsAccountPublicKey(),
495
540
  userTokenAccount: userTokenAccount,
@@ -509,7 +554,7 @@ class ClearingHouse {
509
554
  return false;
510
555
  }
511
556
  }
512
- async getSolWithdrawalIxs(bankIndex, amount) {
557
+ async getSolWithdrawalIxs(marketIndex, amount) {
513
558
  const result = {
514
559
  ixs: [],
515
560
  signers: [],
@@ -525,7 +570,7 @@ class ClearingHouse {
525
570
  signers.forEach((ix) => {
526
571
  result.signers.push(ix);
527
572
  });
528
- const withdrawIx = await this.getWithdrawIx(amount, bankIndex, pubkey, true);
573
+ const withdrawIx = await this.getWithdrawIx(amount, marketIndex, pubkey, true);
529
574
  result.ixs.push(withdrawIx);
530
575
  result.ixs.push(spl_token_1.Token.createCloseAccountInstruction(spl_token_1.TOKEN_PROGRAM_ID, pubkey, authority, authority, []));
531
576
  return result;
@@ -547,7 +592,7 @@ class ClearingHouse {
547
592
  space: 165,
548
593
  programId: spl_token_1.TOKEN_PROGRAM_ID,
549
594
  }));
550
- result.ixs.push(spl_token_1.Token.createInitAccountInstruction(spl_token_1.TOKEN_PROGRAM_ID, banks_1.WRAPPED_SOL_MINT, wrappedSolAccount.publicKey, authority));
595
+ result.ixs.push(spl_token_1.Token.createInitAccountInstruction(spl_token_1.TOKEN_PROGRAM_ID, spotMarkets_1.WRAPPED_SOL_MINT, wrappedSolAccount.publicKey, authority));
551
596
  result.signers.push(wrappedSolAccount);
552
597
  return result;
553
598
  }
@@ -555,20 +600,20 @@ class ClearingHouse {
555
600
  * Creates the Clearing House User account for a user, and deposits some initial collateral
556
601
  * @param amount
557
602
  * @param userTokenAccount
558
- * @param bankIndex
603
+ * @param marketIndex
559
604
  * @param userId
560
605
  * @param name
561
606
  * @param fromUserId
562
607
  * @returns
563
608
  */
564
- async initializeUserAccountAndDepositCollateral(amount, userTokenAccount, bankIndex = new anchor_1.BN(0), userId = 0, name = userName_1.DEFAULT_USER_NAME, fromUserId, referrerInfo) {
609
+ async initializeUserAccountAndDepositCollateral(amount, userTokenAccount, marketIndex = new anchor_1.BN(0), userId = 0, name = userName_1.DEFAULT_USER_NAME, fromUserId, referrerInfo) {
565
610
  const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(userId, name, referrerInfo);
566
611
  const additionalSigners = [];
567
- const bank = this.getBankAccount(bankIndex);
568
- const isSolBank = bank.mint.equals(banks_1.WRAPPED_SOL_MINT);
612
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
613
+ const isSolMarket = spotMarket.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
569
614
  const tx = new web3_js_1.Transaction();
570
615
  const authority = this.wallet.publicKey;
571
- const createWSOLTokenAccount = isSolBank && userTokenAccount.equals(authority);
616
+ const createWSOLTokenAccount = isSolMarket && userTokenAccount.equals(authority);
572
617
  if (createWSOLTokenAccount) {
573
618
  const { ixs: startIxs, signers, pubkey, } = await this.getWrappedSolAccountCreationIxs(amount);
574
619
  userTokenAccount = pubkey;
@@ -578,8 +623,8 @@ class ClearingHouse {
578
623
  signers.forEach((signer) => additionalSigners.push(signer));
579
624
  }
580
625
  const depositCollateralIx = fromUserId != null
581
- ? await this.getTransferDepositIx(amount, bankIndex, fromUserId, userId)
582
- : await this.getDepositInstruction(amount, bankIndex, userTokenAccount, userId, false, false);
626
+ ? await this.getTransferDepositIx(amount, marketIndex, fromUserId, userId)
627
+ : await this.getDepositInstruction(amount, marketIndex, userTokenAccount, userId, false, false);
583
628
  if (userId === 0) {
584
629
  tx.add(await this.getInitializeUserStatsIx());
585
630
  }
@@ -591,10 +636,10 @@ class ClearingHouse {
591
636
  const { txSig } = await this.txSender.send(tx, additionalSigners, this.opts);
592
637
  return [txSig, userAccountPublicKey];
593
638
  }
594
- async initializeUserAccountForDevnet(userId = 0, name = userName_1.DEFAULT_USER_NAME, bankIndex, tokenFaucet, amount, referrerInfo) {
639
+ async initializeUserAccountForDevnet(userId = 0, name = userName_1.DEFAULT_USER_NAME, marketIndex, tokenFaucet, amount, referrerInfo) {
595
640
  const [associateTokenPublicKey, createAssociatedAccountIx, mintToIx] = await tokenFaucet.createAssociatedTokenAccountAndMintToInstructions(this.wallet.publicKey, amount);
596
641
  const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(userId, name, referrerInfo);
597
- const depositCollateralIx = await this.getDepositInstruction(amount, bankIndex, associateTokenPublicKey, userId, false, false);
642
+ const depositCollateralIx = await this.getDepositInstruction(amount, marketIndex, associateTokenPublicKey, userId, false, false);
598
643
  const tx = new web3_js_1.Transaction().add(createAssociatedAccountIx).add(mintToIx);
599
644
  if (userId === 0) {
600
645
  tx.add(await this.getInitializeUserStatsIx());
@@ -603,13 +648,13 @@ class ClearingHouse {
603
648
  const txSig = await this.program.provider.sendAndConfirm(tx, []);
604
649
  return [txSig, userAccountPublicKey];
605
650
  }
606
- async withdraw(amount, bankIndex, userTokenAccount, reduceOnly = false) {
651
+ async withdraw(amount, marketIndex, userTokenAccount, reduceOnly = false) {
607
652
  const tx = new web3_js_1.Transaction();
608
653
  const additionalSigners = [];
609
- const bank = this.getBankAccount(bankIndex);
610
- const isSolBank = bank.mint.equals(banks_1.WRAPPED_SOL_MINT);
654
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
655
+ const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
611
656
  const authority = this.wallet.publicKey;
612
- const createWSOLTokenAccount = isSolBank && userTokenAccount.equals(authority);
657
+ const createWSOLTokenAccount = isSolMarket && userTokenAccount.equals(authority);
613
658
  if (createWSOLTokenAccount) {
614
659
  const { ixs, signers, pubkey } = await this.getWrappedSolAccountCreationIxs(amount);
615
660
  userTokenAccount = pubkey;
@@ -618,7 +663,7 @@ class ClearingHouse {
618
663
  });
619
664
  signers.forEach((signer) => additionalSigners.push(signer));
620
665
  }
621
- const withdrawCollateral = await this.getWithdrawIx(amount, bank.bankIndex, userTokenAccount, reduceOnly);
666
+ const withdrawCollateral = await this.getWithdrawIx(amount, spotMarketAccount.marketIndex, userTokenAccount, reduceOnly);
622
667
  tx.add(withdrawCollateral);
623
668
  // Close the wrapped sol account at the end of the transaction
624
669
  if (createWSOLTokenAccount) {
@@ -627,17 +672,17 @@ class ClearingHouse {
627
672
  const { txSig } = await this.txSender.send(tx, additionalSigners, this.opts);
628
673
  return txSig;
629
674
  }
630
- async getWithdrawIx(amount, bankIndex, userTokenAccount, reduceOnly = false) {
675
+ async getWithdrawIx(amount, marketIndex, userTokenAccount, reduceOnly = false) {
631
676
  const userAccountPublicKey = await this.getUserAccountPublicKey();
632
677
  const remainingAccounts = this.getRemainingAccounts({
633
- writableBankIndex: bankIndex,
678
+ writableSpotMarketIndex: marketIndex,
634
679
  });
635
- const bank = this.getBankAccount(bankIndex);
636
- return await this.program.instruction.withdraw(bankIndex, amount, reduceOnly, {
680
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
681
+ return await this.program.instruction.withdraw(marketIndex, amount, reduceOnly, {
637
682
  accounts: {
638
683
  state: await this.getStatePublicKey(),
639
- bank: bank.pubkey,
640
- bankVault: bank.vault,
684
+ spotMarket: spotMarketAccount.pubkey,
685
+ spotMarketVault: spotMarketAccount.vault,
641
686
  clearingHouseSigner: this.getSignerPublicKey(),
642
687
  user: userAccountPublicKey,
643
688
  userStats: this.getUserStatsAccountPublicKey(),
@@ -648,17 +693,17 @@ class ClearingHouse {
648
693
  remainingAccounts,
649
694
  });
650
695
  }
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);
696
+ async transferDeposit(amount, marketIndex, fromUserId, toUserId) {
697
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getTransferDepositIx(amount, marketIndex, fromUserId, toUserId)), [], this.opts);
653
698
  return txSig;
654
699
  }
655
- async getTransferDepositIx(amount, bankIndex, fromUserId, toUserId) {
700
+ async getTransferDepositIx(amount, marketIndex, fromUserId, toUserId) {
656
701
  const fromUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, fromUserId);
657
702
  const toUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, toUserId);
658
703
  const remainingAccounts = this.getRemainingAccounts({
659
- writableBankIndex: bankIndex,
704
+ writableSpotMarketIndex: marketIndex,
660
705
  });
661
- return await this.program.instruction.transferDeposit(bankIndex, amount, {
706
+ return await this.program.instruction.transferDeposit(marketIndex, amount, {
662
707
  accounts: {
663
708
  authority: this.wallet.publicKey,
664
709
  fromUser,
@@ -669,15 +714,15 @@ class ClearingHouse {
669
714
  remainingAccounts,
670
715
  });
671
716
  }
672
- async updateBankCumulativeInterest(bankIndex) {
673
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.updateBankCumulativeInterestIx(bankIndex)), [], this.opts);
717
+ async updateSpotMarketCumulativeInterest(marketIndex) {
718
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.updateSpotMarketCumulativeInterestIx(marketIndex)), [], this.opts);
674
719
  return txSig;
675
720
  }
676
- async updateBankCumulativeInterestIx(bankIndex) {
677
- const bank = this.getBankAccount(bankIndex);
678
- return await this.program.instruction.updateBankCumulativeInterest({
721
+ async updateSpotMarketCumulativeInterestIx(marketIndex) {
722
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
723
+ return await this.program.instruction.updateSpotMarketCumulativeInterest({
679
724
  accounts: {
680
- bank: bank.pubkey,
725
+ spotMarket: spotMarket.pubkey,
681
726
  },
682
727
  });
683
728
  }
@@ -687,7 +732,7 @@ class ClearingHouse {
687
732
  }
688
733
  async settleLPIx(settleeUserAccountPublicKey, marketIndex) {
689
734
  const settleeUserAccount = (await this.program.account.user.fetch(settleeUserAccountPublicKey));
690
- const userPositions = settleeUserAccount.positions;
735
+ const userPositions = settleeUserAccount.perpPositions;
691
736
  const remainingAccounts = [];
692
737
  let foundMarket = false;
693
738
  for (const position of userPositions) {
@@ -721,12 +766,12 @@ class ClearingHouse {
721
766
  async getRemoveLiquidityIx(marketIndex, sharesToBurn) {
722
767
  const userAccountPublicKey = await this.getUserAccountPublicKey();
723
768
  const remainingAccounts = this.getRemainingAccounts({
724
- writableMarketIndex: marketIndex,
769
+ writablePerpMarketIndex: marketIndex,
725
770
  });
726
771
  if (sharesToBurn == undefined) {
727
772
  const userAccount = this.getUserAccount();
728
- const marketPosition = userAccount.positions.filter((position) => position.marketIndex.eq(marketIndex))[0];
729
- sharesToBurn = marketPosition.lpShares;
773
+ const perpPosition = userAccount.perpPositions.filter((position) => position.marketIndex.eq(marketIndex))[0];
774
+ sharesToBurn = perpPosition.lpShares;
730
775
  console.log('burning lp shares:', sharesToBurn.toString());
731
776
  }
732
777
  return this.program.instruction.removeLiquidity(sharesToBurn, marketIndex, {
@@ -746,7 +791,7 @@ class ClearingHouse {
746
791
  async getAddLiquidityIx(amount, marketIndex) {
747
792
  const userAccountPublicKey = await this.getUserAccountPublicKey();
748
793
  const remainingAccounts = this.getRemainingAccounts({
749
- writableMarketIndex: marketIndex,
794
+ writablePerpMarketIndex: marketIndex,
750
795
  });
751
796
  return this.program.instruction.addLiquidity(amount, marketIndex, {
752
797
  accounts: {
@@ -766,19 +811,51 @@ class ClearingHouse {
766
811
  price: limitPrice,
767
812
  });
768
813
  }
814
+ async sendSignedTx(tx) {
815
+ const { txSig } = await this.txSender.send(tx, undefined, this.opts, true);
816
+ return txSig;
817
+ }
818
+ /**
819
+ * 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.
820
+ * @param orderParams
821
+ * @param userAccountPublicKey
822
+ * @param userAccount
823
+ * @returns
824
+ */
825
+ async sendMarketOrderAndGetSignedFillTx(orderParams, userAccountPublicKey, userAccount) {
826
+ const marketIndex = orderParams.marketIndex;
827
+ const orderId = userAccount.nextOrderId;
828
+ const marketOrderTx = (0, utils_1.wrapInTx)(await this.getPlaceOrderIx(orderParams));
829
+ const fillTx = (0, utils_1.wrapInTx)(await this.getFillOrderIx(userAccountPublicKey, userAccount, {
830
+ orderId,
831
+ marketIndex,
832
+ }));
833
+ // Apply the latest blockhash to the txs so that we can sign before sending them
834
+ const currentBlockHash = (await this.connection.getLatestBlockhash('finalized')).blockhash;
835
+ marketOrderTx.recentBlockhash = currentBlockHash;
836
+ fillTx.recentBlockhash = currentBlockHash;
837
+ marketOrderTx.feePayer = userAccount.authority;
838
+ fillTx.feePayer = userAccount.authority;
839
+ const [signedMarketOrderTx, signedFillTx] = await this.provider.wallet.signAllTransactions([marketOrderTx, fillTx]);
840
+ const { txSig, slot } = await this.txSender.send(signedMarketOrderTx, [], this.opts, true);
841
+ this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
842
+ return { txSig, signedFillTx };
843
+ }
769
844
  async placeOrder(orderParams) {
770
845
  const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceOrderIx(orderParams)), [], this.opts);
771
846
  this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
772
847
  return txSig;
773
848
  }
774
- getOrderParams(optionalOrderParams) {
775
- return Object.assign({}, types_1.DefaultOrderParams, optionalOrderParams);
849
+ getOrderParams(optionalOrderParams, marketType) {
850
+ return Object.assign({}, types_1.DefaultOrderParams, optionalOrderParams, {
851
+ marketType,
852
+ });
776
853
  }
777
854
  async getPlaceOrderIx(orderParams) {
778
- orderParams = this.getOrderParams(orderParams);
855
+ orderParams = this.getOrderParams(orderParams, types_1.MarketType.PERP);
779
856
  const userAccountPublicKey = await this.getUserAccountPublicKey();
780
857
  const remainingAccounts = this.getRemainingAccounts({
781
- readableMarketIndex: orderParams.marketIndex,
858
+ readablePerpMarketIndex: orderParams.marketIndex,
782
859
  });
783
860
  return await this.program.instruction.placeOrder(orderParams, {
784
861
  accounts: {
@@ -802,7 +879,7 @@ class ClearingHouse {
802
879
  const oracleAccountInfos = [];
803
880
  for (const marketIndex of marketIndexes) {
804
881
  if (!marketIndex.eq(new anchor_1.BN(100))) {
805
- const market = this.getMarketAccount(marketIndex);
882
+ const market = this.getPerpMarketAccount(marketIndex);
806
883
  marketAccountInfos.push({
807
884
  pubkey: market.pubkey,
808
885
  isWritable: true,
@@ -824,6 +901,41 @@ class ClearingHouse {
824
901
  remainingAccounts,
825
902
  });
826
903
  }
904
+ async settleExpiredMarket(marketIndex) {
905
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getSettleExpiredMarketIx(marketIndex)), [], this.opts);
906
+ return txSig;
907
+ }
908
+ async getSettleExpiredMarketIx(marketIndex) {
909
+ const marketAccountInfos = [];
910
+ const oracleAccountInfos = [];
911
+ const spotMarketAccountInfos = [];
912
+ const market = this.getPerpMarketAccount(marketIndex);
913
+ marketAccountInfos.push({
914
+ pubkey: market.pubkey,
915
+ isWritable: true,
916
+ isSigner: false,
917
+ });
918
+ oracleAccountInfos.push({
919
+ pubkey: market.amm.oracle,
920
+ isWritable: false,
921
+ isSigner: false,
922
+ });
923
+ spotMarketAccountInfos.push({
924
+ pubkey: this.getSpotMarketAccount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).pubkey,
925
+ isSigner: false,
926
+ isWritable: true,
927
+ });
928
+ const remainingAccounts = oracleAccountInfos
929
+ .concat(spotMarketAccountInfos)
930
+ .concat(marketAccountInfos);
931
+ return await this.program.instruction.settleExpiredMarket(marketIndex, {
932
+ accounts: {
933
+ state: await this.getStatePublicKey(),
934
+ authority: this.wallet.publicKey,
935
+ },
936
+ remainingAccounts,
937
+ });
938
+ }
827
939
  async cancelOrder(orderId) {
828
940
  const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getCancelOrderIx(orderId)), [], this.opts);
829
941
  return txSig;
@@ -847,7 +959,7 @@ class ClearingHouse {
847
959
  async getCancelOrderByUserIdIx(userOrderId) {
848
960
  const userAccountPublicKey = await this.getUserAccountPublicKey();
849
961
  const order = this.getOrderByUserId(userOrderId);
850
- const oracle = this.getMarketAccount(order.marketIndex).amm.oracle;
962
+ const oracle = this.getPerpMarketAccount(order.marketIndex).amm.oracle;
851
963
  const remainingAccounts = this.getRemainingAccounts({});
852
964
  return await this.program.instruction.cancelOrderByUserId(userOrderId, {
853
965
  accounts: {
@@ -870,32 +982,32 @@ class ClearingHouse {
870
982
  const marketIndex = order
871
983
  ? order.marketIndex
872
984
  : userAccount.orders.find((order) => order.orderId.eq(userAccount.nextOrderId.sub(numericConstants_1.ONE))).marketIndex;
873
- const marketAccount = this.getMarketAccount(marketIndex);
985
+ const marketAccount = this.getPerpMarketAccount(marketIndex);
874
986
  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,
987
+ const spotMarketAccountMap = new Map();
988
+ const perpMarketAccountMap = new Map();
989
+ for (const spotPosition of userAccount.spotPositions) {
990
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
991
+ const spotMarketAccount = this.getSpotMarketAccount(spotPosition.marketIndex);
992
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
993
+ pubkey: spotMarketAccount.pubkey,
882
994
  isSigner: false,
883
995
  isWritable: false,
884
996
  });
885
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
886
- oracleAccountMap.set(bankAccount.oracle.toString(), {
887
- pubkey: bankAccount.oracle,
997
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
998
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
999
+ pubkey: spotMarketAccount.oracle,
888
1000
  isSigner: false,
889
1001
  isWritable: false,
890
1002
  });
891
1003
  }
892
1004
  }
893
1005
  }
894
- for (const position of userAccount.positions) {
1006
+ for (const position of userAccount.perpPositions) {
895
1007
  if (!(0, position_1.positionIsAvailable)(position) &&
896
1008
  !position.marketIndex.eq(order.marketIndex)) {
897
- const market = this.getMarketAccount(position.marketIndex);
898
- marketAccountMap.set(position.marketIndex.toNumber(), {
1009
+ const market = this.getPerpMarketAccount(position.marketIndex);
1010
+ perpMarketAccountMap.set(position.marketIndex.toNumber(), {
899
1011
  pubkey: market.pubkey,
900
1012
  isWritable: false,
901
1013
  isSigner: false,
@@ -907,7 +1019,7 @@ class ClearingHouse {
907
1019
  });
908
1020
  }
909
1021
  }
910
- marketAccountMap.set(marketIndex.toNumber(), {
1022
+ perpMarketAccountMap.set(marketIndex.toNumber(), {
911
1023
  pubkey: marketAccount.pubkey,
912
1024
  isWritable: true,
913
1025
  isSigner: false,
@@ -919,8 +1031,8 @@ class ClearingHouse {
919
1031
  });
920
1032
  const remainingAccounts = [
921
1033
  ...oracleAccountMap.values(),
922
- ...bankAccountMap.values(),
923
- ...marketAccountMap.values(),
1034
+ ...spotMarketAccountMap.values(),
1035
+ ...perpMarketAccountMap.values(),
924
1036
  ];
925
1037
  if (makerInfo) {
926
1038
  remainingAccounts.push({
@@ -960,6 +1072,212 @@ class ClearingHouse {
960
1072
  remainingAccounts,
961
1073
  });
962
1074
  }
1075
+ async placeSpotOrder(orderParams) {
1076
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceSpotOrderIx(orderParams)), [], this.opts);
1077
+ return txSig;
1078
+ }
1079
+ async getPlaceSpotOrderIx(orderParams) {
1080
+ orderParams = this.getOrderParams(orderParams, types_1.MarketType.SPOT);
1081
+ const userAccountPublicKey = await this.getUserAccountPublicKey();
1082
+ const remainingAccounts = this.getRemainingAccounts({
1083
+ readableSpotMarketIndex: orderParams.marketIndex,
1084
+ });
1085
+ return await this.program.instruction.placeSpotOrder(orderParams, {
1086
+ accounts: {
1087
+ state: await this.getStatePublicKey(),
1088
+ user: userAccountPublicKey,
1089
+ userStats: this.getUserStatsAccountPublicKey(),
1090
+ authority: this.wallet.publicKey,
1091
+ },
1092
+ remainingAccounts,
1093
+ });
1094
+ }
1095
+ async fillSpotOrder(userAccountPublicKey, user, order, fulfillmentConfig, makerInfo, referrerInfo) {
1096
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getFillSpotOrderIx(userAccountPublicKey, user, order, fulfillmentConfig, makerInfo, referrerInfo)), [], this.opts);
1097
+ return txSig;
1098
+ }
1099
+ async getFillSpotOrderIx(userAccountPublicKey, userAccount, order, fulfillmentConfig, makerInfo, referrerInfo) {
1100
+ const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
1101
+ const fillerPublicKey = await this.getUserAccountPublicKey();
1102
+ const fillerStatsPublicKey = this.getUserStatsAccountPublicKey();
1103
+ const marketIndex = order
1104
+ ? order.marketIndex
1105
+ : userAccount.orders.find((order) => order.orderId.eq(userAccount.nextOrderId.sub(numericConstants_1.ONE))).marketIndex;
1106
+ const oracleAccountMap = new Map();
1107
+ const spotMarketAccountMap = new Map();
1108
+ const perpMarketAccountMap = new Map();
1109
+ for (const spotPosition of userAccount.spotPositions) {
1110
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1111
+ const spotMarket = this.getSpotMarketAccount(spotPosition.marketIndex);
1112
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
1113
+ pubkey: spotMarket.pubkey,
1114
+ isSigner: false,
1115
+ isWritable: false,
1116
+ });
1117
+ if (!spotMarket.oracle.equals(web3_js_1.PublicKey.default)) {
1118
+ oracleAccountMap.set(spotMarket.oracle.toString(), {
1119
+ pubkey: spotMarket.oracle,
1120
+ isSigner: false,
1121
+ isWritable: false,
1122
+ });
1123
+ }
1124
+ }
1125
+ }
1126
+ for (const position of userAccount.perpPositions) {
1127
+ if (!(0, position_1.positionIsAvailable)(position) &&
1128
+ !position.marketIndex.eq(order.marketIndex)) {
1129
+ const market = this.getPerpMarketAccount(position.marketIndex);
1130
+ perpMarketAccountMap.set(position.marketIndex.toNumber(), {
1131
+ pubkey: market.pubkey,
1132
+ isWritable: false,
1133
+ isSigner: false,
1134
+ });
1135
+ oracleAccountMap.set(market.amm.oracle.toString(), {
1136
+ pubkey: market.amm.oracle,
1137
+ isWritable: false,
1138
+ isSigner: false,
1139
+ });
1140
+ }
1141
+ }
1142
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1143
+ spotMarketAccountMap.set(marketIndex.toNumber(), {
1144
+ pubkey: spotMarketAccount.pubkey,
1145
+ isWritable: true,
1146
+ isSigner: false,
1147
+ });
1148
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1149
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1150
+ pubkey: spotMarketAccount.oracle,
1151
+ isWritable: false,
1152
+ isSigner: false,
1153
+ });
1154
+ }
1155
+ const quoteMarketAccount = this.getQuoteSpotMarketAccount();
1156
+ spotMarketAccountMap.set(quoteMarketAccount.marketIndex.toNumber(), {
1157
+ pubkey: quoteMarketAccount.pubkey,
1158
+ isWritable: true,
1159
+ isSigner: false,
1160
+ });
1161
+ const remainingAccounts = [
1162
+ ...oracleAccountMap.values(),
1163
+ ...spotMarketAccountMap.values(),
1164
+ ...perpMarketAccountMap.values(),
1165
+ ];
1166
+ if (makerInfo) {
1167
+ remainingAccounts.push({
1168
+ pubkey: makerInfo.maker,
1169
+ isWritable: true,
1170
+ isSigner: false,
1171
+ });
1172
+ remainingAccounts.push({
1173
+ pubkey: makerInfo.makerStats,
1174
+ isWritable: true,
1175
+ isSigner: false,
1176
+ });
1177
+ }
1178
+ if (referrerInfo) {
1179
+ remainingAccounts.push({
1180
+ pubkey: referrerInfo.referrer,
1181
+ isWritable: true,
1182
+ isSigner: false,
1183
+ });
1184
+ remainingAccounts.push({
1185
+ pubkey: referrerInfo.referrerStats,
1186
+ isWritable: true,
1187
+ isSigner: false,
1188
+ });
1189
+ }
1190
+ const orderId = order.orderId;
1191
+ const makerOrderId = makerInfo ? makerInfo.order.orderId : null;
1192
+ if (fulfillmentConfig) {
1193
+ remainingAccounts.push({
1194
+ pubkey: fulfillmentConfig.pubkey,
1195
+ isWritable: false,
1196
+ isSigner: false,
1197
+ });
1198
+ remainingAccounts.push({
1199
+ pubkey: fulfillmentConfig.serumProgramId,
1200
+ isWritable: false,
1201
+ isSigner: false,
1202
+ });
1203
+ remainingAccounts.push({
1204
+ pubkey: fulfillmentConfig.serumMarket,
1205
+ isWritable: true,
1206
+ isSigner: false,
1207
+ });
1208
+ remainingAccounts.push({
1209
+ pubkey: fulfillmentConfig.serumRequestQueue,
1210
+ isWritable: true,
1211
+ isSigner: false,
1212
+ });
1213
+ remainingAccounts.push({
1214
+ pubkey: fulfillmentConfig.serumEventQueue,
1215
+ isWritable: true,
1216
+ isSigner: false,
1217
+ });
1218
+ remainingAccounts.push({
1219
+ pubkey: fulfillmentConfig.serumBids,
1220
+ isWritable: true,
1221
+ isSigner: false,
1222
+ });
1223
+ remainingAccounts.push({
1224
+ pubkey: fulfillmentConfig.serumAsks,
1225
+ isWritable: true,
1226
+ isSigner: false,
1227
+ });
1228
+ remainingAccounts.push({
1229
+ pubkey: fulfillmentConfig.serumBaseVault,
1230
+ isWritable: true,
1231
+ isSigner: false,
1232
+ });
1233
+ remainingAccounts.push({
1234
+ pubkey: fulfillmentConfig.serumQuoteVault,
1235
+ isWritable: true,
1236
+ isSigner: false,
1237
+ });
1238
+ remainingAccounts.push({
1239
+ pubkey: fulfillmentConfig.serumOpenOrders,
1240
+ isWritable: true,
1241
+ isSigner: false,
1242
+ });
1243
+ remainingAccounts.push({
1244
+ pubkey: (0, pda_1.getSerumSignerPublicKey)(fulfillmentConfig.serumProgramId, fulfillmentConfig.serumMarket, fulfillmentConfig.serumSignerNonce),
1245
+ isWritable: false,
1246
+ isSigner: false,
1247
+ });
1248
+ remainingAccounts.push({
1249
+ pubkey: this.getSignerPublicKey(),
1250
+ isWritable: false,
1251
+ isSigner: false,
1252
+ });
1253
+ remainingAccounts.push({
1254
+ pubkey: spl_token_1.TOKEN_PROGRAM_ID,
1255
+ isWritable: false,
1256
+ isSigner: false,
1257
+ });
1258
+ remainingAccounts.push({
1259
+ pubkey: spotMarketAccount.vault,
1260
+ isWritable: true,
1261
+ isSigner: false,
1262
+ });
1263
+ remainingAccounts.push({
1264
+ pubkey: quoteMarketAccount.vault,
1265
+ isWritable: true,
1266
+ isSigner: false,
1267
+ });
1268
+ }
1269
+ return await this.program.instruction.fillSpotOrder(orderId, fulfillmentConfig ? fulfillmentConfig.fulfillmentType : null, makerOrderId, {
1270
+ accounts: {
1271
+ state: await this.getStatePublicKey(),
1272
+ filler: fillerPublicKey,
1273
+ fillerStats: fillerStatsPublicKey,
1274
+ user: userAccountPublicKey,
1275
+ userStats: userStatsPublicKey,
1276
+ authority: this.wallet.publicKey,
1277
+ },
1278
+ remainingAccounts,
1279
+ });
1280
+ }
963
1281
  async triggerOrder(userAccountPublicKey, user, order) {
964
1282
  const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getTriggerOrderIx(userAccountPublicKey, user, order)), [], this.opts);
965
1283
  return txSig;
@@ -967,32 +1285,32 @@ class ClearingHouse {
967
1285
  async getTriggerOrderIx(userAccountPublicKey, userAccount, order) {
968
1286
  const fillerPublicKey = await this.getUserAccountPublicKey();
969
1287
  const marketIndex = order.marketIndex;
970
- const marketAccount = this.getMarketAccount(marketIndex);
1288
+ const marketAccount = this.getPerpMarketAccount(marketIndex);
971
1289
  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,
1290
+ const spotMarketAccountMap = new Map();
1291
+ const perpMarketAccountMap = new Map();
1292
+ for (const spotPosition of userAccount.spotPositions) {
1293
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1294
+ const spotMarketAccount = this.getSpotMarketAccount(spotPosition.marketIndex);
1295
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
1296
+ pubkey: spotMarketAccount.pubkey,
979
1297
  isSigner: false,
980
1298
  isWritable: false,
981
1299
  });
982
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
983
- oracleAccountMap.set(bankAccount.oracle.toString(), {
984
- pubkey: bankAccount.oracle,
1300
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1301
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1302
+ pubkey: spotMarketAccount.oracle,
985
1303
  isSigner: false,
986
1304
  isWritable: false,
987
1305
  });
988
1306
  }
989
1307
  }
990
1308
  }
991
- for (const position of userAccount.positions) {
1309
+ for (const position of userAccount.perpPositions) {
992
1310
  if (!(0, position_1.positionIsAvailable)(position) &&
993
1311
  !position.marketIndex.eq(order.marketIndex)) {
994
- const market = this.getMarketAccount(position.marketIndex);
995
- marketAccountMap.set(position.marketIndex.toNumber(), {
1312
+ const market = this.getPerpMarketAccount(position.marketIndex);
1313
+ perpMarketAccountMap.set(position.marketIndex.toNumber(), {
996
1314
  pubkey: market.pubkey,
997
1315
  isWritable: false,
998
1316
  isSigner: false,
@@ -1004,7 +1322,7 @@ class ClearingHouse {
1004
1322
  });
1005
1323
  }
1006
1324
  }
1007
- marketAccountMap.set(marketIndex.toNumber(), {
1325
+ perpMarketAccountMap.set(marketIndex.toNumber(), {
1008
1326
  pubkey: marketAccount.pubkey,
1009
1327
  isWritable: true,
1010
1328
  isSigner: false,
@@ -1016,8 +1334,8 @@ class ClearingHouse {
1016
1334
  });
1017
1335
  const remainingAccounts = [
1018
1336
  ...oracleAccountMap.values(),
1019
- ...bankAccountMap.values(),
1020
- ...marketAccountMap.values(),
1337
+ ...spotMarketAccountMap.values(),
1338
+ ...perpMarketAccountMap.values(),
1021
1339
  ];
1022
1340
  const orderId = order.orderId;
1023
1341
  return await this.program.instruction.triggerOrder(orderId, {
@@ -1030,18 +1348,94 @@ class ClearingHouse {
1030
1348
  remainingAccounts,
1031
1349
  });
1032
1350
  }
1351
+ async triggerSpotOrder(userAccountPublicKey, user, order) {
1352
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getTriggerSpotOrderIx(userAccountPublicKey, user, order)), [], this.opts);
1353
+ return txSig;
1354
+ }
1355
+ async getTriggerSpotOrderIx(userAccountPublicKey, userAccount, order) {
1356
+ const fillerPublicKey = await this.getUserAccountPublicKey();
1357
+ const marketIndex = order.marketIndex;
1358
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1359
+ const oracleAccountMap = new Map();
1360
+ const spotMarketAccountMap = new Map();
1361
+ const perpMarketAccountMap = new Map();
1362
+ for (const spotPosition of userAccount.spotPositions) {
1363
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1364
+ const spotMarketAccount = this.getSpotMarketAccount(spotPosition.marketIndex);
1365
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
1366
+ pubkey: spotMarketAccount.pubkey,
1367
+ isSigner: false,
1368
+ isWritable: false,
1369
+ });
1370
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1371
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1372
+ pubkey: spotMarketAccount.oracle,
1373
+ isSigner: false,
1374
+ isWritable: false,
1375
+ });
1376
+ }
1377
+ }
1378
+ }
1379
+ for (const position of userAccount.perpPositions) {
1380
+ if (!(0, position_1.positionIsAvailable)(position) &&
1381
+ !position.marketIndex.eq(order.marketIndex)) {
1382
+ const market = this.getPerpMarketAccount(position.marketIndex);
1383
+ perpMarketAccountMap.set(position.marketIndex.toNumber(), {
1384
+ pubkey: market.pubkey,
1385
+ isWritable: false,
1386
+ isSigner: false,
1387
+ });
1388
+ oracleAccountMap.set(market.amm.oracle.toString(), {
1389
+ pubkey: market.amm.oracle,
1390
+ isWritable: false,
1391
+ isSigner: false,
1392
+ });
1393
+ }
1394
+ }
1395
+ const quoteSpotMarket = this.getQuoteSpotMarketAccount();
1396
+ spotMarketAccountMap.set(quoteSpotMarket.marketIndex.toNumber(), {
1397
+ pubkey: quoteSpotMarket.pubkey,
1398
+ isWritable: true,
1399
+ isSigner: false,
1400
+ });
1401
+ spotMarketAccountMap.set(marketIndex.toNumber(), {
1402
+ pubkey: spotMarketAccount.pubkey,
1403
+ isWritable: false,
1404
+ isSigner: false,
1405
+ });
1406
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1407
+ pubkey: spotMarketAccount.oracle,
1408
+ isWritable: false,
1409
+ isSigner: false,
1410
+ });
1411
+ const remainingAccounts = [
1412
+ ...oracleAccountMap.values(),
1413
+ ...spotMarketAccountMap.values(),
1414
+ ...perpMarketAccountMap.values(),
1415
+ ];
1416
+ const orderId = order.orderId;
1417
+ return await this.program.instruction.triggerSpotOrder(orderId, {
1418
+ accounts: {
1419
+ state: await this.getStatePublicKey(),
1420
+ filler: fillerPublicKey,
1421
+ user: userAccountPublicKey,
1422
+ authority: this.wallet.publicKey,
1423
+ },
1424
+ remainingAccounts,
1425
+ });
1426
+ }
1033
1427
  async placeAndTake(orderParams, makerInfo, referrerInfo) {
1034
1428
  const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceAndTakeIx(orderParams, makerInfo, referrerInfo)), [], this.opts);
1035
1429
  this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
1036
1430
  return txSig;
1037
1431
  }
1038
1432
  async getPlaceAndTakeIx(orderParams, makerInfo, referrerInfo) {
1039
- orderParams = this.getOrderParams(orderParams);
1433
+ orderParams = this.getOrderParams(orderParams, types_1.MarketType.PERP);
1040
1434
  const userStatsPublicKey = await this.getUserStatsAccountPublicKey();
1041
1435
  const userAccountPublicKey = await this.getUserAccountPublicKey();
1042
1436
  const remainingAccounts = this.getRemainingAccounts({
1043
- writableMarketIndex: orderParams.marketIndex,
1044
- writableBankIndex: numericConstants_1.QUOTE_ASSET_BANK_INDEX,
1437
+ writablePerpMarketIndex: orderParams.marketIndex,
1438
+ writableSpotMarketIndex: numericConstants_1.QUOTE_SPOT_MARKET_INDEX,
1045
1439
  });
1046
1440
  let makerOrderId = null;
1047
1441
  if (makerInfo) {
@@ -1085,13 +1479,13 @@ class ClearingHouse {
1085
1479
  return txSig;
1086
1480
  }
1087
1481
  async getPlaceAndMakeIx(orderParams, takerInfo, referrerInfo) {
1088
- orderParams = this.getOrderParams(orderParams);
1482
+ orderParams = this.getOrderParams(orderParams, types_1.MarketType.PERP);
1089
1483
  const userStatsPublicKey = this.getUserStatsAccountPublicKey();
1090
1484
  const userAccountPublicKey = await this.getUserAccountPublicKey();
1091
1485
  // todo merge this with getRemainingAccounts
1092
1486
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1093
1487
  counterPartyUserAccount: takerInfo.takerUserAccount,
1094
- writableMarketIndex: orderParams.marketIndex,
1488
+ writablePerpMarketIndex: orderParams.marketIndex,
1095
1489
  });
1096
1490
  if (referrerInfo) {
1097
1491
  remainingAccounts.push({
@@ -1156,12 +1550,82 @@ class ClearingHouse {
1156
1550
  return txSig;
1157
1551
  }
1158
1552
  async settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
1553
+ const perpMarketAccountMap = new Map();
1554
+ const oracleAccountMap = new Map();
1555
+ const spotMarketAccountMap = new Map();
1556
+ for (const position of settleeUserAccount.perpPositions) {
1557
+ if (!(0, position_1.positionIsAvailable)(position)) {
1558
+ const market = this.getPerpMarketAccount(position.marketIndex);
1559
+ perpMarketAccountMap.set(position.marketIndex.toNumber(), {
1560
+ pubkey: market.pubkey,
1561
+ isWritable: false,
1562
+ isSigner: false,
1563
+ });
1564
+ oracleAccountMap.set(market.amm.oracle.toString(), {
1565
+ pubkey: market.amm.oracle,
1566
+ isWritable: false,
1567
+ isSigner: false,
1568
+ });
1569
+ }
1570
+ }
1571
+ for (const spotPosition of settleeUserAccount.spotPositions) {
1572
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1573
+ const spotMarketAccount = this.getSpotMarketAccount(spotPosition.marketIndex);
1574
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
1575
+ pubkey: spotMarketAccount.pubkey,
1576
+ isSigner: false,
1577
+ isWritable: false,
1578
+ });
1579
+ if (!spotMarketAccount.marketIndex.eq(numericConstants_1.ZERO)) {
1580
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1581
+ pubkey: spotMarketAccount.oracle,
1582
+ isSigner: false,
1583
+ isWritable: false,
1584
+ });
1585
+ }
1586
+ }
1587
+ }
1588
+ const marketAccount = this.getPerpMarketAccount(marketIndex.toNumber());
1589
+ perpMarketAccountMap.set(marketIndex.toNumber(), {
1590
+ pubkey: marketAccount.pubkey,
1591
+ isSigner: false,
1592
+ isWritable: true,
1593
+ });
1594
+ oracleAccountMap.set(marketAccount.amm.oracle.toString(), {
1595
+ pubkey: marketAccount.amm.oracle,
1596
+ isSigner: false,
1597
+ isWritable: false,
1598
+ });
1599
+ spotMarketAccountMap.set(numericConstants_1.QUOTE_SPOT_MARKET_INDEX.toNumber(), {
1600
+ pubkey: this.getSpotMarketAccount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).pubkey,
1601
+ isSigner: false,
1602
+ isWritable: true,
1603
+ });
1604
+ const remainingAccounts = [
1605
+ ...oracleAccountMap.values(),
1606
+ ...spotMarketAccountMap.values(),
1607
+ ...perpMarketAccountMap.values(),
1608
+ ];
1609
+ return await this.program.instruction.settlePnl(marketIndex, {
1610
+ accounts: {
1611
+ state: await this.getStatePublicKey(),
1612
+ authority: this.wallet.publicKey,
1613
+ user: settleeUserAccountPublicKey,
1614
+ },
1615
+ remainingAccounts: remainingAccounts,
1616
+ });
1617
+ }
1618
+ async settleExpiredPosition(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
1619
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getSettleExpiredPositionIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex)), [], this.opts);
1620
+ return txSig;
1621
+ }
1622
+ async getSettleExpiredPositionIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
1159
1623
  const marketAccountMap = new Map();
1160
1624
  const oracleAccountMap = new Map();
1161
- const bankAccountMap = new Map();
1162
- for (const position of settleeUserAccount.positions) {
1625
+ const spotMarketAccountMap = new Map();
1626
+ for (const position of settleeUserAccount.perpPositions) {
1163
1627
  if (!(0, position_1.positionIsAvailable)(position)) {
1164
- const market = this.getMarketAccount(position.marketIndex);
1628
+ const market = this.getPerpMarketAccount(position.marketIndex);
1165
1629
  marketAccountMap.set(position.marketIndex.toNumber(), {
1166
1630
  pubkey: market.pubkey,
1167
1631
  isWritable: false,
@@ -1174,15 +1638,15 @@ class ClearingHouse {
1174
1638
  });
1175
1639
  }
1176
1640
  }
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(), {
1641
+ for (const userBankBalance of settleeUserAccount.spotPositions) {
1642
+ if (!userBankBalance.balance.eq(numericConstants_1.ZERO)) {
1643
+ const bankAccount = this.getSpotMarketAccount(userBankBalance.marketIndex);
1644
+ spotMarketAccountMap.set(userBankBalance.marketIndex.toNumber(), {
1181
1645
  pubkey: bankAccount.pubkey,
1182
1646
  isSigner: false,
1183
1647
  isWritable: false,
1184
1648
  });
1185
- if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
1649
+ if (!bankAccount.marketIndex.eq(numericConstants_1.ZERO)) {
1186
1650
  oracleAccountMap.set(bankAccount.oracle.toString(), {
1187
1651
  pubkey: bankAccount.oracle,
1188
1652
  isSigner: false,
@@ -1191,7 +1655,7 @@ class ClearingHouse {
1191
1655
  }
1192
1656
  }
1193
1657
  }
1194
- const marketAccount = this.getMarketAccount(marketIndex.toNumber());
1658
+ const marketAccount = this.getPerpMarketAccount(marketIndex.toNumber());
1195
1659
  marketAccountMap.set(marketIndex.toNumber(), {
1196
1660
  pubkey: marketAccount.pubkey,
1197
1661
  isSigner: false,
@@ -1202,17 +1666,17 @@ class ClearingHouse {
1202
1666
  isSigner: false,
1203
1667
  isWritable: false,
1204
1668
  });
1205
- bankAccountMap.set(numericConstants_1.QUOTE_ASSET_BANK_INDEX.toNumber(), {
1206
- pubkey: this.getBankAccount(numericConstants_1.QUOTE_ASSET_BANK_INDEX).pubkey,
1669
+ spotMarketAccountMap.set(numericConstants_1.QUOTE_SPOT_MARKET_INDEX.toNumber(), {
1670
+ pubkey: this.getSpotMarketAccount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).pubkey,
1207
1671
  isSigner: false,
1208
1672
  isWritable: true,
1209
1673
  });
1210
1674
  const remainingAccounts = [
1211
1675
  ...oracleAccountMap.values(),
1212
- ...bankAccountMap.values(),
1676
+ ...spotMarketAccountMap.values(),
1213
1677
  ...marketAccountMap.values(),
1214
1678
  ];
1215
- return await this.program.instruction.settlePnl(marketIndex, {
1679
+ return await this.program.instruction.settleExpiredPosition(marketIndex, {
1216
1680
  accounts: {
1217
1681
  state: await this.getStatePublicKey(),
1218
1682
  authority: this.wallet.publicKey,
@@ -1222,7 +1686,8 @@ class ClearingHouse {
1222
1686
  });
1223
1687
  }
1224
1688
  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);
1689
+ const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidatePerpIx(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount)), [], this.opts);
1690
+ this.marketLastSlotCache.set(marketIndex.toNumber(), slot);
1226
1691
  return txSig;
1227
1692
  }
1228
1693
  async getLiquidatePerpIx(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount) {
@@ -1230,7 +1695,7 @@ class ClearingHouse {
1230
1695
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1231
1696
  const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
1232
1697
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1233
- writableMarketIndex: marketIndex,
1698
+ writablePerpMarketIndex: marketIndex,
1234
1699
  counterPartyUserAccount: userAccount,
1235
1700
  });
1236
1701
  return await this.program.instruction.liquidatePerp(marketIndex, maxBaseAssetAmount, {
@@ -1245,17 +1710,17 @@ class ClearingHouse {
1245
1710
  remainingAccounts: remainingAccounts,
1246
1711
  });
1247
1712
  }
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);
1713
+ async liquidateBorrow(userAccountPublicKey, userAccount, assetmarketIndex, liabilitymarketIndex, maxLiabilityTransfer) {
1714
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidateBorrowIx(userAccountPublicKey, userAccount, assetmarketIndex, liabilitymarketIndex, maxLiabilityTransfer)), [], this.opts);
1250
1715
  return txSig;
1251
1716
  }
1252
- async getLiquidateBorrowIx(userAccountPublicKey, userAccount, assetBankIndex, liabilityBankIndex, maxLiabilityTransfer) {
1717
+ async getLiquidateBorrowIx(userAccountPublicKey, userAccount, assetmarketIndex, liabilitymarketIndex, maxLiabilityTransfer) {
1253
1718
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1254
1719
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1255
1720
  counterPartyUserAccount: userAccount,
1256
- writableBankIndexes: [liabilityBankIndex, assetBankIndex],
1721
+ writableSpotMarketIndexes: [liabilitymarketIndex, assetmarketIndex],
1257
1722
  });
1258
- return await this.program.instruction.liquidateBorrow(assetBankIndex, liabilityBankIndex, maxLiabilityTransfer, {
1723
+ return await this.program.instruction.liquidateBorrow(assetmarketIndex, liabilitymarketIndex, maxLiabilityTransfer, {
1259
1724
  accounts: {
1260
1725
  state: await this.getStatePublicKey(),
1261
1726
  authority: this.wallet.publicKey,
@@ -1265,18 +1730,19 @@ class ClearingHouse {
1265
1730
  remainingAccounts: remainingAccounts,
1266
1731
  });
1267
1732
  }
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);
1733
+ async liquidateBorrowForPerpPnl(userAccountPublicKey, userAccount, perpMarketIndex, liabilitymarketIndex, maxLiabilityTransfer) {
1734
+ const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilitymarketIndex, maxLiabilityTransfer)), [], this.opts);
1735
+ this.marketLastSlotCache.set(perpMarketIndex.toNumber(), slot);
1270
1736
  return txSig;
1271
1737
  }
1272
- async getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilityBankIndex, maxLiabilityTransfer) {
1738
+ async getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilitymarketIndex, maxLiabilityTransfer) {
1273
1739
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1274
1740
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1275
1741
  counterPartyUserAccount: userAccount,
1276
- writableMarketIndex: perpMarketIndex,
1277
- writableBankIndexes: [liabilityBankIndex],
1742
+ writablePerpMarketIndex: perpMarketIndex,
1743
+ writableSpotMarketIndexes: [liabilitymarketIndex],
1278
1744
  });
1279
- return await this.program.instruction.liquidateBorrowForPerpPnl(perpMarketIndex, liabilityBankIndex, maxLiabilityTransfer, {
1745
+ return await this.program.instruction.liquidateBorrowForPerpPnl(perpMarketIndex, liabilitymarketIndex, maxLiabilityTransfer, {
1280
1746
  accounts: {
1281
1747
  state: await this.getStatePublicKey(),
1282
1748
  authority: this.wallet.publicKey,
@@ -1286,18 +1752,19 @@ class ClearingHouse {
1286
1752
  remainingAccounts: remainingAccounts,
1287
1753
  });
1288
1754
  }
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);
1755
+ async liquidatePerpPnlForDeposit(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer) {
1756
+ const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer)), [], this.opts);
1757
+ this.marketLastSlotCache.set(perpMarketIndex.toNumber(), slot);
1291
1758
  return txSig;
1292
1759
  }
1293
- async getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetBankIndex, maxPnlTransfer) {
1760
+ async getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer) {
1294
1761
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1295
1762
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1296
1763
  counterPartyUserAccount: userAccount,
1297
- writableMarketIndex: perpMarketIndex,
1298
- writableBankIndexes: [assetBankIndex],
1764
+ writablePerpMarketIndex: perpMarketIndex,
1765
+ writableSpotMarketIndexes: [assetMarketIndex],
1299
1766
  });
1300
- return await this.program.instruction.liquidatePerpPnlForDeposit(perpMarketIndex, assetBankIndex, maxPnlTransfer, {
1767
+ return await this.program.instruction.liquidatePerpPnlForDeposit(perpMarketIndex, assetMarketIndex, maxPnlTransfer, {
1301
1768
  accounts: {
1302
1769
  state: await this.getStatePublicKey(),
1303
1770
  authority: this.wallet.publicKey,
@@ -1307,51 +1774,51 @@ class ClearingHouse {
1307
1774
  remainingAccounts: remainingAccounts,
1308
1775
  });
1309
1776
  }
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);
1777
+ async resolvePerpBankruptcy(userAccountPublicKey, userAccount, marketIndex) {
1778
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, marketIndex)), [], this.opts);
1312
1779
  return txSig;
1313
1780
  }
1314
- async getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, bankIndex, marketIndex) {
1781
+ async getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, marketIndex) {
1315
1782
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1316
1783
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1317
- writableMarketIndex: marketIndex,
1318
- writableBankIndexes: [bankIndex],
1784
+ writablePerpMarketIndex: marketIndex,
1785
+ writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
1319
1786
  counterPartyUserAccount: userAccount,
1320
1787
  });
1321
- const bank = this.getBankAccount(bankIndex);
1322
- return await this.program.instruction.resolvePerpBankruptcy(bankIndex, marketIndex, {
1788
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
1789
+ return await this.program.instruction.resolvePerpBankruptcy(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, marketIndex, {
1323
1790
  accounts: {
1324
1791
  state: await this.getStatePublicKey(),
1325
1792
  authority: this.wallet.publicKey,
1326
1793
  user: userAccountPublicKey,
1327
1794
  liquidator: liquidatorPublicKey,
1328
- bankVault: bank.vault,
1329
- insuranceFundVault: bank.insuranceFundVault,
1795
+ spotMarketVault: spotMarket.vault,
1796
+ insuranceFundVault: spotMarket.insuranceFundVault,
1330
1797
  clearingHouseSigner: this.getSignerPublicKey(),
1331
1798
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1332
1799
  },
1333
1800
  remainingAccounts: remainingAccounts,
1334
1801
  });
1335
1802
  }
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);
1803
+ async resolveBorrowBankruptcy(userAccountPublicKey, userAccount, marketIndex) {
1804
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getResolveBorrowBankruptcyIx(userAccountPublicKey, userAccount, marketIndex)), [], this.opts);
1338
1805
  return txSig;
1339
1806
  }
1340
- async getResolveBorrowBankruptcyIx(userAccountPublicKey, userAccount, bankIndex) {
1807
+ async getResolveBorrowBankruptcyIx(userAccountPublicKey, userAccount, marketIndex) {
1341
1808
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1342
1809
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1343
- writableBankIndexes: [bankIndex],
1810
+ writableSpotMarketIndexes: [marketIndex],
1344
1811
  counterPartyUserAccount: userAccount,
1345
1812
  });
1346
- const bank = this.getBankAccount(bankIndex);
1347
- return await this.program.instruction.resolveBorrowBankruptcy(bankIndex, {
1813
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
1814
+ return await this.program.instruction.resolveBorrowBankruptcy(marketIndex, {
1348
1815
  accounts: {
1349
1816
  state: await this.getStatePublicKey(),
1350
1817
  authority: this.wallet.publicKey,
1351
1818
  user: userAccountPublicKey,
1352
1819
  liquidator: liquidatorPublicKey,
1353
- bankVault: bank.vault,
1354
- insuranceFundVault: bank.insuranceFundVault,
1820
+ spotMarketVault: spotMarket.vault,
1821
+ insuranceFundVault: spotMarket.insuranceFundVault,
1355
1822
  clearingHouseSigner: this.getSignerPublicKey(),
1356
1823
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1357
1824
  },
@@ -1361,28 +1828,28 @@ class ClearingHouse {
1361
1828
  getRemainingAccountsWithCounterparty(params) {
1362
1829
  const counterPartyUserAccount = params.counterPartyUserAccount;
1363
1830
  const oracleAccountMap = new Map();
1364
- const bankAccountMap = new Map();
1831
+ const spotMarketAccountMap = new Map();
1365
1832
  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,
1833
+ for (const spotPosition of counterPartyUserAccount.spotPositions) {
1834
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1835
+ const spotMarket = this.getSpotMarketAccount(spotPosition.marketIndex);
1836
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
1837
+ pubkey: spotMarket.pubkey,
1371
1838
  isSigner: false,
1372
1839
  isWritable: false,
1373
1840
  });
1374
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1375
- oracleAccountMap.set(bankAccount.oracle.toString(), {
1376
- pubkey: bankAccount.oracle,
1841
+ if (!spotMarket.oracle.equals(web3_js_1.PublicKey.default)) {
1842
+ oracleAccountMap.set(spotMarket.oracle.toString(), {
1843
+ pubkey: spotMarket.oracle,
1377
1844
  isSigner: false,
1378
1845
  isWritable: false,
1379
1846
  });
1380
1847
  }
1381
1848
  }
1382
1849
  }
1383
- for (const position of counterPartyUserAccount.positions) {
1850
+ for (const position of counterPartyUserAccount.perpPositions) {
1384
1851
  if (!(0, position_1.positionIsAvailable)(position)) {
1385
- const market = this.getMarketAccount(position.marketIndex);
1852
+ const market = this.getPerpMarketAccount(position.marketIndex);
1386
1853
  marketAccountMap.set(position.marketIndex.toNumber(), {
1387
1854
  pubkey: market.pubkey,
1388
1855
  isWritable: false,
@@ -1404,7 +1871,7 @@ class ClearingHouse {
1404
1871
  // if cache has more recent slot than user positions account slot, add market to remaining accounts
1405
1872
  // otherwise remove from slot
1406
1873
  if (slot > lastUserPositionsSlot) {
1407
- const marketAccount = this.getMarketAccount(marketIndexNum);
1874
+ const marketAccount = this.getPerpMarketAccount(marketIndexNum);
1408
1875
  marketAccountMap.set(marketIndexNum, {
1409
1876
  pubkey: marketAccount.pubkey,
1410
1877
  isSigner: false,
@@ -1420,26 +1887,26 @@ class ClearingHouse {
1420
1887
  this.marketLastSlotCache.delete(marketIndexNum);
1421
1888
  }
1422
1889
  }
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,
1890
+ for (const spotPosition of userAccount.spotPositions) {
1891
+ if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
1892
+ const spotMarket = this.getSpotMarketAccount(spotPosition.marketIndex);
1893
+ spotMarketAccountMap.set(spotPosition.marketIndex.toNumber(), {
1894
+ pubkey: spotMarket.pubkey,
1428
1895
  isSigner: false,
1429
1896
  isWritable: false,
1430
1897
  });
1431
- if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1432
- oracleAccountMap.set(bankAccount.oracle.toString(), {
1433
- pubkey: bankAccount.oracle,
1898
+ if (!spotMarket.oracle.equals(web3_js_1.PublicKey.default)) {
1899
+ oracleAccountMap.set(spotMarket.oracle.toString(), {
1900
+ pubkey: spotMarket.oracle,
1434
1901
  isSigner: false,
1435
1902
  isWritable: false,
1436
1903
  });
1437
1904
  }
1438
1905
  }
1439
1906
  }
1440
- for (const position of userAccount.positions) {
1907
+ for (const position of userAccount.perpPositions) {
1441
1908
  if (!(0, position_1.positionIsAvailable)(position)) {
1442
- const market = this.getMarketAccount(position.marketIndex);
1909
+ const market = this.getPerpMarketAccount(position.marketIndex);
1443
1910
  marketAccountMap.set(position.marketIndex.toNumber(), {
1444
1911
  pubkey: market.pubkey,
1445
1912
  isWritable: false,
@@ -1452,8 +1919,8 @@ class ClearingHouse {
1452
1919
  });
1453
1920
  }
1454
1921
  }
1455
- if (params.writableMarketIndex) {
1456
- const market = this.getMarketAccount(params.writableMarketIndex);
1922
+ if (params.writablePerpMarketIndex) {
1923
+ const market = this.getPerpMarketAccount(params.writablePerpMarketIndex);
1457
1924
  marketAccountMap.set(market.marketIndex.toNumber(), {
1458
1925
  pubkey: market.pubkey,
1459
1926
  isSigner: false,
@@ -1465,17 +1932,17 @@ class ClearingHouse {
1465
1932
  isWritable: false,
1466
1933
  });
1467
1934
  }
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,
1935
+ if (params.writableSpotMarketIndexes) {
1936
+ for (const writableSpotMarketIndex of params.writableSpotMarketIndexes) {
1937
+ const spotMarketAccount = this.getSpotMarketAccount(writableSpotMarketIndex);
1938
+ spotMarketAccountMap.set(spotMarketAccount.marketIndex.toNumber(), {
1939
+ pubkey: spotMarketAccount.pubkey,
1473
1940
  isSigner: false,
1474
1941
  isWritable: true,
1475
1942
  });
1476
- if (!bank.oracle.equals(web3_js_1.PublicKey.default)) {
1477
- oracleAccountMap.set(bank.oracle.toString(), {
1478
- pubkey: bank.oracle,
1943
+ if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
1944
+ oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
1945
+ pubkey: spotMarketAccount.oracle,
1479
1946
  isSigner: false,
1480
1947
  isWritable: false,
1481
1948
  });
@@ -1484,7 +1951,7 @@ class ClearingHouse {
1484
1951
  }
1485
1952
  return [
1486
1953
  ...oracleAccountMap.values(),
1487
- ...bankAccountMap.values(),
1954
+ ...spotMarketAccountMap.values(),
1488
1955
  ...marketAccountMap.values(),
1489
1956
  ];
1490
1957
  }
@@ -1507,7 +1974,7 @@ class ClearingHouse {
1507
1974
  }
1508
1975
  async getSettleFundingPaymentIx(userAccount) {
1509
1976
  const user = (await this.program.account.user.fetch(userAccount));
1510
- const userPositions = user.positions;
1977
+ const userPositions = user.perpPositions;
1511
1978
  const remainingAccounts = [];
1512
1979
  for (const position of userPositions) {
1513
1980
  if (!(0, position_1.positionIsAvailable)(position)) {
@@ -1531,20 +1998,20 @@ class ClearingHouse {
1531
1998
  this.eventEmitter.emit(eventName, data);
1532
1999
  }
1533
2000
  getOracleDataForMarket(marketIndex) {
1534
- const oracleKey = this.getMarketAccount(marketIndex).amm.oracle;
2001
+ const oracleKey = this.getPerpMarketAccount(marketIndex).amm.oracle;
1535
2002
  const oracleData = this.getOraclePriceDataAndSlot(oracleKey).data;
1536
2003
  return oracleData;
1537
2004
  }
1538
- async initializeInsuranceFundStake(bankIndex) {
1539
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getInitializeInsuranceFundStakeIx(bankIndex)), [], this.opts);
2005
+ async initializeInsuranceFundStake(marketIndex) {
2006
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getInitializeInsuranceFundStakeIx(marketIndex)), [], this.opts);
1540
2007
  return txSig;
1541
2008
  }
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, {
2009
+ async getInitializeInsuranceFundStakeIx(marketIndex) {
2010
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
2011
+ return await this.program.instruction.initializeInsuranceFundStake(marketIndex, {
1545
2012
  accounts: {
1546
2013
  insuranceFundStake: ifStakeAccountPublicKey,
1547
- bank: this.getBankAccount(bankIndex).pubkey,
2014
+ spotMarket: this.getSpotMarketAccount(marketIndex).pubkey,
1548
2015
  userStats: this.getUserStatsAccountPublicKey(),
1549
2016
  authority: this.wallet.publicKey,
1550
2017
  payer: this.wallet.publicKey,
@@ -1554,80 +2021,80 @@ class ClearingHouse {
1554
2021
  },
1555
2022
  });
1556
2023
  }
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);
2024
+ async addInsuranceFundStake(marketIndex, amount, collateralAccountPublicKey) {
2025
+ const spotMarket = this.getSpotMarketAccount(marketIndex);
2026
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
1560
2027
  const remainingAccounts = this.getRemainingAccounts({
1561
- writableBankIndex: bankIndex,
2028
+ writableSpotMarketIndex: marketIndex,
1562
2029
  });
1563
- return await this.program.rpc.addInsuranceFundStake(bankIndex, amount, {
2030
+ return await this.program.rpc.addInsuranceFundStake(marketIndex, amount, {
1564
2031
  accounts: {
1565
2032
  state: await this.getStatePublicKey(),
1566
- bank: bank.pubkey,
2033
+ spotMarket: spotMarket.pubkey,
1567
2034
  insuranceFundStake: ifStakeAccountPublicKey,
1568
2035
  userStats: this.getUserStatsAccountPublicKey(),
1569
2036
  authority: this.wallet.publicKey,
1570
- insuranceFundVault: bank.insuranceFundVault,
2037
+ insuranceFundVault: spotMarket.insuranceFundVault,
1571
2038
  userTokenAccount: collateralAccountPublicKey,
1572
2039
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1573
2040
  },
1574
2041
  remainingAccounts,
1575
2042
  });
1576
2043
  }
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);
2044
+ async requestRemoveInsuranceFundStake(marketIndex, amount) {
2045
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
2046
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
1580
2047
  const remainingAccounts = this.getRemainingAccounts({
1581
- writableBankIndex: bankIndex,
2048
+ writableSpotMarketIndex: marketIndex,
1582
2049
  });
1583
- return await this.program.rpc.requestRemoveInsuranceFundStake(bankIndex, amount, {
2050
+ return await this.program.rpc.requestRemoveInsuranceFundStake(marketIndex, amount, {
1584
2051
  accounts: {
1585
2052
  state: await this.getStatePublicKey(),
1586
- bank: bank.pubkey,
2053
+ spotMarket: spotMarketAccount.pubkey,
1587
2054
  insuranceFundStake: ifStakeAccountPublicKey,
1588
2055
  userStats: this.getUserStatsAccountPublicKey(),
1589
2056
  authority: this.wallet.publicKey,
1590
- insuranceFundVault: bank.insuranceFundVault,
2057
+ insuranceFundVault: spotMarketAccount.insuranceFundVault,
1591
2058
  // userTokenAccount: collateralAccountPublicKey,
1592
2059
  // tokenProgram: TOKEN_PROGRAM_ID,
1593
2060
  },
1594
2061
  remainingAccounts,
1595
2062
  });
1596
2063
  }
1597
- async cancelRequestRemoveInsuranceFundStake(bankIndex) {
1598
- const bank = this.getBankAccount(bankIndex);
1599
- const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, bankIndex);
2064
+ async cancelRequestRemoveInsuranceFundStake(marketIndex) {
2065
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
2066
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
1600
2067
  const remainingAccounts = this.getRemainingAccounts({
1601
- writableBankIndex: bankIndex,
2068
+ writableSpotMarketIndex: marketIndex,
1602
2069
  });
1603
- return await this.program.rpc.cancelRequestRemoveInsuranceFundStake(bankIndex, {
2070
+ return await this.program.rpc.cancelRequestRemoveInsuranceFundStake(marketIndex, {
1604
2071
  accounts: {
1605
2072
  state: await this.getStatePublicKey(),
1606
- bank: bank.pubkey,
2073
+ spotMarket: spotMarketAccount.pubkey,
1607
2074
  insuranceFundStake: ifStakeAccountPublicKey,
1608
2075
  userStats: this.getUserStatsAccountPublicKey(),
1609
2076
  authority: this.wallet.publicKey,
1610
- insuranceFundVault: bank.insuranceFundVault,
2077
+ insuranceFundVault: spotMarketAccount.insuranceFundVault,
1611
2078
  // userTokenAccount: collateralAccountPublicKey,
1612
2079
  // tokenProgram: TOKEN_PROGRAM_ID,
1613
2080
  },
1614
2081
  remainingAccounts,
1615
2082
  });
1616
2083
  }
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);
2084
+ async removeInsuranceFundStake(marketIndex, collateralAccountPublicKey) {
2085
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
2086
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
1620
2087
  const remainingAccounts = this.getRemainingAccounts({
1621
- writableBankIndex: bankIndex,
2088
+ writableSpotMarketIndex: marketIndex,
1622
2089
  });
1623
- return await this.program.rpc.removeInsuranceFundStake(bankIndex, {
2090
+ return await this.program.rpc.removeInsuranceFundStake(marketIndex, {
1624
2091
  accounts: {
1625
2092
  state: await this.getStatePublicKey(),
1626
- bank: bank.pubkey,
2093
+ spotMarket: spotMarketAccount.pubkey,
1627
2094
  insuranceFundStake: ifStakeAccountPublicKey,
1628
2095
  userStats: this.getUserStatsAccountPublicKey(),
1629
2096
  authority: this.wallet.publicKey,
1630
- insuranceFundVault: bank.insuranceFundVault,
2097
+ insuranceFundVault: spotMarketAccount.insuranceFundVault,
1631
2098
  clearingHouseSigner: this.getSignerPublicKey(),
1632
2099
  userTokenAccount: collateralAccountPublicKey,
1633
2100
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
@@ -1635,22 +2102,44 @@ class ClearingHouse {
1635
2102
  remainingAccounts,
1636
2103
  });
1637
2104
  }
1638
- async settleRevenueToInsuranceFund(bankIndex) {
1639
- const bank = this.getBankAccount(bankIndex);
2105
+ async settleRevenueToInsuranceFund(marketIndex) {
2106
+ const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
1640
2107
  const remainingAccounts = this.getRemainingAccounts({
1641
- writableBankIndex: bankIndex,
2108
+ writableSpotMarketIndex: marketIndex,
1642
2109
  });
1643
- return await this.program.rpc.settleRevenueToInsuranceFund(bankIndex, {
2110
+ return await this.program.rpc.settleRevenueToInsuranceFund(marketIndex, {
1644
2111
  accounts: {
1645
2112
  state: await this.getStatePublicKey(),
1646
- bank: bank.pubkey,
1647
- bankVault: bank.vault,
2113
+ spotMarket: spotMarketAccount.pubkey,
2114
+ spotMarketVault: spotMarketAccount.vault,
1648
2115
  clearingHouseSigner: this.getSignerPublicKey(),
1649
- insuranceFundVault: bank.insuranceFundVault,
2116
+ insuranceFundVault: spotMarketAccount.insuranceFundVault,
1650
2117
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1651
2118
  },
1652
2119
  remainingAccounts,
1653
2120
  });
1654
2121
  }
2122
+ async resolvePerpPnlDeficit(spotMarketIndex, perpMarketIndex) {
2123
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getResolvePerpPnlDeficitIx(spotMarketIndex, perpMarketIndex)), [], this.opts);
2124
+ return txSig;
2125
+ }
2126
+ async getResolvePerpPnlDeficitIx(spotMarketIndex, perpMarketIndex) {
2127
+ const remainingAccounts = this.getRemainingAccounts({
2128
+ writablePerpMarketIndex: perpMarketIndex,
2129
+ writableSpotMarketIndex: spotMarketIndex,
2130
+ });
2131
+ const spotMarket = this.getSpotMarketAccount(spotMarketIndex);
2132
+ return await this.program.instruction.resolvePerpPnlDeficit(spotMarketIndex, perpMarketIndex, {
2133
+ accounts: {
2134
+ state: await this.getStatePublicKey(),
2135
+ authority: this.wallet.publicKey,
2136
+ spotMarketVault: spotMarket.vault,
2137
+ insuranceFundVault: spotMarket.insuranceFundVault,
2138
+ clearingHouseSigner: this.getSignerPublicKey(),
2139
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
2140
+ },
2141
+ remainingAccounts: remainingAccounts,
2142
+ });
2143
+ }
1655
2144
  }
1656
2145
  exports.ClearingHouse = ClearingHouse;