@vordium/sdk 0.1.2 → 0.1.3
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/README.md +15 -2
- package/dist/cjs/client.js +323 -60
- package/dist/cjs/index.js +6 -1
- package/dist/cjs/network.js +53 -1
- package/dist/cjs/nonce.js +419 -1
- package/dist/cjs/orders.js +3 -0
- package/dist/cjs/pins.js +60 -0
- package/dist/cjs/resend.js +188 -0
- package/dist/esm/client.d.ts +85 -9
- package/dist/esm/client.js +323 -63
- package/dist/esm/index.d.ts +3 -1
- package/dist/esm/index.js +3 -1
- package/dist/esm/network.d.ts +23 -4
- package/dist/esm/network.js +51 -1
- package/dist/esm/nonce.d.ts +109 -0
- package/dist/esm/nonce.js +410 -0
- package/dist/esm/orders.js +3 -0
- package/dist/esm/pins.d.ts +29 -0
- package/dist/esm/pins.js +51 -0
- package/dist/esm/resend.d.ts +74 -0
- package/dist/esm/resend.js +180 -0
- package/package.json +1 -1
package/dist/esm/nonce.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { VordiumError } from './errors.js';
|
|
1
2
|
/**
|
|
2
3
|
* Rising millisecond nonces. The chain admits an account's batch nonces, client nonces and dead-man-switch nonces
|
|
3
4
|
* through ONE window (milliseconds, within 2 days before / 1 day after block time, each used once), so a client takes
|
|
@@ -29,3 +30,412 @@ export function nonceClock(owner) {
|
|
|
29
30
|
}
|
|
30
31
|
return c;
|
|
31
32
|
}
|
|
33
|
+
// ── the persisted allocator ─────────────────────────────────────────────────────────────────────────────────────────
|
|
34
|
+
const DAY_MS = 86_400_000;
|
|
35
|
+
/** Client nonces of orders: strictly inside (block time - 2 days, block time + 1 day). */
|
|
36
|
+
export const ORDER_WINDOW = { behindMs: 2 * DAY_MS, aheadMs: DAY_MS, marginMs: 600_000 };
|
|
37
|
+
/** Session, agent and margin-mode nonces: above the stored one, at most a day ahead of block time. */
|
|
38
|
+
export const ACCOUNT_WINDOW = { behindMs: null, aheadMs: DAY_MS, marginMs: 600_000 };
|
|
39
|
+
/** The nonce this computer would sign is outside the window the network accepts. Nothing was signed. */
|
|
40
|
+
export class ClockOutOfWindow extends VordiumError {
|
|
41
|
+
nonce;
|
|
42
|
+
referenceMs;
|
|
43
|
+
reference;
|
|
44
|
+
constructor(message, nonce, referenceMs, reference) {
|
|
45
|
+
super('clock_out_of_window', message);
|
|
46
|
+
this.nonce = nonce;
|
|
47
|
+
this.referenceMs = referenceMs;
|
|
48
|
+
this.reference = reference;
|
|
49
|
+
this.name = 'ClockOutOfWindow';
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function span(ms) {
|
|
53
|
+
const a = Math.abs(ms);
|
|
54
|
+
if (a >= DAY_MS)
|
|
55
|
+
return `${(a / DAY_MS).toFixed(1)} days`;
|
|
56
|
+
if (a >= 3_600_000)
|
|
57
|
+
return `${(a / 3_600_000).toFixed(1)} hours`;
|
|
58
|
+
if (a >= 60_000)
|
|
59
|
+
return `${Math.round(a / 60_000)} minutes`;
|
|
60
|
+
return `${Math.round(a / 1000)} seconds`;
|
|
61
|
+
}
|
|
62
|
+
/** Throw {@link ClockOutOfWindow} when `nonce` is not safely inside `w` around `refMs` (block time, or this clock). */
|
|
63
|
+
export function checkWindow(nonce, w, refMs, ref, localMs = refMs) {
|
|
64
|
+
const ahead = nonce - refMs;
|
|
65
|
+
const against = ref === 'chain' ? "the network's block time" : "this computer's clock";
|
|
66
|
+
if (w.aheadMs !== null && ahead > w.aheadMs - w.marginMs) {
|
|
67
|
+
const why = ref === 'chain' && localMs - refMs > w.aheadMs - w.marginMs
|
|
68
|
+
? `this computer's clock is ${span(localMs - refMs)} ahead of the network's block time`
|
|
69
|
+
: nonce - localMs > w.aheadMs - w.marginMs
|
|
70
|
+
? `the last nonce used for this account is ${span(nonce - localMs)} ahead of this computer's clock (the clock was ahead, or has been set back)`
|
|
71
|
+
: `the nonce would be ${span(ahead)} ahead of ${against}`;
|
|
72
|
+
throw new ClockOutOfWindow(`Not signed: ${why}, and the network accepts a nonce at most ${span(w.aheadMs)} ahead of its block time. Set this computer's clock right and try again. Nothing was signed or sent.`, nonce, refMs, ref);
|
|
73
|
+
}
|
|
74
|
+
if (w.behindMs !== null && -ahead >= w.behindMs - w.marginMs) {
|
|
75
|
+
throw new ClockOutOfWindow(`Not signed: this computer's clock is ${span(-ahead)} behind ${against}, and the network accepts a nonce at most ${span(w.behindMs)} before its block time. Set this computer's clock right and try again. Nothing was signed or sent.`, nonce, refMs, ref);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** A store in this process's memory (the default outside Node.js). */
|
|
79
|
+
export function memoryNonceStore() {
|
|
80
|
+
const marks = new Map();
|
|
81
|
+
let chain = Promise.resolve();
|
|
82
|
+
return {
|
|
83
|
+
persistent: false,
|
|
84
|
+
update(key, fn) {
|
|
85
|
+
const run = chain.then(() => { const n = fn(marks.get(key) ?? 0); marks.set(key, n); return n; });
|
|
86
|
+
chain = run.catch(() => undefined);
|
|
87
|
+
return run;
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
const nodeModule = async (name) => (await import(name)); // kept out of browser bundles
|
|
92
|
+
const proc = () => globalThis.process ?? null;
|
|
93
|
+
/** Whether a process with this id runs here (EPERM: it runs, under another user). */
|
|
94
|
+
function alive(pid) {
|
|
95
|
+
try {
|
|
96
|
+
proc()?.kill(pid, 0);
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
return e.code === 'EPERM';
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** The nonce lock could not be taken within its time limit. Nothing was signed. */
|
|
104
|
+
export class NonceLockTimeout extends VordiumError {
|
|
105
|
+
constructor(message) { super('nonce_lock_timeout', message); this.name = 'NonceLockTimeout'; }
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* A store in files (Node.js): one file per account and space in `dir` (default `VORDIUM_STATE_DIR`, else
|
|
109
|
+
* `~/.vordium/nonces`), folder 0700, files 0600, behind a lock file so every process on this machine takes turns.
|
|
110
|
+
*
|
|
111
|
+
* The lock file holds its owner's process id and a token, and its holder refreshes its time while it holds it (a hold
|
|
112
|
+
* is short). A lock is stale when its time is older than `staleMs` (its holder stopped refreshing it), or when it names
|
|
113
|
+
* another process that is not running. A lock under this process's own id is never judged by its token: another thread
|
|
114
|
+
* or another copy of this SDK in the same process may hold it. A stale lock is taken over by an atomic rename to a name of the taker's own, after
|
|
115
|
+
* reading its token again; the moved file's token is checked, and a live lock moved by a race is put back. A holder
|
|
116
|
+
* writes the mark only while the lock holds its token and removes only its own lock. Taking the lock gives up after
|
|
117
|
+
* `acquireTimeoutMs` with {@link NonceLockTimeout}; it never waits forever.
|
|
118
|
+
*
|
|
119
|
+
* The lock keeps turns short and orderly; it is not what makes a value unique. A holder whose event loop stalled (a
|
|
120
|
+
* laptop asleep, a stopped process, a long pause) can have its lock taken over while it still works, so every value
|
|
121
|
+
* written is first claimed by an exclusive create of a claim file named after it in the folder `<mark>.claims`. Only
|
|
122
|
+
* the one process whose create succeeds may hand the value out; a value already claimed moves the next one above it.
|
|
123
|
+
* A value is computed above the highest claim present, the highest claim is never removed, and a claim that is not
|
|
124
|
+
* among the highest is removed only once it is older than four times `staleMs`. A holder gives a value up (and takes
|
|
125
|
+
* its turn again) when more than half of `staleMs` passed between reading the claims and claiming it, or since its lock
|
|
126
|
+
* was last seen fresh, so a claim it read past cannot have been removed under it.
|
|
127
|
+
*/
|
|
128
|
+
export function fileNonceStore(dir, opts = {}) {
|
|
129
|
+
const staleMs = opts.staleMs ?? 10_000;
|
|
130
|
+
const acquireTimeoutMs = opts.acquireTimeoutMs ?? 30_000;
|
|
131
|
+
const fenceMs = staleMs / 2; // the longest a holder may take from reading the claims to claiming
|
|
132
|
+
const claimAgeMs = 4 * staleMs; // a claim younger than this is never removed
|
|
133
|
+
const KEEP = 32; // the highest claims are never removed
|
|
134
|
+
const mono = () => globalThis.performance?.now() ?? Date.now();
|
|
135
|
+
let resolved = null;
|
|
136
|
+
let base = null;
|
|
137
|
+
const ready = () => base ??= (async () => {
|
|
138
|
+
const fs = await nodeModule('node:fs/promises');
|
|
139
|
+
const path = await nodeModule('node:path');
|
|
140
|
+
const os = await nodeModule('node:os');
|
|
141
|
+
const env = proc()?.env ?? {};
|
|
142
|
+
const d = dir ?? env.VORDIUM_STATE_DIR ?? path.join(os.homedir(), '.vordium', 'nonces');
|
|
143
|
+
await fs.mkdir(d, { recursive: true, mode: 0o700 });
|
|
144
|
+
await fs.chmod(d, 0o700).catch(() => undefined);
|
|
145
|
+
resolved = d;
|
|
146
|
+
return { fs, path, dir: d };
|
|
147
|
+
})();
|
|
148
|
+
let turn = Promise.resolve(); // one turn at a time inside this process, then the file lock
|
|
149
|
+
const exclusive = (f) => { const r = turn.then(f); turn = r.catch(() => undefined); return r; };
|
|
150
|
+
const rand = () => Math.random().toString(36).slice(2);
|
|
151
|
+
return {
|
|
152
|
+
persistent: true,
|
|
153
|
+
where: (key) => (resolved ? `${resolved}/${key}` : null),
|
|
154
|
+
async update(key, fn, opts) {
|
|
155
|
+
const unique = opts?.unique ?? true;
|
|
156
|
+
const { fs, path, dir: d } = await ready();
|
|
157
|
+
const file = path.join(d, key), lock = file + '.lock', claims = file + '.claims';
|
|
158
|
+
const read = (f) => fs.readFile(f, 'utf8').catch(() => null);
|
|
159
|
+
const stale = async (held) => {
|
|
160
|
+
const st = await fs.stat(lock).catch(() => null);
|
|
161
|
+
if (st && Date.now() - st.mtimeMs > staleMs)
|
|
162
|
+
return true; // its holder stopped refreshing it
|
|
163
|
+
// a lock under this process's own id may be held by another thread or another copy of this SDK in it: only a
|
|
164
|
+
// missing refresh makes it stale. A lock under another id is also stale when that process is not running.
|
|
165
|
+
const [pidText] = held.split(' ');
|
|
166
|
+
const pid = Number(pidText);
|
|
167
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || pid === proc()?.pid)
|
|
168
|
+
return false;
|
|
169
|
+
return !alive(pid);
|
|
170
|
+
};
|
|
171
|
+
/** The values claimed so far (rising). */
|
|
172
|
+
const listClaims = async () => {
|
|
173
|
+
const names = await fs.readdir(claims).catch((e) => { if (e.code === 'ENOENT')
|
|
174
|
+
return []; throw e; });
|
|
175
|
+
return names.filter((x) => /^\d+$/.test(x)).map(Number).filter(Number.isSafeInteger).sort((x, y) => x - y);
|
|
176
|
+
};
|
|
177
|
+
/** Claim `n` for this caller alone: true when this create made the claim, false when it was already claimed. */
|
|
178
|
+
const claim = async (n) => {
|
|
179
|
+
for (let i = 0;; i++) {
|
|
180
|
+
try {
|
|
181
|
+
await (await fs.open(path.join(claims, String(n)), 'wx', 0o600)).close();
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
184
|
+
catch (e) {
|
|
185
|
+
const code = e.code;
|
|
186
|
+
if (code === 'EEXIST')
|
|
187
|
+
return false;
|
|
188
|
+
if (code !== 'ENOENT' || i > 0)
|
|
189
|
+
throw e;
|
|
190
|
+
await fs.mkdir(claims, { recursive: true, mode: 0o700 });
|
|
191
|
+
await fs.chmod(claims, 0o700).catch(() => undefined);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
/** Remove old claims: never one of the highest `KEEP`, never one younger than `claimAgeMs`, never `held`. The
|
|
196
|
+
* whole old backlog goes in one pass (the lowest first, in chunks), so the folder stays near what was claimed in
|
|
197
|
+
* the last `claimAgeMs` however fast values are taken. */
|
|
198
|
+
const prune = async (seen, held) => {
|
|
199
|
+
if (seen.length <= 2 * KEEP)
|
|
200
|
+
return;
|
|
201
|
+
const old = seen.slice(0, seen.length - KEEP).filter((v) => v < held); // rising: the lowest are the oldest
|
|
202
|
+
for (let i = 0, size = 1; i < old.length; i += size, size = 64) { // one look first: usually all young
|
|
203
|
+
const chunk = old.slice(i, i + size);
|
|
204
|
+
const sts = await Promise.all(chunk.map((v) => fs.stat(path.join(claims, String(v))).catch(() => null)));
|
|
205
|
+
let young = false;
|
|
206
|
+
await Promise.all(chunk.map((v, k) => {
|
|
207
|
+
const st = sts[k];
|
|
208
|
+
if (!st)
|
|
209
|
+
return undefined;
|
|
210
|
+
if (Date.now() - st.mtimeMs <= claimAgeMs) {
|
|
211
|
+
young = true;
|
|
212
|
+
return undefined;
|
|
213
|
+
}
|
|
214
|
+
return fs.unlink(path.join(claims, String(v))).catch(() => undefined);
|
|
215
|
+
}));
|
|
216
|
+
if (young)
|
|
217
|
+
break;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
return exclusive(async () => {
|
|
221
|
+
const deadline = Date.now() + acquireTimeoutMs;
|
|
222
|
+
let losses = 0;
|
|
223
|
+
for (;;) {
|
|
224
|
+
const mine = `${proc()?.pid ?? 0} ${Date.now()}.${rand()}${rand()}`;
|
|
225
|
+
// take the lock
|
|
226
|
+
for (let i = 0;; i++) {
|
|
227
|
+
if (Date.now() > deadline) {
|
|
228
|
+
const s = Math.round(acquireTimeoutMs / 1000);
|
|
229
|
+
throw new NonceLockTimeout(losses > 0
|
|
230
|
+
? `The nonce lock ${lock} was taken ${losses} time(s) within ${s} s, but this process paused for longer than ${Math.round(fenceMs)} ms each time before it could finish (a busy or suspended event loop), so it gave each turn up. Nothing was signed.`
|
|
231
|
+
: `The nonce lock ${lock} could not be taken within ${s} s: another process holds it and keeps it fresh. Nothing was signed.`);
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
const h = await fs.open(lock, 'wx', 0o600);
|
|
235
|
+
try {
|
|
236
|
+
await h.writeFile(mine);
|
|
237
|
+
}
|
|
238
|
+
finally {
|
|
239
|
+
await h.close();
|
|
240
|
+
}
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
catch (e) {
|
|
244
|
+
if (e.code !== 'EEXIST')
|
|
245
|
+
throw e;
|
|
246
|
+
const held = await read(lock);
|
|
247
|
+
if (held !== null && await stale(held) && (await read(lock)) === held) {
|
|
248
|
+
const aside = `${lock}.${rand()}.taken`;
|
|
249
|
+
if (await fs.rename(lock, aside).then(() => true, () => false)) {
|
|
250
|
+
if ((await read(aside)) !== held)
|
|
251
|
+
await fs.link(aside, lock).catch(() => undefined); // a live lock: put it back
|
|
252
|
+
await fs.unlink(aside).catch(() => undefined);
|
|
253
|
+
}
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
await new Promise((r) => setTimeout(r, Math.min(20, 1 + i)));
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
// keep the lock fresh while it is held; `fresh` is when it was last seen ours and fresh
|
|
260
|
+
let fresh = mono();
|
|
261
|
+
const keep = setInterval(() => {
|
|
262
|
+
const t = new Date(), at = mono();
|
|
263
|
+
fs.utimes(lock, t, t).then(() => read(lock)).then((h) => { if (h === mine)
|
|
264
|
+
fresh = Math.max(fresh, at); }, () => undefined);
|
|
265
|
+
}, Math.max(50, Math.floor(staleMs / 3)));
|
|
266
|
+
keep.unref?.();
|
|
267
|
+
let lost = false;
|
|
268
|
+
let done = null;
|
|
269
|
+
try {
|
|
270
|
+
let last = 0;
|
|
271
|
+
try {
|
|
272
|
+
const t = (await fs.readFile(file, 'utf8')).trim();
|
|
273
|
+
if (/^\d+$/.test(t))
|
|
274
|
+
last = Number(t);
|
|
275
|
+
}
|
|
276
|
+
catch { /* no mark yet */ }
|
|
277
|
+
let n = last, claimed = false, seen = [];
|
|
278
|
+
if (!unique)
|
|
279
|
+
n = fn(last); // a record, not a nonce
|
|
280
|
+
else {
|
|
281
|
+
// compute a value above every claim present and claim it; a value already claimed moves it above
|
|
282
|
+
let floor = last, taken;
|
|
283
|
+
const tried = new Set();
|
|
284
|
+
for (;;) {
|
|
285
|
+
const t0 = mono();
|
|
286
|
+
seen = await listClaims();
|
|
287
|
+
const top = seen.length ? seen[seen.length - 1] : 0;
|
|
288
|
+
const from = Math.max(floor, top);
|
|
289
|
+
n = fn(from, taken);
|
|
290
|
+
// `fn` would not rise above the claims (a mark it sets back on purpose, or a plain read): its own
|
|
291
|
+
// choice from the mark stands
|
|
292
|
+
if (!(n > from) && from !== floor)
|
|
293
|
+
n = fn(floor, taken);
|
|
294
|
+
if (n === last && taken === undefined)
|
|
295
|
+
break; // nothing to write
|
|
296
|
+
if (tried.has(n)) { // `fn` keeps a value already taken
|
|
297
|
+
throw new VordiumError('nonce_unavailable', `Not signed: the next nonce for ${key} is already taken, and none above it is inside the network's window. Try again in a moment. Nothing was signed.`);
|
|
298
|
+
}
|
|
299
|
+
if (mono() - fresh > fenceMs) {
|
|
300
|
+
lost = true;
|
|
301
|
+
break;
|
|
302
|
+
} // the lock may have been taken over
|
|
303
|
+
if (await claim(n)) {
|
|
304
|
+
if (mono() - t0 > fenceMs)
|
|
305
|
+
lost = true; // stalled since reading the claims
|
|
306
|
+
claimed = true;
|
|
307
|
+
break;
|
|
308
|
+
}
|
|
309
|
+
tried.add(n);
|
|
310
|
+
floor = n;
|
|
311
|
+
taken = n; // claimed by another: from it, above it
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (!lost && n !== last) {
|
|
315
|
+
const tmp = `${file}.${rand()}.tmp`;
|
|
316
|
+
await fs.writeFile(tmp, `${n}\n`, { mode: 0o600 });
|
|
317
|
+
if ((await read(lock)) !== mine) {
|
|
318
|
+
lost = true;
|
|
319
|
+
await fs.unlink(tmp).catch(() => undefined);
|
|
320
|
+
} // not ours: do it again
|
|
321
|
+
else
|
|
322
|
+
await fs.rename(tmp, file);
|
|
323
|
+
}
|
|
324
|
+
if (lost)
|
|
325
|
+
losses++;
|
|
326
|
+
else
|
|
327
|
+
done = { n, prune: claimed ? seen : null };
|
|
328
|
+
}
|
|
329
|
+
finally {
|
|
330
|
+
clearInterval(keep);
|
|
331
|
+
if ((await read(lock)) === mine)
|
|
332
|
+
await fs.unlink(lock).catch(() => undefined); // only our own lock
|
|
333
|
+
}
|
|
334
|
+
if (done) { // old claims go after the turn
|
|
335
|
+
if (done.prune)
|
|
336
|
+
await prune(done.prune, done.n).catch(() => undefined);
|
|
337
|
+
return done.n;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
},
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
const isNode = () => typeof globalThis.process?.versions?.node === 'string';
|
|
345
|
+
let defaultStore = null;
|
|
346
|
+
/** Files under Node.js, memory elsewhere. */
|
|
347
|
+
export function defaultNonceStore() { return defaultStore ??= isNode() ? fileNonceStore() : memoryNonceStore(); }
|
|
348
|
+
/**
|
|
349
|
+
* Strictly rising millisecond nonces for one account in one nonce space: `max(last + 1, now)`, never the same twice
|
|
350
|
+
* across this process and (with a file store) every process on this machine, never back when the clock goes back, and
|
|
351
|
+
* checked against the network's window before use. One mark serves every network: a nonce that rises on all of them is
|
|
352
|
+
* valid on each.
|
|
353
|
+
*/
|
|
354
|
+
export class NonceAllocator {
|
|
355
|
+
space;
|
|
356
|
+
store;
|
|
357
|
+
now;
|
|
358
|
+
account;
|
|
359
|
+
window;
|
|
360
|
+
constructor(account, space = 'orders', store = defaultNonceStore(), now = Date.now, window) {
|
|
361
|
+
this.space = space;
|
|
362
|
+
this.store = store;
|
|
363
|
+
this.now = now;
|
|
364
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(account))
|
|
365
|
+
throw new VordiumError('invalid_request', 'A nonce allocator belongs to one account address.');
|
|
366
|
+
this.account = account.toLowerCase();
|
|
367
|
+
this.window = window ?? (space === 'orders' ? ORDER_WINDOW : ACCOUNT_WINDOW);
|
|
368
|
+
}
|
|
369
|
+
get persistent() { return this.store.persistent; }
|
|
370
|
+
get key() { return `${this.account}.${this.space}`; }
|
|
371
|
+
/** The next nonce, at least `atLeast`; checked against `chainMs` (block time) when given, else this computer's clock. */
|
|
372
|
+
async next(atLeast = 0, chainMs = null) {
|
|
373
|
+
const byValue = new Map();
|
|
374
|
+
const keep = (v, b) => { if (b)
|
|
375
|
+
byValue.set(v, b);
|
|
376
|
+
else
|
|
377
|
+
byValue.delete(v); return v; };
|
|
378
|
+
const out = await this.store.update(this.key, (last, taken) => {
|
|
379
|
+
const prior = taken !== undefined ? byValue.get(taken) ?? null : null;
|
|
380
|
+
const local = Math.floor(this.now());
|
|
381
|
+
const n = Math.max(last + 1, local, Math.floor(atLeast));
|
|
382
|
+
const [ref, kind] = chainMs !== null ? [chainMs, 'chain'] : [local, 'local'];
|
|
383
|
+
try {
|
|
384
|
+
checkWindow(n, this.window, ref, kind, local);
|
|
385
|
+
return keep(n, prior);
|
|
386
|
+
}
|
|
387
|
+
catch (e) {
|
|
388
|
+
const start = Math.max(local, Math.floor(atLeast));
|
|
389
|
+
if (!(e instanceof ClockOutOfWindow) || start >= n)
|
|
390
|
+
throw e;
|
|
391
|
+
if (this.space !== 'orders') {
|
|
392
|
+
const file = this.store.where?.(this.key) ?? null;
|
|
393
|
+
throw new ClockOutOfWindow(`Not signed: the last nonce used for this account is ${span(n - local)} ahead of this computer's clock, and the network accepts a nonce at most ${span(this.window.aheadMs ?? 0)} ahead of its block time. If this computer's clock was ahead when that nonce was used, set the clock right and wait; if the network never received those nonces, ${file ? `delete the file ${file}` : 'clear the stored mark'} to start again from the clock. Nothing was signed or sent.`, n, ref, kind);
|
|
394
|
+
}
|
|
395
|
+
// the order space only needs each nonce unused by the account: start again from the clock (the network
|
|
396
|
+
// refuses a nonce it already holds, so this can never apply a write twice)
|
|
397
|
+
checkWindow(start, this.window, ref, kind, local);
|
|
398
|
+
const notice = `the nonce mark was ${span(n - start)} ahead of the clock, outside the network's window; client nonces continue from the clock`;
|
|
399
|
+
return keep(start, { below: Math.max(n - 1, prior?.below ?? 0), at: chainMs ?? local, notice }); // on the network's clock when known (records carry block time)
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
const r = byValue.get(out);
|
|
403
|
+
if (r) { // nonces up to `below` may have been handed out before the set-back at `at`
|
|
404
|
+
this.notice = r.notice;
|
|
405
|
+
this.onRewind?.(r.notice);
|
|
406
|
+
await this.store.update(`${this.key}.rewind-from`, (old) => Math.max(old, r.below), { unique: false });
|
|
407
|
+
await this.store.update(`${this.key}.rewind-at`, () => r.at, { unique: false });
|
|
408
|
+
}
|
|
409
|
+
return out;
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* When the mark was set back to the clock and `nonce` may also have been handed out before that, the time of the
|
|
413
|
+
* set-back (ms): an order found with this nonce counts as this write's only when it is newer. Else null.
|
|
414
|
+
*/
|
|
415
|
+
async rewoundBefore(nonce) {
|
|
416
|
+
const below = await this.store.update(`${this.key}.rewind-from`, (x) => x, { unique: false });
|
|
417
|
+
if (!below || nonce > below)
|
|
418
|
+
return null;
|
|
419
|
+
const at = await this.store.update(`${this.key}.rewind-at`, (x) => x, { unique: false });
|
|
420
|
+
return at || null;
|
|
421
|
+
}
|
|
422
|
+
/** The last notice of a mark left outside the window that was set back to the clock (orders space), or null. */
|
|
423
|
+
notice = null;
|
|
424
|
+
/** Called with that notice when it happens. */
|
|
425
|
+
onRewind;
|
|
426
|
+
/** Note a nonce the chain already holds, so the next one is above it. */
|
|
427
|
+
async seen(nonce) { await this.store.update(this.key, (last) => Math.max(last, Math.floor(nonce)), { unique: false }); }
|
|
428
|
+
/** The highest nonce handed out or seen (0 when none). */
|
|
429
|
+
last() { return this.store.update(this.key, (last) => last, { unique: false }); }
|
|
430
|
+
}
|
|
431
|
+
const allocators = new Map();
|
|
432
|
+
/** The one allocator of `account` in `space` in this process (default store). */
|
|
433
|
+
export function nonceAllocator(account, space = 'orders') {
|
|
434
|
+
const k = `${account.toLowerCase()}.${space}`;
|
|
435
|
+
let a = allocators.get(k);
|
|
436
|
+
if (!a) {
|
|
437
|
+
a = new NonceAllocator(account, space);
|
|
438
|
+
allocators.set(k, a);
|
|
439
|
+
}
|
|
440
|
+
return a;
|
|
441
|
+
}
|
package/dist/esm/orders.js
CHANGED
|
@@ -226,6 +226,9 @@ export function readAnswer(status, body, retryAfter = null, meanings) {
|
|
|
226
226
|
return { submitted: true, status, refusal: null, actions, answer: body };
|
|
227
227
|
}
|
|
228
228
|
let code = typeof j.code === 'string' ? j.code : null;
|
|
229
|
+
if (status >= 500 && !code) { // a gateway or node error: the write may have reached the chain, neither refused nor accepted
|
|
230
|
+
return { submitted: false, status, refusal: { code: 'delivery_unknown', message: `The network answered ${status}: it is not known whether it received the write. Read the account before sending a new one.`, detail: '', retryAfter: ra }, actions: [], answer: body };
|
|
231
|
+
}
|
|
229
232
|
if (status === 429 && !code)
|
|
230
233
|
code = 'mempool_full';
|
|
231
234
|
if (code === 'agent_refused') { // an agent check at intake: the reason key and its meaning, as the chain gives them
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { NetworkMismatch } from './errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* The identity each named network is pinned to: its chain id and its genesis sha256. These values are part of the SDK.
|
|
4
|
+
* Before anything is signed, the SDK compares the pin with what the network reports (the network spec, the node's
|
|
5
|
+
* `/status` and the JSON-RPC `eth_chainId`); when any of them differs, nothing is signed. The EIP-712 domains are built
|
|
6
|
+
* from the pin. A new genesis for a named network needs a new SDK release that carries the new pin.
|
|
7
|
+
*/
|
|
8
|
+
export interface Pin {
|
|
9
|
+
/** "mainnet" or "testnet" for a named network; absent for a pin you give. */
|
|
10
|
+
name?: string;
|
|
11
|
+
chainId: number;
|
|
12
|
+
/** 64 lower-case hex, no 0x. */
|
|
13
|
+
genesis: string;
|
|
14
|
+
}
|
|
15
|
+
export declare const PINS: Readonly<Record<'mainnet' | 'testnet', Readonly<Pin>>>;
|
|
16
|
+
/** The network reports a chain id or genesis other than its pin. Nothing was signed. */
|
|
17
|
+
export declare class PinMismatch extends NetworkMismatch {
|
|
18
|
+
constructor(message: string);
|
|
19
|
+
}
|
|
20
|
+
/** The network is not a named network and carries no pin. It can be read; nothing is signed for it. */
|
|
21
|
+
export declare class UnpinnedNetwork extends NetworkMismatch {
|
|
22
|
+
constructor(message: string);
|
|
23
|
+
}
|
|
24
|
+
/** A pin checked for shape: a positive safe-integer chain id and a 32-byte genesis (returned lower-case, no 0x). */
|
|
25
|
+
export declare function checkPin(pin: Pin): Pin;
|
|
26
|
+
export declare function pinLabel(pin: Pin): string;
|
|
27
|
+
/** One plain line per reported value that differs from the pin (a value that was not reported is skipped). */
|
|
28
|
+
export declare function pinDifferences(pin: Pin, chainIds: Record<string, number | null | undefined>, geneses: Record<string, string | null | undefined>): string[];
|
|
29
|
+
export declare function pinRefusal(pin: Pin, problems: string[]): string;
|
package/dist/esm/pins.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { NetworkMismatch } from './errors.js';
|
|
2
|
+
export const PINS = Object.freeze({
|
|
3
|
+
mainnet: Object.freeze({ name: 'mainnet', chainId: 101101, genesis: '2c1c0679fa6ab8358f1d3e8d294a8d1c73ac2e2caf9079f1216abedc3d9fdf4f' }),
|
|
4
|
+
testnet: Object.freeze({ name: 'testnet', chainId: 101102, genesis: '8b5d414c5cd5d18bc468b64f87ac8e2c2b5ff494c769d5e09dcf50ce75a59792' }),
|
|
5
|
+
});
|
|
6
|
+
/** The network reports a chain id or genesis other than its pin. Nothing was signed. */
|
|
7
|
+
export class PinMismatch extends NetworkMismatch {
|
|
8
|
+
constructor(message) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = 'PinMismatch';
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** The network is not a named network and carries no pin. It can be read; nothing is signed for it. */
|
|
14
|
+
export class UnpinnedNetwork extends NetworkMismatch {
|
|
15
|
+
constructor(message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = 'UnpinnedNetwork';
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** A pin checked for shape: a positive safe-integer chain id and a 32-byte genesis (returned lower-case, no 0x). */
|
|
21
|
+
export function checkPin(pin) {
|
|
22
|
+
if (!pin || typeof pin !== 'object' || !Number.isSafeInteger(pin.chainId) || pin.chainId <= 0) {
|
|
23
|
+
throw new UnpinnedNetwork('A pin needs a positive integer chain id; nothing was signed.');
|
|
24
|
+
}
|
|
25
|
+
const g = typeof pin.genesis === 'string' ? pin.genesis.replace(/^0x/i, '') : '';
|
|
26
|
+
if (!/^[0-9a-fA-F]{64}$/.test(g))
|
|
27
|
+
throw new UnpinnedNetwork('A pin needs the genesis sha256 as 64 hex characters; nothing was signed.');
|
|
28
|
+
return Object.freeze({ ...(pin.name ? { name: pin.name } : {}), chainId: pin.chainId, genesis: g.toLowerCase() });
|
|
29
|
+
}
|
|
30
|
+
export function pinLabel(pin) {
|
|
31
|
+
return pin.name ?? `the pinned network (chain ${pin.chainId})`;
|
|
32
|
+
}
|
|
33
|
+
/** One plain line per reported value that differs from the pin (a value that was not reported is skipped). */
|
|
34
|
+
export function pinDifferences(pin, chainIds, geneses) {
|
|
35
|
+
const out = [];
|
|
36
|
+
for (const [src, cid] of Object.entries(chainIds)) {
|
|
37
|
+
if (cid !== null && cid !== undefined && cid !== pin.chainId)
|
|
38
|
+
out.push(`${src} reports chain id ${cid}, expected ${pin.chainId}`);
|
|
39
|
+
}
|
|
40
|
+
for (const [src, g] of Object.entries(geneses)) {
|
|
41
|
+
if (g === null || g === undefined)
|
|
42
|
+
continue;
|
|
43
|
+
const n = g.replace(/^0x/i, '').toLowerCase();
|
|
44
|
+
if (n !== pin.genesis)
|
|
45
|
+
out.push(`${src} reports genesis ${n}, expected ${pin.genesis}`);
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
export function pinRefusal(pin, problems) {
|
|
50
|
+
return `Refusing to sign for ${pinLabel(pin)}: ${problems.join('; ')}. Nothing was signed. Check that the endpoint serves this network.`;
|
|
51
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { VordiumError } from './errors.js';
|
|
2
|
+
/** Answers that mean "try again": the write was not taken, or a gateway cannot tell. */
|
|
3
|
+
export declare const RESEND_STATUS: Set<number>;
|
|
4
|
+
/** Whether an answer says the nonce (of a body we sent) is already used. */
|
|
5
|
+
export declare function nonceUsedAnswer(status: number | null, body: unknown): boolean;
|
|
6
|
+
/** The network did not answer any copy of a signed write. It may have arrived: read the account before sending a new
|
|
7
|
+
* one (a new one takes a new nonce). */
|
|
8
|
+
export declare class DeliveryUnknown extends VordiumError {
|
|
9
|
+
readonly nonce: number | null;
|
|
10
|
+
readonly attempts: number;
|
|
11
|
+
/** True when no copy left this machine (the connection could not be made on any try): it certainly did not arrive. */
|
|
12
|
+
neverSent: boolean;
|
|
13
|
+
constructor(message: string, nonce: number | null, attempts: number);
|
|
14
|
+
}
|
|
15
|
+
/** What came back for one signed body. `attempts` copies were sent. `needsReadBack` is true when a copy sent in this
|
|
16
|
+
* call may have reached the network (a lost answer, a gateway error) and the final answer is not a 2xx: that answer (a
|
|
17
|
+
* refusal, the nonce code, a 5xx) may be about a LATER copy while an earlier one applied, so it is never a plain
|
|
18
|
+
* refusal; only a read-back of the write can say what happened (else it is unknown). */
|
|
19
|
+
export interface Sent {
|
|
20
|
+
status: number;
|
|
21
|
+
body: unknown;
|
|
22
|
+
retryAfter: string | null;
|
|
23
|
+
attempts: number;
|
|
24
|
+
needsReadBack: boolean;
|
|
25
|
+
}
|
|
26
|
+
/** True when the error happened while the connection was being made: the name lookup, a connect timeout, or a refused
|
|
27
|
+
* / unreachable error whose `syscall` is `connect`. The same refused or unreachable code on a connection that was
|
|
28
|
+
* already open (after a retransmit timeout), a timeout, or a gateway answer is not that: the copy may have arrived. */
|
|
29
|
+
export declare function neverSent(e: unknown): boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Send one signed body until the network answers it, at most `attempts` times, each time the same bytes.
|
|
32
|
+
*
|
|
33
|
+
* `dedup` says whether the network applies this write once per nonce. Then a thrown error (a lost connection, a
|
|
34
|
+
* timeout) or HTTP 429/502/503/504 sends it again after a short random wait (at least the server's Retry-After); when an
|
|
35
|
+
* earlier copy may have arrived and the final answer is not a 2xx, `needsReadBack` is set. For a write the network does
|
|
36
|
+
* not deduplicate (`dedup: false`) a copy is sent again only when the first never left this machine or was answered
|
|
37
|
+
* 429; a timeout, a dropped connection or any 5xx throws {@link DeliveryUnknown} at once, so the caller reads state
|
|
38
|
+
* instead of risking a second effect.
|
|
39
|
+
*/
|
|
40
|
+
export declare function sendSame(send: () => Promise<{
|
|
41
|
+
status: number;
|
|
42
|
+
body: unknown;
|
|
43
|
+
retryAfter: string | null;
|
|
44
|
+
}>, opts?: {
|
|
45
|
+
attempts?: number;
|
|
46
|
+
nonce?: number | null;
|
|
47
|
+
dedup?: boolean;
|
|
48
|
+
sleep?: (ms: number) => Promise<unknown>;
|
|
49
|
+
}): Promise<Sent>;
|
|
50
|
+
/**
|
|
51
|
+
* The network's block time, estimated as this computer's clock plus the offset measured at the last read: the latest
|
|
52
|
+
* block (JSON-RPC), cross-checked against the node's `/status` head (a JSON-RPC that serves another head is not this
|
|
53
|
+
* chain's clock). Null when unavailable. A reading is kept `ttlMs`; a failed one is retried after a fifth of that.
|
|
54
|
+
*/
|
|
55
|
+
export declare class ChainClock {
|
|
56
|
+
private readonly readBlock;
|
|
57
|
+
private readonly readHead;
|
|
58
|
+
private readonly ttlMs;
|
|
59
|
+
private readonly now;
|
|
60
|
+
private readonly maxHeadGap;
|
|
61
|
+
private offset;
|
|
62
|
+
private nextRead;
|
|
63
|
+
constructor(readBlock: () => Promise<{
|
|
64
|
+
number?: unknown;
|
|
65
|
+
timestamp?: unknown;
|
|
66
|
+
} | null>, readHead: () => Promise<number | null>, ttlMs?: number, now?: () => number, maxHeadGap?: number);
|
|
67
|
+
private static int;
|
|
68
|
+
/** Read the network now: block time minus this computer's clock (ms), or null. */
|
|
69
|
+
measure(): Promise<number | null>;
|
|
70
|
+
private inFlight;
|
|
71
|
+
/** Block time now, or null. When a reading is due, the caller that finds it due runs ONE read and waits for it;
|
|
72
|
+
* every other caller meanwhile is served the last reading at once (null before the first). */
|
|
73
|
+
time(): Promise<number | null>;
|
|
74
|
+
}
|