@drift-labs/sdk 0.1.36-master.7 → 0.2.0-master.10

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 (254) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +6 -6
  2. package/lib/accounts/bulkAccountLoader.js +81 -95
  3. package/lib/accounts/bulkUserSubscription.js +13 -57
  4. package/lib/accounts/fetch.d.ts +4 -0
  5. package/lib/accounts/fetch.js +18 -0
  6. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +34 -38
  7. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +224 -224
  8. package/lib/accounts/pollingOracleSubscriber.d.ts +3 -3
  9. package/lib/accounts/pollingOracleSubscriber.js +37 -49
  10. package/lib/accounts/pollingTokenAccountSubscriber.d.ts +3 -3
  11. package/lib/accounts/pollingTokenAccountSubscriber.js +35 -50
  12. package/lib/accounts/pollingUserAccountSubscriber.d.ts +7 -13
  13. package/lib/accounts/pollingUserAccountSubscriber.js +71 -134
  14. package/lib/accounts/types.d.ts +34 -41
  15. package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -4
  16. package/lib/accounts/webSocketAccountSubscriber.js +39 -35
  17. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +33 -28
  18. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +153 -185
  19. package/lib/accounts/webSocketUserAccountSubscriber.d.ts +5 -11
  20. package/lib/accounts/webSocketUserAccountSubscriber.js +22 -67
  21. package/lib/addresses/marketAddresses.d.ts +4 -0
  22. package/lib/addresses/marketAddresses.js +15 -0
  23. package/lib/addresses/pda.d.ts +12 -0
  24. package/lib/addresses/pda.js +83 -0
  25. package/lib/admin.d.ts +12 -18
  26. package/lib/admin.js +398 -558
  27. package/lib/clearingHouse.d.ts +83 -109
  28. package/lib/clearingHouse.js +832 -893
  29. package/lib/clearingHouseConfig.d.ts +34 -0
  30. package/lib/clearingHouseConfig.js +2 -0
  31. package/lib/clearingHouseUser.d.ts +19 -22
  32. package/lib/clearingHouseUser.js +155 -141
  33. package/lib/clearingHouseUserConfig.d.ts +14 -0
  34. package/lib/clearingHouseUserConfig.js +2 -0
  35. package/lib/config.d.ts +12 -0
  36. package/lib/config.js +35 -4
  37. package/lib/constants/banks.d.ts +16 -0
  38. package/lib/constants/banks.js +41 -0
  39. package/lib/constants/markets.d.ts +8 -3
  40. package/lib/constants/markets.js +13 -206
  41. package/lib/constants/numericConstants.d.ts +17 -0
  42. package/lib/constants/numericConstants.js +23 -6
  43. package/lib/events/eventList.d.ts +22 -0
  44. package/lib/events/eventList.js +77 -0
  45. package/lib/events/eventSubscriber.d.ts +34 -0
  46. package/lib/events/eventSubscriber.js +126 -0
  47. package/lib/events/fetchLogs.d.ts +13 -0
  48. package/lib/events/fetchLogs.js +39 -0
  49. package/lib/events/pollingLogProvider.d.ts +15 -0
  50. package/lib/events/pollingLogProvider.js +53 -0
  51. package/lib/events/sort.d.ts +2 -0
  52. package/lib/events/sort.js +44 -0
  53. package/lib/events/txEventCache.d.ts +24 -0
  54. package/lib/events/txEventCache.js +71 -0
  55. package/lib/events/types.d.ts +49 -0
  56. package/lib/events/types.js +20 -0
  57. package/lib/events/webSocketLogProvider.d.ts +12 -0
  58. package/lib/events/webSocketLogProvider.js +30 -0
  59. package/lib/examples/makeTradeExample.js +26 -27
  60. package/lib/factory/bigNum.d.ts +118 -0
  61. package/lib/factory/bigNum.js +364 -0
  62. package/lib/factory/oracleClient.d.ts +1 -2
  63. package/lib/factory/oracleClient.js +6 -2
  64. package/lib/idl/clearing_house.json +2258 -2774
  65. package/lib/index.d.ts +14 -5
  66. package/lib/index.js +18 -5
  67. package/lib/math/amm.d.ts +24 -29
  68. package/lib/math/amm.js +209 -176
  69. package/lib/math/auction.d.ts +5 -0
  70. package/lib/math/auction.js +42 -0
  71. package/lib/math/bankBalance.d.ts +9 -0
  72. package/lib/math/bankBalance.js +75 -0
  73. package/lib/math/conversion.d.ts +0 -1
  74. package/lib/math/conversion.js +1 -5
  75. package/lib/math/funding.d.ts +6 -6
  76. package/lib/math/funding.js +158 -175
  77. package/lib/math/market.d.ts +6 -6
  78. package/lib/math/market.js +10 -9
  79. package/lib/math/orders.d.ts +6 -1
  80. package/lib/math/orders.js +38 -1
  81. package/lib/math/position.d.ts +7 -5
  82. package/lib/math/position.js +29 -27
  83. package/lib/math/repeg.d.ts +22 -0
  84. package/lib/math/repeg.js +128 -0
  85. package/lib/math/trade.d.ts +5 -4
  86. package/lib/math/trade.js +29 -24
  87. package/lib/mockUSDCFaucet.js +87 -116
  88. package/lib/oracles/oracleClientCache.d.ts +8 -0
  89. package/lib/oracles/oracleClientCache.js +19 -0
  90. package/lib/oracles/pythClient.d.ts +3 -5
  91. package/lib/oracles/pythClient.js +12 -31
  92. package/lib/oracles/quoteAssetOracleClient.d.ts +9 -0
  93. package/lib/oracles/quoteAssetOracleClient.js +21 -0
  94. package/lib/oracles/switchboardClient.d.ts +3 -5
  95. package/lib/oracles/switchboardClient.js +29 -50
  96. package/lib/oracles/types.d.ts +6 -1
  97. package/lib/orderParams.d.ts +14 -5
  98. package/lib/orderParams.js +8 -96
  99. package/lib/orders.d.ts +6 -7
  100. package/lib/orders.js +11 -89
  101. package/lib/slot/SlotSubscriber.d.ts +19 -0
  102. package/lib/slot/SlotSubscriber.js +26 -0
  103. package/lib/tx/retryTxSender.d.ts +2 -2
  104. package/lib/tx/retryTxSender.js +108 -123
  105. package/lib/tx/types.d.ts +5 -1
  106. package/lib/tx/utils.d.ts +1 -1
  107. package/lib/tx/utils.js +11 -2
  108. package/lib/types.d.ts +180 -110
  109. package/lib/types.js +54 -1
  110. package/lib/userName.d.ts +4 -0
  111. package/lib/userName.js +20 -0
  112. package/lib/util/computeUnits.js +10 -21
  113. package/lib/util/tps.js +11 -22
  114. package/lib/wallet.js +7 -20
  115. package/package.json +11 -4
  116. package/src/accounts/bulkAccountLoader.js +197 -0
  117. package/src/accounts/bulkAccountLoader.ts +21 -15
  118. package/src/accounts/bulkUserSubscription.js +33 -0
  119. package/src/accounts/bulkUserSubscription.ts +1 -45
  120. package/src/accounts/fetch.js +29 -0
  121. package/src/accounts/fetch.ts +33 -0
  122. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  123. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +249 -214
  124. package/src/accounts/pollingOracleSubscriber.js +93 -0
  125. package/src/accounts/pollingOracleSubscriber.ts +16 -8
  126. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  127. package/src/accounts/pollingTokenAccountSubscriber.ts +11 -8
  128. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  129. package/src/accounts/pollingUserAccountSubscriber.ts +21 -86
  130. package/src/accounts/types.js +10 -0
  131. package/src/accounts/types.ts +41 -70
  132. package/src/accounts/utils.js +7 -0
  133. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  134. package/src/accounts/webSocketAccountSubscriber.ts +33 -16
  135. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  136. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +190 -240
  137. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  138. package/src/accounts/webSocketUserAccountSubscriber.ts +11 -71
  139. package/src/addresses/marketAddresses.js +26 -0
  140. package/src/addresses/marketAddresses.ts +18 -0
  141. package/{lib/addresses.js → src/addresses/pda.js} +45 -34
  142. package/src/addresses/pda.ts +118 -0
  143. package/src/admin.ts +247 -336
  144. package/src/assert/assert.js +9 -0
  145. package/src/clearingHouse.ts +1023 -1026
  146. package/src/clearingHouseConfig.ts +37 -0
  147. package/src/clearingHouseUser.ts +275 -185
  148. package/src/clearingHouseUserConfig.ts +18 -0
  149. package/src/config.ts +54 -1
  150. package/src/constants/banks.ts +50 -0
  151. package/src/constants/markets.ts +16 -207
  152. package/src/constants/numericConstants.ts +34 -5
  153. package/src/events/eventList.js +77 -0
  154. package/src/events/eventList.ts +94 -0
  155. package/src/events/eventSubscriber.js +139 -0
  156. package/src/events/eventSubscriber.ts +194 -0
  157. package/src/events/fetchLogs.js +50 -0
  158. package/src/events/fetchLogs.ts +80 -0
  159. package/src/events/pollingLogProvider.js +64 -0
  160. package/src/events/pollingLogProvider.ts +79 -0
  161. package/src/events/sort.js +44 -0
  162. package/src/events/sort.ts +65 -0
  163. package/src/events/txEventCache.js +71 -0
  164. package/src/events/txEventCache.ts +74 -0
  165. package/src/events/types.js +20 -0
  166. package/src/events/types.ts +98 -0
  167. package/src/events/webSocketLogProvider.js +41 -0
  168. package/src/events/webSocketLogProvider.ts +38 -0
  169. package/src/examples/makeTradeExample.js +80 -0
  170. package/src/examples/makeTradeExample.ts +20 -11
  171. package/src/factory/bigNum.js +364 -0
  172. package/src/factory/bigNum.ts +524 -0
  173. package/src/factory/oracleClient.js +20 -0
  174. package/src/factory/oracleClient.ts +7 -4
  175. package/src/idl/clearing_house.json +2258 -2774
  176. package/src/index.js +69 -0
  177. package/src/index.ts +14 -5
  178. package/src/math/amm.js +369 -0
  179. package/src/math/amm.ts +382 -243
  180. package/src/math/auction.js +42 -0
  181. package/src/math/auction.ts +43 -0
  182. package/src/math/bankBalance.js +75 -0
  183. package/src/math/bankBalance.ts +112 -0
  184. package/src/math/conversion.js +11 -0
  185. package/src/math/conversion.ts +1 -11
  186. package/src/math/funding.js +248 -0
  187. package/src/math/funding.ts +12 -9
  188. package/src/math/market.js +57 -0
  189. package/src/math/market.ts +37 -30
  190. package/src/math/oracles.js +26 -0
  191. package/src/math/orders.js +110 -0
  192. package/src/math/orders.ts +43 -1
  193. package/src/math/position.js +140 -0
  194. package/src/math/position.ts +52 -35
  195. package/src/math/repeg.js +128 -0
  196. package/src/math/repeg.ts +176 -0
  197. package/src/math/state.js +15 -0
  198. package/src/math/trade.js +253 -0
  199. package/src/math/trade.ts +55 -47
  200. package/src/math/utils.js +26 -0
  201. package/src/math/utils.js.map +1 -0
  202. package/src/mockUSDCFaucet.js +171 -0
  203. package/src/oracles/oracleClientCache.js +19 -0
  204. package/src/oracles/oracleClientCache.ts +20 -0
  205. package/src/oracles/pythClient.js +46 -0
  206. package/src/oracles/pythClient.ts +4 -11
  207. package/src/oracles/quoteAssetOracleClient.js +32 -0
  208. package/src/oracles/quoteAssetOracleClient.ts +25 -0
  209. package/src/oracles/switchboardClient.js +69 -0
  210. package/src/oracles/switchboardClient.ts +11 -24
  211. package/src/oracles/types.js +2 -0
  212. package/src/oracles/types.ts +7 -1
  213. package/src/orderParams.js +20 -0
  214. package/src/orderParams.ts +20 -141
  215. package/src/orders.js +134 -0
  216. package/src/orders.ts +25 -134
  217. package/src/slot/SlotSubscriber.js +39 -0
  218. package/src/slot/SlotSubscriber.ts +42 -0
  219. package/src/token/index.js +38 -0
  220. package/src/tx/retryTxSender.js +188 -0
  221. package/src/tx/retryTxSender.ts +6 -4
  222. package/src/tx/types.js +2 -0
  223. package/src/tx/types.ts +6 -1
  224. package/src/tx/utils.js +17 -0
  225. package/src/tx/utils.ts +22 -3
  226. package/src/types.js +114 -0
  227. package/src/types.ts +176 -124
  228. package/src/userName.js +20 -0
  229. package/src/userName.ts +20 -0
  230. package/src/util/promiseTimeout.js +14 -0
  231. package/src/util/tps.js +27 -0
  232. package/src/wallet.js +35 -0
  233. package/tests/bn/test.ts +255 -0
  234. package/tsconfig.json +12 -12
  235. package/lib/addresses.d.ts +0 -10
  236. package/lib/constants/accounts.d.ts +0 -15
  237. package/lib/constants/accounts.js +0 -18
  238. package/lib/factory/clearingHouse.d.ts +0 -35
  239. package/lib/factory/clearingHouse.js +0 -81
  240. package/lib/factory/clearingHouseUser.d.ts +0 -19
  241. package/lib/factory/clearingHouseUser.js +0 -34
  242. package/lib/math/insuranceFund.d.ts +0 -15
  243. package/lib/math/insuranceFund.js +0 -33
  244. package/lib/settlement.d.ts +0 -4
  245. package/lib/settlement.js +0 -10
  246. package/lib/tx/defaultTxSender.d.ts +0 -8
  247. package/lib/tx/defaultTxSender.js +0 -12
  248. package/src/addresses.ts +0 -82
  249. package/src/constants/accounts.ts +0 -26
  250. package/src/factory/clearingHouse.ts +0 -173
  251. package/src/factory/clearingHouseUser.ts +0 -73
  252. package/src/math/insuranceFund.ts +0 -29
  253. package/src/settlement.ts +0 -9
  254. package/src/tx/defaultTxSender.ts +0 -24
@@ -0,0 +1,34 @@
1
+ /// <reference types="bn.js" />
2
+ import { ConfirmOptions, Connection, PublicKey } from '@solana/web3.js';
3
+ import { IWallet } from './types';
4
+ import { BN } from '@project-serum/anchor';
5
+ import { OracleInfo } from './oracles/types';
6
+ import { BulkAccountLoader } from './accounts/bulkAccountLoader';
7
+ import { DriftEnv } from './config';
8
+ export declare type ClearingHouseConfig = {
9
+ connection: Connection;
10
+ wallet: IWallet;
11
+ programID: PublicKey;
12
+ accountSubscription?: ClearingHouseSubscriptionConfig;
13
+ opts?: ConfirmOptions;
14
+ txSenderConfig?: TxSenderConfig;
15
+ userIds?: number[];
16
+ activeUserId?: number;
17
+ marketIndexes?: BN[];
18
+ bankIndexes?: BN[];
19
+ oracleInfos?: OracleInfo[];
20
+ env?: DriftEnv;
21
+ };
22
+ declare type ClearingHouseSubscriptionConfig = {
23
+ type: 'websocket';
24
+ } | {
25
+ type: 'polling';
26
+ accountLoader: BulkAccountLoader;
27
+ };
28
+ declare type TxSenderConfig = {
29
+ type: 'retry';
30
+ timeout?: number;
31
+ retrySleep?: number;
32
+ additionalConnections?: Connection[];
33
+ };
34
+ export {};
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -4,27 +4,20 @@ 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, SettlementStateAccount, UserAccount, UserOrdersAccount, UserPosition, UserPositionsAccount } from './types';
8
- import { UserAccountSubscriber, UserAccountEvents } from './accounts/types';
7
+ import { MarginCategory, Order, UserAccount, UserPosition } from './types';
8
+ import { UserAccountSubscriber, UserAccountEvents, DataAndSlot } from './accounts/types';
9
9
  import { PositionDirection, BN } from '.';
10
+ import { OraclePriceData } from './oracles/types';
11
+ import { ClearingHouseUserConfig } from './clearingHouseUserConfig';
10
12
  export declare class ClearingHouseUser {
11
13
  clearingHouse: ClearingHouse;
12
- authority: PublicKey;
14
+ userAccountPublicKey: PublicKey;
13
15
  accountSubscriber: UserAccountSubscriber;
14
- userAccountPublicKey?: PublicKey;
15
- userOrdersAccountPublicKey?: PublicKey;
16
16
  _isSubscribed: boolean;
17
17
  eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
18
18
  get isSubscribed(): boolean;
19
19
  set isSubscribed(val: boolean);
20
- /**
21
- * @deprecated You should use getClearingHouseUser factory method instead
22
- * @param clearingHouse
23
- * @param authority
24
- * @returns
25
- */
26
- static from(clearingHouse: ClearingHouse, authority: PublicKey): ClearingHouseUser;
27
- constructor(clearingHouse: ClearingHouse, authority: PublicKey, accountSubscriber: UserAccountSubscriber);
20
+ constructor(config: ClearingHouseUserConfig);
28
21
  /**
29
22
  * Subscribe to ClearingHouseUser state accounts
30
23
  * @returns SusbcriptionSuccess result
@@ -36,8 +29,7 @@ export declare class ClearingHouseUser {
36
29
  fetchAccounts(): Promise<void>;
37
30
  unsubscribe(): Promise<void>;
38
31
  getUserAccount(): UserAccount;
39
- getUserPositionsAccount(): UserPositionsAccount;
40
- getUserOrdersAccount(): UserOrdersAccount | undefined;
32
+ getUserAccountAndSlot(): DataAndSlot<UserAccount> | undefined;
41
33
  /**
42
34
  * Gets the user's current position for a given market. If the user has no position returns undefined
43
35
  * @param marketIndex
@@ -55,8 +47,7 @@ export declare class ClearingHouseUser {
55
47
  * @returns Order
56
48
  */
57
49
  getOrderByUserOrderId(userOrderId: number): Order | undefined;
58
- getUserAccountPublicKey(): Promise<PublicKey>;
59
- getUserOrdersAccountPublicKey(): Promise<PublicKey>;
50
+ getUserAccountPublicKey(): PublicKey;
60
51
  exists(): Promise<boolean>;
61
52
  /**
62
53
  * calculates Buying Power = FC * MAX_LEVERAGE
@@ -78,13 +69,21 @@ export declare class ClearingHouseUser {
78
69
  * @returns : Precision QUOTE_PRECISION
79
70
  */
80
71
  getUnrealizedPNL(withFunding?: boolean, marketIndex?: BN): BN;
72
+ /**
73
+ * calculates unrealized position price pnl
74
+ * @returns : Precision QUOTE_PRECISION
75
+ */
76
+ getUnsettledPNL(marketIndex?: BN): BN;
81
77
  /**
82
78
  * calculates unrealized funding payment pnl
83
79
  * @returns : Precision QUOTE_PRECISION
84
80
  */
85
81
  getUnrealizedFundingPNL(marketIndex?: BN): BN;
82
+ getTotalLiability(): BN;
83
+ getCollateralValue(bankIndex?: BN): BN;
86
84
  /**
87
85
  * calculates TotalCollateral: collateral + unrealized pnl
86
+ * TODO: rename to total equity (for perpetuals swaps)
88
87
  * @returns : Precision QUOTE_PRECISION
89
88
  */
90
89
  getTotalCollateral(): BN;
@@ -97,7 +96,7 @@ export declare class ClearingHouseUser {
97
96
  * calculates position value from closing 100%
98
97
  * @returns : Precision QUOTE_PRECISION
99
98
  */
100
- getPositionValue(marketIndex: BN): BN;
99
+ getPositionValue(marketIndex: BN, oraclePriceData: OraclePriceData): BN;
101
100
  getPositionSide(currentPosition: Pick<UserPosition, 'baseAssetAmount'>): PositionDirection | undefined;
102
101
  /**
103
102
  * calculates average exit price for closing 100% of position
@@ -183,8 +182,6 @@ export declare class ClearingHouseUser {
183
182
  * @returns positionValue : Precision QUOTE_PRECISION
184
183
  */
185
184
  private getTotalPositionValueExcludingMarket;
186
- getClaimableCollateral(settlementState: SettlementStateAccount): BN;
187
- getSettledPositionValue(): BN;
188
- getSettledPositionsPNL(): BN;
189
- estimateClaimableCollateral(): Promise<BN>;
185
+ private getOracleDataForMarket;
186
+ private getOracleDataForBank;
190
187
  }
@@ -1,27 +1,25 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.ClearingHouseUser = void 0;
13
4
  const types_1 = require("./types");
14
5
  const position_1 = require("./math/position");
15
6
  const numericConstants_1 = require("./constants/numericConstants");
16
7
  const _1 = require(".");
17
- const addresses_1 = require("./addresses");
18
- const clearingHouseUser_1 = require("./factory/clearingHouseUser");
8
+ const bankBalance_1 = require("./math/bankBalance");
9
+ const pollingUserAccountSubscriber_1 = require("./accounts/pollingUserAccountSubscriber");
10
+ const webSocketUserAccountSubscriber_1 = require("./accounts/webSocketUserAccountSubscriber");
19
11
  class ClearingHouseUser {
20
- constructor(clearingHouse, authority, accountSubscriber) {
12
+ constructor(config) {
13
+ var _a;
21
14
  this._isSubscribed = false;
22
- this.clearingHouse = clearingHouse;
23
- this.authority = authority;
24
- this.accountSubscriber = accountSubscriber;
15
+ this.clearingHouse = config.clearingHouse;
16
+ this.userAccountPublicKey = config.userAccountPublicKey;
17
+ if (((_a = config.accountSubscription) === null || _a === void 0 ? void 0 : _a.type) === 'polling') {
18
+ this.accountSubscriber = new pollingUserAccountSubscriber_1.PollingUserAccountSubscriber(config.clearingHouse.program, config.userAccountPublicKey, config.accountSubscription.accountLoader);
19
+ }
20
+ else {
21
+ this.accountSubscriber = new webSocketUserAccountSubscriber_1.WebSocketUserAccountSubscriber(config.clearingHouse.program, config.userAccountPublicKey);
22
+ }
25
23
  this.eventEmitter = this.accountSubscriber.eventEmitter;
26
24
  }
27
25
  get isSubscribed() {
@@ -30,52 +28,29 @@ class ClearingHouseUser {
30
28
  set isSubscribed(val) {
31
29
  this._isSubscribed = val;
32
30
  }
33
- /**
34
- * @deprecated You should use getClearingHouseUser factory method instead
35
- * @param clearingHouse
36
- * @param authority
37
- * @returns
38
- */
39
- static from(clearingHouse, authority) {
40
- if (clearingHouse.accountSubscriber.type !== 'websocket')
41
- throw 'This method only works for clearing houses with a websocket account listener. Try using the getClearingHouseUser factory method to initialize a ClearingHouseUser instead';
42
- const config = (0, clearingHouseUser_1.getWebSocketClearingHouseUserConfig)(clearingHouse, authority);
43
- return (0, clearingHouseUser_1.getClearingHouseUser)(config);
44
- }
45
31
  /**
46
32
  * Subscribe to ClearingHouseUser state accounts
47
33
  * @returns SusbcriptionSuccess result
48
34
  */
49
- subscribe() {
50
- return __awaiter(this, void 0, void 0, function* () {
51
- // Clearing house should already be subscribed, but await for the subscription just incase to avoid race condition
52
- yield this.clearingHouse.subscribe();
53
- this.isSubscribed = yield this.accountSubscriber.subscribe();
54
- return this.isSubscribed;
55
- });
35
+ async subscribe() {
36
+ this.isSubscribed = await this.accountSubscriber.subscribe();
37
+ return this.isSubscribed;
56
38
  }
57
39
  /**
58
40
  * Forces the accountSubscriber to fetch account updates from rpc
59
41
  */
60
- fetchAccounts() {
61
- return __awaiter(this, void 0, void 0, function* () {
62
- yield this.accountSubscriber.fetch();
63
- });
42
+ async fetchAccounts() {
43
+ await this.accountSubscriber.fetch();
64
44
  }
65
- unsubscribe() {
66
- return __awaiter(this, void 0, void 0, function* () {
67
- yield this.accountSubscriber.unsubscribe();
68
- this.isSubscribed = false;
69
- });
45
+ async unsubscribe() {
46
+ await this.accountSubscriber.unsubscribe();
47
+ this.isSubscribed = false;
70
48
  }
71
49
  getUserAccount() {
72
- return this.accountSubscriber.getUserAccount();
73
- }
74
- getUserPositionsAccount() {
75
- return this.accountSubscriber.getUserPositionsAccount();
50
+ return this.accountSubscriber.getUserAccountAndSlot().data;
76
51
  }
77
- getUserOrdersAccount() {
78
- return this.accountSubscriber.getUserOrdersAccount();
52
+ getUserAccountAndSlot() {
53
+ return this.accountSubscriber.getUserAccountAndSlot();
79
54
  }
80
55
  /**
81
56
  * Gets the user's current position for a given market. If the user has no position returns undefined
@@ -83,7 +58,7 @@ class ClearingHouseUser {
83
58
  * @returns userPosition
84
59
  */
85
60
  getUserPosition(marketIndex) {
86
- return this.getUserPositionsAccount().positions.find((position) => position.marketIndex.eq(marketIndex));
61
+ return this.getUserAccount().positions.find((position) => position.marketIndex.eq(marketIndex));
87
62
  }
88
63
  getEmptyPosition(marketIndex) {
89
64
  return {
@@ -91,7 +66,11 @@ class ClearingHouseUser {
91
66
  lastCumulativeFundingRate: numericConstants_1.ZERO,
92
67
  marketIndex,
93
68
  quoteAssetAmount: numericConstants_1.ZERO,
69
+ quoteEntryAmount: numericConstants_1.ZERO,
94
70
  openOrders: numericConstants_1.ZERO,
71
+ unsettledPnl: numericConstants_1.ZERO,
72
+ openBids: numericConstants_1.ZERO,
73
+ openAsks: numericConstants_1.ZERO,
95
74
  };
96
75
  }
97
76
  /**
@@ -99,39 +78,21 @@ class ClearingHouseUser {
99
78
  * @returns Order
100
79
  */
101
80
  getOrder(orderId) {
102
- return this.getUserOrdersAccount().orders.find((order) => order.orderId.eq(orderId));
81
+ return this.getUserAccount().orders.find((order) => order.orderId.eq(orderId));
103
82
  }
104
83
  /**
105
84
  * @param userOrderId
106
85
  * @returns Order
107
86
  */
108
87
  getOrderByUserOrderId(userOrderId) {
109
- return this.getUserOrdersAccount().orders.find((order) => order.userOrderId === userOrderId);
88
+ return this.getUserAccount().orders.find((order) => order.userOrderId === userOrderId);
110
89
  }
111
90
  getUserAccountPublicKey() {
112
- return __awaiter(this, void 0, void 0, function* () {
113
- if (this.userAccountPublicKey) {
114
- return this.userAccountPublicKey;
115
- }
116
- this.userAccountPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.clearingHouse.program.programId, this.authority);
117
- return this.userAccountPublicKey;
118
- });
119
- }
120
- getUserOrdersAccountPublicKey() {
121
- return __awaiter(this, void 0, void 0, function* () {
122
- if (this.userOrdersAccountPublicKey) {
123
- return this.userOrdersAccountPublicKey;
124
- }
125
- this.userOrdersAccountPublicKey = yield (0, _1.getUserOrdersAccountPublicKey)(this.clearingHouse.program.programId, yield this.getUserAccountPublicKey());
126
- return this.userOrdersAccountPublicKey;
127
- });
91
+ return this.userAccountPublicKey;
128
92
  }
129
- exists() {
130
- return __awaiter(this, void 0, void 0, function* () {
131
- const userAccountPublicKey = yield this.getUserAccountPublicKey();
132
- const userAccountRPCResponse = yield this.clearingHouse.connection.getParsedAccountInfo(userAccountPublicKey);
133
- return userAccountRPCResponse.value !== null;
134
- });
93
+ async exists() {
94
+ const userAccountRPCResponse = await this.clearingHouse.connection.getParsedAccountInfo(this.userAccountPublicKey);
95
+ return userAccountRPCResponse.value !== null;
135
96
  }
136
97
  /**
137
98
  * calculates Buying Power = FC * MAX_LEVERAGE
@@ -153,34 +114,49 @@ class ClearingHouseUser {
153
114
  return freeCollateral.gte(numericConstants_1.ZERO) ? freeCollateral : numericConstants_1.ZERO;
154
115
  }
155
116
  getInitialMarginRequirement() {
156
- return this.getUserPositionsAccount().positions.reduce((marginRequirement, marketPosition) => {
157
- const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
158
- return marginRequirement.add((0, _1.calculateBaseAssetValue)(market, marketPosition)
117
+ return this.getUserAccount()
118
+ .positions.reduce((marginRequirement, marketPosition) => {
119
+ const market = this.clearingHouse.getMarketAccount(marketPosition.marketIndex);
120
+ return marginRequirement.add((0, _1.calculateBaseAssetValue)(market, marketPosition, this.getOracleDataForMarket(market.marketIndex))
159
121
  .mul(new _1.BN(market.marginRatioInitial))
160
122
  .div(numericConstants_1.MARGIN_PRECISION));
161
- }, numericConstants_1.ZERO);
123
+ }, numericConstants_1.ZERO)
124
+ .add(this.getTotalLiability());
162
125
  }
163
126
  /**
164
127
  * @returns The partial margin requirement in USDC. : QUOTE_PRECISION
165
128
  */
166
129
  getPartialMarginRequirement() {
167
- return this.getUserPositionsAccount().positions.reduce((marginRequirement, marketPosition) => {
168
- const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
169
- return marginRequirement.add((0, _1.calculateBaseAssetValue)(market, marketPosition)
130
+ return this.getUserAccount()
131
+ .positions.reduce((marginRequirement, marketPosition) => {
132
+ const market = this.clearingHouse.getMarketAccount(marketPosition.marketIndex);
133
+ return marginRequirement.add((0, _1.calculateBaseAssetValue)(market, marketPosition, this.getOracleDataForMarket(market.marketIndex))
170
134
  .mul(new _1.BN(market.marginRatioPartial))
171
135
  .div(numericConstants_1.MARGIN_PRECISION));
172
- }, numericConstants_1.ZERO);
136
+ }, numericConstants_1.ZERO)
137
+ .add(this.getTotalLiability());
173
138
  }
174
139
  /**
175
140
  * calculates unrealized position price pnl
176
141
  * @returns : Precision QUOTE_PRECISION
177
142
  */
178
143
  getUnrealizedPNL(withFunding, marketIndex) {
179
- return this.getUserPositionsAccount()
144
+ return this.getUserAccount()
180
145
  .positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
181
146
  .reduce((pnl, marketPosition) => {
182
- const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
183
- return pnl.add((0, _1.calculatePositionPNL)(market, marketPosition, withFunding));
147
+ const market = this.clearingHouse.getMarketAccount(marketPosition.marketIndex);
148
+ return pnl.add((0, _1.calculatePositionPNL)(market, marketPosition, withFunding, this.getOracleDataForMarket(market.marketIndex)));
149
+ }, numericConstants_1.ZERO);
150
+ }
151
+ /**
152
+ * calculates unrealized position price pnl
153
+ * @returns : Precision QUOTE_PRECISION
154
+ */
155
+ getUnsettledPNL(marketIndex) {
156
+ return this.getUserAccount()
157
+ .positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
158
+ .reduce((pnl, marketPosition) => {
159
+ return pnl.add(marketPosition.unsettledPnl);
184
160
  }, numericConstants_1.ZERO);
185
161
  }
186
162
  /**
@@ -188,39 +164,88 @@ class ClearingHouseUser {
188
164
  * @returns : Precision QUOTE_PRECISION
189
165
  */
190
166
  getUnrealizedFundingPNL(marketIndex) {
191
- return this.getUserPositionsAccount()
167
+ return this.getUserAccount()
192
168
  .positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
193
169
  .reduce((pnl, marketPosition) => {
194
- const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
170
+ const market = this.clearingHouse.getMarketAccount(marketPosition.marketIndex);
195
171
  return pnl.add((0, _1.calculatePositionFundingPNL)(market, marketPosition));
196
172
  }, numericConstants_1.ZERO);
197
173
  }
174
+ getTotalLiability() {
175
+ return this.getUserAccount().bankBalances.reduce((totalAssetValue, bankBalance) => {
176
+ if (bankBalance.balance.eq(numericConstants_1.ZERO) ||
177
+ (0, types_1.isVariant)(bankBalance.balanceType, 'deposit')) {
178
+ return totalAssetValue;
179
+ }
180
+ // Todo this needs to account for whether it's based on initial or maintenance requirements
181
+ const bankAccount = this.clearingHouse.getBankAccount(bankBalance.bankIndex);
182
+ const tokenAmount = (0, bankBalance_1.getTokenAmount)(bankBalance.balance, bankAccount, bankBalance.balanceType);
183
+ return totalAssetValue.add(tokenAmount
184
+ .mul(this.getOracleDataForBank(bankAccount.bankIndex).price)
185
+ .mul(bankAccount.initialLiabilityWeight)
186
+ .div(numericConstants_1.BANK_WEIGHT_PRECISION)
187
+ .div(numericConstants_1.MARK_PRICE_PRECISION));
188
+ }, numericConstants_1.ZERO);
189
+ }
190
+ getCollateralValue(bankIndex) {
191
+ return this.getUserAccount().bankBalances.reduce((totalAssetValue, bankBalance) => {
192
+ if (bankBalance.balance.eq(numericConstants_1.ZERO) ||
193
+ (bankIndex !== undefined && !bankBalance.bankIndex.eq(bankIndex))) {
194
+ return totalAssetValue;
195
+ }
196
+ // Todo this needs to account for whether it's based on initial or maintenance requirements
197
+ const bankAccount = this.clearingHouse.getBankAccount(bankBalance.bankIndex);
198
+ let tokenAmount = (0, bankBalance_1.getTokenAmount)(bankBalance.balance, bankAccount, bankBalance.balanceType);
199
+ if ((0, types_1.isVariant)(bankBalance.balanceType, 'borrow')) {
200
+ tokenAmount = tokenAmount.mul(new _1.BN(-1));
201
+ }
202
+ return totalAssetValue.add(tokenAmount
203
+ .mul(this.getOracleDataForBank(bankAccount.bankIndex).price)
204
+ .div(numericConstants_1.MARK_PRICE_PRECISION));
205
+ }, numericConstants_1.ZERO);
206
+ }
198
207
  /**
199
208
  * calculates TotalCollateral: collateral + unrealized pnl
209
+ * TODO: rename to total equity (for perpetuals swaps)
200
210
  * @returns : Precision QUOTE_PRECISION
201
211
  */
202
212
  getTotalCollateral() {
203
- var _a;
204
- return ((_a = this.getUserAccount().collateral.add(this.getUnrealizedPNL(true))) !== null && _a !== void 0 ? _a : new _1.BN(0));
213
+ return this.getUserAccount()
214
+ .bankBalances.reduce((totalAssetValue, bankBalance) => {
215
+ if (bankBalance.balance.eq(numericConstants_1.ZERO) ||
216
+ (0, types_1.isVariant)(bankBalance.balanceType, 'borrow')) {
217
+ return totalAssetValue;
218
+ }
219
+ // Todo this needs to account for whether it's based on initial or maintenance requirements
220
+ const bankAccount = this.clearingHouse.getBankAccount(bankBalance.bankIndex);
221
+ const tokenAmount = (0, bankBalance_1.getTokenAmount)(bankBalance.balance, bankAccount, bankBalance.balanceType);
222
+ return totalAssetValue.add(tokenAmount
223
+ .mul(this.getOracleDataForBank(bankAccount.bankIndex).price)
224
+ .mul(bankAccount.initialAssetWeight)
225
+ .div(numericConstants_1.BANK_WEIGHT_PRECISION)
226
+ .div(numericConstants_1.MARK_PRICE_PRECISION));
227
+ }, numericConstants_1.ZERO)
228
+ .add(this.getUnrealizedPNL(true))
229
+ .add(this.getUnsettledPNL());
205
230
  }
206
231
  /**
207
232
  * calculates sum of position value across all positions
208
233
  * @returns : Precision QUOTE_PRECISION
209
234
  */
210
235
  getTotalPositionValue() {
211
- return this.getUserPositionsAccount().positions.reduce((positionValue, marketPosition) => {
212
- const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
213
- return positionValue.add((0, _1.calculateBaseAssetValue)(market, marketPosition));
236
+ return this.getUserAccount().positions.reduce((positionValue, marketPosition) => {
237
+ const market = this.clearingHouse.getMarketAccount(marketPosition.marketIndex);
238
+ return positionValue.add((0, _1.calculateBaseAssetValue)(market, marketPosition, this.getOracleDataForMarket(market.marketIndex)));
214
239
  }, numericConstants_1.ZERO);
215
240
  }
216
241
  /**
217
242
  * calculates position value from closing 100%
218
243
  * @returns : Precision QUOTE_PRECISION
219
244
  */
220
- getPositionValue(marketIndex) {
245
+ getPositionValue(marketIndex, oraclePriceData) {
221
246
  const userPosition = this.getUserPosition(marketIndex) || this.getEmptyPosition(marketIndex);
222
- const market = this.clearingHouse.getMarket(userPosition.marketIndex);
223
- return (0, _1.calculateBaseAssetValue)(market, userPosition);
247
+ const market = this.clearingHouse.getMarketAccount(userPosition.marketIndex);
248
+ return (0, _1.calculateBaseAssetValue)(market, userPosition, oraclePriceData);
224
249
  }
225
250
  getPositionSide(currentPosition) {
226
251
  if (currentPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
@@ -238,11 +263,12 @@ class ClearingHouseUser {
238
263
  * @returns : Precision MARK_PRICE_PRECISION
239
264
  */
240
265
  getPositionEstimatedExitPriceAndPnl(position, amountToClose) {
241
- const market = this.clearingHouse.getMarket(position.marketIndex);
266
+ const market = this.clearingHouse.getMarketAccount(position.marketIndex);
242
267
  const entryPrice = (0, position_1.calculateEntryPrice)(position);
268
+ const oraclePriceData = this.getOracleDataForMarket(position.marketIndex);
243
269
  if (amountToClose) {
244
270
  if (amountToClose.eq(numericConstants_1.ZERO)) {
245
- return [(0, _1.calculateMarkPrice)(market), numericConstants_1.ZERO];
271
+ return [(0, _1.calculateMarkPrice)(market, oraclePriceData), numericConstants_1.ZERO];
246
272
  }
247
273
  position = {
248
274
  baseAssetAmount: amountToClose,
@@ -251,7 +277,7 @@ class ClearingHouseUser {
251
277
  quoteAssetAmount: position.quoteAssetAmount,
252
278
  };
253
279
  }
254
- const baseAssetValue = (0, _1.calculateBaseAssetValue)(market, position);
280
+ const baseAssetValue = (0, _1.calculateBaseAssetValue)(market, position, oraclePriceData);
255
281
  if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
256
282
  return [numericConstants_1.ZERO, numericConstants_1.ZERO];
257
283
  }
@@ -284,7 +310,7 @@ class ClearingHouseUser {
284
310
  * @returns : Precision TEN_THOUSAND
285
311
  */
286
312
  getMaxLeverage(marketIndex, category = 'Initial') {
287
- const market = this.clearingHouse.getMarket(marketIndex);
313
+ const market = this.clearingHouse.getMarketAccount(marketIndex);
288
314
  let marginRatioCategory;
289
315
  switch (category) {
290
316
  case 'Initial':
@@ -326,12 +352,11 @@ class ClearingHouseUser {
326
352
  * @returns
327
353
  */
328
354
  needsToSettleFundingPayment() {
329
- const marketsAccount = this.clearingHouse.getMarketsAccount();
330
- for (const userPosition of this.getUserPositionsAccount().positions) {
355
+ for (const userPosition of this.getUserAccount().positions) {
331
356
  if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
332
357
  continue;
333
358
  }
334
- const market = marketsAccount.markets[userPosition.marketIndex.toNumber()];
359
+ const market = this.clearingHouse.getMarketAccount(userPosition.marketIndex);
335
360
  if (market.amm.cumulativeFundingRateLong.eq(userPosition.lastCumulativeFundingRate) ||
336
361
  market.amm.cumulativeFundingRateShort.eq(userPosition.lastCumulativeFundingRate)) {
337
362
  continue;
@@ -371,18 +396,22 @@ class ClearingHouseUser {
371
396
  baseAssetAmount: proposedBaseAssetAmount,
372
397
  lastCumulativeFundingRate: currentMarketPosition.lastCumulativeFundingRate,
373
398
  quoteAssetAmount: new _1.BN(0),
399
+ quoteEntryAmount: new _1.BN(0),
374
400
  openOrders: new _1.BN(0),
401
+ unsettledPnl: new _1.BN(0),
402
+ openBids: new _1.BN(0),
403
+ openAsks: new _1.BN(0),
375
404
  };
376
405
  if (proposedBaseAssetAmount.eq(numericConstants_1.ZERO))
377
406
  return new _1.BN(-1);
378
- const market = this.clearingHouse.getMarket(proposedMarketPosition.marketIndex);
379
- const proposedMarketPositionValue = (0, _1.calculateBaseAssetValue)(market, proposedMarketPosition);
407
+ const market = this.clearingHouse.getMarketAccount(proposedMarketPosition.marketIndex);
408
+ const proposedMarketPositionValue = (0, _1.calculateBaseAssetValue)(market, proposedMarketPosition, this.getOracleDataForMarket(market.marketIndex));
380
409
  // total position value after trade
381
410
  const totalPositionValueAfterTrade = totalPositionValueExcludingTargetMarket.add(proposedMarketPositionValue);
382
- const marginRequirementExcludingTargetMarket = this.getUserPositionsAccount().positions.reduce((totalMarginRequirement, position) => {
411
+ const marginRequirementExcludingTargetMarket = this.getUserAccount().positions.reduce((totalMarginRequirement, position) => {
383
412
  if (!position.marketIndex.eq(marketPosition.marketIndex)) {
384
- const market = this.clearingHouse.getMarket(position.marketIndex);
385
- const positionValue = (0, _1.calculateBaseAssetValue)(market, position);
413
+ const market = this.clearingHouse.getMarketAccount(position.marketIndex);
414
+ const positionValue = (0, _1.calculateBaseAssetValue)(market, position, this.getOracleDataForMarket(market.marketIndex));
386
415
  const marketMarginRequirement = positionValue
387
416
  .mul(partial
388
417
  ? new _1.BN(market.marginRatioPartial)
@@ -426,13 +455,13 @@ class ClearingHouseUser {
426
455
  }
427
456
  let markPriceAfterTrade;
428
457
  if (positionBaseSizeChange.eq(numericConstants_1.ZERO)) {
429
- markPriceAfterTrade = (0, _1.calculateMarkPrice)(this.clearingHouse.getMarket(marketPosition.marketIndex));
458
+ markPriceAfterTrade = (0, _1.calculateMarkPrice)(this.clearingHouse.getMarketAccount(marketPosition.marketIndex), this.getOracleDataForMarket(marketPosition.marketIndex));
430
459
  }
431
460
  else {
432
461
  const direction = positionBaseSizeChange.gt(numericConstants_1.ZERO)
433
462
  ? _1.PositionDirection.LONG
434
463
  : _1.PositionDirection.SHORT;
435
- markPriceAfterTrade = (0, _1.calculateTradeSlippage)(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarket(marketPosition.marketIndex), 'base')[3]; // newPrice after swap
464
+ markPriceAfterTrade = (0, _1.calculateTradeSlippage)(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarketAccount(marketPosition.marketIndex), 'base', this.getOracleDataForMarket(marketPosition.marketIndex))[3]; // newPrice after swap
436
465
  }
437
466
  if (priceDelta.gt(markPriceAfterTrade)) {
438
467
  return new _1.BN(-1);
@@ -457,7 +486,7 @@ class ClearingHouseUser {
457
486
  .neg();
458
487
  return this.liquidationPrice({
459
488
  marketIndex: positionMarketIndex,
460
- }, closeBaseAmount);
489
+ }, closeBaseAmount, true);
461
490
  }
462
491
  /**
463
492
  * Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.
@@ -490,10 +519,11 @@ class ClearingHouseUser {
490
519
  const targetingSameSide = !currentPosition
491
520
  ? true
492
521
  : targetSide === currentPositionSide;
522
+ const oracleData = this.getOracleDataForMarket(targetMarketIndex);
493
523
  // add any position we have on the opposite side of the current trade, because we can "flip" the size of this position without taking any extra leverage.
494
524
  const oppositeSizeValueUSDC = targetingSameSide
495
525
  ? numericConstants_1.ZERO
496
- : this.getPositionValue(targetMarketIndex);
526
+ : this.getPositionValue(targetMarketIndex, oracleData);
497
527
  let maxPositionSize = this.getBuyingPower(targetMarketIndex);
498
528
  if (maxPositionSize.gte(numericConstants_1.ZERO)) {
499
529
  if (oppositeSizeValueUSDC.eq(numericConstants_1.ZERO)) {
@@ -508,8 +538,8 @@ class ClearingHouseUser {
508
538
  else {
509
539
  // current leverage is greater than max leverage - can only reduce position size
510
540
  if (!targetingSameSide) {
511
- const market = this.clearingHouse.getMarket(targetMarketIndex);
512
- const marketPositionValue = this.getPositionValue(targetMarketIndex);
541
+ const market = this.clearingHouse.getMarketAccount(targetMarketIndex);
542
+ const marketPositionValue = this.getPositionValue(targetMarketIndex, oracleData);
513
543
  const totalCollateral = this.getTotalCollateral();
514
544
  const marginRequirement = this.getInitialMarginRequirement();
515
545
  const marginFreedByClosing = marketPositionValue
@@ -547,7 +577,8 @@ class ClearingHouseUser {
547
577
  accountLeverageRatioAfterTrade(targetMarketIndex, tradeQuoteAmount, tradeSide) {
548
578
  const currentPosition = this.getUserPosition(targetMarketIndex) ||
549
579
  this.getEmptyPosition(targetMarketIndex);
550
- let currentPositionQuoteAmount = this.getPositionValue(targetMarketIndex);
580
+ const oracleData = this.getOracleDataForMarket(targetMarketIndex);
581
+ let currentPositionQuoteAmount = this.getPositionValue(targetMarketIndex, oracleData);
551
582
  const currentSide = currentPosition && currentPosition.baseAssetAmount.isNeg()
552
583
  ? _1.PositionDirection.SHORT
553
584
  : _1.PositionDirection.LONG;
@@ -591,39 +622,22 @@ class ClearingHouseUser {
591
622
  getTotalPositionValueExcludingMarket(marketToIgnore) {
592
623
  const currentMarketPosition = this.getUserPosition(marketToIgnore) ||
593
624
  this.getEmptyPosition(marketToIgnore);
625
+ const oracleData = this.getOracleDataForMarket(marketToIgnore);
594
626
  let currentMarketPositionValueUSDC = numericConstants_1.ZERO;
595
627
  if (currentMarketPosition) {
596
- currentMarketPositionValueUSDC = this.getPositionValue(marketToIgnore);
628
+ currentMarketPositionValueUSDC = this.getPositionValue(marketToIgnore, oracleData);
597
629
  }
598
630
  return this.getTotalPositionValue().sub(currentMarketPositionValueUSDC);
599
631
  }
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);
632
+ getOracleDataForMarket(marketIndex) {
633
+ const oracleKey = this.clearingHouse.getMarketAccount(marketIndex).amm.oracle;
634
+ const oracleData = this.clearingHouse.getOraclePriceDataAndSlot(oracleKey).data;
635
+ return oracleData;
615
636
  }
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
- });
637
+ getOracleDataForBank(bankIndex) {
638
+ const oracleKey = this.clearingHouse.getBankAccount(bankIndex).oracle;
639
+ const oracleData = this.clearingHouse.getOraclePriceDataAndSlot(oracleKey).data;
640
+ return oracleData;
627
641
  }
628
642
  }
629
643
  exports.ClearingHouseUser = ClearingHouseUser;