@n1xyz/nord-ts 0.0.18-8121ed05.0 → 0.0.19

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 (77) hide show
  1. package/.claude/settings.local.json +11 -0
  2. package/.local/qa.ts +77 -0
  3. package/.local/test-atomic.ts +112 -0
  4. package/check.sh +4 -0
  5. package/default.nix +47 -0
  6. package/package.json +20 -27
  7. package/src/index.ts +0 -16
  8. package/src/nord/api/actions.ts +131 -9
  9. package/src/nord/api/core.ts +0 -71
  10. package/src/nord/client/Nord.ts +142 -76
  11. package/src/nord/client/NordUser.ts +171 -50
  12. package/src/nord/index.ts +0 -2
  13. package/src/nord/models/Subscriber.ts +2 -2
  14. package/src/types.ts +55 -216
  15. package/src/utils.ts +6 -42
  16. package/src/websocket/NordWebSocketClient.ts +23 -15
  17. package/src/websocket/index.ts +1 -1
  18. package/tests/utils.spec.ts +1 -34
  19. package/dist/bridge/client.d.ts +0 -151
  20. package/dist/bridge/client.js +0 -434
  21. package/dist/bridge/const.d.ts +0 -23
  22. package/dist/bridge/const.js +0 -47
  23. package/dist/bridge/index.d.ts +0 -4
  24. package/dist/bridge/index.js +0 -23
  25. package/dist/bridge/types.d.ts +0 -120
  26. package/dist/bridge/types.js +0 -18
  27. package/dist/bridge/utils.d.ts +0 -64
  28. package/dist/bridge/utils.js +0 -131
  29. package/dist/const.d.ts +0 -8
  30. package/dist/const.js +0 -30
  31. package/dist/gen/common.d.ts +0 -68
  32. package/dist/gen/common.js +0 -215
  33. package/dist/gen/nord.d.ts +0 -853
  34. package/dist/gen/nord.js +0 -6368
  35. package/dist/idl/bridge.d.ts +0 -569
  36. package/dist/idl/bridge.js +0 -8
  37. package/dist/idl/bridge.json +0 -1506
  38. package/dist/idl/index.d.ts +0 -607
  39. package/dist/idl/index.js +0 -8
  40. package/dist/index.d.ts +0 -6
  41. package/dist/index.js +0 -30
  42. package/dist/nord/api/actions.d.ts +0 -106
  43. package/dist/nord/api/actions.js +0 -256
  44. package/dist/nord/api/core.d.ts +0 -49
  45. package/dist/nord/api/core.js +0 -164
  46. package/dist/nord/api/market.d.ts +0 -36
  47. package/dist/nord/api/market.js +0 -96
  48. package/dist/nord/api/metrics.d.ts +0 -67
  49. package/dist/nord/api/metrics.js +0 -229
  50. package/dist/nord/api/queries.d.ts +0 -46
  51. package/dist/nord/api/queries.js +0 -109
  52. package/dist/nord/client/Nord.d.ts +0 -284
  53. package/dist/nord/client/Nord.js +0 -491
  54. package/dist/nord/client/NordUser.d.ts +0 -287
  55. package/dist/nord/client/NordUser.js +0 -595
  56. package/dist/nord/index.d.ts +0 -9
  57. package/dist/nord/index.js +0 -33
  58. package/dist/nord/models/Subscriber.d.ts +0 -37
  59. package/dist/nord/models/Subscriber.js +0 -25
  60. package/dist/nord/utils/NordError.d.ts +0 -35
  61. package/dist/nord/utils/NordError.js +0 -49
  62. package/dist/types.d.ts +0 -407
  63. package/dist/types.js +0 -103
  64. package/dist/utils.d.ts +0 -116
  65. package/dist/utils.js +0 -271
  66. package/dist/websocket/NordWebSocketClient.d.ts +0 -68
  67. package/dist/websocket/NordWebSocketClient.js +0 -338
  68. package/dist/websocket/events.d.ts +0 -19
  69. package/dist/websocket/events.js +0 -2
  70. package/dist/websocket/index.d.ts +0 -2
  71. package/dist/websocket/index.js +0 -5
  72. package/jest.config.ts +0 -9
  73. package/nodemon.json +0 -4
  74. package/protoc-generate.sh +0 -23
  75. package/src/idl/bridge.json +0 -1506
  76. package/src/nord/api/market.ts +0 -122
  77. package/src/nord/api/queries.ts +0 -135
@@ -1,106 +0,0 @@
1
- import Decimal from "decimal.js";
2
- import * as proto from "../../gen/nord";
3
- import { FillMode, Side } from "../../types";
4
- import { BigIntValue } from "../../utils";
5
- declare function createSessionImpl(sendFn: (encoded: Uint8Array) => Promise<Uint8Array>, walletSignFn: (message: string | Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
6
- userPubkey: Uint8Array;
7
- sessionPubkey: Uint8Array;
8
- expiryTimestamp?: bigint;
9
- }): Promise<bigint>;
10
- export declare function createSession(serverUrl: string, walletSignFn: (message: string | Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
11
- userPubkey: Uint8Array;
12
- sessionPubkey: Uint8Array;
13
- expiryTimestamp?: bigint;
14
- }): Promise<bigint>;
15
- declare function revokeSessionImpl(sendFn: (encoded: Uint8Array) => Promise<Uint8Array>, walletSignFn: (message: string | Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
16
- sessionId: BigIntValue;
17
- }): Promise<void>;
18
- export declare function revokeSession(serverUrl: string, walletSignFn: (message: string | Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
19
- sessionId: BigIntValue;
20
- }): Promise<void>;
21
- declare function withdrawImpl(sendFn: (encoded: Uint8Array) => Promise<Uint8Array>, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
22
- sizeDecimals: number;
23
- sessionId: BigIntValue;
24
- tokenId: number;
25
- amount: Decimal.Value;
26
- }): Promise<{
27
- actionId: bigint;
28
- } & proto.Receipt_WithdrawResult>;
29
- export declare function withdraw(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
30
- sizeDecimals: number;
31
- sessionId: BigIntValue;
32
- tokenId: number;
33
- amount: number;
34
- }): Promise<{
35
- actionId: bigint;
36
- } & proto.Receipt_WithdrawResult>;
37
- declare function placeOrderImpl(sendFn: (encoded: Uint8Array) => Promise<Uint8Array>, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
38
- sessionId: BigIntValue;
39
- senderId?: number;
40
- liquidateeId?: number;
41
- sizeDecimals: number;
42
- priceDecimals: number;
43
- marketId: number;
44
- side: Side;
45
- fillMode: FillMode;
46
- isReduceOnly: boolean;
47
- size?: Decimal.Value;
48
- price?: Decimal.Value;
49
- quoteSize?: Decimal.Value;
50
- clientOrderId?: BigIntValue;
51
- }): Promise<bigint | undefined>;
52
- export declare function placeOrder(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
53
- sessionId: BigIntValue;
54
- senderId?: number;
55
- sizeDecimals: number;
56
- priceDecimals: number;
57
- marketId: number;
58
- side: Side;
59
- fillMode: FillMode;
60
- isReduceOnly: boolean;
61
- size?: Decimal.Value;
62
- price?: Decimal.Value;
63
- quoteSize?: Decimal.Value;
64
- liquidateeId?: number;
65
- clientOrderId?: BigIntValue;
66
- }): Promise<bigint | undefined>;
67
- declare function cancelOrderImpl(sendFn: (encoded: Uint8Array) => Promise<Uint8Array>, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
68
- sessionId: BigIntValue;
69
- senderId?: number;
70
- orderId: BigIntValue;
71
- liquidateeId?: number;
72
- }): Promise<bigint>;
73
- export declare function cancelOrder(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
74
- sessionId: BigIntValue;
75
- senderId?: number;
76
- orderId: BigIntValue;
77
- liquidateeId?: number;
78
- }): Promise<bigint>;
79
- declare function transferImpl(sendFn: (encoded: Uint8Array) => Promise<Uint8Array>, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
80
- sessionId: BigIntValue;
81
- fromAccountId: number;
82
- toAccountId?: number;
83
- tokenId: number;
84
- tokenDecimals: number;
85
- amount: Decimal.Value;
86
- }): Promise<number | undefined>;
87
- export declare function transfer(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
88
- sessionId: BigIntValue;
89
- fromAccountId: number;
90
- toAccountId?: number;
91
- tokenId: number;
92
- tokenDecimals: number;
93
- amount: Decimal.Value;
94
- }): Promise<number | undefined>;
95
- /**
96
- * For testing purposes
97
- */
98
- export declare const _private: {
99
- createSessionImpl: typeof createSessionImpl;
100
- revokeSessionImpl: typeof revokeSessionImpl;
101
- withdrawImpl: typeof withdrawImpl;
102
- placeOrderImpl: typeof placeOrderImpl;
103
- cancelOrderImpl: typeof cancelOrderImpl;
104
- transferImpl: typeof transferImpl;
105
- };
106
- export {};
@@ -1,256 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports._private = void 0;
37
- exports.createSession = createSession;
38
- exports.revokeSession = revokeSession;
39
- exports.withdraw = withdraw;
40
- exports.placeOrder = placeOrder;
41
- exports.cancelOrder = cancelOrder;
42
- exports.transfer = transfer;
43
- const proto = __importStar(require("../../gen/nord"));
44
- const types_1 = require("../../types");
45
- const utils_1 = require("../../utils");
46
- async function sessionSign(signFn, message) {
47
- const signature = await signFn(message);
48
- return new Uint8Array([...message, ...signature]);
49
- }
50
- async function walletSign(walletSignFn, message) {
51
- const signature = await walletSignFn(message);
52
- return new Uint8Array([...message, ...signature]);
53
- }
54
- function makeSendHttp(serverUrl) {
55
- return async (body) => {
56
- const response = await (0, utils_1.checkedFetch)(`${serverUrl}/action`, {
57
- method: "POST",
58
- headers: {
59
- "Content-Type": "application/json",
60
- },
61
- body,
62
- });
63
- return new Uint8Array(await response.arrayBuffer());
64
- };
65
- }
66
- async function sendAction(sendFn, makeSignedMessage, action, actionErrorDesc) {
67
- const encoded = (0, utils_1.encodeLengthDelimited)(action, proto.Action);
68
- const body = await makeSignedMessage(encoded);
69
- const rawResp = await sendFn(body);
70
- const resp = (0, utils_1.decodeLengthDelimited)(rawResp, proto.Receipt);
71
- if (resp.kind?.$case === "err") {
72
- throw new Error(`Could not ${actionErrorDesc}, reason: ${proto.errorToJSON(resp.kind.value)}`);
73
- }
74
- return resp;
75
- }
76
- async function createSessionImpl(sendFn, walletSignFn, currentTimestamp, nonce, params) {
77
- (0, utils_1.checkPubKeyLength)(types_1.KeyType.Ed25519, params.userPubkey.length);
78
- (0, utils_1.checkPubKeyLength)(types_1.KeyType.Ed25519, params.sessionPubkey.length);
79
- let expiry = 0n;
80
- if (params.expiryTimestamp !== undefined) {
81
- expiry = params.expiryTimestamp;
82
- (0, utils_1.assert)(expiry > currentTimestamp, "Cannot set expiry timestamp in the past");
83
- }
84
- else {
85
- expiry = currentTimestamp + utils_1.SESSION_TTL;
86
- }
87
- const action = {
88
- currentTimestamp,
89
- nonce,
90
- kind: {
91
- $case: "createSession",
92
- value: {
93
- userPubkey: params.userPubkey,
94
- blstPubkey: params.sessionPubkey,
95
- expiryTimestamp: expiry,
96
- },
97
- },
98
- };
99
- const resp = await sendAction(sendFn, (m) => walletSign(walletSignFn, m), action, "create a new session");
100
- if (resp.kind?.$case === "createSessionResult") {
101
- return resp.kind.value.sessionId;
102
- }
103
- else {
104
- throw new Error(`Unexpected receipt kind ${resp.kind?.$case}`);
105
- }
106
- }
107
- async function createSession(serverUrl, walletSignFn, currentTimestamp, nonce, params) {
108
- return createSessionImpl(makeSendHttp(serverUrl), walletSignFn, currentTimestamp, nonce, params);
109
- }
110
- async function revokeSessionImpl(sendFn, walletSignFn, currentTimestamp, nonce, params) {
111
- const action = {
112
- currentTimestamp,
113
- nonce,
114
- kind: {
115
- $case: "revokeSession",
116
- value: {
117
- sessionId: BigInt(params.sessionId),
118
- },
119
- },
120
- };
121
- await sendAction(sendFn, (m) => walletSign(walletSignFn, m), action, "create a new session");
122
- }
123
- async function revokeSession(serverUrl, walletSignFn, currentTimestamp, nonce, params) {
124
- return revokeSessionImpl(makeSendHttp(serverUrl), walletSignFn, currentTimestamp, nonce, params);
125
- }
126
- async function withdrawImpl(sendFn, signFn, currentTimestamp, nonce, params) {
127
- const amount = (0, utils_1.toScaledU64)(params.amount, params.sizeDecimals);
128
- if (amount <= 0) {
129
- throw new Error("Withdraw amount must be positive");
130
- }
131
- const action = {
132
- currentTimestamp,
133
- nonce,
134
- kind: {
135
- $case: "withdraw",
136
- value: {
137
- sessionId: BigInt(params.sessionId),
138
- tokenId: params.tokenId,
139
- amount,
140
- },
141
- },
142
- };
143
- const resp = await sendAction(sendFn, (m) => sessionSign(signFn, m), action, "withdraw");
144
- if (resp.kind?.$case === "withdrawResult") {
145
- return { actionId: resp.actionId, ...resp.kind.value };
146
- }
147
- else {
148
- throw new Error(`Unexpected receipt kind ${resp.kind?.$case}`);
149
- }
150
- }
151
- async function withdraw(serverUrl, signFn, currentTimestamp, nonce, params) {
152
- return withdrawImpl(makeSendHttp(serverUrl), signFn, currentTimestamp, nonce, params);
153
- }
154
- async function placeOrderImpl(sendFn, signFn, currentTimestamp, nonce, params) {
155
- const price = (0, utils_1.toScaledU64)(params.price ?? 0, params.priceDecimals);
156
- const size = (0, utils_1.toScaledU64)(params.size ?? 0, params.sizeDecimals);
157
- const quoteSize = (0, utils_1.toScaledU128)(params.quoteSize ?? 0, params.priceDecimals + params.sizeDecimals);
158
- // Compose action object
159
- const action = {
160
- currentTimestamp,
161
- nonce,
162
- kind: {
163
- $case: "placeOrder",
164
- value: {
165
- sessionId: BigInt(params.sessionId),
166
- senderAccountId: params.senderId,
167
- marketId: params.marketId,
168
- side: params.side === types_1.Side.Bid ? proto.Side.BID : proto.Side.ASK,
169
- fillMode: (0, types_1.fillModeToProtoFillMode)(params.fillMode),
170
- isReduceOnly: params.isReduceOnly,
171
- price,
172
- size,
173
- quoteSize: (0, utils_1.bigIntToProtoU128)(quoteSize),
174
- clientOrderId: (0, utils_1.optMap)(params.clientOrderId, (x) => BigInt(x)),
175
- delegatorAccountId: params.liquidateeId,
176
- },
177
- },
178
- };
179
- const resp = await sendAction(sendFn, (m) => sessionSign(signFn, m), action, "place the order");
180
- if (resp.kind?.$case === "placeOrderResult") {
181
- return resp.kind.value.posted?.orderId;
182
- }
183
- else {
184
- throw new Error(`Unexpected receipt kind ${resp.kind?.$case}`);
185
- }
186
- }
187
- async function placeOrder(serverUrl, signFn, currentTimestamp, nonce, params) {
188
- return placeOrderImpl(makeSendHttp(serverUrl), signFn, currentTimestamp, nonce, params);
189
- }
190
- async function cancelOrderImpl(sendFn, signFn, currentTimestamp, nonce, params) {
191
- const action = {
192
- currentTimestamp,
193
- nonce: nonce,
194
- kind: {
195
- $case: "cancelOrderById",
196
- value: {
197
- orderId: BigInt(params.orderId),
198
- sessionId: BigInt(params.sessionId),
199
- senderAccountId: params.senderId,
200
- delegatorAccountId: params.liquidateeId,
201
- },
202
- },
203
- };
204
- const resp = await sendAction(sendFn, (m) => sessionSign(signFn, m), action, "cancel the order");
205
- if (resp.kind?.$case === "cancelOrderResult") {
206
- return resp.kind.value.orderId;
207
- }
208
- else {
209
- throw new Error(`Unexpected receipt kind ${resp.kind?.$case}`);
210
- }
211
- }
212
- async function cancelOrder(serverUrl, signFn, currentTimestamp, nonce, params) {
213
- return cancelOrderImpl(makeSendHttp(serverUrl), signFn, currentTimestamp, nonce, params);
214
- }
215
- async function transferImpl(sendFn, signFn, currentTimestamp, nonce, params) {
216
- const action = {
217
- currentTimestamp,
218
- nonce: nonce,
219
- kind: {
220
- $case: "transfer",
221
- value: {
222
- sessionId: BigInt(params.sessionId),
223
- fromAccountId: params.fromAccountId,
224
- toAccountId: params.toAccountId,
225
- tokenId: params.tokenId,
226
- amount: (0, utils_1.toScaledU64)(params.amount ?? 0, params.tokenDecimals),
227
- },
228
- },
229
- };
230
- const resp = await sendAction(sendFn, (m) => sessionSign(signFn, m), action, "transfer asset to other account");
231
- if (resp.kind?.$case === "transferred") {
232
- if (resp.kind.value.accountCreated) {
233
- return resp.kind.value.toUserAccount;
234
- }
235
- else {
236
- return undefined;
237
- }
238
- }
239
- else {
240
- throw new Error(`Unexpected receipt kind ${resp.kind?.$case}`);
241
- }
242
- }
243
- async function transfer(serverUrl, signFn, currentTimestamp, nonce, params) {
244
- return transferImpl(makeSendHttp(serverUrl), signFn, currentTimestamp, nonce, params);
245
- }
246
- /**
247
- * For testing purposes
248
- */
249
- exports._private = {
250
- createSessionImpl,
251
- revokeSessionImpl,
252
- withdrawImpl,
253
- placeOrderImpl,
254
- cancelOrderImpl,
255
- transferImpl,
256
- };
@@ -1,49 +0,0 @@
1
- import { Account, Info, SubscriptionPattern } from "../../types";
2
- import { NordWebSocketClient } from "../../websocket/index";
3
- /**
4
- * Get the current timestamp from the Nord server
5
- *
6
- * @param webServerUrl - Base URL for the Nord web server
7
- * @returns Current timestamp as a bigint
8
- * @throws {NordError} If the request fails
9
- */
10
- export declare function getTimestamp(webServerUrl: string): Promise<bigint>;
11
- /**
12
- * Get the next action nonce from the Nord server
13
- *
14
- * @param webServerUrl - Base URL for the Nord web server
15
- * @returns Next action nonce
16
- * @throws {NordError} If the request fails
17
- */
18
- export declare function getLastEventNonce(webServerUrl: string): Promise<number>;
19
- /**
20
- * Get information about the Nord server
21
- *
22
- * @param webServerUrl - Base URL for the Nord web server
23
- * @returns Information about markets and tokens
24
- * @throws {NordError} If the request fails
25
- */
26
- export declare function getInfo(webServerUrl: string): Promise<Info>;
27
- /**
28
- * Get account information
29
- *
30
- * @param webServerUrl - Base URL for the Nord web server
31
- * @param accountId - Account ID to get information for
32
- * @returns Account information
33
- * @throws {NordError} If the request fails
34
- */
35
- export declare function getAccount(webServerUrl: string, accountId: number): Promise<Account>;
36
- /**
37
- * Initialize a WebSocket client for Nord
38
- *
39
- * Connects to the Nord WebSocket endpoint with support for multiple subscription types:
40
- * - trades@SYMBOL - For trade updates
41
- * - deltas@SYMBOL - For orderbook delta updates
42
- * - account@ACCOUNT_ID - For user-specific updates
43
- *
44
- * @param webServerUrl - Base URL for the Nord web server
45
- * @param subscriptions - Array of subscriptions (e.g., ["trades@BTCUSDC", "deltas@BTCUSDC", "account@42"])
46
- * @returns WebSocket client
47
- * @throws {NordError} If initialization fails or invalid subscription is provided
48
- */
49
- export declare function initWebSocketClient(webServerUrl: string, subscriptions?: SubscriptionPattern[] | "trades" | "delta" | "account", initialSubscriptions?: SubscriptionPattern[]): NordWebSocketClient;
@@ -1,164 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getTimestamp = getTimestamp;
4
- exports.getLastEventNonce = getLastEventNonce;
5
- exports.getInfo = getInfo;
6
- exports.getAccount = getAccount;
7
- exports.initWebSocketClient = initWebSocketClient;
8
- const utils_1 = require("../../utils");
9
- const index_1 = require("../../websocket/index");
10
- const NordError_1 = require("../utils/NordError");
11
- /**
12
- * Get the current timestamp from the Nord server
13
- *
14
- * @param webServerUrl - Base URL for the Nord web server
15
- * @returns Current timestamp as a bigint
16
- * @throws {NordError} If the request fails
17
- */
18
- async function getTimestamp(webServerUrl) {
19
- try {
20
- const response = await (0, utils_1.checkedFetch)(`${webServerUrl}/timestamp`);
21
- return BigInt(await response.json());
22
- }
23
- catch (error) {
24
- throw new NordError_1.NordError("Failed to get timestamp", { cause: error });
25
- }
26
- }
27
- /**
28
- * Get the next action nonce from the Nord server
29
- *
30
- * @param webServerUrl - Base URL for the Nord web server
31
- * @returns Next action nonce
32
- * @throws {NordError} If the request fails
33
- */
34
- async function getLastEventNonce(webServerUrl) {
35
- try {
36
- const response = await (0, utils_1.checkedFetch)(`${webServerUrl}/event/last-acked-nonce`);
37
- const data = await response.json();
38
- return data.nonce;
39
- }
40
- catch (error) {
41
- throw new NordError_1.NordError("Failed to get action nonce", { cause: error });
42
- }
43
- }
44
- /**
45
- * Get information about the Nord server
46
- *
47
- * @param webServerUrl - Base URL for the Nord web server
48
- * @returns Information about markets and tokens
49
- * @throws {NordError} If the request fails
50
- */
51
- async function getInfo(webServerUrl) {
52
- try {
53
- const response = await (0, utils_1.checkedFetch)(`${webServerUrl}/info`);
54
- return await response.json();
55
- }
56
- catch (error) {
57
- throw new NordError_1.NordError("Failed to get info", { cause: error });
58
- }
59
- }
60
- /**
61
- * Get account information
62
- *
63
- * @param webServerUrl - Base URL for the Nord web server
64
- * @param accountId - Account ID to get information for
65
- * @returns Account information
66
- * @throws {NordError} If the request fails
67
- */
68
- async function getAccount(webServerUrl, accountId) {
69
- try {
70
- const response = await (0, utils_1.checkedFetch)(`${webServerUrl}/account/${accountId}`);
71
- return await response.json();
72
- }
73
- catch (error) {
74
- throw new NordError_1.NordError(`Failed to get account ${accountId}`, { cause: error });
75
- }
76
- }
77
- /**
78
- * Initialize a WebSocket client for Nord
79
- *
80
- * Connects to the Nord WebSocket endpoint with support for multiple subscription types:
81
- * - trades@SYMBOL - For trade updates
82
- * - deltas@SYMBOL - For orderbook delta updates
83
- * - account@ACCOUNT_ID - For user-specific updates
84
- *
85
- * @param webServerUrl - Base URL for the Nord web server
86
- * @param subscriptions - Array of subscriptions (e.g., ["trades@BTCUSDC", "deltas@BTCUSDC", "account@42"])
87
- * @returns WebSocket client
88
- * @throws {NordError} If initialization fails or invalid subscription is provided
89
- */
90
- function initWebSocketClient(webServerUrl, subscriptions, initialSubscriptions) {
91
- try {
92
- // Determine URL and subscriptions based on parameters
93
- let wsUrl = webServerUrl.replace(/^http/, "ws") + `/ws`;
94
- let wsSubscriptions = [];
95
- // Validate subscriptions parameter
96
- if (typeof subscriptions === "string") {
97
- // Legacy mode - handle endpoint string
98
- if (subscriptions === "trades" ||
99
- subscriptions === "delta" ||
100
- subscriptions === "account") {
101
- wsUrl += `/${subscriptions}`;
102
- // If initialSubscriptions provided, use them
103
- if (initialSubscriptions && initialSubscriptions.length > 0) {
104
- // Validate initialSubscriptions
105
- initialSubscriptions.forEach(validateSubscription);
106
- wsSubscriptions = initialSubscriptions;
107
- }
108
- }
109
- else {
110
- throw new NordError_1.NordError(`Invalid endpoint: ${subscriptions}. Must be "trades", "deltas", or "account".`);
111
- }
112
- }
113
- else if (Array.isArray(subscriptions) && subscriptions.length > 0) {
114
- // New mode - validate and combine subscriptions in URL
115
- subscriptions.forEach(validateSubscription);
116
- wsUrl += `/${subscriptions.join("&")}`;
117
- }
118
- else {
119
- // Default to trades endpoint if no subscriptions specified
120
- wsUrl += `/trades`;
121
- }
122
- console.log(`Initializing WebSocket client with URL: ${wsUrl}`);
123
- // Create and connect the WebSocket client
124
- const ws = new index_1.NordWebSocketClient(wsUrl);
125
- // Add error handler
126
- ws.on("error", (error) => {
127
- console.error("Nord WebSocket error:", error);
128
- });
129
- // Add connected handler for debugging
130
- ws.on("connected", () => {
131
- console.log("Nord WebSocket connected successfully");
132
- // Subscribe to additional subscriptions if provided
133
- // For new format, these are already part of the URL
134
- if (wsSubscriptions.length > 0) {
135
- ws.subscribe(wsSubscriptions);
136
- }
137
- });
138
- // Connect the WebSocket
139
- ws.connect();
140
- return ws;
141
- }
142
- catch (error) {
143
- console.error("Failed to initialize WebSocket client:", error);
144
- throw new NordError_1.NordError("Failed to initialize WebSocket client", {
145
- cause: error,
146
- });
147
- }
148
- }
149
- /**
150
- * Validates a subscription string follows the correct format
151
- *
152
- * @param subscription - The subscription to validate
153
- * @throws {NordError} If the subscription format is invalid
154
- */
155
- function validateSubscription(subscription) {
156
- const [type, param] = subscription.split("@");
157
- if (!type || !param || !["trades", "deltas", "account"].includes(type)) {
158
- throw new NordError_1.NordError(`Invalid subscription format: ${subscription}. Expected format: "trades@SYMBOL", "deltas@SYMBOL", or "account@ID"`);
159
- }
160
- // Additional validation for account subscriptions
161
- if (type === "account" && isNaN(Number(param))) {
162
- throw new NordError_1.NordError(`Invalid account ID in subscription: ${subscription}. Account ID must be a number.`);
163
- }
164
- }
@@ -1,36 +0,0 @@
1
- import { MarketsStatsResponse, OrderbookQuery, OrderbookResponse, TradesQuery, TradesResponse, UserAccountIdsQuery, UserAccountIdsResponse } from "../../types";
2
- /**
3
- * Get market statistics
4
- *
5
- * @param webServerUrl - Base URL for the Nord web server
6
- * @returns Market statistics response
7
- * @throws {NordError} If the request fails
8
- */
9
- export declare function marketsStats(webServerUrl: string): Promise<MarketsStatsResponse>;
10
- /**
11
- * Get trades for a market
12
- *
13
- * @param webServerUrl - Base URL for the Nord web server
14
- * @param query - Trades query parameters
15
- * @returns Trades response
16
- * @throws {NordError} If the request fails
17
- */
18
- export declare function getTrades(webServerUrl: string, query: TradesQuery): Promise<TradesResponse>;
19
- /**
20
- * Get user account IDs
21
- *
22
- * @param webServerUrl - Base URL for the Nord web server
23
- * @param query - User account IDs query parameters
24
- * @returns User account IDs response
25
- * @throws {NordError} If the request fails
26
- */
27
- export declare function getUserAccountIds(webServerUrl: string, query: UserAccountIdsQuery): Promise<UserAccountIdsResponse>;
28
- /**
29
- * Get orderbook for a market
30
- *
31
- * @param webServerUrl - Base URL for the Nord web server
32
- * @param query - Orderbook query parameters
33
- * @returns Orderbook response
34
- * @throws {NordError} If the request fails
35
- */
36
- export declare function getOrderbook(webServerUrl: string, query: OrderbookQuery): Promise<OrderbookResponse>;