@drift-labs/sdk 0.1.36-master.4 → 0.1.36-master.7

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 (41) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +1 -0
  2. package/lib/accounts/bulkAccountLoader.js +4 -0
  3. package/lib/addresses.d.ts +1 -0
  4. package/lib/addresses.js +7 -1
  5. package/lib/admin.d.ts +5 -0
  6. package/lib/admin.js +68 -0
  7. package/lib/clearingHouse.d.ts +11 -3
  8. package/lib/clearingHouse.js +130 -4
  9. package/lib/clearingHouseUser.d.ts +5 -1
  10. package/lib/clearingHouseUser.js +28 -0
  11. package/lib/idl/clearing_house.json +988 -727
  12. package/lib/index.d.ts +1 -0
  13. package/lib/index.js +1 -0
  14. package/lib/math/oracles.d.ts +3 -0
  15. package/lib/math/oracles.js +26 -0
  16. package/lib/math/position.d.ts +1 -0
  17. package/lib/math/position.js +19 -1
  18. package/lib/math/trade.d.ts +10 -6
  19. package/lib/math/trade.js +68 -13
  20. package/lib/oracles/pythClient.js +1 -0
  21. package/lib/oracles/switchboardClient.js +3 -0
  22. package/lib/oracles/types.d.ts +1 -0
  23. package/lib/settlement.d.ts +4 -0
  24. package/lib/settlement.js +10 -0
  25. package/lib/types.d.ts +11 -0
  26. package/package.json +1 -1
  27. package/src/accounts/bulkAccountLoader.ts +5 -0
  28. package/src/addresses.ts +11 -0
  29. package/src/admin.ts +83 -0
  30. package/src/clearingHouse.ts +204 -4
  31. package/src/clearingHouseUser.ts +64 -1
  32. package/src/idl/clearing_house.json +988 -727
  33. package/src/index.ts +1 -0
  34. package/src/math/oracles.ts +36 -0
  35. package/src/math/position.ts +22 -0
  36. package/src/math/trade.ts +84 -16
  37. package/src/oracles/pythClient.ts +1 -0
  38. package/src/oracles/switchboardClient.ts +5 -0
  39. package/src/oracles/types.ts +1 -0
  40. package/src/settlement.ts +9 -0
  41. package/src/types.ts +12 -0
@@ -16,6 +16,7 @@ export declare class BulkAccountLoader {
16
16
  loadPromise?: Promise<void>;
17
17
  loadPromiseResolver: () => void;
18
18
  lastTimeLoadingPromiseCleared: number;
19
+ mostRecentSlot: number;
19
20
  constructor(connection: Connection, commitment: Commitment, pollingFrequency: number);
20
21
  addAccount(publicKey: PublicKey, callback: (buffer: Buffer) => void): string;
21
22
  removeAccount(publicKey: PublicKey, callbackId: string): void;
@@ -20,6 +20,7 @@ class BulkAccountLoader {
20
20
  this.accountData = new Map();
21
21
  this.errorCallbacks = new Map();
22
22
  this.lastTimeLoadingPromiseCleared = Date.now();
23
+ this.mostRecentSlot = 0;
23
24
  this.connection = connection;
24
25
  this.commitment = commitment;
25
26
  this.pollingFrequency = pollingFrequency;
@@ -127,6 +128,9 @@ class BulkAccountLoader {
127
128
  return;
128
129
  }
129
130
  const newSlot = rpcResponse.result.context.slot;
131
+ if (newSlot > this.mostRecentSlot) {
132
+ this.mostRecentSlot = newSlot;
133
+ }
130
134
  for (const i in accountsToLoad) {
131
135
  const accountToLoad = accountsToLoad[i];
132
136
  const key = accountToLoad.publicKey.toString();
@@ -7,3 +7,4 @@ export declare function getUserAccountPublicKeyAndNonce(programId: PublicKey, au
7
7
  export declare function getUserAccountPublicKey(programId: PublicKey, authority: PublicKey): Promise<PublicKey>;
8
8
  export declare function getUserOrdersAccountPublicKeyAndNonce(programId: PublicKey, userAccount: PublicKey): Promise<[PublicKey, number]>;
9
9
  export declare function getUserOrdersAccountPublicKey(programId: PublicKey, userAccount: PublicKey): Promise<PublicKey>;
10
+ export declare function getSettlementStatePublicKey(programId: PublicKey): Promise<PublicKey>;
package/lib/addresses.js CHANGED
@@ -32,7 +32,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
32
32
  });
33
33
  };
34
34
  Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.getUserOrdersAccountPublicKey = exports.getUserOrdersAccountPublicKeyAndNonce = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getClearingHouseStateAccountPublicKey = exports.getOrderStateAccountPublicKeyAndNonce = exports.getOrderStateAccountPublicKey = exports.getClearingHouseStateAccountPublicKeyAndNonce = void 0;
35
+ exports.getSettlementStatePublicKey = exports.getUserOrdersAccountPublicKey = exports.getUserOrdersAccountPublicKeyAndNonce = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getClearingHouseStateAccountPublicKey = exports.getOrderStateAccountPublicKeyAndNonce = exports.getOrderStateAccountPublicKey = exports.getClearingHouseStateAccountPublicKeyAndNonce = void 0;
36
36
  const anchor = __importStar(require("@project-serum/anchor"));
37
37
  function getClearingHouseStateAccountPublicKeyAndNonce(programId) {
38
38
  return __awaiter(this, void 0, void 0, function* () {
@@ -85,3 +85,9 @@ function getUserOrdersAccountPublicKey(programId, userAccount) {
85
85
  });
86
86
  }
87
87
  exports.getUserOrdersAccountPublicKey = getUserOrdersAccountPublicKey;
88
+ function getSettlementStatePublicKey(programId) {
89
+ return __awaiter(this, void 0, void 0, function* () {
90
+ return (yield anchor.web3.PublicKey.findProgramAddress([Buffer.from(anchor.utils.bytes.utf8.encode('settlement_state'))], programId))[0];
91
+ });
92
+ }
93
+ exports.getSettlementStatePublicKey = getSettlementStatePublicKey;
package/lib/admin.d.ts CHANGED
@@ -42,4 +42,9 @@ export declare class Admin extends ClearingHouse {
42
42
  updateFundingPaused(fundingPaused: boolean): Promise<TransactionSignature>;
43
43
  updateExchangePaused(exchangePaused: boolean): Promise<TransactionSignature>;
44
44
  disableAdminControlsPrices(): Promise<TransactionSignature>;
45
+ transferFromInsuranceVaultToCollateralVault(): Promise<TransactionSignature>;
46
+ adminUpdateUserForgoSettlement(authority: PublicKey): Promise<TransactionSignature>;
47
+ initializeSettlementState(): Promise<TransactionSignature>;
48
+ updateSettlementState(): Promise<TransactionSignature>;
49
+ updateSettlementStateEnabled(enabled: boolean): Promise<TransactionSignature>;
45
50
  }
package/lib/admin.js CHANGED
@@ -526,5 +526,73 @@ class Admin extends clearingHouse_1.ClearingHouse {
526
526
  });
527
527
  });
528
528
  }
529
+ transferFromInsuranceVaultToCollateralVault() {
530
+ return __awaiter(this, void 0, void 0, function* () {
531
+ const state = yield this.getStateAccount();
532
+ return yield this.program.rpc.transferFromInsuranceVaultToCollateralVault({
533
+ accounts: {
534
+ admin: this.wallet.publicKey,
535
+ state: yield this.getStatePublicKey(),
536
+ insuranceVault: state.insuranceVault,
537
+ insuranceVaultAuthority: state.insuranceVaultAuthority,
538
+ collateralVault: state.collateralVault,
539
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
540
+ },
541
+ });
542
+ });
543
+ }
544
+ adminUpdateUserForgoSettlement(authority) {
545
+ return __awaiter(this, void 0, void 0, function* () {
546
+ const user = yield (0, addresses_1.getUserAccountPublicKey)(this.program.programId, authority);
547
+ return yield this.program.rpc.adminUpdateUserForgoSettlement({
548
+ accounts: {
549
+ admin: this.wallet.publicKey,
550
+ state: yield this.getStatePublicKey(),
551
+ user: user,
552
+ },
553
+ });
554
+ });
555
+ }
556
+ initializeSettlementState() {
557
+ return __awaiter(this, void 0, void 0, function* () {
558
+ const settlementState = yield (0, addresses_1.getSettlementStatePublicKey)(this.program.programId);
559
+ const settlementSize = yield this.getTotalSettlementSize();
560
+ return yield this.program.rpc.initializeSettlementState(settlementSize, {
561
+ accounts: {
562
+ admin: this.wallet.publicKey,
563
+ state: yield this.getStatePublicKey(),
564
+ settlementState: settlementState,
565
+ rent: web3_js_1.SYSVAR_RENT_PUBKEY,
566
+ systemProgram: anchor.web3.SystemProgram.programId,
567
+ collateralVault: (yield this.getStateAccount()).collateralVault,
568
+ },
569
+ });
570
+ });
571
+ }
572
+ updateSettlementState() {
573
+ return __awaiter(this, void 0, void 0, function* () {
574
+ const settlementState = yield (0, addresses_1.getSettlementStatePublicKey)(this.program.programId);
575
+ return yield this.program.rpc.updateSettlementState({
576
+ accounts: {
577
+ admin: this.wallet.publicKey,
578
+ state: yield this.getStatePublicKey(),
579
+ settlementState: settlementState,
580
+ collateralVault: (yield this.getStateAccount()).collateralVault,
581
+ },
582
+ });
583
+ });
584
+ }
585
+ updateSettlementStateEnabled(enabled) {
586
+ return __awaiter(this, void 0, void 0, function* () {
587
+ const settlementState = yield (0, addresses_1.getSettlementStatePublicKey)(this.program.programId);
588
+ return yield this.program.rpc.updateSettlementStateEnabled(enabled, {
589
+ accounts: {
590
+ admin: this.wallet.publicKey,
591
+ state: yield this.getStatePublicKey(),
592
+ settlementState: settlementState,
593
+ },
594
+ });
595
+ });
596
+ }
529
597
  }
530
598
  exports.Admin = Admin;
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="bn.js" />
3
3
  import { AnchorProvider, BN, Program } from '@project-serum/anchor';
4
- import { MarketsAccount, StateAccount, DepositHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, IWallet, LiquidationHistoryAccount, PositionDirection, TradeHistoryAccount, UserAccount, Market, OrderHistoryAccount, OrderStateAccount, OrderParams, Order, ExtendedCurveHistoryAccount, UserPositionsAccount } from './types';
4
+ import { MarketsAccount, StateAccount, DepositHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, IWallet, LiquidationHistoryAccount, PositionDirection, TradeHistoryAccount, UserAccount, Market, OrderHistoryAccount, OrderStateAccount, OrderParams, Order, ExtendedCurveHistoryAccount, UserPositionsAccount, SettlementStateAccount } from './types';
5
5
  import { Connection, PublicKey, TransactionSignature, Keypair, ConfirmOptions, TransactionInstruction } from '@solana/web3.js';
6
6
  import { MockUSDCFaucet } from './mockUSDCFaucet';
7
7
  import { EventEmitter } from 'events';
@@ -59,6 +59,7 @@ export declare class ClearingHouse {
59
59
  statePublicKey?: PublicKey;
60
60
  getStatePublicKey(): Promise<PublicKey>;
61
61
  getStateAccount(): StateAccount;
62
+ getSettlementAccount(): Promise<SettlementStateAccount>;
62
63
  getMarketsAccount(): MarketsAccount;
63
64
  getMarket(marketIndex: BN | number): Market;
64
65
  getFundingPaymentHistoryAccount(): FundingPaymentHistoryAccount;
@@ -126,8 +127,10 @@ export declare class ClearingHouse {
126
127
  getCancelOrderIx(orderId: BN, oracle?: PublicKey): Promise<TransactionInstruction>;
127
128
  cancelOrderByUserId(userOrderId: number, oracle?: PublicKey): Promise<TransactionSignature>;
128
129
  getCancelOrderByUserIdIx(userOrderId: number, oracle?: PublicKey): Promise<TransactionInstruction>;
129
- cancelAllOrders(oracles?: PublicKey[]): Promise<TransactionSignature>;
130
- getCancelAllOrdersIx(oracles: PublicKey[]): Promise<TransactionInstruction>;
130
+ cancelAllOrders(oracles?: PublicKey[], bestEffort?: boolean): Promise<TransactionSignature>;
131
+ getCancelAllOrdersIx(oracles: PublicKey[], bestEffort?: boolean): Promise<TransactionInstruction>;
132
+ cancelOrdersByMarketAndSide(oracles?: PublicKey[], bestEffort?: boolean, marketIndexOnly?: BN, directionOnly?: PositionDirection): Promise<TransactionSignature>;
133
+ getCancelOrdersByMarketAndSideIx(oracles: PublicKey[], bestEffort?: boolean, marketIndexOnly?: BN, directionOnly?: PositionDirection): Promise<TransactionInstruction>;
131
134
  fillOrder(userAccountPublicKey: PublicKey, userOrdersAccountPublicKey: PublicKey, order: Order): Promise<TransactionSignature>;
132
135
  getFillOrderIx(userAccountPublicKey: PublicKey, userOrdersAccountPublicKey: PublicKey, order: Order): Promise<TransactionInstruction>;
133
136
  initializeUserOrdersThenPlaceAndFillOrder(orderParams: OrderParams, discountToken?: PublicKey, referrer?: PublicKey): Promise<TransactionSignature>;
@@ -150,4 +153,9 @@ export declare class ClearingHouse {
150
153
  settleFundingPayment(userAccount: PublicKey, userPositionsAccount: PublicKey): Promise<TransactionSignature>;
151
154
  getSettleFundingPaymentIx(userAccount: PublicKey, userPositionsAccount: PublicKey): Promise<TransactionInstruction>;
152
155
  triggerEvent(eventName: keyof ClearingHouseAccountEvents, data?: any): void;
156
+ settlePositionAndClaimCollateral(collateralAccountPublicKey: PublicKey): Promise<TransactionSignature>;
157
+ getSettlePositionIx(): Promise<TransactionInstruction>;
158
+ getClaimCollateralIx(collateralAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
159
+ getTotalSettlementSize(): Promise<BN>;
160
+ updateUserForgoSettlement(): Promise<TransactionSignature>;
153
161
  }
@@ -45,6 +45,9 @@ const addresses_1 = require("./addresses");
45
45
  const utils_1 = require("./tx/utils");
46
46
  const clearingHouse_1 = require("./factory/clearingHouse");
47
47
  const numericConstants_1 = require("./constants/numericConstants");
48
+ const bulkAccountLoader_1 = require("./accounts/bulkAccountLoader");
49
+ const clearingHouseUser_1 = require("./factory/clearingHouseUser");
50
+ const bulkUserSubscription_1 = require("./accounts/bulkUserSubscription");
48
51
  /**
49
52
  * # ClearingHouse
50
53
  * 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.
@@ -138,6 +141,12 @@ class ClearingHouse {
138
141
  getStateAccount() {
139
142
  return this.accountSubscriber.getStateAccount();
140
143
  }
144
+ getSettlementAccount() {
145
+ return __awaiter(this, void 0, void 0, function* () {
146
+ // @ts-ignore
147
+ return yield this.program.account.settlementState.fetch(yield (0, addresses_1.getSettlementStatePublicKey)(this.program.programId));
148
+ });
149
+ }
141
150
  getMarketsAccount() {
142
151
  return this.accountSubscriber.getMarketsAccount();
143
152
  }
@@ -622,12 +631,12 @@ class ClearingHouse {
622
631
  });
623
632
  });
624
633
  }
625
- cancelAllOrders(oracles) {
634
+ cancelAllOrders(oracles, bestEffort) {
626
635
  return __awaiter(this, void 0, void 0, function* () {
627
- return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getCancelAllOrdersIx(oracles)), [], this.opts);
636
+ return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getCancelAllOrdersIx(oracles, bestEffort)), [], this.opts);
628
637
  });
629
638
  }
630
- getCancelAllOrdersIx(oracles) {
639
+ getCancelAllOrdersIx(oracles, bestEffort) {
631
640
  return __awaiter(this, void 0, void 0, function* () {
632
641
  const userAccountPublicKey = yield this.getUserAccountPublicKey();
633
642
  const userAccount = yield this.getUserAccount();
@@ -641,7 +650,43 @@ class ClearingHouse {
641
650
  isSigner: false,
642
651
  });
643
652
  }
644
- return yield this.program.instruction.cancelAllOrders({
653
+ return yield this.program.instruction.cancelAllOrders(bestEffort, {
654
+ accounts: {
655
+ state: yield this.getStatePublicKey(),
656
+ user: userAccountPublicKey,
657
+ authority: this.wallet.publicKey,
658
+ markets: state.markets,
659
+ userOrders: yield this.getUserOrdersAccountPublicKey(),
660
+ userPositions: userAccount.positions,
661
+ fundingPaymentHistory: state.fundingPaymentHistory,
662
+ fundingRateHistory: state.fundingRateHistory,
663
+ orderState: yield this.getOrderStatePublicKey(),
664
+ orderHistory: orderState.orderHistory,
665
+ },
666
+ remainingAccounts,
667
+ });
668
+ });
669
+ }
670
+ cancelOrdersByMarketAndSide(oracles, bestEffort, marketIndexOnly, directionOnly) {
671
+ return __awaiter(this, void 0, void 0, function* () {
672
+ return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getCancelOrdersByMarketAndSideIx(oracles, bestEffort, marketIndexOnly, directionOnly)), [], this.opts);
673
+ });
674
+ }
675
+ getCancelOrdersByMarketAndSideIx(oracles, bestEffort, marketIndexOnly, directionOnly) {
676
+ return __awaiter(this, void 0, void 0, function* () {
677
+ const userAccountPublicKey = yield this.getUserAccountPublicKey();
678
+ const userAccount = yield this.getUserAccount();
679
+ const state = this.getStateAccount();
680
+ const orderState = this.getOrderStateAccount();
681
+ const remainingAccounts = [];
682
+ for (const oracle of oracles) {
683
+ remainingAccounts.push({
684
+ pubkey: oracle,
685
+ isWritable: false,
686
+ isSigner: false,
687
+ });
688
+ }
689
+ return yield this.program.instruction.cancelOrdersByMarketAndSide(bestEffort, marketIndexOnly, directionOnly, {
645
690
  accounts: {
646
691
  state: yield this.getStatePublicKey(),
647
692
  user: userAccountPublicKey,
@@ -922,5 +967,86 @@ class ClearingHouse {
922
967
  triggerEvent(eventName, data) {
923
968
  this.eventEmitter.emit(eventName, data);
924
969
  }
970
+ settlePositionAndClaimCollateral(collateralAccountPublicKey) {
971
+ return __awaiter(this, void 0, void 0, function* () {
972
+ const settlePositionIx = yield this.getSettlePositionIx();
973
+ const claimCollateralIx = yield this.getClaimCollateralIx(collateralAccountPublicKey);
974
+ const tx = new web3_js_1.Transaction().add(settlePositionIx).add(claimCollateralIx);
975
+ return this.txSender.send(tx, [], this.opts);
976
+ });
977
+ }
978
+ getSettlePositionIx() {
979
+ return __awaiter(this, void 0, void 0, function* () {
980
+ const userAccountPublicKey = yield this.getUserAccountPublicKey();
981
+ const user = yield this.program.account.user.fetch(userAccountPublicKey);
982
+ const state = this.getStateAccount();
983
+ const settlementState = yield (0, addresses_1.getSettlementStatePublicKey)(this.program.programId);
984
+ return yield this.program.instruction.settlePosition({
985
+ accounts: {
986
+ state: yield this.getStatePublicKey(),
987
+ user: userAccountPublicKey,
988
+ markets: state.markets,
989
+ authority: this.wallet.publicKey,
990
+ userPositions: user.positions,
991
+ settlementState,
992
+ fundingPaymentHistory: state.fundingPaymentHistory,
993
+ },
994
+ });
995
+ });
996
+ }
997
+ getClaimCollateralIx(collateralAccountPublicKey) {
998
+ return __awaiter(this, void 0, void 0, function* () {
999
+ const userAccountPublicKey = yield this.getUserAccountPublicKey();
1000
+ const state = this.getStateAccount();
1001
+ const settlementState = yield (0, addresses_1.getSettlementStatePublicKey)(this.program.programId);
1002
+ return yield this.program.instruction.claimCollateral({
1003
+ accounts: {
1004
+ state: yield this.getStatePublicKey(),
1005
+ user: userAccountPublicKey,
1006
+ collateralVault: state.collateralVault,
1007
+ collateralVaultAuthority: state.collateralVaultAuthority,
1008
+ userCollateralAccount: collateralAccountPublicKey,
1009
+ authority: this.wallet.publicKey,
1010
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
1011
+ settlementState,
1012
+ },
1013
+ });
1014
+ });
1015
+ }
1016
+ getTotalSettlementSize() {
1017
+ return __awaiter(this, void 0, void 0, function* () {
1018
+ const accountLoader = new bulkAccountLoader_1.BulkAccountLoader(this.connection, 'processed', 50000);
1019
+ const clearingHouse = (0, clearingHouse_1.getClearingHouse)((0, clearingHouse_1.getPollingClearingHouseConfig)(this.connection, this.wallet, this.program.programId, accountLoader));
1020
+ console.log('loading all users');
1021
+ const programUserAccounts = (yield this.program.account.user.all());
1022
+ const userArray = [];
1023
+ for (const programUserAccount of programUserAccounts) {
1024
+ const user = (0, clearingHouseUser_1.getClearingHouseUser)((0, clearingHouseUser_1.getPollingClearingHouseUserConfig)(clearingHouse, programUserAccount.account.authority, accountLoader));
1025
+ userArray.push(user);
1026
+ }
1027
+ console.log('subscribing all users');
1028
+ yield (0, bulkUserSubscription_1.bulkPollingUserSubscribe)(userArray, accountLoader);
1029
+ console.log('calculating settlement size');
1030
+ const settlementSize = userArray.reduce((collateralToBeSettled, user) => {
1031
+ return collateralToBeSettled.add(user.getUserAccount().forgoPositionSettlement === 0
1032
+ ? user.getSettledPositionValue()
1033
+ : numericConstants_1.ZERO);
1034
+ }, numericConstants_1.ZERO);
1035
+ for (const user of userArray) {
1036
+ yield user.unsubscribe();
1037
+ }
1038
+ return settlementSize;
1039
+ });
1040
+ }
1041
+ updateUserForgoSettlement() {
1042
+ return __awaiter(this, void 0, void 0, function* () {
1043
+ return yield this.program.rpc.updateUserForgoSettlement({
1044
+ accounts: {
1045
+ authority: this.wallet.publicKey,
1046
+ user: yield this.getUserAccountPublicKey(),
1047
+ },
1048
+ });
1049
+ });
1050
+ }
925
1051
  }
926
1052
  exports.ClearingHouse = ClearingHouse;
@@ -4,7 +4,7 @@ import { PublicKey } from '@solana/web3.js';
4
4
  import { EventEmitter } from 'events';
5
5
  import StrictEventEmitter from 'strict-event-emitter-types';
6
6
  import { ClearingHouse } from './clearingHouse';
7
- import { MarginCategory, Order, UserAccount, UserOrdersAccount, UserPosition, UserPositionsAccount } from './types';
7
+ import { MarginCategory, Order, SettlementStateAccount, UserAccount, UserOrdersAccount, UserPosition, UserPositionsAccount } from './types';
8
8
  import { UserAccountSubscriber, UserAccountEvents } from './accounts/types';
9
9
  import { PositionDirection, BN } from '.';
10
10
  export declare class ClearingHouseUser {
@@ -183,4 +183,8 @@ export declare class ClearingHouseUser {
183
183
  * @returns positionValue : Precision QUOTE_PRECISION
184
184
  */
185
185
  private getTotalPositionValueExcludingMarket;
186
+ getClaimableCollateral(settlementState: SettlementStateAccount): BN;
187
+ getSettledPositionValue(): BN;
188
+ getSettledPositionsPNL(): BN;
189
+ estimateClaimableCollateral(): Promise<BN>;
186
190
  }
@@ -597,5 +597,33 @@ class ClearingHouseUser {
597
597
  }
598
598
  return this.getTotalPositionValue().sub(currentMarketPositionValueUSDC);
599
599
  }
600
+ getClaimableCollateral(settlementState) {
601
+ return this.getSettledPositionValue()
602
+ .mul(settlementState.collateralAvailableToClaim.sub(this.getUserAccount().lastCollateralAvailableToClaim))
603
+ .div(settlementState.totalSettlementValue);
604
+ }
605
+ getSettledPositionValue() {
606
+ return _1.BN.max(this.getUserAccount()
607
+ .collateral.add(this.getUnrealizedFundingPNL().div(numericConstants_1.PRICE_TO_QUOTE_PRECISION))
608
+ .add(this.getSettledPositionsPNL()), numericConstants_1.ZERO);
609
+ }
610
+ getSettledPositionsPNL() {
611
+ return this.getUserPositionsAccount().positions.reduce((pnl, marketPosition) => {
612
+ const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
613
+ return pnl.add((0, position_1.calculateSettledPositionPNL)(market, marketPosition));
614
+ }, numericConstants_1.ZERO);
615
+ }
616
+ estimateClaimableCollateral() {
617
+ return __awaiter(this, void 0, void 0, function* () {
618
+ const currentCollateralVaultBalance = new _1.BN((yield this.clearingHouse.connection.getTokenAccountBalance(this.clearingHouse.getStateAccount().collateralVault)).value.amount);
619
+ const currentInsuranceVaultBalance = new _1.BN((yield this.clearingHouse.connection.getTokenAccountBalance(this.clearingHouse.getStateAccount().insuranceVault)).value.amount);
620
+ const totalClaimableCollateral = currentCollateralVaultBalance.add(currentInsuranceVaultBalance);
621
+ const totalEstimatedSettlementValue = yield this.clearingHouse.getTotalSettlementSize();
622
+ const userSettledPositionValue = yield this.getSettledPositionValue();
623
+ return totalClaimableCollateral
624
+ .mul(userSettledPositionValue)
625
+ .div(totalEstimatedSettlementValue);
626
+ });
627
+ }
600
628
  }
601
629
  exports.ClearingHouseUser = ClearingHouseUser;