@n1xyz/nord-ts 0.1.7 → 0.1.9

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