@integraledger/profile-facilitator 0.5.1 → 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 (44) hide show
  1. package/CHANGELOG.md +449 -0
  2. package/README.md +551 -47
  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 +108 -21
  8. package/dist/module.js +39 -0
  9. package/dist/modules/casper/index.js +14 -2
  10. package/dist/modules/erc7710/index.d.ts +8 -5
  11. package/dist/modules/erc7710/index.js +1110 -33
  12. package/dist/modules/evm/escrow.d.ts +125 -0
  13. package/dist/modules/evm/escrow.js +619 -0
  14. package/dist/modules/evm/forms.d.ts +37 -9
  15. package/dist/modules/evm/forms.js +165 -21
  16. package/dist/modules/evm/index.d.ts +41 -6
  17. package/dist/modules/evm/index.js +1127 -18
  18. package/dist/modules/evm/node.d.ts +16 -1
  19. package/dist/modules/evm/node.js +181 -26
  20. package/dist/modules/evm/nonce-proof.d.ts +186 -0
  21. package/dist/modules/evm/nonce-proof.js +779 -0
  22. package/dist/modules/solana/index.d.ts +3 -0
  23. package/dist/modules/solana/index.js +94 -7
  24. package/dist/modules/solana/reader.d.ts +2 -1
  25. package/dist/modules/solana/reader.js +42 -4
  26. package/dist/modules/solana/upto-claim.d.ts +58 -0
  27. package/dist/modules/solana/upto-claim.js +269 -0
  28. package/dist/modules/stellar/index.d.ts +5 -0
  29. package/dist/modules/stellar/index.js +17 -7
  30. package/dist/modules/stellar/node.d.ts +7 -1
  31. package/dist/modules/stellar/node.js +51 -7
  32. package/dist/modules/sui/index.js +63 -18
  33. package/dist/modules/sui/node.d.ts +13 -0
  34. package/dist/modules/sui/node.js +60 -0
  35. package/dist/modules/ton/index.js +5 -1
  36. package/dist/modules/xrpl/index.js +60 -11
  37. package/dist/modules/xrpl/node.d.ts +31 -2
  38. package/dist/modules/xrpl/node.js +88 -17
  39. package/dist/modules/xrpl/upto.js +105 -19
  40. package/dist/record.d.ts +52 -8
  41. package/dist/record.js +39 -5
  42. package/dist/wrapper.d.ts +3 -1
  43. package/dist/wrapper.js +4 -2
  44. package/package.json +3 -3
@@ -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, phaseOf, } 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. */
@@ -132,6 +133,67 @@ function counted(signer, meter, node) {
132
133
  },
133
134
  });
134
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
+ }
135
197
  /** lcp's checks of a payment of `pairing`, and its reference; the refusal where the module's network differs. */
136
198
  async function checked(network, pairing, payload, requirements) {
137
199
  if (requirements.network !== network || payload.accepted?.network !== network)
@@ -190,7 +252,7 @@ function instrumentOf(pairing, nonce, ref) {
190
252
  * whose later settles are collection (`isOpening` false: an `upto` claim, a batch's voucher, top-up or refund), which
191
253
  * lcp does not read: those go to the class with the network checked, and each is its own row.
192
254
  */
193
- function moduleOf(c, pairing, cls, acceptsZero, isOpening, atSettle) {
255
+ function moduleOf(c, pairing, cls, acceptsZero, isOpening, atSettle, sent, classPending) {
194
256
  const network = c.network;
195
257
  const check = async (payload, requirements) => {
196
258
  if (!isOpening({ payload, requirements })) {
@@ -202,7 +264,7 @@ function moduleOf(c, pairing, cls, acceptsZero, isOpening, atSettle) {
202
264
  return {
203
265
  descriptor: { name: "solana", key: "fee-payer", pairings: [pairing.id], acceptsZero },
204
266
  network,
205
- facilitator: behind(cls, check, atSettle),
267
+ facilitator: pairing.id === uptoSvm.id && sent !== undefined ? givenFirst(behind(cls, check, atSettle), c, isOpening, sent) : behind(cls, check, atSettle),
206
268
  record: {
207
269
  async instrument(p) {
208
270
  if (!isOpening(p)) {
@@ -213,6 +275,12 @@ function moduleOf(c, pairing, cls, acceptsZero, isOpening, atSettle) {
213
275
  instrument: { by: "digest", network, digest: collectionDigest(network, p) },
214
276
  nonce: "unshown",
215
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 } : {}),
216
284
  };
217
285
  }
218
286
  const r = await checked(c.network, pairing, p.payload, p.requirements);
@@ -220,7 +288,11 @@ function moduleOf(c, pairing, cls, acceptsZero, isOpening, atSettle) {
220
288
  },
221
289
  async read(p, at) {
222
290
  if (!isOpening(p)) {
223
- // 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.
224
296
  return outcomeOf({ state: "pending", reason: "not-found", foreign: [] });
225
297
  }
226
298
  const r = await checked(c.network, pairing, p.payload, p.requirements);
@@ -272,6 +344,20 @@ const uptoAtSettle = async (cls, payload, requirements, context) => {
272
344
  const { type: _stamp, ...signed } = body;
273
345
  return cls.verify({ ...payload, payload: signed }, requirements, context);
274
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
+ };
275
361
  /**
276
362
  * Whether a batch-settlement payload goes through lcp's checks as an opening: a deposit that lcp's channel read does not
277
363
  * place within an open channel (a top-up), that is its `open`, and a deposit lcp cannot read, which its checks refuse.
@@ -295,15 +381,15 @@ export function solanaModules(config, state, meter) {
295
381
  const modules = [moduleOf(c, exactSvm, exact, [exactSvm.id], () => true)];
296
382
  if (c.network === SOLANA_MAINNET || state === undefined)
297
383
  return modules;
298
- 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 });
299
385
  const batch = new BatchSvmScheme(c.signer, {
300
386
  ...versions,
301
387
  channelStorage: state.channels,
302
388
  pendingSettlementStore: state.batchPending,
303
389
  });
304
390
  // upto: lcp's filter admits a positive amount only. Batch settlement: zero through it has not been read.
305
- modules.push(moduleOf(c, uptoSvm, upto, [], uptoOpening, uptoAtSettle));
306
- modules.push(moduleOf(c, batchSvm, batch, [], batchOpening));
391
+ modules.push(moduleOf(c, uptoSvm, upto, [], uptoOpening, uptoAtSettle, state.sent, state.pending));
392
+ modules.push(moduleOf(c, batchSvm, batch, [], batchOpening, batchAtSettle));
307
393
  return modules;
308
394
  }
309
395
  /**
@@ -318,6 +404,7 @@ export const starter = {
318
404
  channels: channelStorage(core.state),
319
405
  pending: core.state.pendingSettlements(),
320
406
  batchPending: batchPendingStore(core.state),
407
+ sent: sentBlockhashes(core.state),
321
408
  };
322
409
  return {
323
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>;
@@ -0,0 +1,269 @@
1
+ /**
2
+ * The read of an x402 `upto` claim on Solana, which carries no H and which lcp does not read: what the chain shows of
3
+ * the claim itself, from the payment-channels program's channel account and the channel's own transactions.
4
+ *
5
+ * x402's `upto` class settles a claim as one transaction: the ed25519 precompile's check of the voucher (the receiver
6
+ * authorizer's signature over the channel, the cumulative amount and the expiry), the program's `settle_and_seal` on
7
+ * the channel, and its `distribute`. A zero-amount claim (the cancel) carries no voucher and its `settle_and_seal` says
8
+ * so. Once it lands the channel is no longer `Open`. So:
9
+ *
10
+ * - the claim landed where a finalized transaction on the channel succeeded with a `settle_and_seal` of that channel
11
+ * and, for a positive amount, the precompile instruction carrying this claim's voucher signature, which shows the
12
+ * claim presented is the one that landed, whoever sent it;
13
+ * - another act ended the channel where such a transaction carries another voucher, or none for a positive amount;
14
+ * - the claim has not landed while the channel account reads `Open` at `finalized`.
15
+ *
16
+ * Where the record names a transaction sent for the claim, the read also says whether it can still land: not where the
17
+ * node shows it landed and failed, nor where its blockhash has ended and the node holds no status for it. A blockhash
18
+ * has ended by the rule of lcp's `x402-upto-solana` profile: `isBlockhashValid` answers `false` at `finalized` at a
19
+ * `finalized` slot at least 150 past the context slot of the first answer of `true` at `confirmed`. A node answers
20
+ * `false` at `finalized` also for a blockhash its `finalized` bank does not hold yet, so an answer of `false` before a
21
+ * `true` at `confirmed`, or at a slot short of that bound, decides nothing.
22
+ */
23
+ import { getBase58Encoder, getCompiledTransactionMessageDecoder, getTransactionDecoder } from "@solana/kit";
24
+ import { isObject } from "../../answers.js";
25
+ import { solanaRpc } from "./reader.js";
26
+ /** The payment-channels program x402's `upto` and batch-settlement classes call. */
27
+ export const PAYMENT_CHANNELS_PROGRAM = "CHNLxYvVA28MJP9PrFuDXccuoGXAx7jBacfLEkahyGsX";
28
+ /** Solana's ed25519 signature-verification precompile. */
29
+ const ED25519_PROGRAM = "Ed25519SigVerify111111111111111111111111111";
30
+ /** The program's `settle_and_seal` instruction discriminator; its one argument byte says whether a voucher is checked. */
31
+ const SETTLE_AND_SEAL = 4;
32
+ /** A channel account's `status` byte, after its discriminator, version and bump; `Open` is 0. */
33
+ const STATUS_OFFSET = 3;
34
+ const OPEN = 0;
35
+ /** The signatures one read lists for a channel; an `upto` channel carries a handful. */
36
+ const HISTORY = 1000;
37
+ /** The blocks a blockhash stays valid for after its own, which no count of slots stands in for. */
38
+ const BLOCKHASH_SLOTS = 150n;
39
+ /** The blockhashes in the module's durable state. */
40
+ export function sentBlockhashes(state) {
41
+ const key = (transaction) => `sent-blockhash:${transaction}`;
42
+ const at = (transaction) => `sent-blockhash-valid-at:${transaction}`;
43
+ return {
44
+ remember: (transaction, blockhash) => state.set(key(transaction), blockhash),
45
+ async blockhashOf(transaction) {
46
+ const v = await state.get(key(transaction));
47
+ return typeof v === "string" ? v : undefined;
48
+ },
49
+ async validAt(transaction, slot) {
50
+ await state.swap(at(transaction), undefined, slot.toString());
51
+ },
52
+ async validSince(transaction) {
53
+ const v = await state.get(at(transaction));
54
+ return typeof v === "string" && /^[0-9]+$/.test(v) ? BigInt(v) : undefined;
55
+ },
56
+ async given(row, slot) {
57
+ await state.swap(`claim-given:${row}`, undefined, slot.toString());
58
+ },
59
+ async givenAt(row) {
60
+ const v = await state.get(`claim-given:${row}`);
61
+ return typeof v === "string" && /^[0-9]+$/.test(v) ? BigInt(v) : undefined;
62
+ },
63
+ async landedFor(transaction, row) {
64
+ const k = `landed-claim:${transaction}`;
65
+ await state.swap(k, undefined, row);
66
+ return (await state.get(k)) === row;
67
+ },
68
+ };
69
+ }
70
+ /**
71
+ * `isBlockhashValid` of `blockhash` at `commitment` on `node`: the answer and its context slot; undefined where the
72
+ * answer does not hold both.
73
+ */
74
+ export async function blockhashValid(node, blockhash, commitment, deadline) {
75
+ const r = await solanaRpc(node, "isBlockhashValid", [blockhash, { commitment }], deadline);
76
+ if (!isObject(r) || typeof r["value"] !== "boolean" || !isObject(r["context"]))
77
+ return undefined;
78
+ const slot = r["context"]["slot"];
79
+ if (typeof slot !== "number" || !Number.isSafeInteger(slot) || slot < 0)
80
+ return undefined;
81
+ return { valid: r["value"], slot: BigInt(slot) };
82
+ }
83
+ /**
84
+ * A wire transaction's lifetime token, base58: its recent blockhash, or, for a durable-nonce message, the nonce value,
85
+ * which no node answers valid as a blockhash, so such a transaction is never read as unable to land by its blockhash;
86
+ * undefined where the wire does not decode.
87
+ */
88
+ export function blockhashOf(wireBase64) {
89
+ try {
90
+ const tx = getTransactionDecoder().decode(Buffer.from(wireBase64, "base64"));
91
+ const message = getCompiledTransactionMessageDecoder().decode(tx.messageBytes);
92
+ return typeof message.lifetimeToken === "string" ? message.lifetimeToken : undefined;
93
+ }
94
+ catch {
95
+ return undefined;
96
+ }
97
+ }
98
+ /** The program's settle of `channel` in a `getTransaction` answer (JSON encoding), against this claim. */
99
+ function actOf(tx, channel, amount, voucher) {
100
+ if (!isObject(tx))
101
+ return "none";
102
+ const transaction = tx["transaction"];
103
+ const meta = tx["meta"];
104
+ if (!isObject(transaction) || !isObject(transaction["message"]))
105
+ return "none";
106
+ const message = transaction["message"];
107
+ const loaded = isObject(meta) && isObject(meta["loadedAddresses"]) ? meta["loadedAddresses"] : {};
108
+ const keys = [
109
+ ...(Array.isArray(message["accountKeys"]) ? message["accountKeys"] : []),
110
+ ...(Array.isArray(loaded["writable"]) ? loaded["writable"] : []),
111
+ ...(Array.isArray(loaded["readonly"]) ? loaded["readonly"] : []),
112
+ ];
113
+ const instructions = Array.isArray(message["instructions"]) ? message["instructions"] : [];
114
+ let settle;
115
+ let carries = false;
116
+ for (const ix of instructions) {
117
+ if (!isObject(ix) || typeof ix["data"] !== "string" || typeof ix["programIdIndex"] !== "number")
118
+ continue;
119
+ const program = keys[ix["programIdIndex"]];
120
+ const data = new Uint8Array(getBase58Encoder().encode(ix["data"]));
121
+ const accounts = Array.isArray(ix["accounts"]) ? ix["accounts"] : [];
122
+ if (program === PAYMENT_CHANNELS_PROGRAM && data[0] === SETTLE_AND_SEAL && accounts.some((k) => typeof k === "number" && keys[k] === channel)) {
123
+ settle = data[1] ?? 0;
124
+ }
125
+ if (program === ED25519_PROGRAM && voucher !== undefined && Buffer.from(data).includes(Buffer.from(voucher)))
126
+ carries = true;
127
+ }
128
+ if (settle === undefined)
129
+ return "none";
130
+ if (amount === 0n)
131
+ return settle === 0 ? "this" : "other";
132
+ return settle === 1 && carries ? "this" : "other";
133
+ }
134
+ const pendingAs = (reason, transaction) => ({
135
+ state: "pending",
136
+ reason,
137
+ ...(transaction === undefined ? {} : { transaction }),
138
+ foreign: [],
139
+ });
140
+ /**
141
+ * Whether `transaction`, sent for the claim, can still land: `instrument-live` naming it where it cannot (the node shows
142
+ * it landed and failed, or its blockhash has ended, by the profile's rule, and the node holds no status for it), else
143
+ * `below-mark` naming it.
144
+ */
145
+ async function fateOf(node, transaction, sent, deadline) {
146
+ const status = async () => {
147
+ const r = await solanaRpc(node, "getSignatureStatuses", [[transaction], { searchTransactionHistory: true }], deadline);
148
+ return isObject(r) && Array.isArray(r["value"]) ? r["value"][0] : undefined;
149
+ };
150
+ // A failure is final only once finalized: a fork that drops it may still let the transaction land.
151
+ const failedFinal = (v) => v["err"] !== null && v["confirmationStatus"] === "finalized";
152
+ const first = await status();
153
+ if (isObject(first))
154
+ return failedFinal(first) ? pendingAs("instrument-live", transaction) : pendingAs("below-mark", transaction);
155
+ const blockhash = await sent.blockhashOf(transaction);
156
+ if (blockhash === undefined)
157
+ return pendingAs("below-mark", transaction);
158
+ // The context slot of the first `true` at `confirmed` is at or past the blockhash's own slot, which bounds it from
159
+ // above. Without one, a `false` may be a blockhash this node has not reached yet: nothing is decided.
160
+ let since = await sent.validSince(transaction);
161
+ if (since === undefined) {
162
+ const head = await blockhashValid(node, blockhash, "confirmed", deadline);
163
+ if (head?.valid === true) {
164
+ await sent.validAt(transaction, head.slot);
165
+ since = (await sent.validSince(transaction)) ?? head.slot;
166
+ }
167
+ }
168
+ if (since === undefined)
169
+ return pendingAs("below-mark", transaction);
170
+ // A `finalized` bank at least 150 slots past it holds the blockhash's block, so its `false` is the blockhash ended,
171
+ // which no later block reverses.
172
+ const final = await blockhashValid(node, blockhash, "finalized", deadline);
173
+ if (final === undefined || final.valid || final.slot < since + BLOCKHASH_SLOTS)
174
+ return pendingAs("below-mark", transaction);
175
+ // The blockhash has ended, so no block can take the transaction from now on: a status that appears in between is
176
+ // read once more.
177
+ const again = await status();
178
+ if (isObject(again))
179
+ return failedFinal(again) ? pendingAs("instrument-live", transaction) : pendingAs("below-mark", transaction);
180
+ return pendingAs("instrument-live", transaction);
181
+ }
182
+ /**
183
+ * The read of an `upto` claim (or its zero-amount cancel), at `finalized`. `transaction` is the last one the record
184
+ * names as sent for the claim, where it names one.
185
+ */
186
+ export async function uptoClaimRead(node, p, at, sent, classPending) {
187
+ const body = p.payload.payload;
188
+ const channel = body["channelId"];
189
+ const signature = body["voucherSignature"];
190
+ let amount;
191
+ let voucher;
192
+ try {
193
+ amount = BigInt(p.requirements.amount);
194
+ voucher = typeof signature === "string" && signature !== "" ? new Uint8Array(getBase58Encoder().encode(signature)) : undefined;
195
+ }
196
+ catch {
197
+ return { state: "unreadable", reason: "unparseable", foreign: [] };
198
+ }
199
+ if (typeof channel !== "string" || (amount > 0n && voucher?.length !== 64))
200
+ return { state: "unreadable", reason: "unparseable", foreign: [] };
201
+ try {
202
+ const history = await solanaRpc(node, "getSignaturesForAddress", [channel, { commitment: "finalized", limit: HISTORY }], at.deadline);
203
+ if (!Array.isArray(history))
204
+ return { state: "unreadable", reason: "unparseable", foreign: [] };
205
+ let other;
206
+ for (const h of history) {
207
+ if (!isObject(h) || typeof h["signature"] !== "string" || h["err"] !== null)
208
+ continue;
209
+ const tx = await solanaRpc(node, "getTransaction", [h["signature"], { encoding: "json", commitment: "finalized", maxSupportedTransactionVersion: 1 }], at.deadline);
210
+ if (isObject(tx) && isObject(tx["meta"]) && tx["meta"]["err"] !== null)
211
+ continue;
212
+ const act = actOf(tx, channel, amount, voucher);
213
+ if (act === "this") {
214
+ const landed = h["signature"];
215
+ const settled = (presented) => ({ state: "settled", transaction: landed, finality: "finalized", presented, foreign: [] });
216
+ // A cancel carries no voucher, so which body it was is not shown.
217
+ if (voucher === undefined)
218
+ return settled("unshown");
219
+ // A transaction this settler named belongs to the row that named it, whose own record decides it: to any other
220
+ // row, which body it was is not shown.
221
+ if ((await sent.blockhashOf(landed)) !== undefined)
222
+ return settled("unshown");
223
+ // Landed by another route, it carries the presented voucher signature, which the receiver authorizer made over
224
+ // the channel, the amount and the expiry, and no other member of the body. Bodies that differ outside the
225
+ // voucher are rows of their own. Only a row given to the class at a `confirmed` slot below the slot the
226
+ // transaction landed in, so before it landed, can be the body that landed; of those, the first row read
227
+ // against the transaction is shown as its body, and no other.
228
+ const slot = h["slot"];
229
+ const given = await sent.givenAt(at.row);
230
+ const before = typeof slot === "number" && given !== undefined && given < BigInt(slot);
231
+ return settled(before && (await sent.landedFor(landed, at.row)) ? "yes" : "unshown");
232
+ }
233
+ if (act === "other")
234
+ other ??= h["signature"];
235
+ }
236
+ const account = await solanaRpc(node, "getAccountInfo", [channel, { encoding: "base64", commitment: "finalized" }], at.deadline);
237
+ const value = isObject(account) ? account["value"] : undefined;
238
+ const open = isObject(value) &&
239
+ value["owner"] === PAYMENT_CHANNELS_PROGRAM &&
240
+ Array.isArray(value["data"]) &&
241
+ typeof value["data"][0] === "string" &&
242
+ Buffer.from(value["data"][0], "base64")[STATUS_OFFSET] === OPEN;
243
+ if (open) {
244
+ if (at.transaction === undefined)
245
+ return pendingAs("instrument-live");
246
+ const fate = await fateOf(node, at.transaction, sent, at.deadline);
247
+ if (fate.state === "pending" && fate.reason === "instrument-live" && classPending !== undefined) {
248
+ const key = `upto:${p.requirements.network}:${channel}`;
249
+ if ((await classPending.get(key)) === at.transaction)
250
+ await classPending.delete(key);
251
+ }
252
+ return fate;
253
+ }
254
+ // Another claim or cancel of the channel landed: this one never can.
255
+ if (other !== undefined)
256
+ return { state: "failed", reason: "instrument-consumed", transaction: other, foreign: [] };
257
+ // No channel, or one no longer open whose settle the history does not show: nothing is decided from an absence.
258
+ const unseen = value === null && history.length === 0 ? "not-found" : "search-incomplete";
259
+ if (at.transaction !== undefined) {
260
+ const fate = await fateOf(node, at.transaction, sent, at.deadline);
261
+ if (fate.state === "pending" && fate.reason === "below-mark")
262
+ return fate;
263
+ }
264
+ return pendingAs(unseen, at.transaction);
265
+ }
266
+ catch {
267
+ return { state: "unreadable", reason: "transport", foreign: [] };
268
+ }
269
+ }
@@ -34,6 +34,11 @@ export interface StellarNetworkConfig {
34
34
  maxTransactionFeeStroops?: number;
35
35
  /** The inclusion fee bid above the simulated resource fee, in stroops: x402's `inclusionFeeStroops`, at least 100, default 100. */
36
36
  inclusionFeeStroops?: number;
37
+ /**
38
+ * The most one `getEvents` call of the read may take, in milliseconds. Without it, each is bounded by the read's own
39
+ * deadline alone: an RPC scans up to 10,000 ledgers per call and can take longer than other node calls.
40
+ */
41
+ eventsTimeoutMs?: number;
37
42
  }
38
43
  /** Starts one module per configured network, each its own registration of `exact`. */
39
44
  export declare const starter: ModuleStarter<StellarConfig>;