@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
@@ -12,11 +12,41 @@ function failedOf(method, r) {
12
12
  throw new NodeError("malformed", true, `${method}: ${String(r["error"] ?? "an answer without its members")}`);
13
13
  }
14
14
  const int = (v) => (typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : undefined);
15
- /** A landed transaction from its binary `tx_blob` and `meta`. */
15
+ /**
16
+ * The first of `names` that `t` holds as a string. rippled names a binary answer's members by API version and by method:
17
+ * `tx` answers `tx` and `meta` on API version 1, `tx_blob` and `meta_blob` on version 2; `account_tx` answers `tx_blob`
18
+ * and `meta` on version 1, `tx_blob` and `meta_blob` on version 2 (rippled 3.1.3; xrpld 3.3.0).
19
+ */
20
+ const hexOf = (t, ...names) => names.map((n) => t[n]).find((v) => typeof v === "string");
21
+ /** A Payment's flag that lets it deliver less than its `Amount` (`tfPartialPayment`). */
22
+ const PARTIAL_PAYMENT = 0x00020000;
23
+ /**
24
+ * What a successful Payment delivered where its metadata names no amount: its `Amount`, unless it is a partial payment.
25
+ * A binary answer's metadata never holds `delivered_amount`, which rippled adds to a JSON answer only, and holds
26
+ * `DeliveredAmount` for a partial payment only; a Payment that is not partial delivers its `Amount` exactly or fails
27
+ * (xrpl.org, "Partial Payments", "The delivered_amount Field"). A partial payment with no `DeliveredAmount` names none.
28
+ */
29
+ function deliveredOf(blob, result) {
30
+ if (result !== "tesSUCCESS")
31
+ return undefined;
32
+ let tx;
33
+ try {
34
+ tx = decode(blob);
35
+ }
36
+ catch {
37
+ // A transaction the codec cannot decode names nothing delivered here; lcp reads its blob as it reads any other.
38
+ return undefined;
39
+ }
40
+ if (tx["TransactionType"] !== "Payment")
41
+ return undefined;
42
+ const flags = typeof tx["Flags"] === "number" ? tx["Flags"] : 0;
43
+ return (flags & PARTIAL_PAYMENT) === 0 ? tx["Amount"] : undefined;
44
+ }
45
+ /** A landed transaction from its binary transaction and metadata, in any of the forms rippled answers. */
16
46
  function landedOf(t, method) {
17
- const blob = t["tx_blob"];
18
- const metaHex = t["meta"];
19
- if (typeof blob !== "string" || typeof metaHex !== "string")
47
+ const blob = hexOf(t, "tx_blob", "tx");
48
+ const metaHex = hexOf(t, "meta_blob", "meta");
49
+ if (blob === undefined || metaHex === undefined)
20
50
  return failedOf(method, t);
21
51
  const meta = decode(metaHex);
22
52
  const result = meta["TransactionResult"];
@@ -33,7 +63,7 @@ function landedOf(t, method) {
33
63
  out.push(node["LedgerIndex"]);
34
64
  }
35
65
  }
36
- const delivered = meta["delivered_amount"] ?? meta["DeliveredAmount"];
66
+ const delivered = meta["delivered_amount"] ?? meta["DeliveredAmount"] ?? deliveredOf(blob, result);
37
67
  const index = int(t["ledger_index"]);
38
68
  const parent = meta["ParentBatchID"];
39
69
  return {
@@ -58,12 +88,12 @@ export function xrplReader(network, url, deadline) {
58
88
  const r = await call("server_info", {});
59
89
  const info = isObject(r["info"]) ? r["info"] : failedOf("server_info", r);
60
90
  const validated = isObject(info["validated_ledger"]) ? int(info["validated_ledger"]["seq"]) : undefined;
61
- const current = await call("ledger_current", {});
62
- const latest = int(current["ledger_current_index"]);
63
- if (validated === undefined || latest === undefined || typeof info["complete_ledgers"] !== "string")
91
+ if (validated === undefined || typeof info["complete_ledgers"] !== "string")
64
92
  return failedOf("server_info", r);
65
93
  const id = int(info["network_id"]);
66
- return { validated, latest, completeLedgers: info["complete_ledgers"], ...(id === undefined ? {} : { networkId: id }) };
94
+ // lcp's read takes `validated`: every search of `account_tx` ends there, since `account_tx` reads validated ledgers
95
+ // only.
96
+ return { validated, completeLedgers: info["complete_ledgers"], ...(id === undefined ? {} : { networkId: id }) };
67
97
  },
68
98
  async tx(hash, range) {
69
99
  const r = await call("tx", { transaction: hash, binary: true, ...(range ? { min_ledger: range.min, max_ledger: range.max } : {}) });
@@ -71,6 +101,11 @@ export function xrplReader(network, url, deadline) {
71
101
  return { notFound: true, searchedAll: r["searched_all"] === true };
72
102
  if (r["error"] !== undefined)
73
103
  return failedOf("tx", r);
104
+ // A transaction the server knows that no validated ledger holds, answered with no metadata: a submission rippled
105
+ // refused and keeps in its cache (`tefPAST_SEQ`, `tefMAX_LEDGER`), or one no closed ledger holds yet. lcp's reader
106
+ // contract reads it as not found, its search not whole.
107
+ if (r["validated"] !== true && hexOf(r, "meta_blob", "meta") === undefined)
108
+ return { notFound: true, searchedAll: false };
74
109
  return landedOf({ ...r, hash: r["hash"] ?? hash }, "tx");
75
110
  },
76
111
  async accountTx(account, range, marker) {
@@ -127,6 +162,32 @@ export async function validatedLedger(url, deadline) {
127
162
  }
128
163
  /** The account's flag that disables its master key (`lsfDisableMaster`). */
129
164
  const DISABLE_MASTER = 0x00100000;
165
+ /** An account's regular key and whether its master key is disabled, from its `account_data`. */
166
+ function authorizationOf(data) {
167
+ const flags = int(data["Flags"]) ?? 0;
168
+ return {
169
+ ...(typeof data["RegularKey"] === "string" ? { regularKey: data["RegularKey"] } : {}),
170
+ isMasterKeyDisabled: (flags & DISABLE_MASTER) !== 0,
171
+ };
172
+ }
173
+ const DROPS = /^[0-9]{1,19}$/;
174
+ /** The channel balances of a JSON (not binary) transaction answer's `meta`, as `ChannelBalances` states them. */
175
+ export function channelBalancesOf(meta) {
176
+ const out = new Map();
177
+ for (const n of Array.isArray(meta["AffectedNodes"]) ? meta["AffectedNodes"] : []) {
178
+ if (!isObject(n))
179
+ continue;
180
+ const node = isObject(n["ModifiedNode"]) ? n["ModifiedNode"] : isObject(n["DeletedNode"]) ? n["DeletedNode"] : undefined;
181
+ if (node === undefined || node["LedgerEntryType"] !== "PayChannel" || typeof node["LedgerIndex"] !== "string")
182
+ continue;
183
+ const final = isObject(node["FinalFields"]) ? node["FinalFields"]["Balance"] : undefined;
184
+ const previous = isObject(node["PreviousFields"]) ? (node["PreviousFields"]["Balance"] ?? final) : final;
185
+ if (typeof final !== "string" || typeof previous !== "string" || !DROPS.test(final) || !DROPS.test(previous))
186
+ continue;
187
+ out.set(node["LedgerIndex"].toUpperCase(), { before: BigInt(previous), after: BigInt(final) });
188
+ }
189
+ return out;
190
+ }
130
191
  /** The node calls over the server at `url`, each bounded by the node bounds; a submission waits up to `waitMs`. */
131
192
  export function xrplNode(url, waitMs) {
132
193
  const call = (method, params) => xrplRpc(url, method, params, performance.now() + 5_000);
@@ -143,12 +204,13 @@ export function xrplNode(url, waitMs) {
143
204
  return int((await accountData(account, "current"))["Sequence"]) ?? failedOf("account_info", {});
144
205
  },
145
206
  async authorization(account) {
146
- const data = await accountData(account, "validated");
147
- const flags = int(data["Flags"]) ?? 0;
148
- return {
149
- ...(typeof data["RegularKey"] === "string" ? { regularKey: data["RegularKey"] } : {}),
150
- isMasterKeyDisabled: (flags & DISABLE_MASTER) !== 0,
151
- };
207
+ return authorizationOf(await accountData(account, "validated"));
208
+ },
209
+ async signerAuthorization(account) {
210
+ const r = await call("account_info", { account, ledger_index: "validated" });
211
+ if (r["error"] === "actNotFound")
212
+ return null;
213
+ return authorizationOf(isObject(r["account_data"]) ? r["account_data"] : failedOf("account_info", r));
152
214
  },
153
215
  async ticket(account, ticketSequence) {
154
216
  const r = await call("ledger_entry", { ticket: { account, ticket_seq: ticketSequence }, ledger_index: "validated" });
@@ -210,7 +272,16 @@ export function xrplNode(url, waitMs) {
210
272
  const meta = r["meta"];
211
273
  if (!isObject(meta) || typeof meta["TransactionResult"] !== "string")
212
274
  return { validated: false, resultCode: "" };
213
- return { validated: r["validated"] === true, resultCode: meta["TransactionResult"] };
275
+ // The transaction's fields: at the answer's top level on API version 1, which a request naming no `api_version`
276
+ // gets, and in `tx_json` on version 2.
277
+ const tx = isObject(r["tx_json"]) ? r["tx_json"] : r;
278
+ const balance = typeof tx["Balance"] === "string" ? tx["Balance"] : undefined;
279
+ return {
280
+ validated: r["validated"] === true,
281
+ resultCode: meta["TransactionResult"],
282
+ channels: channelBalancesOf(meta),
283
+ ...(balance === undefined ? {} : { balance }),
284
+ };
214
285
  },
215
286
  async submit(blob) {
216
287
  const sent = await call("submit", { tx_blob: blob });
@@ -220,7 +291,7 @@ export function xrplNode(url, waitMs) {
220
291
  for (;;) {
221
292
  const r = await call("tx", { transaction: hash });
222
293
  if (r["validated"] === true && isObject(r["meta"]) && typeof r["meta"]["TransactionResult"] === "string") {
223
- return { hash, validated: true, resultCode: r["meta"]["TransactionResult"] };
294
+ return { hash, validated: true, resultCode: r["meta"]["TransactionResult"], channels: channelBalancesOf(r["meta"]) };
224
295
  }
225
296
  if (performance.now() + 1_000 > until)
226
297
  return { hash, validated: false, resultCode: engine };
@@ -5,8 +5,10 @@
5
5
  * and of that claim, and refuses a payload carrying `settlementTransaction`. At `/settle` the resource server adds
6
6
  * `settlementTransaction`, a `PaymentChannelClaim` its `payTo` key signed for the actual charge with `tfClose`; the
7
7
  * module's checks before it submits (`phaseOf` the context: `settle`) and its settle check it against the payment and
8
- * the channel, and the settle submits it unchanged and waits for it in a validated ledger. The module holds no key and
9
- * pays no fee (`extra.key` `none`).
8
+ * the channel, and the settle submits it unchanged and waits for it in a validated ledger. A validated `tesSUCCESS` is a
9
+ * success only where the claim's metadata shows the channel's `Balance` at or above the charge: rippled closes a channel
10
+ * that has expired by the ledger the claim lands in without delivering, and still answers `tesSUCCESS`. The module holds
11
+ * no key and pays no fee (`extra.key` `none`).
10
12
  *
11
13
  * The record names the payment by its channel, which one claim closes: one row per channel, as the scheme's
12
14
  * duplicate-settlement rule keys it. Nothing the payer signs carries H, and lcp reads the channel's create, the
@@ -15,7 +17,7 @@
15
17
  */
16
18
  import { isRefusal } from "@integraledger/lcp";
17
19
  import { uptoXrpl } from "@integraledger/lcp/x402-upto-xrpl";
18
- import { decode, deriveAddress, encodeForSigning, encodeForSigningClaim, verifyKeypairSignature } from "xrpl";
20
+ import { decode, deriveAddress, encodeForSigning, encodeForSigningClaim, hashes, verifyKeypairSignature } from "xrpl";
19
21
  import { isObject } from "../../answers.js";
20
22
  import { outcomeOf, phaseOf } from "../../module.js";
21
23
  /** The scheme's landing margin, in seconds: two ledger closes at a pessimistic 10-second rate. */
@@ -28,6 +30,12 @@ const TF_CLOSE = 0x00020000;
28
30
  const TF_RENEW = 0x00010000;
29
31
  /** The largest network id that carries no `NetworkID` field. */
30
32
  const LEGACY_NETWORK_ID = 1024;
33
+ /**
34
+ * The settle-time charge in canonical drops (the scheme's `amount`, a string): zero, or a positive decimal with no sign, space or
35
+ * leading zero, below 10^17 as lcp holds an option's amount. `BigInt` reads `""`, `" 0"` and `"0x0"` as zero, so the
36
+ * form is checked before the charge is read, and before anything is submitted.
37
+ */
38
+ const CHARGE = /^(0|[1-9][0-9]{0,16})$/;
31
39
  /** The x402 reason for one of lcp's refusals: the version, the option, or else the payload. */
32
40
  function reasonOf(r) {
33
41
  if (r.code === "x402/not-v2")
@@ -37,20 +45,24 @@ function reasonOf(r) {
37
45
  return "invalid_payload";
38
46
  }
39
47
  /**
40
- * The requirements the payment's `accepted` must equal: at `/verify` the requirements as given; with a settlement
41
- * transaction, the settle-time requirements with `payload.maxAmount` for `amount`, as the scheme's re-verification
42
- * makes them.
48
+ * The requirements the payment's `accepted` must equal: at `/verify` the requirements as given; at `/settle`
49
+ * (`settling`), or with a settlement transaction, the settle-time requirements with `payload.maxAmount` for `amount`, as
50
+ * the scheme's re-verification makes them. A `/settle` that carries no settlement transaction is held to the same terms
51
+ * as one that does, so that it reaches the scheme's `invalid_upto_xrpl_missing_settlement_transaction` at any charge.
43
52
  */
44
- function termsOf(payload, r) {
45
- const settling = typeof payload.payload["settlementTransaction"] === "string";
53
+ function termsOf(payload, r, settling) {
54
+ const relaxed = settling || typeof payload.payload["settlementTransaction"] === "string";
46
55
  const max = payload.payload["maxAmount"];
47
- return settling && typeof max === "string" ? { ...r, amount: max } : r;
56
+ return relaxed && typeof max === "string" ? { ...r, amount: max } : r;
48
57
  }
49
- /** The checks that read neither the chain nor the clock: the network, then lcp's checks of the payment and its option. */
50
- async function pure(network, payload, r) {
58
+ /**
59
+ * The checks that read neither the chain nor the clock: the network, then lcp's checks of the payment and its option,
60
+ * against `termsOf` the phase.
61
+ */
62
+ async function pure(network, payload, r, settling) {
51
63
  if (r.network !== network || payload.accepted?.network !== network)
52
64
  return { reason: "invalid_network" };
53
- const ref = await uptoXrpl.reference(payload, termsOf(payload, r));
65
+ const ref = await uptoXrpl.reference(payload, termsOf(payload, r, settling));
54
66
  if (isRefusal(ref))
55
67
  return { reason: reasonOf(ref), code: ref.code };
56
68
  const p = payload.payload;
@@ -72,6 +84,18 @@ async function pure(network, payload, r) {
72
84
  };
73
85
  }
74
86
  const isPresented = (v) => !("reason" in v);
87
+ /**
88
+ * The pure checks as the record holds a payment, which carries no phase: the payment under either phase's terms, the
89
+ * `/verify` terms first and their refusal where neither holds. The instrument is the channel, whatever the charge;
90
+ * the facilitator's checks then hold the payment to its own phase's terms.
91
+ */
92
+ async function held(network, payload, r) {
93
+ const strict = await pure(network, payload, r, false);
94
+ if (isPresented(strict))
95
+ return strict;
96
+ const relaxed = await pure(network, payload, r, true);
97
+ return isPresented(relaxed) ? relaxed : strict;
98
+ }
75
99
  const same = (a, b) => typeof a === "string" && typeof b === "string" && a.toUpperCase() === b.toUpperCase();
76
100
  const int = (v) => (typeof v === "number" && Number.isSafeInteger(v) ? v : undefined);
77
101
  /**
@@ -116,6 +140,8 @@ async function channelChecks(node, p, r, settling) {
116
140
  return { reason: "invalid_upto_xrpl_payload_not_yet_valid" };
117
141
  }
118
142
  else {
143
+ // The scheme's settle-time headroom, against the validated ledger: an admission floor, not a landing guarantee (rule
144
+ // 7). The ledger the claim lands in is not yet closed; what it did is read from the claim's metadata (`deliveredOf`).
119
145
  if (cancelAfter !== undefined && cancelAfter < closeTime + MARGIN_S)
120
146
  return { reason: "invalid_upto_xrpl_payload_channel_expiring" };
121
147
  if (expiration !== undefined && expiration < closeTime + MARGIN_S)
@@ -178,14 +204,55 @@ async function settlementChecks(node, network, p, r, channel, ledger) {
178
204
  }
179
205
  return undefined;
180
206
  }
207
+ /**
208
+ * What a claim in a validated ledger with `tesSUCCESS` delivered, by its metadata (`channels`), against the charge: the
209
+ * channel's `Balance` after it at or above the charge, which a claim reaches by delivering its `Balance` less what the
210
+ * channel already carried, and a bare close finds already reached; or the shortfall. A charge of zero asks nothing. A
211
+ * claim applied to a channel that expired by the ledger it lands in, by `CancelAfter` or by the payer's requested close
212
+ * (`Expiration`), closes the channel delivering nothing and still answers `tesSUCCESS`: the metadata, not the result
213
+ * code nor the settle-time headroom check, is what the landing ledger did. Metadata that shows no node of the channel,
214
+ * which a claim landing with `tesSUCCESS` always modifies or deletes, does not show what the claim did: that is
215
+ * `unread`, never a shortfall, since an answer the module cannot read is no evidence that nothing was delivered. A
216
+ * charge that is not canonical drops (`CHARGE`) is `unread` too: no delivery can be judged against it.
217
+ */
218
+ function deliveredOf(channels, channelId, charge) {
219
+ if (typeof charge !== "string" || !CHARGE.test(charge))
220
+ return { unread: `the charge ${JSON.stringify(charge)} is not a number of drops` };
221
+ if (BigInt(charge) === 0n)
222
+ return { delivered: true };
223
+ const c = channels?.get(channelId.toUpperCase());
224
+ if (c === undefined)
225
+ return { unread: `the transaction's metadata shows no node of channel ${channelId}` };
226
+ if (c.after >= BigInt(charge))
227
+ return { delivered: true };
228
+ return { delivered: false, message: `the channel's Balance is ${c.after} drops after the claim (${c.after - c.before} delivered by it), below the charge of ${charge}` };
229
+ }
230
+ /**
231
+ * The charge the claim the record holds was sent for, against which its delivery is judged, whoever presents the
232
+ * payment next: the `Balance` the claim carries, which the settlement checks hold equal to the settle-time charge. A
233
+ * bare close carries none: it is sent only for a charge of zero or one the channel had already delivered, which closing
234
+ * takes nothing back from, so its charge is met by the `Balance` the channel carried before it. Where the metadata
235
+ * shows no node of the channel, `charge`, the presented requirements' amount: such a claim reads as unread at any
236
+ * charge above zero, and at one that is not canonical drops.
237
+ */
238
+ function chargeOf(t, channelId, charge) {
239
+ if (t.balance !== undefined)
240
+ return t.balance;
241
+ const c = t.channels?.get(channelId.toUpperCase());
242
+ return c === undefined ? charge : String(c.before);
243
+ }
181
244
  function verifyFailure(f, payer) {
182
245
  return { isValid: false, invalidReason: f.reason, ...(f.code ? { invalidMessage: f.code } : {}), ...(payer ? { payer } : {}) };
183
246
  }
184
247
  /** The settler's own `upto` facilitator over the seller's server. */
185
248
  function uptoFacilitator(network, node) {
186
- /** The scheme's checks at `/verify`, or at `/settle` (`settling`), where the settlement transaction is the server's. */
249
+ /**
250
+ * The scheme's checks at `/verify`, or at `/settle` (`settling`), where the settlement transaction is the server's and
251
+ * the requirements' `amount` the charge, refused `invalid_payment_requirements` (`x402/option-malformed`) where it is
252
+ * not a string of `CHARGE`'s canonical drops, before the node is read.
253
+ */
187
254
  const checked = async (payload, r, settling) => {
188
- const p = await pure(network, payload, r);
255
+ const p = await pure(network, payload, r, settling);
189
256
  if (!isPresented(p))
190
257
  return p;
191
258
  if (!settling && p.settlementTransaction !== undefined) {
@@ -194,6 +261,8 @@ function uptoFacilitator(network, node) {
194
261
  if (settling && p.settlementTransaction === undefined) {
195
262
  return { reason: "invalid_upto_xrpl_missing_settlement_transaction", payer: p.payer };
196
263
  }
264
+ if (settling && (typeof r.amount !== "string" || !CHARGE.test(r.amount)))
265
+ return { reason: "invalid_payment_requirements", code: "x402/option-malformed", payer: p.payer };
197
266
  const c = await channelChecks(node, p, r, settling);
198
267
  if ("reason" in c)
199
268
  return { ...c, payer: p.payer };
@@ -221,8 +290,14 @@ function uptoFacilitator(network, node) {
221
290
  return { success: false, errorReason: p.reason, ...(p.code ? { errorMessage: p.code } : {}), transaction: "", network: n, ...(payer ? { payer } : {}) };
222
291
  }
223
292
  const sent = await node.submit(p.settlementTransaction);
224
- if (sent.validated && sent.resultCode === "tesSUCCESS")
225
- return { success: true, transaction: sent.hash, network: n, payer: p.payer, amount: r.amount };
293
+ if (sent.validated && sent.resultCode === "tesSUCCESS") {
294
+ const d = deliveredOf(sent.channels, p.channelId, r.amount);
295
+ if ("unread" in d)
296
+ return { success: false, errorReason: "settlement_pending", errorMessage: d.unread, transaction: sent.hash, network: n, payer: p.payer };
297
+ if (d.delivered)
298
+ return { success: true, transaction: sent.hash, network: n, payer: p.payer, amount: r.amount };
299
+ return { success: false, errorReason: "transaction_failed", errorMessage: d.message, transaction: sent.hash, network: n, payer: p.payer };
300
+ }
226
301
  if (!sent.validated)
227
302
  return { success: false, errorReason: "settlement_pending", transaction: sent.hash, network: n, payer: p.payer };
228
303
  return { success: false, errorReason: `transaction_failed: ${sent.resultCode}`, transaction: sent.hash, network: n, payer: p.payer };
@@ -239,7 +314,7 @@ export function uptoModule(network, node) {
239
314
  facilitator: uptoFacilitator(network, node),
240
315
  record: {
241
316
  async instrument(p) {
242
- const r = await pure(network, p.payload, p.requirements);
317
+ const r = await held(network, p.payload, p.requirements);
243
318
  if (!isPresented(r))
244
319
  return { refused: r.reason };
245
320
  return {
@@ -250,7 +325,7 @@ export function uptoModule(network, node) {
250
325
  keep: { until: "settler" },
251
326
  };
252
327
  },
253
- async read(_p, at) {
328
+ async read(p, at) {
254
329
  // lcp reads the channel's create, the payer's act, and no claim; the claim the record holds is read by its hash.
255
330
  if (at.transaction === undefined)
256
331
  return outcomeOf({ state: "pending", reason: "not-found", foreign: [] });
@@ -258,7 +333,18 @@ export function uptoModule(network, node) {
258
333
  if (t === null || !t.validated)
259
334
  return outcomeOf({ state: "pending", reason: "not-found", foreign: [] });
260
335
  if (t.resultCode === "tesSUCCESS") {
261
- return outcomeOf({ state: "settled", transaction: at.transaction, finality: "validated", presented: "yes", foreign: [] });
336
+ const r = await held(network, p.payload, p.requirements);
337
+ const d = isPresented(r) ? deliveredOf(t.channels, r.channelId, chargeOf(t, r.channelId, p.requirements.amount)) : undefined;
338
+ // Metadata that shows no node of the channel is unreadable: an error is never an absence of delivery.
339
+ if (d !== undefined && "unread" in d)
340
+ return outcomeOf({ state: "unreadable", reason: "unparseable", foreign: [] });
341
+ if (isPresented(r) && d !== undefined && "delivered" in d && d.delivered) {
342
+ // Settled by the claim the record holds; this call presents that claim only where it carries the same one.
343
+ const mine = r.settlementTransaction !== undefined && same(hashes.hashSignedTx(r.settlementTransaction), at.transaction);
344
+ return outcomeOf({ state: "settled", transaction: at.transaction, finality: "validated", presented: mine ? "yes" : "no", foreign: [] });
345
+ }
346
+ // A claim that closed the channel short of the charge: the channel is gone, and nothing can deliver it now.
347
+ return outcomeOf({ state: "failed", reason: "transaction-failed", transaction: at.transaction, foreign: [] });
262
348
  }
263
349
  // A claim that failed in a validated ledger consumed nothing: the channel stays open to another claim.
264
350
  return outcomeOf({ state: "pending", reason: "instrument-live", transaction: at.transaction, foreign: [] });
package/dist/record.d.ts CHANGED
@@ -15,7 +15,7 @@ export declare function answerReserve(settleWaitMs: number): number;
15
15
  export declare function inTime<T>(p: Promise<T>, deadline: number): Promise<T>;
16
16
  /** How long a final row is kept past its form's lapse or life: a day, as the settler has kept one since its first release. */
17
17
  export declare const KEEP_AFTER_MS: number;
18
- export declare const RECORD_SCHEMA = "CREATE TABLE IF NOT EXISTS instrument (\n network text NOT NULL,\n key text NOT NULL,\n pairing text NOT NULL,\n claimed bigint NOT NULL,\n held_until bigint NOT NULL,\n final boolean NOT NULL DEFAULT false,\n outcome text,\n answer jsonb,\n transaction text,\n sent text[] NOT NULL DEFAULT '{}',\n body text,\n payer text,\n search jsonb,\n since jsonb,\n keep_until bigint,\n PRIMARY KEY (network, key)\n);\nCREATE INDEX IF NOT EXISTS instrument_final_keep ON instrument (keep_until) WHERE final AND keep_until IS NOT NULL;\nCREATE TABLE IF NOT EXISTS fee (\n network text NOT NULL,\n transaction text NOT NULL,\n at bigint NOT NULL,\n fee numeric(78, 0) NOT NULL,\n included boolean NOT NULL,\n PRIMARY KEY (network, transaction)\n);\nCREATE INDEX IF NOT EXISTS fee_at ON fee (network, at);\nCREATE TABLE IF NOT EXISTS module_state (\n module text NOT NULL,\n key text NOT NULL,\n value jsonb NOT NULL,\n PRIMARY KEY (module, key)\n)";
18
+ export declare const RECORD_SCHEMA = "CREATE TABLE IF NOT EXISTS instrument (\n network text NOT NULL,\n key text NOT NULL,\n pairing text NOT NULL,\n claimed bigint NOT NULL,\n held_until bigint NOT NULL,\n final boolean NOT NULL DEFAULT false,\n outcome text,\n answer jsonb,\n transaction text,\n sent text[] NOT NULL DEFAULT '{}',\n body text,\n payer text,\n search jsonb,\n since jsonb,\n keep_until bigint,\n submitted boolean NOT NULL DEFAULT false,\n fence bigint NOT NULL DEFAULT 1,\n PRIMARY KEY (network, key)\n);\nCREATE INDEX IF NOT EXISTS instrument_final_keep ON instrument (keep_until) WHERE final AND keep_until IS NOT NULL;\nCREATE TABLE IF NOT EXISTS fee (\n network text NOT NULL,\n transaction text NOT NULL,\n at bigint NOT NULL,\n fee numeric(78, 0) NOT NULL,\n included boolean NOT NULL,\n PRIMARY KEY (network, transaction)\n);\nCREATE INDEX IF NOT EXISTS fee_at ON fee (network, at);\nCREATE TABLE IF NOT EXISTS module_state (\n module text NOT NULL,\n key text NOT NULL,\n value jsonb NOT NULL,\n PRIMARY KEY (module, key)\n)";
19
19
  /** A JSON value with each `bigint` written as `{"$bigint": "<decimal>"}`, so that it survives the store. */
20
20
  export declare function toStored(value: unknown): unknown;
21
21
  /** A stored JSON value, with each `{"$bigint": "<decimal>"}` read back as a `bigint`. */
@@ -40,7 +40,10 @@ export interface Row {
40
40
  readonly final: boolean;
41
41
  /** For a final row: `settled`, or the reason of lcp's `failed` answer that made it final. */
42
42
  readonly outcome?: string;
43
- /** For a final row: the answer as first given. */
43
+ /**
44
+ * For a final row: the answer as first given. For a row that is not final: the success given on a receipt whose block
45
+ * the chain had not yet shown final (`answered`), which the row's next final read either confirms or replaces.
46
+ */
44
47
  readonly answer?: Record<string, unknown>;
45
48
  /** The transaction the row names: the last one the settler's submissions named, or the one a read found. */
46
49
  readonly transaction?: string;
@@ -56,6 +59,17 @@ export interface Row {
56
59
  readonly search?: unknown;
57
60
  /** The chain's position the module read just before the claim, from which its reads search. */
58
61
  readonly since?: unknown;
62
+ /**
63
+ * Whether a settle holding the claim gave the payment to the class's settle, which may have sent it although no
64
+ * answer naming a transaction came back (the answer lost, or the settler stopped before it).
65
+ */
66
+ readonly submitted: boolean;
67
+ /**
68
+ * The claim's fencing number: 1 for the settle that claimed the row, one more for each settle that took it again
69
+ * since. Only the settle holding the latest one may name a transaction for the claim (`naming`), take back one it
70
+ * named (`unsent`), or end the hold (`release`).
71
+ */
72
+ readonly fence: number;
59
73
  }
60
74
  /** What makes a row final. */
61
75
  export interface Finish {
@@ -81,22 +95,52 @@ export interface InstrumentRecord {
81
95
  holdMs: number;
82
96
  }): Promise<boolean>;
83
97
  /**
84
- * Takes a claim that is not final and whose hold has ended, until `now + holdMs`: the row as this call took it, or
85
- * undefined where it did not take it.
98
+ * Takes a claim that is not final and whose hold has ended, until `now + holdMs`, with the next fencing number: the
99
+ * row as this call took it, or undefined where it did not take it.
86
100
  */
87
101
  retake(network: string, key: string, now: number, holdMs: number): Promise<Row | undefined>;
88
102
  /** Adds a transaction the settler's submission named to a claim that is not final, as the one the row names. */
89
103
  sent(network: string, key: string, transaction: string): Promise<void>;
90
- /** Ends this call's hold of a claim that is not final, keeping the search position of its read. */
91
- release(network: string, key: string, learnt: {
104
+ /**
105
+ * Takes back from a claim that is not final a transaction a module named before it sent it and then did not send:
106
+ * out of `sent`, and, where the row names it, the row names the last one left, or none. It writes only where the
107
+ * row's fencing number is still `fence`, the one the calling settle took the claim with: true where it wrote, false
108
+ * where the row is final or another settle took the claim since, whose names it never takes back.
109
+ */
110
+ unsent(network: string, key: string, fence: number, transaction: string): Promise<boolean>;
111
+ /**
112
+ * Adds a transaction about to be sent to a claim that is not final, as the one the row names, in one statement that
113
+ * writes only where the row's fencing number is still `fence`: false, and nothing written, where the row is final or
114
+ * another settle took it since. Called before the transaction leaves the settler, so that nothing is sent for a claim
115
+ * whose hold another settle took.
116
+ */
117
+ naming(network: string, key: string, fence: number, transaction: string): Promise<boolean>;
118
+ /**
119
+ * Keeps a success the class answered on a receipt whose block is not yet shown final in a claim that is not final:
120
+ * `transaction` as the one the row names, `answer` as the success given, and ends the hold, so that the next settle
121
+ * reads the chain. It writes only where the row's fencing number is still `fence`: true where it wrote, false where the
122
+ * row is final or another settle took the claim since.
123
+ */
124
+ answered(network: string, key: string, fence: number, transaction: string, answer: Record<string, unknown>, payer?: string, keepUntil?: number | null): Promise<boolean>;
125
+ /** Marks a claim that is not final as given to the class's settle; it stays marked. */
126
+ submitting(network: string, key: string): Promise<void>;
127
+ /**
128
+ * Ends this call's hold of a claim that is not final, keeping the search position of its read. It writes only where
129
+ * the row's fencing number is still `fence`, the one this call took the claim with: true where it wrote, false where
130
+ * the row is final or another settle took the claim since, whose hold it never ends.
131
+ */
132
+ release(network: string, key: string, fence: number, learnt: {
92
133
  search?: unknown;
93
- }): Promise<void>;
134
+ }): Promise<boolean>;
94
135
  /**
95
136
  * Makes the row final with `f.answer`, unless it is final already; a row the record does not hold is inserted final.
96
137
  * True where this call made it final: the one call whose answer is the row's.
97
138
  */
98
139
  finish(network: string, key: string, f: Finish): Promise<boolean>;
99
- /** Drops the final rows kept past `KEEP_AFTER_MS` after their keep, and the fees older than `feesBefore`. */
140
+ /**
141
+ * Drops the final rows, and the open rows holding a success given at the head, kept past `KEEP_AFTER_MS` after their
142
+ * keep, and the fees older than `feesBefore`.
143
+ */
100
144
  sweep(now: number, feesBefore: number): Promise<void>;
101
145
  }
102
146
  /** The record over `pool`, its tables created. */
package/dist/record.js CHANGED
@@ -59,6 +59,8 @@ export const RECORD_SCHEMA = `CREATE TABLE IF NOT EXISTS instrument (
59
59
  search jsonb,
60
60
  since jsonb,
61
61
  keep_until bigint,
62
+ submitted boolean NOT NULL DEFAULT false,
63
+ fence bigint NOT NULL DEFAULT 1,
62
64
  PRIMARY KEY (network, key)
63
65
  );
64
66
  CREATE INDEX IF NOT EXISTS instrument_final_keep ON instrument (keep_until) WHERE final AND keep_until IS NOT NULL;
@@ -135,10 +137,12 @@ function rowOf(r) {
135
137
  ...(r.payer === null ? {} : { payer: r.payer }),
136
138
  ...(r.search === null || r.search === undefined ? {} : { search: fromStored(r.search) }),
137
139
  ...(r.since === null || r.since === undefined ? {} : { since: fromStored(r.since) }),
140
+ submitted: r.submitted,
141
+ fence: Number(r.fence),
138
142
  };
139
143
  }
140
144
  /** The columns of a row, as `rowOf` reads them. */
141
- const COLUMNS = "pairing, claimed, held_until, final, outcome, answer, transaction, sent, body, payer, search, since";
145
+ const COLUMNS = "pairing, claimed, held_until, final, outcome, answer, transaction, sent, body, payer, search, since, submitted, fence";
142
146
  /** The record over `pool`, its tables created. */
143
147
  export async function openRecord(pool) {
144
148
  await pool.query(RECORD_SCHEMA);
@@ -164,7 +168,8 @@ export async function openRecord(pool) {
164
168
  return r.rowCount === 1;
165
169
  },
166
170
  async retake(network, key, now, holdMs) {
167
- const r = await pool.query(`UPDATE instrument SET held_until = $4 WHERE network = $1 AND key = $2 AND NOT final AND held_until <= $3
171
+ const r = await pool.query(`UPDATE instrument SET held_until = $4, fence = fence + 1
172
+ WHERE network = $1 AND key = $2 AND NOT final AND held_until <= $3
168
173
  RETURNING ${COLUMNS}`, [network, key, now, now + holdMs]);
169
174
  return r.rows[0] === undefined ? undefined : rowOf(r.rows[0]);
170
175
  },
@@ -173,8 +178,33 @@ export async function openRecord(pool) {
173
178
  sent = CASE WHEN $3 = ANY(sent) THEN sent ELSE array_append(sent, $3::text) END
174
179
  WHERE network = $1 AND key = $2 AND NOT final`, [network, key, transaction]);
175
180
  },
176
- async release(network, key, learnt) {
177
- await pool.query(`UPDATE instrument SET held_until = 0, search = COALESCE($3, search) WHERE network = $1 AND key = $2 AND NOT final`, [network, key, learnt.search === undefined ? null : JSON.stringify(toStored(learnt.search))]);
181
+ async unsent(network, key, fence, transaction) {
182
+ const r = await pool.query(`UPDATE instrument SET sent = array_remove(sent, $4::text),
183
+ transaction = CASE WHEN transaction = $4 THEN (array_remove(sent, $4::text))[cardinality(array_remove(sent, $4::text))]
184
+ ELSE transaction END
185
+ WHERE network = $1 AND key = $2 AND NOT final AND fence = $3`, [network, key, fence, transaction]);
186
+ return r.rowCount === 1;
187
+ },
188
+ async naming(network, key, fence, transaction) {
189
+ const r = await pool.query(`UPDATE instrument SET transaction = $4,
190
+ sent = CASE WHEN $4 = ANY(sent) THEN sent ELSE array_append(sent, $4::text) END
191
+ WHERE network = $1 AND key = $2 AND NOT final AND fence = $3`, [network, key, fence, transaction]);
192
+ return r.rowCount === 1;
193
+ },
194
+ async answered(network, key, fence, transaction, answer, payer, keep) {
195
+ const r = await pool.query(`UPDATE instrument SET transaction = $4,
196
+ sent = CASE WHEN $4 = ANY(sent) THEN sent ELSE array_append(sent, $4::text) END,
197
+ answer = $5, payer = COALESCE(payer, $6), held_until = 0, keep_until = $7
198
+ WHERE network = $1 AND key = $2 AND NOT final AND fence = $3`, [network, key, fence, transaction, JSON.stringify(answer), payer ?? null, keep ?? null]);
199
+ return r.rowCount === 1;
200
+ },
201
+ async submitting(network, key) {
202
+ await pool.query(`UPDATE instrument SET submitted = true WHERE network = $1 AND key = $2 AND NOT final`, [network, key]);
203
+ },
204
+ async release(network, key, fence, learnt) {
205
+ const r = await pool.query(`UPDATE instrument SET held_until = 0, search = COALESCE($4, search)
206
+ WHERE network = $1 AND key = $2 AND NOT final AND fence = $3`, [network, key, fence, learnt.search === undefined ? null : JSON.stringify(toStored(learnt.search))]);
207
+ return r.rowCount === 1;
178
208
  },
179
209
  async finish(network, key, f) {
180
210
  const r = await pool.query(`INSERT INTO instrument (network, key, pairing, claimed, held_until, final, outcome, answer, transaction, payer,
@@ -197,7 +227,9 @@ export async function openRecord(pool) {
197
227
  return r.rowCount === 1;
198
228
  },
199
229
  async sweep(now, feesBefore) {
200
- await pool.query(`DELETE FROM instrument WHERE final AND keep_until IS NOT NULL AND keep_until < $1`, [
230
+ // A row left open after a success at the head that no repeat made final is dropped as a final row is: past its
231
+ // keep, its signed payment can no longer land.
232
+ await pool.query(`DELETE FROM instrument WHERE (final OR (NOT final AND answer->>'success' = 'true')) AND keep_until IS NOT NULL AND keep_until < $1`, [
201
233
  now - KEEP_AFTER_MS,
202
234
  ]);
203
235
  await pool.query(`DELETE FROM fee WHERE at < $1`, [feesBefore]);
@@ -226,7 +258,9 @@ export function feesOn(pool, budgets) {
226
258
  WHERE NOT fee.included`, [network, transaction, now, fee.toString(), included]);
227
259
  },
228
260
  meter(network, now, log) {
261
+ const budget = byNetwork.get(network)?.amount;
229
262
  return {
263
+ ...(budget === undefined ? {} : { budget }),
230
264
  async sending(s) {
231
265
  const b = byNetwork.get(network);
232
266
  if (b === undefined)
package/dist/wrapper.d.ts CHANGED
@@ -37,7 +37,9 @@ export declare function route(r: Registration, payload: PaymentPayload, requirem
37
37
  /**
38
38
  * The kind's declaration, held to a payment before the class is asked: an option of amount zero whose pairing the kind
39
39
  * does not name as taking zero, and a form outside the pairings the module the payment goes to submits, are refused
40
- * `invalid_payment_requirements`.
40
+ * `invalid_payment_requirements`. A later message on an instrument an earlier payment opened (`Instrumented.later`)
41
+ * pays no option's amount, and the zero-amount rule does not hold it: x402's batch-settlement channel manager sends its
42
+ * claim and settle at amount `"0"`.
41
43
  */
42
44
  export declare function declared(kind: Kind, module: Module, p: X402Payment, i: Instrumented, phase: Phase): string | undefined;
43
45
  /**
package/dist/wrapper.js CHANGED
@@ -49,10 +49,12 @@ function optionAmount(kind, p, phase) {
49
49
  /**
50
50
  * The kind's declaration, held to a payment before the class is asked: an option of amount zero whose pairing the kind
51
51
  * does not name as taking zero, and a form outside the pairings the module the payment goes to submits, are refused
52
- * `invalid_payment_requirements`.
52
+ * `invalid_payment_requirements`. A later message on an instrument an earlier payment opened (`Instrumented.later`)
53
+ * pays no option's amount, and the zero-amount rule does not hold it: x402's batch-settlement channel manager sends its
54
+ * claim and settle at amount `"0"`.
53
55
  */
54
56
  export function declared(kind, module, p, i, phase) {
55
- if (/^0+$/.test(optionAmount(kind, p, phase)) && !kind.acceptsZero.includes(i.pairing))
57
+ if (i.later !== true && /^0+$/.test(optionAmount(kind, p, phase)) && !kind.acceptsZero.includes(i.pairing))
56
58
  return "invalid_payment_requirements";
57
59
  if (!module.descriptor.pairings.includes(i.pairing))
58
60
  return "invalid_payment_requirements";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@integraledger/profile-facilitator",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "An x402 facilitator for the pairings @integraledger/lcp ships: it checks, submits what the payer signed, records each payment once in Postgres, and answers what the chain shows, with one module per chain form on x402's published facilitator classes where x402 publishes them.",
5
5
  "license": "Apache-2.0",
6
6
  "engines": {
@@ -53,7 +53,7 @@
53
53
  "LICENSE"
54
54
  ],
55
55
  "peerDependencies": {
56
- "@integraledger/lcp": "~0.6.3"
56
+ "@integraledger/lcp": "~0.7.0"
57
57
  },
58
58
  "dependencies": {
59
59
  "@algorandfoundation/algokit-utils": "10.0.0-alpha.46",
@@ -84,7 +84,7 @@
84
84
  "xrpl": "4.7.0"
85
85
  },
86
86
  "devDependencies": {
87
- "@integraledger/lcp": "0.6.3",
87
+ "@integraledger/lcp": "0.7.0",
88
88
  "vitest": "5.0.4"
89
89
  },
90
90
  "scripts": {