@drift-labs/sdk 0.1.36-master.5 → 0.2.0-master.0

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 (197) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +7 -6
  2. package/lib/accounts/bulkAccountLoader.js +83 -93
  3. package/lib/accounts/bulkUserSubscription.js +13 -57
  4. package/lib/accounts/fetch.d.ts +4 -0
  5. package/lib/accounts/fetch.js +18 -0
  6. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +34 -38
  7. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +224 -224
  8. package/lib/accounts/pollingOracleSubscriber.d.ts +3 -3
  9. package/lib/accounts/pollingOracleSubscriber.js +37 -49
  10. package/lib/accounts/pollingTokenAccountSubscriber.d.ts +3 -3
  11. package/lib/accounts/pollingTokenAccountSubscriber.js +35 -50
  12. package/lib/accounts/pollingUserAccountSubscriber.d.ts +7 -13
  13. package/lib/accounts/pollingUserAccountSubscriber.js +71 -134
  14. package/lib/accounts/types.d.ts +34 -41
  15. package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -4
  16. package/lib/accounts/webSocketAccountSubscriber.js +39 -35
  17. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +33 -28
  18. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +153 -185
  19. package/lib/accounts/webSocketUserAccountSubscriber.d.ts +5 -11
  20. package/lib/accounts/webSocketUserAccountSubscriber.js +22 -67
  21. package/lib/addresses/marketAddresses.d.ts +4 -0
  22. package/lib/addresses/marketAddresses.js +15 -0
  23. package/lib/addresses/pda.d.ts +12 -0
  24. package/lib/addresses/pda.js +83 -0
  25. package/lib/admin.d.ts +8 -12
  26. package/lib/admin.js +366 -490
  27. package/lib/clearingHouse.d.ts +84 -103
  28. package/lib/clearingHouse.js +779 -810
  29. package/lib/clearingHouseConfig.d.ts +34 -0
  30. package/lib/clearingHouseConfig.js +2 -0
  31. package/lib/clearingHouseUser.d.ts +19 -18
  32. package/lib/clearingHouseUser.js +157 -115
  33. package/lib/clearingHouseUserConfig.d.ts +14 -0
  34. package/lib/clearingHouseUserConfig.js +2 -0
  35. package/lib/config.d.ts +12 -0
  36. package/lib/config.js +35 -4
  37. package/lib/constants/banks.d.ts +16 -0
  38. package/lib/constants/banks.js +34 -0
  39. package/lib/constants/markets.d.ts +8 -3
  40. package/lib/constants/markets.js +13 -206
  41. package/lib/constants/numericConstants.d.ts +16 -0
  42. package/lib/constants/numericConstants.js +22 -6
  43. package/lib/events/eventList.d.ts +22 -0
  44. package/lib/events/eventList.js +77 -0
  45. package/lib/events/eventSubscriber.d.ts +34 -0
  46. package/lib/events/eventSubscriber.js +126 -0
  47. package/lib/events/fetchLogs.d.ts +13 -0
  48. package/lib/events/fetchLogs.js +39 -0
  49. package/lib/events/pollingLogProvider.d.ts +15 -0
  50. package/lib/events/pollingLogProvider.js +53 -0
  51. package/lib/events/sort.d.ts +2 -0
  52. package/lib/events/sort.js +44 -0
  53. package/lib/events/txEventCache.d.ts +24 -0
  54. package/lib/events/txEventCache.js +71 -0
  55. package/lib/events/types.d.ts +49 -0
  56. package/lib/events/types.js +20 -0
  57. package/lib/events/webSocketLogProvider.d.ts +12 -0
  58. package/lib/events/webSocketLogProvider.js +30 -0
  59. package/lib/examples/makeTradeExample.js +26 -27
  60. package/lib/factory/bigNum.d.ts +112 -0
  61. package/lib/factory/bigNum.js +356 -0
  62. package/lib/factory/oracleClient.d.ts +1 -2
  63. package/lib/factory/oracleClient.js +6 -2
  64. package/lib/idl/clearing_house.json +1739 -2287
  65. package/lib/index.d.ts +13 -4
  66. package/lib/index.js +13 -4
  67. package/lib/math/amm.d.ts +19 -29
  68. package/lib/math/amm.js +129 -179
  69. package/lib/math/auction.d.ts +5 -0
  70. package/lib/math/auction.js +39 -0
  71. package/lib/math/bankBalance.d.ts +9 -0
  72. package/lib/math/bankBalance.js +75 -0
  73. package/lib/math/conversion.d.ts +0 -1
  74. package/lib/math/conversion.js +1 -5
  75. package/lib/math/funding.d.ts +6 -6
  76. package/lib/math/funding.js +158 -175
  77. package/lib/math/market.d.ts +6 -6
  78. package/lib/math/market.js +10 -9
  79. package/lib/math/oracles.d.ts +3 -0
  80. package/lib/math/oracles.js +26 -0
  81. package/lib/math/orders.d.ts +5 -0
  82. package/lib/math/orders.js +31 -1
  83. package/lib/math/position.d.ts +7 -4
  84. package/lib/math/position.js +27 -9
  85. package/lib/math/repeg.d.ts +22 -0
  86. package/lib/math/repeg.js +128 -0
  87. package/lib/math/trade.d.ts +13 -8
  88. package/lib/math/trade.js +85 -22
  89. package/lib/mockUSDCFaucet.js +87 -116
  90. package/lib/oracles/oracleClientCache.d.ts +8 -0
  91. package/lib/oracles/oracleClientCache.js +19 -0
  92. package/lib/oracles/pythClient.d.ts +3 -5
  93. package/lib/oracles/pythClient.js +12 -30
  94. package/lib/oracles/quoteAssetOracleClient.d.ts +9 -0
  95. package/lib/oracles/quoteAssetOracleClient.js +21 -0
  96. package/lib/oracles/switchboardClient.d.ts +3 -5
  97. package/lib/oracles/switchboardClient.js +29 -47
  98. package/lib/oracles/types.d.ts +7 -1
  99. package/lib/orders.d.ts +6 -6
  100. package/lib/orders.js +10 -9
  101. package/lib/slot/SlotSubscriber.d.ts +12 -0
  102. package/lib/slot/SlotSubscriber.js +23 -0
  103. package/lib/tx/retryTxSender.d.ts +2 -2
  104. package/lib/tx/retryTxSender.js +108 -123
  105. package/lib/tx/types.d.ts +5 -1
  106. package/lib/tx/utils.d.ts +1 -1
  107. package/lib/tx/utils.js +11 -2
  108. package/lib/types.d.ts +105 -98
  109. package/lib/types.js +13 -1
  110. package/lib/userName.d.ts +4 -0
  111. package/lib/userName.js +20 -0
  112. package/lib/util/computeUnits.js +10 -21
  113. package/lib/util/tps.js +11 -22
  114. package/lib/wallet.js +7 -20
  115. package/package.json +10 -3
  116. package/src/accounts/bulkAccountLoader.ts +26 -15
  117. package/src/accounts/bulkUserSubscription.ts +1 -45
  118. package/src/accounts/fetch.ts +33 -0
  119. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +249 -214
  120. package/src/accounts/pollingOracleSubscriber.ts +16 -8
  121. package/src/accounts/pollingTokenAccountSubscriber.ts +11 -8
  122. package/src/accounts/pollingUserAccountSubscriber.ts +21 -86
  123. package/src/accounts/types.ts +41 -70
  124. package/src/accounts/webSocketAccountSubscriber.ts +33 -16
  125. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +190 -240
  126. package/src/accounts/webSocketUserAccountSubscriber.ts +11 -71
  127. package/src/addresses/marketAddresses.ts +18 -0
  128. package/src/addresses/pda.ts +118 -0
  129. package/src/admin.ts +209 -267
  130. package/src/clearingHouse.ts +921 -829
  131. package/src/clearingHouseConfig.ts +37 -0
  132. package/src/clearingHouseUser.ts +280 -127
  133. package/src/clearingHouseUserConfig.ts +18 -0
  134. package/src/config.ts +54 -1
  135. package/src/constants/banks.ts +43 -0
  136. package/src/constants/markets.ts +16 -207
  137. package/src/constants/numericConstants.ts +33 -5
  138. package/src/events/eventList.ts +94 -0
  139. package/src/events/eventSubscriber.ts +194 -0
  140. package/src/events/fetchLogs.ts +80 -0
  141. package/src/events/pollingLogProvider.ts +79 -0
  142. package/src/events/sort.ts +65 -0
  143. package/src/events/txEventCache.ts +74 -0
  144. package/src/events/types.ts +98 -0
  145. package/src/events/webSocketLogProvider.ts +38 -0
  146. package/src/examples/makeTradeExample.ts +20 -11
  147. package/src/factory/bigNum.ts +507 -0
  148. package/src/factory/oracleClient.ts +7 -4
  149. package/src/idl/clearing_house.json +1739 -2287
  150. package/src/index.ts +13 -4
  151. package/src/math/amm.ts +229 -245
  152. package/src/math/auction.ts +39 -0
  153. package/src/math/bankBalance.ts +112 -0
  154. package/src/math/conversion.ts +1 -11
  155. package/src/math/funding.ts +12 -9
  156. package/src/math/market.ts +37 -30
  157. package/src/math/oracles.ts +36 -0
  158. package/src/math/orders.ts +38 -0
  159. package/src/math/position.ts +48 -13
  160. package/src/math/repeg.ts +175 -0
  161. package/src/math/trade.ts +114 -36
  162. package/src/math/utils.js +27 -0
  163. package/src/math/utils.js.map +1 -0
  164. package/src/oracles/oracleClientCache.ts +20 -0
  165. package/src/oracles/pythClient.ts +5 -11
  166. package/src/oracles/quoteAssetOracleClient.ts +25 -0
  167. package/src/oracles/switchboardClient.ts +16 -24
  168. package/src/oracles/types.ts +8 -1
  169. package/src/orders.ts +35 -20
  170. package/src/slot/SlotSubscriber.ts +32 -0
  171. package/src/tx/retryTxSender.ts +6 -4
  172. package/src/tx/types.ts +6 -1
  173. package/src/tx/utils.ts +22 -3
  174. package/src/types.ts +108 -110
  175. package/src/userName.ts +20 -0
  176. package/src/util/computeUnits.js +17 -0
  177. package/src/util/computeUnits.js.map +1 -0
  178. package/tests/bn/test.ts +255 -0
  179. package/tsconfig.json +12 -12
  180. package/lib/addresses.d.ts +0 -9
  181. package/lib/addresses.js +0 -87
  182. package/lib/constants/accounts.d.ts +0 -15
  183. package/lib/constants/accounts.js +0 -18
  184. package/lib/factory/clearingHouse.d.ts +0 -35
  185. package/lib/factory/clearingHouse.js +0 -81
  186. package/lib/factory/clearingHouseUser.d.ts +0 -19
  187. package/lib/factory/clearingHouseUser.js +0 -34
  188. package/lib/math/insuranceFund.d.ts +0 -15
  189. package/lib/math/insuranceFund.js +0 -33
  190. package/lib/tx/defaultTxSender.d.ts +0 -8
  191. package/lib/tx/defaultTxSender.js +0 -12
  192. package/src/addresses.ts +0 -71
  193. package/src/constants/accounts.ts +0 -26
  194. package/src/factory/clearingHouse.ts +0 -173
  195. package/src/factory/clearingHouseUser.ts +0 -73
  196. package/src/math/insuranceFund.ts +0 -29
  197. package/src/tx/defaultTxSender.ts +0 -24
@@ -1,31 +1,32 @@
1
1
  /// <reference types="node" />
2
2
  import { Commitment, Connection, PublicKey } from '@solana/web3.js';
3
- import { AccountData } from './types';
3
+ import { BufferAndSlot } from './types';
4
4
  declare type AccountToLoad = {
5
5
  publicKey: PublicKey;
6
- callbacks: Map<string, (buffer: Buffer) => void>;
6
+ callbacks: Map<string, (buffer: Buffer, slot: number) => void>;
7
7
  };
8
8
  export declare class BulkAccountLoader {
9
9
  connection: Connection;
10
10
  commitment: Commitment;
11
11
  pollingFrequency: number;
12
12
  accountsToLoad: Map<string, AccountToLoad>;
13
- accountData: Map<string, AccountData>;
13
+ bufferAndSlotMap: Map<string, BufferAndSlot>;
14
14
  errorCallbacks: Map<string, (e: any) => void>;
15
15
  intervalId?: NodeJS.Timer;
16
16
  loadPromise?: Promise<void>;
17
17
  loadPromiseResolver: () => void;
18
18
  lastTimeLoadingPromiseCleared: number;
19
+ mostRecentSlot: number;
19
20
  constructor(connection: Connection, commitment: Commitment, pollingFrequency: number);
20
- addAccount(publicKey: PublicKey, callback: (buffer: Buffer) => void): string;
21
+ addAccount(publicKey: PublicKey, callback: (buffer: Buffer, slot: number) => void): string;
21
22
  removeAccount(publicKey: PublicKey, callbackId: string): void;
22
23
  addErrorCallbacks(callback: (error: Error) => void): string;
23
24
  removeErrorCallbacks(callbackId: string): void;
24
25
  chunks<T>(array: readonly T[], size: number): T[][];
25
26
  load(): Promise<void>;
26
27
  loadChunk(accountsToLoad: AccountToLoad[]): Promise<void>;
27
- handleAccountCallbacks(accountToLoad: AccountToLoad, buffer: Buffer): void;
28
- getAccountData(publicKey: PublicKey): Buffer | undefined;
28
+ handleAccountCallbacks(accountToLoad: AccountToLoad, buffer: Buffer, slot: number): void;
29
+ getBufferAndSlot(publicKey: PublicKey): BufferAndSlot | undefined;
29
30
  startPolling(): void;
30
31
  stopPolling(): void;
31
32
  log(msg: string): void;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.BulkAccountLoader = void 0;
13
4
  const uuid_1 = require("uuid");
@@ -17,9 +8,10 @@ const oneMinute = 60 * 1000;
17
8
  class BulkAccountLoader {
18
9
  constructor(connection, commitment, pollingFrequency) {
19
10
  this.accountsToLoad = new Map();
20
- this.accountData = new Map();
11
+ this.bufferAndSlotMap = new Map();
21
12
  this.errorCallbacks = new Map();
22
13
  this.lastTimeLoadingPromiseCleared = Date.now();
14
+ this.mostRecentSlot = 0;
23
15
  this.connection = connection;
24
16
  this.commitment = commitment;
25
17
  this.pollingFrequency = pollingFrequency;
@@ -73,100 +65,98 @@ class BulkAccountLoader {
73
65
  .map((_, index) => index * size)
74
66
  .map((begin) => array.slice(begin, begin + size));
75
67
  }
76
- load() {
77
- return __awaiter(this, void 0, void 0, function* () {
78
- if (this.loadPromise) {
79
- const now = Date.now();
80
- if (now - this.lastTimeLoadingPromiseCleared > oneMinute) {
81
- this.loadPromise = undefined;
82
- }
83
- else {
84
- return this.loadPromise;
85
- }
86
- }
87
- this.loadPromise = new Promise((resolver) => {
88
- this.loadPromiseResolver = resolver;
89
- });
90
- this.lastTimeLoadingPromiseCleared = Date.now();
91
- try {
92
- const chunks = this.chunks(Array.from(this.accountsToLoad.values()), GET_MULTIPLE_ACCOUNTS_CHUNK_SIZE);
93
- yield Promise.all(chunks.map((chunk) => {
94
- return this.loadChunk(chunk);
95
- }));
96
- }
97
- catch (e) {
98
- console.error(`Error in bulkAccountLoader.load()`);
99
- console.error(e);
100
- for (const [_, callback] of this.errorCallbacks) {
101
- callback(e);
102
- }
103
- }
104
- finally {
105
- this.loadPromiseResolver();
68
+ async load() {
69
+ if (this.loadPromise) {
70
+ const now = Date.now();
71
+ if (now - this.lastTimeLoadingPromiseCleared > oneMinute) {
106
72
  this.loadPromise = undefined;
107
73
  }
74
+ else {
75
+ return this.loadPromise;
76
+ }
77
+ }
78
+ this.loadPromise = new Promise((resolver) => {
79
+ this.loadPromiseResolver = resolver;
108
80
  });
81
+ this.lastTimeLoadingPromiseCleared = Date.now();
82
+ try {
83
+ const chunks = this.chunks(Array.from(this.accountsToLoad.values()), GET_MULTIPLE_ACCOUNTS_CHUNK_SIZE);
84
+ await Promise.all(chunks.map((chunk) => {
85
+ return this.loadChunk(chunk);
86
+ }));
87
+ }
88
+ catch (e) {
89
+ console.error(`Error in bulkAccountLoader.load()`);
90
+ console.error(e);
91
+ for (const [_, callback] of this.errorCallbacks) {
92
+ callback(e);
93
+ }
94
+ }
95
+ finally {
96
+ this.loadPromiseResolver();
97
+ this.loadPromise = undefined;
98
+ }
109
99
  }
110
- loadChunk(accountsToLoad) {
111
- return __awaiter(this, void 0, void 0, function* () {
112
- if (accountsToLoad.length === 0) {
113
- return;
100
+ async loadChunk(accountsToLoad) {
101
+ if (accountsToLoad.length === 0) {
102
+ return;
103
+ }
104
+ const args = [
105
+ accountsToLoad.map((accountToLoad) => {
106
+ return accountToLoad.publicKey.toBase58();
107
+ }),
108
+ { commitment: this.commitment },
109
+ ];
110
+ const rpcResponse = await (0, promiseTimeout_1.promiseTimeout)(
111
+ // @ts-ignore
112
+ this.connection._rpcRequest('getMultipleAccounts', args), 10 * 1000 // 30 second timeout
113
+ );
114
+ if (rpcResponse === null) {
115
+ this.log('request to rpc timed out');
116
+ return;
117
+ }
118
+ const newSlot = rpcResponse.result.context.slot;
119
+ if (newSlot > this.mostRecentSlot) {
120
+ this.mostRecentSlot = newSlot;
121
+ }
122
+ for (const i in accountsToLoad) {
123
+ const accountToLoad = accountsToLoad[i];
124
+ const key = accountToLoad.publicKey.toString();
125
+ const oldRPCResponse = this.bufferAndSlotMap.get(key);
126
+ let newBuffer = undefined;
127
+ if (rpcResponse.result.value[i]) {
128
+ const raw = rpcResponse.result.value[i].data[0];
129
+ const dataType = rpcResponse.result.value[i].data[1];
130
+ newBuffer = Buffer.from(raw, dataType);
114
131
  }
115
- const args = [
116
- accountsToLoad.map((accountToLoad) => {
117
- return accountToLoad.publicKey.toBase58();
118
- }),
119
- { commitment: this.commitment },
120
- ];
121
- const rpcResponse = yield (0, promiseTimeout_1.promiseTimeout)(
122
- // @ts-ignore
123
- this.connection._rpcRequest('getMultipleAccounts', args), 10 * 1000 // 30 second timeout
124
- );
125
- if (rpcResponse === null) {
126
- this.log('request to rpc timed out');
127
- return;
132
+ if (!oldRPCResponse) {
133
+ this.bufferAndSlotMap.set(key, {
134
+ slot: newSlot,
135
+ buffer: newBuffer,
136
+ });
137
+ this.handleAccountCallbacks(accountToLoad, newBuffer, newSlot);
138
+ continue;
128
139
  }
129
- const newSlot = rpcResponse.result.context.slot;
130
- for (const i in accountsToLoad) {
131
- const accountToLoad = accountsToLoad[i];
132
- const key = accountToLoad.publicKey.toString();
133
- const oldRPCResponse = this.accountData.get(key);
134
- let newBuffer = undefined;
135
- if (rpcResponse.result.value[i]) {
136
- const raw = rpcResponse.result.value[i].data[0];
137
- const dataType = rpcResponse.result.value[i].data[1];
138
- newBuffer = Buffer.from(raw, dataType);
139
- }
140
- if (!oldRPCResponse) {
141
- this.accountData.set(key, {
142
- slot: newSlot,
143
- buffer: newBuffer,
144
- });
145
- this.handleAccountCallbacks(accountToLoad, newBuffer);
146
- continue;
147
- }
148
- if (newSlot <= oldRPCResponse.slot) {
149
- continue;
150
- }
151
- const oldBuffer = oldRPCResponse.buffer;
152
- if (newBuffer && (!oldBuffer || !newBuffer.equals(oldBuffer))) {
153
- this.accountData.set(key, {
154
- slot: newSlot,
155
- buffer: newBuffer,
156
- });
157
- this.handleAccountCallbacks(accountToLoad, newBuffer);
158
- }
140
+ if (newSlot <= oldRPCResponse.slot) {
141
+ continue;
159
142
  }
160
- });
143
+ const oldBuffer = oldRPCResponse.buffer;
144
+ if (newBuffer && (!oldBuffer || !newBuffer.equals(oldBuffer))) {
145
+ this.bufferAndSlotMap.set(key, {
146
+ slot: newSlot,
147
+ buffer: newBuffer,
148
+ });
149
+ this.handleAccountCallbacks(accountToLoad, newBuffer, newSlot);
150
+ }
151
+ }
161
152
  }
162
- handleAccountCallbacks(accountToLoad, buffer) {
153
+ handleAccountCallbacks(accountToLoad, buffer, slot) {
163
154
  for (const [_, callback] of accountToLoad.callbacks) {
164
- callback(buffer);
155
+ callback(buffer, slot);
165
156
  }
166
157
  }
167
- getAccountData(publicKey) {
168
- const accountData = this.accountData.get(publicKey.toString());
169
- return accountData === null || accountData === void 0 ? void 0 : accountData.buffer;
158
+ getBufferAndSlot(publicKey) {
159
+ return this.bufferAndSlotMap.get(publicKey.toString());
170
160
  }
171
161
  startPolling() {
172
162
  if (this.intervalId) {
@@ -1,66 +1,22 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.bulkPollingUserSubscribe = void 0;
13
4
  /**
14
5
  * @param users
15
6
  * @param accountLoader
16
7
  */
17
- function bulkPollingUserSubscribe(users, accountLoader) {
18
- return __awaiter(this, void 0, void 0, function* () {
19
- if (users.length === 0) {
20
- yield accountLoader.load();
21
- return;
22
- }
23
- // Fetch all the accounts first
24
- const program = users[0].clearingHouse.program;
25
- let userProgramAccounts;
26
- let orderProgramAccounts;
27
- yield Promise.all([
28
- (() => __awaiter(this, void 0, void 0, function* () {
29
- userProgramAccounts = yield program.account.user.all();
30
- }))(),
31
- (() => __awaiter(this, void 0, void 0, function* () {
32
- orderProgramAccounts = yield program.account.userOrders.all();
33
- }))(),
34
- ]);
35
- // Create a map of the authority to keys
36
- const authorityToKeys = new Map();
37
- const userToAuthority = new Map();
38
- for (const userProgramAccount of userProgramAccounts) {
39
- const userAccountPublicKey = userProgramAccount.publicKey;
40
- const userAccount = userProgramAccount.account;
41
- authorityToKeys.set(userAccount.authority.toString(), {
42
- user: userAccountPublicKey,
43
- userPositions: userAccount.positions,
44
- userOrders: undefined,
45
- });
46
- userToAuthority.set(userAccountPublicKey.toString(), userAccount.authority.toString());
47
- }
48
- for (const orderProgramAccount of orderProgramAccounts) {
49
- const userOrderAccountPublicKey = orderProgramAccount.publicKey;
50
- const userOrderAccount = orderProgramAccount.account;
51
- const authority = userToAuthority.get(userOrderAccount.user.toString());
52
- const userPublicKeys = authorityToKeys.get(authority);
53
- userPublicKeys.userOrders = userOrderAccountPublicKey;
54
- }
55
- yield Promise.all(users.map((user) => {
56
- // Pull the keys from the authority map so we can skip fetching them in addToAccountLoader
57
- const userPublicKeys = authorityToKeys.get(user.authority.toString());
58
- return user.accountSubscriber.addToAccountLoader(userPublicKeys);
59
- }));
60
- yield accountLoader.load();
61
- yield Promise.all(users.map((user) => __awaiter(this, void 0, void 0, function* () {
62
- return user.subscribe();
63
- })));
64
- });
8
+ async function bulkPollingUserSubscribe(users, accountLoader) {
9
+ if (users.length === 0) {
10
+ await accountLoader.load();
11
+ return;
12
+ }
13
+ await Promise.all(users.map((user) => {
14
+ // Pull the keys from the authority map so we can skip fetching them in addToAccountLoader
15
+ return user.accountSubscriber.addToAccountLoader();
16
+ }));
17
+ await accountLoader.load();
18
+ await Promise.all(users.map(async (user) => {
19
+ return user.subscribe();
20
+ }));
65
21
  }
66
22
  exports.bulkPollingUserSubscribe = bulkPollingUserSubscribe;
@@ -0,0 +1,4 @@
1
+ import { Connection, PublicKey } from '@solana/web3.js';
2
+ import { UserAccount } from '../types';
3
+ import { Program } from '@project-serum/anchor';
4
+ export declare function fetchUserAccounts(connection: Connection, program: Program, authority: PublicKey, limit?: number): Promise<(UserAccount | undefined)[]>;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetchUserAccounts = void 0;
4
+ const pda_1 = require("../addresses/pda");
5
+ async function fetchUserAccounts(connection, program, authority, limit = 8) {
6
+ const userAccountPublicKeys = new Array();
7
+ for (let i = 0; i < limit; i++) {
8
+ userAccountPublicKeys.push(await (0, pda_1.getUserAccountPublicKey)(program.programId, authority, i));
9
+ }
10
+ const accountInfos = await connection.getMultipleAccountsInfo(userAccountPublicKeys, 'confirmed');
11
+ return accountInfos.map((accountInfo) => {
12
+ if (!accountInfo) {
13
+ return undefined;
14
+ }
15
+ return program.account.user.coder.accounts.decode('User', accountInfo.data);
16
+ });
17
+ }
18
+ exports.fetchUserAccounts = fetchUserAccounts;
@@ -1,65 +1,61 @@
1
+ /// <reference types="bn.js" />
1
2
  /// <reference types="node" />
2
- import { AccountToPoll, ClearingHouseAccountEvents, ClearingHouseAccountSubscriber, ClearingHouseAccountTypes } from './types';
3
- import { Program } from '@project-serum/anchor';
3
+ import { DataAndSlot, AccountToPoll, ClearingHouseAccountEvents, ClearingHouseAccountSubscriber, OraclesToPoll } from './types';
4
+ import { BN, Program } from '@project-serum/anchor';
4
5
  import StrictEventEmitter from 'strict-event-emitter-types';
5
6
  import { EventEmitter } from 'events';
6
- import { DepositHistoryAccount, ExtendedCurveHistoryAccount, FundingPaymentHistoryAccount, FundingRateHistoryAccount, LiquidationHistoryAccount, MarketsAccount, OrderHistoryAccount, OrderStateAccount, StateAccount, TradeHistoryAccount } from '../types';
7
+ import { BankAccount, MarketAccount, StateAccount, UserAccount } from '../types';
7
8
  import { BulkAccountLoader } from './bulkAccountLoader';
8
- import { ClearingHouseConfigType } from '../factory/clearingHouse';
9
9
  import { PublicKey } from '@solana/web3.js';
10
+ import { OracleInfo, OraclePriceData } from '../oracles/types';
11
+ import { OracleClientCache } from '../oracles/oracleClientCache';
10
12
  export declare class PollingClearingHouseAccountSubscriber implements ClearingHouseAccountSubscriber {
11
13
  isSubscribed: boolean;
12
14
  program: Program;
15
+ marketIndexes: BN[];
16
+ bankIndexes: BN[];
17
+ oracleInfos: OracleInfo[];
18
+ oracleClientCache: OracleClientCache;
13
19
  eventEmitter: StrictEventEmitter<EventEmitter, ClearingHouseAccountEvents>;
14
20
  accountLoader: BulkAccountLoader;
15
21
  accountsToPoll: Map<string, AccountToPoll>;
22
+ oraclesToPoll: Map<string, OraclesToPoll>;
16
23
  errorCallbackId?: string;
17
- state?: StateAccount;
18
- markets?: MarketsAccount;
19
- orderState?: OrderStateAccount;
20
- tradeHistory?: TradeHistoryAccount;
21
- depositHistory?: DepositHistoryAccount;
22
- fundingPaymentHistory?: FundingPaymentHistoryAccount;
23
- fundingRateHistory?: FundingRateHistoryAccount;
24
- liquidationHistory?: LiquidationHistoryAccount;
25
- extendedCurveHistory: ExtendedCurveHistoryAccount;
26
- orderHistory?: OrderHistoryAccount;
27
- optionalExtraSubscriptions: ClearingHouseAccountTypes[];
28
- type: ClearingHouseConfigType;
24
+ state?: DataAndSlot<StateAccount>;
25
+ market: Map<number, DataAndSlot<MarketAccount>>;
26
+ bank: Map<number, DataAndSlot<BankAccount>>;
27
+ oracles: Map<string, DataAndSlot<OraclePriceData>>;
28
+ user?: DataAndSlot<UserAccount>;
29
29
  private isSubscribing;
30
30
  private subscriptionPromise;
31
31
  private subscriptionPromiseResolver;
32
- constructor(program: Program, accountLoader: BulkAccountLoader);
33
- subscribe(optionalSubscriptions?: ClearingHouseAccountTypes[]): Promise<boolean>;
32
+ constructor(program: Program, accountLoader: BulkAccountLoader, marketIndexes: BN[], bankIndexes: BN[], oracleInfos: OracleInfo[]);
33
+ subscribe(): Promise<boolean>;
34
34
  updateAccountsToPoll(): Promise<void>;
35
+ updateMarketAccountsToPoll(): Promise<boolean>;
36
+ addMarketAccountToPoll(marketIndex: BN): Promise<boolean>;
37
+ updateBankAccountsToPoll(): Promise<boolean>;
38
+ addBankAccountToPoll(bankIndex: BN): Promise<boolean>;
39
+ updateOraclesToPoll(): boolean;
40
+ addOracleToPoll(oracleInfo: OracleInfo): boolean;
35
41
  getClearingHouseAccounts(): Promise<ClearingHouseAccounts>;
36
42
  addToAccountLoader(): Promise<void>;
43
+ addAccountToAccountLoader(accountToPoll: AccountToPoll): void;
44
+ addOracleToAccountLoader(oracleToPoll: OraclesToPoll): void;
37
45
  fetch(): Promise<void>;
38
46
  didSubscriptionSucceed(): boolean;
39
47
  unsubscribe(): Promise<void>;
48
+ addBank(bankIndex: BN): Promise<boolean>;
49
+ addMarket(marketIndex: BN): Promise<boolean>;
50
+ addOracle(oracleInfo: OracleInfo): Promise<boolean>;
40
51
  assertIsSubscribed(): void;
41
- assertOptionalIsSubscribed(optionalSubscription: ClearingHouseAccountTypes): void;
42
- getStateAccount(): StateAccount;
43
- getMarketsAccount(): MarketsAccount;
44
- getOrderStateAccount(): OrderStateAccount;
45
- getTradeHistoryAccount(): TradeHistoryAccount;
46
- getDepositHistoryAccount(): DepositHistoryAccount;
47
- getFundingPaymentHistoryAccount(): FundingPaymentHistoryAccount;
48
- getFundingRateHistoryAccount(): FundingRateHistoryAccount;
49
- getCurveHistoryAccount(): ExtendedCurveHistoryAccount;
50
- getLiquidationHistoryAccount(): LiquidationHistoryAccount;
51
- getOrderHistoryAccount(): OrderHistoryAccount;
52
+ getStateAccountAndSlot(): DataAndSlot<StateAccount>;
53
+ getMarketAccountAndSlot(marketIndex: BN): DataAndSlot<MarketAccount> | undefined;
54
+ getMarketAccountsAndSlots(): DataAndSlot<MarketAccount>[];
55
+ getBankAccountAndSlot(bankIndex: BN): DataAndSlot<BankAccount> | undefined;
56
+ getOraclePriceDataAndSlot(oraclePublicKey: PublicKey): DataAndSlot<OraclePriceData> | undefined;
52
57
  }
53
58
  declare type ClearingHouseAccounts = {
54
59
  state: PublicKey;
55
- markets: PublicKey;
56
- orderState: PublicKey;
57
- tradeHistory?: PublicKey;
58
- depositHistory?: PublicKey;
59
- fundingPaymentHistory?: PublicKey;
60
- fundingRateHistory?: PublicKey;
61
- extendedCurveHistory?: PublicKey;
62
- liquidationHistory?: PublicKey;
63
- orderHistory?: PublicKey;
64
60
  };
65
61
  export {};