@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
package/dist/utils.d.ts DELETED
@@ -1,116 +0,0 @@
1
- import { Decimal } from "decimal.js";
2
- import { KeyType, type Market, type Token } from "./types";
3
- import * as proto from "./gen/nord";
4
- import { ethers } from "ethers";
5
- import { RequestInfo, RequestInit, Response } from "node-fetch";
6
- import { Keypair } from "@solana/web3.js";
7
- export declare const SESSION_TTL: bigint;
8
- export declare const ZERO_DECIMAL: Decimal;
9
- export declare const MAX_BUFFER_LEN = 10000;
10
- /** Any type convertible to bigint */
11
- export type BigIntValue = bigint | number | string;
12
- export declare function panic(message: string): never;
13
- export declare function assert(predicate: boolean, message?: string): void;
14
- /**
15
- * Extracts value out of optional if it's defined, or throws error if it's not
16
- * @param value Optional value to unwrap
17
- * @param message Error message
18
- * @returns Unwrapped value
19
- */
20
- export declare function optExpect<T>(value: T | undefined, message: string): T;
21
- /**
22
- * Unwraps optional value with default error message
23
- * @param value
24
- * @returns
25
- */
26
- export declare function optUnwrap<T>(value: T | undefined): T;
27
- /**
28
- * Applies function to value if it's defined, or passes `undefined` through
29
- * @param value Optional value to map
30
- * @param mapFn Mapper function
31
- * @returns Either mapped value or undefined
32
- */
33
- export declare function optMap<T, U>(value: T | undefined, mapFn: (arg: T) => U): U | undefined;
34
- /** Behaves same as `node-fetch/fetch` but throws if response is a failure
35
- *
36
- * @param url Request HTTP URL
37
- * @param init Request parameters
38
- * @returns Raw response if fetch succeeded
39
- * @throws If response wasn't Ok
40
- */
41
- export declare function checkedFetch(url: RequestInfo, init?: RequestInit): Promise<Response>;
42
- /**
43
- * Signs an action using the specified secret key and key type.
44
- * @param action - The action data to be signed.
45
- * @param sk - Secret key used for signing the action.
46
- * @param keyType - Type of the key used for signing.
47
- * @returns A new Uint8Array containing the action followed by its signature.
48
- */
49
- export declare function signAction(action: Uint8Array, sk: Uint8Array, keyType: KeyType): Uint8Array;
50
- /**
51
- * Constructs wallet signing function, usable with `NordUser` type
52
- *
53
- * @param walletKey Either raw signing key as bytes array or hex string prefixed with `"0x"`
54
- * @returns Async function which accepts arbitrary message, generates its digets,
55
- * then signs it with provided user wallet key and returns signature
56
- * as hex string prefixed with `"0x"`
57
- */
58
- export declare function makeWalletSignFn(walletKey: ethers.BytesLike): (message: Uint8Array | string) => Promise<string>;
59
- /**
60
- * Converts decimal value into rescaled 64-bit unsigned integer
61
- * by scaling it up by specified number of decimal digits.
62
- *
63
- * Ensures that number won't accidentally become zero
64
- * or exceed U64's value range
65
- *
66
- * @param x Decimal value to rescale
67
- * @param decimals Number of decimal digits
68
- * @returns Rescaled unsigned integer
69
- */
70
- export declare const toScaledU64: (x: Decimal.Value, decimals: number) => bigint;
71
- /**
72
- * Converts decimal value into rescaled 128-bit unsigned integer
73
- * by scaling it up by specified number of decimal digits.
74
- *
75
- * Ensures that number won't accidentally become zero
76
- * or exceed U128's value range
77
- *
78
- * @param x Decimal value to rescale
79
- * @param decimals Number of decimal digits
80
- * @returns Rescaled unsigned integer
81
- */
82
- export declare const toScaledU128: (x: Decimal.Value, decimals: number) => bigint;
83
- /**
84
- * Converts U128 into pair of U64 numbers, to pass it through protobuf
85
- * @param value integer, must fit U128 limits
86
- * @returns Pair of U64 integers which represent original number split in two
87
- */
88
- export declare function bigIntToProtoU128(value: bigint): proto.U128;
89
- /**
90
- * Encodes any protobuf message into a length-delimited format,
91
- * i.e. prefixed with its length encoded as varint
92
- * @param message message object
93
- * @param coder associated coder object which implements `MessageFns` interface
94
- * @returns Encoded message as Uint8Array, prefixed with its length
95
- */
96
- export declare function encodeLengthDelimited<T, M extends proto.MessageFns<T>>(message: T, coder: M): Uint8Array;
97
- /**
98
- * Decodes any protobuf message from a length-delimited format,
99
- * i.e. prefixed with its length encoded as varint
100
- *
101
- * NB: Please note that due to limitations of Typescript type inference
102
- * it requires to specify variable type explicitly:
103
- *
104
- * ```
105
- * const foo: proto.Bar = decodeLengthDelimited(bytes, proto.Bar);
106
- * ```
107
- *
108
- * @param bytes Byte array with encoded message
109
- * @param coder associated coder object which implements `MessageFns` interface
110
- * @returns Decoded Action as Uint8Array.
111
- */
112
- export declare function decodeLengthDelimited<T, M extends proto.MessageFns<T>>(bytes: Uint8Array, coder: M): T;
113
- export declare function checkPubKeyLength(keyType: KeyType, len: number): void;
114
- export declare function findMarket(markets: Market[], marketId: number): Market;
115
- export declare function findToken(tokens: Token[], tokenId: number): Token;
116
- export declare function keypairFromPrivateKey(privateKey: string | Uint8Array): Keypair;
package/dist/utils.js DELETED
@@ -1,271 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.toScaledU128 = exports.toScaledU64 = exports.MAX_BUFFER_LEN = exports.ZERO_DECIMAL = exports.SESSION_TTL = void 0;
7
- exports.panic = panic;
8
- exports.assert = assert;
9
- exports.optExpect = optExpect;
10
- exports.optUnwrap = optUnwrap;
11
- exports.optMap = optMap;
12
- exports.checkedFetch = checkedFetch;
13
- exports.signAction = signAction;
14
- exports.makeWalletSignFn = makeWalletSignFn;
15
- exports.bigIntToProtoU128 = bigIntToProtoU128;
16
- exports.encodeLengthDelimited = encodeLengthDelimited;
17
- exports.decodeLengthDelimited = decodeLengthDelimited;
18
- exports.checkPubKeyLength = checkPubKeyLength;
19
- exports.findMarket = findMarket;
20
- exports.findToken = findToken;
21
- exports.keypairFromPrivateKey = keypairFromPrivateKey;
22
- const decimal_js_1 = require("decimal.js");
23
- const ed25519_1 = require("@noble/curves/ed25519");
24
- const bls12_381_1 = require("@noble/curves/bls12-381");
25
- const secp256k1_1 = require("@noble/curves/secp256k1");
26
- const sha256_1 = require("@noble/hashes/sha256");
27
- const types_1 = require("./types");
28
- const wire_1 = require("@bufbuild/protobuf/wire");
29
- const ethers_1 = require("ethers");
30
- const node_fetch_1 = __importDefault(require("node-fetch"));
31
- const web3_js_1 = require("@solana/web3.js");
32
- const bs58_1 = __importDefault(require("bs58"));
33
- exports.SESSION_TTL = 60n * 60n * 24n * 30n;
34
- exports.ZERO_DECIMAL = new decimal_js_1.Decimal(0);
35
- exports.MAX_BUFFER_LEN = 10000;
36
- const MAX_PAYLOAD_SIZE = 100 * 1024; // 100 kB
37
- function panic(message) {
38
- throw new Error(message);
39
- }
40
- function assert(predicate, message) {
41
- if (!predicate)
42
- panic(message ?? "Assertion violated");
43
- }
44
- /**
45
- * Extracts value out of optional if it's defined, or throws error if it's not
46
- * @param value Optional value to unwrap
47
- * @param message Error message
48
- * @returns Unwrapped value
49
- */
50
- function optExpect(value, message) {
51
- if (value === undefined)
52
- throw new Error(message);
53
- return value;
54
- }
55
- /**
56
- * Unwraps optional value with default error message
57
- * @param value
58
- * @returns
59
- */
60
- function optUnwrap(value) {
61
- return optExpect(value, "Optional contains no value");
62
- }
63
- /**
64
- * Applies function to value if it's defined, or passes `undefined` through
65
- * @param value Optional value to map
66
- * @param mapFn Mapper function
67
- * @returns Either mapped value or undefined
68
- */
69
- function optMap(value, mapFn) {
70
- return value !== undefined ? mapFn(value) : undefined;
71
- }
72
- /** Behaves same as `node-fetch/fetch` but throws if response is a failure
73
- *
74
- * @param url Request HTTP URL
75
- * @param init Request parameters
76
- * @returns Raw response if fetch succeeded
77
- * @throws If response wasn't Ok
78
- */
79
- async function checkedFetch(url, init) {
80
- const resp = await (0, node_fetch_1.default)(url, init);
81
- assert(resp.ok, `Request failed with ${resp.status}: ${resp.statusText}`);
82
- return resp;
83
- }
84
- /**
85
- * Signs an action using the specified secret key and key type.
86
- * @param action - The action data to be signed.
87
- * @param sk - Secret key used for signing the action.
88
- * @param keyType - Type of the key used for signing.
89
- * @returns A new Uint8Array containing the action followed by its signature.
90
- */
91
- function signAction(action, sk, keyType) {
92
- let sig;
93
- if (keyType === types_1.KeyType.Ed25519) {
94
- sig = ed25519_1.ed25519.sign(action, sk);
95
- }
96
- else if (keyType === types_1.KeyType.Bls12_381) {
97
- sig = bls12_381_1.bls12_381.sign(action, sk);
98
- }
99
- else if (keyType === types_1.KeyType.Secp256k1) {
100
- sig = secp256k1_1.secp256k1.sign((0, sha256_1.sha256)(action), sk).toCompactRawBytes();
101
- }
102
- else {
103
- throw new Error("Invalid key type");
104
- }
105
- return new Uint8Array([...action, ...sig]);
106
- }
107
- /**
108
- * Constructs wallet signing function, usable with `NordUser` type
109
- *
110
- * @param walletKey Either raw signing key as bytes array or hex string prefixed with `"0x"`
111
- * @returns Async function which accepts arbitrary message, generates its digets,
112
- * then signs it with provided user wallet key and returns signature
113
- * as hex string prefixed with `"0x"`
114
- */
115
- function makeWalletSignFn(walletKey) {
116
- const signingKey = new ethers_1.ethers.SigningKey(walletKey);
117
- return async (message) => signingKey.sign(ethers_1.ethers.hashMessage(message)).serialized;
118
- }
119
- function makeToScaledBigUint(params) {
120
- const Dec = decimal_js_1.Decimal.clone({
121
- precision: params.precision,
122
- toExpPos: params.exponent,
123
- toExpNeg: -params.exponent,
124
- });
125
- const Ten = new Dec(10);
126
- const Max = new Dec(((1n << BigInt(params.bits)) - 1n).toString());
127
- return (x, decimals) => {
128
- const dec = new Dec(x);
129
- if (dec.isZero()) {
130
- return 0n;
131
- }
132
- if (dec.isNeg()) {
133
- throw new Error(`Number is negative`);
134
- }
135
- const scaled = Ten.pow(decimals).mul(dec).truncated();
136
- if (scaled.isZero()) {
137
- throw new Error(`Precision loss when converting ${dec} to scaled integer`);
138
- }
139
- if (scaled.greaterThan(Max)) {
140
- throw new Error(`Integer is out of range: ${scaled} exceeds limit ${Max}`);
141
- }
142
- return BigInt(scaled.toString());
143
- };
144
- }
145
- /**
146
- * Converts decimal value into rescaled 64-bit unsigned integer
147
- * by scaling it up by specified number of decimal digits.
148
- *
149
- * Ensures that number won't accidentally become zero
150
- * or exceed U64's value range
151
- *
152
- * @param x Decimal value to rescale
153
- * @param decimals Number of decimal digits
154
- * @returns Rescaled unsigned integer
155
- */
156
- exports.toScaledU64 = makeToScaledBigUint({
157
- bits: 64,
158
- precision: 20,
159
- exponent: 28,
160
- });
161
- /**
162
- * Converts decimal value into rescaled 128-bit unsigned integer
163
- * by scaling it up by specified number of decimal digits.
164
- *
165
- * Ensures that number won't accidentally become zero
166
- * or exceed U128's value range
167
- *
168
- * @param x Decimal value to rescale
169
- * @param decimals Number of decimal digits
170
- * @returns Rescaled unsigned integer
171
- */
172
- exports.toScaledU128 = makeToScaledBigUint({
173
- bits: 128,
174
- precision: 40,
175
- exponent: 56,
176
- });
177
- const U64_MAX = (1n << 64n) - 1n;
178
- const U128_MAX = (1n << 128n) - 1n;
179
- /**
180
- * Converts U128 into pair of U64 numbers, to pass it through protobuf
181
- * @param value integer, must fit U128 limits
182
- * @returns Pair of U64 integers which represent original number split in two
183
- */
184
- function bigIntToProtoU128(value) {
185
- if (value < 0n) {
186
- throw new Error(`Negative number (${value})`);
187
- }
188
- if (value > U128_MAX) {
189
- throw new Error(`U128 overflow (${value})`);
190
- }
191
- return {
192
- lo: value & U64_MAX,
193
- hi: (value >> 64n) & U64_MAX,
194
- };
195
- }
196
- /**
197
- * Encodes any protobuf message into a length-delimited format,
198
- * i.e. prefixed with its length encoded as varint
199
- * @param message message object
200
- * @param coder associated coder object which implements `MessageFns` interface
201
- * @returns Encoded message as Uint8Array, prefixed with its length
202
- */
203
- function encodeLengthDelimited(message, coder) {
204
- const encoded = coder.encode(message).finish();
205
- if (encoded.byteLength > MAX_PAYLOAD_SIZE) {
206
- throw new Error(`Encoded message size (${encoded.byteLength} bytes) is greater than max payload size (${MAX_PAYLOAD_SIZE} bytes).`);
207
- }
208
- const encodedLength = new wire_1.BinaryWriter().uint32(encoded.byteLength).finish();
209
- return new Uint8Array([...encodedLength, ...encoded]);
210
- }
211
- /**
212
- * Decodes any protobuf message from a length-delimited format,
213
- * i.e. prefixed with its length encoded as varint
214
- *
215
- * NB: Please note that due to limitations of Typescript type inference
216
- * it requires to specify variable type explicitly:
217
- *
218
- * ```
219
- * const foo: proto.Bar = decodeLengthDelimited(bytes, proto.Bar);
220
- * ```
221
- *
222
- * @param bytes Byte array with encoded message
223
- * @param coder associated coder object which implements `MessageFns` interface
224
- * @returns Decoded Action as Uint8Array.
225
- */
226
- function decodeLengthDelimited(bytes, coder) {
227
- const lengthReader = new wire_1.BinaryReader(bytes);
228
- const msgLength = lengthReader.uint32();
229
- const startsAt = lengthReader.pos;
230
- if (msgLength > MAX_PAYLOAD_SIZE) {
231
- throw new Error(`Encoded message size (${msgLength} bytes) is greater than max payload size (${MAX_PAYLOAD_SIZE} bytes).`);
232
- }
233
- if (startsAt + msgLength > bytes.byteLength) {
234
- throw new Error(`Encoded message size (${msgLength} bytes) is greater than remaining buffer size (${bytes.byteLength - startsAt} bytes).`);
235
- }
236
- return coder.decode(bytes.slice(startsAt, startsAt + msgLength));
237
- }
238
- function checkPubKeyLength(keyType, len) {
239
- if (keyType === types_1.KeyType.Bls12_381) {
240
- throw new Error("Cannot create a user using Bls12_381, use Ed25119 or Secp256k1 instead.");
241
- }
242
- if (len !== 32 && keyType === types_1.KeyType.Ed25519) {
243
- throw new Error("Ed25519 pubkeys must be 32 length.");
244
- }
245
- if (len !== 33 && keyType === types_1.KeyType.Secp256k1) {
246
- throw new Error("Secp256k1 pubkeys must be 33 length.");
247
- }
248
- }
249
- function findMarket(markets, marketId) {
250
- if (marketId < 0 || markets.length - 1 < marketId) {
251
- throw new Error(`The market with marketId=${marketId} not found`);
252
- }
253
- return markets[marketId];
254
- }
255
- function findToken(tokens, tokenId) {
256
- if (tokenId < 0 || tokens.length - 1 < tokenId) {
257
- throw new Error(`The token with tokenId=${tokenId} not found`);
258
- }
259
- return tokens[tokenId];
260
- }
261
- function keypairFromPrivateKey(privateKey) {
262
- if (typeof privateKey === "string") {
263
- if (!privateKey.startsWith("0x")) {
264
- return web3_js_1.Keypair.fromSecretKey(bs58_1.default.decode(privateKey));
265
- }
266
- const hex = privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey;
267
- const bytes = new Uint8Array(hex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
268
- return web3_js_1.Keypair.fromSecretKey(bytes);
269
- }
270
- return web3_js_1.Keypair.fromSecretKey(privateKey);
271
- }
@@ -1,68 +0,0 @@
1
- import { EventEmitter } from "events";
2
- import { NordWebSocketClientEvents } from "./events";
3
- /**
4
- * WebSocket client for Nord exchange
5
- *
6
- * This client connects to one of the specific Nord WebSocket endpoints:
7
- *
8
- * Each endpoint handles a specific type of data and subscriptions must match
9
- * the endpoint type (e.g., only 'trades@BTCUSDC' subscriptions are valid on
10
- * the /ws/trades endpoint).
11
- */
12
- export declare class NordWebSocketClient extends EventEmitter implements NordWebSocketClientEvents {
13
- private ws;
14
- private url;
15
- private subscriptions;
16
- private reconnectAttempts;
17
- private maxReconnectAttempts;
18
- private reconnectDelay;
19
- private pingInterval;
20
- private pingTimeout;
21
- private isBrowser;
22
- /**
23
- * Create a new NordWebSocketClient
24
- * @param url WebSocket server URL
25
- */
26
- constructor(url: string);
27
- /**
28
- * Validate stream format
29
- * @param stream Stream identifier to validate
30
- * @throws Error if stream format is invalid
31
- */
32
- private validateStream;
33
- /**
34
- * Setup WebSocket ping/pong heartbeat
35
- */
36
- private setupHeartbeat;
37
- /**
38
- * Get the appropriate WebSocket class based on environment
39
- */
40
- private getWebSocketClass;
41
- /**
42
- * Connect to the Nord WebSocket server
43
- */
44
- connect(): void;
45
- /**
46
- * Subscribe to one or more streams
47
- * @param streams Array of streams to subscribe to (e.g. ["trades@BTCUSDC", "deltas@BTCUSDC"])
48
- */
49
- subscribe(streams: string[]): void;
50
- /**
51
- * Unsubscribe from one or more streams
52
- * @param streams Array of streams to unsubscribe from
53
- */
54
- unsubscribe(streams: string[]): void;
55
- /**
56
- * Close the WebSocket connection
57
- */
58
- close(): void;
59
- /**
60
- * Handle incoming WebSocket messages
61
- * @param message WebSocket message
62
- */
63
- private handleMessage;
64
- /**
65
- * Attempt to reconnect to the WebSocket server
66
- */
67
- private reconnect;
68
- }