@n1xyz/nord-ts 0.3.3 → 0.3.4

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 (45) hide show
  1. package/dist/actions.js +184 -0
  2. package/dist/client/Nord.d.ts +1 -13
  3. package/dist/client/Nord.js +759 -0
  4. package/dist/client/NordAdmin.js +362 -0
  5. package/dist/client/NordUser.d.ts +3 -1
  6. package/dist/client/NordUser.js +752 -0
  7. package/dist/const.js +27 -0
  8. package/dist/error.js +51 -0
  9. package/dist/gen/nord_pb.d.ts +132 -114
  10. package/dist/gen/nord_pb.js +1068 -0
  11. package/dist/gen/openapi.d.ts +153 -123
  12. package/dist/gen/openapi.js +5 -0
  13. package/dist/index.browser.js +64196 -83277
  14. package/dist/index.common.js +60080 -86747
  15. package/dist/index.js +10 -0
  16. package/dist/nord/api/actions.d.ts +128 -0
  17. package/dist/nord/api/actions.js +396 -0
  18. package/dist/nord/api/core.d.ts +16 -0
  19. package/dist/nord/api/core.js +81 -0
  20. package/dist/nord/api/metrics.d.ts +67 -0
  21. package/dist/nord/api/metrics.js +229 -0
  22. package/dist/nord/api/triggers.d.ts +7 -0
  23. package/dist/nord/api/triggers.js +38 -0
  24. package/dist/nord/client/Nord.d.ts +387 -0
  25. package/dist/nord/client/Nord.js +747 -0
  26. package/dist/nord/client/NordAdmin.d.ts +226 -0
  27. package/dist/nord/client/NordAdmin.js +410 -0
  28. package/dist/nord/client/NordClient.d.ts +16 -0
  29. package/dist/nord/client/NordClient.js +28 -0
  30. package/dist/nord/client/NordUser.d.ts +379 -0
  31. package/dist/nord/client/NordUser.js +787 -0
  32. package/dist/nord/index.d.ts +8 -0
  33. package/dist/nord/index.js +34 -0
  34. package/dist/nord/models/Subscriber.d.ts +37 -0
  35. package/dist/nord/models/Subscriber.js +25 -0
  36. package/dist/nord/utils/NordError.d.ts +35 -0
  37. package/dist/nord/utils/NordError.js +49 -0
  38. package/dist/types.d.ts +2 -4
  39. package/dist/types.js +92 -0
  40. package/dist/utils.js +193 -0
  41. package/dist/websocket/NordWebSocketClient.js +242 -0
  42. package/dist/websocket/Subscriber.js +24 -0
  43. package/dist/websocket/events.js +1 -0
  44. package/dist/websocket/index.js +80 -0
  45. package/package.json +1 -1
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
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";
@@ -0,0 +1,128 @@
1
+ import Decimal from "decimal.js";
2
+ import * as proto from "../../gen/nord_pb";
3
+ import { paths } from "../../gen/openapi";
4
+ import { Client } from "openapi-fetch";
5
+ import { FillMode, Side, QuoteSize, TriggerKind } from "../../types";
6
+ import { BigIntValue } from "../../utils";
7
+ type ReceiptKind = NonNullable<proto.Receipt["kind"]>;
8
+ type ExtractReceiptKind<K extends ReceiptKind["case"]> = Extract<ReceiptKind, {
9
+ case: K;
10
+ }>;
11
+ export declare function formatReceiptError(receipt: proto.Receipt): string;
12
+ export declare function expectReceiptKind<K extends ReceiptKind["case"]>(receipt: proto.Receipt, expected: K, action: string): asserts receipt is proto.Receipt & {
13
+ kind: ExtractReceiptKind<K>;
14
+ };
15
+ export declare function createAction(currentTimestamp: bigint, nonce: number, kind: proto.Action["kind"]): proto.Action;
16
+ export declare function sendAction(serverUrl: string, makeSignedMessage: (message: Uint8Array) => Promise<Uint8Array>, action: proto.Action, client?: Client<paths>): Promise<proto.Receipt>;
17
+ export declare function prepareAction(action: proto.Action, makeSignedMessage: (message: Uint8Array) => Promise<Uint8Array>): Promise<Uint8Array<ArrayBufferLike>>;
18
+ export declare function createSession(serverUrl: string, walletSignFn: (x: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
19
+ userPubkey: Uint8Array;
20
+ sessionPubkey: Uint8Array;
21
+ expiryTimestamp?: bigint;
22
+ }, client?: Client<paths>): Promise<{
23
+ actionId: bigint;
24
+ sessionId: bigint;
25
+ }>;
26
+ export declare function revokeSession(serverUrl: string, walletSignFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
27
+ sessionId: BigIntValue;
28
+ }, client?: Client<paths>): Promise<{
29
+ actionId: bigint;
30
+ }>;
31
+ export declare function withdraw(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
32
+ sizeDecimals: number;
33
+ sessionId: BigIntValue;
34
+ tokenId: number;
35
+ amount: Decimal.Value;
36
+ }): Promise<{
37
+ actionId: bigint;
38
+ } & proto.Receipt_WithdrawResult>;
39
+ export declare function placeOrder(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
40
+ sessionId: BigIntValue;
41
+ senderId?: number;
42
+ sizeDecimals: number;
43
+ priceDecimals: number;
44
+ marketId: number;
45
+ side: Side;
46
+ fillMode: FillMode;
47
+ isReduceOnly: boolean;
48
+ size?: Decimal.Value;
49
+ price?: Decimal.Value;
50
+ quoteSize?: QuoteSize;
51
+ liquidateeId?: number;
52
+ clientOrderId?: BigIntValue;
53
+ }): Promise<{
54
+ actionId: bigint;
55
+ orderId?: bigint;
56
+ fills: proto.Receipt_Trade[];
57
+ }>;
58
+ export declare function cancelOrder(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
59
+ sessionId: BigIntValue;
60
+ senderId?: number;
61
+ orderId: BigIntValue;
62
+ liquidateeId?: number;
63
+ }): Promise<{
64
+ actionId: bigint;
65
+ orderId: bigint;
66
+ accountId: number;
67
+ }>;
68
+ export declare function transfer(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
69
+ sessionId: BigIntValue;
70
+ fromAccountId: number;
71
+ toAccountId?: number;
72
+ tokenId: number;
73
+ tokenDecimals: number;
74
+ amount: Decimal.Value;
75
+ }): Promise<{
76
+ actionId: bigint;
77
+ fromAccountId: number;
78
+ toAccountId?: number;
79
+ tokenId: number;
80
+ amount: bigint;
81
+ accountCreated: boolean;
82
+ }>;
83
+ export declare function addTrigger(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
84
+ sessionId: BigIntValue;
85
+ marketId: number;
86
+ side: Side;
87
+ kind: TriggerKind;
88
+ priceDecimals: number;
89
+ triggerPrice: Decimal.Value;
90
+ limitPrice?: Decimal.Value;
91
+ accountId?: number;
92
+ }): Promise<{
93
+ actionId: bigint;
94
+ }>;
95
+ export declare function removeTrigger(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
96
+ sessionId: BigIntValue;
97
+ marketId: number;
98
+ side: Side;
99
+ kind: TriggerKind;
100
+ accountId?: number;
101
+ }): Promise<{
102
+ actionId: bigint;
103
+ }>;
104
+ export type AtomicSubaction = {
105
+ kind: "place";
106
+ marketId: number;
107
+ side: Side;
108
+ fillMode: FillMode;
109
+ isReduceOnly: boolean;
110
+ sizeDecimals: number;
111
+ priceDecimals: number;
112
+ size?: Decimal.Value;
113
+ price?: Decimal.Value;
114
+ quoteSize?: QuoteSize;
115
+ clientOrderId?: BigIntValue;
116
+ } | {
117
+ kind: "cancel";
118
+ orderId: BigIntValue;
119
+ };
120
+ export declare function atomic(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
121
+ sessionId: BigIntValue;
122
+ accountId?: number;
123
+ actions: AtomicSubaction[];
124
+ }, client?: Client<paths>): Promise<{
125
+ actionId: bigint;
126
+ results: proto.Receipt_AtomicSubactionResultKind[];
127
+ }>;
128
+ export {};
@@ -0,0 +1,396 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.formatReceiptError = formatReceiptError;
40
+ exports.expectReceiptKind = expectReceiptKind;
41
+ exports.createAction = createAction;
42
+ exports.sendAction = sendAction;
43
+ exports.prepareAction = prepareAction;
44
+ exports.createSession = createSession;
45
+ exports.revokeSession = revokeSession;
46
+ exports.withdraw = withdraw;
47
+ exports.placeOrder = placeOrder;
48
+ exports.cancelOrder = cancelOrder;
49
+ exports.transfer = transfer;
50
+ exports.addTrigger = addTrigger;
51
+ exports.removeTrigger = removeTrigger;
52
+ exports.atomic = atomic;
53
+ const proto = __importStar(require("../../gen/nord_pb"));
54
+ const openapi_fetch_1 = __importDefault(require("openapi-fetch"));
55
+ const protobuf_1 = require("@bufbuild/protobuf");
56
+ const types_1 = require("../../types");
57
+ const utils_1 = require("../../utils");
58
+ const wire_1 = require("@bufbuild/protobuf/wire");
59
+ const NordError_1 = require("../utils/NordError");
60
+ function formatReceiptError(receipt) {
61
+ if (receipt.kind?.case === "err") {
62
+ const err = receipt.kind.value;
63
+ return proto.Error[err] ?? err.toString();
64
+ }
65
+ return receipt.kind?.case ?? "unknown";
66
+ }
67
+ function expectReceiptKind(receipt, expected, action) {
68
+ if (receipt.kind?.case !== expected) {
69
+ const label = formatReceiptError(receipt);
70
+ throw new NordError_1.NordError(`Failed to ${action}: ${label}`);
71
+ }
72
+ }
73
+ async function sessionSign(signFn, message) {
74
+ const signature = await signFn(message);
75
+ return new Uint8Array([...message, ...signature]);
76
+ }
77
+ async function walletSign(walletSignFn, message) {
78
+ const signature = await walletSignFn(message);
79
+ return new Uint8Array([...message, ...signature]);
80
+ }
81
+ // Helper to create an action with common fields
82
+ function createAction(currentTimestamp, nonce, kind) {
83
+ return (0, protobuf_1.create)(proto.ActionSchema, {
84
+ currentTimestamp,
85
+ nonce,
86
+ kind,
87
+ });
88
+ }
89
+ async function sendAction(serverUrl, makeSignedMessage, action, client) {
90
+ const body = await prepareAction(action, makeSignedMessage);
91
+ const httpClient = client ?? (0, openapi_fetch_1.default)({ baseUrl: serverUrl });
92
+ const response = await httpClient.POST("/action", {
93
+ params: {
94
+ header: {
95
+ "content-type": "application/octet-stream",
96
+ },
97
+ },
98
+ body: body,
99
+ // NOTE: openapi-fetch ignores headers and types/const headers in schema, and always assume all things are JSON
100
+ // to handle multi type bodies, need these overrides and later adhoc parsing
101
+ bodySerializer: (body) => body,
102
+ parseAs: "stream",
103
+ });
104
+ if (response.error) {
105
+ throw new Error(`Failed to ${action.kind.case}, HTTP status ${JSON.stringify(response.error)}`);
106
+ }
107
+ const rawResp = new Uint8Array(await response.response.bytes());
108
+ const resp = (0, utils_1.decodeLengthDelimited)(rawResp, proto.ReceiptSchema);
109
+ if (resp.kind?.case === "err") {
110
+ throw new Error(`Could not execute ${action.kind.case}, reason: ${proto.Error[resp.kind.value]}`);
111
+ }
112
+ return resp;
113
+ }
114
+ // Given action and signature function, prepare the signed message to send to server as `body`.
115
+ // `makeSignedMessage` must include the original message and signature.
116
+ async function prepareAction(action, makeSignedMessage) {
117
+ const encoded = (0, wire_1.sizeDelimitedEncode)(proto.ActionSchema, action);
118
+ // NOTE(agent): keep in sync with MAX_ENCODED_ACTION_SIZE in Rust code
119
+ const MAX_ENCODED_ACTION_SIZE = 1024;
120
+ if (encoded.byteLength > MAX_ENCODED_ACTION_SIZE) {
121
+ console.warn("Encoded message:", encoded);
122
+ throw new Error(`Encoded message size (${encoded.byteLength} bytes) is greater than max payload size (${MAX_ENCODED_ACTION_SIZE} bytes).`);
123
+ }
124
+ const body = await makeSignedMessage(encoded);
125
+ if (body.byteLength > MAX_ENCODED_ACTION_SIZE) {
126
+ console.warn("Encoded length:", encoded.byteLength);
127
+ throw new Error(`Signed message size (${body.byteLength} bytes) is greater than max payload size (${MAX_ENCODED_ACTION_SIZE} bytes).`);
128
+ }
129
+ return body;
130
+ }
131
+ async function createSession(serverUrl, walletSignFn, currentTimestamp, nonce, params, client) {
132
+ (0, utils_1.checkPubKeyLength)(types_1.KeyType.Ed25519, params.userPubkey.length);
133
+ (0, utils_1.checkPubKeyLength)(types_1.KeyType.Ed25519, params.sessionPubkey.length);
134
+ let expiry = 0n;
135
+ if (params.expiryTimestamp !== undefined) {
136
+ expiry = params.expiryTimestamp;
137
+ (0, utils_1.assert)(expiry > currentTimestamp, "Cannot set expiry timestamp in the past");
138
+ }
139
+ else {
140
+ expiry = currentTimestamp + utils_1.SESSION_TTL;
141
+ }
142
+ const action = createAction(currentTimestamp, nonce, {
143
+ case: "createSession",
144
+ value: (0, protobuf_1.create)(proto.Action_CreateSessionSchema, {
145
+ userPubkey: params.userPubkey,
146
+ blstPubkey: params.sessionPubkey,
147
+ expiryTimestamp: expiry,
148
+ }),
149
+ });
150
+ const resp = await sendAction(serverUrl, (m) => walletSign(walletSignFn, m), action, client);
151
+ if (resp.kind?.case === "createSessionResult") {
152
+ return {
153
+ actionId: resp.actionId,
154
+ sessionId: resp.kind.value.sessionId,
155
+ };
156
+ }
157
+ else {
158
+ throw new Error(`Unexpected receipt kind ${resp.kind?.case}`);
159
+ }
160
+ }
161
+ async function revokeSession(serverUrl, walletSignFn, currentTimestamp, nonce, params, client) {
162
+ const action = createAction(currentTimestamp, nonce, {
163
+ case: "revokeSession",
164
+ value: (0, protobuf_1.create)(proto.Action_RevokeSessionSchema, {
165
+ sessionId: BigInt(params.sessionId),
166
+ }),
167
+ });
168
+ const resp = await sendAction(serverUrl, (m) => walletSign(walletSignFn, m), action, client);
169
+ return { actionId: resp.actionId };
170
+ }
171
+ async function withdraw(serverUrl, signFn, currentTimestamp, nonce, params) {
172
+ const amount = (0, utils_1.toScaledU64)(params.amount, params.sizeDecimals);
173
+ if (amount <= 0) {
174
+ throw new Error("Withdraw amount must be positive");
175
+ }
176
+ const action = createAction(currentTimestamp, nonce, {
177
+ case: "withdraw",
178
+ value: (0, protobuf_1.create)(proto.Action_WithdrawSchema, {
179
+ sessionId: BigInt(params.sessionId),
180
+ tokenId: params.tokenId,
181
+ amount,
182
+ }),
183
+ });
184
+ const resp = await sendAction(serverUrl, (m) => sessionSign(signFn, m), action);
185
+ if (resp.kind?.case === "withdrawResult") {
186
+ return { actionId: resp.actionId, ...resp.kind.value };
187
+ }
188
+ else {
189
+ throw new Error(`Unexpected receipt kind ${resp.kind?.case}`);
190
+ }
191
+ }
192
+ async function placeOrder(serverUrl, signFn, currentTimestamp, nonce, params) {
193
+ const price = (0, utils_1.toScaledU64)(params.price ?? 0, params.priceDecimals);
194
+ const size = (0, utils_1.toScaledU64)(params.size ?? 0, params.sizeDecimals);
195
+ const scaledQuote = params.quoteSize
196
+ ? params.quoteSize.toWire(params.priceDecimals, params.sizeDecimals)
197
+ : undefined;
198
+ (0, utils_1.assert)(price > 0n || size > 0n || scaledQuote !== undefined, "OrderLimit must include at least one of: size, price, or quoteSize");
199
+ const action = createAction(currentTimestamp, nonce, {
200
+ case: "placeOrder",
201
+ value: (0, protobuf_1.create)(proto.Action_PlaceOrderSchema, {
202
+ sessionId: BigInt(params.sessionId),
203
+ senderAccountId: params.senderId,
204
+ marketId: params.marketId,
205
+ side: params.side === types_1.Side.Bid ? proto.Side.BID : proto.Side.ASK,
206
+ fillMode: (0, types_1.fillModeToProtoFillMode)(params.fillMode),
207
+ isReduceOnly: params.isReduceOnly,
208
+ price,
209
+ size,
210
+ quoteSize: scaledQuote === undefined
211
+ ? undefined
212
+ : (0, protobuf_1.create)(proto.QuoteSizeSchema, {
213
+ size: scaledQuote.size,
214
+ price: scaledQuote.price,
215
+ }),
216
+ clientOrderId: params.clientOrderId === undefined
217
+ ? undefined
218
+ : BigInt(params.clientOrderId),
219
+ delegatorAccountId: params.liquidateeId,
220
+ }),
221
+ });
222
+ const resp = await sendAction(serverUrl, (m) => sessionSign(signFn, m), action);
223
+ if (resp.kind?.case === "placeOrderResult") {
224
+ return {
225
+ actionId: resp.actionId,
226
+ orderId: resp.kind.value.posted?.orderId,
227
+ fills: resp.kind.value.fills,
228
+ };
229
+ }
230
+ else {
231
+ throw new Error(`Unexpected receipt kind ${resp.kind?.case}`);
232
+ }
233
+ }
234
+ async function cancelOrder(serverUrl, signFn, currentTimestamp, nonce, params) {
235
+ const action = createAction(currentTimestamp, nonce, {
236
+ case: "cancelOrderById",
237
+ value: (0, protobuf_1.create)(proto.Action_CancelOrderByIdSchema, {
238
+ orderId: BigInt(params.orderId),
239
+ sessionId: BigInt(params.sessionId),
240
+ senderAccountId: params.senderId,
241
+ delegatorAccountId: params.liquidateeId,
242
+ }),
243
+ });
244
+ const resp = await sendAction(serverUrl, (m) => sessionSign(signFn, m), action);
245
+ if (resp.kind?.case === "cancelOrderResult") {
246
+ return {
247
+ actionId: resp.actionId,
248
+ orderId: resp.kind.value.orderId,
249
+ accountId: resp.kind.value.accountId,
250
+ };
251
+ }
252
+ else {
253
+ throw new Error(`Unexpected receipt kind ${resp.kind?.case}`);
254
+ }
255
+ }
256
+ async function transfer(serverUrl, signFn, currentTimestamp, nonce, params) {
257
+ const action = createAction(currentTimestamp, nonce, {
258
+ case: "transfer",
259
+ value: (0, protobuf_1.create)(proto.Action_TransferSchema, {
260
+ sessionId: BigInt(params.sessionId),
261
+ fromAccountId: params.fromAccountId,
262
+ toAccountId: params.toAccountId,
263
+ tokenId: params.tokenId,
264
+ amount: (0, utils_1.toScaledU64)(params.amount ?? 0, params.tokenDecimals),
265
+ }),
266
+ });
267
+ const resp = await sendAction(serverUrl, (m) => sessionSign(signFn, m), action);
268
+ if (resp.kind?.case === "transferred") {
269
+ return {
270
+ actionId: resp.actionId,
271
+ fromAccountId: resp.kind.value.fromAccountId,
272
+ toAccountId: resp.kind.value.toUserAccount,
273
+ tokenId: resp.kind.value.tokenId,
274
+ amount: resp.kind.value.amount,
275
+ accountCreated: resp.kind.value.accountCreated,
276
+ };
277
+ }
278
+ else {
279
+ throw new Error(`Unexpected receipt kind ${resp.kind?.case}`);
280
+ }
281
+ }
282
+ async function addTrigger(serverUrl, signFn, currentTimestamp, nonce, params) {
283
+ const triggerPrice = (0, utils_1.toScaledU64)(params.triggerPrice, params.priceDecimals);
284
+ (0, utils_1.assert)(triggerPrice > 0n, "Trigger price must be positive");
285
+ const limitPrice = params.limitPrice === undefined
286
+ ? undefined
287
+ : (0, utils_1.toScaledU64)(params.limitPrice, params.priceDecimals);
288
+ if (limitPrice !== undefined) {
289
+ (0, utils_1.assert)(limitPrice > 0n, "Limit price must be positive");
290
+ }
291
+ const key = (0, protobuf_1.create)(proto.TriggerKeySchema, {
292
+ kind: params.kind === types_1.TriggerKind.StopLoss
293
+ ? proto.TriggerKind.STOP_LOSS
294
+ : proto.TriggerKind.TAKE_PROFIT,
295
+ side: params.side === types_1.Side.Bid ? proto.Side.BID : proto.Side.ASK,
296
+ });
297
+ const prices = (0, protobuf_1.create)(proto.Action_TriggerPricesSchema, {
298
+ triggerPrice,
299
+ limitPrice,
300
+ });
301
+ const action = createAction(currentTimestamp, nonce, {
302
+ case: "addTrigger",
303
+ value: (0, protobuf_1.create)(proto.Action_AddTriggerSchema, {
304
+ sessionId: BigInt(params.sessionId),
305
+ marketId: params.marketId,
306
+ key,
307
+ prices,
308
+ accountId: params.accountId,
309
+ }),
310
+ });
311
+ const resp = await sendAction(serverUrl, (m) => sessionSign(signFn, m), action);
312
+ if (resp.kind?.case === "triggerAdded") {
313
+ return { actionId: resp.actionId };
314
+ }
315
+ throw new Error(`Unexpected receipt kind ${resp.kind?.case}`);
316
+ }
317
+ async function removeTrigger(serverUrl, signFn, currentTimestamp, nonce, params) {
318
+ const key = (0, protobuf_1.create)(proto.TriggerKeySchema, {
319
+ kind: params.kind === types_1.TriggerKind.StopLoss
320
+ ? proto.TriggerKind.STOP_LOSS
321
+ : proto.TriggerKind.TAKE_PROFIT,
322
+ side: params.side === types_1.Side.Bid ? proto.Side.BID : proto.Side.ASK,
323
+ });
324
+ const action = createAction(currentTimestamp, nonce, {
325
+ case: "removeTrigger",
326
+ value: (0, protobuf_1.create)(proto.Action_RemoveTriggerSchema, {
327
+ sessionId: BigInt(params.sessionId),
328
+ marketId: params.marketId,
329
+ key,
330
+ accountId: params.accountId,
331
+ }),
332
+ });
333
+ const resp = await sendAction(serverUrl, (m) => sessionSign(signFn, m), action);
334
+ if (resp.kind?.case === "triggerRemoved") {
335
+ return { actionId: resp.actionId };
336
+ }
337
+ throw new Error(`Unexpected receipt kind ${resp.kind?.case}`);
338
+ }
339
+ async function atomic(serverUrl, signFn, currentTimestamp, nonce, params, client) {
340
+ (0, utils_1.assert)(params.actions.length > 0 && params.actions.length <= 4, "Atomic action must contain between 1 and 4 sub-actions");
341
+ const subactions = params.actions.map((a) => {
342
+ if (a.kind === "place") {
343
+ const price = (0, utils_1.toScaledU64)(a.price ?? 0, a.priceDecimals);
344
+ const size = (0, utils_1.toScaledU64)(a.size ?? 0, a.sizeDecimals);
345
+ const scaledQuote = a.quoteSize
346
+ ? a.quoteSize.toWire(a.priceDecimals, a.sizeDecimals)
347
+ : undefined;
348
+ // Require at least one limit to be set (non-zero size, non-zero price, or quoteSize)
349
+ (0, utils_1.assert)(price > 0n || size > 0n || scaledQuote !== undefined, "OrderLimit must include at least one of: size, price, or quoteSize");
350
+ const tradeOrPlace = (0, protobuf_1.create)(proto.TradeOrPlaceSchema, {
351
+ marketId: a.marketId,
352
+ orderType: (0, protobuf_1.create)(proto.OrderTypeSchema, {
353
+ side: a.side === types_1.Side.Bid ? proto.Side.BID : proto.Side.ASK,
354
+ fillMode: (0, types_1.fillModeToProtoFillMode)(a.fillMode),
355
+ isReduceOnly: a.isReduceOnly,
356
+ }),
357
+ limit: (0, protobuf_1.create)(proto.OrderLimitSchema, {
358
+ price,
359
+ size,
360
+ quoteSize: scaledQuote === undefined
361
+ ? undefined
362
+ : (0, protobuf_1.create)(proto.QuoteSizeSchema, {
363
+ size: scaledQuote.size,
364
+ price: scaledQuote.price,
365
+ }),
366
+ }),
367
+ clientOrderId: a.clientOrderId === undefined ? undefined : BigInt(a.clientOrderId),
368
+ });
369
+ return (0, protobuf_1.create)(proto.AtomicSubactionKindSchema, {
370
+ inner: { case: "tradeOrPlace", value: tradeOrPlace },
371
+ });
372
+ }
373
+ return (0, protobuf_1.create)(proto.AtomicSubactionKindSchema, {
374
+ inner: {
375
+ case: "cancelOrder",
376
+ value: (0, protobuf_1.create)(proto.CancelOrderSchema, { orderId: BigInt(a.orderId) }),
377
+ },
378
+ });
379
+ });
380
+ const action = createAction(currentTimestamp, nonce, {
381
+ case: "atomic",
382
+ value: (0, protobuf_1.create)(proto.AtomicSchema, {
383
+ sessionId: BigInt(params.sessionId),
384
+ accountId: params.accountId, // optional
385
+ actions: subactions,
386
+ }),
387
+ });
388
+ const resp = await sendAction(serverUrl, (m) => sessionSign(signFn, m), action, client);
389
+ if (resp.kind?.case === "atomic") {
390
+ return {
391
+ actionId: resp.actionId,
392
+ results: resp.kind.value.results,
393
+ };
394
+ }
395
+ throw new Error(`Unexpected receipt kind ${resp.kind?.case}`);
396
+ }
@@ -0,0 +1,16 @@
1
+ import { SubscriptionPattern } from "../../types";
2
+ import { NordWebSocketClient } from "../../websocket/index";
3
+ /**
4
+ * Initialize a WebSocket client for Nord
5
+ *
6
+ * Connects to the Nord WebSocket endpoint with support for multiple subscription types:
7
+ * - trades@SYMBOL - For trade updates
8
+ * - deltas@SYMBOL - For orderbook delta updates
9
+ * - account@ACCOUNT_ID - For user-specific updates
10
+ *
11
+ * @param webServerUrl - Base URL for the Nord web server
12
+ * @param subscriptions - Array of subscriptions (e.g., ["trades@BTCUSDC", "deltas@BTCUSDC", "account@42"])
13
+ * @returns WebSocket client
14
+ * @throws {NordError} If initialization fails or invalid subscription is provided
15
+ */
16
+ export declare function initWebSocketClient(webServerUrl: string, subscriptions?: SubscriptionPattern[] | "trades" | "delta" | "account"): NordWebSocketClient;
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initWebSocketClient = initWebSocketClient;
4
+ const index_1 = require("../../websocket/index");
5
+ const NordError_1 = require("../utils/NordError");
6
+ /**
7
+ * Initialize a WebSocket client for Nord
8
+ *
9
+ * Connects to the Nord WebSocket endpoint with support for multiple subscription types:
10
+ * - trades@SYMBOL - For trade updates
11
+ * - deltas@SYMBOL - For orderbook delta updates
12
+ * - account@ACCOUNT_ID - For user-specific updates
13
+ *
14
+ * @param webServerUrl - Base URL for the Nord web server
15
+ * @param subscriptions - Array of subscriptions (e.g., ["trades@BTCUSDC", "deltas@BTCUSDC", "account@42"])
16
+ * @returns WebSocket client
17
+ * @throws {NordError} If initialization fails or invalid subscription is provided
18
+ */
19
+ function initWebSocketClient(webServerUrl, subscriptions) {
20
+ try {
21
+ // Determine URL and subscriptions based on parameters
22
+ let wsUrl = webServerUrl.replace(/^http/, "ws") + `/ws`;
23
+ // Validate subscriptions parameter
24
+ if (typeof subscriptions === "string") {
25
+ // Legacy mode - handle endpoint string
26
+ if (subscriptions === "trades" ||
27
+ subscriptions === "delta" ||
28
+ subscriptions === "account") {
29
+ wsUrl += `/${subscriptions}`;
30
+ }
31
+ else {
32
+ throw new NordError_1.NordError(`Invalid endpoint: ${subscriptions}. Must be "trades", "deltas", or "account".`);
33
+ }
34
+ }
35
+ else if (Array.isArray(subscriptions) && subscriptions.length > 0) {
36
+ // New mode - validate and combine subscriptions in URL
37
+ subscriptions.forEach(validateSubscription);
38
+ wsUrl += `/${subscriptions.join("&")}`;
39
+ }
40
+ else {
41
+ // Default to trades endpoint if no subscriptions specified
42
+ wsUrl += `/trades`;
43
+ }
44
+ console.log(`Initializing WebSocket client with URL: ${wsUrl}`);
45
+ // Create and connect the WebSocket client
46
+ const ws = new index_1.NordWebSocketClient(wsUrl);
47
+ // Add error handler
48
+ ws.on("error", (error) => {
49
+ console.error("Nord WebSocket error:", error);
50
+ });
51
+ // Add connected handler for debugging
52
+ ws.on("connected", () => {
53
+ console.log("Nord WebSocket connected successfully");
54
+ });
55
+ // Connect the WebSocket
56
+ ws.connect();
57
+ return ws;
58
+ }
59
+ catch (error) {
60
+ console.error("Failed to initialize WebSocket client:", error);
61
+ throw new NordError_1.NordError("Failed to initialize WebSocket client", {
62
+ cause: error,
63
+ });
64
+ }
65
+ }
66
+ /**
67
+ * Validates a subscription string follows the correct format
68
+ *
69
+ * @param subscription - The subscription to validate
70
+ * @throws {NordError} If the subscription format is invalid
71
+ */
72
+ function validateSubscription(subscription) {
73
+ const [type, param] = subscription.split("@");
74
+ if (!type || !param || !["trades", "deltas", "account"].includes(type)) {
75
+ throw new NordError_1.NordError(`Invalid subscription format: ${subscription}. Expected format: "trades@SYMBOL", "deltas@SYMBOL", or "account@ID"`);
76
+ }
77
+ // Additional validation for account subscriptions
78
+ if (type === "account" && isNaN(Number(param))) {
79
+ throw new NordError_1.NordError(`Invalid account ID in subscription: ${subscription}. Account ID must be a number.`);
80
+ }
81
+ }