@integraledger/profile-facilitator 0.1.0 → 0.3.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/README.md CHANGED
@@ -12,25 +12,26 @@ In x402, a **facilitator** is the role that verifies a payment and settles it on
12
12
  facilitator API: `GET /supported`, `POST /verify` and `POST /settle`. x402 specifies neither Tron nor Polkadot. The
13
13
  Legal Context Protocol (LCP) defines one transfer method on each, in which the payer's own signed transaction carries
14
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.
15
+ Approving that transaction is then the buyer's acceptance of that exact record, and the proof is on chain.
16
16
 
17
17
  | Profile | `network` | `extra.assetTransferMethod` | Where H rides |
18
18
  |---|---|---|---|
19
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`. |
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
21
 
22
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).
23
+ `@integraledger/lcp`, in [its repository at 0.4.0](https://github.com/IntegraLedger/integra-protocol/tree/v0.4.0/lcp/profiles), the release this package pins.
24
24
 
25
25
  The facilitator is a pass-through. It checks the payment against the requirements it is given, asks a node to
26
26
  validate or simulate it, submits exactly the bytes the payer signed, deduplicates, and reports what the network shows.
27
27
 
28
28
  ## Key concepts
29
29
 
30
- - **Agentic Transaction Record (ATR):** the agreement's record, a JSON document the seller serves.
30
+ - **Agentic Transaction Record (ATR):** the agreement's record, the exact bytes the seller serves.
31
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.
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.
34
35
  - **Pairing:** a payment protocol, scheme and rail combination. This facilitator serves two:
35
36
  `x402/exact/tron/lcp-trc20-memo` and `x402/exact/polkadot/lcp-assets-remark`.
36
37
  - **Binding:** how H rides in a pairing's payment: here, the Tron memo and the Polkadot remark.
@@ -45,7 +46,7 @@ sequenceDiagram
45
46
  participant P as Postgres
46
47
  participant N as Network node
47
48
  R->>F: POST /verify
48
- F->>N: simulate (Tron) or validate (Polkadot)
49
+ F->>N: read the permission, reference block and id, and simulate (Tron), or validate (Polkadot)
49
50
  F-->>R: isValid, payer
50
51
  R->>F: POST /settle
51
52
  F->>P: read, then claim the transaction id
@@ -60,11 +61,15 @@ sequenceDiagram
60
61
  ## Install
61
62
 
62
63
  ```sh
63
- npm install @integraledger/profile-facilitator
64
+ npm install @integraledger/profile-facilitator @integraledger/lcp@~0.4.0
64
65
  ```
65
66
 
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.
67
+ It needs Node.js `>=26.11.1`, 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.4.0`) is its peer dependency: install
72
+ it beside it.
68
73
 
69
74
  ## Quickstart
70
75
 
@@ -160,6 +165,7 @@ open connections, disconnects from the Polkadot nodes and closes the Postgres po
160
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`. |
161
166
  | `store` | `{ url }` | The Postgres connection string. Postgres holds the deduplication table only. |
162
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). |
163
169
 
164
170
  The facilitator serves only the networks it is configured with. A request for any other network is answered
165
171
  `invalid_network`. At start it creates its table if it does not exist; a Polkadot node's runtime metadata is loaded on
@@ -221,25 +227,67 @@ In order; the first failure is the answer.
221
227
  3. `asset` and `payTo` are Tron addresses, else `invalid_payment_requirements`.
222
228
  4. The contract called is `asset`, and the call data is exactly `transfer(payTo, amount)`, else `invalid_payload`.
223
229
  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`.
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`.
228
249
 
229
250
  The answer is `{isValid: true, payer}`, with `payer` the owner in base58check.
230
251
 
231
252
  ### What `/settle` does on Tron
232
253
 
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.
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.
243
291
 
244
292
  Success is `{success: true, transaction, network, payer}`, where `transaction` is the transaction id in hex.
245
293
 
@@ -249,7 +297,9 @@ Success is `{success: true, transaction, network, payer}`, where `transaction` i
249
297
  `invalid_payment_requirements`.
250
298
  2. `payload.extrinsic` and `payload.call` are lowercase hex; the call is exactly
251
299
  `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`.
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.
253
303
  3. With the network's runtime metadata, the extrinsic decodes as a signed v4 extrinsic whose call is `payload.call`
254
304
  byte for byte, with a mortal era, else `invalid_payload`. The node must serve the chain the network names (its
255
305
  genesis hash), else `unexpected_verify_error`.
@@ -259,17 +309,47 @@ The answer is `{isValid: true, payer}`, with `payer` the signer in SS58.
259
309
 
260
310
  ### What `/settle` does on Polkadot
261
311
 
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.
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.
273
353
 
274
354
  Success is `{success: true, transaction, network, payer}`, where `transaction` is `<block hash>-<extrinsic index>`.
275
355
  While the extrinsic is broadcast but not yet in a block, the answer is `settlement_pending` with `transaction` set to
@@ -277,11 +357,26 @@ the extrinsic's hash.
277
357
 
278
358
  ### Pending and repeated settles
279
359
 
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.
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.
285
380
 
286
381
  ## API reference
287
382
 
@@ -291,16 +386,14 @@ The package's entry point exports:
291
386
  |---|---|---|
292
387
  | `serveProfileFacilitator(config)` | `(c: ProfileFacilitatorConfig) => Promise<{ close(): Promise<void> }>` | Opens the store, starts the HTTP server and resolves once it listens. |
293
388
  | `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
389
 
297
390
  ### HTTP API
298
391
 
299
392
  | Request | Answer |
300
393
  |---|---|
301
394
  | `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. |
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. |
304
397
  | A body over 64 KiB | `413`, and the connection is closed. |
305
398
  | Another method on a served path | `405` `{error}`. |
306
399
  | Any other path | `404` `{error}`. |
@@ -317,15 +410,16 @@ controls, to the resource servers that use it.
317
410
  | `invalid_network` | yes | yes | The network is not one this facilitator is configured with. |
318
411
  | `invalid_payment_requirements` | yes | yes | The requirements are not ones the profile admits. |
319
412
  | `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. |
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). |
326
419
 
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.
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.
329
423
 
330
424
  ### Storage
331
425
 
@@ -338,57 +432,143 @@ CREATE TABLE IF NOT EXISTS settlement (
338
432
  answer jsonb,
339
433
  until timestamptz NOT NULL,
340
434
  since bigint,
435
+ unread bigint[] NOT NULL DEFAULT '{}',
341
436
  PRIMARY KEY (network, id)
342
- )
437
+ );
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'
343
440
  ```
344
441
 
345
442
  - One row per settled payment, keyed by network and transaction id (Tron) or extrinsic hash (Polkadot).
346
443
  - `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.
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.
352
468
  - The pool holds at most 10 connections. Acquiring a connection, each query and each statement are bounded by 5
353
469
  seconds.
354
470
 
355
471
  ### Bounds and logs
356
472
 
357
- - Each node call has a timeout of at most 5 seconds and an answer of at most 4 MiB.
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.
358
488
  - 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`.
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`.
362
518
 
363
519
  ## Security model and guarantees
364
520
 
365
521
  - **No key, no fee.** The facilitator signs nothing. It submits exactly the bytes the payer signed, and the payer pays
366
522
  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.
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.
369
527
  - **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.
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.
375
542
 
376
543
  ## Test vectors and conformance
377
544
 
378
545
  The tests check each profile's rule 5 against local node stubs, with the transactions of `@integraledger/lcp`'s
379
546
  shared vectors. The Tron stubs answer with Tron mainnet's recorded answers (`test/fixtures/tron-mainnet-answers.json`),
380
547
  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
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
384
558
  `INTEGRA_DATABASE_URL` set to a Postgres database.
385
559
 
386
560
  ## Requirements
387
561
 
388
- - Node.js `>=26.10.0`.
562
+ - Node.js `>=26.11.1`.
389
563
  - 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.
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`.
392
572
 
393
573
  ## Contributing
394
574
 
package/dist/answers.d.ts CHANGED
@@ -19,11 +19,12 @@ export interface FacilitatorRequest {
19
19
  };
20
20
  }
21
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.
22
+ * The reasons a payment is refused. The x402 codes are the x402 specification's (§9); `invalid_transaction_state` in
23
+ * a verify answer is a Tron transaction id the node or the store already holds. `unsupported_permission` and
24
+ * `invalid_transaction` are this facilitator's: a Tron owner permission that does not accept the transaction's one
25
+ * signature, and a transaction the node refuses in simulation or validation.
25
26
  */
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 InvalidReason = "invalid_x402_version" | "unsupported_scheme" | "invalid_network" | "invalid_payment_requirements" | "invalid_payload" | "unsupported_permission" | "invalid_transaction" | "invalid_transaction_state" | "unexpected_verify_error";
27
28
  export type VerifyAnswer = {
28
29
  isValid: true;
29
30
  payer: string;
@@ -48,8 +49,29 @@ export declare function invalid(invalidReason: InvalidReason, payer?: string): V
48
49
  export declare function pending(transaction: string, network: string): SettleAnswer;
49
50
  export declare function failed(errorReason: string, transaction: string, network: string): SettleAnswer;
50
51
  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;
52
+ /**
53
+ * An entry for the operator: what the facilitator saw that the answer does not carry. `network`, `payer` and
54
+ * `transaction` name the payment it concerns, each where it is known.
55
+ */
56
+ export interface OperatorEntry {
57
+ event: string;
58
+ network?: string;
59
+ payer?: string;
60
+ transaction?: string;
61
+ [field: string]: unknown;
62
+ }
63
+ /** Receives each operator entry, with the error that caused it when there is one. */
64
+ export type OperatorLog = (entry: OperatorEntry, cause?: unknown) => void;
65
+ /**
66
+ * The default operator log: one JSON line per entry on standard error. An entry with a cause carries it as `cause`:
67
+ * the error's name, message and stack, and its own `cause` chain.
68
+ */
69
+ export declare function operatorLine(entry: OperatorEntry, cause?: unknown): void;
70
+ /**
71
+ * `log` as the facilitator calls it: what it throws, or a promise it returns that rejects, never reaches an answer.
72
+ * The entry is then written by `operatorLine`, with an `operator-log-failed` entry whose cause is what `log` threw.
73
+ */
74
+ export declare function guarded(log: OperatorLog): OperatorLog;
53
75
  export declare function isObject(v: unknown): v is Record<string, unknown>;
54
76
  /**
55
77
  * The shared shape checks of a request: the versions, the scheme, and the objects the rails read. Returns the typed
package/dist/answers.js CHANGED
@@ -12,9 +12,49 @@ export function failed(errorReason, transaction, network) {
12
12
  export function isPending(a) {
13
13
  return !a.success && a.errorReason === "settlement_pending";
14
14
  }
15
- /** One JSON line on standard error, for the operator: what the node reported that the answer does not carry. */
16
- export function operatorLog(entry) {
17
- process.stderr.write(`${JSON.stringify(entry)}\n`);
15
+ /** An error as a JSON value: its name, message and stack, and its `cause` the same way, at most 8 deep. */
16
+ function described(e, depth = 0) {
17
+ if (!(e instanceof Error))
18
+ return { message: String(e) };
19
+ const out = { name: e.name, message: e.message, stack: e.stack };
20
+ if (e.cause !== undefined && depth < 8)
21
+ out["cause"] = described(e.cause, depth + 1);
22
+ return out;
23
+ }
24
+ /**
25
+ * The default operator log: one JSON line per entry on standard error. An entry with a cause carries it as `cause`:
26
+ * the error's name, message and stack, and its own `cause` chain.
27
+ */
28
+ export function operatorLine(entry, cause) {
29
+ const line = cause === undefined ? entry : { ...entry, cause: described(cause) };
30
+ process.stderr.write(`${JSON.stringify(line)}\n`);
31
+ }
32
+ /**
33
+ * `log` as the facilitator calls it: what it throws, or a promise it returns that rejects, never reaches an answer.
34
+ * The entry is then written by `operatorLine`, with an `operator-log-failed` entry whose cause is what `log` threw.
35
+ */
36
+ export function guarded(log) {
37
+ if (log === operatorLine)
38
+ return log;
39
+ return (entry, cause) => {
40
+ const fallBack = (e) => {
41
+ operatorLine(entry, cause);
42
+ const failure = { event: "operator-log-failed" };
43
+ for (const field of ["network", "payer", "transaction"]) {
44
+ if (entry[field] !== undefined)
45
+ failure[field] = entry[field];
46
+ }
47
+ operatorLine(failure, e);
48
+ };
49
+ try {
50
+ const returned = log(entry, cause);
51
+ if (returned instanceof Promise)
52
+ returned.catch(fallBack);
53
+ }
54
+ catch (e) {
55
+ fallBack(e);
56
+ }
57
+ };
18
58
  }
19
59
  export function isObject(v) {
20
60
  return typeof v === "object" && v !== null && !Array.isArray(v);