@integraledger/profile-facilitator 0.5.0 → 0.6.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +556 -0
  2. package/README.md +754 -111
  3. package/dist/core.d.ts +1 -1
  4. package/dist/core.js +683 -66
  5. package/dist/http.d.ts +19 -4
  6. package/dist/http.js +16 -6
  7. package/dist/module.d.ts +111 -24
  8. package/dist/module.js +39 -0
  9. package/dist/modules/algorand/index.js +1 -1
  10. package/dist/modules/aptos/index.js +1 -1
  11. package/dist/modules/cardano/index.js +1 -1
  12. package/dist/modules/casper/index.js +15 -3
  13. package/dist/modules/concordium/index.js +1 -1
  14. package/dist/modules/erc7710/index.d.ts +8 -5
  15. package/dist/modules/erc7710/index.js +1111 -34
  16. package/dist/modules/evm/escrow.d.ts +125 -0
  17. package/dist/modules/evm/escrow.js +619 -0
  18. package/dist/modules/evm/forms.d.ts +39 -11
  19. package/dist/modules/evm/forms.js +191 -25
  20. package/dist/modules/evm/index.d.ts +41 -6
  21. package/dist/modules/evm/index.js +1135 -20
  22. package/dist/modules/evm/node.d.ts +16 -1
  23. package/dist/modules/evm/node.js +181 -26
  24. package/dist/modules/evm/nonce-proof.d.ts +186 -0
  25. package/dist/modules/evm/nonce-proof.js +779 -0
  26. package/dist/modules/hedera/executor.js +1 -1
  27. package/dist/modules/hedera/index.js +1 -1
  28. package/dist/modules/lnbtc/index.js +3 -2
  29. package/dist/modules/near/index.js +1 -1
  30. package/dist/modules/polkadot/index.js +1 -1
  31. package/dist/modules/solana/index.d.ts +3 -0
  32. package/dist/modules/solana/index.js +119 -10
  33. package/dist/modules/solana/reader.d.ts +2 -1
  34. package/dist/modules/solana/reader.js +42 -4
  35. package/dist/modules/solana/upto-claim.d.ts +58 -0
  36. package/dist/modules/solana/upto-claim.js +269 -0
  37. package/dist/modules/starknet/index.js +9 -2
  38. package/dist/modules/stellar/index.d.ts +5 -0
  39. package/dist/modules/stellar/index.js +18 -8
  40. package/dist/modules/stellar/node.d.ts +7 -1
  41. package/dist/modules/stellar/node.js +51 -7
  42. package/dist/modules/sui/index.js +66 -20
  43. package/dist/modules/sui/node.d.ts +13 -0
  44. package/dist/modules/sui/node.js +60 -0
  45. package/dist/modules/ton/index.js +6 -2
  46. package/dist/modules/tron/index.js +1 -1
  47. package/dist/modules/xrpl/index.js +61 -12
  48. package/dist/modules/xrpl/node.d.ts +31 -2
  49. package/dist/modules/xrpl/node.js +88 -17
  50. package/dist/modules/xrpl/upto.js +106 -20
  51. package/dist/record.d.ts +52 -8
  52. package/dist/record.js +39 -5
  53. package/dist/wrapper.d.ts +7 -5
  54. package/dist/wrapper.js +7 -5
  55. package/package.json +4 -3
@@ -285,7 +285,7 @@ export function transferExecutorModule(c, offering) {
285
285
  },
286
286
  };
287
287
  return {
288
- descriptor: { name: "hedera", key: "relayer", pairings: [exactHederaExecutor.id], acceptsZero: false },
288
+ descriptor: { name: "hedera", key: "relayer", pairings: [exactHederaExecutor.id], acceptsZero: [] },
289
289
  network,
290
290
  facilitator,
291
291
  record: {
@@ -69,7 +69,7 @@ export function hederaModule(c) {
69
69
  const mirror = mirrorOf(c);
70
70
  return {
71
71
  // A zero transfer is not established on Hedera, so the kind does not take zero.
72
- descriptor: { name: "hedera", key: "fee-payer", pairings: [exactHedera.id], acceptsZero: false },
72
+ descriptor: { name: "hedera", key: "fee-payer", pairings: [exactHedera.id], acceptsZero: [] },
73
73
  network,
74
74
  facilitator: naming(new ExactHederaScheme(c.signer)),
75
75
  record: {
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * The Lightning module: x402's `exact` scheme on the `lnbtc` networks, for lcp's pairing `x402/exact/lnbtc/payment-hash`,
3
- * written to x402's scheme text (`specs/schemes/exact/scheme_exact_lnbtc.md`) and lcp's profile `x402-exact-lnbtc.md`.
3
+ * written to x402's scheme text (`specs/schemes/exact/scheme_exact_lnbtc.md`) and lcp's profile
4
+ * `x402-exact-lnbtc-payment-hash.md`.
4
5
  * The buyer's node paid the invoice before the preimage reached the buyer, so settling moves nothing. The module makes
5
6
  * the scheme's whole validation through lcp's `validateExactLnbtc`, the export a resource server also runs before it
6
7
  * settles: the invoice's signature, its signer against `payTo`, its `h` against the request hash, its `p` against
@@ -90,7 +91,7 @@ const record = {
90
91
  };
91
92
  function moduleOn(network) {
92
93
  return {
93
- descriptor: { name: "lnbtc", key: "none", pairings: [exactLnbtcPaymentHash.id], acceptsZero: false, verifyForbidden: true },
94
+ descriptor: { name: "lnbtc", key: "none", pairings: [exactLnbtcPaymentHash.id], acceptsZero: [], verifyForbidden: true },
94
95
  network,
95
96
  facilitator,
96
97
  record,
@@ -177,7 +177,7 @@ export function nearModule(c) {
177
177
  const network = c.network;
178
178
  return {
179
179
  // The standard token refuses a zero ft_transfer, so the kind does not take zero.
180
- descriptor: { name: "near", key: "relayer", pairings: [exactNear.id], acceptsZero: false },
180
+ descriptor: { name: "near", key: "relayer", pairings: [exactNear.id], acceptsZero: [] },
181
181
  network,
182
182
  facilitator: new ExactNearScheme(c.signer),
183
183
  record: {
@@ -92,7 +92,7 @@ export function polkadotModules(rail, log) {
92
92
  pairings: [exactPolkadotRemark.id],
93
93
  // The assets pallet returns early on a transfer of zero and emits no `Transferred` event, so the smallest
94
94
  // amount is one base unit (polkadot-sdk `substrate/frame/assets/src/functions.rs`, `do_transfer`).
95
- acceptsZero: false,
95
+ acceptsZero: [],
96
96
  },
97
97
  network,
98
98
  facilitator,
@@ -15,6 +15,7 @@ import type { FacilitatorSvmSigner } from "@x402/svm";
15
15
  import { type BatchPendingSettlementStore, type PaymentChannelStorage } from "@x402/svm/batch-settlement/facilitator";
16
16
  import type { PendingSettlementStore } from "@x402/core/facilitator";
17
17
  import { type FeeMeter, type Module, type ModuleStarter, type X402Payment } from "../../module.js";
18
+ import { type SentBlockhashes } from "./upto-claim.js";
18
19
  /** Solana mainnet, where the payment-channels program the `upto` and batch-settlement forms call is not deployed. */
19
20
  export declare const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
20
21
  /** The durable state the channel forms' classes keep, from the settler's database. */
@@ -25,6 +26,8 @@ export interface SolanaChannelState {
25
26
  readonly pending: PendingSettlementStore;
26
27
  /** The batch-settlement class's own pending signatures. */
27
28
  readonly batchPending: BatchPendingSettlementStore;
29
+ /** The blockhash of each `upto` claim transaction named before it was sent, which bounds when it can land. */
30
+ readonly sent: SentBlockhashes;
28
31
  }
29
32
  export interface SolanaConfig {
30
33
  /** The network, exactly one. */
@@ -20,9 +20,10 @@ import { getBase58Decoder, getTransactionDecoder } from "@solana/kit";
20
20
  import { createHash } from "node:crypto";
21
21
  import { isObject } from "../../answers.js";
22
22
  import { NODE_TIMEOUT_MS } from "../../http.js";
23
- import { outcomeOf, } from "../../module.js";
23
+ import { beforeSend, outcomeOf, phaseOf, sendsNamed, } from "../../module.js";
24
24
  import { chargedOn, svmReader } from "./reader.js";
25
25
  import { batchPendingStore, channelStorage } from "./state.js";
26
+ import { blockhashOf, blockhashValid, sentBlockhashes, uptoClaimRead } from "./upto-claim.js";
26
27
  /** Solana mainnet, where the payment-channels program the `upto` and batch-settlement forms call is not deployed. */
27
28
  export const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
28
29
  /** The x402 reason for an lcp refusal: the version, the option, or else the payload. */
@@ -39,9 +40,10 @@ function presented(payload) {
39
40
  }
40
41
  /**
41
42
  * The published class, unchanged, with the module's checks before it on both calls: a payment they refuse is answered
42
- * by x402's failure shape with lcp's code as its message, and the class never sees it.
43
+ * by x402's failure shape with lcp's code as its message, and the class never sees it. At `/settle`, the class's check
44
+ * is `atSettle` where given, else its `verify`.
43
45
  */
44
- function behind(cls, check) {
46
+ function behind(cls, check, atSettle) {
45
47
  return {
46
48
  scheme: cls.scheme,
47
49
  caipFamily: cls.caipFamily,
@@ -52,6 +54,8 @@ function behind(cls, check) {
52
54
  if (refused !== null) {
53
55
  return { isValid: false, invalidReason: refused.reason, ...(refused.code ? { invalidMessage: refused.code } : {}) };
54
56
  }
57
+ if (atSettle !== undefined && phaseOf(context) === "settle")
58
+ return atSettle(cls, payload, requirements, context);
55
59
  return cls.verify(payload, requirements, context);
56
60
  },
57
61
  async settle(payload, requirements, context) {
@@ -129,6 +133,67 @@ function counted(signer, meter, node) {
129
133
  },
130
134
  });
131
135
  }
136
+ /**
137
+ * The fee payer's signer object as the `upto` class takes it: where the settle running holds a claim whose transactions
138
+ * are named before they are sent, each transaction's blockhash is kept and its id given to the core before it is sent,
139
+ * and nothing is sent where either fails. Before the send, the read node `node` is also asked whether the blockhash is
140
+ * valid at `confirmed`, and a `true` is kept with its context slot, from which the claim's read later tells the
141
+ * blockhash ended; an answer of anything else, or none, is kept nowhere and stops nothing. Every other member is
142
+ * unchanged.
143
+ */
144
+ function naming(signer, sent, node) {
145
+ return new Proxy(signer, {
146
+ get(inner, member) {
147
+ const value = Reflect.get(inner, member);
148
+ if (typeof value !== "function")
149
+ return value;
150
+ if (member === "sendTransaction") {
151
+ return async (wire, network) => {
152
+ if (sendsNamed()) {
153
+ const transaction = txidOf(wire);
154
+ const blockhash = blockhashOf(wire);
155
+ if (transaction === undefined || blockhash === undefined)
156
+ throw new Error("a transaction whose id and blockhash do not decode is not sent");
157
+ await sent.remember(transaction, blockhash);
158
+ await beforeSend(transaction);
159
+ try {
160
+ const head = await blockhashValid(node, blockhash, "confirmed", performance.now() + NODE_TIMEOUT_MS);
161
+ if (head?.valid === true)
162
+ await sent.validAt(transaction, head.slot);
163
+ }
164
+ catch {
165
+ // The claim's read asks again.
166
+ }
167
+ }
168
+ return value.call(inner, wire, network);
169
+ };
170
+ }
171
+ return value.bind(inner);
172
+ },
173
+ });
174
+ }
175
+ /**
176
+ * The `upto` class with each claim's first giving kept: before a claim (any settle that is not an opening) reaches the
177
+ * class's `settle`, the read node's `confirmed` slot is kept for the claim's row, where none is kept yet, so that the
178
+ * claim's read can tell a row given before its claim landed by another route from one given after. Where the slot
179
+ * cannot be read, the settle throws and nothing reaches the class.
180
+ */
181
+ function givenFirst(f, c, isOpening, sent) {
182
+ return {
183
+ ...f,
184
+ getExtra: (network) => f.getExtra(network),
185
+ getSigners: (network) => f.getSigners(network),
186
+ verify: (payload, requirements, context) => f.verify(payload, requirements, context),
187
+ async settle(payload, requirements, context) {
188
+ const p = { payload, requirements };
189
+ if (!isOpening(p)) {
190
+ const slot = await svmReader(c.network, c.node, performance.now() + NODE_TIMEOUT_MS).slot("confirmed");
191
+ await sent.given(collectionDigest(c.network, p), slot);
192
+ }
193
+ return f.settle(payload, requirements, context);
194
+ },
195
+ };
196
+ }
132
197
  /** lcp's checks of a payment of `pairing`, and its reference; the refusal where the module's network differs. */
133
198
  async function checked(network, pairing, payload, requirements) {
134
199
  if (requirements.network !== network || payload.accepted?.network !== network)
@@ -187,7 +252,7 @@ function instrumentOf(pairing, nonce, ref) {
187
252
  * whose later settles are collection (`isOpening` false: an `upto` claim, a batch's voucher, top-up or refund), which
188
253
  * lcp does not read: those go to the class with the network checked, and each is its own row.
189
254
  */
190
- function moduleOf(c, pairing, cls, acceptsZero, isOpening) {
255
+ function moduleOf(c, pairing, cls, acceptsZero, isOpening, atSettle, sent, classPending) {
191
256
  const network = c.network;
192
257
  const check = async (payload, requirements) => {
193
258
  if (!isOpening({ payload, requirements })) {
@@ -199,7 +264,7 @@ function moduleOf(c, pairing, cls, acceptsZero, isOpening) {
199
264
  return {
200
265
  descriptor: { name: "solana", key: "fee-payer", pairings: [pairing.id], acceptsZero },
201
266
  network,
202
- facilitator: behind(cls, check),
267
+ facilitator: pairing.id === uptoSvm.id && sent !== undefined ? givenFirst(behind(cls, check, atSettle), c, isOpening, sent) : behind(cls, check, atSettle),
203
268
  record: {
204
269
  async instrument(p) {
205
270
  if (!isOpening(p)) {
@@ -210,6 +275,12 @@ function moduleOf(c, pairing, cls, acceptsZero, isOpening) {
210
275
  instrument: { by: "digest", network, digest: collectionDigest(network, p) },
211
276
  nonce: "unshown",
212
277
  keep: { until: "settler" },
278
+ // Batch settlement's claim, seal and settle (x402's channel manager's) are not recorded: see `batchAtSettle`.
279
+ ...(pairing.id === batchSvm.id && ["claim", "seal", "settle"].includes(String(p.payload.payload["type"])) ? { unrecorded: true } : {}),
280
+ // An `upto` claim (every `upto` settle that is not its opening): its transactions are named before they are
281
+ // sent, and its read shows the claim landed, the channel ended by another act, or the channel open.
282
+ // Batch settlement's later messages are not stated so.
283
+ ...(pairing.id === uptoSvm.id && sent !== undefined ? { landsOnce: true } : {}),
213
284
  };
214
285
  }
215
286
  const r = await checked(c.network, pairing, p.payload, p.requirements);
@@ -217,7 +288,11 @@ function moduleOf(c, pairing, cls, acceptsZero, isOpening) {
217
288
  },
218
289
  async read(p, at) {
219
290
  if (!isOpening(p)) {
220
- // A collection settle carries no H and lcp has no read of it: the read finds nothing it can test.
291
+ // An `upto` claim is read from the program's channel and the channel's transactions.
292
+ if (pairing.id === uptoSvm.id && sent !== undefined) {
293
+ return outcomeOf(await uptoClaimRead(c.node, p, { deadline: at.deadline, row: collectionDigest(network, p), ...(at.transaction === undefined ? {} : { transaction: at.transaction }) }, sent, classPending));
294
+ }
295
+ // Another collection settle carries no H and lcp has no read of it: the read finds nothing it can test.
221
296
  return outcomeOf({ state: "pending", reason: "not-found", foreign: [] });
222
297
  }
223
298
  const r = await checked(c.network, pairing, p.payload, p.requirements);
@@ -250,6 +325,39 @@ function uptoOpening(p) {
250
325
  return false;
251
326
  return !(type === undefined && typeof body["voucherSignature"] === "string");
252
327
  }
328
+ /**
329
+ * The `upto` class's check at `/settle`. The resource server stamps `type` on each settle it sends (x402's `upto`
330
+ * server: `deposit` before its handler runs, `claim` after it), and the class's `verify`, the check of the buyer's
331
+ * opening, refuses a payload that carries one. A deposit is checked by that `verify` as the buyer sent it, without
332
+ * the stamp. A claim, which that `verify` never takes, is checked by the class's `settle` before it sends anything (the
333
+ * channel it opened, the receiver authorizer, the validity window, the voucher): here it is valid, naming the
334
+ * payload's payer.
335
+ */
336
+ const uptoAtSettle = async (cls, payload, requirements, context) => {
337
+ const body = payload.payload;
338
+ if (!uptoOpening({ payload, requirements })) {
339
+ const from = body["from"];
340
+ return { isValid: true, ...(typeof from === "string" ? { payer: from } : {}) };
341
+ }
342
+ if (body["type"] !== "deposit")
343
+ return cls.verify(payload, requirements, context);
344
+ const { type: _stamp, ...signed } = body;
345
+ return cls.verify({ ...payload, payload: signed }, requirements, context);
346
+ };
347
+ /**
348
+ * The batch-settlement class's check at `/settle`. x402's channel manager sends `claim`, `seal` and `settle`, which the
349
+ * class's `verify`, the check of what a buyer sends, does not take (it answers
350
+ * `invalid_batch_settlement_svm_payload_type`). The class's `settle` checks each before it sends anything: the channel
351
+ * it derives from the configuration and that channel's status, and for a claim or a seal the payer authorizer's
352
+ * voucher signature and a cumulative amount above what the channel has settled and at most its deposit. Here it is
353
+ * valid. Every other type is checked by that `verify`.
354
+ */
355
+ const batchAtSettle = async (cls, payload, requirements, context) => {
356
+ const type = payload.payload["type"];
357
+ if (type === "claim" || type === "seal" || type === "settle")
358
+ return { isValid: true };
359
+ return cls.verify(payload, requirements, context);
360
+ };
253
361
  /**
254
362
  * Whether a batch-settlement payload goes through lcp's checks as an opening: a deposit that lcp's channel read does not
255
363
  * place within an open channel (a top-up), that is its `open`, and a deposit lcp cannot read, which its checks refuse.
@@ -270,18 +378,18 @@ export function solanaModules(config, state, meter) {
270
378
  const pending = state === undefined ? {} : { pendingSettlementStore: state.pending };
271
379
  const exact = new ExactSvmScheme(c.signer, undefined, { ...versions, ...pending });
272
380
  // lcp's floor on x402/exact/solana is 0: a zero TransferChecked lands, and the class compares amounts by equality.
273
- const modules = [moduleOf(c, exactSvm, exact, true, () => true)];
381
+ const modules = [moduleOf(c, exactSvm, exact, [exactSvm.id], () => true)];
274
382
  if (c.network === SOLANA_MAINNET || state === undefined)
275
383
  return modules;
276
- const upto = new UptoSvmScheme(c.signer, { ...versions, channelStorage: state.channels, pendingSettlementStore: state.pending });
384
+ const upto = new UptoSvmScheme(naming(c.signer, state.sent, c.node), { ...versions, channelStorage: state.channels, pendingSettlementStore: state.pending });
277
385
  const batch = new BatchSvmScheme(c.signer, {
278
386
  ...versions,
279
387
  channelStorage: state.channels,
280
388
  pendingSettlementStore: state.batchPending,
281
389
  });
282
390
  // upto: lcp's filter admits a positive amount only. Batch settlement: zero through it has not been read.
283
- modules.push(moduleOf(c, uptoSvm, upto, false, uptoOpening));
284
- modules.push(moduleOf(c, batchSvm, batch, false, batchOpening));
391
+ modules.push(moduleOf(c, uptoSvm, upto, [], uptoOpening, uptoAtSettle, state.sent, state.pending));
392
+ modules.push(moduleOf(c, batchSvm, batch, [], batchOpening, batchAtSettle));
285
393
  return modules;
286
394
  }
287
395
  /**
@@ -296,6 +404,7 @@ export const starter = {
296
404
  channels: channelStorage(core.state),
297
405
  pending: core.state.pendingSettlements(),
298
406
  batchPending: batchPendingStore(core.state),
407
+ sent: sentBlockhashes(core.state),
299
408
  };
300
409
  return {
301
410
  registrations: networks.flatMap((c) => solanaModules(c, state, core.meter(c.network)).map((module) => ({ network: module.network, module, own: [] }))),
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * lcp's Solana reader over one Solana JSON-RPC endpoint: the calls `SvmReader` names, each a POST of one JSON-RPC
3
3
  * request bounded by the settler's node bounds and by the read's deadline, a `performance.now()` time. Every failure
4
- * rejects, an error answer of the node among them, so lcp reads it as `unreadable`.
4
+ * rejects, an error answer of the node among them, so lcp reads it as `unreadable`; a `getSignaturesForAddress` the
5
+ * node refuses as not yet at its `minContextSlot` is first asked again, a few times within the deadline.
5
6
  */
6
7
  import type { SolanaNetwork, SvmLanded, SvmReader } from "@integraledger/lcp/svm";
7
8
  /** One JSON-RPC call: its `result`, or a rejection where the node answers an error or no result. */
@@ -1,13 +1,29 @@
1
1
  import { getBase58Encoder, getCompiledTransactionMessageDecoder, getTransactionDecoder } from "@solana/kit";
2
2
  import { isObject } from "../../answers.js";
3
- import { NodeError, postJson } from "../../http.js";
3
+ import { NodeError, postJson, sleep } from "../../http.js";
4
+ /** A JSON-RPC error the node answered, with its code where it gave a number. */
5
+ class RpcRefusal extends NodeError {
6
+ rpcCode;
7
+ constructor(rpcCode, detail) {
8
+ super("malformed", true, detail);
9
+ this.rpcCode = rpcCode;
10
+ }
11
+ }
12
+ /** Solana's JSON-RPC error for a request whose `minContextSlot` the node has not reached. */
13
+ const MIN_CONTEXT_SLOT_NOT_REACHED = -32016;
14
+ /** The tries of a call the node answers with that error, and the wait before each next one: about a slot. */
15
+ const BEHIND_TRIES = 5;
16
+ const BEHIND_WAIT_MS = 400;
4
17
  /** One JSON-RPC call: its `result`, or a rejection where the node answers an error or no result. */
5
18
  export async function solanaRpc(url, method, params, deadline) {
6
19
  const answer = await postJson(url, { jsonrpc: "2.0", id: 1, method, params }, deadline - performance.now());
7
20
  if (!isObject(answer))
8
21
  throw new NodeError("malformed", true, `${method}: the answer is not an object`);
9
- if (answer["error"] !== undefined)
10
- throw new NodeError("malformed", true, `${method}: ${JSON.stringify(answer["error"])}`);
22
+ const error = answer["error"];
23
+ if (error !== undefined) {
24
+ const code = isObject(error) && typeof error["code"] === "number" ? error["code"] : undefined;
25
+ throw new RpcRefusal(code, `${method}: ${JSON.stringify(error)}`);
26
+ }
11
27
  if (!("result" in answer))
12
28
  throw new NodeError("malformed", true, `${method}: no result`);
13
29
  return answer["result"];
@@ -111,7 +127,29 @@ export function svmReader(network, url, deadline) {
111
127
  return result === null ? { notFound: true, slot: at } : landedOf(result);
112
128
  },
113
129
  async signatures(address, page) {
114
- const result = await call("getSignaturesForAddress", [address, page]);
130
+ // lcp gives `minContextSlot` as a bigint, which JSON cannot carry: the node takes it as a JSON number, within the
131
+ // range this reader reads a slot in.
132
+ const { minContextSlot, ...rest } = page;
133
+ if (minContextSlot !== undefined && (minContextSlot < 0n || minContextSlot > BigInt(Number.MAX_SAFE_INTEGER))) {
134
+ return malformed("getSignaturesForAddress's minContextSlot is not a slot");
135
+ }
136
+ const options = minContextSlot === undefined ? rest : { ...rest, minContextSlot: Number(minContextSlot) };
137
+ // A node not yet at `minContextSlot` refuses the call: a load-balanced endpoint can answer it from a backend a
138
+ // slot or two behind the one that gave lcp the slot. It is asked again, about a slot later, a few times within the
139
+ // deadline; the refusal is never an answer, and the last one rejects.
140
+ let result;
141
+ for (let tried = 1;; tried++) {
142
+ try {
143
+ result = await call("getSignaturesForAddress", [address, options]);
144
+ break;
145
+ }
146
+ catch (e) {
147
+ const behind = e instanceof RpcRefusal && e.rpcCode === MIN_CONTEXT_SLOT_NOT_REACHED;
148
+ if (!behind || tried >= BEHIND_TRIES || deadline - performance.now() <= BEHIND_WAIT_MS)
149
+ throw e;
150
+ await sleep(BEHIND_WAIT_MS);
151
+ }
152
+ }
115
153
  if (!Array.isArray(result))
116
154
  return malformed("getSignaturesForAddress is not a list");
117
155
  return result.map((s) => {
@@ -0,0 +1,58 @@
1
+ import type { ModuleState, ReadAnswer, X402Payment } from "../../module.js";
2
+ /** The payment-channels program x402's `upto` and batch-settlement classes call. */
3
+ export declare const PAYMENT_CHANNELS_PROGRAM = "CHNLxYvVA28MJP9PrFuDXccuoGXAx7jBacfLEkahyGsX";
4
+ /**
5
+ * Where the module keeps the blockhash of each transaction it named before sending, and the context slot of the first
6
+ * `isBlockhashValid` answer of `true` at `confirmed` for it, which bound when it can land.
7
+ */
8
+ export interface SentBlockhashes {
9
+ remember(transaction: string, blockhash: string): Promise<void>;
10
+ blockhashOf(transaction: string): Promise<string | undefined>;
11
+ /** Keeps `slot` where no slot is kept yet for `transaction`: the first answer of `true` stands. */
12
+ validAt(transaction: string, slot: bigint): Promise<void>;
13
+ /** The slot kept for `transaction`, where one is. */
14
+ validSince(transaction: string): Promise<bigint | undefined>;
15
+ /** Keeps `slot`, the read node's `confirmed` slot, where no slot is kept yet for `row`: when it was first given. */
16
+ given(row: string, slot: bigint): Promise<void>;
17
+ /** The slot kept for `row`, where one is. */
18
+ givenAt(row: string): Promise<bigint | undefined>;
19
+ /**
20
+ * Whether the landed claim `transaction`, which no transaction this settler named, is `row`'s: the first row asked
21
+ * about it holds it, and every other is answered false.
22
+ */
23
+ landedFor(transaction: string, row: string): Promise<boolean>;
24
+ }
25
+ /**
26
+ * x402's `upto` class keeps a claim's signature whose confirmation it stopped waiting for, under
27
+ * `upto:<network>:<channel>`, and on the next settle waits for that signature again instead of building a claim. Where
28
+ * the chain shows that signature unable to land, the read removes it, so that the class builds the claim again.
29
+ */
30
+ export interface ClassPending {
31
+ get(key: string): Promise<string | undefined>;
32
+ delete(key: string): Promise<void>;
33
+ }
34
+ /** The blockhashes in the module's durable state. */
35
+ export declare function sentBlockhashes(state: ModuleState): SentBlockhashes;
36
+ /**
37
+ * `isBlockhashValid` of `blockhash` at `commitment` on `node`: the answer and its context slot; undefined where the
38
+ * answer does not hold both.
39
+ */
40
+ export declare function blockhashValid(node: string, blockhash: string, commitment: "confirmed" | "finalized", deadline: number): Promise<{
41
+ valid: boolean;
42
+ slot: bigint;
43
+ } | undefined>;
44
+ /**
45
+ * A wire transaction's lifetime token, base58: its recent blockhash, or, for a durable-nonce message, the nonce value,
46
+ * which no node answers valid as a blockhash, so such a transaction is never read as unable to land by its blockhash;
47
+ * undefined where the wire does not decode.
48
+ */
49
+ export declare function blockhashOf(wireBase64: string): string | undefined;
50
+ /**
51
+ * The read of an `upto` claim (or its zero-amount cancel), at `finalized`. `transaction` is the last one the record
52
+ * names as sent for the claim, where it names one.
53
+ */
54
+ export declare function uptoClaimRead(node: string, p: X402Payment, at: {
55
+ readonly deadline: number;
56
+ readonly transaction?: string;
57
+ readonly row: string;
58
+ }, sent: SentBlockhashes, classPending?: ClassPending): Promise<ReadAnswer>;