@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
@@ -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
+ }
@@ -19,6 +19,12 @@ const ID = exactStarknet.id;
19
19
  const U128 = 1n << 128n;
20
20
  const POLL_MS = 1_000;
21
21
  const NETWORKS = ["starknet:SN_MAIN", "starknet:SN_SEPOLIA"];
22
+ /**
23
+ * The networks whose kind names the pairing in `extra.acceptsZero`: each holds a token on which lcp's `starknetFloor`
24
+ * answers 0 (the profile's rule 24), on Starknet Sepolia STRK and USDC. lcp's check of the option refuses an amount of
25
+ * "0" on any other token, `starknet/option-malformed`, which the module answers `invalid_payment_requirements`.
26
+ */
27
+ const ZERO_NETWORKS = ["starknet:SN_SEPOLIA"];
22
28
  /** The `l2_gas` a simulation may spend, which charges no fee: Starknet's per-transaction execution bound. */
23
29
  const SIMULATION_L2_GAS = 1000000000n;
24
30
  const no = (reason, message) => (message === undefined ? { reason } : { reason, message });
@@ -486,8 +492,9 @@ export function starknetModule(c, core) {
486
492
  name: "starknet",
487
493
  key: "relayer",
488
494
  pairings: [ID],
489
- // The profile's floor is one base unit on every token until a run shows a token's `Transfer` for zero (rule 24).
490
- acceptsZero: false,
495
+ // A `transfer` of 0 of STRK and of USDC on Starknet Sepolia emits a `Transfer` of 0 (`starknet_simulateTransactions`
496
+ // at block 18422698, lcp's test/fixtures/starknet-zero-transfer-sepolia.json).
497
+ acceptsZero: ZERO_NETWORKS.includes(network) ? [ID] : [],
491
498
  },
492
499
  network: network,
493
500
  facilitator,
@@ -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>;
@@ -84,7 +84,7 @@ export function stellarModule(c, core) {
84
84
  const network = c.network;
85
85
  const passphrase = PASSPHRASE[network];
86
86
  const sourceKey = Keypair.fromPublicKey(source).rawPublicKey();
87
- const node = stellarNode(c.rpc.replace(/\/+$/, ""));
87
+ const node = stellarNode(c.rpc.replace(/\/+$/, ""), c.eventsTimeoutMs === undefined ? {} : { eventsTimeoutMs: c.eventsTimeoutMs });
88
88
  const { log, settleWaitMs } = core;
89
89
  const meter = core.meter(network);
90
90
  /** The source account's transactions are sent one at a time; `last` is the sequence number of the last one sent. */
@@ -286,9 +286,10 @@ export function stellarModule(c, core) {
286
286
  * Builds the transaction the module submits: the buyer's, its preconditions, memo and operation (the buyer's entry
287
287
  * among it) unchanged, with the source account, the next sequence number, the fee and the simulation's resource data
288
288
  * the module's own. The fee meter allows it, the source account's signer signs it, and the buyer's signature of the
289
- * signed payload goes beside that signature. A request that cannot have reached the node sends nothing: the module's
290
- * own failure with no transaction, as does a node that refuses it. One that may have reached it is read for its
291
- * result.
289
+ * signed payload goes beside that signature. Its hash then goes in the claim's record (`Core.naming`) before it is
290
+ * sent: where the store does not take it, nothing is sent. A request that cannot have reached the node sends nothing:
291
+ * the module's own failure with no transaction, as does a node that refuses it, and the hash is taken back out of the
292
+ * record. One that may have reached it is read for its result.
292
293
  */
293
294
  async function send(i, sim, fee, deadline) {
294
295
  let seq;
@@ -330,6 +331,10 @@ export function stellarModule(c, core) {
330
331
  return { answer: failed("settle_exact_stellar_transaction_signing_failed", "") };
331
332
  }
332
333
  const envelope = xdr.TransactionEnvelope.fromXdrObject({ type: 2, v1: { tx, signatures: [...signed, i.payloadSignature] } }).toXdr("base64");
334
+ // The hash goes in the claim's record before the envelope leaves the settler, so that a stop before the send's
335
+ // answer still leaves the record naming it, and the read is made by it. Where the store does not take it, nothing
336
+ // is sent.
337
+ const withdraw = await core.naming(hash);
333
338
  try {
334
339
  const sent = await node.send(envelope, deadline);
335
340
  if (sent.status === "PENDING" || sent.status === "DUPLICATE") {
@@ -338,6 +343,7 @@ export function stellarModule(c, core) {
338
343
  log({ event: "transaction-hash-differs", ...about(i), transaction: sent.hash, computed: hash });
339
344
  return { transaction: hash };
340
345
  }
346
+ await withdraw();
341
347
  if (sent.status === "TRY_AGAIN_LATER")
342
348
  return { answer: failed("settle_exact_stellar_transaction_submission_retryable", "") };
343
349
  const code = resultCode(sent.errorResultXdr);
@@ -350,8 +356,10 @@ export function stellarModule(c, core) {
350
356
  }
351
357
  catch (e) {
352
358
  const entry = { event: "node-call-failed", ...about(i), call: "sendTransaction", transaction: hash };
353
- if (e instanceof RpcFault || (e instanceof NodeError && !e.sent))
359
+ if (e instanceof RpcFault || (e instanceof NodeError && !e.sent)) {
360
+ await withdraw();
354
361
  return { answer: unexpected(entry, e) };
362
+ }
355
363
  log(entry, e);
356
364
  return { transaction: hash };
357
365
  }
@@ -410,7 +418,7 @@ export function stellarModule(c, core) {
410
418
  key: "relayer",
411
419
  pairings: [ID],
412
420
  // The Stellar Asset Contract refuses only a negative amount and emits its event at zero (the profile, rule 13).
413
- acceptsZero: true,
421
+ acceptsZero: [ID],
414
422
  },
415
423
  network: network,
416
424
  facilitator,
@@ -431,7 +439,8 @@ export function stellarModule(c, core) {
431
439
  },
432
440
  /**
433
441
  * lcp's read, its search starting at the earliest ledger the buyer's entry can land in: the ledger it was signed
434
- * for, its expiration less the option's timeout in ledgers (the profile, rule 5), less x402's tolerance.
442
+ * for, its expiration less the option's timeout in ledgers (the profile, rule 5), less x402's tolerance. Where the
443
+ * record holds the transaction the module submitted, the read is made by it, not by the first act under H.
435
444
  */
436
445
  async read(p, at) {
437
446
  const i = await inspect(p.payload, p.requirements);
@@ -439,7 +448,8 @@ export function stellarModule(c, core) {
439
448
  return outcomeOf({ state: "unreadable", reason: "unparseable", foreign: [] });
440
449
  const fromLedger = Math.max(0, i.ref.expiration - Math.ceil(i.maxTimeoutSeconds / LEDGER_SECONDS) - EXPIRATION_TOLERANCE);
441
450
  const query = { act: "agreement", finality: "finalized", ...(typeof at.search === "string" ? { search: at.search } : {}) };
442
- return outcomeOf(await exactStellarPrecondition.status({ ...i.ref, fromLedger }, node.reader(at.deadline), query));
451
+ const named = at.transaction === undefined ? {} : { transaction: at.transaction.toLowerCase() };
452
+ return outcomeOf(await exactStellarPrecondition.status({ ...i.ref, fromLedger, ...named }, node.reader(at.deadline), query));
443
453
  },
444
454
  },
445
455
  fees: {
@@ -54,4 +54,10 @@ export interface StellarNode {
54
54
  /** lcp's reader over this node, each of its calls ending by `deadline`. */
55
55
  reader(deadline: number): StellarReader;
56
56
  }
57
- export declare function stellarNode(url: string): StellarNode;
57
+ /**
58
+ * `eventsTimeoutMs` bounds each `getEvents` call, which an RPC answers by scanning up to 10,000 ledgers and can take
59
+ * longer than the settler's other node calls; without it, each is bounded by the read's deadline alone.
60
+ */
61
+ export declare function stellarNode(url: string, options?: {
62
+ eventsTimeoutMs?: number;
63
+ }): StellarNode;
@@ -12,10 +12,31 @@ export class RpcFault extends Error {
12
12
  /** The events one `getEvents` page asks for: Stellar RPC's default page, which its documentation states as 100. */
13
13
  const PAGE = 100;
14
14
  const isLedger = (v) => Number.isInteger(v) && v >= 0 && v <= 0xffffffff;
15
- export function stellarNode(url) {
15
+ /** Stellar RPC's `getEvents` cursor: an event id, its operation's TOID in 19 digits, `-`, and an index in 10. */
16
+ const CURSOR = /^([0-9]{19})-([0-9]{10})$/;
17
+ /**
18
+ * The ledger a `getEvents` cursor shows scanned through, where it is the cursor the RPC gives at the end of its scan:
19
+ * the TOID of the ledger's last possible operation (its low 32 bits all set) and the index 2^32 − 1. Undefined for any
20
+ * other cursor, such as the id of the last event a page holds.
21
+ */
22
+ const scannedThrough = (c) => {
23
+ const m = CURSOR.exec(c);
24
+ if (m === null || m[2] !== "4294967295")
25
+ return undefined;
26
+ const toid = BigInt(m[1]);
27
+ return (toid & 0xffffffffn) === 0xffffffffn ? Number(toid >> 32n) : undefined;
28
+ };
29
+ /** The RPC's refusal of a `startLedger` outside what it holds, which names that range. */
30
+ const OUT_OF_RANGE = /^startLedger must be within the ledger range: ([0-9]+) - ([0-9]+)$/;
31
+ /**
32
+ * `eventsTimeoutMs` bounds each `getEvents` call, which an RPC answers by scanning up to 10,000 ledgers and can take
33
+ * longer than the settler's other node calls; without it, each is bounded by the read's deadline alone.
34
+ */
35
+ export function stellarNode(url, options = {}) {
16
36
  let id = 0;
17
- async function call(method, params, deadline) {
18
- const answer = await postJson(url, { jsonrpc: "2.0", id: ++id, method, params }, deadline - performance.now());
37
+ const eventsCap = options.eventsTimeoutMs !== undefined && options.eventsTimeoutMs > 0 ? options.eventsTimeoutMs : Infinity;
38
+ async function call(method, params, deadline, capMs) {
39
+ const answer = await postJson(url, { jsonrpc: "2.0", id: ++id, method, params }, deadline - performance.now(), undefined, capMs);
19
40
  if (!isObject(answer))
20
41
  throw new NodeError("malformed", true, method);
21
42
  const error = answer["error"];
@@ -113,13 +134,27 @@ export function stellarNode(url) {
113
134
  };
114
135
  },
115
136
  // Stellar RPC's `getEvents` takes a ledger range or a cursor, never both, and its `endLedger` is exclusive (lcp's
116
- // `StellarReader.events`); a page shorter than the page asked for is the last of the range.
137
+ // `StellarReader.events`). The RPC scans at most 10,000 ledgers per call: a page shorter than the page asked for,
138
+ // even an empty one, ends the range only where its cursor names a ledger at or past the last one asked for or
139
+ // the last one the RPC holds. A refusal of a start below the oldest ledger the RPC holds answers that oldest
140
+ // ledger, which is the history gap it is; a refusal of one above its latest is the node behind, a failure.
117
141
  async events(f) {
118
142
  const filters = [{ type: "contract", topics: f.topics }];
119
143
  const params = f.cursor === undefined
120
144
  ? { startLedger: f.fromLedger, endLedger: f.toLedger + 1, filters, pagination: { limit: PAGE } }
121
145
  : { filters, pagination: { cursor: f.cursor, limit: PAGE } };
122
- const r = await call("getEvents", params, deadline);
146
+ let r;
147
+ try {
148
+ r = await call("getEvents", params, deadline, eventsCap);
149
+ }
150
+ catch (e) {
151
+ const range = e instanceof RpcFault && e.code === -32600 && f.cursor === undefined ? OUT_OF_RANGE.exec(e.message.slice(e.message.indexOf(": ") + 2)) : null;
152
+ const oldest = range === null ? NaN : Number(range[1]);
153
+ const latest = range === null ? NaN : Number(range[2]);
154
+ if (isLedger(oldest) && isLedger(latest) && oldest > f.fromLedger)
155
+ return { events: [], oldestLedger: oldest, latestLedger: latest };
156
+ throw e;
157
+ }
123
158
  const rows = r["events"];
124
159
  if (!Array.isArray(rows) || !isLedger(r["oldestLedger"]) || !isLedger(r["latestLedger"]))
125
160
  return malformed("getEvents");
@@ -141,8 +176,17 @@ export function stellarNode(url) {
141
176
  value: e["value"],
142
177
  });
143
178
  }
144
- const more = rows.length === PAGE && !past && typeof r["cursor"] === "string";
145
- return { events, oldestLedger: r["oldestLedger"], latestLedger: r["latestLedger"], ...(more ? { cursor: r["cursor"] } : {}) };
179
+ // A page that met no event past the range ends it only by a cursor at the end of a scan that reached the last
180
+ // ledger asked for or the last the RPC holds; a page with no cursor in the documented form is out of form.
181
+ const cursor = r["cursor"];
182
+ let more = false;
183
+ if (!past) {
184
+ if (typeof cursor !== "string" || !CURSOR.test(cursor))
185
+ return malformed("getEvents");
186
+ const scanned = scannedThrough(cursor);
187
+ more = rows.length === PAGE || scanned === undefined || scanned < Math.min(f.toLedger, r["latestLedger"]);
188
+ }
189
+ return { events, oldestLedger: r["oldestLedger"], latestLedger: r["latestLedger"], ...(more ? { cursor: cursor } : {}) };
146
190
  },
147
191
  };
148
192
  },
@@ -2,11 +2,13 @@
2
2
  * Sui: the settler's own facilitator for the pairing `x402/exact/sui`, written to x402's Sui scheme
3
3
  * (`scheme_exact_sui.md`), which x402 specifies and publishes no code for, and to lcp's profile `x402-exact-sui.md`. The
4
4
  * payer signs one programmable transaction carrying H as its one unused `Pure` input; the module checks it (the network,
5
- * the signature, the gas path the option fixes, a simulation showing the payee's credit) and executes it unchanged.
5
+ * the signature, the gas path the option fixes, each object it names at a version still at that version, a simulation
6
+ * showing the payee's credit) and executes it unchanged.
6
7
  * It serves the paths where the buyer pays gas and where none is paid (`extra.gasless`), and holds no key: x402's
7
8
  * sponsored path needs a gas station, whose wire x402's scheme does not state and whose caller is the buyer's client,
8
- * so an option naming one is refused. A transaction the buyer already executed is judged at `/verify` by its effects and not refused for having executed; its `/settle`
9
- * answers a failure naming it. lcp decodes the payment (`bound`, `reference`, `decodeSuiTx`) and reads it (`status`).
9
+ * so an option naming one is refused. A transaction already executed is refused at `/verify`, `invalid_transaction_state`,
10
+ * since `isValid: true` tells the caller that a settle may follow, and its `/settle` answers a failure naming it. lcp
11
+ * decodes the payment (`bound`, `reference`, `decodeSuiTx`) and reads it (`status`).
10
12
  */
11
13
  import { canonicalJson, isRefusal } from "@integraledger/lcp";
12
14
  import { decodeSuiTx, exactSui } from "@integraledger/lcp/sui";
@@ -125,8 +127,9 @@ export function suiModule(c, core) {
125
127
  }
126
128
  }
127
129
  /**
128
- * The checks that read the chain: the signature, then the transaction by its digest. One already executed is judged by its effects (status success, its bytes, the payee's
129
- * credit); one not executed is simulated, and must succeed and credit the payee.
130
+ * The checks that read the chain: the signature, then the transaction by its digest. One already executed is returned
131
+ * with its effects, the node's bytes for the digest being the payment's; one not executed is simulated, and must
132
+ * succeed and credit the payee.
130
133
  */
131
134
  async function chainChecks(i, deadline) {
132
135
  const sig = await signed(i, deadline);
@@ -141,16 +144,25 @@ export function suiModule(c, core) {
141
144
  catch (e) {
142
145
  return no(unexpectedVerify(log, { event: "node-call-failed", ...about(i), call: "transaction" }, e));
143
146
  }
144
- if (read.executed !== null) {
145
- const { bytes, effects } = read.executed;
146
- if (toBase64(bytes) !== toBase64(i.tx.bytes))
147
- return no(unexpectedVerify(log, { event: "node-answer-differs", ...about(i), call: "transaction" }));
148
- if (effects.status !== "SUCCESS")
149
- return no("invalid_transaction_state", "sui/executed-failed");
150
- if (!credited(i, effects))
151
- return no("invalid_payload", "sui/payee-not-credited");
152
- return { executed: effects, latest: read.latest };
147
+ if (read.executed !== null)
148
+ return executedAs(i, read.executed, read.latest);
149
+ // Sui's simulation takes an owned input at its latest version, not the version the transaction names, and answers
150
+ // success for one the buyer has since spent; execution refuses it. The node's index is read instead: an input it
151
+ // shows moved past the version named can never be taken. Where it shows that, the transaction is read again by its
152
+ // digest, the payment itself being what may have moved it since the first read.
153
+ let moved;
154
+ try {
155
+ moved = await node.unavailable(objectInputs(i.v1), deadline);
156
+ if (moved !== null)
157
+ read = await node.transaction(i.tx.digest, deadline);
158
+ }
159
+ catch (e) {
160
+ return no(unexpectedVerify(log, { event: "node-call-failed", ...about(i), call: "multiGetObjects" }, e));
153
161
  }
162
+ if (read.executed !== null)
163
+ return executedAs(i, read.executed, read.latest);
164
+ if (moved !== null)
165
+ return no("invalid_transaction", "sui/object-version-unavailable");
154
166
  let simulated;
155
167
  try {
156
168
  simulated = await node.simulate(i.tx.bytes, deadline);
@@ -166,6 +178,12 @@ export function suiModule(c, core) {
166
178
  return no("invalid_payload", "sui/payee-not-credited");
167
179
  return { executed: null, latest: read.latest };
168
180
  }
181
+ /** A transaction already executed, where the node's bytes for the digest are the payment's. */
182
+ function executedAs(i, executed, latest) {
183
+ if (toBase64(executed.bytes) !== toBase64(i.tx.bytes))
184
+ return no(unexpectedVerify(log, { event: "node-answer-differs", ...about(i), call: "transaction" }));
185
+ return { executed: executed.effects, latest };
186
+ }
169
187
  async function verify(payload, requirements) {
170
188
  const deadline = performance.now() + settleWaitMs;
171
189
  const i = await inspect(payload, requirements);
@@ -174,7 +192,10 @@ export function suiModule(c, core) {
174
192
  const checked = await chainChecks(i, deadline);
175
193
  if (isNo(checked))
176
194
  return refusedVerify(checked);
177
- // A transaction the buyer already executed is judged by its effects, and not refused for having executed.
195
+ // A transaction already executed can never be settled here, and `isValid: true` would tell the caller that a settle
196
+ // may follow: whoever presents it, it is refused.
197
+ if (checked.executed !== null)
198
+ return refusedVerify(no("invalid_transaction_state", "sui/executed-by-payer"));
178
199
  return { isValid: true, payer: i.sender };
179
200
  }
180
201
  async function settle(payload, requirements) {
@@ -185,9 +206,15 @@ export function suiModule(c, core) {
185
206
  const checked = await chainChecks(i, deadline);
186
207
  if (isNo(checked))
187
208
  return failed(settleReason(checked.reason), "", checked.message);
188
- // A transaction the buyer executed was not submitted here: a failure naming it, never a success.
189
- if (checked.executed !== null)
209
+ // A transaction already executed was not submitted here: a failure, never a success, naming it where it succeeded
210
+ // and credited the payee.
211
+ if (checked.executed !== null) {
212
+ if (checked.executed.status !== "SUCCESS")
213
+ return failed(settleReason("invalid_transaction_state"), "", "sui/executed-failed");
214
+ if (!credited(i, checked.executed))
215
+ return failed(settleReason("invalid_payload"), "", "sui/payee-not-credited");
190
216
  return failed("invalid_transaction_state", i.tx.digest, "sui/executed-by-payer");
217
+ }
191
218
  const signatures = [i.signature];
192
219
  try {
193
220
  const effects = await node.execute(i.tx.bytes, signatures, deadline);
@@ -248,9 +275,9 @@ export function suiModule(c, core) {
248
275
  name: "sui",
249
276
  key: "none",
250
277
  pairings: [ID],
251
- // Zero through this module is not yet established by a run on any gas path.
252
- acceptsZero: false,
253
- verifiesLanded: true,
278
+ // A transfer of 0 executes where the buyer pays gas: Sui testnet transaction 7EjfN1kqGng3phZjqgCzy8RRRXCP2Ybt7mikGgjBUwKA,
279
+ // status SUCCESS, its only balance change the sender's gas. lcp's option filter refuses 0 on the gasless path.
280
+ acceptsZero: [ID],
254
281
  },
255
282
  network: network,
256
283
  facilitator,
@@ -300,6 +327,25 @@ export function suiModule(c, core) {
300
327
  };
301
328
  return module;
302
329
  }
330
+ /**
331
+ * The objects the transaction takes at a version it names: its gas payment, and each owned or immutable object and
332
+ * each object it receives among its inputs. A shared object is named by its initial version and is not among them.
333
+ */
334
+ function objectInputs(v1) {
335
+ const refs = [...(v1.gasData.payment ?? [])];
336
+ if (v1.kind.$kind === "ProgrammableTransaction") {
337
+ for (const input of v1.kind.ProgrammableTransaction.inputs) {
338
+ if (input.$kind !== "Object")
339
+ continue;
340
+ const o = input.Object;
341
+ if (o.$kind === "ImmOrOwnedObject")
342
+ refs.push(o.ImmOrOwnedObject);
343
+ else if (o.$kind === "Receiving")
344
+ refs.push(o.Receiving);
345
+ }
346
+ }
347
+ return refs.map((r) => ({ objectId: normalizeSuiAddress(r.objectId), version: BigInt(r.version), digest: r.digest }));
348
+ }
303
349
  function refusedVerify(r) {
304
350
  return { isValid: false, invalidReason: r.reason, ...(r.message === undefined ? {} : { invalidMessage: r.message }) };
305
351
  }