@vordium/sdk 0.0.0-stage → 0.1.2
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.
- package/LICENSE +21 -0
- package/README.md +109 -2
- package/dist/cjs/account.js +126 -0
- package/dist/cjs/agents.js +237 -0
- package/dist/cjs/client.js +526 -0
- package/dist/cjs/domains.js +37 -0
- package/dist/cjs/errors.js +39 -0
- package/dist/cjs/feeds.js +278 -0
- package/dist/cjs/http.js +97 -0
- package/dist/cjs/index.js +37 -0
- package/dist/cjs/network.js +114 -0
- package/dist/cjs/nonce.js +36 -0
- package/dist/cjs/orders.js +260 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/reads.js +121 -0
- package/dist/cjs/rounding.js +252 -0
- package/dist/cjs/sign.js +49 -0
- package/dist/cjs/types.js +57 -0
- package/dist/cjs/units.js +78 -0
- package/dist/esm/account.d.ts +61 -0
- package/dist/esm/account.js +114 -0
- package/dist/esm/agents.d.ts +71 -0
- package/dist/esm/agents.js +225 -0
- package/dist/esm/client.d.ts +239 -0
- package/dist/esm/client.js +520 -0
- package/dist/esm/domains.d.ts +21 -0
- package/dist/esm/domains.js +30 -0
- package/dist/esm/errors.d.ts +18 -0
- package/dist/esm/errors.js +32 -0
- package/dist/esm/feeds.d.ts +97 -0
- package/dist/esm/feeds.js +267 -0
- package/dist/esm/http.d.ts +24 -0
- package/dist/esm/http.js +93 -0
- package/dist/esm/index.d.ts +15 -0
- package/dist/esm/index.js +15 -0
- package/dist/esm/network.d.ts +44 -0
- package/dist/esm/network.js +107 -0
- package/dist/esm/nonce.d.ts +15 -0
- package/dist/esm/nonce.js +31 -0
- package/dist/esm/orders.d.ts +141 -0
- package/dist/esm/orders.js +238 -0
- package/dist/esm/reads.d.ts +59 -0
- package/dist/esm/reads.js +113 -0
- package/dist/esm/rounding.d.ts +70 -0
- package/dist/esm/rounding.js +229 -0
- package/dist/esm/sign.d.ts +27 -0
- package/dist/esm/sign.js +43 -0
- package/dist/esm/types.d.ts +41 -0
- package/dist/esm/types.js +51 -0
- package/dist/esm/units.d.ts +16 -0
- package/dist/esm/units.js +70 -0
- package/package.json +53 -4
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live feeds over one WebSocket: order book, trades, your orders and your fills.
|
|
3
|
+
*
|
|
4
|
+
* Subscribe with `{method:"subscribe", channel:"book"|"trades", pair}` or `{method:"subscribe", channel:"orders"|"fills",
|
|
5
|
+
* account}`. Every subscription starts with a snapshot, then updates. `seq` only rises on a subscription; each message's
|
|
6
|
+
* `prev_seq` names the message before it (null on the snapshot). A `prev_seq` that is not the last `seq` seen means a
|
|
7
|
+
* message was missed: the only correct move is to subscribe again and start from the new snapshot — {@link Feeds} does
|
|
8
|
+
* that by itself. Book updates list only the levels that changed; a size of "0" removes the level.
|
|
9
|
+
*/
|
|
10
|
+
export declare const CHANNELS: readonly ["book", "trades", "orders", "fills"];
|
|
11
|
+
export type Channel = typeof CHANNELS[number];
|
|
12
|
+
export type FeedMessage = Record<string, unknown>;
|
|
13
|
+
export type SubKey = string;
|
|
14
|
+
export declare function subKey(channel: Channel, target: number | string): SubKey;
|
|
15
|
+
export declare function subscribeMessage(channel: Channel, target: number | string, method?: 'subscribe' | 'unsubscribe'): FeedMessage;
|
|
16
|
+
/** The subscription a message belongs to, or null (pong, acknowledgements, errors). */
|
|
17
|
+
export declare function keyOf(msg: FeedMessage): SubKey | null;
|
|
18
|
+
export type Verdict = 'snapshot' | 'update' | 'gap' | 'stale' | 'ignore';
|
|
19
|
+
/** Per subscription: accept a snapshot, then only an update whose `prev_seq` is the last `seq`. */
|
|
20
|
+
export declare class SeqTracker {
|
|
21
|
+
private last;
|
|
22
|
+
reset(k: SubKey): void;
|
|
23
|
+
observe(msg: FeedMessage): Verdict;
|
|
24
|
+
}
|
|
25
|
+
/** One pair's book from a snapshot and its updates. Prices (8 decimals) and sizes (18 decimals) exact as bigint. */
|
|
26
|
+
export declare class Book {
|
|
27
|
+
readonly pair: number;
|
|
28
|
+
bids: Map<bigint, bigint>;
|
|
29
|
+
asks: Map<bigint, bigint>;
|
|
30
|
+
seq: number | null;
|
|
31
|
+
height: number | null;
|
|
32
|
+
constructor(pair: number);
|
|
33
|
+
apply(msg: FeedMessage): void;
|
|
34
|
+
bestBid(): [bigint, bigint] | null;
|
|
35
|
+
bestAsk(): [bigint, bigint] | null;
|
|
36
|
+
}
|
|
37
|
+
/** A wait before a reconnect: a random point between half the backoff and the backoff. */
|
|
38
|
+
export declare function reconnectDelay(backoffMs: number, rand?: () => number): number;
|
|
39
|
+
/** The part of a WebSocket the feeds use (the browser's and Node's `ws` both fit). */
|
|
40
|
+
export interface SocketLike {
|
|
41
|
+
send(data: string): void;
|
|
42
|
+
close(): void;
|
|
43
|
+
onopen: ((ev: unknown) => void) | null;
|
|
44
|
+
onmessage: ((ev: {
|
|
45
|
+
data: unknown;
|
|
46
|
+
}) => void) | null;
|
|
47
|
+
onclose: ((ev: unknown) => void) | null;
|
|
48
|
+
onerror: ((ev: unknown) => void) | null;
|
|
49
|
+
}
|
|
50
|
+
export type SocketFactory = (url: string) => SocketLike | Promise<SocketLike>;
|
|
51
|
+
/** The WebSocket of the runtime: the global one (browsers, Node 22+), else the `ws` package. */
|
|
52
|
+
export declare function defaultSocket(url: string): Promise<SocketLike>;
|
|
53
|
+
export type FeedEvent = {
|
|
54
|
+
kind: 'snapshot' | 'update';
|
|
55
|
+
message: FeedMessage;
|
|
56
|
+
} | {
|
|
57
|
+
kind: 'resubscribed';
|
|
58
|
+
key: SubKey;
|
|
59
|
+
} | {
|
|
60
|
+
kind: 'reconnected';
|
|
61
|
+
error: string;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* One connection, any number of subscriptions, resubscribed by itself after a gap or a reconnect. Listen with
|
|
65
|
+
* `onEvent`; book state per pair is kept in `books` for book subscriptions. A connection that delivers nothing for
|
|
66
|
+
* `idleMs` is pinged once and replaced if the ping is not answered.
|
|
67
|
+
*/
|
|
68
|
+
export declare class Feeds {
|
|
69
|
+
readonly url: string;
|
|
70
|
+
private readonly opts;
|
|
71
|
+
readonly books: Map<number, Book>;
|
|
72
|
+
private subs;
|
|
73
|
+
private seq;
|
|
74
|
+
private sock;
|
|
75
|
+
/** True once the socket is open: a message sent while it is still connecting is refused by the runtime. */
|
|
76
|
+
private ready;
|
|
77
|
+
private closed;
|
|
78
|
+
private backoffMs;
|
|
79
|
+
private idleTimer;
|
|
80
|
+
private pinged;
|
|
81
|
+
onEvent: (e: FeedEvent) => void;
|
|
82
|
+
constructor(url: string, opts?: {
|
|
83
|
+
socket?: SocketFactory;
|
|
84
|
+
maxBackoffMs?: number;
|
|
85
|
+
idleMs?: number;
|
|
86
|
+
});
|
|
87
|
+
open(): Promise<void>;
|
|
88
|
+
private armIdle;
|
|
89
|
+
/** Send now when the socket is open; otherwise the subscription list is sent when it opens. */
|
|
90
|
+
private send;
|
|
91
|
+
private lost;
|
|
92
|
+
subscribe(channel: Channel, target: number | string): void;
|
|
93
|
+
unsubscribe(channel: Channel, target: number | string): void;
|
|
94
|
+
/** Apply one message; returns its kind (null for messages that are not feed data). */
|
|
95
|
+
handle(msg: FeedMessage): Verdict | 'resubscribed' | null;
|
|
96
|
+
close(): void;
|
|
97
|
+
}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { InvalidRequest } from './errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* Live feeds over one WebSocket: order book, trades, your orders and your fills.
|
|
4
|
+
*
|
|
5
|
+
* Subscribe with `{method:"subscribe", channel:"book"|"trades", pair}` or `{method:"subscribe", channel:"orders"|"fills",
|
|
6
|
+
* account}`. Every subscription starts with a snapshot, then updates. `seq` only rises on a subscription; each message's
|
|
7
|
+
* `prev_seq` names the message before it (null on the snapshot). A `prev_seq` that is not the last `seq` seen means a
|
|
8
|
+
* message was missed: the only correct move is to subscribe again and start from the new snapshot — {@link Feeds} does
|
|
9
|
+
* that by itself. Book updates list only the levels that changed; a size of "0" removes the level.
|
|
10
|
+
*/
|
|
11
|
+
export const CHANNELS = ['book', 'trades', 'orders', 'fills'];
|
|
12
|
+
const MARKET = new Set(['book', 'trades']);
|
|
13
|
+
export function subKey(channel, target) {
|
|
14
|
+
if (!CHANNELS.includes(channel))
|
|
15
|
+
throw new InvalidRequest(`channel is one of ${CHANNELS.join(', ')}, not ${String(channel)}.`);
|
|
16
|
+
if (MARKET.has(channel)) {
|
|
17
|
+
if (typeof target !== 'number' || !Number.isSafeInteger(target))
|
|
18
|
+
throw new InvalidRequest(`${channel} needs a pair id.`);
|
|
19
|
+
return `${channel}:${target}`;
|
|
20
|
+
}
|
|
21
|
+
if (typeof target !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(target))
|
|
22
|
+
throw new InvalidRequest(`${channel} needs an account address.`);
|
|
23
|
+
return `${channel}:${target.toLowerCase()}`;
|
|
24
|
+
}
|
|
25
|
+
export function subscribeMessage(channel, target, method = 'subscribe') {
|
|
26
|
+
subKey(channel, target);
|
|
27
|
+
return MARKET.has(channel) ? { method, channel, pair: target } : { method, channel, account: target };
|
|
28
|
+
}
|
|
29
|
+
/** The subscription a message belongs to, or null (pong, acknowledgements, errors). */
|
|
30
|
+
export function keyOf(msg) {
|
|
31
|
+
const ch = msg.channel;
|
|
32
|
+
if ((ch === 'book' || ch === 'trades') && typeof msg.pair === 'number')
|
|
33
|
+
return `${ch}:${msg.pair}`;
|
|
34
|
+
if ((ch === 'orders' || ch === 'fills') && typeof msg.account === 'string')
|
|
35
|
+
return `${ch}:${msg.account.toLowerCase()}`;
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
/** Per subscription: accept a snapshot, then only an update whose `prev_seq` is the last `seq`. */
|
|
39
|
+
export class SeqTracker {
|
|
40
|
+
last = new Map();
|
|
41
|
+
reset(k) { this.last.delete(k); }
|
|
42
|
+
observe(msg) {
|
|
43
|
+
const k = keyOf(msg);
|
|
44
|
+
const seq = msg.seq;
|
|
45
|
+
if (k === null || typeof seq !== 'number' || !Number.isSafeInteger(seq))
|
|
46
|
+
return 'ignore';
|
|
47
|
+
if (msg.type === 'snapshot') {
|
|
48
|
+
this.last.set(k, seq);
|
|
49
|
+
return 'snapshot';
|
|
50
|
+
}
|
|
51
|
+
const last = this.last.get(k);
|
|
52
|
+
if (last === undefined)
|
|
53
|
+
return 'stale';
|
|
54
|
+
if (seq <= last)
|
|
55
|
+
return 'stale';
|
|
56
|
+
if (msg.prev_seq !== last) {
|
|
57
|
+
this.last.delete(k);
|
|
58
|
+
return 'gap';
|
|
59
|
+
}
|
|
60
|
+
this.last.set(k, seq);
|
|
61
|
+
return 'update';
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** One pair's book from a snapshot and its updates. Prices (8 decimals) and sizes (18 decimals) exact as bigint. */
|
|
65
|
+
export class Book {
|
|
66
|
+
pair;
|
|
67
|
+
bids = new Map();
|
|
68
|
+
asks = new Map();
|
|
69
|
+
seq = null;
|
|
70
|
+
height = null;
|
|
71
|
+
constructor(pair) {
|
|
72
|
+
this.pair = pair;
|
|
73
|
+
}
|
|
74
|
+
apply(msg) {
|
|
75
|
+
if (msg.type === 'snapshot') {
|
|
76
|
+
this.bids = new Map();
|
|
77
|
+
this.asks = new Map();
|
|
78
|
+
}
|
|
79
|
+
for (const [side, book] of [['bids', this.bids], ['asks', this.asks]]) {
|
|
80
|
+
const levels = Array.isArray(msg[side]) ? msg[side] : [];
|
|
81
|
+
for (const lvl of levels) {
|
|
82
|
+
const price = BigInt(String(lvl[0])), size = BigInt(String(lvl[1]));
|
|
83
|
+
if (size === 0n)
|
|
84
|
+
book.delete(price);
|
|
85
|
+
else
|
|
86
|
+
book.set(price, size);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (typeof msg.seq === 'number')
|
|
90
|
+
this.seq = msg.seq;
|
|
91
|
+
if (typeof msg.height === 'number')
|
|
92
|
+
this.height = msg.height;
|
|
93
|
+
}
|
|
94
|
+
bestBid() { return best(this.bids, (a, b) => a > b); }
|
|
95
|
+
bestAsk() { return best(this.asks, (a, b) => a < b); }
|
|
96
|
+
}
|
|
97
|
+
function best(m, better) {
|
|
98
|
+
let out = null;
|
|
99
|
+
for (const [p, s] of m)
|
|
100
|
+
if (!out || better(p, out[0]))
|
|
101
|
+
out = [p, s];
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
/** A wait before a reconnect: a random point between half the backoff and the backoff. */
|
|
105
|
+
export function reconnectDelay(backoffMs, rand = Math.random) {
|
|
106
|
+
return backoffMs * (0.5 + 0.5 * rand());
|
|
107
|
+
}
|
|
108
|
+
/** The WebSocket of the runtime: the global one (browsers, Node 22+), else the `ws` package. */
|
|
109
|
+
export async function defaultSocket(url) {
|
|
110
|
+
const G = globalThis.WebSocket;
|
|
111
|
+
if (G)
|
|
112
|
+
return new G(url);
|
|
113
|
+
const mod = (await import('ws'));
|
|
114
|
+
const C = mod.WebSocket ?? mod.default;
|
|
115
|
+
if (!C)
|
|
116
|
+
throw new InvalidRequest('No WebSocket is available in this runtime.');
|
|
117
|
+
return new C(url);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* One connection, any number of subscriptions, resubscribed by itself after a gap or a reconnect. Listen with
|
|
121
|
+
* `onEvent`; book state per pair is kept in `books` for book subscriptions. A connection that delivers nothing for
|
|
122
|
+
* `idleMs` is pinged once and replaced if the ping is not answered.
|
|
123
|
+
*/
|
|
124
|
+
export class Feeds {
|
|
125
|
+
url;
|
|
126
|
+
opts;
|
|
127
|
+
books = new Map();
|
|
128
|
+
subs = new Map();
|
|
129
|
+
seq = new SeqTracker();
|
|
130
|
+
sock = null;
|
|
131
|
+
/** True once the socket is open: a message sent while it is still connecting is refused by the runtime. */
|
|
132
|
+
ready = false;
|
|
133
|
+
closed = false;
|
|
134
|
+
backoffMs = 1000;
|
|
135
|
+
idleTimer = null;
|
|
136
|
+
pinged = false;
|
|
137
|
+
onEvent = () => { };
|
|
138
|
+
constructor(url, opts = {}) {
|
|
139
|
+
this.url = url;
|
|
140
|
+
this.opts = opts;
|
|
141
|
+
}
|
|
142
|
+
async open() {
|
|
143
|
+
this.closed = false;
|
|
144
|
+
const s = await (this.opts.socket ?? defaultSocket)(this.url);
|
|
145
|
+
this.sock = s;
|
|
146
|
+
this.ready = false;
|
|
147
|
+
s.onopen = () => {
|
|
148
|
+
this.ready = true;
|
|
149
|
+
for (const [k, m] of this.subs) {
|
|
150
|
+
this.seq.reset(k);
|
|
151
|
+
s.send(JSON.stringify(m));
|
|
152
|
+
}
|
|
153
|
+
this.armIdle();
|
|
154
|
+
};
|
|
155
|
+
s.onmessage = (ev) => {
|
|
156
|
+
this.armIdle();
|
|
157
|
+
this.pinged = false;
|
|
158
|
+
let msg;
|
|
159
|
+
try {
|
|
160
|
+
msg = JSON.parse(typeof ev.data === 'string' ? ev.data : String(ev.data));
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (!msg || typeof msg !== 'object' || Array.isArray(msg))
|
|
166
|
+
return;
|
|
167
|
+
this.backoffMs = 1000; // reset only once a connection has delivered a message
|
|
168
|
+
try {
|
|
169
|
+
this.handle(msg);
|
|
170
|
+
}
|
|
171
|
+
catch { /* a malformed message is skipped */ }
|
|
172
|
+
};
|
|
173
|
+
s.onclose = () => this.lost('the connection closed');
|
|
174
|
+
s.onerror = () => { };
|
|
175
|
+
}
|
|
176
|
+
armIdle() {
|
|
177
|
+
if (this.idleTimer)
|
|
178
|
+
clearTimeout(this.idleTimer);
|
|
179
|
+
const idle = this.opts.idleMs ?? 30000;
|
|
180
|
+
this.idleTimer = setTimeout(() => {
|
|
181
|
+
if (this.closed || !this.sock)
|
|
182
|
+
return;
|
|
183
|
+
if (this.pinged) {
|
|
184
|
+
this.sock.close();
|
|
185
|
+
return;
|
|
186
|
+
} // no message and no answer to a ping
|
|
187
|
+
this.pinged = true;
|
|
188
|
+
try {
|
|
189
|
+
this.sock.send(JSON.stringify({ method: 'ping' }));
|
|
190
|
+
}
|
|
191
|
+
catch { /* onclose follows */ }
|
|
192
|
+
this.armIdle();
|
|
193
|
+
}, idle);
|
|
194
|
+
}
|
|
195
|
+
/** Send now when the socket is open; otherwise the subscription list is sent when it opens. */
|
|
196
|
+
send(m) {
|
|
197
|
+
if (this.sock && this.ready)
|
|
198
|
+
this.sock.send(JSON.stringify(m));
|
|
199
|
+
}
|
|
200
|
+
lost(error) {
|
|
201
|
+
if (this.idleTimer) {
|
|
202
|
+
clearTimeout(this.idleTimer);
|
|
203
|
+
this.idleTimer = null;
|
|
204
|
+
}
|
|
205
|
+
this.sock = null;
|
|
206
|
+
this.ready = false;
|
|
207
|
+
if (this.closed)
|
|
208
|
+
return;
|
|
209
|
+
const wait = reconnectDelay(this.backoffMs);
|
|
210
|
+
this.backoffMs = Math.min(this.backoffMs * 2, this.opts.maxBackoffMs ?? 30000);
|
|
211
|
+
this.onEvent({ kind: 'reconnected', error });
|
|
212
|
+
setTimeout(() => { if (!this.closed)
|
|
213
|
+
this.open().catch((e) => this.lost(String(e?.message ?? e))); }, wait);
|
|
214
|
+
}
|
|
215
|
+
subscribe(channel, target) {
|
|
216
|
+
const k = subKey(channel, target);
|
|
217
|
+
const m = subscribeMessage(channel, target);
|
|
218
|
+
this.subs.set(k, m);
|
|
219
|
+
if (channel === 'book')
|
|
220
|
+
this.books.set(target, this.books.get(target) ?? new Book(target));
|
|
221
|
+
this.seq.reset(k);
|
|
222
|
+
this.send(m);
|
|
223
|
+
}
|
|
224
|
+
unsubscribe(channel, target) {
|
|
225
|
+
const k = subKey(channel, target);
|
|
226
|
+
this.subs.delete(k);
|
|
227
|
+
this.seq.reset(k);
|
|
228
|
+
if (channel === 'book')
|
|
229
|
+
this.books.delete(target);
|
|
230
|
+
this.send(subscribeMessage(channel, target, 'unsubscribe'));
|
|
231
|
+
}
|
|
232
|
+
/** Apply one message; returns its kind (null for messages that are not feed data). */
|
|
233
|
+
handle(msg) {
|
|
234
|
+
const verdict = this.seq.observe(msg);
|
|
235
|
+
const k = keyOf(msg);
|
|
236
|
+
if (verdict === 'gap' && k && this.subs.has(k)) {
|
|
237
|
+
if (k.startsWith('book:')) {
|
|
238
|
+
const p = Number(k.slice(5));
|
|
239
|
+
this.books.set(p, new Book(p));
|
|
240
|
+
}
|
|
241
|
+
this.send(this.subs.get(k));
|
|
242
|
+
this.onEvent({ kind: 'resubscribed', key: k });
|
|
243
|
+
return 'resubscribed';
|
|
244
|
+
}
|
|
245
|
+
if (verdict === 'snapshot' || verdict === 'update') {
|
|
246
|
+
if (k && k.startsWith('book:')) {
|
|
247
|
+
const p = Number(k.slice(5));
|
|
248
|
+
const b = this.books.get(p) ?? new Book(p);
|
|
249
|
+
b.apply(msg);
|
|
250
|
+
this.books.set(p, b);
|
|
251
|
+
}
|
|
252
|
+
this.onEvent({ kind: verdict, message: msg });
|
|
253
|
+
return verdict;
|
|
254
|
+
}
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
close() {
|
|
258
|
+
this.closed = true;
|
|
259
|
+
if (this.idleTimer)
|
|
260
|
+
clearTimeout(this.idleTimer);
|
|
261
|
+
try {
|
|
262
|
+
this.sock?.close();
|
|
263
|
+
}
|
|
264
|
+
catch { /* closed */ }
|
|
265
|
+
this.sock = null;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** How the SDK talks to a node. Injectable, so tests and other runtimes can answer without a network. */
|
|
2
|
+
export interface Transport {
|
|
3
|
+
get(url: string, timeoutMs: number): Promise<{
|
|
4
|
+
status: number;
|
|
5
|
+
body: unknown;
|
|
6
|
+
}>;
|
|
7
|
+
/** One attempt. `body` is sent byte for byte. */
|
|
8
|
+
post(url: string, body: string, timeoutMs: number): Promise<{
|
|
9
|
+
status: number;
|
|
10
|
+
body: unknown;
|
|
11
|
+
retryAfter: string | null;
|
|
12
|
+
}>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The default transport: `fetch`. A read (GET) is tried up to three times on a connection error, a timeout, 429 or
|
|
16
|
+
* 502–504, with a random wait and the server's Retry-After. A write (POST) is never retried: a second attempt could
|
|
17
|
+
* apply the same signed request twice.
|
|
18
|
+
*/
|
|
19
|
+
export declare const fetchTransport: Transport;
|
|
20
|
+
/**
|
|
21
|
+
* JSON.parse that keeps whole numbers past 2^53 exact: they come back as their digit strings (a size or a price in base
|
|
22
|
+
* units can be larger than a JavaScript number holds). Every other value is parsed as usual.
|
|
23
|
+
*/
|
|
24
|
+
export declare function parseExactJson(text: string): unknown;
|
package/dist/esm/http.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { VordiumError } from './errors.js';
|
|
2
|
+
const RETRY_STATUS = new Set([429, 502, 503, 504]);
|
|
3
|
+
async function fetchWithTimeout(url, init, timeoutMs) {
|
|
4
|
+
const ctl = new AbortController();
|
|
5
|
+
const t = setTimeout(() => ctl.abort(), timeoutMs);
|
|
6
|
+
try {
|
|
7
|
+
return await fetch(url, { ...init, signal: ctl.signal });
|
|
8
|
+
}
|
|
9
|
+
finally {
|
|
10
|
+
clearTimeout(t);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
async function readBody(r) {
|
|
14
|
+
const text = await r.text();
|
|
15
|
+
if (!text)
|
|
16
|
+
return null;
|
|
17
|
+
try {
|
|
18
|
+
return parseExactJson(text);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return text.slice(0, 300);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
|
|
25
|
+
/**
|
|
26
|
+
* The default transport: `fetch`. A read (GET) is tried up to three times on a connection error, a timeout, 429 or
|
|
27
|
+
* 502–504, with a random wait and the server's Retry-After. A write (POST) is never retried: a second attempt could
|
|
28
|
+
* apply the same signed request twice.
|
|
29
|
+
*/
|
|
30
|
+
export const fetchTransport = {
|
|
31
|
+
async get(url, timeoutMs) {
|
|
32
|
+
let last = null;
|
|
33
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
34
|
+
try {
|
|
35
|
+
const r = await fetchWithTimeout(url, { headers: { accept: 'application/json' } }, timeoutMs);
|
|
36
|
+
if (RETRY_STATUS.has(r.status) && attempt < 2) {
|
|
37
|
+
const ra = Number(r.headers.get('retry-after'));
|
|
38
|
+
await sleep(Number.isFinite(ra) && ra > 0 ? Math.min(ra, 5) * 1000 : 250 * 2 ** attempt * (0.5 + Math.random() / 2));
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
return { status: r.status, body: await readBody(r) };
|
|
42
|
+
}
|
|
43
|
+
catch (e) {
|
|
44
|
+
last = e;
|
|
45
|
+
if (attempt < 2)
|
|
46
|
+
await sleep(250 * 2 ** attempt * (0.5 + Math.random() / 2));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
throw new VordiumError('unreachable', `The node at ${url} did not answer.`, String(last?.message ?? last));
|
|
50
|
+
},
|
|
51
|
+
async post(url, body, timeoutMs) {
|
|
52
|
+
const r = await fetchWithTimeout(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body }, timeoutMs);
|
|
53
|
+
return { status: r.status, body: await readBody(r), retryAfter: r.headers.get('retry-after') };
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* JSON.parse that keeps whole numbers past 2^53 exact: they come back as their digit strings (a size or a price in base
|
|
58
|
+
* units can be larger than a JavaScript number holds). Every other value is parsed as usual.
|
|
59
|
+
*/
|
|
60
|
+
export function parseExactJson(text) {
|
|
61
|
+
// Quote every bare integer literal of 16+ digits outside strings, then parse.
|
|
62
|
+
let out = '';
|
|
63
|
+
let inStr = false;
|
|
64
|
+
for (let i = 0; i < text.length; i++) {
|
|
65
|
+
const c = text[i];
|
|
66
|
+
if (inStr) {
|
|
67
|
+
out += c;
|
|
68
|
+
if (c === '\\') {
|
|
69
|
+
out += text[++i] ?? '';
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (c === '"')
|
|
73
|
+
inStr = false;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (c === '"') {
|
|
77
|
+
inStr = true;
|
|
78
|
+
out += c;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if ((c === '-' || (c >= '0' && c <= '9')) && /[\s,:[]/.test(out.trimEnd().slice(-1) || '[')) {
|
|
82
|
+
let j = i + 1;
|
|
83
|
+
while (j < text.length && /[0-9.eE+-]/.test(text[j]))
|
|
84
|
+
j++;
|
|
85
|
+
const lit = text.slice(i, j);
|
|
86
|
+
out += /^-?\d{16,}$/.test(lit) && !Number.isSafeInteger(Number(lit)) ? `"${lit}"` : lit;
|
|
87
|
+
i = j - 1;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
out += c;
|
|
91
|
+
}
|
|
92
|
+
return JSON.parse(out);
|
|
93
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export * from './errors.js';
|
|
2
|
+
export { fetchTransport, parseExactJson, type Transport } from './http.js';
|
|
3
|
+
export * from './domains.js';
|
|
4
|
+
export * from './types.js';
|
|
5
|
+
export * from './sign.js';
|
|
6
|
+
export * from './network.js';
|
|
7
|
+
export * from './nonce.js';
|
|
8
|
+
export * from './units.js';
|
|
9
|
+
export * from './orders.js';
|
|
10
|
+
export * from './rounding.js';
|
|
11
|
+
export * from './account.js';
|
|
12
|
+
export * from './agents.js';
|
|
13
|
+
export * from './reads.js';
|
|
14
|
+
export * from './feeds.js';
|
|
15
|
+
export { Vordium, Account, twapOnSteps, type Result, type ConnectOptions } from './client.js';
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export * from './errors.js';
|
|
2
|
+
export { fetchTransport, parseExactJson } from './http.js';
|
|
3
|
+
export * from './domains.js';
|
|
4
|
+
export * from './types.js';
|
|
5
|
+
export * from './sign.js';
|
|
6
|
+
export * from './network.js';
|
|
7
|
+
export * from './nonce.js';
|
|
8
|
+
export * from './units.js';
|
|
9
|
+
export * from './orders.js';
|
|
10
|
+
export * from './rounding.js';
|
|
11
|
+
export * from './account.js';
|
|
12
|
+
export * from './agents.js';
|
|
13
|
+
export * from './reads.js';
|
|
14
|
+
export * from './feeds.js';
|
|
15
|
+
export { Vordium, Account, twapOnSteps } from './client.js';
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type Transport } from './http.js';
|
|
2
|
+
/**
|
|
3
|
+
* Where the SDK asks. A preset never supplies a chain id or a genesis: those are read from the network itself, and the
|
|
4
|
+
* three sources (the network spec, the node's `/status` and the JSON-RPC `eth_chainId`) must agree before anything is
|
|
5
|
+
* signed.
|
|
6
|
+
*/
|
|
7
|
+
export interface NetworkPreset {
|
|
8
|
+
name: string;
|
|
9
|
+
/** The network spec (JSON). */
|
|
10
|
+
spec: string;
|
|
11
|
+
/** JSON-RPC (POST). */
|
|
12
|
+
rpc: string;
|
|
13
|
+
/** The REST API: orders, accounts, sessions, agents. */
|
|
14
|
+
api: string;
|
|
15
|
+
/** The live feeds WebSocket, when the network publishes one. */
|
|
16
|
+
feeds?: string;
|
|
17
|
+
}
|
|
18
|
+
export declare const NETWORKS: Record<'mainnet' | 'testnet', NetworkPreset>;
|
|
19
|
+
/** A network the SDK has read and checked. */
|
|
20
|
+
export interface Network extends NetworkPreset {
|
|
21
|
+
chainId: number;
|
|
22
|
+
/** 64 lower-case hex, no 0x. */
|
|
23
|
+
genesis: string;
|
|
24
|
+
/** The network spec as read. */
|
|
25
|
+
specRead: Record<string, unknown>;
|
|
26
|
+
}
|
|
27
|
+
export interface NodeIdentity {
|
|
28
|
+
chainId: number;
|
|
29
|
+
genesis: string;
|
|
30
|
+
}
|
|
31
|
+
/** A node identity from a `/status` answer; refused unless it names both. */
|
|
32
|
+
export declare function readIdentity(status: unknown): NodeIdentity;
|
|
33
|
+
/** Where a node's `/status` is read: under the API's own path first, then at the host root. */
|
|
34
|
+
export declare function statusUrls(api: string): string[];
|
|
35
|
+
export declare function nodeIdentity(api: string, transport?: Transport, timeoutMs?: number): Promise<NodeIdentity>;
|
|
36
|
+
/**
|
|
37
|
+
* Read and check a network. Refuses (NetworkMismatch, nothing signed) unless the spec, the node's `/status` and
|
|
38
|
+
* `eth_chainId` name the same chain id, the spec and the node the same genesis, and the spec's `testnet` flag matches
|
|
39
|
+
* the preset (a test network never stands in for the main network, nor the reverse).
|
|
40
|
+
*/
|
|
41
|
+
export declare function connectNetwork(network?: 'mainnet' | 'testnet' | NetworkPreset, opts?: {
|
|
42
|
+
transport?: Transport;
|
|
43
|
+
timeoutMs?: number;
|
|
44
|
+
}): Promise<Network>;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { NetworkMismatch, VordiumError } from './errors.js';
|
|
2
|
+
import { fetchTransport } from './http.js';
|
|
3
|
+
import { genesisHex } from './domains.js';
|
|
4
|
+
export const NETWORKS = {
|
|
5
|
+
mainnet: {
|
|
6
|
+
name: 'mainnet',
|
|
7
|
+
spec: 'https://rpc.vordium.com/network-spec.json',
|
|
8
|
+
rpc: 'https://rpc.vordium.com',
|
|
9
|
+
api: 'https://rpc.vordium.com',
|
|
10
|
+
feeds: 'wss://rpc.vordium.com/feeds',
|
|
11
|
+
},
|
|
12
|
+
testnet: {
|
|
13
|
+
name: 'testnet',
|
|
14
|
+
spec: 'https://testnet.vordex.xyz/network-spec.json',
|
|
15
|
+
rpc: 'https://rpc-testnet.vordium.com',
|
|
16
|
+
api: 'https://testnet.vordex.xyz/chain',
|
|
17
|
+
feeds: 'wss://testnet.vordex.xyz/chain/feeds',
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
/** A node identity from a `/status` answer; refused unless it names both. */
|
|
21
|
+
export function readIdentity(status) {
|
|
22
|
+
if (!status || typeof status !== 'object')
|
|
23
|
+
throw new VordiumError('no_identity', "The node's /status is not an object; refusing to sign.");
|
|
24
|
+
const s = status;
|
|
25
|
+
let cid = s.chain_id;
|
|
26
|
+
if (typeof cid === 'string' && /^\d+$/.test(cid))
|
|
27
|
+
cid = Number(cid);
|
|
28
|
+
if (typeof cid !== 'number' || !Number.isSafeInteger(cid) || cid <= 0)
|
|
29
|
+
throw new VordiumError('no_identity', "The node's /status names no chain id; refusing to sign.");
|
|
30
|
+
let g;
|
|
31
|
+
try {
|
|
32
|
+
g = genesisHex(String(s.genesis_sha256 ?? ''));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
throw new VordiumError('no_identity', "The node's /status names no genesis; refusing to sign.");
|
|
36
|
+
}
|
|
37
|
+
return { chainId: cid, genesis: g };
|
|
38
|
+
}
|
|
39
|
+
/** Where a node's `/status` is read: under the API's own path first, then at the host root. */
|
|
40
|
+
export function statusUrls(api) {
|
|
41
|
+
const u = new URL(api);
|
|
42
|
+
const own = `${u.origin}${u.pathname.replace(/\/$/, '')}/status`;
|
|
43
|
+
const root = `${u.origin}/status`;
|
|
44
|
+
return own === root ? [own] : [own, root];
|
|
45
|
+
}
|
|
46
|
+
export async function nodeIdentity(api, transport = fetchTransport, timeoutMs = 8000) {
|
|
47
|
+
let last = null;
|
|
48
|
+
for (const url of statusUrls(api)) {
|
|
49
|
+
try {
|
|
50
|
+
const r = await transport.get(url, timeoutMs);
|
|
51
|
+
if (r.status === 200)
|
|
52
|
+
return readIdentity(r.body);
|
|
53
|
+
last = new Error(`HTTP ${r.status}`);
|
|
54
|
+
}
|
|
55
|
+
catch (e) {
|
|
56
|
+
last = e;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
throw new VordiumError('no_identity', `The node at ${api} did not give its chain id and genesis; refusing to sign.`, String(last?.message ?? last));
|
|
60
|
+
}
|
|
61
|
+
async function rpcChainId(rpc, transport, timeoutMs) {
|
|
62
|
+
const r = await transport.post(rpc, JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_chainId', params: [] }), timeoutMs);
|
|
63
|
+
const res = r.body?.result;
|
|
64
|
+
if (r.status !== 200 || typeof res !== 'string' || !/^0x[0-9a-f]+$/i.test(res)) {
|
|
65
|
+
throw new VordiumError('no_identity', `The JSON-RPC endpoint ${rpc} did not answer eth_chainId.`);
|
|
66
|
+
}
|
|
67
|
+
return Number(BigInt(res));
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Read and check a network. Refuses (NetworkMismatch, nothing signed) unless the spec, the node's `/status` and
|
|
71
|
+
* `eth_chainId` name the same chain id, the spec and the node the same genesis, and the spec's `testnet` flag matches
|
|
72
|
+
* the preset (a test network never stands in for the main network, nor the reverse).
|
|
73
|
+
*/
|
|
74
|
+
export async function connectNetwork(network = 'testnet', opts = {}) {
|
|
75
|
+
const p = typeof network === 'string' ? NETWORKS[network] : network;
|
|
76
|
+
if (!p)
|
|
77
|
+
throw new VordiumError('unknown_network', `Unknown network ${String(network)}; known: mainnet, testnet.`);
|
|
78
|
+
const t = opts.transport ?? fetchTransport;
|
|
79
|
+
const ms = opts.timeoutMs ?? 10000;
|
|
80
|
+
const sr = await t.get(p.spec, ms);
|
|
81
|
+
if (sr.status !== 200 || !sr.body || typeof sr.body !== 'object')
|
|
82
|
+
throw new VordiumError('no_spec', `The network spec at ${p.spec} could not be read.`);
|
|
83
|
+
const spec = sr.body;
|
|
84
|
+
const specChain = Number(spec.chainId);
|
|
85
|
+
if (!Number.isSafeInteger(specChain) || specChain <= 0)
|
|
86
|
+
throw new VordiumError('no_spec', 'The network spec names no chain id.');
|
|
87
|
+
const specTest = spec.testnet === true;
|
|
88
|
+
if (p.name === 'testnet' && !specTest)
|
|
89
|
+
throw new NetworkMismatch('The spec at the testnet address does not say it is the test network; refusing to sign.');
|
|
90
|
+
if (p.name === 'mainnet' && specTest)
|
|
91
|
+
throw new NetworkMismatch('The spec at the main-network address says it is a test network; refusing to sign.');
|
|
92
|
+
const [ident, rpcChain] = await Promise.all([nodeIdentity(p.api, t, ms), rpcChainId(p.rpc, t, ms)]);
|
|
93
|
+
if (ident.chainId !== specChain || rpcChain !== specChain) {
|
|
94
|
+
throw new NetworkMismatch(`The spec says chain ${specChain}, the node ${ident.chainId}, JSON-RPC ${rpcChain}; refusing to sign.`);
|
|
95
|
+
}
|
|
96
|
+
let specGenesis = null;
|
|
97
|
+
try {
|
|
98
|
+
specGenesis = genesisHex(String(spec.genesisSha256 ?? ''));
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
specGenesis = null;
|
|
102
|
+
}
|
|
103
|
+
if (specGenesis !== null && specGenesis !== ident.genesis) {
|
|
104
|
+
throw new NetworkMismatch(`The spec names genesis ${specGenesis.slice(0, 8)}…, the node ${ident.genesis.slice(0, 8)}…; refusing to sign.`);
|
|
105
|
+
}
|
|
106
|
+
return { ...p, chainId: ident.chainId, genesis: ident.genesis, specRead: spec };
|
|
107
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rising millisecond nonces. The chain admits an account's batch nonces, client nonces and dead-man-switch nonces
|
|
3
|
+
* through ONE window (milliseconds, within 2 days before / 1 day after block time, each used once), so a client takes
|
|
4
|
+
* them all from one clock per account: never the same twice, never below the wall clock.
|
|
5
|
+
*/
|
|
6
|
+
export declare class NonceClock {
|
|
7
|
+
private readonly now;
|
|
8
|
+
private last;
|
|
9
|
+
constructor(now?: () => number);
|
|
10
|
+
next(atLeast?: number): number;
|
|
11
|
+
/** Note a nonce the chain already holds, so the next one is above it. */
|
|
12
|
+
seen(nonce: number): void;
|
|
13
|
+
}
|
|
14
|
+
/** The one nonce clock of `owner` in this process. */
|
|
15
|
+
export declare function nonceClock(owner: string): NonceClock;
|