@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
@@ -1,18 +1,740 @@
1
+ /**
2
+ * The `evm` module: x402's published EVM facilitator classes of `@x402/evm` 2.31.0, one module for each configured
3
+ * scheme on one `eip155` network. `exact` settles EIP-3009 and Permit2 (`ExactEvmScheme`), `upto` Permit2
4
+ * (`UptoEvmScheme`), `auth-capture` the commerce-payments escrow over either (`AuthCaptureEvmScheme`), and
5
+ * `batch-settlement` the payment channel, in each of its modes (`BatchSettlementEvmScheme`). Each class verifies and
6
+ * settles unchanged; the module adds the profile's pure checks, which lcp's codecs make before the class is asked, the
7
+ * record's key and lcp's read, and what the fee budget counts. The key is the seller's gas key: it sends each
8
+ * transaction and pays its gas, so `extra.key` is `relayer` and its address is the class's signer. A class names in its
9
+ * answer the one transaction that pays, which the core counts; the module counts every transaction the key sends, so
10
+ * that one the class sends and does not name, the deployment of a payer's ERC-6492 wallet, is counted too.
11
+ */
12
+ import { AsyncLocalStorage } from "node:async_hooks";
1
13
  import { AuthCaptureEvmScheme } from "@x402/evm/auth-capture/facilitator";
14
+ import { batchSettlementABI, computeChannelId } from "@x402/evm/batch-settlement";
2
15
  import { BatchSettlementEvmScheme } from "@x402/evm/batch-settlement/facilitator";
3
16
  import { ExactEvmScheme } from "@x402/evm/exact/facilitator";
4
17
  import { UptoEvmScheme } from "@x402/evm/upto/facilitator";
18
+ import { BATCH_SETTLEMENT_ADDRESS } from "@x402/evm";
19
+ import { concat, encodeEventTopics, encodeFunctionData, keccak256, parseTransaction, recoverTransactionAddress } from "viem";
5
20
  import { NODE_TIMEOUT_MS } from "../../http.js";
6
- import { phaseOf } from "../../module.js";
21
+ import { beforeSend, namedBefore, outcomeOf, phaseOf, sendsNamed, } from "../../module.js";
7
22
  import { exactEip3009 } from "@integraledger/lcp/x402";
8
- import { admit, instrumentOf, PAIRINGS, readOf } from "./forms.js";
9
- import { chargedFrom, evmReader, feeShown } from "./node.js";
23
+ import { captureLanded, countAt, escrowPosition, escrowRead, finalizedBlock, isVoidCall, unexecutedAt, voidOf } from "./escrow.js";
24
+ import { admit, escrowMessage, instrumentOf, PAIRINGS, readOf } from "./forms.js";
25
+ import { chargedFrom, evmReader, feeShown, rpcCall } from "./node.js";
26
+ import { anchorsIn, finalizedReceipt, nonceProof, registerAnchors } from "./nonce-proof.js";
27
+ /** Where the module keeps the signed bytes of an escrow call it named, by their hash. */
28
+ function keptAt(transaction) {
29
+ return `signed:${transaction.toLowerCase()}`;
30
+ }
31
+ /**
32
+ * Where the module records the void of the payment's remainder an escrow capture's claim carries, by the message's row
33
+ * key: written before anything is sent for it, so that the void is sent whichever body of the row is presented next.
34
+ */
35
+ function voidAt(message) {
36
+ return `void-for:${message}`;
37
+ }
38
+ /** The void the claim of the escrow capture `p` (row key `message`) carries, as recorded before its send; undefined where none. */
39
+ async function recordedVoid(state, message, p) {
40
+ const body = await state.get(voidAt(message));
41
+ return typeof body === "object" && body !== null ? { payload: { ...p.payload, payload: body }, requirements: p.requirements } : undefined;
42
+ }
43
+ /**
44
+ * Where the module marks an escrow call it signed and has not yet named in the claim's row (`beforeSend`), by its hash:
45
+ * set before the naming, deleted once the naming holds. Nothing sends those bytes unless a row names them first (this
46
+ * settle's send, or another's same bytes again, each after its own naming), so a marked transaction no row named was
47
+ * never given to the node: a settle whose naming the fence refused, or one stopped between signing and naming.
48
+ */
49
+ function unnamedAt(transaction) {
50
+ return `unnamed:${transaction.toLowerCase()}`;
51
+ }
52
+ /** Where the module lists the transactions whose signed bytes it keeps for one escrow message, by the message's row key. */
53
+ function listedAt(message) {
54
+ return `signed-for:${message}`;
55
+ }
56
+ /**
57
+ * Where the module keeps the block an escrow message is read from (`escrowPosition`), by the message's row key: the
58
+ * node's head read before anything was signed for it, at its claim or, where that read failed, before its first
59
+ * signing. The read searches from it where the record's row holds none.
60
+ */
61
+ function positionAt(message) {
62
+ return `position-for:${message}`;
63
+ }
64
+ /** The row key of an escrow message: its instrument's digest, as the record keys it. */
65
+ async function messageKey(network, p, a) {
66
+ const i = await instrumentOf(network, p, a);
67
+ return "refused" in i || i.instrument.by !== "digest" ? undefined : i.instrument.digest;
68
+ }
69
+ /**
70
+ * The escrow message whose class settle is running, where one is: its row key (the instrument's digest), and the
71
+ * transactions this settle named for it, first to last.
72
+ */
73
+ const settlingMessage = new AsyncLocalStorage();
74
+ /** Lists `transaction` under the escrow message `message`, beside those listed before, once. */
75
+ async function listUnder(state, message, transaction) {
76
+ for (;;) {
77
+ const was = await state.get(listedAt(message));
78
+ const listed = Array.isArray(was) ? was : [];
79
+ if (listed.includes(transaction.toLowerCase()))
80
+ return;
81
+ if (await state.swap(listedAt(message), was, [...listed, transaction.toLowerCase()]))
82
+ return;
83
+ }
84
+ }
85
+ /** The transactions whose signed bytes the module keeps for the escrow message `message`: those its claim named. */
86
+ async function listedOf(state, message) {
87
+ const listed = await state.get(listedAt(message));
88
+ return Array.isArray(listed) ? listed : [];
89
+ }
90
+ /**
91
+ * Deletes the signed bytes the module keeps for the escrow message `message`, and their list: called once the read
92
+ * shows the message final at the finalized block, after which no settle of its row sends anything again.
93
+ */
94
+ async function forget(state, message) {
95
+ const listed = await state.get(listedAt(message));
96
+ for (const t of Array.isArray(listed) ? listed : []) {
97
+ await state.delete(keptAt(t));
98
+ await state.delete(whenAt(t));
99
+ await state.delete(unnamedAt(t));
100
+ }
101
+ await state.delete(listedAt(message));
102
+ await state.delete(voidAt(message));
103
+ await state.delete(positionAt(message));
104
+ }
105
+ /** A JSON-RPC object, as the node answers one. */
106
+ function isRecord(v) {
107
+ return typeof v === "object" && v !== null && !Array.isArray(v);
108
+ }
109
+ /**
110
+ * What the node shows of a signed transaction by its hash: `mined` where it names the block that holds it, `held` where
111
+ * it holds it unmined, `unshown` where it answers nothing for it. `unshown` is no fact about the chain: a node behind
112
+ * the block that holds it, or one that dropped it from its pool, answers the same.
113
+ */
114
+ async function shownOf(rpc, signed, deadline) {
115
+ const t = await rpcCall(rpc, "eth_getTransactionByHash", [keccak256(signed)], deadline);
116
+ if (t === null)
117
+ return "unshown";
118
+ if (!isRecord(t))
119
+ throw new Error("the node's transaction is not one JSON-RPC defines");
120
+ return t["blockNumber"] === null || t["blockNumber"] === undefined ? "held" : "mined";
121
+ }
122
+ /**
123
+ * Whether the node's `pending` count for `from`, or its count at the latest block, is above `nonce`: it holds a
124
+ * transaction at that nonce, mined or in its pool, perhaps this one. Both are read, since a node can answer a `pending`
125
+ * count below its own `latest` count for a moment after a block.
126
+ */
127
+ async function heldAt(rpc, from, nonce, deadline) {
128
+ for (const at of ["pending", "latest"]) {
129
+ const v = await rpcCall(rpc, "eth_getTransactionCount", [from, at], deadline);
130
+ if (typeof v !== "string")
131
+ throw new Error("the node's transaction count is not a quantity");
132
+ if (BigInt(v) > BigInt(nonce))
133
+ return true;
134
+ }
135
+ return false;
136
+ }
137
+ /** The nonce and the sending account of a signed transaction. */
138
+ async function senderOf(signed) {
139
+ const from = (await recoverTransactionAddress({ serializedTransaction: signed })).toLowerCase();
140
+ return { nonce: parseTransaction(signed).nonce ?? 0, from };
141
+ }
142
+ /**
143
+ * Whether a signed transaction makes the same call as one to `to` with `data`: the same contract and the same function
144
+ * (its selector). Every transaction judged is one signed for the same message, so another function is the only other
145
+ * call among them (a capture's, beside the void of its remainder); call data that differs past the selector (a
146
+ * `dataSuffix` the class appends from the payment's extensions) is still the same call, and could execute it.
147
+ */
148
+ function calls(signed, to, data) {
149
+ const t = parseTransaction(signed);
150
+ return (t.to ?? "").toLowerCase() === to.toLowerCase() && (t.data ?? "0x").slice(0, 10).toLowerCase() === data.slice(0, 10).toLowerCase();
151
+ }
152
+ /**
153
+ * The gas key as the auth-capture class takes it, each escrow call it writes (`writeContract`) signed first, its signed
154
+ * bytes kept in the module's state for a claim whose calls are named (a capture's, void's or refund's, listed under its
155
+ * message until the class answers it success or the read shows it final, then deleted), its hash named in the claim's
156
+ * record (`beforeSend`, which writes only while no other settle has taken the claim since, and throws otherwise), and
157
+ * only then sent. Every transaction signed before for the message (named by an earlier settle, by this one, or kept as a
158
+ * replacement) is first judged, and nothing is sent where one of them may still execute it:
159
+ *
160
+ * - One still marked signed and not named (`unnamedAt`), and not named in the row as this run sees it (before this
161
+ * settle's claim, or by this run): the mark is deleted before its only fresh send, so it was never given to the node
162
+ * (the fence refused its naming, a stop came first, or the mark's deletion failed), and it is passed over unread.
163
+ * - One the node shows mined, or holds unmined: for the same call, nothing more is sent (the read decides it, and a held
164
+ * one is replaced only at its own nonce, `replaced`); for another call (a capture, before the void of its remainder),
165
+ * it does not stop this one.
166
+ * - One the node does not show, which is no fact about the chain: the block the node names `finalized` is read, by its
167
+ * hash, for two facts (EIP-1898). The gas key's transaction count there has passed its nonce, and the escrow's state
168
+ * there shows this message unexecuted (`unexecutedAt`): then it can never execute, and it is passed over. Where the
169
+ * count has not passed its nonce, it may still land: for the same call, its same signed bytes are sent again, and no
170
+ * other, unless the node's `pending` count shows a transaction held at its nonce (then nothing is sent); for another
171
+ * call, nothing is sent. Where the count has passed and the state does not show the message
172
+ * unexecuted, nothing is sent.
173
+ *
174
+ * A transaction is signed at a new nonce (the key's `pending` count) only where every one signed before is passed over.
175
+ * A failed read sends nothing. A key that does not sign without sending sends no escrow call. A wait for a receipt
176
+ * ends only with the receipt of the transaction waited for (`ownReceipt`), so that the class answers pending, and the
177
+ * record's read decides, where another transaction took its nonce. Every other member is the key's own.
178
+ */
179
+ function named(signer, rpc, state) {
180
+ const { signTransaction, sendRawTransaction } = signer;
181
+ return new Proxy(signer, {
182
+ get(inner, member) {
183
+ const value = Reflect.get(inner, member);
184
+ if (member === "waitForTransactionReceipt" && typeof value === "function") {
185
+ // A wait for an escrow call's receipt ends only with that call's own receipt (`ownReceipt`).
186
+ return async (args) => ownReceipt(args.hash, await value.call(inner, args));
187
+ }
188
+ if (member !== "writeContract")
189
+ return typeof value === "function" ? value.bind(inner) : value;
190
+ return async (args) => {
191
+ if (signTransaction === undefined || sendRawTransaction === undefined) {
192
+ throw new Error("the gas key does not sign without sending (EvmSender): no escrow call is sent");
193
+ }
194
+ const deadline = performance.now() + NODE_TIMEOUT_MS;
195
+ const data = concat([
196
+ encodeFunctionData({ abi: args.abi, functionName: args.functionName, args: (args.args ?? []) }),
197
+ ...(args.dataSuffix === undefined ? [] : [args.dataSuffix]),
198
+ ]);
199
+ const to = args.address.toLowerCase();
200
+ const message = settlingMessage.getStore();
201
+ const earlier = [];
202
+ for (const t of [...namedBefore(), ...(message?.names ?? []), ...(message === undefined ? [] : await listedOf(state, message.key))]) {
203
+ if (!earlier.includes(t.toLowerCase()))
204
+ earlier.push(t.toLowerCase());
205
+ }
206
+ let finalized;
207
+ // The same signed bytes to send again, where one signed before for this call may still land: the last signed
208
+ // at its nonce (a replacement after the one it replaced).
209
+ let again;
210
+ // The transactions a row named, before this settle's claim or by it: only these can have been given to the node.
211
+ const rowNamed = new Set([...namedBefore(), ...(message?.names ?? [])].map((t) => t.toLowerCase()));
212
+ for (const t of earlier) {
213
+ // Signed for the claim and never named in its row (its naming refused by the fence, or a stop before it): never
214
+ // sent, so it can never land, and it stops nothing.
215
+ if (!rowNamed.has(t) && (await state.get(unnamedAt(t))) !== undefined)
216
+ continue;
217
+ const kept = await state.get(keptAt(t));
218
+ if (typeof kept !== "string")
219
+ throw new Error(`the transaction named before, ${t}, has no signed bytes kept: nothing is sent`);
220
+ const raw = kept;
221
+ const same = calls(raw, to, data);
222
+ const shown = await shownOf(rpc, raw, deadline);
223
+ if (shown !== "unshown") {
224
+ if (same)
225
+ throw new Error(`the node shows ${t}, signed before for this call, ${shown}: nothing more is sent`);
226
+ continue;
227
+ }
228
+ const { nonce, from } = await senderOf(raw);
229
+ finalized ??= await finalizedBlock(rpc, deadline);
230
+ const passed = (await countAt(rpc, from, finalized, deadline)) > BigInt(nonce);
231
+ if (!passed) {
232
+ if (!same)
233
+ throw new Error(`${t}, another call signed before for this claim, may still land: nothing is sent`);
234
+ if (again !== undefined && again.nonce !== nonce)
235
+ throw new Error(`two transactions signed for this call at different nonces may still land: nothing is sent`);
236
+ again = { raw, nonce };
237
+ continue;
238
+ }
239
+ if (!same)
240
+ continue;
241
+ // The message this call sends: the void of a capture's remainder where the class sends that void inside the
242
+ // capture's settle, else the message settled.
243
+ const subject = message === undefined ? undefined : isVoidCall(data) ? (voidOf(message.payment) ?? message.payment) : message.payment;
244
+ if (subject === undefined || !(await unexecutedAt(rpc, subject, finalized, deadline))) {
245
+ throw new Error(`the escrow's state at the finalized block ${finalized.hash} does not show the message unexecuted: nothing is sent for ${t}`);
246
+ }
247
+ }
248
+ if (again !== undefined) {
249
+ // Where the node holds a transaction at its nonce (perhaps this one, which its lookup did not find), nothing.
250
+ if (await heldAt(rpc, (await senderOf(again.raw)).from, again.nonce, deadline)) {
251
+ throw new Error(`the node holds a transaction of the key at nonce ${again.nonce}: nothing more is sent`);
252
+ }
253
+ // The same signed bytes, named again under this settle's hold, and sent.
254
+ const transaction = keccak256(again.raw);
255
+ await beforeSend(transaction);
256
+ message?.names.push(transaction);
257
+ await sendRawTransaction.call(inner, { serializedTransaction: again.raw });
258
+ return transaction;
259
+ }
260
+ // The first signing for a message whose position could not be read at its claim: the node's head is read now,
261
+ // before anything is signed, and nothing is signed where it cannot be read. Without it the read could never
262
+ // search the escrow's events for the message.
263
+ if (sendsNamed() && message !== undefined && earlier.length === 0 && (await state.get(positionAt(message.key))) === undefined) {
264
+ await state.set(positionAt(message.key), await escrowPosition(rpc, deadline));
265
+ }
266
+ const raw = await signTransaction.call(inner, { to: args.address, data, ...(args.gas === undefined ? {} : { gas: args.gas }) });
267
+ const transaction = keccak256(raw);
268
+ // Kept only for a claim whose calls are named (an escrow message's): a later settle of the same claim reads
269
+ // them. Listed under the message, so that they are deleted once the read shows it final.
270
+ if (sendsNamed() && message !== undefined) {
271
+ // Marked first: a stop at any point before the naming leaves it marked, and a mark with nothing listed is never read.
272
+ await state.set(unnamedAt(transaction), Date.now());
273
+ await state.set(keptAt(transaction), raw);
274
+ await state.set(whenAt(transaction), Date.now());
275
+ await listUnder(state, message.key, transaction);
276
+ }
277
+ await beforeSend(transaction);
278
+ // Named in the row: from here it may be sent. Where the mark cannot be deleted, nothing is sent: the row names
279
+ // it, so a later settle judges it and sends its same bytes, never a new nonce.
280
+ if (sendsNamed() && message !== undefined)
281
+ await state.delete(unnamedAt(transaction));
282
+ message?.names.push(transaction);
283
+ return sendRawTransaction.call(inner, { serializedTransaction: raw });
284
+ };
285
+ },
286
+ });
287
+ }
288
+ /** Where the module keeps when it signed a transaction for an escrow message, by its hash (milliseconds). */
289
+ function whenAt(transaction) {
290
+ return `signed-when:${transaction.toLowerCase()}`;
291
+ }
292
+ /** The fee a replacement at the same nonce must at least raise by, as nodes take one: an eighth, above their tenth. */
293
+ function raised(fee) {
294
+ return fee + fee / 8n + 1n;
295
+ }
296
+ /**
297
+ * Replaces a transaction signed for an escrow message that the node holds unmined and underpriced by the same call
298
+ * signed at the same nonce: its fee cap below the base fee of the node's latest block, or its tip below the tip the
299
+ * node suggests (`eth_maxPriorityFeePerGas`) a whole settle wait after the last transaction at its nonce was signed.
300
+ * One priced by `gasPrice` alone tips its price less the base fee, and offers its whole price as its tip. The
301
+ * replacement's tip is the larger of the tip the held one offers raised by an eighth and the node's suggestion, and its
302
+ * fee cap the larger of the held one's raised by an eighth and twice the base fee and the tip, so that a replacement is made
303
+ * again only where the base fee passes its cap or the node's suggested tip rises past its own: the fees follow what
304
+ * the node asks, and repeats alone never raise them. Named in the row first (`Core.naming`, under the repeat's
305
+ * fencing number), kept and listed under the message like the transaction it replaces, and only then sent; nothing is
306
+ * sent where its naming fails or the signer does not sign at that nonce with those fees. Both can be the one that
307
+ * lands, and the nonce lets one only. `signed` is the transaction the node holds at that nonce for the message, and
308
+ * `when` when the last at that nonce was signed (`heldAtNonce`); one the node does not show goes again only by the
309
+ * class's settle (`named`). Where the replacement's send fails and the node does not show it by its hash, the row names
310
+ * `signed` again, which a later repeat replaces again: with the same fees while the node asks the same.
311
+ *
312
+ * `dropped`: the node shows none of the transactions signed at the nonce. Then the same call is signed again at that
313
+ * nonce, with the same fees a replacement takes, only where neither the node's `pending` count nor its count at the
314
+ * latest block shows a transaction of the key at the nonce (`heldAt`: it holds none there, and none is mined there) and the fee cap of `signed`, the last signed at the nonce,
315
+ * is below the base fee of the node's latest block: the same bytes would be refused, or dropped again, for their price
316
+ * alone. Both are at one nonce, so one only can land.
317
+ *
318
+ * No replacement is signed whose own bound, its gas limit times its fee cap, is above the network's whole fee budget
319
+ * (`FeeMeter.budget`): the transaction signed before stays the last at its nonce.
320
+ */
321
+ async function replaced(signer, rpc, state, message, signed, when, meter, core, deadline, dropped = false) {
322
+ const { signTransaction, sendRawTransaction } = signer;
323
+ if (signTransaction === undefined || sendRawTransaction === undefined)
324
+ return;
325
+ if ((await shownOf(rpc, signed, deadline)) !== (dropped ? "unshown" : "held"))
326
+ return;
327
+ const held = parseTransaction(signed);
328
+ if (held.to === undefined || held.to === null || held.nonce === undefined)
329
+ return;
330
+ if (dropped && (await heldAt(rpc, (await senderOf(signed)).from, held.nonce, deadline)))
331
+ return;
332
+ const block = await rpcCall(rpc, "eth_getBlockByNumber", ["latest", false], deadline);
333
+ const tipNow = await rpcCall(rpc, "eth_maxPriorityFeePerGas", [], deadline);
334
+ if (!isRecord(block) || typeof block["baseFeePerGas"] !== "string" || typeof tipNow !== "string")
335
+ throw new Error("the node's fees are not quantities");
336
+ const base = BigInt(block["baseFeePerGas"]);
337
+ const suggested = BigInt(tipNow);
338
+ // A transaction priced by `gasPrice` alone tips what its price leaves above the base fee, and offers its whole price
339
+ // as its tip (EIP-1559): its replacement's tip is raised from that price, so that it pays no less at any base fee.
340
+ const price = held.gasPrice ?? 0n;
341
+ const heldTip = held.maxPriorityFeePerGas ?? (price > base ? price - base : 0n);
342
+ const offered = held.maxPriorityFeePerGas ?? price;
343
+ const feeCap = held.maxFeePerGas ?? price;
344
+ const waited = when === undefined || Date.now() - when >= core.settleWaitMs;
345
+ if (feeCap >= base && (dropped || !(waited && heldTip < suggested)))
346
+ return;
347
+ const larger = (a, b) => (a > b ? a : b);
348
+ const tip = larger(raised(offered), suggested);
349
+ const cap = larger(raised(feeCap), 2n * base + tip);
350
+ if (meter.budget !== undefined && held.gas !== undefined && held.gas * cap > meter.budget)
351
+ return;
352
+ const request = { to: held.to, data: held.data ?? "0x", nonce: held.nonce, ...(held.gas === undefined ? {} : { gas: held.gas }), maxFeePerGas: cap, maxPriorityFeePerGas: tip };
353
+ const raw = await signTransaction.call(signer, request);
354
+ const next = parseTransaction(raw);
355
+ if ((await senderOf(raw)).from !== (await senderOf(signed)).from || next.nonce !== held.nonce || next.maxFeePerGas !== cap || next.maxPriorityFeePerGas !== tip || next.to?.toLowerCase() !== held.to.toLowerCase() || next.data !== held.data) {
356
+ throw new Error("the signer did not sign the replacement from that account at that nonce with those fees: nothing is sent");
357
+ }
358
+ const transaction = keccak256(raw);
359
+ await state.set(keptAt(transaction), raw);
360
+ await state.set(whenAt(transaction), Date.now());
361
+ // Named in the row before it is listed and sent; where the naming throws (the claim taken since, or the store call
362
+ // failed), nothing is sent, and the transaction it would replace stays the last at its nonce.
363
+ await core.naming(transaction);
364
+ await listUnder(state, message, transaction);
365
+ try {
366
+ await sendRawTransaction.call(signer, { serializedTransaction: raw });
367
+ }
368
+ catch (e) {
369
+ // A replacement the node does not show is judged only once the node shows it: the row names again the transaction it holds.
370
+ if ((await shownOf(rpc, raw, deadline).catch(() => undefined)) === "unshown")
371
+ await core.naming(keccak256(signed));
372
+ throw e;
373
+ }
374
+ meter.sent(transaction, () => feeShown(rpc, transaction, performance.now() + NODE_TIMEOUT_MS));
375
+ }
376
+ /**
377
+ * Of the transactions signed for the escrow message `message` at the nonce of `transaction` (the one the record names
378
+ * and those it replaced or replaced it), the one whose receipt the node shows; `transaction` where it shows none.
379
+ */
380
+ async function shownAtNonce(state, message, transaction, reader) {
381
+ const first = await state.get(keptAt(transaction));
382
+ if (typeof first !== "string")
383
+ return transaction;
384
+ const { nonce } = await senderOf(first);
385
+ const at = [];
386
+ for (const t of await listedOf(state, message)) {
387
+ const raw = await state.get(keptAt(t));
388
+ if (typeof raw === "string" && (await senderOf(raw)).nonce === nonce)
389
+ at.push(t);
390
+ }
391
+ for (const t of at)
392
+ if ((await reader.receipt(t.toLowerCase())) !== null)
393
+ return t;
394
+ return transaction;
395
+ }
396
+ /**
397
+ * Of the transactions signed for the escrow message `message` at the nonce of `transaction`, by their kept bytes: the
398
+ * last signed that the node shows by its hash, mined or not, and when the last of them was signed; where the node shows
399
+ * none, the last signed of them, `unshown`. Undefined where none is kept. A failed lookup rejects.
400
+ */
401
+ async function heldAtNonce(rpc, state, message, transaction, deadline) {
402
+ const first = await state.get(keptAt(transaction));
403
+ if (typeof first !== "string")
404
+ return undefined;
405
+ const { nonce } = await senderOf(first);
406
+ // First to last as listed; `transaction` first where it is not listed.
407
+ const at = [];
408
+ for (const t of await listedOf(state, message)) {
409
+ const raw = await state.get(keptAt(t));
410
+ if (typeof raw === "string" && (await senderOf(raw)).nonce === nonce)
411
+ at.push(raw);
412
+ }
413
+ if (!at.includes(first))
414
+ at.unshift(first);
415
+ let when;
416
+ for (const raw of at) {
417
+ const w = await state.get(whenAt(keccak256(raw)));
418
+ if (typeof w === "number" && (when === undefined || w > when))
419
+ when = w;
420
+ }
421
+ for (const raw of at.reverse())
422
+ if ((await shownOf(rpc, raw, deadline)) !== "unshown")
423
+ return { signed: raw, when };
424
+ return { signed: at[0], when, unshown: true };
425
+ }
426
+ /**
427
+ * The transactions signed for the escrow message `message` that make the message's own call (a void's for a void; for
428
+ * a capture or refund, not the void of a capture's remainder), each with the account and nonce its kept bytes name
429
+ * (`SignedCall`): every one listed under the message, and `transaction`, the one the row names; by its hash alone
430
+ * where no bytes are kept for it. One still marked signed and not named is among them: a row may have named it since,
431
+ * and its same bytes been sent.
432
+ */
433
+ async function signedCalls(state, message, p, transaction) {
434
+ const voidMessage = kindOf(p) === "void";
435
+ const named = transaction?.toLowerCase();
436
+ const out = [];
437
+ const listed = await listedOf(state, message);
438
+ for (const t of named === undefined || listed.includes(named) ? listed : [...listed, named]) {
439
+ const raw = await state.get(keptAt(t));
440
+ if (typeof raw !== "string") {
441
+ out.push({ hash: t });
442
+ continue;
443
+ }
444
+ if (isVoidCall(parseTransaction(raw).data ?? "0x") !== voidMessage)
445
+ continue;
446
+ const { nonce, from } = await senderOf(raw);
447
+ out.push({ hash: t, from, nonce: BigInt(nonce) });
448
+ }
449
+ return out;
450
+ }
451
+ /**
452
+ * Whether the node holds a transaction of one of the gas key's addresses unmined: its `pending` count above its `latest`
453
+ * one. The pending count is read first, so that a transaction mined between the two reads counts as mined, not held.
454
+ */
455
+ async function keyHolds(rpc, keys, deadline) {
456
+ for (const k of keys) {
457
+ const pending = await rpcCall(rpc, "eth_getTransactionCount", [k, "pending"], deadline);
458
+ const latest = await rpcCall(rpc, "eth_getTransactionCount", [k, "latest"], deadline);
459
+ if (typeof pending !== "string" || typeof latest !== "string")
460
+ throw new Error("the node's transaction count is not a quantity");
461
+ if (BigInt(pending) > BigInt(latest))
462
+ return true;
463
+ }
464
+ return false;
465
+ }
466
+ /** The gas key's own addresses, the accounts that sign and send its transactions, in lowercase. */
467
+ function gasKeys(signer) {
468
+ return signer.getAddresses().map((a) => a.toLowerCase());
469
+ }
470
+ /** The type a batch settlement's later message names (`claim`, `settle`, `refund`); undefined for any other payload. */
471
+ function kindOf(p) {
472
+ return p.payload.payload?.["type"];
473
+ }
474
+ /**
475
+ * The final answer for a transaction the finalized chain shows mined and reverted (`finalizedReceipt`: its block, by
476
+ * the receipt's hash, on the chain below the finalized block's own hash): `failed` (`transaction-failed`), naming it.
477
+ * Undefined while its receipt is not shown, it executed, or its block is not shown on the finalized chain: its fate is
478
+ * then not known, or not this read's to state.
479
+ */
480
+ async function revertedAtFinalized(rpc, transaction, deadline) {
481
+ const r = await finalizedReceipt(rpc, transaction, deadline);
482
+ if (r === undefined || r.status !== 0)
483
+ return undefined;
484
+ return outcomeOf({ state: "failed", reason: "transaction-failed", transaction, finality: "finalized", foreign: [] });
485
+ }
486
+ /**
487
+ * The final answer for a channel refund the finalized chain shows mined and executed (`finalizedReceipt`), whose own
488
+ * receipt, in that same block, holds the channel contract's `Refunded` for the channel the refund names (its id
489
+ * computed from the payload's `channelConfig`, as the contract computes it): `settled`, naming it. Undefined while its
490
+ * receipt is not shown on the finalized chain, it reverted, or its logs hold no such event: its fate is then not known,
491
+ * or not this read's to state.
492
+ */
493
+ async function refundedAtFinalized(rpc, transaction, p, deadline) {
494
+ const config = p.payload.payload?.["channelConfig"];
495
+ if (!isRecord(config))
496
+ return undefined;
497
+ const channel = computeChannelId(config, p.requirements.network).toLowerCase();
498
+ const r = await finalizedReceipt(rpc, transaction, deadline);
499
+ if (r === undefined || r.status !== 1)
500
+ return undefined;
501
+ const receipt = await rpcCall(rpc, "eth_getTransactionReceipt", [transaction], deadline);
502
+ if (!isRecord(receipt) || typeof receipt["blockHash"] !== "string" || receipt["blockHash"].toLowerCase() !== r.blockHash.toLowerCase())
503
+ return undefined;
504
+ if (typeof receipt["transactionHash"] !== "string" || receipt["transactionHash"].toLowerCase() !== transaction.toLowerCase())
505
+ return undefined;
506
+ const [topic] = encodeEventTopics({ abi: batchSettlementABI, eventName: "Refunded" });
507
+ const logs = Array.isArray(receipt["logs"]) ? receipt["logs"] : [];
508
+ const refunded = logs.some((l) => isRecord(l) &&
509
+ typeof l["address"] === "string" &&
510
+ l["address"].toLowerCase() === BATCH_SETTLEMENT_ADDRESS.toLowerCase() &&
511
+ Array.isArray(l["topics"]) &&
512
+ String(l["topics"][0]).toLowerCase() === topic.toLowerCase() &&
513
+ String(l["topics"][1]).toLowerCase() === channel);
514
+ if (!refunded)
515
+ return undefined;
516
+ return outcomeOf({ state: "settled", transaction, finality: "finalized", presented: "yes", foreign: [] });
517
+ }
518
+ /** A pending-settlement store that keeps nothing: the record and the escrow's read decide what is sent again. */
519
+ const KEEPS_NOTHING = { get: async () => undefined, set: async () => { }, delete: async () => { } };
10
520
  const SCHEMES = ["exact", "upto", "auth-capture", "batch-settlement"];
521
+ /** A transaction's hash, as JSON-RPC answers one. */
522
+ const HASH = /^0x[0-9a-fA-F]{64}$/;
523
+ /** Where the module keeps the sending account, nonce, call and send head of a pending settlement's transaction, by its hash. */
524
+ function sentAt(transaction) {
525
+ return `sent-at:${transaction.toLowerCase()}`;
526
+ }
527
+ /**
528
+ * The most the module's own node calls hold a class's settle, in milliseconds: before a wait for a transaction the
529
+ * class keeps (the proof that lets it go, where no earlier call made it; a proof still running then goes on beside the
530
+ * wait, and the next repeat has its answer), and after a wait that ended with a receipt that does not name the
531
+ * transaction waited for. A wait that ends with the transaction's own receipt, and one that ends with none, make no
532
+ * node call of the module's before the class has its answer.
533
+ */
534
+ const HELD_MS = 2_000;
535
+ /** The call a transaction makes, as one value: the contract it calls and its call data. */
536
+ function callOf(to, data) {
537
+ return keccak256(concat([to.toLowerCase(), data.toLowerCase()]));
538
+ }
539
+ const NOTED = 4096;
540
+ /** Sets `key` in `m`, the oldest entry dropped past `NOTED`. */
541
+ function capped(m, key, value) {
542
+ m.set(key, value);
543
+ if (m.size > NOTED)
544
+ m.delete(m.keys().next().value);
545
+ return value;
546
+ }
547
+ function noted(notes, transaction) {
548
+ const key = transaction.toLowerCase();
549
+ return notes.n.get(key) ?? capped(notes.n, key, {});
550
+ }
551
+ /**
552
+ * Writes what is known of `transaction` to the module's state, where a class keeps it and its account and nonce are
553
+ * known. A write that fails leaves nothing, and the pending settlement then stays as x402's class keeps it.
554
+ */
555
+ async function keep(notes, transaction) {
556
+ const key = transaction.toLowerCase();
557
+ const v = notes.n.get(key);
558
+ if (v?.kept !== true || v.from === undefined || v.nonce === undefined)
559
+ return;
560
+ const row = { from: v.from, nonce: v.nonce, ...(v.call === undefined ? {} : { call: v.call }), ...(v.since === undefined ? {} : { since: v.since }) };
561
+ await notes.state.set(sentAt(key), row).catch(() => { });
562
+ // Shown or let go while it was written: nothing is left of it.
563
+ if (notes.n.get(key)?.kept !== true)
564
+ await notes.state.delete(sentAt(key)).catch(() => { });
565
+ }
566
+ /** Forgets `transaction`: what is known of it, and what the module's state keeps of it where a class kept it. */
567
+ async function forgetSent(notes, transaction, kept) {
568
+ const key = transaction.toLowerCase();
569
+ const was = notes.n.get(key);
570
+ notes.n.delete(key);
571
+ notes.taken.delete(key);
572
+ if (kept ?? was?.kept === true)
573
+ await notes.state.delete(sentAt(key)).catch(() => { });
574
+ }
575
+ /** The node's head, as a decimal string; undefined where the read fails. Never rejects. */
576
+ async function headOf(rpc) {
577
+ try {
578
+ const head = await rpcCall(rpc, "eth_blockNumber", [], performance.now() + NODE_TIMEOUT_MS);
579
+ return typeof head === "string" && /^0x[0-9a-fA-F]{1,16}$/.test(head) ? BigInt(head).toString(10) : undefined;
580
+ }
581
+ catch {
582
+ // No head noted: the proof then searches from the network's first block.
583
+ return undefined;
584
+ }
585
+ }
586
+ /** Notes `head`, once it is read, as the head `transaction` was signed at; written where a class keeps it by then. */
587
+ function sinceHead(notes, transaction, head) {
588
+ void head.then(async (since) => {
589
+ const v = notes.n.get(transaction.toLowerCase());
590
+ if (since === undefined || v === undefined || v.since !== undefined)
591
+ return;
592
+ v.since = since;
593
+ await keep(notes, transaction);
594
+ });
595
+ }
596
+ /** A transaction as the node answers it by `hash`: its account, nonce and call. Undefined where it answers another, or none. */
597
+ async function shownBy(rpc, hash, deadline) {
598
+ const t = await rpcCall(rpc, "eth_getTransactionByHash", [hash], deadline);
599
+ if (!isRecord(t) || typeof t["hash"] !== "string" || t["hash"].toLowerCase() !== hash.toLowerCase())
600
+ return undefined;
601
+ if (typeof t["from"] !== "string" || typeof t["nonce"] !== "string" || !/^0x[0-9a-fA-F]{1,16}$/.test(t["nonce"]))
602
+ return undefined;
603
+ if (typeof t["to"] !== "string" || typeof t["input"] !== "string" || !/^0x([0-9a-fA-F]{2})*$/.test(t["input"]) || !/^0x[0-9a-fA-F]{40}$/.test(t["to"]))
604
+ return undefined;
605
+ return { from: t["from"].toLowerCase(), nonce: BigInt(t["nonce"]).toString(10), call: callOf(t["to"], t["input"]) };
606
+ }
607
+ /**
608
+ * Notes the account, nonce and call of `transaction` from the node's answer by its hash. A node that shows nothing, or
609
+ * answers another hash, notes nothing, and decides nothing. Only for a transaction whose account and nonce are not
610
+ * known from its signing: a key that does not sign without sending. Never awaited by a class's settle.
611
+ */
612
+ async function noteSent(rpc, notes, transaction) {
613
+ const key = transaction.toLowerCase();
614
+ if (notes.n.get(key)?.from !== undefined)
615
+ return;
616
+ try {
617
+ const t = await shownBy(rpc, key, performance.now() + NODE_TIMEOUT_MS);
618
+ const v = notes.n.get(key);
619
+ if (t === undefined || v === undefined || v.from !== undefined)
620
+ return;
621
+ Object.assign(v, t);
622
+ await keep(notes, key);
623
+ }
624
+ catch {
625
+ // Nothing noted: the pending settlement then stays as x402's class keeps it.
626
+ }
627
+ }
628
+ /** The call a class writes, as the transaction's `to` and `data`: what viem's `writeContract` sends. */
629
+ function writeOf(args) {
630
+ return {
631
+ to: args.address,
632
+ data: concat([encodeFunctionData({ abi: args.abi, functionName: args.functionName, args: (args.args ?? []) }), ...(args.dataSuffix === undefined ? [] : [args.dataSuffix])]),
633
+ };
634
+ }
635
+ /**
636
+ * Sends a call a stock class writes. Where the key signs without sending (`EvmSender`), the call is signed first, so
637
+ * that its account, nonce and call are known from the signed bytes whatever the node later shows of it, then those
638
+ * bytes are sent. Where the key does not, or does not sign this call (its own preparation failed, or it signed another
639
+ * call), the call goes to the key's own `writeContract`, whose answer or error is then the class's as without the
640
+ * settler, and the node is asked for the transaction by its hash beside the class's wait for it (`counted`). The
641
+ * node's head is read beside the signing, and nothing waits for it.
642
+ */
643
+ async function written(inner, write, args, rpc, notes) {
644
+ const head = headOf(rpc);
645
+ const { signTransaction, sendRawTransaction } = inner;
646
+ if (signTransaction !== undefined && sendRawTransaction !== undefined) {
647
+ let signed;
648
+ try {
649
+ const a = args;
650
+ const { to, data } = writeOf(a);
651
+ const raw = await signTransaction.call(inner, { to, data, ...(a.gas === undefined ? {} : { gas: a.gas }) });
652
+ const t = parseTransaction(raw);
653
+ if ((t.to ?? "").toLowerCase() === to.toLowerCase() && (t.data ?? "0x").toLowerCase() === data.toLowerCase() && t.nonce !== undefined) {
654
+ const { from, nonce } = await senderOf(raw);
655
+ signed = { raw, transaction: keccak256(raw), from, nonce: String(nonce), call: callOf(to, data) };
656
+ }
657
+ }
658
+ catch {
659
+ // Not signed: the key's own `writeContract` answers the class.
660
+ }
661
+ if (signed !== undefined) {
662
+ Object.assign(noted(notes, signed.transaction), { from: signed.from, nonce: signed.nonce, call: signed.call });
663
+ sinceHead(notes, signed.transaction, head);
664
+ await sendRawTransaction.call(inner, { serializedTransaction: signed.raw });
665
+ return signed.transaction;
666
+ }
667
+ }
668
+ const transaction = await write(args);
669
+ if (typeof transaction === "string" && HASH.test(transaction)) {
670
+ noted(notes, transaction);
671
+ sinceHead(notes, transaction, head);
672
+ }
673
+ return transaction;
674
+ }
675
+ /**
676
+ * Whether the node shows the receipt of `transaction` itself, mined, with the status `receipt` states: then a receipt
677
+ * that names no transaction, as x402's own receipt type (`{ status, logs? }`) names none, is that transaction's own,
678
+ * since the chain that holds it holds no other transaction of the key at its nonce. A read that fails, or a node that
679
+ * does not show it (one behind the block that holds it), is false, and the settle is then answered pending.
680
+ */
681
+ async function ownShown(rpc, transaction, receipt, deadline) {
682
+ try {
683
+ const r = await rpcCall(rpc, "eth_getTransactionReceipt", [transaction], deadline);
684
+ if (!isRecord(r) || typeof r["transactionHash"] !== "string" || r["transactionHash"].toLowerCase() !== transaction.toLowerCase())
685
+ return false;
686
+ if (typeof r["blockHash"] !== "string" || !HASH.test(r["blockHash"]))
687
+ return false;
688
+ const status = receipt?.status;
689
+ return (r["status"] === "0x1" && status === "success") || (r["status"] === "0x0" && status === "reverted");
690
+ }
691
+ catch {
692
+ return false;
693
+ }
694
+ }
695
+ /**
696
+ * Whether `other`, the transaction whose receipt ended the wait for `transaction`, carries this payment's own
697
+ * execution: the node shows it by its hash as a transaction of the same account at the same nonce making the same call
698
+ * (the same contract, the same call data), which is the transaction waited for at another fee. Its receipt is then this
699
+ * payment's. Any other transaction at the nonce is another's, and so is one the node does not show, or whose call is
700
+ * not known: for a transaction whose account and nonce were never learnt, they are noted from it, as viem matched it
701
+ * to them.
702
+ */
703
+ async function carries(rpc, notes, transaction, other, deadline) {
704
+ try {
705
+ const t = await shownBy(rpc, other, deadline);
706
+ if (t === undefined)
707
+ return false;
708
+ const v = noted(notes, transaction);
709
+ if (v.from === undefined) {
710
+ v.from = t.from;
711
+ v.nonce = t.nonce;
712
+ void keep(notes, transaction);
713
+ return false;
714
+ }
715
+ return v.call !== undefined && t.from === v.from && t.nonce === v.nonce && t.call === v.call;
716
+ }
717
+ catch {
718
+ return false;
719
+ }
720
+ }
11
721
  /**
12
722
  * The gas key as the classes take it, each transaction it sends (`writeContract`, `sendTransaction`) given to the
13
- * network's fee meter once sent and again once a class's wait for its receipt ends; every other member unchanged.
723
+ * network's fee meter once sent and again once a class's wait for its receipt ends. A wait for a receipt ends only with
724
+ * a receipt that carries the execution of the transaction waited for: its own (`ownReceipt`), or, for the key of the
725
+ * stock classes (`notes`), that of the same call signed again at its nonce at another fee (`carries`), which the
726
+ * class's answer then names (`landed`), or one that names no transaction where the node shows the transaction's own
727
+ * receipt (`ownShown`). viem's `waitForTransactionReceipt` answers the receipt of another transaction of the key at the
728
+ * same nonce where it finds one, and x402's classes answer success on any receipt whose status is success: a receipt
729
+ * that does not carry this payment ends the wait with an error, which the classes answer pending. Where `notes` is
730
+ * given, the key of the classes whose pending settlements `proven` reads (the one key every scheme of the network is
731
+ * given, `batch-settlement` included, whose notes no store writes), each call a class writes is signed before it is
732
+ * sent where the key can (`written`), so that what `proven` needs of it is known without the node; a wait makes none of
733
+ * the module's node calls before it, and none after it but for a receipt that does not name the transaction waited for
734
+ * (one lookup, `HELD_MS` at most); and a wait that ends with the transaction's own receipt forgets what is known of
735
+ * it, and deletes what `proven` kept for it. Every other member unchanged.
14
736
  */
15
- function counted(signer, meter, rpc) {
737
+ function counted(signer, meter, rpc, notes) {
16
738
  const count = (transaction) => meter.sent(transaction, () => feeShown(rpc, transaction, performance.now() + NODE_TIMEOUT_MS));
17
739
  return new Proxy(signer, {
18
740
  get(inner, member) {
@@ -21,7 +743,7 @@ function counted(signer, meter, rpc) {
21
743
  return value;
22
744
  if (member === "writeContract" || member === "sendTransaction") {
23
745
  return async (args) => {
24
- const transaction = (await value.call(inner, args));
746
+ const transaction = member === "writeContract" && notes !== undefined ? await written(inner, (a) => value.call(inner, a), args, rpc, notes) : (await value.call(inner, args));
25
747
  count(transaction);
26
748
  return transaction;
27
749
  };
@@ -29,7 +751,36 @@ function counted(signer, meter, rpc) {
29
751
  if (member === "waitForTransactionReceipt") {
30
752
  return async (args) => {
31
753
  try {
32
- return await value.call(inner, args);
754
+ // Its account and nonce, where they are not known from its signing, asked of the node beside the wait.
755
+ if (notes !== undefined && noted(notes, args.hash).from === undefined)
756
+ void noteSent(rpc, notes, args.hash);
757
+ let receipt;
758
+ try {
759
+ receipt = await value.call(inner, args);
760
+ }
761
+ catch (e) {
762
+ // And again where they are still not known: beside the class's answer.
763
+ if (notes !== undefined)
764
+ void noteSent(rpc, notes, args.hash);
765
+ throw e;
766
+ }
767
+ if (notes === undefined)
768
+ return ownReceipt(args.hash, receipt);
769
+ const named = receipt?.transactionHash;
770
+ if (typeof named !== "string") {
771
+ if (!(await ownShown(rpc, args.hash, receipt, performance.now() + HELD_MS))) {
772
+ throw new Error(`the receipt answered for ${args.hash} names no transaction, and the node does not show that transaction's own: its fate is not shown`);
773
+ }
774
+ }
775
+ else if (named.toLowerCase() !== args.hash.toLowerCase()) {
776
+ if (!HASH.test(named) || !(await carries(rpc, notes, args.hash, named, performance.now() + HELD_MS)))
777
+ return ownReceipt(args.hash, receipt);
778
+ capped(notes.landed, args.hash.toLowerCase(), named.toLowerCase());
779
+ count(named.toLowerCase());
780
+ }
781
+ // No longer needed once a receipt that carries it is shown: what is known of it, and what `proven` kept.
782
+ await forgetSent(notes, args.hash);
783
+ return receipt;
33
784
  }
34
785
  finally {
35
786
  count(args.hash);
@@ -40,6 +791,142 @@ function counted(signer, meter, rpc) {
40
791
  },
41
792
  });
42
793
  }
794
+ /**
795
+ * What one finalized block, read by its hash, shows at the nonce of `transaction`, a transaction `exact` or `upto`
796
+ * keeps as a pending settlement, of which `v` is known: undefined while it shows no other transaction of the account
797
+ * there (`nonceProof` is not `taken-by-another`; its search starts at the head noted as the transaction was signed, so
798
+ * that a node that keeps only recent state can answer it), or where that other transaction's call, or the receipt of
799
+ * one that makes the same call, cannot be read; else that transaction, and whether it executed the same call (the
800
+ * node's answer by the hash the proof names, of the same account and nonce, and its receipt on the finalized chain,
801
+ * `finalizedReceipt`). A finalized block's facts stand for ever, so what it showed is kept in memory and read no more. The answer
802
+ * is waited for `waitMs` at most: a proof that takes longer goes on, bounded by its own deadline, and a later call has
803
+ * its answer. A lookup that finds nothing, or a failed read, is undefined: it decides nothing.
804
+ */
805
+ async function takenBy(rpc, notes, transaction, v, waitMs) {
806
+ const key = transaction.toLowerCase();
807
+ const known = notes.taken.get(key);
808
+ if (known !== undefined)
809
+ return known;
810
+ if (v.from === undefined || v.nonce === undefined)
811
+ return undefined;
812
+ const { from, nonce, call, since } = v;
813
+ const prove = async () => {
814
+ const deadline = performance.now() + NODE_TIMEOUT_MS;
815
+ const proof = await nonceProof(rpc, from, BigInt(nonce), [key], { deadline, ...(since === undefined ? {} : { from: BigInt(since) }) });
816
+ if (proof.answer !== "taken-by-another")
817
+ return undefined;
818
+ let executed = false;
819
+ if (call !== undefined) {
820
+ const t = await shownBy(rpc, proof.transaction, deadline).catch(() => undefined);
821
+ if (t === undefined || t.from !== from || t.nonce !== nonce)
822
+ return undefined;
823
+ if (t.call === call) {
824
+ // The same call: whether it executed is its receipt's to state, on the finalized chain.
825
+ const r = await finalizedReceipt(rpc, proof.transaction, deadline);
826
+ if (r === undefined)
827
+ return undefined;
828
+ executed = r.status === 1;
829
+ }
830
+ }
831
+ return capped(notes.taken, key, { transaction: proof.transaction, executed });
832
+ };
833
+ let running = notes.proving.get(key);
834
+ if (running === undefined) {
835
+ running = prove()
836
+ .catch(() => undefined)
837
+ .finally(() => notes.proving.delete(key));
838
+ notes.proving.set(key, running);
839
+ }
840
+ let timer;
841
+ const late = new Promise((r) => {
842
+ timer = setTimeout(() => r(undefined), waitMs);
843
+ });
844
+ try {
845
+ return await Promise.race([running, late]);
846
+ }
847
+ finally {
848
+ clearTimeout(timer);
849
+ }
850
+ }
851
+ /**
852
+ * What is known of `transaction` where a class keeps it as a pending settlement: from memory, else from the module's
853
+ * state (after a restart), which is then held in memory again. Undefined where nothing is kept of it, or what is kept
854
+ * names no account and nonce.
855
+ */
856
+ async function keptOf(notes, transaction) {
857
+ const key = transaction.toLowerCase();
858
+ const v = notes.n.get(key);
859
+ if (v?.kept === true)
860
+ return v.from === undefined || v.nonce === undefined ? undefined : v;
861
+ const kept = await notes.state.get(sentAt(key));
862
+ if (!isRecord(kept) || typeof kept["from"] !== "string" || typeof kept["nonce"] !== "string" || !/^[0-9]+$/.test(kept["nonce"]))
863
+ return undefined;
864
+ return capped(notes.n, key, {
865
+ from: kept["from"].toLowerCase(),
866
+ nonce: kept["nonce"],
867
+ ...(typeof kept["call"] === "string" && HASH.test(kept["call"]) ? { call: kept["call"].toLowerCase() } : {}),
868
+ ...(typeof kept["since"] === "string" && /^[0-9]+$/.test(kept["since"]) ? { since: kept["since"] } : {}),
869
+ kept: true,
870
+ });
871
+ }
872
+ /**
873
+ * x402's pending-settlement store, as `exact` and `upto` keep in it the transaction they sent and wait for again on a
874
+ * repeat instead of sending. Where the class keeps a transaction, what is known of it (`counted`) is written to the
875
+ * module's state. A transaction it holds is given back to the class unless one finalized block, read by its hash, shows
876
+ * a different transaction of the same account at its nonce that did not execute its call (`takenBy`): another call, or
877
+ * the same call reverted. Then it can never land, and nothing executed its payment at its nonce: the entry is deleted,
878
+ * and the class checks the payment again and may send the same signed authorization, which the token or Permit2
879
+ * executes once. A transaction at its nonce that executed the same call executed this payment: nothing is let go, and
880
+ * the record's read answers the payment once it shows it. A lookup that finds nothing, a failed read or an account and
881
+ * nonce never learnt changes nothing. `batch-settlement` is not given it: the core never gives a repeat of a channel's
882
+ * deposit back to the class (its row is keyed by a digest, neither `resendable` nor `landsOnce`), so it would never be
883
+ * read.
884
+ */
885
+ function proven(store, rpc, notes) {
886
+ return {
887
+ async get(key) {
888
+ const transaction = await store.get(key);
889
+ if (transaction === undefined)
890
+ return transaction;
891
+ try {
892
+ const v = await keptOf(notes, transaction);
893
+ if (v === undefined)
894
+ return transaction;
895
+ const taken = await takenBy(rpc, notes, transaction, v, HELD_MS);
896
+ if (taken === undefined || taken.executed)
897
+ return transaction;
898
+ await store.delete(key);
899
+ await forgetSent(notes, transaction, true);
900
+ return undefined;
901
+ }
902
+ catch {
903
+ return transaction;
904
+ }
905
+ },
906
+ async set(key, transaction) {
907
+ const v = notes.n.get(transaction.toLowerCase());
908
+ if (v !== undefined && v.kept !== true) {
909
+ v.kept = true;
910
+ await keep(notes, transaction);
911
+ }
912
+ await store.set(key, transaction);
913
+ },
914
+ delete: (key) => store.delete(key),
915
+ };
916
+ }
917
+ /**
918
+ * `receipt` where it is the receipt of `transaction`; otherwise it throws, so that the escrow's class or the `erc7710`
919
+ * module answers the transaction pending and the record's read decides (neither keeps a pending settlement of its own). viem's `waitForTransactionReceipt` answers, by default, the receipt of another
920
+ * transaction of the same key at the same nonce where it finds one: a replacement of the same call, which the read
921
+ * then shows, or another payment's transaction, which paid nothing of this one.
922
+ */
923
+ export function ownReceipt(transaction, receipt) {
924
+ const hash = receipt?.transactionHash;
925
+ if (typeof hash !== "string" || hash.toLowerCase() !== transaction.toLowerCase()) {
926
+ throw new Error(`the receipt answered for ${transaction} is another transaction's (${String(hash)}): its own fate is not shown`);
927
+ }
928
+ return receipt;
929
+ }
43
930
  /** x402's class for `scheme`, given the module's key and configuration, unchanged. */
44
931
  function classOf(scheme, c, signer, pendingSettlementStore) {
45
932
  const factories = [...(c.eip6492AllowedFactories ?? [])];
@@ -50,7 +937,8 @@ function classOf(scheme, c, signer, pendingSettlementStore) {
50
937
  case "upto":
51
938
  return new UptoEvmScheme(signer, pending);
52
939
  case "auth-capture":
53
- return new AuthCaptureEvmScheme(signer, c.authCapture);
940
+ // The class's own store would keep a transaction it waited for in vain and wait on it again on every resend.
941
+ return new AuthCaptureEvmScheme(signer, { ...c.authCapture, pendingSettlementStore: KEEPS_NOTHING });
54
942
  case "batch-settlement":
55
943
  return new BatchSettlementEvmScheme(signer, undefined, { eip6492AllowedFactories: factories, ...pending });
56
944
  }
@@ -65,13 +953,46 @@ function payerOf(payload) {
65
953
  }
66
954
  return undefined;
67
955
  }
956
+ /**
957
+ * Whether the class's own `settle` is the check of a payment at `/settle`: a batch settlement's `claim`, `settle` or
958
+ * `refund`. The channel manager sends each under requirements of its own (amount `"0"`, no `extra`), which the class's
959
+ * `verify` refuses for a refund (`invalid_batch_settlement_evm_receiver_authorizer_mismatch`, as it reads the
960
+ * requirements' `receiverAuthorizer`); the manager itself never asks `verify`, and the class's `settle` checks the
961
+ * refundable amount and the signatures and simulates the contract's call before it sends anything.
962
+ */
963
+ function settleChecks(scheme, payload) {
964
+ const kind = payload.payload?.["type"];
965
+ return scheme === "batch-settlement" && (kind === "claim" || kind === "settle" || kind === "refund");
966
+ }
967
+ /**
968
+ * The reason `AuthCaptureEvmScheme` of `@x402/evm` 2.31.0 gives a lifecycle message whose expected amounts do not stand.
969
+ */
970
+ const UNEXPECTED_PAYMENT_STATE = "invalid_auth_capture_evm_unexpected_payment_state";
68
971
  /**
69
972
  * The class behind the profile's pure checks: a payment they refuse is answered with their reason and never reaches
70
973
  * the class; every other call is the class's own, its `getExtra` and `getSigners` included. At `/settle` of `upto`,
71
974
  * whose requirements carry the charge, the class's `verify` is given them at the maximum the payment accepted, as its
72
- * own `settle` verifies the permit before it submits.
975
+ * own `settle` verifies the permit before it submits. At `/settle` of a batch settlement's `claim`, `settle` or
976
+ * `refund`, which the class's `verify` does not take under the channel manager's requirements (`settleChecks`), the
977
+ * class's check is its own `settle`, which simulates the contract's call before it sends anything; at `/verify` the
978
+ * class's `verify` answers them, as it answers them without the settler. An escrow capture that also voids the
979
+ * payment's remainder (`carriesVoid`) is settled as the class settles it, its void sent once the capture settled; where
980
+ * the class answers the capture a success and the node does not show that void, its call goes to the gas key again,
981
+ * which sends only what every escrow call may be sent (`named`: its same signed bytes, or nothing); where its capture
982
+ * failed after a send the escrow took, or a transaction its claim named holds the capture's event, only the void is
983
+ * sent (the class's `verify` and `settle` of it), and the answer names the capture.
73
984
  */
74
- function checked(scheme, inner, pairings) {
985
+ function checked(scheme, inner, pairings, state, rpc, reader, landed) {
986
+ // The class's answer, naming the transaction whose receipt ended its wait where that was the same call signed again
987
+ // at its nonce (`counted`): the transaction that executed the payment, in place of the one the class sent.
988
+ const naming = (s) => {
989
+ const key = typeof s.transaction === "string" ? s.transaction.toLowerCase() : "";
990
+ const by = landed?.get(key);
991
+ if (by === undefined)
992
+ return s;
993
+ landed.delete(key);
994
+ return { ...s, transaction: by };
995
+ };
75
996
  return {
76
997
  scheme: inner.scheme,
77
998
  caipFamily: inner.caipFamily,
@@ -83,14 +1004,107 @@ function checked(scheme, inner, pairings) {
83
1004
  const payer = payerOf(payload);
84
1005
  return payer === undefined ? { isValid: false, invalidReason: a.refused } : { isValid: false, invalidReason: a.refused, payer };
85
1006
  }
1007
+ if (phaseOf(context) === "settle" && settleChecks(scheme, payload))
1008
+ return { isValid: true };
86
1009
  const held = scheme === "upto" && phaseOf(context) === "settle" ? { ...requirements, amount: payload.accepted.amount } : requirements;
87
- return inner.verify(payload, held, context);
1010
+ const v = await inner.verify(payload, held, context);
1011
+ // A capture that voids the payment's remainder, whose capture its own claim sent and the escrow took: at
1012
+ // `/settle`, its check is the class's check of the void it carries, which `settle` then sends. A capture the
1013
+ // claim's own transactions do not show landed keeps the class's refusal.
1014
+ const message = phaseOf(context) === "settle" && !v.isValid && v.invalidReason === UNEXPECTED_PAYMENT_STATE && escrowMessage(a) ? await messageKey(requirements.network, { payload, requirements }, a) : undefined;
1015
+ const remainder = message === undefined ? undefined : (voidOf({ payload, requirements }) ?? (await recordedVoid(state, message, { payload, requirements })));
1016
+ if (message !== undefined && remainder !== undefined) {
1017
+ const own = await listedOf(state, message);
1018
+ const landed = await captureLanded(reader(), rpc, { payload, requirements }, own, performance.now() + NODE_TIMEOUT_MS, true).catch(() => undefined);
1019
+ if (landed !== undefined)
1020
+ return inner.verify(remainder.payload, remainder.requirements, context);
1021
+ }
1022
+ return v;
88
1023
  },
89
1024
  async settle(payload, requirements, context) {
90
1025
  const a = await admit(scheme, { payload, requirements }, pairings);
91
1026
  if ("refused" in a)
92
1027
  return { success: false, errorReason: a.refused, transaction: "", network: requirements.network };
93
- return inner.settle(payload, requirements, context);
1028
+ const message = escrowMessage(a) ? await messageKey(requirements.network, { payload, requirements }, a) : undefined;
1029
+ if (message === undefined)
1030
+ return naming(await inner.settle(payload, requirements, context));
1031
+ // A capture that voids the payment's remainder, whose own capture an earlier settle of the claim sent and the escrow
1032
+ // took (its answer lost): the void is still to send, as x402's class sends it once its capture settled. Only the
1033
+ // void is sent, and the answer names the capture.
1034
+ // The void this body carries, recorded before anything is sent for the claim; else the one its claim carries.
1035
+ const presented = voidOf({ payload, requirements });
1036
+ if (presented !== undefined)
1037
+ await state.set(voidAt(message), presented.payload.payload);
1038
+ const remainder = presented ?? (await recordedVoid(state, message, { payload, requirements }));
1039
+ const landed = (named) => remainder === undefined ? Promise.resolve(undefined) : captureLanded(reader(), rpc, { payload, requirements }, named, performance.now() + NODE_TIMEOUT_MS, true).catch(() => undefined);
1040
+ const run = (p, names) => settlingMessage.run({ key: message, names, payment: p }, () => inner.settle(p.payload, p.requirements, context));
1041
+ // The capture's amount as x402's class answers a capture it settled (`amount` read with `BigInt`).
1042
+ const captured = (() => {
1043
+ try {
1044
+ return BigInt(String(payload.payload["amount"])).toString(10);
1045
+ }
1046
+ catch {
1047
+ return undefined;
1048
+ }
1049
+ })();
1050
+ // The answer for the capture where the void's answer decides it: the void's outcome and reason, with the capture's
1051
+ // transaction, network, payer and amount, never the void's amount.
1052
+ const forCapture = (v, transaction) => ({
1053
+ success: v.success,
1054
+ ...(v.success ? {} : { errorReason: v.errorReason, ...(v.errorMessage === undefined ? {} : { errorMessage: v.errorMessage }) }),
1055
+ transaction,
1056
+ network: v.network,
1057
+ ...(v.payer === undefined ? {} : { payer: v.payer }),
1058
+ ...(captured === undefined ? {} : { amount: captured }),
1059
+ });
1060
+ const voided = async (capture) => {
1061
+ const v = await run(remainder, []);
1062
+ // What was signed is kept until the read shows the message final: a success on a receipt at the head leaves the
1063
+ // row open, and a repeat may find the transaction it named not on the chain.
1064
+ // Answered for the capture: a void not sent leaves the capture's own transaction named, so the core answers it pending.
1065
+ return forCapture(v, capture);
1066
+ };
1067
+ const earlier = await landed(namedBefore());
1068
+ if (earlier !== undefined)
1069
+ return voided(earlier);
1070
+ const names = [];
1071
+ const s = await run({ payload, requirements }, names);
1072
+ if (s.success && remainder !== undefined) {
1073
+ // x402's class answers the capture a success whatever became of the void it sends after it: where the node
1074
+ // does not show that void (the capture's own transaction the only one named, or the void's send never reached
1075
+ // the node), its call goes to the gas key again now, which sends only its same signed bytes where one was signed
1076
+ // (`named`, never a new nonce on a lookup that found nothing), and where that fails the answer is the void's
1077
+ // failure naming the capture, which the core answers pending, and a repeat sends the void.
1078
+ const last = names.length >= 2 ? names.at(-1) : undefined;
1079
+ let held = null;
1080
+ if (last !== undefined) {
1081
+ try {
1082
+ held = await reader().transaction(last.toLowerCase());
1083
+ // The node holds the void unmined: the row stays open until it is mined, so that a void the node drops is
1084
+ // sent again. The capture's own transaction is named, so the core answers it pending.
1085
+ if (held !== null && (await reader().receipt(last.toLowerCase())) === null) {
1086
+ return forCapture({ success: false, errorReason: "the void of the remainder is not yet mined", transaction: "", network: s.network, ...(s.payer === undefined ? {} : { payer: s.payer }) }, s.transaction);
1087
+ }
1088
+ }
1089
+ catch (e) {
1090
+ // The node could not say: nothing more is sent. The capture's own transaction is named, so the core answers
1091
+ // it pending, and a repeat finds the void the node holds or sends it.
1092
+ return forCapture({ success: false, errorReason: e instanceof Error ? e.message : "the node's answer for the void is unreadable", transaction: "", network: s.network, ...(s.payer === undefined ? {} : { payer: s.payer }) }, s.transaction);
1093
+ }
1094
+ }
1095
+ if (held === null) {
1096
+ const v = await run(remainder, []);
1097
+ if (!v.success)
1098
+ return forCapture(v, s.transaction);
1099
+ }
1100
+ }
1101
+ // A success on a receipt at the head: the core keeps the row open until its read shows the message final, which
1102
+ // deletes what was signed (`read`); until then a repeat may need it.
1103
+ if (s.success || remainder === undefined)
1104
+ return s;
1105
+ // The class's capture failed after a send: where the escrow took it (its answer lost), the void is sent now.
1106
+ const now = await landed(names);
1107
+ return now === undefined ? s : voided(now);
94
1108
  },
95
1109
  };
96
1110
  }
@@ -98,14 +1112,24 @@ function checked(scheme, inner, pairings) {
98
1112
  * The `evm` module's schemes on one network, each x402's class with what the core needs beside it, the gas key counted
99
1113
  * by `meter`, the network's fee meter. `pending` is where `exact`, `upto` and `batch-settlement` keep a settlement they
100
1114
  * sent and the chain does not yet show, so that a retried settle reconciles against it; each class keeps its own in
101
- * memory where absent.
1115
+ * memory where absent. `core` names an escrow call's replacement in the row before it is sent (`Core.naming`) and
1116
+ * gives the settle wait a tip-only replacement waits for; where absent, no replacement is made.
102
1117
  */
103
- export function evmModules(c, meter, pending) {
1118
+ export function evmModules(c, meter, state, pending, core) {
104
1119
  const network = c.network;
105
- const signer = counted(c.signer, meter, c.rpc);
1120
+ // The blocks a proof showed on the finalized chain, kept so that a later proof walks on from them.
1121
+ registerAnchors(c.rpc, anchorsIn(state, `finalized-anchors:${c.network}`));
1122
+ // What is known of each transaction the stock classes send, and of what took the place of one they keep.
1123
+ const notes = pending === undefined ? undefined : { n: new Map(), state, landed: new Map(), taken: new Map(), proving: new Map() };
1124
+ const signer = counted(c.signer, meter, c.rpc, notes);
1125
+ const stored = pending === undefined || notes === undefined ? undefined : proven(pending, c.rpc, notes);
106
1126
  return (c.schemes ?? SCHEMES).map((scheme) => {
1127
+ const key = scheme === "auth-capture" ? counted(named(c.signer, c.rpc, state), meter, c.rpc) : signer;
107
1128
  const pairings = PAIRINGS[scheme];
1129
+ const facilitator = checked(scheme, classOf(scheme, c, key, scheme === "exact" || scheme === "upto" ? stored : pending), pairings, state, c.rpc, () => evmReader(c.network, c.rpc, performance.now() + NODE_TIMEOUT_MS), scheme === "auth-capture" ? undefined : notes?.landed);
108
1130
  const record = {
1131
+ // x402's classes answer a success on viem's first receipt, at the head.
1132
+ successAtHead: true,
109
1133
  async instrument(p) {
110
1134
  const a = await admit(scheme, p, pairings);
111
1135
  return "refused" in a ? a : instrumentOf(network, p, a);
@@ -114,8 +1138,87 @@ export function evmModules(c, meter, pending) {
114
1138
  const a = await admit(scheme, p, pairings);
115
1139
  if ("refused" in a)
116
1140
  return { outcome: "live", answer: { state: "unreadable", reason: "unparseable", foreign: [] } };
117
- return readOf(evmReader(c.network, c.rpc, at.deadline), a, at);
1141
+ const reader = evmReader(c.network, c.rpc, at.deadline);
1142
+ if (scheme === "batch-settlement" && a.later === true && at.transaction !== undefined && kindOf(p) === "refund") {
1143
+ const reverted = await revertedAtFinalized(c.rpc, at.transaction.toLowerCase(), at.deadline).catch(() => undefined);
1144
+ if (reverted !== undefined)
1145
+ return reverted;
1146
+ const refunded = await refundedAtFinalized(c.rpc, at.transaction.toLowerCase(), p, at.deadline).catch(() => undefined);
1147
+ if (refunded !== undefined)
1148
+ return refunded;
1149
+ }
1150
+ if (!escrowMessage(a)) {
1151
+ const read = await readOf(reader, a, at);
1152
+ // Final: no settle of the row gives the payment to the class again, so what was kept of the transaction the
1153
+ // row names is no longer needed. A failure to delete it leaves it, and changes no answer.
1154
+ if ((scheme === "exact" || scheme === "upto") && notes !== undefined && at.transaction !== undefined && read.outcome === "final") {
1155
+ await forgetSent(notes, at.transaction, true);
1156
+ }
1157
+ // The escrow's hold (its authorize or charge): an authorization the chain shows unused, while a transaction of
1158
+ // the gas key is unmined, which may be the hold's own send. Read as `escrowRead` reads a later message: pending
1159
+ // (`below-mark`), so that no repeat signs the hold again beside it, at any nonce.
1160
+ if (scheme === "auth-capture" && read.outcome === "live" && read.answer.state === "pending" && read.answer.reason === "instrument-live" && (await keyHolds(c.rpc, gasKeys(c.signer), at.deadline))) {
1161
+ return outcomeOf({ state: "pending", reason: "below-mark", ...(at.transaction === undefined ? {} : { transaction: at.transaction }), foreign: [] });
1162
+ }
1163
+ return read;
1164
+ }
1165
+ const message = await messageKey(network, p, a);
1166
+ // A capture whose claim carries the void of its remainder is read as carrying it, whatever body is presented.
1167
+ const voids = message !== undefined && (await state.get(voidAt(message))) !== undefined;
1168
+ // The record names one of the transactions signed at a nonce (a replacement, or the one it replaced where the
1169
+ // node holds that one): the read judges the one at that nonce the node shows a receipt for, whichever is named.
1170
+ const named = message === undefined || at.transaction === undefined ? at.transaction : await shownAtNonce(state, message, at.transaction, reader);
1171
+ // The position kept for the message where the row holds none (the read of the head at its claim failed).
1172
+ const kept = message === undefined || at.from !== undefined ? undefined : await state.get(positionAt(message));
1173
+ const from = at.from === undefined && typeof kept === "string" && /^[0-9]+$/.test(kept) ? { from: kept } : {};
1174
+ const own = message === undefined ? [] : await signedCalls(state, message, p, at.transaction);
1175
+ const read = await escrowRead(reader, c.rpc, gasKeys(c.signer), p, { ...at, ...from, ...(named === undefined || named === at.transaction ? {} : { transaction: named }) }, voids, own);
1176
+ // The signed bytes are no longer needed: a failure to delete them leaves them, and changes no answer.
1177
+ if (message !== undefined && read.outcome === "final")
1178
+ await forget(state, message).catch(() => { });
1179
+ return read;
118
1180
  },
1181
+ async position(p, at) {
1182
+ const a = await admit(scheme, p, pairings);
1183
+ if ("refused" in a || !escrowMessage(a))
1184
+ return undefined;
1185
+ const position = await escrowPosition(c.rpc, at.deadline);
1186
+ // Kept for the message too: its first signing reads the head again only where none is kept (`named`).
1187
+ const message = await messageKey(network, p, a);
1188
+ if (message !== undefined && (await state.get(positionAt(message))) === undefined)
1189
+ await state.set(positionAt(message), position);
1190
+ return position;
1191
+ },
1192
+ ...(scheme === "auth-capture"
1193
+ ? {
1194
+ // Before a repeat reads the chain: each transaction the row names, where the node holds it unmined for fees
1195
+ // below those it asks, is replaced at its own nonce (`replaced`). Never `gone`: a name stays in the row,
1196
+ // and anything else is sent only by the class's settle (`named`), a new nonce only on the finalized chain's
1197
+ // facts.
1198
+ async resend(p, transaction, at) {
1199
+ const a = await admit(scheme, p, pairings);
1200
+ if ("refused" in a || !escrowMessage(a))
1201
+ return "kept";
1202
+ // Only for a payment the class's own check passes (its receiver authorizer's signature, the escrow's
1203
+ // amounts): a copy it refuses sends nothing, not even the bytes signed for the message it copies.
1204
+ const message = await messageKey(network, p, a);
1205
+ if (message === undefined)
1206
+ return "kept";
1207
+ // The one the node shows at the nonce, the last signed of those it shows: a replacement it never took
1208
+ // is judged only once the node shows it, and each is replaced only on the repeat's call for its own hash.
1209
+ const shown = await heldAtNonce(c.rpc, state, message, transaction, at.deadline);
1210
+ const last = shown !== undefined && keccak256(shown.signed) === transaction.toLowerCase() ? shown.signed : undefined;
1211
+ // The void of a capture's remainder is checked as the void it is, by the class's check of that void, since
1212
+ // the class refuses the capture once the capture executed.
1213
+ const subject = last !== undefined && isVoidCall(parseTransaction(last).data ?? "0x") ? (voidOf(p) ?? (await recordedVoid(state, message, p))) : p;
1214
+ if (subject === undefined || (await facilitator.verify(subject.payload, subject.requirements).catch(() => undefined))?.isValid !== true)
1215
+ return "kept";
1216
+ if (last !== undefined && core !== undefined)
1217
+ await replaced(c.signer, c.rpc, state, message, last, shown?.when, meter, core, at.deadline, shown?.unshown === true);
1218
+ return "kept";
1219
+ },
1220
+ }
1221
+ : {}),
119
1222
  };
120
1223
  return {
121
1224
  descriptor: {
@@ -128,7 +1231,7 @@ export function evmModules(c, meter, pending) {
128
1231
  acceptsZero: scheme === "exact" ? [exactEip3009.id] : [],
129
1232
  },
130
1233
  network,
131
- facilitator: checked(scheme, classOf(scheme, c, signer, pending), pairings),
1234
+ facilitator,
132
1235
  record,
133
1236
  fees: {
134
1237
  paysFee: () => true,
@@ -146,9 +1249,15 @@ export function evmModules(c, meter, pending) {
146
1249
  export const starter = {
147
1250
  name: "evm",
148
1251
  async start(networks, core) {
1252
+ // An auth-capture call is signed before it is sent: a key that cannot is refused at the start, not at its first hold.
1253
+ for (const c of networks) {
1254
+ if ((c.schemes ?? SCHEMES).includes("auth-capture") && (typeof c.signer.signTransaction !== "function" || typeof c.signer.sendRawTransaction !== "function")) {
1255
+ throw new TypeError(`evm on ${c.network}: auth-capture needs a signer that gives signTransaction and sendRawTransaction`);
1256
+ }
1257
+ }
149
1258
  const pending = core.state.pendingSettlements();
150
1259
  return {
151
- registrations: networks.flatMap((c) => evmModules(c, core.meter(c.network), pending).map((module) => ({ network: module.network, module, own: [] }))),
1260
+ registrations: networks.flatMap((c) => evmModules(c, core.meter(c.network), core.state, pending, core).map((module) => ({ network: module.network, module, own: [] }))),
152
1261
  };
153
1262
  },
154
1263
  };