@integraledger/profile-facilitator 0.1.0 → 0.2.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
@@ -17,7 +17,7 @@ Paying is then agreeing to that exact record, and the proof is on chain.
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
23
  `@integraledger/lcp`, in [integra-protocol](https://github.com/IntegraLedger/integra-protocol).
@@ -45,7 +45,7 @@ sequenceDiagram
45
45
  participant P as Postgres
46
46
  participant N as Network node
47
47
  R->>F: POST /verify
48
- F->>N: simulate (Tron) or validate (Polkadot)
48
+ F->>N: read the permission, reference block and id, and simulate (Tron), or validate (Polkadot)
49
49
  F-->>R: isValid, payer
50
50
  R->>F: POST /settle
51
51
  F->>P: read, then claim the transaction id
@@ -221,25 +221,48 @@ In order; the first failure is the answer.
221
221
  3. `asset` and `payTo` are Tron addresses, else `invalid_payment_requirements`.
222
222
  4. The contract called is `asset`, and the call data is exactly `transfer(payTo, amount)`, else `invalid_payload`.
223
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`.
224
+ transaction's owner, else `invalid_payload`.
225
+ 6. The store does not hold the transaction id, else `invalid_transaction_state`.
226
+ 7. `expiration` is in the future and no later than now plus `maxTimeoutSeconds`, else `invalid_payload`.
227
+ 8. Five reads of the FullNode, made together. The first refusal in this order is the answer, and a node that does
228
+ not answer gives `unexpected_verify_error`:
229
+ - **The owner's permission.** `/wallet/getaccount` gives the owner permission, and the weight it gives the
230
+ owner's key must be at least its threshold, else `unsupported_permission`. An account with no owner permission
231
+ set, or one the node does not hold, has the network's default: its own key, weight 1, threshold 1. So a
232
+ multi-signature owner, or an owner whose permission does not hold the address's own key, is refused here
233
+ rather than at broadcast.
234
+ - **TaPoS.** The node accepts a transaction only when `ref_block_hash` equals bytes 8–15 of the id of the latest
235
+ block whose number's bytes 6–7 are `ref_block_bytes`. The facilitator reads the head with
236
+ `/wallet/getnowblock`, then that block with `/wallet/getblock`, and makes the same comparison, else
237
+ `invalid_transaction`.
238
+ - **The id.** `/wallet/gettransactionbyid` must not find the transaction in a block, and
239
+ `/wallet/gettransactionfrompending` must not find it in the node's pending pool, else
240
+ `invalid_transaction_state`.
241
+ - **The simulation.** `/wallet/triggerconstantcontract` simulates the transfer without failure, else
242
+ `invalid_transaction`.
228
243
 
229
244
  The answer is `{isValid: true, payer}`, with `payer` the owner in base58check.
230
245
 
231
246
  ### What `/settle` does on Tron
232
247
 
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.
248
+ 1. Repeats the checks of `/verify` that read neither the store nor the node (steps 1 to 5).
249
+ 2. Reads the stored answer for the transaction id. A stored success means the payment is consumed: the answer is
250
+ `invalid_transaction_state` with the transaction id, never a second success. Any other final answer is returned
251
+ as it is. A claimed id, or a stored `settlement_pending`, goes on to step 6 and broadcasts nothing.
252
+ 3. For an id the store does not hold, repeats the expiration check and the node reads of `/verify`. An id the node
253
+ already holds is a consumed payment, answered `invalid_transaction_state` with the id.
254
+ 4. Claims the transaction id with one conditional insert, so concurrent settles of one payment broadcast once.
255
+ 5. Broadcasts the signed bytes with `/wallet/broadcasthex`. A `DUP_TRANSACTION_ERROR` counts as broadcast.
256
+ 6. Reads the transaction's status every second with `@integraledger/lcp`'s `tronStatus`: the Solidity node's
257
+ `gettransactioninfobyid` first, then the FullNode's. Success requires receipt result `SUCCESS` **and** a
258
+ `Transfer` log emitted by `asset`. The value the call returned is not read: a TRC-20 token may return false from
259
+ `transfer` and still transfer, and USDT-TRC20 does. A receipt with another result, or `SUCCESS` with no such log,
260
+ is a failure only once the Solidity node, which serves solidified blocks alone, shows it. A transaction whose
261
+ expiration has passed and that no node shows once the solidified head is two slots past it can never be included.
262
+ Each failure is answered `invalid_transaction_state`.
263
+ 7. Stores the answer and returns it. A success is returned only by the settle whose write stored it, so of two
264
+ concurrent settles of one payment, one answers success and the other `invalid_transaction_state` with the id. A
265
+ success whose write fails is answered `settlement_pending` with the id.
243
266
 
244
267
  Success is `{success: true, transaction, network, payer}`, where `transaction` is the transaction id in hex.
245
268
 
@@ -249,7 +272,9 @@ Success is `{success: true, transaction, network, payer}`, where `transaction` i
249
272
  `invalid_payment_requirements`.
250
273
  2. `payload.extrinsic` and `payload.call` are lowercase hex; the call is exactly
251
274
  `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`.
275
+ `asset`, `payTo` and `amount`, and R is exactly the 77 bytes `lcp:sha256:` followed by H in lowercase hex, else
276
+ `invalid_payload`. `System.Remarked` carries the BLAKE2b-256 of the remark's bytes as signed, so a remark that
277
+ spells H any other way, such as with upper-case digits, is refused.
253
278
  3. With the network's runtime metadata, the extrinsic decodes as a signed v4 extrinsic whose call is `payload.call`
254
279
  byte for byte, with a mortal era, else `invalid_payload`. The node must serve the chain the network names (its
255
280
  genesis hash), else `unexpected_verify_error`.
@@ -260,16 +285,28 @@ The answer is `{isValid: true, payer}`, with `payer` the signer in SS58.
260
285
  ### What `/settle` does on Polkadot
261
286
 
262
287
  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.
288
+ 2. Reads the stored answer for the extrinsic's BLAKE2b-256 hash. A stored success means the payment is consumed: the
289
+ repeat answers `invalid_transaction_state` with the success's `transaction`, never a second success. Any other
290
+ final answer is returned as it is.
264
291
  3. Claims the hash, with the first block to scan: the block after the finalized head read before validation, never
265
292
  before the era's birth.
266
293
  4. Submits with `author_submitExtrinsic`. A refusal that says the node has already seen the extrinsic or its nonce is
267
294
  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.
295
+ 5. Scans every second, up to the last block that can include the extrinsic: the era's last block, and no later than
296
+ `System.BlockHashCount` + 1 blocks after the era's birth. Each block's execution keeps only the hashes of the
297
+ `BlockHashCount` + 1 blocks before it, and the chain refuses an extrinsic whose birth block's hash is gone. The scan
298
+ reads first the finalized blocks, then the blocks up to the head. In the block that holds the extrinsic, success
299
+ needs `System.ExtrinsicSuccess`, `System.Remarked` for R's BLAKE2b-256 and `Assets.Transferred` for `asset`. A
300
+ failure counts only in a finalized block.
301
+ 6. A finalized block the node cannot give, its body or, for the block that holds the extrinsic, its events, is recorded
302
+ 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
303
+ unread block is read again on each later pass and on each repeat. A block read that cannot start before the deadline,
304
+ because the process's 4 block reads are all running, is recorded the same way. A block above the finalized head that
305
+ cannot be read is skipped, since it is read again at finality.
306
+ 7. Once every block to the last is finalized without the extrinsic, and no block is unread, it can never be included:
307
+ `invalid_transaction_state`.
308
+ 8. Stores the answer and returns it. A success is given only by the `/settle` that stores it. When it cannot be stored,
309
+ the answer is `settlement_pending` with the extrinsic's hash, and a later `/settle` reads the chain again.
273
310
 
274
311
  Success is `{success: true, transaction, network, payer}`, where `transaction` is `<block hash>-<extrinsic index>`.
275
312
  While the extrinsic is broadcast but not yet in a block, the answer is `settlement_pending` with `transaction` set to
@@ -277,11 +314,20 @@ the extrinsic's hash.
277
314
 
278
315
  ### Pending and repeated settles
279
316
 
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.
317
+ When the wait ends first, `/settle` answers `{success: false, errorReason: "settlement_pending", transaction}` with the
318
+ transaction id or extrinsic hash; x402 requires that `transaction` not be empty. Call `/settle` again with the same
319
+ request: it reads the chain from where it stopped, never submits twice, and returns the final answer once there is one.
320
+ The facilitator keeps the payment's row until that final answer is written, however long that takes, so a repeat made
321
+ after the validity window has ended still reads the chain. On Tron a payment is answered success once: every later
322
+ `/settle` of it answers `invalid_transaction_state` with the transaction id, because x402's `exact` family requires that
323
+ a consumed payment produce a settlement failure, never a success. An answer with an empty `transaction` means nothing
324
+ was submitted. When the store cannot be read, the facilitator cannot know whether the payment was submitted, so it
325
+ answers `settlement_pending` with the id.
326
+
327
+ A payment whose success has been answered is consumed. On Polkadot, a repeated `/settle` for it answers
328
+ `invalid_transaction_state` with the success's `transaction`, never a second success, as x402's `exact` family
329
+ requires: *"A consumed primitive MUST produce a settlement failure, never a success."* Of two concurrent settles of
330
+ one payment, one answers success and the other that failure.
285
331
 
286
332
  ## API reference
287
333
 
@@ -317,15 +363,16 @@ controls, to the resource servers that use it.
317
363
  | `invalid_network` | yes | yes | The network is not one this facilitator is configured with. |
318
364
  | `invalid_payment_requirements` | yes | yes | The requirements are not ones the profile admits. |
319
365
  | `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. |
366
+ | `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). |
367
+ | `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. |
368
+ | `unexpected_verify_error` | yes | no | The node or the store could not be read. |
323
369
  | `unexpected_settle_error` | no | yes | The node could not be read before submission, or refused the submission. |
324
370
  | `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. |
371
+ | `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. |
326
372
 
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.
373
+ `unsupported_permission` and `invalid_transaction` are this facilitator's, for a Tron owner permission that does not
374
+ accept the transaction's one signature and for a transaction the node refuses in simulation or validation. The
375
+ others are the x402 specification's.
329
376
 
330
377
  ### Storage
331
378
 
@@ -338,57 +385,102 @@ CREATE TABLE IF NOT EXISTS settlement (
338
385
  answer jsonb,
339
386
  until timestamptz NOT NULL,
340
387
  since bigint,
388
+ unread bigint[] NOT NULL DEFAULT '{}',
341
389
  PRIMARY KEY (network, id)
342
- )
390
+ );
391
+ CREATE INDEX IF NOT EXISTS settlement_final_until ON settlement (until)
392
+ WHERE answer IS NOT NULL AND answer->>'errorReason' IS DISTINCT FROM 'settlement_pending'
343
393
  ```
344
394
 
345
395
  - One row per settled payment, keyed by network and transaction id (Tron) or extrinsic hash (Polkadot).
346
396
  - `answer` is null while the row is claimed and the answer is not yet written. A final answer is never replaced; a
347
397
  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.
398
+ - `until` is the end of the payment's validity window: Tron's `expiration`, or, for Polkadot, the end of the last
399
+ block that can include the extrinsic (the era's last, and no later than `System.BlockHashCount` + 1 blocks after its
400
+ birth), counted from the best block at 12 seconds a block.
401
+ - A row whose answer is final (`success: true`, or a failure other than `settlement_pending`) is kept for 24 hours
402
+ after `until`, so a repeat in that time reads the stored answer before anything is verified again.
403
+ - A row whose answer is not final (claimed with no answer, or `settlement_pending`) is kept, whatever its age, until a
404
+ repeated `/settle` reads the chain and writes a final answer. A repeat therefore always finds the id of a payment
405
+ that was submitted, and never answers with an empty `transaction` for it.
406
+ - A sweep every minute drops the rows whose answer is final and whose `until` is more than 24 hours past. It reads
407
+ them through `settlement_final_until`, an index that holds only rows with a final answer, so the rows it keeps add
408
+ nothing to its work.
409
+ - `since` is, for Polkadot, the first block the scan has not yet read at finality.
410
+ - `unread` is, for Polkadot, the finalized blocks below `since` that the node could not give. None of them is shown to
411
+ lack the extrinsic, so each is read again, and the answer that the extrinsic can never be included waits until the
412
+ list is empty. A scan's write keeps every block of the list that the scan did not read, so concurrent repeats lose
413
+ none. It holds at most one entry per block of the validity window.
352
414
  - The pool holds at most 10 connections. Acquiring a connection, each query and each statement are bounded by 5
353
415
  seconds.
354
416
 
355
417
  ### Bounds and logs
356
418
 
357
- - Each node call has a timeout of at most 5 seconds and an answer of at most 4 MiB.
419
+ - Each node call has a timeout of at most 5 seconds and an answer of at most 4 MiB, except Polkadot's
420
+ `chain_getBlock`. Its bound is sized from the runtime's `System.BlockLength`, read from the metadata: 4 MiB, plus
421
+ 9/2 of the largest class limit (an extrinsic of n encoded bytes is at most 2n + 5 JSON characters), plus 7 times
422
+ `maxHeaderSize`. For Polkadot Asset Hub's runtime 2005000 that is 28,504,064 bytes. At most 4 of these reads run at
423
+ once in one process, so block answers take at most 114,016,256 bytes for that runtime. A read waits for a free slot
424
+ until the scan's deadline; one that cannot start by then is recorded as unread, like a block the node cannot give,
425
+ and read again later. Every other node call has no such limit. On Tron, `/verify` makes six FullNode calls:
426
+ the account, the two id reads, the simulation and the head read at once, then the reference block read.
358
427
  - A request body is at most 64 KiB. The server's request timeout is `settleWaitMs` plus 60 seconds.
428
+ - The table holds a row with a final answer until 24 hours after its validity window ends. A row with no final answer
429
+ stays until a repeated `/settle` for it gives one. Each such row is a payment that passed every check and was
430
+ claimed for submission; it is one row of fixed columns, the sweep's index does not hold it, and each repeat reads the
431
+ chain within `settleWaitMs`. On Tron, one repeat made once the latest solidified block is two slots past the
432
+ expiration gives a final answer whenever the nodes answer its reads.
359
433
  - 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`.
434
+ carry: `settlement-failed` (with the events, or the receipt result and why the transfer does not count, that the
435
+ chain shows), `settlement-expired`, `answer-not-stored`, `block-unreadable` (a finalized Polkadot block recorded
436
+ as unread, with the node's reason) and `settlement-consumed` (a repeated `/settle` of a Polkadot payment whose
437
+ success has been answered).
362
438
 
363
439
  ## Security model and guarantees
364
440
 
365
441
  - **No key, no fee.** The facilitator signs nothing. It submits exactly the bytes the payer signed, and the payer pays
366
442
  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.
443
+ - **Settled once.** Settlements are deduplicated by transaction id or extrinsic hash, atomically, for as long as the
444
+ answer is not final, and for at least 24 hours after the validity window ends. A payment is answered success once,
445
+ across every process that shares the store, to the `/settle` whose write stores it, on Tron and on Polkadot. On
446
+ Tron, a transaction id the node already holds is refused.
369
447
  - **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.
448
+ the profile's success conditions: on Tron, receipt result `SUCCESS` and a `Transfer` log from the token.
449
+ - **What it does not check.** It checks that the payment carries H in the profile's form, not which H the seller issued.
450
+ Its store claims a payment's id once, so the payment is submitted once. On Tron and on Polkadot, a success is answered
451
+ only by the settle whose write stored it, and a repeated `/settle` of that payment answers `invalid_transaction_state`
452
+ with the transaction. Each profile's rule 6 puts the remaining checks on the resource server: it accepts a payment
453
+ only when the payment's H is one it issued for that request and has not seen claimed. The seller door's `claim` makes
454
+ both checks. It answers `404 claim/unknown` for an H it holds no record of, `409 claim/not-this-request` for a payment
455
+ of another request, and `409 claim/in-progress` or `409 claim/paid` once the ATR's payment has been claimed. The
456
+ facilitator checks the amount, asset and payee against the requirements it is given because x402 requires that of a
457
+ facilitator, and carries no business or legal logic beyond that.
375
458
 
376
459
  ## Test vectors and conformance
377
460
 
378
461
  The tests check each profile's rule 5 against local node stubs, with the transactions of `@integraledger/lcp`'s
379
462
  shared vectors. The Tron stubs answer with Tron mainnet's recorded answers (`test/fixtures/tron-mainnet-answers.json`),
380
463
  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
464
+ (`test/fixtures/polkadot-asset-hub-2005000.json.gz`); the Tron account, block and transaction reads follow
465
+ java-tron's HTTP answers and its signature and TaPoS checks. They cover two concurrent settles of one payment (one
466
+ submission), repeated settles while the node is down, a settle that finds its id claimed and unanswered, the end of
467
+ each validity window (Tron's expiration and Polkadot's mortal era, capped by `System.BlockHashCount`), and a
468
+ Polkadot remark that spells H with upper-case digits, refused before the node is asked. On Tron they also cover the
469
+ owner's permission, TaPoS, a transaction id the node (in a block or its pending pool) or the store already holds, a
470
+ consumed payment, and a `SUCCESS` receipt with and without the token's `Transfer` log, including the live
471
+ USDT-TRC20 receipt whose `transfer` returned false. On Polkadot they also cover a repeat of a consumed payment, a
472
+ block answer over 4 MiB and one over the `System.BlockLength` bound, and a block the node cannot give, before and
473
+ after the era's end. They need
384
474
  `INTEGRA_DATABASE_URL` set to a Postgres database.
385
475
 
386
476
  ## Requirements
387
477
 
388
478
  - Node.js `>=26.10.0`.
389
479
  - 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.
480
+ - For Tron, a FullNode and a Solidity node with java-tron's HTTP API: the FullNode serves `/wallet/getaccount`,
481
+ `/wallet/getnowblock`, `/wallet/getblock`, `/wallet/gettransactionbyid`, `/wallet/gettransactionfrompending`,
482
+ `/wallet/triggerconstantcontract`, `/wallet/broadcasthex` and `/wallet/gettransactioninfobyid`. For Polkadot, an
483
+ Asset Hub RPC node that serves JSON-RPC over HTTP.
392
484
 
393
485
  ## Contributing
394
486
 
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;
package/dist/http.d.ts CHANGED
@@ -9,8 +9,8 @@ export declare class NodeError extends Error {
9
9
  readonly sent: boolean;
10
10
  constructor(code: "timeout" | "transport" | "http-status" | "too-large" | "malformed", sent: boolean, detail: string);
11
11
  }
12
- /** POSTs a JSON body and reads a JSON answer within the timeout (at most 5 s) and the size bound. */
13
- export declare function postJson(url: string, body: unknown, timeoutMs?: number): Promise<unknown>;
12
+ /** POSTs a JSON body and reads a JSON answer within the timeout (at most 5 s) and `maxBytes` (4 MiB unless given). */
13
+ export declare function postJson(url: string, body: unknown, timeoutMs?: number, maxBytes?: number): Promise<unknown>;
14
14
  /** Reads a request body of at most 64 KiB as JSON; undefined when it is larger or is not JSON. */
15
15
  export declare function readRequestJson(req: IncomingMessage): Promise<{
16
16
  json: unknown;
@@ -21,3 +21,13 @@ export declare function sendJson(res: ServerResponse, status: number, body: unkn
21
21
  export declare function sleep(ms: number): Promise<void>;
22
22
  /** `p`'s outcome, or a `timeout` NodeError once `ms` has passed first. */
23
23
  export declare function within<T>(p: Promise<T>, ms: number): Promise<T>;
24
+ /**
25
+ * A fixed number of slots shared by the callers that hold one. `take` gives a slot within `ms`, as the function that
26
+ * gives it back (a second call does nothing), or undefined when none is free in time. A slot given back goes to the
27
+ * longest waiter first.
28
+ */
29
+ export declare class Slots {
30
+ #private;
31
+ constructor(count: number);
32
+ take(ms: number): Promise<(() => void) | undefined>;
33
+ }
package/dist/http.js CHANGED
@@ -16,8 +16,8 @@ export class NodeError extends Error {
16
16
  this.sent = sent;
17
17
  }
18
18
  }
19
- /** POSTs a JSON body and reads a JSON answer within the timeout (at most 5 s) and the size bound. */
20
- export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS) {
19
+ /** POSTs a JSON body and reads a JSON answer within the timeout (at most 5 s) and `maxBytes` (4 MiB unless given). */
20
+ export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS, maxBytes = NODE_MAX_BYTES) {
21
21
  const ms = Number.isFinite(timeoutMs) ? Math.max(1, Math.ceil(Math.min(timeoutMs, NODE_TIMEOUT_MS))) : NODE_TIMEOUT_MS;
22
22
  const signal = AbortSignal.timeout(ms);
23
23
  let res;
@@ -36,7 +36,7 @@ export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS) {
36
36
  const unsent = typeof cause === "string" && UNSENT.has(cause);
37
37
  throw new NodeError("transport", !unsent, e instanceof Error ? e.message : String(e));
38
38
  }
39
- const bytes = await readBounded(res, signal);
39
+ const bytes = await readBounded(res, signal, maxBytes);
40
40
  if (res.status < 200 || res.status > 299)
41
41
  throw new NodeError("http-status", true, `status ${res.status}`);
42
42
  try {
@@ -46,9 +46,9 @@ export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS) {
46
46
  throw new NodeError("malformed", true, "the answer is not JSON");
47
47
  }
48
48
  }
49
- async function readBounded(res, signal) {
49
+ async function readBounded(res, signal, maxBytes) {
50
50
  const declared = Number(res.headers.get("content-length"));
51
- if (Number.isFinite(declared) && declared > NODE_MAX_BYTES) {
51
+ if (Number.isFinite(declared) && declared > maxBytes) {
52
52
  await res.body?.cancel();
53
53
  throw new NodeError("too-large", true, `content-length ${declared}`);
54
54
  }
@@ -63,9 +63,9 @@ async function readBounded(res, signal) {
63
63
  if (done)
64
64
  break;
65
65
  total += value.byteLength;
66
- if (total > NODE_MAX_BYTES) {
66
+ if (total > maxBytes) {
67
67
  await reader.cancel();
68
- throw new NodeError("too-large", true, `more than ${NODE_MAX_BYTES} bytes`);
68
+ throw new NodeError("too-large", true, `more than ${maxBytes} bytes`);
69
69
  }
70
70
  parts.push(value);
71
71
  }
@@ -129,3 +129,49 @@ export async function within(p, ms) {
129
129
  clearTimeout(timer);
130
130
  }
131
131
  }
132
+ /**
133
+ * A fixed number of slots shared by the callers that hold one. `take` gives a slot within `ms`, as the function that
134
+ * gives it back (a second call does nothing), or undefined when none is free in time. A slot given back goes to the
135
+ * longest waiter first.
136
+ */
137
+ export class Slots {
138
+ #free;
139
+ #waiting = [];
140
+ constructor(count) {
141
+ this.#free = count;
142
+ }
143
+ take(ms) {
144
+ if (this.#free > 0) {
145
+ this.#free -= 1;
146
+ return Promise.resolve(this.#release());
147
+ }
148
+ if (!(ms > 0))
149
+ return Promise.resolve(undefined);
150
+ return new Promise((resolve) => {
151
+ const wake = (release) => {
152
+ clearTimeout(timer);
153
+ resolve(release);
154
+ };
155
+ const timer = setTimeout(() => {
156
+ const at = this.#waiting.indexOf(wake);
157
+ if (at >= 0)
158
+ this.#waiting.splice(at, 1);
159
+ resolve(undefined);
160
+ }, ms);
161
+ this.#waiting.push(wake);
162
+ });
163
+ }
164
+ #release() {
165
+ let given = false;
166
+ return () => {
167
+ if (given)
168
+ return;
169
+ given = true;
170
+ const next = this.#waiting.shift();
171
+ if (next === undefined)
172
+ this.#free += 1;
173
+ else
174
+ next(this.#release());
175
+ };
176
+ }
177
+ }
@@ -1,10 +1,18 @@
1
1
  import { type PolkadotNetwork } from "@integraledger/lcp/polkadot";
2
2
  import { type FacilitatorRequest, type SettleAnswer, type VerifyAnswer } from "./answers.js";
3
+ import { Slots } from "./http.js";
3
4
  import { type SettlementStore } from "./store.js";
4
5
  export interface PolkadotNode {
5
6
  network: PolkadotNetwork;
6
7
  rpc: string;
7
8
  }
9
+ /**
10
+ * How many `chain_getBlock` reads, each bounded by the runtime's `System.BlockLength`, run at once in this process:
11
+ * for Polkadot Asset Hub's runtime 2005000, at most 4 × 28,504,064 = 114,016,256 bytes of block answers.
12
+ */
13
+ export declare const BLOCK_READS = 4;
14
+ /** The slots of `BLOCK_READS`, shared by every network and every scan in this process. */
15
+ export declare const blockReads: Slots;
8
16
  export declare function createPolkadot(nodes: readonly PolkadotNode[], s: SettlementStore, settleWaitMs: number): {
9
17
  verify: (r: FacilitatorRequest) => Promise<VerifyAnswer>;
10
18
  settle: (r: FacilitatorRequest) => Promise<SettleAnswer>;