@integraledger/profile-facilitator 0.1.0 → 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 +256 -76
- package/dist/answers.d.ts +28 -6
- package/dist/answers.js +43 -3
- package/dist/http.d.ts +33 -6
- package/dist/http.js +93 -26
- package/dist/index.d.ts +15 -1
- package/dist/index.js +25 -11
- package/dist/polkadot.d.ts +10 -2
- package/dist/polkadot.js +429 -133
- package/dist/store.d.ts +29 -14
- package/dist/store.js +40 -23
- package/dist/tron.d.ts +2 -2
- package/dist/tron.js +378 -131
- package/dist/unexpected.d.ts +21 -0
- package/dist/unexpected.js +27 -0
- package/package.json +9 -6
package/dist/polkadot.js
CHANGED
|
@@ -5,23 +5,43 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { ApiPromise } from "@polkadot/api";
|
|
7
7
|
import { blake2b } from "@noble/hashes/blake2.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
8
|
+
import { pairingOf } from "@integraledger/lcp";
|
|
9
|
+
import { isRefusal } from "@integraledger/lcp/core";
|
|
10
|
+
import { decodeProfileCall, exactPolkadotRemark, extrinsicHash, ss58Decode, } from "@integraledger/lcp/polkadot";
|
|
11
|
+
import { failed, invalid, isObject, isPending, pending, } from "./answers.js";
|
|
12
|
+
import { NODE_MAX_BYTES, NODE_TIMEOUT_MS, NodeError, Slots, isSpent, postJson, sleep, within } from "./http.js";
|
|
11
13
|
import { answerReserve, inTime } from "./store.js";
|
|
14
|
+
import { settleReason, unexpectedSettle, unexpectedVerify } from "./unexpected.js";
|
|
12
15
|
const POLL_MS = 1_000;
|
|
13
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* The longest a metadata load may take. Each of its calls is bounded by the node call bound and by the time the load
|
|
18
|
+
* has left, and a call the load has no time left for is not sent: a load given up at this bound has no call in flight
|
|
19
|
+
* and sends no further call.
|
|
20
|
+
*/
|
|
14
21
|
const INIT_TIMEOUT_MS = 30_000;
|
|
15
22
|
/** Milliseconds per block, used to turn the era's last block into the row's `until`. */
|
|
16
23
|
const SLOW_BLOCK_MS = 12_000;
|
|
17
24
|
/** `TransactionSource::External`. */
|
|
18
25
|
const EXTERNAL = "02";
|
|
26
|
+
/**
|
|
27
|
+
* How many `chain_getBlock` reads, each bounded by the runtime's `System.BlockLength`, run at once in this process:
|
|
28
|
+
* for Polkadot Asset Hub's runtime 2005000, at most 4 × 28,504,064 = 114,016,256 bytes of block answers.
|
|
29
|
+
*/
|
|
30
|
+
export const BLOCK_READS = 4;
|
|
31
|
+
/** The slots of `BLOCK_READS`, shared by every network and every scan in this process. */
|
|
32
|
+
export const blockReads = new Slots(BLOCK_READS);
|
|
19
33
|
/** The JSON-RPC error `author_submitExtrinsic` gives for an extrinsic already in the pool. */
|
|
20
34
|
const ALREADY_IMPORTED = 1013;
|
|
21
35
|
/** The JSON-RPC error for an extrinsic the pool refuses as invalid; its message or data names the reason. */
|
|
22
36
|
const INVALID_TRANSACTION = 1010;
|
|
23
37
|
/** The JSON-RPC error for an extrinsic the pool has recently seen and will not take again for a while. */
|
|
24
38
|
const TEMPORARILY_BANNED = 1012;
|
|
39
|
+
/** No slot of `blockReads` came free before the pass's deadline, so block `n` was not read. */
|
|
40
|
+
class NoBlockReadSlot extends Error {
|
|
41
|
+
constructor(n) {
|
|
42
|
+
super(`block ${n}: no block read slot before the deadline`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
25
45
|
/** A JSON-RPC error answer: the node read the call and refused it. */
|
|
26
46
|
class RpcError extends Error {
|
|
27
47
|
code;
|
|
@@ -34,15 +54,15 @@ class RpcError extends Error {
|
|
|
34
54
|
}
|
|
35
55
|
/**
|
|
36
56
|
* True when a refused submission says the node has already seen the extrinsic or its nonce (already in the pool,
|
|
37
|
-
* temporarily banned, or an outdated nonce),
|
|
57
|
+
* temporarily banned, or an outdated nonce): the payment's replay primitive, the payer's nonce, is consumed.
|
|
38
58
|
*/
|
|
39
59
|
function seenBefore(e) {
|
|
40
60
|
if (e.code === ALREADY_IMPORTED || e.code === TEMPORARILY_BANNED)
|
|
41
61
|
return true;
|
|
42
62
|
return e.code === INVALID_TRANSACTION && /outdated|stale/i.test(`${e.message} ${e.data}`);
|
|
43
63
|
}
|
|
44
|
-
async function rpc(url, method, params, timeoutMs) {
|
|
45
|
-
const answer = await postJson(url, { jsonrpc: "2.0", id: 1, method, params }, timeoutMs);
|
|
64
|
+
async function rpc(url, method, params, timeoutMs, maxBytes) {
|
|
65
|
+
const answer = await postJson(url, { jsonrpc: "2.0", id: 1, method, params }, timeoutMs, maxBytes);
|
|
46
66
|
if (!isObject(answer))
|
|
47
67
|
throw new NodeError("malformed", true, `${method}: not a JSON-RPC answer`);
|
|
48
68
|
const error = answer["error"];
|
|
@@ -52,14 +72,20 @@ async function rpc(url, method, params, timeoutMs) {
|
|
|
52
72
|
}
|
|
53
73
|
return answer["result"];
|
|
54
74
|
}
|
|
55
|
-
/**
|
|
56
|
-
|
|
75
|
+
/**
|
|
76
|
+
* A provider for `@polkadot/api`, with no subscriptions, for one metadata load that ends at `deadline` (on
|
|
77
|
+
* `performance.now()`). Every call is one JSON-RPC POST bounded by the node call bound and by the time left before
|
|
78
|
+
* `deadline`; once `deadline` has passed, a call is not sent and fails as `spent`. `@polkadot/api` goes on with a
|
|
79
|
+
* load's calls once its caller stops waiting for the load; this bound ends them, so a load given up at its deadline has
|
|
80
|
+
* no call in flight and sends no further call.
|
|
81
|
+
*/
|
|
82
|
+
function boundedProvider(url, deadline) {
|
|
57
83
|
const provider = {
|
|
58
84
|
hasSubscriptions: false,
|
|
59
85
|
isClonable: false,
|
|
60
86
|
isConnected: true,
|
|
61
87
|
clone() {
|
|
62
|
-
return boundedProvider(url);
|
|
88
|
+
return boundedProvider(url, deadline);
|
|
63
89
|
},
|
|
64
90
|
async connect() { },
|
|
65
91
|
async disconnect() { },
|
|
@@ -67,7 +93,10 @@ function boundedProvider(url) {
|
|
|
67
93
|
return () => { };
|
|
68
94
|
},
|
|
69
95
|
send(method, params) {
|
|
70
|
-
|
|
96
|
+
const left = deadline - performance.now();
|
|
97
|
+
if (left <= 0)
|
|
98
|
+
return Promise.reject(new NodeError("spent", false, method));
|
|
99
|
+
return rpc(url, method, params, left);
|
|
71
100
|
},
|
|
72
101
|
subscribe() {
|
|
73
102
|
return Promise.reject(new Error("subscriptions are not used"));
|
|
@@ -92,35 +121,113 @@ function blockNumber(header) {
|
|
|
92
121
|
return Number.parseInt(n, 16);
|
|
93
122
|
return undefined;
|
|
94
123
|
}
|
|
95
|
-
|
|
124
|
+
function isCount(v) {
|
|
125
|
+
return typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
|
|
126
|
+
}
|
|
127
|
+
/** `System.BlockLength` and `System.BlockHashCount` from the metadata; undefined when either is missing or malformed. */
|
|
128
|
+
function runtimeBounds(api) {
|
|
129
|
+
const system = api.consts["system"];
|
|
130
|
+
const length = system?.["blockLength"]?.toJSON();
|
|
131
|
+
const count = Number(system?.["blockHashCount"]?.toString());
|
|
132
|
+
if (!isObject(length) || !isObject(length["max"]) || !isCount(count) || count === 0)
|
|
133
|
+
return undefined;
|
|
134
|
+
const classes = [length["max"]["normal"], length["max"]["operational"], length["max"]["mandatory"]];
|
|
135
|
+
if (!classes.every(isCount))
|
|
136
|
+
return undefined;
|
|
137
|
+
const header = length["maxHeaderSize"];
|
|
138
|
+
const headerBytes = isCount(header) ? header : 0;
|
|
139
|
+
const body = Math.max(...classes);
|
|
140
|
+
return { blockAnswerBytes: NODE_MAX_BYTES + Math.ceil((9 * body) / 2) + 7 * headerBytes, blockHashCount: count };
|
|
141
|
+
}
|
|
142
|
+
export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
96
143
|
const byNetwork = new Map(nodes.map((n) => [n.network, n]));
|
|
97
144
|
const apis = new Map();
|
|
98
|
-
/** The
|
|
99
|
-
|
|
145
|
+
/** The fields that name a payment in an operator entry: the payer once the extrinsic is decoded. */
|
|
146
|
+
const about = (c) => ({
|
|
147
|
+
network: c.network,
|
|
148
|
+
...(c.payer === undefined ? {} : { payer: c.payer }),
|
|
149
|
+
transaction: c.id,
|
|
150
|
+
});
|
|
151
|
+
/**
|
|
152
|
+
* `unexpected_verify_error` for an answer to `call` this facilitator cannot read: a `node-call-failed` entry whose
|
|
153
|
+
* cause is a `malformed` NodeError naming the part it cannot read.
|
|
154
|
+
*/
|
|
155
|
+
const malformed = (c, call, part) => unexpectedVerify(log, { event: "node-call-failed", ...about(c), call }, new NodeError("malformed", true, `${call}: ${part}`));
|
|
156
|
+
/** The entry for a settle whose deadline, `settleWaitMs` after its request, passed before `before`. */
|
|
157
|
+
const deadlinePassed = (c, before) => ({
|
|
158
|
+
event: "settle-deadline-passed",
|
|
159
|
+
...about(c),
|
|
160
|
+
before,
|
|
161
|
+
settleWaitMs,
|
|
162
|
+
});
|
|
163
|
+
/**
|
|
164
|
+
* `unexpected_verify_error` for a `/verify` step whose own bound left no time for its call `call`: the call was not
|
|
165
|
+
* sent, and the entry is a failed call's, its cause a `spent` NodeError.
|
|
166
|
+
*/
|
|
167
|
+
const notSent = (c, call) => unexpectedVerify(log, { event: "node-call-failed", ...about(c), call }, new NodeError("spent", false, call));
|
|
168
|
+
/** The stored row, or undefined when the store does not answer by `deadline`; the failure goes to the operator log. */
|
|
169
|
+
const readStored = (c, deadline) => inTime(s.read(c.network, c.id), deadline).catch((e) => {
|
|
170
|
+
log({ event: "store-call-failed", ...about(c), call: "read" }, e);
|
|
171
|
+
return undefined;
|
|
172
|
+
});
|
|
173
|
+
/**
|
|
174
|
+
* The network's metadata, loaded once and loaded again when the node's runtime version changes, within `timeoutMs`:
|
|
175
|
+
* the version read, the wait for a load another request started, and the wait for a new load. One failed load is one
|
|
176
|
+
* failure, with one operator entry. A load that fails while the request that started it waits is that request's
|
|
177
|
+
* failure, which it reports; one that fails once that request has stopped waiting goes to the operator log from the
|
|
178
|
+
* handler below, with that request's payment `fields` and the load's cause. Once `timeoutMs` is spent, a new load is
|
|
179
|
+
* not started and a load in flight is not waited for: that is a `spent` NodeError.
|
|
180
|
+
*/
|
|
181
|
+
async function apiFor(node, fields, timeoutMs) {
|
|
182
|
+
const deadline = performance.now() + timeoutMs;
|
|
183
|
+
const left = () => deadline - performance.now();
|
|
100
184
|
const version = await rpc(node.rpc, "state_getRuntimeVersion", [], timeoutMs);
|
|
101
185
|
const spec = isObject(version) ? version["specVersion"] : undefined;
|
|
102
186
|
if (typeof spec !== "number")
|
|
103
187
|
throw new NodeError("malformed", true, "state_getRuntimeVersion: no specVersion");
|
|
104
188
|
let loading = apis.get(node.network);
|
|
105
189
|
if (loading !== undefined) {
|
|
106
|
-
|
|
190
|
+
// A load that failed has gone to the operator log, from the request that started it or from the handler below;
|
|
191
|
+
// a new one is made.
|
|
192
|
+
// With no time left, a load in flight ends the wait at once: this request sends nothing.
|
|
193
|
+
const spent = left() <= 0;
|
|
194
|
+
const api = await within(loading.catch(() => undefined), left()).catch((e) => {
|
|
195
|
+
throw spent ? new NodeError("spent", false, "metadata") : e;
|
|
196
|
+
});
|
|
107
197
|
if (api !== undefined && api.runtimeVersion.specVersion.toNumber() === spec)
|
|
108
198
|
return api;
|
|
109
199
|
apis.delete(node.network);
|
|
110
200
|
void api?.disconnect();
|
|
111
201
|
}
|
|
202
|
+
if (left() <= 0)
|
|
203
|
+
throw new NodeError("spent", false, "metadata");
|
|
112
204
|
const fresh = load(node);
|
|
113
205
|
apis.set(node.network, fresh);
|
|
114
|
-
|
|
206
|
+
let waiting = true;
|
|
207
|
+
// Registered before the wait below, so a failure that ends the wait reaches this handler while `waiting` holds.
|
|
208
|
+
fresh.catch((e) => {
|
|
115
209
|
if (apis.get(node.network) === fresh)
|
|
116
210
|
apis.delete(node.network);
|
|
211
|
+
if (!waiting)
|
|
212
|
+
log({ event: "node-call-failed", ...fields, call: "metadata" }, e);
|
|
117
213
|
});
|
|
118
|
-
|
|
214
|
+
try {
|
|
215
|
+
return await within(fresh, left());
|
|
216
|
+
}
|
|
217
|
+
finally {
|
|
218
|
+
waiting = false;
|
|
219
|
+
}
|
|
119
220
|
}
|
|
221
|
+
/**
|
|
222
|
+
* The network's metadata, loaded through a provider whose calls end at the load's deadline, `INIT_TIMEOUT_MS` after
|
|
223
|
+
* the load starts. The load is given up at that deadline: it has no call in flight then and sends none after it, and
|
|
224
|
+
* a later request starts a fresh load.
|
|
225
|
+
*/
|
|
120
226
|
async function load(node) {
|
|
121
|
-
const
|
|
227
|
+
const deadline = performance.now() + INIT_TIMEOUT_MS;
|
|
228
|
+
const api = new ApiPromise({ provider: boundedProvider(node.rpc, deadline), noInitWarn: true, initWasm: false });
|
|
122
229
|
try {
|
|
123
|
-
await within(api.isReadyOrError,
|
|
230
|
+
await within(api.isReadyOrError, deadline - performance.now());
|
|
124
231
|
}
|
|
125
232
|
catch (e) {
|
|
126
233
|
void api.disconnect();
|
|
@@ -138,7 +245,7 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
138
245
|
const node = byNetwork.get(req.network);
|
|
139
246
|
if (node === undefined)
|
|
140
247
|
return "invalid_network";
|
|
141
|
-
if (
|
|
248
|
+
if (pairingOf(req) !== "x402/exact/polkadot/lcp-assets-remark")
|
|
142
249
|
return "invalid_payment_requirements";
|
|
143
250
|
const { extrinsic, call } = r.paymentPayload.payload;
|
|
144
251
|
if (!isLowerHex(extrinsic) || !isLowerHex(call))
|
|
@@ -148,7 +255,7 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
148
255
|
return "invalid_payload";
|
|
149
256
|
const profile = decodeProfileCall(Buffer.from(call.slice(2), "hex"));
|
|
150
257
|
const dest = ss58Decode(req.payTo);
|
|
151
|
-
if (
|
|
258
|
+
if (isRefusal(profile) || isRefusal(dest))
|
|
152
259
|
return "invalid_payload";
|
|
153
260
|
if (profile.assetId !== Number(req.asset) || profile.amount !== BigInt(req.amount))
|
|
154
261
|
return "invalid_payload";
|
|
@@ -163,20 +270,27 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
163
270
|
remarkHash: `0x${hexOf(blake2b(profile.remark, { dkLen: 32 }))}`,
|
|
164
271
|
};
|
|
165
272
|
}
|
|
166
|
-
/**
|
|
273
|
+
/**
|
|
274
|
+
* The checks of rule 5 that decode the extrinsic with the network's metadata, within `timeoutMs`. A metadata read that
|
|
275
|
+
* `timeoutMs` leaves no time for is not made, and the answer is `{ spent: "metadata" }`.
|
|
276
|
+
*/
|
|
167
277
|
async function decode(l, timeoutMs) {
|
|
278
|
+
const fields = about({ network: l.node.network, id: l.id });
|
|
168
279
|
let api;
|
|
169
280
|
try {
|
|
170
|
-
api = await
|
|
281
|
+
api = await apiFor(l.node, fields, timeoutMs);
|
|
171
282
|
}
|
|
172
|
-
catch {
|
|
173
|
-
|
|
283
|
+
catch (e) {
|
|
284
|
+
if (isSpent(e))
|
|
285
|
+
return { spent: "metadata" };
|
|
286
|
+
return unexpectedVerify(log, { event: "node-call-failed", ...fields, call: "metadata" }, e);
|
|
174
287
|
}
|
|
175
288
|
let xt;
|
|
176
289
|
try {
|
|
177
290
|
xt = api.createType("Extrinsic", l.extrinsic);
|
|
178
291
|
}
|
|
179
292
|
catch {
|
|
293
|
+
// The payer's own extrinsic bytes do not decode: refused `invalid_payload` to the client that sent them.
|
|
180
294
|
return "invalid_payload";
|
|
181
295
|
}
|
|
182
296
|
if (!xt.isSigned || xt.type !== 4 || xt.toHex() !== l.extrinsic || xt.method.toHex() !== l.call)
|
|
@@ -194,24 +308,41 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
194
308
|
}
|
|
195
309
|
if (!xt.era.isMortalEra)
|
|
196
310
|
return "invalid_payload";
|
|
311
|
+
const payer = xt.signer.toString();
|
|
312
|
+
const decoded = { network: l.node.network, id: l.id, payer };
|
|
197
313
|
const eventsKey = api.query["system"]?.["events"]?.key();
|
|
198
314
|
if (eventsKey === undefined)
|
|
199
|
-
return "
|
|
315
|
+
return malformed(decoded, "metadata", "System.Events");
|
|
316
|
+
const bounds = runtimeBounds(api);
|
|
317
|
+
if (bounds === undefined)
|
|
318
|
+
return malformed(decoded, "metadata", "System.BlockLength, System.BlockHashCount");
|
|
200
319
|
return {
|
|
201
320
|
network: l.node.network,
|
|
202
321
|
api,
|
|
203
322
|
hex: l.extrinsic,
|
|
204
323
|
id: l.id,
|
|
205
|
-
payer
|
|
324
|
+
payer,
|
|
206
325
|
assetId: l.assetId,
|
|
207
326
|
remarkHash: l.remarkHash,
|
|
208
327
|
era: xt.era.asMortalEra,
|
|
209
328
|
eventsKey,
|
|
329
|
+
bounds,
|
|
210
330
|
};
|
|
211
331
|
}
|
|
332
|
+
/**
|
|
333
|
+
* The last block that can include the extrinsic, for a block `at` from its era's birth to that last block: the era's
|
|
334
|
+
* last block, and no later than `BlockHashCount` + 1 blocks after its birth. Each block's execution keeps the hashes of
|
|
335
|
+
* the `BlockHashCount` + 1 blocks before it in `System.BlockHash`, and `CheckMortality` refuses an extrinsic whose
|
|
336
|
+
* birth block's hash is not there.
|
|
337
|
+
*/
|
|
338
|
+
function lastBlock(c, at) {
|
|
339
|
+
const birth = c.era.birth(at);
|
|
340
|
+
return Math.min(c.era.death(at) - 1, birth + c.bounds.blockHashCount + 1);
|
|
341
|
+
}
|
|
212
342
|
/**
|
|
213
343
|
* `TaggedTransactionQueue_validate_transaction` at the best block, within `timeoutMs`: the best block's height, and
|
|
214
|
-
* when the
|
|
344
|
+
* when the last block that can include the extrinsic ends. A call `timeoutMs` leaves no time for is not sent, and the
|
|
345
|
+
* answer names it.
|
|
215
346
|
*/
|
|
216
347
|
async function validate(c, timeoutMs = 3 * NODE_TIMEOUT_MS) {
|
|
217
348
|
const url = byNetwork.get(c.network).rpc;
|
|
@@ -220,22 +351,29 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
220
351
|
let best;
|
|
221
352
|
let header;
|
|
222
353
|
let validity;
|
|
354
|
+
let call = "chain_getBlockHash";
|
|
223
355
|
try {
|
|
224
|
-
best = await rpc(url,
|
|
356
|
+
best = await rpc(url, call, [], left());
|
|
225
357
|
if (!isLowerHex(best) || best.length !== 66)
|
|
226
|
-
return "
|
|
227
|
-
|
|
228
|
-
|
|
358
|
+
return malformed(c, call, "the block hash");
|
|
359
|
+
call = "chain_getHeader";
|
|
360
|
+
header = await rpc(url, call, [best], left());
|
|
361
|
+
call = "state_call";
|
|
362
|
+
validity = await rpc(url, call, ["TaggedTransactionQueue_validate_transaction", `0x${EXTERNAL}${c.hex.slice(2)}${best.slice(2)}`, best], left());
|
|
229
363
|
}
|
|
230
|
-
catch {
|
|
231
|
-
|
|
364
|
+
catch (e) {
|
|
365
|
+
if (isSpent(e))
|
|
366
|
+
return { spent: call };
|
|
367
|
+
return unexpectedVerify(log, { event: "node-call-failed", ...about(c), call }, e);
|
|
232
368
|
}
|
|
233
369
|
const height = blockNumber(header);
|
|
234
|
-
if (height === undefined
|
|
235
|
-
return "
|
|
370
|
+
if (height === undefined)
|
|
371
|
+
return malformed(c, "chain_getHeader", "number");
|
|
372
|
+
if (typeof validity !== "string")
|
|
373
|
+
return malformed(c, "state_call", "the validity");
|
|
236
374
|
if (!validity.startsWith("0x00"))
|
|
237
375
|
return "invalid_transaction";
|
|
238
|
-
const blocksLeft = Math.max(0, c
|
|
376
|
+
const blocksLeft = Math.max(0, lastBlock(c, height) + 1 - height);
|
|
239
377
|
return { best: height, until: new Date(Date.now() + blocksLeft * SLOW_BLOCK_MS) };
|
|
240
378
|
}
|
|
241
379
|
async function verify(r) {
|
|
@@ -245,8 +383,14 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
245
383
|
const c = await decode(l, INIT_TIMEOUT_MS);
|
|
246
384
|
if (typeof c === "string")
|
|
247
385
|
return invalid(c);
|
|
386
|
+
if ("spent" in c)
|
|
387
|
+
return invalid(notSent({ network: l.node.network, id: l.id }, c.spent));
|
|
248
388
|
const v = await validate(c);
|
|
249
|
-
|
|
389
|
+
if (typeof v === "string")
|
|
390
|
+
return invalid(v, c.payer);
|
|
391
|
+
if ("spent" in v)
|
|
392
|
+
return invalid(notSent(c, v.spent), c.payer);
|
|
393
|
+
return { isValid: true, payer: c.payer };
|
|
250
394
|
}
|
|
251
395
|
/**
|
|
252
396
|
* The answer for the extrinsic at `index` of block `hash`, from that block's events. A failure is logged for the
|
|
@@ -265,90 +409,188 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
265
409
|
return { success: true, transaction: timepoint, network: c.network, payer: c.payer };
|
|
266
410
|
const seen = mine.map((r) => `${r.event.section}.${r.event.method}`);
|
|
267
411
|
if (final)
|
|
268
|
-
|
|
412
|
+
log({ event: "settlement-failed", ...about(c), transaction: timepoint, events: seen });
|
|
269
413
|
return failed("invalid_transaction_state", timepoint, c.network);
|
|
270
414
|
}
|
|
271
|
-
/**
|
|
272
|
-
|
|
415
|
+
/**
|
|
416
|
+
* The finalized head's height, read before `deadline`. Undefined when a read fails or the header names no number, a
|
|
417
|
+
* node answer this facilitator cannot read; either is a `node-call-failed` entry with the call. A read `deadline`
|
|
418
|
+
* leaves no time for is not sent, and the answer names it.
|
|
419
|
+
*/
|
|
420
|
+
async function finalizedHeight(c, url, deadline) {
|
|
421
|
+
let call = "chain_getFinalizedHead";
|
|
273
422
|
try {
|
|
274
|
-
const hash = await rpc(url,
|
|
275
|
-
|
|
423
|
+
const hash = await rpc(url, call, [], deadline - performance.now());
|
|
424
|
+
call = "chain_getHeader";
|
|
425
|
+
const height = blockNumber(await rpc(url, call, [hash], deadline - performance.now()));
|
|
426
|
+
if (height === undefined)
|
|
427
|
+
throw new NodeError("malformed", true, `${call}: number`);
|
|
428
|
+
return height;
|
|
276
429
|
}
|
|
277
|
-
catch {
|
|
430
|
+
catch (e) {
|
|
431
|
+
if (isSpent(e))
|
|
432
|
+
return { spent: call };
|
|
433
|
+
log({ event: "node-call-failed", ...about(c), call }, e);
|
|
434
|
+
return undefined;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* The head's height. Undefined when the read fails or the header names no number, a node answer this facilitator
|
|
439
|
+
* cannot read; either is a `node-call-failed` entry with the call. Undefined too, with no entry, when `left()` leaves
|
|
440
|
+
* no time for the read, which is not sent.
|
|
441
|
+
*/
|
|
442
|
+
async function headHeight(c, url, left) {
|
|
443
|
+
try {
|
|
444
|
+
const height = blockNumber(await rpc(url, "chain_getHeader", [], left()));
|
|
445
|
+
if (height === undefined)
|
|
446
|
+
throw new NodeError("malformed", true, "chain_getHeader: number");
|
|
447
|
+
return height;
|
|
448
|
+
}
|
|
449
|
+
catch (e) {
|
|
450
|
+
if (!isSpent(e))
|
|
451
|
+
log({ event: "node-call-failed", ...about(c), call: "chain_getHeader" }, e);
|
|
278
452
|
return undefined;
|
|
279
453
|
}
|
|
280
454
|
}
|
|
281
|
-
/**
|
|
455
|
+
/**
|
|
456
|
+
* The extrinsic's index in the block at `n`, and the block's hash; the index is -1 when the block does not hold it.
|
|
457
|
+
* The block is read in one of `blockReads`' slots, waited for until `left()` ends; a read that cannot start by then
|
|
458
|
+
* throws `NoBlockReadSlot`.
|
|
459
|
+
*/
|
|
282
460
|
async function findIn(c, url, n, left) {
|
|
283
461
|
const hash = await rpc(url, "chain_getBlockHash", [n], left());
|
|
284
|
-
const
|
|
462
|
+
const release = await blockReads.take(left());
|
|
463
|
+
if (release === undefined)
|
|
464
|
+
throw new NoBlockReadSlot(n);
|
|
465
|
+
let block;
|
|
466
|
+
try {
|
|
467
|
+
block = await rpc(url, "chain_getBlock", [hash], left(), c.bounds.blockAnswerBytes);
|
|
468
|
+
}
|
|
469
|
+
finally {
|
|
470
|
+
release();
|
|
471
|
+
}
|
|
285
472
|
const xts = isObject(block) && isObject(block["block"]) ? block["block"]["extrinsics"] : undefined;
|
|
286
473
|
if (typeof hash !== "string" || !Array.isArray(xts))
|
|
287
474
|
throw new NodeError("malformed", true, `block ${n}`);
|
|
288
475
|
return { hash, index: xts.findIndex((x) => isLowerHex(x) && extrinsicHash(Buffer.from(x.slice(2), "hex")) === c.id) };
|
|
289
476
|
}
|
|
290
477
|
/**
|
|
291
|
-
*
|
|
292
|
-
*
|
|
293
|
-
*
|
|
294
|
-
*
|
|
295
|
-
* the
|
|
478
|
+
* Block `n` read for the extrinsic: the answer when the block holds it, `absent` when it does not, `unreadable` (with
|
|
479
|
+
* the reason) when the node gives neither the block nor, for the block that holds it, its events, or when no block
|
|
480
|
+
* read slot comes free before the deadline, and `stopped` when the deadline ends a read that started. A call the
|
|
481
|
+
* deadline leaves no time for is not sent, and the read is `stopped` with no entry; each other read that gives no
|
|
482
|
+
* block goes to the operator log, with what stopped it.
|
|
483
|
+
*/
|
|
484
|
+
async function readBlock(c, url, n, left, final) {
|
|
485
|
+
try {
|
|
486
|
+
const found = await findIn(c, url, n, left);
|
|
487
|
+
if (found.index < 0)
|
|
488
|
+
return "absent";
|
|
489
|
+
return await included(c, url, found.hash, found.index, left(), final);
|
|
490
|
+
}
|
|
491
|
+
catch (e) {
|
|
492
|
+
if (isSpent(e))
|
|
493
|
+
return "stopped";
|
|
494
|
+
if (!(e instanceof NoBlockReadSlot) && left() <= 0) {
|
|
495
|
+
log({ event: "block-read-stopped", ...about(c), block: n }, e);
|
|
496
|
+
return "stopped";
|
|
497
|
+
}
|
|
498
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
499
|
+
log({ event: "block-unreadable", ...about(c), block: n, final, reason }, e);
|
|
500
|
+
return { unreadable: reason };
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* One pass until `deadline`, no further than the last block that can include the extrinsic. First the blocks from
|
|
505
|
+
* `at.proven` up to the finalized head, read at finality: a block that cannot be read is recorded as unread and
|
|
506
|
+
* skipped, and the pass goes on to the blocks after it. Then the blocks above them, up to the head, where only a
|
|
507
|
+
* success is an answer: a failure there waits until its block is final, and a block that cannot be read is skipped,
|
|
508
|
+
* since it is read again at finality. Then, with the time left, the blocks recorded as unread before this pass are
|
|
509
|
+
* read again. Once every block to the last is read at finality, and none is unread, the extrinsic can never be
|
|
510
|
+
* included, and the answer is `invalid_transaction_state` with its hash. The head is not read once `deadline` has
|
|
511
|
+
* passed. Gives the final answer, or where the scan has got to.
|
|
296
512
|
*/
|
|
297
513
|
async function scanOnce(c, since, at, deadline) {
|
|
298
514
|
const url = byNetwork.get(c.network).rpc;
|
|
299
515
|
const left = () => deadline - performance.now();
|
|
300
|
-
const last = c
|
|
516
|
+
const last = lastBlock(c, since);
|
|
301
517
|
let { proven, next } = at;
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
518
|
+
const unread = new Set(at.unread);
|
|
519
|
+
const resolved = new Set(at.resolved);
|
|
520
|
+
const position = () => ({ proven, next, unread: [...unread].sort((a, b) => a - b), resolved: [...resolved] });
|
|
521
|
+
const read = await finalizedHeight(c, url, deadline);
|
|
522
|
+
const finalized = typeof read === "number" ? read : undefined;
|
|
523
|
+
while (finalized !== undefined && proven <= Math.min(finalized, last) && left() > 0) {
|
|
524
|
+
const read = await readBlock(c, url, proven, left, true);
|
|
525
|
+
if (read === "stopped")
|
|
526
|
+
return position();
|
|
527
|
+
if (typeof read === "object" && "unreadable" in read) {
|
|
528
|
+
unread.add(proven);
|
|
309
529
|
}
|
|
310
|
-
if (
|
|
311
|
-
|
|
312
|
-
return { answer: failed("invalid_transaction_state", c.id, c.network) };
|
|
530
|
+
else if (read !== "absent") {
|
|
531
|
+
return { answer: read };
|
|
313
532
|
}
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
533
|
+
proven += 1;
|
|
534
|
+
}
|
|
535
|
+
next = Math.max(next, proven);
|
|
536
|
+
const head = left() > 0 ? await headHeight(c, url, left) : undefined;
|
|
537
|
+
while (head !== undefined && next <= Math.min(head, last) && left() > 0) {
|
|
538
|
+
const read = await readBlock(c, url, next, left, false);
|
|
539
|
+
if (read === "stopped")
|
|
540
|
+
return position();
|
|
541
|
+
if (typeof read === "object" && !("unreadable" in read)) {
|
|
542
|
+
if (read.success)
|
|
543
|
+
return { answer: read };
|
|
544
|
+
break;
|
|
325
545
|
}
|
|
546
|
+
next += 1;
|
|
326
547
|
}
|
|
327
|
-
|
|
328
|
-
|
|
548
|
+
for (const n of at.unread) {
|
|
549
|
+
if (finalized === undefined || n > finalized || left() <= 0)
|
|
550
|
+
break;
|
|
551
|
+
const read = await readBlock(c, url, n, left, true);
|
|
552
|
+
if (read === "stopped")
|
|
553
|
+
return position();
|
|
554
|
+
if (typeof read === "object" && "unreadable" in read)
|
|
555
|
+
continue;
|
|
556
|
+
unread.delete(n);
|
|
557
|
+
resolved.add(n);
|
|
558
|
+
if (read !== "absent")
|
|
559
|
+
return { answer: read };
|
|
329
560
|
}
|
|
330
|
-
|
|
561
|
+
if (proven > last && unread.size === 0) {
|
|
562
|
+
log({ event: "settlement-expired", ...about(c) });
|
|
563
|
+
return { answer: failed("invalid_transaction_state", c.id, c.network) };
|
|
564
|
+
}
|
|
565
|
+
return position();
|
|
331
566
|
}
|
|
332
567
|
/**
|
|
333
|
-
* Scans for the extrinsic from `since` every second until `deadline`, reading the
|
|
334
|
-
* set, and answers with the first final answer either gives.
|
|
335
|
-
*
|
|
568
|
+
* Scans for the extrinsic from `since`, with the stored `unread` blocks, every second until `deadline`, reading the
|
|
569
|
+
* stored answer too when `stored` is set, and answers with the first final answer either gives. Once `deadline` has
|
|
570
|
+
* passed, no pass is made: the answer is the one the wait's end gives. Where the scan got to at finality is stored:
|
|
571
|
+
* `since` moves on, and the blocks it could not read are recorded. Submits nothing.
|
|
336
572
|
*/
|
|
337
|
-
async function scan(c, since, deadline, stored) {
|
|
338
|
-
let at = { proven: since, next: since };
|
|
573
|
+
async function scan(c, since, unread, deadline, stored) {
|
|
574
|
+
let at = { proven: since, next: since, unread, resolved: [] };
|
|
339
575
|
for (;;) {
|
|
340
576
|
if (stored) {
|
|
341
|
-
const row = await
|
|
577
|
+
const row = await readStored(c, deadline);
|
|
342
578
|
if (row?.state === "answered" && !isPending(row.answer))
|
|
343
579
|
return row.answer;
|
|
344
580
|
}
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
581
|
+
if (deadline - performance.now() > 0) {
|
|
582
|
+
const step = await scanOnce(c, since, at, deadline);
|
|
583
|
+
if ("answer" in step)
|
|
584
|
+
return step.answer;
|
|
585
|
+
at = step;
|
|
586
|
+
}
|
|
349
587
|
if (performance.now() + POLL_MS > deadline) {
|
|
350
|
-
if (at.proven > since)
|
|
351
|
-
|
|
588
|
+
if (at.proven > since || at.unread.length > 0 || at.resolved.length > 0) {
|
|
589
|
+
const to = Math.min(at.proven, lastBlock(c, since));
|
|
590
|
+
void s
|
|
591
|
+
.advance(c.network, c.id, { from: since, to, unread: at.unread, resolved: at.resolved })
|
|
592
|
+
.catch((e) => log({ event: "store-call-failed", ...about(c), call: "advance" }, e));
|
|
593
|
+
}
|
|
352
594
|
return pending(c.id, c.network);
|
|
353
595
|
}
|
|
354
596
|
await sleep(POLL_MS);
|
|
@@ -356,7 +598,10 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
356
598
|
}
|
|
357
599
|
/**
|
|
358
600
|
* Submits, then scans for the extrinsic until `deadline`. A refusal that says the node has already seen the extrinsic
|
|
359
|
-
* or its nonce is
|
|
601
|
+
* or its nonce is a consumed payment: `invalid_transaction_state` with the extrinsic's hash, and no scan. Any other
|
|
602
|
+
* refusal, or a request that cannot have reached the node, gives `unexpected_settle_error` with no transaction:
|
|
603
|
+
* nothing was submitted. So does a submission `deadline` leaves no time for, as after a claim that answers late: it
|
|
604
|
+
* is not sent, and its entry is `settle-deadline-passed`.
|
|
360
605
|
*/
|
|
361
606
|
async function submit(c, since, deadline) {
|
|
362
607
|
const url = byNetwork.get(c.network).rpc;
|
|
@@ -364,48 +609,85 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
364
609
|
await rpc(url, "author_submitExtrinsic", [c.hex], deadline - performance.now());
|
|
365
610
|
}
|
|
366
611
|
catch (e) {
|
|
367
|
-
if (
|
|
368
|
-
return
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
if (
|
|
372
|
-
return
|
|
612
|
+
if (isSpent(e))
|
|
613
|
+
return unexpectedSettle(log, deadlinePassed(c, "author_submitExtrinsic"));
|
|
614
|
+
const entry = { event: "node-call-failed", ...about(c), call: "author_submitExtrinsic" };
|
|
615
|
+
const notSubmitted = e instanceof RpcError ? !seenBefore(e) : e instanceof NodeError && !e.sent;
|
|
616
|
+
if (notSubmitted)
|
|
617
|
+
return unexpectedSettle(log, entry, e);
|
|
618
|
+
log(entry, e);
|
|
619
|
+
return e instanceof RpcError ? failed("invalid_transaction_state", c.id, c.network) : pending(c.id, c.network);
|
|
373
620
|
}
|
|
374
|
-
return scan(c, since, deadline, false);
|
|
621
|
+
return scan(c, since, [], deadline, false);
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* What a repeated `/settle` gets for a stored answer. A success is given once, to the settle that stored it, so the
|
|
625
|
+
* payment is consumed: a repeat gets `invalid_transaction_state` with the success's transaction (x402's `exact`
|
|
626
|
+
* family: a consumed primitive produces a settlement failure, never a success). Any other answer is given as stored.
|
|
627
|
+
*/
|
|
628
|
+
function repeatOf(stored) {
|
|
629
|
+
if (!stored.success)
|
|
630
|
+
return stored;
|
|
631
|
+
log({ event: "settlement-consumed", network: stored.network, payer: stored.payer, transaction: stored.transaction });
|
|
632
|
+
return failed("invalid_transaction_state", stored.transaction, stored.network);
|
|
375
633
|
}
|
|
376
|
-
/**
|
|
634
|
+
/**
|
|
635
|
+
* Stores the answer, unless the row holds a final one. A success is given only by the settle whose write stored it:
|
|
636
|
+
* when the row already holds a final answer, the answer is what a repeat gets for it, and when the write fails, it is
|
|
637
|
+
* pending with the hash, for a later read of the chain. An answer with no transaction, a refused submission or one
|
|
638
|
+
* that cannot have reached the node, is given the same way: only once it is the stored answer. Any other answer is
|
|
639
|
+
* given whether or not it is stored; a failed write leaves the row for a later read of the chain.
|
|
640
|
+
*/
|
|
377
641
|
async function keep(c, answer, deadline) {
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
642
|
+
let wrote;
|
|
643
|
+
try {
|
|
644
|
+
wrote = await inTime(s.answer(c.network, c.id, answer), deadline);
|
|
645
|
+
}
|
|
646
|
+
catch (e) {
|
|
647
|
+
log({ event: "answer-not-stored", ...about(c) }, e);
|
|
648
|
+
return answer.success || answer.transaction === "" ? pending(c.id, c.network) : answer;
|
|
649
|
+
}
|
|
650
|
+
if (wrote || (!answer.success && answer.transaction !== ""))
|
|
651
|
+
return answer;
|
|
652
|
+
const row = await readStored(c, deadline);
|
|
653
|
+
return row?.state === "answered" && !isPending(row.answer) ? repeatOf(row.answer) : pending(c.id, c.network);
|
|
382
654
|
}
|
|
383
655
|
/**
|
|
384
656
|
* Reads a claimed id, or a stored pending answer, again from the chain until the answer's reserve before `deadline`,
|
|
385
|
-
* then stores what it read.
|
|
657
|
+
* from the stored `since` and `unread`, then stores what it read. The decode is bounded by that wait too. Once that
|
|
658
|
+
* wait has ended, the node is asked nothing: the answer is the stored one, as a repeat gets it, or pending with the
|
|
659
|
+
* hash.
|
|
386
660
|
*/
|
|
387
|
-
async function follow(l, since, deadline) {
|
|
388
|
-
const
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
661
|
+
async function follow(l, since, unread, deadline) {
|
|
662
|
+
const waitUntil = deadline - answerReserve(settleWaitMs);
|
|
663
|
+
const c = waitUntil - performance.now() > 0 ? await decode(l, waitUntil - performance.now()) : undefined;
|
|
664
|
+
const decoded = typeof c === "object" && !("spent" in c) ? c : undefined;
|
|
665
|
+
if (decoded === undefined || since === null) {
|
|
666
|
+
const row = await readStored(decoded ?? { network: l.node.network, id: l.id }, deadline);
|
|
667
|
+
return row?.state === "answered" ? repeatOf(row.answer) : pending(l.id, l.node.network);
|
|
392
668
|
}
|
|
393
|
-
return keep(
|
|
669
|
+
return keep(decoded, await scan(decoded, since, unread, waitUntil, true), deadline);
|
|
394
670
|
}
|
|
395
671
|
/**
|
|
396
672
|
* Answers within `settleWaitMs`. The stored answer is read before the node is asked anything, and a final one is
|
|
397
|
-
* given as it
|
|
398
|
-
*
|
|
399
|
-
* refused
|
|
400
|
-
*
|
|
401
|
-
*
|
|
402
|
-
*
|
|
673
|
+
* given as a repeat gets it. A claimed id, or a stored pending answer, is read again from the chain. A claimed id is
|
|
674
|
+
* never released: a submission the node refused as one it has already seen is a consumed payment, and any other
|
|
675
|
+
* refused submission, or a submission request that cannot have reached the node, gives `unexpected_settle_error`
|
|
676
|
+
* with no transaction, which says nothing was submitted. Each is stored final, and every repeat gets the stored
|
|
677
|
+
* answer. When the store cannot be read, the facilitator cannot know whether the extrinsic was submitted, so the
|
|
678
|
+
* answer is pending with its hash. For a hash the store does not hold, the deadline is checked before each node read:
|
|
679
|
+
* the decode, the finalized head read and the validation. A deadline spent there sends no node call, and gives
|
|
680
|
+
* `unexpected_settle_error`; so does a call inside one of them that the deadline leaves no time for, which is not sent,
|
|
681
|
+
* with its entry naming the call. A refusal the client's own bytes give comes first, so the decode's refusals, which
|
|
682
|
+
* need the metadata, are given when the deadline leaves time for it. The scan starts after the finalized head read before
|
|
683
|
+
* validation (never before the era's birth): validation at the best block shows the extrinsic absent from that
|
|
684
|
+
* block's ancestry, and the finalized head is in every later best chain. No hash is claimed once the wait for the
|
|
685
|
+
* chain has ended: its submission would have no time left.
|
|
403
686
|
*/
|
|
404
687
|
async function settle(r) {
|
|
405
688
|
const deadline = performance.now() + settleWaitMs;
|
|
406
689
|
const left = () => deadline - performance.now();
|
|
407
690
|
const network = r.paymentRequirements.network;
|
|
408
|
-
const settleReason = (v) => (v === "unexpected_verify_error" ? "unexpected_settle_error" : v);
|
|
409
691
|
const l = await local(r);
|
|
410
692
|
if (typeof l === "string")
|
|
411
693
|
return failed(l, "", network);
|
|
@@ -413,45 +695,59 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
413
695
|
try {
|
|
414
696
|
stored = await inTime(s.read(l.node.network, l.id), deadline);
|
|
415
697
|
}
|
|
416
|
-
catch {
|
|
698
|
+
catch (e) {
|
|
699
|
+
log({ event: "store-call-failed", ...about({ network: l.node.network, id: l.id }), call: "read" }, e);
|
|
417
700
|
return pending(l.id, l.node.network);
|
|
418
701
|
}
|
|
419
702
|
if (stored.state === "answered" && !isPending(stored.answer))
|
|
420
|
-
return stored.answer;
|
|
703
|
+
return repeatOf(stored.answer);
|
|
421
704
|
if (stored.state !== "none")
|
|
422
|
-
return follow(l, stored.since, deadline);
|
|
705
|
+
return follow(l, stored.since, stored.unread, deadline);
|
|
706
|
+
const hashed = { network: l.node.network, id: l.id };
|
|
707
|
+
if (left() <= 0)
|
|
708
|
+
return unexpectedSettle(log, deadlinePassed(hashed, "node reads"));
|
|
423
709
|
const c = await decode(l, left());
|
|
424
710
|
if (typeof c === "string")
|
|
425
711
|
return failed(settleReason(c), "", network);
|
|
426
|
-
|
|
712
|
+
if ("spent" in c)
|
|
713
|
+
return unexpectedSettle(log, deadlinePassed(hashed, c.spent));
|
|
714
|
+
if (left() <= 0)
|
|
715
|
+
return unexpectedSettle(log, deadlinePassed(c, "finalized head"));
|
|
716
|
+
const finalized = await finalizedHeight(c, l.node.rpc, deadline);
|
|
717
|
+
if (typeof finalized === "object")
|
|
718
|
+
return unexpectedSettle(log, deadlinePassed(c, finalized.spent));
|
|
719
|
+
if (left() <= 0)
|
|
720
|
+
return unexpectedSettle(log, deadlinePassed(c, "validation"));
|
|
427
721
|
const v = await validate(c, left());
|
|
428
722
|
if (typeof v === "string")
|
|
429
723
|
return failed(settleReason(v), "", network);
|
|
430
|
-
if (
|
|
431
|
-
return
|
|
724
|
+
if ("spent" in v)
|
|
725
|
+
return unexpectedSettle(log, deadlinePassed(c, v.spent));
|
|
726
|
+
const waitUntil = deadline - answerReserve(settleWaitMs);
|
|
727
|
+
if (waitUntil - performance.now() <= 0)
|
|
728
|
+
return unexpectedSettle(log, deadlinePassed(c, "claim"));
|
|
432
729
|
const birth = c.era.birth(v.best);
|
|
433
|
-
const since = finalized === undefined ? birth : Math.max(birth, finalized + 1);
|
|
730
|
+
const since = Math.min(finalized === undefined ? birth : Math.max(birth, finalized + 1), lastBlock(c, v.best));
|
|
434
731
|
let won;
|
|
435
732
|
try {
|
|
436
733
|
won = await inTime(s.claim(c.network, c.id, v.until, since), deadline);
|
|
437
734
|
}
|
|
438
|
-
catch {
|
|
735
|
+
catch (e) {
|
|
736
|
+
log({ event: "store-call-failed", ...about(c), call: "claim" }, e);
|
|
439
737
|
return pending(c.id, c.network);
|
|
440
738
|
}
|
|
441
739
|
if (!won) {
|
|
442
|
-
const row = await
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
return keep(c, answer, deadline);
|
|
448
|
-
const released = await inTime(s.release(c.network, c.id), deadline).catch(() => false);
|
|
449
|
-
return released ? answer : pending(c.id, c.network);
|
|
740
|
+
const row = await readStored(c, deadline);
|
|
741
|
+
const claimed = row !== undefined && row.state !== "none" ? row : undefined;
|
|
742
|
+
return follow(l, claimed?.since ?? null, claimed?.unread ?? [], deadline);
|
|
743
|
+
}
|
|
744
|
+
return keep(c, await submit(c, since, waitUntil), deadline);
|
|
450
745
|
}
|
|
451
746
|
async function close() {
|
|
452
|
-
const all = [...apis
|
|
747
|
+
const all = [...apis];
|
|
453
748
|
apis.clear();
|
|
454
|
-
|
|
749
|
+
// A load that failed has gone to the operator log from `decode` or `apiFor`; a failed disconnect goes there here.
|
|
750
|
+
await Promise.all(all.map(([network, p]) => p.then((api) => api.disconnect().catch((e) => log({ event: "node-call-failed", network, call: "disconnect" }, e)), () => undefined)));
|
|
455
751
|
}
|
|
456
752
|
return { verify, settle, close, networks: nodes.map((n) => n.network) };
|
|
457
753
|
}
|