@n1xyz/nord-ts 0.3.1 → 0.3.3

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 (47) hide show
  1. package/dist/client/Nord.d.ts +9 -3
  2. package/dist/gen/openapi.d.ts +366 -4
  3. package/dist/index.browser.js +96626 -0
  4. package/dist/index.common.js +115002 -0
  5. package/dist/types.d.ts +13 -2
  6. package/dist/websocket/NordWebSocketClient.d.ts +1 -0
  7. package/dist/websocket/Subscriber.d.ts +7 -1
  8. package/dist/websocket/events.d.ts +2 -1
  9. package/dist/websocket/index.d.ts +1 -1
  10. package/package.json +7 -4
  11. package/dist/actions.js +0 -184
  12. package/dist/client/Nord.js +0 -759
  13. package/dist/client/NordAdmin.js +0 -362
  14. package/dist/client/NordUser.js +0 -752
  15. package/dist/const.js +0 -27
  16. package/dist/error.js +0 -51
  17. package/dist/gen/nord_pb.js +0 -1068
  18. package/dist/gen/openapi.js +0 -5
  19. package/dist/index.js +0 -10
  20. package/dist/nord/api/actions.d.ts +0 -128
  21. package/dist/nord/api/actions.js +0 -396
  22. package/dist/nord/api/core.d.ts +0 -16
  23. package/dist/nord/api/core.js +0 -81
  24. package/dist/nord/api/metrics.d.ts +0 -67
  25. package/dist/nord/api/metrics.js +0 -229
  26. package/dist/nord/api/triggers.d.ts +0 -7
  27. package/dist/nord/api/triggers.js +0 -38
  28. package/dist/nord/client/Nord.d.ts +0 -387
  29. package/dist/nord/client/Nord.js +0 -747
  30. package/dist/nord/client/NordAdmin.d.ts +0 -226
  31. package/dist/nord/client/NordAdmin.js +0 -410
  32. package/dist/nord/client/NordClient.d.ts +0 -16
  33. package/dist/nord/client/NordClient.js +0 -28
  34. package/dist/nord/client/NordUser.d.ts +0 -379
  35. package/dist/nord/client/NordUser.js +0 -787
  36. package/dist/nord/index.d.ts +0 -8
  37. package/dist/nord/index.js +0 -34
  38. package/dist/nord/models/Subscriber.d.ts +0 -37
  39. package/dist/nord/models/Subscriber.js +0 -25
  40. package/dist/nord/utils/NordError.d.ts +0 -35
  41. package/dist/nord/utils/NordError.js +0 -49
  42. package/dist/types.js +0 -92
  43. package/dist/utils.js +0 -193
  44. package/dist/websocket/NordWebSocketClient.js +0 -242
  45. package/dist/websocket/Subscriber.js +0 -24
  46. package/dist/websocket/events.js +0 -1
  47. package/dist/websocket/index.js +0 -80
package/dist/types.d.ts CHANGED
@@ -5,7 +5,7 @@ import { Connection } from "@solana/web3.js";
5
5
  /**
6
6
  * Nord subscription type for trades or deltas
7
7
  */
8
- export type SubscriptionType = "trades" | "deltas" | "account";
8
+ export type SubscriptionType = "trades" | "deltas" | "account" | "candle";
9
9
  /**
10
10
  * Pattern for a valid Nord subscription
11
11
  * Format should be: "<type>@<parameter>"
@@ -196,6 +196,7 @@ export declare enum WebSocketMessageType {
196
196
  DeltaUpdate = "delta",
197
197
  AccountUpdate = "account"
198
198
  }
199
+ export type CandleResolution = "1" | "5" | "15" | "30" | "60" | "1D" | "1W" | "1M";
199
200
  /**
200
201
  * WebSocket trade update message
201
202
  */
@@ -242,13 +243,23 @@ export interface WebSocketAccountUpdate {
242
243
  }>;
243
244
  balances: Record<string, number>;
244
245
  }
246
+ export interface WebSocketCandleUpdate {
247
+ res: CandleResolution;
248
+ mid: number;
249
+ t: number;
250
+ o: number;
251
+ h: number;
252
+ l: number;
253
+ c: number;
254
+ v: number;
255
+ }
245
256
  export type WebSocketMessage = {
246
257
  trades: WebSocketTradeUpdate;
247
258
  } | {
248
259
  delta: WebSocketDeltaUpdate;
249
260
  } | {
250
261
  account: WebSocketAccountUpdate;
251
- };
262
+ } | WebSocketCandleUpdate;
252
263
  export interface SPLTokenInfo {
253
264
  mint: string;
254
265
  precision: number;
@@ -50,6 +50,7 @@ export declare class NordWebSocketClient extends EventEmitter implements NordWeb
50
50
  * @param message WebSocket message
51
51
  */
52
52
  private handleMessage;
53
+ private isCandleUpdate;
53
54
  /**
54
55
  * Attempt to reconnect to the WebSocket server
55
56
  */
@@ -1,5 +1,5 @@
1
1
  import { EventEmitter } from "events";
2
- import { Account, DeltaEvent, WebSocketDeltaUpdate, SubscriberConfig, Trades, WebSocketTradeUpdate } from "../types";
2
+ import { Account, DeltaEvent, WebSocketDeltaUpdate, SubscriberConfig, Trades, WebSocketTradeUpdate, WebSocketCandleUpdate } from "../types";
3
3
  /**
4
4
  * Subscriber class for handling WebSocket subscriptions
5
5
  */
@@ -35,3 +35,9 @@ export interface TradeSubscription extends EventEmitter {
35
35
  close(): void;
36
36
  removeAllListeners(event?: string): this;
37
37
  }
38
+ export interface CandleSubscription extends EventEmitter {
39
+ on(event: "message", listener: (data: WebSocketCandleUpdate) => void): this;
40
+ on(event: "error", listener: (error: Error) => void): this;
41
+ close(): void;
42
+ removeAllListeners(event?: string): this;
43
+ }
@@ -1,4 +1,4 @@
1
- import { WebSocketTradeUpdate, WebSocketDeltaUpdate, WebSocketAccountUpdate } from "../types";
1
+ import { WebSocketTradeUpdate, WebSocketDeltaUpdate, WebSocketAccountUpdate, WebSocketCandleUpdate } from "../types";
2
2
  /**
3
3
  * Event type definitions for the NordWebSocketClient
4
4
  */
@@ -9,6 +9,7 @@ export interface NordWebSocketEvents {
9
9
  trade: (update: WebSocketTradeUpdate) => void;
10
10
  delta: (update: WebSocketDeltaUpdate) => void;
11
11
  account: (update: WebSocketAccountUpdate) => void;
12
+ candle: (update: WebSocketCandleUpdate) => void;
12
13
  }
13
14
  /**
14
15
  * Type declaration for NordWebSocketClient event methods
@@ -16,4 +16,4 @@ export { NordWebSocketClient, NordWebSocketEvents, NordWebSocketClientEvents, Su
16
16
  * @returns WebSocket client
17
17
  * @throws {NordError} If initialization fails or invalid subscription is provided
18
18
  */
19
- export declare function initWebSocketClient(webServerUrl: string, subscriptions?: SubscriptionPattern[] | "trades" | "delta" | "account"): NordWebSocketClient;
19
+ export declare function initWebSocketClient(webServerUrl: string, subscriptions?: SubscriptionPattern[] | "trades" | "delta" | "account" | "candle"): NordWebSocketClient;
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@n1xyz/nord-ts",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Typescript for Nord",
5
5
  "keywords": [],
6
6
  "author": "",
7
7
  "license": "ISC",
8
8
  "type": "module",
9
- "main": "dist/index.js",
9
+ "main": "dist/index.common.js",
10
+ "browser": "dist/index.browser.js",
10
11
  "types": "dist/index.d.ts",
11
12
  "files": [
12
13
  "dist/",
@@ -17,12 +18,14 @@
17
18
  "gen:proto": "bunx @bufbuild/buf generate ../engine",
18
19
  "gen:api": "nix run ..#openapi | bunx openapi-typescript > src/gen/openapi.ts",
19
20
  "gen": "bun run gen:proto && bun run gen:api",
20
- "build": "bun run gen && bunx tsc && bun run docs",
21
+ "build:node": "bun build ./src/index.ts --target=node --format=esm --outfile=dist/index.common.js",
22
+ "build:browser": "bun build ./src/index.ts --target=browser --format=esm --outfile=dist/index.browser.js",
23
+ "build": "bun run gen && bunx tsc && bun run build:node && bun run build:browser && bun run docs",
21
24
  "docs": "bunx typedoc --out ./docs ./src",
22
25
  "compile": "tsc",
23
26
  "clean": "rm -rf ./src/gen ./dist ./docs",
24
27
  "fmt": "prettier --write src tests",
25
- "ci": "bunx eslint && prettier --check src tests",
28
+ "ci": "bunx eslint && bunx tsc && prettier --check src tests",
26
29
  "all": "bun install && bun run build && bun run ci && bun fmt"
27
30
  },
28
31
  "devDependencies": {
package/dist/actions.js DELETED
@@ -1,184 +0,0 @@
1
- import * as proto from "./gen/nord_pb";
2
- import { create } from "@bufbuild/protobuf";
3
- import { fillModeToProtoFillMode, Side } from "./types";
4
- import { assert, decodeLengthDelimited, SESSION_TTL, toScaledU64, signUserPayload, } from "./utils";
5
- import { sizeDelimitedEncode } from "@bufbuild/protobuf/wire";
6
- import { NordError } from "./error";
7
- export function formatReceiptError(receipt) {
8
- if (receipt.kind?.case === "err") {
9
- const err = receipt.kind.value;
10
- return proto.Error[err] ?? err.toString();
11
- }
12
- return receipt.kind?.case ?? "unknown";
13
- }
14
- export function expectReceiptKind(receipt, expected, action) {
15
- if (receipt.kind?.case !== expected) {
16
- const label = formatReceiptError(receipt);
17
- throw new NordError(`Failed to ${action}: ${label}`);
18
- }
19
- }
20
- async function sessionSign(signFn, message) {
21
- const signature = await signFn(message);
22
- return new Uint8Array([...message, ...signature]);
23
- }
24
- // Helper to create an action with common fields
25
- export function createAction(currentTimestamp, nonce, kind) {
26
- return create(proto.ActionSchema, {
27
- currentTimestamp,
28
- nonce,
29
- kind,
30
- });
31
- }
32
- export async function sendAction(client, makeSignedMessage, action) {
33
- const body = await prepareAction(action, makeSignedMessage);
34
- const response = await client.POST("/action", {
35
- params: {
36
- header: {
37
- "content-type": "application/octet-stream",
38
- },
39
- },
40
- body: body,
41
- // NOTE: openapi-fetch ignores headers and types/const headers in schema, and always assume all things are JSON
42
- // to handle multi type bodies, need these overrides and later adhoc parsing
43
- bodySerializer: (body) => body,
44
- parseAs: "stream",
45
- });
46
- if (response.error) {
47
- throw new Error(`Failed to ${action.kind.case}, HTTP status ${JSON.stringify(response.error)}`);
48
- }
49
- const rawResp = new Uint8Array(await response.response.arrayBuffer());
50
- const resp = decodeLengthDelimited(rawResp, proto.ReceiptSchema);
51
- if (resp.kind?.case === "err") {
52
- throw new Error(`Could not execute ${action.kind.case}, reason: ${proto.Error[resp.kind.value]}`);
53
- }
54
- return resp;
55
- }
56
- // Given action and signature function, prepare the signed message to send to server as `body`.
57
- // `makeSignedMessage` must include the original message and signature.
58
- export async function prepareAction(action, makeSignedMessage) {
59
- const encoded = sizeDelimitedEncode(proto.ActionSchema, action);
60
- // NOTE(agent): keep in sync with MAX_ENCODED_ACTION_SIZE in Rust code
61
- const MAX_ENCODED_ACTION_SIZE = 1024;
62
- if (encoded.byteLength > MAX_ENCODED_ACTION_SIZE) {
63
- console.warn("Encoded message:", encoded);
64
- throw new Error(`Encoded message size (${encoded.byteLength} bytes) is greater than max payload size (${MAX_ENCODED_ACTION_SIZE} bytes).`);
65
- }
66
- const body = await makeSignedMessage(encoded);
67
- if (body.byteLength > MAX_ENCODED_ACTION_SIZE) {
68
- console.warn("Encoded length:", encoded.byteLength);
69
- throw new Error(`Signed message size (${body.byteLength} bytes) is greater than max payload size (${MAX_ENCODED_ACTION_SIZE} bytes).`);
70
- }
71
- return body;
72
- }
73
- export async function createSession(client, signMessage, currentTimestamp, nonce, params) {
74
- let expiry = 0n;
75
- if (params.expiryTimestamp !== undefined) {
76
- expiry = params.expiryTimestamp;
77
- assert(expiry > currentTimestamp, "Cannot set expiry timestamp in the past");
78
- }
79
- else {
80
- expiry = currentTimestamp + SESSION_TTL;
81
- }
82
- const action = createAction(currentTimestamp, nonce, {
83
- case: "createSession",
84
- value: create(proto.Action_CreateSessionSchema, {
85
- userPubkey: params.userPubkey.toBytes(),
86
- blstPubkey: params.sessionPubkey.toBytes(),
87
- expiryTimestamp: expiry,
88
- }),
89
- });
90
- const resp = await sendAction(client, async (payload) => {
91
- return new Uint8Array([
92
- ...payload,
93
- ...(await signUserPayload({
94
- payload,
95
- signMessage,
96
- })),
97
- ]);
98
- }, action);
99
- if (resp.kind?.case === "createSessionResult") {
100
- return {
101
- actionId: resp.actionId,
102
- sessionId: resp.kind.value.sessionId,
103
- };
104
- }
105
- else {
106
- throw new Error(`Unexpected receipt kind ${resp.kind?.case}`);
107
- }
108
- }
109
- export async function revokeSession(client, signMessage, currentTimestamp, nonce, params) {
110
- const action = createAction(currentTimestamp, nonce, {
111
- case: "revokeSession",
112
- value: create(proto.Action_RevokeSessionSchema, {
113
- sessionId: BigInt(params.sessionId),
114
- }),
115
- });
116
- const resp = await sendAction(client, async (payload) => {
117
- return new Uint8Array([
118
- ...payload,
119
- ...(await signUserPayload({
120
- payload,
121
- signMessage,
122
- })),
123
- ]);
124
- }, action);
125
- return { actionId: resp.actionId };
126
- }
127
- export async function atomic(client, signFn, currentTimestamp, nonce, params) {
128
- assert(params.actions.length > 0 && params.actions.length <= 4, "Atomic action must contain between 1 and 4 sub-actions");
129
- const subactions = params.actions.map((a) => {
130
- if (a.kind === "place") {
131
- const price = toScaledU64(a.price ?? 0, a.priceDecimals);
132
- const size = toScaledU64(a.size ?? 0, a.sizeDecimals);
133
- const scaledQuote = a.quoteSize
134
- ? a.quoteSize.toWire(a.priceDecimals, a.sizeDecimals)
135
- : undefined;
136
- // Require at least one limit to be set (non-zero size, non-zero price, or quoteSize)
137
- assert(price > 0n || size > 0n || scaledQuote !== undefined, "OrderLimit must include at least one of: size, price, or quoteSize");
138
- const tradeOrPlace = create(proto.TradeOrPlaceSchema, {
139
- marketId: a.marketId,
140
- orderType: create(proto.OrderTypeSchema, {
141
- side: a.side === Side.Bid ? proto.Side.BID : proto.Side.ASK,
142
- fillMode: fillModeToProtoFillMode(a.fillMode),
143
- isReduceOnly: a.isReduceOnly,
144
- }),
145
- limit: create(proto.OrderLimitSchema, {
146
- price,
147
- size,
148
- quoteSize: scaledQuote === undefined
149
- ? undefined
150
- : create(proto.QuoteSizeSchema, {
151
- size: scaledQuote.size,
152
- price: scaledQuote.price,
153
- }),
154
- }),
155
- clientOrderId: a.clientOrderId === undefined ? undefined : BigInt(a.clientOrderId),
156
- });
157
- return create(proto.AtomicSubactionKindSchema, {
158
- inner: { case: "tradeOrPlace", value: tradeOrPlace },
159
- });
160
- }
161
- return create(proto.AtomicSubactionKindSchema, {
162
- inner: {
163
- case: "cancelOrder",
164
- value: create(proto.CancelOrderSchema, { orderId: BigInt(a.orderId) }),
165
- },
166
- });
167
- });
168
- const action = createAction(currentTimestamp, nonce, {
169
- case: "atomic",
170
- value: create(proto.AtomicSchema, {
171
- sessionId: BigInt(params.sessionId),
172
- accountId: params.accountId, // optional
173
- actions: subactions,
174
- }),
175
- });
176
- const resp = await sendAction(client, (m) => sessionSign(signFn, m), action);
177
- if (resp.kind?.case === "atomic") {
178
- return {
179
- actionId: resp.actionId,
180
- results: resp.kind.value.results,
181
- };
182
- }
183
- throw new Error(`Unexpected receipt kind ${resp.kind?.case}`);
184
- }