@wagmipro/sdk 0.0.0-stage → 0.6.0

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.
@@ -0,0 +1,81 @@
1
+ export interface StreamMessage {
2
+ type: string;
3
+ channel?: string;
4
+ seq?: number;
5
+ ts?: number;
6
+ data?: Record<string, unknown> & {
7
+ event?: string;
8
+ };
9
+ [k: string]: unknown;
10
+ }
11
+ type WSLike = {
12
+ send(d: string): void;
13
+ close(code?: number): void;
14
+ readyState: number;
15
+ onopen: ((e?: unknown) => void) | null;
16
+ onmessage: ((e: {
17
+ data: unknown;
18
+ }) => void) | null;
19
+ onclose: ((e?: unknown) => void) | null;
20
+ onerror: ((e?: unknown) => void) | null;
21
+ };
22
+ export interface StreamOptions {
23
+ url?: string;
24
+ apiKey?: string;
25
+ apiSecret?: string;
26
+ WebSocket?: new (url: string) => WSLike;
27
+ now?: () => number;
28
+ /** No message for this long: {type: "stale"} to every handler and a new connection (default 10000; 0 turns it off). */
29
+ staleAfterMs?: number;
30
+ /** A message this far behind (a gap with nothing, or its ts against the heartbeats' clock) is marked stale (default 5000). */
31
+ lateAfterMs?: number;
32
+ }
33
+ export declare class WagmiStream {
34
+ private readonly o;
35
+ private ws;
36
+ private channels;
37
+ private handlers;
38
+ private events;
39
+ private waiters;
40
+ private backoff;
41
+ private closed;
42
+ private id;
43
+ private ready;
44
+ /** When the current connection last delivered anything; whether it was called stale; how late recent messages were. */
45
+ private lastAt;
46
+ private staleSent;
47
+ private lateMode;
48
+ private lags;
49
+ private everOpen;
50
+ private watchdog;
51
+ constructor(o?: StreamOptions);
52
+ /** Opens the socket (and authenticates with a key). Called by subscribe; you need not call it yourself. */
53
+ connect(): Promise<void>;
54
+ private emit;
55
+ /**
56
+ * Marks a late message (see the header): a gap of more than lateAfterMs + 2 s before it starts a late run that ends
57
+ * with the first message on time or the server's own resync; a message behind its ts by more than lateAfterMs (against
58
+ * the smallest delay seen in the last 2 minutes, which is the clocks' offset) is late on its own.
59
+ */
60
+ private markLate;
61
+ /** No message for staleAfterMs: {type: "stale"} to every handler, then a new connection (the old one is let go). */
62
+ private startWatchdog;
63
+ /** Whether the stream is silent past staleAfterMs or delivering late data. */
64
+ isStale(): boolean;
65
+ private resubscribe;
66
+ /** Every message, as it arrives. Returns a function that removes the handler. */
67
+ onMessage(h: (m: StreamMessage) => void): () => void;
68
+ subscribe(channels: string[]): Promise<void>;
69
+ unsubscribe(channels: string[]): Promise<void>;
70
+ /**
71
+ * The orders channel's "confirmed" or "refused" event for one order (by clientOrderId, or by orderId for a cancel or a
72
+ * modify), or null after timeoutMs; an order a cancel all ended answers with its "cancelled" event (0.4.1). Subscribe to
73
+ * "orders" before you send the order.
74
+ */
75
+ waitForOrder(ref: {
76
+ clientOrderId?: string | number;
77
+ orderId?: string;
78
+ }, timeoutMs?: number): Promise<StreamMessage | null>;
79
+ close(): void;
80
+ }
81
+ export {};
package/dist/stream.js ADDED
@@ -0,0 +1,234 @@
1
+ /**
2
+ * The WAGMI.PRO websocket (wss://api.wagmi.pro/v1/ws): public channels with no key; with a key, the auth message and your
3
+ * account channels. Reconnects by itself (1 s to 30 s) and subscribes again. The orders channel's events ("sent", then
4
+ * "confirmed" or "refused") are kept for 60 s, so waitForOrder finds one that came before it was asked.
5
+ *
6
+ * LATE DATA IS MARKED (0.4.2). The server sends a heartbeat (with its ts) after 5 s with nothing else, so silence means
7
+ * data is not reaching you. After staleAfterMs (10 s) of nothing, every handler gets {type: "stale", reason: "silent"}
8
+ * and the stream opens a new connection (the old one's network path is usually what stalled); the new one's snapshots
9
+ * follow {type: "resync", reason: "reconnected"}. Anything that arrives late anyway (after a gap, or more than
10
+ * lateAfterMs behind its ts against the heartbeats' clock, or on the replaced connection) is delivered with stale: true
11
+ * and lateMs, and its data says stale: true, staleSince and staleReason "late".
12
+ */
13
+ import { hmacHex } from './sign.js';
14
+ export class WagmiStream {
15
+ o;
16
+ ws = null;
17
+ channels = new Set();
18
+ handlers = new Set();
19
+ events = [];
20
+ waiters = new Set();
21
+ backoff = 1_000;
22
+ closed = false;
23
+ id = 0;
24
+ ready = null;
25
+ /** When the current connection last delivered anything; whether it was called stale; how late recent messages were. */
26
+ lastAt = 0;
27
+ staleSent = false;
28
+ lateMode = false;
29
+ lags = [];
30
+ everOpen = false;
31
+ watchdog = null;
32
+ constructor(o = {}) {
33
+ this.o = o;
34
+ }
35
+ /** Opens the socket (and authenticates with a key). Called by subscribe; you need not call it yourself. */
36
+ connect() {
37
+ if (this.ready)
38
+ return this.ready;
39
+ this.ready = new Promise((resolve, reject) => {
40
+ const Ctor = this.o.WebSocket ?? globalThis.WebSocket;
41
+ if (!Ctor) {
42
+ reject(new Error('no WebSocket: Node 22 or later, a browser, or pass options.WebSocket (the ws package)'));
43
+ return;
44
+ }
45
+ const base = this.o.url ?? 'wss://api.wagmi.pro/v1/ws';
46
+ const url = this.o.apiKey ? `${base}?key=${this.o.apiKey}` : base;
47
+ const ws = new Ctor(url);
48
+ this.ws = ws;
49
+ let opened = false;
50
+ const isOpen = () => {
51
+ opened = true;
52
+ this.backoff = 1_000;
53
+ this.lastAt = Date.now();
54
+ this.staleSent = false;
55
+ this.lateMode = false;
56
+ this.lags = [];
57
+ if (this.everOpen && this.channels.size)
58
+ this.emit({ type: 'resync', reason: 'reconnected', ts: Date.now(), message: 'a new connection: replace each channel\'s state with the snapshot that follows' });
59
+ this.everOpen = true;
60
+ this.startWatchdog();
61
+ this.resubscribe();
62
+ resolve();
63
+ };
64
+ ws.onopen = () => {
65
+ if (!this.o.apiKey)
66
+ isOpen();
67
+ else {
68
+ const ts = (this.o.now ?? Date.now)();
69
+ void hmacHex(this.o.apiSecret ?? '', `${ts}GET/v1/ws?key=${this.o.apiKey}`).then((sig) => ws.send(JSON.stringify({ op: 'auth', key: this.o.apiKey, ts, sig })));
70
+ }
71
+ };
72
+ ws.onmessage = (e) => {
73
+ let m;
74
+ try {
75
+ m = JSON.parse(String(e.data));
76
+ }
77
+ catch {
78
+ return;
79
+ }
80
+ const replaced = ws !== this.ws;
81
+ this.markLate(m, replaced);
82
+ if (replaced && m.type !== 'event')
83
+ return; // the replaced connection: only its order events still count
84
+ if (m.type === 'authenticated')
85
+ isOpen();
86
+ if (m.type === 'error' && !opened) {
87
+ reject(Object.assign(new Error(String(m.message ?? m.code)), { code: m.code }));
88
+ return;
89
+ }
90
+ if (m.type === 'event' && m.channel === 'orders') {
91
+ const at = Date.now();
92
+ this.events.push({ at, m });
93
+ while (this.events.length && at - this.events[0].at > 60_000)
94
+ this.events.shift();
95
+ for (const w of [...this.waiters])
96
+ if (w.match(m)) {
97
+ this.waiters.delete(w);
98
+ w.done(m);
99
+ }
100
+ }
101
+ this.emit(m);
102
+ };
103
+ ws.onclose = () => {
104
+ if (ws !== this.ws)
105
+ return; // a connection already replaced (stale) closes quietly
106
+ this.ws = null;
107
+ this.ready = null;
108
+ if (!opened)
109
+ reject(new Error('the websocket closed before it was ready'));
110
+ if (this.closed)
111
+ return;
112
+ const t = setTimeout(() => { void this.connect().catch(() => undefined); }, this.backoff);
113
+ t.unref?.();
114
+ this.backoff = Math.min(30_000, this.backoff * 2);
115
+ };
116
+ ws.onerror = () => { };
117
+ });
118
+ return this.ready;
119
+ }
120
+ emit(m) { for (const h of this.handlers)
121
+ h(m); }
122
+ /**
123
+ * Marks a late message (see the header): a gap of more than lateAfterMs + 2 s before it starts a late run that ends
124
+ * with the first message on time or the server's own resync; a message behind its ts by more than lateAfterMs (against
125
+ * the smallest delay seen in the last 2 minutes, which is the clocks' offset) is late on its own.
126
+ */
127
+ markLate(m, replaced) {
128
+ const now = Date.now();
129
+ const late = this.o.lateAfterMs ?? 5_000;
130
+ const gap = this.lastAt ? now - this.lastAt : 0;
131
+ if (!replaced) {
132
+ this.lastAt = now;
133
+ this.staleSent = false;
134
+ }
135
+ let lagMs = null;
136
+ if (typeof m.ts === 'number' && !/snapshot$/.test(m.type)) {
137
+ const raw = now - m.ts;
138
+ this.lags.push({ at: now, lag: raw });
139
+ while (this.lags.length && now - this.lags[0].at > 120_000)
140
+ this.lags.shift();
141
+ lagMs = raw - Math.min(...this.lags.map((x) => x.lag));
142
+ }
143
+ if (!replaced && gap > late + 2_000)
144
+ this.lateMode = true;
145
+ if (m.type === 'resync' || (lagMs !== null && lagMs < 1_000))
146
+ this.lateMode = false;
147
+ const isLate = replaced || this.lateMode || (lagMs !== null && lagMs > late);
148
+ if (!isLate || m.type === 'heartbeat' || m.type === 'resync' || m.type === 'stale')
149
+ return;
150
+ const since = new Date(typeof m.ts === 'number' ? m.ts : now - gap).toISOString();
151
+ m.stale = true;
152
+ m.lateMs = Math.max(lagMs ?? 0, gap);
153
+ if (m.data && typeof m.data === 'object' && !Array.isArray(m.data)) {
154
+ const d = m.data;
155
+ if (d.stale !== true) {
156
+ d.stale = true;
157
+ d.staleSince = since;
158
+ d.staleReason = 'late';
159
+ }
160
+ }
161
+ }
162
+ /** No message for staleAfterMs: {type: "stale"} to every handler, then a new connection (the old one is let go). */
163
+ startWatchdog() {
164
+ const after = this.o.staleAfterMs ?? 10_000;
165
+ if (this.watchdog || !after)
166
+ return;
167
+ this.watchdog = setInterval(() => {
168
+ if (this.closed || !this.ws || this.staleSent || !this.lastAt)
169
+ return;
170
+ const silent = Date.now() - this.lastAt;
171
+ if (silent < after)
172
+ return;
173
+ this.staleSent = true;
174
+ this.emit({ type: 'stale', reason: 'silent', silentMs: silent, ts: Date.now(), message: `nothing for ${Math.round(silent / 1000)} s (the server sends a heartbeat every 5 s): reconnecting; what you hold is not known current` });
175
+ const old = this.ws;
176
+ this.ws = null;
177
+ this.ready = null;
178
+ void this.connect().catch(() => undefined);
179
+ setTimeout(() => { try {
180
+ old.close(4000);
181
+ }
182
+ catch { /* gone */ } }, 5_000);
183
+ }, Math.min(1_000, Math.max(50, after / 4)));
184
+ this.watchdog.unref?.();
185
+ }
186
+ /** Whether the stream is silent past staleAfterMs or delivering late data. */
187
+ isStale() { return this.staleSent || this.lateMode; }
188
+ resubscribe() { if (this.channels.size)
189
+ this.ws?.send(JSON.stringify({ op: 'subscribe', channels: [...this.channels], id: ++this.id })); }
190
+ /** Every message, as it arrives. Returns a function that removes the handler. */
191
+ onMessage(h) { this.handlers.add(h); return () => this.handlers.delete(h); }
192
+ async subscribe(channels) {
193
+ for (const c of channels)
194
+ this.channels.add(c);
195
+ await this.connect();
196
+ this.ws?.send(JSON.stringify({ op: 'subscribe', channels, id: ++this.id }));
197
+ }
198
+ async unsubscribe(channels) {
199
+ for (const c of channels)
200
+ this.channels.delete(c);
201
+ this.ws?.send(JSON.stringify({ op: 'unsubscribe', channels, id: ++this.id }));
202
+ }
203
+ /**
204
+ * The orders channel's "confirmed" or "refused" event for one order (by clientOrderId, or by orderId for a cancel or a
205
+ * modify), or null after timeoutMs; an order a cancel all ended answers with its "cancelled" event (0.4.1). Subscribe to
206
+ * "orders" before you send the order.
207
+ */
208
+ waitForOrder(ref, timeoutMs = 30_000) {
209
+ const match = (m) => {
210
+ const d = m.data ?? {};
211
+ if (d.event !== 'confirmed' && d.event !== 'refused' && d.event !== 'cancelled')
212
+ return false;
213
+ // a cancel all's own "confirmed" names no order: never one order's answer
214
+ if (d.event === 'confirmed' && d.request === 'cancel_all')
215
+ return false;
216
+ if (ref.orderId !== undefined && String(d.orderId) === String(ref.orderId))
217
+ return true;
218
+ return ref.clientOrderId !== undefined && String(d.clientOrderId) === String(ref.clientOrderId);
219
+ };
220
+ const seen = this.events.find((x) => match(x.m));
221
+ if (seen)
222
+ return Promise.resolve(seen.m);
223
+ return new Promise((resolve) => {
224
+ const w = { match, done: (m) => { clearTimeout(t); resolve(m); } };
225
+ const t = setTimeout(() => { this.waiters.delete(w); resolve(null); }, timeoutMs);
226
+ this.waiters.add(w);
227
+ });
228
+ }
229
+ close() { this.closed = true; if (this.watchdog) {
230
+ clearInterval(this.watchdog);
231
+ this.watchdog = null;
232
+ } for (const w of [...this.waiters])
233
+ w.done(null); this.waiters.clear(); this.ws?.close(1000); this.ws = null; }
234
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@wagmipro/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.0",
4
+ "description": "The official WAGMI.PRO API client: market data, your account, every trading action built and signed, sent and confirmed, and the websocket.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "test/vectors.test.mjs",
18
+ "README.md",
19
+ "LICENSE",
20
+ "testvectors.json"
21
+ ],
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "sideEffects": false,
26
+ "homepage": "https://docs.wagmi.pro/api/client-libraries",
27
+ "keywords": [
28
+ "wagmipro",
29
+ "api",
30
+ "trading",
31
+ "sdk"
32
+ ],
33
+ "scripts": {
34
+ "build": "tsc -p tsconfig.json",
35
+ "test": "node test/vectors.test.mjs"
36
+ }
37
+ }
@@ -0,0 +1,31 @@
1
+ // The signing format's test vectors (testvectors.json, made from the API server's own code): every action text,
2
+ // request message, signature, body and key signature exactly; every refusal with its code. node test/vectors.test.mjs
3
+ import { readFileSync } from 'node:fs';
4
+ import { buildAction, requestMessage, signRequest, sha256Hex, keyHeaders, hmacHex, WagmiError } from '../dist/index.js';
5
+
6
+ const v = JSON.parse(readFileSync(new URL('../testvectors.json', import.meta.url), 'utf8'));
7
+ let pass = 0, fail = 0;
8
+ const ok = (name, cond, extra = '') => { if (cond) pass++; else { fail++; console.log(`FAIL ${name} ${extra}`); } };
9
+ const ctxOf = (t) => ({ ...(t.symbol ? { market: v.markets.find((m) => m.symbol === t.symbol) } : { asset: v.assets.find((a) => a.symbol === t.asset) }), signedAt: v.vectors[0].auth.ts, now: v.vectors[0].auth.ts });
10
+ for (const t of v.vectors) {
11
+ const action = buildAction(t.request, ctxOf(t));
12
+ ok(`${t.name}: action`, action === t.action, `\n got ${action}\n want ${t.action}`);
13
+ ok(`${t.name}: sha256`, (await sha256Hex(action)) === t.actionSha256);
14
+ const message = await requestMessage(v.grantId, t.auth.ts, t.auth.nonce, action);
15
+ ok(`${t.name}: message`, message === t.message);
16
+ const sig = await signRequest(v.signingKey, message);
17
+ ok(`${t.name}: signature`, sig === t.sig);
18
+ const body = JSON.stringify({ ...(t.symbol ? { symbol: t.symbol } : { asset: t.asset }), request: t.request, action, auth: { ts: t.auth.ts, nonce: t.auth.nonce, sig } });
19
+ ok(`${t.name}: body`, body === t.body);
20
+ const h = await keyHeaders(v.apiKey, v.apiSecret, 'POST', t.route, body, Number(t.headers['X-FX-TIMESTAMP']));
21
+ ok(`${t.name}: X-FX-SIGNATURE`, h['X-FX-SIGNATURE'] === t.headers['X-FX-SIGNATURE']);
22
+ }
23
+ for (const r of v.refusals) {
24
+ let code = null;
25
+ try { buildAction(r.request, ctxOf(r)); } catch (e) { code = e instanceof WagmiError ? e.code : String(e); }
26
+ ok(`refusal ${r.name}`, code === r.error, `got ${code}`);
27
+ }
28
+ const w = v.websocketAuth;
29
+ ok('websocket auth', (await hmacHex(v.apiSecret, `${w.ts}GET/v1/ws?key=${w.keyId}`)) === w.sig);
30
+ console.log(`${pass} passed, ${fail} failed (${v.vectors.length} vectors, ${v.refusals.length} refusals)`);
31
+ process.exit(fail ? 1 : 0);