@drift-labs/sdk 0.2.0-master.4 → 0.2.0-master.41

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 (247) hide show
  1. package/README.md +27 -27
  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 +9 -9
  30. package/lib/config.js +25 -21
  31. package/lib/constants/numericConstants.d.ts +30 -12
  32. package/lib/constants/numericConstants.js +41 -21
  33. package/lib/constants/perpMarkets.d.ts +18 -0
  34. package/lib/constants/{markets.js → perpMarkets.js} +7 -7
  35. package/lib/constants/spotMarkets.d.ts +19 -0
  36. package/lib/constants/spotMarkets.js +53 -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.js +3 -0
  48. package/lib/events/eventSubscriber.d.ts +5 -2
  49. package/lib/events/eventSubscriber.js +25 -11
  50. package/lib/events/fetchLogs.d.ts +13 -2
  51. package/lib/events/fetchLogs.js +40 -12
  52. package/lib/events/pollingLogProvider.d.ts +2 -1
  53. package/lib/events/pollingLogProvider.js +7 -3
  54. package/lib/events/sort.js +8 -11
  55. package/lib/events/types.d.ts +11 -3
  56. package/lib/events/types.js +8 -0
  57. package/lib/events/webSocketLogProvider.js +1 -1
  58. package/lib/examples/makeTradeExample.js +30 -18
  59. package/lib/factory/bigNum.d.ts +8 -4
  60. package/lib/factory/bigNum.js +109 -19
  61. package/lib/idl/drift.json +8386 -0
  62. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  63. package/lib/index.d.ts +30 -13
  64. package/lib/index.js +30 -13
  65. package/lib/math/amm.d.ts +9 -6
  66. package/lib/math/amm.js +91 -38
  67. package/lib/math/conversion.js +1 -1
  68. package/lib/math/exchangeStatus.d.ts +4 -0
  69. package/lib/math/exchangeStatus.js +18 -0
  70. package/lib/math/funding.d.ts +6 -6
  71. package/lib/math/funding.js +23 -21
  72. package/lib/math/insurance.d.ts +4 -0
  73. package/lib/math/insurance.js +27 -0
  74. package/lib/math/margin.d.ts +11 -0
  75. package/lib/math/margin.js +82 -0
  76. package/lib/math/market.d.ts +14 -9
  77. package/lib/math/market.js +70 -10
  78. package/lib/math/oracles.d.ts +4 -0
  79. package/lib/math/oracles.js +36 -8
  80. package/lib/math/orders.d.ts +16 -6
  81. package/lib/math/orders.js +97 -17
  82. package/lib/math/position.d.ts +27 -13
  83. package/lib/math/position.js +92 -36
  84. package/lib/math/repeg.js +17 -8
  85. package/lib/math/spotBalance.d.ts +22 -0
  86. package/lib/math/spotBalance.js +192 -0
  87. package/lib/math/spotMarket.d.ts +4 -0
  88. package/lib/math/spotMarket.js +8 -0
  89. package/lib/math/spotPosition.d.ts +6 -0
  90. package/lib/math/spotPosition.js +23 -0
  91. package/lib/math/trade.d.ts +10 -10
  92. package/lib/math/trade.js +27 -31
  93. package/lib/oracles/pythClient.js +1 -1
  94. package/lib/oracles/quoteAssetOracleClient.js +1 -1
  95. package/lib/oracles/switchboardClient.js +1 -1
  96. package/lib/orderParams.d.ts +4 -4
  97. package/lib/orderParams.js +12 -4
  98. package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
  99. package/lib/serum/serumFulfillmentConfigMap.js +17 -0
  100. package/lib/serum/serumSubscriber.d.ts +27 -0
  101. package/lib/serum/serumSubscriber.js +56 -0
  102. package/lib/serum/types.d.ts +11 -0
  103. package/lib/{clearingHouseUserConfig.js → serum/types.js} +0 -0
  104. package/lib/slot/SlotSubscriber.d.ts +7 -0
  105. package/lib/slot/SlotSubscriber.js +3 -0
  106. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  107. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  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/tx/utils.js +1 -1
  112. package/lib/types.d.ts +688 -216
  113. package/lib/types.js +153 -24
  114. package/lib/user.d.ts +228 -0
  115. package/lib/user.js +959 -0
  116. package/lib/userConfig.d.ts +14 -0
  117. package/lib/userConfig.js +2 -0
  118. package/lib/userMap/userMap.d.ts +41 -0
  119. package/lib/userMap/userMap.js +85 -0
  120. package/lib/userMap/userStatsMap.d.ts +19 -0
  121. package/lib/userMap/userStatsMap.js +68 -0
  122. package/lib/userName.d.ts +1 -0
  123. package/lib/userName.js +3 -2
  124. package/lib/userStats.d.ts +18 -0
  125. package/lib/userStats.js +49 -0
  126. package/lib/userStatsConfig.d.ts +14 -0
  127. package/lib/userStatsConfig.js +2 -0
  128. package/lib/util/computeUnits.js +1 -1
  129. package/lib/util/getTokenAddress.d.ts +2 -0
  130. package/lib/util/getTokenAddress.js +9 -0
  131. package/package.json +11 -4
  132. package/src/accounts/bulkAccountLoader.ts +44 -34
  133. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  134. package/src/accounts/bulkUserSubscription.ts +2 -3
  135. package/src/accounts/fetch.ts +27 -2
  136. package/src/accounts/{pollingClearingHouseAccountSubscriber.ts → pollingDriftClientAccountSubscriber.ts} +65 -75
  137. package/src/accounts/{pollingOracleSubscriber.ts → pollingOracleAccountSubscriber.ts} +2 -2
  138. package/src/accounts/pollingUserAccountSubscriber.ts +5 -12
  139. package/src/accounts/pollingUserStatsAccountSubscriber.ts +166 -0
  140. package/src/accounts/types.ts +35 -15
  141. package/src/accounts/{webSocketClearingHouseAccountSubscriber.ts → webSocketDriftClientAccountSubscriber.ts} +78 -73
  142. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  143. package/src/addresses/marketAddresses.ts +3 -4
  144. package/src/addresses/pda.ts +105 -33
  145. package/src/adminClient.ts +1207 -0
  146. package/src/assert/assert.js +9 -0
  147. package/src/config.ts +37 -31
  148. package/src/constants/numericConstants.ts +58 -24
  149. package/src/constants/{markets.ts → perpMarkets.ts} +10 -10
  150. package/src/constants/spotMarkets.ts +73 -0
  151. package/src/dlob/DLOB.ts +1120 -0
  152. package/src/dlob/DLOBNode.ts +155 -0
  153. package/src/dlob/NodeList.ts +195 -0
  154. package/src/driftClient.ts +3594 -0
  155. package/src/{clearingHouseConfig.ts → driftClientConfig.ts} +9 -8
  156. package/src/events/eventList.js +77 -0
  157. package/src/events/eventList.ts +3 -0
  158. package/src/events/eventSubscriber.ts +36 -14
  159. package/src/events/fetchLogs.ts +55 -13
  160. package/src/events/pollingLogProvider.ts +11 -3
  161. package/src/events/sort.ts +11 -15
  162. package/src/events/types.ts +27 -2
  163. package/src/events/webSocketLogProvider.ts +1 -1
  164. package/src/examples/makeTradeExample.js +157 -0
  165. package/src/examples/makeTradeExample.ts +44 -28
  166. package/src/factory/bigNum.ts +150 -22
  167. package/src/idl/drift.json +8386 -0
  168. package/src/idl/pyth.json +98 -2
  169. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  170. package/src/index.ts +30 -13
  171. package/src/math/amm.ts +161 -48
  172. package/src/math/conversion.ts +2 -2
  173. package/src/math/exchangeStatus.ts +31 -0
  174. package/src/math/funding.ts +41 -31
  175. package/src/math/insurance.ts +35 -0
  176. package/src/math/margin.ts +133 -0
  177. package/src/math/market.ts +143 -14
  178. package/src/math/oracles.ts +63 -9
  179. package/src/math/orders.ts +168 -26
  180. package/src/math/position.ts +136 -58
  181. package/src/math/repeg.ts +19 -9
  182. package/src/math/spotBalance.ts +319 -0
  183. package/src/math/spotMarket.ts +9 -0
  184. package/src/math/spotPosition.ts +47 -0
  185. package/src/math/trade.ts +33 -37
  186. package/src/oracles/pythClient.ts +2 -2
  187. package/src/oracles/quoteAssetOracleClient.ts +2 -2
  188. package/src/oracles/switchboardClient.ts +2 -2
  189. package/src/orderParams.ts +16 -8
  190. package/src/serum/serumFulfillmentConfigMap.ts +26 -0
  191. package/src/serum/serumSubscriber.ts +99 -0
  192. package/src/serum/types.ts +13 -0
  193. package/src/slot/SlotSubscriber.ts +11 -1
  194. package/src/token/index.js +38 -0
  195. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  196. package/src/tx/retryTxSender.ts +16 -5
  197. package/src/tx/types.js +2 -0
  198. package/src/tx/types.ts +2 -1
  199. package/src/tx/utils.js +17 -0
  200. package/src/tx/utils.ts +1 -1
  201. package/src/types.ts +650 -189
  202. package/src/user.ts +1599 -0
  203. package/src/{clearingHouseUserConfig.ts → userConfig.ts} +5 -5
  204. package/src/userMap/userMap.ts +124 -0
  205. package/src/userMap/userStatsMap.ts +108 -0
  206. package/src/userName.ts +2 -1
  207. package/src/userStats.ts +75 -0
  208. package/src/userStatsConfig.ts +18 -0
  209. package/src/util/computeUnits.js +21 -11
  210. package/src/util/computeUnits.ts +1 -1
  211. package/src/util/getTokenAddress.js +9 -0
  212. package/src/util/getTokenAddress.ts +18 -0
  213. package/src/util/promiseTimeout.js +14 -0
  214. package/src/util/tps.js +27 -0
  215. package/tests/bn/test.ts +46 -11
  216. package/tests/dlob/helpers.ts +620 -0
  217. package/tests/dlob/test.ts +4586 -0
  218. package/yarn-error.log +3160 -0
  219. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +0 -49
  220. package/lib/admin.d.ts +0 -44
  221. package/lib/admin.js +0 -433
  222. package/lib/clearingHouse.d.ts +0 -133
  223. package/lib/clearingHouse.js +0 -931
  224. package/lib/clearingHouseUser.d.ts +0 -187
  225. package/lib/clearingHouseUser.js +0 -643
  226. package/lib/clearingHouseUserConfig.d.ts +0 -14
  227. package/lib/constants/banks.d.ts +0 -16
  228. package/lib/constants/banks.js +0 -34
  229. package/lib/constants/markets.d.ts +0 -19
  230. package/lib/idl/clearing_house.json +0 -3998
  231. package/lib/math/bankBalance.d.ts +0 -9
  232. package/lib/math/bankBalance.js +0 -75
  233. package/lib/math/state.d.ts +0 -8
  234. package/lib/math/state.js +0 -15
  235. package/lib/orders.d.ts +0 -8
  236. package/lib/orders.js +0 -134
  237. package/src/admin.ts +0 -722
  238. package/src/clearingHouse.ts +0 -1451
  239. package/src/clearingHouseUser.ts +0 -989
  240. package/src/constants/banks.ts +0 -43
  241. package/src/idl/clearing_house.json +0 -3998
  242. package/src/math/bankBalance.ts +0 -112
  243. package/src/math/state.ts +0 -14
  244. package/src/math/utils.js +0 -27
  245. package/src/math/utils.js.map +0 -1
  246. package/src/orders.ts +0 -244
  247. package/src/util/computeUnits.js.map +0 -1
@@ -1,931 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.ClearingHouse = void 0;
30
- const anchor_1 = require("@project-serum/anchor");
31
- const spl_token_1 = require("@solana/spl-token");
32
- const types_1 = require("./types");
33
- const anchor = __importStar(require("@project-serum/anchor"));
34
- const clearing_house_json_1 = __importDefault(require("./idl/clearing_house.json"));
35
- const web3_js_1 = require("@solana/web3.js");
36
- const pda_1 = require("./addresses/pda");
37
- const utils_1 = require("./tx/utils");
38
- const numericConstants_1 = require("./constants/numericConstants");
39
- const position_1 = require("./math/position");
40
- const bankBalance_1 = require("./math/bankBalance");
41
- const userName_1 = require("./userName");
42
- const pollingClearingHouseAccountSubscriber_1 = require("./accounts/pollingClearingHouseAccountSubscriber");
43
- const webSocketClearingHouseAccountSubscriber_1 = require("./accounts/webSocketClearingHouseAccountSubscriber");
44
- const retryTxSender_1 = require("./tx/retryTxSender");
45
- const clearingHouseUser_1 = require("./clearingHouseUser");
46
- const config_1 = require("./config");
47
- /**
48
- * # ClearingHouse
49
- * 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.
50
- */
51
- class ClearingHouse {
52
- constructor(config) {
53
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
54
- this.users = new Map();
55
- this._isSubscribed = false;
56
- this.marketLastSlotCache = new Map();
57
- this.connection = config.connection;
58
- this.wallet = config.wallet;
59
- this.opts = config.opts || anchor_1.AnchorProvider.defaultOptions();
60
- this.provider = new anchor_1.AnchorProvider(config.connection, config.wallet, this.opts);
61
- this.program = new anchor_1.Program(clearing_house_json_1.default, config.programID, this.provider);
62
- const userIds = (_a = config.userIds) !== null && _a !== void 0 ? _a : [0];
63
- this.activeUserId = (_b = config.activeUserId) !== null && _b !== void 0 ? _b : userIds[0];
64
- this.userAccountSubscriptionConfig =
65
- ((_c = config.accountSubscription) === null || _c === void 0 ? void 0 : _c.type) === 'polling'
66
- ? {
67
- type: 'polling',
68
- accountLoader: config.accountSubscription.accountLoader,
69
- }
70
- : {
71
- type: 'websocket',
72
- };
73
- this.createUsers(userIds, this.userAccountSubscriptionConfig);
74
- let marketIndexes = config.marketIndexes;
75
- let bankIndexes = config.bankIndexes;
76
- let oracleInfos = config.oracleInfos;
77
- if (config.env) {
78
- const { marketIndexes: envMarketIndexes, bankIndexes: envBankIndexes, oracleInfos: envOralceInfos, } = (0, config_1.getMarketsBanksAndOraclesForSubscription)(config.env);
79
- marketIndexes = marketIndexes ? marketIndexes : envMarketIndexes;
80
- bankIndexes = bankIndexes ? bankIndexes : envBankIndexes;
81
- oracleInfos = oracleInfos ? oracleInfos : envOralceInfos;
82
- }
83
- if (((_d = config.accountSubscription) === null || _d === void 0 ? void 0 : _d.type) === 'polling') {
84
- this.accountSubscriber = new pollingClearingHouseAccountSubscriber_1.PollingClearingHouseAccountSubscriber(this.program, config.accountSubscription.accountLoader, marketIndexes !== null && marketIndexes !== void 0 ? marketIndexes : [], bankIndexes !== null && bankIndexes !== void 0 ? bankIndexes : [], oracleInfos !== null && oracleInfos !== void 0 ? oracleInfos : []);
85
- }
86
- else {
87
- this.accountSubscriber = new webSocketClearingHouseAccountSubscriber_1.WebSocketClearingHouseAccountSubscriber(this.program, (_e = config.marketIndexes) !== null && _e !== void 0 ? _e : [], (_f = config.bankIndexes) !== null && _f !== void 0 ? _f : [], (_g = config.oracleInfos) !== null && _g !== void 0 ? _g : []);
88
- }
89
- this.eventEmitter = this.accountSubscriber.eventEmitter;
90
- this.txSender = new retryTxSender_1.RetryTxSender(this.provider, (_h = config.txSenderConfig) === null || _h === void 0 ? void 0 : _h.timeout, (_j = config.txSenderConfig) === null || _j === void 0 ? void 0 : _j.retrySleep, (_k = config.txSenderConfig) === null || _k === void 0 ? void 0 : _k.additionalConnections);
91
- }
92
- get isSubscribed() {
93
- return this._isSubscribed && this.accountSubscriber.isSubscribed;
94
- }
95
- set isSubscribed(val) {
96
- this._isSubscribed = val;
97
- }
98
- createUsers(userIds, accountSubscriptionConfig) {
99
- for (const userId of userIds) {
100
- const user = this.createUser(userId, accountSubscriptionConfig);
101
- this.users.set(userId, user);
102
- }
103
- }
104
- createUser(userId, accountSubscriptionConfig) {
105
- const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, userId);
106
- return new clearingHouseUser_1.ClearingHouseUser({
107
- clearingHouse: this,
108
- userAccountPublicKey,
109
- accountSubscription: accountSubscriptionConfig,
110
- });
111
- }
112
- async subscribe() {
113
- const subscribePromises = this.subscribeUsers().concat(this.accountSubscriber.subscribe());
114
- this.isSubscribed = (await Promise.all(subscribePromises)).reduce((success, prevSuccess) => success && prevSuccess);
115
- return this.isSubscribed;
116
- }
117
- subscribeUsers() {
118
- return [...this.users.values()].map((user) => user.subscribe());
119
- }
120
- /**
121
- * Forces the accountSubscriber to fetch account updates from rpc
122
- */
123
- async fetchAccounts() {
124
- await Promise.all([...this.users.values()]
125
- .map((user) => user.fetchAccounts())
126
- .concat(this.accountSubscriber.fetch()));
127
- }
128
- async unsubscribe() {
129
- const unsubscribePromises = this.unsubscribeUsers().concat(this.accountSubscriber.unsubscribe());
130
- await Promise.all(unsubscribePromises);
131
- this.isSubscribed = false;
132
- }
133
- unsubscribeUsers() {
134
- return [...this.users.values()].map((user) => user.unsubscribe());
135
- }
136
- async getStatePublicKey() {
137
- if (this.statePublicKey) {
138
- return this.statePublicKey;
139
- }
140
- this.statePublicKey = await (0, pda_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
141
- return this.statePublicKey;
142
- }
143
- getStateAccount() {
144
- return this.accountSubscriber.getStateAccountAndSlot().data;
145
- }
146
- getMarketAccount(marketIndex) {
147
- var _a;
148
- marketIndex = marketIndex instanceof anchor_1.BN ? marketIndex : new anchor_1.BN(marketIndex);
149
- return (_a = this.accountSubscriber.getMarketAccountAndSlot(marketIndex)) === null || _a === void 0 ? void 0 : _a.data;
150
- }
151
- getMarketAccounts() {
152
- return this.accountSubscriber
153
- .getMarketAccountsAndSlots()
154
- .map((value) => value.data);
155
- }
156
- getBankAccount(bankIndex) {
157
- bankIndex = bankIndex instanceof anchor_1.BN ? bankIndex : new anchor_1.BN(bankIndex);
158
- return this.accountSubscriber.getBankAccountAndSlot(bankIndex).data;
159
- }
160
- getQuoteAssetBankAccount() {
161
- return this.accountSubscriber.getBankAccountAndSlot(numericConstants_1.QUOTE_ASSET_BANK_INDEX)
162
- .data;
163
- }
164
- getOraclePriceDataAndSlot(oraclePublicKey) {
165
- return this.accountSubscriber.getOraclePriceDataAndSlot(oraclePublicKey);
166
- }
167
- /**
168
- * Update the wallet to use for clearing house transactions and linked user account
169
- * @param newWallet
170
- * @param userIds
171
- * @param activeUserId
172
- */
173
- async updateWallet(newWallet, userIds = [0], activeUserId = 0) {
174
- const newProvider = new anchor_1.AnchorProvider(this.connection, newWallet, this.opts);
175
- const newProgram = new anchor_1.Program(clearing_house_json_1.default, this.program.programId, newProvider);
176
- // Update provider for txSender with new wallet details
177
- this.txSender.provider = newProvider;
178
- this.wallet = newWallet;
179
- this.provider = newProvider;
180
- this.program = newProgram;
181
- if (this.isSubscribed) {
182
- await Promise.all(this.unsubscribeUsers());
183
- }
184
- this.users.clear();
185
- this.createUsers(userIds, this.userAccountSubscriptionConfig);
186
- if (this.isSubscribed) {
187
- await Promise.all(this.subscribeUsers());
188
- }
189
- this.activeUserId = activeUserId;
190
- }
191
- async switchActiveUser(userId) {
192
- this.activeUserId = userId;
193
- }
194
- async addUser(userId) {
195
- if (this.users.has(userId)) {
196
- return;
197
- }
198
- const user = this.createUser(userId, this.userAccountSubscriptionConfig);
199
- await user.subscribe();
200
- this.users.set(userId, user);
201
- }
202
- async initializeUserAccount(userId = 0, name = userName_1.DEFAULT_USER_NAME) {
203
- const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(userId, name);
204
- const tx = new web3_js_1.Transaction().add(initializeUserAccountIx);
205
- const { txSig } = await this.txSender.send(tx, [], this.opts);
206
- return [txSig, userAccountPublicKey];
207
- }
208
- async getInitializeUserInstructions(userId = 0, name = userName_1.DEFAULT_USER_NAME) {
209
- const userAccountPublicKey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, userId);
210
- const nameBuffer = (0, userName_1.encodeName)(name);
211
- const initializeUserAccountIx = await this.program.instruction.initializeUser(userId, nameBuffer, {
212
- accounts: {
213
- user: userAccountPublicKey,
214
- authority: this.wallet.publicKey,
215
- payer: this.wallet.publicKey,
216
- rent: anchor.web3.SYSVAR_RENT_PUBKEY,
217
- systemProgram: anchor.web3.SystemProgram.programId,
218
- state: await this.getStatePublicKey(),
219
- },
220
- });
221
- return [userAccountPublicKey, initializeUserAccountIx];
222
- }
223
- getUser(userId) {
224
- userId = userId !== null && userId !== void 0 ? userId : this.activeUserId;
225
- if (!this.users.has(userId)) {
226
- throw new Error(`Clearing House has no user for user id ${userId}`);
227
- }
228
- return this.users.get(userId);
229
- }
230
- getUsers() {
231
- return [...this.users.values()];
232
- }
233
- async getUserAccountPublicKey() {
234
- return this.getUser().userAccountPublicKey;
235
- }
236
- getUserAccount(userId) {
237
- return this.getUser(userId).getUserAccount();
238
- }
239
- getUserAccountAndSlot(userId) {
240
- return this.getUser(userId).getUserAccountAndSlot();
241
- }
242
- getUserBankBalance(bankIndex) {
243
- const bankIndexBN = bankIndex instanceof anchor_1.BN ? bankIndex : new anchor_1.BN(bankIndex);
244
- return this.getUserAccount().bankBalances.find((bankBalance) => bankBalance.bankIndex.eq(bankIndexBN));
245
- }
246
- getQuoteAssetTokenAmount() {
247
- const bank = this.getBankAccount(numericConstants_1.QUOTE_ASSET_BANK_INDEX);
248
- const userBankBalance = this.getUserBankBalance(numericConstants_1.QUOTE_ASSET_BANK_INDEX);
249
- return (0, bankBalance_1.getTokenAmount)(userBankBalance.balance, bank, userBankBalance.balanceType);
250
- }
251
- getRemainingAccounts(params) {
252
- const userAccountAndSlot = this.getUserAccountAndSlot();
253
- if (!userAccountAndSlot) {
254
- throw Error('No user account found. Most likely user account does not exist or failed to fetch account');
255
- }
256
- const { data: userAccount, slot: lastUserPositionsSlot } = userAccountAndSlot;
257
- const oracleAccountMap = new Map();
258
- const bankAccountMap = new Map();
259
- const marketAccountMap = new Map();
260
- for (const [marketIndexNum, slot] of this.marketLastSlotCache.entries()) {
261
- // if cache has more recent slot than user positions account slot, add market to remaining accounts
262
- // otherwise remove from slot
263
- if (slot > lastUserPositionsSlot) {
264
- const marketAccount = this.getMarketAccount(marketIndexNum);
265
- marketAccountMap.set(marketIndexNum, {
266
- pubkey: marketAccount.pubkey,
267
- isSigner: false,
268
- isWritable: false,
269
- });
270
- oracleAccountMap.set(marketAccount.amm.oracle.toString(), {
271
- pubkey: marketAccount.amm.oracle,
272
- isSigner: false,
273
- isWritable: false,
274
- });
275
- }
276
- else {
277
- this.marketLastSlotCache.delete(marketIndexNum);
278
- }
279
- }
280
- for (const position of userAccount.positions) {
281
- if (!(0, position_1.positionIsAvailable)(position)) {
282
- const marketIndexNum = position.marketIndex.toNumber();
283
- const marketAccount = this.getMarketAccount(marketIndexNum);
284
- marketAccountMap.set(marketIndexNum, {
285
- pubkey: marketAccount.pubkey,
286
- isSigner: false,
287
- // isWritable: false, // TODO
288
- isWritable: true,
289
- });
290
- oracleAccountMap.set(marketAccount.pubkey.toString(), {
291
- pubkey: marketAccount.amm.oracle,
292
- isSigner: false,
293
- isWritable: false,
294
- });
295
- }
296
- }
297
- if (params.writableMarketIndex) {
298
- const marketAccount = this.getMarketAccount(params.writableMarketIndex.toNumber());
299
- marketAccountMap.set(params.writableMarketIndex.toNumber(), {
300
- pubkey: marketAccount.pubkey,
301
- isSigner: false,
302
- isWritable: true,
303
- });
304
- oracleAccountMap.set(marketAccount.amm.oracle.toString(), {
305
- pubkey: marketAccount.amm.oracle,
306
- isSigner: false,
307
- isWritable: false,
308
- });
309
- }
310
- for (const userBankBalance of userAccount.bankBalances) {
311
- if (!userBankBalance.balance.eq(numericConstants_1.ZERO)) {
312
- const bankAccount = this.getBankAccount(userBankBalance.bankIndex);
313
- bankAccountMap.set(userBankBalance.bankIndex.toNumber(), {
314
- pubkey: bankAccount.pubkey,
315
- isSigner: false,
316
- isWritable: false,
317
- });
318
- if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
319
- oracleAccountMap.set(bankAccount.oracle.toString(), {
320
- pubkey: bankAccount.oracle,
321
- isSigner: false,
322
- isWritable: false,
323
- });
324
- }
325
- }
326
- }
327
- if (params.writableBankIndex) {
328
- const bankAccount = this.getBankAccount(params.writableBankIndex);
329
- bankAccountMap.set(params.writableBankIndex.toNumber(), {
330
- pubkey: bankAccount.pubkey,
331
- isSigner: false,
332
- isWritable: true,
333
- });
334
- if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
335
- oracleAccountMap.set(bankAccount.oracle.toString(), {
336
- pubkey: bankAccount.oracle,
337
- isSigner: false,
338
- isWritable: false,
339
- });
340
- }
341
- }
342
- return [
343
- ...oracleAccountMap.values(),
344
- ...bankAccountMap.values(),
345
- ...marketAccountMap.values(),
346
- ];
347
- }
348
- getOrder(orderId) {
349
- var _a;
350
- const orderIdBN = orderId instanceof anchor_1.BN ? orderId : new anchor_1.BN(orderId);
351
- return (_a = this.getUserAccount()) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.orderId.eq(orderIdBN));
352
- }
353
- getOrderByUserId(userOrderId) {
354
- var _a;
355
- return (_a = this.getUserAccount()) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.userOrderId === userOrderId);
356
- }
357
- async deposit(amount, bankIndex, collateralAccountPublicKey, userId, reduceOnly = false) {
358
- const depositCollateralIx = await this.getDepositInstruction(amount, bankIndex, collateralAccountPublicKey, userId, reduceOnly, true);
359
- const tx = new web3_js_1.Transaction().add(depositCollateralIx);
360
- const { txSig } = await this.txSender.send(tx);
361
- return txSig;
362
- }
363
- async getDepositInstruction(amount, bankIndex, userTokenAccount, userId, reduceOnly = false, userInitialized = true) {
364
- const userAccountPublicKey = userId
365
- ? await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, userId)
366
- : await this.getUserAccountPublicKey();
367
- let remainingAccounts = [];
368
- if (userInitialized) {
369
- remainingAccounts = this.getRemainingAccounts({
370
- writableBankIndex: bankIndex,
371
- });
372
- }
373
- else {
374
- remainingAccounts = [
375
- {
376
- pubkey: this.getBankAccount(bankIndex).pubkey,
377
- isSigner: false,
378
- isWritable: true,
379
- },
380
- ];
381
- }
382
- const bank = this.getBankAccount(bankIndex);
383
- return await this.program.instruction.deposit(bankIndex, amount, reduceOnly, {
384
- accounts: {
385
- state: await this.getStatePublicKey(),
386
- bank: bank.pubkey,
387
- bankVault: bank.vault,
388
- user: userAccountPublicKey,
389
- userTokenAccount: userTokenAccount,
390
- authority: this.wallet.publicKey,
391
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
392
- },
393
- remainingAccounts,
394
- });
395
- }
396
- /**
397
- * Creates the Clearing House User account for a user, and deposits some initial collateral
398
- * @param userId
399
- * @param name
400
- * @param amount
401
- * @param userTokenAccount
402
- * @param fromUserId
403
- * @returns
404
- */
405
- async initializeUserAccountAndDepositCollateral(amount, userTokenAccount, bankIndex = new anchor_1.BN(0), userId = 0, name = userName_1.DEFAULT_USER_NAME, fromUserId) {
406
- const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(userId, name);
407
- const depositCollateralIx = fromUserId != null
408
- ? await this.getTransferDepositIx(amount, bankIndex, fromUserId, userId)
409
- : await this.getDepositInstruction(amount, bankIndex, userTokenAccount, userId, false, false);
410
- const tx = new web3_js_1.Transaction()
411
- .add(initializeUserAccountIx)
412
- .add(depositCollateralIx);
413
- const { txSig } = await this.txSender.send(tx, []);
414
- return [txSig, userAccountPublicKey];
415
- }
416
- async initializeUserAccountForDevnet(userId = 0, name = userName_1.DEFAULT_USER_NAME, mockUSDCFaucet, amount) {
417
- const [associateTokenPublicKey, createAssociatedAccountIx, mintToIx] = await mockUSDCFaucet.createAssociatedTokenAccountAndMintToInstructions(this.wallet.publicKey, amount);
418
- const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(userId, name);
419
- const depositCollateralIx = await this.getDepositInstruction(amount, new anchor_1.BN(0), associateTokenPublicKey, userId, false, false);
420
- const tx = new web3_js_1.Transaction()
421
- .add(createAssociatedAccountIx)
422
- .add(mintToIx)
423
- .add(initializeUserAccountIx)
424
- .add(depositCollateralIx);
425
- const txSig = await this.program.provider.sendAndConfirm(tx, []);
426
- return [txSig, userAccountPublicKey];
427
- }
428
- async withdraw(amount, bankIndex, userTokenAccount, reduceOnly = false) {
429
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getWithdrawIx(amount, bankIndex, userTokenAccount, reduceOnly)), [], this.opts);
430
- return txSig;
431
- }
432
- async getWithdrawIx(amount, bankIndex, userTokenAccount, reduceOnly = false) {
433
- const userAccountPublicKey = await this.getUserAccountPublicKey();
434
- const remainingAccounts = this.getRemainingAccounts({
435
- writableBankIndex: bankIndex,
436
- });
437
- const bank = this.getBankAccount(bankIndex);
438
- return await this.program.instruction.withdraw(bankIndex, amount, reduceOnly, {
439
- accounts: {
440
- state: await this.getStatePublicKey(),
441
- bank: bank.pubkey,
442
- bankVault: bank.vault,
443
- bankVaultAuthority: bank.vaultAuthority,
444
- user: userAccountPublicKey,
445
- userTokenAccount: userTokenAccount,
446
- authority: this.wallet.publicKey,
447
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
448
- },
449
- remainingAccounts,
450
- });
451
- }
452
- async transferDeposit(amount, bankIndex, fromUserId, toUserId) {
453
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getTransferDepositIx(amount, bankIndex, fromUserId, toUserId)), [], this.opts);
454
- return txSig;
455
- }
456
- async getTransferDepositIx(amount, bankIndex, fromUserId, toUserId) {
457
- const fromUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, fromUserId);
458
- const toUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, toUserId);
459
- const remainingAccounts = this.getRemainingAccounts({
460
- writableBankIndex: bankIndex,
461
- });
462
- return await this.program.instruction.transferDeposit(bankIndex, amount, {
463
- accounts: {
464
- authority: this.wallet.publicKey,
465
- fromUser,
466
- toUser,
467
- state: await this.getStatePublicKey(),
468
- },
469
- remainingAccounts,
470
- });
471
- }
472
- async updateBankCumulativeInterest(bankIndex) {
473
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.updateBankCumulativeInterestIx(bankIndex)), [], this.opts);
474
- return txSig;
475
- }
476
- async updateBankCumulativeInterestIx(bankIndex) {
477
- const bank = this.getBankAccount(bankIndex);
478
- return await this.program.instruction.updateBankCumulativeInterest({
479
- accounts: {
480
- bank: bank.pubkey,
481
- },
482
- });
483
- }
484
- async openPosition(direction, amount, marketIndex, limitPrice) {
485
- return await this.placeAndTake({
486
- orderType: types_1.OrderType.MARKET,
487
- marketIndex,
488
- direction,
489
- baseAssetAmount: amount,
490
- price: limitPrice,
491
- });
492
- }
493
- async placeOrder(orderParams) {
494
- const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceOrderIx(orderParams)), [], this.opts);
495
- this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
496
- return txSig;
497
- }
498
- getOrderParams(optionalOrderParams) {
499
- return Object.assign({}, types_1.DefaultOrderParams, optionalOrderParams);
500
- }
501
- async getPlaceOrderIx(orderParams) {
502
- orderParams = this.getOrderParams(orderParams);
503
- const userAccountPublicKey = await this.getUserAccountPublicKey();
504
- const remainingAccounts = this.getRemainingAccounts({
505
- writableMarketIndex: orderParams.marketIndex,
506
- });
507
- return await this.program.instruction.placeOrder(orderParams, {
508
- accounts: {
509
- state: await this.getStatePublicKey(),
510
- user: userAccountPublicKey,
511
- authority: this.wallet.publicKey,
512
- },
513
- remainingAccounts,
514
- });
515
- }
516
- async updateAMMs(marketIndexes) {
517
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getUpdateAMMsIx(marketIndexes)), [], this.opts);
518
- return txSig;
519
- }
520
- async getUpdateAMMsIx(marketIndexes) {
521
- for (let i = marketIndexes.length; i < 5; i++) {
522
- marketIndexes.push(new anchor_1.BN(100));
523
- }
524
- const marketAccountInfos = [];
525
- const oracleAccountInfos = [];
526
- for (const marketIndex of marketIndexes) {
527
- if (!marketIndex.eq(new anchor_1.BN(100))) {
528
- const market = this.getMarketAccount(marketIndex);
529
- marketAccountInfos.push({
530
- pubkey: market.pubkey,
531
- isWritable: true,
532
- isSigner: false,
533
- });
534
- oracleAccountInfos.push({
535
- pubkey: market.amm.oracle,
536
- isWritable: false,
537
- isSigner: false,
538
- });
539
- }
540
- }
541
- const remainingAccounts = oracleAccountInfos.concat(marketAccountInfos);
542
- return await this.program.instruction.updateAmms(marketIndexes, {
543
- accounts: {
544
- state: await this.getStatePublicKey(),
545
- authority: this.wallet.publicKey,
546
- },
547
- remainingAccounts,
548
- });
549
- }
550
- async cancelOrder(orderId) {
551
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getCancelOrderIx(orderId)), [], this.opts);
552
- return txSig;
553
- }
554
- async getCancelOrderIx(orderId) {
555
- const userAccountPublicKey = await this.getUserAccountPublicKey();
556
- const remainingAccounts = this.getRemainingAccounts({});
557
- return await this.program.instruction.cancelOrder(orderId !== null && orderId !== void 0 ? orderId : null, {
558
- accounts: {
559
- state: await this.getStatePublicKey(),
560
- user: userAccountPublicKey,
561
- authority: this.wallet.publicKey,
562
- },
563
- remainingAccounts,
564
- });
565
- }
566
- async cancelOrderByUserId(userOrderId) {
567
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getCancelOrderByUserIdIx(userOrderId)), [], this.opts);
568
- return txSig;
569
- }
570
- async getCancelOrderByUserIdIx(userOrderId) {
571
- const userAccountPublicKey = await this.getUserAccountPublicKey();
572
- const order = this.getOrderByUserId(userOrderId);
573
- const oracle = this.getMarketAccount(order.marketIndex).amm.oracle;
574
- const remainingAccounts = this.getRemainingAccounts({});
575
- return await this.program.instruction.cancelOrderByUserId(userOrderId, {
576
- accounts: {
577
- state: await this.getStatePublicKey(),
578
- user: userAccountPublicKey,
579
- authority: this.wallet.publicKey,
580
- oracle,
581
- },
582
- remainingAccounts,
583
- });
584
- }
585
- async fillOrder(userAccountPublicKey, user, order, makerInfo) {
586
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getFillOrderIx(userAccountPublicKey, user, order, makerInfo)), [], this.opts);
587
- return txSig;
588
- }
589
- async getFillOrderIx(userAccountPublicKey, userAccount, order, makerInfo) {
590
- const fillerPublicKey = await this.getUserAccountPublicKey();
591
- const marketIndex = order.marketIndex;
592
- const marketAccount = this.getMarketAccount(marketIndex);
593
- const bankAccountInfos = [
594
- {
595
- pubkey: this.getQuoteAssetBankAccount().pubkey,
596
- isSigner: false,
597
- isWritable: true,
598
- },
599
- ];
600
- const marketAccountInfos = [
601
- {
602
- pubkey: marketAccount.pubkey,
603
- isWritable: true,
604
- isSigner: false,
605
- },
606
- ];
607
- const oracleAccountInfos = [
608
- {
609
- pubkey: marketAccount.amm.oracle,
610
- isWritable: false,
611
- isSigner: false,
612
- },
613
- ];
614
- for (const position of userAccount.positions) {
615
- if (!(0, position_1.positionIsAvailable)(position) &&
616
- !position.marketIndex.eq(order.marketIndex)) {
617
- const market = this.getMarketAccount(position.marketIndex);
618
- marketAccountInfos.push({
619
- pubkey: market.pubkey,
620
- isWritable: true,
621
- isSigner: false,
622
- });
623
- oracleAccountInfos.push({
624
- pubkey: market.amm.oracle,
625
- isWritable: false,
626
- isSigner: false,
627
- });
628
- }
629
- }
630
- const remainingAccounts = oracleAccountInfos.concat(bankAccountInfos.concat(marketAccountInfos));
631
- if (makerInfo) {
632
- remainingAccounts.push({
633
- pubkey: makerInfo.maker,
634
- isWritable: true,
635
- isSigner: false,
636
- });
637
- }
638
- const orderId = order.orderId;
639
- const makerOrderId = makerInfo ? makerInfo.order.orderId : null;
640
- return await this.program.instruction.fillOrder(orderId, makerOrderId, {
641
- accounts: {
642
- state: await this.getStatePublicKey(),
643
- filler: fillerPublicKey,
644
- user: userAccountPublicKey,
645
- authority: this.wallet.publicKey,
646
- },
647
- remainingAccounts,
648
- });
649
- }
650
- async triggerOrder(userAccountPublicKey, user, order) {
651
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getTriggerOrderIx(userAccountPublicKey, user, order)), [], this.opts);
652
- return txSig;
653
- }
654
- async getTriggerOrderIx(userAccountPublicKey, userAccount, order) {
655
- const fillerPublicKey = await this.getUserAccountPublicKey();
656
- const marketIndex = order.marketIndex;
657
- const marketAccount = this.getMarketAccount(marketIndex);
658
- const bankAccountInfos = [
659
- {
660
- pubkey: this.getQuoteAssetBankAccount().pubkey,
661
- isSigner: false,
662
- isWritable: true,
663
- },
664
- ];
665
- const marketAccountInfos = [
666
- {
667
- pubkey: marketAccount.pubkey,
668
- isWritable: true,
669
- isSigner: false,
670
- },
671
- ];
672
- const oracleAccountInfos = [
673
- {
674
- pubkey: marketAccount.amm.oracle,
675
- isWritable: false,
676
- isSigner: false,
677
- },
678
- ];
679
- for (const position of userAccount.positions) {
680
- if (!(0, position_1.positionIsAvailable)(position) &&
681
- !position.marketIndex.eq(order.marketIndex)) {
682
- const market = this.getMarketAccount(position.marketIndex);
683
- marketAccountInfos.push({
684
- pubkey: market.pubkey,
685
- isWritable: false,
686
- isSigner: false,
687
- });
688
- oracleAccountInfos.push({
689
- pubkey: market.amm.oracle,
690
- isWritable: false,
691
- isSigner: false,
692
- });
693
- }
694
- }
695
- const remainingAccounts = oracleAccountInfos.concat(bankAccountInfos.concat(marketAccountInfos));
696
- const orderId = order.orderId;
697
- return await this.program.instruction.triggerOrder(orderId, {
698
- accounts: {
699
- state: await this.getStatePublicKey(),
700
- filler: fillerPublicKey,
701
- user: userAccountPublicKey,
702
- authority: this.wallet.publicKey,
703
- },
704
- remainingAccounts,
705
- });
706
- }
707
- async placeAndTake(orderParams, makerInfo) {
708
- const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceAndTakeIx(orderParams, makerInfo)), [], this.opts);
709
- this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
710
- return txSig;
711
- }
712
- async getPlaceAndTakeIx(orderParams, makerInfo) {
713
- orderParams = this.getOrderParams(orderParams);
714
- const userAccountPublicKey = await this.getUserAccountPublicKey();
715
- const remainingAccounts = this.getRemainingAccounts({
716
- writableMarketIndex: orderParams.marketIndex,
717
- writableBankIndex: numericConstants_1.QUOTE_ASSET_BANK_INDEX,
718
- });
719
- let makerOrderId = null;
720
- if (makerInfo) {
721
- makerOrderId = makerInfo.order.orderId;
722
- remainingAccounts.push({
723
- pubkey: makerInfo.maker,
724
- isSigner: false,
725
- isWritable: true,
726
- });
727
- }
728
- return await this.program.instruction.placeAndTake(orderParams, makerOrderId, {
729
- accounts: {
730
- state: await this.getStatePublicKey(),
731
- user: userAccountPublicKey,
732
- authority: this.wallet.publicKey,
733
- },
734
- remainingAccounts,
735
- });
736
- }
737
- /**
738
- * Close an entire position. If you want to reduce a position, use the {@link openPosition} method in the opposite direction of the current position.
739
- * @param marketIndex
740
- * @returns
741
- */
742
- async closePosition(marketIndex) {
743
- const userPosition = this.getUser().getUserPosition(marketIndex);
744
- if (!userPosition) {
745
- throw Error(`No position in market ${marketIndex.toString()}`);
746
- }
747
- return await this.placeAndTake({
748
- orderType: types_1.OrderType.MARKET,
749
- marketIndex,
750
- direction: (0, position_1.findDirectionToClose)(userPosition),
751
- baseAssetAmount: userPosition.baseAssetAmount,
752
- reduceOnly: true,
753
- });
754
- }
755
- async settlePNLs(users, marketIndex) {
756
- const ixs = [];
757
- for (const { settleeUserAccountPublicKey, settleeUserAccount } of users) {
758
- ixs.push(await this.settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex));
759
- }
760
- const tx = new web3_js_1.Transaction().add(...ixs);
761
- const { txSig } = await this.txSender.send(tx, [], this.opts);
762
- return txSig;
763
- }
764
- async settlePNL(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
765
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex)), [], this.opts);
766
- return txSig;
767
- }
768
- async settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
769
- const marketAccountMap = new Map();
770
- const oracleAccountMap = new Map();
771
- const bankAccountMap = new Map();
772
- for (const position of settleeUserAccount.positions) {
773
- if (!(0, position_1.positionIsAvailable)(position)) {
774
- const market = this.getMarketAccount(position.marketIndex);
775
- marketAccountMap.set(position.marketIndex.toNumber(), {
776
- pubkey: market.pubkey,
777
- isWritable: true,
778
- isSigner: false,
779
- });
780
- oracleAccountMap.set(market.amm.oracle.toString(), {
781
- pubkey: market.amm.oracle,
782
- isWritable: false,
783
- isSigner: false,
784
- });
785
- }
786
- }
787
- for (const userBankBalance of settleeUserAccount.bankBalances) {
788
- if (!userBankBalance.balance.eq(numericConstants_1.QUOTE_ASSET_BANK_INDEX)) {
789
- const bankAccount = this.getBankAccount(userBankBalance.bankIndex);
790
- bankAccountMap.set(userBankBalance.bankIndex.toNumber(), {
791
- pubkey: bankAccount.pubkey,
792
- isSigner: false,
793
- isWritable: false,
794
- });
795
- if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
796
- oracleAccountMap.set(bankAccount.oracle.toString(), {
797
- pubkey: bankAccount.oracle,
798
- isSigner: false,
799
- isWritable: false,
800
- });
801
- }
802
- }
803
- }
804
- const marketAccount = this.getMarketAccount(marketIndex.toNumber());
805
- marketAccountMap.set(marketIndex.toNumber(), {
806
- pubkey: marketAccount.pubkey,
807
- isSigner: false,
808
- isWritable: true,
809
- });
810
- oracleAccountMap.set(marketAccount.amm.oracle.toString(), {
811
- pubkey: marketAccount.amm.oracle,
812
- isSigner: false,
813
- isWritable: false,
814
- });
815
- bankAccountMap.set(numericConstants_1.QUOTE_ASSET_BANK_INDEX.toNumber(), {
816
- pubkey: this.getBankAccount(numericConstants_1.QUOTE_ASSET_BANK_INDEX).pubkey,
817
- isSigner: false,
818
- isWritable: true,
819
- });
820
- const remainingAccounts = [
821
- ...oracleAccountMap.values(),
822
- ...bankAccountMap.values(),
823
- ...marketAccountMap.values(),
824
- ];
825
- return await this.program.instruction.settlePnl(marketIndex, {
826
- accounts: {
827
- state: await this.getStatePublicKey(),
828
- authority: this.wallet.publicKey,
829
- user: settleeUserAccountPublicKey,
830
- },
831
- remainingAccounts: remainingAccounts,
832
- });
833
- }
834
- async liquidate(liquidateeUserAccountPublicKey) {
835
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
836
- return txSig;
837
- }
838
- async getLiquidateIx(liquidateeUserAccountPublicKey) {
839
- const userAccountPublicKey = await this.getUserAccountPublicKey();
840
- const liquidateeUserAccount = (await this.program.account.user.fetch(liquidateeUserAccountPublicKey));
841
- const bankAccountInfos = [
842
- {
843
- pubkey: this.getQuoteAssetBankAccount().pubkey,
844
- isSigner: false,
845
- isWritable: true,
846
- },
847
- ];
848
- const marketAccountInfos = [];
849
- const oracleAccountInfos = [];
850
- for (const position of liquidateeUserAccount.positions) {
851
- if (!(0, position_1.positionIsAvailable)(position)) {
852
- const market = this.getMarketAccount(position.marketIndex);
853
- const marketPublicKey = await (0, pda_1.getMarketPublicKey)(this.program.programId, position.marketIndex);
854
- marketAccountInfos.push({
855
- pubkey: marketPublicKey,
856
- isWritable: true,
857
- isSigner: false,
858
- });
859
- oracleAccountInfos.push({
860
- pubkey: market.amm.oracle,
861
- isWritable: false,
862
- isSigner: false,
863
- });
864
- }
865
- }
866
- const remainingAccounts = oracleAccountInfos.concat(bankAccountInfos.concat(marketAccountInfos));
867
- const state = this.getStateAccount();
868
- const quoteAssetBankAccount = this.getQuoteAssetBankAccount();
869
- return await this.program.instruction.liquidate({
870
- accounts: {
871
- state: await this.getStatePublicKey(),
872
- authority: this.wallet.publicKey,
873
- user: liquidateeUserAccountPublicKey,
874
- liquidator: userAccountPublicKey,
875
- bankVault: quoteAssetBankAccount.vault,
876
- bankVaultAuthority: quoteAssetBankAccount.vaultAuthority,
877
- insuranceVault: state.insuranceVault,
878
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
879
- },
880
- remainingAccounts: remainingAccounts,
881
- });
882
- }
883
- async updateFundingRate(oracle, marketIndex) {
884
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getUpdateFundingRateIx(oracle, marketIndex)), [], this.opts);
885
- return txSig;
886
- }
887
- async getUpdateFundingRateIx(oracle, marketIndex) {
888
- return await this.program.instruction.updateFundingRate(marketIndex, {
889
- accounts: {
890
- state: await this.getStatePublicKey(),
891
- market: await (0, pda_1.getMarketPublicKey)(this.program.programId, marketIndex),
892
- oracle: oracle,
893
- },
894
- });
895
- }
896
- async settleFundingPayment(userAccount) {
897
- const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getSettleFundingPaymentIx(userAccount)), [], this.opts);
898
- return txSig;
899
- }
900
- async getSettleFundingPaymentIx(userAccount) {
901
- const user = (await this.program.account.user.fetch(userAccount));
902
- const userPositions = user.positions;
903
- const remainingAccounts = [];
904
- for (const position of userPositions) {
905
- if (!(0, position_1.positionIsAvailable)(position)) {
906
- const marketPublicKey = await (0, pda_1.getMarketPublicKey)(this.program.programId, position.marketIndex);
907
- remainingAccounts.push({
908
- pubkey: marketPublicKey,
909
- isWritable: false,
910
- isSigner: false,
911
- });
912
- }
913
- }
914
- return await this.program.instruction.settleFundingPayment({
915
- accounts: {
916
- state: await this.getStatePublicKey(),
917
- user: userAccount,
918
- },
919
- remainingAccounts,
920
- });
921
- }
922
- triggerEvent(eventName, data) {
923
- this.eventEmitter.emit(eventName, data);
924
- }
925
- getOracleDataForMarket(marketIndex) {
926
- const oracleKey = this.getMarketAccount(marketIndex).amm.oracle;
927
- const oracleData = this.getOraclePriceDataAndSlot(oracleKey).data;
928
- return oracleData;
929
- }
930
- }
931
- exports.ClearingHouse = ClearingHouse;