@drift-labs/sdk 0.1.29-master.1 → 0.1.30-master.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 (73) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +2 -1
  2. package/lib/accounts/bulkAccountLoader.js +44 -32
  3. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +15 -0
  4. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +50 -23
  5. package/lib/clearingHouse.d.ts +4 -2
  6. package/lib/clearingHouse.js +49 -14
  7. package/lib/constants/accounts.d.ts +15 -0
  8. package/lib/constants/accounts.js +18 -0
  9. package/lib/constants/markets.js +11 -0
  10. package/lib/factory/clearingHouse.d.ts +14 -4
  11. package/lib/factory/clearingHouse.js +23 -6
  12. package/lib/idl/clearing_house.json +53 -33
  13. package/lib/math/amm.d.ts +18 -0
  14. package/lib/math/amm.js +88 -1
  15. package/lib/oracles/pythClient.js +1 -1
  16. package/lib/orderParams.d.ts +1 -1
  17. package/lib/orderParams.js +2 -2
  18. package/lib/tx/retryTxSender.d.ts +5 -2
  19. package/lib/tx/retryTxSender.js +14 -1
  20. package/lib/util/promiseTimeout.d.ts +1 -0
  21. package/lib/util/promiseTimeout.js +14 -0
  22. package/package.json +1 -1
  23. package/src/accounts/bulkAccountLoader.ts +51 -40
  24. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +73 -30
  25. package/src/clearingHouse.ts +71 -13
  26. package/src/constants/accounts.ts +26 -0
  27. package/src/constants/markets.ts +11 -0
  28. package/src/factory/clearingHouse.ts +47 -7
  29. package/src/idl/clearing_house.json +53 -33
  30. package/src/math/amm.ts +127 -2
  31. package/src/oracles/pythClient.ts +1 -1
  32. package/src/orderParams.ts +3 -2
  33. package/src/tx/retryTxSender.ts +19 -1
  34. package/src/util/promiseTimeout.ts +14 -0
  35. package/lib/math/repeg.d.ts +0 -32
  36. package/lib/math/repeg.js +0 -178
  37. package/src/accounts/bulkUserSubscription.js +0 -56
  38. package/src/accounts/bulkUserSubscription.js.map +0 -1
  39. package/src/accounts/pollingClearingHouseAccountSubscriber.js +0 -210
  40. package/src/accounts/pollingClearingHouseAccountSubscriber.js.map +0 -1
  41. package/src/accounts/pollingOracleSubscriber.js +0 -65
  42. package/src/accounts/pollingOracleSubscriber.js.map +0 -1
  43. package/src/accounts/pollingTokenAccountSubscriber.js +0 -65
  44. package/src/accounts/pollingTokenAccountSubscriber.js.map +0 -1
  45. package/src/accounts/pollingUserAccountSubscriber.js +0 -139
  46. package/src/accounts/pollingUserAccountSubscriber.js.map +0 -1
  47. package/src/accounts/types.js +0 -11
  48. package/src/accounts/types.js.map +0 -1
  49. package/src/accounts/utils.js +0 -8
  50. package/src/accounts/utils.js.map +0 -1
  51. package/src/accounts/webSocketAccountSubscriber.js +0 -64
  52. package/src/accounts/webSocketAccountSubscriber.js.map +0 -1
  53. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +0 -212
  54. package/src/accounts/webSocketClearingHouseAccountSubscriber.js.map +0 -1
  55. package/src/accounts/webSocketUserAccountSubscriber.js +0 -78
  56. package/src/accounts/webSocketUserAccountSubscriber.js.map +0 -1
  57. package/src/constants/markets.js +0 -167
  58. package/src/constants/markets.js.map +0 -1
  59. package/src/constants/numericConstants.js +0 -22
  60. package/src/constants/numericConstants.js.map +0 -1
  61. package/src/factory/clearingHouse.js +0 -65
  62. package/src/factory/clearingHouse.js.map +0 -1
  63. package/src/factory/clearingHouseUser.js +0 -35
  64. package/src/factory/clearingHouseUser.js.map +0 -1
  65. package/src/factory/oracleClient.js +0 -17
  66. package/src/factory/oracleClient.js.map +0 -1
  67. package/src/math/amm.js +0 -285
  68. package/src/math/amm.js.map +0 -1
  69. package/src/math/repeg.ts +0 -253
  70. package/src/oracles/pythClient.js +0 -39
  71. package/src/oracles/pythClient.js.map +0 -1
  72. package/src/tx/retryTxSender.js +0 -137
  73. package/src/tx/retryTxSender.js.map +0 -1
@@ -16,7 +16,7 @@ export declare class BulkAccountLoader {
16
16
  loadPromise?: Promise<void>;
17
17
  loadPromiseResolver: () => void;
18
18
  loggingEnabled: boolean;
19
- lastUpdate: number;
19
+ lastTimeLoadingPromiseCleared: number;
20
20
  constructor(connection: Connection, commitment: Commitment, pollingFrequency: number);
21
21
  addAccount(publicKey: PublicKey, callback: (buffer: Buffer) => void): string;
22
22
  removeAccount(publicKey: PublicKey, callbackId: string): void;
@@ -29,5 +29,6 @@ export declare class BulkAccountLoader {
29
29
  getAccountData(publicKey: PublicKey): Buffer | undefined;
30
30
  startPolling(): void;
31
31
  stopPolling(): void;
32
+ log(msg: string, force?: boolean): void;
32
33
  }
33
34
  export {};
@@ -10,18 +10,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.BulkAccountLoader = void 0;
13
- const web3_js_1 = require("@solana/web3.js");
14
13
  const uuid_1 = require("uuid");
14
+ const promiseTimeout_1 = require("../util/promiseTimeout");
15
15
  const GET_MULTIPLE_ACCOUNTS_CHUNK_SIZE = 99;
16
16
  const oneMinute = 60 * 1000;
17
- const fiveMinutes = 5 * 60 * 1000;
18
17
  class BulkAccountLoader {
19
18
  constructor(connection, commitment, pollingFrequency) {
20
19
  this.accountsToLoad = new Map();
21
20
  this.accountData = new Map();
22
21
  this.errorCallbacks = new Map();
23
22
  this.loggingEnabled = false;
24
- this.lastUpdate = Date.now();
23
+ this.lastTimeLoadingPromiseCleared = Date.now();
25
24
  this.connection = connection;
26
25
  this.commitment = commitment;
27
26
  this.pollingFrequency = pollingFrequency;
@@ -29,11 +28,14 @@ class BulkAccountLoader {
29
28
  addAccount(publicKey, callback) {
30
29
  const existingSize = this.accountsToLoad.size;
31
30
  const callbackId = (0, uuid_1.v4)();
31
+ this.log(`Adding account ${publicKey.toString()} callback id ${callbackId}`);
32
32
  const existingAccountToLoad = this.accountsToLoad.get(publicKey.toString());
33
33
  if (existingAccountToLoad) {
34
+ this.log(`account already exists`);
34
35
  existingAccountToLoad.callbacks.set(callbackId, callback);
35
36
  }
36
37
  else {
38
+ this.log(`account doesn't already exist. creating new callback map`);
37
39
  const callbacks = new Map();
38
40
  callbacks.set(callbackId, callback);
39
41
  const newAccountToLoad = {
@@ -50,6 +52,7 @@ class BulkAccountLoader {
50
52
  return callbackId;
51
53
  }
52
54
  removeAccount(publicKey, callbackId) {
55
+ this.log(`Removing account ${publicKey.toString()} callback id ${callbackId}`);
53
56
  const existingAccountToLoad = this.accountsToLoad.get(publicKey.toString());
54
57
  if (existingAccountToLoad) {
55
58
  existingAccountToLoad.callbacks.delete(callbackId);
@@ -78,13 +81,24 @@ class BulkAccountLoader {
78
81
  load() {
79
82
  return __awaiter(this, void 0, void 0, function* () {
80
83
  if (this.loadPromise) {
81
- return this.loadPromise;
84
+ const now = Date.now();
85
+ if (now - this.lastTimeLoadingPromiseCleared > oneMinute) {
86
+ this.log(`Load promise hasnt been clearing for one minute. Clearing.`);
87
+ this.loadPromise = undefined;
88
+ }
89
+ else {
90
+ this.log(`Load promise exists. Returning early`);
91
+ return this.loadPromise;
92
+ }
82
93
  }
83
94
  this.loadPromise = new Promise((resolver) => {
84
95
  this.loadPromiseResolver = resolver;
85
96
  });
97
+ this.lastTimeLoadingPromiseCleared = Date.now();
98
+ this.log(`Loading`);
86
99
  try {
87
100
  const chunks = this.chunks(Array.from(this.accountsToLoad.values()), GET_MULTIPLE_ACCOUNTS_CHUNK_SIZE);
101
+ this.log(`${chunks.length} chunks`);
88
102
  yield Promise.all(chunks.map((chunk) => {
89
103
  return this.loadChunk(chunk);
90
104
  }));
@@ -95,25 +109,19 @@ class BulkAccountLoader {
95
109
  for (const [_, callback] of this.errorCallbacks) {
96
110
  callback(e);
97
111
  }
112
+ this.log('finished error callbacks');
98
113
  }
99
114
  finally {
115
+ this.log(`resetting load promise`);
100
116
  this.loadPromiseResolver();
101
117
  this.loadPromise = undefined;
102
- const now = Date.now();
103
- if (now - this.lastUpdate > fiveMinutes) {
104
- if (this.loggingEnabled) {
105
- console.log("Haven't seen updated account in five minutes. Bulk account loader creating new Connection Object");
106
- }
107
- this.connection = new web3_js_1.Connection(
108
- // @ts-ignore
109
- this.connection._rpcEndpoint, this.connection.commitment);
110
- }
111
118
  }
112
119
  });
113
120
  }
114
121
  loadChunk(accountsToLoad) {
115
122
  return __awaiter(this, void 0, void 0, function* () {
116
123
  if (accountsToLoad.length === 0) {
124
+ this.log(`no accounts in chunk`);
117
125
  return;
118
126
  }
119
127
  const args = [
@@ -122,11 +130,13 @@ class BulkAccountLoader {
122
130
  }),
123
131
  { commitment: this.commitment },
124
132
  ];
133
+ const rpcResponse = yield (0, promiseTimeout_1.promiseTimeout)(
125
134
  // @ts-ignore
126
- const rpcResponse = yield this.connection._rpcRequest('getMultipleAccounts', args);
127
- const oneMinuteSinceLastUpdate = Date.now() - this.lastUpdate > oneMinute;
128
- if (this.loggingEnabled && oneMinuteSinceLastUpdate) {
129
- console.log('rpcResponse', JSON.stringify(rpcResponse));
135
+ this.connection._rpcRequest('getMultipleAccounts', args), 10 * 1000 // 30 second timeout
136
+ );
137
+ if (rpcResponse === null) {
138
+ this.log('request to rpc timed out', true);
139
+ return;
130
140
  }
131
141
  const newSlot = rpcResponse.result.context.slot;
132
142
  for (const i in accountsToLoad) {
@@ -139,42 +149,43 @@ class BulkAccountLoader {
139
149
  const dataType = rpcResponse.result.value[i].data[1];
140
150
  newBuffer = Buffer.from(raw, dataType);
141
151
  }
142
- if (this.loggingEnabled && oneMinuteSinceLastUpdate) {
143
- console.log('oldRPCResponse', oldRPCResponse);
144
- }
145
152
  if (!oldRPCResponse) {
153
+ this.log('No old rpc response, updating account data');
146
154
  this.accountData.set(key, {
147
155
  slot: newSlot,
148
156
  buffer: newBuffer,
149
157
  });
150
158
  this.handleAccountCallbacks(accountToLoad, newBuffer);
151
- this.lastUpdate = Date.now();
152
159
  continue;
153
160
  }
154
161
  if (newSlot <= oldRPCResponse.slot) {
162
+ this.log(`new slot ${newSlot} old slot ${oldRPCResponse.slot}`);
155
163
  continue;
156
164
  }
157
165
  const oldBuffer = oldRPCResponse.buffer;
158
166
  if (newBuffer && (!oldBuffer || !newBuffer.equals(oldBuffer))) {
167
+ this.log('new buffer, updating account data');
159
168
  this.accountData.set(key, {
160
169
  slot: newSlot,
161
170
  buffer: newBuffer,
162
171
  });
163
172
  this.handleAccountCallbacks(accountToLoad, newBuffer);
164
- this.lastUpdate = Date.now();
165
173
  }
166
- else if (this.loggingEnabled) {
167
- console.log('unable to update account for newest slot');
168
- console.log('oldBuffer', oldBuffer);
169
- console.log('newBuffer', newBuffer);
174
+ else {
175
+ this.log('unable to update account for newest slot');
176
+ this.log('oldBuffer ' + oldBuffer);
177
+ this.log('newBuffer ' + newBuffer);
178
+ this.log('buffers equal ' + newBuffer.equals(oldBuffer));
170
179
  }
171
180
  }
172
181
  });
173
182
  }
174
183
  handleAccountCallbacks(accountToLoad, buffer) {
184
+ this.log('handling account callbacks');
175
185
  for (const [_, callback] of accountToLoad.callbacks) {
176
186
  callback(buffer);
177
187
  }
188
+ this.log('finished account callbacks');
178
189
  }
179
190
  getAccountData(publicKey) {
180
191
  const accountData = this.accountData.get(publicKey.toString());
@@ -184,18 +195,19 @@ class BulkAccountLoader {
184
195
  if (this.intervalId) {
185
196
  return;
186
197
  }
187
- if (this.loggingEnabled) {
188
- console.log(`startPolling`);
189
- }
198
+ this.log('startPolling');
190
199
  this.intervalId = setInterval(this.load.bind(this), this.pollingFrequency);
191
200
  }
192
201
  stopPolling() {
193
202
  if (this.intervalId) {
194
203
  clearInterval(this.intervalId);
195
204
  this.intervalId = undefined;
196
- if (this.loggingEnabled) {
197
- console.log(`stopPolling`);
198
- }
205
+ this.log('stopPolling');
206
+ }
207
+ }
208
+ log(msg, force = false) {
209
+ if (this.loggingEnabled || force) {
210
+ console.log(msg);
199
211
  }
200
212
  }
201
213
  }
@@ -6,6 +6,7 @@ import { EventEmitter } from 'events';
6
6
  import { DepositHistoryAccount, ExtendedCurveHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, LiquidationHistoryAccount, MarketsAccount, OrderHistoryAccount, OrderStateAccount, StateAccount, TradeHistoryAccount } from '../types';
7
7
  import { BulkAccountLoader } from './bulkAccountLoader';
8
8
  import { ClearingHouseConfigType } from '../factory/clearingHouse';
9
+ import { PublicKey } from '@solana/web3.js';
9
10
  export declare class PollingClearingHouseAccountSubscriber implements ClearingHouseAccountSubscriber {
10
11
  isSubscribed: boolean;
11
12
  program: Program;
@@ -31,6 +32,7 @@ export declare class PollingClearingHouseAccountSubscriber implements ClearingHo
31
32
  constructor(program: Program, accountLoader: BulkAccountLoader);
32
33
  subscribe(optionalSubscriptions?: ClearingHouseAccountTypes[]): Promise<boolean>;
33
34
  updateAccountsToPoll(): Promise<void>;
35
+ getClearingHouseAccounts(): Promise<ClearingHouseAccounts>;
34
36
  addToAccountLoader(): Promise<void>;
35
37
  fetch(): Promise<void>;
36
38
  unsubscribe(): Promise<void>;
@@ -47,3 +49,16 @@ export declare class PollingClearingHouseAccountSubscriber implements ClearingHo
47
49
  getLiquidationHistoryAccount(): LiquidationHistoryAccount;
48
50
  getOrderHistoryAccount(): OrderHistoryAccount;
49
51
  }
52
+ declare type ClearingHouseAccounts = {
53
+ state: PublicKey;
54
+ markets: PublicKey;
55
+ orderState: PublicKey;
56
+ tradeHistory?: PublicKey;
57
+ depositHistory?: PublicKey;
58
+ fundingPaymentHistory?: PublicKey;
59
+ fundingRateHistory?: PublicKey;
60
+ extendedCurveHistory?: PublicKey;
61
+ liquidationHistory?: PublicKey;
62
+ orderHistory?: PublicKey;
63
+ };
64
+ export {};
@@ -14,6 +14,7 @@ const types_1 = require("./types");
14
14
  const events_1 = require("events");
15
15
  const addresses_1 = require("../addresses");
16
16
  const utils_1 = require("./utils");
17
+ const accounts_1 = require("../constants/accounts");
17
18
  class PollingClearingHouseAccountSubscriber {
18
19
  constructor(program, accountLoader) {
19
20
  this.accountsToPoll = new Map();
@@ -54,75 +55,101 @@ class PollingClearingHouseAccountSubscriber {
54
55
  if (this.accountsToPoll.size > 0) {
55
56
  return;
56
57
  }
57
- const statePublicKey = yield (0, addresses_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
58
- const state = (yield this.program.account.state.fetch(statePublicKey));
59
- this.accountsToPoll.set(statePublicKey.toString(), {
58
+ const accounts = yield this.getClearingHouseAccounts();
59
+ this.accountsToPoll.set(accounts.state.toString(), {
60
60
  key: 'state',
61
- publicKey: statePublicKey,
61
+ publicKey: accounts.state,
62
62
  eventType: 'stateAccountUpdate',
63
63
  });
64
- this.accountsToPoll.set(state.markets.toString(), {
64
+ this.accountsToPoll.set(accounts.markets.toString(), {
65
65
  key: 'markets',
66
- publicKey: state.markets,
66
+ publicKey: accounts.markets,
67
67
  eventType: 'marketsAccountUpdate',
68
68
  });
69
- this.accountsToPoll.set(state.orderState.toString(), {
69
+ this.accountsToPoll.set(accounts.orderState.toString(), {
70
70
  key: 'orderState',
71
- publicKey: state.orderState,
71
+ publicKey: accounts.orderState,
72
72
  eventType: 'orderStateAccountUpdate',
73
73
  });
74
74
  if ((_a = this.optionalExtraSubscriptions) === null || _a === void 0 ? void 0 : _a.includes('tradeHistoryAccount')) {
75
- this.accountsToPoll.set(state.tradeHistory.toString(), {
75
+ this.accountsToPoll.set(accounts.tradeHistory.toString(), {
76
76
  key: 'tradeHistory',
77
- publicKey: state.tradeHistory,
77
+ publicKey: accounts.tradeHistory,
78
78
  eventType: 'tradeHistoryAccountUpdate',
79
79
  });
80
80
  }
81
81
  if ((_b = this.optionalExtraSubscriptions) === null || _b === void 0 ? void 0 : _b.includes('depositHistoryAccount')) {
82
- this.accountsToPoll.set(state.depositHistory.toString(), {
82
+ this.accountsToPoll.set(accounts.depositHistory.toString(), {
83
83
  key: 'depositHistory',
84
- publicKey: state.depositHistory,
84
+ publicKey: accounts.depositHistory,
85
85
  eventType: 'depositHistoryAccountUpdate',
86
86
  });
87
87
  }
88
88
  if ((_c = this.optionalExtraSubscriptions) === null || _c === void 0 ? void 0 : _c.includes('fundingPaymentHistoryAccount')) {
89
- this.accountsToPoll.set(state.fundingPaymentHistory.toString(), {
89
+ this.accountsToPoll.set(accounts.fundingPaymentHistory.toString(), {
90
90
  key: 'fundingPaymentHistory',
91
- publicKey: state.fundingPaymentHistory,
91
+ publicKey: accounts.fundingPaymentHistory,
92
92
  eventType: 'fundingPaymentHistoryAccountUpdate',
93
93
  });
94
94
  }
95
95
  if ((_d = this.optionalExtraSubscriptions) === null || _d === void 0 ? void 0 : _d.includes('fundingRateHistoryAccount')) {
96
- this.accountsToPoll.set(state.fundingRateHistory.toString(), {
96
+ this.accountsToPoll.set(accounts.fundingRateHistory.toString(), {
97
97
  key: 'fundingRateHistory',
98
- publicKey: state.fundingRateHistory,
98
+ publicKey: accounts.fundingRateHistory,
99
99
  eventType: 'fundingRateHistoryAccountUpdate',
100
100
  });
101
101
  }
102
102
  if ((_e = this.optionalExtraSubscriptions) === null || _e === void 0 ? void 0 : _e.includes('curveHistoryAccount')) {
103
- this.accountsToPoll.set(state.extendedCurveHistory.toString(), {
103
+ this.accountsToPoll.set(accounts.extendedCurveHistory.toString(), {
104
104
  key: 'extendedCurveHistory',
105
- publicKey: state.extendedCurveHistory,
105
+ publicKey: accounts.extendedCurveHistory,
106
106
  eventType: 'curveHistoryAccountUpdate',
107
107
  });
108
108
  }
109
109
  if ((_f = this.optionalExtraSubscriptions) === null || _f === void 0 ? void 0 : _f.includes('liquidationHistoryAccount')) {
110
- this.accountsToPoll.set(state.liquidationHistory.toString(), {
110
+ this.accountsToPoll.set(accounts.liquidationHistory.toString(), {
111
111
  key: 'liquidationHistory',
112
- publicKey: state.liquidationHistory,
112
+ publicKey: accounts.liquidationHistory,
113
113
  eventType: 'liquidationHistoryAccountUpdate',
114
114
  });
115
115
  }
116
116
  if ((_g = this.optionalExtraSubscriptions) === null || _g === void 0 ? void 0 : _g.includes('orderHistoryAccount')) {
117
- const orderState = (yield this.program.account.orderState.fetch(state.orderState));
118
- this.accountsToPoll.set(orderState.orderHistory.toString(), {
117
+ this.accountsToPoll.set(accounts.orderHistory.toString(), {
119
118
  key: 'orderHistory',
120
- publicKey: orderState.orderHistory,
119
+ publicKey: accounts.orderHistory,
121
120
  eventType: 'orderHistoryAccountUpdate',
122
121
  });
123
122
  }
124
123
  });
125
124
  }
125
+ getClearingHouseAccounts() {
126
+ var _a;
127
+ return __awaiter(this, void 0, void 0, function* () {
128
+ // Skip extra calls to rpc if we already know all the accounts
129
+ if (accounts_1.CLEARING_HOUSE_STATE_ACCOUNTS[this.program.programId.toString()]) {
130
+ return accounts_1.CLEARING_HOUSE_STATE_ACCOUNTS[this.program.programId.toString()];
131
+ }
132
+ const statePublicKey = yield (0, addresses_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
133
+ const state = (yield this.program.account.state.fetch(statePublicKey));
134
+ const accounts = {
135
+ state: statePublicKey,
136
+ markets: state.markets,
137
+ orderState: state.orderState,
138
+ tradeHistory: state.tradeHistory,
139
+ depositHistory: state.depositHistory,
140
+ fundingPaymentHistory: state.fundingPaymentHistory,
141
+ fundingRateHistory: state.fundingRateHistory,
142
+ extendedCurveHistory: state.extendedCurveHistory,
143
+ liquidationHistory: state.liquidationHistory,
144
+ orderHistory: undefined,
145
+ };
146
+ if ((_a = this.optionalExtraSubscriptions) === null || _a === void 0 ? void 0 : _a.includes('orderHistoryAccount')) {
147
+ const orderState = (yield this.program.account.orderState.fetch(state.orderState));
148
+ accounts.orderHistory = orderState.orderHistory;
149
+ }
150
+ return accounts;
151
+ });
152
+ }
126
153
  addToAccountLoader() {
127
154
  return __awaiter(this, void 0, void 0, function* () {
128
155
  for (const [_, accountToPoll] of this.accountsToPoll) {
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="bn.js" />
3
3
  import { BN, Program, Provider } from '@project-serum/anchor';
4
- import { MarketsAccount, StateAccount, DepositHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, IWallet, LiquidationHistoryAccount, PositionDirection, TradeHistoryAccount, UserAccount, Market, OrderHistoryAccount, OrderStateAccount, OrderParams, Order, ExtendedCurveHistoryAccount } from './types';
4
+ import { MarketsAccount, StateAccount, DepositHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, IWallet, LiquidationHistoryAccount, PositionDirection, TradeHistoryAccount, UserAccount, Market, OrderHistoryAccount, OrderStateAccount, OrderParams, Order, ExtendedCurveHistoryAccount, UserPositionsAccount } from './types';
5
5
  import { Connection, PublicKey, TransactionSignature, Keypair, ConfirmOptions, TransactionInstruction } from '@solana/web3.js';
6
6
  import { MockUSDCFaucet } from './mockUSDCFaucet';
7
7
  import { EventEmitter } from 'events';
@@ -113,7 +113,6 @@ export declare class ClearingHouse {
113
113
  */
114
114
  initializeUserAccountAndDepositCollateral(amount: BN, collateralAccountPublicKey: PublicKey): Promise<[TransactionSignature, PublicKey]>;
115
115
  initializeUserAccountForDevnet(mockUSDCFaucet: MockUSDCFaucet, amount: BN): Promise<[TransactionSignature, PublicKey]>;
116
- deleteUser(): Promise<TransactionSignature>;
117
116
  withdrawCollateral(amount: BN, collateralAccountPublicKey: PublicKey): Promise<TransactionSignature>;
118
117
  getWithdrawCollateralIx(amount: BN, collateralAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
119
118
  openPosition(direction: PositionDirection, amount: BN, marketIndex: BN, limitPrice?: BN, discountToken?: PublicKey, referrer?: PublicKey): Promise<TransactionSignature>;
@@ -127,6 +126,8 @@ export declare class ClearingHouse {
127
126
  getCancelOrderIx(orderId: BN, oracle?: PublicKey): Promise<TransactionInstruction>;
128
127
  cancelOrderByUserId(userOrderId: number, oracle?: PublicKey): Promise<TransactionSignature>;
129
128
  getCancelOrderByUserIdIx(userOrderId: number, oracle?: PublicKey): Promise<TransactionInstruction>;
129
+ cancelAllOrders(oracles?: PublicKey[]): Promise<TransactionSignature>;
130
+ getCancelAllOrdersIx(oracles: PublicKey[]): Promise<TransactionInstruction>;
130
131
  fillOrder(userAccountPublicKey: PublicKey, userOrdersAccountPublicKey: PublicKey, order: Order): Promise<TransactionSignature>;
131
132
  getFillOrderIx(userAccountPublicKey: PublicKey, userOrdersAccountPublicKey: PublicKey, order: Order): Promise<TransactionInstruction>;
132
133
  initializeUserOrdersThenPlaceAndFillOrder(orderParams: OrderParams, discountToken?: PublicKey, referrer?: PublicKey): Promise<TransactionSignature>;
@@ -141,6 +142,7 @@ export declare class ClearingHouse {
141
142
  */
142
143
  closePosition(marketIndex: BN, discountToken?: PublicKey, referrer?: PublicKey): Promise<TransactionSignature>;
143
144
  getClosePositionIx(marketIndex: BN, discountToken?: PublicKey, referrer?: PublicKey): Promise<TransactionInstruction>;
145
+ closeAllPositions(userPositionsAccount: UserPositionsAccount, discountToken?: PublicKey, referrer?: PublicKey): Promise<TransactionSignature>;
144
146
  liquidate(liquidateeUserAccountPublicKey: PublicKey): Promise<TransactionSignature>;
145
147
  getLiquidateIx(liquidateeUserAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
146
148
  updateFundingRate(oracle: PublicKey, marketIndex: BN): Promise<TransactionSignature>;
@@ -371,20 +371,6 @@ class ClearingHouse {
371
371
  return [txSig, userAccountPublicKey];
372
372
  });
373
373
  }
374
- deleteUser() {
375
- return __awaiter(this, void 0, void 0, function* () {
376
- const userAccountPublicKey = yield this.getUserAccountPublicKey();
377
- const user = yield this.program.account.user.fetch(userAccountPublicKey);
378
- const deleteUserTx = yield this.program.transaction.deleteUser({
379
- accounts: {
380
- user: userAccountPublicKey,
381
- userPositions: user.positions,
382
- authority: this.wallet.publicKey,
383
- },
384
- });
385
- return this.txSender.send(deleteUserTx, [], this.opts);
386
- });
387
- }
388
374
  withdrawCollateral(amount, collateralAccountPublicKey) {
389
375
  return __awaiter(this, void 0, void 0, function* () {
390
376
  return this.txSender.send((0, utils_1.wrapInTx)(yield this.getWithdrawCollateralIx(amount, collateralAccountPublicKey)), [], this.opts);
@@ -634,6 +620,42 @@ class ClearingHouse {
634
620
  });
635
621
  });
636
622
  }
623
+ cancelAllOrders(oracles) {
624
+ return __awaiter(this, void 0, void 0, function* () {
625
+ return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getCancelAllOrdersIx(oracles)), [], this.opts);
626
+ });
627
+ }
628
+ getCancelAllOrdersIx(oracles) {
629
+ return __awaiter(this, void 0, void 0, function* () {
630
+ const userAccountPublicKey = yield this.getUserAccountPublicKey();
631
+ const userAccount = yield this.getUserAccount();
632
+ const state = this.getStateAccount();
633
+ const orderState = this.getOrderStateAccount();
634
+ const remainingAccounts = [];
635
+ for (const oracle of oracles) {
636
+ remainingAccounts.push({
637
+ pubkey: oracle,
638
+ isWritable: false,
639
+ isSigner: false,
640
+ });
641
+ }
642
+ return yield this.program.instruction.cancelAllOrders({
643
+ accounts: {
644
+ state: yield this.getStatePublicKey(),
645
+ user: userAccountPublicKey,
646
+ authority: this.wallet.publicKey,
647
+ markets: state.markets,
648
+ userOrders: yield this.getUserOrdersAccountPublicKey(),
649
+ userPositions: userAccount.positions,
650
+ fundingPaymentHistory: state.fundingPaymentHistory,
651
+ fundingRateHistory: state.fundingRateHistory,
652
+ orderState: yield this.getOrderStatePublicKey(),
653
+ orderHistory: orderState.orderHistory,
654
+ },
655
+ remainingAccounts,
656
+ });
657
+ });
658
+ }
637
659
  fillOrder(userAccountPublicKey, userOrdersAccountPublicKey, order) {
638
660
  return __awaiter(this, void 0, void 0, function* () {
639
661
  return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getFillOrderIx(userAccountPublicKey, userOrdersAccountPublicKey, order)), [], this.opts);
@@ -801,6 +823,19 @@ class ClearingHouse {
801
823
  });
802
824
  });
803
825
  }
826
+ closeAllPositions(userPositionsAccount, discountToken, referrer) {
827
+ return __awaiter(this, void 0, void 0, function* () {
828
+ const ixs = [];
829
+ for (const userPosition of userPositionsAccount.positions) {
830
+ if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
831
+ continue;
832
+ }
833
+ ixs.push(yield this.getClosePositionIx(userPosition.marketIndex, discountToken, referrer));
834
+ }
835
+ const tx = new web3_js_1.Transaction().add(...ixs);
836
+ return this.txSender.send(tx, [], this.opts);
837
+ });
838
+ }
804
839
  liquidate(liquidateeUserAccountPublicKey) {
805
840
  return __awaiter(this, void 0, void 0, function* () {
806
841
  return this.txSender.send((0, utils_1.wrapInTx)(yield this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
@@ -0,0 +1,15 @@
1
+ import { PublicKey } from '@solana/web3.js';
2
+ export declare const CLEARING_HOUSE_STATE_ACCOUNTS: {
3
+ dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN: {
4
+ state: PublicKey;
5
+ markets: PublicKey;
6
+ orderState: PublicKey;
7
+ tradeHistory: PublicKey;
8
+ depositHistory: PublicKey;
9
+ fundingPaymentHistory: PublicKey;
10
+ fundingRateHistory: PublicKey;
11
+ extendedCurveHistory: PublicKey;
12
+ liquidationHistory: PublicKey;
13
+ orderHistory: PublicKey;
14
+ };
15
+ };
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CLEARING_HOUSE_STATE_ACCOUNTS = void 0;
4
+ const web3_js_1 = require("@solana/web3.js");
5
+ exports.CLEARING_HOUSE_STATE_ACCOUNTS = {
6
+ dammHkt7jmytvbS3nHTxQNEcP59aE57nxwV21YdqEDN: {
7
+ state: new web3_js_1.PublicKey('FExhvPycCCwYnZGeDsVtLhpEQ3yEkVY2k1HuPyfLj91L'),
8
+ markets: new web3_js_1.PublicKey('773hq3SbGPKVj93TXi5qV5CREuhxobywfALjS3XVHhLH'),
9
+ orderState: new web3_js_1.PublicKey('4cC34bWwTPGncBaX2S6v5mH3Lj4Nb3byPMrxQSDcY985'),
10
+ tradeHistory: new web3_js_1.PublicKey('FCuCXEoQppoaCYdttA7rK3HNQfYkTNEGpwuBESzYcENp'),
11
+ depositHistory: new web3_js_1.PublicKey('C7rF2Qy2rnDGQLRijBRRArJyaeuQcFi81BXDrUCQ45ya'),
12
+ fundingPaymentHistory: new web3_js_1.PublicKey('895iPhzwT2tBufLnRpYtBG3gif1HDDUfpH2AqbS5joo4'),
13
+ fundingRateHistory: new web3_js_1.PublicKey('BWiJLMbmrwfqHVpcPJa8715XamNyNYamDDKQVQMnduEC'),
14
+ extendedCurveHistory: new web3_js_1.PublicKey('7vBbqvMdtZLQdTVdzt5y63pZdAFE5W42kP3avngSJKCk'),
15
+ liquidationHistory: new web3_js_1.PublicKey('CSFaaf8yVoTx6NcXUKtNPYAewv76CH2jATqSVRBvUWKM'),
16
+ orderHistory: new web3_js_1.PublicKey('DZ7XfUqyHoRKnJLRApxmJ943xHJ7NDBUTqpbooviEtbU'),
17
+ },
18
+ };
@@ -177,6 +177,17 @@ exports.Markets = [
177
177
  launchTs: 1648607439000,
178
178
  oracleSource: __1.OracleSource.PYTH,
179
179
  },
180
+ {
181
+ fullName: 'Near',
182
+ category: ['L1', 'Infra'],
183
+ symbol: 'NEAR-PERP',
184
+ baseAssetSymbol: 'NEAR',
185
+ marketIndex: new __1.BN(16),
186
+ devnetPublicKey: '3gnSbT7bhoTdGkFVZc1dW1PvjreWzpUNUD5ppXwv1N59',
187
+ mainnetPublicKey: 'ECSFWQ1bnnpqPVvoy9237t2wddZAaHisW88mYxuEHKWf',
188
+ launchTs: 1649105516000,
189
+ oracleSource: __1.OracleSource.PYTH,
190
+ },
180
191
  // {
181
192
  // symbol: 'mSOL-PERP',
182
193
  // baseAssetSymbol: 'mSOL',
@@ -1,7 +1,6 @@
1
1
  import { ConfirmOptions, Connection, PublicKey } from '@solana/web3.js';
2
2
  import { IWallet } from '../types';
3
3
  import { BulkAccountLoader } from '../accounts/bulkAccountLoader';
4
- import { TxSender } from '../tx/types';
5
4
  import { ClearingHouse } from '../clearingHouse';
6
5
  import { Admin } from '../admin';
7
6
  export declare type ClearingHouseConfigType = 'websocket' | 'polling' | 'custom';
@@ -11,15 +10,26 @@ declare type BaseClearingHouseConfig = {
11
10
  wallet: IWallet;
12
11
  programID: PublicKey;
13
12
  opts?: ConfirmOptions;
14
- txSender?: TxSender;
13
+ txSenderConfig?: TxSenderConfig;
15
14
  };
16
15
  declare type WebSocketClearingHouseConfiguration = BaseClearingHouseConfig;
17
16
  declare type PollingClearingHouseConfiguration = BaseClearingHouseConfig & {
18
17
  accountLoader: BulkAccountLoader;
19
18
  };
20
19
  declare type ClearingHouseConfig = PollingClearingHouseConfiguration | WebSocketClearingHouseConfiguration;
21
- export declare function getWebSocketClearingHouseConfig(connection: Connection, wallet: IWallet, programID: PublicKey, opts?: ConfirmOptions, txSender?: TxSender): WebSocketClearingHouseConfiguration;
22
- export declare function getPollingClearingHouseConfig(connection: Connection, wallet: IWallet, programID: PublicKey, accountLoader: BulkAccountLoader, opts?: ConfirmOptions, txSender?: TxSender): PollingClearingHouseConfiguration;
20
+ export declare type TxSenderType = 'default' | 'retry';
21
+ declare type BaseTxSenderConfig = {
22
+ type: TxSenderType;
23
+ };
24
+ declare type DefaultTxSenderConfig = BaseTxSenderConfig;
25
+ declare type RetryTxSenderConfig = BaseTxSenderConfig & {
26
+ timeout?: number;
27
+ retrySleep?: number;
28
+ additionalConnections?: Connection[];
29
+ };
30
+ declare type TxSenderConfig = DefaultTxSenderConfig | RetryTxSenderConfig;
31
+ export declare function getWebSocketClearingHouseConfig(connection: Connection, wallet: IWallet, programID: PublicKey, opts?: ConfirmOptions, txSenderConfig?: TxSenderConfig): WebSocketClearingHouseConfiguration;
32
+ export declare function getPollingClearingHouseConfig(connection: Connection, wallet: IWallet, programID: PublicKey, accountLoader: BulkAccountLoader, opts?: ConfirmOptions, txSenderConfig?: TxSenderConfig): PollingClearingHouseConfiguration;
23
33
  export declare function getClearingHouse(config: ClearingHouseConfig): ClearingHouse;
24
34
  export declare function getAdmin(config: ClearingHouseConfig): Admin;
25
35
  export {};