@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/http.d.ts CHANGED
@@ -2,7 +2,24 @@
2
2
  import type { IncomingMessage, ServerResponse } from "node:http";
3
3
  export declare const NODE_TIMEOUT_MS = 5000;
4
4
  export declare const NODE_MAX_BYTES: number;
5
- export declare const REQUEST_MAX_BYTES: number;
5
+ /**
6
+ * The largest `/verify` or `/settle` body the settler reads: the largest payment lcp's x402 codec admits, with its
7
+ * requirements. lcp decodes a payment payload (x402's `PAYMENT-SIGNATURE`) of at most `MAX_HEADER_BYTES` bytes of JSON
8
+ * and reads the option it answers from a `PAYMENT-REQUIRED` of at most `MAX_HEADER_BYTES`, so each of the body's two
9
+ * members is at most `MAX_HEADER_BYTES` as the payer's client wrote it; x402's facilitator client writes the body as one
10
+ * object holding `x402Version` and those two, and `JSON.stringify` writes a value that `JSON.stringify` wrote and
11
+ * `JSON.parse` read back byte for byte as before. The rest of the body is its own members' names and the version, which
12
+ * `X402_ENVELOPE_BYTES` holds with room for a writer that spaces them. The bound assumes the payer's client wrote its
13
+ * payload with `JSON.stringify`, as x402's clients do: lcp admits any JSON object of that size, and one whose numbers
14
+ * another writer spelled shorter (`1e21` for `JSON.stringify`'s `1e+21`) can come back longer.
15
+ */
16
+ export declare const X402_ENVELOPE_BYTES = 1024;
17
+ export declare const X402_REQUEST_MAX_BYTES: number;
18
+ /**
19
+ * A node's URL as an error names it: its origin alone, since a path or a query can hold the endpoint's API key, and
20
+ * every error reaches the operator log.
21
+ */
22
+ export declare function site(url: string): string;
6
23
  /**
7
24
  * Why a node call gave no answer. `sent` is false only when the request cannot have reached the node. `spent` is a call
8
25
  * whose deadline left it no time: it is not sent.
@@ -24,10 +41,10 @@ export declare function isSpent(e: unknown): boolean;
24
41
  */
25
42
  export declare function postJson(url: string, body: unknown, timeoutMs?: number, maxBytes?: number): Promise<unknown>;
26
43
  /**
27
- * Reads a request body of at most 64 KiB as JSON: `tooLarge` when it is larger, `left` when the request ends before
44
+ * Reads a request body of at most `maxBytes` as JSON: `tooLarge` when it is larger, `left` when the request ends before
28
45
  * its body does (the client left), and undefined when it is not JSON.
29
46
  */
30
- export declare function readRequestJson(req: IncomingMessage): Promise<{
47
+ export declare function readRequestJson(req: IncomingMessage, maxBytes: number): Promise<{
31
48
  json: unknown;
32
49
  } | {
33
50
  tooLarge: true;
package/dist/http.js CHANGED
@@ -1,6 +1,31 @@
1
+ import { MAX_HEADER_BYTES } from "@integraledger/lcp";
1
2
  export const NODE_TIMEOUT_MS = 5_000;
2
3
  export const NODE_MAX_BYTES = 4 * 1024 * 1024;
3
- export const REQUEST_MAX_BYTES = 64 * 1024;
4
+ /**
5
+ * The largest `/verify` or `/settle` body the settler reads: the largest payment lcp's x402 codec admits, with its
6
+ * requirements. lcp decodes a payment payload (x402's `PAYMENT-SIGNATURE`) of at most `MAX_HEADER_BYTES` bytes of JSON
7
+ * and reads the option it answers from a `PAYMENT-REQUIRED` of at most `MAX_HEADER_BYTES`, so each of the body's two
8
+ * members is at most `MAX_HEADER_BYTES` as the payer's client wrote it; x402's facilitator client writes the body as one
9
+ * object holding `x402Version` and those two, and `JSON.stringify` writes a value that `JSON.stringify` wrote and
10
+ * `JSON.parse` read back byte for byte as before. The rest of the body is its own members' names and the version, which
11
+ * `X402_ENVELOPE_BYTES` holds with room for a writer that spaces them. The bound assumes the payer's client wrote its
12
+ * payload with `JSON.stringify`, as x402's clients do: lcp admits any JSON object of that size, and one whose numbers
13
+ * another writer spelled shorter (`1e21` for `JSON.stringify`'s `1e+21`) can come back longer.
14
+ */
15
+ export const X402_ENVELOPE_BYTES = 1024;
16
+ export const X402_REQUEST_MAX_BYTES = 2 * MAX_HEADER_BYTES + X402_ENVELOPE_BYTES;
17
+ /**
18
+ * A node's URL as an error names it: its origin alone, since a path or a query can hold the endpoint's API key, and
19
+ * every error reaches the operator log.
20
+ */
21
+ export function site(url) {
22
+ try {
23
+ return new URL(url).origin;
24
+ }
25
+ catch {
26
+ return "the node";
27
+ }
28
+ }
4
29
  /** Connection errors after which no byte of the request can have reached the node. */
5
30
  const UNSENT = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH"]);
6
31
  function isObject(v) {
@@ -29,7 +54,7 @@ export function isSpent(e) {
29
54
  */
30
55
  export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS, maxBytes = NODE_MAX_BYTES) {
31
56
  if (timeoutMs <= 0)
32
- throw new NodeError("spent", false, url);
57
+ throw new NodeError("spent", false, site(url));
33
58
  const ms = Number.isFinite(timeoutMs) ? Math.ceil(Math.min(timeoutMs, NODE_TIMEOUT_MS)) : NODE_TIMEOUT_MS;
34
59
  const signal = AbortSignal.timeout(ms);
35
60
  let res;
@@ -43,7 +68,7 @@ export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS, maxBytes
43
68
  }
44
69
  catch (e) {
45
70
  if (signal.aborted)
46
- throw new NodeError("timeout", true, url, { cause: e });
71
+ throw new NodeError("timeout", true, site(url), { cause: e });
47
72
  const code = e instanceof Error && isObject(e.cause) ? e.cause["code"] : undefined;
48
73
  const unsent = typeof code === "string" && UNSENT.has(code);
49
74
  throw new NodeError("transport", !unsent, e instanceof Error ? e.message : String(e), { cause: e });
@@ -98,12 +123,12 @@ async function readBounded(res, signal, maxBytes) {
98
123
  return out;
99
124
  }
100
125
  /**
101
- * Reads a request body of at most 64 KiB as JSON: `tooLarge` when it is larger, `left` when the request ends before
126
+ * Reads a request body of at most `maxBytes` as JSON: `tooLarge` when it is larger, `left` when the request ends before
102
127
  * its body does (the client left), and undefined when it is not JSON.
103
128
  */
104
- export async function readRequestJson(req) {
129
+ export async function readRequestJson(req, maxBytes) {
105
130
  const declared = Number(req.headers["content-length"]);
106
- if (Number.isFinite(declared) && declared > REQUEST_MAX_BYTES)
131
+ if (Number.isFinite(declared) && declared > maxBytes)
107
132
  return { tooLarge: true };
108
133
  const parts = [];
109
134
  let total = 0;
@@ -111,7 +136,7 @@ export async function readRequestJson(req) {
111
136
  for await (const chunk of req) {
112
137
  const b = chunk;
113
138
  total += b.byteLength;
114
- if (total > REQUEST_MAX_BYTES)
139
+ if (total > maxBytes)
115
140
  return { tooLarge: true };
116
141
  parts.push(b);
117
142
  }
package/dist/index.d.ts CHANGED
@@ -1,39 +1,15 @@
1
- import { type PolkadotNetwork } from "@integraledger/lcp/polkadot";
2
- export interface ProfileFacilitatorConfig {
3
- /** "host:port" */
4
- listen: string;
5
- tron?: {
6
- network: `tron:${number}`;
7
- fullNode: string;
8
- solidityNode: string;
9
- }[];
10
- /** An RPC node that serves `state_call` and `author_submitExtrinsic`. */
11
- polkadot?: {
12
- network: PolkadotNetwork;
13
- rpc: string;
14
- }[];
15
- /** Postgres, for deduplication only. */
16
- store: {
17
- url: string;
18
- };
19
- /** How long `/settle` waits for inclusion before answering `settlement_pending`; default 30 000. */
20
- settleWaitMs: number;
21
- /**
22
- * Receives every entry for the operator: what the facilitator saw that its answer does not carry, with `network`,
23
- * `payer` and `transaction` naming the payment where they are known. `cause` is the error that caused the entry,
24
- * when there is one; the answer to the client is the same either way, and carries nothing from it. Called once per
25
- * entry; what it throws, or a promise it returns that rejects, goes to the default with an `operator-log-failed`
26
- * entry. Default: one JSON line per entry on standard error, the cause as its `cause` (name, message, stack and its
27
- * own `cause` chain).
28
- */
29
- operatorLog?: (entry: {
30
- event: string;
31
- network?: string;
32
- payer?: string;
33
- transaction?: string;
34
- [field: string]: unknown;
35
- }, cause?: unknown) => void;
36
- }
1
+ /**
2
+ * The settler: an x402 facilitator, `GET /supported`, `POST /verify` and `POST /settle` over `node:http`, on x402's
3
+ * facilitator class, with one module per configured chain form. It checks a payment against its requirements and its
4
+ * pairing's profile, asks the configured node to validate or simulate, submits what the payer signed, records each
5
+ * instrument once in Postgres, and answers what the chain shows.
6
+ */
7
+ import { type SettlerConfig } from "./core.js";
8
+ import { type ModulesConfig } from "./modules/index.js";
9
+ export type { FeeBudgetConfig } from "./core.js";
10
+ /** The settler's configuration: the core's members, and each module's own member, named for the module. */
11
+ export type ProfileFacilitatorConfig = SettlerConfig & ModulesConfig;
12
+ /** Starts the settler; `close` stops it and closes what it opened. */
37
13
  export declare function serveProfileFacilitator(c: ProfileFacilitatorConfig): Promise<{
38
14
  close(): Promise<void>;
39
15
  }>;
package/dist/index.js CHANGED
@@ -1,165 +1,12 @@
1
1
  /**
2
- * A reference x402 facilitator for two LCP profiles, `x402/exact/tron/lcp-trc20-memo` and
3
- * `x402/exact/polkadot/lcp-assets-remark`: `GET /supported`, `POST /verify` and `POST /settle` over `node:http`. It
4
- * holds no key and pays no fee; it checks, submits what the payer signed, deduplicates, and reports what the network
5
- * shows.
2
+ * The settler: an x402 facilitator, `GET /supported`, `POST /verify` and `POST /settle` over `node:http`, on x402's
3
+ * facilitator class, with one module per configured chain form. It checks a payment against its requirements and its
4
+ * pairing's profile, asks the configured node to validate or simulate, submits what the payer signed, records each
5
+ * instrument once in Postgres, and answers what the chain shows.
6
6
  */
7
- import { createServer } from "node:http";
8
- import { LCP_ASSETS_REMARK } from "@integraledger/lcp/polkadot";
9
- import { LCP_TRC20_MEMO } from "@integraledger/lcp/tron";
10
- import { failed, guarded, invalid, isObject, operatorLine, readRequest, } from "./answers.js";
11
- import { readRequestJson, sendJson } from "./http.js";
12
- import { createPolkadot } from "./polkadot.js";
13
- import { openStore } from "./store.js";
14
- import { createTron } from "./tron.js";
15
- import { unexpectedSettle, unexpectedVerify } from "./unexpected.js";
16
- const DEFAULT_SETTLE_WAIT_MS = 30_000;
17
- /** The body's `paymentRequirements.network` when it is a string, else "". */
18
- function networkOf(body) {
19
- const requirements = isObject(body) ? body["paymentRequirements"] : undefined;
20
- const network = isObject(requirements) ? requirements["network"] : undefined;
21
- return typeof network === "string" ? network : "";
22
- }
23
- function hostPort(listen) {
24
- const m = /^\[?([^\]]*)\]?:(\d{1,5})$/.exec(listen);
25
- const port = m === null ? NaN : Number(m[2]);
26
- if (m === null || !(port >= 0 && port <= 65_535))
27
- throw new TypeError(`listen must be "host:port": ${listen}`);
28
- return { host: m[1], port };
29
- }
30
- function trimmed(url) {
31
- return url.replace(/\/+$/, "");
32
- }
33
- export async function serveProfileFacilitator(c) {
34
- const { host, port } = hostPort(c.listen);
35
- const settleWaitMs = Number.isFinite(c.settleWaitMs) && c.settleWaitMs > 0 ? c.settleWaitMs : DEFAULT_SETTLE_WAIT_MS;
36
- const log = guarded(c.operatorLog ?? operatorLine);
37
- const store = await openStore(c.store.url, log);
38
- // If the facilitator does not start, what it opened is closed before its error goes to the caller unchanged: the
39
- // store's pool and sweep, and the Polkadot rail, which opens a node's client only on that node's first request.
40
- let closeNodes = async () => { };
41
- try {
42
- const tron = createTron((c.tron ?? []).map((n) => ({ ...n, fullNode: trimmed(n.fullNode), solidityNode: trimmed(n.solidityNode) })), store, settleWaitMs, log);
43
- const polkadot = createPolkadot((c.polkadot ?? []).map((n) => ({ ...n, rpc: trimmed(n.rpc) })), store, settleWaitMs, log);
44
- closeNodes = () => polkadot.close();
45
- const supported = {
46
- kinds: [
47
- ...tron.networks.map((network) => ({
48
- x402Version: 2,
49
- scheme: "exact",
50
- network,
51
- extra: { assetTransferMethod: LCP_TRC20_MEMO },
52
- })),
53
- ...polkadot.networks.map((network) => ({
54
- x402Version: 2,
55
- scheme: "exact",
56
- network,
57
- extra: { assetTransferMethod: LCP_ASSETS_REMARK },
58
- })),
59
- ],
60
- extensions: [],
61
- signers: {},
62
- };
63
- function railOf(r) {
64
- const n = r.paymentRequirements.network;
65
- if (tron.networks.includes(n))
66
- return tron;
67
- if (polkadot.networks.includes(n))
68
- return polkadot;
69
- return undefined;
70
- }
71
- async function verify(body) {
72
- const r = readRequest(body);
73
- if (typeof r === "string")
74
- return { isValid: false, invalidReason: r };
75
- const rail = railOf(r);
76
- if (rail === undefined)
77
- return { isValid: false, invalidReason: "invalid_network" };
78
- try {
79
- return await rail.verify(r);
80
- }
81
- catch (e) {
82
- return invalid(unexpectedVerify(log, { event: "verify-error", network: r.paymentRequirements.network }, e));
83
- }
84
- }
85
- async function settle(body) {
86
- const r = readRequest(body);
87
- if (typeof r === "string")
88
- return failed(r, "", networkOf(body));
89
- const network = r.paymentRequirements.network;
90
- const rail = railOf(r);
91
- if (rail === undefined)
92
- return failed("invalid_network", "", network);
93
- try {
94
- return await rail.settle(r);
95
- }
96
- catch (e) {
97
- return unexpectedSettle(log, { event: "settle-error", network }, e);
98
- }
99
- }
100
- async function handle(req, res) {
101
- const path = (req.url ?? "").split("?")[0];
102
- if (path === "/supported") {
103
- if (req.method !== "GET")
104
- return sendJson(res, 405, { error: "method not allowed" });
105
- return sendJson(res, 200, supported);
106
- }
107
- if (path !== "/verify" && path !== "/settle")
108
- return sendJson(res, 404, { error: "not found" });
109
- if (req.method !== "POST")
110
- return sendJson(res, 405, { error: "method not allowed" });
111
- const read = await readRequestJson(req);
112
- if (read !== undefined && "tooLarge" in read) {
113
- res.setHeader("connection", "close");
114
- sendJson(res, 413, { error: "the body is larger than 64 KiB" });
115
- req.destroy();
116
- return;
117
- }
118
- if (read !== undefined && "left" in read) {
119
- // The client left before its body was complete: there is no one to answer, and nothing failed here to log.
120
- res.destroy();
121
- return;
122
- }
123
- if (path === "/verify") {
124
- if (read === undefined)
125
- return sendJson(res, 400, { isValid: false, invalidReason: "invalid_payload" });
126
- return sendJson(res, 200, await verify(read.json));
127
- }
128
- if (read === undefined)
129
- return sendJson(res, 400, failed("invalid_payload", "", ""));
130
- return sendJson(res, 200, await settle(read.json));
131
- }
132
- const server = createServer((req, res) => {
133
- handle(req, res).catch((e) => {
134
- log({ event: "request-error", path: (req.url ?? "").split("?")[0] }, e);
135
- if (!res.headersSent)
136
- sendJson(res, 500, { error: "internal error" });
137
- else
138
- res.destroy();
139
- });
140
- });
141
- server.requestTimeout = settleWaitMs + 60_000;
142
- await new Promise((resolve, reject) => {
143
- server.once("error", reject);
144
- server.listen(port, host, () => {
145
- server.off("error", reject);
146
- resolve();
147
- });
148
- });
149
- return {
150
- async close() {
151
- await new Promise((resolve) => {
152
- server.close(() => resolve());
153
- server.closeAllConnections();
154
- });
155
- await polkadot.close();
156
- await store.close();
157
- },
158
- };
159
- }
160
- catch (e) {
161
- await closeNodes();
162
- await store.close();
163
- throw e;
164
- }
7
+ import { serveSettler } from "./core.js";
8
+ import { MODULES } from "./modules/index.js";
9
+ /** Starts the settler; `close` stops it and closes what it opened. */
10
+ export function serveProfileFacilitator(c) {
11
+ return serveSettler(c, MODULES);
165
12
  }