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