ault-sdk-ts 0.0.2-alpha.19 → 0.0.2-alpha.21

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.
@@ -3,5 +3,6 @@ export declare function aultToEvm(aultAddress: string): string;
3
3
  export declare function isValidAultAddress(address: string): boolean;
4
4
  export declare function isValidEvmAddress(address: string): boolean;
5
5
  export declare function addressEquals(a: string, b: string): boolean;
6
+ export declare function addressBytes(s: string): Uint8Array | null;
6
7
  export declare function isValidValidatorAddress(address: string): boolean;
7
8
  export declare function assertValidatorAddress(address: string): string;
@@ -1,4 +1,6 @@
1
- import type { DexWsEventMap, DexWsOptions, PayloadFor, Subscription, SubscriptionHandlers, WsConnectionState } from "./types";
1
+ import type { DexWsEventMap, DexWsOptions, PayloadFor, Subscription, SubscriptionHandlers, WsChannelType, WsConnectionState, WsSubscription } from "./types";
2
+ /** Standard `WebSocket.readyState` value for an open socket. */
3
+ export declare const WS_READY_STATE_OPEN = 1;
2
4
  export declare class DexWsClient {
3
5
  private url;
4
6
  private options;
@@ -16,17 +18,52 @@ export declare class DexWsClient {
16
18
  get state(): WsConnectionState;
17
19
  connect(): Promise<void>;
18
20
  disconnect(): void;
19
- subscribe<T extends string>(topic: T, handlers: SubscriptionHandlers<PayloadFor<T>>, options?: {
21
+ /**
22
+ * Subscribe to a channel. `handlers.onData` receives every frame (snapshot
23
+ * and deltas alike); the SDK makes no assumption that the first frame is a
24
+ * delta. Returns a handle whose `unsubscribe()` tears the subscription down.
25
+ */
26
+ subscribe<T extends WsChannelType>(subscription: WsSubscription & {
27
+ type: T;
28
+ }, handlers: SubscriptionHandlers<PayloadFor<T>>, options?: {
20
29
  ttl?: number;
21
30
  }): Subscription;
22
- unsubscribe(topic: string): void;
31
+ /**
32
+ * Send a subscribe for an already-registered active subscription and wire its
33
+ * ack/error/onSubscribed handling. Shared by the initial subscribe and the
34
+ * reconnect replay so both paths surface failures via onError instead of
35
+ * leaving a silent dead subscription.
36
+ */
37
+ private dispatchSubscribe;
38
+ /**
39
+ * Enforce the per-channel required key at runtime. The `WsSubscription` union
40
+ * already encodes this at compile time, but a caller can cast through it (e.g.
41
+ * `type` via `as never` for a not-yet-typed channel). Registering a partial
42
+ * sub is unsafe: a user channel with no `user` would match every frame on that
43
+ * channel (frameMatches returns true for orderUpdates/userEvents) until the
44
+ * async server reject lands. Throw before `subscriptions.set` instead.
45
+ */
46
+ private assertRequiredKey;
47
+ /**
48
+ * Guard against multiplexing two different users across a user-ambiguous
49
+ * channel (orderUpdates/userEvents) on one connection. Their frames carry no
50
+ * `user`, so a second user's subscription would fan out into the first's
51
+ * handler and vice-versa, leaking private order flow. Re-subscribing the same
52
+ * user is allowed (it just refreshes handlers/ttl).
53
+ */
54
+ private assertNoUserAmbiguity;
55
+ unsubscribe(subscription: WsSubscription): void;
23
56
  on<E extends keyof DexWsEventMap>(event: E, handler: DexWsEventMap[E]): () => void;
24
57
  private createSocket;
25
58
  private resolveFactory;
26
59
  private handleMessage;
60
+ private handleChannelError;
61
+ private handleAck;
62
+ private handleExpired;
63
+ private dispatchData;
64
+ private deliver;
27
65
  private send;
28
- private sendCommand;
29
- private commandKey;
66
+ private sendSubscribe;
30
67
  private scheduleReconnect;
31
68
  private resubscribeAll;
32
69
  private resolveConnect;
@@ -1,77 +1,251 @@
1
- import type { OrderbookResponse, TradeResponse, TickerResponse, OrderResponse, OHLCVEntry } from "../rest/dex.generated";
2
- export interface WsTradeInfo {
3
- address: string;
4
- paid: string;
5
- received: string;
6
- block_height: string;
7
- }
8
- export interface WsOrderInfo {
9
- orderer: string;
10
- block_height: string;
11
- tx_index: number;
12
- remaining_deposit: string;
13
- chain_status: string;
14
- chain_type: string;
15
- }
16
- export interface WsTradeUpdate extends Omit<TradeResponse, "info"> {
17
- info: WsTradeInfo;
18
- }
19
- export interface WsOrderUpdate extends Omit<OrderResponse, "info"> {
20
- info: WsOrderInfo;
21
- }
22
- export interface CurrencyBalanceDelta {
23
- free?: string;
24
- used?: string;
25
- total?: string;
26
- }
27
- export type WsBalancesUpdate = Record<string, CurrencyBalanceDelta>;
28
- export type WsEvent = "snapshot" | "new_trades" | "update" | "bar_update" | "response" | "subscription_expired";
29
- export interface WsServerMessage<T = unknown> {
30
- topic: string;
31
- event: WsEvent;
32
- data: T;
33
- ts: number;
34
- height: number;
1
+ /** Market channels require a `coin` (BASE/QUOTE) subscription field. */
2
+ export type WsMarketChannel = "l2Book" | "bbo" | "trades" | "candle" | "activeAssetCtx";
3
+ /** User channels require a `user` (address) subscription field. */
4
+ export type WsUserChannel = "orderUpdates" | "openOrders" | "userFills" | "userEvents" | "spotState";
5
+ /** Keyless channels require no key. `chainBlock` is an Ault extension. */
6
+ export type WsKeylessChannel = "allMids" | "chainBlock";
7
+ export type WsChannelType = WsMarketChannel | WsUserChannel | WsKeylessChannel;
8
+ /** Named candle intervals accepted by the `candle` channel. */
9
+ export type CandleInterval = "1m" | "3m" | "5m" | "15m" | "30m" | "1h" | "2h" | "4h" | "8h" | "12h" | "1d" | "3d" | "1w" | "1M";
10
+ /**
11
+ * A subscription descriptor, modeled as a discriminated union on `type` so the
12
+ * required key per channel is enforced at compile time: market channels carry
13
+ * `coin`, `candle` additionally carries `interval`, user channels carry `user`,
14
+ * and keyless channels carry neither. The client omits empty optionals on the
15
+ * wire. A runtime guard in `subscribe()` re-checks the same invariant for
16
+ * untyped callers (e.g. `type` cast through `as never`).
17
+ */
18
+ export type WsSubscription = {
19
+ type: Exclude<WsMarketChannel, "candle">;
20
+ coin: string;
21
+ user?: undefined;
22
+ interval?: undefined;
23
+ } | {
24
+ type: "candle";
25
+ coin: string;
26
+ interval: CandleInterval;
27
+ user?: undefined;
28
+ } | {
29
+ type: WsUserChannel;
30
+ user: string;
31
+ coin?: undefined;
32
+ interval?: undefined;
33
+ } | {
34
+ type: WsKeylessChannel;
35
+ coin?: undefined;
36
+ user?: undefined;
37
+ interval?: undefined;
38
+ };
39
+ export type WsSide = "buy" | "sell";
40
+ /**
41
+ * A single book level. `px` and `sz` are canonical decimal strings with the
42
+ * relay's LegacyDec 18-decimal padding already collapsed server-side (`"1.5"`,
43
+ * not `"1.500000000000000000"`); `sz` is in human units. Do not re-pad or
44
+ * assume a fixed precision. `n` is the order count at the level and is `0`
45
+ * until the relay supplies it.
46
+ */
47
+ export interface WsLevel {
48
+ px: string;
49
+ sz: string;
50
+ n: number;
35
51
  }
36
- export interface WsSubscribeCommand {
37
- action: "subscribe";
38
- topic: string;
39
- ttl?: number;
52
+ /** `allMids` — map of every market's current mid price (decimal strings). */
53
+ export interface WsAllMids {
54
+ mids: Record<string, string>;
40
55
  }
41
- export interface WsUnsubscribeCommand {
42
- action: "unsubscribe";
43
- topic: string;
56
+ /**
57
+ * `l2Book` — `levels[0]` is bids (descending), `levels[1]` is asks (ascending).
58
+ * Snapshot-gated: the first frame after subscribe is the book snapshot, then
59
+ * per-block deltas stream.
60
+ */
61
+ export interface WsBook {
62
+ coin: string;
63
+ levels: [WsLevel[], WsLevel[]];
64
+ time: number;
44
65
  }
45
- export type WsClientCommand = WsSubscribeCommand | WsUnsubscribeCommand;
46
- export interface WsCommandResponse {
47
- action: string;
48
- topic?: string;
49
- success: boolean;
50
- error?: string;
51
- ttl?: number;
66
+ /**
67
+ * `bbo` — best bid/offer. `bbo[0]` is the best bid (or `null`), `bbo[1]` the
68
+ * best ask (or `null`). Emitted only when the top of book changes.
69
+ */
70
+ export interface WsBbo {
71
+ coin: string;
72
+ time: number;
73
+ bbo: [WsLevel | null, WsLevel | null];
74
+ }
75
+ /** A single execution in the `trades` array. `tid` is a 50-bit numeric id. */
76
+ export interface WsTrade {
77
+ coin: string;
78
+ side: WsSide;
79
+ px: string;
80
+ sz: string;
81
+ time: number;
82
+ tid: number;
52
83
  }
84
+ /** `trades` — array of executions in the block. */
85
+ export type WsTrades = WsTrade[];
53
86
  /**
54
- * Payload for the `chain:block` topic. Emitted once per new block regardless
55
- * of market activity so subscribers can drive liveness indicators.
56
- *
57
- * The block header fields (hash, proposer, txCount, gasUsed, gasWanted) are
58
- * optional because older chain versions may not supply them.
59
- *
60
- * `height` is a decimal string for symmetry with the WS trade/order
61
- * `info.block_height`. At one-second blocks the JS-Number boundary
62
- * (~285k years) is a practical non-issue today; the string form keeps
63
- * the numeric WS contract uniform so consumers don't have to special-case
64
- * `chain:block` in their parsing layer.
65
- *
66
- * Field casing: `txCount`, `gasUsed`, `gasWanted` mirror the wire format
67
- * the dex-api WS layer currently emits. Earlier dex-api builds (≤ alpha.13
68
- * era) shipped these as `tx_count` / `gas_used` / `gas_wanted`; consumers
69
- * running against an older API can fall back to the snake-case names by
70
- * widening the type at the boundary, but the SDK has no compatibility
71
- * shim because the wire format is the contract.
72
- */
73
- export interface BlockUpdate {
74
- height: string;
87
+ * A candle bar. `t` is the open time, `T` the close time (`t + period`), both
88
+ * in ms. `s` / `i` echo the coin and interval. OHLCV values are numbers; `n`
89
+ * is the trade count (`0` for snapshot bars).
90
+ */
91
+ export interface WsCandle {
92
+ t: number;
93
+ T: number;
94
+ s: string;
95
+ i: CandleInterval;
96
+ o: number;
97
+ c: number;
98
+ h: number;
99
+ l: number;
100
+ v: number;
101
+ n: number;
102
+ }
103
+ /**
104
+ * `candle` — always an array. The snapshot sends recent history (up to 300
105
+ * bars); a streaming update sends a single-element array.
106
+ */
107
+ export type WsCandles = WsCandle[];
108
+ /**
109
+ * `activeAssetCtx` — per-block market context. The Hyperliquid base fields
110
+ * (`dayNtlVlm`, `prevDayPx`, `markPx`, `midPx`, `circulatingSupply`) are JSON
111
+ * numbers; the Ault extension fields are decimal strings to preserve precision
112
+ * past 2^53. `midPx` and the extension fields are present only when the
113
+ * underlying value resolved (the relay omits them otherwise).
114
+ * `circulatingSupply` is always `0` (not tracked).
115
+ */
116
+ export interface WsActiveAssetCtxData {
117
+ dayNtlVlm: number;
118
+ prevDayPx: number;
119
+ markPx: number;
120
+ midPx?: number;
121
+ circulatingSupply: number;
122
+ high?: string;
123
+ low?: string;
124
+ last?: string;
125
+ average?: string;
126
+ bid?: string;
127
+ bidVolume?: string;
128
+ ask?: string;
129
+ askVolume?: string;
130
+ vwap?: string;
131
+ change?: string;
132
+ percentage?: string;
133
+ baseVolume: string;
134
+ quoteVolume: string;
135
+ }
136
+ export interface WsActiveAssetCtx {
137
+ coin: string;
138
+ ctx: WsActiveAssetCtxData;
139
+ }
140
+ /** HL-collapsed public order status. */
141
+ export type WsOrderStatus = "open" | "filled" | "canceled" | "triggered" | "unknown";
142
+ /** Ault extension: the granular chain-side order status. */
143
+ export type WsChainOrderStatus = "open" | "partially_filled" | "filled" | "cancelled" | "expired" | "triggered_pending";
144
+ /**
145
+ * The basic order shape shared by `orderUpdates` and `openOrders`. `oid` is the
146
+ * JS-safe 50-bit numeric id; `oidHex` is the full 32-char hex id. `sz` is the
147
+ * current remaining size, `origSz` the original. Prices/sizes are decimal
148
+ * strings in human units.
149
+ */
150
+ export interface WsBasicOrder {
151
+ coin: string;
152
+ side: WsSide;
153
+ limitPx: string;
154
+ sz: string;
155
+ oid: number;
156
+ oidHex: string;
157
+ timestamp: number;
158
+ origSz: string;
159
+ }
160
+ /** A single entry in the `orderUpdates` array. */
161
+ export interface WsOrderUpdate {
162
+ order: WsBasicOrder;
163
+ status: WsOrderStatus;
164
+ /** Ault extension: granular chain status. */
165
+ chainStatus: WsChainOrderStatus;
166
+ statusTimestamp: number;
167
+ }
168
+ /** `orderUpdates` — array of changed orders. */
169
+ export type WsOrderUpdates = WsOrderUpdate[];
170
+ /** `openOrders` — snapshot-only. `dex` is always `"ault"`. */
171
+ export interface WsOpenOrders {
172
+ dex: string;
173
+ user: string;
174
+ orders: WsBasicOrder[];
175
+ }
176
+ /**
177
+ * A single fill, shared by `userFills` and the `userEvents` fills shape.
178
+ * `crossed` is `true` for taker fills (all fills are taker-side today). `fee`
179
+ * is estimated from the taker rate; `feeToken` is the quote currency.
180
+ */
181
+ export interface WsFill {
182
+ coin: string;
183
+ px: string;
184
+ sz: string;
185
+ side: WsSide;
186
+ time: number;
187
+ oid: number;
188
+ tid: number;
189
+ crossed: boolean;
190
+ fee: string;
191
+ feeToken: string;
192
+ }
193
+ /**
194
+ * `userFills` — the first frame after subscribe is the snapshot (recent fills,
195
+ * up to 200) with `isSnapshot: true`; live frames carry `isSnapshot: false`.
196
+ */
197
+ export interface WsUserFills {
198
+ isSnapshot: boolean;
199
+ user: string;
200
+ fills: WsFill[];
201
+ }
202
+ /** A system-initiated cancel in the `userEvents` nonUserCancel shape. */
203
+ export interface WsNonUserCancel {
204
+ coin: string;
205
+ oid: number;
206
+ }
207
+ /**
208
+ * `userEvents` — delivered on the `user` channel (not `userEvents`). Each block
209
+ * carries one of two shapes: a `fills` array or a `nonUserCancel` array. A
210
+ * non-user cancel is currently emitted only for expired orders.
211
+ */
212
+ export type WsUserEvents = {
213
+ fills: WsFill[];
214
+ } | {
215
+ nonUserCancel: WsNonUserCancel[];
216
+ };
217
+ /**
218
+ * A single balance entry. `hold` is the amount locked in open orders. `token`
219
+ * is `0` for all assets (Ault assigns no numeric token ids) and `entryNtl` is
220
+ * `"0"` (cost basis not tracked). Amounts are decimal strings in human units.
221
+ */
222
+ export interface WsSpotBalance {
223
+ coin: string;
224
+ token: number;
225
+ hold: string;
226
+ total: string;
227
+ entryNtl: string;
228
+ }
229
+ /**
230
+ * `spotState` — the first frame after subscribe is the full balance set;
231
+ * subsequent frames are **deltas** containing only the balances that changed in
232
+ * the block. Merge them into local state by `coin`. There is no `isSnapshot`
233
+ * flag (matching Hyperliquid).
234
+ */
235
+ export interface WsSpotState {
236
+ user: string;
237
+ spotState: {
238
+ balances: WsSpotBalance[];
239
+ };
240
+ }
241
+ /**
242
+ * `chainBlock` — **Ault extension.** One frame per finalized block. `height`
243
+ * and `timestamp` are always present (both JSON numbers). `hash`, `proposer`,
244
+ * `txCount`, `gasUsed`, and `gasWanted` are present only when the chain
245
+ * publisher supplied block info (older chains omit them).
246
+ */
247
+ export interface WsChainBlock {
248
+ height: number;
75
249
  timestamp: number;
76
250
  hash?: string;
77
251
  proposer?: string;
@@ -79,15 +253,103 @@ export interface BlockUpdate {
79
253
  gasUsed?: number;
80
254
  gasWanted?: number;
81
255
  }
82
- export type PayloadFor<T extends string> = T extends `orderbook:${string}` ? OrderbookResponse : T extends `trades:${string}` ? WsTradeUpdate[] : T extends `ticker:${string}` ? TickerResponse : T extends `chart:${string}` ? OHLCVEntry : T extends `orders:${string}` ? WsOrderUpdate[] : T extends `balances:${string}` ? WsBalancesUpdate : T extends `mytrades:${string}` ? WsTradeUpdate[] : T extends "chain:block" ? BlockUpdate : unknown;
256
+ export interface WsPayloadMap {
257
+ allMids: WsAllMids;
258
+ l2Book: WsBook;
259
+ bbo: WsBbo;
260
+ trades: WsTrades;
261
+ candle: WsCandles;
262
+ activeAssetCtx: WsActiveAssetCtx;
263
+ orderUpdates: WsOrderUpdates;
264
+ openOrders: WsOpenOrders;
265
+ userFills: WsUserFills;
266
+ userEvents: WsUserEvents;
267
+ spotState: WsSpotState;
268
+ chainBlock: WsChainBlock;
269
+ }
270
+ /** Resolves a channel type to its payload shape. */
271
+ export type PayloadFor<T extends WsChannelType> = T extends keyof WsPayloadMap ? WsPayloadMap[T] : unknown;
272
+ /**
273
+ * Every server message is a two-field envelope. `channel` is the subscription
274
+ * `type`, with one exception: `userEvents` data is delivered on the `user`
275
+ * channel. Three control channels (`subscriptionResponse`, `error`,
276
+ * `subscriptionExpired`) carry lifecycle payloads rather than channel data.
277
+ */
278
+ export interface WsServerMessage<T = unknown> {
279
+ channel: string;
280
+ data: T;
281
+ }
282
+ /**
283
+ * Data attached to a `subscriptionResponse`. Echoes the subscription back so
284
+ * the client's view round-trips intact — including ignored fields like `dex`
285
+ * and, for user channels, the `user` in the exact format the client sent
286
+ * (bech32 or `0x`). `ttl` is the effective (clamped) lifetime; `error` is
287
+ * present on failure.
288
+ */
289
+ export interface WsSubscriptionAck {
290
+ type: string;
291
+ coin?: string;
292
+ user?: string;
293
+ interval?: string;
294
+ ttl?: number;
295
+ dex?: string;
296
+ error?: string;
297
+ [key: string]: unknown;
298
+ }
299
+ /**
300
+ * Data attached to an `error` frame (protocol-level failure). When the failure
301
+ * is tied to a specific subscribe/unsubscribe command (e.g. rate limit,
302
+ * rejection), the server echoes the offending `subscription` so the client can
303
+ * reject the matching pending command and notify only that subscription instead
304
+ * of relying on the 10s command timeout.
305
+ */
306
+ export interface WsErrorData {
307
+ message: string;
308
+ subscription?: WsSubscription;
309
+ }
310
+ /** Data attached to a `subscriptionExpired` frame. */
311
+ export interface WsSubscriptionExpiredData {
312
+ subscription: WsSubscription;
313
+ reason: string;
314
+ }
315
+ /**
316
+ * The subscription object sent on the wire (descriptor + optional ttl). Modeled
317
+ * as an intersection because `WsSubscription` is a discriminated union — an
318
+ * interface cannot `extends` a union, so we add the `ttl` field across every
319
+ * member instead.
320
+ *
321
+ * Ault extension: `ttl` is the subscription lifetime in seconds. `0` = no
322
+ * expiry. The server caps it at 3,600 (1 hour) and echoes the effective value
323
+ * in the ack.
324
+ */
325
+ export type WsSubscriptionRequest = WsSubscription & {
326
+ ttl?: number;
327
+ };
328
+ export interface WsSubscribeCommand {
329
+ method: "subscribe";
330
+ subscription: WsSubscriptionRequest;
331
+ }
332
+ export interface WsUnsubscribeCommand {
333
+ method: "unsubscribe";
334
+ subscription: WsSubscription;
335
+ }
336
+ export type WsClientCommand = WsSubscribeCommand | WsUnsubscribeCommand;
83
337
  export interface SubscriptionHandlers<T> {
338
+ /** Called for every data frame on the channel (snapshot and deltas alike). */
84
339
  onData: (data: T, message: WsServerMessage<T>) => void;
340
+ /** Called on subscribe failure or a per-frame handler throw. */
85
341
  onError?: (error: Error) => void;
86
- onSubscribed?: () => void;
342
+ /**
343
+ * Called once the server acks the subscription. The ack carries the
344
+ * effective (clamped) `ttl` and the echoed `user` in the client's original
345
+ * format.
346
+ */
347
+ onSubscribed?: (ack: WsSubscriptionAck) => void;
348
+ /** Called when a TTL-based subscription expires server-side. */
87
349
  onExpired?: () => void;
88
350
  }
89
351
  export interface Subscription {
90
- topic: string;
352
+ subscription: WsSubscription;
91
353
  unsubscribe: () => void;
92
354
  }
93
355
  export type WsConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ault-sdk-ts",
3
- "version": "0.0.2-alpha.19",
3
+ "version": "0.0.2-alpha.21",
4
4
  "description": "TypeScript SDK for the Ault blockchain with high-level transaction methods and REST query clients",
5
5
  "keywords": [
6
6
  "ault",