@vordium/sdk 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -5
- package/dist/cjs/client.js +9 -3
- package/dist/cjs/http.js +58 -4
- package/dist/cjs/index.js +1 -0
- package/dist/cjs/network.js +128 -10
- package/dist/cjs/nonce.js +7 -3
- package/dist/cjs/releaseRecord.js +833 -0
- package/dist/cjs/rounding.js +4 -0
- package/dist/esm/client.d.ts +9 -3
- package/dist/esm/client.js +10 -4
- package/dist/esm/http.d.ts +11 -0
- package/dist/esm/http.js +57 -3
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js +1 -0
- package/dist/esm/network.d.ts +60 -12
- package/dist/esm/network.js +126 -9
- package/dist/esm/nonce.d.ts +3 -1
- package/dist/esm/nonce.js +7 -3
- package/dist/esm/pins.d.ts +3 -1
- package/dist/esm/releaseRecord.d.ts +141 -0
- package/dist/esm/releaseRecord.js +819 -0
- package/dist/esm/rounding.js +4 -0
- package/package.json +3 -1
package/dist/cjs/rounding.js
CHANGED
|
@@ -220,6 +220,10 @@ function pairSpecs(read) {
|
|
|
220
220
|
if (!s || typeof s !== 'object')
|
|
221
221
|
throw new OrderValueError('the market rules read has no specs; nothing was signed.');
|
|
222
222
|
const sp = s;
|
|
223
|
+
if (Array.isArray(sp.pairs) && sp.pairs.length && (sp.min_order_notional_6dec === undefined || sp.min_order_notional_6dec === null || sp.min_order_notional_6dec === '')) {
|
|
224
|
+
// a read that lists markets but not the smallest order value is trimmed or out of date: never read it as "no minimum"
|
|
225
|
+
throw new SpecsUnavailable('the market rules do not name the smallest order value (min_order_notional_6dec); nothing was signed.');
|
|
226
|
+
}
|
|
223
227
|
const minNotional6 = count(sp.min_order_notional_6dec);
|
|
224
228
|
const out = new Map();
|
|
225
229
|
for (const p of Array.isArray(sp.pairs) ? sp.pairs : []) {
|
package/dist/esm/client.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { type PolicyV1 } from './agents.js';
|
|
|
3
3
|
import { type DomainClass, type TypedDomain } from './domains.js';
|
|
4
4
|
import { type Transport } from './http.js';
|
|
5
5
|
import { type Network, type NetworkPreset } from './network.js';
|
|
6
|
-
import { type NonceSource } from './nonce.js';
|
|
6
|
+
import { type NonceSource, type NonceStore } from './nonce.js';
|
|
7
7
|
import { ChainClock } from './resend.js';
|
|
8
8
|
import { type BatchAction, type OrderInput, type Submitted } from './orders.js';
|
|
9
9
|
import { type AgentRefusal, type Equity, type OpenOrder, type Position } from './reads.js';
|
|
@@ -37,6 +37,12 @@ export interface ConnectOptions {
|
|
|
37
37
|
* default with the built-in transport; with a transport of your own, off unless set. Off: against this computer's clock.
|
|
38
38
|
*/
|
|
39
39
|
chainClock?: boolean;
|
|
40
|
+
/** Tests only: armoured OpenPGP public keys that replace the shipped release key (see `releaseRecord.ts`). */
|
|
41
|
+
releaseKeys?: readonly string[];
|
|
42
|
+
/** Where the highest release-record sequence seen is kept (default: the nonce store, files 0600 under Node.js). */
|
|
43
|
+
releaseRecordStore?: NonceStore;
|
|
44
|
+
/** Tests only: this computer's clock in milliseconds, for the release record's expiry. */
|
|
45
|
+
releaseRecordNow?: () => number;
|
|
40
46
|
}
|
|
41
47
|
/** A connection to one Vordium network: reads, and the signing domains of its node. */
|
|
42
48
|
export declare class Vordium {
|
|
@@ -53,8 +59,8 @@ export declare class Vordium {
|
|
|
53
59
|
/** Read and check the network (spec, node and JSON-RPC must agree) and return a client for it. Testnet by default. */
|
|
54
60
|
static connect(opts?: ConnectOptions): Promise<Vordium>;
|
|
55
61
|
/**
|
|
56
|
-
* The signing domain of the node this client posts to, built from the network's
|
|
57
|
-
* reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
|
|
62
|
+
* The signing domain of the node this client posts to, built from the network's identity (the signed release record's,
|
|
63
|
+
* else its pin in `PINS`) after the network's reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
|
|
58
64
|
* chain is refused, never followed.
|
|
59
65
|
*/
|
|
60
66
|
domain(cls: DomainClass): Promise<TypedDomain>;
|
package/dist/esm/client.js
CHANGED
|
@@ -4,7 +4,7 @@ import { LOWERCASE_ADDRESS_OPS, loosens, policyFromRead, policyProblems, policyV
|
|
|
4
4
|
import { domain } from './domains.js';
|
|
5
5
|
import { InvalidRequest, NetworkMismatch, VordiumError } from './errors.js';
|
|
6
6
|
import { fetchTransport } from './http.js';
|
|
7
|
-
import { connectNetwork, nodeIdentity, signingPin } from './network.js';
|
|
7
|
+
import { connectNetwork, nodeIdentity, refreshRecord, signingPin } from './network.js';
|
|
8
8
|
import { PinMismatch, pinDifferences, pinRefusal } from './pins.js';
|
|
9
9
|
import { NonceAllocator, nonceAllocator } from './nonce.js';
|
|
10
10
|
import { ChainClock, DeliveryUnknown, sendSame } from './resend.js';
|
|
@@ -70,15 +70,19 @@ export class Vordium {
|
|
|
70
70
|
static async connect(opts = {}) {
|
|
71
71
|
const transport = opts.transport ?? fetchTransport;
|
|
72
72
|
const timeoutMs = opts.timeoutMs ?? 15000;
|
|
73
|
-
const net = await connectNetwork(opts.network ?? 'testnet', {
|
|
73
|
+
const net = await connectNetwork(opts.network ?? 'testnet', {
|
|
74
|
+
transport, timeoutMs, onPinProblem: opts.onPinProblem,
|
|
75
|
+
releaseKeys: opts.releaseKeys, releaseRecordStore: opts.releaseRecordStore, releaseRecordNow: opts.releaseRecordNow,
|
|
76
|
+
});
|
|
74
77
|
return new Vordium(net, transport, timeoutMs, opts.identityTtlMs ?? 60000, opts.chainClock ?? opts.transport === undefined);
|
|
75
78
|
}
|
|
76
79
|
/**
|
|
77
|
-
* The signing domain of the node this client posts to, built from the network's
|
|
78
|
-
* reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
|
|
80
|
+
* The signing domain of the node this client posts to, built from the network's identity (the signed release record's,
|
|
81
|
+
* else its pin in `PINS`) after the network's reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
|
|
79
82
|
* chain is refused, never followed.
|
|
80
83
|
*/
|
|
81
84
|
async domain(cls) {
|
|
85
|
+
await refreshRecord(this.network);
|
|
82
86
|
const pin = signingPin(this.network);
|
|
83
87
|
if (Date.now() - this.checkedAt >= this.ttlMs) {
|
|
84
88
|
const id = await nodeIdentity(this.network.api, this.transport, this.timeoutMs);
|
|
@@ -98,6 +102,8 @@ export class Vordium {
|
|
|
98
102
|
const r = await this.transport.get(this.network.api + path, this.timeoutMs);
|
|
99
103
|
if (r.status === 404)
|
|
100
104
|
return null;
|
|
105
|
+
if (r.status >= 300 && r.status < 400)
|
|
106
|
+
throw new VordiumError('redirect_refused', `The read ${path} was answered with a redirect, which is not followed: use the https address of the node.`);
|
|
101
107
|
if (r.status !== 200)
|
|
102
108
|
throw new VordiumError('read_failed', `The read ${path} answered HTTP ${r.status}.`);
|
|
103
109
|
return r.body;
|
package/dist/esm/http.d.ts
CHANGED
|
@@ -10,7 +10,18 @@ export interface Transport {
|
|
|
10
10
|
body: unknown;
|
|
11
11
|
retryAfter: string | null;
|
|
12
12
|
}>;
|
|
13
|
+
/** The exact bytes served at `url` (the signed release record is verified over them), read no further than `limit` + 1
|
|
14
|
+
* bytes. A transport without it reads no release record. */
|
|
15
|
+
getBytes?(url: string, timeoutMs: number, limit?: number): Promise<{
|
|
16
|
+
status: number;
|
|
17
|
+
bytes: Uint8Array;
|
|
18
|
+
}>;
|
|
13
19
|
}
|
|
20
|
+
/** What a redirect answer reads as: never the redirect's own body. */
|
|
21
|
+
export declare const REDIRECT_REFUSAL: Readonly<{
|
|
22
|
+
code: "redirect_refused";
|
|
23
|
+
error: "The node answered with a redirect, which is not followed: use the https address of the node.";
|
|
24
|
+
}>;
|
|
14
25
|
/**
|
|
15
26
|
* The default transport: `fetch`. A read (GET) is tried up to three times on a connection error, a timeout, 429 or
|
|
16
27
|
* 502–504, with a random wait and the server's Retry-After. A write (POST) is never retried: a second attempt could
|
package/dist/esm/http.js
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
import { VordiumError } from './errors.js';
|
|
2
2
|
const RETRY_STATUS = new Set([429, 502, 503, 504]);
|
|
3
|
+
/**
|
|
4
|
+
* One fetch with a time limit. Redirects are never followed (`redirect: 'manual'`), for reads or writes: a 3xx comes back
|
|
5
|
+
* as the answer it is, so a node (or anything in front of it) cannot send a signed body, or a read, to another address.
|
|
6
|
+
*/
|
|
3
7
|
async function fetchWithTimeout(url, init, timeoutMs) {
|
|
4
8
|
const ctl = new AbortController();
|
|
5
9
|
const t = setTimeout(() => ctl.abort(), timeoutMs);
|
|
6
10
|
try {
|
|
7
|
-
return await fetch(url, { ...init, signal: ctl.signal });
|
|
11
|
+
return await fetch(url, { ...init, redirect: 'manual', signal: ctl.signal });
|
|
8
12
|
}
|
|
9
13
|
finally {
|
|
10
14
|
clearTimeout(t);
|
|
@@ -22,6 +26,35 @@ async function readBody(r) {
|
|
|
22
26
|
}
|
|
23
27
|
}
|
|
24
28
|
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
|
|
29
|
+
/** The body of `r`, read no further than `limit` + 1 bytes (the rest is not downloaded). */
|
|
30
|
+
async function readCapped(r, limit) {
|
|
31
|
+
if (!r.body)
|
|
32
|
+
return new Uint8Array(0);
|
|
33
|
+
const reader = r.body.getReader();
|
|
34
|
+
const parts = [];
|
|
35
|
+
let n = 0;
|
|
36
|
+
for (;;) {
|
|
37
|
+
const { done, value } = await reader.read();
|
|
38
|
+
if (done)
|
|
39
|
+
break;
|
|
40
|
+
parts.push(value);
|
|
41
|
+
n += value.length;
|
|
42
|
+
if (n > limit) {
|
|
43
|
+
await reader.cancel().catch(() => undefined);
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const out = new Uint8Array(n);
|
|
48
|
+
let i = 0;
|
|
49
|
+
for (const p of parts) {
|
|
50
|
+
out.set(p, i);
|
|
51
|
+
i += p.length;
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
const isRedirect = (status) => status >= 300 && status < 400;
|
|
56
|
+
/** What a redirect answer reads as: never the redirect's own body. */
|
|
57
|
+
export const REDIRECT_REFUSAL = Object.freeze({ code: 'redirect_refused', error: 'The node answered with a redirect, which is not followed: use the https address of the node.' });
|
|
25
58
|
/**
|
|
26
59
|
* The default transport: `fetch`. A read (GET) is tried up to three times on a connection error, a timeout, 429 or
|
|
27
60
|
* 502–504, with a random wait and the server's Retry-After. A write (POST) is never retried: a second attempt could
|
|
@@ -38,7 +71,27 @@ export const fetchTransport = {
|
|
|
38
71
|
await sleep(Number.isFinite(ra) && ra > 0 ? Math.min(ra, 5) * 1000 : 250 * 2 ** attempt * (0.5 + Math.random() / 2));
|
|
39
72
|
continue;
|
|
40
73
|
}
|
|
41
|
-
return { status: r.status, body: await readBody(r) };
|
|
74
|
+
return { status: r.status, body: isRedirect(r.status) ? { ...REDIRECT_REFUSAL } : await readBody(r) };
|
|
75
|
+
}
|
|
76
|
+
catch (e) {
|
|
77
|
+
last = e;
|
|
78
|
+
if (attempt < 2)
|
|
79
|
+
await sleep(250 * 2 ** attempt * (0.5 + Math.random() / 2));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
throw new VordiumError('unreachable', `The node at ${url} did not answer.`, String(last?.message ?? last));
|
|
83
|
+
},
|
|
84
|
+
async getBytes(url, timeoutMs, limit = Infinity) {
|
|
85
|
+
let last = null;
|
|
86
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
87
|
+
try {
|
|
88
|
+
const r = await fetchWithTimeout(url, {}, timeoutMs);
|
|
89
|
+
if (RETRY_STATUS.has(r.status) && attempt < 2) {
|
|
90
|
+
await sleep(250 * 2 ** attempt * (0.5 + Math.random() / 2));
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
// a redirect is not followed and its body is not read
|
|
94
|
+
return { status: r.status, bytes: isRedirect(r.status) ? new Uint8Array(0) : await readCapped(r, limit) };
|
|
42
95
|
}
|
|
43
96
|
catch (e) {
|
|
44
97
|
last = e;
|
|
@@ -50,7 +103,8 @@ export const fetchTransport = {
|
|
|
50
103
|
},
|
|
51
104
|
async post(url, body, timeoutMs) {
|
|
52
105
|
const r = await fetchWithTimeout(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body }, timeoutMs);
|
|
53
|
-
|
|
106
|
+
// a redirect is not an answer about the write: no body is read from it
|
|
107
|
+
return { status: r.status, body: isRedirect(r.status) ? { ...REDIRECT_REFUSAL } : await readBody(r), retryAfter: r.headers.get('retry-after') };
|
|
54
108
|
},
|
|
55
109
|
};
|
|
56
110
|
/**
|
package/dist/esm/index.d.ts
CHANGED
package/dist/esm/index.js
CHANGED
package/dist/esm/network.d.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { type Transport } from './http.js';
|
|
2
2
|
import { type Pin } from './pins.js';
|
|
3
|
+
import { type PublicKey, type ReadRecordOptions, type VerifiedRecord } from './releaseRecord.js';
|
|
4
|
+
import type { NonceStore } from './nonce.js';
|
|
3
5
|
/**
|
|
4
|
-
* Where the SDK asks, and the
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
6
|
+
* Where the SDK asks, and the identity the network is held to. A named network's identity comes from the signed release
|
|
7
|
+
* record when one is served (`releaseRecord.ts`: its genesis for the network's chain id), else from the SDK's pins
|
|
8
|
+
* (`PINS`). A preset of your own (another address) names the network it serves (`name: 'mainnet' | 'testnet'`), or
|
|
9
|
+
* carries an explicit `pin`, or names the `chainId` of a network the signed record lists. Before anything is signed,
|
|
10
|
+
* the network spec, the node's `/status` and the JSON-RPC `eth_chainId` must agree with each other and with it.
|
|
8
11
|
*/
|
|
9
12
|
export interface NetworkPreset {
|
|
10
13
|
/** 'mainnet' or 'testnet' holds the preset to that network's pin; any other name needs `pin`. */
|
|
@@ -19,6 +22,10 @@ export interface NetworkPreset {
|
|
|
19
22
|
feeds?: string;
|
|
20
23
|
/** An explicit pin, for a network that is not a named one (or the named network's own pin). */
|
|
21
24
|
pin?: Pin;
|
|
25
|
+
/** A network that only the signed release record names: its chain id (nothing is signed without a record listing it). */
|
|
26
|
+
recordChainId?: number;
|
|
27
|
+
/** Tests only: where the signed release record is read (the named networks read `RELEASE_RECORD_URLS`). */
|
|
28
|
+
releaseRecord?: string;
|
|
22
29
|
}
|
|
23
30
|
export declare const NETWORKS: Record<'mainnet' | 'testnet', NetworkPreset>;
|
|
24
31
|
/** A network the SDK has read and checked. `chainId` and `genesis` are what the network reports. */
|
|
@@ -30,7 +37,39 @@ export interface Network extends NetworkPreset {
|
|
|
30
37
|
specRead: Record<string, unknown>;
|
|
31
38
|
/** Why nothing may be signed for this network (its reports differ from its pin, or it has no pin); null when none. */
|
|
32
39
|
pinProblem: string | null;
|
|
40
|
+
/** The signed release record the network was checked against (its genesis is the pin, its bridge the bridge); null
|
|
41
|
+
* when none is served (the SDK's pin applies). */
|
|
42
|
+
record: VerifiedRecord | null;
|
|
43
|
+
/** Why the served release record cannot be used; nothing is signed while it is set. */
|
|
44
|
+
recordProblem: string | null;
|
|
45
|
+
/** Where the record is read again, and the record as last read: signing uses the record as it is now (see
|
|
46
|
+
* {@link refreshRecord}). Absent for a network with a pin of its own. */
|
|
47
|
+
recordLive?: RecordLive;
|
|
33
48
|
}
|
|
49
|
+
/** How a connected network's release record is read again, and what was last read. */
|
|
50
|
+
export interface RecordLive {
|
|
51
|
+
chainId: number;
|
|
52
|
+
urls: readonly string[];
|
|
53
|
+
keys: readonly PublicKey[];
|
|
54
|
+
byChain: boolean;
|
|
55
|
+
read: ReadRecordOptions;
|
|
56
|
+
record: VerifiedRecord | null;
|
|
57
|
+
problem: string | null;
|
|
58
|
+
/** Date.now() when it was read. */
|
|
59
|
+
at: number;
|
|
60
|
+
}
|
|
61
|
+
/** How long a network's release record is used before it is read again (ms), and how soon a refused one is retried. */
|
|
62
|
+
export declare const RECORD_TTL_MS = 300000;
|
|
63
|
+
export declare const RECORD_RETRY_MS = 30000;
|
|
64
|
+
/**
|
|
65
|
+
* Read the network's release record again when it has expired, when it is older than {@link RECORD_TTL_MS}, or when it
|
|
66
|
+
* was refused more than {@link RECORD_RETRY_MS} ago. A client calls it before every signature; {@link signingPin} then
|
|
67
|
+
* judges the record as it is now.
|
|
68
|
+
*/
|
|
69
|
+
export declare function refreshRecord(net: Network, opts?: {
|
|
70
|
+
ttlMs?: number;
|
|
71
|
+
retryMs?: number;
|
|
72
|
+
}): Promise<void>;
|
|
34
73
|
/** The pin a preset is held to: its own `pin`, else the pin of the named network it names; null when it has none. */
|
|
35
74
|
export declare function presetPin(p: NetworkPreset): Pin | null;
|
|
36
75
|
/**
|
|
@@ -47,17 +86,26 @@ export declare function readIdentity(status: unknown): NodeIdentity;
|
|
|
47
86
|
/** Where a node's `/status` is read: under the API's own path first, then at the host root. */
|
|
48
87
|
export declare function statusUrls(api: string): string[];
|
|
49
88
|
export declare function nodeIdentity(api: string, transport?: Transport, timeoutMs?: number): Promise<NodeIdentity>;
|
|
89
|
+
/** Options of {@link connectNetwork}. `releaseKeys`, `releaseRecordStore` and `releaseRecordNow` are for tests only. */
|
|
90
|
+
export interface ConnectNetworkOptions {
|
|
91
|
+
transport?: Transport;
|
|
92
|
+
timeoutMs?: number;
|
|
93
|
+
onPinProblem?: (message: string) => void;
|
|
94
|
+
/** Tests only: armoured OpenPGP public keys that replace the shipped release key. */
|
|
95
|
+
releaseKeys?: readonly string[];
|
|
96
|
+
/** Where the highest record sequence seen is kept (default: the nonce store). */
|
|
97
|
+
releaseRecordStore?: NonceStore;
|
|
98
|
+
/** Tests only: this computer's clock in milliseconds. */
|
|
99
|
+
releaseRecordNow?: () => number;
|
|
100
|
+
}
|
|
50
101
|
/**
|
|
51
102
|
* Read and check a network. Refuses (NetworkMismatch, nothing signed) unless the spec, the node's `/status` and
|
|
52
103
|
* `eth_chainId` name the same chain id, the spec and the node the same genesis, and the spec's `testnet` flag matches
|
|
53
104
|
* the preset (a test network never stands in for the main network, nor the reverse).
|
|
54
105
|
*
|
|
55
|
-
* The
|
|
56
|
-
*
|
|
57
|
-
*
|
|
106
|
+
* The network's identity comes from the signed release record when one is served (its genesis for the network's chain
|
|
107
|
+
* id; see `readRecord`), else from its pin. When the reports differ (or the network has no identity, or the served
|
|
108
|
+
* record cannot be used) the connection still reads, `pinProblem` says why, `onPinProblem` (when given) is called with
|
|
109
|
+
* it, and every signature is refused (`PinMismatch` / `UnpinnedNetwork`). The SDK prints nothing.
|
|
58
110
|
*/
|
|
59
|
-
export declare function connectNetwork(network?: 'mainnet' | 'testnet' | NetworkPreset, opts?:
|
|
60
|
-
transport?: Transport;
|
|
61
|
-
timeoutMs?: number;
|
|
62
|
-
onPinProblem?: (message: string) => void;
|
|
63
|
-
}): Promise<Network>;
|
|
111
|
+
export declare function connectNetwork(network?: 'mainnet' | 'testnet' | NetworkPreset, opts?: ConnectNetworkOptions): Promise<Network>;
|
package/dist/esm/network.js
CHANGED
|
@@ -2,6 +2,7 @@ import { NetworkMismatch, VordiumError } from './errors.js';
|
|
|
2
2
|
import { fetchTransport } from './http.js';
|
|
3
3
|
import { genesisHex } from './domains.js';
|
|
4
4
|
import { PINS, PinMismatch, UnpinnedNetwork, checkPin, pinDifferences, pinRefusal } from './pins.js';
|
|
5
|
+
import { RELEASE_RECORD_URLS, RecordRefused, pinnedKeys, readRecord } from './releaseRecord.js';
|
|
5
6
|
export const NETWORKS = {
|
|
6
7
|
mainnet: {
|
|
7
8
|
name: 'mainnet',
|
|
@@ -20,6 +21,81 @@ export const NETWORKS = {
|
|
|
20
21
|
feeds: 'wss://testnet.vordex.xyz/chain/feeds',
|
|
21
22
|
},
|
|
22
23
|
};
|
|
24
|
+
/** How long a network's release record is used before it is read again (ms), and how soon a refused one is retried. */
|
|
25
|
+
export const RECORD_TTL_MS = 300_000;
|
|
26
|
+
export const RECORD_RETRY_MS = 30_000;
|
|
27
|
+
/**
|
|
28
|
+
* Read the network's release record again when it has expired, when it is older than {@link RECORD_TTL_MS}, or when it
|
|
29
|
+
* was refused more than {@link RECORD_RETRY_MS} ago. A client calls it before every signature; {@link signingPin} then
|
|
30
|
+
* judges the record as it is now.
|
|
31
|
+
*/
|
|
32
|
+
export async function refreshRecord(net, opts = {}) {
|
|
33
|
+
const l = net.recordLive;
|
|
34
|
+
if (!l)
|
|
35
|
+
return;
|
|
36
|
+
const now = l.read.now ?? Date.now;
|
|
37
|
+
const age = Date.now() - l.at;
|
|
38
|
+
const due = (l.record && (now() / 1000 > l.record.record.validUntil || age >= (opts.ttlMs ?? RECORD_TTL_MS)))
|
|
39
|
+
|| (l.problem !== null && age >= (opts.retryMs ?? RECORD_RETRY_MS));
|
|
40
|
+
if (!due)
|
|
41
|
+
return;
|
|
42
|
+
try {
|
|
43
|
+
l.record = await readRecord(l.chainId, l.urls, l.keys, l.read);
|
|
44
|
+
l.problem = null;
|
|
45
|
+
}
|
|
46
|
+
catch (e) {
|
|
47
|
+
if (!(e instanceof RecordRefused))
|
|
48
|
+
throw e;
|
|
49
|
+
l.record = null;
|
|
50
|
+
l.problem = `${e.message} Nothing was signed.`;
|
|
51
|
+
}
|
|
52
|
+
if (!l.record && !l.problem && l.byChain)
|
|
53
|
+
l.problem = noRecordText(l.chainId);
|
|
54
|
+
l.at = Date.now();
|
|
55
|
+
}
|
|
56
|
+
const noRecordText = (chainId) => `Refusing to sign: no signed release record lists chain ${chainId}, and a network named only by its chain id needs one. Nothing was signed.`;
|
|
57
|
+
/** The pin from the network's release record as last read (throws when it cannot be used), or null when no record is
|
|
58
|
+
* served and none was used for the network (then its pin applies). */
|
|
59
|
+
function recordSigningPin(net, l) {
|
|
60
|
+
const now = l.read.now ?? Date.now;
|
|
61
|
+
let problem = l.problem;
|
|
62
|
+
if (!problem && l.record && now() / 1000 > l.record.record.validUntil)
|
|
63
|
+
problem = `The signed release record expired; it is read again before the next signature. Nothing was signed.`;
|
|
64
|
+
if (!problem && !l.record && net.record)
|
|
65
|
+
problem = 'Refusing to sign: the signed release record this network was checked against is not served now. Nothing was signed.';
|
|
66
|
+
if (problem)
|
|
67
|
+
throw l.byChain ? new UnpinnedNetwork(problem) : new PinMismatch(problem);
|
|
68
|
+
let pin;
|
|
69
|
+
if (!l.record) {
|
|
70
|
+
if (!net.recordProblem)
|
|
71
|
+
return null;
|
|
72
|
+
const named = presetPinOrNull({ ...net, pin: undefined });
|
|
73
|
+
if (!named)
|
|
74
|
+
throw new UnpinnedNetwork(net.recordProblem);
|
|
75
|
+
pin = named;
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
pin = Object.freeze({ ...(net.name ? { name: net.name } : {}), chainId: l.record.entry.chainId, genesis: l.record.entry.genesis });
|
|
79
|
+
}
|
|
80
|
+
const same = !!(net.record && l.record && net.record.entry.genesis === l.record.entry.genesis);
|
|
81
|
+
if (same && net.pinProblem)
|
|
82
|
+
throw new PinMismatch(net.pinProblem);
|
|
83
|
+
const d = pinDifferences(pin, { 'the network': net.chainId }, { 'the network': net.genesis });
|
|
84
|
+
if (l.record && l.record.entry.retiredGenesis.includes(net.genesis)) {
|
|
85
|
+
d.unshift(`the node serves genesis ${net.genesis}, which the signed release record lists in retired_genesis for chain ${l.record.entry.chainId}`);
|
|
86
|
+
}
|
|
87
|
+
if (d.length)
|
|
88
|
+
throw new PinMismatch(pinRefusal(pin, d));
|
|
89
|
+
return pin;
|
|
90
|
+
}
|
|
91
|
+
function presetPinOrNull(p) {
|
|
92
|
+
try {
|
|
93
|
+
return presetPin(p);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
23
99
|
/** The pin a preset is held to: its own `pin`, else the pin of the named network it names; null when it has none. */
|
|
24
100
|
export function presetPin(p) {
|
|
25
101
|
const named = Object.prototype.hasOwnProperty.call(PINS, p.name) ? PINS[p.name] : undefined;
|
|
@@ -37,7 +113,14 @@ export function presetPin(p) {
|
|
|
37
113
|
* `PinMismatch` when what it reported differs from the pin; nothing may be signed then.
|
|
38
114
|
*/
|
|
39
115
|
export function signingPin(net) {
|
|
40
|
-
|
|
116
|
+
if (net.recordLive) {
|
|
117
|
+
const live = recordSigningPin(net, net.recordLive);
|
|
118
|
+
if (live)
|
|
119
|
+
return live;
|
|
120
|
+
}
|
|
121
|
+
if (net.recordProblem)
|
|
122
|
+
throw net.record || presetPinOrNull(net) ? new PinMismatch(net.recordProblem) : new UnpinnedNetwork(net.recordProblem);
|
|
123
|
+
const pin = net.record && net.pin ? net.pin : presetPin(net);
|
|
41
124
|
if (net.pinProblem)
|
|
42
125
|
throw pin ? new PinMismatch(net.pinProblem) : new UnpinnedNetwork(net.pinProblem);
|
|
43
126
|
if (!pin)
|
|
@@ -105,17 +188,48 @@ async function rpcChainId(rpc, transport, timeoutMs) {
|
|
|
105
188
|
* `eth_chainId` name the same chain id, the spec and the node the same genesis, and the spec's `testnet` flag matches
|
|
106
189
|
* the preset (a test network never stands in for the main network, nor the reverse).
|
|
107
190
|
*
|
|
108
|
-
* The
|
|
109
|
-
*
|
|
110
|
-
*
|
|
191
|
+
* The network's identity comes from the signed release record when one is served (its genesis for the network's chain
|
|
192
|
+
* id; see `readRecord`), else from its pin. When the reports differ (or the network has no identity, or the served
|
|
193
|
+
* record cannot be used) the connection still reads, `pinProblem` says why, `onPinProblem` (when given) is called with
|
|
194
|
+
* it, and every signature is refused (`PinMismatch` / `UnpinnedNetwork`). The SDK prints nothing.
|
|
111
195
|
*/
|
|
112
196
|
export async function connectNetwork(network = 'testnet', opts = {}) {
|
|
113
197
|
const p = typeof network === 'string' ? NETWORKS[network] : network;
|
|
114
198
|
if (!p)
|
|
115
199
|
throw new VordiumError('unknown_network', `Unknown network ${String(network)}; known: mainnet, testnet.`);
|
|
116
|
-
const
|
|
200
|
+
const named = Object.prototype.hasOwnProperty.call(PINS, p.name) ? PINS[p.name] : undefined;
|
|
201
|
+
if (p.recordChainId !== undefined && (!Number.isSafeInteger(p.recordChainId) || p.recordChainId <= 0 || p.pin || named)) {
|
|
202
|
+
throw new VordiumError('unknown_network', 'recordChainId names a network only the signed release record lists: give a positive chain id, with no pin and a name that is not mainnet or testnet.');
|
|
203
|
+
}
|
|
204
|
+
const hardPin = presetPin(p);
|
|
117
205
|
const t = opts.transport ?? fetchTransport;
|
|
118
206
|
const ms = opts.timeoutMs ?? 10000;
|
|
207
|
+
// The identity: the signed record's for a named network or a record-only chain id; an explicit pin of your own skips it.
|
|
208
|
+
const recordChain = p.recordChainId ?? (named ? named.chainId : null);
|
|
209
|
+
let record = null;
|
|
210
|
+
let recordProblem = null;
|
|
211
|
+
let recordLive;
|
|
212
|
+
if (recordChain !== null) {
|
|
213
|
+
const urls = p.releaseRecord ? [p.releaseRecord]
|
|
214
|
+
: p.recordChainId !== undefined ? Object.values(RELEASE_RECORD_URLS).flat() // a chain only the record names: every address
|
|
215
|
+
: RELEASE_RECORD_URLS[p.name] ?? [];
|
|
216
|
+
const read = { transport: t, timeoutMs: ms, store: opts.releaseRecordStore, now: opts.releaseRecordNow };
|
|
217
|
+
try {
|
|
218
|
+
const keys = pinnedKeys(opts.releaseKeys);
|
|
219
|
+
recordLive = { chainId: recordChain, urls, keys, byChain: p.recordChainId !== undefined, read, record: null, problem: null, at: Date.now() };
|
|
220
|
+
record = await readRecord(recordChain, urls, keys, read);
|
|
221
|
+
}
|
|
222
|
+
catch (e) {
|
|
223
|
+
if (!(e instanceof RecordRefused))
|
|
224
|
+
throw e;
|
|
225
|
+
recordProblem = `${e.message} Nothing was signed.`;
|
|
226
|
+
}
|
|
227
|
+
if (!record && !recordProblem && p.recordChainId !== undefined)
|
|
228
|
+
recordProblem = noRecordText(p.recordChainId);
|
|
229
|
+
if (recordLive)
|
|
230
|
+
Object.assign(recordLive, { record, problem: recordProblem, at: Date.now() });
|
|
231
|
+
}
|
|
232
|
+
const pin = record ? Object.freeze({ ...(p.name ? { name: p.name } : {}), chainId: recordChain, genesis: record.entry.genesis }) : hardPin;
|
|
119
233
|
const sr = await t.get(p.spec, ms);
|
|
120
234
|
if (sr.status !== 200 || !sr.body || typeof sr.body !== 'object')
|
|
121
235
|
throw new VordiumError('no_spec', `The network spec at ${p.spec} could not be read.`);
|
|
@@ -142,16 +256,19 @@ export async function connectNetwork(network = 'testnet', opts = {}) {
|
|
|
142
256
|
if (specGenesis !== null && specGenesis !== ident.genesis) {
|
|
143
257
|
throw new NetworkMismatch(`The spec names genesis ${specGenesis.slice(0, 8)}…, the node ${ident.genesis.slice(0, 8)}…; refusing to sign.`);
|
|
144
258
|
}
|
|
145
|
-
let pinProblem =
|
|
146
|
-
if (!pin) {
|
|
259
|
+
let pinProblem = recordProblem;
|
|
260
|
+
if (!pinProblem && !pin) {
|
|
147
261
|
pinProblem = unpinnedText(p);
|
|
148
262
|
}
|
|
149
|
-
else {
|
|
263
|
+
else if (!pinProblem && pin) {
|
|
150
264
|
const d = 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 });
|
|
265
|
+
if (record && record.entry.retiredGenesis.includes(ident.genesis)) {
|
|
266
|
+
d.unshift(`the node serves genesis ${ident.genesis}, which the signed release record lists in retired_genesis for chain ${record.entry.chainId}`);
|
|
267
|
+
}
|
|
151
268
|
if (d.length)
|
|
152
269
|
pinProblem = pinRefusal(pin, d);
|
|
153
270
|
}
|
|
154
271
|
if (pinProblem && opts.onPinProblem)
|
|
155
272
|
opts.onPinProblem(pinProblem);
|
|
156
|
-
return { ...p, ...(pin ? { pin } : {}), chainId: ident.chainId, genesis: ident.genesis, specRead: spec, pinProblem };
|
|
273
|
+
return { ...p, ...(pin ? { pin } : {}), chainId: ident.chainId, genesis: ident.genesis, specRead: spec, pinProblem, record, recordProblem, ...(recordLive ? { recordLive } : {}) };
|
|
157
274
|
}
|
package/dist/esm/nonce.d.ts
CHANGED
|
@@ -47,9 +47,11 @@ export interface NonceStore {
|
|
|
47
47
|
/** Writes what `fn` returns when it differs from the mark (the allocator keeps it rising). `fn` may be called more
|
|
48
48
|
* than once in one update (a value already taken, a lock lost); the value kept is its last call's, and `taken` is
|
|
49
49
|
* the value its previous call returned when that one was already taken. `unique` (default true): every value
|
|
50
|
-
* written is one no other caller received; false for a record that is not a nonce.
|
|
50
|
+
* written is one no other caller received; false for a record that is not a nonce. `strict`: a mark that cannot be
|
|
51
|
+
* read throws (`state_unreadable`) instead of reading as 0. */
|
|
51
52
|
update(key: string, fn: (last: number, taken?: number) => number, opts?: {
|
|
52
53
|
unique?: boolean;
|
|
54
|
+
strict?: boolean;
|
|
53
55
|
}): Promise<number>;
|
|
54
56
|
/** Where the mark of `key` lives, for a message (a file path), or null. */
|
|
55
57
|
where?(key: string): string | null;
|
package/dist/esm/nonce.js
CHANGED
|
@@ -268,12 +268,16 @@ export function fileNonceStore(dir, opts = {}) {
|
|
|
268
268
|
let done = null;
|
|
269
269
|
try {
|
|
270
270
|
let last = 0;
|
|
271
|
+
let text = null;
|
|
271
272
|
try {
|
|
272
|
-
|
|
273
|
-
if (/^\d+$/.test(t))
|
|
274
|
-
last = Number(t);
|
|
273
|
+
text = (await fs.readFile(file, 'utf8')).trim();
|
|
275
274
|
}
|
|
276
275
|
catch { /* no mark yet */ }
|
|
276
|
+
if (text !== null && /^\d+$/.test(text))
|
|
277
|
+
last = Number(text);
|
|
278
|
+
else if (text !== null && opts?.strict) {
|
|
279
|
+
throw new VordiumError('state_unreadable', `The mark in ${file} cannot be read. Check the file, or remove it to start again.`);
|
|
280
|
+
}
|
|
277
281
|
let n = last, claimed = false, seen = [];
|
|
278
282
|
if (!unique)
|
|
279
283
|
n = fn(last); // a record, not a nonce
|
package/dist/esm/pins.d.ts
CHANGED
|
@@ -3,7 +3,9 @@ import { NetworkMismatch } from './errors.js';
|
|
|
3
3
|
* The identity each named network is pinned to: its chain id and its genesis sha256. These values are part of the SDK.
|
|
4
4
|
* Before anything is signed, the SDK compares the pin with what the network reports (the network spec, the node's
|
|
5
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.
|
|
6
|
+
* from the pin. When the signed release record is served (`releaseRecord.ts`: `releases.json` with its detached signature
|
|
7
|
+
* by the release key), a named network's genesis comes from it instead, so a new genesis listed there needs no new SDK
|
|
8
|
+
* release. These pins apply while no record is served.
|
|
7
9
|
*/
|
|
8
10
|
export interface Pin {
|
|
9
11
|
/** "mainnet" or "testnet" for a named network; absent for a pin you give. */
|