@metaflux-dex/client 0.0.1

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +157 -0
  3. package/dist/client.d.ts +32 -0
  4. package/dist/client.d.ts.map +1 -0
  5. package/dist/client.js +344 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/http.d.ts +17 -0
  8. package/dist/http.d.ts.map +1 -0
  9. package/dist/http.js +106 -0
  10. package/dist/http.js.map +1 -0
  11. package/dist/index.d.ts +9 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +26 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/info-types.d.ts +380 -0
  16. package/dist/info-types.d.ts.map +1 -0
  17. package/dist/info-types.js +16 -0
  18. package/dist/info-types.js.map +1 -0
  19. package/dist/info.d.ts +65 -0
  20. package/dist/info.d.ts.map +1 -0
  21. package/dist/info.js +252 -0
  22. package/dist/info.js.map +1 -0
  23. package/dist/native.d.ts +10 -0
  24. package/dist/native.d.ts.map +1 -0
  25. package/dist/native.js +252 -0
  26. package/dist/native.js.map +1 -0
  27. package/dist/types.d.ts +143 -0
  28. package/dist/types.d.ts.map +1 -0
  29. package/dist/types.js +13 -0
  30. package/dist/types.js.map +1 -0
  31. package/dist/wasm.d.ts +28 -0
  32. package/dist/wasm.d.ts.map +1 -0
  33. package/dist/wasm.js +279 -0
  34. package/dist/wasm.js.map +1 -0
  35. package/dist/ws.d.ts +43 -0
  36. package/dist/ws.d.ts.map +1 -0
  37. package/dist/ws.js +221 -0
  38. package/dist/ws.js.map +1 -0
  39. package/package.json +65 -0
  40. package/src/client.ts +454 -0
  41. package/src/http.ts +153 -0
  42. package/src/index.ts +144 -0
  43. package/src/info-types.ts +783 -0
  44. package/src/info.ts +355 -0
  45. package/src/native.ts +307 -0
  46. package/src/types.ts +305 -0
  47. package/src/wasm.ts +384 -0
  48. package/src/ws.ts +279 -0
@@ -0,0 +1,143 @@
1
+ export type Side = 0 | 1;
2
+ export type Tif = 0 | 1 | 2;
3
+ export type StpMode = 0 | 1 | 2 | 3;
4
+ export interface Builder {
5
+ fee: number;
6
+ user: string;
7
+ }
8
+ export interface Order {
9
+ asset: number;
10
+ side: Side;
11
+ priceE8: bigint;
12
+ sizeE8: bigint;
13
+ tif: Tif;
14
+ stp?: StpMode;
15
+ cloid?: bigint;
16
+ reduceOnly?: boolean;
17
+ builder?: Builder;
18
+ }
19
+ export interface SignedOrder {
20
+ payload: Uint8Array;
21
+ signature: Uint8Array;
22
+ signer: Uint8Array;
23
+ }
24
+ export interface NativeOrder {
25
+ owner: string;
26
+ market: number;
27
+ side: NativeSide;
28
+ kind: NativeOrderKind;
29
+ size: number;
30
+ limit_px: number;
31
+ tif: NativeTif;
32
+ stp_mode: NativeStpMode;
33
+ reduce_only: boolean;
34
+ cloid?: string;
35
+ builder?: NativeBuilder;
36
+ }
37
+ export interface NativeCancel {
38
+ owner: string;
39
+ market: number;
40
+ oid?: number;
41
+ cloid?: string;
42
+ }
43
+ export type NativeSide = 'bid' | 'ask';
44
+ export type NativeOrderKind = 'limit' | 'market' | 'stop_loss' | 'take_profit';
45
+ export type NativeTif = 'gtc' | 'ioc' | 'aon' | 'alo';
46
+ export type NativeStpMode = 'cancel_oldest' | 'cancel_newest' | 'cancel_both' | 'reject';
47
+ export interface NativeBuilder {
48
+ fee: number;
49
+ user: string;
50
+ }
51
+ export interface NativeSignedAction {
52
+ actionJson: string;
53
+ nonce: bigint;
54
+ signature: string;
55
+ }
56
+ export type OrderStatus = {
57
+ resting: {
58
+ oid: number;
59
+ cloid?: string;
60
+ };
61
+ } | {
62
+ filled: {
63
+ oid: number;
64
+ total_sz: string;
65
+ avg_px: string;
66
+ };
67
+ } | {
68
+ error: string;
69
+ } | {
70
+ pending: {
71
+ action_hash: string;
72
+ nonce: number;
73
+ };
74
+ };
75
+ export interface NativeExchangeAck {
76
+ statuses?: OrderStatus[];
77
+ accepted?: boolean;
78
+ error?: string;
79
+ mempool_depth?: number;
80
+ nonce?: number;
81
+ action_hash?: string;
82
+ }
83
+ export interface OrderAck {
84
+ id: string;
85
+ timestamp: number;
86
+ datetime: string;
87
+ symbol: string;
88
+ type: 'limit' | 'market';
89
+ side: 'buy' | 'sell';
90
+ price?: string;
91
+ amount: string;
92
+ filled: string;
93
+ remaining: string;
94
+ status: 'open' | 'closed' | 'canceled' | 'expired' | 'rejected';
95
+ clientOrderId?: string;
96
+ }
97
+ export interface Market {
98
+ id: string;
99
+ symbol: string;
100
+ base: string;
101
+ quote: string;
102
+ settle?: string;
103
+ active: boolean;
104
+ spot: boolean;
105
+ contract: boolean;
106
+ swap: boolean;
107
+ future: boolean;
108
+ linear: boolean;
109
+ precision: {
110
+ amount: number;
111
+ price: number;
112
+ };
113
+ limits: {
114
+ amount: {
115
+ min?: string;
116
+ max?: string;
117
+ };
118
+ price: {
119
+ min?: string;
120
+ max?: string;
121
+ };
122
+ cost: {
123
+ min?: string;
124
+ max?: string;
125
+ };
126
+ };
127
+ }
128
+ export interface Position {
129
+ symbol: string;
130
+ side: 'long' | 'short';
131
+ contracts: string;
132
+ notional?: string;
133
+ entryPrice?: string;
134
+ markPrice?: string;
135
+ liquidationPrice?: string;
136
+ unrealizedPnl?: string;
137
+ leverage?: string;
138
+ timestamp: number;
139
+ }
140
+ export interface ErrorEnvelope {
141
+ error: string;
142
+ }
143
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAgBA,MAAM,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;AAKzB,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAO5B,MAAM,MAAM,OAAO,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAMpC,MAAM,WAAW,OAAO;IAItB,GAAG,EAAE,M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pB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB;AAKD,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;CACf"}
package/dist/types.js ADDED
@@ -0,0 +1,13 @@
1
+ // Type definitions for the @metaflux-dex/client surface.
2
+ //
3
+ // Shapes mirror the CCXT-compat REST responses emitted by the MetaFlux
4
+ // api-gateway (`metaflux/crates/api-gateway/src/ccxt/types.rs`). The
5
+ // monetary-fields-as-decimal-strings convention is load-bearing — CCXT
6
+ // clients pass these straight into `Decimal(value)` and any drift to
7
+ // number-typed fields silently loses precision.
8
+ //
9
+ // `Order` / `SignedOrder` are MTF-native (they carry pre-signed bytes
10
+ // the gateway forwards to the node). The other types match what the
11
+ // gateway emits.
12
+ export {};
13
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,yDAAyD;AACzD,EAAE;AACF,uEAAuE;AACvE,qEAAqE;AACrE,uEAAuE;AACvE,qEAAqE;AACrE,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,iBAAiB"}
package/dist/wasm.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import type { Builder, Side, StpMode, Tif } from './types.js';
2
+ interface WasmModule {
3
+ default: (path?: string | URL | Request) => Promise<unknown>;
4
+ keccak256: (data: Uint8Array) => Uint8Array;
5
+ sign_secp256k1: (privKey: Uint8Array, messageHash: Uint8Array) => Uint8Array;
6
+ recover_pubkey: (sig: Uint8Array, messageHash: Uint8Array) => Uint8Array;
7
+ verify_secp256k1: (pubkeyCompressed: Uint8Array, sig: Uint8Array, messageHash: Uint8Array) => boolean;
8
+ eip712_typed_data_hash: (domainSeparator: Uint8Array, messageHash: Uint8Array) => Uint8Array;
9
+ encode_limit_order: (asset: number, side: number, sizeE8Lo: bigint, sizeE8Hi: bigint, priceE8Lo: bigint, priceE8Hi: bigint, tif: number, stp: number, hasCloid: boolean, cloidLo: bigint, cloidHi: bigint, reduceOnly: boolean, hasBuilder: boolean, builderFee: number, builderUser: Uint8Array) => Uint8Array;
10
+ derive_address_from_pubkey: (pubkey: Uint8Array) => Uint8Array;
11
+ }
12
+ export declare class WasmNotBuiltError extends Error {
13
+ constructor(cause?: unknown);
14
+ }
15
+ export declare class WasmCallError extends Error {
16
+ readonly call: string;
17
+ constructor(call: string, hint?: string);
18
+ }
19
+ export declare function loadWasm(): Promise<WasmModule>;
20
+ export declare function _resetWasmCacheForTest(): void;
21
+ export declare function keccak256(data: Uint8Array): Promise<Uint8Array>;
22
+ export declare function signSecp256k1(privKey: Uint8Array, messageHash: Uint8Array): Promise<Uint8Array>;
23
+ export declare function recoverPubkey(sig: Uint8Array, messageHash: Uint8Array): Promise<Uint8Array>;
24
+ export declare function eip712TypedDataHash(domainSeparator: Uint8Array, messageHash: Uint8Array): Promise<Uint8Array>;
25
+ export declare function encodeLimitOrder(asset: number, side: Side, sizeE8: bigint, priceE8: bigint, tif: Tif, stp?: StpMode, cloid?: bigint, reduceOnly?: boolean, builder?: Builder): Promise<Uint8Array>;
26
+ export declare function deriveAddressFromPubkey(pubkey: Uint8Array): Promise<Uint8Array>;
27
+ export {};
28
+ //# sourceMappingURL=wasm.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wasm.d.ts","sourceRoot":"","sources":["../src/wasm.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAK9D,UAAU,UAAU;IAClB,OAAO,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,KAAK,OAAO,CAAC,OAAO,CAA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,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAOrE;AAID,wBAAsB,aAAa,CACjC,OAAO,EAAE,UAAU,EACnB,WAAW,EAAE,UAAU,GACtB,OAAO,CAAC,UAAU,CAAC,CAUrB;AAGD,wBAAsB,aAAa,CACjC,GAAG,EAAE,UAAU,EACf,WAAW,EAAE,UAAU,GACtB,OAAO,CAAC,UAAU,CAAC,CAUrB;AAGD,wBAAsB,mBAAmB,CACvC,eAAe,EAAE,UAAU,EAC3B,WAAW,EAAE,UAAU,GACtB,OAAO,CAAC,UAAU,CAAC,CAUrB;AAqBD,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,GAAG,EACR,GAAG,GAAE,OAAW,EAChB,KAAK,CAAC,EAAE,MAAM,EACd,UAAU,UAAQ,EAClB,OAAO,CAAC,EAAE,OAAO,GAChB,OAAO,CAAC,UAAU,CAAC,CAkErB;AAgCD,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,UAAU,CAAC,CAUrB"}
package/dist/wasm.js ADDED
@@ -0,0 +1,279 @@
1
+ // WASM module loader + typed facade.
2
+ //
3
+ // The wasm-pack-emitted `pkg/metaflux_client_wasm.js` is dynamically
4
+ // imported so the bundle can be tree-shaken when consumers only want
5
+ // the pure-TS REST surface. `loadWasm()` is idempotent; first call
6
+ // instantiates, subsequent calls reuse the resolved promise.
7
+ //
8
+ // Why dynamic import + facade?
9
+ //
10
+ // 1. The `pkg/` directory is only present after `npm run build:wasm`.
11
+ // A top-level `import` would crash on a fresh clone before that step
12
+ // runs; dynamic import lets the WASM-using code paths fail with a
13
+ // helpful error pointing to the build command.
14
+ // 2. The wasm-bindgen-generated module exports raw `Uint8Array` returns
15
+ // that are zero-length on encoder failure (see `lib.rs`). The facade
16
+ // promotes that to a typed exception, keeping the Client surface
17
+ // free of "did this succeed?" branches.
18
+ let wasmPromise;
19
+ /// Custom error thrown when the WASM module cannot be loaded — e.g. on
20
+ /// a fresh clone before `npm run build:wasm` has produced `pkg/`. The
21
+ /// message points at the fix.
22
+ export class WasmNotBuiltError extends Error {
23
+ constructor(cause) {
24
+ super('metaflux_client_wasm not built. Run `npm run build:wasm` first ' +
25
+ '(requires `wasm-pack`; install via `brew install wasm-pack`).');
26
+ this.name = 'WasmNotBuiltError';
27
+ if (cause !== undefined) {
28
+ this.cause = cause;
29
+ }
30
+ }
31
+ }
32
+ /// Thrown when a WASM-side encoder/signer returns an empty buffer (the
33
+ /// `lib.rs` convention for invalid input). Carries the failed call name.
34
+ export class WasmCallError extends Error {
35
+ call;
36
+ constructor(call, hint) {
37
+ super(`WASM call '${call}' returned empty result` +
38
+ (hint !== undefined ? ` (${hint})` : ''));
39
+ this.call = call;
40
+ this.name = 'WasmCallError';
41
+ }
42
+ }
43
+ /// Idempotently load + initialise the WASM module.
44
+ ///
45
+ /// First call dynamically imports `../pkg/metaflux_client_wasm.js`
46
+ /// (the wasm-pack output), invokes the default-export `init`, and
47
+ /// caches the resolved module. Subsequent calls return the cached
48
+ /// promise — both fast-path and re-entrant safe.
49
+ ///
50
+ /// The dynamic import path is built from a string variable so the
51
+ /// TypeScript compiler does not try to statically resolve the
52
+ /// (until-built) `pkg/` directory at typecheck time. The shape
53
+ /// expected from the loaded module is enforced by the cast to
54
+ /// `WasmModule`.
55
+ export async function loadWasm() {
56
+ if (wasmPromise === undefined) {
57
+ wasmPromise = (async () => {
58
+ let mod;
59
+ try {
60
+ // Path is relative to the *compiled* dist/ output (one level
61
+ // above pkg/ at the repo root). At dev-mode (vitest running
62
+ // .ts directly) the same relative path lands on the same
63
+ // pkg/ directory because vitest cwd is the repo root.
64
+ const wasmPath = '../pkg/metaflux_client_wasm.js';
65
+ mod = (await import(/* @vite-ignore */ wasmPath));
66
+ }
67
+ catch (err) {
68
+ throw new WasmNotBuiltError(err);
69
+ }
70
+ // wasm-pack's default-export `init` accepts an optional .wasm source;
71
+ // we let it auto-resolve relative to the .js shim. The Node-target
72
+ // build (`--target nodejs`) loads the .wasm synchronously at
73
+ // module-load time and exposes NO default export — only `web` /
74
+ // `bundler` builds need this call.
75
+ if (typeof mod.default === 'function') {
76
+ const init = mod
77
+ .default;
78
+ try {
79
+ // Browser / bundler: default-resolve the .wasm via fetch.
80
+ await init();
81
+ }
82
+ catch (fetchErr) {
83
+ // Node (incl. vitest): the web-target shim's `init()` fetches the
84
+ // .wasm by file URL, which Node's fetch refuses. Fall back to
85
+ // reading + compiling the bytes ourselves and handing them to
86
+ // init(). Only attempt this where `node:fs` is importable; if it
87
+ // is not (true browser), rethrow the original fetch error.
88
+ const compiled = await compileWasmFromFs();
89
+ if (compiled === undefined)
90
+ throw fetchErr;
91
+ await init({ module_or_path: compiled });
92
+ }
93
+ }
94
+ return mod;
95
+ })();
96
+ }
97
+ return wasmPromise;
98
+ }
99
+ /// Reset the cached module — used by tests that want to exercise the
100
+ /// WasmNotBuiltError path. Not part of the public API.
101
+ export function _resetWasmCacheForTest() {
102
+ wasmPromise = undefined;
103
+ }
104
+ /// Node-only: read + compile the wasm-pack `_bg.wasm` bytes so the web-target
105
+ /// `init()` can be fed a ready module instead of fetching a file URL (which
106
+ /// Node's `fetch` rejects). Returns `undefined` in environments without
107
+ /// `node:fs` (a real browser), where the fetch path is correct anyway.
108
+ async function compileWasmFromFs() {
109
+ try {
110
+ const fs = await import('node:fs/promises');
111
+ const url = await import('node:url');
112
+ const path = await import('node:path');
113
+ // Resolve the .wasm next to the wasm-pack .js shim. From dev (vitest on
114
+ // src/*.ts) the cwd is the repo root and pkg/ sits there; from the
115
+ // compiled dist/ output pkg/ is one level up. Try both.
116
+ const candidates = [
117
+ path.resolve(process.cwd(), 'pkg', 'metaflux_client_wasm_bg.wasm'),
118
+ url.fileURLToPath(new URL('../pkg/metaflux_client_wasm_bg.wasm', import.meta.url)),
119
+ ];
120
+ for (const c of candidates) {
121
+ try {
122
+ const bytes = await fs.readFile(c);
123
+ return await WebAssembly.compile(bytes);
124
+ }
125
+ catch {
126
+ // Try the next candidate.
127
+ }
128
+ }
129
+ return undefined;
130
+ }
131
+ catch {
132
+ // `node:fs` unavailable -> not Node; the fetch path is the right one.
133
+ return undefined;
134
+ }
135
+ }
136
+ // ============================================================================
137
+ // Typed wrappers — each promotes an empty WASM result to a thrown error.
138
+ // ============================================================================
139
+ /// `keccak256(data)` -> 32-byte digest. Throws `WasmCallError` on empty
140
+ /// result (should not happen — keccak accepts any length input).
141
+ export async function keccak256(data) {
142
+ const wasm = await loadWasm();
143
+ const out = wasm.keccak256(data);
144
+ if (out.length !== 32) {
145
+ throw new WasmCallError('keccak256', `got ${out.length} bytes, want 32`);
146
+ }
147
+ return out;
148
+ }
149
+ /// Produce a recoverable ECDSA signature in `r || s || v` 65-byte form.
150
+ /// Throws on a malformed private key or message hash length.
151
+ export async function signSecp256k1(privKey, messageHash) {
152
+ const wasm = await loadWasm();
153
+ const out = wasm.sign_secp256k1(privKey, messageHash);
154
+ if (out.length !== 65) {
155
+ throw new WasmCallError('sign_secp256k1', 'invalid private key or message hash length (expected 32 bytes each)');
156
+ }
157
+ return out;
158
+ }
159
+ /// Recover the 33-byte compressed pubkey from a sig + message digest.
160
+ export async function recoverPubkey(sig, messageHash) {
161
+ const wasm = await loadWasm();
162
+ const out = wasm.recover_pubkey(sig, messageHash);
163
+ if (out.length !== 33) {
164
+ throw new WasmCallError('recover_pubkey', 'malformed signature or message hash');
165
+ }
166
+ return out;
167
+ }
168
+ /// EIP-712 envelope hash: `keccak256(0x1901 || domain || message)`.
169
+ export async function eip712TypedDataHash(domainSeparator, messageHash) {
170
+ const wasm = await loadWasm();
171
+ const out = wasm.eip712_typed_data_hash(domainSeparator, messageHash);
172
+ if (out.length !== 32) {
173
+ throw new WasmCallError('eip712_typed_data_hash', `got ${out.length} bytes, want 32`);
174
+ }
175
+ return out;
176
+ }
177
+ /// Encode the canonical msgpack body for an `order` action. The 128-bit
178
+ /// `priceE8` / `sizeE8` amounts are split into (lo, hi) `bigint` words
179
+ /// for the wasm-bindgen ABI — see `lib.rs::u128_from_parts`.
180
+ ///
181
+ /// `stp` (self-trade-prevention) and `reduceOnly` are REQUIRED on the node's
182
+ /// signed wire (`OrderParams` has no serde default for either); they default
183
+ /// here to `0` (CancelNewest) / `false` so callers can omit them, but are
184
+ /// always emitted into the body.
185
+ ///
186
+ /// `cloid` (optional client order id) rides the signed body as the raw 128-bit
187
+ /// integer — the node's `Cloid(u128)` wire form — split into (lo, hi) words for
188
+ /// the wasm-bindgen ABI. Omit for no cloid (the key is skipped; the node fills
189
+ /// `None`).
190
+ ///
191
+ /// `builder` (ADR-012 §L.5.2) is optional. When supplied it is encoded
192
+ /// INSIDE the body so the carve is covered by the EIP-712 signature; an
193
+ /// omitted builder produces byte-identical output to the pre-builder
194
+ /// encoder (the `builder` key is skipped, and the node defaults it to
195
+ /// `None`).
196
+ export async function encodeLimitOrder(asset, side, sizeE8, priceE8, tif, stp = 0, cloid, reduceOnly = false, builder) {
197
+ if (sizeE8 < 0n)
198
+ throw new RangeError('sizeE8 must be non-negative');
199
+ if (priceE8 < 0n)
200
+ throw new RangeError('priceE8 must be non-negative');
201
+ if (sizeE8 >= 1n << 128n)
202
+ throw new RangeError('sizeE8 overflows u128');
203
+ if (priceE8 >= 1n << 128n)
204
+ throw new RangeError('priceE8 overflows u128');
205
+ const mask64 = (1n << 64n) - 1n;
206
+ const sizeLo = sizeE8 & mask64;
207
+ const sizeHi = (sizeE8 >> 64n) & mask64;
208
+ const priceLo = priceE8 & mask64;
209
+ const priceHi = (priceE8 >> 64n) & mask64;
210
+ // Cloid: optional 128-bit client order id. On the signed wire it is the
211
+ // raw u128 (node `Cloid(u128)`), split into (lo, hi) for the ABI.
212
+ let hasCloid = false;
213
+ let cloidLo = 0n;
214
+ let cloidHi = 0n;
215
+ if (cloid !== undefined) {
216
+ if (cloid < 0n)
217
+ throw new RangeError('cloid must be non-negative');
218
+ if (cloid >= 1n << 128n)
219
+ throw new RangeError('cloid overflows u128');
220
+ hasCloid = true;
221
+ cloidLo = cloid & mask64;
222
+ cloidHi = (cloid >> 64n) & mask64;
223
+ }
224
+ // Builder carve. Validate fee + address shape on the TS side so a
225
+ // malformed carve fails loudly here rather than encoding silently —
226
+ // an unsigned or dropped builder would be worse than a thrown error.
227
+ let hasBuilder = false;
228
+ let builderFee = 0;
229
+ let builderUser = EMPTY_BYTES;
230
+ if (builder !== undefined) {
231
+ if (!Number.isInteger(builder.fee) || builder.fee < 0 || builder.fee > 0xffff) {
232
+ throw new RangeError('builder.fee must be a u16 (0..=65535) in basis points');
233
+ }
234
+ builderUser = addressHexToBytes(builder.user);
235
+ hasBuilder = true;
236
+ builderFee = builder.fee;
237
+ }
238
+ const wasm = await loadWasm();
239
+ const out = wasm.encode_limit_order(asset, side, sizeLo, sizeHi, priceLo, priceHi, tif, stp, hasCloid, cloidLo, cloidHi, reduceOnly, hasBuilder, builderFee, builderUser);
240
+ if (out.length === 0) {
241
+ throw new WasmCallError('encode_limit_order', 'msgpack encoder failed (invalid builder address length?)');
242
+ }
243
+ return out;
244
+ }
245
+ /// Shared empty buffer for the no-builder fast path — avoids allocating a
246
+ /// fresh zero-length `Uint8Array` per call.
247
+ const EMPTY_BYTES = new Uint8Array(0);
248
+ /// Parse a `0x`-prefixed (or bare) 40-char hex address into 20 raw bytes.
249
+ /// Mirrors `core_state::address::Address::from_hex`. Throws on any
250
+ /// non-hex char or wrong length — a malformed builder address must never
251
+ /// reach the signed body.
252
+ function addressHexToBytes(addr) {
253
+ const hex = addr.startsWith('0x') ? addr.slice(2) : addr;
254
+ if (hex.length !== 40) {
255
+ throw new RangeError(`builder.user must be a 20-byte (40 hex char) address, got '${addr}'`);
256
+ }
257
+ // Whole-string hex check up front — `parseInt('1z', 16)` would silently
258
+ // return 1, so per-byte parsing alone could mask a malformed char.
259
+ if (!/^[0-9a-fA-F]{40}$/.test(hex)) {
260
+ throw new RangeError(`builder.user contains a non-hex character: '${addr}'`);
261
+ }
262
+ const out = new Uint8Array(20);
263
+ for (let i = 0; i < 20; i++) {
264
+ out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
265
+ }
266
+ return out;
267
+ }
268
+ /// Derive the standard 20-byte EVM address from a SEC1 public key.
269
+ /// Accepts 33-byte compressed, 64-byte raw x||y, or 65-byte
270
+ /// uncompressed `0x04 || x || y`.
271
+ export async function deriveAddressFromPubkey(pubkey) {
272
+ const wasm = await loadWasm();
273
+ const out = wasm.derive_address_from_pubkey(pubkey);
274
+ if (out.length !== 20) {
275
+ throw new WasmCallError('derive_address_from_pubkey', 'malformed pubkey (expected 33, 64, or 65 bytes)');
276
+ }
277
+ return out;
278
+ }
279
+ //# sourceMappingURL=wasm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wasm.js","sourceRoot":"","sources":["../src/wasm.ts"],"names":[],"mappings":"AAAA,qCAAqC;AACrC,EAAE;AACF,qEAAqE;AACrE,qEAAqE;AACrE,mEAAmE;AACnE,6DAA6D;AAC7D,EAAE;AACF,+BAA+B;AAC/B,EAAE;AACF,sEAAsE;AACtE,wEAAwE;AACxE,qEAAqE;AACrE,kDAAkD;AAClD,wEAAwE;AACxE,wEAAwE;AACxE,oEAAoE;AACpE,2CAA2C;AAyC3C,IAAI,WAA4C,CAAC;AAEjD,uEAAuE;AACvE,sEAAsE;AACtE,8BAA8B;AAC9B,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAC1C,YAAY,KAAe;QACzB,KAAK,CACH,iEAAiE;YAC/D,+DAA+D,CAClE,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;QAChC,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACvB,IAA4B,CAAC,KAAK,GAAG,KAAK,CAAC;QAC9C,CAAC;IACH,CAAC;CACF;AAED,uEAAuE;AACvE,yEAAyE;AACzE,MAAM,OAAO,aAAc,SAAQ,KAAK;IACV;IAA5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AAC,CAAC;IAC/E,CAAC;IACD,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IAC/B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC;QAC5B,GAAG,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAC5D,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,mEAAmE;AACnE,4DAA4D;AAC5D,kCAAkC;AAClC,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,MAAkB;IAElB,MAAM,IAAI,GAAG,MAAM,QAAQ,EAAE,CAAC;IAC9B,MAAM,GAAG,GAAG,IAAI,CAAC,0BAA0B,CAAC,MAAM,CAAC,CAAC;IACpD,IAAI,GAAG,CAAC,MAAM,KAAK,EAAE,EAAE,CAAC;QACtB,MAAM,IAAI,aAAa,CACrB,4BAA4B,EAC5B,iDAAiD,CAClD,CAAC;IACJ,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
package/dist/ws.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ export type WsChannel = 'l2Book' | 'trades' | 'bbo' | 'fills' | 'candles' | 'userEvents';
2
+ export declare const WS_CHANNELS: readonly WsChannel[];
3
+ export interface WsSubscription {
4
+ type: WsChannel;
5
+ coin?: string;
6
+ }
7
+ export interface WsFrame {
8
+ channel: string;
9
+ data: unknown;
10
+ }
11
+ export type WsMessageHandler = (frame: WsFrame) => void;
12
+ export interface WsConfig {
13
+ pingIntervalMs: number;
14
+ initialBackoffMs: number;
15
+ maxBackoffMs: number;
16
+ autoReconnect: boolean;
17
+ }
18
+ export declare class WsClient {
19
+ private readonly url;
20
+ private readonly config;
21
+ private socket;
22
+ private readonly active;
23
+ private readonly handlers;
24
+ private pingTimer;
25
+ private reconnectTimer;
26
+ private backoffMs;
27
+ private closed;
28
+ constructor(url: string, config?: Partial<WsConfig>);
29
+ onMessage(handler: WsMessageHandler): () => void;
30
+ connect(): Promise<void>;
31
+ subscribe(sub: WsSubscription): Promise<void>;
32
+ unsubscribe(sub: WsSubscription): Promise<void>;
33
+ get isOpen(): boolean;
34
+ close(): void;
35
+ private openOnce;
36
+ private scheduleReconnect;
37
+ private startPing;
38
+ private send;
39
+ private dispatch;
40
+ private clearTimers;
41
+ private clearPing;
42
+ }
43
+ //# sourceMappingURL=ws.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ws.d.ts","sourceRoot":"","sources":["../src/ws.ts"],"names":[],"mappings":"AAuBA,MAAM,MAAM,SAAS,GACjB,QAAQ,GACR,QAAQ,GACR,KAAK,GACL,OAAO,GACP,SAAS,GACT,YAAY,CAAC;AAGjB,eAAO,MAAM,WAAW,EAAE,SAAS,SAAS,EAOlC,CAAC;AAKX,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,SAAS,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAOD,MAAM,WAAW,OAAO;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,OAAO,CAAC;CACf;AAGD,MAAM,MAAM,gBAAgB,GAAG,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;AAGxD,MAAM,WAAW,QAAQ;IAEvB,cAAc,EAAE,MAAM,CAAC;IAEvB,gBAAgB,EAAE,MAAM,CAAC;IAEzB,YAAY,EAAE,MAAM,CAAC;IAErB,aAAa,EAAE,OAAO,CAAC;CACxB;AA6BD,qBAAa,QAAQ;IACnB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAW;IAClC,OAAO,CAAC,MAAM,CAAwB;IAEtC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAqC;IAC5D,OAAO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