@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/README.md CHANGED
@@ -1,579 +1,904 @@
1
1
  # @integraledger/profile-facilitator
2
2
 
3
- An x402 facilitator for two LCP profiles: `x402/exact/tron/lcp-trc20-memo` and
4
- `x402/exact/polkadot/lcp-assets-remark`. It verifies and settles payments whose payer-signed transaction carries the
5
- ATR hash, and it holds no key and pays no fee.
3
+ The settler: an x402 facilitator that holds each payment to its pairing's LCP profile (hence the package name), for
4
+ the x402 pairings that [`@integraledger/lcp`](https://www.npmjs.com/package/@integraledger/lcp) ships. A resource server
5
+ calls it over x402's facilitator API, one HTTP surface: `GET /supported`, `POST /verify` and `POST /settle`. It checks
6
+ each payment against its pairing's profile and the requirements it answers, submits what the payer signed, records each
7
+ payment once in Postgres, and answers what the chain shows.
6
8
 
7
- **Documentation:** [connectors.integraledger.com/guides/facilitator](https://connectors.integraledger.com/guides/facilitator)
9
+ This page is for the operator who runs it: at the end you can install it, configure each module with its keys, nodes
10
+ and database, put it behind TLS, and read every answer it gives.
8
11
 
9
12
  ## What it is
10
13
 
11
- In x402, a **facilitator** is the role that verifies a payment and settles it on its network, answering the x402
12
- facilitator API: `GET /supported`, `POST /verify` and `POST /settle`. x402 specifies neither Tron nor Polkadot. The
13
- Legal Context Protocol (LCP) defines one transfer method on each, in which the payer's own signed transaction carries
14
- the **ATR hash (H)**: SHA-256 over the exact bytes of the Agentic Transaction Record (ATR), the agreement's record.
15
- Approving that transaction is then the buyer's acceptance of that exact record, and the proof is on chain.
14
+ In x402, a **facilitator** is the role that verifies a payment and settles it on its network. The resource server, the
15
+ seller's x402 server, sends it the buyer's payment and the requirements that payment answers. `POST /verify` says
16
+ whether the payment is valid, `POST /settle` submits it and answers with the transaction, and `GET /supported` lists the
17
+ kinds of payment it serves. The seller chooses its facilitator.
16
18
 
17
- | Profile | `network` | `extra.assetTransferMethod` | Where H rides |
18
- |---|---|---|---|
19
- | `x402/exact/tron/lcp-trc20-memo` | `tron:<chain id in decimal>` | `lcp-trc20-memo` | The transaction's `raw_data.data`: the 77 ASCII bytes `lcp:sha256:` followed by H, beside one TRC-20 `transfer(payTo, amount)`. |
20
- | `x402/exact/polkadot/lcp-assets-remark` | `polkadot:68d56f15f85d3136970ec16946040bc1` (Polkadot Asset Hub) or `polkadot:67f9723393ef76214df0118c34bbbd3d` (Westend Asset Hub) | `lcp-assets-remark` | `system.remark_with_event(R)`, where R is exactly `lcp:sha256:` followed by H in lowercase hex, batched with `assets.transfer_keep_alive` in one `utility.batch_all`. |
21
-
22
- This package implements each profile's rule 5, the facilitator's duties. The profiles themselves are published with
23
- `@integraledger/lcp`, in [its repository at 0.5.0](https://github.com/IntegraLedger/integra-protocol/tree/v0.5.0/lcp/profiles), the release this package pins.
19
+ The Legal Context Protocol (LCP) binds a payment to the agreement's record: the payer's signed act carries the **ATR
20
+ hash (H)**, SHA-256 over the exact bytes of the Agentic Transaction Record (ATR). A **pairing** is one protocol, scheme
21
+ and rail, and its profile, published with `@integraledger/lcp`, fixes where H rides
22
+ ([the pairing registry](https://github.com/IntegraLedger/integra-protocol/blob/main/docs/reference/pairings.md)).
24
23
 
25
- The facilitator is a pass-through. It checks the payment against the requirements it is given, asks a node to
26
- validate or simulate it, submits exactly the bytes the payer signed, deduplicates, and reports what the network shows.
24
+ The settler runs x402's own facilitator class, `x402Facilitator` of `@x402/core` 2.31.0, with one registration for each
25
+ scheme on each configured network. Behind each registration is a **module**: x402's published facilitator class for
26
+ that chain, registered unchanged, or the settler's own facilitator where x402 publishes no class. Around the class the
27
+ settler adds three things:
27
28
 
28
- ## Key concepts
29
-
30
- - **Agentic Transaction Record (ATR):** the agreement's record, the exact bytes the seller serves.
31
- - **ATR hash (H):** SHA-256 over the ATR's exact bytes.
32
- - **Legal Context Protocol (LCP):** the pattern these profiles implement: H bound into the payment, so that where the
33
- payment the buyer approves carries H, that approval is the buyer's acceptance of that exact record; where it does
34
- not, the pairing's `proves` says so.
35
- - **Pairing:** a payment protocol, scheme and rail combination. This facilitator serves two:
36
- `x402/exact/tron/lcp-trc20-memo` and `x402/exact/polkadot/lcp-assets-remark`.
37
- - **Binding:** how H rides in a pairing's payment: here, the Tron memo and the Polkadot remark.
38
- - **Seller:** the party serving the resource. It calls this facilitator from its x402 resource server.
39
- - **Facilitator:** the x402 role that verifies and settles.
40
- - **Deduplication:** each payment is settled at most once, keyed by its network and transaction id, in Postgres.
29
+ - **lcp's checks of the pairing**, made from the payment and its requirements alone before the class is asked: the
30
+ payment carries H in its profile's form, and its form is one the kind declares.
31
+ - **The record**: one row per payment in Postgres, keyed as its profile names the payment (the single-use value its
32
+ signer signed, or its transaction id), so that one payment is submitted once and answered success once, across
33
+ every process that shares the database.
34
+ - **lcp's read of the chain**, which decides whether a payment the class did not answer success for is final.
41
35
 
42
36
  ```mermaid
43
37
  sequenceDiagram
44
- participant R as Resource server (seller)
45
- participant F as Profile facilitator
38
+ participant R as Resource server
39
+ participant S as Settler
46
40
  participant P as Postgres
47
- participant N as Network node
48
- R->>F: POST /verify
49
- F->>N: read the permission, reference block and id, and simulate (Tron), or validate (Polkadot)
50
- F-->>R: isValid, payer
51
- R->>F: POST /settle
52
- F->>P: read, then claim the transaction id
53
- F->>N: broadcast or submit the signed bytes
54
- loop every second until included or the wait ends
55
- F->>N: read the receipt or the blocks
56
- end
57
- F->>P: store the answer
58
- F-->>R: success, transaction, payer
41
+ participant N as Node
42
+ R->>S: POST /verify
43
+ Note over S: lcp's checks, the record, the class's verify, lcp's read
44
+ S-->>R: isValid, payer
45
+ R->>S: POST /settle
46
+ S->>P: claim the payment
47
+ S->>N: the class submits what the payer signed
48
+ S->>N: lcp's read, where the class did not answer success
49
+ S->>P: store the answer
50
+ S-->>R: success, transaction, payer
59
51
  ```
60
52
 
53
+ **What it checks, and what it does not.** It checks that the payment carries H in its profile's form. It does not check
54
+ that this H is the one the resource server issued for the request, or that the resource server has not accepted it
55
+ before: those are the resource server's own records
56
+ ([the seller guide](https://github.com/IntegraLedger/integra-protocol/blob/main/docs/guides/seller.md)). It checks the
57
+ amount, asset and payee against the requirements because x402 requires that of a facilitator, and carries no business
58
+ or legal logic beyond that.
59
+
61
60
  ## Install
62
61
 
63
62
  ```sh
64
- npm install @integraledger/profile-facilitator @integraledger/lcp@~0.5.0
63
+ npm install @integraledger/profile-facilitator @integraledger/lcp@~0.6.3
64
+ ```
65
+
66
+ It needs Node.js `>=24.22.1`, Postgres 11 or later ([The database](#the-database)), and, for each network it serves,
67
+ the node its module reads. It is ESM only. `@integraledger/lcp` is its peer dependency, at `~0.6.3`: install it with
68
+ the settler ([Versions](#versions)). A module that holds a key takes it as the signer object of x402's class for that
69
+ chain; make it with that chain's x402 package at 2.31.0, the release the settler's classes are pinned to
70
+ (`@x402/evm`, `@x402/svm`, `@x402/avm`, and so on).
71
+
72
+ Two packages in its dependency tree have install scripts that it runs without: `protobufjs` (through `@hiero-ledger/sdk`
73
+ and `@concordium/web-sdk`) and `secp256k1` (through `@x402/near`). This repository installs with both denied, and runs
74
+ the settler's tests so. pnpm 12 stops an install at a build script it has no decision for (`ERR_PNPM_IGNORED_BUILDS`);
75
+ deny both in your `pnpm-workspace.yaml`:
76
+
77
+ ```yaml
78
+ permissions:
79
+ protobufjs: {build: false}
80
+ secp256k1: {build: false}
81
+ ```
82
+
83
+ With npm, `npm install --ignore-scripts` runs neither.
84
+
85
+ A project that installs under pnpm's `trustPolicy: no-downgrade`, as this repository does, excludes exactly two
86
+ versions from it, and nothing wider:
87
+
88
+ ```yaml
89
+ trustPolicy: no-downgrade
90
+ trustPolicyExclude:
91
+ - '@noble/ed25519@1.7.5'
92
+ - '@noble/secp256k1@1.7.2'
65
93
  ```
66
94
 
67
- It needs Node.js `>=24`, Postgres (the tests run on Postgres 18), and an HTTP endpoint for each network you
68
- serve: a Tron FullNode that keeps the block history (not a lite FullNode) and a Solidity node, or a Polkadot Asset Hub
69
- RPC node. A Polkadot node that keeps the state of every block (an archive node) gives the events of any block; a
70
- pruning node discards the state of older blocks, and a block that holds the extrinsic and whose state is discarded
71
- keeps the answer `settlement_pending`. It is ESM only. `@integraledger/lcp` (`~0.5.0`) is its peer dependency: install
72
- it beside it.
95
+ The Casper module registers `@x402/casper` 2.31.0, which pins `casper-js-sdk` 5.1.1; every `casper-js-sdk` from 5.1.1
96
+ to 5.3.1 requires `@noble/ed25519` `^1.7.5` and `@noble/secp256k1` `^1.7.2`, with which it verifies a payer's ed25519
97
+ and secp256k1 signatures and signs with the settler's key, and no version of either package avoids them. Both were
98
+ published in April 2025 as maintenance releases of the packages' 1.x lines without provenance, after each package's
99
+ 2.1.0 had been published with it in March 2024, so `no-downgrade` refuses them. Every other version of the two
100
+ packages, and every other package, stays under the policy.
101
+
102
+ A pnpm project that turns hoisting off (`hoist: false`) also declares, for the Concordium module, the one dependency
103
+ `@concordium/web-sdk` 12.0.2 imports without declaring it, `@protobuf-ts/runtime`; without it the module does not load
104
+ ("Cannot find package '@protobuf-ts/runtime'"). With hoisting on, pnpm's default, and with npm, nothing is needed.
105
+
106
+ ```yaml
107
+ packageExtensions:
108
+ "@concordium/web-sdk@12.0.2":
109
+ dependencies:
110
+ "@protobuf-ts/runtime": "2.11.1"
111
+ ```
73
112
 
74
113
  ## Quickstart
75
114
 
76
- Start the facilitator for Tron mainnet and read what it supports. The node URLs below are java-tron's default HTTP
77
- ports on your own node; the facilitator calls them only when a payment arrives. `DATABASE_URL` is your Postgres
78
- connection string.
115
+ Start the settler for Tron mainnet and Polkadot Asset Hub, and read what it supports. Neither module holds a key, so
116
+ this deployment needs no credential. The node URLs are your own nodes; the settler calls them only when a payment
117
+ arrives. `DATABASE_URL` is your Postgres connection string.
79
118
 
80
- ```ts title="supported.ts"
119
+ ```ts no-check title="supported.ts"
81
120
  import { serveProfileFacilitator } from "@integraledger/profile-facilitator";
82
121
 
83
- const facilitator = await serveProfileFacilitator({
122
+ const settler = await serveProfileFacilitator({
84
123
  listen: "127.0.0.1:4020",
85
- tron: [{ network: "tron:728126428", fullNode: "http://127.0.0.1:8090", solidityNode: "http://127.0.0.1:8091" }],
86
- polkadot: [{ network: "polkadot:68d56f15f85d3136970ec16946040bc1", rpc: "http://127.0.0.1:9944" }],
87
124
  store: { url: process.env.DATABASE_URL ?? "postgres://postgres@127.0.0.1:5432/postgres" },
88
125
  settleWaitMs: 30_000,
126
+ tron: [{ network: "tron:728126428", fullNode: "http://127.0.0.1:8090", solidityNode: "http://127.0.0.1:8091" }],
127
+ polkadot: [{ network: "polkadot:68d56f15f85d3136970ec16946040bc1", rpc: "http://127.0.0.1:9944" }],
89
128
  });
90
129
 
91
130
  const supported = await (await fetch("http://127.0.0.1:4020/supported")).json();
92
131
  console.log(JSON.stringify(supported, null, 2));
93
- await facilitator.close();
132
+ await settler.close();
94
133
  ```
95
134
 
96
- ```text output
135
+ ```text
97
136
  {
98
137
  "kinds": [
99
138
  {
100
139
  "x402Version": 2,
101
140
  "scheme": "exact",
102
- "network": "tron:728126428",
141
+ "network": "polkadot:68d56f15f85d3136970ec16946040bc1",
103
142
  "extra": {
104
- "assetTransferMethod": "lcp-trc20-memo"
143
+ "assetTransferMethod": "lcp-assets-remark",
144
+ "key": "none",
145
+ "acceptsZero": [],
146
+ "pairings": [
147
+ "x402/exact/polkadot/lcp-assets-remark"
148
+ ]
105
149
  }
106
150
  },
107
151
  {
108
152
  "x402Version": 2,
109
153
  "scheme": "exact",
110
- "network": "polkadot:68d56f15f85d3136970ec16946040bc1",
154
+ "network": "tron:728126428",
111
155
  "extra": {
112
- "assetTransferMethod": "lcp-assets-remark"
156
+ "assetTransferMethod": "lcp-trc20-memo",
157
+ "key": "none",
158
+ "acceptsZero": [],
159
+ "pairings": [
160
+ "x402/exact/tron/lcp-trc20-memo"
161
+ ]
113
162
  }
114
163
  }
115
164
  ],
116
165
  "extensions": [],
117
- "signers": {}
166
+ "signers": {
167
+ "polkadot:*": [],
168
+ "tron:*": []
169
+ }
118
170
  }
119
171
  ```
120
172
 
121
- ## Run it
173
+ ## Run it as a service
122
174
 
123
- The package exports one function that starts the server; it has no command-line entry. A service is a short module
124
- that reads its configuration and stops cleanly on a signal:
175
+ The package exports one function that starts the server; it has no command-line entry. It reads no environment variable
176
+ and no file: every setting is a member of the configuration, and the variable names in these samples are the samples'
177
+ own. A service is a short module that reads its configuration, makes the signer objects its keyed modules take, and
178
+ stops cleanly on a signal. This one serves x402's `exact` scheme on Base Sepolia through the `evm` module, whose key,
179
+ the seller's gas key, sends each transaction and pays its gas:
125
180
 
126
- ```ts title="facilitator.ts" server
181
+ ```ts no-check title="settler.ts"
127
182
  import { serveProfileFacilitator } from "@integraledger/profile-facilitator";
183
+ import { toFacilitatorEvmSigner } from "@x402/evm";
184
+ import { createWalletClient, http, publicActions, type Hex } from "viem";
185
+ import { privateKeyToAccount } from "viem/accounts";
186
+ import { baseSepolia } from "viem/chains";
187
+
188
+ const rpc = process.env.BASE_SEPOLIA_RPC ?? "http://127.0.0.1:8545";
189
+ const credential = process.env.SETTLER_CREDENTIAL;
190
+ const gasKey = process.env.SELLER_GAS_KEY as Hex | undefined;
191
+ if (credential === undefined || gasKey === undefined) throw new Error("set SETTLER_CREDENTIAL and SELLER_GAS_KEY");
192
+
193
+ // The seller's gas key, as x402's EVM classes take it.
194
+ const account = privateKeyToAccount(gasKey);
195
+ const client = createWalletClient({ account, chain: baseSepolia, transport: http(rpc) }).extend(publicActions);
196
+ const signer = toFacilitatorEvmSigner(
197
+ {
198
+ address: account.address,
199
+ getCode: (a) => client.getCode(a),
200
+ readContract: (a) => client.readContract({ ...a, args: a.args ?? [] } as never),
201
+ verifyTypedData: (a) => client.verifyTypedData(a as never),
202
+ writeContract: (a) => client.writeContract({ ...a, args: a.args ?? [] } as never),
203
+ sendTransaction: (a) => client.sendTransaction(a as never),
204
+ waitForTransactionReceipt: (a) => client.waitForTransactionReceipt(a) as never,
205
+ simulateCalls: (a) => client.simulateCalls(a as never) as never,
206
+ },
207
+ // Below settleWaitMs, so /settle answers settlement_pending instead of waiting up to x402's default 180 s.
208
+ { confirmationTimeoutMs: 25_000 },
209
+ );
128
210
 
129
211
  const listen = process.env.LISTEN ?? "127.0.0.1:4021";
130
- const facilitator = await serveProfileFacilitator({
212
+ const settler = await serveProfileFacilitator({
131
213
  listen,
132
- tron: [
133
- {
134
- network: "tron:728126428",
135
- fullNode: process.env.TRON_FULL_NODE ?? "http://127.0.0.1:8090",
136
- solidityNode: process.env.TRON_SOLIDITY_NODE ?? "http://127.0.0.1:8091",
137
- },
138
- ],
139
214
  store: { url: process.env.DATABASE_URL ?? "postgres://postgres@127.0.0.1:5432/postgres" },
140
- settleWaitMs: Number(process.env.SETTLE_WAIT_MS ?? 30_000),
215
+ settleWaitMs: 30_000,
216
+ credential,
217
+ evm: [{ network: "eip155:84532", rpc, signer, schemes: ["exact"] }],
218
+ // At most 0.01 ETH of gas in any 24 hours; past it, payments whose gas the key pays are refused.
219
+ feeBudgets: [{ network: "eip155:84532", amount: "10000000000000000", periodSeconds: 86_400 }],
141
220
  });
142
221
  for (const signal of ["SIGINT", "SIGTERM"] as const) {
143
222
  process.once(signal, () => {
144
- void facilitator.close().then(() => process.exit(0));
223
+ void settler.close().then(() => process.exit(0));
145
224
  });
146
225
  }
147
- console.log(`facilitator listening on ${listen}`);
226
+ console.log(`settler listening on ${listen}`);
148
227
  ```
149
228
 
150
- ```text output
151
- facilitator listening on 127.0.0.1:4021
229
+ ```text
230
+ settler listening on 127.0.0.1:4021
152
231
  ```
153
232
 
154
- Run it with `node facilitator.ts`: Node.js 26 runs TypeScript directly. `close()` stops accepting requests, closes
155
- open connections, disconnects from the Polkadot nodes and closes the Postgres pool.
233
+ Run it with `node settler.ts`: Node.js 26 runs TypeScript directly. Every call must then carry
234
+ `Authorization: Bearer <credential>`. Its `/supported` states:
156
235
 
157
- ### Configuration
236
+ ```json
237
+ {
238
+ "kinds": [
239
+ {
240
+ "x402Version": 2,
241
+ "scheme": "exact",
242
+ "network": "eip155:84532",
243
+ "extra": {
244
+ "key": "relayer",
245
+ "acceptsZero": ["x402/exact/eip155/eip3009"],
246
+ "pairings": ["x402/exact/eip155/eip3009", "x402/exact/eip155/permit2"],
247
+ "feeBudget": true
248
+ }
249
+ }
250
+ ],
251
+ "extensions": [],
252
+ "signers": { "eip155:*": ["<the gas key's address>"] }
253
+ }
254
+ ```
255
+
256
+ `close()` stops accepting requests, closes open connections, closes what each module opened (the Polkadot nodes'
257
+ connections among them), stops the sweep and closes the Postgres pool. If the settler cannot start, it closes what it
258
+ opened and rejects with the error that stopped it, such as the listen's `EADDRINUSE` or a configuration it refuses
259
+ ([What stops the start](#what-stops-the-start)).
260
+
261
+ ## Configuration
158
262
 
159
- `serveProfileFacilitator(config)` takes a `ProfileFacilitatorConfig`:
263
+ `serveProfileFacilitator(config)` takes a `ProfileFacilitatorConfig`: the core's members, and one member for each module
264
+ the deployment starts, named for the module. A module whose member is absent is neither loaded nor started.
160
265
 
161
- | Field | Type | Meaning |
266
+ ### The core's members
267
+
268
+ | Member | Type | Meaning |
162
269
  |---|---|---|
163
270
  | `listen` | `string` | `"host:port"`; an IPv6 host may be written in brackets. |
164
- | `tron` | `{ network, fullNode, solidityNode }[]`, optional | One entry per Tron network. `network` is `tron:<chain id in decimal>`. `fullNode` serves `/wallet/…` and `solidityNode` serves `/walletsolidity/…`; give each its base URL. |
165
- | `polkadot` | `{ network, rpc }[]`, optional | One entry per network, `polkadot:68d56f15f85d3136970ec16946040bc1` or `polkadot:67f9723393ef76214df0118c34bbbd3d`. `rpc` is an HTTP JSON-RPC endpoint that serves `state_call` and `author_submitExtrinsic`. |
166
- | `store` | `{ url }` | The Postgres connection string. Postgres holds the deduplication table only. |
167
- | `settleWaitMs` | `number` | How long `/settle` waits for inclusion before it answers `settlement_pending`. A value that is not a positive finite number means 30 000. |
168
- | `operatorLog` | `(entry, cause?) => void`, optional | Receives every entry for the operator (see "Bounds and logs"). `entry` is `{ event, network?, payer?, transaction?, … }`, naming the payment where it is known; `cause` is the error behind it, when there is one. The answer to the client is the same either way and carries nothing from the cause. A log that throws, or returns a promise that rejects, changes no answer: the entry is written by the default, with an `operator-log-failed` entry. The default writes one JSON line per entry on standard error, the cause as `cause` (its name, message, stack and `cause` chain). |
271
+ | `store` | `{ url: string }` | The Postgres connection string. Postgres holds the record, the fee count and the modules' durable state; the settler creates its tables at start where they do not exist ([The database](#the-database)). |
272
+ | `settleWaitMs` | `number` | How long `/settle` waits for the chain before it answers `settlement_pending`. A value that is not a positive finite number means 30 000. |
273
+ | `credential` | `string`, optional | The credential every call must present as `Authorization: Bearer <credential>`; required where a configured module holds a key ([The credential](#the-credential)). Its characters are those RFC 6750 admits in a bearer token: letters, digits and `-._~+/`, then any `=`. |
274
+ | `feeBudgets` | `{ network, amount, periodSeconds }[]`, optional | At most one per network, each on a network a configured module serves ([The fee budget](#the-fee-budget)). `amount` is in the smallest unit of the network's fee asset, a `bigint` or its decimal digits, and positive; `periodSeconds` is a positive whole number. |
275
+ | `operatorLog` | `(entry, cause?) => void`, optional | Receives every entry for the operator ([Bounds and logs](#bounds-and-logs)). The default writes one JSON line per entry on standard error. |
276
+
277
+ ### The database
278
+
279
+ The settler needs Postgres 11 or later: nothing it runs is newer than `hashtextextended`, which Postgres 11 added. Its
280
+ tests run on Postgres 18. At every start it runs `CREATE TABLE IF NOT EXISTS` and `CREATE INDEX IF NOT EXISTS` for its
281
+ three tables and two indexes ([Storage](#storage)), so the role in `store.url` needs `CREATE` on the schema they live
282
+ in and owns them. From Postgres 15, the schema `public` grants `CREATE` to no role but its owner by default: grant it,
283
+ or create a schema named for the role and owned by it, which Postgres's default `search_path` (`"$user", public`) puts
284
+ first. The role then reads and writes only those tables, and takes transaction-level advisory locks. Each process holds
285
+ at most 10 connections.
286
+
287
+ Every settler process that may settle the same payments uses the same database: the record is what keeps one payment
288
+ submitted once and answered success once. Do not truncate or replace its tables while payments they hold can still
289
+ land, and back them up as you back up payment records.
290
+
291
+ ### The modules
292
+
293
+ Each module's member lists the networks it serves. Its keys reach it inside that member, as the signer objects its
294
+ classes take; the settler reads no key material of its own. A network is the CAIP-2 id lcp's type for the chain
295
+ names, and the table gives the ones each module takes.
296
+
297
+ | Member | Chain | Networks | Scheme: pairings (`confirmed`) | `extra.key` | `extra.acceptsZero` | Facilitator |
298
+ |---|---|---|---|---|---|---|
299
+ | `algorand` | Algorand | `algorand:<genesis hash prefix>` | `exact`: `x402/exact/algorand` (yes) | `fee-payer` | `x402/exact/algorand` | `@x402/avm`'s class; the settler's own path for a rekeyed payer signing with one key and a Falcon-key payer |
300
+ | `aptos` | Aptos | `aptos:<chain id>` | `exact`: `x402/exact/aptos` (yes) | `fee-payer`, or `none` with `sponsor: false` | `[]` | `@x402/aptos`'s class |
301
+ | `cardano` | Cardano | `cardano:mainnet`, `cardano:preprod`, `cardano:preview` | `exact`: `x402/exact/cardano` (yes), `x402/exact/cardano/lock` (yes) | `none` | `[]` | `@x402/cardano`'s class |
302
+ | `casper` | Casper | `casper:casper-test` | `exact`: `x402/exact/casper` (no) | `relayer` | `[]` | `@x402/casper`'s class |
303
+ | `concordium` | Concordium | `ccd:<genesis hash prefix>` | `exact`: `x402/exact/ccd` (no) | `fee-payer` | `x402/exact/ccd` | `@x402/concordium`'s class |
304
+ | `evm` | EVM | `eip155:<chain id>` | `exact`: `x402/exact/eip155/eip3009` (yes), `x402/exact/eip155/permit2` (yes); `upto`: `x402/upto/eip155/permit2` (yes); `auth-capture`: `x402/auth-capture/eip155/eip3009` (yes), `x402/auth-capture/eip155/permit2` (yes); `batch-settlement`: `x402/batch-settlement/eip155` (yes) | `relayer` | `x402/exact/eip155/eip3009` on `exact`; `[]` on the others | `@x402/evm`'s classes |
305
+ | `erc7710` | EVM | `eip155:<chain id>`, where `evm` registers `exact` | `exact` with `erc7710`: `x402/exact/eip155/erc7710` (yes), `x402/exact/eip155/erc7710-salt` (yes) | `relayer` | `[]` | the settler's own, behind the `evm` module's `exact` |
306
+ | `hedera` | Hedera | `hedera:mainnet`, `hedera:testnet`, `hedera:previewnet`, `hedera:devnet` | `exact`: `x402/exact/hedera` (yes) | `fee-payer` | `[]` | `@x402/hedera`'s class |
307
+ | `lnbtc` | Lightning | `lnbtc:000000000019d6689c085ae165831e93`, `lnbtc:000000000933ea01ad0ee984209779ba` | `exact`: `x402/exact/lnbtc/payment-hash` (yes) | `none` | `[]` | the settler's own |
308
+ | `near` | NEAR | `near:mainnet`, `near:testnet` | `exact`: `x402/exact/near` (yes) | `relayer` | `[]` | `@x402/near`'s class |
309
+ | `polkadot` | Polkadot Asset Hub | `polkadot:68d56f15f85d3136970ec16946040bc1`, `polkadot:67f9723393ef76214df0118c34bbbd3d` | `exact`: `x402/exact/polkadot/lcp-assets-remark` (yes) | `none` | `[]` | the settler's own |
310
+ | `solana` | Solana | `solana:<genesis hash prefix>`; `upto` and `batch-settlement` not on `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp` | `exact`: `x402/exact/solana` (yes); `upto`: `x402/upto/solana` (no); `batch-settlement`: `x402/batch-settlement/solana` (no) | `fee-payer` | `x402/exact/solana` on `exact`; `[]` on the others | `@x402/svm`'s classes |
311
+ | `starknet` | Starknet | `starknet:SN_MAIN`, `starknet:SN_SEPOLIA` | `exact`: `x402/exact/starknet` (yes) | `relayer` | `x402/exact/starknet` on `starknet:SN_SEPOLIA`; `[]` on `starknet:SN_MAIN` | the settler's own |
312
+ | `stellar` | Stellar | `stellar:pubnet`, `stellar:testnet` | `exact` with `lcp-precondition`: `x402/exact/stellar/precondition` (yes) | `relayer` | `x402/exact/stellar/precondition` | the settler's own |
313
+ | `sui` | Sui | `sui:mainnet`, `sui:testnet`, `sui:devnet` | `exact`: `x402/exact/sui` (yes) | `none` | `x402/exact/sui` | the settler's own |
314
+ | `ton` | TON | `tvm:-239`, `tvm:-3` | `exact`: `x402/exact/tvm` (yes) | `relayer` | `x402/exact/tvm` | `@x402/tvm`'s class |
315
+ | `tron` | Tron | `tron:<chain id in decimal>` | `exact`: `x402/exact/tron/lcp-trc20-memo` (yes) | `none` | `[]` | the settler's own |
316
+ | `xrpl` | XRP Ledger | `xrpl:<NetworkID>` | `exact`: `x402/exact/xrpl` (yes); `upto`: `x402/upto/xrpl` (yes) | `none` | `[]` | `@x402/xrpl`'s class for a payer signing with one key; the settler's own for a multisigned payer and for `upto` |
317
+
318
+ `confirmed` is lcp's registry's: whether something outside lcp has shown the form as its profile defines it
319
+ ([the pairing registry](https://github.com/IntegraLedger/integra-protocol/blob/main/docs/reference/pairings.md)). The
320
+ settler serves the forms marked `no` as their profiles define them, but no recorded run outside lcp has yet shown one.
321
+ The `casper` and `concordium` modules serve only such forms: run them on a test network, and do not offer those forms
322
+ to buyers until the registry says `yes`.
323
+
324
+ Each member, one entry per network unless it says otherwise:
325
+
326
+ - **`algorand`**: `network`; `signer`, the seller's fee payer as `@x402/avm`'s class takes it (`FacilitatorAvmSigner`),
327
+ with its algod node; `indexer`, the seller's Indexer, which lcp's read uses; `archival`, optional, true where that
328
+ Indexer holds every round. The fee payer pools the group's fee by its own zero-amount payment in the same atomic
329
+ group. The class signs every entry of the group that one of the key's addresses sends, so a group may hold one such
330
+ entry, and only where the option's `extra.feePayer` names its sender: a group with two, or with one the option's
331
+ `extra.feePayer` does not name, is refused `invalid_exact_avm_invalid_fee_payer`; with no `extra.feePayer` the buyer
332
+ pays its own fee. An entry a logic signature authorises, and one that names `asnd`, are refused before anything
333
+ moves.
334
+ - **`aptos`**: `network`; `signer`, the seller's account (`FacilitatorAptosSigner`); `sponsor`, optional, whether the
335
+ key pays the payer's gas as its fee payer (default true, the class's own default); `node`, the seller's REST endpoint,
336
+ its base without `/v1`. With `sponsor: false` the payer pays its own gas and the key signs nothing: the kind states
337
+ `extra.key` `none` and `/supported` names no signer for it, and an option that names an `extra.feePayer` is refused
338
+ `invalid_payment_requirements` before the class is asked, since the class pays the gas of any payment whose option
339
+ names one of the key's addresses.
340
+ - **`cardano`**: `network`; `signer`, the chain-query object `@x402/cardano`'s class takes over the seller's provider (a
341
+ provider's project id is its configuration, not a key); `reader`, lcp's `CardanoReader` over the seller's indexer. The
342
+ class broadcasts the transaction the buyer signed, whose fee the buyer pays. `@x402/cardano` 2.31.0 reads a
343
+ transaction's confirmations from Blockfrost alone: over Koios alone it sees none, so an option it settles there
344
+ states `extra.confirmationPolicy` as `{ "l1Confirmations": 0 }`, and an option that states none, whose default asks
345
+ one confirmation, is refused at `/verify`. A provider with a Blockfrost project serves an option that asks
346
+ confirmations. `/settle` answers success where the class does, and
347
+ otherwise once lcp's read through `reader` shows the transaction final, at the ledger's security parameter of
348
+ confirmations (2160 on mainnet and Preprod, some 12 hours); until then it answers `settlement_pending` naming the
349
+ transaction. Over Koios alone the class's settle gives no success, so a payment is answered at that mark. Its guard
350
+ against broadcasting one transaction twice is kept in the settler's database, so a repeat after a restart resumes
351
+ observing what was broadcast.
352
+ - **`casper`**: `network`, `casper:casper-test` (the settler does not start on `casper:casper`: see *What it does not
353
+ serve*); `signer`, the seller's key as `@x402/casper`'s class takes it (`FacilitatorCasperSigner`, made with its
354
+ `toFacilitatorCasperSigner` and an `rpcUrlConfig` that names `rpc` for the network), which sends the transaction that
355
+ calls the token package's `transfer_with_authorization` with the payer's CEP-3009 authorization, and pays its gas;
356
+ `rpc`, the seller's node, through which the class reads the token before it settles, lcp's read finds the payment and
357
+ the fee count reads its cost. The settler does not start where the signer names another node, as `@x402/casper`'s
358
+ signer does for a network its `rpcUrlConfig` leaves out, falling back to a public node, nor where its
359
+ `speculativeRpcUrlConfig` names a node other than `rpc`: with one, the class's check has the key sign a deploy of the
360
+ payer's authorization at every `/verify` and `/settle` and sends it there for speculative execution. `paymentMotes`,
361
+ optional, is the most the transaction can pay, in motes (`@x402/casper`'s default, 2.5 CSPR, where absent), which the
362
+ fee budget counts from the transaction's submission until the node shows the cost. The class refuses a zero amount.
363
+ `signers` lists the key's account hash, 64 hex digits without the `00` tag a payload's address carries. The class's
364
+ node calls and lcp's read carry no header of the seller's, so a node credential reaches the node only within `rpc`'s
365
+ URL; and the class waits up to a minute for its transaction, its node calls without a timeout of their own, so its
366
+ settle can run past `settleWaitMs`. lcp's read takes the token's used nonces from its dictionary
367
+ `used_nonces`, as lcp's profile names it, where the class's check before it settles reads `authorization_state`.
368
+ - **`concordium`**: `network`, the one the signer is connected to; `signer`, the seller's sponsor account and its key
369
+ with its node (`FacilitatorConcordiumSigner`), which co-signs the payer's sponsored transaction and pays its energy;
370
+ `reader`, lcp's `CcdReader` over the seller's node. The record names each payment by the digest of what its sender
371
+ signed, so a payment is never sent twice.
372
+ - **`evm`**: `network`; `rpc`, the seller's JSON-RPC endpoint, which lcp's reads and the fee's read go through; `signer`,
373
+ the seller's gas key (`FacilitatorEvmSigner`, made with `toFacilitatorEvmSigner` over the same node); `schemes`,
374
+ optional, the schemes registered (`exact`, `upto`, `auth-capture`, `batch-settlement`; all four where absent);
375
+ `eip6492AllowedFactories`, optional, the ERC-6492 factories `exact` and `batch-settlement` may call to deploy a payer's
376
+ wallet (none where absent); `authCapture`, optional, `auth-capture`'s own configuration, passed to its class
377
+ unchanged. Before the class is asked, `exact` refuses an option that pays several payees (a non-empty
378
+ `extra.splits`) and Circle's batched option (`extra.name` `GatewayWalletBatched`, or an `extra.verifyingContract`
379
+ other than the asset), which no published EVM class settles. At `/settle`, `upto` settles the amount its requirements
380
+ state, the charge: requirements that are the option the payment accepted in every member but an `amount` at or below
381
+ the accepted one are held as that option, and the class checks the permit against the accepted maximum, as its own
382
+ settle does; any other requirements are refused `invalid_payload`. `exact`'s `extra.acceptsZero` names
383
+ `x402/exact/eip155/eip3009` alone, and every other kind's is `[]`. On Base Sepolia, USDC's EIP-3009
384
+ `transferWithAuthorization` of 0 succeeds, emitting `AuthorizationUsed` and a `Transfer` of 0 (`eth_simulateV1` at
385
+ block 61198157); at block 61194449, x402's `exact` and `upto` Permit2 proxies revert `InvalidAmount` and the
386
+ commerce-payments escrow's `authorize` reverts `ZeroAmount`; batch settlement's facilitator requires a deposit above
387
+ 0.
388
+ - **`erc7710`**: `network`; `rpc`; `signer`, the seller's gas key, whose node must answer `eth_simulateV1`. The key
389
+ sends from its first address, so that address is the delegate the leaf delegation must name (or the reference
390
+ implementation's wildcard delegate), and the account the simulation runs from. It registers nothing of its own: on
391
+ each of its networks it is offered to the `evm` module's `exact` registration, which hands it every payment whose
392
+ option names `erc7710`. The settler does not start where the `evm` module does not register `exact` on such a
393
+ network. It simulates the redemption the payment names, then calls `redeemDelegations` on the delegation manager the
394
+ payload names, with one execution that transfers the option's amount to `payTo`.
395
+ - **`hedera`**: `network`; `signer`, the seller's fee-payer account and its key (`FacilitatorHederaSigner`): the class
396
+ takes only a payment whose transaction id names an account it manages as `extra.feePayer`; `mirror`, the seller's
397
+ Mirror Node REST base URL, which lcp's read and the fee count use; `archival`, optional, true where it holds every
398
+ record since the network began. `@x402/hedera` 2.31.0 makes the signer from its parts rather than from a key alone:
399
+ `toFacilitatorHederaSigner` over `signAndSubmitTransaction` from `createHederaSignAndSubmitTransaction` (a client per
400
+ network, such as `createHederaClient`'s, and the fee payer's `PrivateKey`), `verifyPayerSignature` from
401
+ `createHederaVerifyPayerSignature`, and `preflightTransfer` from `createHederaPreflightTransfer`.
402
+ - **`lnbtc`**: `network`, x402's `lnbtc` id of Bitcoin mainnet (`lnbtc:000000000019d6689c085ae165831e93`) or testnet3
403
+ (`lnbtc:000000000933ea01ad0ee984209779ba`). The buyer's node paid the invoice before the preimage reached the buyer,
404
+ so settling moves nothing: the module makes the scheme's validation through lcp's `validateExactLnbtc`, answers the
405
+ invoice's payment hash as the transaction, names no payer, and reads nothing. x402's scheme forbids `/verify` for
406
+ this flow, so `/verify` answers `unsupported_scheme`; `/settle` makes the validation before the record's claim.
407
+ - **`near`**: `network`; `signer`, the seller's relayer account and key with its RPC node (`FacilitatorNearSigner`),
408
+ which wraps the payer's NEP-366 delegate action in a transaction of its own and pays its gas and one-yoctoNEAR
409
+ deposit; `rpc`, the seller's RPC node.
410
+ - **`polkadot`**: `network`, `polkadot:68d56f15f85d3136970ec16946040bc1` (Polkadot Asset Hub) or
411
+ `polkadot:67f9723393ef76214df0118c34bbbd3d` (Westend Asset Hub); `rpc`, an HTTP JSON-RPC endpoint. The payer signs
412
+ and pays every fee. A node that keeps the state of every block (an archive node) gives the events of any block; a
413
+ pruning node discards the state of older blocks, and a block that holds the extrinsic and whose state is discarded
414
+ keeps the answer `settlement_pending`. The runtime metadata is loaded on the first payment for the network, and again
415
+ whenever the node's runtime version changes. A success names `<block hash>-<extrinsic index>`; a pending answer
416
+ names the extrinsic's hash. The kind's `extra.acceptsZero` is `[]`: lcp's option filter takes a positive amount only
417
+ (its profile's rule 1), and a `transfer_keep_alive` of 0, dry-run on Westend Asset Hub at block 19635446, dispatches
418
+ and emits no event.
419
+ - **`solana`**: `network`; `node`, the seller's JSON-RPC endpoint, one whose `getFirstAvailableBlock` is at or below the
420
+ slot at which each payment was issued; `signer`, the seller's fee payer (`FacilitatorSvmSigner`), which co-signs every
421
+ transaction the payer signed and, on the channel forms, pays the channel's rent; `transactionVersions`, optional, the
422
+ message versions the classes accept (their default `[0, 1]`). `upto` and `batch-settlement` need the payment-channels
423
+ program, which is deployed on devnet and testnet and not on mainnet: on Solana mainnet
424
+ (`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`) only `exact` is registered. Their channels are kept in the settler's
425
+ database. `upto` is settled in the order x402's `upto` resource server sends it: `/verify` of the opening as the buyer
426
+ sent it, then `/settle` of its deposit before the resource server's handler runs and of its claim after, each
427
+ carrying the `type` (`deposit`, `claim`) that server adds. A claim needs the voucher of the option's
428
+ `extra.receiverAuthorizer`, which the module does not sign: the resource server signs it with its own key.
429
+ - **`starknet`**: an object `{ networks }`, one entry per network: `network`; `rpc`, a JSON-RPC node (specification 0.9
430
+ or later) that serves `starknet_traceTransaction` and `starknet_simulateTransactions`; `executor`, an `address` and
431
+ its `signer`, the account the payer's outside execution names as its caller, stated as `extra.feePayer`, which
432
+ sends and pays for the transaction that executes it; `maxFee`, optional, the most one settlement's resource bounds
433
+ may pay, in fri; `skewMarginSeconds` (default 60) and `minSettleMarginSeconds` (default 30), optional, the scheme's
434
+ margins. x402 specifies Starknet and publishes no code for it, so the module is written to x402's scheme text and
435
+ lcp's profile. On `starknet:SN_SEPOLIA` the kind's `extra.acceptsZero` names `x402/exact/starknet`, and an option of
436
+ amount `"0"` is taken on STRK (`0x4718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d`) and USDC
437
+ (`0x53b40a647cedfca6ca84f542a0fe36736031905a9639a7f19a3c1e66bfd5080`), the tokens on which lcp's `starknetFloor`
438
+ answers 0 (its profile's rule 24): a `transfer` of 0 of each, simulated on Starknet Sepolia at block 18422698, emits a
439
+ `Transfer` of 0. lcp refuses `"0"` on any other token, `starknet/option-malformed`, which the module answers
440
+ `invalid_payment_requirements`. On `starknet:SN_MAIN` the list is `[]`.
441
+ - **`stellar`**: an object `{ networks }`: `network`; `rpc`, a Stellar RPC endpoint that holds the history the read
442
+ searches; `source`, the seller's funded account as a signer (`address` and `signTransaction`, such as x402's
443
+ `createEd25519Signer` of `@x402/stellar` or a SEP-43 wallet), the transaction's source, which pays its fee;
444
+ `maxTransactionFeeStroops`, optional (default 50,000), and `inclusionFeeStroops`, optional (at least 100, default
445
+ 100). It serves the agreement form, the option whose `extra.assetTransferMethod` is `lcp-precondition`: the module
446
+ builds the transaction around the buyer's operation and preconditions, unchanged, signs it as its source, and carries
447
+ the buyer's payload signature with its own.
448
+ - **`sui`**: an object `{ networks }`: `network` (`sui:mainnet`, `sui:testnet` or `sui:devnet`); `graphql`, the seller's
449
+ GraphQL endpoint. It serves the path where the buyer pays gas and the gasless path (`extra.gasless`), and holds no
450
+ key. A transaction the buyer already executed is judged at `/verify` by its effects, and not refused for having
451
+ executed; its `/settle` answers a failure naming it. The kind's `extra.acceptsZero` names `x402/exact/sui`: a
452
+ transfer of 0 executes where the buyer pays gas (Sui testnet transaction
453
+ `7EjfN1kqGng3phZjqgCzy8RRRXCP2Ybt7mikGgjBUwKA`, status `SUCCESS`, its only balance change the sender's gas), and at
454
+ 0 the signed transfer must name the option's payee. lcp's option filter refuses 0 on the gasless path.
455
+ - **`ton`**: `network`; `signer`, the seller's highload-v3 wallet and its node (`FacilitatorTvmSigner`), which relays
456
+ the payer's W5 request in a message of its own and pays its gas; `reader`, lcp's `TvmReader` over the seller's TON
457
+ Center v3 index.
458
+ - **`tron`**: `network`, `tron:<chain id in decimal>`; `fullNode` and `solidityNode`, the base URLs of a FullNode that
459
+ keeps the block history (not a lite FullNode) and of a Solidity node, with java-tron's HTTP API. The payer signs and
460
+ pays every fee.
461
+ - **`xrpl`**: `network`; `node`, the seller's rippled or Clio JSON-RPC endpoint, holding the ledgers from each payment's
462
+ issue to the validated ledger; `waitMs`, optional, how long a settle waits for its transaction in a validated ledger
463
+ (default 30 000); `maxFeeDrops`, optional, the most fee a payment may sign (the class's default, 10 000). Both paths
464
+ refuse a payment that names a `Delegate` or carries `Memos`, as x402's scheme requires. For `upto`, the payer opens a
465
+ payment channel to `payTo` and signs one claim off the ledger; at `/settle` the resource server adds
466
+ `settlementTransaction`, a `PaymentChannelClaim` its `payTo` key signed for the actual charge with `tfClose`, which the
467
+ module checks and submits unchanged; `/verify` refuses a payload that already carries one, as the scheme requires.
468
+
469
+ The `cardano`, `concordium` and `ton` modules take an lcp reader in `reader` rather than a node's URL, and lcp ships the
470
+ interface but no implementation: `CardanoReader` of `@integraledger/lcp/cardano`, `CcdReader` of
471
+ `@integraledger/lcp/ccd` and `TvmReader` of `@integraledger/lcp/tvm`, each documented member by member on its API page
472
+ ([`cardano`](https://github.com/IntegraLedger/integra-protocol/blob/main/docs/reference/api/cardano.md),
473
+ [`ccd`](https://github.com/IntegraLedger/integra-protocol/blob/main/docs/reference/api/ccd.md),
474
+ [`tvm`](https://github.com/IntegraLedger/integra-protocol/blob/main/docs/reference/api/tvm.md)), with the calls each
475
+ makes in
476
+ [Rails: reading settlement](https://github.com/IntegraLedger/integra-protocol/blob/main/docs/guides/rails.md#reading-settlement).
477
+ Write one over your own indexer or node. Its `network` is the module's `network`: the module refuses to start where they
478
+ differ. Each call is read-only and bounded by your own timeout and byte limit, and rejects on any failure, with lcp's
479
+ `ReaderError` (`@integraledger/lcp/evm`) where the kind is known: a rejection reads as `unreadable`, never as absence.
480
+ An item the endpoint does not hold is answered only in the form the interface names for it (`null`, or
481
+ `{ notFound: true, ... }` with the point the interface asks for), and only where the endpoint answered in the form it
482
+ documents for a missing item. lcp makes no other call, so the endpoint, its credentials, its timeouts and its retries
483
+ are yours.
484
+
485
+ ### What stops the start
486
+
487
+ `serveProfileFacilitator` rejects with the first of these it meets, in this order, having closed what it opened; each
488
+ message starts as shown:
489
+
490
+ | The configuration | The message |
491
+ |---|---|
492
+ | `listen` is not `host:port` | `listen must be "host:port"` |
493
+ | `credential` holds a character RFC 6750 does not admit | `credential must be a bearer token` |
494
+ | A fee budget whose amount is not a positive integer, or whose period is not a positive whole number of seconds | `the fee budget of <network>: its amount is not a positive integer`, `the fee budget of <network>: its period is not a positive number of seconds` |
495
+ | Two fee budgets on one network | `<network> has two fee budgets` |
496
+ | Postgres cannot be reached, or the tables cannot be created ([The database](#the-database)) | the driver's own error |
497
+ | A module's member it refuses, the modules taken in the order of their names | `casper on <network>: not served` (`casper:casper`), `casper on <network>: the signer reads`, `casper on <network>: the signer's speculative execution goes to`, `casper on <network>: the signer names the chain`; `the Cardano reader serves`; `the Concordium signer and reader must serve`; `lnbtc: <network> is not an lnbtc network`; `not a Starknet network`, `the executor's address is not an account address`; `not a Stellar network`, `the source account's address is not an account strkey`, `the fee ceiling must be positive, and the inclusion fee at least 100 stroops`; `not a Sui network`; `the TON reader serves` |
498
+ | An `erc7710` network where the `evm` module does not register `exact` | `an own module is offered to exact on <network>, which no module registers` |
499
+ | A module's class that states `pairings`, `key`, `acceptsZero` or `feeBudget` in its `extra` | `<network>: a module's facilitator states` |
500
+ | Two registrations of one scheme on one network | `two registrations of <scheme> <network>` |
501
+ | Two modules behind one registration whose keys sign for different purposes | `<scheme> on <network>: its modules' keys sign for` |
502
+ | A fee budget on a network no module serves | `the fee budget of <network>: no module serves it` |
503
+ | A fee budget on a network where a keyed module neither counts nor shows its fees (`ton`, `concordium`) | `the fee budget of <network>: the <module> module's key pays fees it neither meters nor shows` |
504
+ | A keyed module, and no `credential` | `a module holds a key (<scheme> on <network>, ...): credential is required` |
505
+
506
+ Any other rejection is the error of a call the start makes, such as the listen's `EADDRINUSE`.
507
+
508
+ ## Keys
509
+
510
+ `extra.key` states what the module's key signs, by one of three values:
511
+
512
+ | `extra.key` | The key | Modules |
513
+ |---|---|---|
514
+ | `none` | The module holds no key and signs nothing: it submits what the payer signed, and the payer pays the fee. | `cardano`, `lnbtc`, `polkadot`, `sui`, `tron`, `xrpl`, and `aptos` with `sponsor: false` |
515
+ | `relayer` | The key sends the transaction and pays its network fee. | `casper`, `erc7710`, `evm`, `near`, `starknet`, `stellar`, `ton` |
516
+ | `fee-payer` | The key co-signs the payer's transaction as the account that pays its fee. | `algorand`, `aptos`, `concordium`, `hedera`, `solana` |
517
+
518
+ Each chain's own name for the role (a gas key, a sponsor, a source account, an executor) stays in its module's notes
519
+ above. The key is always the seller's: the operator's code makes the signer object the module's class takes and passes
520
+ it in the configuration, and its address is in `/supported`'s `signers`. One kind states one purpose: two modules
521
+ behind one registration whose keys sign for different purposes are refused at start.
522
+
523
+ ## The credential
524
+
525
+ The resource server names the payee and the amount, and a keyed module pays a fee for whatever it submits, so an open
526
+ settler would spend the seller's money on payments between other parties. A deployment with a module whose key is not
527
+ `none` therefore does not start without `credential`. Every call, `GET /supported` included, must then present it as
528
+ `Authorization: Bearer <credential>`; the settler compares the SHA-256 of what is presented with that of the credential
529
+ in constant time, and answers a call without it `401` `{"error":"unauthorized"}` with `WWW-Authenticate: Bearer`,
530
+ before it reads the body, closing the connection. A keyless deployment may set one too, with the same effect.
531
+
532
+ ## Security
533
+
534
+ The settler serves plain HTTP (`node:http`, no TLS option): the credential and every payment cross the network in clear
535
+ unless TLS is in front of it. Bind `listen` to loopback or a private interface and terminate TLS in a proxy before it,
536
+ or run the settler on the resource server's own host. The credential is its only gate: anyone who holds it can have a
537
+ keyed module pay fees for payments between other parties, without limit unless a fee budget caps them ([The fee
538
+ budget](#the-fee-budget)), so keep it as you keep the keys, and set a budget on each network whose fees a key pays (the
539
+ `ton` and `concordium` modules take none). The keys live in the operator's process, as the signer objects passed in; the
540
+ settler reads no key material itself, and names a node in an error by its origin alone. It does not check that H is the
541
+ one the resource server issued, nor that the resource server has not accepted it before ([What it is](#what-it-is)):
542
+ those checks are the resource server's.
543
+
544
+ ## What `/supported` states
545
+
546
+ `GET /supported` answers `{kinds, extensions, signers}` as x402's facilitator class gives it. Each kind is
547
+ `{x402Version: 2, scheme, network, extra}`, one per scheme on each configured network, and its `extra` holds:
548
+
549
+ | Member | Value |
550
+ |---|---|
551
+ | `extra.pairings` | The lcp pairing ids the kind submits. A scheme on one network can hold several forms, so the scheme alone does not name them. |
552
+ | `extra.key` | `none`, `relayer` or `fee-payer` ([Keys](#keys)). |
553
+ | `extra.acceptsZero` | The pairings of `extra.pairings` the kind settles at an amount of zero; `[]` where none does. An option of amount zero whose pairing it does not name is refused `invalid_payment_requirements`. |
554
+ | `extra.feeBudget` | `true` on each kind of a network whose fee budget the operator set; absent otherwise. Neither the amount nor what remains is stated. |
555
+ | The class's own members | Kept unchanged, such as `assetTransferMethod` on Tron and Polkadot, `feePayer` where a fee payer co-signs, and `areFeesSponsored` on the XRP Ledger and Stellar. No module's class may state one of the four members above: the settler refuses one that does at start. |
169
556
 
170
- The facilitator serves only the networks it is configured with. A request for any other network is answered
171
- `invalid_network`. At start it creates its table if it does not exist; a Polkadot node's runtime metadata is loaded on
172
- the first payment for that network, and loaded again whenever the node's runtime version changes.
557
+ `signers` is keyed as x402's class keys it, by CAIP family (`eip155:*`, `solana:*`, ...), and holds the address of every
558
+ key that signs on that family. A seller reads `extra.key` to know what a deployment must hold, `extra.pairings` to know
559
+ which forms it can offer with this settler, and `extra.acceptsZero` before choosing a zero agreement amount.
173
560
 
174
561
  ## Verify and settle
175
562
 
176
- Both `POST /verify` and `POST /settle` take the x402 facilitator request:
177
- `{x402Version: 2, paymentPayload, paymentRequirements}`, with `paymentPayload.x402Version` 2 and
178
- `paymentRequirements.scheme` `"exact"`.
563
+ Both `POST /verify` and `POST /settle` take x402's facilitator request,
564
+ `{x402Version: 2, paymentPayload, paymentRequirements}`, with `paymentPayload.x402Version` 2. A refusal answers `200`
565
+ with the refusal in its body.
179
566
 
180
- ```ts title="verify.ts"
567
+ ```ts no-check title="verify.ts"
181
568
  import { serveProfileFacilitator } from "@integraledger/profile-facilitator";
182
569
 
183
- const facilitator = await serveProfileFacilitator({
570
+ const settler = await serveProfileFacilitator({
184
571
  listen: "127.0.0.1:4022",
185
- tron: [{ network: "tron:728126428", fullNode: "http://127.0.0.1:8090", solidityNode: "http://127.0.0.1:8091" }],
186
572
  store: { url: process.env.DATABASE_URL ?? "postgres://postgres@127.0.0.1:5432/postgres" },
187
573
  settleWaitMs: 30_000,
574
+ tron: [{ network: "tron:728126428", fullNode: "http://127.0.0.1:8090", solidityNode: "http://127.0.0.1:8091" }],
188
575
  });
189
576
 
190
- const request = {
191
- x402Version: 2,
192
- paymentPayload: { x402Version: 2, payload: { transaction: "0a02" } },
193
- paymentRequirements: {
194
- scheme: "exact",
195
- network: "tron:3448148188",
196
- amount: "10000",
197
- asset: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
198
- payTo: "TCwX1UeSkVfu43HD5xNMmFqDR2Xgjdxihx",
199
- maxTimeoutSeconds: 60,
200
- extra: { assetTransferMethod: "lcp-trc20-memo" },
201
- },
577
+ const requirements = {
578
+ scheme: "exact",
579
+ amount: "10000",
580
+ asset: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
581
+ payTo: "TCwX1UeSkVfu43HD5xNMmFqDR2Xgjdxihx",
582
+ maxTimeoutSeconds: 60,
583
+ extra: { assetTransferMethod: "lcp-trc20-memo" },
202
584
  };
203
- for (const path of ["/verify", "/settle"]) {
204
- const res = await fetch(`http://127.0.0.1:4022${path}`, {
205
- method: "POST",
206
- headers: { "content-type": "application/json" },
207
- body: JSON.stringify(request),
208
- });
209
- console.log(path, res.status, JSON.stringify(await res.json()));
585
+ // The first network is configured, and its payload is not a Tron transaction; the second is not configured.
586
+ for (const network of ["tron:728126428", "tron:3448148188"]) {
587
+ const body = {
588
+ x402Version: 2,
589
+ paymentPayload: { x402Version: 2, payload: { transaction: "0a02" } },
590
+ paymentRequirements: { ...requirements, network },
591
+ };
592
+ for (const path of ["/verify", "/settle"]) {
593
+ const res = await fetch(`http://127.0.0.1:4022${path}`, {
594
+ method: "POST",
595
+ headers: { "content-type": "application/json" },
596
+ body: JSON.stringify(body),
597
+ });
598
+ console.log(path, res.status, JSON.stringify(await res.json()));
599
+ }
210
600
  }
211
- await facilitator.close();
601
+ await settler.close();
212
602
  ```
213
603
 
214
- ```text output
604
+ ```text
605
+ /verify 200 {"isValid":false,"invalidReason":"invalid_payload"}
606
+ /settle 200 {"success":false,"errorReason":"invalid_payload","transaction":"","network":"tron:728126428"}
215
607
  /verify 200 {"isValid":false,"invalidReason":"invalid_network"}
216
608
  /settle 200 {"success":false,"errorReason":"invalid_network","transaction":"","network":"tron:3448148188"}
217
609
  ```
218
610
 
219
- ### What `/verify` checks on Tron
220
-
221
- In order; the first failure is the answer.
222
-
223
- 1. The network is configured, and the requirements are ones the profile admits (its rule 1), else
224
- `invalid_network` or `invalid_payment_requirements`.
225
- 2. `payload.transaction` is a serialized Tron `Transaction` in hex that decodes to exactly one
226
- `TriggerSmartContract` whose `data` is an LCP `sha256` string, else `invalid_payload`.
227
- 3. `asset` and `payTo` are Tron addresses, else `invalid_payment_requirements`.
228
- 4. The contract called is `asset`, and the call data is exactly `transfer(payTo, amount)`, else `invalid_payload`.
229
- 5. The transaction carries exactly one signature, else `unsupported_permission`. That signature recovers to the
230
- transaction's owner, else `invalid_payload`.
231
- 6. The store does not hold the transaction id, else `invalid_transaction_state`.
232
- 7. `expiration` is in the future and no later than now plus `maxTimeoutSeconds`, else `invalid_payload`.
233
- 8. Five reads of the FullNode, made together. The first refusal in this order is the answer, and a node that does
234
- not answer gives `unexpected_verify_error`:
235
- - **The owner's permission.** `/wallet/getaccount` gives the owner permission, and the weight it gives the
236
- owner's key must be at least its threshold, else `unsupported_permission`. An account with no owner permission
237
- set, or one the node does not hold, has the network's default: its own key, weight 1, threshold 1. So a
238
- multi-signature owner, or an owner whose permission does not hold the address's own key, is refused here
239
- rather than at broadcast.
240
- - **TaPoS.** The node accepts a transaction only when `ref_block_hash` equals bytes 8–15 of the id of the latest
241
- block whose number's bytes 6–7 are `ref_block_bytes`. The facilitator reads the head with
242
- `/wallet/getnowblock`, then that block with `/wallet/getblock`, and makes the same comparison, else
243
- `invalid_transaction`.
244
- - **The id.** `/wallet/gettransactionbyid` must not find the transaction in a block, and
245
- `/wallet/gettransactionfrompending` must not find it in the node's pending pool, else
246
- `invalid_transaction_state`.
247
- - **The simulation.** `/wallet/triggerconstantcontract` simulates the transfer without failure, else
248
- `invalid_transaction`.
249
-
250
- The answer is `{isValid: true, payer}`, with `payer` the owner in base58check.
251
-
252
- ### What `/settle` does on Tron
253
-
254
- 1. Repeats the checks of `/verify` that read neither the store nor the node (steps 1 to 5).
255
- 2. Reads the stored answer for the transaction id. A stored success means the payment is consumed: the answer is
256
- `invalid_transaction_state` with the transaction id, never a second success. Any other final answer is returned
257
- as it is. A claimed id, or a stored `settlement_pending`, goes on to step 6 and broadcasts nothing.
258
- 3. For an id the store does not hold, checks the expiration window and then the settle's wait: once `settleWaitMs`
259
- has passed, it sends no node call and answers `unexpected_settle_error` (`invalid_payload` for an expiration
260
- outside the window). Otherwise it reads the id first, with `/wallet/gettransactionbyid` and
261
- `/wallet/gettransactionfrompending`. An id the FullNode holds, in a block or its pending pool, is a consumed
262
- payment, answered `invalid_transaction_state` with the id, whatever the other checks give, an expiration outside
263
- the window among them. A node that does not answer the id reads gives `unexpected_settle_error`. Otherwise an
264
- expiration outside the window is answered `invalid_payload`, and for one inside it the facilitator makes the other
265
- node reads of `/verify`; a refusal is answered with an empty `transaction`. Once the reads have started, one the
266
- wait leaves no time for is not sent, and in its place among the refusals is answered `unexpected_settle_error`;
267
- for an expiration outside the window, an id read not sent finds nothing, and the answer is `invalid_payload`.
268
- 4. Claims the transaction id with one conditional insert, so concurrent settles of one payment broadcast once. Once
269
- the wait for the chain has ended, the broadcast would have no time left: it claims nothing and answers
270
- `unexpected_settle_error`, and nothing is stored, so a repeat of the payment is settled as a new one.
271
- 5. Broadcasts the signed bytes with `/wallet/broadcasthex`. A `DUP_TRANSACTION_ERROR` says the node already holds the
272
- transaction: the payment is consumed, answered `invalid_transaction_state` with the id. Any other refusal, or a
273
- request that cannot have reached the node, is answered `unexpected_settle_error` with an empty `transaction`:
274
- nothing was broadcast. So is a broadcast the wait leaves no time for, as after a claim that answers late: it is not
275
- sent. Either answer is stored final and every repeat gets it. The claim is never removed, so the payment is
276
- broadcast at most once.
277
- 6. Reads the transaction's status every second with `@integraledger/lcp`'s `tronStatus`, by transaction id: through the
278
- Solidity node's `/walletsolidity` API for solidified data first, then the FullNode's `/wallet` API at the head.
279
- Success requires receipt result `SUCCESS` **and** a `Transfer` log emitted by `asset`. A success read at the head,
280
- before its block is solidified, can be reorganised out of the chain. The value the call returned is not read: a
281
- TRC-20 token may return false from `transfer` and still transfer, and USDT-TRC20 does. `tronStatus` answers a receipt
282
- with another result, or `SUCCESS` with no such log, as failed at whichever lookup finds it first; the facilitator
283
- takes that failure as final only from the Solidity node's lookup, which reads solidified blocks alone. A transaction
284
- whose expiration has passed can never be included once the solidified head, read first, is two slots past it and
285
- neither lookup finds it, each naming a latest block at or past that head's time, read from its node before the
286
- lookup. A lookup whose node cannot give that time, or whose latest block is behind the head, leaves the answer
287
- pending. Each failure is answered `invalid_transaction_state`.
288
- 7. Stores the answer and returns it. A success is returned only by the settle whose write stored it, so of two
289
- concurrent settles of one payment, one answers success and the other `invalid_transaction_state` with the id. A
290
- success, or an answer with an empty `transaction`, whose write fails is answered `settlement_pending` with the id.
291
-
292
- Success is `{success: true, transaction, network, payer}`, where `transaction` is the transaction id in hex.
293
-
294
- ### What `/verify` checks on Polkadot
295
-
296
- 1. The network is configured, and the requirements are ones the profile admits, else `invalid_network` or
297
- `invalid_payment_requirements`.
298
- 2. `payload.extrinsic` and `payload.call` are lowercase hex; the call is exactly
299
- `utility.batch_all([assets.transfer_keep_alive(asset, Id(payTo), amount), system.remark_with_event(R)])` for this
300
- `asset`, `payTo` and `amount`, and R is exactly the 77 bytes `lcp:sha256:` followed by H in lowercase hex, else
301
- `invalid_payload`. `System.Remarked` carries the BLAKE2b-256 of the remark's bytes as signed, so a remark that
302
- spells H any other way, such as with upper-case digits, is refused.
303
- 3. With the network's runtime metadata, the extrinsic decodes as a signed v4 extrinsic whose call is `payload.call`
304
- byte for byte, with a mortal era, else `invalid_payload`. The node must serve the chain the network names (its
305
- genesis hash), else `unexpected_verify_error`.
306
- 4. `TaggedTransactionQueue_validate_transaction` at the best block returns `Ok`, else `invalid_transaction`.
307
-
308
- The answer is `{isValid: true, payer}`, with `payer` the signer in SS58.
309
-
310
- ### What `/settle` does on Polkadot
311
-
312
- 1. Repeats the checks of `/verify` that read nothing from the node (steps 1 and 2).
313
- 2. Reads the stored answer for the extrinsic's BLAKE2b-256 hash. A stored success means the payment is consumed: the
314
- repeat answers `invalid_transaction_state` with the success's `transaction`, never a second success. Any other
315
- final answer is returned as it is. A claimed hash, or a stored `settlement_pending`, is followed from the chain: the
316
- extrinsic is decoded again and step 5's scan goes on from the blocks its row records as not yet read, and nothing
317
- is submitted.
318
- 3. For a hash the store does not hold, decodes the extrinsic and asks the node to validate it, as `/verify` does
319
- (steps 3 and 4), reading the finalized head before the validation. The settle's wait is checked before each of
320
- these three node reads and before each node call they make: once `settleWaitMs` has passed, it sends no node call
321
- and answers `unexpected_settle_error`. A metadata load, which serves every request for the network, is not started
322
- then; one started earlier goes on within its own bound of 30 seconds, and sends no node call once that bound has
323
- passed.
324
- Step 1's refusals come first; the decode's refusals need the node's metadata, so they are given only while the wait
325
- leaves time for it. Then claims the hash, with the first block to scan: the block after the finalized head read
326
- before validation, never before the era's birth. Once the wait for the chain has ended, the submission would have
327
- no time left: it claims nothing and answers `unexpected_settle_error`, and nothing is stored, so a repeat of the
328
- payment is settled as a new one.
329
- 4. Submits with `author_submitExtrinsic`. A refusal that says the node has already seen the extrinsic or its nonce
330
- (1013 already imported, 1012 temporarily banned, or 1010 with an outdated nonce) is a consumed payment, answered
331
- `invalid_transaction_state` with the extrinsic's hash, and no block is scanned for it. Any other refusal, or a
332
- request that cannot have reached the node, is answered `unexpected_settle_error` with an empty `transaction`:
333
- nothing was submitted. So is a submission the wait leaves no time for, as after a claim that answers late: it is not
334
- sent. Either answer is stored final and every repeat gets it. The claim is never removed, so the extrinsic is
335
- submitted at most once.
336
- 5. Scans every second, up to the last block that can include the extrinsic: the era's last block, and no later than
337
- `System.BlockHashCount` + 1 blocks after the era's birth. Each block's execution keeps only the hashes of the
338
- `BlockHashCount` + 1 blocks before it, and the chain refuses an extrinsic whose birth block's hash is gone. The scan
339
- reads first the finalized blocks, then the blocks up to the head. In the block that holds the extrinsic, success
340
- needs `System.ExtrinsicSuccess`, `System.Remarked` for R's BLAKE2b-256 and `Assets.Transferred` for `asset`. A
341
- success read in a block above the finalized head can be reorganised out of the chain. A failure counts only in a
342
- finalized block.
343
- 6. A finalized block the node cannot give, its body or, for the block that holds the extrinsic, its events, is recorded
344
- as unread and skipped. The scan goes on to the blocks after it, so a success in a later block is still found, and the
345
- unread block is read again on each later pass and on each repeat. A block read that cannot start before the deadline,
346
- because the process's 4 block reads are all running, is recorded the same way. A block above the finalized head that
347
- cannot be read is skipped, since it is read again at finality.
348
- 7. Once every block to the last is finalized without the extrinsic, and no block is unread, it can never be included:
349
- `invalid_transaction_state`.
350
- 8. Stores the answer and returns it. A success is given only by the `/settle` that stores it, and an answer with an
351
- empty `transaction` only once it is the stored answer. When either cannot be stored, the answer is
352
- `settlement_pending` with the extrinsic's hash, and a later `/settle` reads the chain again.
353
-
354
- Success is `{success: true, transaction, network, payer}`, where `transaction` is `<block hash>-<extrinsic index>`.
355
- While the extrinsic is broadcast but not yet in a block, the answer is `settlement_pending` with `transaction` set to
356
- the extrinsic's hash.
357
-
358
- ### Pending and repeated settles
359
-
360
- When the wait ends first, `/settle` answers `{success: false, errorReason: "settlement_pending", transaction}` with the
361
- transaction id or extrinsic hash; x402 requires that `transaction` not be empty. Call `/settle` again with the same
362
- request: it reads the chain from where it stopped, never submits twice, and returns the final answer once there is one.
363
- The facilitator keeps the payment's row until that final answer is written, however long that takes, so a repeat made
364
- after the validity window has ended still reads the chain. On Tron a payment is answered success once: every later
365
- `/settle` of it answers `invalid_transaction_state` with the transaction id, because x402's `exact` family requires that
366
- a consumed payment produce a settlement failure, never a success. Once the payment's row is gone, the FullNode's blocks
367
- give that answer. A broadcast or submission the node refused, or never received, is stored too, and every repeat gets
368
- its answer. When the store cannot be read, the facilitator cannot know whether the payment was submitted, so it answers
369
- `settlement_pending` with the id.
370
-
371
- An answer with an empty `transaction` means nothing was submitted: on Tron always, and on Polkadot while the
372
- facilitator keeps the payment's row (until 24 hours after its validity window). After that, a repeated `/settle` of a
373
- Polkadot extrinsic that landed finds no row, the node's validation refuses it, and the answer is `invalid_transaction`
374
- with an empty `transaction`.
375
-
376
- A payment whose success has been answered is consumed. On Polkadot, while the facilitator keeps the payment's row, a
377
- repeated `/settle` for it answers `invalid_transaction_state` with the success's `transaction`, never a second
378
- success, as x402's `exact` family requires: *"A consumed primitive MUST produce a settlement failure, never a
379
- success."* Of two concurrent settles of one payment, one answers success and the other that failure.
380
-
381
- ## API reference
382
-
383
- The package's entry point exports:
384
-
385
- | Export | Kind | What it is |
386
- |---|---|---|
387
- | `serveProfileFacilitator(config)` | `(c: ProfileFacilitatorConfig) => Promise<{ close(): Promise<void> }>` | Opens the store, starts the HTTP server and resolves once it listens. If it cannot start, it closes the store and rejects with the error that stopped it, such as the listen's `EADDRINUSE`. |
388
- | `ProfileFacilitatorConfig` | interface | The configuration above. |
389
-
390
- ### HTTP API
611
+ ### `/verify`
612
+
613
+ `/verify` moves nothing. In order; the first refusal is the answer:
614
+
615
+ 1. The request's shape: `invalid_x402_version`, `invalid_payload`.
616
+ 2. The network is one a module serves, else `invalid_network`, and the scheme one a module registers on it, else
617
+ `unsupported_scheme`. Where an own module claims the payment (by a member of the option, or by what the payment
618
+ holds), it goes to that module, else to the registration's class. On `lnbtc` the answer is `unsupported_scheme`.
619
+ 3. lcp's checks of the pairing, from the payment and its requirements alone. A refusal carries x402's reason and, on
620
+ the `algorand`, `aptos`, `casper`, `hedera`, `solana`, `starknet` and `sui` modules, lcp's refusal code as
621
+ `invalidMessage` (on `starknet` and `sui`, the module's own code where its own check refused).
622
+ 4. The record: a payment it holds, claimed or final, is refused `invalid_transaction_state`, since `isValid: true`
623
+ tells the caller that a settle may follow.
624
+ 5. What the kind declares: an amount of zero whose pairing `extra.acceptsZero` does not name, and a form outside the
625
+ pairings of the module the payment goes to, are refused `invalid_payment_requirements`.
626
+ 6. The fee budget, where the module's key pays the fee: a spent budget is refused `fee_budget_spent`.
627
+ 7. The class's verify, unchanged, with its own reasons.
628
+ 8. lcp's read of the chain: a payment the chain shows final (landed, or consumed by another act) is refused
629
+ `invalid_transaction_state`. A read that fails goes to the operator log and leaves the class's answer.
630
+
631
+ On `sui`, whose `/verify` judges a transaction the buyer already executed by its effects, steps 4 and 8 are not made.
632
+ The answer is `{isValid: true, payer}` or `{isValid: false, invalidReason, invalidMessage?, payer?}`.
633
+
634
+ ### `/settle`
635
+
636
+ 1. Steps 1 to 3 of `/verify`, with `errorMessage` for `invalidMessage`; `lnbtc` is served here.
637
+ 2. The record: a final row is answered `invalid_transaction_state` naming the transaction it holds, never a second
638
+ success.
639
+ 3. What the kind declares, as `/verify` checks it.
640
+ 4. A claim the record holds that is not final, which another settle holds or whose hold has ended: it is answered as
641
+ [the record](#the-record-and-what-a-repeat-answers) says, and no step below is made.
642
+ 5. The class's verify. Where it refuses, lcp's read of the chain: a payment the chain shows landed, or whose value
643
+ another act consumed, is stored final and answered `invalid_transaction_state` naming its transaction; otherwise the
644
+ class's refusal is the answer, nothing is stored, and a repeat is checked again.
645
+ 6. Where the module's read searches from a position no x402 call carries (a ledger, a slot, a block), the chain's
646
+ position, read just before the claim, which the row keeps for every later read.
647
+ 7. The claim: one conditional insert of the payment's row, held by this settle for `settleWaitMs`, so that of two
648
+ settles of one payment only one submits.
649
+ 8. The fee budget, where the module's key pays the fee: a spent budget answers `fee_budget_spent`, sends nothing, and
650
+ leaves the claim, not final.
651
+ 9. The class's settle, which submits what the payer signed. A success that names a transaction is stored final, then
652
+ answered `{success: true, transaction, network, payer}`. Anything else is classified by lcp's read: a payment the
653
+ chain shows final is stored final and answered (success only where the read shows a transaction this settler sent,
654
+ or the payment it presented, settled); one still live is answered `settlement_pending` naming the transaction sent,
655
+ or the class's own failure where it named no transaction or its failure consumed nothing.
656
+
657
+ A success is answered once, only by the settle whose write stored it: of two settles of one payment, only one answers
658
+ success, and the other answers `invalid_transaction_state` naming the transaction, or `settlement_pending` where its
659
+ wait ends first. A success that cannot be stored is answered `settlement_pending` naming its transaction, and a later
660
+ `/settle` reads the chain again.
661
+
662
+ ## The record, and what a repeat answers
663
+
664
+ The record is one row per payment, its **instrument**, within its network: the single-use value its signer signed (an
665
+ authorization nonce, a sequence number, an account nonce, with the token or nonce key it counts in), or the transaction
666
+ id where the chain derives it from the signed content alone, or the digest of the signed payment where the pairing's
667
+ single-use value is not shown. It is never the single-use value alone, which two payers can share, and never a hash
668
+ that a copy signed again would change. An agreement and a payment of one payer under one H are two instruments.
669
+
670
+ A row is **final** once its answer can never change: a success; a failed result that consumed the single-use value; a
671
+ value another act consumed; a validity that passed with the value unconsumed; or a payment that landed by another
672
+ route. A refused submission, one that cannot have reached the node, and a failed result that consumed nothing leave the
673
+ row a claim, which a repeat reads again. A claim is never removed.
674
+
675
+ | A repeated `/settle` finds | It answers |
676
+ |---|---|
677
+ | A final row | `invalid_transaction_state` naming the transaction the row holds. Never a second success, as x402's `exact` family requires: a consumed payment produces a settlement failure. |
678
+ | A claim another settle holds | It reads the row every second and sends nothing, until that settle answers or its hold ends; then the row's answer, or lcp's read. It answers `settlement_pending` naming the transaction where one is known, and `unexpected_settle_error` where none is known when its wait ends. |
679
+ | A claim whose hold has ended | It takes the claim and reads the chain. A payment the chain shows final is stored and answered. The identical signed payment is submitted again only where the pairing's `nonce` is `single-use` in lcp's registry, the row is not named by the digest of the signed payment, the read shows the value unconsumed and its validity open, the body is the one that claimed the row, and the class's verify passes again. Another body under the same instrument is answered `invalid_transaction_state`. Otherwise `settlement_pending` naming the transaction sent, or `unexpected_settle_error` where none is known. |
680
+ | No row, and the store cannot be read | `settlement_pending` where the payment's transaction id is known before it is sent, else `unexpected_settle_error`: the settler cannot know whether it was sent. |
681
+
682
+ When the wait ends first, `/settle` answers `{success: false, errorReason: "settlement_pending", transaction}`; x402
683
+ requires that `transaction` not be empty. Call `/settle` again with the same request: it reads the chain from where the
684
+ last read stopped, never sends what it sent before unless the rule above admits it, and returns the final answer once
685
+ there is one. A final row is kept at least 24 hours past the time its payment can last land (its signed validity, or
686
+ the longest the rail keeps a signed payment payable), and for the settler's life where neither is known or the
687
+ pairing's `nonce` is not `single-use`; a claim that is not final is kept until a repeat makes it final.
688
+
689
+ ## The fee budget
690
+
691
+ A keyed module pays fees for what it submits. `feeBudgets` caps them per network: an amount of the network's fee asset,
692
+ in its smallest unit, over a period of seconds. The count holds every transaction a module whose key pays the fee
693
+ submitted on the network over the last period: its bound until the chain shows it included, then the fee it paid.
694
+ Where the count has reached the amount:
695
+
696
+ - `/verify` and `/settle` refuse a payment whose fee the module's key would pay, `fee_budget_spent`, before anything is
697
+ sent. A payment whose payer pays the fee is never refused for it.
698
+ - Each kind of the network states `extra.feeBudget: true`, so that a resource server learns that the settler may refuse
699
+ every payment on that network for a period.
700
+
701
+ The fee counted is what the chain shows. On an EVM network it is the gas used times its price and, on an OP Stack
702
+ network, the L1 data fee the receipt shows (`l1Fee`); before inclusion, the gas limit times the fee cap, with the L1
703
+ data fee the network's GasPriceOracle (`getL1Fee`) gives. On Hedera it is the fee the Mirror Node shows, asked for up
704
+ to five seconds after the settle answers; where the mirror shows none by then, the `maxFee` the payer signed. The
705
+ `evm`, `solana`, `aptos` and `casper` modules count each transaction their key sends as it is sent, one their class
706
+ does not name in its answer included: a payer's ERC-6492 wallet deployment on EVM, or a Solana or Casper transaction
707
+ whose send failed.
708
+
709
+ At start the settler refuses a budget on a network no configured module serves, and one on a network where a module
710
+ whose key pays fees can neither show the fee of what it sent nor count it as it sends: the `ton` and `concordium`
711
+ modules, whose classes and lcp's reads give no fee.
712
+
713
+ Its stated costs:
714
+
715
+ - A transaction is counted once it is sent (`evm`, `solana`, `aptos`, `casper`) or once its settle answers (`algorand`,
716
+ `erc7710`, `hedera`, `near`), so settles that run at once on a nearly spent budget can each pass the check before the
717
+ first is counted. The `starknet` and `stellar` modules count each send before it is made, one at a time per network.
718
+ The `evm` module's count at the send is what its node shows then: a transaction the node does not show yet (the
719
+ operator log's `fee-not-counted`, reason `not-shown`) is not counted until a later read shows it, when the class's
720
+ wait for its receipt ends or when the settle answers, and one the node never shows, never mined, is not counted.
721
+ - A transaction whose id is not known before it is sent is counted at its bound for the whole period, as well as at
722
+ the fee it paid once included. The count can exceed what was paid; it never falls short of it.
723
+
724
+ ## What it does not serve
725
+
726
+ - **MPP.** The settler answers x402's facilitator calls only, and serves none of MPP's calls.
727
+ - **Sui's sponsored path.** x402's Sui scheme needs a gas station, whose wire its scheme does not state and whose caller
728
+ is the buyer's client, which does not hold the resource server's credential. An option that names one is refused
729
+ `invalid_payment_requirements`; the `sui` module holds no key.
730
+ - **Hedera's transfer executor** (`x402/exact/hedera/transfer-executor`). No member of the configuration names an
731
+ executor, and x402's specification of the method admits none by default.
732
+ - **Solana's channel forms on mainnet.** `x402/upto/solana` and `x402/batch-settlement/solana` need the payment-channels
733
+ program, which is not deployed on Solana mainnet; there only `exact` is registered.
734
+ - **Casper mainnet.** x402's Casper scheme names `casper:casper`, but no token there has yet been shown to execute
735
+ `transfer_with_authorization`, so the `casper` module does not start on it; it serves `casper:casper-test`.
736
+ - **lcp's x402 pairings that another party settles.** `x402/exact/eip155/gateway-batched`, Circle's batched option,
737
+ which the `evm` module refuses, and `x402/batch-settlement/cloudflare`, on Cloudflare's `cloudflare:402` network,
738
+ which no module serves.
739
+
740
+ ## HTTP API
391
741
 
392
742
  | Request | Answer |
393
743
  |---|---|
394
- | `GET /supported` | `200` `{kinds, extensions: [], signers: {}}`, one kind per configured network. |
395
- | `POST /verify` | `200` `{isValid: true, payer}` or `{isValid: false, invalidReason, payer?}`; `400` `{isValid: false, invalidReason: "invalid_payload"}` when the body is not JSON. |
396
- | `POST /settle` | `200` `{success: true, transaction, network, payer}` or `{success: false, errorReason, transaction, network}`; `400` with `errorReason` `invalid_payload` when the body is not JSON. |
397
- | A body over 64 KiB | `413`, and the connection is closed. |
744
+ | `GET /supported` | `200` `{kinds, extensions, signers}`. |
745
+ | `POST /verify` | `200` `{isValid: true, payer}` or `{isValid: false, invalidReason, invalidMessage?, payer?}`; `400` `{isValid: false, invalidReason: "invalid_payload"}` when the body is not JSON. |
746
+ | `POST /settle` | `200` `{success: true, transaction, network, payer}` or `{success: false, errorReason, errorMessage?, transaction, network}`; `400` with `errorReason` `invalid_payload` when the body is not JSON. |
747
+ | A call without the credential, where one is configured | `401` `{error: "unauthorized"}` with `WWW-Authenticate: Bearer`, before the body is read; the connection is closed. |
748
+ | A body over 132,096 bytes | `413`, and the connection is closed. |
398
749
  | Another method on a served path | `405` `{error}`. |
399
750
  | Any other path | `404` `{error}`. |
751
+ | An error outside every answer | `500` `{error: "internal error"}`, once its entry is in the operator log. |
400
752
 
401
- The facilitator has no authentication of its own. Serve it on a private interface, or behind your own network
402
- controls, to the resource servers that use it.
753
+ The body bound is twice lcp's `MAX_HEADER_BYTES` (65,536), the largest payment payload and the largest option lcp's
754
+ x402 codec reads, and 1,024 bytes for the envelope.
403
755
 
404
756
  ### Reasons
405
757
 
406
758
  | Reason | `/verify` | `/settle` | Meaning |
407
759
  |---|---|---|---|
408
760
  | `invalid_x402_version` | yes | yes | `x402Version` is not 2 in the request or the payload. |
409
- | `unsupported_scheme` | yes | yes | `scheme` is not `"exact"`. |
410
- | `invalid_network` | yes | yes | The network is not one this facilitator is configured with. |
411
- | `invalid_payment_requirements` | yes | yes | The requirements are not ones the profile admits. |
412
- | `invalid_payload` | yes | yes | The payload does not match the profile or the requirements, or its signature or expiration fails. |
413
- | `unsupported_permission` | yes | yes | Tron: the transaction carries more than one signature, or the owner's permission does not accept its one signature (the key's weight is below the threshold). |
414
- | `invalid_transaction` | yes | yes | The node refuses the transaction in simulation or validation. On Tron this includes a reference block (TaPoS) that does not match the node's. |
415
- | `unexpected_verify_error` | yes | no | The node or the store could not be read. |
416
- | `unexpected_settle_error` | no | yes | The node could not be read before submission, or refused the submission, or the settle's `settleWaitMs` passed before a node read, or its wait for the chain ended before its claim or its submission. |
417
- | `settlement_pending` | no | yes | Submitted, or possibly submitted (the store could not be read), and not yet final or not yet stored when the wait ended. |
418
- | `invalid_transaction_state` | yes | yes | `/settle`: included and failed, or it can never be included. On Tron also a consumed payment: its success was already answered, or the node already holds its id. `/verify` (Tron): the node, in a block or its pending pool, or the store already holds the transaction id. On Polkadot, also a repeat of a payment whose success has been answered, or a submission the node refuses as one it has already seen (already imported, temporarily banned, or an outdated nonce). |
761
+ | `invalid_network` | yes | yes | No configured module serves the network. |
762
+ | `unsupported_scheme` | yes | yes | No module registers the scheme on the network. On `lnbtc`, every `/verify`. |
763
+ | `invalid_payment_requirements` | yes | yes | The requirements are not ones the pairing's profile admits; an amount of zero whose pairing the kind's `extra.acceptsZero` does not name; a form outside the kind's pairings; an option the module refuses (each module's notes). |
764
+ | `invalid_payload` | yes | yes | The payload does not match the profile or the requirements. |
765
+ | `unsupported_permission` | yes | yes | Tron: the owner's permission does not accept the transaction's signatures. |
766
+ | `invalid_transaction` | yes | yes | The node refuses the transaction in simulation or validation, in a module of the settler's own. |
767
+ | `invalid_transaction_state` | yes | yes | `/verify`: the record or the chain already holds the payment. `/settle`: a repeat of a final row, or a payment the chain shows failed, consumed by another act, lapsed or landed by another route; each names the transaction where one is known. |
768
+ | `fee_budget_spent` | yes | yes | The network's fee budget is spent, and the module's key would pay the fee. |
769
+ | `settlement_pending` | no | yes | Submitted, or possibly submitted, and not yet final or not yet stored when the wait ended; `transaction` names it. |
770
+ | `unexpected_verify_error` | yes | no | A node or the store could not be read. |
771
+ | `unexpected_settle_error` | no | yes | A node or the store could not be read before submission, the settle's wait ended before it, or the submission failed with nothing sent. |
419
772
 
420
- `unsupported_permission` and `invalid_transaction` are this facilitator's, for a Tron owner permission that does not
421
- accept the transaction's one signature and for a transaction the node refuses in simulation or validation. The
422
- others are the x402 specification's.
773
+ `unsupported_permission`, `invalid_transaction` and `fee_budget_spent` are the settler's own; the others are x402's. A
774
+ published class's own reasons, such as `invalid_exact_evm_payload_signature`, pass unchanged.
423
775
 
424
- ### Storage
776
+ ## Storage
425
777
 
426
- Postgres holds one table, created at start:
778
+ Postgres holds three tables, created at start where they do not exist:
427
779
 
428
780
  ```sql
429
- CREATE TABLE IF NOT EXISTS settlement (
781
+ CREATE TABLE IF NOT EXISTS instrument (
430
782
  network text NOT NULL,
431
- id text NOT NULL,
783
+ key text NOT NULL,
784
+ pairing text NOT NULL,
785
+ claimed bigint NOT NULL,
786
+ held_until bigint NOT NULL,
787
+ final boolean NOT NULL DEFAULT false,
788
+ outcome text,
432
789
  answer jsonb,
433
- until timestamptz NOT NULL,
434
- since bigint,
435
- unread bigint[] NOT NULL DEFAULT '{}',
436
- PRIMARY KEY (network, id)
790
+ transaction text,
791
+ sent text[] NOT NULL DEFAULT '{}',
792
+ body text,
793
+ payer text,
794
+ search jsonb,
795
+ since jsonb,
796
+ keep_until bigint,
797
+ PRIMARY KEY (network, key)
798
+ );
799
+ CREATE INDEX IF NOT EXISTS instrument_final_keep ON instrument (keep_until) WHERE final AND keep_until IS NOT NULL;
800
+ CREATE TABLE IF NOT EXISTS fee (
801
+ network text NOT NULL,
802
+ transaction text NOT NULL,
803
+ at bigint NOT NULL,
804
+ fee numeric(78, 0) NOT NULL,
805
+ included boolean NOT NULL,
806
+ PRIMARY KEY (network, transaction)
437
807
  );
438
- CREATE INDEX IF NOT EXISTS settlement_final_until ON settlement (until)
439
- WHERE answer IS NOT NULL AND answer->>'errorReason' IS DISTINCT FROM 'settlement_pending'
808
+ CREATE INDEX IF NOT EXISTS fee_at ON fee (network, at);
809
+ CREATE TABLE IF NOT EXISTS module_state (
810
+ module text NOT NULL,
811
+ key text NOT NULL,
812
+ value jsonb NOT NULL,
813
+ PRIMARY KEY (module, key)
814
+ )
440
815
  ```
441
816
 
442
- - One row per settled payment, keyed by network and transaction id (Tron) or extrinsic hash (Polkadot).
443
- - `answer` is null while the row is claimed and the answer is not yet written. A final answer is never replaced; a
444
- pending one is replaced by what a later read of the chain shows, or by the stored answer to a broadcast or
445
- submission the node refused or never received.
446
- - `until` is the end of the payment's validity window: Tron's `expiration`, or, for Polkadot, the end of the last
447
- block that can include the extrinsic (the era's last, and no later than `System.BlockHashCount` + 1 blocks after its
448
- birth), counted from the best block at 12 seconds a block.
449
- - A row whose answer is final (`success: true`, or a failure other than `settlement_pending`) is kept for 24 hours
450
- after `until`, so a repeat in that time reads the stored answer before the expiration check and the node reads are
451
- made again.
452
- - A row whose answer is not final (claimed with no answer, or `settlement_pending`) is kept, whatever its age, until a
453
- repeated `/settle` reads the chain and writes a final answer, or the answer to a refused or unsent broadcast or
454
- submission makes it final. A repeat therefore always finds the id of a payment this facilitator submitted, and never
455
- answers with an empty `transaction` for it.
456
- - A claim is never removed. A broadcast or submission the node refuses, or that cannot have reached it, stores its
457
- answer, final, in the claimed row: `invalid_transaction_state` with the id when the node says it already holds the
458
- transaction, and `unexpected_settle_error` with an empty `transaction` for any other refusal or a request that cannot
459
- have reached the node. Every repeat gets that stored answer, so a payment is submitted at most once.
460
- - A sweep every minute drops the rows whose answer is final and whose `until` is more than 24 hours past. It reads
461
- them through `settlement_final_until`, an index that holds only rows with a final answer, so the rows it keeps add
462
- nothing to its work.
463
- - `since` is, for Polkadot, the first block the scan has not yet read at finality.
464
- - `unread` is, for Polkadot, the finalized blocks below `since` that the node could not give. None of them is shown to
465
- lack the extrinsic, so each is read again, and the answer that the extrinsic can never be included waits until the
466
- list is empty. A scan's write keeps every block of the list that the scan did not read, so concurrent repeats lose
467
- none. It holds at most one entry per block of the validity window.
468
- - The pool holds at most 10 connections. Acquiring a connection, each query and each statement are bounded by 5
469
- seconds.
470
-
471
- ### Bounds and logs
472
-
473
- - Each node call has a timeout of at most 5 seconds and an answer of at most 4 MiB, except Polkadot's
474
- `chain_getBlock`. Its bound is sized from the runtime's `System.BlockLength`, read from the metadata: 4 MiB, plus
475
- 9/2 of the largest class limit (an extrinsic of n encoded bytes is at most 2n + 5 JSON characters), plus 7 times
476
- `maxHeaderSize`. For Polkadot Asset Hub's runtime 2005000 that is 28,504,064 bytes. At most 4 of these reads run at
477
- once in one process, so block answers take at most 114,016,256 bytes for that runtime. A read waits for a free slot
478
- until the scan's deadline; one that cannot start by then is recorded as unread, like a block the node cannot give,
479
- and read again later. Every other node call has no such limit. On Tron, `/verify` makes six FullNode calls:
480
- the account, the two id reads, the simulation and the head read at once, then the reference block read. A node call
481
- is sent only while its bound leaves it time. In `/settle` that bound is the settle's deadline for the node reads
482
- before the claim, and the end of the wait for the chain for the submission and the reads that follow the chain:
483
- that wait ends a second before the deadline (a quarter of a shorter `settleWaitMs`), the time kept for storing the
484
- answer. A call its bound leaves no time for is not sent. A Polkadot metadata load serves every request for its
485
- network, so no request's deadline bounds it: the load has 30 seconds as a whole, and each of its calls has the node
486
- call bound within the time the load has left. Once the 30 seconds have passed, the load is given up: it has no call
487
- in flight and sends no further call, and a later request starts a fresh load.
488
- - A request body is at most 64 KiB. The server's request timeout is `settleWaitMs` plus 60 seconds.
489
- - The table holds a row with a final answer until 24 hours after its validity window ends. A row with no final answer
490
- stays until a repeated `/settle` for it gives one. Each such row is a payment that passed every check and was
491
- claimed for submission; it is one row of fixed columns, the sweep's index does not hold it, and each repeat reads the
492
- chain within `settleWaitMs`. On Tron, one repeat made once the latest solidified block is two slots past the
493
- expiration gives a final answer whenever the nodes answer its reads, each naming a latest block at or past that one.
494
- - The facilitator gives its operator log (`operatorLog`; by default one JSON line on standard error) what the operator
495
- should see and the answer does not carry, each entry with `network`, `payer` and `transaction` where they are known:
496
- `settlement-failed` (with the events, or the receipt result and why the transfer does not count, that the chain
497
- shows), `settlement-expired`, `answer-not-stored`, `block-unreadable` (a Polkadot block the node does not give, with
498
- the node's reason; `final` when it was read at finality and is recorded as unread), `block-read-stopped` (a block read
499
- the settle's deadline ended) and `settlement-consumed` (a repeated `/settle` of a Polkadot payment whose success has
500
- been answered). Each error the facilitator turns into an answer or a retry is an entry with the error as its cause:
501
- `verify-error`, `settle-error` and `request-error` (an error the request's handling threw), `node-call-failed` and
502
- `store-call-failed` (with the `call`), and `store-connection-error`. Every `unexpected_verify_error` and
503
- `unexpected_settle_error` answer has an entry that names why, written when it is first given (a repeated `/settle`
504
- gets the stored answer), with the call or the bound: an error's entry above;
505
- `node-call-failed` for a node answer the facilitator cannot read, its cause a `malformed` error naming the part, and
506
- for a Tron broadcast the node does not accept, its cause the node's `code` and `message`; and
507
- `settle-deadline-passed` for a settle whose deadline passed before its node reads or one of their node calls, or
508
- whose wait for the chain ended before its claim or its submission, with `before`, the step it did not start
509
- (`node reads` or `claim`, and on Polkadot, once the extrinsic is decoded, `finalized head` or `validation`) or the
510
- call it did not send, named as `node-call-failed` names it, and `settleWaitMs`. A read made while following the
511
- chain (a Tron status read, a Polkadot head or block read) that the wait for the chain leaves no time for is not
512
- sent and writes no entry: the answer is the one the wait's end gives.
513
- A request refused for its own bytes (a body that is not JSON, a signature
514
- that recovers no key, an extrinsic that does not decode) is answered to its client and not logged, and a client that
515
- leaves before its request body is complete writes no entry: the connection is destroyed.
516
- `@polkadot/api`, which loads each Polkadot network's metadata, also writes its own lines (not JSON) on standard error
517
- when that load fails; the facilitator's entry for it is `node-call-failed` with `call: metadata`.
518
-
519
- ## Security model and guarantees
520
-
521
- - **No key, no fee.** The facilitator signs nothing. It submits exactly the bytes the payer signed, and the payer pays
522
- every fee, as both profiles require.
523
- - **Settled once.** Settlements are deduplicated by transaction id or extrinsic hash, atomically, for as long as the
524
- answer is not final, and for at least 24 hours after the validity window ends. A payment is answered success once,
525
- across every process that shares the store, to the `/settle` whose write stores it, on Tron and on Polkadot. On
526
- Tron, a transaction id the node already holds is refused.
527
- - **Success only from the chain.** `success: true` is given only when a node shows the transaction in a block with
528
- the facilitator's success conditions: on Tron, receipt result `SUCCESS`, which the profile requires, and a `Transfer`
529
- log from the token. A success read at the head, above the solidified or finalized block, can be reorganised out of
530
- the chain.
531
- - **What it does not check.** It checks that the payment carries H in the profile's form, not which H the seller issued.
532
- Its store claims a payment's id once, so the payment is submitted once. On Tron and on Polkadot, a success is answered
533
- only by the settle whose write stored it, and a repeated `/settle` of that payment answers `invalid_transaction_state`
534
- with the transaction: on Tron from the stored answer or, once the row is gone, from the FullNode's blocks; on Polkadot
535
- while the facilitator keeps the payment's row (until 24 hours after its validity window). Each profile's rule 6 puts
536
- the remaining checks on the resource server: it accepts a payment only when the payment's H is one it issued for that
537
- request and has not seen claimed. The seller door's `claim` makes both checks. It answers `404 claim/unknown` for an H
538
- it holds no record of, `409 claim/not-this-request` for a payment of another request, and `409 claim/in-progress` or
539
- `409 claim/paid` once the ATR's payment has been claimed. The facilitator checks the amount, asset and payee against
540
- the requirements it is given because x402 requires that of a facilitator, and carries no business or legal logic
541
- beyond that.
542
-
543
- ## Test vectors and conformance
544
-
545
- The tests check each profile's rule 5 against local node stubs, with the transactions of `@integraledger/lcp`'s
546
- shared vectors. The Tron stubs answer with Tron mainnet's recorded answers (`test/fixtures/tron-mainnet-answers.json`),
547
- and the Polkadot stub with Polkadot Asset Hub's recorded runtime metadata
548
- (`test/fixtures/polkadot-asset-hub-2005000.json.gz`); the Tron account, block and transaction reads follow
549
- java-tron's HTTP answers and its signature and TaPoS checks. They cover two concurrent settles of one payment (one
550
- submission), repeated settles while the node is down, a settle that finds its id claimed and unanswered, the end of
551
- each validity window (Tron's expiration and Polkadot's mortal era, capped by `System.BlockHashCount`), and a
552
- Polkadot remark that spells H with upper-case digits, refused before the node is asked. On Tron they also cover the
553
- owner's permission, TaPoS, a transaction id the node (in a block or its pending pool) or the store already holds,
554
- before and after the expiration and after the sweep has dropped the payment's row, a consumed payment, and a `SUCCESS`
555
- receipt with and without the token's `Transfer` log, including the live USDT-TRC20 receipt whose `transfer` returned
556
- false. On Polkadot they also cover a repeat of a consumed payment, a block answer over 4 MiB and one over the
557
- `System.BlockLength` bound, and a block the node cannot give, before and after the era's end. They need
558
- `INTEGRA_DATABASE_URL` set to a Postgres database.
559
-
560
- ## Requirements
561
-
562
- - Node.js `>=24`.
563
- - Postgres; the tests run on Postgres 18.
564
- - For Tron, a FullNode and a Solidity node with java-tron's HTTP API: the FullNode serves `/wallet/getaccount`,
565
- `/wallet/getnowblock`, `/wallet/getblock`, `/wallet/gettransactionbyid`, `/wallet/gettransactionfrompending`,
566
- `/wallet/triggerconstantcontract`, `/wallet/broadcasthex` and `/wallet/gettransactioninfobyid`. The FullNode keeps
567
- the block history, not a lite FullNode: `/wallet/gettransactionbyid` finds a transaction only in the blocks the node
568
- holds, and it answers a repeated `/settle` of a payment whose row is gone.
569
- - For Polkadot, an Asset Hub RPC node that serves JSON-RPC over HTTP. A node that keeps the state of every block (an
570
- archive node) gives the events of any block; a pruning node discards the state of older blocks, and a block that
571
- holds the extrinsic and whose state is discarded keeps the answer `settlement_pending`.
817
+ - `instrument` is the record: `key` is the instrument, its kind and parts as a JSON array. `held_until` is when the
818
+ settle holding the claim may no longer send (0 once it answered); `answer` is the answer as first given, once
819
+ `final`; `transaction` the transaction the row names; `sent` every transaction the settler's submissions for the
820
+ claim named, any of which can be the one that lands; `body` the SHA-256 of the body that claimed the row, the only
821
+ body sent again; `search` where the next read resumes; `since` the chain's position read just before the claim; times
822
+ are Unix milliseconds.
823
+ - `fee` is the fee count: one row per transaction a keyed module submitted on a network with a budget.
824
+ - `module_state` is the modules' durable state, under each module's name: a class's pending settlements, Cardano's
825
+ broadcast guard, Solana's channels.
826
+ - A sweep every minute drops the final rows kept 24 hours past their keep, and the fees older than the longest budget
827
+ period. The pool holds at most 10 connections; acquiring one, each query and each statement are bounded by 5 seconds.
828
+
829
+ ## Bounds and logs
830
+
831
+ - Each node call the settler makes itself has a timeout of at most 5 seconds and an answer of at most 4 MiB, except
832
+ Polkadot's block reads, bounded by the runtime's `System.BlockLength` (at most 4 of them at once in a process). A
833
+ published class's calls are bounded by the class, and its settle takes no deadline: `settleWaitMs` bounds the
834
+ settler's own reads and store calls, and a class's settle runs on its own bounds. x402's EVM signer waits up to
835
+ 180 s for a receipt unless `toFacilitatorEvmSigner`'s `confirmationTimeoutMs` is set: set it below `settleWaitMs`,
836
+ as the service above does, or a `/settle` can outlast its wait.
837
+ - `/settle`'s reads and submission end a second before `settleWaitMs` (a quarter of a shorter wait), the time kept for
838
+ storing the answer. The server's request timeout is `settleWaitMs` plus 60 seconds.
839
+ - An error names a node by its origin alone, since a URL's path or query can hold an API key.
840
+ - The operator log (`operatorLog`; by default one JSON line on standard error) receives what the operator should see
841
+ and the answer does not carry, each entry with `network`, `payer` and `transaction` where they are known, and the
842
+ error that caused it as `cause`. The answer to the client is the same either way and carries nothing from the cause.
843
+ A log that throws, or returns a promise that rejects, changes no answer: the entry is written by the default, with an
844
+ `operator-log-failed` entry. The core's entries are `verify-error`, `settle-error` and `request-error` (an error the
845
+ handling threw); `read-failed` and `position-unread` (lcp's read, or the position before a claim, could not be made);
846
+ `store-call-failed` (with the `call`), `store-connection-error` and `answer-not-stored`; `settle-deadline-passed`
847
+ (with `before`, the step not started); `claim-unread` (a held claim whose read told nothing); `success-not-stored`;
848
+ and `fee-not-counted`. Each module adds its own, such as `node-call-failed` and `settlement-failed`. Every
849
+ `unexpected_verify_error` and `unexpected_settle_error` has an entry that names why, written when it is first given.
850
+
851
+ ## Versions
852
+
853
+ 0.5.1 takes `@integraledger/lcp` `~0.6.3` as its peer dependency: install `@integraledger/lcp@~0.6.3` beside it. A
854
+ later lcp minor release needs a settler release that names it. While both packages are 0.x, a minor release may change
855
+ the configuration, the answers or the storage; [the CHANGELOG](./CHANGELOG.md) lists what each release changes. It
856
+ needs Node.js 24.22.1 or later.
857
+
858
+ ### Upgrading from 0.4.0
859
+
860
+ 0.4.0 served the `tron` and `polkadot` modules alone. 0.5.0 takes `listen`, `store`, `settleWaitMs`, `operatorLog`,
861
+ `tron` and `polkadot` unchanged, and needs `@integraledger/lcp` `~0.6.0` (0.4.0 took `~0.5.0`) and Node.js 24.22.1.
862
+
863
+ 0.4.0 kept its record in the table `settlement`. 0.5.0 creates `instrument`, `fee` and `module_state` beside it, never
864
+ reads or writes `settlement`, and does not fill `instrument` from it, so it does not know the payments 0.4.0 answered.
865
+ A repeated `/settle` of one of them is judged afresh, by the module's checks and lcp's read of the chain:
866
+
867
+ - **A payment 0.4.0 answered success is never answered success again.** On Tron, the module's checks refuse a
868
+ transaction id the node holds in its blocks or pending pool, and an expiration already passed; on Polkadot, the node
869
+ no longer answers the extrinsic valid once its nonce is used. The answer is `invalid_transaction_state` naming the
870
+ transaction, stored, where lcp's read shows the payment final, and otherwise the check's refusal, with nothing stored.
871
+ - **A payment 0.4.0 answered `settlement_pending` is answered the same way once its transaction is in a block, and so
872
+ is never answered success by 0.5.0, though it landed.** The one exception is a Polkadot extrinsic still in the
873
+ node's pool, not yet in a block, when the repeat arrives: it passes the checks, 0.5.0 claims it, the node refuses
874
+ its submission as already seen, and 0.5.0 answers success once lcp's read shows it final.
875
+ - **A payment 0.4.0 claimed and never sent** is new to 0.5.0, which settles it.
876
+
877
+ Neither rail lets one signed payment land twice: a Tron transaction id and a Polkadot account nonce are each used once.
878
+ Before you switch, call `/settle` on 0.4.0 again for each payment it left pending, until each has a final answer (its
879
+ rows in `settlement` whose `answer` is null or whose `answer->>'errorReason'` is `settlement_pending`), or read those
880
+ payments with lcp's `status` after the switch. Do not run 0.4.0 and 0.5.0 at once for the same payments: each keeps its
881
+ own record, so each can submit a payment and answer it success. `settlement` can be dropped once no payment it holds
882
+ can still land.
883
+
884
+ ## Tests (in a clone of this repository)
885
+
886
+ The package ships no tests: they run in a clone of [the repository](https://github.com/IntegraLedger/integra-protocol).
887
+ They feed lcp's vectors for each module's pairings through the settler's `/verify` and `/settle`, against local node
888
+ stubs that replay recorded node answers (`test/fixtures/tron-mainnet-answers.json`, Polkadot Asset Hub's runtime
889
+ metadata in `test/fixtures/polkadot-asset-hub-2005000.json.gz`) or answers derived from the pairing's profile. They
890
+ need Postgres: set `INTEGRA_DATABASE_URL` to a connection string whose user may create databases. Each test file makes
891
+ and drops its own database, so test runs share one server. CI runs them against a Postgres 18 service.
892
+
893
+ ```sh
894
+ INTEGRA_DATABASE_URL=postgres://postgres@127.0.0.1:5432/postgres pnpm --filter @integraledger/profile-facilitator test
895
+ ```
572
896
 
573
897
  ## Contributing
574
898
 
575
- See the [repository's README](https://github.com/IntegraLedger/integra-agentic-connectors#readme) and
576
- [CONTRIBUTING.md](https://github.com/IntegraLedger/integra-agentic-connectors/blob/main/CONTRIBUTING.md).
899
+ See the [repository's README](https://github.com/IntegraLedger/integra-protocol#readme) and
900
+ [CONTRIBUTING.md](https://github.com/IntegraLedger/integra-protocol/blob/main/CONTRIBUTING.md). The settler's
901
+ documentation is also at [lcp.integraledger.com](https://lcp.integraledger.com/guides/settler).
577
902
 
578
903
  ## License
579
904