@n1xyz/nord-ts 0.1.6 → 0.1.8

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 (85) hide show
  1. package/dist/actions.d.ts +57 -0
  2. package/dist/actions.js +186 -0
  3. package/dist/bundle.js +79181 -0
  4. package/dist/{nord/client → client}/Nord.d.ts +90 -107
  5. package/dist/{nord/client → client}/Nord.js +157 -218
  6. package/dist/{nord/client → client}/NordAdmin.d.ts +68 -102
  7. package/dist/{nord/client → client}/NordAdmin.js +109 -140
  8. package/dist/{nord/client → client}/NordUser.d.ts +86 -98
  9. package/dist/{nord/client → client}/NordUser.js +204 -271
  10. package/dist/const.js +5 -8
  11. package/dist/{nord/utils/NordError.js → error.js} +7 -5
  12. package/dist/gen/nord_pb.js +88 -92
  13. package/dist/gen/openapi.d.ts +39 -0
  14. package/dist/gen/openapi.js +1 -2
  15. package/dist/index.d.ts +6 -1
  16. package/dist/index.js +10 -21
  17. package/dist/types.d.ts +5 -50
  18. package/dist/types.js +21 -83
  19. package/dist/utils.d.ts +8 -11
  20. package/dist/utils.js +55 -90
  21. package/dist/websocket/NordWebSocketClient.js +12 -17
  22. package/dist/{nord/models → websocket}/Subscriber.d.ts +1 -1
  23. package/dist/{nord/models → websocket}/Subscriber.js +6 -7
  24. package/dist/websocket/events.js +1 -2
  25. package/dist/websocket/index.d.ts +19 -2
  26. package/dist/websocket/index.js +80 -5
  27. package/package.json +2 -3
  28. package/dist/api/client.d.ts +0 -14
  29. package/dist/api/client.js +0 -45
  30. package/dist/bridge/client.d.ts +0 -151
  31. package/dist/bridge/client.js +0 -434
  32. package/dist/bridge/const.d.ts +0 -23
  33. package/dist/bridge/const.js +0 -47
  34. package/dist/bridge/index.d.ts +0 -4
  35. package/dist/bridge/index.js +0 -23
  36. package/dist/bridge/types.d.ts +0 -120
  37. package/dist/bridge/types.js +0 -18
  38. package/dist/bridge/utils.d.ts +0 -64
  39. package/dist/bridge/utils.js +0 -131
  40. package/dist/gen/common.d.ts +0 -68
  41. package/dist/gen/common.js +0 -215
  42. package/dist/gen/nord.d.ts +0 -882
  43. package/dist/gen/nord.js +0 -6520
  44. package/dist/idl/bridge.d.ts +0 -569
  45. package/dist/idl/bridge.js +0 -8
  46. package/dist/idl/bridge.json +0 -1506
  47. package/dist/idl/index.d.ts +0 -607
  48. package/dist/idl/index.js +0 -8
  49. package/dist/nord/api/actions.d.ts +0 -126
  50. package/dist/nord/api/actions.js +0 -397
  51. package/dist/nord/api/core.d.ts +0 -16
  52. package/dist/nord/api/core.js +0 -81
  53. package/dist/nord/api/market.d.ts +0 -36
  54. package/dist/nord/api/market.js +0 -96
  55. package/dist/nord/api/metrics.d.ts +0 -67
  56. package/dist/nord/api/metrics.js +0 -229
  57. package/dist/nord/api/queries.d.ts +0 -46
  58. package/dist/nord/api/queries.js +0 -109
  59. package/dist/nord/api/triggers.d.ts +0 -7
  60. package/dist/nord/api/triggers.js +0 -38
  61. package/dist/nord/client/NordClient.d.ts +0 -33
  62. package/dist/nord/client/NordClient.js +0 -45
  63. package/dist/nord/index.d.ts +0 -11
  64. package/dist/nord/index.js +0 -36
  65. package/src/const.ts +0 -34
  66. package/src/gen/.gitkeep +0 -0
  67. package/src/gen/nord_pb.ts +0 -5053
  68. package/src/gen/openapi.ts +0 -2864
  69. package/src/index.ts +0 -5
  70. package/src/nord/api/actions.ts +0 -648
  71. package/src/nord/api/core.ts +0 -96
  72. package/src/nord/api/metrics.ts +0 -269
  73. package/src/nord/client/Nord.ts +0 -937
  74. package/src/nord/client/NordAdmin.ts +0 -514
  75. package/src/nord/client/NordClient.ts +0 -79
  76. package/src/nord/client/NordUser.ts +0 -1211
  77. package/src/nord/index.ts +0 -25
  78. package/src/nord/models/Subscriber.ts +0 -56
  79. package/src/nord/utils/NordError.ts +0 -76
  80. package/src/types.ts +0 -377
  81. package/src/utils.ts +0 -269
  82. package/src/websocket/NordWebSocketClient.ts +0 -316
  83. package/src/websocket/events.ts +0 -31
  84. package/src/websocket/index.ts +0 -2
  85. /package/dist/{nord/utils/NordError.d.ts → error.d.ts} +0 -0
@@ -1,937 +0,0 @@
1
- import { ProtonClient } from "@n1xyz/proton";
2
- import { Connection, PublicKey } from "@solana/web3.js";
3
- import { EventEmitter } from "events";
4
- import createClient, { Client, FetchOptions } from "openapi-fetch";
5
- import * as proto from "../../gen/nord_pb";
6
- import type { paths } from "../../gen/openapi.ts";
7
- import {
8
- Account,
9
- AccountPnlPage,
10
- AccountPnlQuery,
11
- ActionResponse,
12
- AggregateMetrics,
13
- MarketsInfo,
14
- Market,
15
- MarketStats,
16
- NordConfig,
17
- OrderbookQuery,
18
- OrderbookResponse,
19
- FeeTierConfig,
20
- PeakTpsPeriodUnit,
21
- SubscriptionPattern,
22
- Token,
23
- TradesResponse,
24
- User,
25
- AccountTriggerInfo,
26
- HistoryTriggerQuery,
27
- TriggerHistoryPage,
28
- FeeTierId,
29
- AccountFeeTierPage,
30
- PageResultStringOrderInfo,
31
- PageResultStringTrade,
32
- OrderInfoFromApi,
33
- TokenStats,
34
- FillRole,
35
- } from "../../types";
36
- import * as utils from "../../utils";
37
- import { NordWebSocketClient } from "../../websocket/index";
38
- import * as core from "../api/core";
39
- import * as metrics from "../api/metrics";
40
- import { OrderbookSubscription, TradeSubscription } from "../models/Subscriber";
41
- import { NordError } from "../utils/NordError";
42
-
43
- /**
44
- * User subscription interface
45
- */
46
- export interface UserSubscription extends EventEmitter {
47
- close: () => void;
48
- }
49
-
50
- /**
51
- * WebSocket subscription options interface
52
- */
53
- export interface WebSocketSubscriptionOptions {
54
- /** Market symbols to subscribe to for trade updates */
55
- trades?: string[];
56
- /** Market symbols to subscribe to for orderbook delta updates */
57
- deltas?: string[];
58
- /** Account IDs to subscribe to for account updates */
59
- accounts?: number[];
60
- }
61
-
62
- /**
63
- * Main Nord client class for interacting with the Nord API
64
- */
65
- export class Nord {
66
- /** Base URL for the Nord web server */
67
- public readonly webServerUrl: string;
68
-
69
- /** Solana RPC URL */
70
- public readonly solanaUrl: string;
71
-
72
- /** Available markets */
73
- public markets: Market[] = [];
74
-
75
- /** Available tokens */
76
- public tokens: Token[] = [];
77
-
78
- /** Map of symbol to market_id */
79
- private symbolToMarketId: Map<string, number> = new Map();
80
-
81
- /** Proton client for proton related operations */
82
- public protonClient: ProtonClient;
83
-
84
- /** HTTP client for Nord operations */
85
- private httpClient: Client<paths>;
86
-
87
- /**
88
- * Create a new Nord client
89
- *
90
- * @param config - Configuration options for the Nord client
91
- * @param config.webServerUrl - Base URL for the Nord web server
92
- * @param config.solanaUrl - Solana cluster URL
93
- * @throws {Error} If required configuration is missing
94
- */
95
- private constructor({
96
- solanaUrl,
97
- webServerUrl,
98
- protonClient,
99
- }: Readonly<{
100
- solanaUrl: string;
101
- webServerUrl: string;
102
- protonClient: ProtonClient;
103
- }>) {
104
- this.webServerUrl = webServerUrl;
105
- this.solanaUrl = solanaUrl;
106
- this.protonClient = protonClient;
107
- this.httpClient = createClient<paths>({ baseUrl: webServerUrl });
108
- }
109
-
110
- /**
111
- * Create a WebSocket client with specific subscriptions
112
- *
113
- * @param options - Subscription options that specify which data streams to subscribe to
114
- * @returns A new WebSocket client with the requested subscriptions
115
- * @throws {NordError} If invalid subscription options are provided
116
- *
117
- * @example
118
- * // Create a client for trades and deltas from one market and an account
119
- * const wsClient = nord.createWebSocketClient({
120
- * trades: ["BTCUSDC"],
121
- * deltas: ["BTCUSDC"],
122
- * accounts: [123]
123
- * });
124
- *
125
- * @example
126
- * // Create a client for trades from multiple markets
127
- * const tradesClient = nord.createWebSocketClient({
128
- * trades: ["BTCUSDC", "ETHUSDC"]
129
- * });
130
- */
131
- public createWebSocketClient(
132
- options: WebSocketSubscriptionOptions,
133
- ): NordWebSocketClient {
134
- const subscriptions: SubscriptionPattern[] = [];
135
-
136
- // Add trade subscriptions
137
- if (options.trades && options.trades.length > 0) {
138
- options.trades.forEach((symbol) => {
139
- subscriptions.push(`trades@${symbol}` as SubscriptionPattern);
140
- });
141
- }
142
-
143
- // Add delta subscriptions
144
- if (options.deltas && options.deltas.length > 0) {
145
- options.deltas.forEach((symbol) => {
146
- subscriptions.push(`deltas@${symbol}` as SubscriptionPattern);
147
- });
148
- }
149
-
150
- // Add account subscriptions
151
- if (options.accounts && options.accounts.length > 0) {
152
- options.accounts.forEach((accountId) => {
153
- if (isNaN(accountId) || accountId <= 0) {
154
- throw new NordError(
155
- `Invalid account ID: ${accountId}. Must be a positive number.`,
156
- );
157
- }
158
- subscriptions.push(`account@${accountId}` as SubscriptionPattern);
159
- });
160
- }
161
-
162
- // Validate that at least one subscription was provided
163
- if (subscriptions.length === 0) {
164
- throw new NordError("At least one subscription must be provided");
165
- }
166
-
167
- // Create and return a new WebSocket client
168
- return core.initWebSocketClient(this.webServerUrl, subscriptions);
169
- }
170
-
171
- private async GET<P extends keyof paths & string>(
172
- path: P,
173
- options: FetchOptions<paths[P]["get"]>,
174
- ) {
175
- const r = await this.httpClient.GET(path, options);
176
- if (r.error) {
177
- throw new NordError(`failed to GET ${path}`, { cause: r.error });
178
- }
179
- if (r.data === undefined) {
180
- // this should never happen, but the type checker seems unhappy.
181
- // if we catch this we'll need to debug accordingly.
182
- throw new NordError("internal assertion violation", { cause: r });
183
- }
184
- return r.data;
185
- }
186
-
187
- /**
188
- * Get the current timestamp from the Nord server
189
- *
190
- * @returns Current timestamp as a bigint
191
- * @throws {NordError} If the request fails
192
- */
193
- async getTimestamp(): Promise<bigint> {
194
- return BigInt(await this.GET("/timestamp", {}));
195
- }
196
-
197
- /**
198
- * Get the last event nonce from the Nord server
199
- *
200
- * @returns Next action nonce
201
- * @throws {NordError} If the request fails
202
- */
203
- async getActionNonce(): Promise<number> {
204
- return await this.GET("/event/last-acked-nonce", {});
205
- }
206
-
207
- /**
208
- * Fetch information about Nord markets and tokens
209
- *
210
- * @throws {NordError} If the request fails
211
- */
212
- async fetchNordInfo(): Promise<void> {
213
- try {
214
- const info = await this.GET("/info", {});
215
- this.markets = info.markets;
216
- this.tokens = info.tokens;
217
-
218
- // Populate the symbolToMarketId map
219
- this.symbolToMarketId.clear();
220
- info.markets.forEach((market) => {
221
- this.symbolToMarketId.set(market.symbol, market.marketId);
222
- });
223
- } catch (error) {
224
- throw new NordError("Failed to fetch Nord info", { cause: error });
225
- }
226
- }
227
-
228
- /**
229
- * Initialize a new Nord client
230
- *
231
- * @param nordConfig - Configuration options for the Nord client
232
- * @param nordConfig.webServerUrl - Base URL for the Nord web server
233
- * @param nordConfig.app - App address
234
- * @param nordConfig.solanaUrl - Solana cluster URL
235
- * @returns Initialized Nord client
236
- * @throws {NordError} If initialization fails
237
- */
238
- public static async initNord({
239
- app,
240
- solanaUrl,
241
- webServerUrl,
242
- protonUrl,
243
- }: Readonly<NordConfig>): Promise<Nord> {
244
- // TODO: we should parametrize the connectionn not have it done here.
245
- // this is a dogshit api, only here to be compatible with the shitty
246
- // vibecoded code and not break zero one team's workflow.
247
- const connection = new Connection(solanaUrl, { commitment: "confirmed" });
248
- const protonClient = await ProtonClient.init({
249
- protonUrl: protonUrl ?? webServerUrl,
250
- app: new PublicKey(app),
251
- solConn: connection,
252
- });
253
- const nord = new Nord({
254
- protonClient,
255
- solanaUrl,
256
- webServerUrl,
257
- });
258
- await nord.init();
259
- return nord;
260
- }
261
-
262
- /**
263
- * Initialize the Nord client
264
- * @private
265
- */
266
- private async init(): Promise<void> {
267
- await this.fetchNordInfo();
268
- }
269
-
270
- /**
271
- * Query a specific action
272
- *
273
- * @param query - Action query parameters
274
- * @returns Action response
275
- * @throws {NordError} If the request fails
276
- */
277
- async queryAction({
278
- action_id,
279
- }: {
280
- action_id: number;
281
- }): Promise<ActionResponse | null> {
282
- return (
283
- (
284
- await this.queryRecentActions({
285
- from: action_id,
286
- to: action_id,
287
- })
288
- )[0] ?? null
289
- );
290
- }
291
-
292
- /**
293
- * Query recent actions
294
- *
295
- * @param from - Starting action index
296
- * @param to - Ending action index
297
- * @returns Actions response
298
- * @throws {NordError} If the request fails
299
- */
300
- async queryRecentActions(query: {
301
- from: number;
302
- to: number;
303
- }): Promise<ActionResponse[]> {
304
- const xs = await this.GET("/action", {
305
- params: {
306
- query,
307
- },
308
- });
309
- return xs.map((x) => ({
310
- actionId: x.actionId,
311
- action: utils.decodeLengthDelimited(
312
- Buffer.from(x.payload, "base64"),
313
- proto.ActionSchema,
314
- ),
315
- physicalExecTime: new Date(x.physicalTime),
316
- }));
317
- }
318
-
319
- /**
320
- * Get the last action ID
321
- *
322
- * @returns Last action ID
323
- * @throws {NordError} If the request fails
324
- */
325
- async getLastActionId(): Promise<number> {
326
- return await this.GET("/action/last-executed-id", {});
327
- }
328
-
329
- /**
330
- * Fetch aggregate metrics from the Nord API
331
- *
332
- * @param txPeakTpsPeriod - Period for peak TPS calculation
333
- * @param txPeakTpsPeriodUnit - Unit for peak TPS period
334
- * @returns Aggregate metrics
335
- * @throws {NordError} If the request fails
336
- */
337
- async aggregateMetrics(
338
- txPeakTpsPeriod = 1,
339
- txPeakTpsPeriodUnit: PeakTpsPeriodUnit = PeakTpsPeriodUnit.Day,
340
- ): Promise<AggregateMetrics> {
341
- return metrics.aggregateMetrics(
342
- this.webServerUrl,
343
- txPeakTpsPeriod,
344
- txPeakTpsPeriodUnit,
345
- );
346
- }
347
-
348
- /**
349
- * Get current transactions per second
350
- *
351
- * @param period - Time period for the query
352
- * @returns Current TPS value
353
- * @throws {NordError} If the request fails
354
- */
355
- async getCurrentTps(period: string = "1m") {
356
- return metrics.getCurrentTps(this.webServerUrl, period);
357
- }
358
-
359
- /**
360
- * Get peak transactions per second
361
- *
362
- * @param period - Time period for the query
363
- * @returns Peak TPS value
364
- * @throws {NordError} If the request fails
365
- */
366
- async getPeakTps(period: string = "24h") {
367
- return metrics.getPeakTps(this.webServerUrl, period);
368
- }
369
-
370
- /**
371
- * Get median transaction latency
372
- *
373
- * @param period - Time period for the query
374
- * @returns Median latency in milliseconds
375
- * @throws {NordError} If the request fails
376
- */
377
- async getMedianLatency(period: string = "1m") {
378
- return metrics.getMedianLatency(this.webServerUrl, period);
379
- }
380
-
381
- /**
382
- * Get total transaction count
383
- *
384
- * @returns Total transaction count
385
- * @throws {NordError} If the request fails
386
- */
387
- async getTotalTransactions() {
388
- return metrics.getTotalTransactions(this.webServerUrl);
389
- }
390
-
391
- /**
392
- * Query Prometheus metrics
393
- *
394
- * @param params - Prometheus query parameters
395
- * @returns Query result as a number
396
- * @throws {NordError} If the request fails
397
- */
398
- async queryPrometheus(params: string): Promise<number> {
399
- return metrics.queryPrometheus(this.webServerUrl, params);
400
- }
401
-
402
- /**
403
- * Subscribe to orderbook updates for a market
404
- *
405
- * @param symbol - Market symbol
406
- * @returns Orderbook subscription
407
- * @throws {NordError} If symbol is invalid
408
- */
409
- public subscribeOrderbook(symbol: string): OrderbookSubscription {
410
- if (!symbol || typeof symbol !== "string") {
411
- throw new NordError("Invalid market symbol");
412
- }
413
-
414
- const subscription = new EventEmitter() as OrderbookSubscription;
415
- const wsClient = this.createWebSocketClient({
416
- deltas: [symbol],
417
- });
418
-
419
- const handleDelta = (update: {
420
- symbol: string;
421
- bids: [number, number][];
422
- asks: [number, number][];
423
- }) => {
424
- if (update.symbol !== symbol) {
425
- return;
426
- }
427
-
428
- subscription.emit("message", update);
429
- };
430
-
431
- wsClient.on("delta", handleDelta);
432
-
433
- subscription.close = () => {
434
- wsClient.removeListener("delta", handleDelta);
435
- subscription.removeAllListeners();
436
- };
437
-
438
- return subscription;
439
- }
440
-
441
- /**
442
- * Subscribe to trade updates for a market
443
- *
444
- * @param symbol - Market symbol
445
- * @returns Trade subscription
446
- * @throws {NordError} If symbol is invalid
447
- */
448
- public subscribeTrades(symbol: string): TradeSubscription {
449
- if (!symbol || typeof symbol !== "string") {
450
- throw new NordError("Invalid market symbol");
451
- }
452
-
453
- const subscription = new EventEmitter() as TradeSubscription;
454
- const wsClient = this.createWebSocketClient({
455
- trades: [symbol],
456
- });
457
-
458
- const handleTrade = (update: {
459
- symbol: string;
460
- trades: Array<{
461
- price: number;
462
- size: number;
463
- side: string;
464
- timestamp: number;
465
- }>;
466
- }) => {
467
- if (update.symbol !== symbol) {
468
- return;
469
- }
470
-
471
- subscription.emit("message", update);
472
- };
473
-
474
- wsClient.on("trades", handleTrade);
475
-
476
- subscription.close = () => {
477
- wsClient.removeListener("trades", handleTrade);
478
- subscription.removeAllListeners();
479
- };
480
-
481
- return subscription;
482
- }
483
-
484
- /**
485
- * Subscribe to account updates
486
- *
487
- * @param accountId - Account ID to subscribe to
488
- * @returns User subscription
489
- * @throws {NordError} If accountId is invalid
490
- */
491
- public subscribeAccount(accountId: number): UserSubscription {
492
- if (isNaN(accountId) || accountId <= 0) {
493
- throw new NordError("Invalid account ID");
494
- }
495
-
496
- const subscription = new EventEmitter() as UserSubscription;
497
- const wsClient = this.createWebSocketClient({
498
- accounts: [accountId],
499
- });
500
-
501
- const handleAccountUpdate = (update: any) => {
502
- if (update.account_id !== accountId) {
503
- return;
504
- }
505
-
506
- subscription.emit("message", update);
507
- };
508
-
509
- wsClient.on("account", handleAccountUpdate);
510
-
511
- subscription.close = () => {
512
- wsClient.removeListener("account", handleAccountUpdate);
513
- subscription.removeAllListeners();
514
- };
515
-
516
- return subscription;
517
- }
518
-
519
- /**
520
- * Get trades for a market
521
- *
522
- * @param query - Trades query parameters
523
- * @returns Trades response
524
- * @throws {NordError} If the request fails
525
- */
526
- public async getTrades(
527
- query: Readonly<{
528
- marketId?: number;
529
- takerId?: number;
530
- makerId?: number;
531
- takerSide?: "bid" | "ask";
532
- pageSize?: number;
533
- sinceRcf3339?: string;
534
- untilRfc3339?: string;
535
- pageId?: string;
536
- }>,
537
- ): Promise<TradesResponse> {
538
- if (query.sinceRcf3339 && !utils.isRfc3339(query.sinceRcf3339)) {
539
- throw new NordError(`Invalid RFC3339 timestamp: ${query.sinceRcf3339}`);
540
- }
541
- if (query.untilRfc3339 && !utils.isRfc3339(query.untilRfc3339)) {
542
- throw new NordError(`Invalid RFC3339 timestamp: ${query.untilRfc3339}`);
543
- }
544
- return await this.GET("/trades", {
545
- params: {
546
- query: {
547
- takerId: query.takerId,
548
- makerId: query.makerId,
549
- marketId: query.marketId,
550
- pageSize: query.pageSize,
551
- takerSide: query.takerSide,
552
- since: query.sinceRcf3339,
553
- until: query.untilRfc3339,
554
- startInclusive: query.pageId,
555
- },
556
- },
557
- });
558
- }
559
-
560
- /**
561
- * Get user account IDs
562
- *
563
- * @param query - User account IDs query parameters
564
- * @returns User account IDs response
565
- * @throws {NordError} If the request fails
566
- */
567
- public async getUser(query: {
568
- pubkey: string | PublicKey;
569
- }): Promise<User | null> {
570
- const r = await this.httpClient.GET("/user/{pubkey}", {
571
- params: {
572
- path: { pubkey: query.pubkey.toString() },
573
- },
574
- });
575
- if (r.response.status === 404) {
576
- return null;
577
- }
578
- return r.data!;
579
- }
580
-
581
- /**
582
- * Get orderbook for a market
583
- *
584
- * @param query - Orderbook query parameters (either market_id or symbol must be provided)
585
- * @returns Orderbook response
586
- * @throws {NordError} If the request fails or if the market symbol is unknown
587
- * @remarks It's recommended to initialize the Nord client using the static `initNord` method
588
- * to ensure market information is properly loaded before calling this method.
589
- */
590
- public async getOrderbook(query: OrderbookQuery): Promise<OrderbookResponse> {
591
- // If only symbol is provided, convert it to market_id
592
- let marketId: number;
593
- if (query.symbol && query.market_id === undefined) {
594
- // If the map is empty, try to fetch market information first
595
- if (this.symbolToMarketId.size === 0) {
596
- await this.fetchNordInfo();
597
- }
598
-
599
- const id = this.symbolToMarketId.get(query.symbol);
600
- if (id === undefined) {
601
- throw new NordError(`Unknown market symbol: ${query.symbol}`);
602
- }
603
- marketId = id;
604
- } else if (query.market_id !== undefined) {
605
- marketId = query.market_id;
606
- } else {
607
- throw new NordError(
608
- "Either symbol or market_id must be provided for orderbook query",
609
- );
610
- }
611
-
612
- return await this.GET("/market/{market_id}/orderbook", {
613
- params: {
614
- path: { market_id: marketId },
615
- },
616
- });
617
- }
618
-
619
- /**
620
- * Get information about the Nord server
621
- *
622
- * @returns Information about markets and tokens
623
- * @throws {NordError} If the request fails
624
- */
625
- public async getInfo(): Promise<MarketsInfo> {
626
- return await this.GET("/info", {});
627
- }
628
-
629
- /**
630
- * Fetch the current fee tier brackets configured on Nord.
631
- *
632
- * @returns Array of fee tier identifiers paired with their configuration
633
- * @throws {NordError} If the request fails
634
- */
635
- public async getFeeBrackets(): Promise<Array<[FeeTierId, FeeTierConfig]>> {
636
- return await this.GET("/fee/brackets/info", {});
637
- }
638
-
639
- /**
640
- * Retrieve the fee tier assigned to a specific account.
641
- *
642
- * @param accountId - Account identifier to query
643
- * @returns Fee tier details for the requested account
644
- * @throws {NordError} If the request fails
645
- */
646
- public async getAccountFeeTier(accountId: number): Promise<FeeTierId> {
647
- return await this.GET("/account/{account_id}/fee/tier", {
648
- params: {
649
- path: { account_id: accountId },
650
- },
651
- });
652
- }
653
-
654
- /**
655
- * Get account information
656
- *
657
- * @param accountId - Account ID to get information for
658
- * @returns Account information
659
- * @throws {NordError} If the request fails
660
- */
661
- public async getAccount(accountId: number): Promise<Account> {
662
- return await this.GET("/account/{account_id}", {
663
- params: {
664
- path: { account_id: accountId },
665
- },
666
- });
667
- }
668
-
669
- /**
670
- * Get the public key associated with an account id.
671
- *
672
- * @param accountId - Account id to query
673
- * @returns Base58-encoded account public key
674
- * @throws {NordError} If the request fails
675
- */
676
- public async getAccountPubkey(accountId: number): Promise<string> {
677
- return await this.GET("/account/{account_id}/pubkey", {
678
- params: {
679
- path: { account_id: accountId },
680
- },
681
- });
682
- }
683
-
684
- /**
685
- * Get the withdrawal fee charged for an account.
686
- *
687
- * @param accountId - Account id to query
688
- * @returns Withdrawal fee quoted in quote token units
689
- * @throws {NordError} If the request fails
690
- */
691
- public async getAccountWithdrawalFee(accountId: number): Promise<number> {
692
- return await this.GET("/account/{account_id}/fees/withdrawal", {
693
- params: {
694
- path: { account_id: accountId },
695
- },
696
- });
697
- }
698
-
699
- /**
700
- * Get open orders for an account.
701
- *
702
- * @param accountId - Account id to query
703
- * @param query - Optional pagination parameters
704
- * @returns Page of orders keyed by client order id
705
- * @throws {NordError} If the request fails
706
- */
707
- public async getAccountOrders(
708
- accountId: number,
709
- query?: { startInclusive?: string | null; pageSize?: number | null },
710
- ): Promise<PageResultStringOrderInfo> {
711
- return await this.GET("/account/{account_id}/orders", {
712
- params: {
713
- path: { account_id: accountId },
714
- query: {
715
- startInclusive: query?.startInclusive,
716
- pageSize: query?.pageSize,
717
- },
718
- },
719
- });
720
- }
721
-
722
- /**
723
- * List account fee tiers with pagination support.
724
- */
725
- public async getAccountsFeeTiers(query?: {
726
- startInclusive?: number | null;
727
- pageSize?: number | null;
728
- }): Promise<AccountFeeTierPage> {
729
- return await this.GET("/accounts/fee-tiers", {
730
- params: {
731
- query: {
732
- startInclusive: query?.startInclusive ?? undefined,
733
- pageSize: query?.pageSize ?? undefined,
734
- },
735
- },
736
- });
737
- }
738
-
739
- /**
740
- * Get profit and loss history for an account
741
- *
742
- * @param accountId - Account ID to query
743
- * @param query - Optional time and pagination filters
744
- * @returns Page of PnL entries ordered from latest to oldest
745
- * @throws {NordError} If the request fails
746
- */
747
- public async getAccountPnl(
748
- accountId: number,
749
- query?: Partial<AccountPnlQuery>,
750
- ): Promise<AccountPnlPage> {
751
- return await this.GET("/account/{account_id}/pnl", {
752
- params: {
753
- path: { account_id: accountId },
754
- query: {
755
- since: query?.since,
756
- until: query?.until,
757
- startInclusive: query?.startInclusive,
758
- pageSize: query?.pageSize,
759
- },
760
- },
761
- });
762
- }
763
-
764
- /**
765
- * Get market statistics (alias for marketsStats for backward compatibility)
766
- *
767
- * @returns Market statistics response
768
- */
769
- public async getMarketStats({
770
- marketId,
771
- }: {
772
- marketId: number;
773
- }): Promise<MarketStats> {
774
- return await this.GET("/market/{market_id}/stats", {
775
- params: {
776
- path: { market_id: marketId },
777
- },
778
- });
779
- }
780
-
781
- /**
782
- * Fetch the per-market fee quote for an account.
783
- *
784
- * @param params - Market id, fee kind, and account id to quote
785
- * @returns Fee in quote token units (negative means fee is charged)
786
- * @throws {NordError} If the request fails
787
- */
788
- public async getMarketFee({
789
- marketId,
790
- feeKind,
791
- accountId,
792
- }: {
793
- marketId: number;
794
- feeKind: FillRole;
795
- accountId: number;
796
- }): Promise<number> {
797
- return await this.GET("/market/{market_id}/fees/{fee_kind}/{account_id}", {
798
- params: {
799
- path: {
800
- market_id: marketId,
801
- fee_kind: feeKind,
802
- account_id: accountId,
803
- },
804
- },
805
- });
806
- }
807
-
808
- /**
809
- * Fetch token statistics such as index price and oracle metadata.
810
- *
811
- * @param tokenId - Token identifier
812
- * @returns Token stats
813
- * @throws {NordError} If the request fails
814
- */
815
- public async getTokenStats(tokenId: number): Promise<TokenStats> {
816
- return await this.GET("/tokens/{token_id}/stats", {
817
- params: {
818
- path: { token_id: tokenId },
819
- },
820
- });
821
- }
822
-
823
- /**
824
- * Get order summary by order id.
825
- *
826
- * @param orderId - Order identifier
827
- * @returns Order information
828
- * @throws {NordError} If the request fails
829
- */
830
- public async getOrder(orderId: string): Promise<OrderInfoFromApi> {
831
- return await this.GET("/order/{order_id}", {
832
- params: {
833
- path: { order_id: orderId },
834
- },
835
- });
836
- }
837
-
838
- /**
839
- * Get trade history for a specific order.
840
- *
841
- * @param orderId - Order identifier
842
- * @param query - Optional pagination parameters
843
- * @returns Page of trades associated with the order
844
- * @throws {NordError} If the request fails
845
- */
846
- public async getOrderTrades(
847
- orderId: string,
848
- query?: { startInclusive?: string | null; pageSize?: number | null },
849
- ): Promise<PageResultStringTrade> {
850
- return await this.GET("/order/{order_id}/trades", {
851
- params: {
852
- path: { order_id: orderId },
853
- query: {
854
- startInclusive: query?.startInclusive,
855
- pageSize: query?.pageSize,
856
- },
857
- },
858
- });
859
- }
860
-
861
- /**
862
- * Check if an account exists for the given address
863
- *
864
- * @param address - The public key address to check
865
- * @returns True if the account exists, false otherwise
866
- * @deprecated use getUser instead
867
- */
868
- public async accountExists(pubkey: string | PublicKey): Promise<boolean> {
869
- return !!(await this.getUser({ pubkey }));
870
- }
871
-
872
- /**
873
- * Fetch active triggers for an account.
874
- *
875
- * @param params Optional parameters containing an explicit account id.
876
- * @throws {NordError} If no account can be resolved or the request fails.
877
- */
878
- async getAccountTriggers(params?: {
879
- accountId?: number;
880
- }): Promise<AccountTriggerInfo[]> {
881
- const accountId = params?.accountId;
882
-
883
- if (accountId == null) {
884
- throw new NordError(
885
- "Account ID is undefined. Make sure to call updateAccountId() before requesting triggers.",
886
- );
887
- }
888
-
889
- try {
890
- const triggers = await this.GET("/account/{account_id}/triggers", {
891
- params: {
892
- path: { account_id: accountId },
893
- },
894
- });
895
- return triggers ?? [];
896
- } catch (error) {
897
- throw new NordError("Failed to fetch account triggers", { cause: error });
898
- }
899
- }
900
-
901
- /**
902
- * Fetch trigger history for an account.
903
- *
904
- * @param params Optional parameters with account id and history query filters.
905
- * @throws {NordError} If no account can be resolved or the request fails.
906
- */
907
- async getAccountTriggerHistory(
908
- params: HistoryTriggerQuery & { accountId?: number },
909
- ): Promise<TriggerHistoryPage> {
910
- const accountId = params?.accountId;
911
-
912
- if (accountId == null) {
913
- throw new NordError(
914
- "Account ID is undefined. Make sure to call updateAccountId() before requesting trigger history.",
915
- );
916
- }
917
-
918
- const { accountId: _, ...query } = params;
919
- try {
920
- return await this.GET("/account/{account_id}/triggers/history", {
921
- params: {
922
- path: { account_id: accountId },
923
- query: {
924
- since: query.since,
925
- until: query.until,
926
- pageSize: query.pageSize,
927
- startInclusive: query.startInclusive,
928
- },
929
- },
930
- });
931
- } catch (error) {
932
- throw new NordError("Failed to fetch account trigger history", {
933
- cause: error,
934
- });
935
- }
936
- }
937
- }