@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.
Files changed (91) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +781 -456
  3. package/dist/answers.d.ts +11 -4
  4. package/dist/answers.js +24 -0
  5. package/dist/core.d.ts +51 -0
  6. package/dist/core.js +758 -0
  7. package/dist/http.d.ts +20 -3
  8. package/dist/http.js +32 -7
  9. package/dist/index.d.ts +12 -36
  10. package/dist/index.js +9 -162
  11. package/dist/module.d.ts +372 -0
  12. package/dist/module.js +13 -0
  13. package/dist/modules/algorand/index.d.ts +22 -0
  14. package/dist/modules/algorand/index.js +247 -0
  15. package/dist/modules/algorand/own.d.ts +26 -0
  16. package/dist/modules/algorand/own.js +231 -0
  17. package/dist/modules/aptos/index.d.ts +23 -0
  18. package/dist/modules/aptos/index.js +232 -0
  19. package/dist/modules/cardano/index.d.ts +18 -0
  20. package/dist/modules/cardano/index.js +124 -0
  21. package/dist/modules/casper/index.d.ts +120 -0
  22. package/dist/modules/casper/index.js +442 -0
  23. package/dist/modules/concordium/index.d.ts +16 -0
  24. package/dist/modules/concordium/index.js +77 -0
  25. package/dist/modules/erc7710/index.d.ts +26 -0
  26. package/dist/modules/erc7710/index.js +220 -0
  27. package/dist/modules/evm/forms.d.ts +74 -0
  28. package/dist/modules/evm/forms.js +204 -0
  29. package/dist/modules/evm/index.d.ts +40 -0
  30. package/dist/modules/evm/index.js +154 -0
  31. package/dist/modules/evm/node.d.ts +29 -0
  32. package/dist/modules/evm/node.js +222 -0
  33. package/dist/modules/hedera/executor.d.ts +63 -0
  34. package/dist/modules/hedera/executor.js +343 -0
  35. package/dist/modules/hedera/index.d.ts +23 -0
  36. package/dist/modules/hedera/index.js +136 -0
  37. package/dist/modules/hedera/mirror.d.ts +32 -0
  38. package/dist/modules/hedera/mirror.js +111 -0
  39. package/dist/modules/index.d.ts +23 -0
  40. package/dist/modules/index.js +24 -0
  41. package/dist/modules/lnbtc/index.d.ts +10 -0
  42. package/dist/modules/lnbtc/index.js +112 -0
  43. package/dist/modules/near/index.d.ts +18 -0
  44. package/dist/modules/near/index.js +246 -0
  45. package/dist/modules/polkadot/index.d.ts +12 -0
  46. package/dist/modules/polkadot/index.js +149 -0
  47. package/dist/modules/polkadot/rail.d.ts +40 -0
  48. package/dist/{polkadot.js → modules/polkadot/rail.js} +214 -288
  49. package/dist/modules/solana/index.d.ts +60 -0
  50. package/dist/modules/solana/index.js +326 -0
  51. package/dist/modules/solana/reader.d.ts +25 -0
  52. package/dist/modules/solana/reader.js +194 -0
  53. package/dist/modules/solana/state.d.ts +6 -0
  54. package/dist/modules/solana/state.js +103 -0
  55. package/dist/modules/starknet/index.d.ts +35 -0
  56. package/dist/modules/starknet/index.js +548 -0
  57. package/dist/modules/starknet/node.d.ts +78 -0
  58. package/dist/modules/starknet/node.js +339 -0
  59. package/dist/modules/stellar/index.d.ts +44 -0
  60. package/dist/modules/stellar/index.js +481 -0
  61. package/dist/modules/stellar/node.d.ts +57 -0
  62. package/dist/modules/stellar/node.js +151 -0
  63. package/dist/modules/sui/index.d.ts +16 -0
  64. package/dist/modules/sui/index.js +310 -0
  65. package/dist/modules/sui/node.d.ts +49 -0
  66. package/dist/modules/sui/node.js +197 -0
  67. package/dist/modules/ton/index.d.ts +16 -0
  68. package/dist/modules/ton/index.js +73 -0
  69. package/dist/modules/tron/index.d.ts +12 -0
  70. package/dist/modules/tron/index.js +120 -0
  71. package/dist/modules/tron/rail.d.ts +32 -0
  72. package/dist/{tron.js → modules/tron/rail.js} +206 -195
  73. package/dist/modules/xrpl/index.d.ts +28 -0
  74. package/dist/modules/xrpl/index.js +299 -0
  75. package/dist/modules/xrpl/node.d.ts +52 -0
  76. package/dist/modules/xrpl/node.js +231 -0
  77. package/dist/modules/xrpl/upto.d.ts +5 -0
  78. package/dist/modules/xrpl/upto.js +269 -0
  79. package/dist/record.d.ts +131 -0
  80. package/dist/record.js +330 -0
  81. package/dist/unexpected.d.ts +3 -2
  82. package/dist/unexpected.js +2 -1
  83. package/dist/wrapper.d.ts +68 -0
  84. package/dist/wrapper.js +126 -0
  85. package/package.json +48 -12
  86. package/dist/polkadot.d.ts +0 -21
  87. package/dist/store.d.ts +0 -59
  88. package/dist/store.js +0 -103
  89. package/dist/tron.d.ts +0 -12
  90. /package/dist/{base58check.d.ts → modules/tron/base58check.d.ts} +0 -0
  91. /package/dist/{base58check.js → modules/tron/base58check.js} +0 -0
package/dist/record.js ADDED
@@ -0,0 +1,330 @@
1
+ /**
2
+ * The settler's record, in Postgres: one row per instrument, keyed by the network
3
+ * and the instrument as the form's profile names it (never the single-use value alone, never a hash a re-signed copy
4
+ * changes). A row is claimed by one conditional insert, so two settles of one instrument submit once, and a claim is
5
+ * never removed. A row is final only once its answer can never change: a success, a failed result that consumed the
6
+ * value, a value another act consumed, or a validity that passed with the value unconsumed. A refused submission, one
7
+ * that cannot have reached the node, and a failed result that consumed nothing leave the row a claim, which a repeat
8
+ * reads again. A final row is kept at least `KEEP_AFTER_MS` past the form's lapse or life, and for the settler's life
9
+ * where the form has neither or its nonce is not single-use.
10
+ *
11
+ * The same database holds the fees the settler's keys paid on each network, by which a fee budget is counted, and the
12
+ * modules' durable state.
13
+ */
14
+ import { randomUUID } from "node:crypto";
15
+ import pg from "pg";
16
+ import { operatorLine } from "./answers.js";
17
+ import { within } from "./http.js";
18
+ /** The bound on acquiring a connection, on each query as the client waits for it, and on each statement in the server. */
19
+ export const STORE_TIMEOUT_MS = 5_000;
20
+ /** Opens the pool of the settler's database. `log` receives an error the pool reports for an idle connection. */
21
+ export async function openPool(url, log = operatorLine) {
22
+ const pool = new pg.Pool({
23
+ connectionString: url,
24
+ max: 10,
25
+ connectionTimeoutMillis: STORE_TIMEOUT_MS,
26
+ query_timeout: STORE_TIMEOUT_MS,
27
+ statement_timeout: STORE_TIMEOUT_MS,
28
+ });
29
+ pool.on("error", (e) => log({ event: "store-connection-error" }, e));
30
+ return pool;
31
+ }
32
+ /**
33
+ * The part of `settleWaitMs` kept for writing the answer once the wait for the chain ends: a second, or a quarter of a
34
+ * shorter wait. The node calls and the waits end that much before the deadline, so the answer is stored, then given.
35
+ */
36
+ export function answerReserve(settleWaitMs) {
37
+ return Math.min(1_000, settleWaitMs / 4);
38
+ }
39
+ /** A store call bounded by `STORE_TIMEOUT_MS` and by what is left before `deadline` (a `performance.now()` time). */
40
+ export function inTime(p, deadline) {
41
+ return within(p, Math.min(STORE_TIMEOUT_MS, deadline - performance.now()));
42
+ }
43
+ /** How long a final row is kept past its form's lapse or life: a day, as the settler has kept one since its first release. */
44
+ export const KEEP_AFTER_MS = 24 * 60 * 60 * 1000;
45
+ const SWEEP_EVERY_MS = 60_000;
46
+ export const RECORD_SCHEMA = `CREATE TABLE IF NOT EXISTS instrument (
47
+ network text NOT NULL,
48
+ key text NOT NULL,
49
+ pairing text NOT NULL,
50
+ claimed bigint NOT NULL,
51
+ held_until bigint NOT NULL,
52
+ final boolean NOT NULL DEFAULT false,
53
+ outcome text,
54
+ answer jsonb,
55
+ transaction text,
56
+ sent text[] NOT NULL DEFAULT '{}',
57
+ body text,
58
+ payer text,
59
+ search jsonb,
60
+ since jsonb,
61
+ keep_until bigint,
62
+ PRIMARY KEY (network, key)
63
+ );
64
+ CREATE INDEX IF NOT EXISTS instrument_final_keep ON instrument (keep_until) WHERE final AND keep_until IS NOT NULL;
65
+ CREATE TABLE IF NOT EXISTS fee (
66
+ network text NOT NULL,
67
+ transaction text NOT NULL,
68
+ at bigint NOT NULL,
69
+ fee numeric(78, 0) NOT NULL,
70
+ included boolean NOT NULL,
71
+ PRIMARY KEY (network, transaction)
72
+ );
73
+ CREATE INDEX IF NOT EXISTS fee_at ON fee (network, at);
74
+ CREATE TABLE IF NOT EXISTS module_state (
75
+ module text NOT NULL,
76
+ key text NOT NULL,
77
+ value jsonb NOT NULL,
78
+ PRIMARY KEY (module, key)
79
+ )`;
80
+ /** A JSON value with each `bigint` written as `{"$bigint": "<decimal>"}`, so that it survives the store. */
81
+ export function toStored(value) {
82
+ return JSON.parse(JSON.stringify(value, (_k, v) => (typeof v === "bigint" ? { $bigint: v.toString() } : v)));
83
+ }
84
+ /** A stored JSON value, with each `{"$bigint": "<decimal>"}` read back as a `bigint`. */
85
+ export function fromStored(value) {
86
+ if (Array.isArray(value))
87
+ return value.map(fromStored);
88
+ if (typeof value !== "object" || value === null)
89
+ return value;
90
+ const o = value;
91
+ const keys = Object.keys(o);
92
+ if (keys.length === 1 && keys[0] === "$bigint" && typeof o["$bigint"] === "string")
93
+ return BigInt(o["$bigint"]);
94
+ return Object.fromEntries(keys.map((k) => [k, fromStored(o[k])]));
95
+ }
96
+ /**
97
+ * The record's key for an instrument, within its network: its kind and its parts as a JSON array, so that no two
98
+ * instruments share one.
99
+ */
100
+ export function keyOf(i) {
101
+ switch (i.by) {
102
+ case "single-use":
103
+ return JSON.stringify(["single-use", i.signer, i.scope ?? null, i.value, i.signed ?? null]);
104
+ case "transaction":
105
+ return JSON.stringify(["transaction", i.transaction]);
106
+ case "digest":
107
+ return JSON.stringify(["digest", i.digest]);
108
+ }
109
+ }
110
+ /**
111
+ * The earliest time, in Unix milliseconds, at which a final row may be dropped, before `KEEP_AFTER_MS`: the form's
112
+ * lapse, or its life counted from the claim; null for the settler's life, where the form has neither or its nonce is
113
+ * not single-use.
114
+ */
115
+ export function keepUntil(keep, nonce, claimed) {
116
+ if (nonce !== "single-use")
117
+ return null;
118
+ if (keep.until === "lapse")
119
+ return keep.at;
120
+ if (keep.until === "life")
121
+ return claimed + keep.ms;
122
+ return null;
123
+ }
124
+ function rowOf(r) {
125
+ return {
126
+ pairing: r.pairing,
127
+ claimed: Number(r.claimed),
128
+ heldUntil: Number(r.held_until),
129
+ final: r.final,
130
+ ...(r.outcome === null ? {} : { outcome: r.outcome }),
131
+ ...(r.answer === null ? {} : { answer: r.answer }),
132
+ ...(r.transaction === null ? {} : { transaction: r.transaction }),
133
+ sent: r.sent ?? [],
134
+ ...(r.body === null ? {} : { body: r.body }),
135
+ ...(r.payer === null ? {} : { payer: r.payer }),
136
+ ...(r.search === null || r.search === undefined ? {} : { search: fromStored(r.search) }),
137
+ ...(r.since === null || r.since === undefined ? {} : { since: fromStored(r.since) }),
138
+ };
139
+ }
140
+ /** The columns of a row, as `rowOf` reads them. */
141
+ const COLUMNS = "pairing, claimed, held_until, final, outcome, answer, transaction, sent, body, payer, search, since";
142
+ /** The record over `pool`, its tables created. */
143
+ export async function openRecord(pool) {
144
+ await pool.query(RECORD_SCHEMA);
145
+ return {
146
+ async read(network, key) {
147
+ const r = await pool.query(`SELECT ${COLUMNS} FROM instrument WHERE network = $1 AND key = $2`, [network, key]);
148
+ return r.rows[0] === undefined ? undefined : rowOf(r.rows[0]);
149
+ },
150
+ async claim(network, key, c) {
151
+ const r = await pool.query(`INSERT INTO instrument (network, key, pairing, claimed, held_until, payer, transaction, sent, body, since)
152
+ VALUES ($1, $2, $3, $4, $5, $6, $7, CASE WHEN $7::text IS NULL THEN '{}'::text[] ELSE ARRAY[$7::text] END, $8, $9)
153
+ ON CONFLICT DO NOTHING`, [
154
+ network,
155
+ key,
156
+ c.pairing,
157
+ c.now,
158
+ c.now + c.holdMs,
159
+ c.payer ?? null,
160
+ c.transaction ?? null,
161
+ c.body,
162
+ c.since === undefined ? null : JSON.stringify(toStored(c.since)),
163
+ ]);
164
+ return r.rowCount === 1;
165
+ },
166
+ async retake(network, key, now, holdMs) {
167
+ const r = await pool.query(`UPDATE instrument SET held_until = $4 WHERE network = $1 AND key = $2 AND NOT final AND held_until <= $3
168
+ RETURNING ${COLUMNS}`, [network, key, now, now + holdMs]);
169
+ return r.rows[0] === undefined ? undefined : rowOf(r.rows[0]);
170
+ },
171
+ async sent(network, key, transaction) {
172
+ await pool.query(`UPDATE instrument SET transaction = $3,
173
+ sent = CASE WHEN $3 = ANY(sent) THEN sent ELSE array_append(sent, $3::text) END
174
+ WHERE network = $1 AND key = $2 AND NOT final`, [network, key, transaction]);
175
+ },
176
+ async release(network, key, learnt) {
177
+ await pool.query(`UPDATE instrument SET held_until = 0, search = COALESCE($3, search) WHERE network = $1 AND key = $2 AND NOT final`, [network, key, learnt.search === undefined ? null : JSON.stringify(toStored(learnt.search))]);
178
+ },
179
+ async finish(network, key, f) {
180
+ const r = await pool.query(`INSERT INTO instrument (network, key, pairing, claimed, held_until, final, outcome, answer, transaction, payer,
181
+ keep_until)
182
+ VALUES ($1, $2, $3, $4, 0, true, $5, $6, $7, $8, $9)
183
+ ON CONFLICT (network, key) DO UPDATE SET final = true, held_until = 0, outcome = EXCLUDED.outcome,
184
+ answer = EXCLUDED.answer, transaction = COALESCE(EXCLUDED.transaction, instrument.transaction),
185
+ payer = COALESCE(instrument.payer, EXCLUDED.payer), keep_until = EXCLUDED.keep_until
186
+ WHERE NOT instrument.final`, [
187
+ network,
188
+ key,
189
+ f.pairing,
190
+ f.now,
191
+ f.outcome,
192
+ JSON.stringify(f.answer),
193
+ f.transaction ?? null,
194
+ f.payer ?? null,
195
+ f.keepUntil,
196
+ ]);
197
+ return r.rowCount === 1;
198
+ },
199
+ async sweep(now, feesBefore) {
200
+ await pool.query(`DELETE FROM instrument WHERE final AND keep_until IS NOT NULL AND keep_until < $1`, [
201
+ now - KEEP_AFTER_MS,
202
+ ]);
203
+ await pool.query(`DELETE FROM fee WHERE at < $1`, [feesBefore]);
204
+ },
205
+ };
206
+ }
207
+ /** The fee count over `pool`, for `budgets`, at most one per network. */
208
+ export function feesOn(pool, budgets) {
209
+ const byNetwork = new Map(budgets.map((b) => [b.network, b]));
210
+ const longest = Math.max(0, ...budgets.map((b) => b.periodSeconds * 1000));
211
+ async function counted(q, b, now) {
212
+ const r = await q.query("SELECT COALESCE(sum(fee), 0)::text AS n FROM fee WHERE network = $1 AND at > $2", [b.network, now - b.periodSeconds * 1000]);
213
+ return BigInt(r.rows[0].n);
214
+ }
215
+ const fees = {
216
+ budgeted: (network) => byNetwork.has(network),
217
+ async spent(network, now) {
218
+ const b = byNetwork.get(network);
219
+ return b !== undefined && (await counted(pool, b, now)) >= b.amount;
220
+ },
221
+ async count(network, transaction, fee, included, now) {
222
+ if (!byNetwork.has(network))
223
+ return;
224
+ await pool.query(`INSERT INTO fee (network, transaction, at, fee, included) VALUES ($1, $2, $3, $4, $5)
225
+ ON CONFLICT (network, transaction) DO UPDATE SET fee = EXCLUDED.fee, included = EXCLUDED.included
226
+ WHERE NOT fee.included`, [network, transaction, now, fee.toString(), included]);
227
+ },
228
+ meter(network, now, log) {
229
+ return {
230
+ async sending(s) {
231
+ const b = byNetwork.get(network);
232
+ if (b === undefined)
233
+ return true;
234
+ // One sender at a time per network, so that two never both pass a count that has room for one.
235
+ const client = await pool.connect();
236
+ try {
237
+ await client.query("BEGIN");
238
+ await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [`fee:${network}`]);
239
+ const at = now();
240
+ if ((await counted(client, b, at)) >= b.amount) {
241
+ await client.query("ROLLBACK");
242
+ return false;
243
+ }
244
+ // A transaction whose id is not known before it is sent is counted at its bound for the whole period.
245
+ const id = s.transaction ?? `unnamed:${randomUUID()}`;
246
+ await client.query(`INSERT INTO fee (network, transaction, at, fee, included) VALUES ($1, $2, $3, $4, false)
247
+ ON CONFLICT (network, transaction) DO NOTHING`, [network, id, at, s.bound.toString()]);
248
+ await client.query("COMMIT");
249
+ return true;
250
+ }
251
+ catch (e) {
252
+ await client.query("ROLLBACK").catch(() => { });
253
+ throw e;
254
+ }
255
+ finally {
256
+ client.release();
257
+ }
258
+ },
259
+ included(i) {
260
+ fees.count(network, i.transaction, i.fee, true, now()).catch((e) => log({ event: "store-call-failed", network, transaction: i.transaction, call: "fee" }, e));
261
+ },
262
+ sent(transaction, shown) {
263
+ if (!byNetwork.has(network))
264
+ return;
265
+ shown()
266
+ .then((c) => {
267
+ if (c === undefined)
268
+ return log({ event: "fee-not-counted", network, transaction, reason: "not-shown" });
269
+ return fees.count(network, transaction, c.fee, c.included, now());
270
+ })
271
+ .catch((e) => log({ event: "fee-not-counted", network, transaction }, e));
272
+ },
273
+ };
274
+ },
275
+ oldest: (now) => now - longest,
276
+ };
277
+ return fees;
278
+ }
279
+ /** `module`'s durable state over `pool`. */
280
+ export function moduleState(pool, module) {
281
+ const state = {
282
+ async get(key) {
283
+ const r = await pool.query("SELECT value FROM module_state WHERE module = $1 AND key = $2", [
284
+ module,
285
+ key,
286
+ ]);
287
+ return r.rows[0] === undefined ? undefined : fromStored(r.rows[0].value);
288
+ },
289
+ async set(key, value) {
290
+ await pool.query(`INSERT INTO module_state (module, key, value) VALUES ($1, $2, $3)
291
+ ON CONFLICT (module, key) DO UPDATE SET value = EXCLUDED.value`, [module, key, JSON.stringify(toStored(value))]);
292
+ },
293
+ async swap(key, expected, value) {
294
+ const stored = JSON.stringify(toStored(value));
295
+ const r = expected === undefined
296
+ ? await pool.query("INSERT INTO module_state (module, key, value) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING", [module, key, stored])
297
+ : await pool.query("UPDATE module_state SET value = $3 WHERE module = $1 AND key = $2 AND value = $4::jsonb", [
298
+ module,
299
+ key,
300
+ stored,
301
+ JSON.stringify(toStored(expected)),
302
+ ]);
303
+ return r.rowCount === 1;
304
+ },
305
+ async delete(key) {
306
+ await pool.query("DELETE FROM module_state WHERE module = $1 AND key = $2", [module, key]);
307
+ },
308
+ pendingSettlements() {
309
+ const named = (key) => `pending-settlement:${key}`;
310
+ return {
311
+ async get(key) {
312
+ const v = await state.get(named(key));
313
+ return typeof v === "string" ? v : undefined;
314
+ },
315
+ set: (key, txHash) => state.set(named(key), txHash),
316
+ delete: (key) => state.delete(named(key)),
317
+ };
318
+ },
319
+ };
320
+ return state;
321
+ }
322
+ /** Runs `record.sweep` every minute until the returned function is called; a sweep that fails goes to `log`. */
323
+ export function sweeping(record, fees, log = operatorLine) {
324
+ const timer = setInterval(() => {
325
+ const now = Date.now();
326
+ record.sweep(now, fees.oldest(now)).catch((e) => log({ event: "store-call-failed", call: "sweep" }, e));
327
+ }, SWEEP_EVERY_MS);
328
+ timer.unref();
329
+ return () => clearInterval(timer);
330
+ }
@@ -16,6 +16,7 @@ export declare function unexpectedSettle(log: OperatorLog, entry: OperatorEntry
16
16
  }, cause?: unknown): SettleAnswer;
17
17
  /**
18
18
  * A verify reason as a settle answer's: a node or store that could not be read before submission is a settle error.
19
- * Its entry is the one written where the verify reason is given.
19
+ * Its entry is the one written where the verify reason is given. Any other reason, a published class's among them, is
20
+ * the same on both calls.
20
21
  */
21
- export declare function settleReason(r: InvalidReason): string;
22
+ export declare function settleReason(r: InvalidReason | string): string;
@@ -20,7 +20,8 @@ export function unexpectedSettle(log, entry, cause) {
20
20
  }
21
21
  /**
22
22
  * A verify reason as a settle answer's: a node or store that could not be read before submission is a settle error.
23
- * Its entry is the one written where the verify reason is given.
23
+ * Its entry is the one written where the verify reason is given. Any other reason, a published class's among them, is
24
+ * the same on both calls.
24
25
  */
25
26
  export function settleReason(r) {
26
27
  return r === "unexpected_verify_error" ? "unexpected_settle_error" : r;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The wrapper the settler registers with x402's facilitator class for one scheme on one network: it states the kind's
3
+ * `extra` (the settler's members with every member the module's facilitator states), gives the signers of every
4
+ * module behind it, and hands a payment an own module claims to that module before the published class sees it. The
5
+ * published verification and settlement run unchanged.
6
+ */
7
+ import type { PairingId } from "@integraledger/lcp";
8
+ import type { FacilitatorContext, Network, PaymentPayload, PaymentRequirements, SchemeNetworkFacilitator, SettleResponse, VerifyResponse } from "@x402/core/types";
9
+ import { type Instrumented, type KeyPurpose, type Module, type Phase, type Registration, type X402Payment } from "./module.js";
10
+ /** The members of a kind's `extra` that the settler states, which no module's facilitator may state itself. */
11
+ export declare const SETTLER_MEMBERS: readonly ["key", "acceptsZero", "pairings", "feeBudget"];
12
+ /** What a kind declares: one registration's modules, the published one and its own ones, as one kind. */
13
+ export interface Kind {
14
+ readonly registration: Registration;
15
+ readonly scheme: string;
16
+ readonly network: Network;
17
+ readonly key: KeyPurpose;
18
+ /** The kind's pairings that take an amount of zero: each one every module submitting it names so. */
19
+ readonly acceptsZero: readonly PairingId[];
20
+ /** Every pairing a module behind the kind submits, each once. */
21
+ readonly pairings: readonly PairingId[];
22
+ /** Whether the network has a fee budget. */
23
+ readonly feeBudget: boolean;
24
+ }
25
+ /** Every module behind a registration: its own modules, in the order they are tried, then the published one. */
26
+ export declare function modulesOf(r: Registration): Module[];
27
+ /**
28
+ * The kind of a registration. Its key is the one key purpose its modules hold: `none` where none holds one. Two
29
+ * modules behind one kind whose keys sign for different purposes are refused, since a kind states one.
30
+ */
31
+ export declare function kindOf(r: Registration, feeBudget: boolean): Kind;
32
+ /**
33
+ * The module a payment goes to: the first own module whose claim takes it, by the option's member or by what the
34
+ * payment holds, else the registration's module. A claim reads neither the chain nor the clock.
35
+ */
36
+ export declare function route(r: Registration, payload: PaymentPayload, requirements: PaymentRequirements): Module;
37
+ /**
38
+ * The kind's declaration, held to a payment before the class is asked: an option of amount zero whose pairing the kind
39
+ * does not name as taking zero, and a form outside the pairings the module the payment goes to submits, are refused
40
+ * `invalid_payment_requirements`.
41
+ */
42
+ export declare function declared(kind: Kind, module: Module, p: X402Payment, i: Instrumented, phase: Phase): string | undefined;
43
+ /**
44
+ * The wrapper of one kind, as x402's class registers it for the kind's one network, in one phase: the context it gives
45
+ * a module's `verify` names that phase (`phaseOf`), every extension x402's class gives kept.
46
+ */
47
+ export declare class Wrapper implements SchemeNetworkFacilitator {
48
+ readonly kind: Kind;
49
+ readonly phase: Phase;
50
+ readonly scheme: string;
51
+ readonly caipFamily: string;
52
+ constructor(kind: Kind, phase: Phase);
53
+ private phased;
54
+ /**
55
+ * The kind's `extra`: each own module's members, then the published module's, which win where two state one, then the
56
+ * settler's, which no module states (the core refuses one that does at its start).
57
+ */
58
+ getExtra(network: Network): Record<string, unknown>;
59
+ /** Every address a module behind the kind signs with, each once. */
60
+ getSigners(network: string): string[];
61
+ verify(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<VerifyResponse>;
62
+ settle(payload: PaymentPayload, requirements: PaymentRequirements, context?: FacilitatorContext): Promise<SettleResponse>;
63
+ }
64
+ /**
65
+ * Why a registration cannot be served, or undefined: its network is not its modules', its own modules hold another
66
+ * scheme, or a module's facilitator states a member the settler states.
67
+ */
68
+ export declare function unsound(r: Registration): string | undefined;
@@ -0,0 +1,126 @@
1
+ import { PHASE } from "./module.js";
2
+ /** The members of a kind's `extra` that the settler states, which no module's facilitator may state itself. */
3
+ export const SETTLER_MEMBERS = ["key", "acceptsZero", "pairings", "feeBudget"];
4
+ /** Every module behind a registration: its own modules, in the order they are tried, then the published one. */
5
+ export function modulesOf(r) {
6
+ return [...r.own.map((h) => h.module), r.module];
7
+ }
8
+ /**
9
+ * The kind of a registration. Its key is the one key purpose its modules hold: `none` where none holds one. Two
10
+ * modules behind one kind whose keys sign for different purposes are refused, since a kind states one.
11
+ */
12
+ export function kindOf(r, feeBudget) {
13
+ const modules = modulesOf(r);
14
+ const keys = [...new Set(modules.map((m) => m.descriptor.key).filter((k) => k !== "none"))];
15
+ if (keys.length > 1) {
16
+ throw new TypeError(`${r.module.facilitator.scheme} on ${r.network}: its modules' keys sign for ${keys.join(" and ")}`);
17
+ }
18
+ const pairings = [...new Set(modules.flatMap((m) => m.descriptor.pairings))];
19
+ return {
20
+ registration: r,
21
+ scheme: r.module.facilitator.scheme,
22
+ network: r.network,
23
+ key: keys[0] ?? "none",
24
+ acceptsZero: pairings.filter((id) => modules.every((m) => !m.descriptor.pairings.includes(id) || m.descriptor.acceptsZero.includes(id))),
25
+ pairings,
26
+ feeBudget,
27
+ };
28
+ }
29
+ /**
30
+ * The module a payment goes to: the first own module whose claim takes it, by the option's member or by what the
31
+ * payment holds, else the registration's module. A claim reads neither the chain nor the clock.
32
+ */
33
+ export function route(r, payload, requirements) {
34
+ for (const h of r.own) {
35
+ const claims = h.claim.by === "option" ? h.claim.claims(requirements) : h.claim.claims(payload, requirements);
36
+ if (claims)
37
+ return h.module;
38
+ }
39
+ return r.module;
40
+ }
41
+ /**
42
+ * The amount of the option a payment answers: the requirements' own, but at `/settle` of x402's `upto`, whose
43
+ * requirements then carry the charge, at most the maximum the payment authorises and zero where the resource server
44
+ * charges nothing (a close that moves nothing), the maximum, as the option the payment accepted states it.
45
+ */
46
+ function optionAmount(kind, p, phase) {
47
+ return String(phase === "settle" && kind.scheme === "upto" ? p.payload.accepted?.amount : p.requirements.amount);
48
+ }
49
+ /**
50
+ * The kind's declaration, held to a payment before the class is asked: an option of amount zero whose pairing the kind
51
+ * does not name as taking zero, and a form outside the pairings the module the payment goes to submits, are refused
52
+ * `invalid_payment_requirements`.
53
+ */
54
+ export function declared(kind, module, p, i, phase) {
55
+ if (/^0+$/.test(optionAmount(kind, p, phase)) && !kind.acceptsZero.includes(i.pairing))
56
+ return "invalid_payment_requirements";
57
+ if (!module.descriptor.pairings.includes(i.pairing))
58
+ return "invalid_payment_requirements";
59
+ return undefined;
60
+ }
61
+ /**
62
+ * The wrapper of one kind, as x402's class registers it for the kind's one network, in one phase: the context it gives
63
+ * a module's `verify` names that phase (`phaseOf`), every extension x402's class gives kept.
64
+ */
65
+ export class Wrapper {
66
+ kind;
67
+ phase;
68
+ scheme;
69
+ caipFamily;
70
+ constructor(kind, phase) {
71
+ this.kind = kind;
72
+ this.phase = phase;
73
+ this.scheme = kind.scheme;
74
+ this.caipFamily = kind.registration.module.facilitator.caipFamily;
75
+ }
76
+ phased(given) {
77
+ const named = { key: PHASE, phase: this.phase };
78
+ return {
79
+ getExtension: (key) => key === PHASE ? named : given?.getExtension(key),
80
+ };
81
+ }
82
+ /**
83
+ * The kind's `extra`: each own module's members, then the published module's, which win where two state one, then the
84
+ * settler's, which no module states (the core refuses one that does at its start).
85
+ */
86
+ getExtra(network) {
87
+ const { registration: r } = this.kind;
88
+ const own = r.own.map((h) => h.module.facilitator.getExtra(network) ?? {});
89
+ return {
90
+ ...Object.assign({}, ...own),
91
+ ...(r.module.facilitator.getExtra(network) ?? {}),
92
+ key: this.kind.key,
93
+ acceptsZero: this.kind.acceptsZero,
94
+ pairings: this.kind.pairings,
95
+ ...(this.kind.feeBudget ? { feeBudget: true } : {}),
96
+ };
97
+ }
98
+ /** Every address a module behind the kind signs with, each once. */
99
+ getSigners(network) {
100
+ return [...new Set(modulesOf(this.kind.registration).flatMap((m) => m.facilitator.getSigners(network)))];
101
+ }
102
+ verify(payload, requirements, context) {
103
+ return route(this.kind.registration, payload, requirements).facilitator.verify(payload, requirements, this.phased(context));
104
+ }
105
+ settle(payload, requirements, context) {
106
+ return route(this.kind.registration, payload, requirements).facilitator.settle(payload, requirements, context);
107
+ }
108
+ }
109
+ /**
110
+ * Why a registration cannot be served, or undefined: its network is not its modules', its own modules hold another
111
+ * scheme, or a module's facilitator states a member the settler states.
112
+ */
113
+ export function unsound(r) {
114
+ for (const m of modulesOf(r)) {
115
+ if (m.network !== r.network)
116
+ return `a module of ${r.network} serves ${m.network}`;
117
+ if (m.facilitator.scheme !== r.module.facilitator.scheme) {
118
+ return `${r.network}: an own module of ${m.facilitator.scheme} behind ${r.module.facilitator.scheme}`;
119
+ }
120
+ const extra = m.facilitator.getExtra(r.network) ?? {};
121
+ const stated = SETTLER_MEMBERS.filter((k) => k in extra);
122
+ if (stated.length > 0)
123
+ return `${r.network}: a module's facilitator states ${stated.join(", ")}`;
124
+ }
125
+ return undefined;
126
+ }
package/package.json CHANGED
@@ -1,27 +1,40 @@
1
1
  {
2
2
  "name": "@integraledger/profile-facilitator",
3
- "version": "0.4.0",
4
- "description": "An x402 facilitator for the LCP profiles x402/exact/tron/lcp-trc20-memo and x402/exact/polkadot/lcp-assets-remark: verifies and settles payments whose signed transaction carries the ATR hash.",
3
+ "version": "0.5.1",
4
+ "description": "An x402 facilitator for the pairings @integraledger/lcp ships: it checks, submits what the payer signed, records each payment once in Postgres, and answers what the chain shows, with one module per chain form on x402's published facilitator classes where x402 publishes them.",
5
5
  "license": "Apache-2.0",
6
6
  "engines": {
7
- "node": ">=24"
7
+ "node": ">=24.22.1"
8
8
  },
9
9
  "repository": {
10
10
  "type": "git",
11
- "url": "git+https://github.com/IntegraLedger/integra-agentic-connectors.git",
12
- "directory": "profile-facilitator"
11
+ "url": "git+https://github.com/IntegraLedger/integra-protocol.git",
12
+ "directory": "settler"
13
13
  },
14
- "homepage": "https://github.com/IntegraLedger/integra-agentic-connectors/tree/main/profile-facilitator#readme",
15
- "bugs": "https://github.com/IntegraLedger/integra-agentic-connectors/issues",
14
+ "homepage": "https://github.com/IntegraLedger/integra-protocol/tree/main/settler#readme",
15
+ "bugs": "https://github.com/IntegraLedger/integra-protocol/issues",
16
16
  "keywords": [
17
17
  "lcp",
18
18
  "legal-context-protocol",
19
19
  "x402",
20
20
  "facilitator",
21
+ "settler",
22
+ "evm",
23
+ "solana",
24
+ "stellar",
25
+ "hedera",
26
+ "xrpl",
27
+ "algorand",
28
+ "aptos",
29
+ "near",
30
+ "ton",
31
+ "cardano",
32
+ "concordium",
33
+ "sui",
34
+ "starknet",
21
35
  "tron",
22
- "trc20",
23
36
  "polkadot",
24
- "asset-hub"
37
+ "lightning"
25
38
  ],
26
39
  "type": "module",
27
40
  "publishConfig": {
@@ -36,19 +49,42 @@
36
49
  "files": [
37
50
  "dist",
38
51
  "README.md",
52
+ "CHANGELOG.md",
39
53
  "LICENSE"
40
54
  ],
41
55
  "peerDependencies": {
42
- "@integraledger/lcp": "~0.5.0"
56
+ "@integraledger/lcp": "~0.6.3"
43
57
  },
44
58
  "dependencies": {
59
+ "@algorandfoundation/algokit-utils": "10.0.0-alpha.46",
60
+ "@hiero-ledger/sdk": "2.90.1",
61
+ "@mysten/sui": "2.35.0",
45
62
  "@noble/curves": "2.4.0",
46
63
  "@noble/hashes": "2.4.0",
47
64
  "@polkadot/api": "17.0.2",
48
- "pg": "8.23.1"
65
+ "@solana/kit": "8.4.0",
66
+ "@stellar/stellar-sdk": "17.2.1",
67
+ "@x402/aptos": "2.31.0",
68
+ "@x402/avm": "2.31.0",
69
+ "@x402/cardano": "2.31.0",
70
+ "@x402/casper": "2.31.0",
71
+ "@x402/concordium": "2.31.0",
72
+ "@x402/core": "2.31.0",
73
+ "@x402/evm": "2.31.0",
74
+ "@x402/hedera": "2.31.0",
75
+ "@x402/near": "2.31.0",
76
+ "@x402/svm": "2.31.0",
77
+ "@x402/tvm": "2.31.0",
78
+ "@x402/xrpl": "2.31.0",
79
+ "borsh": "2.0.0",
80
+ "casper-js-sdk": "5.1.1",
81
+ "pg": "8.23.1",
82
+ "starknet": "10.7.6",
83
+ "viem": "2.57.4",
84
+ "xrpl": "4.7.0"
49
85
  },
50
86
  "devDependencies": {
51
- "@integraledger/lcp": "0.5.0",
87
+ "@integraledger/lcp": "0.6.3",
52
88
  "vitest": "5.0.4"
53
89
  },
54
90
  "scripts": {
@@ -1,21 +0,0 @@
1
- import { type PolkadotNetwork } from "@integraledger/lcp/polkadot";
2
- import { type FacilitatorRequest, type OperatorLog, type SettleAnswer, type VerifyAnswer } from "./answers.js";
3
- import { Slots } from "./http.js";
4
- import { type SettlementStore } from "./store.js";
5
- export interface PolkadotNode {
6
- network: PolkadotNetwork;
7
- rpc: string;
8
- }
9
- /**
10
- * How many `chain_getBlock` reads, each bounded by the runtime's `System.BlockLength`, run at once in this process:
11
- * for Polkadot Asset Hub's runtime 2005000, at most 4 × 28,504,064 = 114,016,256 bytes of block answers.
12
- */
13
- export declare const BLOCK_READS = 4;
14
- /** The slots of `BLOCK_READS`, shared by every network and every scan in this process. */
15
- export declare const blockReads: Slots;
16
- export declare function createPolkadot(nodes: readonly PolkadotNode[], s: SettlementStore, settleWaitMs: number, log: OperatorLog): {
17
- verify: (r: FacilitatorRequest) => Promise<VerifyAnswer>;
18
- settle: (r: FacilitatorRequest) => Promise<SettleAnswer>;
19
- close: () => Promise<void>;
20
- networks: string[];
21
- };