@integraledger/profile-facilitator 0.4.0 → 0.5.1

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 (91) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +781 -456
  3. package/dist/answers.d.ts +11 -4
  4. package/dist/answers.js +24 -0
  5. package/dist/core.d.ts +51 -0
  6. package/dist/core.js +758 -0
  7. package/dist/http.d.ts +20 -3
  8. package/dist/http.js +32 -7
  9. package/dist/index.d.ts +12 -36
  10. package/dist/index.js +9 -162
  11. package/dist/module.d.ts +372 -0
  12. package/dist/module.js +13 -0
  13. package/dist/modules/algorand/index.d.ts +22 -0
  14. package/dist/modules/algorand/index.js +247 -0
  15. package/dist/modules/algorand/own.d.ts +26 -0
  16. package/dist/modules/algorand/own.js +231 -0
  17. package/dist/modules/aptos/index.d.ts +23 -0
  18. package/dist/modules/aptos/index.js +232 -0
  19. package/dist/modules/cardano/index.d.ts +18 -0
  20. package/dist/modules/cardano/index.js +124 -0
  21. package/dist/modules/casper/index.d.ts +120 -0
  22. package/dist/modules/casper/index.js +442 -0
  23. package/dist/modules/concordium/index.d.ts +16 -0
  24. package/dist/modules/concordium/index.js +77 -0
  25. package/dist/modules/erc7710/index.d.ts +26 -0
  26. package/dist/modules/erc7710/index.js +220 -0
  27. package/dist/modules/evm/forms.d.ts +74 -0
  28. package/dist/modules/evm/forms.js +204 -0
  29. package/dist/modules/evm/index.d.ts +40 -0
  30. package/dist/modules/evm/index.js +154 -0
  31. package/dist/modules/evm/node.d.ts +29 -0
  32. package/dist/modules/evm/node.js +222 -0
  33. package/dist/modules/hedera/executor.d.ts +63 -0
  34. package/dist/modules/hedera/executor.js +343 -0
  35. package/dist/modules/hedera/index.d.ts +23 -0
  36. package/dist/modules/hedera/index.js +136 -0
  37. package/dist/modules/hedera/mirror.d.ts +32 -0
  38. package/dist/modules/hedera/mirror.js +111 -0
  39. package/dist/modules/index.d.ts +23 -0
  40. package/dist/modules/index.js +24 -0
  41. package/dist/modules/lnbtc/index.d.ts +10 -0
  42. package/dist/modules/lnbtc/index.js +112 -0
  43. package/dist/modules/near/index.d.ts +18 -0
  44. package/dist/modules/near/index.js +246 -0
  45. package/dist/modules/polkadot/index.d.ts +12 -0
  46. package/dist/modules/polkadot/index.js +149 -0
  47. package/dist/modules/polkadot/rail.d.ts +40 -0
  48. package/dist/{polkadot.js → modules/polkadot/rail.js} +214 -288
  49. package/dist/modules/solana/index.d.ts +60 -0
  50. package/dist/modules/solana/index.js +326 -0
  51. package/dist/modules/solana/reader.d.ts +25 -0
  52. package/dist/modules/solana/reader.js +194 -0
  53. package/dist/modules/solana/state.d.ts +6 -0
  54. package/dist/modules/solana/state.js +103 -0
  55. package/dist/modules/starknet/index.d.ts +35 -0
  56. package/dist/modules/starknet/index.js +548 -0
  57. package/dist/modules/starknet/node.d.ts +78 -0
  58. package/dist/modules/starknet/node.js +339 -0
  59. package/dist/modules/stellar/index.d.ts +44 -0
  60. package/dist/modules/stellar/index.js +481 -0
  61. package/dist/modules/stellar/node.d.ts +57 -0
  62. package/dist/modules/stellar/node.js +151 -0
  63. package/dist/modules/sui/index.d.ts +16 -0
  64. package/dist/modules/sui/index.js +310 -0
  65. package/dist/modules/sui/node.d.ts +49 -0
  66. package/dist/modules/sui/node.js +197 -0
  67. package/dist/modules/ton/index.d.ts +16 -0
  68. package/dist/modules/ton/index.js +73 -0
  69. package/dist/modules/tron/index.d.ts +12 -0
  70. package/dist/modules/tron/index.js +120 -0
  71. package/dist/modules/tron/rail.d.ts +32 -0
  72. package/dist/{tron.js → modules/tron/rail.js} +206 -195
  73. package/dist/modules/xrpl/index.d.ts +28 -0
  74. package/dist/modules/xrpl/index.js +299 -0
  75. package/dist/modules/xrpl/node.d.ts +52 -0
  76. package/dist/modules/xrpl/node.js +231 -0
  77. package/dist/modules/xrpl/upto.d.ts +5 -0
  78. package/dist/modules/xrpl/upto.js +269 -0
  79. package/dist/record.d.ts +131 -0
  80. package/dist/record.js +330 -0
  81. package/dist/unexpected.d.ts +3 -2
  82. package/dist/unexpected.js +2 -1
  83. package/dist/wrapper.d.ts +68 -0
  84. package/dist/wrapper.js +126 -0
  85. package/package.json +48 -12
  86. package/dist/polkadot.d.ts +0 -21
  87. package/dist/store.d.ts +0 -59
  88. package/dist/store.js +0 -103
  89. package/dist/tron.d.ts +0 -12
  90. /package/dist/{base58check.d.ts → modules/tron/base58check.d.ts} +0 -0
  91. /package/dist/{base58check.js → modules/tron/base58check.js} +0 -0
@@ -1,19 +1,19 @@
1
1
  /**
2
2
  * Rule 5 of `x402/exact/tron/lcp-trc20-memo` against one network's FullNode and Solidity node: `/verify` checks the
3
- * signed transaction against the requirements, the owner's permission, its reference block and the ids already held,
4
- * and simulates it; `/settle` repeats that, claims the transaction id, broadcasts, and reads the transaction's status
5
- * until it is final.
3
+ * signed transaction against the requirements, the owner's permission, its reference block and the ids the node already
4
+ * holds, and simulates it; `/settle` repeats that, broadcasts, and reads the payment by lcp's read until it is final.
5
+ * Which payments were already settled is the settler's record, not the rail's: the rail keeps no row.
6
6
  */
7
7
  import { secp256k1 } from "@noble/curves/secp256k1.js";
8
8
  import { keccak_256 } from "@noble/hashes/sha3.js";
9
9
  import { pairingOf } from "@integraledger/lcp";
10
10
  import { isRefusal } from "@integraledger/lcp/core";
11
- import { decodeTronTx, tronAddress, tronCarrier, tronStatus, } from "@integraledger/lcp/tron";
12
- import { failed, invalid, isObject, isPending, pending, } from "./answers.js";
11
+ import { ReaderError } from "@integraledger/lcp/evm";
12
+ import { decodeTronTx, exactTronMemo, tronAddress, tronCarrier, } from "@integraledger/lcp/tron";
13
+ import { failed, invalid, isObject, pending, } from "../../answers.js";
14
+ import { isSpent, NodeError, postJson, sleep } from "../../http.js";
15
+ import { settleReason, unexpectedSettle, unexpectedVerify } from "../../unexpected.js";
13
16
  import { base58check } from "./base58check.js";
14
- import { isSpent, NodeError, postJson, sleep } from "./http.js";
15
- import { answerReserve, inTime } from "./store.js";
16
- import { settleReason, unexpectedSettle, unexpectedVerify } from "./unexpected.js";
17
17
  const POLL_MS = 1_000;
18
18
  function hexOf(b) {
19
19
  return Buffer.from(b).toString("hex");
@@ -68,7 +68,58 @@ function signerOf(signature, txid) {
68
68
  return undefined;
69
69
  }
70
70
  }
71
- export function createTron(nodes, s, settleWaitMs, log) {
71
+ /** A `getnowblock` answer: its number, `blockID` and time in milliseconds. */
72
+ function nowOf(o) {
73
+ const id = isObject(o) ? o["blockID"] : undefined;
74
+ const header = isObject(o) ? o["block_header"] : undefined;
75
+ const raw = isObject(header) ? header["raw_data"] : undefined;
76
+ const number = isObject(raw) ? raw["number"] : undefined;
77
+ const timestamp = isObject(raw) ? raw["timestamp"] : undefined;
78
+ if (typeof id !== "string" || !/^[0-9a-f]{64}$/.test(id))
79
+ throw new NodeError("malformed", true, "getnowblock blockID");
80
+ if (!Number.isSafeInteger(number) || !Number.isSafeInteger(timestamp)) {
81
+ throw new NodeError("malformed", true, "getnowblock fields");
82
+ }
83
+ return { number: BigInt(number), blockId: `0x${id}`, timestamp: BigInt(timestamp) };
84
+ }
85
+ /**
86
+ * A block as `getblockbylimitnext` and `getblockbynum` print it with `visible` false: its `blockID`, its header's
87
+ * `raw_data` `number` and `parentHash`, and each transaction's `raw_data_hex`; a block with no transactions has no
88
+ * `transactions` member (java-tron `framework/src/main/java/org/tron/core/services/http/Util.java`,
89
+ * `printBlockToJSON`). Throws for any other shape, which lcp's read takes as a read that failed.
90
+ */
91
+ function blockOf(o) {
92
+ const id = isObject(o) ? o["blockID"] : undefined;
93
+ const header = isObject(o) ? o["block_header"] : undefined;
94
+ const raw = isObject(header) ? header["raw_data"] : undefined;
95
+ const number = isObject(raw) ? raw["number"] : undefined;
96
+ const parent = isObject(raw) ? raw["parentHash"] : undefined;
97
+ const txs = isObject(o) ? (o["transactions"] ?? []) : undefined;
98
+ if (typeof id !== "string" || !/^[0-9a-f]{64}$/.test(id) || typeof parent !== "string" || !/^[0-9a-f]{64}$/.test(parent)) {
99
+ throw new NodeError("malformed", true, "block blockID, parentHash");
100
+ }
101
+ if (!Number.isSafeInteger(number) || !Array.isArray(txs))
102
+ throw new NodeError("malformed", true, "block number, transactions");
103
+ const transactions = txs.map((t) => {
104
+ const hex = isObject(t) ? t["raw_data_hex"] : undefined;
105
+ if (typeof hex !== "string")
106
+ throw new NodeError("malformed", true, "block transactions[].raw_data_hex");
107
+ return hex;
108
+ });
109
+ return { blockId: `0x${id}`, number: BigInt(number), parentHash: `0x${parent}`, transactions };
110
+ }
111
+ /** The x402 answer to `/settle` for lcp's read of the payment, where it is final for the transaction; else undefined. */
112
+ function finalAnswer(st, c) {
113
+ // Success is given only for the transaction presented, the one the rail broadcast: a transaction the payer signed
114
+ // again over H is another payment, and the one presented can still land until its expiration.
115
+ if (st.state === "settled") {
116
+ return st.presented === "yes" ? { success: true, transaction: c.txid, network: c.network, payer: c.payer } : undefined;
117
+ }
118
+ if (st.state === "failed")
119
+ return failed("invalid_transaction_state", st.transaction?.replace(/^0x/, "") ?? c.txid, c.network);
120
+ return undefined;
121
+ }
122
+ export function createTron(nodes, settleWaitMs, log) {
72
123
  const byNetwork = new Map(nodes.map((n) => [n.network, n]));
73
124
  /** The fields that name a payment in an operator entry. */
74
125
  const about = (c) => ({ network: c.network, payer: c.payer, transaction: c.txid });
@@ -98,12 +149,11 @@ export function createTron(nodes, s, settleWaitMs, log) {
98
149
  * entry is a failed call's, its cause a `spent` NodeError.
99
150
  */
100
151
  const notSent = (c, call) => unexpectedVerify(log, { event: "node-call-failed", ...about(c), call }, new NodeError("spent", false, call));
101
- /** The stored row, or undefined when the store does not answer by `deadline`; the failure goes to the operator log. */
102
- const readStored = (c, deadline) => inTime(s.read(c.network, c.txid), deadline).catch((e) => {
103
- log({ event: "store-call-failed", ...about(c), call: "read" }, e);
104
- return undefined;
105
- });
106
- /** Every check of rule 5 that reads neither the clock nor the node. */
152
+ /**
153
+ * Every check of rule 5 that reads neither the clock nor the node. The signatures are one to five, as lcp decodes
154
+ * them, each over the transaction id; each must recover a key, and no key may sign twice, which java-tron refuses
155
+ * (`TransactionCapsule.checkWeight`). Whether the owner's permission accepts them is read from the node.
156
+ */
107
157
  async function check(r) {
108
158
  const req = r.paymentRequirements;
109
159
  if (!byNetwork.has(req.network))
@@ -127,18 +177,23 @@ export function createTron(nodes, s, settleWaitMs, log) {
127
177
  return "invalid_payload";
128
178
  if (!sameBytes(tx.raw.callData, transferCall(payTo, BigInt(req.amount))))
129
179
  return "invalid_payload";
130
- if (tx.signatures.length !== 1)
131
- return "unsupported_permission";
132
180
  const txid = carried.txid.slice(2);
133
- const signer = signerOf(tx.signatures[0], Buffer.from(txid, "hex"));
134
- if (signer === undefined || !sameBytes(signer, tx.raw.owner))
135
- return "invalid_payload";
181
+ const signers = [];
182
+ for (const signature of tx.signatures) {
183
+ const signer = signerOf(signature, Buffer.from(txid, "hex"));
184
+ if (signer === undefined)
185
+ return "invalid_payload";
186
+ if (signers.includes(hexOf(signer)))
187
+ return "unsupported_permission";
188
+ signers.push(hexOf(signer));
189
+ }
136
190
  return {
137
191
  network: req.network,
138
192
  hex,
139
193
  raw: tx.raw,
140
194
  txid,
141
195
  payer: base58check(tx.raw.owner),
196
+ signers,
142
197
  maxTimeoutSeconds: req.maxTimeoutSeconds,
143
198
  };
144
199
  }
@@ -159,9 +214,10 @@ export function createTron(nodes, s, settleWaitMs, log) {
159
214
  }
160
215
  }
161
216
  /**
162
- * The owner's permission accepts the one signature: the weight it gives the owner's own key is at least its
163
- * threshold. An account the node does not hold, or one with no owner permission set, has java-tron's default owner
164
- * permission: the address's own key, weight 1, threshold 1.
217
+ * The owner's permission accepts the signatures: every key that signed is one of the permission's keys, and the
218
+ * weights the permission gives those keys add up to at least its threshold, as java-tron weighs them
219
+ * (`TransactionCapsule.checkWeight`). An account the node does not hold, or one with no owner permission set, has
220
+ * java-tron's default owner permission: the address's own key, weight 1, threshold 1.
165
221
  */
166
222
  async function permitted(c, deadline) {
167
223
  const call = "/wallet/getaccount";
@@ -171,16 +227,16 @@ export function createTron(nodes, s, settleWaitMs, log) {
171
227
  const account = read.answer;
172
228
  if (!isObject(account))
173
229
  return malformed(c, call, "the account");
174
- const permission = account["owner_permission"];
175
- if (permission === undefined)
176
- return null;
230
+ const permission = account["owner_permission"] ?? {
231
+ threshold: 1,
232
+ keys: [{ address: hexOf(c.raw.owner), weight: 1 }],
233
+ };
177
234
  if (!isObject(permission) || !Array.isArray(permission["keys"]))
178
235
  return malformed(c, call, "owner_permission.keys");
179
236
  const threshold = int64(permission["threshold"]);
180
237
  if (threshold === undefined)
181
238
  return malformed(c, call, "owner_permission.threshold");
182
- const owner = hexOf(c.raw.owner);
183
- let weight = 0n;
239
+ const weights = new Map();
184
240
  for (const key of permission["keys"]) {
185
241
  if (!isObject(key) || typeof key["address"] !== "string") {
186
242
  return malformed(c, call, "owner_permission.keys[].address");
@@ -188,8 +244,14 @@ export function createTron(nodes, s, settleWaitMs, log) {
188
244
  const w = int64(key["weight"]);
189
245
  if (w === undefined)
190
246
  return malformed(c, call, "owner_permission.keys[].weight");
191
- if (key["address"].toLowerCase() === owner)
192
- weight = w;
247
+ weights.set(key["address"].toLowerCase(), w);
248
+ }
249
+ let weight = 0n;
250
+ for (const signer of c.signers) {
251
+ const w = weights.get(signer);
252
+ if (w === undefined)
253
+ return "unsupported_permission";
254
+ weight += w;
193
255
  }
194
256
  return weight >= threshold ? null : "unsupported_permission";
195
257
  }
@@ -297,53 +359,41 @@ export function createTron(nodes, s, settleWaitMs, log) {
297
359
  ]);
298
360
  return [account, reference, inBlocks, inPool, simulation].find((r) => r !== null) ?? null;
299
361
  }
300
- /** Every check of `/verify`: the transaction, the store, which must not hold its id, and the node reads. */
362
+ /** Every check of `/verify`: the transaction, and the node reads. */
301
363
  async function verify(r) {
302
364
  const c = await check(r);
303
365
  if (typeof c === "string")
304
366
  return invalid(c);
305
- let stored;
306
- try {
307
- stored = await inTime(s.read(c.network, c.txid), Infinity);
308
- }
309
- catch (e) {
310
- return invalid(unexpectedVerify(log, { event: "store-call-failed", ...about(c), call: "read" }, e), c.payer);
311
- }
312
- if (stored.state !== "none")
313
- return invalid("invalid_transaction_state", c.payer);
314
367
  const now = beforeReads(c, Infinity) ?? (await nodeReads(c, Infinity, idReads(c, Infinity)));
315
368
  if (now === null)
316
369
  return { isValid: true, payer: c.payer };
317
370
  return invalid(typeof now === "string" ? now : notSent(c, now.spent), c.payer);
318
371
  }
319
372
  /**
320
- * The profile's reads at the Solidity node's `/walletsolidity` API and the FullNode's `/wallet` API, each bounded by
321
- * `deadline`. A receipt lookup that finds nothing names the time of the latest block at its level, read from the same
322
- * node before the lookup, or null when that read fails or its answer lacks the time. A read that fails is given to the
323
- * operator log; one `deadline` leaves no time for is not sent, and writes no entry.
373
+ * The reader lcp's Tron read takes, over the network's FullNode (`/wallet`) and Solidity node (`/walletsolidity`),
374
+ * each call bounded by `deadline` and by the node call bound. A receipt lookup that finds nothing, and each block
375
+ * read, names the latest block at its level on the node that answered, read from that node just before. A read that
376
+ * fails is given to the operator log; one `deadline` leaves no time for is not sent, and writes no entry. The FullNode
377
+ * keeps the block history, as this settler requires of it, so the reader declares it archival.
324
378
  */
325
- function reader(c, deadline) {
379
+ function statusReader(c, deadline) {
326
380
  const node = byNetwork.get(c.network);
327
381
  const left = () => deadline - performance.now();
328
- /** `getnowblock` at `api`: the latest block's number and time in milliseconds. */
329
- async function latest(api) {
330
- const o = await postJson(`${api}/getnowblock`, {}, left());
331
- const header = isObject(o) ? o["block_header"] : undefined;
332
- const raw = isObject(header) ? header["raw_data"] : undefined;
333
- const number = isObject(raw) ? raw["number"] : undefined;
334
- const timestamp = isObject(raw) ? raw["timestamp"] : undefined;
335
- if (!Number.isSafeInteger(number) || !Number.isSafeInteger(timestamp)) {
336
- throw new NodeError("malformed", true, "getnowblock fields");
337
- }
338
- return { number: BigInt(number), timestamp: BigInt(timestamp) };
339
- }
382
+ const api = (level) => (level === "solid" ? `${node.solidityNode}/walletsolidity` : `${node.fullNode}/wallet`);
383
+ const path = (level, call) => `${level === "solid" ? "/walletsolidity" : "/wallet"}/${call}`;
384
+ const now = (level) => reported(c, path(level, "getnowblock"), postJson(`${api(level)}/getnowblock`, {}, left()).then(nowOf));
385
+ /** The latest block's number at `level`, read from the node that answers the call after it, or null. */
386
+ const headOf = (level) => now(level).then((b) => b.number, () => null);
387
+ /** A block read whose answer is over the byte bound rejects as lcp's reader errors do, with `too-large`. */
388
+ const read = (level, call, body) => reported(c, path(level, call), postJson(`${api(level)}/${call}`, body, left())).catch((e) => {
389
+ throw e instanceof NodeError && e.code === "too-large" ? new ReaderError("too-large", e.message) : e;
390
+ });
340
391
  return {
341
392
  network: c.network,
393
+ archival: true,
342
394
  async info(txid, level) {
343
- const path = level === "solid" ? "/walletsolidity" : "/wallet";
344
- const api = `${level === "solid" ? node.solidityNode : node.fullNode}${path}`;
345
- const readTo = await reported(c, `${path}/getnowblock`, latest(api)).then((block) => block.timestamp, () => null);
346
- const o = await postJson(`${api}/gettransactioninfobyid`, { value: txid.replace(/^0x/, "") }, left());
395
+ const readTo = await now(level).then((b) => b.timestamp, () => null);
396
+ const o = await reported(c, path(level, "gettransactioninfobyid"), postJson(`${api(level)}/gettransactioninfobyid`, { value: txid.replace(/^0x/, "") }, left()));
347
397
  if (!isObject(o))
348
398
  throw new NodeError("malformed", true, "gettransactioninfobyid");
349
399
  if (Object.keys(o).length === 0)
@@ -357,90 +407,102 @@ export function createTron(nodes, s, settleWaitMs, log) {
357
407
  return { blockNumber: BigInt(blockNumber), result, logs };
358
408
  },
359
409
  transaction() {
360
- return Promise.reject(new NodeError("malformed", false, "not read by this facilitator"));
410
+ return Promise.reject(new NodeError("malformed", false, "not read by this settler"));
361
411
  },
362
- solidHead() {
363
- return latest(`${node.solidityNode}/walletsolidity`);
412
+ now,
413
+ async blocks(start, end, level) {
414
+ const head = await headOf(level);
415
+ const o = await read(level, "getblockbylimitnext", { startNum: Number(start), endNum: Number(end) });
416
+ if (!isObject(o))
417
+ throw new NodeError("malformed", true, "getblockbylimitnext");
418
+ const blocks = o["block"] ?? [];
419
+ if (!Array.isArray(blocks))
420
+ throw new NodeError("malformed", true, "getblockbylimitnext block");
421
+ return { head, blocks: blocks.map(blockOf) };
422
+ },
423
+ async block(num, level) {
424
+ const head = await headOf(level);
425
+ const o = await read(level, "getblockbynum", { num: Number(num) });
426
+ if (!isObject(o))
427
+ throw new NodeError("malformed", true, "getblockbynum");
428
+ return { head, block: Object.keys(o).length === 0 ? null : blockOf(o) };
364
429
  },
365
430
  };
366
431
  }
367
432
  /**
368
- * One read of the transaction's status through the profile's `tronStatus`: settled, at the Solidity node or the
369
- * FullNode, only with receipt result `SUCCESS` and a `Transfer` log from the asset, whatever the call returned (a
370
- * TRC-20 token may return false from `transfer` and still transfer). A failed receipt, or one with no such log, is
371
- * final only when the Solidity node, which serves solidified blocks alone, shows it. A transaction that neither
372
- * lookup finds, with the latest solidified block, read first, two slots past its expiration, can never be included
373
- * once each lookup names a latest block at or past that block's time. Anything else gives undefined.
433
+ * lcp's read of the payment, the act `payment` at the final mark, `solidified`, its search for H starting after
434
+ * `from` where it is given, or resuming from `search`. A request whose payment the form's checks refuse, or that lcp's
435
+ * `reference` refuses, is read as nothing: `unreadable`, `unparseable`, as lcp answers a reference that is not one.
374
436
  */
375
- async function outcome(c, deadline) {
376
- const reads = reader(c, deadline);
377
- let found;
378
- const st = await tronStatus({
379
- network: c.network,
380
- txid: `0x${c.txid}`,
381
- asset: `0x${hexOf(c.raw.contractAddress)}`,
382
- expiration: c.raw.expiration.toString(),
383
- }, {
384
- ...reads,
385
- async info(txid, level) {
386
- const api = level === "solid" ? "/walletsolidity" : "/wallet";
387
- const info = await reported(c, `${api}/gettransactioninfobyid`, reads.info(txid, level));
388
- if (!("notFound" in info))
389
- found = level;
390
- return info;
391
- },
392
- solidHead: () => reported(c, "/walletsolidity/getnowblock", reads.solidHead()),
393
- });
394
- if (st.state === "settled")
395
- return { success: true, transaction: c.txid, network: c.network, payer: c.payer };
396
- if (st.state === "pending")
397
- return undefined;
398
- if (st.why === "expired") {
399
- log({ event: "settlement-expired", ...about(c) });
400
- return failed("invalid_transaction_state", c.txid, c.network);
401
- }
402
- if (found !== "solid")
403
- return undefined;
404
- log({ event: "settlement-failed", ...about(c), why: st.why, result: st.result });
405
- return failed("invalid_transaction_state", c.txid, c.network);
437
+ async function status(r, deadline, from, search) {
438
+ const c = await check(r);
439
+ if (typeof c === "string")
440
+ return { state: "unreadable", reason: "unparseable", foreign: [] };
441
+ return read(c, r, deadline, from, search);
406
442
  }
407
- /** The answer to a `/settle` of a payment whose success has already been answered: a consumed payment fails. */
408
- function consumed(c) {
409
- return failed("invalid_transaction_state", c.txid, c.network);
443
+ async function read(c, r, deadline, from, search) {
444
+ const ref = await exactTronMemo.reference(r.paymentPayload, r.paymentRequirements);
445
+ if (isRefusal(ref))
446
+ return { state: "unreadable", reason: "unparseable", foreign: [] };
447
+ const resume = search ?? from;
448
+ return exactTronMemo.status(ref, statusReader(c, deadline), {
449
+ act: "payment",
450
+ finality: "solidified",
451
+ ...(resume === undefined ? {} : { search: resume }),
452
+ });
410
453
  }
411
454
  /**
412
- * Reads the transaction's status every second until `deadline`, and the stored answer too when `stored` is set,
413
- * answering with the first final answer either gives. A stored success is another settle's, so it gives the consumed
414
- * answer. Once `deadline` has passed, neither the store nor the status is read: the answer is the one the wait's end
415
- * gives. Broadcasts nothing.
455
+ * Reads the payment by lcp's read every second until `deadline`, answering with the first final answer: success for
456
+ * the transaction broadcast once lcp's read settles it at the solidified level, and `invalid_transaction_state`
457
+ * naming the transaction once it answers `failed`. Each live answer's search position is where the next read
458
+ * resumes. Once `deadline` has passed, nothing is read: the answer is pending with the id. Broadcasts nothing.
416
459
  */
417
- async function watch(c, deadline, stored) {
460
+ async function watch(c, r, deadline, from) {
461
+ let search;
418
462
  for (;;) {
419
463
  if (deadline - performance.now() <= 0)
420
464
  return pending(c.txid, c.network);
421
- if (stored) {
422
- const row = await readStored(c, deadline);
423
- if (row?.state === "answered" && !isPending(row.answer))
424
- return row.answer.success ? consumed(c) : row.answer;
425
- }
426
- if (deadline - performance.now() <= 0)
427
- return pending(c.txid, c.network);
428
- const final = await outcome(c, deadline);
429
- if (final !== undefined)
465
+ const st = await read(c, r, deadline, from, search);
466
+ const final = finalAnswer(st, c);
467
+ if (final !== undefined) {
468
+ if (!final.success)
469
+ log({ event: "settlement-failed", ...about(c), why: st.state === "failed" ? st.reason : undefined });
430
470
  return final;
471
+ }
472
+ if (st.state === "pending" && st.search !== undefined)
473
+ search = st.search;
431
474
  if (performance.now() + POLL_MS > deadline)
432
475
  return pending(c.txid, c.network);
433
476
  await sleep(POLL_MS);
434
477
  }
435
478
  }
479
+ /** The answer to a `/settle` of a payment the node already holds: the id is consumed, and the answer names it. */
480
+ function consumed(c) {
481
+ return failed("invalid_transaction_state", c.txid, c.network);
482
+ }
436
483
  /**
437
- * Broadcasts, then reads the transaction's status until `deadline`. A `DUP_TRANSACTION_ERROR` says the node already
438
- * holds the transaction id, so the payment is consumed. Any other refusal, or a request that cannot have reached the
439
- * node, gives `unexpected_settle_error` with no transaction: nothing was broadcast. So does a broadcast `deadline`
440
- * leaves no time for, as after a claim that answers late: it is not sent, and its entry is `settle-deadline-passed`.
484
+ * The last solidified block, read before the broadcast, where the read's search for H starts; undefined when the
485
+ * read fails, the read then searching nothing and holding the payment's absence to the lookups by id.
441
486
  */
442
- async function submit(c, deadline) {
487
+ async function solidified(c, deadline) {
443
488
  const node = byNetwork.get(c.network);
489
+ try {
490
+ const b = await reported(c, "/walletsolidity/getnowblock", postJson(`${node.solidityNode}/walletsolidity/getnowblock`, {}, deadline - performance.now()).then(nowOf));
491
+ return { number: b.number, blockId: b.blockId };
492
+ }
493
+ catch {
494
+ return undefined;
495
+ }
496
+ }
497
+ /**
498
+ * Broadcasts, then reads the payment until `deadline`. A `DUP_TRANSACTION_ERROR` says the node already holds the
499
+ * transaction id, so the payment is consumed. Any other refusal, or a request that cannot have reached the node, gives
500
+ * `unexpected_settle_error` with no transaction: nothing was broadcast, the id is not consumed, and the answer is not
501
+ * final. So does a broadcast `deadline` leaves no time for: it is not sent, and its entry is `settle-deadline-passed`.
502
+ */
503
+ async function submit(c, r, deadline) {
504
+ const node = byNetwork.get(c.network);
505
+ const from = await solidified(c, deadline);
444
506
  let sent;
445
507
  try {
446
508
  sent = await postJson(`${node.fullNode}/wallet/broadcasthex`, { transaction: c.hex }, deadline - performance.now());
@@ -460,53 +522,17 @@ export function createTron(nodes, s, settleWaitMs, log) {
460
522
  const entry = { event: "node-call-failed", ...about(c), call: "/wallet/broadcasthex" };
461
523
  return unexpectedSettle(log, entry, refusalOf(sent));
462
524
  }
463
- return watch(c, deadline, false);
525
+ return watch(c, r, deadline, from);
464
526
  }
465
527
  /**
466
- * Stores the answer unless the row holds a final one. A success is given only by the settle whose write stored it,
467
- * so one payment is answered success once: a success another settle stored first gives the consumed answer, and a
468
- * success whose write fails gives `settlement_pending` with the id. An answer with no transaction, a refused
469
- * broadcast or one that cannot have reached the node, is given only once it is the stored answer: when the row holds
470
- * another final answer, the answer is what a repeat gets for it, and when the write fails, `settlement_pending` with
471
- * the id. A failed write of any other answer leaves the row for a later read of the chain.
472
- */
473
- async function keep(c, answer, deadline) {
474
- let wrote;
475
- try {
476
- wrote = await inTime(s.answer(c.network, c.txid, answer), deadline);
477
- }
478
- catch (e) {
479
- log({ event: "answer-not-stored", ...about(c) }, e);
480
- return answer.success || answer.transaction === "" ? pending(c.txid, c.network) : answer;
481
- }
482
- if (wrote)
483
- return answer;
484
- if (answer.success)
485
- return consumed(c);
486
- if (answer.transaction !== "")
487
- return answer;
488
- const row = await readStored(c, deadline);
489
- if (row?.state !== "answered" || isPending(row.answer))
490
- return pending(c.txid, c.network);
491
- return row.answer.success ? consumed(c) : row.answer;
492
- }
493
- /**
494
- * Answers within `settleWaitMs`. A stored success means the payment is consumed, and gives
495
- * `invalid_transaction_state` with the id; any other stored final answer is given as it is. A claimed id, or a stored
496
- * pending answer, is read again from the chain. For an id the store does not hold, the expiration window and then
497
- * the deadline are checked before any node call: a deadline spent there sends none, and gives
498
- * `unexpected_settle_error`, or `invalid_payload` for an expiration outside the window. A node read the deadline
499
- * leaves no time for once the reads have started is not sent either, and in its place among the refusals gives
500
- * `unexpected_settle_error`, with one entry naming the call; for an expiration outside the window, an id read not
501
- * sent finds nothing, and the answer is `invalid_payload`, with no entry. The node's id reads answer first: an id
502
- * the node holds, in a block or its pending pool, is consumed too, whatever else the checks refuse, the expiration
503
- * window among them, and a node that does not answer them gives `unexpected_settle_error`.
504
- * No id is claimed once the wait for the chain has ended: its broadcast would have no time left.
505
- * A claimed id is never released: a broadcast the node refused as a duplicate is a consumed payment, and any other
506
- * refused broadcast, or a broadcast request that cannot have reached the node, gives `unexpected_settle_error` with
507
- * no transaction, which says nothing was broadcast. Each is stored final, and every repeat gets the stored answer.
508
- * When the store cannot be read, the facilitator cannot know whether the transaction was broadcast, so the answer is
509
- * pending with its id.
528
+ * Answers within `settleWaitMs`, less a reserve in which the settler stores the answer: a second, or a quarter of a
529
+ * shorter wait. The expiration window and then the deadline are checked before any node call: a deadline spent there
530
+ * sends none, and gives `unexpected_settle_error`, or `invalid_payload` for an expiration outside the window. A node
531
+ * read the deadline leaves no time for once the reads have started is not sent either, and in its place among the
532
+ * refusals gives `unexpected_settle_error`, with one entry naming the call; for an expiration outside the window, an
533
+ * id read not sent finds nothing, and the answer is `invalid_payload`, with no entry. The node's id reads answer
534
+ * first: an id the node holds, in a block or its pending pool, is consumed, whatever else the checks refuse, the
535
+ * expiration window among them, and a node that does not answer them gives `unexpected_settle_error`.
510
536
  */
511
537
  async function settle(r) {
512
538
  const deadline = performance.now() + settleWaitMs;
@@ -515,20 +541,6 @@ export function createTron(nodes, s, settleWaitMs, log) {
515
541
  const c = await check(r);
516
542
  if (typeof c === "string")
517
543
  return failed(settleReason(c), "", network);
518
- let stored;
519
- try {
520
- stored = await inTime(s.read(c.network, c.txid), deadline);
521
- }
522
- catch (e) {
523
- log({ event: "store-call-failed", ...about(c), call: "read" }, e);
524
- return pending(c.txid, c.network);
525
- }
526
- if (stored.state === "answered" && !isPending(stored.answer)) {
527
- return stored.answer.success ? consumed(c) : stored.answer;
528
- }
529
- const waitUntil = deadline - answerReserve(settleWaitMs);
530
- if (stored.state !== "none")
531
- return keep(c, await watch(c, waitUntil, true), deadline);
532
544
  // An expiration outside the window waits for the id reads while the deadline leaves time for them.
533
545
  const before = beforeReads(c, deadline);
534
546
  if (before !== null && (before !== "invalid_payload" || left() <= 0)) {
@@ -547,19 +559,18 @@ export function createTron(nodes, s, settleWaitMs, log) {
547
559
  return unexpectedSettle(log, deadlinePassed(c, refused.spent));
548
560
  return failed(settleReason(refused), "", network);
549
561
  }
562
+ const waitUntil = deadline - Math.min(1_000, settleWaitMs / 4);
550
563
  if (waitUntil - performance.now() <= 0)
551
- return unexpectedSettle(log, deadlinePassed(c, "claim"));
552
- let won;
553
- try {
554
- won = await inTime(s.claim(c.network, c.txid, new Date(Number(c.raw.expiration))), deadline);
555
- }
556
- catch (e) {
557
- log({ event: "store-call-failed", ...about(c), call: "claim" }, e);
558
- return pending(c.txid, c.network);
559
- }
560
- if (!won)
561
- return keep(c, await watch(c, waitUntil, true), deadline);
562
- return keep(c, await submit(c, waitUntil), deadline);
564
+ return unexpectedSettle(log, deadlinePassed(c, "/wallet/broadcasthex"));
565
+ return submit(c, r, waitUntil);
566
+ }
567
+ /**
568
+ * Where the settler's read of the payment `r` searches for H from: the last solidified block, read before anything
569
+ * is broadcast; undefined for a payment the form's checks refuse, or where the read fails.
570
+ */
571
+ async function position(r, deadline) {
572
+ const c = await check(r);
573
+ return typeof c === "string" ? undefined : solidified(c, deadline);
563
574
  }
564
- return { verify, settle, networks: nodes.map((n) => n.network) };
575
+ return { verify, settle, check, status, position, networks: nodes.map((n) => n.network) };
565
576
  }
@@ -0,0 +1,28 @@
1
+ import type { XrplNetwork } from "@integraledger/lcp/xrpl";
2
+ import type { PaymentPayload } from "@x402/core/types";
3
+ import { type ModuleStarter, type Registration } from "../../module.js";
4
+ import { type XrplNode } from "./node.js";
5
+ export interface XrplConfig {
6
+ /** The network, exactly one. */
7
+ readonly network: XrplNetwork;
8
+ /**
9
+ * The seller's rippled or Clio server's JSON-RPC endpoint, holding the ledgers from each payment's issue to the
10
+ * validated ledger, which the class, the own path and lcp's read call.
11
+ */
12
+ readonly node: string;
13
+ /** How long a settle waits for its transaction in a validated ledger; default 30 000. */
14
+ readonly waitMs?: number;
15
+ /** The most fee, in drops, a payment may sign; the class's default, 10 000, where absent. */
16
+ readonly maxFeeDrops?: string;
17
+ }
18
+ /** The payer variant the published class refuses: a transaction that carries `Signers`. */
19
+ export declare function isMultisigned(payload: PaymentPayload): boolean;
20
+ /** The registration of `x402/exact/xrpl` on the configured network, the multisigned payer handed to the own path. */
21
+ export declare function xrplRegistration(c: XrplConfig, node?: XrplNode): Registration;
22
+ /** The registration of `x402/upto/xrpl` on the configured network: the module's own facilitator, x402 publishing none. */
23
+ export declare function uptoRegistration(c: XrplConfig, node?: XrplNode): Registration;
24
+ /**
25
+ * How the core starts the module: the configuration's `xrpl` member lists the networks, one entry each, and each is
26
+ * served `exact` and `upto` over its server.
27
+ */
28
+ export declare const starter: ModuleStarter<readonly XrplConfig[]>;