@integraledger/profile-facilitator 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,400 @@
1
+ # @integraledger/profile-facilitator
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.
6
+
7
+ **Documentation:** [connectors.integraledger.com/guides/facilitator](https://connectors.integraledger.com/guides/facilitator)
8
+
9
+ ## What it is
10
+
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
+ Paying is then agreeing to that exact record, and the proof is on chain.
16
+
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 `lcp:sha256:` followed by H, 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 [integra-protocol](https://github.com/IntegraLedger/integra-protocol).
24
+
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.
27
+
28
+ ## Key concepts
29
+
30
+ - **Agentic Transaction Record (ATR):** the agreement's record, a JSON document 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: the payment carries H, so paying is agreeing
33
+ to that exact record.
34
+ - **Pairing:** a payment protocol, scheme and rail combination. This facilitator serves two:
35
+ `x402/exact/tron/lcp-trc20-memo` and `x402/exact/polkadot/lcp-assets-remark`.
36
+ - **Binding:** how H rides in a pairing's payment: here, the Tron memo and the Polkadot remark.
37
+ - **Seller:** the party serving the resource. It calls this facilitator from its x402 resource server.
38
+ - **Facilitator:** the x402 role that verifies and settles.
39
+ - **Deduplication:** each payment is settled at most once, keyed by its network and transaction id, in Postgres.
40
+
41
+ ```mermaid
42
+ sequenceDiagram
43
+ participant R as Resource server (seller)
44
+ participant F as Profile facilitator
45
+ participant P as Postgres
46
+ participant N as Network node
47
+ R->>F: POST /verify
48
+ F->>N: simulate (Tron) or validate (Polkadot)
49
+ F-->>R: isValid, payer
50
+ R->>F: POST /settle
51
+ F->>P: read, then claim the transaction id
52
+ F->>N: broadcast or submit the signed bytes
53
+ loop every second until included or the wait ends
54
+ F->>N: read the receipt or the blocks
55
+ end
56
+ F->>P: store the answer
57
+ F-->>R: success, transaction, payer
58
+ ```
59
+
60
+ ## Install
61
+
62
+ ```sh
63
+ npm install @integraledger/profile-facilitator
64
+ ```
65
+
66
+ It needs Node.js `>=26.10.0`, Postgres (the tests run on Postgres 18), and an HTTP endpoint for each network you
67
+ serve: a Tron FullNode and Solidity node, or a Polkadot Asset Hub RPC node. It is ESM only.
68
+
69
+ ## Quickstart
70
+
71
+ Start the facilitator for Tron mainnet and read what it supports. The node URLs below are java-tron's default HTTP
72
+ ports on your own node; the facilitator calls them only when a payment arrives. `DATABASE_URL` is your Postgres
73
+ connection string.
74
+
75
+ ```ts title="supported.ts"
76
+ import { serveProfileFacilitator } from "@integraledger/profile-facilitator";
77
+
78
+ const facilitator = await serveProfileFacilitator({
79
+ listen: "127.0.0.1:4020",
80
+ tron: [{ network: "tron:728126428", fullNode: "http://127.0.0.1:8090", solidityNode: "http://127.0.0.1:8091" }],
81
+ polkadot: [{ network: "polkadot:68d56f15f85d3136970ec16946040bc1", rpc: "http://127.0.0.1:9944" }],
82
+ store: { url: process.env.DATABASE_URL ?? "postgres://postgres@127.0.0.1:5432/postgres" },
83
+ settleWaitMs: 30_000,
84
+ });
85
+
86
+ const supported = await (await fetch("http://127.0.0.1:4020/supported")).json();
87
+ console.log(JSON.stringify(supported, null, 2));
88
+ await facilitator.close();
89
+ ```
90
+
91
+ ```text output
92
+ {
93
+ "kinds": [
94
+ {
95
+ "x402Version": 2,
96
+ "scheme": "exact",
97
+ "network": "tron:728126428",
98
+ "extra": {
99
+ "assetTransferMethod": "lcp-trc20-memo"
100
+ }
101
+ },
102
+ {
103
+ "x402Version": 2,
104
+ "scheme": "exact",
105
+ "network": "polkadot:68d56f15f85d3136970ec16946040bc1",
106
+ "extra": {
107
+ "assetTransferMethod": "lcp-assets-remark"
108
+ }
109
+ }
110
+ ],
111
+ "extensions": [],
112
+ "signers": {}
113
+ }
114
+ ```
115
+
116
+ ## Run it
117
+
118
+ The package exports one function that starts the server; it has no command-line entry. A service is a short module
119
+ that reads its configuration and stops cleanly on a signal:
120
+
121
+ ```ts title="facilitator.ts" server
122
+ import { serveProfileFacilitator } from "@integraledger/profile-facilitator";
123
+
124
+ const listen = process.env.LISTEN ?? "127.0.0.1:4021";
125
+ const facilitator = await serveProfileFacilitator({
126
+ listen,
127
+ tron: [
128
+ {
129
+ network: "tron:728126428",
130
+ fullNode: process.env.TRON_FULL_NODE ?? "http://127.0.0.1:8090",
131
+ solidityNode: process.env.TRON_SOLIDITY_NODE ?? "http://127.0.0.1:8091",
132
+ },
133
+ ],
134
+ store: { url: process.env.DATABASE_URL ?? "postgres://postgres@127.0.0.1:5432/postgres" },
135
+ settleWaitMs: Number(process.env.SETTLE_WAIT_MS ?? 30_000),
136
+ });
137
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
138
+ process.once(signal, () => {
139
+ void facilitator.close().then(() => process.exit(0));
140
+ });
141
+ }
142
+ console.log(`facilitator listening on ${listen}`);
143
+ ```
144
+
145
+ ```text output
146
+ facilitator listening on 127.0.0.1:4021
147
+ ```
148
+
149
+ Run it with `node facilitator.ts`: Node.js 26 runs TypeScript directly. `close()` stops accepting requests, closes
150
+ open connections, disconnects from the Polkadot nodes and closes the Postgres pool.
151
+
152
+ ### Configuration
153
+
154
+ `serveProfileFacilitator(config)` takes a `ProfileFacilitatorConfig`:
155
+
156
+ | Field | Type | Meaning |
157
+ |---|---|---|
158
+ | `listen` | `string` | `"host:port"`; an IPv6 host may be written in brackets. |
159
+ | `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. |
160
+ | `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`. |
161
+ | `store` | `{ url }` | The Postgres connection string. Postgres holds the deduplication table only. |
162
+ | `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. |
163
+
164
+ The facilitator serves only the networks it is configured with. A request for any other network is answered
165
+ `invalid_network`. At start it creates its table if it does not exist; a Polkadot node's runtime metadata is loaded on
166
+ the first payment for that network, and loaded again whenever the node's runtime version changes.
167
+
168
+ ## Verify and settle
169
+
170
+ Both `POST /verify` and `POST /settle` take the x402 facilitator request:
171
+ `{x402Version: 2, paymentPayload, paymentRequirements}`, with `paymentPayload.x402Version` 2 and
172
+ `paymentRequirements.scheme` `"exact"`.
173
+
174
+ ```ts title="verify.ts"
175
+ import { serveProfileFacilitator } from "@integraledger/profile-facilitator";
176
+
177
+ const facilitator = await serveProfileFacilitator({
178
+ listen: "127.0.0.1:4022",
179
+ tron: [{ network: "tron:728126428", fullNode: "http://127.0.0.1:8090", solidityNode: "http://127.0.0.1:8091" }],
180
+ store: { url: process.env.DATABASE_URL ?? "postgres://postgres@127.0.0.1:5432/postgres" },
181
+ settleWaitMs: 30_000,
182
+ });
183
+
184
+ const request = {
185
+ x402Version: 2,
186
+ paymentPayload: { x402Version: 2, payload: { transaction: "0a02" } },
187
+ paymentRequirements: {
188
+ scheme: "exact",
189
+ network: "tron:3448148188",
190
+ amount: "10000",
191
+ asset: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
192
+ payTo: "TCwX1UeSkVfu43HD5xNMmFqDR2Xgjdxihx",
193
+ maxTimeoutSeconds: 60,
194
+ extra: { assetTransferMethod: "lcp-trc20-memo" },
195
+ },
196
+ };
197
+ for (const path of ["/verify", "/settle"]) {
198
+ const res = await fetch(`http://127.0.0.1:4022${path}`, {
199
+ method: "POST",
200
+ headers: { "content-type": "application/json" },
201
+ body: JSON.stringify(request),
202
+ });
203
+ console.log(path, res.status, JSON.stringify(await res.json()));
204
+ }
205
+ await facilitator.close();
206
+ ```
207
+
208
+ ```text output
209
+ /verify 200 {"isValid":false,"invalidReason":"invalid_network"}
210
+ /settle 200 {"success":false,"errorReason":"invalid_network","transaction":"","network":"tron:3448148188"}
211
+ ```
212
+
213
+ ### What `/verify` checks on Tron
214
+
215
+ In order; the first failure is the answer.
216
+
217
+ 1. The network is configured, and the requirements are ones the profile admits (its rule 1), else
218
+ `invalid_network` or `invalid_payment_requirements`.
219
+ 2. `payload.transaction` is a serialized Tron `Transaction` in hex that decodes to exactly one
220
+ `TriggerSmartContract` whose `data` is an LCP `sha256` string, else `invalid_payload`.
221
+ 3. `asset` and `payTo` are Tron addresses, else `invalid_payment_requirements`.
222
+ 4. The contract called is `asset`, and the call data is exactly `transfer(payTo, amount)`, else `invalid_payload`.
223
+ 5. The transaction carries exactly one signature, else `unsupported_permission`. That signature recovers to the
224
+ transaction's owner, else `invalid_payload`. A multi-signature owner permission is not served.
225
+ 6. `expiration` is in the future and no later than now plus `maxTimeoutSeconds`, else `invalid_payload`.
226
+ 7. The FullNode's `/wallet/triggerconstantcontract` simulates the transfer without failure, else
227
+ `invalid_transaction`. A node that does not answer gives `unexpected_verify_error`.
228
+
229
+ The answer is `{isValid: true, payer}`, with `payer` the owner in base58check.
230
+
231
+ ### What `/settle` does on Tron
232
+
233
+ 1. Repeats every check of `/verify`.
234
+ 2. Reads the stored answer for the transaction id. A final one is returned as it is, so a repeated `/settle` gets the
235
+ first answer.
236
+ 3. Claims the transaction id with one conditional insert, so concurrent settles of one payment broadcast once.
237
+ 4. Broadcasts the signed bytes with `/wallet/broadcasthex`. A `DUP_TRANSACTION_ERROR` counts as broadcast.
238
+ 5. Reads the receipt with `gettransactioninfobyid` every second. `SUCCESS` at the FullNode is success. Any other
239
+ result is a failure only once the Solidity node, which serves solidified blocks alone, shows it. A transaction
240
+ whose expiration has passed and that no node shows once the solidified head is two slots past it can never be
241
+ included, and is answered `invalid_transaction_state`.
242
+ 6. Stores the answer and returns it.
243
+
244
+ Success is `{success: true, transaction, network, payer}`, where `transaction` is the transaction id in hex.
245
+
246
+ ### What `/verify` checks on Polkadot
247
+
248
+ 1. The network is configured, and the requirements are ones the profile admits, else `invalid_network` or
249
+ `invalid_payment_requirements`.
250
+ 2. `payload.extrinsic` and `payload.call` are lowercase hex; the call is exactly
251
+ `utility.batch_all([assets.transfer_keep_alive(asset, Id(payTo), amount), system.remark_with_event(R)])` for this
252
+ `asset`, `payTo` and `amount`, and R carries an LCP `sha256` string, else `invalid_payload`.
253
+ 3. With the network's runtime metadata, the extrinsic decodes as a signed v4 extrinsic whose call is `payload.call`
254
+ byte for byte, with a mortal era, else `invalid_payload`. The node must serve the chain the network names (its
255
+ genesis hash), else `unexpected_verify_error`.
256
+ 4. `TaggedTransactionQueue_validate_transaction` at the best block returns `Ok`, else `invalid_transaction`.
257
+
258
+ The answer is `{isValid: true, payer}`, with `payer` the signer in SS58.
259
+
260
+ ### What `/settle` does on Polkadot
261
+
262
+ 1. Repeats every check of `/verify`.
263
+ 2. Reads the stored answer for the extrinsic's BLAKE2b-256 hash, and returns a final one as it is.
264
+ 3. Claims the hash, with the first block to scan: the block after the finalized head read before validation, never
265
+ before the era's birth.
266
+ 4. Submits with `author_submitExtrinsic`. A refusal that says the node has already seen the extrinsic or its nonce is
267
+ read as possibly included, and the scan runs.
268
+ 5. Scans every second: first the finalized blocks, then the blocks up to the head. In the block that holds the
269
+ extrinsic, success needs `System.ExtrinsicSuccess`, `System.Remarked` for R's BLAKE2b-256 and `Assets.Transferred`
270
+ for `asset`. A failure counts only in a finalized block. Once every block to the era's last is finalized without
271
+ the extrinsic, it can never be included: `invalid_transaction_state`.
272
+ 6. Stores the answer and returns it.
273
+
274
+ Success is `{success: true, transaction, network, payer}`, where `transaction` is `<block hash>-<extrinsic index>`.
275
+ While the extrinsic is broadcast but not yet in a block, the answer is `settlement_pending` with `transaction` set to
276
+ the extrinsic's hash.
277
+
278
+ ### Pending and repeated settles
279
+
280
+ When the wait ends first, `/settle` answers `{success: false, errorReason: "settlement_pending", transaction}` with
281
+ the transaction id or extrinsic hash; x402 requires that `transaction` not be empty. Call `/settle` again with the
282
+ same request: it reads the chain from where it stopped, never submits twice, and returns the final answer once there
283
+ is one. An answer with an empty `transaction` means nothing was submitted. When the store cannot be read, the
284
+ facilitator cannot know whether the payment was submitted, so it answers `settlement_pending` with the id.
285
+
286
+ ## API reference
287
+
288
+ The package's entry point exports:
289
+
290
+ | Export | Kind | What it is |
291
+ |---|---|---|
292
+ | `serveProfileFacilitator(config)` | `(c: ProfileFacilitatorConfig) => Promise<{ close(): Promise<void> }>` | Opens the store, starts the HTTP server and resolves once it listens. |
293
+ | `ProfileFacilitatorConfig` | interface | The configuration above. |
294
+ | `VerifyAnswer` | type | `{isValid: true, payer}` or `{isValid: false, invalidReason, payer?}`. |
295
+ | `SettleAnswer` | type | `{success: true, transaction, network, payer}` or `{success: false, errorReason, transaction, network}`. |
296
+
297
+ ### HTTP API
298
+
299
+ | Request | Answer |
300
+ |---|---|
301
+ | `GET /supported` | `200` `{kinds, extensions: [], signers: {}}`, one kind per configured network. |
302
+ | `POST /verify` | `200` with a `VerifyAnswer`; `400` `{isValid: false, invalidReason: "invalid_payload"}` when the body is not JSON. |
303
+ | `POST /settle` | `200` with a `SettleAnswer`; `400` with `errorReason` `invalid_payload` when the body is not JSON. |
304
+ | A body over 64 KiB | `413`, and the connection is closed. |
305
+ | Another method on a served path | `405` `{error}`. |
306
+ | Any other path | `404` `{error}`. |
307
+
308
+ The facilitator has no authentication of its own. Serve it on a private interface, or behind your own network
309
+ controls, to the resource servers that use it.
310
+
311
+ ### Reasons
312
+
313
+ | Reason | `/verify` | `/settle` | Meaning |
314
+ |---|---|---|---|
315
+ | `invalid_x402_version` | yes | yes | `x402Version` is not 2 in the request or the payload. |
316
+ | `unsupported_scheme` | yes | yes | `scheme` is not `"exact"`. |
317
+ | `invalid_network` | yes | yes | The network is not one this facilitator is configured with. |
318
+ | `invalid_payment_requirements` | yes | yes | The requirements are not ones the profile admits. |
319
+ | `invalid_payload` | yes | yes | The payload does not match the profile or the requirements, or its signature or expiration fails. |
320
+ | `unsupported_permission` | yes | yes | Tron: the transaction carries more than one signature. |
321
+ | `invalid_transaction` | yes | yes | The node refuses the transaction in simulation or validation. |
322
+ | `unexpected_verify_error` | yes | no | The node could not be read. |
323
+ | `unexpected_settle_error` | no | yes | The node could not be read before submission, or refused the submission. |
324
+ | `settlement_pending` | no | yes | Submitted, and not yet final when the wait ended. |
325
+ | `invalid_transaction_state` | no | yes | Included and failed, or it can never be included. |
326
+
327
+ `unsupported_permission` and `invalid_transaction` are this facilitator's, for a multi-signature Tron owner and for
328
+ a transaction the node refuses in simulation or validation. The others are the x402 specification's.
329
+
330
+ ### Storage
331
+
332
+ Postgres holds one table, created at start:
333
+
334
+ ```sql
335
+ CREATE TABLE IF NOT EXISTS settlement (
336
+ network text NOT NULL,
337
+ id text NOT NULL,
338
+ answer jsonb,
339
+ until timestamptz NOT NULL,
340
+ since bigint,
341
+ PRIMARY KEY (network, id)
342
+ )
343
+ ```
344
+
345
+ - One row per settled payment, keyed by network and transaction id (Tron) or extrinsic hash (Polkadot).
346
+ - `answer` is null while the row is claimed and the answer is not yet written. A final answer is never replaced; a
347
+ pending one is replaced by what a later read of the chain shows.
348
+ - `until` is the end of the payment's validity window: Tron's `expiration`, or the end of the Polkadot era. A row is
349
+ kept for 24 hours after it, so a repeat in that time reads the stored answer before anything is verified again. A
350
+ sweep every minute drops older rows.
351
+ - `since` is, for Polkadot, the first block not yet shown at finality to lack the extrinsic.
352
+ - The pool holds at most 10 connections. Acquiring a connection, each query and each statement are bounded by 5
353
+ seconds.
354
+
355
+ ### Bounds and logs
356
+
357
+ - Each node call has a timeout of at most 5 seconds and an answer of at most 4 MiB.
358
+ - A request body is at most 64 KiB. The server's request timeout is `settleWaitMs` plus 60 seconds.
359
+ - The facilitator writes one JSON line on standard error for what the operator should see and the answer does not
360
+ carry: `settlement-failed` (with the events or receipt result the chain shows), `settlement-expired` and
361
+ `answer-not-stored`.
362
+
363
+ ## Security model and guarantees
364
+
365
+ - **No key, no fee.** The facilitator signs nothing. It submits exactly the bytes the payer signed, and the payer pays
366
+ every fee, as both profiles require.
367
+ - **Settled once.** Settlements are deduplicated by transaction id or extrinsic hash, atomically, until the validity
368
+ window ends and for 24 hours after.
369
+ - **Success only from the chain.** `success: true` is given only when a node shows the transaction in a block with
370
+ the profile's success conditions.
371
+ - **What it does not check.** It checks that the payment carries an LCP `sha256` string, not which H the seller
372
+ issued. The resource server refuses a payment whose H it did not issue for that request (each profile's rule 6),
373
+ for example through the seller door's `claim`. It checks the amount, asset and payee against the requirements it
374
+ is given because x402 requires that of a facilitator, and carries no business or legal logic beyond that.
375
+
376
+ ## Test vectors and conformance
377
+
378
+ The tests check each profile's rule 5 against local node stubs, with the transactions of `@integraledger/lcp`'s
379
+ shared vectors. The Tron stubs answer with Tron mainnet's recorded answers (`test/fixtures/tron-mainnet-answers.json`),
380
+ and the Polkadot stub with Polkadot Asset Hub's recorded runtime metadata
381
+ (`test/fixtures/polkadot-asset-hub-2005000.json.gz`). They cover two concurrent settles of one payment (one
382
+ submission, equal answers), repeated settles while the node is down, a settle that finds its id claimed and
383
+ unanswered, and the end of each validity window: Tron's expiration and Polkadot's mortal era. They need
384
+ `INTEGRA_DATABASE_URL` set to a Postgres database.
385
+
386
+ ## Requirements
387
+
388
+ - Node.js `>=26.10.0`.
389
+ - Postgres; the tests run on Postgres 18.
390
+ - For Tron, a FullNode and a Solidity node with java-tron's HTTP API. For Polkadot, an Asset Hub RPC node that serves
391
+ JSON-RPC over HTTP.
392
+
393
+ ## Contributing
394
+
395
+ See the [repository's README](https://github.com/IntegraLedger/integra-agentic-connectors#readme) and
396
+ [CONTRIBUTING.md](https://github.com/IntegraLedger/integra-agentic-connectors/blob/main/CONTRIBUTING.md).
397
+
398
+ ## License
399
+
400
+ [Apache-2.0](./LICENSE).
@@ -0,0 +1,58 @@
1
+ /** The x402 facilitator API's bodies, as this facilitator reads and writes them. */
2
+ /** `POST /verify` and `POST /settle` take the same body. */
3
+ export interface FacilitatorRequest {
4
+ x402Version: 2;
5
+ paymentPayload: {
6
+ x402Version: 2;
7
+ accepted?: unknown;
8
+ payload: Record<string, unknown>;
9
+ [k: string]: unknown;
10
+ };
11
+ paymentRequirements: {
12
+ scheme: string;
13
+ network: string;
14
+ amount: string;
15
+ asset: string;
16
+ payTo: string;
17
+ maxTimeoutSeconds: number;
18
+ extra?: Record<string, unknown>;
19
+ };
20
+ }
21
+ /**
22
+ * The reasons a payment is refused. The x402 codes are the x402 specification's (§9); `unsupported_permission` and
23
+ * `invalid_transaction` are this facilitator's, for a multi-signature Tron owner and for a transaction the node
24
+ * refuses in simulation or validation.
25
+ */
26
+ export type InvalidReason = "invalid_x402_version" | "unsupported_scheme" | "invalid_network" | "invalid_payment_requirements" | "invalid_payload" | "unsupported_permission" | "invalid_transaction" | "unexpected_verify_error";
27
+ export type VerifyAnswer = {
28
+ isValid: true;
29
+ payer: string;
30
+ } | {
31
+ isValid: false;
32
+ invalidReason: InvalidReason;
33
+ payer?: string;
34
+ };
35
+ export type SettleAnswer = {
36
+ success: true;
37
+ transaction: string;
38
+ network: string;
39
+ payer: string;
40
+ } | {
41
+ success: false;
42
+ errorReason: string;
43
+ transaction: string;
44
+ network: string;
45
+ };
46
+ export declare function invalid(invalidReason: InvalidReason, payer?: string): VerifyAnswer;
47
+ /** x402 requires a non-empty `transaction` on `settlement_pending`. */
48
+ export declare function pending(transaction: string, network: string): SettleAnswer;
49
+ export declare function failed(errorReason: string, transaction: string, network: string): SettleAnswer;
50
+ export declare function isPending(a: SettleAnswer): boolean;
51
+ /** One JSON line on standard error, for the operator: what the node reported that the answer does not carry. */
52
+ export declare function operatorLog(entry: Record<string, unknown>): void;
53
+ export declare function isObject(v: unknown): v is Record<string, unknown>;
54
+ /**
55
+ * The shared shape checks of a request: the versions, the scheme, and the objects the rails read. Returns the typed
56
+ * request, or the reason it is refused.
57
+ */
58
+ export declare function readRequest(body: unknown): FacilitatorRequest | InvalidReason;