@n1xyz/nord-ts 0.2.0 → 0.3.2

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.
@@ -1,5 +0,0 @@
1
- /**
2
- * This file was auto-generated by openapi-typescript.
3
- * Do not make direct changes to the file.
4
- */
5
- export {};
package/dist/index.js DELETED
@@ -1,10 +0,0 @@
1
- export * from "./types";
2
- export * from "./utils";
3
- export * from "./const";
4
- export * from "./error";
5
- export * from "./websocket/index";
6
- export * from "./client/Nord";
7
- export * from "./client/NordUser";
8
- export * from "./client/NordAdmin";
9
- export * as proto from "./gen/nord_pb";
10
- export * as openapi from "./gen/openapi";
package/dist/types.js DELETED
@@ -1,92 +0,0 @@
1
- import * as proto from "./gen/nord_pb";
2
- import Decimal from "decimal.js";
3
- import { toScaledU64 } from "./utils";
4
- export var Side;
5
- (function (Side) {
6
- Side["Ask"] = "ask";
7
- Side["Bid"] = "bid";
8
- })(Side || (Side = {}));
9
- export var FillMode;
10
- (function (FillMode) {
11
- FillMode[FillMode["Limit"] = 0] = "Limit";
12
- FillMode[FillMode["PostOnly"] = 1] = "PostOnly";
13
- FillMode[FillMode["ImmediateOrCancel"] = 2] = "ImmediateOrCancel";
14
- FillMode[FillMode["FillOrKill"] = 3] = "FillOrKill";
15
- })(FillMode || (FillMode = {}));
16
- export var TriggerKind;
17
- (function (TriggerKind) {
18
- TriggerKind[TriggerKind["StopLoss"] = 0] = "StopLoss";
19
- TriggerKind[TriggerKind["TakeProfit"] = 1] = "TakeProfit";
20
- })(TriggerKind || (TriggerKind = {}));
21
- export var TriggerStatus;
22
- (function (TriggerStatus) {
23
- TriggerStatus[TriggerStatus["Active"] = 0] = "Active";
24
- TriggerStatus[TriggerStatus["Success"] = 1] = "Success";
25
- TriggerStatus[TriggerStatus["Cancel"] = 2] = "Cancel";
26
- TriggerStatus[TriggerStatus["Remove"] = 4] = "Remove";
27
- })(TriggerStatus || (TriggerStatus = {}));
28
- /**
29
- * Converts a `FillMode` enum to its corresponding protobuf representation.
30
- *
31
- * @param x - The fill mode to convert.
32
- * @returns The corresponding protobuf fill mode.
33
- * @throws Will throw an error if provided with an invalid fill mode.
34
- */
35
- export function fillModeToProtoFillMode(x) {
36
- if (x === FillMode.Limit)
37
- return proto.FillMode.LIMIT;
38
- if (x === FillMode.PostOnly)
39
- return proto.FillMode.POST_ONLY;
40
- if (x === FillMode.ImmediateOrCancel) {
41
- return proto.FillMode.IMMEDIATE_OR_CANCEL;
42
- }
43
- if (x === FillMode.FillOrKill)
44
- return proto.FillMode.FILL_OR_KILL;
45
- throw new Error("Invalid fill mode");
46
- }
47
- /**
48
- * WebSocket message types
49
- */
50
- export var WebSocketMessageType;
51
- (function (WebSocketMessageType) {
52
- WebSocketMessageType["TradeUpdate"] = "trades";
53
- WebSocketMessageType["DeltaUpdate"] = "delta";
54
- WebSocketMessageType["AccountUpdate"] = "account";
55
- })(WebSocketMessageType || (WebSocketMessageType = {}));
56
- // Positive decimal price and size.
57
- // Example:
58
- // ```
59
- // const limit = new QuoteSize(new Decimal(114000), new Decimal(0.00035)),
60
- //```
61
- // Gives 40$ USD limit.
62
- //
63
- // Given price is same(or very close) to the market price,
64
- // limit gives size tick as close as possible to settlemnt size tick.
65
- // If you want to get smaller tick on client (on server it will not change),
66
- // do `new QuoteSize(new Decimal(114000/2), new Decimal(0.00070))`.
67
- // It will be 40$ limit, but may help if BTC suddently moves fast.
68
- export class QuoteSize {
69
- price;
70
- size;
71
- /// Input can be only positive values.
72
- constructor(quotePrice, quoteSize) {
73
- const p = new Decimal(quotePrice);
74
- const s = new Decimal(quoteSize);
75
- if (!p.isPositive() || !s.isPositive()) {
76
- throw new Error("quotePrice and quoteSize must be positive");
77
- }
78
- this.price = p;
79
- this.size = s;
80
- }
81
- // USD value of limit, use for debug
82
- value() {
83
- return this.price.mul(this.size);
84
- }
85
- // Converts to wire format to be send to server, scaling price and size according to market decimals.
86
- toWire(marketPriceDecimals, marketSizeDecimals) {
87
- return {
88
- price: toScaledU64(this.price, marketPriceDecimals),
89
- size: toScaledU64(this.size, marketSizeDecimals),
90
- };
91
- }
92
- }
package/dist/utils.js DELETED
@@ -1,193 +0,0 @@
1
- import { Decimal } from "decimal.js";
2
- import { sizeDelimitedPeek } from "@bufbuild/protobuf/wire";
3
- import { fromBinary } from "@bufbuild/protobuf";
4
- import { ethers } from "ethers";
5
- import fetch from "node-fetch";
6
- import { Keypair } from "@solana/web3.js";
7
- import bs58 from "bs58";
8
- import * as solana from "@solana/web3.js";
9
- import { Buffer } from "buffer";
10
- export const SESSION_TTL = 60n * 60n * 24n * 30n;
11
- export const ZERO_DECIMAL = new Decimal(0);
12
- export const MAX_BUFFER_LEN = 10_000;
13
- // Max size of data returned from Nord endpoints
14
- const MAX_PAYLOAD_SIZE = 100 * 1024; // 100 kB
15
- export function panic(message) {
16
- throw new Error(message);
17
- }
18
- export function isRfc3339(s) {
19
- const REGEX = /^((?:(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2}(?:\.\d+)?))(Z|[\+-]\d{2}:\d{2})?)$/;
20
- return REGEX.test(s);
21
- }
22
- export function assert(predicate, message) {
23
- if (!predicate)
24
- panic(message ?? "Assertion violated");
25
- }
26
- /**
27
- * Extracts value out of optional if it's defined, or throws error if it's not
28
- * @param value Optional value to unwrap
29
- * @param message Error message
30
- * @returns Unwrapped value
31
- */
32
- export function optExpect(value, message) {
33
- if (value === undefined)
34
- throw new Error(message);
35
- return value;
36
- }
37
- /** Behaves same as `node-fetch/fetch` but throws if response is a failure
38
- *
39
- * @param url Request HTTP URL
40
- * @param init Request parameters
41
- * @returns Raw response if fetch succeeded
42
- * @throws If response wasn't Ok
43
- */
44
- export async function checkedFetch(url, init) {
45
- const resp = await fetch(url, init);
46
- assert(resp.ok, `Request failed with ${resp.status}: ${resp.statusText}`);
47
- return resp;
48
- }
49
- /**
50
- * Constructs wallet signing function, usable with `NordUser` type
51
- *
52
- * @param walletKey Either raw signing key as bytes array or hex string prefixed with `"0x"`
53
- * @returns Async function which accepts arbitrary message, generates its digets,
54
- * then signs it with provided user wallet key and returns signature
55
- * as hex string prefixed with `"0x"`
56
- */
57
- export function makeWalletSignFn(walletKey) {
58
- const signingKey = new ethers.SigningKey(walletKey);
59
- return async (message) => signingKey.sign(ethers.hashMessage(message)).serialized;
60
- }
61
- // Returned numbers do fit into specified bits range, or error is thrown.
62
- function makeToScaledBigUint(params) {
63
- const Dec = Decimal.clone({
64
- precision: params.precision,
65
- toExpPos: params.exponent,
66
- toExpNeg: -params.exponent,
67
- });
68
- const Ten = new Dec(10);
69
- const Max = new Dec(((1n << BigInt(params.bits)) - 1n).toString());
70
- return (x, decimals) => {
71
- const dec = new Dec(x);
72
- if (dec.isZero()) {
73
- return 0n;
74
- }
75
- if (dec.isNeg()) {
76
- throw new Error(`Number is negative`);
77
- }
78
- const scaled = Ten.pow(decimals).mul(dec).truncated();
79
- if (scaled.isZero()) {
80
- throw new Error(`Precision loss when converting ${dec} to scaled integer`);
81
- }
82
- if (scaled.greaterThan(Max)) {
83
- throw new Error(`Integer is out of range: ${scaled} exceeds limit ${Max}`);
84
- }
85
- return BigInt(scaled.toString());
86
- };
87
- }
88
- /**
89
- * Converts decimal value into rescaled 64-bit unsigned integer
90
- * by scaling it up by specified number of decimal digits.
91
- *
92
- * Ensures that number won't accidentally become zero
93
- * or exceed U64's value range
94
- *
95
- * @param x Decimal value to rescale
96
- * @param decimals Number of decimal digits
97
- * @returns Rescaled unsigned integer
98
- */
99
- export const toScaledU64 = makeToScaledBigUint({
100
- bits: 64,
101
- precision: 20,
102
- exponent: 28,
103
- });
104
- /**
105
- * Converts decimal value into rescaled 128-bit unsigned integer
106
- * by scaling it up by specified number of decimal digits.
107
- *
108
- * Ensures that number won't accidentally become zero
109
- * or exceed U128's value range
110
- *
111
- * @param x Decimal value to rescale
112
- * @param decimals Number of decimal digits
113
- * @returns Rescaled unsigned integer
114
- */
115
- export const toScaledU128 = makeToScaledBigUint({
116
- bits: 128,
117
- precision: 40,
118
- exponent: 56,
119
- });
120
- /**
121
- * Decodes any protobuf message from a length-delimited format,
122
- * i.e. prefixed with its length encoded as varint
123
- *
124
- * @param bytes Byte array with encoded message
125
- * @param schema Message schema for decoding
126
- * @returns Decoded message
127
- */
128
- export function decodeLengthDelimited(bytes, schema) {
129
- // use sizeDelimitedPeek to extract the message length and offset
130
- const peekResult = sizeDelimitedPeek(bytes);
131
- if (peekResult.size === null || peekResult.offset === null) {
132
- throw new Error("Failed to parse size-delimited message");
133
- }
134
- if (peekResult.size > MAX_PAYLOAD_SIZE) {
135
- throw new Error(`Encoded message size (${peekResult.size} bytes) is greater than max payload size (${MAX_PAYLOAD_SIZE} bytes).`);
136
- }
137
- if (peekResult.offset + peekResult.size > bytes.length) {
138
- throw new Error(`Encoded message size (${peekResult.size} bytes) is greater than remaining buffer size (${bytes.length - peekResult.offset} bytes).`);
139
- }
140
- // decode the message using the offset and size from peek
141
- return fromBinary(schema, bytes.slice(peekResult.offset, peekResult.offset + peekResult.size));
142
- }
143
- export function decodeHex(value) {
144
- const hex = value.startsWith("0x") ? value.slice(2) : value;
145
- return Uint8Array.from(Buffer.from(hex, "hex"));
146
- }
147
- export function findMarket(markets, marketId) {
148
- if (marketId < 0 || markets.length - 1 < marketId) {
149
- throw new Error(`The market with marketId=${marketId} not found`);
150
- }
151
- return markets[marketId];
152
- }
153
- export function findToken(tokens, tokenId) {
154
- if (tokenId < 0 || tokens.length - 1 < tokenId) {
155
- throw new Error(`The token with tokenId=${tokenId} not found`);
156
- }
157
- return tokens[tokenId];
158
- }
159
- export function keypairFromPrivateKey(privateKey) {
160
- if (typeof privateKey === "string") {
161
- if (!privateKey.startsWith("0x")) {
162
- return Keypair.fromSecretKey(bs58.decode(privateKey));
163
- }
164
- const hex = privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey;
165
- const bytes = new Uint8Array(hex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
166
- return Keypair.fromSecretKey(bytes);
167
- }
168
- return Keypair.fromSecretKey(privateKey);
169
- }
170
- export async function signAdminPayload({ payload, user, signTransaction, }) {
171
- const tx = new solana.Transaction({
172
- blockhash: bs58.encode(new Uint8Array(32)),
173
- lastValidBlockHeight: 0,
174
- feePayer: user,
175
- });
176
- tx.add(new solana.TransactionInstruction({
177
- keys: [],
178
- programId: user,
179
- data: Buffer.from(payload),
180
- }));
181
- const signedTx = await signTransaction(tx);
182
- const sig = signedTx.signatures[0];
183
- assert(sig !== undefined, //.
184
- "signed transaction must have a signature");
185
- assert(sig.signature !== null, "signature must be non-null; check your signTransaction function");
186
- assert(sig.signature.length === 64, //.
187
- "signature must be 64 bytes");
188
- assert(sig.publicKey.equals(user), `signature is for ${sig.publicKey}, expected ${user}`);
189
- return sig.signature;
190
- }
191
- export async function signUserPayload({ payload, signMessage, }) {
192
- return await signMessage(new TextEncoder().encode(payload.toHex()));
193
- }
@@ -1,242 +0,0 @@
1
- import { EventEmitter } from "events";
2
- import WebSocket from "ws";
3
- const VALID_STREAM_TYPES = ["trades", "delta", "account"];
4
- /**
5
- * WebSocket client for Nord exchange
6
- *
7
- * This client connects to one of the specific Nord WebSocket endpoints:
8
- *
9
- * Each endpoint handles a specific type of data and subscriptions must match
10
- * the endpoint type (e.g., only 'trades@BTCUSDC' subscriptions are valid on
11
- * the /ws/trades endpoint).
12
- */
13
- export class NordWebSocketClient extends EventEmitter {
14
- ws = null;
15
- url;
16
- reconnectAttempts = 0;
17
- maxReconnectAttempts = 5;
18
- reconnectDelay = 1000;
19
- pingInterval = null;
20
- pingTimeout = null;
21
- isBrowser;
22
- /**
23
- * Create a new NordWebSocketClient
24
- * @param url WebSocket server URL
25
- */
26
- constructor(url) {
27
- super();
28
- this.url = url;
29
- // Check if we're in a browser environment
30
- // The most reliable way is to check for Node.js process
31
- this.isBrowser =
32
- typeof process === "undefined" ||
33
- !process.versions ||
34
- !process.versions.node;
35
- }
36
- /**
37
- * Validate stream format
38
- * @param stream Stream identifier to validate
39
- * @throws Error if stream format is invalid
40
- */
41
- validateStream(stream) {
42
- const [type, params] = stream.split("@");
43
- if (!type || !params) {
44
- throw new Error(`Invalid stream format: ${stream}. Expected format: <type>@<params>`);
45
- }
46
- // Extract the endpoint from the URL
47
- const urlPath = new URL(this.url).pathname;
48
- const endpoint = urlPath.split("/").pop();
49
- // Ensure the stream type matches the endpoint we're connected to
50
- if (endpoint && type !== endpoint) {
51
- throw new Error(`Stream type '${type}' doesn't match the connected endpoint '${endpoint}'`);
52
- }
53
- if (!VALID_STREAM_TYPES.includes(type)) {
54
- throw new Error(`Invalid stream type: ${type}. Valid types are: ${VALID_STREAM_TYPES.join(", ")}`);
55
- }
56
- if (type === "account" && !/^\d+$/.test(params)) {
57
- throw new Error(`Invalid account ID in stream: ${params}. Expected numeric ID`);
58
- }
59
- }
60
- /**
61
- * Setup WebSocket ping/pong heartbeat
62
- */
63
- setupHeartbeat() {
64
- if (this.pingInterval) {
65
- clearInterval(this.pingInterval);
66
- }
67
- if (this.pingTimeout) {
68
- clearTimeout(this.pingTimeout);
69
- }
70
- // In browser, we rely on the browser's WebSocket implementation to handle ping/pong
71
- if (this.isBrowser) {
72
- return;
73
- }
74
- this.pingInterval = setInterval(() => {
75
- if (this.ws && !this.isBrowser) {
76
- // Only use ping() method in Node.js environment
77
- this.ws.ping();
78
- // Set timeout for pong response
79
- this.pingTimeout = setTimeout(() => {
80
- this.emit("error", new Error("WebSocket ping timeout"));
81
- this.close();
82
- this.reconnect();
83
- }, 5000); // 5 second timeout
84
- }
85
- }, 30000); // Send ping every 30 seconds
86
- }
87
- /**
88
- * Get the appropriate WebSocket class based on environment
89
- */
90
- getWebSocketClass() {
91
- if (this.isBrowser) {
92
- // In browser environments
93
- if (typeof globalThis !== "undefined" && globalThis.WebSocket) {
94
- return globalThis.WebSocket;
95
- }
96
- throw new Error("WebSocket is not available in this environment");
97
- }
98
- else {
99
- // In Node.js
100
- return WebSocket;
101
- }
102
- }
103
- /**
104
- * Connect to the Nord WebSocket server
105
- */
106
- connect() {
107
- if (this.ws) {
108
- return;
109
- }
110
- try {
111
- const WebSocketClass = this.getWebSocketClass();
112
- if (this.isBrowser) {
113
- // Browser WebSocket setup
114
- this.ws = new WebSocketClass(this.url);
115
- this.ws.onopen = () => {
116
- this.emit("connected");
117
- this.reconnectAttempts = 0;
118
- this.reconnectDelay = 1000;
119
- };
120
- this.ws.onmessage = (event) => {
121
- try {
122
- const message = JSON.parse(event.data);
123
- this.handleMessage(message);
124
- }
125
- catch (error) {
126
- this.emit("error", new Error(`Failed to parse message: ${error instanceof Error ? error.message : String(error)}`));
127
- }
128
- };
129
- this.ws.onclose = (_event) => {
130
- this.emit("disconnected");
131
- this.reconnect();
132
- };
133
- this.ws.onerror = (event) => {
134
- const errorMsg = `WebSocket error: ${event && event.type ? event.type : "unknown"}`;
135
- this.emit("error", new Error(errorMsg));
136
- };
137
- }
138
- else {
139
- // Node.js WebSocket setup
140
- const nodeWs = new WebSocketClass(this.url);
141
- this.ws = nodeWs;
142
- nodeWs.on("open", () => {
143
- this.emit("connected");
144
- this.reconnectAttempts = 0;
145
- this.reconnectDelay = 1000;
146
- this.setupHeartbeat();
147
- });
148
- nodeWs.on("message", (data) => {
149
- try {
150
- const message = JSON.parse(data.toString());
151
- this.handleMessage(message);
152
- }
153
- catch (error) {
154
- this.emit("error", new Error(`Failed to parse message: ${error instanceof Error ? error.message : String(error)}`));
155
- }
156
- });
157
- nodeWs.on("close", (_code, _reason) => {
158
- this.emit("disconnected");
159
- if (this.pingInterval) {
160
- clearInterval(this.pingInterval);
161
- }
162
- if (this.pingTimeout) {
163
- clearTimeout(this.pingTimeout);
164
- }
165
- this.reconnect();
166
- });
167
- nodeWs.on("error", (error) => {
168
- this.emit("error", error);
169
- });
170
- nodeWs.on("pong", () => {
171
- if (this.pingTimeout) {
172
- clearTimeout(this.pingTimeout);
173
- }
174
- });
175
- }
176
- }
177
- catch (error) {
178
- const errorMsg = `Failed to initialize WebSocket: ${error instanceof Error ? error.message : String(error)}`;
179
- this.emit("error", new Error(errorMsg));
180
- }
181
- }
182
- /**
183
- * Close the WebSocket connection
184
- */
185
- close() {
186
- if (this.ws) {
187
- if (this.isBrowser) {
188
- this.ws.close();
189
- }
190
- else {
191
- this.ws.close();
192
- }
193
- this.ws = null;
194
- }
195
- if (this.pingInterval) {
196
- clearInterval(this.pingInterval);
197
- this.pingInterval = null;
198
- }
199
- if (this.pingTimeout) {
200
- clearTimeout(this.pingTimeout);
201
- this.pingTimeout = null;
202
- }
203
- }
204
- /**
205
- * Handle incoming WebSocket messages
206
- * @param message WebSocket message
207
- */
208
- handleMessage(message) {
209
- if (!message || typeof message !== "object") {
210
- this.emit("error", new Error(`Unexpected message type: ${message}`));
211
- return;
212
- }
213
- const hasOwn = (k) => Object.prototype.hasOwnProperty.call(message, k);
214
- if (hasOwn("trades")) {
215
- this.emit("trades", message.trades);
216
- return;
217
- }
218
- if (hasOwn("delta")) {
219
- this.emit("delta", message.delta);
220
- return;
221
- }
222
- if (hasOwn("account")) {
223
- this.emit("account", message.account);
224
- return;
225
- }
226
- this.emit("error", new Error(`Unexpected message type: ${message}`));
227
- }
228
- /**
229
- * Attempt to reconnect to the WebSocket server
230
- */
231
- reconnect() {
232
- if (this.reconnectAttempts >= this.maxReconnectAttempts) {
233
- this.emit("error", new Error("Max reconnection attempts reached"));
234
- return;
235
- }
236
- setTimeout(() => {
237
- this.reconnectAttempts++;
238
- this.reconnectDelay *= 2; // Exponential backoff
239
- this.connect();
240
- }, this.reconnectDelay);
241
- }
242
- }
@@ -1,24 +0,0 @@
1
- import { MAX_BUFFER_LEN } from "../utils";
2
- /**
3
- * Subscriber class for handling WebSocket subscriptions
4
- */
5
- export class Subscriber {
6
- streamURL;
7
- buffer;
8
- maxBufferLen;
9
- /**
10
- * Create a new Subscriber instance
11
- * @param config Subscriber configuration
12
- */
13
- constructor(config) {
14
- this.streamURL = config.streamURL;
15
- this.buffer = [];
16
- this.maxBufferLen = config.maxBufferLen ?? MAX_BUFFER_LEN;
17
- }
18
- /**
19
- * Subscribe to WebSocket events
20
- */
21
- subscribe() {
22
- // TODO: Implement subscription logic
23
- }
24
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,80 +0,0 @@
1
- import { NordWebSocketClient } from "./NordWebSocketClient";
2
- import { NordError } from "../error";
3
- import { Subscriber } from "./Subscriber";
4
- export { NordWebSocketClient, Subscriber, };
5
- /**
6
- * Initialize a WebSocket client for Nord
7
- *
8
- * Connects to the Nord WebSocket endpoint with support for multiple subscription types:
9
- * - trades@SYMBOL - For trade updates
10
- * - deltas@SYMBOL - For orderbook delta updates
11
- * - account@ACCOUNT_ID - For user-specific updates
12
- *
13
- * @param webServerUrl - Base URL for the Nord web server
14
- * @param subscriptions - Array of subscriptions (e.g., ["trades@BTCUSDC", "deltas@BTCUSDC", "account@42"])
15
- * @returns WebSocket client
16
- * @throws {NordError} If initialization fails or invalid subscription is provided
17
- */
18
- export function initWebSocketClient(webServerUrl, subscriptions) {
19
- try {
20
- // Determine URL and subscriptions based on parameters
21
- let wsUrl = webServerUrl.replace(/^http/, "ws") + `/ws`;
22
- // Validate subscriptions parameter
23
- if (typeof subscriptions === "string") {
24
- // Legacy mode - handle endpoint string
25
- if (subscriptions === "trades" ||
26
- subscriptions === "delta" ||
27
- subscriptions === "account") {
28
- wsUrl += `/${subscriptions}`;
29
- }
30
- else {
31
- throw new NordError(`Invalid endpoint: ${subscriptions}. Must be "trades", "deltas", or "account".`);
32
- }
33
- }
34
- else if (Array.isArray(subscriptions) && subscriptions.length > 0) {
35
- // New mode - validate and combine subscriptions in URL
36
- subscriptions.forEach(validateSubscription);
37
- wsUrl += `/${subscriptions.join("&")}`;
38
- }
39
- else {
40
- // Default to trades endpoint if no subscriptions specified
41
- wsUrl += `/trades`;
42
- }
43
- console.log(`Initializing WebSocket client with URL: ${wsUrl}`);
44
- // Create and connect the WebSocket client
45
- const ws = new NordWebSocketClient(wsUrl);
46
- // Add error handler
47
- ws.on("error", (error) => {
48
- console.error("Nord WebSocket error:", error);
49
- });
50
- // Add connected handler for debugging
51
- ws.on("connected", () => {
52
- console.log("Nord WebSocket connected successfully");
53
- });
54
- // Connect the WebSocket
55
- ws.connect();
56
- return ws;
57
- }
58
- catch (error) {
59
- console.error("Failed to initialize WebSocket client:", error);
60
- throw new NordError("Failed to initialize WebSocket client", {
61
- cause: error,
62
- });
63
- }
64
- }
65
- /**
66
- * Validates a subscription string follows the correct format
67
- *
68
- * @param subscription - The subscription to validate
69
- * @throws {NordError} If the subscription format is invalid
70
- */
71
- function validateSubscription(subscription) {
72
- const [type, param] = subscription.split("@");
73
- if (!type || !param || !["trades", "deltas", "account"].includes(type)) {
74
- throw new NordError(`Invalid subscription format: ${subscription}. Expected format: "trades@SYMBOL", "deltas@SYMBOL", or "account@ID"`);
75
- }
76
- // Additional validation for account subscriptions
77
- if (type === "account" && isNaN(Number(param))) {
78
- throw new NordError(`Invalid account ID in subscription: ${subscription}. Account ID must be a number.`);
79
- }
80
- }