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