@drift-labs/sdk 0.2.0-temp.2 → 2.0.1

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 (278) hide show
  1. package/README.md +27 -29
  2. package/lib/accounts/bulkAccountLoader.d.ts +2 -0
  3. package/lib/accounts/bulkAccountLoader.js +36 -29
  4. package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
  5. package/lib/accounts/bulkUserStatsSubscription.js +21 -0
  6. package/lib/accounts/bulkUserSubscription.d.ts +2 -2
  7. package/lib/accounts/bulkUserSubscription.js +0 -1
  8. package/lib/accounts/fetch.d.ts +2 -1
  9. package/lib/accounts/fetch.js +9 -1
  10. package/lib/accounts/{pollingClearingHouseAccountSubscriber.d.ts → pollingDriftClientAccountSubscriber.d.ts} +20 -25
  11. package/lib/accounts/{pollingClearingHouseAccountSubscriber.js → pollingDriftClientAccountSubscriber.js} +45 -49
  12. package/lib/accounts/{pollingOracleSubscriber.d.ts → pollingOracleAccountSubscriber.d.ts} +2 -2
  13. package/lib/accounts/{pollingOracleSubscriber.js → pollingOracleAccountSubscriber.js} +3 -3
  14. package/lib/accounts/pollingUserAccountSubscriber.d.ts +1 -1
  15. package/lib/accounts/pollingUserAccountSubscriber.js +5 -11
  16. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  17. package/lib/accounts/pollingUserStatsAccountSubscriber.js +107 -0
  18. package/lib/accounts/types.d.ts +26 -15
  19. package/lib/accounts/webSocketDriftClientAccountSubscriber.d.ts +49 -0
  20. package/lib/accounts/{webSocketClearingHouseAccountSubscriber.js → webSocketDriftClientAccountSubscriber.js} +47 -45
  21. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  22. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  23. package/lib/addresses/marketAddresses.d.ts +1 -3
  24. package/lib/addresses/marketAddresses.js +1 -1
  25. package/lib/addresses/pda.d.ts +15 -9
  26. package/lib/addresses/pda.js +73 -35
  27. package/lib/adminClient.d.ts +65 -0
  28. package/lib/adminClient.js +637 -0
  29. package/lib/config.d.ts +10 -10
  30. package/lib/config.js +26 -22
  31. package/lib/constants/numericConstants.d.ts +29 -12
  32. package/lib/constants/numericConstants.js +40 -21
  33. package/lib/constants/perpMarkets.d.ts +18 -0
  34. package/lib/constants/{markets.js → perpMarkets.js} +20 -9
  35. package/lib/constants/spotMarkets.d.ts +19 -0
  36. package/lib/constants/spotMarkets.js +63 -0
  37. package/lib/dlob/DLOB.d.ts +82 -0
  38. package/lib/dlob/DLOB.js +694 -0
  39. package/lib/dlob/DLOBNode.d.ts +54 -0
  40. package/lib/dlob/DLOBNode.js +77 -0
  41. package/lib/dlob/NodeList.d.ts +27 -0
  42. package/lib/dlob/NodeList.js +144 -0
  43. package/lib/driftClient.d.ts +234 -0
  44. package/lib/driftClient.js +2108 -0
  45. package/lib/{clearingHouseConfig.d.ts → driftClientConfig.d.ts} +9 -9
  46. package/lib/{clearingHouseConfig.js → driftClientConfig.js} +0 -0
  47. package/lib/events/eventList.d.ts +0 -1
  48. package/lib/events/eventList.js +0 -7
  49. package/lib/events/eventSubscriber.d.ts +5 -2
  50. package/lib/events/eventSubscriber.js +25 -11
  51. package/lib/events/fetchLogs.d.ts +13 -2
  52. package/lib/events/fetchLogs.js +45 -14
  53. package/lib/events/pollingLogProvider.d.ts +2 -1
  54. package/lib/events/pollingLogProvider.js +7 -3
  55. package/lib/events/sort.js +8 -11
  56. package/lib/events/txEventCache.d.ts +0 -2
  57. package/lib/events/txEventCache.js +0 -14
  58. package/lib/events/types.d.ts +11 -3
  59. package/lib/events/types.js +8 -0
  60. package/lib/events/webSocketLogProvider.js +1 -1
  61. package/lib/examples/makeTradeExample.js +30 -18
  62. package/lib/factory/bigNum.d.ts +8 -4
  63. package/lib/factory/bigNum.js +109 -19
  64. package/lib/idl/drift.json +8392 -0
  65. package/lib/index.d.ts +29 -12
  66. package/lib/index.js +29 -12
  67. package/lib/math/amm.d.ts +9 -6
  68. package/lib/math/amm.js +91 -38
  69. package/lib/math/conversion.js +1 -1
  70. package/lib/math/exchangeStatus.d.ts +4 -0
  71. package/lib/math/exchangeStatus.js +18 -0
  72. package/lib/math/funding.d.ts +6 -6
  73. package/lib/math/funding.js +23 -21
  74. package/lib/math/insurance.d.ts +4 -0
  75. package/lib/math/insurance.js +27 -0
  76. package/lib/math/margin.d.ts +11 -0
  77. package/lib/math/margin.js +82 -0
  78. package/lib/math/market.d.ts +14 -9
  79. package/lib/math/market.js +70 -10
  80. package/lib/math/oracles.d.ts +4 -0
  81. package/lib/math/oracles.js +36 -8
  82. package/lib/math/orders.d.ts +16 -6
  83. package/lib/math/orders.js +97 -17
  84. package/lib/math/position.d.ts +27 -13
  85. package/lib/math/position.js +91 -37
  86. package/lib/math/repeg.js +17 -8
  87. package/lib/math/spotBalance.d.ts +22 -0
  88. package/lib/math/spotBalance.js +192 -0
  89. package/lib/math/spotMarket.d.ts +4 -0
  90. package/lib/math/spotMarket.js +8 -0
  91. package/lib/math/spotPosition.d.ts +6 -0
  92. package/lib/math/spotPosition.js +23 -0
  93. package/lib/math/trade.d.ts +10 -10
  94. package/lib/math/trade.js +27 -31
  95. package/lib/oracles/pythClient.js +1 -1
  96. package/lib/oracles/quoteAssetOracleClient.js +1 -1
  97. package/lib/oracles/switchboardClient.js +1 -1
  98. package/lib/orderParams.d.ts +4 -4
  99. package/lib/orderParams.js +12 -4
  100. package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
  101. package/lib/serum/serumFulfillmentConfigMap.js +17 -0
  102. package/lib/serum/serumSubscriber.d.ts +27 -0
  103. package/lib/serum/serumSubscriber.js +56 -0
  104. package/lib/serum/types.d.ts +11 -0
  105. package/{src/oracles → lib/serum}/types.js +0 -0
  106. package/lib/tokenFaucet.d.ts +1 -0
  107. package/lib/tokenFaucet.js +23 -12
  108. package/lib/tx/retryTxSender.d.ts +1 -1
  109. package/lib/tx/retryTxSender.js +13 -4
  110. package/lib/tx/types.d.ts +1 -1
  111. package/lib/types.d.ts +631 -222
  112. package/lib/types.js +137 -24
  113. package/lib/user.d.ts +228 -0
  114. package/lib/user.js +959 -0
  115. package/lib/userConfig.d.ts +14 -0
  116. package/lib/{clearingHouseUserConfig.js → userConfig.js} +0 -0
  117. package/lib/userMap/userMap.d.ts +41 -0
  118. package/lib/userMap/userMap.js +85 -0
  119. package/lib/userMap/userStatsMap.d.ts +19 -0
  120. package/lib/userMap/userStatsMap.js +68 -0
  121. package/lib/userName.d.ts +1 -0
  122. package/lib/userName.js +3 -2
  123. package/lib/userStats.d.ts +18 -0
  124. package/lib/userStats.js +49 -0
  125. package/lib/userStatsConfig.d.ts +14 -0
  126. package/{src/clearingHouseConfig.js → lib/userStatsConfig.js} +0 -0
  127. package/lib/util/getTokenAddress.d.ts +2 -0
  128. package/lib/util/getTokenAddress.js +9 -0
  129. package/package.json +12 -5
  130. package/src/accounts/bulkAccountLoader.ts +44 -34
  131. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  132. package/src/accounts/bulkUserSubscription.ts +2 -3
  133. package/src/accounts/fetch.ts +27 -2
  134. package/src/accounts/{pollingClearingHouseAccountSubscriber.ts → pollingDriftClientAccountSubscriber.ts} +65 -75
  135. package/src/accounts/{pollingOracleSubscriber.ts → pollingOracleAccountSubscriber.ts} +2 -2
  136. package/src/accounts/pollingUserAccountSubscriber.ts +5 -12
  137. package/src/accounts/pollingUserStatsAccountSubscriber.ts +166 -0
  138. package/src/accounts/types.ts +35 -15
  139. package/src/accounts/{webSocketClearingHouseAccountSubscriber.ts → webSocketDriftClientAccountSubscriber.ts} +78 -73
  140. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  141. package/src/addresses/marketAddresses.ts +3 -4
  142. package/src/addresses/pda.ts +105 -33
  143. package/src/adminClient.ts +1207 -0
  144. package/src/config.ts +41 -34
  145. package/src/constants/numericConstants.ts +59 -26
  146. package/src/constants/{markets.ts → perpMarkets.ts} +22 -11
  147. package/src/constants/spotMarkets.ts +83 -0
  148. package/src/dlob/DLOB.ts +1120 -0
  149. package/src/dlob/DLOBNode.ts +155 -0
  150. package/src/dlob/NodeList.ts +195 -0
  151. package/src/driftClient.ts +3594 -0
  152. package/src/{clearingHouseConfig.ts → driftClientConfig.ts} +9 -8
  153. package/src/events/eventList.ts +1 -8
  154. package/src/events/eventSubscriber.ts +36 -14
  155. package/src/events/fetchLogs.ts +60 -15
  156. package/src/events/pollingLogProvider.ts +11 -3
  157. package/src/events/sort.ts +11 -15
  158. package/src/events/txEventCache.ts +0 -16
  159. package/src/events/types.ts +27 -2
  160. package/src/events/webSocketLogProvider.ts +1 -1
  161. package/src/examples/makeTradeExample.js +152 -75
  162. package/src/examples/makeTradeExample.ts +44 -28
  163. package/src/factory/bigNum.ts +150 -22
  164. package/src/idl/drift.json +8392 -0
  165. package/src/idl/pyth.json +98 -2
  166. package/src/index.ts +29 -12
  167. package/src/math/amm.ts +161 -48
  168. package/src/math/conversion.ts +2 -2
  169. package/src/math/exchangeStatus.ts +31 -0
  170. package/src/math/funding.ts +41 -31
  171. package/src/math/insurance.ts +35 -0
  172. package/src/math/margin.ts +133 -0
  173. package/src/math/market.ts +143 -14
  174. package/src/math/oracles.ts +63 -9
  175. package/src/math/orders.ts +168 -26
  176. package/src/math/position.ts +133 -59
  177. package/src/math/repeg.ts +19 -9
  178. package/src/math/spotBalance.ts +319 -0
  179. package/src/math/spotMarket.ts +9 -0
  180. package/src/math/spotPosition.ts +47 -0
  181. package/src/math/trade.ts +33 -37
  182. package/src/oracles/pythClient.ts +2 -2
  183. package/src/oracles/quoteAssetOracleClient.ts +2 -2
  184. package/src/oracles/switchboardClient.ts +2 -2
  185. package/src/orderParams.ts +16 -8
  186. package/src/serum/serumFulfillmentConfigMap.ts +26 -0
  187. package/src/serum/serumSubscriber.ts +99 -0
  188. package/src/serum/types.ts +13 -0
  189. package/src/tokenFaucet.ts +38 -15
  190. package/src/tx/retryTxSender.ts +16 -5
  191. package/src/tx/types.ts +2 -1
  192. package/src/types.ts +594 -195
  193. package/src/user.ts +1599 -0
  194. package/src/{clearingHouseUserConfig.ts → userConfig.ts} +5 -5
  195. package/src/userMap/userMap.ts +124 -0
  196. package/src/userMap/userStatsMap.ts +108 -0
  197. package/src/userName.ts +2 -1
  198. package/src/userStats.ts +75 -0
  199. package/src/userStatsConfig.ts +18 -0
  200. package/src/util/getTokenAddress.ts +18 -0
  201. package/tests/bn/test.ts +46 -11
  202. package/tests/dlob/helpers.ts +619 -0
  203. package/tests/dlob/test.ts +4586 -0
  204. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +0 -49
  205. package/lib/admin.d.ts +0 -44
  206. package/lib/admin.js +0 -438
  207. package/lib/clearingHouse.d.ts +0 -146
  208. package/lib/clearingHouse.js +0 -1154
  209. package/lib/clearingHouseUser.d.ts +0 -187
  210. package/lib/clearingHouseUser.js +0 -634
  211. package/lib/clearingHouseUserConfig.d.ts +0 -14
  212. package/lib/constants/banks.d.ts +0 -16
  213. package/lib/constants/banks.js +0 -41
  214. package/lib/constants/markets.d.ts +0 -19
  215. package/lib/idl/clearing_house.json +0 -4464
  216. package/lib/math/bankBalance.d.ts +0 -9
  217. package/lib/math/bankBalance.js +0 -75
  218. package/lib/math/state.d.ts +0 -8
  219. package/lib/math/state.js +0 -15
  220. package/lib/orders.d.ts +0 -8
  221. package/lib/orders.js +0 -134
  222. package/src/accounts/bulkAccountLoader.js +0 -197
  223. package/src/accounts/bulkUserSubscription.js +0 -33
  224. package/src/accounts/pollingClearingHouseAccountSubscriber.js +0 -311
  225. package/src/accounts/pollingOracleSubscriber.js +0 -93
  226. package/src/accounts/pollingTokenAccountSubscriber.js +0 -90
  227. package/src/accounts/pollingUserAccountSubscriber.js +0 -132
  228. package/src/accounts/types.js +0 -10
  229. package/src/accounts/utils.js +0 -7
  230. package/src/accounts/webSocketAccountSubscriber.js +0 -93
  231. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +0 -233
  232. package/src/accounts/webSocketUserAccountSubscriber.js +0 -62
  233. package/src/addresses/marketAddresses.js +0 -26
  234. package/src/admin.js +0 -517
  235. package/src/admin.ts +0 -730
  236. package/src/clearingHouse.ts +0 -1828
  237. package/src/clearingHouseUser.ts +0 -978
  238. package/src/clearingHouseUserConfig.js +0 -2
  239. package/src/config.js +0 -67
  240. package/src/constants/banks.js +0 -42
  241. package/src/constants/banks.ts +0 -50
  242. package/src/constants/markets.js +0 -42
  243. package/src/constants/numericConstants.js +0 -41
  244. package/src/events/eventSubscriber.js +0 -139
  245. package/src/events/fetchLogs.js +0 -50
  246. package/src/events/pollingLogProvider.js +0 -64
  247. package/src/events/sort.js +0 -44
  248. package/src/events/txEventCache.js +0 -71
  249. package/src/events/types.js +0 -20
  250. package/src/events/webSocketLogProvider.js +0 -41
  251. package/src/factory/bigNum.js +0 -390
  252. package/src/factory/oracleClient.js +0 -20
  253. package/src/idl/clearing_house.json +0 -4464
  254. package/src/index.js +0 -69
  255. package/src/math/amm.js +0 -369
  256. package/src/math/auction.js +0 -42
  257. package/src/math/bankBalance.ts +0 -112
  258. package/src/math/conversion.js +0 -11
  259. package/src/math/funding.js +0 -248
  260. package/src/math/oracles.js +0 -26
  261. package/src/math/repeg.js +0 -128
  262. package/src/math/state.js +0 -15
  263. package/src/math/state.ts +0 -14
  264. package/src/math/trade.js +0 -253
  265. package/src/math/utils.js +0 -26
  266. package/src/math/utils.js.map +0 -1
  267. package/src/mockUSDCFaucet.js +0 -280
  268. package/src/oracles/oracleClientCache.js +0 -19
  269. package/src/oracles/pythClient.js +0 -46
  270. package/src/oracles/quoteAssetOracleClient.js +0 -32
  271. package/src/oracles/switchboardClient.js +0 -69
  272. package/src/orderParams.js +0 -20
  273. package/src/orders.ts +0 -245
  274. package/src/slot/SlotSubscriber.js +0 -39
  275. package/src/tokenFaucet.js +0 -189
  276. package/src/types.js +0 -125
  277. package/src/userName.js +0 -20
  278. package/src/wallet.js +0 -35
@@ -1,634 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ClearingHouseUser = void 0;
4
- const types_1 = require("./types");
5
- const position_1 = require("./math/position");
6
- const numericConstants_1 = require("./constants/numericConstants");
7
- const _1 = require(".");
8
- const bankBalance_1 = require("./math/bankBalance");
9
- const pollingUserAccountSubscriber_1 = require("./accounts/pollingUserAccountSubscriber");
10
- const webSocketUserAccountSubscriber_1 = require("./accounts/webSocketUserAccountSubscriber");
11
- class ClearingHouseUser {
12
- constructor(config) {
13
- var _a;
14
- this._isSubscribed = false;
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
- }
23
- this.eventEmitter = this.accountSubscriber.eventEmitter;
24
- }
25
- get isSubscribed() {
26
- return this._isSubscribed && this.accountSubscriber.isSubscribed;
27
- }
28
- set isSubscribed(val) {
29
- this._isSubscribed = val;
30
- }
31
- /**
32
- * Subscribe to ClearingHouseUser state accounts
33
- * @returns SusbcriptionSuccess result
34
- */
35
- async subscribe() {
36
- this.isSubscribed = await this.accountSubscriber.subscribe();
37
- return this.isSubscribed;
38
- }
39
- /**
40
- * Forces the accountSubscriber to fetch account updates from rpc
41
- */
42
- async fetchAccounts() {
43
- await this.accountSubscriber.fetch();
44
- }
45
- async unsubscribe() {
46
- await this.accountSubscriber.unsubscribe();
47
- this.isSubscribed = false;
48
- }
49
- getUserAccount() {
50
- return this.accountSubscriber.getUserAccountAndSlot().data;
51
- }
52
- getUserAccountAndSlot() {
53
- return this.accountSubscriber.getUserAccountAndSlot();
54
- }
55
- /**
56
- * Gets the user's current position for a given market. If the user has no position returns undefined
57
- * @param marketIndex
58
- * @returns userPosition
59
- */
60
- getUserPosition(marketIndex) {
61
- return this.getUserAccount().positions.find((position) => position.marketIndex.eq(marketIndex));
62
- }
63
- getEmptyPosition(marketIndex) {
64
- return {
65
- baseAssetAmount: numericConstants_1.ZERO,
66
- lastCumulativeFundingRate: numericConstants_1.ZERO,
67
- marketIndex,
68
- quoteAssetAmount: numericConstants_1.ZERO,
69
- quoteEntryAmount: numericConstants_1.ZERO,
70
- openOrders: numericConstants_1.ZERO,
71
- unsettledPnl: numericConstants_1.ZERO,
72
- openBids: numericConstants_1.ZERO,
73
- openAsks: numericConstants_1.ZERO,
74
- };
75
- }
76
- /**
77
- * @param orderId
78
- * @returns Order
79
- */
80
- getOrder(orderId) {
81
- return this.getUserAccount().orders.find((order) => order.orderId.eq(orderId));
82
- }
83
- /**
84
- * @param userOrderId
85
- * @returns Order
86
- */
87
- getOrderByUserOrderId(userOrderId) {
88
- return this.getUserAccount().orders.find((order) => order.userOrderId === userOrderId);
89
- }
90
- getUserAccountPublicKey() {
91
- return this.userAccountPublicKey;
92
- }
93
- async exists() {
94
- const userAccountRPCResponse = await this.clearingHouse.connection.getParsedAccountInfo(this.userAccountPublicKey);
95
- return userAccountRPCResponse.value !== null;
96
- }
97
- /**
98
- * calculates Buying Power = FC * MAX_LEVERAGE
99
- * @returns : Precision QUOTE_PRECISION
100
- */
101
- getBuyingPower(marketIndex) {
102
- return this.getFreeCollateral()
103
- .mul(this.getMaxLeverage(marketIndex, 'Initial'))
104
- .div(numericConstants_1.TEN_THOUSAND);
105
- }
106
- /**
107
- * calculates Free Collateral = Total collateral - initial margin requirement
108
- * @returns : Precision QUOTE_PRECISION
109
- */
110
- getFreeCollateral() {
111
- const totalCollateral = this.getTotalCollateral();
112
- const initialMarginRequirement = this.getInitialMarginRequirement();
113
- const freeCollateral = totalCollateral.sub(initialMarginRequirement);
114
- return freeCollateral.gte(numericConstants_1.ZERO) ? freeCollateral : numericConstants_1.ZERO;
115
- }
116
- getInitialMarginRequirement() {
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))
121
- .mul(new _1.BN(market.marginRatioInitial))
122
- .div(numericConstants_1.MARGIN_PRECISION));
123
- }, numericConstants_1.ZERO)
124
- .add(this.getTotalLiability());
125
- }
126
- /**
127
- * @returns The partial margin requirement in USDC. : QUOTE_PRECISION
128
- */
129
- getMaintenanceMarginRequirement() {
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))
134
- .mul(new _1.BN(market.marginRatioMaintenance))
135
- .div(numericConstants_1.MARGIN_PRECISION));
136
- }, numericConstants_1.ZERO)
137
- .add(this.getTotalLiability());
138
- }
139
- /**
140
- * calculates unrealized position price pnl
141
- * @returns : Precision QUOTE_PRECISION
142
- */
143
- getUnrealizedPNL(withFunding, marketIndex) {
144
- return this.getUserAccount()
145
- .positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
146
- .reduce((pnl, marketPosition) => {
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);
160
- }, numericConstants_1.ZERO);
161
- }
162
- /**
163
- * calculates unrealized funding payment pnl
164
- * @returns : Precision QUOTE_PRECISION
165
- */
166
- getUnrealizedFundingPNL(marketIndex) {
167
- return this.getUserAccount()
168
- .positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
169
- .reduce((pnl, marketPosition) => {
170
- const market = this.clearingHouse.getMarketAccount(marketPosition.marketIndex);
171
- return pnl.add((0, _1.calculatePositionFundingPNL)(market, marketPosition));
172
- }, numericConstants_1.ZERO);
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
- }
207
- /**
208
- * calculates TotalCollateral: collateral + unrealized pnl
209
- * TODO: rename to total equity (for perpetuals swaps)
210
- * @returns : Precision QUOTE_PRECISION
211
- */
212
- getTotalCollateral() {
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());
230
- }
231
- /**
232
- * calculates sum of position value across all positions
233
- * @returns : Precision QUOTE_PRECISION
234
- */
235
- getTotalPositionValue() {
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)));
239
- }, numericConstants_1.ZERO);
240
- }
241
- /**
242
- * calculates position value from closing 100%
243
- * @returns : Precision QUOTE_PRECISION
244
- */
245
- getPositionValue(marketIndex, oraclePriceData) {
246
- const userPosition = this.getUserPosition(marketIndex) || this.getEmptyPosition(marketIndex);
247
- const market = this.clearingHouse.getMarketAccount(userPosition.marketIndex);
248
- return (0, _1.calculateBaseAssetValue)(market, userPosition, oraclePriceData);
249
- }
250
- getPositionSide(currentPosition) {
251
- if (currentPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
252
- return _1.PositionDirection.LONG;
253
- }
254
- else if (currentPosition.baseAssetAmount.lt(numericConstants_1.ZERO)) {
255
- return _1.PositionDirection.SHORT;
256
- }
257
- else {
258
- return undefined;
259
- }
260
- }
261
- /**
262
- * calculates average exit price for closing 100% of position
263
- * @returns : Precision MARK_PRICE_PRECISION
264
- */
265
- getPositionEstimatedExitPriceAndPnl(position, amountToClose) {
266
- const market = this.clearingHouse.getMarketAccount(position.marketIndex);
267
- const entryPrice = (0, position_1.calculateEntryPrice)(position);
268
- const oraclePriceData = this.getOracleDataForMarket(position.marketIndex);
269
- if (amountToClose) {
270
- if (amountToClose.eq(numericConstants_1.ZERO)) {
271
- return [(0, _1.calculateMarkPrice)(market, oraclePriceData), numericConstants_1.ZERO];
272
- }
273
- position = {
274
- baseAssetAmount: amountToClose,
275
- lastCumulativeFundingRate: position.lastCumulativeFundingRate,
276
- marketIndex: position.marketIndex,
277
- quoteAssetAmount: position.quoteAssetAmount,
278
- };
279
- }
280
- const baseAssetValue = (0, _1.calculateBaseAssetValue)(market, position, oraclePriceData);
281
- if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
282
- return [numericConstants_1.ZERO, numericConstants_1.ZERO];
283
- }
284
- const exitPrice = baseAssetValue
285
- .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
286
- .mul(numericConstants_1.MARK_PRICE_PRECISION)
287
- .div(position.baseAssetAmount.abs());
288
- const pnlPerBase = exitPrice.sub(entryPrice);
289
- const pnl = pnlPerBase
290
- .mul(position.baseAssetAmount)
291
- .div(numericConstants_1.MARK_PRICE_PRECISION)
292
- .div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
293
- return [exitPrice, pnl];
294
- }
295
- /**
296
- * calculates current user leverage across all positions
297
- * @returns : Precision TEN_THOUSAND
298
- */
299
- getLeverage() {
300
- const totalCollateral = this.getTotalCollateral();
301
- const totalPositionValue = this.getTotalPositionValue();
302
- if (totalPositionValue.eq(numericConstants_1.ZERO) && totalCollateral.eq(numericConstants_1.ZERO)) {
303
- return numericConstants_1.ZERO;
304
- }
305
- return totalPositionValue.mul(numericConstants_1.TEN_THOUSAND).div(totalCollateral);
306
- }
307
- /**
308
- * calculates max allowable leverage exceeding hitting requirement category
309
- * @params category {Initial, Partial, Maintenance}
310
- * @returns : Precision TEN_THOUSAND
311
- */
312
- getMaxLeverage(marketIndex, category = 'Initial') {
313
- const market = this.clearingHouse.getMarketAccount(marketIndex);
314
- let marginRatioCategory;
315
- switch (category) {
316
- case 'Initial':
317
- marginRatioCategory = market.marginRatioInitial;
318
- break;
319
- case 'Maintenance':
320
- marginRatioCategory = market.marginRatioMaintenance;
321
- break;
322
- default:
323
- marginRatioCategory = market.marginRatioInitial;
324
- break;
325
- }
326
- const maxLeverage = numericConstants_1.TEN_THOUSAND.mul(numericConstants_1.TEN_THOUSAND).div(new _1.BN(marginRatioCategory));
327
- return maxLeverage;
328
- }
329
- /**
330
- * calculates margin ratio: total collateral / |total position value|
331
- * @returns : Precision TEN_THOUSAND
332
- */
333
- getMarginRatio() {
334
- const totalPositionValue = this.getTotalPositionValue();
335
- if (totalPositionValue.eq(numericConstants_1.ZERO)) {
336
- return numericConstants_1.BN_MAX;
337
- }
338
- return this.getTotalCollateral().mul(numericConstants_1.TEN_THOUSAND).div(totalPositionValue);
339
- }
340
- canBeLiquidated() {
341
- const totalCollateral = this.getTotalCollateral();
342
- const partialMaintenanceRequirement = this.getMaintenanceMarginRequirement();
343
- const marginRatio = this.getMarginRatio();
344
- const canLiquidate = totalCollateral.lt(partialMaintenanceRequirement);
345
- return [canLiquidate, marginRatio];
346
- }
347
- /**
348
- * Checks if any user position cumulative funding differs from respective market cumulative funding
349
- * @returns
350
- */
351
- needsToSettleFundingPayment() {
352
- for (const userPosition of this.getUserAccount().positions) {
353
- if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
354
- continue;
355
- }
356
- const market = this.clearingHouse.getMarketAccount(userPosition.marketIndex);
357
- if (market.amm.cumulativeFundingRateLong.eq(userPosition.lastCumulativeFundingRate) ||
358
- market.amm.cumulativeFundingRateShort.eq(userPosition.lastCumulativeFundingRate)) {
359
- continue;
360
- }
361
- return true;
362
- }
363
- return false;
364
- }
365
- /**
366
- * Calculate the liquidation price of a position, with optional parameter to calculate the liquidation price after a trade
367
- * @param marketPosition
368
- * @param positionBaseSizeChange // change in position size to calculate liquidation price for : Precision 10^13
369
- * @param partial
370
- * @returns Precision : MARK_PRICE_PRECISION
371
- */
372
- liquidationPrice(marketPosition, positionBaseSizeChange = numericConstants_1.ZERO) {
373
- // solves formula for example canBeLiquidated below
374
- /* example: assume BTC price is $40k (examine 10% up/down)
375
-
376
- if 10k deposit and levered 10x short BTC => BTC up $400 means:
377
- 1. higher base_asset_value (+$4k)
378
- 2. lower collateral (-$4k)
379
- 3. (10k - 4k)/(100k + 4k) => 6k/104k => .0576
380
-
381
- for 10x long, BTC down $400:
382
- 3. (10k - 4k) / (100k - 4k) = 6k/96k => .0625 */
383
- const totalCollateral = this.getTotalCollateral();
384
- // calculate the total position value ignoring any value from the target market of the trade
385
- const totalPositionValueExcludingTargetMarket = this.getTotalPositionValueExcludingMarket(marketPosition.marketIndex);
386
- const currentMarketPosition = this.getUserPosition(marketPosition.marketIndex) ||
387
- this.getEmptyPosition(marketPosition.marketIndex);
388
- const currentMarketPositionBaseSize = currentMarketPosition.baseAssetAmount;
389
- const proposedBaseAssetAmount = currentMarketPositionBaseSize.add(positionBaseSizeChange);
390
- // calculate position for current market after trade
391
- const proposedMarketPosition = {
392
- marketIndex: marketPosition.marketIndex,
393
- baseAssetAmount: proposedBaseAssetAmount,
394
- lastCumulativeFundingRate: currentMarketPosition.lastCumulativeFundingRate,
395
- quoteAssetAmount: new _1.BN(0),
396
- quoteEntryAmount: new _1.BN(0),
397
- openOrders: new _1.BN(0),
398
- unsettledPnl: new _1.BN(0),
399
- openBids: new _1.BN(0),
400
- openAsks: new _1.BN(0),
401
- };
402
- if (proposedBaseAssetAmount.eq(numericConstants_1.ZERO))
403
- return new _1.BN(-1);
404
- const market = this.clearingHouse.getMarketAccount(proposedMarketPosition.marketIndex);
405
- const proposedMarketPositionValue = (0, _1.calculateBaseAssetValue)(market, proposedMarketPosition, this.getOracleDataForMarket(market.marketIndex));
406
- // total position value after trade
407
- const totalPositionValueAfterTrade = totalPositionValueExcludingTargetMarket.add(proposedMarketPositionValue);
408
- const marginRequirementExcludingTargetMarket = this.getUserAccount().positions.reduce((totalMarginRequirement, position) => {
409
- if (!position.marketIndex.eq(marketPosition.marketIndex)) {
410
- const market = this.clearingHouse.getMarketAccount(position.marketIndex);
411
- const positionValue = (0, _1.calculateBaseAssetValue)(market, position, this.getOracleDataForMarket(market.marketIndex));
412
- const marketMarginRequirement = positionValue
413
- .mul(new _1.BN(market.marginRatioMaintenance))
414
- .div(numericConstants_1.MARGIN_PRECISION);
415
- totalMarginRequirement = totalMarginRequirement.add(marketMarginRequirement);
416
- }
417
- return totalMarginRequirement;
418
- }, numericConstants_1.ZERO);
419
- const freeCollateralExcludingTargetMarket = totalCollateral.sub(marginRequirementExcludingTargetMarket);
420
- // if the position value after the trade is less than free collateral, there is no liq price
421
- if (totalPositionValueAfterTrade.lte(freeCollateralExcludingTargetMarket) &&
422
- proposedMarketPosition.baseAssetAmount.abs().gt(numericConstants_1.ZERO)) {
423
- return new _1.BN(-1);
424
- }
425
- const marginRequirementAfterTrade = marginRequirementExcludingTargetMarket.add(proposedMarketPositionValue
426
- .mul(new _1.BN(market.marginRatioMaintenance))
427
- .div(numericConstants_1.MARGIN_PRECISION));
428
- const freeCollateralAfterTrade = totalCollateral.sub(marginRequirementAfterTrade);
429
- const marketMaxLeverage = this.getMaxLeverage(proposedMarketPosition.marketIndex, 'Maintenance');
430
- let priceDelta;
431
- if (proposedBaseAssetAmount.lt(numericConstants_1.ZERO)) {
432
- priceDelta = freeCollateralAfterTrade
433
- .mul(marketMaxLeverage) // precision is TEN_THOUSAND
434
- .div(marketMaxLeverage.add(numericConstants_1.TEN_THOUSAND))
435
- .mul(numericConstants_1.PRICE_TO_QUOTE_PRECISION)
436
- .mul(numericConstants_1.AMM_RESERVE_PRECISION)
437
- .div(proposedBaseAssetAmount);
438
- }
439
- else {
440
- priceDelta = freeCollateralAfterTrade
441
- .mul(marketMaxLeverage) // precision is TEN_THOUSAND
442
- .div(marketMaxLeverage.sub(numericConstants_1.TEN_THOUSAND))
443
- .mul(numericConstants_1.PRICE_TO_QUOTE_PRECISION)
444
- .mul(numericConstants_1.AMM_RESERVE_PRECISION)
445
- .div(proposedBaseAssetAmount);
446
- }
447
- let markPriceAfterTrade;
448
- if (positionBaseSizeChange.eq(numericConstants_1.ZERO)) {
449
- markPriceAfterTrade = (0, _1.calculateMarkPrice)(this.clearingHouse.getMarketAccount(marketPosition.marketIndex), this.getOracleDataForMarket(marketPosition.marketIndex));
450
- }
451
- else {
452
- const direction = positionBaseSizeChange.gt(numericConstants_1.ZERO)
453
- ? _1.PositionDirection.LONG
454
- : _1.PositionDirection.SHORT;
455
- markPriceAfterTrade = (0, _1.calculateTradeSlippage)(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarketAccount(marketPosition.marketIndex), 'base', this.getOracleDataForMarket(marketPosition.marketIndex))[3]; // newPrice after swap
456
- }
457
- if (priceDelta.gt(markPriceAfterTrade)) {
458
- return new _1.BN(-1);
459
- }
460
- return markPriceAfterTrade.sub(priceDelta);
461
- }
462
- /**
463
- * Calculates the estimated liquidation price for a position after closing a quote amount of the position.
464
- * @param positionMarketIndex
465
- * @param closeQuoteAmount
466
- * @returns : Precision MARK_PRICE_PRECISION
467
- */
468
- liquidationPriceAfterClose(positionMarketIndex, closeQuoteAmount) {
469
- const currentPosition = this.getUserPosition(positionMarketIndex) ||
470
- this.getEmptyPosition(positionMarketIndex);
471
- const closeBaseAmount = currentPosition.baseAssetAmount
472
- .mul(closeQuoteAmount)
473
- .div(currentPosition.quoteAssetAmount)
474
- .add(currentPosition.baseAssetAmount
475
- .mul(closeQuoteAmount)
476
- .mod(currentPosition.quoteAssetAmount))
477
- .neg();
478
- return this.liquidationPrice({
479
- marketIndex: positionMarketIndex,
480
- }, closeBaseAmount);
481
- }
482
- /**
483
- * Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.
484
- *
485
- * To Calculate Max Quote Available:
486
- *
487
- * Case 1: SameSide
488
- * => Remaining quote to get to maxLeverage
489
- *
490
- * Case 2: NOT SameSide && currentLeverage <= maxLeverage
491
- * => Current opposite position x2 + remaining to get to maxLeverage
492
- *
493
- * Case 3: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition > maxLeverage
494
- * => strictly reduce current position size
495
- *
496
- * Case 4: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition < maxLeverage
497
- * => current position + remaining to get to maxLeverage
498
- *
499
- * @param targetMarketIndex
500
- * @param tradeSide
501
- * @returns tradeSizeAllowed : Precision QUOTE_PRECISION
502
- */
503
- getMaxTradeSizeUSDC(targetMarketIndex, tradeSide) {
504
- const currentPosition = this.getUserPosition(targetMarketIndex) ||
505
- this.getEmptyPosition(targetMarketIndex);
506
- const targetSide = (0, types_1.isVariant)(tradeSide, 'short') ? 'short' : 'long';
507
- const currentPositionSide = (currentPosition === null || currentPosition === void 0 ? void 0 : currentPosition.baseAssetAmount.isNeg())
508
- ? 'short'
509
- : 'long';
510
- const targetingSameSide = !currentPosition
511
- ? true
512
- : targetSide === currentPositionSide;
513
- const oracleData = this.getOracleDataForMarket(targetMarketIndex);
514
- // 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.
515
- const oppositeSizeValueUSDC = targetingSameSide
516
- ? numericConstants_1.ZERO
517
- : this.getPositionValue(targetMarketIndex, oracleData);
518
- let maxPositionSize = this.getBuyingPower(targetMarketIndex);
519
- if (maxPositionSize.gte(numericConstants_1.ZERO)) {
520
- if (oppositeSizeValueUSDC.eq(numericConstants_1.ZERO)) {
521
- // case 1 : Regular trade where current total position less than max, and no opposite position to account for
522
- // do nothing
523
- }
524
- else {
525
- // case 2 : trade where current total position less than max, but need to account for flipping the current position over to the other side
526
- maxPositionSize = maxPositionSize.add(oppositeSizeValueUSDC.mul(new _1.BN(2)));
527
- }
528
- }
529
- else {
530
- // current leverage is greater than max leverage - can only reduce position size
531
- if (!targetingSameSide) {
532
- const market = this.clearingHouse.getMarketAccount(targetMarketIndex);
533
- const marketPositionValue = this.getPositionValue(targetMarketIndex, oracleData);
534
- const totalCollateral = this.getTotalCollateral();
535
- const marginRequirement = this.getInitialMarginRequirement();
536
- const marginFreedByClosing = marketPositionValue
537
- .mul(new _1.BN(market.marginRatioInitial))
538
- .div(numericConstants_1.MARGIN_PRECISION);
539
- const marginRequirementAfterClosing = marginRequirement.sub(marginFreedByClosing);
540
- if (marginRequirementAfterClosing.gt(totalCollateral)) {
541
- maxPositionSize = marketPositionValue;
542
- }
543
- else {
544
- const freeCollateralAfterClose = totalCollateral.sub(marginRequirementAfterClosing);
545
- const buyingPowerAfterClose = freeCollateralAfterClose
546
- .mul(this.getMaxLeverage(targetMarketIndex))
547
- .div(numericConstants_1.TEN_THOUSAND);
548
- maxPositionSize = marketPositionValue.add(buyingPowerAfterClose);
549
- }
550
- }
551
- else {
552
- // do nothing if targetting same side
553
- }
554
- }
555
- // subtract oneMillionth of maxPositionSize
556
- // => to avoid rounding errors when taking max leverage
557
- const oneMilli = maxPositionSize.div(numericConstants_1.QUOTE_PRECISION);
558
- return maxPositionSize.sub(oneMilli);
559
- }
560
- // TODO - should this take the price impact of the trade into account for strict accuracy?
561
- /**
562
- * Returns the leverage ratio for the account after adding (or subtracting) the given quote size to the given position
563
- * @param targetMarketIndex
564
- * @param positionMarketIndex
565
- * @param tradeQuoteAmount
566
- * @returns leverageRatio : Precision TEN_THOUSAND
567
- */
568
- accountLeverageRatioAfterTrade(targetMarketIndex, tradeQuoteAmount, tradeSide) {
569
- const currentPosition = this.getUserPosition(targetMarketIndex) ||
570
- this.getEmptyPosition(targetMarketIndex);
571
- const oracleData = this.getOracleDataForMarket(targetMarketIndex);
572
- let currentPositionQuoteAmount = this.getPositionValue(targetMarketIndex, oracleData);
573
- const currentSide = currentPosition && currentPosition.baseAssetAmount.isNeg()
574
- ? _1.PositionDirection.SHORT
575
- : _1.PositionDirection.LONG;
576
- if (currentSide === _1.PositionDirection.SHORT)
577
- currentPositionQuoteAmount = currentPositionQuoteAmount.neg();
578
- if (tradeSide === _1.PositionDirection.SHORT)
579
- tradeQuoteAmount = tradeQuoteAmount.neg();
580
- const currentMarketPositionAfterTrade = currentPositionQuoteAmount
581
- .add(tradeQuoteAmount)
582
- .abs();
583
- const totalPositionAfterTradeExcludingTargetMarket = this.getTotalPositionValueExcludingMarket(targetMarketIndex);
584
- const totalCollateral = this.getTotalCollateral();
585
- if (totalCollateral.gt(numericConstants_1.ZERO)) {
586
- const newLeverage = currentMarketPositionAfterTrade
587
- .add(totalPositionAfterTradeExcludingTargetMarket)
588
- .abs()
589
- .mul(numericConstants_1.TEN_THOUSAND)
590
- .div(totalCollateral);
591
- return newLeverage;
592
- }
593
- else {
594
- return new _1.BN(0);
595
- }
596
- }
597
- /**
598
- * Calculates how much fee will be taken for a given sized trade
599
- * @param quoteAmount
600
- * @returns feeForQuote : Precision QUOTE_PRECISION
601
- */
602
- calculateFeeForQuoteAmount(quoteAmount) {
603
- const feeStructure = this.clearingHouse.getStateAccount().feeStructure;
604
- return quoteAmount
605
- .mul(feeStructure.feeNumerator)
606
- .div(feeStructure.feeDenominator);
607
- }
608
- /**
609
- * Get the total position value, excluding any position coming from the given target market
610
- * @param marketToIgnore
611
- * @returns positionValue : Precision QUOTE_PRECISION
612
- */
613
- getTotalPositionValueExcludingMarket(marketToIgnore) {
614
- const currentMarketPosition = this.getUserPosition(marketToIgnore) ||
615
- this.getEmptyPosition(marketToIgnore);
616
- const oracleData = this.getOracleDataForMarket(marketToIgnore);
617
- let currentMarketPositionValueUSDC = numericConstants_1.ZERO;
618
- if (currentMarketPosition) {
619
- currentMarketPositionValueUSDC = this.getPositionValue(marketToIgnore, oracleData);
620
- }
621
- return this.getTotalPositionValue().sub(currentMarketPositionValueUSDC);
622
- }
623
- getOracleDataForMarket(marketIndex) {
624
- const oracleKey = this.clearingHouse.getMarketAccount(marketIndex).amm.oracle;
625
- const oracleData = this.clearingHouse.getOraclePriceDataAndSlot(oracleKey).data;
626
- return oracleData;
627
- }
628
- getOracleDataForBank(bankIndex) {
629
- const oracleKey = this.clearingHouse.getBankAccount(bankIndex).oracle;
630
- const oracleData = this.clearingHouse.getOraclePriceDataAndSlot(oracleKey).data;
631
- return oracleData;
632
- }
633
- }
634
- exports.ClearingHouseUser = ClearingHouseUser;
@@ -1,14 +0,0 @@
1
- import { ClearingHouse } from './clearingHouse';
2
- import { PublicKey } from '@solana/web3.js';
3
- import { BulkAccountLoader } from './accounts/bulkAccountLoader';
4
- export declare type ClearingHouseUserConfig = {
5
- accountSubscription?: ClearingHouseUserAccountSubscriptionConfig;
6
- clearingHouse: ClearingHouse;
7
- userAccountPublicKey: PublicKey;
8
- };
9
- export declare type ClearingHouseUserAccountSubscriptionConfig = {
10
- type: 'websocket';
11
- } | {
12
- type: 'polling';
13
- accountLoader: BulkAccountLoader;
14
- };
@@ -1,16 +0,0 @@
1
- /// <reference types="bn.js" />
2
- import { BN, OracleSource } from '../';
3
- import { DriftEnv } from '../';
4
- import { PublicKey } from '@solana/web3.js';
5
- export declare type BankConfig = {
6
- symbol: string;
7
- bankIndex: BN;
8
- oracle: PublicKey;
9
- mint: PublicKey;
10
- oracleSource: OracleSource;
11
- };
12
- export declare const DevnetBanks: BankConfig[];
13
- export declare const MainnetBanks: BankConfig[];
14
- export declare const Banks: {
15
- [key in DriftEnv]: BankConfig[];
16
- };