@integraledger/profile-facilitator 0.1.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.
@@ -0,0 +1,457 @@
1
+ /**
2
+ * Rule 5 of `x402/exact/polkadot/lcp-assets-remark` against one network's RPC node: `/verify` decodes the extrinsic
3
+ * with the network's runtime metadata, checks its call against the requirements and asks the node to validate it;
4
+ * `/settle` repeats that, claims the extrinsic's hash, submits, and scans new blocks for its inclusion and events.
5
+ */
6
+ import { ApiPromise } from "@polkadot/api";
7
+ import { blake2b } from "@noble/hashes/blake2.js";
8
+ import { decodeProfileCall, exactPolkadotRemark, extrinsicHash, polkadotPairingOf, ss58Decode, } from "@integraledger/lcp/polkadot";
9
+ import { failed, invalid, isObject, isPending, operatorLog, pending, } from "./answers.js";
10
+ import { NODE_TIMEOUT_MS, NodeError, postJson, sleep, within } from "./http.js";
11
+ import { answerReserve, inTime } from "./store.js";
12
+ const POLL_MS = 1_000;
13
+ /** The longest a metadata load may take: its calls are each bounded, and this bounds them together. */
14
+ const INIT_TIMEOUT_MS = 30_000;
15
+ /** Milliseconds per block, used to turn the era's last block into the row's `until`. */
16
+ const SLOW_BLOCK_MS = 12_000;
17
+ /** `TransactionSource::External`. */
18
+ const EXTERNAL = "02";
19
+ /** The JSON-RPC error `author_submitExtrinsic` gives for an extrinsic already in the pool. */
20
+ const ALREADY_IMPORTED = 1013;
21
+ /** The JSON-RPC error for an extrinsic the pool refuses as invalid; its message or data names the reason. */
22
+ const INVALID_TRANSACTION = 1010;
23
+ /** The JSON-RPC error for an extrinsic the pool has recently seen and will not take again for a while. */
24
+ const TEMPORARILY_BANNED = 1012;
25
+ /** A JSON-RPC error answer: the node read the call and refused it. */
26
+ class RpcError extends Error {
27
+ code;
28
+ data;
29
+ constructor(code, message, data) {
30
+ super(message);
31
+ this.code = code;
32
+ this.data = data;
33
+ }
34
+ }
35
+ /**
36
+ * 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), so it may be included.
38
+ */
39
+ function seenBefore(e) {
40
+ if (e.code === ALREADY_IMPORTED || e.code === TEMPORARILY_BANNED)
41
+ return true;
42
+ return e.code === INVALID_TRANSACTION && /outdated|stale/i.test(`${e.message} ${e.data}`);
43
+ }
44
+ async function rpc(url, method, params, timeoutMs) {
45
+ const answer = await postJson(url, { jsonrpc: "2.0", id: 1, method, params }, timeoutMs);
46
+ if (!isObject(answer))
47
+ throw new NodeError("malformed", true, `${method}: not a JSON-RPC answer`);
48
+ const error = answer["error"];
49
+ if (isObject(error)) {
50
+ const data = error["data"] === undefined ? "" : String(error["data"]);
51
+ throw new RpcError(typeof error["code"] === "number" ? error["code"] : 0, String(error["message"]), data);
52
+ }
53
+ return answer["result"];
54
+ }
55
+ /** A provider for `@polkadot/api` whose every call is one bounded JSON-RPC POST, with no subscriptions. */
56
+ function boundedProvider(url) {
57
+ const provider = {
58
+ hasSubscriptions: false,
59
+ isClonable: false,
60
+ isConnected: true,
61
+ clone() {
62
+ return boundedProvider(url);
63
+ },
64
+ async connect() { },
65
+ async disconnect() { },
66
+ on() {
67
+ return () => { };
68
+ },
69
+ send(method, params) {
70
+ return rpc(url, method, params);
71
+ },
72
+ subscribe() {
73
+ return Promise.reject(new Error("subscriptions are not used"));
74
+ },
75
+ unsubscribe() {
76
+ return Promise.resolve(false);
77
+ },
78
+ };
79
+ return provider;
80
+ }
81
+ function hexOf(b) {
82
+ return Buffer.from(b).toString("hex");
83
+ }
84
+ function isLowerHex(v) {
85
+ return typeof v === "string" && /^0x(?:[0-9a-f]{2})+$/.test(v);
86
+ }
87
+ function blockNumber(header) {
88
+ const n = isObject(header) ? header["number"] : undefined;
89
+ if (typeof n === "number")
90
+ return n;
91
+ if (typeof n === "string" && /^0x[0-9a-f]+$/i.test(n))
92
+ return Number.parseInt(n, 16);
93
+ return undefined;
94
+ }
95
+ export function createPolkadot(nodes, s, settleWaitMs) {
96
+ const byNetwork = new Map(nodes.map((n) => [n.network, n]));
97
+ const apis = new Map();
98
+ /** The network's metadata, loaded once and loaded again when the node's runtime version changes. */
99
+ async function apiFor(node, timeoutMs = NODE_TIMEOUT_MS) {
100
+ const version = await rpc(node.rpc, "state_getRuntimeVersion", [], timeoutMs);
101
+ const spec = isObject(version) ? version["specVersion"] : undefined;
102
+ if (typeof spec !== "number")
103
+ throw new NodeError("malformed", true, "state_getRuntimeVersion: no specVersion");
104
+ let loading = apis.get(node.network);
105
+ if (loading !== undefined) {
106
+ const api = await loading.catch(() => undefined);
107
+ if (api !== undefined && api.runtimeVersion.specVersion.toNumber() === spec)
108
+ return api;
109
+ apis.delete(node.network);
110
+ void api?.disconnect();
111
+ }
112
+ const fresh = load(node);
113
+ apis.set(node.network, fresh);
114
+ fresh.catch(() => {
115
+ if (apis.get(node.network) === fresh)
116
+ apis.delete(node.network);
117
+ });
118
+ return fresh;
119
+ }
120
+ async function load(node) {
121
+ const api = new ApiPromise({ provider: boundedProvider(node.rpc), noInitWarn: true, initWasm: false });
122
+ try {
123
+ await within(api.isReadyOrError, INIT_TIMEOUT_MS);
124
+ }
125
+ catch (e) {
126
+ void api.disconnect();
127
+ throw e;
128
+ }
129
+ if (api.genesisHash.toHex().slice(2, 34) !== node.network.slice("polkadot:".length)) {
130
+ void api.disconnect();
131
+ throw new Error(`the node at ${node.network} serves another chain`);
132
+ }
133
+ return api;
134
+ }
135
+ /** The checks of rule 5 that read nothing from the node. */
136
+ async function local(r) {
137
+ const req = r.paymentRequirements;
138
+ const node = byNetwork.get(req.network);
139
+ if (node === undefined)
140
+ return "invalid_network";
141
+ if (polkadotPairingOf(req) === undefined)
142
+ return "invalid_payment_requirements";
143
+ const { extrinsic, call } = r.paymentPayload.payload;
144
+ if (!isLowerHex(extrinsic) || !isLowerHex(call))
145
+ return "invalid_payload";
146
+ const bound = await exactPolkadotRemark.bound({ x402Version: 2, accepted: req, payload: { extrinsic, call } });
147
+ if (typeof bound !== "string")
148
+ return "invalid_payload";
149
+ const profile = decodeProfileCall(Buffer.from(call.slice(2), "hex"));
150
+ const dest = ss58Decode(req.payTo);
151
+ if ("refused" in profile || "refused" in dest)
152
+ return "invalid_payload";
153
+ if (profile.assetId !== Number(req.asset) || profile.amount !== BigInt(req.amount))
154
+ return "invalid_payload";
155
+ if (hexOf(profile.dest) !== hexOf(dest))
156
+ return "invalid_payload";
157
+ return {
158
+ node,
159
+ extrinsic,
160
+ call,
161
+ id: extrinsicHash(Buffer.from(extrinsic.slice(2), "hex")),
162
+ assetId: profile.assetId,
163
+ remarkHash: `0x${hexOf(blake2b(profile.remark, { dkLen: 32 }))}`,
164
+ };
165
+ }
166
+ /** The checks of rule 5 that decode the extrinsic with the network's metadata, within `timeoutMs`. */
167
+ async function decode(l, timeoutMs) {
168
+ let api;
169
+ try {
170
+ api = await within(apiFor(l.node, timeoutMs), timeoutMs);
171
+ }
172
+ catch {
173
+ return "unexpected_verify_error";
174
+ }
175
+ let xt;
176
+ try {
177
+ xt = api.createType("Extrinsic", l.extrinsic);
178
+ }
179
+ catch {
180
+ return "invalid_payload";
181
+ }
182
+ if (!xt.isSigned || xt.type !== 4 || xt.toHex() !== l.extrinsic || xt.method.toHex() !== l.call)
183
+ return "invalid_payload";
184
+ const calls = xt.method.args[0];
185
+ if (xt.method.section !== "utility" ||
186
+ xt.method.method !== "batchAll" ||
187
+ !Array.isArray(calls) ||
188
+ calls.length !== 2 ||
189
+ calls[0].section !== "assets" ||
190
+ calls[0].method !== "transferKeepAlive" ||
191
+ calls[1].section !== "system" ||
192
+ calls[1].method !== "remarkWithEvent") {
193
+ return "invalid_payload";
194
+ }
195
+ if (!xt.era.isMortalEra)
196
+ return "invalid_payload";
197
+ const eventsKey = api.query["system"]?.["events"]?.key();
198
+ if (eventsKey === undefined)
199
+ return "unexpected_verify_error";
200
+ return {
201
+ network: l.node.network,
202
+ api,
203
+ hex: l.extrinsic,
204
+ id: l.id,
205
+ payer: xt.signer.toString(),
206
+ assetId: l.assetId,
207
+ remarkHash: l.remarkHash,
208
+ era: xt.era.asMortalEra,
209
+ eventsKey,
210
+ };
211
+ }
212
+ /**
213
+ * `TaggedTransactionQueue_validate_transaction` at the best block, within `timeoutMs`: the best block's height, and
214
+ * when the era ends.
215
+ */
216
+ async function validate(c, timeoutMs = 3 * NODE_TIMEOUT_MS) {
217
+ const url = byNetwork.get(c.network).rpc;
218
+ const deadline = performance.now() + timeoutMs;
219
+ const left = () => deadline - performance.now();
220
+ let best;
221
+ let header;
222
+ let validity;
223
+ try {
224
+ best = await rpc(url, "chain_getBlockHash", [], left());
225
+ if (!isLowerHex(best) || best.length !== 66)
226
+ return "unexpected_verify_error";
227
+ header = await rpc(url, "chain_getHeader", [best], left());
228
+ validity = await rpc(url, "state_call", ["TaggedTransactionQueue_validate_transaction", `0x${EXTERNAL}${c.hex.slice(2)}${best.slice(2)}`, best], left());
229
+ }
230
+ catch {
231
+ return "unexpected_verify_error";
232
+ }
233
+ const height = blockNumber(header);
234
+ if (height === undefined || typeof validity !== "string")
235
+ return "unexpected_verify_error";
236
+ if (!validity.startsWith("0x00"))
237
+ return "invalid_transaction";
238
+ const blocksLeft = Math.max(0, c.era.death(height) - height);
239
+ return { best: height, until: new Date(Date.now() + blocksLeft * SLOW_BLOCK_MS) };
240
+ }
241
+ async function verify(r) {
242
+ const l = await local(r);
243
+ if (typeof l === "string")
244
+ return invalid(l);
245
+ const c = await decode(l, INIT_TIMEOUT_MS);
246
+ if (typeof c === "string")
247
+ return invalid(c);
248
+ const v = await validate(c);
249
+ return typeof v === "string" ? invalid(v, c.payer) : { isValid: true, payer: c.payer };
250
+ }
251
+ /**
252
+ * The answer for the extrinsic at `index` of block `hash`, from that block's events. A failure is logged for the
253
+ * operator when `final`, that is when the block was read at finality.
254
+ */
255
+ async function included(c, url, hash, index, timeoutMs, final) {
256
+ const timepoint = `${hash}-${index}`;
257
+ const raw = await rpc(url, "state_getStorage", [c.eventsKey, hash], timeoutMs);
258
+ const records = c.api.createType("Vec<EventRecord>", raw);
259
+ const mine = records.filter((r) => r.phase.isApplyExtrinsic && r.phase.asApplyExtrinsic.toNumber() === index);
260
+ const has = (section, method, test) => mine.some((r) => r.event.section === section && r.event.method === method && test(r.event.data));
261
+ const ok = has("system", "ExtrinsicSuccess", () => true) &&
262
+ has("system", "Remarked", (d) => d[1]?.toHex() === c.remarkHash) &&
263
+ has("assets", "Transferred", (d) => d[0]?.toString() === String(c.assetId));
264
+ if (ok)
265
+ return { success: true, transaction: timepoint, network: c.network, payer: c.payer };
266
+ const seen = mine.map((r) => `${r.event.section}.${r.event.method}`);
267
+ if (final)
268
+ operatorLog({ event: "settlement-failed", network: c.network, transaction: timepoint, events: seen });
269
+ return failed("invalid_transaction_state", timepoint, c.network);
270
+ }
271
+ /** The finalized head's height, read before `deadline`; undefined when the node does not give it. */
272
+ async function finalizedHeight(url, deadline) {
273
+ try {
274
+ const hash = await rpc(url, "chain_getFinalizedHead", [], deadline - performance.now());
275
+ return blockNumber(await rpc(url, "chain_getHeader", [hash], deadline - performance.now()));
276
+ }
277
+ catch {
278
+ return undefined;
279
+ }
280
+ }
281
+ /** 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. */
282
+ async function findIn(c, url, n, left) {
283
+ const hash = await rpc(url, "chain_getBlockHash", [n], left());
284
+ const block = await rpc(url, "chain_getBlock", [hash], left());
285
+ const xts = isObject(block) && isObject(block["block"]) ? block["block"]["extrinsics"] : undefined;
286
+ if (typeof hash !== "string" || !Array.isArray(xts))
287
+ throw new NodeError("malformed", true, `block ${n}`);
288
+ return { hash, index: xts.findIndex((x) => isLowerHex(x) && extrinsicHash(Buffer.from(x.slice(2), "hex")) === c.id) };
289
+ }
290
+ /**
291
+ * One pass until `deadline`, no further than the era's last block. First the blocks from `at.proven` up to the
292
+ * finalized head, which are read at finality; once every block to the era's last is read so, the extrinsic can never
293
+ * be included, and the answer is `invalid_transaction_state` with its hash. Then the blocks above them, up to the head,
294
+ * where only a success is an answer: a failure there waits until its block is final. Gives the final answer, or where
295
+ * the scan has got to.
296
+ */
297
+ async function scanOnce(c, since, at, deadline) {
298
+ const url = byNetwork.get(c.network).rpc;
299
+ const left = () => deadline - performance.now();
300
+ const last = c.era.death(since) - 1;
301
+ let { proven, next } = at;
302
+ try {
303
+ const finalized = await finalizedHeight(url, deadline);
304
+ while (finalized !== undefined && proven <= Math.min(finalized, last) && left() > 0) {
305
+ const found = await findIn(c, url, proven, left);
306
+ if (found.index >= 0)
307
+ return { answer: await included(c, url, found.hash, found.index, left(), true) };
308
+ proven += 1;
309
+ }
310
+ if (proven > last) {
311
+ operatorLog({ event: "settlement-expired", network: c.network, transaction: c.id });
312
+ return { answer: failed("invalid_transaction_state", c.id, c.network) };
313
+ }
314
+ next = Math.max(next, proven);
315
+ const head = blockNumber(await rpc(url, "chain_getHeader", [], left()));
316
+ while (head !== undefined && next <= Math.min(head, last) && left() > 0) {
317
+ const found = await findIn(c, url, next, left);
318
+ if (found.index >= 0) {
319
+ const answer = await included(c, url, found.hash, found.index, left(), false);
320
+ if (answer.success)
321
+ return { answer };
322
+ break;
323
+ }
324
+ next += 1;
325
+ }
326
+ }
327
+ catch {
328
+ // A failed read leaves the scan where it is; the next poll reads again.
329
+ }
330
+ return { proven, next };
331
+ }
332
+ /**
333
+ * Scans for the extrinsic from `since` every second until `deadline`, reading the stored answer too when `stored` is
334
+ * set, and answers with the first final answer either gives. Blocks read at finality that do not hold it move the
335
+ * stored `since` on. Submits nothing.
336
+ */
337
+ async function scan(c, since, deadline, stored) {
338
+ let at = { proven: since, next: since };
339
+ for (;;) {
340
+ if (stored) {
341
+ const row = await inTime(s.read(c.network, c.id), deadline).catch(() => undefined);
342
+ if (row?.state === "answered" && !isPending(row.answer))
343
+ return row.answer;
344
+ }
345
+ const step = await scanOnce(c, since, at, deadline);
346
+ if ("answer" in step)
347
+ return step.answer;
348
+ at = step;
349
+ if (performance.now() + POLL_MS > deadline) {
350
+ if (at.proven > since)
351
+ void s.advance(c.network, c.id, at.proven).catch(() => { });
352
+ return pending(c.id, c.network);
353
+ }
354
+ await sleep(POLL_MS);
355
+ }
356
+ }
357
+ /**
358
+ * Submits, then scans for the extrinsic until `deadline`. A refusal that says the node has already seen the extrinsic
359
+ * or its nonce is read as possibly included, and the scan runs; any other refusal means nothing was submitted.
360
+ */
361
+ async function submit(c, since, deadline) {
362
+ const url = byNetwork.get(c.network).rpc;
363
+ try {
364
+ await rpc(url, "author_submitExtrinsic", [c.hex], deadline - performance.now());
365
+ }
366
+ catch (e) {
367
+ if (e instanceof RpcError && !seenBefore(e))
368
+ return failed("unexpected_settle_error", "", c.network);
369
+ if (e instanceof NodeError && !e.sent)
370
+ return failed("unexpected_settle_error", "", c.network);
371
+ if (!(e instanceof RpcError))
372
+ return pending(c.id, c.network);
373
+ }
374
+ return scan(c, since, deadline, false);
375
+ }
376
+ /** Stores the answer, unless the row holds a final one; a failed write leaves the row for a later read of the chain. */
377
+ async function keep(c, answer, deadline) {
378
+ await inTime(s.answer(c.network, c.id, answer), deadline).catch(() => {
379
+ operatorLog({ event: "answer-not-stored", network: c.network, transaction: c.id });
380
+ });
381
+ return answer;
382
+ }
383
+ /**
384
+ * 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.
386
+ */
387
+ async function follow(l, since, deadline) {
388
+ const c = await decode(l, deadline - performance.now());
389
+ if (typeof c === "string" || since === null) {
390
+ const row = await inTime(s.read(l.node.network, l.id), deadline).catch(() => undefined);
391
+ return row?.state === "answered" ? row.answer : pending(l.id, l.node.network);
392
+ }
393
+ return keep(c, await scan(c, since, deadline - answerReserve(settleWaitMs), true), deadline);
394
+ }
395
+ /**
396
+ * Answers within `settleWaitMs`. The stored answer is read before the node is asked anything, and a final one is
397
+ * given as it is. A claimed id, or a stored pending answer, is read again from the chain. An answer with no
398
+ * transaction says nothing was submitted, so it is given only for an id the store does not hold: a submission the node
399
+ * refused releases the claim, and when nothing is released the answer is pending with its hash. When the store cannot
400
+ * be read, the facilitator cannot know whether the extrinsic was submitted, so the answer is pending with its hash. The
401
+ * scan starts after the finalized head read before validation (never before the era's birth): validation at the best
402
+ * block shows the extrinsic absent from that block's ancestry, and the finalized head is in every later best chain.
403
+ */
404
+ async function settle(r) {
405
+ const deadline = performance.now() + settleWaitMs;
406
+ const left = () => deadline - performance.now();
407
+ const network = r.paymentRequirements.network;
408
+ const settleReason = (v) => (v === "unexpected_verify_error" ? "unexpected_settle_error" : v);
409
+ const l = await local(r);
410
+ if (typeof l === "string")
411
+ return failed(l, "", network);
412
+ let stored;
413
+ try {
414
+ stored = await inTime(s.read(l.node.network, l.id), deadline);
415
+ }
416
+ catch {
417
+ return pending(l.id, l.node.network);
418
+ }
419
+ if (stored.state === "answered" && !isPending(stored.answer))
420
+ return stored.answer;
421
+ if (stored.state !== "none")
422
+ return follow(l, stored.since, deadline);
423
+ const c = await decode(l, left());
424
+ if (typeof c === "string")
425
+ return failed(settleReason(c), "", network);
426
+ const finalized = await finalizedHeight(l.node.rpc, deadline);
427
+ const v = await validate(c, left());
428
+ if (typeof v === "string")
429
+ return failed(settleReason(v), "", network);
430
+ if (left() <= 0)
431
+ return failed("unexpected_settle_error", "", network);
432
+ const birth = c.era.birth(v.best);
433
+ const since = finalized === undefined ? birth : Math.max(birth, finalized + 1);
434
+ let won;
435
+ try {
436
+ won = await inTime(s.claim(c.network, c.id, v.until, since), deadline);
437
+ }
438
+ catch {
439
+ return pending(c.id, c.network);
440
+ }
441
+ if (!won) {
442
+ const row = await inTime(s.read(c.network, c.id), deadline).catch(() => undefined);
443
+ return follow(l, row !== undefined && row.state !== "none" ? row.since : null, deadline);
444
+ }
445
+ const answer = await submit(c, since, deadline - answerReserve(settleWaitMs));
446
+ if (answer.success || answer.transaction !== "")
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);
450
+ }
451
+ async function close() {
452
+ const all = [...apis.values()];
453
+ apis.clear();
454
+ await Promise.all(all.map((p) => p.then((api) => api.disconnect()).catch(() => { })));
455
+ }
456
+ return { verify, settle, close, networks: nodes.map((n) => n.network) };
457
+ }
@@ -0,0 +1,44 @@
1
+ import { type SettleAnswer } from "./answers.js";
2
+ export declare const SCHEMA = "CREATE TABLE IF NOT EXISTS settlement (\n network text NOT NULL,\n id text NOT NULL,\n answer jsonb,\n until timestamptz NOT NULL,\n since bigint,\n PRIMARY KEY (network, id)\n)";
3
+ /** The bound on acquiring a connection, on each query as the client waits for it, and on each statement in the server. */
4
+ export declare const STORE_TIMEOUT_MS = 5000;
5
+ /** How long a row is kept after `until`. */
6
+ export declare const KEEP_AFTER_UNTIL_MS: number;
7
+ /**
8
+ * What the table holds for an id: nothing, a claim whose answer is not written yet, or the answer. `since` is, for a
9
+ * Polkadot extrinsic, the first block not yet shown at finality to lack it: at the claim, the block after the finalized
10
+ * head read before validation (never before the era's birth), and later moved on past blocks read at finality that do
11
+ * not hold it. It is null for Tron.
12
+ */
13
+ export type Stored = {
14
+ state: "none";
15
+ } | {
16
+ state: "claimed";
17
+ since: number | null;
18
+ } | {
19
+ state: "answered";
20
+ answer: SettleAnswer;
21
+ since: number | null;
22
+ };
23
+ export interface SettlementStore {
24
+ read(network: string, id: string): Promise<Stored>;
25
+ /** True when this call inserted the row, and so owns the submission. */
26
+ claim(network: string, id: string, until: Date, since?: number): Promise<boolean>;
27
+ /** Writes the answer unless the row already holds a final one. */
28
+ answer(network: string, id: string, answer: SettleAnswer): Promise<void>;
29
+ /** Removes a claim that has no answer: the claimant submitted nothing. True when a row was removed. */
30
+ release(network: string, id: string): Promise<boolean>;
31
+ /** Moves `since` on to `block`, never back. */
32
+ advance(network: string, id: string, block: number): Promise<void>;
33
+ /** Drops the rows whose `until` is more than `KEEP_AFTER_UNTIL_MS` past. */
34
+ drop(): Promise<void>;
35
+ close(): Promise<void>;
36
+ }
37
+ export declare function openStore(url: string): Promise<SettlementStore>;
38
+ /**
39
+ * The part of `settleWaitMs` kept for writing the answer once the wait for the chain ends: a second, or a quarter of a
40
+ * shorter wait. The node calls and the waits end that much before the deadline, so the answer is stored, then given.
41
+ */
42
+ export declare function answerReserve(settleWaitMs: number): number;
43
+ /** A store call bounded by `STORE_TIMEOUT_MS` and by what is left before `deadline` (a `performance.now()` time). */
44
+ export declare function inTime<T>(p: Promise<T>, deadline: number): Promise<T>;
package/dist/store.js ADDED
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The deduplication table: one row per settled payment, keyed by network and transaction id, holding the answer the
3
+ * first `/settle` gave. A row is claimed by one conditional insert, so concurrent settles of one payment submit once.
4
+ * A final answer is never replaced; a pending one is replaced by what a later read of the chain shows. A row is kept
5
+ * until `KEEP_AFTER_UNTIL_MS` after its validity window has ended, so a repeat in that time reads the stored answer and
6
+ * the chain before anything is verified again. Every call to the database is bounded by `STORE_TIMEOUT_MS`.
7
+ */
8
+ import pg from "pg";
9
+ import { isPending } from "./answers.js";
10
+ import { within } from "./http.js";
11
+ export const SCHEMA = `CREATE TABLE IF NOT EXISTS settlement (
12
+ network text NOT NULL,
13
+ id text NOT NULL,
14
+ answer jsonb,
15
+ until timestamptz NOT NULL,
16
+ since bigint,
17
+ PRIMARY KEY (network, id)
18
+ )`;
19
+ /** The bound on acquiring a connection, on each query as the client waits for it, and on each statement in the server. */
20
+ export const STORE_TIMEOUT_MS = 5_000;
21
+ /** How long a row is kept after `until`. */
22
+ export const KEEP_AFTER_UNTIL_MS = 24 * 60 * 60 * 1000;
23
+ const DROP_EVERY_MS = 60_000;
24
+ export async function openStore(url) {
25
+ const pool = new pg.Pool({
26
+ connectionString: url,
27
+ max: 10,
28
+ connectionTimeoutMillis: STORE_TIMEOUT_MS,
29
+ query_timeout: STORE_TIMEOUT_MS,
30
+ statement_timeout: STORE_TIMEOUT_MS,
31
+ });
32
+ pool.on("error", () => { });
33
+ await pool.query(SCHEMA);
34
+ const store = {
35
+ async read(network, id) {
36
+ const r = await pool.query("SELECT answer, since FROM settlement WHERE network = $1 AND id = $2", [network, id]);
37
+ const row = r.rows[0];
38
+ if (row === undefined)
39
+ return { state: "none" };
40
+ const since = row.since === null ? null : Number(row.since);
41
+ return row.answer === null ? { state: "claimed", since } : { state: "answered", answer: row.answer, since };
42
+ },
43
+ async claim(network, id, until, since) {
44
+ const r = await pool.query("INSERT INTO settlement (network, id, answer, until, since) VALUES ($1, $2, NULL, $3, $4) ON CONFLICT DO NOTHING", [network, id, until.toISOString(), since ?? null]);
45
+ return r.rowCount === 1;
46
+ },
47
+ async answer(network, id, answer) {
48
+ await pool.query(`UPDATE settlement SET answer = $3 WHERE network = $1 AND id = $2
49
+ AND (answer IS NULL OR answer->>'errorReason' = 'settlement_pending')${isPending(answer) ? " AND answer IS NULL" : ""}`, [network, id, JSON.stringify(answer)]);
50
+ },
51
+ async release(network, id) {
52
+ const r = await pool.query("DELETE FROM settlement WHERE network = $1 AND id = $2 AND answer IS NULL", [network, id]);
53
+ return r.rowCount === 1;
54
+ },
55
+ async advance(network, id, block) {
56
+ await pool.query("UPDATE settlement SET since = GREATEST(since, $3) WHERE network = $1 AND id = $2", [
57
+ network,
58
+ id,
59
+ block,
60
+ ]);
61
+ },
62
+ async drop() {
63
+ await pool.query("DELETE FROM settlement WHERE until + $1 * interval '1 millisecond' < now()", [KEEP_AFTER_UNTIL_MS]);
64
+ },
65
+ async close() {
66
+ clearInterval(timer);
67
+ await pool.end();
68
+ },
69
+ };
70
+ const timer = setInterval(() => {
71
+ store.drop().catch(() => { });
72
+ }, DROP_EVERY_MS);
73
+ timer.unref();
74
+ return store;
75
+ }
76
+ /**
77
+ * The part of `settleWaitMs` kept for writing the answer once the wait for the chain ends: a second, or a quarter of a
78
+ * shorter wait. The node calls and the waits end that much before the deadline, so the answer is stored, then given.
79
+ */
80
+ export function answerReserve(settleWaitMs) {
81
+ return Math.min(1_000, settleWaitMs / 4);
82
+ }
83
+ /** A store call bounded by `STORE_TIMEOUT_MS` and by what is left before `deadline` (a `performance.now()` time). */
84
+ export function inTime(p, deadline) {
85
+ return within(p, Math.min(STORE_TIMEOUT_MS, deadline - performance.now()));
86
+ }
package/dist/tron.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { type FacilitatorRequest, type SettleAnswer, type VerifyAnswer } from "./answers.js";
2
+ import { type SettlementStore } from "./store.js";
3
+ export interface TronNode {
4
+ network: `tron:${number}`;
5
+ fullNode: string;
6
+ solidityNode: string;
7
+ }
8
+ export declare function createTron(nodes: readonly TronNode[], s: SettlementStore, settleWaitMs: number): {
9
+ verify: (r: FacilitatorRequest) => Promise<VerifyAnswer>;
10
+ settle: (r: FacilitatorRequest) => Promise<SettleAnswer>;
11
+ networks: string[];
12
+ };