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

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 (58) hide show
  1. package/lib/addresses/pda.d.ts +4 -0
  2. package/lib/addresses/pda.js +27 -1
  3. package/lib/admin.d.ts +3 -0
  4. package/lib/admin.js +36 -10
  5. package/lib/clearingHouse.d.ts +11 -2
  6. package/lib/clearingHouse.js +140 -5
  7. package/lib/clearingHouseUser.d.ts +3 -1
  8. package/lib/clearingHouseUser.js +11 -9
  9. package/lib/config.js +1 -1
  10. package/lib/constants/banks.d.ts +2 -0
  11. package/lib/constants/banks.js +9 -0
  12. package/lib/constants/numericConstants.d.ts +2 -0
  13. package/lib/constants/numericConstants.js +4 -1
  14. package/lib/events/eventSubscriber.d.ts +4 -2
  15. package/lib/events/eventSubscriber.js +16 -9
  16. package/lib/events/fetchLogs.d.ts +10 -1
  17. package/lib/events/fetchLogs.js +27 -7
  18. package/lib/events/pollingLogProvider.d.ts +2 -1
  19. package/lib/events/pollingLogProvider.js +6 -2
  20. package/lib/events/sort.js +7 -10
  21. package/lib/events/types.d.ts +4 -2
  22. package/lib/events/types.js +2 -0
  23. package/lib/examples/makeTradeExample.js +13 -1
  24. package/lib/idl/clearing_house.json +1081 -173
  25. package/lib/index.d.ts +2 -0
  26. package/lib/index.js +2 -0
  27. package/lib/math/amm.d.ts +3 -1
  28. package/lib/math/amm.js +41 -3
  29. package/lib/math/insurance.d.ts +4 -0
  30. package/lib/math/insurance.js +27 -0
  31. package/lib/math/margin.d.ts +1 -1
  32. package/lib/math/margin.js +5 -7
  33. package/lib/math/position.js +1 -1
  34. package/lib/types.d.ts +79 -24
  35. package/lib/types.js +7 -4
  36. package/package.json +1 -1
  37. package/src/addresses/pda.ts +56 -0
  38. package/src/admin.ts +64 -18
  39. package/src/clearingHouse.ts +230 -10
  40. package/src/clearingHouseUser.ts +16 -11
  41. package/src/config.ts +1 -1
  42. package/src/constants/banks.ts +16 -0
  43. package/src/constants/numericConstants.ts +4 -0
  44. package/src/events/eventSubscriber.ts +20 -12
  45. package/src/events/fetchLogs.ts +35 -8
  46. package/src/events/pollingLogProvider.ts +10 -2
  47. package/src/events/sort.ts +10 -14
  48. package/src/events/types.ts +7 -1
  49. package/src/examples/makeTradeExample.ts +20 -1
  50. package/src/idl/clearing_house.json +1081 -173
  51. package/src/index.ts +2 -0
  52. package/src/math/amm.ts +67 -2
  53. package/src/math/insurance.ts +35 -0
  54. package/src/math/margin.ts +3 -10
  55. package/src/math/position.ts +2 -2
  56. package/src/types.ts +83 -24
  57. package/src/events/eventSubscriber.js +0 -139
  58. package/src/events/sort.js +0 -44
@@ -11,3 +11,7 @@ export declare function getMarketPublicKey(programId: PublicKey, marketIndex: BN
11
11
  export declare function getBankPublicKey(programId: PublicKey, bankIndex: BN): Promise<PublicKey>;
12
12
  export declare function getBankVaultPublicKey(programId: PublicKey, bankIndex: BN): Promise<PublicKey>;
13
13
  export declare function getBankVaultAuthorityPublicKey(programId: PublicKey, bankIndex: BN): Promise<PublicKey>;
14
+ export declare function getInsuranceFundVaultPublicKey(programId: PublicKey, bankIndex: BN): Promise<PublicKey>;
15
+ export declare function getInsuranceFundVaultAuthorityPublicKey(programId: PublicKey, bankIndex: BN): Promise<PublicKey>;
16
+ export declare function getInsuranceFundStakeAccountPublicKey(programId: PublicKey, authority: PublicKey, bankIndex: BN): PublicKey;
17
+ export declare function getClearingHouseSignerPublicKey(programId: PublicKey): PublicKey;
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.getBankVaultAuthorityPublicKey = exports.getBankVaultPublicKey = exports.getBankPublicKey = exports.getMarketPublicKey = exports.getUserStatsAccountPublicKey = exports.getUserAccountPublicKeySync = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getClearingHouseStateAccountPublicKey = exports.getClearingHouseStateAccountPublicKeyAndNonce = void 0;
26
+ exports.getClearingHouseSignerPublicKey = exports.getInsuranceFundStakeAccountPublicKey = exports.getInsuranceFundVaultAuthorityPublicKey = exports.getInsuranceFundVaultPublicKey = exports.getBankVaultAuthorityPublicKey = exports.getBankVaultPublicKey = exports.getBankPublicKey = exports.getMarketPublicKey = exports.getUserStatsAccountPublicKey = exports.getUserAccountPublicKeySync = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getClearingHouseStateAccountPublicKey = exports.getClearingHouseStateAccountPublicKeyAndNonce = void 0;
27
27
  const anchor = __importStar(require("@project-serum/anchor"));
28
28
  async function getClearingHouseStateAccountPublicKeyAndNonce(programId) {
29
29
  return anchor.web3.PublicKey.findProgramAddress([Buffer.from(anchor.utils.bytes.utf8.encode('clearing_house'))], programId);
@@ -88,3 +88,29 @@ async function getBankVaultAuthorityPublicKey(programId, bankIndex) {
88
88
  ], programId))[0];
89
89
  }
90
90
  exports.getBankVaultAuthorityPublicKey = getBankVaultAuthorityPublicKey;
91
+ async function getInsuranceFundVaultPublicKey(programId, bankIndex) {
92
+ return (await anchor.web3.PublicKey.findProgramAddress([
93
+ Buffer.from(anchor.utils.bytes.utf8.encode('insurance_fund_vault')),
94
+ bankIndex.toArrayLike(Buffer, 'le', 8),
95
+ ], programId))[0];
96
+ }
97
+ exports.getInsuranceFundVaultPublicKey = getInsuranceFundVaultPublicKey;
98
+ async function getInsuranceFundVaultAuthorityPublicKey(programId, bankIndex) {
99
+ return (await anchor.web3.PublicKey.findProgramAddress([
100
+ Buffer.from(anchor.utils.bytes.utf8.encode('insurance_fund_vault_authority')),
101
+ bankIndex.toArrayLike(Buffer, 'le', 8),
102
+ ], programId))[0];
103
+ }
104
+ exports.getInsuranceFundVaultAuthorityPublicKey = getInsuranceFundVaultAuthorityPublicKey;
105
+ function getInsuranceFundStakeAccountPublicKey(programId, authority, bankIndex) {
106
+ return anchor.web3.PublicKey.findProgramAddressSync([
107
+ Buffer.from(anchor.utils.bytes.utf8.encode('insurance_fund_stake')),
108
+ authority.toBuffer(),
109
+ bankIndex.toArrayLike(Buffer, 'le', 8),
110
+ ], programId)[0];
111
+ }
112
+ exports.getInsuranceFundStakeAccountPublicKey = getInsuranceFundStakeAccountPublicKey;
113
+ function getClearingHouseSignerPublicKey(programId) {
114
+ return anchor.web3.PublicKey.findProgramAddressSync([Buffer.from(anchor.utils.bytes.utf8.encode('clearing_house_signer'))], programId)[0];
115
+ }
116
+ exports.getClearingHouseSignerPublicKey = getClearingHouseSignerPublicKey;
package/lib/admin.d.ts CHANGED
@@ -20,6 +20,7 @@ export declare class Admin extends ClearingHouse {
20
20
  updateCurveUpdateIntensity(marketIndex: BN, curveUpdateIntensity: number): Promise<TransactionSignature>;
21
21
  updateMarginRatio(marketIndex: BN, marginRatioInitial: number, marginRatioMaintenance: number): Promise<TransactionSignature>;
22
22
  updateMarketBaseSpread(marketIndex: BN, baseSpread: number): Promise<TransactionSignature>;
23
+ updateAmmJitIntensity(marketIndex: BN, ammJitIntensity: number): Promise<TransactionSignature>;
23
24
  updateMarketMaxSpread(marketIndex: BN, maxSpread: number): Promise<TransactionSignature>;
24
25
  updatePartialLiquidationClosePercentage(numerator: BN, denominator: BN): Promise<TransactionSignature>;
25
26
  updatePartialLiquidationPenaltyPercentage(numerator: BN, denominator: BN): Promise<TransactionSignature>;
@@ -30,6 +31,8 @@ export declare class Admin extends ClearingHouse {
30
31
  updateFee(fees: FeeStructure): Promise<TransactionSignature>;
31
32
  updateOracleGuardRails(oracleGuardRails: OracleGuardRails): Promise<TransactionSignature>;
32
33
  updateBankWithdrawGuardThreshold(bankIndex: BN, withdrawGuardThreshold: BN): Promise<TransactionSignature>;
34
+ updateBankIfFactor(bankIndex: BN, userIfFactor: BN, totalIfFactor: BN, liquidationIfFactor: BN): Promise<TransactionSignature>;
35
+ updateBankInsuranceWithdrawEscrowPeriod(bankIndex: BN, insuranceWithdrawEscrowPeriod: BN): Promise<TransactionSignature>;
33
36
  updateLpCooldownTime(marketIndex: BN, cooldownTime: BN): Promise<TransactionSignature>;
34
37
  updateMarketOracle(marketIndex: BN, oracle: PublicKey, oracleSource: OracleSource): Promise<TransactionSignature>;
35
38
  updateMarketMinimumQuoteAssetTradeSize(marketIndex: BN, minimumTradeSize: BN): Promise<TransactionSignature>;
package/lib/admin.js CHANGED
@@ -40,17 +40,16 @@ class Admin extends clearingHouse_1.ClearingHouse {
40
40
  if (stateAccountRPCResponse.value !== null) {
41
41
  throw new Error('Clearing house already initialized');
42
42
  }
43
- const [insuranceVaultPublicKey] = await web3_js_1.PublicKey.findProgramAddress([Buffer.from(anchor.utils.bytes.utf8.encode('insurance_vault'))], this.program.programId);
44
- const [insuranceVaultAuthority] = await web3_js_1.PublicKey.findProgramAddress([insuranceVaultPublicKey.toBuffer()], this.program.programId);
45
43
  const [clearingHouseStatePublicKey] = await (0, pda_1.getClearingHouseStateAccountPublicKeyAndNonce)(this.program.programId);
44
+ const [insuranceVaultPublicKey] = await web3_js_1.PublicKey.findProgramAddress([Buffer.from(anchor.utils.bytes.utf8.encode('insurance_vault'))], this.program.programId);
46
45
  const initializeTx = await this.program.transaction.initialize(adminControlsPrices, {
47
46
  accounts: {
48
47
  admin: this.wallet.publicKey,
49
48
  state: clearingHouseStatePublicKey,
50
49
  quoteAssetMint: usdcMint,
51
- insuranceVault: insuranceVaultPublicKey,
52
- insuranceVaultAuthority: insuranceVaultAuthority,
53
50
  rent: web3_js_1.SYSVAR_RENT_PUBKEY,
51
+ insuranceVault: insuranceVaultPublicKey,
52
+ clearingHouseSigner: this.getSignerPublicKey(),
54
53
  systemProgram: anchor.web3.SystemProgram.programId,
55
54
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
56
55
  },
@@ -62,14 +61,15 @@ class Admin extends clearingHouse_1.ClearingHouse {
62
61
  const bankIndex = this.getStateAccount().numberOfBanks;
63
62
  const bank = await (0, pda_1.getBankPublicKey)(this.program.programId, bankIndex);
64
63
  const bankVault = await (0, pda_1.getBankVaultPublicKey)(this.program.programId, bankIndex);
65
- const bankVaultAuthority = await (0, pda_1.getBankVaultAuthorityPublicKey)(this.program.programId, bankIndex);
64
+ const insuranceFundVault = await (0, pda_1.getInsuranceFundVaultPublicKey)(this.program.programId, bankIndex);
66
65
  const initializeTx = await this.program.transaction.initializeBank(optimalUtilization, optimalRate, maxRate, oracleSource, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight, imfFactor, liquidationFee, {
67
66
  accounts: {
68
67
  admin: this.wallet.publicKey,
69
68
  state: await this.getStatePublicKey(),
70
69
  bank,
71
70
  bankVault,
72
- bankVaultAuthority,
71
+ insuranceFundVault,
72
+ clearingHouseSigner: this.getSignerPublicKey(),
73
73
  bankMint: mint,
74
74
  oracle,
75
75
  rent: web3_js_1.SYSVAR_RENT_PUBKEY,
@@ -184,7 +184,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
184
184
  state: await this.getStatePublicKey(),
185
185
  bank: bank.pubkey,
186
186
  insuranceVault: state.insuranceVault,
187
- insuranceVaultAuthority: state.insuranceVaultAuthority,
187
+ clearingHouseSigner: this.getSignerPublicKey(),
188
188
  recipient: recipient,
189
189
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
190
190
  },
@@ -200,7 +200,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
200
200
  market: marketPublicKey,
201
201
  bank: bank.pubkey,
202
202
  bankVault: bank.vault,
203
- bankVaultAuthority: bank.vaultAuthority,
203
+ clearingHouseSigner: this.getSignerPublicKey(),
204
204
  recipient: recipient,
205
205
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
206
206
  },
@@ -215,10 +215,9 @@ class Admin extends clearingHouse_1.ClearingHouse {
215
215
  state: await this.getStatePublicKey(),
216
216
  market: await (0, pda_1.getMarketPublicKey)(this.program.programId, marketIndex),
217
217
  insuranceVault: state.insuranceVault,
218
- insuranceVaultAuthority: state.insuranceVaultAuthority,
218
+ clearingHouseSigner: this.getSignerPublicKey(),
219
219
  bank: bank.pubkey,
220
220
  bankVault: bank.vault,
221
- bankVaultAuthority: bank.vaultAuthority,
222
221
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
223
222
  },
224
223
  });
@@ -260,6 +259,15 @@ class Admin extends clearingHouse_1.ClearingHouse {
260
259
  },
261
260
  });
262
261
  }
262
+ async updateAmmJitIntensity(marketIndex, ammJitIntensity) {
263
+ return await this.program.rpc.updateAmmJitIntensity(ammJitIntensity, {
264
+ accounts: {
265
+ admin: this.wallet.publicKey,
266
+ state: await this.getStatePublicKey(),
267
+ market: await (0, pda_1.getMarketPublicKey)(this.program.programId, marketIndex),
268
+ },
269
+ });
270
+ }
263
271
  async updateMarketMaxSpread(marketIndex, maxSpread) {
264
272
  return await this.program.rpc.updateMarketMaxSpread(maxSpread, {
265
273
  accounts: {
@@ -342,6 +350,24 @@ class Admin extends clearingHouse_1.ClearingHouse {
342
350
  },
343
351
  });
344
352
  }
353
+ async updateBankIfFactor(bankIndex, userIfFactor, totalIfFactor, liquidationIfFactor) {
354
+ return await this.program.rpc.updateBankIfFactor(bankIndex, userIfFactor, totalIfFactor, liquidationIfFactor, {
355
+ accounts: {
356
+ admin: this.wallet.publicKey,
357
+ state: await this.getStatePublicKey(),
358
+ bank: await (0, pda_1.getBankPublicKey)(this.program.programId, bankIndex),
359
+ },
360
+ });
361
+ }
362
+ async updateBankInsuranceWithdrawEscrowPeriod(bankIndex, insuranceWithdrawEscrowPeriod) {
363
+ return await this.program.rpc.updateBankInsuranceWithdrawEscrowPeriod(insuranceWithdrawEscrowPeriod, {
364
+ accounts: {
365
+ admin: this.wallet.publicKey,
366
+ state: await this.getStatePublicKey(),
367
+ bank: await (0, pda_1.getBankPublicKey)(this.program.programId, bankIndex),
368
+ },
369
+ });
370
+ }
345
371
  async updateLpCooldownTime(marketIndex, cooldownTime) {
346
372
  return await this.program.rpc.updateLpCooldownTime(cooldownTime, {
347
373
  accounts: {
@@ -47,6 +47,8 @@ export declare class ClearingHouse {
47
47
  unsubscribeUsers(): Promise<void>[];
48
48
  statePublicKey?: PublicKey;
49
49
  getStatePublicKey(): Promise<PublicKey>;
50
+ signerPublicKey?: PublicKey;
51
+ getSignerPublicKey(): PublicKey;
50
52
  getStateAccount(): StateAccount;
51
53
  getMarketAccount(marketIndex: BN | number): MarketAccount | undefined;
52
54
  getMarketAccounts(): MarketAccount[];
@@ -149,8 +151,8 @@ export declare class ClearingHouse {
149
151
  getLiquidateBorrowForPerpPnlIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, perpMarketIndex: BN, liabilityBankIndex: BN, maxLiabilityTransfer: BN): Promise<TransactionInstruction>;
150
152
  liquidatePerpPnlForDeposit(userAccountPublicKey: PublicKey, userAccount: UserAccount, perpMarketIndex: BN, assetBankIndex: BN, maxPnlTransfer: BN): Promise<TransactionSignature>;
151
153
  getLiquidatePerpPnlForDepositIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, perpMarketIndex: BN, assetBankIndex: BN, maxPnlTransfer: BN): Promise<TransactionInstruction>;
152
- resolvePerpBankruptcy(userAccountPublicKey: PublicKey, userAccount: UserAccount, marketIndex: BN): Promise<TransactionSignature>;
153
- getResolvePerpBankruptcyIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, marketIndex: BN): Promise<TransactionInstruction>;
154
+ resolvePerpBankruptcy(userAccountPublicKey: PublicKey, userAccount: UserAccount, bankIndex: BN, marketIndex: BN): Promise<TransactionSignature>;
155
+ getResolvePerpBankruptcyIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, bankIndex: BN, marketIndex: BN): Promise<TransactionInstruction>;
154
156
  resolveBorrowBankruptcy(userAccountPublicKey: PublicKey, userAccount: UserAccount, bankIndex: BN): Promise<TransactionSignature>;
155
157
  getResolveBorrowBankruptcyIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, bankIndex: BN): Promise<TransactionInstruction>;
156
158
  getRemainingAccountsWithCounterparty(params: {
@@ -164,4 +166,11 @@ export declare class ClearingHouse {
164
166
  getSettleFundingPaymentIx(userAccount: PublicKey): Promise<TransactionInstruction>;
165
167
  triggerEvent(eventName: keyof ClearingHouseAccountEvents, data?: any): void;
166
168
  getOracleDataForMarket(marketIndex: BN): OraclePriceData;
169
+ initializeInsuranceFundStake(bankIndex: BN): Promise<TransactionSignature>;
170
+ getInitializeInsuranceFundStakeIx(bankIndex: BN): Promise<TransactionInstruction>;
171
+ addInsuranceFundStake(bankIndex: BN, amount: BN, collateralAccountPublicKey: PublicKey): Promise<TransactionSignature>;
172
+ requestRemoveInsuranceFundStake(bankIndex: BN, amount: BN): Promise<TransactionSignature>;
173
+ cancelRequestRemoveInsuranceFundStake(bankIndex: BN): Promise<TransactionSignature>;
174
+ removeInsuranceFundStake(bankIndex: BN, collateralAccountPublicKey: PublicKey): Promise<TransactionSignature>;
175
+ settleRevenueToInsuranceFund(bankIndex: BN): Promise<TransactionSignature>;
167
176
  }
@@ -159,6 +159,13 @@ class ClearingHouse {
159
159
  this.statePublicKey = await (0, pda_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
160
160
  return this.statePublicKey;
161
161
  }
162
+ getSignerPublicKey() {
163
+ if (this.signerPublicKey) {
164
+ return this.signerPublicKey;
165
+ }
166
+ this.signerPublicKey = (0, pda_1.getClearingHouseSignerPublicKey)(this.program.programId);
167
+ return this.signerPublicKey;
168
+ }
162
169
  getStateAccount() {
163
170
  return this.accountSubscriber.getStateAccountAndSlot().data;
164
171
  }
@@ -631,7 +638,7 @@ class ClearingHouse {
631
638
  state: await this.getStatePublicKey(),
632
639
  bank: bank.pubkey,
633
640
  bankVault: bank.vault,
634
- bankVaultAuthority: bank.vaultAuthority,
641
+ clearingHouseSigner: this.getSignerPublicKey(),
635
642
  user: userAccountPublicKey,
636
643
  userStats: this.getUserStatsAccountPublicKey(),
637
644
  userTokenAccount: userTokenAccount,
@@ -1300,22 +1307,28 @@ class ClearingHouse {
1300
1307
  remainingAccounts: remainingAccounts,
1301
1308
  });
1302
1309
  }
1303
- async resolvePerpBankruptcy(userAccountPublicKey, userAccount, marketIndex) {
1304
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, marketIndex)), [], this.opts);
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);
1305
1312
  return txSig;
1306
1313
  }
1307
- async getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, marketIndex) {
1314
+ async getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, bankIndex, marketIndex) {
1308
1315
  const liquidatorPublicKey = await this.getUserAccountPublicKey();
1309
1316
  const remainingAccounts = this.getRemainingAccountsWithCounterparty({
1310
1317
  writableMarketIndex: marketIndex,
1318
+ writableBankIndexes: [bankIndex],
1311
1319
  counterPartyUserAccount: userAccount,
1312
1320
  });
1313
- return await this.program.instruction.resolvePerpBankruptcy(marketIndex, {
1321
+ const bank = this.getBankAccount(bankIndex);
1322
+ return await this.program.instruction.resolvePerpBankruptcy(bankIndex, marketIndex, {
1314
1323
  accounts: {
1315
1324
  state: await this.getStatePublicKey(),
1316
1325
  authority: this.wallet.publicKey,
1317
1326
  user: userAccountPublicKey,
1318
1327
  liquidator: liquidatorPublicKey,
1328
+ bankVault: bank.vault,
1329
+ insuranceFundVault: bank.insuranceFundVault,
1330
+ clearingHouseSigner: this.getSignerPublicKey(),
1331
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1319
1332
  },
1320
1333
  remainingAccounts: remainingAccounts,
1321
1334
  });
@@ -1330,12 +1343,17 @@ class ClearingHouse {
1330
1343
  writableBankIndexes: [bankIndex],
1331
1344
  counterPartyUserAccount: userAccount,
1332
1345
  });
1346
+ const bank = this.getBankAccount(bankIndex);
1333
1347
  return await this.program.instruction.resolveBorrowBankruptcy(bankIndex, {
1334
1348
  accounts: {
1335
1349
  state: await this.getStatePublicKey(),
1336
1350
  authority: this.wallet.publicKey,
1337
1351
  user: userAccountPublicKey,
1338
1352
  liquidator: liquidatorPublicKey,
1353
+ bankVault: bank.vault,
1354
+ insuranceFundVault: bank.insuranceFundVault,
1355
+ clearingHouseSigner: this.getSignerPublicKey(),
1356
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1339
1357
  },
1340
1358
  remainingAccounts: remainingAccounts,
1341
1359
  });
@@ -1517,5 +1535,122 @@ class ClearingHouse {
1517
1535
  const oracleData = this.getOraclePriceDataAndSlot(oracleKey).data;
1518
1536
  return oracleData;
1519
1537
  }
1538
+ async initializeInsuranceFundStake(bankIndex) {
1539
+ const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getInitializeInsuranceFundStakeIx(bankIndex)), [], this.opts);
1540
+ return txSig;
1541
+ }
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, {
1545
+ accounts: {
1546
+ insuranceFundStake: ifStakeAccountPublicKey,
1547
+ bank: this.getBankAccount(bankIndex).pubkey,
1548
+ userStats: this.getUserStatsAccountPublicKey(),
1549
+ authority: this.wallet.publicKey,
1550
+ payer: this.wallet.publicKey,
1551
+ rent: anchor.web3.SYSVAR_RENT_PUBKEY,
1552
+ systemProgram: anchor.web3.SystemProgram.programId,
1553
+ state: await this.getStatePublicKey(),
1554
+ },
1555
+ });
1556
+ }
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);
1560
+ const remainingAccounts = this.getRemainingAccounts({
1561
+ writableBankIndex: bankIndex,
1562
+ });
1563
+ return await this.program.rpc.addInsuranceFundStake(bankIndex, amount, {
1564
+ accounts: {
1565
+ state: await this.getStatePublicKey(),
1566
+ bank: bank.pubkey,
1567
+ insuranceFundStake: ifStakeAccountPublicKey,
1568
+ userStats: this.getUserStatsAccountPublicKey(),
1569
+ authority: this.wallet.publicKey,
1570
+ insuranceFundVault: bank.insuranceFundVault,
1571
+ userTokenAccount: collateralAccountPublicKey,
1572
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1573
+ },
1574
+ remainingAccounts,
1575
+ });
1576
+ }
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);
1580
+ const remainingAccounts = this.getRemainingAccounts({
1581
+ writableBankIndex: bankIndex,
1582
+ });
1583
+ return await this.program.rpc.requestRemoveInsuranceFundStake(bankIndex, amount, {
1584
+ accounts: {
1585
+ state: await this.getStatePublicKey(),
1586
+ bank: bank.pubkey,
1587
+ insuranceFundStake: ifStakeAccountPublicKey,
1588
+ userStats: this.getUserStatsAccountPublicKey(),
1589
+ authority: this.wallet.publicKey,
1590
+ insuranceFundVault: bank.insuranceFundVault,
1591
+ // userTokenAccount: collateralAccountPublicKey,
1592
+ // tokenProgram: TOKEN_PROGRAM_ID,
1593
+ },
1594
+ remainingAccounts,
1595
+ });
1596
+ }
1597
+ async cancelRequestRemoveInsuranceFundStake(bankIndex) {
1598
+ const bank = this.getBankAccount(bankIndex);
1599
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, bankIndex);
1600
+ const remainingAccounts = this.getRemainingAccounts({
1601
+ writableBankIndex: bankIndex,
1602
+ });
1603
+ return await this.program.rpc.cancelRequestRemoveInsuranceFundStake(bankIndex, {
1604
+ accounts: {
1605
+ state: await this.getStatePublicKey(),
1606
+ bank: bank.pubkey,
1607
+ insuranceFundStake: ifStakeAccountPublicKey,
1608
+ userStats: this.getUserStatsAccountPublicKey(),
1609
+ authority: this.wallet.publicKey,
1610
+ insuranceFundVault: bank.insuranceFundVault,
1611
+ // userTokenAccount: collateralAccountPublicKey,
1612
+ // tokenProgram: TOKEN_PROGRAM_ID,
1613
+ },
1614
+ remainingAccounts,
1615
+ });
1616
+ }
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);
1620
+ const remainingAccounts = this.getRemainingAccounts({
1621
+ writableBankIndex: bankIndex,
1622
+ });
1623
+ return await this.program.rpc.removeInsuranceFundStake(bankIndex, {
1624
+ accounts: {
1625
+ state: await this.getStatePublicKey(),
1626
+ bank: bank.pubkey,
1627
+ insuranceFundStake: ifStakeAccountPublicKey,
1628
+ userStats: this.getUserStatsAccountPublicKey(),
1629
+ authority: this.wallet.publicKey,
1630
+ insuranceFundVault: bank.insuranceFundVault,
1631
+ clearingHouseSigner: this.getSignerPublicKey(),
1632
+ userTokenAccount: collateralAccountPublicKey,
1633
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1634
+ },
1635
+ remainingAccounts,
1636
+ });
1637
+ }
1638
+ async settleRevenueToInsuranceFund(bankIndex) {
1639
+ const bank = this.getBankAccount(bankIndex);
1640
+ const remainingAccounts = this.getRemainingAccounts({
1641
+ writableBankIndex: bankIndex,
1642
+ });
1643
+ return await this.program.rpc.settleRevenueToInsuranceFund(bankIndex, {
1644
+ accounts: {
1645
+ state: await this.getStatePublicKey(),
1646
+ bank: bank.pubkey,
1647
+ bankVault: bank.vault,
1648
+ clearingHouseSigner: this.getSignerPublicKey(),
1649
+ insuranceFundVault: bank.insuranceFundVault,
1650
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1651
+ },
1652
+ remainingAccounts,
1653
+ });
1654
+ }
1520
1655
  }
1521
1656
  exports.ClearingHouse = ClearingHouse;
@@ -52,7 +52,9 @@ export declare class ClearingHouseUser {
52
52
  exists(): Promise<boolean>;
53
53
  /**
54
54
  * calculates the market position if the lp position was settled
55
- * @returns : userPosition
55
+ * @returns : the settled userPosition
56
+ * @returns : the dust base asset amount (ie, < stepsize)
57
+ * @returns : pnl from settle
56
58
  */
57
59
  getSettledLPPosition(marketIndex: BN): [UserPosition, BN, BN];
58
60
  /**
@@ -105,7 +105,9 @@ class ClearingHouseUser {
105
105
  }
106
106
  /**
107
107
  * calculates the market position if the lp position was settled
108
- * @returns : userPosition
108
+ * @returns : the settled userPosition
109
+ * @returns : the dust base asset amount (ie, < stepsize)
110
+ * @returns : pnl from settle
109
111
  */
110
112
  getSettledLPPosition(marketIndex) {
111
113
  const _position = this.getUserPosition(marketIndex);
@@ -138,8 +140,6 @@ class ClearingHouseUser {
138
140
  }
139
141
  const standardizedBaa = deltaBaa.sub(remainderBaa);
140
142
  const reaminderPerLP = remainderBaa.mul(numericConstants_1.AMM_RESERVE_PRECISION).div(nShares);
141
- position.baseAssetAmount = position.baseAssetAmount.add(standardizedBaa);
142
- position.quoteAssetAmount = position.quoteAssetAmount.add(deltaQaa);
143
143
  position.lastNetBaseAssetAmountPerLp =
144
144
  market.amm.marketPositionPerLp.baseAssetAmount.sub(reaminderPerLP);
145
145
  let updateType;
@@ -168,13 +168,15 @@ class ClearingHouseUser {
168
168
  newQuoteEntry = position.quoteEntryAmount.sub(position.quoteEntryAmount
169
169
  .mul(deltaBaa.abs())
170
170
  .div(position.baseAssetAmount.abs()));
171
- pnl = position.quoteEntryAmount.sub(newQuoteEntry);
171
+ pnl = position.quoteEntryAmount.sub(newQuoteEntry).add(deltaQaa);
172
172
  }
173
173
  else {
174
174
  newQuoteEntry = deltaQaa.sub(deltaQaa.mul(position.baseAssetAmount.abs()).div(deltaBaa.abs()));
175
175
  pnl = position.quoteEntryAmount.add(deltaQaa.sub(newQuoteEntry));
176
176
  }
177
177
  position.quoteEntryAmount = newQuoteEntry;
178
+ position.baseAssetAmount = position.baseAssetAmount.add(standardizedBaa);
179
+ position.quoteAssetAmount = position.quoteAssetAmount.add(deltaQaa);
178
180
  if (position.baseAssetAmount.gt(numericConstants_1.ZERO)) {
179
181
  position.lastCumulativeFundingRate = market.amm.cumulativeFundingRateLong;
180
182
  }
@@ -363,7 +365,7 @@ class ClearingHouseUser {
363
365
  getTotalPositionValue() {
364
366
  return this.getUserAccount().positions.reduce((positionValue, marketPosition) => {
365
367
  const market = this.clearingHouse.getMarketAccount(marketPosition.marketIndex);
366
- const posVal = (0, margin_1.calculateMarginBaseAssetValue)(market, marketPosition, this.getOracleDataForMarket(market.marketIndex));
368
+ const posVal = (0, margin_1.calculateBaseAssetValueWithOracle)(market, marketPosition, this.getOracleDataForMarket(market.marketIndex));
367
369
  return positionValue.add(posVal);
368
370
  }, numericConstants_1.ZERO);
369
371
  }
@@ -374,7 +376,7 @@ class ClearingHouseUser {
374
376
  getPositionValue(marketIndex, oraclePriceData) {
375
377
  const userPosition = this.getUserPosition(marketIndex) || this.getEmptyPosition(marketIndex);
376
378
  const market = this.clearingHouse.getMarketAccount(userPosition.marketIndex);
377
- return (0, margin_1.calculateMarginBaseAssetValue)(market, userPosition, oraclePriceData);
379
+ return (0, margin_1.calculateBaseAssetValueWithOracle)(market, userPosition, oraclePriceData);
378
380
  }
379
381
  getPositionSide(currentPosition) {
380
382
  if (currentPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
@@ -411,7 +413,7 @@ class ClearingHouseUser {
411
413
  baseAssetValue = (0, _1.calculateBaseAssetValue)(market, position, oraclePriceData);
412
414
  }
413
415
  else {
414
- baseAssetValue = (0, margin_1.calculateMarginBaseAssetValue)(market, position, oraclePriceData);
416
+ baseAssetValue = (0, margin_1.calculateBaseAssetValueWithOracle)(market, position, oraclePriceData);
415
417
  }
416
418
  if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
417
419
  return [numericConstants_1.ZERO, numericConstants_1.ZERO];
@@ -533,13 +535,13 @@ class ClearingHouseUser {
533
535
  if (proposedBaseAssetAmount.eq(numericConstants_1.ZERO))
534
536
  return new _1.BN(-1);
535
537
  const market = this.clearingHouse.getMarketAccount(proposedMarketPosition.marketIndex);
536
- const proposedMarketPositionValue = (0, margin_1.calculateMarginBaseAssetValue)(market, proposedMarketPosition, this.getOracleDataForMarket(market.marketIndex));
538
+ const proposedMarketPositionValue = (0, margin_1.calculateBaseAssetValueWithOracle)(market, proposedMarketPosition, this.getOracleDataForMarket(market.marketIndex));
537
539
  // total position value after trade
538
540
  const totalPositionValueAfterTrade = totalPositionValueExcludingTargetMarket.add(proposedMarketPositionValue);
539
541
  const marginRequirementExcludingTargetMarket = this.getUserAccount().positions.reduce((totalMarginRequirement, position) => {
540
542
  if (!position.marketIndex.eq(marketPosition.marketIndex)) {
541
543
  const market = this.clearingHouse.getMarketAccount(position.marketIndex);
542
- const positionValue = (0, margin_1.calculateMarginBaseAssetValue)(market, position, this.getOracleDataForMarket(market.marketIndex));
544
+ const positionValue = (0, margin_1.calculateBaseAssetValueWithOracle)(market, position, this.getOracleDataForMarket(market.marketIndex));
543
545
  const marketMarginRequirement = positionValue
544
546
  .mul(new _1.BN((0, _1.calculateMarketMarginRatio)(market, position.baseAssetAmount.abs(), 'Maintenance')))
545
547
  .div(numericConstants_1.MARGIN_PRECISION);
package/lib/config.js CHANGED
@@ -7,7 +7,7 @@ exports.configs = {
7
7
  devnet: {
8
8
  ENV: 'devnet',
9
9
  PYTH_ORACLE_MAPPING_ADDRESS: 'BmA9Z6FjioHJPpjT39QazZyhDRUdZy2ezwx4GiDdE2u2',
10
- CLEARING_HOUSE_PROGRAM_ID: '65sz7dRiWDRPZjiRxcTxPM7AE6VK4Nag9HEK6oBJXhJn',
10
+ CLEARING_HOUSE_PROGRAM_ID: '3v1iEjbSSLSSYyt1pmx4UB5rqJGurmz71RibXF7X6UF3',
11
11
  USDC_MINT_ADDRESS: '8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2',
12
12
  MARKETS: markets_1.DevnetMarkets,
13
13
  BANKS: banks_1.DevnetBanks,
@@ -7,6 +7,8 @@ export declare type BankConfig = {
7
7
  oracle: PublicKey;
8
8
  mint: PublicKey;
9
9
  oracleSource: OracleSource;
10
+ precision: BN;
11
+ precisionExp: BN;
10
12
  };
11
13
  export declare const WRAPPED_SOL_MINT: PublicKey;
12
14
  export declare const DevnetBanks: BankConfig[];
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Banks = exports.MainnetBanks = exports.DevnetBanks = exports.WRAPPED_SOL_MINT = void 0;
4
4
  const web3_js_1 = require("@solana/web3.js");
5
5
  const __1 = require("../");
6
+ const numericConstants_1 = require("./numericConstants");
6
7
  exports.WRAPPED_SOL_MINT = new web3_js_1.PublicKey('So11111111111111111111111111111111111111112');
7
8
  exports.DevnetBanks = [
8
9
  {
@@ -11,6 +12,8 @@ exports.DevnetBanks = [
11
12
  oracle: web3_js_1.PublicKey.default,
12
13
  oracleSource: __1.OracleSource.QUOTE_ASSET,
13
14
  mint: new web3_js_1.PublicKey('8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2'),
15
+ precision: numericConstants_1.BANK_BALANCE_PRECISION,
16
+ precisionExp: numericConstants_1.BANK_BALANCE_PRECISION_EXP,
14
17
  },
15
18
  {
16
19
  symbol: 'SOL',
@@ -18,6 +21,8 @@ exports.DevnetBanks = [
18
21
  oracle: new web3_js_1.PublicKey('J83w4HKfqxwcq3BEMMkPFSppX3gqekLyLJBexebFVkix'),
19
22
  oracleSource: __1.OracleSource.PYTH,
20
23
  mint: new web3_js_1.PublicKey(exports.WRAPPED_SOL_MINT),
24
+ precision: numericConstants_1.LAMPORTS_PRECISION,
25
+ precisionExp: numericConstants_1.LAMPORTS_EXP,
21
26
  },
22
27
  {
23
28
  symbol: 'BTC',
@@ -25,6 +30,8 @@ exports.DevnetBanks = [
25
30
  oracle: new web3_js_1.PublicKey('HovQMDrbAgAYPCmHVSrezcSmkMtXSSUsLDFANExrZh2J'),
26
31
  oracleSource: __1.OracleSource.PYTH,
27
32
  mint: new web3_js_1.PublicKey('3BZPwbcqB5kKScF3TEXxwNfx5ipV13kbRVDvfVp5c6fv'),
33
+ precision: numericConstants_1.BANK_BALANCE_PRECISION,
34
+ precisionExp: numericConstants_1.BANK_BALANCE_PRECISION_EXP,
28
35
  },
29
36
  ];
30
37
  exports.MainnetBanks = [
@@ -34,6 +41,8 @@ exports.MainnetBanks = [
34
41
  oracle: web3_js_1.PublicKey.default,
35
42
  oracleSource: __1.OracleSource.QUOTE_ASSET,
36
43
  mint: new web3_js_1.PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),
44
+ precision: numericConstants_1.BANK_BALANCE_PRECISION,
45
+ precisionExp: numericConstants_1.BANK_BALANCE_PRECISION_EXP,
37
46
  },
38
47
  ];
39
48
  exports.Banks = {
@@ -41,3 +41,5 @@ export declare const MARGIN_PRECISION: BN;
41
41
  export declare const BID_ASK_SPREAD_PRECISION: BN;
42
42
  export declare const ONE_YEAR: BN;
43
43
  export declare const QUOTE_ASSET_BANK_INDEX: BN;
44
+ export declare const LAMPORTS_PRECISION: BN;
45
+ export declare const LAMPORTS_EXP: BN;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.QUOTE_ASSET_BANK_INDEX = exports.ONE_YEAR = exports.BID_ASK_SPREAD_PRECISION = exports.MARGIN_PRECISION = exports.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO = exports.PRICE_TO_QUOTE_PRECISION = exports.PRICE_DIV_PEG = exports.AMM_TO_QUOTE_PRECISION_RATIO = exports.BASE_PRECISION_EXP = exports.BASE_PRECISION = exports.AMM_RESERVE_PRECISION = exports.PEG_PRECISION = exports.FUNDING_PAYMENT_PRECISION = exports.MARK_PRICE_PRECISION = exports.QUOTE_PRECISION = exports.LIQUIDATION_FEE_PRECISION = exports.BANK_IMF_PRECISION = exports.BANK_IMF_PRECISION_EXP = exports.BANK_BALANCE_PRECISION = exports.BANK_BALANCE_PRECISION_EXP = exports.BANK_WEIGHT_PRECISION = exports.BANK_RATE_PRECISION = exports.BANK_UTILIZATION_PRECISION = exports.BANK_CUMULATIVE_INTEREST_PRECISION = exports.BANK_CUMULATIVE_INTEREST_PRECISION_EXP = exports.BANK_INTEREST_PRECISION = exports.BANK_INTEREST_PRECISION_EXP = exports.AMM_RESERVE_PRECISION_EXP = exports.PEG_PRECISION_EXP = exports.FUNDING_RATE_PRECISION_EXP = exports.MARK_PRICE_PRECISION_EXP = exports.FUNDING_PAYMENT_PRECISION_EXP = exports.QUOTE_PRECISION_EXP = exports.MAX_LEVERAGE = exports.TEN_MILLION = exports.BN_MAX = exports.TEN_THOUSAND = exports.TEN = exports.TWO = exports.ONE = exports.ZERO = void 0;
3
+ exports.LAMPORTS_EXP = exports.LAMPORTS_PRECISION = exports.QUOTE_ASSET_BANK_INDEX = exports.ONE_YEAR = exports.BID_ASK_SPREAD_PRECISION = exports.MARGIN_PRECISION = exports.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO = exports.PRICE_TO_QUOTE_PRECISION = exports.PRICE_DIV_PEG = exports.AMM_TO_QUOTE_PRECISION_RATIO = exports.BASE_PRECISION_EXP = exports.BASE_PRECISION = exports.AMM_RESERVE_PRECISION = exports.PEG_PRECISION = exports.FUNDING_PAYMENT_PRECISION = exports.MARK_PRICE_PRECISION = exports.QUOTE_PRECISION = exports.LIQUIDATION_FEE_PRECISION = exports.BANK_IMF_PRECISION = exports.BANK_IMF_PRECISION_EXP = exports.BANK_BALANCE_PRECISION = exports.BANK_BALANCE_PRECISION_EXP = exports.BANK_WEIGHT_PRECISION = exports.BANK_RATE_PRECISION = exports.BANK_UTILIZATION_PRECISION = exports.BANK_CUMULATIVE_INTEREST_PRECISION = exports.BANK_CUMULATIVE_INTEREST_PRECISION_EXP = exports.BANK_INTEREST_PRECISION = exports.BANK_INTEREST_PRECISION_EXP = exports.AMM_RESERVE_PRECISION_EXP = exports.PEG_PRECISION_EXP = exports.FUNDING_RATE_PRECISION_EXP = exports.MARK_PRICE_PRECISION_EXP = exports.FUNDING_PAYMENT_PRECISION_EXP = exports.QUOTE_PRECISION_EXP = exports.MAX_LEVERAGE = exports.TEN_MILLION = exports.BN_MAX = exports.TEN_THOUSAND = exports.TEN = exports.TWO = exports.ONE = exports.ZERO = void 0;
4
+ const web3_js_1 = require("@solana/web3.js");
4
5
  const __1 = require("../");
5
6
  exports.ZERO = new __1.BN(0);
6
7
  exports.ONE = new __1.BN(1);
@@ -43,3 +44,5 @@ exports.MARGIN_PRECISION = exports.TEN_THOUSAND;
43
44
  exports.BID_ASK_SPREAD_PRECISION = new __1.BN(1000000);
44
45
  exports.ONE_YEAR = new __1.BN(31536000);
45
46
  exports.QUOTE_ASSET_BANK_INDEX = new __1.BN(0);
47
+ exports.LAMPORTS_PRECISION = new __1.BN(web3_js_1.LAMPORTS_PER_SOL);
48
+ exports.LAMPORTS_EXP = new __1.BN(Math.log10(web3_js_1.LAMPORTS_PER_SOL));
@@ -15,10 +15,12 @@ export declare class EventSubscriber {
15
15
  private awaitTxResolver;
16
16
  private logProvider;
17
17
  eventEmitter: StrictEventEmitter<EventEmitter, EventSubscriberEvents>;
18
+ private lastSeenSlot;
19
+ lastSeenTxSig: string;
18
20
  constructor(connection: Connection, program: Program, options?: EventSubscriptionOptions);
19
- subscribe(): boolean;
21
+ subscribe(): Promise<boolean>;
20
22
  private handleTxLogs;
21
- private fetchPreviousTx;
23
+ fetchPreviousTx(fetchMax?: boolean): Promise<void>;
22
24
  unsubscribe(): Promise<boolean>;
23
25
  private parseEventsFromLogs;
24
26
  awaitTx(txSig: TransactionSignature): Promise<void>;
@@ -30,17 +30,21 @@ class EventSubscriber {
30
30
  this.logProvider = new pollingLogProvider_1.PollingLogProvider(this.connection, this.program.programId, options.commitment, this.options.logProviderConfig.frequency);
31
31
  }
32
32
  }
33
- subscribe() {
34
- if (this.logProvider.isSubscribed()) {
33
+ async subscribe() {
34
+ try {
35
+ if (this.logProvider.isSubscribed()) {
36
+ return true;
37
+ }
38
+ this.logProvider.subscribe((txSig, slot, logs) => {
39
+ this.handleTxLogs(txSig, slot, logs);
40
+ }, true);
35
41
  return true;
36
42
  }
37
- this.fetchPreviousTx().catch((e) => {
43
+ catch (e) {
38
44
  console.error('Error fetching previous txs in event subscriber');
39
45
  console.error(e);
40
- });
41
- return this.logProvider.subscribe((txSig, slot, logs) => {
42
- this.handleTxLogs(txSig, slot, logs);
43
- });
46
+ return false;
47
+ }
44
48
  }
45
49
  handleTxLogs(txSig, slot, logs) {
46
50
  if (this.txEventCache.has(txSig)) {
@@ -56,10 +60,13 @@ class EventSubscriber {
56
60
  this.awaitTxResolver.get(txSig)();
57
61
  this.awaitTxResolver.delete(txSig);
58
62
  }
63
+ if (slot > this.lastSeenSlot) {
64
+ this.lastSeenTxSig = txSig;
65
+ }
59
66
  this.txEventCache.add(txSig, wrappedEvents);
60
67
  }
61
- async fetchPreviousTx() {
62
- if (!this.options.untilTx) {
68
+ async fetchPreviousTx(fetchMax) {
69
+ if (!this.options.untilTx && !fetchMax) {
63
70
  return;
64
71
  }
65
72
  let txFetched = 0;