@n1xyz/nord-ts 0.0.1 → 0.0.4

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 (237) hide show
  1. package/.eslintrc.js +11 -0
  2. package/README.md +148 -65
  3. package/dist/bridge/NordUser.d.ts +78 -0
  4. package/dist/bridge/NordUser.js +196 -0
  5. package/dist/bridge/client.d.ts +150 -0
  6. package/dist/bridge/client.js +394 -0
  7. package/dist/bridge/const.d.ts +23 -0
  8. package/dist/bridge/const.js +47 -0
  9. package/dist/bridge/index.d.ts +5 -0
  10. package/dist/bridge/index.js +23 -0
  11. package/dist/bridge/types.d.ts +118 -0
  12. package/dist/bridge/types.js +16 -0
  13. package/dist/bridge/utils.d.ts +64 -0
  14. package/dist/bridge/utils.js +131 -0
  15. package/dist/client.d.ts +70 -0
  16. package/dist/client.js +129 -0
  17. package/dist/const.d.ts +2 -5
  18. package/dist/const.js +18 -22
  19. package/dist/constants/endpoints.d.ts +65 -0
  20. package/dist/constants/endpoints.js +68 -0
  21. package/dist/gen/common.d.ts +6 -1
  22. package/dist/gen/common.js +19 -9
  23. package/dist/gen/nord.d.ts +75 -17
  24. package/dist/gen/nord.js +987 -423
  25. package/dist/idl/bridge.d.ts +2 -0
  26. package/dist/idl/bridge.js +703 -0
  27. package/dist/index.d.ts +8 -5
  28. package/dist/index.js +18 -2
  29. package/dist/models/account.d.ts +58 -0
  30. package/dist/models/account.js +6 -0
  31. package/dist/models/index.d.ts +8 -0
  32. package/dist/models/index.js +28 -0
  33. package/dist/models/market.d.ts +137 -0
  34. package/dist/models/market.js +6 -0
  35. package/dist/models/order.d.ts +211 -0
  36. package/dist/models/order.js +6 -0
  37. package/dist/models/token.d.ts +50 -0
  38. package/dist/models/token.js +6 -0
  39. package/dist/nord/Nord.d.ts +222 -49
  40. package/dist/nord/Nord.js +290 -278
  41. package/dist/nord/NordError.d.ts +23 -0
  42. package/dist/nord/NordError.js +48 -0
  43. package/dist/nord/NordImpl.d.ts +6 -2
  44. package/dist/nord/NordImpl.js +21 -1
  45. package/dist/nord/NordUser.d.ts +208 -42
  46. package/dist/nord/NordUser.js +389 -157
  47. package/dist/nord/Subscriber.d.ts +37 -0
  48. package/dist/nord/Subscriber.js +29 -0
  49. package/dist/nord/api/actions.d.ts +101 -0
  50. package/dist/nord/api/actions.js +250 -0
  51. package/dist/nord/api/core.d.ts +49 -0
  52. package/dist/nord/api/core.js +121 -0
  53. package/dist/nord/api/index.d.ts +1 -0
  54. package/dist/nord/api/index.js +17 -0
  55. package/dist/nord/api/market.d.ts +36 -0
  56. package/dist/nord/api/market.js +98 -0
  57. package/dist/nord/api/metrics.d.ts +67 -0
  58. package/dist/nord/api/metrics.js +132 -0
  59. package/dist/nord/api/orderFunctions.d.ts +168 -0
  60. package/dist/nord/api/orderFunctions.js +133 -0
  61. package/dist/nord/api/queries.d.ts +81 -0
  62. package/dist/nord/api/queries.js +187 -0
  63. package/dist/nord/client/Nord.d.ts +335 -0
  64. package/dist/nord/client/Nord.js +532 -0
  65. package/dist/nord/client/NordUser.d.ts +320 -0
  66. package/dist/nord/client/NordUser.js +701 -0
  67. package/dist/nord/core.d.ts +48 -0
  68. package/dist/nord/core.js +97 -0
  69. package/dist/nord/index.d.ts +9 -2
  70. package/dist/nord/index.js +30 -6
  71. package/dist/nord/market.d.ts +36 -0
  72. package/dist/nord/market.js +90 -0
  73. package/dist/nord/metrics.d.ts +67 -0
  74. package/dist/nord/metrics.js +124 -0
  75. package/dist/nord/models/Subscriber.d.ts +37 -0
  76. package/dist/nord/models/Subscriber.js +29 -0
  77. package/dist/nord/queries.d.ts +81 -0
  78. package/dist/nord/queries.js +181 -0
  79. package/dist/nord/types.d.ts +88 -0
  80. package/dist/nord/types.js +2 -0
  81. package/dist/nord/utils/NordError.d.ts +35 -0
  82. package/dist/nord/utils/NordError.js +46 -0
  83. package/dist/nord/websocket.d.ts +49 -0
  84. package/dist/nord/websocket.js +107 -0
  85. package/dist/operations/account.d.ts +58 -0
  86. package/dist/operations/account.js +112 -0
  87. package/dist/operations/market.d.ts +65 -0
  88. package/dist/operations/market.js +131 -0
  89. package/dist/operations/orders.d.ts +57 -0
  90. package/dist/operations/orders.js +129 -0
  91. package/dist/solana/NordUser.d.ts +78 -0
  92. package/dist/solana/NordUser.js +196 -0
  93. package/dist/solana/client.d.ts +139 -0
  94. package/dist/solana/client.js +360 -0
  95. package/dist/solana/const.d.ts +23 -0
  96. package/dist/solana/const.js +47 -0
  97. package/dist/solana/index.d.ts +5 -0
  98. package/dist/solana/index.js +23 -0
  99. package/dist/solana/types.d.ts +118 -0
  100. package/dist/solana/types.js +16 -0
  101. package/dist/solana/utils.d.ts +64 -0
  102. package/dist/solana/utils.js +131 -0
  103. package/dist/types/api.d.ts +152 -0
  104. package/dist/types/api.js +6 -0
  105. package/dist/types/config.d.ts +34 -0
  106. package/dist/types/config.js +6 -0
  107. package/dist/types.d.ts +144 -87
  108. package/dist/types.js +13 -2
  109. package/dist/utils/errors.d.ts +96 -0
  110. package/dist/utils/errors.js +132 -0
  111. package/dist/utils/http.d.ts +35 -0
  112. package/dist/utils/http.js +105 -0
  113. package/dist/utils.d.ts +14 -5
  114. package/dist/utils.js +26 -7
  115. package/dist/websocket/NordWebSocketClient.d.ts +71 -0
  116. package/dist/websocket/NordWebSocketClient.js +343 -0
  117. package/dist/websocket/client.d.ts +93 -0
  118. package/dist/websocket/client.js +222 -0
  119. package/dist/websocket/events.d.ts +19 -0
  120. package/dist/websocket/events.js +2 -0
  121. package/dist/websocket/index.d.ts +2 -0
  122. package/dist/websocket/index.js +5 -0
  123. package/dist/websocket.d.ts +55 -0
  124. package/dist/websocket.js +211 -0
  125. package/docs/assets/navigation.js +1 -1
  126. package/docs/assets/search.js +1 -1
  127. package/docs/classes/Nord.html +2 -15
  128. package/docs/classes/NordUser.html +4 -4
  129. package/docs/enums/FillMode.html +2 -2
  130. package/docs/enums/KeyType.html +2 -2
  131. package/docs/enums/PeakTpsPeriodUnit.html +2 -2
  132. package/docs/enums/Side.html +2 -2
  133. package/docs/functions/assert.html +1 -1
  134. package/docs/functions/bigIntToProtoU128.html +1 -1
  135. package/docs/functions/checkPubKeyLength.html +1 -1
  136. package/docs/functions/checkedFetch.html +1 -1
  137. package/docs/functions/decodeLengthDelimited.html +1 -1
  138. package/docs/functions/encodeLengthDelimited.html +1 -1
  139. package/docs/functions/fillModeToProtoFillMode.html +1 -1
  140. package/docs/functions/findMarket.html +1 -1
  141. package/docs/functions/findToken.html +1 -1
  142. package/docs/functions/makeWalletSignFn.html +1 -1
  143. package/docs/functions/optExpect.html +1 -1
  144. package/docs/functions/optMap.html +1 -1
  145. package/docs/functions/optUnwrap.html +1 -1
  146. package/docs/functions/panic.html +1 -1
  147. package/docs/functions/signAction.html +1 -1
  148. package/docs/functions/toScaledU128.html +1 -1
  149. package/docs/functions/toScaledU64.html +1 -1
  150. package/docs/interfaces/Account.html +2 -2
  151. package/docs/interfaces/ActionInfo.html +2 -2
  152. package/docs/interfaces/ActionQuery.html +2 -2
  153. package/docs/interfaces/ActionResponse.html +2 -2
  154. package/docs/interfaces/ActionsExtendedInfo.html +2 -2
  155. package/docs/interfaces/ActionsQuery.html +2 -2
  156. package/docs/interfaces/ActionsResponse.html +2 -2
  157. package/docs/interfaces/AggregateMetrics.html +2 -2
  158. package/docs/interfaces/BlockQuery.html +2 -2
  159. package/docs/interfaces/BlockResponse.html +2 -2
  160. package/docs/interfaces/BlockSummary.html +2 -2
  161. package/docs/interfaces/BlockSummaryResponse.html +2 -2
  162. package/docs/interfaces/DeltaEvent.html +2 -2
  163. package/docs/interfaces/ERC20TokenInfo.html +2 -2
  164. package/docs/interfaces/Info.html +2 -2
  165. package/docs/interfaces/Market.html +2 -2
  166. package/docs/interfaces/MarketStats.html +2 -2
  167. package/docs/interfaces/MarketsStatsResponse.html +2 -2
  168. package/docs/interfaces/NordConfig.html +2 -2
  169. package/docs/interfaces/Order.html +2 -2
  170. package/docs/interfaces/OrderInfo.html +2 -2
  171. package/docs/interfaces/PerpMarketStats.html +2 -2
  172. package/docs/interfaces/RollmanActionExtendedInfo.html +2 -2
  173. package/docs/interfaces/RollmanActionInfo.html +2 -2
  174. package/docs/interfaces/RollmanActionResponse.html +2 -2
  175. package/docs/interfaces/RollmanActionsResponse.html +2 -2
  176. package/docs/interfaces/RollmanBlockResponse.html +2 -2
  177. package/docs/interfaces/SubscriberConfig.html +2 -2
  178. package/docs/interfaces/Token.html +2 -2
  179. package/docs/interfaces/Trade.html +2 -2
  180. package/docs/interfaces/Trades.html +2 -2
  181. package/docs/modules.html +0 -7
  182. package/docs/types/BigIntValue.html +1 -1
  183. package/docs/variables/DEBUG_KEYS.html +1 -1
  184. package/docs/variables/DEFAULT_FUNDING_AMOUNTS.html +1 -1
  185. package/docs/variables/DEV_CONTRACT_ADDRESS.html +1 -1
  186. package/docs/variables/DEV_TOKEN_INFOS.html +1 -1
  187. package/docs/variables/DEV_URL.html +1 -1
  188. package/docs/variables/ERC20_ABI.html +1 -1
  189. package/docs/variables/EVM_DEV_URL.html +1 -1
  190. package/docs/variables/FAUCET_PRIVATE_ADDRESS.html +1 -1
  191. package/docs/variables/MAX_BUFFER_LEN.html +1 -1
  192. package/docs/variables/NORD_GETTERS_FACET_ABI.html +1 -1
  193. package/docs/variables/NORD_RAMP_FACET_ABI.html +1 -1
  194. package/docs/variables/SESSION_TTL.html +1 -1
  195. package/docs/variables/WEBSERVER_DEV_URL.html +1 -1
  196. package/docs/variables/ZERO_DECIMAL.html +1 -1
  197. package/package.json +10 -12
  198. package/src/bridge/client.ts +487 -0
  199. package/src/bridge/const.ts +53 -0
  200. package/src/bridge/index.ts +7 -0
  201. package/src/bridge/types.ts +127 -0
  202. package/src/bridge/utils.ts +140 -0
  203. package/src/const.ts +20 -25
  204. package/src/gen/common.ts +27 -10
  205. package/src/gen/nord.ts +1044 -483
  206. package/src/idl/bridge.ts +702 -0
  207. package/src/index.ts +24 -5
  208. package/src/nord/{actions.ts → api/actions.ts} +33 -37
  209. package/src/nord/api/core.ts +130 -0
  210. package/src/nord/api/market.ts +125 -0
  211. package/src/nord/api/metrics.ts +154 -0
  212. package/src/nord/api/queries.ts +236 -0
  213. package/src/nord/client/Nord.ts +652 -0
  214. package/src/nord/client/NordUser.ts +1105 -0
  215. package/src/nord/index.ts +16 -2
  216. package/src/nord/models/Subscriber.ts +57 -0
  217. package/src/nord/utils/NordError.ts +72 -0
  218. package/src/types.ts +170 -99
  219. package/src/utils.ts +40 -19
  220. package/src/websocket/NordWebSocketClient.ts +432 -0
  221. package/src/websocket/events.ts +31 -0
  222. package/src/websocket/index.ts +2 -0
  223. package/tests/utils.spec.ts +24 -24
  224. package/docs/classes/Subscriber.html +0 -6
  225. package/docs/functions/createWebSocketSubscription.html +0 -12
  226. package/docs/interfaces/OrderbookOrder.html +0 -6
  227. package/docs/interfaces/OrderbookResponse.html +0 -10
  228. package/docs/interfaces/TradeInfo.html +0 -20
  229. package/docs/interfaces/TradesQueryParams.html +0 -10
  230. package/docs/interfaces/TradesResponse.html +0 -12
  231. package/src/abis/ERC20_ABI.ts +0 -310
  232. package/src/abis/NORD_GETTERS_FACET_ABI.ts +0 -192
  233. package/src/abis/NORD_RAMP_FACET_ABI.ts +0 -141
  234. package/src/abis/index.ts +0 -3
  235. package/src/nord/Nord.ts +0 -504
  236. package/src/nord/NordImpl.ts +0 -8
  237. package/src/nord/NordUser.ts +0 -469
@@ -0,0 +1,652 @@
1
+ import { EventEmitter } from 'events';
2
+ import {
3
+ Account,
4
+ ActionQuery,
5
+ ActionResponse,
6
+ ActionsResponse,
7
+ AggregateMetrics,
8
+ BlockQuery,
9
+ BlockResponse,
10
+ BlockSummaryResponse,
11
+ Info,
12
+ Market,
13
+ MarketsStatsResponse,
14
+ NordConfig,
15
+ OrderbookQuery,
16
+ OrderbookResponse,
17
+ PeakTpsPeriodUnit,
18
+ RollmanActionResponse,
19
+ RollmanActionsResponse,
20
+ RollmanBlockResponse,
21
+ Token,
22
+ TradesQuery,
23
+ TradesResponse,
24
+ UserAccountIdsQuery,
25
+ UserAccountIdsResponse,
26
+ } from '../../types';
27
+ import { NordWebSocketClient } from '../../websocket/index';
28
+ import * as core from '../api/core';
29
+ import * as market from '../api/market';
30
+ import * as metrics from '../api/metrics';
31
+ import * as queries from '../api/queries';
32
+ import { OrderbookSubscription, TradeSubscription } from '../models/Subscriber';
33
+ import { NordError } from '../utils/NordError';
34
+
35
+ /**
36
+ * User subscription interface
37
+ */
38
+ export interface UserSubscription extends EventEmitter {
39
+ close: () => void;
40
+ }
41
+
42
+ /**
43
+ * Main Nord client class for interacting with the Nord API
44
+ */
45
+ export class Nord {
46
+ /** Base URL for the Nord web server */
47
+ public readonly webServerUrl: string;
48
+
49
+ /** Solana program ID */
50
+ public readonly solanaProgramId: string;
51
+
52
+ /** Solana RPC URL */
53
+ public readonly solanaUrl: string;
54
+
55
+ /** Available markets */
56
+ public markets: Market[] = [];
57
+
58
+ /** Available tokens */
59
+ public tokens: Token[] = [];
60
+
61
+ /** Map of symbol to market_id */
62
+ private symbolToMarketId: Map<string, number> = new Map();
63
+
64
+ /**
65
+ * WebSocket client for trades
66
+ * @private
67
+ */
68
+ private tradesWs: NordWebSocketClient | null = null;
69
+
70
+ /**
71
+ * WebSocket client for orderbook deltas
72
+ * @private
73
+ */
74
+ private deltasWs: NordWebSocketClient | null = null;
75
+
76
+ /**
77
+ * WebSocket client for user updates
78
+ * @private
79
+ */
80
+ private userWs: NordWebSocketClient | null = null;
81
+
82
+ /**
83
+ * Initial subscriptions for the trades WebSocket
84
+ * @private
85
+ */
86
+ private tradesSubscriptions?: string[];
87
+
88
+ /**
89
+ * Initial subscriptions for the deltas WebSocket
90
+ * @private
91
+ */
92
+ private deltasSubscriptions?: string[];
93
+
94
+ /**
95
+ * Create a new Nord client
96
+ *
97
+ * @param config - Configuration options for the Nord client
98
+ * @param config.webServerUrl - Base URL for the Nord web server
99
+ * @param config.solanaProgramId - Solana program ID
100
+ * @param config.solanaUrl - Solana cluster URL
101
+ * @param config.initWebSockets - Whether to initialize WebSockets on creation, defaults to true
102
+ * @param config.tradesSubscriptions - Optional array of trades subscriptions to initialize with (e.g., ["trades@BTCUSDC"])
103
+ * @param config.deltasSubscriptions - Optional array of deltas subscriptions to initialize with (e.g., ["deltas@BTCUSDC"])
104
+ * @throws {Error} If required configuration is missing
105
+ */
106
+ constructor({
107
+ webServerUrl,
108
+ solanaProgramId,
109
+ solanaUrl,
110
+ initWebSockets = true,
111
+ tradesSubscriptions,
112
+ deltasSubscriptions,
113
+ }: NordConfig) {
114
+ if (!webServerUrl) {
115
+ throw new NordError('webServerUrl is required');
116
+ }
117
+
118
+ if (!solanaProgramId) {
119
+ throw new NordError('solanaProgramId is required');
120
+ }
121
+
122
+ if (!solanaUrl) {
123
+ throw new NordError('solanaUrl is required');
124
+ }
125
+
126
+ this.webServerUrl = webServerUrl;
127
+ this.solanaProgramId = solanaProgramId;
128
+ this.solanaUrl = solanaUrl;
129
+
130
+ // Store subscription parameters
131
+ this.tradesSubscriptions = tradesSubscriptions;
132
+ this.deltasSubscriptions = deltasSubscriptions;
133
+
134
+ // Initialize WebSocket clients only if initWebSockets is true
135
+ if (initWebSockets) {
136
+ this.initializeWebSockets();
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Initialize WebSocket clients for trades and deltas
142
+ *
143
+ * This method can be called manually if websockets were not initialized during construction
144
+ * (i.e., if initWebSockets was set to false in the constructor).
145
+ *
146
+ * It initializes the trades and deltas WebSocket clients. The user WebSocket client
147
+ * is initialized on demand when needed.
148
+ *
149
+ * @param tradesSubscriptions - Optional array of trades subscriptions to initialize with
150
+ * @param deltasSubscriptions - Optional array of deltas subscriptions to initialize with
151
+ */
152
+ public initializeWebSockets(
153
+ tradesSubscriptions?: string[],
154
+ deltasSubscriptions?: string[],
155
+ ): void {
156
+ // Use provided subscriptions or fall back to stored ones
157
+ const trades = tradesSubscriptions || this.tradesSubscriptions;
158
+ const deltas = deltasSubscriptions || this.deltasSubscriptions;
159
+
160
+ // Initialize WebSocket clients for each endpoint with subscriptions
161
+ this.tradesWs = core.initWebSocketClient(
162
+ this.webServerUrl,
163
+ 'trades',
164
+ trades,
165
+ );
166
+ this.deltasWs = core.initWebSocketClient(
167
+ this.webServerUrl,
168
+ 'deltas',
169
+ deltas,
170
+ );
171
+ }
172
+
173
+ /**
174
+ * Get the current timestamp from the Nord server
175
+ *
176
+ * @returns Current timestamp as a bigint
177
+ * @throws {NordError} If the request fails
178
+ */
179
+ async getTimestamp(): Promise<bigint> {
180
+ return core.getTimestamp(this.webServerUrl);
181
+ }
182
+
183
+ /**
184
+ * Get the next action nonce from the Nord server
185
+ *
186
+ * @returns Next action nonce
187
+ * @throws {NordError} If the request fails
188
+ */
189
+ async getActionNonce(): Promise<number> {
190
+ return core.getActionNonce(this.webServerUrl);
191
+ }
192
+
193
+ /**
194
+ * Fetch information about Nord markets and tokens
195
+ *
196
+ * @throws {NordError} If the request fails
197
+ */
198
+ async fetchNordInfo(): Promise<void> {
199
+ try {
200
+ const info = await core.getInfo(this.webServerUrl);
201
+ this.markets = info.markets;
202
+ this.tokens = info.tokens;
203
+
204
+ // Populate the symbolToMarketId map
205
+ this.symbolToMarketId.clear();
206
+ info.markets.forEach((market) => {
207
+ this.symbolToMarketId.set(market.symbol, market.marketId);
208
+ });
209
+ } catch (error) {
210
+ throw new NordError('Failed to fetch Nord info', { cause: error });
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Initialize a new Nord client
216
+ *
217
+ * @param nordConfig - Configuration options for the Nord client
218
+ * @param nordConfig.webServerUrl - Base URL for the Nord web server
219
+ * @param nordConfig.solanaProgramId - Solana program ID
220
+ * @param nordConfig.solanaUrl - Solana cluster URL
221
+ * @param nordConfig.initWebSockets - Whether to initialize WebSockets on creation, defaults to true
222
+ * @param nordConfig.tradesSubscriptions - Optional array of trades subscriptions (e.g., ["trades@BTCUSDC"])
223
+ * @param nordConfig.deltasSubscriptions - Optional array of deltas subscriptions (e.g., ["deltas@BTCUSDC"])
224
+ * @returns Initialized Nord client
225
+ * @throws {NordError} If initialization fails
226
+ */
227
+ public static async initNord(nordConfig: NordConfig): Promise<Nord> {
228
+ const nord = new Nord(nordConfig);
229
+ await nord.fetchNordInfo();
230
+ return nord;
231
+ }
232
+
233
+ /**
234
+ * Get market statistics
235
+ *
236
+ * @returns Market statistics response
237
+ * @throws {NordError} If the request fails
238
+ */
239
+ public async marketsStats(): Promise<MarketsStatsResponse> {
240
+ return market.marketsStats(this.webServerUrl);
241
+ }
242
+
243
+ /**
244
+ * Query a specific block
245
+ *
246
+ * @param query - Block query parameters
247
+ * @returns Block response
248
+ * @throws {NordError} If the request fails
249
+ */
250
+ async queryBlock(query: BlockQuery): Promise<BlockResponse> {
251
+ return queries.queryBlock(this.webServerUrl, query);
252
+ }
253
+
254
+ /**
255
+ * Query the last N blocks
256
+ *
257
+ * @returns Block response for the last N blocks
258
+ * @throws {NordError} If the request fails
259
+ */
260
+ async queryLastNBlocks(): Promise<BlockResponse> {
261
+ return queries.queryLastNBlocks(this.webServerUrl);
262
+ }
263
+
264
+ /**
265
+ * Query recent blocks
266
+ *
267
+ * @param last_n - Number of recent blocks to query
268
+ * @returns Block summary response
269
+ * @throws {NordError} If the request fails
270
+ */
271
+ async queryRecentBlocks(last_n: number): Promise<BlockSummaryResponse> {
272
+ return queries.queryRecentBlocks(this.webServerUrl, last_n);
273
+ }
274
+
275
+ /**
276
+ * Query a specific action
277
+ *
278
+ * @param query - Action query parameters
279
+ * @returns Action response
280
+ * @throws {NordError} If the request fails
281
+ */
282
+ async queryAction(query: ActionQuery): Promise<ActionResponse> {
283
+ return queries.queryAction(this.webServerUrl, query);
284
+ }
285
+
286
+ /**
287
+ * Query recent actions
288
+ *
289
+ * @param last_n - Number of recent actions to query
290
+ * @returns Actions response
291
+ * @throws {NordError} If the request fails
292
+ */
293
+ async queryRecentActions(last_n: number): Promise<ActionsResponse> {
294
+ return queries.queryRecentActions(this.webServerUrl, last_n);
295
+ }
296
+
297
+ /**
298
+ * Fetch aggregate metrics from the Nord API
299
+ *
300
+ * @param txPeakTpsPeriod - Period for peak TPS calculation
301
+ * @param txPeakTpsPeriodUnit - Unit for peak TPS period
302
+ * @returns Aggregate metrics
303
+ * @throws {NordError} If the request fails
304
+ */
305
+ async aggregateMetrics(
306
+ txPeakTpsPeriod = 1,
307
+ txPeakTpsPeriodUnit: PeakTpsPeriodUnit = PeakTpsPeriodUnit.Day,
308
+ ): Promise<AggregateMetrics> {
309
+ return metrics.aggregateMetrics(
310
+ this.webServerUrl,
311
+ txPeakTpsPeriod,
312
+ txPeakTpsPeriodUnit,
313
+ );
314
+ }
315
+
316
+ /**
317
+ * Get current transactions per second
318
+ *
319
+ * @param period - Time period for the query
320
+ * @returns Current TPS value
321
+ * @throws {NordError} If the request fails
322
+ */
323
+ async getCurrentTps(period: string = '1m') {
324
+ return metrics.getCurrentTps(this.webServerUrl, period);
325
+ }
326
+
327
+ /**
328
+ * Get peak transactions per second
329
+ *
330
+ * @param period - Time period for the query
331
+ * @returns Peak TPS value
332
+ * @throws {NordError} If the request fails
333
+ */
334
+ async getPeakTps(period: string = '24h') {
335
+ return metrics.getPeakTps(this.webServerUrl, period);
336
+ }
337
+
338
+ /**
339
+ * Get median transaction latency
340
+ *
341
+ * @param period - Time period for the query
342
+ * @returns Median latency in milliseconds
343
+ * @throws {NordError} If the request fails
344
+ */
345
+ async getMedianLatency(period: string = '1m') {
346
+ return metrics.getMedianLatency(this.webServerUrl, period);
347
+ }
348
+
349
+ /**
350
+ * Get total transaction count
351
+ *
352
+ * @returns Total transaction count
353
+ * @throws {NordError} If the request fails
354
+ */
355
+ async getTotalTransactions() {
356
+ return metrics.getTotalTransactions(this.webServerUrl);
357
+ }
358
+
359
+ /**
360
+ * Query a block from Rollman
361
+ *
362
+ * @param query - Block query parameters
363
+ * @returns Rollman block response
364
+ * @throws {NordError} If the request fails
365
+ */
366
+ async blockQueryRollman(query: BlockQuery): Promise<RollmanBlockResponse> {
367
+ return queries.blockQueryRollman(this.webServerUrl, query);
368
+ }
369
+
370
+ /**
371
+ * Query block summaries from Rollman
372
+ *
373
+ * @param last_n - Number of recent blocks to query
374
+ * @returns Block summary response
375
+ * @throws {NordError} If the request fails
376
+ */
377
+ async blockSummaryQueryRollman(
378
+ last_n: number,
379
+ ): Promise<BlockSummaryResponse> {
380
+ return queries.blockSummaryQueryRollman(this.webServerUrl, last_n);
381
+ }
382
+
383
+ /**
384
+ * Query an action from Rollman
385
+ *
386
+ * @param query - Action query parameters
387
+ * @returns Rollman action response
388
+ * @throws {NordError} If the request fails
389
+ */
390
+ async actionQueryRollman(query: ActionQuery): Promise<RollmanActionResponse> {
391
+ return queries.actionQueryRollman(this.webServerUrl, query);
392
+ }
393
+
394
+ /**
395
+ * Query actions from Rollman
396
+ *
397
+ * @param last_n - Number of recent actions to query
398
+ * @returns Rollman actions response
399
+ * @throws {NordError} If the request fails
400
+ */
401
+ async actionsQueryRollman(last_n: number): Promise<RollmanActionsResponse> {
402
+ return queries.actionsQueryRollman(this.webServerUrl, last_n);
403
+ }
404
+
405
+ /**
406
+ * Query Prometheus metrics
407
+ *
408
+ * @param params - Prometheus query parameters
409
+ * @returns Query result as a number
410
+ * @throws {NordError} If the request fails
411
+ */
412
+ async queryPrometheus(params: string): Promise<number> {
413
+ return metrics.queryPrometheus(this.webServerUrl, params);
414
+ }
415
+
416
+ /**
417
+ * Get the trades WebSocket client (default)
418
+ * If not already initialized, it will be created
419
+ *
420
+ * @returns WebSocket client for trades
421
+ */
422
+ public getWebSocketClient(): NordWebSocketClient {
423
+ if (!this.tradesWs) {
424
+ this.initializeWebSockets();
425
+ }
426
+ return this.tradesWs!;
427
+ }
428
+
429
+ /**
430
+ * Get the trades WebSocket client
431
+ * If not already initialized, it will be created
432
+ *
433
+ * @returns WebSocket client for trades
434
+ */
435
+ public getTradesWebSocketClient(): NordWebSocketClient {
436
+ if (!this.tradesWs) {
437
+ this.initializeWebSockets();
438
+ }
439
+ return this.tradesWs!;
440
+ }
441
+
442
+ /**
443
+ * Get the deltas WebSocket client
444
+ * If not already initialized, it will be created
445
+ *
446
+ * @returns WebSocket client for orderbook deltas
447
+ */
448
+ public getDeltasWebSocketClient(): NordWebSocketClient {
449
+ if (!this.deltasWs) {
450
+ this.initializeWebSockets();
451
+ }
452
+ return this.deltasWs!;
453
+ }
454
+
455
+ /**
456
+ * Get the user WebSocket client
457
+ * If not already initialized, it will be created
458
+ *
459
+ * @returns WebSocket client for user updates
460
+ */
461
+ public getUserWebSocketClient(): NordWebSocketClient {
462
+ if (!this.userWs) {
463
+ // Initialize user WebSocket client on demand
464
+ this.userWs = core.initWebSocketClient(this.webServerUrl, 'user');
465
+ return this.userWs;
466
+ }
467
+ return this.userWs;
468
+ }
469
+
470
+ /**
471
+ * Subscribe to orderbook updates for a market
472
+ *
473
+ * @param symbol - Market symbol
474
+ * @returns Orderbook subscription
475
+ */
476
+ public subscribeOrderbook(symbol: string): OrderbookSubscription {
477
+ const subscription = new EventEmitter() as OrderbookSubscription;
478
+
479
+ const handleDelta = (update: {
480
+ symbol: string;
481
+ bids: [number, number][];
482
+ asks: [number, number][];
483
+ }) => {
484
+ if (update.symbol !== symbol) {
485
+ return;
486
+ }
487
+
488
+ subscription.emit('message', update);
489
+ };
490
+
491
+ // Initialize deltas websocket if it doesn't exist
492
+ if (!this.deltasWs) {
493
+ this.initializeWebSockets();
494
+ }
495
+
496
+ this.deltasWs!.on('delta', handleDelta);
497
+ this.deltasWs!.subscribe([`deltas@${symbol}`]);
498
+
499
+ subscription.close = () => {
500
+ this.deltasWs!.unsubscribe([`deltas@${symbol}`]);
501
+ this.deltasWs!.removeListener('delta', handleDelta);
502
+ subscription.removeAllListeners();
503
+ };
504
+
505
+ return subscription;
506
+ }
507
+
508
+ /**
509
+ * Subscribe to trade updates for a market
510
+ *
511
+ * @param symbol - Market symbol
512
+ * @returns Trade subscription
513
+ */
514
+ public subscribeTrades(symbol: string): TradeSubscription {
515
+ const subscription = new EventEmitter() as TradeSubscription;
516
+
517
+ const handleTrade = (update: {
518
+ symbol: string;
519
+ trades: Array<{
520
+ price: number;
521
+ size: number;
522
+ side: string;
523
+ timestamp: number;
524
+ }>;
525
+ }) => {
526
+ if (update.symbol !== symbol) {
527
+ return;
528
+ }
529
+
530
+ subscription.emit('message', update);
531
+ };
532
+
533
+ // Initialize trades websocket if it doesn't exist
534
+ if (!this.tradesWs) {
535
+ this.initializeWebSockets();
536
+ }
537
+
538
+ this.tradesWs!.on('trade', handleTrade);
539
+ this.tradesWs!.subscribe([`trades@${symbol}`]);
540
+
541
+ subscription.close = () => {
542
+ this.tradesWs!.unsubscribe([`trades@${symbol}`]);
543
+ this.tradesWs!.removeListener('trade', handleTrade);
544
+ subscription.removeAllListeners();
545
+ };
546
+
547
+ return subscription;
548
+ }
549
+
550
+ /**
551
+ * Get trades for a market
552
+ *
553
+ * @param query - Trades query parameters
554
+ * @returns Trades response
555
+ * @throws {NordError} If the request fails
556
+ */
557
+ public async getTrades(query: TradesQuery): Promise<TradesResponse> {
558
+ return market.getTrades(this.webServerUrl, query);
559
+ }
560
+
561
+ /**
562
+ * Get user account IDs
563
+ *
564
+ * @param query - User account IDs query parameters
565
+ * @returns User account IDs response
566
+ * @throws {NordError} If the request fails
567
+ */
568
+ public async getUserAccountIds(
569
+ query: UserAccountIdsQuery,
570
+ ): Promise<UserAccountIdsResponse> {
571
+ return market.getUserAccountIds(this.webServerUrl, query);
572
+ }
573
+
574
+ /**
575
+ * Get orderbook for a market
576
+ *
577
+ * @param query - Orderbook query parameters (either market_id or symbol must be provided)
578
+ * @returns Orderbook response
579
+ * @throws {NordError} If the request fails or if the market symbol is unknown
580
+ * @remarks It's recommended to initialize the Nord client using the static `initNord` method
581
+ * to ensure market information is properly loaded before calling this method.
582
+ */
583
+ public async getOrderbook(query: OrderbookQuery): Promise<OrderbookResponse> {
584
+ // If only symbol is provided, convert it to market_id
585
+ if (query.symbol && query.market_id === undefined) {
586
+ // If the map is empty, try to fetch market information first
587
+ if (this.symbolToMarketId.size === 0) {
588
+ await this.fetchNordInfo();
589
+ }
590
+
591
+ const marketId = this.symbolToMarketId.get(query.symbol);
592
+ if (marketId === undefined) {
593
+ throw new NordError(`Unknown market symbol: ${query.symbol}`);
594
+ }
595
+
596
+ query = { market_id: marketId };
597
+ }
598
+
599
+ // Ensure market_id is provided
600
+ if (query.market_id === undefined) {
601
+ throw new NordError('market_id is required for orderbook query');
602
+ }
603
+
604
+ return market.getOrderbook(this.webServerUrl, query);
605
+ }
606
+
607
+ /**
608
+ * Get information about the Nord server
609
+ *
610
+ * @returns Information about markets and tokens
611
+ * @throws {NordError} If the request fails
612
+ */
613
+ public async getInfo(): Promise<Info> {
614
+ return core.getInfo(this.webServerUrl);
615
+ }
616
+
617
+ /**
618
+ * Get account information
619
+ *
620
+ * @param accountId - Account ID to get information for
621
+ * @returns Account information
622
+ * @throws {NordError} If the request fails
623
+ */
624
+ public async getAccount(accountId: number): Promise<Account> {
625
+ return core.getAccount(this.webServerUrl, accountId);
626
+ }
627
+
628
+ /**
629
+ * Get market statistics (alias for marketsStats for backward compatibility)
630
+ *
631
+ * @deprecated Use marketsStats instead
632
+ * @returns Market statistics response
633
+ */
634
+ public async getMarketStats(): Promise<MarketsStatsResponse> {
635
+ return this.marketsStats();
636
+ }
637
+
638
+ /**
639
+ * Check if an account exists for the given address
640
+ *
641
+ * @param address - The public key address to check
642
+ * @returns True if the account exists, false otherwise
643
+ */
644
+ public async accountExists(address: string): Promise<boolean> {
645
+ try {
646
+ await market.getUserAccountIds(this.webServerUrl, { pubkey: address });
647
+ return true;
648
+ } catch (error) {
649
+ return false;
650
+ }
651
+ }
652
+ }