@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
@@ -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
  }
@@ -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);
@@ -251,7 +278,6 @@ export function suiModule(c, core) {
251
278
  // A transfer of 0 executes where the buyer pays gas: Sui testnet transaction 7EjfN1kqGng3phZjqgCzy8RRRXCP2Ybt7mikGgjBUwKA,
252
279
  // status SUCCESS, its only balance change the sender's gas. lcp's option filter refuses 0 on the gasless path.
253
280
  acceptsZero: [ID],
254
- verifiesLanded: true,
255
281
  },
256
282
  network: network,
257
283
  facilitator,
@@ -301,6 +327,25 @@ export function suiModule(c, core) {
301
327
  };
302
328
  return module;
303
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
+ }
304
349
  function refusedVerify(r) {
305
350
  return { isValid: false, invalidReason: r.reason, ...(r.message === undefined ? {} : { invalidMessage: r.message }) };
306
351
  }
@@ -30,6 +30,13 @@ export interface Latest {
30
30
  epoch: bigint;
31
31
  referenceGasPrice: bigint;
32
32
  }
33
+ /** An owned or immutable object a transaction names at one version, as its signed bytes give it. */
34
+ export interface ObjectRef {
35
+ objectId: string;
36
+ version: bigint;
37
+ /** Base58, as the bytes and the node state it. */
38
+ digest: string;
39
+ }
33
40
  export interface SuiNode {
34
41
  readonly network: SuiNetwork;
35
42
  /** The transaction with `digest`, or null where the node holds none, and the newest checkpoint. */
@@ -37,6 +44,12 @@ export interface SuiNode {
37
44
  executed: Executed | null;
38
45
  latest: Latest;
39
46
  }>;
47
+ /**
48
+ * The first of `refs` the node can no longer take as an input, or null where it shows none: the node holds the
49
+ * version named and that version's digest is another, or the object is now at a later version or no longer live
50
+ * (deleted or wrapped). An object or version the node's index does not yet hold shows nothing.
51
+ */
52
+ unavailable(refs: readonly ObjectRef[], deadline: number): Promise<ObjectRef | null>;
40
53
  /** Simulates the transaction with Sui's checks, its signatures apart. */
41
54
  simulate(bytes: Uint8Array, deadline: number): Promise<Effects>;
42
55
  /** Executes the transaction with its signatures; its effects, the checkpoint where the node states one. */
@@ -14,6 +14,34 @@ export class GraphqlFault extends Error {
14
14
  this.messages = messages;
15
15
  }
16
16
  }
17
+ /**
18
+ * The most bytes one objects request's body carries. Sui GraphQL's `maxQueryPayloadSize`, 5000 on the public testnet and
19
+ * mainnet endpoints, counts the whole body, variables included: about 26 references fit, and a wallet may pay gas with up
20
+ * to 256 coins. Under it, each request is far below `maxMultiGetSize` (200).
21
+ */
22
+ const OBJECTS_PAYLOAD_BYTES = 4800;
23
+ const OBJECTS_QUERY = `query($at: [ObjectKey!]!, $now: [ObjectKey!]!) { at: multiGetObjects(keys: $at) { version digest } now: multiGetObjects(keys: $now) { version } }`;
24
+ const objectsBody = (part) => ({
25
+ at: part.map((r) => ({ address: r.objectId, version: Number(r.version) })),
26
+ now: part.map((r) => ({ address: r.objectId })),
27
+ });
28
+ /** `refs` in order, in parts whose request body stays within `OBJECTS_PAYLOAD_BYTES`. */
29
+ function objectParts(refs) {
30
+ const parts = [];
31
+ let part = [];
32
+ for (const ref of refs) {
33
+ const next = [...part, ref];
34
+ if (part.length > 0 && JSON.stringify({ query: OBJECTS_QUERY, variables: objectsBody(next) }).length > OBJECTS_PAYLOAD_BYTES) {
35
+ parts.push(part);
36
+ part = [ref];
37
+ }
38
+ else
39
+ part = next;
40
+ }
41
+ if (part.length > 0)
42
+ parts.push(part);
43
+ return parts;
44
+ }
17
45
  const EFFECTS = `status checkpoint { sequenceNumber } balanceChangesJson
18
46
  gasEffects { gasSummary { computationCost storageCost storageRebate } }`;
19
47
  const LATEST = `checkpoint { sequenceNumber epoch { epochId referenceGasPrice } }`;
@@ -116,6 +144,38 @@ export function suiNode(network, url) {
116
144
  }
117
145
  return { executed, latest: latestOf(data) };
118
146
  },
147
+ async unavailable(refs, deadline) {
148
+ // A version past 2^53 - 1 is beyond the schema's UInt53: such a reference shows nothing.
149
+ const named = refs.filter((r) => r.version <= BigInt(Number.MAX_SAFE_INTEGER));
150
+ for (const part of objectParts(named)) {
151
+ // One request reads both lists from one view of the index: the version named, and the object's latest.
152
+ const data = await query(OBJECTS_QUERY, objectsBody(part), deadline);
153
+ const at = data["at"], now = data["now"];
154
+ if (!Array.isArray(at) || !Array.isArray(now) || at.length !== part.length || now.length !== part.length)
155
+ throw malformed("multiGetObjects");
156
+ for (const [k, ref] of part.entries()) {
157
+ const held = at[k], latest = now[k];
158
+ // A latest version past the one named is decisive alone: an object's version only increases, so the version
159
+ // named can never be taken, whether or not the index still holds it.
160
+ if (latest !== null) {
161
+ if (!isObject(latest))
162
+ throw malformed("object");
163
+ if (u53(latest["version"], "version") > ref.version)
164
+ return ref;
165
+ }
166
+ // The version named is not in the index (not yet, never or pruned): nothing more is shown.
167
+ if (held === null)
168
+ continue;
169
+ if (!isObject(held) || typeof held["digest"] !== "string")
170
+ throw malformed("object");
171
+ if (held["digest"] !== ref.digest)
172
+ return ref;
173
+ if (latest === null)
174
+ return ref;
175
+ }
176
+ }
177
+ return null;
178
+ },
119
179
  async simulate(bytes, deadline) {
120
180
  const data = await query(`query($t: JSON!) { simulateTransaction(transaction: $t, checksEnabled: true) { effects { ${EFFECTS} } } }`, { t: { bcs: { value: toBase64(bytes) } } }, deadline);
121
181
  const r = data["simulateTransaction"];
@@ -46,12 +46,16 @@ export function tonModule(c) {
46
46
  keep: { until: "lapse", at: ref.validUntil * 1000 },
47
47
  };
48
48
  },
49
+ /**
50
+ * lcp's read, made by the request the payment presents (`byRequest`): the payer's signed W5 request names it before
51
+ * anything is sent, by its body hash, so the read never settles on another payment of the payer under H.
52
+ */
49
53
  async read(p, at) {
50
54
  const ref = await checked(p);
51
55
  if (isRefusal(ref))
52
56
  return outcomeOf({ state: "unreadable", reason: "unparseable", foreign: [] });
53
57
  const search = at.search;
54
- return outcomeOf(await exactTvm.status(ref, c.reader, { act: "payment", finality: "finalized", ...(search === undefined ? {} : { search }) }));
58
+ return outcomeOf(await exactTvm.status({ ...ref, byRequest: true }, c.reader, { act: "payment", finality: "finalized", ...(search === undefined ? {} : { search }) }));
55
59
  },
56
60
  },
57
61
  fees: {
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { isRefusal } from "@integraledger/lcp";
15
15
  import { exactXrpl } from "@integraledger/lcp/x402-exact-xrpl";
16
+ import { compareDecimalStrings, getMaxLastLedgerSequence, isDecimalString, isIssuedCurrencyAmount, isValidDestinationTag } from "@x402/xrpl";
16
17
  import { ExactXrplScheme } from "@x402/xrpl/exact/facilitator";
17
18
  import { decode, deriveAddress, encodeForMultiSigning, verifyKeypairSignature } from "xrpl";
18
19
  import { isObject } from "../../answers.js";
@@ -136,10 +137,36 @@ function amountMatches(tx, r) {
136
137
  amount["value"] === r.amount);
137
138
  }
138
139
  /**
139
- * The checks of a multisigned payment that read the chain: the Payment's form against the requirements, as the class
140
- * makes them for a payment signed with one key; each signer's signature over the transaction's multisigning data with
141
- * its own key, a key that is its master key or its regular key; the payer's signer list met by those signers' weights;
142
- * its Sequence or ticket unconsumed; and the server's simulation. The payer, or the refusal.
140
+ * The `SendMax` rule the class makes of a payment signed with one key (`@x402/xrpl` 2.31.0, `verifyXrpAmount` and
141
+ * `verifyIouAmount`), with its reasons: none for XRP; for an issued currency, required, of the Amount's currency and
142
+ * issuer, and no less than the Amount, which the payer may spend to deliver it (a transfer fee). Undefined: it holds.
143
+ */
144
+ function sendMaxFailure(tx, r) {
145
+ const sendMax = tx["SendMax"];
146
+ if (r.asset === "XRP")
147
+ return sendMax === undefined ? undefined : "invalid_exact_xrpl_payload_sendmax_not_allowed";
148
+ const amount = tx["Amount"];
149
+ if (!isIssuedCurrencyAmount(sendMax) || !isIssuedCurrencyAmount(amount))
150
+ return "invalid_exact_xrpl_payload_sendmax_required";
151
+ if (sendMax.currency !== amount.currency || sendMax.issuer !== amount.issuer)
152
+ return "invalid_exact_xrpl_payload_sendmax_iou_mismatch";
153
+ // The class's comparison throws on a value that is no plain decimal, a negative one among them: refused as too low.
154
+ if (!isDecimalString(sendMax.value) || !isDecimalString(amount.value) || compareDecimalStrings(sendMax.value, amount.value) < 0) {
155
+ return "invalid_exact_xrpl_payload_sendmax_too_low";
156
+ }
157
+ return undefined;
158
+ }
159
+ /**
160
+ * The checks of a multisigned payment that read the chain, after lcp's reference of it: a `Payment` with an empty
161
+ * `SigningPubKey`; its `Destination`, `DestinationTag` and `Amount` against the requirements, the tag by the class's
162
+ * rule; `SendMax`, then `Paths`, `DeliverMin` and the partial-payment flag, by the class's rules and in its order; the
163
+ * fee against `maxFeeDrops`; each signer's signature over the transaction's multisigning data with its own key, a key
164
+ * that is its master key or its regular key; the payer's signer list met by those signers' weights; its
165
+ * LastLedgerSequence past the validated ledger and within the requirements' timeout, by the class's rule; its Sequence
166
+ * or ticket unconsumed; and the server's simulation. These are not every form check the class makes for a payment
167
+ * signed with one key: its NetworkID, InvoiceID and sequencing-field checks are not made here as the class makes
168
+ * them, so a payment that fails one is refused with another reason (lcp's reference, the ticket or sequence read, or
169
+ * the simulation). Nothing is submitted unless every check passes. The payer, or the refusal.
143
170
  */
144
171
  async function multisigChecks(c, node, payload, r) {
145
172
  const ref = await pure(c.network, payload, r);
@@ -153,13 +180,27 @@ async function multisigChecks(c, node, payload, r) {
153
180
  return { reason: "invalid_exact_xrpl_payload_signing_pub_key" };
154
181
  if (tx["Destination"] !== r.payTo)
155
182
  return { reason: "invalid_exact_xrpl_payload_destination_mismatch" };
183
+ // The class's destination-tag rule (`@x402/xrpl` 2.31.0, `verifyPaymentTransactionStructure`): where the requirements
184
+ // name a tag, it is a 32-bit unsigned integer and the Payment carries that tag; where they name none, any tag passes.
185
+ const tag = r.extra?.["destinationTag"];
186
+ if (tag !== undefined) {
187
+ if (!isValidDestinationTag(tag))
188
+ return { reason: "invalid_exact_xrpl_destination_tag_malformed" };
189
+ if (tx["DestinationTag"] !== tag)
190
+ return { reason: "invalid_exact_xrpl_payload_destination_tag_mismatch" };
191
+ }
156
192
  if (!amountMatches(tx, r))
157
193
  return { reason: "invalid_exact_xrpl_payload_amount_mismatch" };
194
+ const sendMax = sendMaxFailure(tx, r);
195
+ if (sendMax !== undefined)
196
+ return { reason: sendMax };
197
+ if (tx["Paths"] !== undefined)
198
+ return { reason: "invalid_exact_xrpl_payload_paths_not_allowed" };
199
+ if (tx["DeliverMin"] !== undefined)
200
+ return { reason: "invalid_exact_xrpl_payload_delivermin_not_allowed" };
201
+ // The class's order: SendMax, Paths, DeliverMin, then the partial-payment flag.
158
202
  if (((Number(tx["Flags"] ?? 0) >>> 0) & PARTIAL_PAYMENT) !== 0)
159
203
  return { reason: "invalid_exact_xrpl_payload_partial_payment_not_allowed" };
160
- if (tx["SendMax"] !== undefined || tx["Paths"] !== undefined || tx["DeliverMin"] !== undefined) {
161
- return { reason: "invalid_exact_xrpl_payload_paths_not_allowed" };
162
- }
163
204
  if (typeof tx["Fee"] !== "string" || BigInt(tx["Fee"]) > BigInt(c.maxFeeDrops ?? DEFAULT_MAX_FEE_DROPS)) {
164
205
  return { reason: "invalid_exact_xrpl_payload_fee_too_high" };
165
206
  }
@@ -184,21 +225,29 @@ async function multisigChecks(c, node, payload, r) {
184
225
  const data = encodeForMultiSigning(tx, who);
185
226
  if (!verifyKeypairSignature(data, sig, key))
186
227
  return { reason: "invalid_exact_xrpl_payload_signature" };
228
+ // rippled's rule for each signer: a key that is the signer's regular key, or its master key where the master key is
229
+ // not disabled; a signer with no account signs with its master key, the key its address derives from.
187
230
  const derived = deriveAddress(key);
231
+ const auth = await node.signerAuthorization(who);
188
232
  if (derived !== who) {
189
- const auth = await node.authorization(who);
190
- if (auth.regularKey !== derived)
233
+ if (auth === null || auth.regularKey !== derived)
191
234
  return { reason: "invalid_exact_xrpl_payload_signer_not_authorized" };
192
235
  }
193
- else if ((await node.authorization(who)).isMasterKeyDisabled) {
236
+ else if (auth !== null && auth.isMasterKeyDisabled) {
194
237
  return { reason: "invalid_exact_xrpl_payload_signer_not_authorized" };
195
238
  }
196
239
  weight += list.weights.get(who) ?? 0;
197
240
  }
198
241
  if (weight < list.quorum)
199
242
  return { reason: "invalid_exact_xrpl_payload_signer_not_authorized" };
200
- if ((await node.validatedLedger()) >= last)
243
+ // The class's rule for a payment signed with one key (`@x402/xrpl` 2.31.0, `verifyLedgerExpiry`), against the
244
+ // validated ledger: a LastLedgerSequence that ledger has reached has expired, and one past the ledgers the
245
+ // requirements' `maxTimeoutSeconds` spans, at the class's close time and tolerance, is too large.
246
+ const current = await node.validatedLedger();
247
+ if (last <= current)
201
248
  return { reason: "invalid_exact_xrpl_payload_expired" };
249
+ if (last > getMaxLastLedgerSequence(current, r))
250
+ return { reason: "invalid_exact_xrpl_payload_lastledgersequence_too_large" };
202
251
  const ticket = tx["TicketSequence"];
203
252
  if (typeof ticket === "number") {
204
253
  if (!(await node.ticket(account, ticket)))
@@ -11,6 +11,17 @@ export declare function xrplRpc(url: string, method: string, params: Record<stri
11
11
  export declare function xrplReader(network: XrplNetwork, url: string, deadline: number): XrplReader;
12
12
  /** The index of the server's latest validated ledger, its call ending by `deadline`. */
13
13
  export declare function validatedLedger(url: string, deadline: number): Promise<number>;
14
+ /**
15
+ * What a transaction's metadata shows of each payment channel it modified or deleted, by the channel's id in upper
16
+ * case: its `Balance`, the drops the channel has delivered to its destination, before the transaction and after it. A
17
+ * channel whose `Balance` the transaction left unchanged has no `PreviousFields.Balance`, and reads the same on both.
18
+ */
19
+ export type ChannelBalances = ReadonlyMap<string, {
20
+ readonly before: bigint;
21
+ readonly after: bigint;
22
+ }>;
23
+ /** The channel balances of a JSON (not binary) transaction answer's `meta`, as `ChannelBalances` states them. */
24
+ export declare function channelBalancesOf(meta: Record<string, unknown>): ChannelBalances;
14
25
  /** What the class and the own module read of the payer's account and the ledger, and how they submit. */
15
26
  export interface XrplNode {
16
27
  validatedLedger(): Promise<number>;
@@ -19,6 +30,14 @@ export interface XrplNode {
19
30
  regularKey?: string;
20
31
  isMasterKeyDisabled: boolean;
21
32
  }>;
33
+ /**
34
+ * A signer's account at the validated ledger as `authorization` reads it, or null where no such account exists: a
35
+ * signer list's entries need not be funded accounts, and such a signer signs with the key its address derives from.
36
+ */
37
+ signerAuthorization(account: string): Promise<{
38
+ regularKey?: string;
39
+ isMasterKeyDisabled: boolean;
40
+ } | null>;
22
41
  ticket(account: string, ticketSequence: number): Promise<boolean>;
23
42
  /** The account's signer list at the validated ledger: its quorum and each signer's weight, or none. */
24
43
  signerList(account: string): Promise<{
@@ -29,11 +48,15 @@ export interface XrplNode {
29
48
  engineResult: string;
30
49
  engineResultMessage?: string;
31
50
  }>;
32
- /** Submits the signed blob and waits up to `waitMs` for it in a validated ledger. */
51
+ /**
52
+ * Submits the signed blob and waits up to `waitMs` for it in a validated ledger; once validated, with the channel
53
+ * balances its metadata shows.
54
+ */
33
55
  submit(blob: string): Promise<{
34
56
  hash: string;
35
57
  validated: boolean;
36
58
  resultCode: string;
59
+ channels?: ChannelBalances;
37
60
  }>;
38
61
  /** The `PayChannel` ledger entry `id` names at the validated ledger, its fields as the server gives them, or none. */
39
62
  payChannel(id: string): Promise<Record<string, unknown> | null>;
@@ -42,10 +65,16 @@ export interface XrplNode {
42
65
  index: number;
43
66
  closeTime: number;
44
67
  }>;
45
- /** A transaction by its hash: whether a validated ledger holds it, and its result; none where the server holds none. */
68
+ /**
69
+ * A transaction by its hash: whether a validated ledger holds it, its result, the channel balances its metadata
70
+ * shows, and the `Balance` the transaction itself carries, where it carries one (a channel claim's); none where the
71
+ * server holds none.
72
+ */
46
73
  transaction(hash: string): Promise<{
47
74
  validated: boolean;
48
75
  resultCode: string;
76
+ channels?: ChannelBalances;
77
+ balance?: string;
49
78
  } | null>;
50
79
  }
51
80
  /** The node calls over the server at `url`, each bounded by the node bounds; a submission waits up to `waitMs`. */