@integraledger/profile-facilitator 0.4.0 → 0.5.1
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/CHANGELOG.md +107 -0
- package/README.md +781 -456
- package/dist/answers.d.ts +11 -4
- package/dist/answers.js +24 -0
- package/dist/core.d.ts +51 -0
- package/dist/core.js +758 -0
- package/dist/http.d.ts +20 -3
- package/dist/http.js +32 -7
- package/dist/index.d.ts +12 -36
- package/dist/index.js +9 -162
- package/dist/module.d.ts +372 -0
- package/dist/module.js +13 -0
- package/dist/modules/algorand/index.d.ts +22 -0
- package/dist/modules/algorand/index.js +247 -0
- package/dist/modules/algorand/own.d.ts +26 -0
- package/dist/modules/algorand/own.js +231 -0
- package/dist/modules/aptos/index.d.ts +23 -0
- package/dist/modules/aptos/index.js +232 -0
- package/dist/modules/cardano/index.d.ts +18 -0
- package/dist/modules/cardano/index.js +124 -0
- package/dist/modules/casper/index.d.ts +120 -0
- package/dist/modules/casper/index.js +442 -0
- package/dist/modules/concordium/index.d.ts +16 -0
- package/dist/modules/concordium/index.js +77 -0
- package/dist/modules/erc7710/index.d.ts +26 -0
- package/dist/modules/erc7710/index.js +220 -0
- package/dist/modules/evm/forms.d.ts +74 -0
- package/dist/modules/evm/forms.js +204 -0
- package/dist/modules/evm/index.d.ts +40 -0
- package/dist/modules/evm/index.js +154 -0
- package/dist/modules/evm/node.d.ts +29 -0
- package/dist/modules/evm/node.js +222 -0
- package/dist/modules/hedera/executor.d.ts +63 -0
- package/dist/modules/hedera/executor.js +343 -0
- package/dist/modules/hedera/index.d.ts +23 -0
- package/dist/modules/hedera/index.js +136 -0
- package/dist/modules/hedera/mirror.d.ts +32 -0
- package/dist/modules/hedera/mirror.js +111 -0
- package/dist/modules/index.d.ts +23 -0
- package/dist/modules/index.js +24 -0
- package/dist/modules/lnbtc/index.d.ts +10 -0
- package/dist/modules/lnbtc/index.js +112 -0
- package/dist/modules/near/index.d.ts +18 -0
- package/dist/modules/near/index.js +246 -0
- package/dist/modules/polkadot/index.d.ts +12 -0
- package/dist/modules/polkadot/index.js +149 -0
- package/dist/modules/polkadot/rail.d.ts +40 -0
- package/dist/{polkadot.js → modules/polkadot/rail.js} +214 -288
- package/dist/modules/solana/index.d.ts +60 -0
- package/dist/modules/solana/index.js +326 -0
- package/dist/modules/solana/reader.d.ts +25 -0
- package/dist/modules/solana/reader.js +194 -0
- package/dist/modules/solana/state.d.ts +6 -0
- package/dist/modules/solana/state.js +103 -0
- package/dist/modules/starknet/index.d.ts +35 -0
- package/dist/modules/starknet/index.js +548 -0
- package/dist/modules/starknet/node.d.ts +78 -0
- package/dist/modules/starknet/node.js +339 -0
- package/dist/modules/stellar/index.d.ts +44 -0
- package/dist/modules/stellar/index.js +481 -0
- package/dist/modules/stellar/node.d.ts +57 -0
- package/dist/modules/stellar/node.js +151 -0
- package/dist/modules/sui/index.d.ts +16 -0
- package/dist/modules/sui/index.js +310 -0
- package/dist/modules/sui/node.d.ts +49 -0
- package/dist/modules/sui/node.js +197 -0
- package/dist/modules/ton/index.d.ts +16 -0
- package/dist/modules/ton/index.js +73 -0
- package/dist/modules/tron/index.d.ts +12 -0
- package/dist/modules/tron/index.js +120 -0
- package/dist/modules/tron/rail.d.ts +32 -0
- package/dist/{tron.js → modules/tron/rail.js} +206 -195
- package/dist/modules/xrpl/index.d.ts +28 -0
- package/dist/modules/xrpl/index.js +299 -0
- package/dist/modules/xrpl/node.d.ts +52 -0
- package/dist/modules/xrpl/node.js +231 -0
- package/dist/modules/xrpl/upto.d.ts +5 -0
- package/dist/modules/xrpl/upto.js +269 -0
- package/dist/record.d.ts +131 -0
- package/dist/record.js +330 -0
- package/dist/unexpected.d.ts +3 -2
- package/dist/unexpected.js +2 -1
- package/dist/wrapper.d.ts +68 -0
- package/dist/wrapper.js +126 -0
- package/package.json +48 -12
- package/dist/polkadot.d.ts +0 -21
- package/dist/store.d.ts +0 -59
- package/dist/store.js +0 -103
- package/dist/tron.d.ts +0 -12
- /package/dist/{base58check.d.ts → modules/tron/base58check.d.ts} +0 -0
- /package/dist/{base58check.js → modules/tron/base58check.js} +0 -0
|
@@ -1,17 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Rule 5 of `x402/exact/polkadot/lcp-assets-remark` against one network's RPC node: `/verify` decodes the extrinsic
|
|
3
3
|
* with the network's runtime metadata, checks its call against the requirements and asks the node to validate it;
|
|
4
|
-
* `/settle` repeats that,
|
|
4
|
+
* `/settle` repeats that, submits, and reads the payment by lcp's read until it is final. Which payments were already
|
|
5
|
+
* settled is the settler's record, not the rail's: the rail keeps no row.
|
|
5
6
|
*/
|
|
6
7
|
import { ApiPromise } from "@polkadot/api";
|
|
7
|
-
import { blake2b } from "@noble/hashes/blake2.js";
|
|
8
8
|
import { pairingOf } from "@integraledger/lcp";
|
|
9
9
|
import { isRefusal } from "@integraledger/lcp/core";
|
|
10
10
|
import { decodeProfileCall, exactPolkadotRemark, extrinsicHash, ss58Decode, } from "@integraledger/lcp/polkadot";
|
|
11
|
-
import { failed, invalid, isObject,
|
|
12
|
-
import { NODE_MAX_BYTES, NODE_TIMEOUT_MS, NodeError, Slots, isSpent, postJson, sleep, within } from "
|
|
13
|
-
import {
|
|
14
|
-
import { settleReason, unexpectedSettle, unexpectedVerify } from "./unexpected.js";
|
|
11
|
+
import { failed, invalid, isObject, pending, } from "../../answers.js";
|
|
12
|
+
import { NODE_MAX_BYTES, NODE_TIMEOUT_MS, NodeError, Slots, isSpent, postJson, sleep, within } from "../../http.js";
|
|
13
|
+
import { settleReason, unexpectedSettle, unexpectedVerify } from "../../unexpected.js";
|
|
15
14
|
const POLL_MS = 1_000;
|
|
16
15
|
/**
|
|
17
16
|
* The longest a metadata load may take. Each of its calls is bounded by the node call bound and by the time the load
|
|
@@ -19,8 +18,6 @@ const POLL_MS = 1_000;
|
|
|
19
18
|
* and sends no further call.
|
|
20
19
|
*/
|
|
21
20
|
const INIT_TIMEOUT_MS = 30_000;
|
|
22
|
-
/** Milliseconds per block, used to turn the era's last block into the row's `until`. */
|
|
23
|
-
const SLOW_BLOCK_MS = 12_000;
|
|
24
21
|
/** `TransactionSource::External`. */
|
|
25
22
|
const EXTERNAL = "02";
|
|
26
23
|
/**
|
|
@@ -139,7 +136,7 @@ function runtimeBounds(api) {
|
|
|
139
136
|
const body = Math.max(...classes);
|
|
140
137
|
return { blockAnswerBytes: NODE_MAX_BYTES + Math.ceil((9 * body) / 2) + 7 * headerBytes, blockHashCount: count };
|
|
141
138
|
}
|
|
142
|
-
export function createPolkadot(nodes,
|
|
139
|
+
export function createPolkadot(nodes, settleWaitMs, log) {
|
|
143
140
|
const byNetwork = new Map(nodes.map((n) => [n.network, n]));
|
|
144
141
|
const apis = new Map();
|
|
145
142
|
/** The fields that name a payment in an operator entry: the payer once the extrinsic is decoded. */
|
|
@@ -165,11 +162,6 @@ export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
|
165
162
|
* sent, and the entry is a failed call's, its cause a `spent` NodeError.
|
|
166
163
|
*/
|
|
167
164
|
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
165
|
/**
|
|
174
166
|
* The network's metadata, loaded once and loaded again when the node's runtime version changes, within `timeoutMs`:
|
|
175
167
|
* the version read, the wait for a load another request started, and the wait for a new load. One failed load is one
|
|
@@ -266,8 +258,6 @@ export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
|
266
258
|
extrinsic,
|
|
267
259
|
call,
|
|
268
260
|
id: extrinsicHash(Buffer.from(extrinsic.slice(2), "hex")),
|
|
269
|
-
assetId: profile.assetId,
|
|
270
|
-
remarkHash: `0x${hexOf(blake2b(profile.remark, { dkLen: 32 }))}`,
|
|
271
261
|
};
|
|
272
262
|
}
|
|
273
263
|
/**
|
|
@@ -322,8 +312,6 @@ export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
|
322
312
|
hex: l.extrinsic,
|
|
323
313
|
id: l.id,
|
|
324
314
|
payer,
|
|
325
|
-
assetId: l.assetId,
|
|
326
|
-
remarkHash: l.remarkHash,
|
|
327
315
|
era: xt.era.asMortalEra,
|
|
328
316
|
eventsKey,
|
|
329
317
|
bounds,
|
|
@@ -340,9 +328,8 @@ export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
|
340
328
|
return Math.min(c.era.death(at) - 1, birth + c.bounds.blockHashCount + 1);
|
|
341
329
|
}
|
|
342
330
|
/**
|
|
343
|
-
* `TaggedTransactionQueue_validate_transaction` at the best block, within `timeoutMs`: the best block's height,
|
|
344
|
-
*
|
|
345
|
-
* answer names it.
|
|
331
|
+
* `TaggedTransactionQueue_validate_transaction` at the best block, within `timeoutMs`: the best block's height, at which
|
|
332
|
+
* the chain answered the extrinsic valid. A call `timeoutMs` leaves no time for is not sent, and the answer names it.
|
|
346
333
|
*/
|
|
347
334
|
async function validate(c, timeoutMs = 3 * NODE_TIMEOUT_MS) {
|
|
348
335
|
const url = byNetwork.get(c.network).rpc;
|
|
@@ -373,8 +360,7 @@ export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
|
373
360
|
return malformed(c, "state_call", "the validity");
|
|
374
361
|
if (!validity.startsWith("0x00"))
|
|
375
362
|
return "invalid_transaction";
|
|
376
|
-
|
|
377
|
-
return { best: height, until: new Date(Date.now() + blocksLeft * SLOW_BLOCK_MS) };
|
|
363
|
+
return { best: height };
|
|
378
364
|
}
|
|
379
365
|
async function verify(r) {
|
|
380
366
|
const l = await local(r);
|
|
@@ -392,26 +378,6 @@ export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
|
392
378
|
return invalid(notSent(c, v.spent), c.payer);
|
|
393
379
|
return { isValid: true, payer: c.payer };
|
|
394
380
|
}
|
|
395
|
-
/**
|
|
396
|
-
* The answer for the extrinsic at `index` of block `hash`, from that block's events. A failure is logged for the
|
|
397
|
-
* operator when `final`, that is when the block was read at finality.
|
|
398
|
-
*/
|
|
399
|
-
async function included(c, url, hash, index, timeoutMs, final) {
|
|
400
|
-
const timepoint = `${hash}-${index}`;
|
|
401
|
-
const raw = await rpc(url, "state_getStorage", [c.eventsKey, hash], timeoutMs);
|
|
402
|
-
const records = c.api.createType("Vec<EventRecord>", raw);
|
|
403
|
-
const mine = records.filter((r) => r.phase.isApplyExtrinsic && r.phase.asApplyExtrinsic.toNumber() === index);
|
|
404
|
-
const has = (section, method, test) => mine.some((r) => r.event.section === section && r.event.method === method && test(r.event.data));
|
|
405
|
-
const ok = has("system", "ExtrinsicSuccess", () => true) &&
|
|
406
|
-
has("system", "Remarked", (d) => d[1]?.toHex() === c.remarkHash) &&
|
|
407
|
-
has("assets", "Transferred", (d) => d[0]?.toString() === String(c.assetId));
|
|
408
|
-
if (ok)
|
|
409
|
-
return { success: true, transaction: timepoint, network: c.network, payer: c.payer };
|
|
410
|
-
const seen = mine.map((r) => `${r.event.section}.${r.event.method}`);
|
|
411
|
-
if (final)
|
|
412
|
-
log({ event: "settlement-failed", ...about(c), transaction: timepoint, events: seen });
|
|
413
|
-
return failed("invalid_transaction_state", timepoint, c.network);
|
|
414
|
-
}
|
|
415
381
|
/**
|
|
416
382
|
* The finalized head's height, read before `deadline`. Undefined when a read fails or the header names no number, a
|
|
417
383
|
* node answer this facilitator cannot read; either is a `node-call-failed` entry with the call. A read `deadline`
|
|
@@ -434,176 +400,187 @@ export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
|
434
400
|
return undefined;
|
|
435
401
|
}
|
|
436
402
|
}
|
|
437
|
-
/**
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
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);
|
|
452
|
-
return undefined;
|
|
453
|
-
}
|
|
454
|
-
}
|
|
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
|
-
*/
|
|
460
|
-
async function findIn(c, url, n, left) {
|
|
461
|
-
const hash = await rpc(url, "chain_getBlockHash", [n], left());
|
|
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
|
-
}
|
|
472
|
-
const xts = isObject(block) && isObject(block["block"]) ? block["block"]["extrinsics"] : undefined;
|
|
473
|
-
if (typeof hash !== "string" || !Array.isArray(xts))
|
|
474
|
-
throw new NodeError("malformed", true, `block ${n}`);
|
|
475
|
-
return { hash, index: xts.findIndex((x) => isLowerHex(x) && extrinsicHash(Buffer.from(x.slice(2), "hex")) === c.id) };
|
|
476
|
-
}
|
|
477
|
-
/**
|
|
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
|
-
}
|
|
403
|
+
/** A JSON-RPC block number, as a header prints it. */
|
|
404
|
+
function heightOf(header, call) {
|
|
405
|
+
const n = blockNumber(header);
|
|
406
|
+
if (n === undefined)
|
|
407
|
+
throw new NodeError("malformed", true, `${call}: number`);
|
|
408
|
+
return BigInt(n);
|
|
502
409
|
}
|
|
503
410
|
/**
|
|
504
|
-
*
|
|
505
|
-
*
|
|
506
|
-
*
|
|
507
|
-
*
|
|
508
|
-
*
|
|
509
|
-
*
|
|
510
|
-
*
|
|
511
|
-
* passed. Gives the final answer, or where the scan has got to.
|
|
411
|
+
* The reader lcp's Polkadot read takes, over the network's JSON-RPC node, each call bounded by `deadline` and by the
|
|
412
|
+
* node call bound: a block's extrinsics by `chain_getBlock`, read in one of `blockReads`' slots and bounded by the
|
|
413
|
+
* runtime's `System.BlockLength`; an extrinsic's events by `System.Events` at its block, decoded with the network's
|
|
414
|
+
* metadata, each argument as the codec gives it plainly (an account in SS58, an amount as an integer or its decimal,
|
|
415
|
+
* a result as `{ ok }` or `{ err }`); the account nonce from `System.Account` at the finalized head or the best
|
|
416
|
+
* block; the heights from the headers; and the validation at the best block. A read that fails rejects, and lcp's
|
|
417
|
+
* read answers it `unreadable`.
|
|
512
418
|
*/
|
|
513
|
-
|
|
419
|
+
function reader(c, deadline) {
|
|
514
420
|
const url = byNetwork.get(c.network).rpc;
|
|
515
421
|
const left = () => deadline - performance.now();
|
|
516
|
-
const
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
422
|
+
const call = (method, params, maxBytes) => rpc(url, method, params, left(), maxBytes);
|
|
423
|
+
const hashAt = async (block) => {
|
|
424
|
+
if (typeof block !== "bigint")
|
|
425
|
+
return block;
|
|
426
|
+
const hash = await call("chain_getBlockHash", [Number(block)]);
|
|
427
|
+
if (hash === null)
|
|
428
|
+
return null;
|
|
429
|
+
if (!isLowerHex(hash) || hash.length !== 66)
|
|
430
|
+
throw new NodeError("malformed", true, "chain_getBlockHash");
|
|
431
|
+
return hash;
|
|
432
|
+
};
|
|
433
|
+
const blockAt = async (hash) => {
|
|
434
|
+
const release = await blockReads.take(left());
|
|
435
|
+
if (release === undefined)
|
|
436
|
+
throw new NodeError("spent", false, "chain_getBlock: no block read slot");
|
|
437
|
+
let block;
|
|
438
|
+
try {
|
|
439
|
+
block = await call("chain_getBlock", [hash], c.bounds.blockAnswerBytes);
|
|
532
440
|
}
|
|
533
|
-
|
|
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;
|
|
441
|
+
finally {
|
|
442
|
+
release();
|
|
545
443
|
}
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
444
|
+
if (block === null)
|
|
445
|
+
return null;
|
|
446
|
+
const inner = isObject(block) ? block["block"] : undefined;
|
|
447
|
+
const xts = isObject(inner) ? inner["extrinsics"] : undefined;
|
|
448
|
+
if (!isObject(inner) || !Array.isArray(xts) || !xts.every(isLowerHex))
|
|
449
|
+
throw new NodeError("malformed", true, "chain_getBlock");
|
|
450
|
+
return { height: heightOf(inner["header"], "chain_getBlock"), extrinsics: xts };
|
|
451
|
+
};
|
|
452
|
+
const finalizedHash = async () => {
|
|
453
|
+
const hash = await call("chain_getFinalizedHead", []);
|
|
454
|
+
if (!isLowerHex(hash) || hash.length !== 66)
|
|
455
|
+
throw new NodeError("malformed", true, "chain_getFinalizedHead");
|
|
456
|
+
return hash;
|
|
457
|
+
};
|
|
458
|
+
return {
|
|
459
|
+
network: c.network,
|
|
460
|
+
async rawExtrinsics(block) {
|
|
461
|
+
const hash = await hashAt(block);
|
|
462
|
+
const read = hash === null ? null : await blockAt(hash);
|
|
463
|
+
return read === null ? null : read.extrinsics;
|
|
464
|
+
},
|
|
465
|
+
async extrinsic(block, index) {
|
|
466
|
+
const hash = await hashAt(block);
|
|
467
|
+
const read = hash === null ? null : await blockAt(hash);
|
|
468
|
+
const xt = read?.extrinsics[index];
|
|
469
|
+
if (hash === null || read === null || xt === undefined)
|
|
470
|
+
return null;
|
|
471
|
+
const raw = await call("state_getStorage", [c.eventsKey, hash]);
|
|
472
|
+
const records = c.api.createType("Vec<EventRecord>", raw);
|
|
473
|
+
const mine = records.filter((r) => r.phase.isApplyExtrinsic && r.phase.asApplyExtrinsic.toNumber() === index);
|
|
474
|
+
const events = mine.map((r) => ({
|
|
475
|
+
pallet: r.event.section,
|
|
476
|
+
method: r.event.method,
|
|
477
|
+
data: r.event.data.map((d) => d.toPrimitive()),
|
|
478
|
+
}));
|
|
479
|
+
return {
|
|
480
|
+
at: { height: read.height, hash: hash },
|
|
481
|
+
hash: extrinsicHash(Buffer.from(xt.slice(2), "hex")),
|
|
482
|
+
success: events.some((e) => e.pallet === "system" && e.method === "ExtrinsicSuccess"),
|
|
483
|
+
events,
|
|
484
|
+
};
|
|
485
|
+
},
|
|
486
|
+
async finalizedHeight() {
|
|
487
|
+
return heightOf(await call("chain_getHeader", [await finalizedHash()]), "chain_getHeader");
|
|
488
|
+
},
|
|
489
|
+
async headHeight() {
|
|
490
|
+
return heightOf(await call("chain_getHeader", []), "chain_getHeader");
|
|
491
|
+
},
|
|
492
|
+
async accountNonce(account, at) {
|
|
493
|
+
const hash = at === "finalized" ? await finalizedHash() : await call("chain_getBlockHash", []);
|
|
494
|
+
const key = c.api.query["system"]?.["account"]?.key(account);
|
|
495
|
+
if (key === undefined)
|
|
496
|
+
throw new NodeError("malformed", true, "metadata: System.Account");
|
|
497
|
+
const raw = await call("state_getStorage", [key, hash]);
|
|
498
|
+
if (raw === null)
|
|
499
|
+
return 0n;
|
|
500
|
+
const info = c.api.createType("AccountInfo", raw);
|
|
501
|
+
return info.nonce.toBigInt();
|
|
502
|
+
},
|
|
503
|
+
async validate(extrinsic) {
|
|
504
|
+
const best = await call("chain_getBlockHash", []);
|
|
505
|
+
if (!isLowerHex(best) || best.length !== 66)
|
|
506
|
+
throw new NodeError("malformed", true, "chain_getBlockHash");
|
|
507
|
+
const head = heightOf(await call("chain_getHeader", [best]), "chain_getHeader");
|
|
508
|
+
const validity = await call("state_call", [
|
|
509
|
+
"TaggedTransactionQueue_validate_transaction",
|
|
510
|
+
`0x${EXTERNAL}${extrinsic.slice(2)}${best.slice(2)}`,
|
|
511
|
+
best,
|
|
512
|
+
]);
|
|
513
|
+
if (typeof validity !== "string")
|
|
514
|
+
throw new NodeError("malformed", true, "state_call: the validity");
|
|
515
|
+
return { valid: validity.startsWith("0x00"), head };
|
|
516
|
+
},
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* lcp's read of the payment, the act `payment` at the final mark, `finalized`, after the position `from` the settler
|
|
521
|
+
* read before its submission, resuming from `search`, the search position an earlier answer returned, or else from
|
|
522
|
+
* the one `from` holds. A request whose payment the form's checks refuse, or that lcp's `reference` or `bound` refuses, is read
|
|
523
|
+
* as nothing: `unreadable`, `unparseable`. One whose metadata cannot be loaded is `unreadable`, `transport`.
|
|
524
|
+
*/
|
|
525
|
+
async function status(r, deadline, from, search) {
|
|
526
|
+
const l = await local(r);
|
|
527
|
+
if (typeof l === "string")
|
|
528
|
+
return { state: "unreadable", reason: "unparseable", foreign: [] };
|
|
529
|
+
const c = await decode(l, deadline - performance.now());
|
|
530
|
+
if (typeof c === "string")
|
|
531
|
+
return { state: "unreadable", reason: "unparseable", foreign: [] };
|
|
532
|
+
if ("spent" in c)
|
|
533
|
+
return { state: "unreadable", reason: "transport", foreign: [] };
|
|
534
|
+
return read(c, r, deadline, from, search);
|
|
535
|
+
}
|
|
536
|
+
async function read(c, r, deadline, from, search) {
|
|
537
|
+
const ref = await exactPolkadotRemark.reference(r.paymentPayload, r.paymentRequirements);
|
|
538
|
+
const h = await exactPolkadotRemark.bound(r.paymentPayload);
|
|
539
|
+
if (isRefusal(ref) || isRefusal(h))
|
|
540
|
+
return { state: "unreadable", reason: "unparseable", foreign: [] };
|
|
541
|
+
const resume = search ?? from?.search;
|
|
542
|
+
return exactPolkadotRemark.status({ ...ref, h }, reader(c, deadline), {
|
|
543
|
+
act: "payment",
|
|
544
|
+
finality: "finalized",
|
|
545
|
+
...(from === undefined ? {} : { after: from.after }),
|
|
546
|
+
...(resume === undefined ? {} : { search: resume }),
|
|
547
|
+
});
|
|
566
548
|
}
|
|
567
549
|
/**
|
|
568
|
-
*
|
|
569
|
-
*
|
|
570
|
-
*
|
|
571
|
-
*
|
|
550
|
+
* Reads the payment by lcp's read every second until `deadline`, from the search position `from`, answering with the
|
|
551
|
+
* first final answer: success once lcp's read settles the extrinsic presented at the finalized head, naming its
|
|
552
|
+
* timepoint, and `invalid_transaction_state` naming the transaction once it answers `failed`. Each live answer's
|
|
553
|
+
* search position is where the next read resumes. Once `deadline` has passed, nothing is read: the answer is pending
|
|
554
|
+
* with the extrinsic's hash. Submits nothing.
|
|
572
555
|
*/
|
|
573
|
-
async function
|
|
574
|
-
let
|
|
556
|
+
async function watch(c, r, from, deadline) {
|
|
557
|
+
let search = from.search;
|
|
575
558
|
for (;;) {
|
|
576
|
-
if (
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
559
|
+
if (deadline - performance.now() <= 0)
|
|
560
|
+
return pending(c.id, c.network);
|
|
561
|
+
const st = await read(c, r, deadline, from, search);
|
|
562
|
+
if (st.state === "settled" && st.presented === "yes") {
|
|
563
|
+
return { success: true, transaction: st.transaction, network: c.network, payer: c.payer };
|
|
580
564
|
}
|
|
581
|
-
if (
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
return step.answer;
|
|
585
|
-
at = step;
|
|
565
|
+
if (st.state === "failed") {
|
|
566
|
+
log({ event: "settlement-failed", ...about(c), why: st.reason, ...(st.transaction === undefined ? {} : { at: st.transaction }) });
|
|
567
|
+
return failed("invalid_transaction_state", st.transaction ?? c.id, c.network);
|
|
586
568
|
}
|
|
587
|
-
if (
|
|
588
|
-
|
|
589
|
-
|
|
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
|
-
}
|
|
569
|
+
if (st.state === "pending" && st.search !== undefined)
|
|
570
|
+
search = st.search;
|
|
571
|
+
if (performance.now() + POLL_MS > deadline)
|
|
594
572
|
return pending(c.id, c.network);
|
|
595
|
-
}
|
|
596
573
|
await sleep(POLL_MS);
|
|
597
574
|
}
|
|
598
575
|
}
|
|
599
576
|
/**
|
|
600
|
-
* Submits, then
|
|
601
|
-
*
|
|
602
|
-
*
|
|
603
|
-
*
|
|
604
|
-
* is not sent, and its entry is `settle-deadline-passed`.
|
|
577
|
+
* Submits, then reads the payment until `deadline`. A refusal that says the node has already seen the extrinsic or
|
|
578
|
+
* its nonce is a consumed payment: `invalid_transaction_state` with the extrinsic's hash. Any other refusal, or a
|
|
579
|
+
* request that cannot have reached the node, gives `unexpected_settle_error` with no transaction: nothing was
|
|
580
|
+
* submitted, the nonce is not consumed, and the answer is not final. So does a submission `deadline` leaves no time
|
|
581
|
+
* for: it is not sent, and its entry is `settle-deadline-passed`.
|
|
605
582
|
*/
|
|
606
|
-
async function submit(c,
|
|
583
|
+
async function submit(c, r, from, deadline) {
|
|
607
584
|
const url = byNetwork.get(c.network).rpc;
|
|
608
585
|
try {
|
|
609
586
|
await rpc(url, "author_submitExtrinsic", [c.hex], deadline - performance.now());
|
|
@@ -618,71 +595,18 @@ export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
|
618
595
|
log(entry, e);
|
|
619
596
|
return e instanceof RpcError ? failed("invalid_transaction_state", c.id, c.network) : pending(c.id, c.network);
|
|
620
597
|
}
|
|
621
|
-
return
|
|
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);
|
|
633
|
-
}
|
|
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
|
-
*/
|
|
641
|
-
async function keep(c, answer, deadline) {
|
|
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);
|
|
598
|
+
return watch(c, r, from, deadline);
|
|
654
599
|
}
|
|
655
600
|
/**
|
|
656
|
-
*
|
|
657
|
-
*
|
|
658
|
-
*
|
|
659
|
-
*
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
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);
|
|
668
|
-
}
|
|
669
|
-
return keep(decoded, await scan(decoded, since, unread, waitUntil, true), deadline);
|
|
670
|
-
}
|
|
671
|
-
/**
|
|
672
|
-
* Answers within `settleWaitMs`. The stored answer is read before the node is asked anything, and a final one is
|
|
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.
|
|
601
|
+
* Answers within `settleWaitMs`, less a reserve in which the settler stores the answer: a second, or a quarter of a
|
|
602
|
+
* shorter wait. The deadline is checked before each node read: the decode, the finalized head read and the
|
|
603
|
+
* validation. A deadline spent there sends no node call, and gives `unexpected_settle_error`; so does a call inside
|
|
604
|
+
* one of them that the deadline leaves no time for, which is not sent, with its entry naming the call. A refusal the
|
|
605
|
+
* client's own bytes give comes first, so the decode's refusals, which need the metadata, are given when the deadline
|
|
606
|
+
* leaves time for it. The read starts after the finalized head read before validation (never before the era's birth):
|
|
607
|
+
* validation at the best block shows the extrinsic absent from that block's ancestry, and the finalized head is in
|
|
608
|
+
* every later best chain; its position keeps the head the validation answered valid at, which proves the era's last
|
|
609
|
+
* block.
|
|
686
610
|
*/
|
|
687
611
|
async function settle(r) {
|
|
688
612
|
const deadline = performance.now() + settleWaitMs;
|
|
@@ -691,18 +615,6 @@ export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
|
691
615
|
const l = await local(r);
|
|
692
616
|
if (typeof l === "string")
|
|
693
617
|
return failed(l, "", network);
|
|
694
|
-
let stored;
|
|
695
|
-
try {
|
|
696
|
-
stored = await inTime(s.read(l.node.network, l.id), deadline);
|
|
697
|
-
}
|
|
698
|
-
catch (e) {
|
|
699
|
-
log({ event: "store-call-failed", ...about({ network: l.node.network, id: l.id }), call: "read" }, e);
|
|
700
|
-
return pending(l.id, l.node.network);
|
|
701
|
-
}
|
|
702
|
-
if (stored.state === "answered" && !isPending(stored.answer))
|
|
703
|
-
return repeatOf(stored.answer);
|
|
704
|
-
if (stored.state !== "none")
|
|
705
|
-
return follow(l, stored.since, stored.unread, deadline);
|
|
706
618
|
const hashed = { network: l.node.network, id: l.id };
|
|
707
619
|
if (left() <= 0)
|
|
708
620
|
return unexpectedSettle(log, deadlinePassed(hashed, "node reads"));
|
|
@@ -723,25 +635,39 @@ export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
|
723
635
|
return failed(settleReason(v), "", network);
|
|
724
636
|
if ("spent" in v)
|
|
725
637
|
return unexpectedSettle(log, deadlinePassed(c, v.spent));
|
|
726
|
-
const waitUntil = deadline -
|
|
638
|
+
const waitUntil = deadline - Math.min(1_000, settleWaitMs / 4);
|
|
727
639
|
if (waitUntil - performance.now() <= 0)
|
|
728
|
-
return unexpectedSettle(log, deadlinePassed(c, "
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
640
|
+
return unexpectedSettle(log, deadlinePassed(c, "author_submitExtrinsic"));
|
|
641
|
+
return submit(c, r, startAt(c, finalized, v.best), waitUntil);
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Where the read of an extrinsic validated at the best block `best` searches from: after the finalized head read
|
|
645
|
+
* before that validation (never before the era's birth), keeping `best` as the head the chain answered it valid at.
|
|
646
|
+
*/
|
|
647
|
+
function startAt(c, finalized, best) {
|
|
648
|
+
const birth = c.era.birth(best);
|
|
649
|
+
const since = Math.min(finalized === undefined ? birth : Math.max(birth, finalized + 1), lastBlock(c, best));
|
|
650
|
+
return { after: BigInt(since) - 1n, search: { next: BigInt(since), hits: [], validated: BigInt(best) } };
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Where the settler's read of the payment `r` searches from, read before anything is submitted as `/settle` reads it:
|
|
654
|
+
* the finalized head, then the validation at the best block. Undefined for a payment the form's checks refuse, where
|
|
655
|
+
* a read fails, and where the chain does not answer the extrinsic valid.
|
|
656
|
+
*/
|
|
657
|
+
async function position(r, deadline) {
|
|
658
|
+
const l = await local(r);
|
|
659
|
+
if (typeof l === "string")
|
|
660
|
+
return undefined;
|
|
661
|
+
const c = await decode(l, deadline - performance.now());
|
|
662
|
+
if (typeof c === "string" || "spent" in c)
|
|
663
|
+
return undefined;
|
|
664
|
+
const finalized = await finalizedHeight(c, l.node.rpc, deadline);
|
|
665
|
+
if (typeof finalized === "object")
|
|
666
|
+
return undefined;
|
|
667
|
+
const v = await validate(c, deadline - performance.now());
|
|
668
|
+
if (typeof v === "string" || "spent" in v)
|
|
669
|
+
return undefined;
|
|
670
|
+
return startAt(c, finalized, v.best);
|
|
745
671
|
}
|
|
746
672
|
async function close() {
|
|
747
673
|
const all = [...apis];
|
|
@@ -749,5 +675,5 @@ export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
|
749
675
|
// A load that failed has gone to the operator log from `decode` or `apiFor`; a failed disconnect goes there here.
|
|
750
676
|
await Promise.all(all.map(([network, p]) => p.then((api) => api.disconnect().catch((e) => log({ event: "node-call-failed", network, call: "disconnect" }, e)), () => undefined)));
|
|
751
677
|
}
|
|
752
|
-
return { verify, settle, close, networks: nodes.map((n) => n.network) };
|
|
678
|
+
return { verify, settle, local, status, position, close, networks: nodes.map((n) => n.network) };
|
|
753
679
|
}
|