@vordium/sdk 0.2.1 → 0.3.0
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 +31 -5
- package/dist/cjs/client.js +257 -52
- package/dist/cjs/http.js +46 -0
- package/dist/cjs/index.js +6 -1
- package/dist/cjs/network.js +150 -10
- package/dist/cjs/nonce.js +7 -3
- package/dist/cjs/outcome.js +649 -0
- package/dist/cjs/outcomeWords.js +172 -0
- package/dist/cjs/pins.js +5 -0
- package/dist/cjs/releaseRecord.js +870 -0
- package/dist/cjs/types.js +2 -1
- package/dist/esm/client.d.ts +92 -9
- package/dist/esm/client.js +257 -52
- package/dist/esm/http.d.ts +6 -0
- package/dist/esm/http.js +46 -0
- package/dist/esm/index.d.ts +4 -1
- package/dist/esm/index.js +4 -1
- package/dist/esm/network.d.ts +66 -12
- package/dist/esm/network.js +148 -9
- package/dist/esm/nonce.d.ts +3 -1
- package/dist/esm/nonce.js +7 -3
- package/dist/esm/outcome.d.ts +201 -0
- package/dist/esm/outcome.js +623 -0
- package/dist/esm/outcomeWords.d.ts +168 -0
- package/dist/esm/outcomeWords.js +169 -0
- package/dist/esm/pins.d.ts +8 -1
- package/dist/esm/pins.js +5 -0
- package/dist/esm/releaseRecord.d.ts +147 -0
- package/dist/esm/releaseRecord.js +856 -0
- package/dist/esm/types.d.ts +1 -0
- package/dist/esm/types.js +2 -1
- package/package.json +3 -1
package/dist/esm/http.js
CHANGED
|
@@ -26,6 +26,32 @@ async function readBody(r) {
|
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
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
|
+
}
|
|
29
55
|
const isRedirect = (status) => status >= 300 && status < 400;
|
|
30
56
|
/** What a redirect answer reads as: never the redirect's own body. */
|
|
31
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.' });
|
|
@@ -55,6 +81,26 @@ export const fetchTransport = {
|
|
|
55
81
|
}
|
|
56
82
|
throw new VordiumError('unreachable', `The node at ${url} did not answer.`, String(last?.message ?? last));
|
|
57
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) };
|
|
95
|
+
}
|
|
96
|
+
catch (e) {
|
|
97
|
+
last = e;
|
|
98
|
+
if (attempt < 2)
|
|
99
|
+
await sleep(250 * 2 ** attempt * (0.5 + Math.random() / 2));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
throw new VordiumError('unreachable', `The node at ${url} did not answer.`, String(last?.message ?? last));
|
|
103
|
+
},
|
|
58
104
|
async post(url, body, timeoutMs) {
|
|
59
105
|
const r = await fetchWithTimeout(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body }, timeoutMs);
|
|
60
106
|
// a redirect is not an answer about the write: no body is read from it
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export * from './types.js';
|
|
|
5
5
|
export * from './sign.js';
|
|
6
6
|
export * from './network.js';
|
|
7
7
|
export * from './pins.js';
|
|
8
|
+
export * from './releaseRecord.js';
|
|
8
9
|
export * from './nonce.js';
|
|
9
10
|
export * from './resend.js';
|
|
10
11
|
export * from './units.js';
|
|
@@ -15,4 +16,6 @@ export * from './agents.js';
|
|
|
15
16
|
export * from './reads.js';
|
|
16
17
|
export * from './feeds.js';
|
|
17
18
|
export * from './builder.js';
|
|
18
|
-
export { Vordium, Account, twapOnSteps, matchesSigned, twapMatches, cancelOutcome, type Result, type ConnectOptions, type SignedOrder } from './client.js';
|
|
19
|
+
export { Vordium, Account, twapOnSteps, matchesSigned, twapMatches, cancelOutcome, STOP_ALL_AHEAD_S, type Result, type Checked, type ConnectOptions, type SignedOrder } from './client.js';
|
|
20
|
+
export * from './outcome.js';
|
|
21
|
+
export { OUTCOME_WORDS } from './outcomeWords.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -5,6 +5,7 @@ export * from './types.js';
|
|
|
5
5
|
export * from './sign.js';
|
|
6
6
|
export * from './network.js';
|
|
7
7
|
export * from './pins.js';
|
|
8
|
+
export * from './releaseRecord.js';
|
|
8
9
|
export * from './nonce.js';
|
|
9
10
|
export * from './resend.js';
|
|
10
11
|
export * from './units.js';
|
|
@@ -15,4 +16,6 @@ export * from './agents.js';
|
|
|
15
16
|
export * from './reads.js';
|
|
16
17
|
export * from './feeds.js';
|
|
17
18
|
export * from './builder.js';
|
|
18
|
-
export { Vordium, Account, twapOnSteps, matchesSigned, twapMatches, cancelOutcome } from './client.js';
|
|
19
|
+
export { Vordium, Account, twapOnSteps, matchesSigned, twapMatches, cancelOutcome, STOP_ALL_AHEAD_S } from './client.js';
|
|
20
|
+
export * from './outcome.js';
|
|
21
|
+
export { OUTCOME_WORDS } from './outcomeWords.js';
|
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,43 @@ 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
|
+
/** The code of `recordProblem` (`expired`, `rollback`, `not_served`, `unsigned`, `bad_signature`, `not_listed`, …). */
|
|
46
|
+
recordProblemCode?: string | null;
|
|
47
|
+
/** Where the record is read again, and the record as last read: signing uses the record as it is now (see
|
|
48
|
+
* {@link refreshRecord}). Absent for a network with a pin of its own. */
|
|
49
|
+
recordLive?: RecordLive;
|
|
33
50
|
}
|
|
51
|
+
/** How a connected network's release record is read again, and what was last read. */
|
|
52
|
+
export interface RecordLive {
|
|
53
|
+
chainId: number;
|
|
54
|
+
urls: readonly string[];
|
|
55
|
+
keys: readonly PublicKey[];
|
|
56
|
+
byChain: boolean;
|
|
57
|
+
read: ReadRecordOptions;
|
|
58
|
+
record: VerifiedRecord | null;
|
|
59
|
+
problem: string | null;
|
|
60
|
+
/** The code of `problem`. */
|
|
61
|
+
code?: string | null;
|
|
62
|
+
/** Date.now() when it was read. */
|
|
63
|
+
at: number;
|
|
64
|
+
}
|
|
65
|
+
/** How long a network's release record is used before it is read again (ms), and how soon a refused one is retried. */
|
|
66
|
+
export declare const RECORD_TTL_MS = 300000;
|
|
67
|
+
export declare const RECORD_RETRY_MS = 30000;
|
|
68
|
+
/**
|
|
69
|
+
* Read the network's release record again when it has expired, when it is older than {@link RECORD_TTL_MS}, or when it
|
|
70
|
+
* was refused more than {@link RECORD_RETRY_MS} ago. A client calls it before every signature; {@link signingPin} then
|
|
71
|
+
* judges the record as it is now.
|
|
72
|
+
*/
|
|
73
|
+
export declare function refreshRecord(net: Network, opts?: {
|
|
74
|
+
ttlMs?: number;
|
|
75
|
+
retryMs?: number;
|
|
76
|
+
}): Promise<void>;
|
|
34
77
|
/** 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
78
|
export declare function presetPin(p: NetworkPreset): Pin | null;
|
|
36
79
|
/**
|
|
@@ -47,17 +90,28 @@ export declare function readIdentity(status: unknown): NodeIdentity;
|
|
|
47
90
|
/** Where a node's `/status` is read: under the API's own path first, then at the host root. */
|
|
48
91
|
export declare function statusUrls(api: string): string[];
|
|
49
92
|
export declare function nodeIdentity(api: string, transport?: Transport, timeoutMs?: number): Promise<NodeIdentity>;
|
|
93
|
+
/** Options of {@link connectNetwork}. `releaseKeys`, `releaseRecordStore` and `releaseRecordNow` are for tests only. */
|
|
94
|
+
export interface ConnectNetworkOptions {
|
|
95
|
+
transport?: Transport;
|
|
96
|
+
timeoutMs?: number;
|
|
97
|
+
onPinProblem?: (message: string) => void;
|
|
98
|
+
/** Tests only: armoured OpenPGP public keys that replace the shipped release key. */
|
|
99
|
+
releaseKeys?: readonly string[];
|
|
100
|
+
/** Where the highest record sequence seen is kept (default: the nonce store). */
|
|
101
|
+
releaseRecordStore?: NonceStore;
|
|
102
|
+
/** Tests only: this computer's clock in milliseconds. */
|
|
103
|
+
releaseRecordNow?: () => number;
|
|
104
|
+
/** Tests only: the lowest record sequence accepted per chain id, instead of `MIN_RECORD_SEQUENCE`. */
|
|
105
|
+
releaseRecordMinSequence?: Readonly<Record<number, number>>;
|
|
106
|
+
}
|
|
50
107
|
/**
|
|
51
108
|
* Read and check a network. Refuses (NetworkMismatch, nothing signed) unless the spec, the node's `/status` and
|
|
52
109
|
* `eth_chainId` name the same chain id, the spec and the node the same genesis, and the spec's `testnet` flag matches
|
|
53
110
|
* the preset (a test network never stands in for the main network, nor the reverse).
|
|
54
111
|
*
|
|
55
|
-
* The
|
|
56
|
-
*
|
|
57
|
-
*
|
|
112
|
+
* The network's identity comes from the signed release record when one is served (its genesis for the network's chain
|
|
113
|
+
* id; see `readRecord`), else from its pin. When the reports differ (or the network has no identity, or the served
|
|
114
|
+
* record cannot be used) the connection still reads, `pinProblem` says why, `onPinProblem` (when given) is called with
|
|
115
|
+
* it, and every signature is refused (`PinMismatch` / `UnpinnedNetwork`). The SDK prints nothing.
|
|
58
116
|
*/
|
|
59
|
-
export declare function connectNetwork(network?: 'mainnet' | 'testnet' | NetworkPreset, opts?:
|
|
60
|
-
transport?: Transport;
|
|
61
|
-
timeoutMs?: number;
|
|
62
|
-
onPinProblem?: (message: string) => void;
|
|
63
|
-
}): Promise<Network>;
|
|
117
|
+
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,96 @@ 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
|
+
l.code = null;
|
|
46
|
+
}
|
|
47
|
+
catch (e) {
|
|
48
|
+
if (!(e instanceof RecordRefused))
|
|
49
|
+
throw e;
|
|
50
|
+
l.record = null;
|
|
51
|
+
l.problem = withNothing(e.message);
|
|
52
|
+
l.code = e.code;
|
|
53
|
+
}
|
|
54
|
+
if (!l.record && !l.problem && l.byChain) {
|
|
55
|
+
l.problem = noRecordText(l.chainId);
|
|
56
|
+
l.code = 'not_listed';
|
|
57
|
+
}
|
|
58
|
+
l.at = Date.now();
|
|
59
|
+
}
|
|
60
|
+
/** A record refusal's sentence, saying once that nothing was signed. */
|
|
61
|
+
const withNothing = (m) => (/Nothing (is|was) signed/.test(m) ? m : `${m} Nothing was signed.`);
|
|
62
|
+
/** The error for a record problem: a `PinMismatch` (or `UnpinnedNetwork` for a network named only by its chain id) whose
|
|
63
|
+
* `recordCode` names why. */
|
|
64
|
+
function recordError(message, code, unpinned) {
|
|
65
|
+
return Object.assign(unpinned ? new UnpinnedNetwork(message) : new PinMismatch(message), { recordCode: code ?? null });
|
|
66
|
+
}
|
|
67
|
+
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.`;
|
|
68
|
+
/** The pin from the network's release record as last read (throws when it cannot be used), or null when no record is
|
|
69
|
+
* served and none was used for the network (then its pin applies). */
|
|
70
|
+
function recordSigningPin(net, l) {
|
|
71
|
+
const now = l.read.now ?? Date.now;
|
|
72
|
+
let problem = l.problem, code = l.code ?? null;
|
|
73
|
+
if (!problem && l.record && now() / 1000 > l.record.record.validUntil) {
|
|
74
|
+
problem = "The signed release record expired; it is read again before the next signature. Nothing was signed. Try again later; if this persists, check this computer's clock.";
|
|
75
|
+
code = 'expired';
|
|
76
|
+
}
|
|
77
|
+
if (!problem && !l.record && net.record) {
|
|
78
|
+
problem = 'Refusing to sign: the signed release record this network was checked against is not served now. Nothing was signed.';
|
|
79
|
+
code = 'not_served';
|
|
80
|
+
}
|
|
81
|
+
if (problem)
|
|
82
|
+
throw recordError(problem, code, l.byChain);
|
|
83
|
+
let pin;
|
|
84
|
+
if (!l.record) {
|
|
85
|
+
if (!net.recordProblem)
|
|
86
|
+
return null;
|
|
87
|
+
const named = presetPinOrNull({ ...net, pin: undefined });
|
|
88
|
+
if (!named)
|
|
89
|
+
throw recordError(net.recordProblem, net.recordProblemCode, true);
|
|
90
|
+
pin = named;
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
pin = Object.freeze({ ...(net.name ? { name: net.name } : {}), chainId: l.record.entry.chainId, genesis: l.record.entry.genesis });
|
|
94
|
+
}
|
|
95
|
+
const same = !!(net.record && l.record && net.record.entry.genesis === l.record.entry.genesis);
|
|
96
|
+
if (same && net.pinProblem)
|
|
97
|
+
throw new PinMismatch(net.pinProblem);
|
|
98
|
+
const d = pinDifferences(pin, { 'the network': net.chainId }, { 'the network': net.genesis });
|
|
99
|
+
if (l.record && l.record.entry.retiredGenesis.includes(net.genesis)) {
|
|
100
|
+
d.unshift(`the node serves genesis ${net.genesis}, which the signed release record lists in retired_genesis for chain ${l.record.entry.chainId}`);
|
|
101
|
+
}
|
|
102
|
+
if (d.length)
|
|
103
|
+
throw new PinMismatch(pinRefusal(pin, d));
|
|
104
|
+
return pin;
|
|
105
|
+
}
|
|
106
|
+
function presetPinOrNull(p) {
|
|
107
|
+
try {
|
|
108
|
+
return presetPin(p);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
23
114
|
/** 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
115
|
export function presetPin(p) {
|
|
25
116
|
const named = Object.prototype.hasOwnProperty.call(PINS, p.name) ? PINS[p.name] : undefined;
|
|
@@ -37,7 +128,14 @@ export function presetPin(p) {
|
|
|
37
128
|
* `PinMismatch` when what it reported differs from the pin; nothing may be signed then.
|
|
38
129
|
*/
|
|
39
130
|
export function signingPin(net) {
|
|
40
|
-
|
|
131
|
+
if (net.recordLive) {
|
|
132
|
+
const live = recordSigningPin(net, net.recordLive);
|
|
133
|
+
if (live)
|
|
134
|
+
return live;
|
|
135
|
+
}
|
|
136
|
+
if (net.recordProblem)
|
|
137
|
+
throw recordError(net.recordProblem, net.recordProblemCode, !(net.record || presetPinOrNull(net)));
|
|
138
|
+
const pin = net.record && net.pin ? net.pin : presetPin(net);
|
|
41
139
|
if (net.pinProblem)
|
|
42
140
|
throw pin ? new PinMismatch(net.pinProblem) : new UnpinnedNetwork(net.pinProblem);
|
|
43
141
|
if (!pin)
|
|
@@ -105,17 +203,52 @@ async function rpcChainId(rpc, transport, timeoutMs) {
|
|
|
105
203
|
* `eth_chainId` name the same chain id, the spec and the node the same genesis, and the spec's `testnet` flag matches
|
|
106
204
|
* the preset (a test network never stands in for the main network, nor the reverse).
|
|
107
205
|
*
|
|
108
|
-
* The
|
|
109
|
-
*
|
|
110
|
-
*
|
|
206
|
+
* The network's identity comes from the signed release record when one is served (its genesis for the network's chain
|
|
207
|
+
* id; see `readRecord`), else from its pin. When the reports differ (or the network has no identity, or the served
|
|
208
|
+
* record cannot be used) the connection still reads, `pinProblem` says why, `onPinProblem` (when given) is called with
|
|
209
|
+
* it, and every signature is refused (`PinMismatch` / `UnpinnedNetwork`). The SDK prints nothing.
|
|
111
210
|
*/
|
|
112
211
|
export async function connectNetwork(network = 'testnet', opts = {}) {
|
|
113
212
|
const p = typeof network === 'string' ? NETWORKS[network] : network;
|
|
114
213
|
if (!p)
|
|
115
214
|
throw new VordiumError('unknown_network', `Unknown network ${String(network)}; known: mainnet, testnet.`);
|
|
116
|
-
const
|
|
215
|
+
const named = Object.prototype.hasOwnProperty.call(PINS, p.name) ? PINS[p.name] : undefined;
|
|
216
|
+
if (p.recordChainId !== undefined && (!Number.isSafeInteger(p.recordChainId) || p.recordChainId <= 0 || p.pin || named)) {
|
|
217
|
+
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.');
|
|
218
|
+
}
|
|
219
|
+
const hardPin = presetPin(p);
|
|
117
220
|
const t = opts.transport ?? fetchTransport;
|
|
118
221
|
const ms = opts.timeoutMs ?? 10000;
|
|
222
|
+
// The identity: the signed record's for a named network or a record-only chain id; an explicit pin of your own skips it.
|
|
223
|
+
const recordChain = p.recordChainId ?? (named ? named.chainId : null);
|
|
224
|
+
let record = null;
|
|
225
|
+
let recordProblem = null;
|
|
226
|
+
let recordProblemCode = null;
|
|
227
|
+
let recordLive;
|
|
228
|
+
if (recordChain !== null) {
|
|
229
|
+
const urls = p.releaseRecord ? [p.releaseRecord]
|
|
230
|
+
: p.recordChainId !== undefined ? Object.values(RELEASE_RECORD_URLS).flat() // a chain only the record names: every address
|
|
231
|
+
: RELEASE_RECORD_URLS[p.name] ?? [];
|
|
232
|
+
const read = { transport: t, timeoutMs: ms, store: opts.releaseRecordStore, now: opts.releaseRecordNow, minSequence: opts.releaseRecordMinSequence };
|
|
233
|
+
try {
|
|
234
|
+
const keys = pinnedKeys(opts.releaseKeys);
|
|
235
|
+
recordLive = { chainId: recordChain, urls, keys, byChain: p.recordChainId !== undefined, read, record: null, problem: null, at: Date.now() };
|
|
236
|
+
record = await readRecord(recordChain, urls, keys, read);
|
|
237
|
+
}
|
|
238
|
+
catch (e) {
|
|
239
|
+
if (!(e instanceof RecordRefused))
|
|
240
|
+
throw e;
|
|
241
|
+
recordProblem = withNothing(e.message);
|
|
242
|
+
recordProblemCode = e.code;
|
|
243
|
+
}
|
|
244
|
+
if (!record && !recordProblem && p.recordChainId !== undefined) {
|
|
245
|
+
recordProblem = noRecordText(p.recordChainId);
|
|
246
|
+
recordProblemCode = 'not_listed';
|
|
247
|
+
}
|
|
248
|
+
if (recordLive)
|
|
249
|
+
Object.assign(recordLive, { record, problem: recordProblem, code: recordProblemCode, at: Date.now() });
|
|
250
|
+
}
|
|
251
|
+
const pin = record ? Object.freeze({ ...(p.name ? { name: p.name } : {}), chainId: recordChain, genesis: record.entry.genesis }) : hardPin;
|
|
119
252
|
const sr = await t.get(p.spec, ms);
|
|
120
253
|
if (sr.status !== 200 || !sr.body || typeof sr.body !== 'object')
|
|
121
254
|
throw new VordiumError('no_spec', `The network spec at ${p.spec} could not be read.`);
|
|
@@ -142,16 +275,22 @@ export async function connectNetwork(network = 'testnet', opts = {}) {
|
|
|
142
275
|
if (specGenesis !== null && specGenesis !== ident.genesis) {
|
|
143
276
|
throw new NetworkMismatch(`The spec names genesis ${specGenesis.slice(0, 8)}…, the node ${ident.genesis.slice(0, 8)}…; refusing to sign.`);
|
|
144
277
|
}
|
|
145
|
-
let pinProblem =
|
|
146
|
-
if (!pin) {
|
|
278
|
+
let pinProblem = recordProblem;
|
|
279
|
+
if (!pinProblem && !pin) {
|
|
147
280
|
pinProblem = unpinnedText(p);
|
|
148
281
|
}
|
|
149
|
-
else {
|
|
282
|
+
else if (!pinProblem && pin) {
|
|
150
283
|
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 });
|
|
284
|
+
if (record && record.entry.retiredGenesis.includes(ident.genesis)) {
|
|
285
|
+
d.unshift(`the node serves genesis ${ident.genesis}, which the signed release record lists in retired_genesis for chain ${record.entry.chainId}`);
|
|
286
|
+
}
|
|
151
287
|
if (d.length)
|
|
152
288
|
pinProblem = pinRefusal(pin, d);
|
|
289
|
+
if (d.length && !record && recordChain !== null && d.some((x) => x.includes('genesis'))) {
|
|
290
|
+
pinProblem += " The signed release record could not be read, so the SDK's own pin was used: if this network has moved to a new genesis, try again once the record can be read.";
|
|
291
|
+
}
|
|
153
292
|
}
|
|
154
293
|
if (pinProblem && opts.onPinProblem)
|
|
155
294
|
opts.onPinProblem(pinProblem);
|
|
156
|
-
return { ...p, ...(pin ? { pin } : {}), chainId: ident.chainId, genesis: ident.genesis, specRead: spec, pinProblem };
|
|
295
|
+
return { ...p, ...(pin ? { pin } : {}), chainId: ident.chainId, genesis: ident.genesis, specRead: spec, pinProblem, record, recordProblem, recordProblemCode, ...(recordLive ? { recordLive } : {}) };
|
|
157
296
|
}
|
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
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { OUTCOME_WORDS } from './outcomeWords.js';
|
|
2
|
+
import { type SignedOrder } from './client.js';
|
|
3
|
+
export type OutcomeAction = keyof typeof OUTCOME_WORDS.actions;
|
|
4
|
+
export type OutcomeState = 'pending_checking' | 'applied' | 'applied_other' | 'refused' | 'not_applied' | 'still_unknown';
|
|
5
|
+
/** How long after the send an outcome is checked before it is called `still_unknown`. */
|
|
6
|
+
export declare const LIMIT_MS: number;
|
|
7
|
+
/** How long a call waits for the outcome before it returns `pending_checking` (0 returns at once). */
|
|
8
|
+
export declare const SETTLE_MS = 30000;
|
|
9
|
+
/** The time limit of each read while checking. */
|
|
10
|
+
export declare const READ_TIMEOUT_MS = 6000;
|
|
11
|
+
/** How many of the account's latest records are read (the records have no filter by client nonce). */
|
|
12
|
+
export declare const RECORDS_LIMIT = 200;
|
|
13
|
+
/** A deadline counts as passed only this long after it, on the network's clock (seconds). */
|
|
14
|
+
export declare const DEADLINE_GRACE_S = 10;
|
|
15
|
+
/** Milliseconds to the next read: 1 s for the first 10 s, 2 s to 30 s, then 5 s. */
|
|
16
|
+
export declare const intervalMs: (elapsedMs: number) => number;
|
|
17
|
+
type Fill = Record<string, string | number | boolean | null | undefined>;
|
|
18
|
+
/** {text, next} of `action` in `state`, the placeholders filled. */
|
|
19
|
+
export declare function say(action: OutcomeAction, state: OutcomeState, fill?: Fill): {
|
|
20
|
+
text: string;
|
|
21
|
+
next: string;
|
|
22
|
+
};
|
|
23
|
+
/** A chain meaning as the end of a sentence ("Not placed: {meaning}."): no closing stop, a lower-case first word. */
|
|
24
|
+
export declare function clause(meaning: unknown): string;
|
|
25
|
+
/** sha256 hex of the exact bytes sent: the same on every copy of one signed write. */
|
|
26
|
+
export declare function bodyDigest(body: string): string;
|
|
27
|
+
export interface OutcomeRead {
|
|
28
|
+
source: 'node';
|
|
29
|
+
route: string | null;
|
|
30
|
+
height: number | null;
|
|
31
|
+
atMs: number;
|
|
32
|
+
}
|
|
33
|
+
export interface Resend {
|
|
34
|
+
allowed: boolean;
|
|
35
|
+
sameBytes: boolean;
|
|
36
|
+
label: string | null;
|
|
37
|
+
why: string;
|
|
38
|
+
}
|
|
39
|
+
/** Where one write stands. `applied` is true for applied / applied_other, false for refused / not_applied, null while it
|
|
40
|
+
* is not known. `read` is the read that decided; `resend` whether the same signed bytes may go again. */
|
|
41
|
+
export interface Outcome {
|
|
42
|
+
action: OutcomeAction;
|
|
43
|
+
state: OutcomeState;
|
|
44
|
+
text: string;
|
|
45
|
+
next: string;
|
|
46
|
+
applied: boolean | null;
|
|
47
|
+
final: boolean;
|
|
48
|
+
refusal: {
|
|
49
|
+
code: string;
|
|
50
|
+
meaning: string | null;
|
|
51
|
+
action: string | null;
|
|
52
|
+
} | null;
|
|
53
|
+
read: OutcomeRead | null;
|
|
54
|
+
resend: Resend;
|
|
55
|
+
nonce: number | null;
|
|
56
|
+
orderId: string | null;
|
|
57
|
+
agent: string | null;
|
|
58
|
+
digest: string | null;
|
|
59
|
+
attempts: number;
|
|
60
|
+
counts: Record<string, number | boolean>;
|
|
61
|
+
}
|
|
62
|
+
export declare function resendRule(action: OutcomeAction, state: OutcomeState): Resend;
|
|
63
|
+
/** One check's finding: `state` a final state or null (not shown yet). */
|
|
64
|
+
export interface View {
|
|
65
|
+
state: OutcomeState | null;
|
|
66
|
+
fill: Fill;
|
|
67
|
+
read: OutcomeRead | null;
|
|
68
|
+
refusal?: Outcome['refusal'];
|
|
69
|
+
still?: Fill;
|
|
70
|
+
/** The word-file key used instead of `still_unknown` once the limit passed (`still_unknown_gone`: the order left the
|
|
71
|
+
* book with no record yet; `still_unknown_unread`: the read that decides did not answer). */
|
|
72
|
+
stillKey?: string;
|
|
73
|
+
found?: Record<string, unknown> | null;
|
|
74
|
+
}
|
|
75
|
+
/** One GET of the node: {status, body}; status null when it failed. */
|
|
76
|
+
export type NodeRead = (path: string) => Promise<{
|
|
77
|
+
status: number | null;
|
|
78
|
+
body: unknown;
|
|
79
|
+
}>;
|
|
80
|
+
/** GET reads of one node; every route read is kept in `routes`. */
|
|
81
|
+
export declare class NodeReads {
|
|
82
|
+
private readonly read;
|
|
83
|
+
readonly routes: string[];
|
|
84
|
+
private codesRead;
|
|
85
|
+
constructor(read: NodeRead);
|
|
86
|
+
get(path: string): Promise<{
|
|
87
|
+
status: number | null;
|
|
88
|
+
body: unknown;
|
|
89
|
+
}>;
|
|
90
|
+
ok(path: string): Promise<unknown>;
|
|
91
|
+
records(owner: string): Promise<{
|
|
92
|
+
recs: Array<Record<string, unknown>> | null;
|
|
93
|
+
cov: Record<string, unknown>;
|
|
94
|
+
}>;
|
|
95
|
+
head(): Promise<number | null>;
|
|
96
|
+
codes(): Promise<Record<string, unknown>>;
|
|
97
|
+
meaning(code: string, agent: boolean): Promise<{
|
|
98
|
+
meaning: string | null;
|
|
99
|
+
action: string | null;
|
|
100
|
+
}>;
|
|
101
|
+
}
|
|
102
|
+
/** Refusal codes that name the nonce: a later copy of OUR write (or another signer's) meets them while an earlier copy
|
|
103
|
+
* applied, so they never prove that our write did not apply. */
|
|
104
|
+
export declare const NONCE_CODES: Set<string>;
|
|
105
|
+
/** Whether the signer of a write is an agent of the account, read once from the node (`/agents/{owner}/{signer}`) and
|
|
106
|
+
* kept only once the read answered: {known, agent address or null}. */
|
|
107
|
+
export declare function signerOf(r: NodeReads, owner: string, signer: string | null, journalId?: string | null): () => Promise<{
|
|
108
|
+
known: boolean;
|
|
109
|
+
agent: string | null;
|
|
110
|
+
}>;
|
|
111
|
+
/** An order by its client nonce: listed with what was signed, its closing or placing record, a refusal record with its
|
|
112
|
+
* nonce, or — for an order with a signed deadline, once it passed and a full read of the records shows nothing —
|
|
113
|
+
* not_applied. */
|
|
114
|
+
export declare function judgeOrder(r: NodeReads, owner: string, clientNonce: number, signed: SignedOrder | null, o?: {
|
|
115
|
+
rewound?: number | null;
|
|
116
|
+
validUntilS?: number | null;
|
|
117
|
+
sentAtMs?: number | null;
|
|
118
|
+
chainMs?: (() => Promise<number | null>) | null;
|
|
119
|
+
agent?: string | null;
|
|
120
|
+
}): Promise<View>;
|
|
121
|
+
/** A cancel: the order no longer listed AND its record says cancelled (applied) or filled (applied_other). */
|
|
122
|
+
export declare function judgeCancel(r: NodeReads, owner: string, orderId: bigint): Promise<View>;
|
|
123
|
+
/** The account's order ids in an `/orders` read (the network's liquidation order left out); null when unreadable. */
|
|
124
|
+
export declare function orderIds(rows: unknown, pairId?: number): string[] | null;
|
|
125
|
+
/** A cancel-all: none of the orders listed before the send is still listed, every one of them has its closing record,
|
|
126
|
+
* and at least one closed as cancelled (applied; applied_other when some filled first). With nothing listed before, or
|
|
127
|
+
* no cancel among the records, nothing shows that the cancel-all applied: it stays not known. */
|
|
128
|
+
export declare function judgeCancelAll(r: NodeReads, owner: string, before: string[] | null, pairId?: number): Promise<View>;
|
|
129
|
+
/** A batch: every place shown (or refused) by its client nonce, and every cancelled order (by id, or by client nonce)
|
|
130
|
+
* no longer listed and closed in the records. Applied only when every action is decided. */
|
|
131
|
+
export declare function judgeBatch(r: NodeReads, owner: string, places: Array<[number, SignedOrder]>, cancels: string[], rewound?: number | null, cancelNonces?: number[], agent?: string | null): Promise<View>;
|
|
132
|
+
/** An agent revoke: the agent's committed record reads `revoked`. */
|
|
133
|
+
export declare function judgeRevoke(r: NodeReads, owner: string, agent: string): Promise<View>;
|
|
134
|
+
/** The session nonce a read names (`nonce`, `last_nonce` or `session_nonce`, the largest), else null. */
|
|
135
|
+
export declare function storedSessionNonce(...reads: unknown[]): number | null;
|
|
136
|
+
/** The stop (StopAllSigners): no trading key (the session read answers "no active session") and no live agent
|
|
137
|
+
* (`/signers` names `app_session` as null and `live_agents` 0); then the open orders decide applied (none) or
|
|
138
|
+
* applied_other (orders the wallet placed itself stay). Past its deadline with a key or an agent still live, and the
|
|
139
|
+
* stored session nonce still below the stop's `nonce`: not_applied. */
|
|
140
|
+
export declare function judgeStop(r: NodeReads, owner: string, validUntilS?: number | null, chainMs?: (() => Promise<number | null>) | null, nonce?: number | null): Promise<View>;
|
|
141
|
+
/** The clock the checks run on (tests replace it with a virtual one). */
|
|
142
|
+
export declare const outcomeClock: {
|
|
143
|
+
now: () => number;
|
|
144
|
+
sleep: (ms: number) => Promise<void>;
|
|
145
|
+
};
|
|
146
|
+
export interface PendingMeta {
|
|
147
|
+
nonce?: number | null;
|
|
148
|
+
orderId?: string | null;
|
|
149
|
+
agent?: string | null;
|
|
150
|
+
digest?: string | null;
|
|
151
|
+
attempts?: number;
|
|
152
|
+
}
|
|
153
|
+
/** A sent write whose outcome is being read: `check()` reads once, `wait()` reads until a final or a time limit,
|
|
154
|
+
* `resendSame()` sends the same signed bytes again (only where the network applies the write once). */
|
|
155
|
+
export declare class PendingWrite {
|
|
156
|
+
readonly action: OutcomeAction;
|
|
157
|
+
private readonly judge;
|
|
158
|
+
private readonly opts;
|
|
159
|
+
readonly startedMs: number;
|
|
160
|
+
attempts: number;
|
|
161
|
+
last: Outcome;
|
|
162
|
+
found: Record<string, unknown> | null;
|
|
163
|
+
private busy;
|
|
164
|
+
constructor(action: OutcomeAction, judge: () => Promise<View>, opts?: {
|
|
165
|
+
meta?: PendingMeta;
|
|
166
|
+
resend?: () => Promise<unknown>;
|
|
167
|
+
journalId?: string | null;
|
|
168
|
+
startedMs?: number;
|
|
169
|
+
limitMs?: number;
|
|
170
|
+
});
|
|
171
|
+
get limitMs(): number;
|
|
172
|
+
get elapsedMs(): number;
|
|
173
|
+
private outcome;
|
|
174
|
+
/** Read once. A final ends it (and takes it off the journal); else `pending_checking` within the limit,
|
|
175
|
+
* `still_unknown` after it. */
|
|
176
|
+
check(): Promise<Outcome>;
|
|
177
|
+
/** Read until a final, or `limitMs` from now (default: to the end of the limit after the send; at least one read). */
|
|
178
|
+
wait(limitMs?: number): Promise<Outcome>;
|
|
179
|
+
/** Send the same signed bytes once more (a cancel, a revoke, the stop), then read once. Throws for any other write
|
|
180
|
+
* or once the outcome is final. */
|
|
181
|
+
resendSame(): Promise<Outcome>;
|
|
182
|
+
}
|
|
183
|
+
/** Wait inside the call: up to `settleMs` (0 = no read: `pending_checking` at once). */
|
|
184
|
+
export declare function settle(pw: PendingWrite, settleMs: number): Promise<Outcome>;
|
|
185
|
+
export declare const JOURNAL_NAME = "outcome-pending-js.json";
|
|
186
|
+
type Entry = Record<string, unknown> & {
|
|
187
|
+
digest: string;
|
|
188
|
+
sentAtMs: number;
|
|
189
|
+
};
|
|
190
|
+
/** Note a write BEFORE it is sent; returns its id (the digest of its bytes). */
|
|
191
|
+
export declare function journalAdd(entry: Entry): Promise<string>;
|
|
192
|
+
export declare function journalSet(id: string | null | undefined, fields: Record<string, unknown>): Promise<void>;
|
|
193
|
+
export declare function journalDone(id: string | null | undefined): Promise<void>;
|
|
194
|
+
/** The writes noted in this computer's journal whose outcome is not known yet (younger than a day). Check one with
|
|
195
|
+
* {@link pendingCheck} and a client of its network. */
|
|
196
|
+
export declare function pending(maxAgeMs?: number): Promise<Entry[]>;
|
|
197
|
+
/** Read one journal entry once at a node (`read`, the node it was sent to: entry.rest); a final takes it off. */
|
|
198
|
+
export declare function pendingCheck(e: Entry, read: NodeRead, chainMs?: (() => Promise<number | null>) | null): Promise<Outcome>;
|
|
199
|
+
/** A JSON value with bigint fields as strings (for the journal). */
|
|
200
|
+
export declare const plain: (v: unknown) => unknown;
|
|
201
|
+
export {};
|