@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.
- package/dist/actions.d.ts +57 -0
- package/dist/actions.js +186 -0
- package/dist/bundle.js +79181 -0
- package/dist/{nord/client → client}/Nord.d.ts +90 -107
- package/dist/{nord/client → client}/Nord.js +157 -218
- package/dist/{nord/client → client}/NordAdmin.d.ts +68 -102
- package/dist/{nord/client → client}/NordAdmin.js +109 -140
- package/dist/{nord/client → client}/NordUser.d.ts +86 -98
- package/dist/{nord/client → client}/NordUser.js +204 -271
- package/dist/const.js +5 -8
- package/dist/{nord/utils/NordError.js → error.js} +7 -5
- package/dist/gen/nord_pb.js +88 -92
- package/dist/gen/openapi.d.ts +39 -0
- package/dist/gen/openapi.js +1 -2
- package/dist/index.d.ts +6 -1
- package/dist/index.js +10 -21
- package/dist/types.d.ts +5 -50
- package/dist/types.js +21 -83
- package/dist/utils.d.ts +8 -11
- package/dist/utils.js +55 -90
- package/dist/websocket/NordWebSocketClient.js +12 -17
- package/dist/{nord/models → websocket}/Subscriber.d.ts +1 -1
- package/dist/{nord/models → websocket}/Subscriber.js +6 -7
- package/dist/websocket/events.js +1 -2
- package/dist/websocket/index.d.ts +19 -2
- package/dist/websocket/index.js +80 -5
- package/package.json +2 -3
- package/dist/api/client.d.ts +0 -14
- package/dist/api/client.js +0 -45
- package/dist/bridge/client.d.ts +0 -151
- package/dist/bridge/client.js +0 -434
- package/dist/bridge/const.d.ts +0 -23
- package/dist/bridge/const.js +0 -47
- package/dist/bridge/index.d.ts +0 -4
- package/dist/bridge/index.js +0 -23
- package/dist/bridge/types.d.ts +0 -120
- package/dist/bridge/types.js +0 -18
- package/dist/bridge/utils.d.ts +0 -64
- package/dist/bridge/utils.js +0 -131
- package/dist/gen/common.d.ts +0 -68
- package/dist/gen/common.js +0 -215
- package/dist/gen/nord.d.ts +0 -882
- package/dist/gen/nord.js +0 -6520
- package/dist/idl/bridge.d.ts +0 -569
- package/dist/idl/bridge.js +0 -8
- package/dist/idl/bridge.json +0 -1506
- package/dist/idl/index.d.ts +0 -607
- package/dist/idl/index.js +0 -8
- package/dist/nord/api/actions.d.ts +0 -126
- package/dist/nord/api/actions.js +0 -397
- package/dist/nord/api/core.d.ts +0 -16
- package/dist/nord/api/core.js +0 -81
- package/dist/nord/api/market.d.ts +0 -36
- package/dist/nord/api/market.js +0 -96
- package/dist/nord/api/metrics.d.ts +0 -67
- package/dist/nord/api/metrics.js +0 -229
- package/dist/nord/api/queries.d.ts +0 -46
- package/dist/nord/api/queries.js +0 -109
- package/dist/nord/api/triggers.d.ts +0 -7
- package/dist/nord/api/triggers.js +0 -38
- package/dist/nord/client/NordClient.d.ts +0 -33
- package/dist/nord/client/NordClient.js +0 -45
- package/dist/nord/index.d.ts +0 -11
- package/dist/nord/index.js +0 -36
- package/src/const.ts +0 -34
- package/src/gen/.gitkeep +0 -0
- package/src/gen/nord_pb.ts +0 -5053
- package/src/gen/openapi.ts +0 -2864
- package/src/index.ts +0 -5
- package/src/nord/api/actions.ts +0 -648
- package/src/nord/api/core.ts +0 -96
- package/src/nord/api/metrics.ts +0 -269
- package/src/nord/client/Nord.ts +0 -937
- package/src/nord/client/NordAdmin.ts +0 -514
- package/src/nord/client/NordClient.ts +0 -79
- package/src/nord/client/NordUser.ts +0 -1211
- package/src/nord/index.ts +0 -25
- package/src/nord/models/Subscriber.ts +0 -56
- package/src/nord/utils/NordError.ts +0 -76
- package/src/types.ts +0 -377
- package/src/utils.ts +0 -269
- package/src/websocket/NordWebSocketClient.ts +0 -316
- package/src/websocket/events.ts +0 -31
- package/src/websocket/index.ts +0 -2
- /package/dist/{nord/utils/NordError.d.ts → error.d.ts} +0 -0
package/src/utils.ts
DELETED
|
@@ -1,269 +0,0 @@
|
|
|
1
|
-
import { Decimal } from "decimal.js";
|
|
2
|
-
import { ed25519 } from "@noble/curves/ed25519";
|
|
3
|
-
import { bls12_381 as bls } from "@noble/curves/bls12-381";
|
|
4
|
-
import { secp256k1 as secp } from "@noble/curves/secp256k1";
|
|
5
|
-
import { sha256 } from "@noble/hashes/sha256";
|
|
6
|
-
import { KeyType, type Market, type Token } from "./types";
|
|
7
|
-
import { sizeDelimitedPeek } from "@bufbuild/protobuf/wire";
|
|
8
|
-
import { fromBinary, type Message } from "@bufbuild/protobuf";
|
|
9
|
-
import type { GenMessage } from "@bufbuild/protobuf/codegenv2";
|
|
10
|
-
import { ethers } from "ethers";
|
|
11
|
-
import fetch from "node-fetch";
|
|
12
|
-
import { RequestInfo, RequestInit, Response } from "node-fetch";
|
|
13
|
-
import { Keypair } from "@solana/web3.js";
|
|
14
|
-
import bs58 from "bs58";
|
|
15
|
-
|
|
16
|
-
export const SESSION_TTL: bigint = 60n * 60n * 24n * 30n;
|
|
17
|
-
export const ZERO_DECIMAL = new Decimal(0);
|
|
18
|
-
export const MAX_BUFFER_LEN = 10_000;
|
|
19
|
-
|
|
20
|
-
// Max size of data returned from Nord endpoints
|
|
21
|
-
const MAX_PAYLOAD_SIZE = 100 * 1024; // 100 kB
|
|
22
|
-
|
|
23
|
-
/** Any type convertible to bigint */
|
|
24
|
-
export type BigIntValue = bigint | number | string;
|
|
25
|
-
|
|
26
|
-
export function panic(message: string): never {
|
|
27
|
-
throw new Error(message);
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export function isRfc3339(s: string): boolean {
|
|
31
|
-
const REGEX =
|
|
32
|
-
/^((?:(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2}(?:\.\d+)?))(Z|[\+-]\d{2}:\d{2})?)$/;
|
|
33
|
-
return REGEX.test(s);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export function assert(predicate: boolean, message?: string): void {
|
|
37
|
-
if (!predicate) panic(message ?? "Assertion violated");
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Extracts value out of optional if it's defined, or throws error if it's not
|
|
41
|
-
* @param value Optional value to unwrap
|
|
42
|
-
* @param message Error message
|
|
43
|
-
* @returns Unwrapped value
|
|
44
|
-
*/
|
|
45
|
-
export function optExpect<T>(value: T | undefined, message: string): T {
|
|
46
|
-
if (value === undefined) throw new Error(message);
|
|
47
|
-
return value as T;
|
|
48
|
-
}
|
|
49
|
-
/** Behaves same as `node-fetch/fetch` but throws if response is a failure
|
|
50
|
-
*
|
|
51
|
-
* @param url Request HTTP URL
|
|
52
|
-
* @param init Request parameters
|
|
53
|
-
* @returns Raw response if fetch succeeded
|
|
54
|
-
* @throws If response wasn't Ok
|
|
55
|
-
*/
|
|
56
|
-
export async function checkedFetch(
|
|
57
|
-
url: RequestInfo,
|
|
58
|
-
init?: RequestInit,
|
|
59
|
-
): Promise<Response> {
|
|
60
|
-
const resp = await fetch(url, init);
|
|
61
|
-
assert(resp.ok, `Request failed with ${resp.status}: ${resp.statusText}`);
|
|
62
|
-
return resp;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Signs an action using the specified secret key and key type.
|
|
67
|
-
* @param action - The action data to be signed.
|
|
68
|
-
* @param sk - Secret key used for signing the action.
|
|
69
|
-
* @param keyType - Type of the key used for signing.
|
|
70
|
-
* @returns A new Uint8Array containing the action followed by its signature.
|
|
71
|
-
*/
|
|
72
|
-
export function signAction(
|
|
73
|
-
action: Uint8Array,
|
|
74
|
-
sk: Uint8Array,
|
|
75
|
-
keyType: KeyType,
|
|
76
|
-
): Uint8Array {
|
|
77
|
-
let sig: Uint8Array;
|
|
78
|
-
if (keyType === KeyType.Ed25519) {
|
|
79
|
-
sig = ed25519.sign(action, sk);
|
|
80
|
-
} else if (keyType === KeyType.Bls12_381) {
|
|
81
|
-
sig = bls.sign(action, sk);
|
|
82
|
-
} else if (keyType === KeyType.Secp256k1) {
|
|
83
|
-
sig = secp.sign(sha256(action), sk).toCompactRawBytes();
|
|
84
|
-
} else {
|
|
85
|
-
throw new Error("Invalid key type");
|
|
86
|
-
}
|
|
87
|
-
return new Uint8Array([...action, ...sig]);
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Constructs wallet signing function, usable with `NordUser` type
|
|
92
|
-
*
|
|
93
|
-
* @param walletKey Either raw signing key as bytes array or hex string prefixed with `"0x"`
|
|
94
|
-
* @returns Async function which accepts arbitrary message, generates its digets,
|
|
95
|
-
* then signs it with provided user wallet key and returns signature
|
|
96
|
-
* as hex string prefixed with `"0x"`
|
|
97
|
-
*/
|
|
98
|
-
export function makeWalletSignFn(
|
|
99
|
-
walletKey: ethers.BytesLike,
|
|
100
|
-
): (message: Uint8Array | string) => Promise<string> {
|
|
101
|
-
const signingKey = new ethers.SigningKey(walletKey);
|
|
102
|
-
return async (message) =>
|
|
103
|
-
signingKey.sign(ethers.hashMessage(message)).serialized;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// Returned numbers do fit into specified bits range, or error is thrown.
|
|
107
|
-
function makeToScaledBigUint(params: {
|
|
108
|
-
precision: number;
|
|
109
|
-
exponent: number;
|
|
110
|
-
bits: number;
|
|
111
|
-
}): (x: Decimal.Value, decimals: number) => bigint {
|
|
112
|
-
const Dec = Decimal.clone({
|
|
113
|
-
precision: params.precision,
|
|
114
|
-
toExpPos: params.exponent,
|
|
115
|
-
toExpNeg: -params.exponent,
|
|
116
|
-
});
|
|
117
|
-
|
|
118
|
-
const Ten = new Dec(10);
|
|
119
|
-
|
|
120
|
-
const Max = new Dec(((1n << BigInt(params.bits)) - 1n).toString());
|
|
121
|
-
|
|
122
|
-
return (x, decimals) => {
|
|
123
|
-
const dec = new Dec(x);
|
|
124
|
-
|
|
125
|
-
if (dec.isZero()) {
|
|
126
|
-
return 0n;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
if (dec.isNeg()) {
|
|
130
|
-
throw new Error(`Number is negative`);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
const scaled = Ten.pow(decimals).mul(dec).truncated();
|
|
134
|
-
if (scaled.isZero()) {
|
|
135
|
-
throw new Error(
|
|
136
|
-
`Precision loss when converting ${dec} to scaled integer`,
|
|
137
|
-
);
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
if (scaled.greaterThan(Max)) {
|
|
141
|
-
throw new Error(
|
|
142
|
-
`Integer is out of range: ${scaled} exceeds limit ${Max}`,
|
|
143
|
-
);
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
return BigInt(scaled.toString());
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
/**
|
|
150
|
-
* Converts decimal value into rescaled 64-bit unsigned integer
|
|
151
|
-
* by scaling it up by specified number of decimal digits.
|
|
152
|
-
*
|
|
153
|
-
* Ensures that number won't accidentally become zero
|
|
154
|
-
* or exceed U64's value range
|
|
155
|
-
*
|
|
156
|
-
* @param x Decimal value to rescale
|
|
157
|
-
* @param decimals Number of decimal digits
|
|
158
|
-
* @returns Rescaled unsigned integer
|
|
159
|
-
*/
|
|
160
|
-
export const toScaledU64 = makeToScaledBigUint({
|
|
161
|
-
bits: 64,
|
|
162
|
-
precision: 20,
|
|
163
|
-
exponent: 28,
|
|
164
|
-
});
|
|
165
|
-
/**
|
|
166
|
-
* Converts decimal value into rescaled 128-bit unsigned integer
|
|
167
|
-
* by scaling it up by specified number of decimal digits.
|
|
168
|
-
*
|
|
169
|
-
* Ensures that number won't accidentally become zero
|
|
170
|
-
* or exceed U128's value range
|
|
171
|
-
*
|
|
172
|
-
* @param x Decimal value to rescale
|
|
173
|
-
* @param decimals Number of decimal digits
|
|
174
|
-
* @returns Rescaled unsigned integer
|
|
175
|
-
*/
|
|
176
|
-
export const toScaledU128 = makeToScaledBigUint({
|
|
177
|
-
bits: 128,
|
|
178
|
-
precision: 40,
|
|
179
|
-
exponent: 56,
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* Decodes any protobuf message from a length-delimited format,
|
|
184
|
-
* i.e. prefixed with its length encoded as varint
|
|
185
|
-
*
|
|
186
|
-
* @param bytes Byte array with encoded message
|
|
187
|
-
* @param schema Message schema for decoding
|
|
188
|
-
* @returns Decoded message
|
|
189
|
-
*/
|
|
190
|
-
export function decodeLengthDelimited<T extends Message>(
|
|
191
|
-
bytes: Uint8Array,
|
|
192
|
-
schema: GenMessage<T>,
|
|
193
|
-
): T {
|
|
194
|
-
// use sizeDelimitedPeek to extract the message length and offset
|
|
195
|
-
const peekResult = sizeDelimitedPeek(bytes);
|
|
196
|
-
|
|
197
|
-
if (peekResult.size === null || peekResult.offset === null) {
|
|
198
|
-
throw new Error("Failed to parse size-delimited message");
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
if (peekResult.size > MAX_PAYLOAD_SIZE) {
|
|
202
|
-
throw new Error(
|
|
203
|
-
`Encoded message size (${peekResult.size} bytes) is greater than max payload size (${MAX_PAYLOAD_SIZE} bytes).`,
|
|
204
|
-
);
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
if (peekResult.offset + peekResult.size > bytes.length) {
|
|
208
|
-
throw new Error(
|
|
209
|
-
`Encoded message size (${peekResult.size} bytes) is greater than remaining buffer size (${bytes.length - peekResult.offset} bytes).`,
|
|
210
|
-
);
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
// decode the message using the offset and size from peek
|
|
214
|
-
return fromBinary(
|
|
215
|
-
schema,
|
|
216
|
-
bytes.slice(peekResult.offset, peekResult.offset + peekResult.size),
|
|
217
|
-
);
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
export function checkPubKeyLength(keyType: KeyType, len: number): void {
|
|
221
|
-
if (keyType === KeyType.Bls12_381) {
|
|
222
|
-
throw new Error(
|
|
223
|
-
"Cannot create a user using Bls12_381, use Ed25119 or Secp256k1 instead.",
|
|
224
|
-
);
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
if (len !== 32 && keyType === KeyType.Ed25519) {
|
|
228
|
-
throw new Error("Ed25519 pubkeys must be 32 length.");
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
if (len !== 33 && keyType === KeyType.Secp256k1) {
|
|
232
|
-
throw new Error("Secp256k1 pubkeys must be 33 length.");
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
export function decodeHex(value: string): Uint8Array {
|
|
237
|
-
const hex = value.startsWith("0x") ? value.slice(2) : value;
|
|
238
|
-
return Uint8Array.from(Buffer.from(hex, "hex"));
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
export function findMarket(markets: Market[], marketId: number): Market {
|
|
242
|
-
if (marketId < 0 || markets.length - 1 < marketId) {
|
|
243
|
-
throw new Error(`The market with marketId=${marketId} not found`);
|
|
244
|
-
}
|
|
245
|
-
return markets[marketId];
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
export function findToken(tokens: Token[], tokenId: number): Token {
|
|
249
|
-
if (tokenId < 0 || tokens.length - 1 < tokenId) {
|
|
250
|
-
throw new Error(`The token with tokenId=${tokenId} not found`);
|
|
251
|
-
}
|
|
252
|
-
return tokens[tokenId];
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
export function keypairFromPrivateKey(
|
|
256
|
-
privateKey: string | Uint8Array,
|
|
257
|
-
): Keypair {
|
|
258
|
-
if (typeof privateKey === "string") {
|
|
259
|
-
if (!privateKey.startsWith("0x")) {
|
|
260
|
-
return Keypair.fromSecretKey(bs58.decode(privateKey));
|
|
261
|
-
}
|
|
262
|
-
const hex = privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey;
|
|
263
|
-
const bytes = new Uint8Array(
|
|
264
|
-
hex.match(/.{1,2}/g)!.map((byte) => parseInt(byte, 16)),
|
|
265
|
-
);
|
|
266
|
-
return Keypair.fromSecretKey(bytes);
|
|
267
|
-
}
|
|
268
|
-
return Keypair.fromSecretKey(privateKey);
|
|
269
|
-
}
|
|
@@ -1,316 +0,0 @@
|
|
|
1
|
-
import { EventEmitter } from "events";
|
|
2
|
-
import WebSocket from "ws";
|
|
3
|
-
import {
|
|
4
|
-
WebSocketAccountUpdate,
|
|
5
|
-
WebSocketDeltaUpdate,
|
|
6
|
-
WebSocketMessage,
|
|
7
|
-
WebSocketTradeUpdate,
|
|
8
|
-
} from "../types";
|
|
9
|
-
import { NordWebSocketClientEvents } from "./events";
|
|
10
|
-
|
|
11
|
-
// Define a type that works for both Node.js ws and browser WebSocket
|
|
12
|
-
type BrowserWebSocket = {
|
|
13
|
-
OPEN: number;
|
|
14
|
-
CONNECTING: number;
|
|
15
|
-
CLOSING: number;
|
|
16
|
-
CLOSED: number;
|
|
17
|
-
readyState: number;
|
|
18
|
-
send: (data: string) => void;
|
|
19
|
-
close: () => void;
|
|
20
|
-
onopen: ((this: any, ev: any) => any) | null;
|
|
21
|
-
onmessage: ((this: any, ev: { data: any }) => any) | null;
|
|
22
|
-
onclose: ((this: any, ev: any) => any) | null;
|
|
23
|
-
onerror: ((this: any, ev: any) => any) | null;
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
type WebSocketInstance = WebSocket | BrowserWebSocket;
|
|
27
|
-
|
|
28
|
-
const VALID_STREAM_TYPES = ["trades", "delta", "account"];
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* WebSocket client for Nord exchange
|
|
32
|
-
*
|
|
33
|
-
* This client connects to one of the specific Nord WebSocket endpoints:
|
|
34
|
-
*
|
|
35
|
-
* Each endpoint handles a specific type of data and subscriptions must match
|
|
36
|
-
* the endpoint type (e.g., only 'trades@BTCUSDC' subscriptions are valid on
|
|
37
|
-
* the /ws/trades endpoint).
|
|
38
|
-
*/
|
|
39
|
-
export class NordWebSocketClient
|
|
40
|
-
extends EventEmitter
|
|
41
|
-
implements NordWebSocketClientEvents
|
|
42
|
-
{
|
|
43
|
-
private ws: WebSocketInstance | null = null;
|
|
44
|
-
private url: string;
|
|
45
|
-
private reconnectAttempts: number = 0;
|
|
46
|
-
private maxReconnectAttempts: number = 5;
|
|
47
|
-
private reconnectDelay: number = 1000;
|
|
48
|
-
private pingInterval: NodeJS.Timeout | null = null;
|
|
49
|
-
private pingTimeout: NodeJS.Timeout | null = null;
|
|
50
|
-
private isBrowser: boolean;
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Create a new NordWebSocketClient
|
|
54
|
-
* @param url WebSocket server URL
|
|
55
|
-
*/
|
|
56
|
-
constructor(url: string) {
|
|
57
|
-
super();
|
|
58
|
-
this.url = url;
|
|
59
|
-
// Check if we're in a browser environment
|
|
60
|
-
// The most reliable way is to check for Node.js process
|
|
61
|
-
this.isBrowser =
|
|
62
|
-
typeof process === "undefined" ||
|
|
63
|
-
!process.versions ||
|
|
64
|
-
!process.versions.node;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* Validate stream format
|
|
69
|
-
* @param stream Stream identifier to validate
|
|
70
|
-
* @throws Error if stream format is invalid
|
|
71
|
-
*/
|
|
72
|
-
private validateStream(stream: string): void {
|
|
73
|
-
const [type, params] = stream.split("@");
|
|
74
|
-
|
|
75
|
-
if (!type || !params) {
|
|
76
|
-
throw new Error(
|
|
77
|
-
`Invalid stream format: ${stream}. Expected format: <type>@<params>`,
|
|
78
|
-
);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// Extract the endpoint from the URL
|
|
82
|
-
const urlPath = new URL(this.url).pathname;
|
|
83
|
-
const endpoint = urlPath.split("/").pop();
|
|
84
|
-
|
|
85
|
-
// Ensure the stream type matches the endpoint we're connected to
|
|
86
|
-
if (endpoint && type !== endpoint) {
|
|
87
|
-
throw new Error(
|
|
88
|
-
`Stream type '${type}' doesn't match the connected endpoint '${endpoint}'`,
|
|
89
|
-
);
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
if (!VALID_STREAM_TYPES.includes(type)) {
|
|
93
|
-
throw new Error(
|
|
94
|
-
`Invalid stream type: ${type}. Valid types are: ${VALID_STREAM_TYPES.join(", ")}`,
|
|
95
|
-
);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
if (type === "account" && !/^\d+$/.test(params)) {
|
|
99
|
-
throw new Error(
|
|
100
|
-
`Invalid account ID in stream: ${params}. Expected numeric ID`,
|
|
101
|
-
);
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* Setup WebSocket ping/pong heartbeat
|
|
107
|
-
*/
|
|
108
|
-
private setupHeartbeat(): void {
|
|
109
|
-
if (this.pingInterval) {
|
|
110
|
-
clearInterval(this.pingInterval);
|
|
111
|
-
}
|
|
112
|
-
if (this.pingTimeout) {
|
|
113
|
-
clearTimeout(this.pingTimeout);
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// In browser, we rely on the browser's WebSocket implementation to handle ping/pong
|
|
117
|
-
if (this.isBrowser) {
|
|
118
|
-
return;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
this.pingInterval = setInterval(() => {
|
|
122
|
-
if (this.ws && !this.isBrowser) {
|
|
123
|
-
// Only use ping() method in Node.js environment
|
|
124
|
-
(this.ws as WebSocket).ping();
|
|
125
|
-
|
|
126
|
-
// Set timeout for pong response
|
|
127
|
-
this.pingTimeout = setTimeout(() => {
|
|
128
|
-
this.emit("error", new Error("WebSocket ping timeout"));
|
|
129
|
-
this.close();
|
|
130
|
-
this.reconnect();
|
|
131
|
-
}, 5000); // 5 second timeout
|
|
132
|
-
}
|
|
133
|
-
}, 30000); // Send ping every 30 seconds
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Get the appropriate WebSocket class based on environment
|
|
138
|
-
*/
|
|
139
|
-
private getWebSocketClass(): any {
|
|
140
|
-
if (this.isBrowser) {
|
|
141
|
-
// In browser environments
|
|
142
|
-
if (typeof globalThis !== "undefined" && globalThis.WebSocket) {
|
|
143
|
-
return globalThis.WebSocket;
|
|
144
|
-
}
|
|
145
|
-
throw new Error("WebSocket is not available in this environment");
|
|
146
|
-
} else {
|
|
147
|
-
// In Node.js
|
|
148
|
-
return WebSocket;
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/**
|
|
153
|
-
* Connect to the Nord WebSocket server
|
|
154
|
-
*/
|
|
155
|
-
public connect(): void {
|
|
156
|
-
if (this.ws) {
|
|
157
|
-
return;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
try {
|
|
161
|
-
const WebSocketClass = this.getWebSocketClass();
|
|
162
|
-
|
|
163
|
-
if (this.isBrowser) {
|
|
164
|
-
// Browser WebSocket setup
|
|
165
|
-
this.ws = new WebSocketClass(this.url) as BrowserWebSocket;
|
|
166
|
-
|
|
167
|
-
(this.ws as BrowserWebSocket).onopen = () => {
|
|
168
|
-
this.emit("connected");
|
|
169
|
-
this.reconnectAttempts = 0;
|
|
170
|
-
this.reconnectDelay = 1000;
|
|
171
|
-
};
|
|
172
|
-
|
|
173
|
-
(this.ws as BrowserWebSocket).onmessage = (event: { data: any }) => {
|
|
174
|
-
try {
|
|
175
|
-
const message = JSON.parse(
|
|
176
|
-
event.data as string,
|
|
177
|
-
) as WebSocketMessage;
|
|
178
|
-
this.handleMessage(message);
|
|
179
|
-
} catch (error) {
|
|
180
|
-
this.emit(
|
|
181
|
-
"error",
|
|
182
|
-
new Error(
|
|
183
|
-
`Failed to parse message: ${error instanceof Error ? error.message : String(error)}`,
|
|
184
|
-
),
|
|
185
|
-
);
|
|
186
|
-
}
|
|
187
|
-
};
|
|
188
|
-
|
|
189
|
-
(this.ws as BrowserWebSocket).onclose = (_event: any) => {
|
|
190
|
-
this.emit("disconnected");
|
|
191
|
-
this.reconnect();
|
|
192
|
-
};
|
|
193
|
-
|
|
194
|
-
(this.ws as BrowserWebSocket).onerror = (event: any) => {
|
|
195
|
-
const errorMsg = `WebSocket error: ${event && event.type ? event.type : "unknown"}`;
|
|
196
|
-
this.emit("error", new Error(errorMsg));
|
|
197
|
-
};
|
|
198
|
-
} else {
|
|
199
|
-
// Node.js WebSocket setup
|
|
200
|
-
const nodeWs = new WebSocketClass(this.url) as WebSocket;
|
|
201
|
-
this.ws = nodeWs;
|
|
202
|
-
|
|
203
|
-
nodeWs.on("open", () => {
|
|
204
|
-
this.emit("connected");
|
|
205
|
-
this.reconnectAttempts = 0;
|
|
206
|
-
this.reconnectDelay = 1000;
|
|
207
|
-
this.setupHeartbeat();
|
|
208
|
-
});
|
|
209
|
-
|
|
210
|
-
nodeWs.on("message", (data: WebSocket.Data) => {
|
|
211
|
-
try {
|
|
212
|
-
const message = JSON.parse(data.toString()) as WebSocketMessage;
|
|
213
|
-
this.handleMessage(message);
|
|
214
|
-
} catch (error) {
|
|
215
|
-
this.emit(
|
|
216
|
-
"error",
|
|
217
|
-
new Error(
|
|
218
|
-
`Failed to parse message: ${error instanceof Error ? error.message : String(error)}`,
|
|
219
|
-
),
|
|
220
|
-
);
|
|
221
|
-
}
|
|
222
|
-
});
|
|
223
|
-
|
|
224
|
-
nodeWs.on("close", (_code: number, _reason: string) => {
|
|
225
|
-
this.emit("disconnected");
|
|
226
|
-
if (this.pingInterval) {
|
|
227
|
-
clearInterval(this.pingInterval);
|
|
228
|
-
}
|
|
229
|
-
if (this.pingTimeout) {
|
|
230
|
-
clearTimeout(this.pingTimeout);
|
|
231
|
-
}
|
|
232
|
-
this.reconnect();
|
|
233
|
-
});
|
|
234
|
-
|
|
235
|
-
nodeWs.on("error", (error: Error) => {
|
|
236
|
-
this.emit("error", error);
|
|
237
|
-
});
|
|
238
|
-
|
|
239
|
-
nodeWs.on("pong", () => {
|
|
240
|
-
if (this.pingTimeout) {
|
|
241
|
-
clearTimeout(this.pingTimeout);
|
|
242
|
-
}
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
} catch (error) {
|
|
246
|
-
const errorMsg = `Failed to initialize WebSocket: ${error instanceof Error ? error.message : String(error)}`;
|
|
247
|
-
this.emit("error", new Error(errorMsg));
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
/**
|
|
252
|
-
* Close the WebSocket connection
|
|
253
|
-
*/
|
|
254
|
-
public close(): void {
|
|
255
|
-
if (this.ws) {
|
|
256
|
-
if (this.isBrowser) {
|
|
257
|
-
(this.ws as BrowserWebSocket).close();
|
|
258
|
-
} else {
|
|
259
|
-
(this.ws as WebSocket).close();
|
|
260
|
-
}
|
|
261
|
-
this.ws = null;
|
|
262
|
-
}
|
|
263
|
-
if (this.pingInterval) {
|
|
264
|
-
clearInterval(this.pingInterval);
|
|
265
|
-
this.pingInterval = null;
|
|
266
|
-
}
|
|
267
|
-
if (this.pingTimeout) {
|
|
268
|
-
clearTimeout(this.pingTimeout);
|
|
269
|
-
this.pingTimeout = null;
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/**
|
|
274
|
-
* Handle incoming WebSocket messages
|
|
275
|
-
* @param message WebSocket message
|
|
276
|
-
*/
|
|
277
|
-
private handleMessage(message: WebSocketMessage): void {
|
|
278
|
-
if (!message || typeof message !== "object") {
|
|
279
|
-
this.emit("error", new Error(`Unexpected message type: ${message}`));
|
|
280
|
-
return;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
const hasOwn = (k: string) =>
|
|
284
|
-
Object.prototype.hasOwnProperty.call(message, k);
|
|
285
|
-
if (hasOwn("trades")) {
|
|
286
|
-
this.emit("trades", message as WebSocketTradeUpdate);
|
|
287
|
-
return;
|
|
288
|
-
}
|
|
289
|
-
if (hasOwn("delta")) {
|
|
290
|
-
this.emit("delta", message as WebSocketDeltaUpdate);
|
|
291
|
-
return;
|
|
292
|
-
}
|
|
293
|
-
if (hasOwn("account")) {
|
|
294
|
-
this.emit("account", message as WebSocketAccountUpdate);
|
|
295
|
-
return;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
this.emit("error", new Error(`Unexpected message type: ${message}`));
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
/**
|
|
302
|
-
* Attempt to reconnect to the WebSocket server
|
|
303
|
-
*/
|
|
304
|
-
private reconnect(): void {
|
|
305
|
-
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
306
|
-
this.emit("error", new Error("Max reconnection attempts reached"));
|
|
307
|
-
return;
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
setTimeout(() => {
|
|
311
|
-
this.reconnectAttempts++;
|
|
312
|
-
this.reconnectDelay *= 2; // Exponential backoff
|
|
313
|
-
this.connect();
|
|
314
|
-
}, this.reconnectDelay);
|
|
315
|
-
}
|
|
316
|
-
}
|
package/src/websocket/events.ts
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
WebSocketTradeUpdate,
|
|
3
|
-
WebSocketDeltaUpdate,
|
|
4
|
-
WebSocketAccountUpdate,
|
|
5
|
-
} from "../types";
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Event type definitions for the NordWebSocketClient
|
|
9
|
-
*/
|
|
10
|
-
export interface NordWebSocketEvents {
|
|
11
|
-
connected: () => void;
|
|
12
|
-
disconnected: () => void;
|
|
13
|
-
error: (error: Error) => void;
|
|
14
|
-
trade: (update: WebSocketTradeUpdate) => void;
|
|
15
|
-
delta: (update: WebSocketDeltaUpdate) => void;
|
|
16
|
-
account: (update: WebSocketAccountUpdate) => void;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Type declaration for NordWebSocketClient event methods
|
|
21
|
-
*/
|
|
22
|
-
export declare interface NordWebSocketClientEvents {
|
|
23
|
-
on<E extends keyof NordWebSocketEvents>(
|
|
24
|
-
event: E,
|
|
25
|
-
listener: NordWebSocketEvents[E],
|
|
26
|
-
): this;
|
|
27
|
-
emit<E extends keyof NordWebSocketEvents>(
|
|
28
|
-
event: E,
|
|
29
|
-
...args: Parameters<NordWebSocketEvents[E]>
|
|
30
|
-
): boolean;
|
|
31
|
-
}
|
package/src/websocket/index.ts
DELETED
|
File without changes
|