@integraledger/profile-facilitator 0.3.1 → 0.5.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 (90) hide show
  1. package/README.md +642 -456
  2. package/dist/answers.d.ts +11 -4
  3. package/dist/answers.js +24 -0
  4. package/dist/core.d.ts +51 -0
  5. package/dist/core.js +758 -0
  6. package/dist/http.d.ts +20 -3
  7. package/dist/http.js +32 -7
  8. package/dist/index.d.ts +12 -36
  9. package/dist/index.js +9 -162
  10. package/dist/module.d.ts +372 -0
  11. package/dist/module.js +13 -0
  12. package/dist/modules/algorand/index.d.ts +22 -0
  13. package/dist/modules/algorand/index.js +247 -0
  14. package/dist/modules/algorand/own.d.ts +26 -0
  15. package/dist/modules/algorand/own.js +231 -0
  16. package/dist/modules/aptos/index.d.ts +23 -0
  17. package/dist/modules/aptos/index.js +232 -0
  18. package/dist/modules/cardano/index.d.ts +18 -0
  19. package/dist/modules/cardano/index.js +124 -0
  20. package/dist/modules/casper/index.d.ts +120 -0
  21. package/dist/modules/casper/index.js +442 -0
  22. package/dist/modules/concordium/index.d.ts +16 -0
  23. package/dist/modules/concordium/index.js +77 -0
  24. package/dist/modules/erc7710/index.d.ts +26 -0
  25. package/dist/modules/erc7710/index.js +220 -0
  26. package/dist/modules/evm/forms.d.ts +74 -0
  27. package/dist/modules/evm/forms.js +182 -0
  28. package/dist/modules/evm/index.d.ts +40 -0
  29. package/dist/modules/evm/index.js +148 -0
  30. package/dist/modules/evm/node.d.ts +29 -0
  31. package/dist/modules/evm/node.js +222 -0
  32. package/dist/modules/hedera/executor.d.ts +63 -0
  33. package/dist/modules/hedera/executor.js +343 -0
  34. package/dist/modules/hedera/index.d.ts +23 -0
  35. package/dist/modules/hedera/index.js +136 -0
  36. package/dist/modules/hedera/mirror.d.ts +32 -0
  37. package/dist/modules/hedera/mirror.js +111 -0
  38. package/dist/modules/index.d.ts +23 -0
  39. package/dist/modules/index.js +24 -0
  40. package/dist/modules/lnbtc/index.d.ts +10 -0
  41. package/dist/modules/lnbtc/index.js +111 -0
  42. package/dist/modules/near/index.d.ts +18 -0
  43. package/dist/modules/near/index.js +246 -0
  44. package/dist/modules/polkadot/index.d.ts +12 -0
  45. package/dist/modules/polkadot/index.js +149 -0
  46. package/dist/modules/polkadot/rail.d.ts +40 -0
  47. package/dist/{polkadot.js → modules/polkadot/rail.js} +214 -288
  48. package/dist/modules/solana/index.d.ts +60 -0
  49. package/dist/modules/solana/index.js +304 -0
  50. package/dist/modules/solana/reader.d.ts +25 -0
  51. package/dist/modules/solana/reader.js +194 -0
  52. package/dist/modules/solana/state.d.ts +6 -0
  53. package/dist/modules/solana/state.js +103 -0
  54. package/dist/modules/starknet/index.d.ts +35 -0
  55. package/dist/modules/starknet/index.js +541 -0
  56. package/dist/modules/starknet/node.d.ts +78 -0
  57. package/dist/modules/starknet/node.js +339 -0
  58. package/dist/modules/stellar/index.d.ts +44 -0
  59. package/dist/modules/stellar/index.js +481 -0
  60. package/dist/modules/stellar/node.d.ts +57 -0
  61. package/dist/modules/stellar/node.js +151 -0
  62. package/dist/modules/sui/index.d.ts +16 -0
  63. package/dist/modules/sui/index.js +309 -0
  64. package/dist/modules/sui/node.d.ts +49 -0
  65. package/dist/modules/sui/node.js +197 -0
  66. package/dist/modules/ton/index.d.ts +16 -0
  67. package/dist/modules/ton/index.js +73 -0
  68. package/dist/modules/tron/index.d.ts +12 -0
  69. package/dist/modules/tron/index.js +120 -0
  70. package/dist/modules/tron/rail.d.ts +32 -0
  71. package/dist/{tron.js → modules/tron/rail.js} +206 -195
  72. package/dist/modules/xrpl/index.d.ts +28 -0
  73. package/dist/modules/xrpl/index.js +299 -0
  74. package/dist/modules/xrpl/node.d.ts +52 -0
  75. package/dist/modules/xrpl/node.js +231 -0
  76. package/dist/modules/xrpl/upto.d.ts +5 -0
  77. package/dist/modules/xrpl/upto.js +269 -0
  78. package/dist/record.d.ts +131 -0
  79. package/dist/record.js +330 -0
  80. package/dist/unexpected.d.ts +3 -2
  81. package/dist/unexpected.js +2 -1
  82. package/dist/wrapper.d.ts +68 -0
  83. package/dist/wrapper.js +126 -0
  84. package/package.json +47 -12
  85. package/dist/polkadot.d.ts +0 -21
  86. package/dist/store.d.ts +0 -59
  87. package/dist/store.js +0 -103
  88. package/dist/tron.d.ts +0 -12
  89. /package/dist/{base58check.d.ts → modules/tron/base58check.d.ts} +0 -0
  90. /package/dist/{base58check.js → modules/tron/base58check.js} +0 -0
@@ -0,0 +1,26 @@
1
+ import type { FacilitatorEvmSigner } from "@x402/evm";
2
+ import type { Handoff, ModuleStarter } from "../../module.js";
3
+ import type { EvmModule } from "../evm/index.js";
4
+ /** One `eip155` network the `erc7710` module serves. */
5
+ export interface Erc7710Config {
6
+ readonly network: `eip155:${number}`;
7
+ /** The seller's node, an EVM JSON-RPC endpoint, which lcp's reads and the fee's read go through. */
8
+ readonly rpc: string;
9
+ /**
10
+ * The seller's gas key, the delegate the leaf delegations it redeems name, as x402's EVM classes take a signer; it must
11
+ * simulate calls (`eth_simulateV1`), since the simulation's logs show the transfer the redemption would make.
12
+ */
13
+ readonly signer: FacilitatorEvmSigner;
14
+ }
15
+ /**
16
+ * The `erc7710` module on one network, as the hand-off the `exact` registration there takes: every payment whose option
17
+ * names the `erc7710` method, by the option's own member, before x402's `exact` class sees it.
18
+ */
19
+ export declare function erc7710Handoff(c: Erc7710Config): Handoff & {
20
+ readonly module: EvmModule;
21
+ };
22
+ /**
23
+ * How the core starts the module: the configuration's `erc7710` member lists the networks, one entry each, and on each
24
+ * the module is offered to the `exact` registration there, behind which it takes every option naming `erc7710`.
25
+ */
26
+ export declare const starter: ModuleStarter<readonly Erc7710Config[]>;
@@ -0,0 +1,220 @@
1
+ /**
2
+ * The `erc7710` module: x402's `exact` scheme with the `erc7710` asset transfer method, at both of lcp's levels (the
3
+ * leaf delegation's salt H, through the reference DelegationManager; and every other delegation, which signs no H).
4
+ * x402 specifies the method and leaves the `permissionContext` opaque, and no published facilitator class settles it,
5
+ * so the module is the settler's own: it simulates the redemption the payment names, and then sends it, calling
6
+ * `redeemDelegations` on the delegation manager the payload names with one single-call execution that transfers the
7
+ * option's amount of its asset to `payTo`. Its key is the seller's gas key, which must be the delegate the leaf
8
+ * delegation names (or the reference implementation's wildcard delegate); it sends the transaction and pays its gas.
9
+ * It registers nothing of its own: it is offered to the `exact` registration the `evm` module makes on each of its
10
+ * networks, which hands it every payment whose option names `erc7710`, and the settler does not start where the `evm`
11
+ * module does not register `exact` on such a network.
12
+ */
13
+ import { decodePermissionContext } from "@integraledger/lcp/evm";
14
+ import { isRefusal } from "@integraledger/lcp";
15
+ import { encodeFunctionData, encodePacked, getAddress, isAddress, isHex } from "viem";
16
+ import { admit, ERC7710_PAIRINGS, instrumentOf, readOf } from "../evm/forms.js";
17
+ import { chargedFrom, evmReader } from "../evm/node.js";
18
+ /** The reference implementation's wildcard delegate, which any redeemer may redeem as. */
19
+ const ANY_DELEGATE = "0x0000000000000000000000000000000000000a11";
20
+ /** keccak256("Transfer(address,address,uint256)"). */
21
+ const TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
22
+ /** ERC-7579's mode for one call that reverts on failure: call type single (0x00), exec type default (0x00). */
23
+ const SINGLE_DEFAULT_MODE = `0x${"00".repeat(32)}`;
24
+ const REDEEM_ABI = [
25
+ {
26
+ type: "function",
27
+ name: "redeemDelegations",
28
+ stateMutability: "nonpayable",
29
+ inputs: [
30
+ { name: "_permissionContexts", type: "bytes[]" },
31
+ { name: "_modes", type: "bytes32[]" },
32
+ { name: "_executionCallDatas", type: "bytes[]" },
33
+ ],
34
+ outputs: [],
35
+ },
36
+ ];
37
+ const TRANSFER_ABI = [
38
+ {
39
+ type: "function",
40
+ name: "transfer",
41
+ stateMutability: "nonpayable",
42
+ inputs: [
43
+ { name: "to", type: "address" },
44
+ { name: "value", type: "uint256" },
45
+ ],
46
+ outputs: [{ type: "bool" }],
47
+ },
48
+ ];
49
+ function redemptionOf(payload, requirements) {
50
+ const p = payload.payload;
51
+ const manager = p["delegationManager"];
52
+ const context = p["permissionContext"];
53
+ const delegator = p["delegator"];
54
+ if (typeof manager !== "string" || !isAddress(manager) || typeof delegator !== "string" || !isAddress(delegator))
55
+ return undefined;
56
+ if (typeof context !== "string" || !isHex(context) || !isAddress(requirements.asset) || !isAddress(requirements.payTo))
57
+ return undefined;
58
+ return {
59
+ manager: getAddress(manager),
60
+ context: context,
61
+ delegator: getAddress(delegator),
62
+ token: getAddress(requirements.asset),
63
+ payTo: getAddress(requirements.payTo),
64
+ amount: BigInt(requirements.amount),
65
+ };
66
+ }
67
+ /** The `redeemDelegations` call the redemption is: one context, one single-call execution of the token's `transfer`. */
68
+ function redeemCall(r) {
69
+ const transfer = encodeFunctionData({ abi: TRANSFER_ABI, functionName: "transfer", args: [r.payTo, r.amount] });
70
+ const execution = encodePacked(["address", "uint256", "bytes"], [r.token, 0n, transfer]);
71
+ return [[r.context], [SINGLE_DEFAULT_MODE], [execution]];
72
+ }
73
+ function same(a, b) {
74
+ return typeof a === "string" && a.toLowerCase() === b.toLowerCase();
75
+ }
76
+ /** Whether `logs` hold the token's `Transfer` of exactly the option's amount from the delegator to `payTo`. */
77
+ function transfers(logs, r) {
78
+ const word = (a) => `0x${a.slice(2).toLowerCase().padStart(64, "0")}`;
79
+ return (logs ?? []).some((l) => same(l.address, r.token) &&
80
+ l.topics.length === 3 &&
81
+ same(l.topics[0], TRANSFER_TOPIC) &&
82
+ same(l.topics[1], word(r.delegator)) &&
83
+ same(l.topics[2], word(r.payTo)) &&
84
+ isHex(l.data) &&
85
+ l.data.length === 66 &&
86
+ BigInt(l.data) === r.amount);
87
+ }
88
+ /** The module's own facilitator for x402's `erc7710` method. */
89
+ function facilitatorOf(c) {
90
+ const signer = c.signer;
91
+ /** lcp's checks, the leaf's delegate, the manager's code and the simulation, in that order; nothing is sent. */
92
+ async function check(payload, requirements) {
93
+ const a = await admit("erc7710", { payload, requirements }, ERC7710_PAIRINGS);
94
+ if ("refused" in a)
95
+ return { isValid: false, invalidReason: a.refused };
96
+ const r = redemptionOf(payload, requirements);
97
+ if (r === undefined)
98
+ return { isValid: false, invalidReason: "invalid_payload" };
99
+ const payer = r.delegator;
100
+ // A context the reference manager's encoding reads names its leaf's delegate, which alone may redeem it; another
101
+ // manager's context is opaque, and its simulation shows whether the module's key may redeem it. The key sends from
102
+ // its first address, `writeContract` taking no account, so that is the delegate the leaf must name, and the account
103
+ // the simulation runs from.
104
+ const delegations = decodePermissionContext(r.context);
105
+ const from = signer.getAddresses()[0];
106
+ if (from === undefined)
107
+ return { isValid: false, invalidReason: "invalid_payload", payer };
108
+ if (!isRefusal(delegations) && delegations.length > 0) {
109
+ const delegate = delegations[0].delegate.toLowerCase();
110
+ if (delegate !== ANY_DELEGATE && delegate !== from.toLowerCase())
111
+ return { isValid: false, invalidReason: "invalid_payload", payer };
112
+ }
113
+ const code = await signer.getCode({ address: r.manager });
114
+ if (code === undefined || code === "0x")
115
+ return { isValid: false, invalidReason: "invalid_transaction", payer };
116
+ if (signer.simulateCalls === undefined)
117
+ return { isValid: false, invalidReason: "invalid_transaction", payer };
118
+ const [contexts, modes, executions] = redeemCall(r);
119
+ const data = encodeFunctionData({ abi: REDEEM_ABI, functionName: "redeemDelegations", args: [contexts, modes, executions] });
120
+ const simulated = await signer.simulateCalls({ account: from, calls: [{ to: r.manager, data }] });
121
+ const result = simulated.results[0];
122
+ if (result === undefined || result.status !== "success" || !transfers(result.logs, r)) {
123
+ return { isValid: false, invalidReason: "invalid_transaction", payer };
124
+ }
125
+ return { redemption: r, from };
126
+ }
127
+ return {
128
+ scheme: "exact",
129
+ caipFamily: "eip155:*",
130
+ getExtra: () => undefined,
131
+ getSigners: () => [...signer.getAddresses()],
132
+ async verify(payload, requirements) {
133
+ const checked = await check(payload, requirements);
134
+ return "redemption" in checked ? { isValid: true, payer: checked.redemption.delegator } : checked;
135
+ },
136
+ async settle(payload, requirements) {
137
+ const network = requirements.network;
138
+ const checked = await check(payload, requirements);
139
+ if (!("redemption" in checked)) {
140
+ return { success: false, errorReason: checked.invalidReason ?? "invalid_payload", transaction: "", network, ...(checked.payer === undefined ? {} : { payer: checked.payer }) };
141
+ }
142
+ const r = checked.redemption;
143
+ const payer = r.delegator;
144
+ let transaction;
145
+ try {
146
+ transaction = (await signer.writeContract({
147
+ address: r.manager,
148
+ abi: REDEEM_ABI,
149
+ functionName: "redeemDelegations",
150
+ args: redeemCall(r),
151
+ }));
152
+ }
153
+ catch {
154
+ return { success: false, errorReason: "invalid_transaction", transaction: "", network, payer };
155
+ }
156
+ let receipt;
157
+ try {
158
+ receipt = await signer.waitForTransactionReceipt({ hash: transaction });
159
+ }
160
+ catch {
161
+ return { success: false, errorReason: "settlement_pending", transaction, network, payer };
162
+ }
163
+ if (receipt.status !== "success" || !transfers(receipt.logs, r)) {
164
+ return { success: false, errorReason: "invalid_transaction", transaction, network, payer };
165
+ }
166
+ return { success: true, transaction, network, payer };
167
+ },
168
+ };
169
+ }
170
+ /**
171
+ * The `erc7710` module on one network, as the hand-off the `exact` registration there takes: every payment whose option
172
+ * names the `erc7710` method, by the option's own member, before x402's `exact` class sees it.
173
+ */
174
+ export function erc7710Handoff(c) {
175
+ const network = c.network;
176
+ const record = {
177
+ async instrument(p) {
178
+ const a = await admit("erc7710", p, ERC7710_PAIRINGS);
179
+ return "refused" in a ? a : instrumentOf(network, p, a);
180
+ },
181
+ // The level that signs no H is found only by the transaction the record holds, the one this module's settle named.
182
+ async read(p, at) {
183
+ const a = await admit("erc7710", p, ERC7710_PAIRINGS);
184
+ if ("refused" in a)
185
+ return { outcome: "live", answer: { state: "unreadable", reason: "unparseable", foreign: [] } };
186
+ return readOf(evmReader(c.network, c.rpc, at.deadline), a, at);
187
+ },
188
+ };
189
+ const module = {
190
+ descriptor: { name: "erc7710", key: "relayer", pairings: ERC7710_PAIRINGS, acceptsZero: false },
191
+ network,
192
+ facilitator: facilitatorOf(c),
193
+ record,
194
+ fees: {
195
+ paysFee: () => true,
196
+ payerBroadcast: () => false,
197
+ charged: chargedFrom(c.rpc),
198
+ },
199
+ };
200
+ return {
201
+ claim: {
202
+ by: "option",
203
+ claims: (requirements) => requirements.scheme === "exact" && requirements.extra?.["assetTransferMethod"] === "erc7710",
204
+ },
205
+ module,
206
+ };
207
+ }
208
+ /**
209
+ * How the core starts the module: the configuration's `erc7710` member lists the networks, one entry each, and on each
210
+ * the module is offered to the `exact` registration there, behind which it takes every option naming `erc7710`.
211
+ */
212
+ export const starter = {
213
+ name: "erc7710",
214
+ async start(networks) {
215
+ return {
216
+ registrations: [],
217
+ handoffs: networks.map((c) => ({ scheme: "exact", network: c.network, handoff: erc7710Handoff(c) })),
218
+ };
219
+ },
220
+ };
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The EVM forms x402's published classes settle, as lcp's codecs read them: which pairing a payment is, the pure checks
3
+ * of its profile, the instrument the record keys it by, how long a final row is kept, and lcp's read of it. Nothing here
4
+ * reads the chain or the clock but the read itself.
5
+ */
6
+ import { type PairingId } from "@integraledger/lcp";
7
+ import { type EvmReader } from "@integraledger/lcp/evm";
8
+ import type { Network } from "@x402/core/types";
9
+ import { type ChainRead, type Instrumented, type Refused, type X402Payment } from "../../module.js";
10
+ /** The forms of one scheme on EVM, by the lcp pairing ids the scheme's class submits. */
11
+ export type EvmScheme = "exact" | "upto" | "auth-capture" | "batch-settlement";
12
+ /** The pairings each scheme's class submits on an `eip155` network. */
13
+ export declare const PAIRINGS: {
14
+ readonly exact: readonly ["x402/exact/eip155/eip3009", "x402/exact/eip155/permit2"];
15
+ readonly upto: readonly ["x402/upto/eip155/permit2"];
16
+ readonly "auth-capture": readonly ["x402/auth-capture/eip155/eip3009", "x402/auth-capture/eip155/permit2"];
17
+ readonly "batch-settlement": readonly ["x402/batch-settlement/eip155"];
18
+ };
19
+ /** Both ERC-7710 levels, which share the `erc7710` option of `exact`. */
20
+ export declare const ERC7710_PAIRINGS: readonly ["x402/exact/eip155/erc7710", "x402/exact/eip155/erc7710-salt"];
21
+ type EvmPairing = (typeof PAIRINGS)[EvmScheme][number] | (typeof ERC7710_PAIRINGS)[number];
22
+ /** A presented payment's read keys, as the pairing's `reference` gives them: an object lcp checks again at `status`. */
23
+ type Ref = Record<string, unknown>;
24
+ /** What the pure checks found: the payment's pairing and the read keys lcp gives it, where its form has them. */
25
+ export interface Admitted {
26
+ readonly pairing: EvmPairing;
27
+ readonly ref?: Ref;
28
+ }
29
+ /**
30
+ * The options of `exact` on EVM that no published EVM class may settle: one that pays several payees (a non-empty
31
+ * `extra.splits`, which `exact` does not carry), and Circle's batched option, which signs under the Gateway Wallet's
32
+ * EIP-712 domain and not the token's (`extra.name` `GatewayWalletBatched`, or an `extra.verifyingContract` other than
33
+ * the asset). Each is refused before x402's class is asked, which reads none of these members.
34
+ */
35
+ export declare function exactOptionRefused(requirements: {
36
+ readonly asset: string;
37
+ readonly extra?: Record<string, unknown>;
38
+ }): boolean;
39
+ /**
40
+ * The profile's pure checks of a payment answering an option of `scheme`: the option is one of the pairings `pairings`
41
+ * names, as lcp's option filter reads it alone (`invalid_payment_requirements` otherwise), and the payment is that
42
+ * pairing's as lcp's `reference` reads it against the option (`invalid_payload` otherwise). A batch settlement's
43
+ * payment that is no opening has no reference: lcp's channel read holds its configuration to its voucher's channel,
44
+ * and the claim, settle and refund calls a resource server makes of the channel, which lcp does not decode, are x402's
45
+ * class's to check.
46
+ */
47
+ export declare function admit(scheme: EvmScheme | "erc7710", p: X402Payment, pairings: readonly PairingId[]): Promise<Admitted | Refused>;
48
+ /**
49
+ * The record's key and keep for an admitted payment. EIP-3009: the network, the token, the authorization's `from` and
50
+ * its nonce, kept to `validBefore`; the auth-capture escrow's ERC-3009 collector signs its nonce in the token's one
51
+ * nonce space, so it is keyed alike. Permit2: the network, the owner and the permit's nonce in Permit2's one bitmap per
52
+ * owner, kept to the deadline. Neither is the nonce alone, and for an agreement the nonce signed is the agreement's own
53
+ * value, so one payer's agreement and payment under one H are two rows. A batch settlement's call and an ERC-7710
54
+ * redemption hold no single-use value: each is keyed by a digest, for the settler's life. A batch call's is the digest
55
+ * of its signed payload. A redemption's is the digest of the delegation it redeems as signed, whatever its spelling: the
56
+ * manager and the delegator in lowercase, and the leaf delegation's EIP-712 hash where the context decodes as the
57
+ * reference manager's encoding (the hash commits to its caveats, its salt and, through its authority, the chain above
58
+ * it; not to the signatures or the encoding's padding), else the context's bytes in lowercase hex. So one delegation is
59
+ * one row, presented in any letter case or re-encoded.
60
+ */
61
+ export declare function instrumentOf(network: Network, p: X402Payment, a: Admitted): Promise<Instrumented | Refused>;
62
+ /**
63
+ * lcp's read of an admitted payment, by the pairing's search, at the final mark `finalized`, as the act `payment`: the
64
+ * value an agreement signs stands in H's place in its reference, so the search for it is the search for that value.
65
+ * `at.search` resumes an earlier search. `at.transaction` is the transaction the settler's record holds for the
66
+ * payment, which the reference names as the transaction a settler names: read beside the search, and on a level that
67
+ * signs no H (`x402/exact/eip155/erc7710`) the only way the read finds the payment. A batch settlement's payment that
68
+ * is no opening has no reference and no read of its own: `pending`, `search-incomplete`, live.
69
+ */
70
+ export declare function readOf(reader: EvmReader, a: Admitted, at: {
71
+ readonly search?: unknown;
72
+ readonly transaction?: string;
73
+ }): Promise<ChainRead>;
74
+ export {};
@@ -0,0 +1,182 @@
1
+ /**
2
+ * The EVM forms x402's published classes settle, as lcp's codecs read them: which pairing a payment is, the pure checks
3
+ * of its profile, the instrument the record keys it by, how long a final row is kept, and lcp's read of it. Nothing here
4
+ * reads the chain or the clock but the read itself.
5
+ */
6
+ import { digestJson, isRefusal, pairingOf } from "@integraledger/lcp";
7
+ import { PERMIT2 } from "@integraledger/lcp/evm";
8
+ import { authCaptureEip3009, authCapturePermit2, exactEip3009, exactErc7710, exactErc7710Salt, exactPermit2, pairingOfPayment, uptoPermit2, } from "@integraledger/lcp/x402";
9
+ import { batchEvm } from "@integraledger/lcp/x402-batch-settlement";
10
+ import { outcomeOf } from "../../module.js";
11
+ /** The pairings each scheme's class submits on an `eip155` network. */
12
+ export const PAIRINGS = {
13
+ exact: [exactEip3009.id, exactPermit2.id],
14
+ upto: [uptoPermit2.id],
15
+ "auth-capture": [authCaptureEip3009.id, authCapturePermit2.id],
16
+ "batch-settlement": [batchEvm.id],
17
+ };
18
+ /** Both ERC-7710 levels, which share the `erc7710` option of `exact`. */
19
+ export const ERC7710_PAIRINGS = [exactErc7710.id, exactErc7710Salt.id];
20
+ /** Each pairing's lcp members the module calls. */
21
+ const CODEC = {
22
+ [exactEip3009.id]: codec(exactEip3009),
23
+ [exactPermit2.id]: codec(exactPermit2),
24
+ [uptoPermit2.id]: codec(uptoPermit2),
25
+ [authCaptureEip3009.id]: codec(authCaptureEip3009),
26
+ [authCapturePermit2.id]: codec(authCapturePermit2),
27
+ [batchEvm.id]: codec(batchEvm),
28
+ [exactErc7710.id]: codec(exactErc7710),
29
+ [exactErc7710Salt.id]: codec(exactErc7710Salt),
30
+ };
31
+ function codec(b) {
32
+ return { reference: b.reference, status: b.status, nonce: b.data.nonce };
33
+ }
34
+ function isObject(v) {
35
+ return typeof v === "object" && v !== null && !Array.isArray(v);
36
+ }
37
+ /**
38
+ * The options of `exact` on EVM that no published EVM class may settle: one that pays several payees (a non-empty
39
+ * `extra.splits`, which `exact` does not carry), and Circle's batched option, which signs under the Gateway Wallet's
40
+ * EIP-712 domain and not the token's (`extra.name` `GatewayWalletBatched`, or an `extra.verifyingContract` other than
41
+ * the asset). Each is refused before x402's class is asked, which reads none of these members.
42
+ */
43
+ export function exactOptionRefused(requirements) {
44
+ const extra = requirements.extra;
45
+ if (extra === undefined)
46
+ return false;
47
+ const splits = extra["splits"];
48
+ if (splits !== undefined && !(Array.isArray(splits) && splits.length === 0))
49
+ return true;
50
+ if (extra["name"] === "GatewayWalletBatched")
51
+ return true;
52
+ const verifying = extra["verifyingContract"];
53
+ return (verifying !== undefined &&
54
+ !(typeof verifying === "string" && typeof requirements.asset === "string" && verifying.toLowerCase() === requirements.asset.toLowerCase()));
55
+ }
56
+ /**
57
+ * The profile's pure checks of a payment answering an option of `scheme`: the option is one of the pairings `pairings`
58
+ * names, as lcp's option filter reads it alone (`invalid_payment_requirements` otherwise), and the payment is that
59
+ * pairing's as lcp's `reference` reads it against the option (`invalid_payload` otherwise). A batch settlement's
60
+ * payment that is no opening has no reference: lcp's channel read holds its configuration to its voucher's channel,
61
+ * and the claim, settle and refund calls a resource server makes of the channel, which lcp does not decode, are x402's
62
+ * class's to check.
63
+ */
64
+ export async function admit(scheme, p, pairings) {
65
+ const { payload, requirements } = p;
66
+ if (requirements.scheme !== (scheme === "erc7710" ? "exact" : scheme))
67
+ return { refused: "invalid_payment_requirements" };
68
+ if (requirements.scheme === "exact" && exactOptionRefused(requirements))
69
+ return { refused: "invalid_payment_requirements" };
70
+ const option = pairingOf(requirements);
71
+ if (option === undefined)
72
+ return { refused: "invalid_payment_requirements" };
73
+ const level = option === exactErc7710.id ? pairingOfPayment(payload) : option;
74
+ if (level === undefined || !pairings.includes(level) || !(level in CODEC)) {
75
+ return { refused: "invalid_payment_requirements" };
76
+ }
77
+ const pairing = level;
78
+ if (pairing === batchEvm.id) {
79
+ const kind = isObject(payload.payload) ? payload.payload["type"] : undefined;
80
+ if (kind === "claim" || kind === "settle")
81
+ return { pairing };
82
+ const k = batchEvm.channel.kind(payload);
83
+ if (isRefusal(k))
84
+ return { refused: "invalid_payload" };
85
+ if (k !== "open") {
86
+ const channel = await batchEvm.channel.ref(payload);
87
+ return isRefusal(channel) ? { refused: "invalid_payload" } : { pairing };
88
+ }
89
+ }
90
+ const ref = await CODEC[pairing].reference(payload, requirements);
91
+ if (isRefusal(ref))
92
+ return { refused: "invalid_payload" };
93
+ return { pairing, ref: ref };
94
+ }
95
+ function lower(v) {
96
+ return String(v).toLowerCase();
97
+ }
98
+ /** A Permit2 nonce in decimal, one spelling for every pairing that signs one, so that one nonce of one owner is one row. */
99
+ function permit2Nonce(v) {
100
+ return BigInt(String(v)).toString(10);
101
+ }
102
+ /** Unix seconds, as a decimal the reference gives, in Unix milliseconds. */
103
+ function lapse(seconds) {
104
+ return { until: "lapse", at: Number(BigInt(String(seconds))) * 1000 };
105
+ }
106
+ /**
107
+ * The record's key and keep for an admitted payment. EIP-3009: the network, the token, the authorization's `from` and
108
+ * its nonce, kept to `validBefore`; the auth-capture escrow's ERC-3009 collector signs its nonce in the token's one
109
+ * nonce space, so it is keyed alike. Permit2: the network, the owner and the permit's nonce in Permit2's one bitmap per
110
+ * owner, kept to the deadline. Neither is the nonce alone, and for an agreement the nonce signed is the agreement's own
111
+ * value, so one payer's agreement and payment under one H are two rows. A batch settlement's call and an ERC-7710
112
+ * redemption hold no single-use value: each is keyed by a digest, for the settler's life. A batch call's is the digest
113
+ * of its signed payload. A redemption's is the digest of the delegation it redeems as signed, whatever its spelling: the
114
+ * manager and the delegator in lowercase, and the leaf delegation's EIP-712 hash where the context decodes as the
115
+ * reference manager's encoding (the hash commits to its caveats, its salt and, through its authority, the chain above
116
+ * it; not to the signatures or the encoding's padding), else the context's bytes in lowercase hex. So one delegation is
117
+ * one row, presented in any letter case or re-encoded.
118
+ */
119
+ export async function instrumentOf(network, p, a) {
120
+ const nonce = CODEC[a.pairing].nonce;
121
+ const ref = a.ref;
122
+ const digestOf = async (signed) => {
123
+ const d = await digestJson(signed);
124
+ if (isRefusal(d))
125
+ return { refused: "invalid_payload" };
126
+ return { pairing: a.pairing, instrument: { by: "digest", network, digest: d }, nonce, keep: { until: "settler" } };
127
+ };
128
+ const digest = () => digestOf(p.payload.payload);
129
+ if (a.pairing === exactErc7710.id || a.pairing === exactErc7710Salt.id) {
130
+ const r = isObject(p.payload.payload) ? p.payload.payload : {};
131
+ const leaf = isObject(ref?.["presented"]) ? ref["presented"]["delegation"] : undefined;
132
+ return digestOf({
133
+ delegationManager: lower(r["delegationManager"]),
134
+ delegator: lower(r["delegator"]),
135
+ ...(typeof leaf === "string" ? { delegation: lower(leaf) } : { permissionContext: lower(r["permissionContext"]) }),
136
+ });
137
+ }
138
+ if (ref === undefined)
139
+ return digest();
140
+ const presented = isObject(ref["presented"]) ? ref["presented"] : {};
141
+ let instrument;
142
+ let keep;
143
+ switch (a.pairing) {
144
+ case exactEip3009.id:
145
+ instrument = { by: "single-use", network, signer: lower(ref["payer"]), value: lower(presented["nonce"]), scope: lower(ref["asset"]) };
146
+ keep = lapse(ref["validBefore"]);
147
+ break;
148
+ case exactPermit2.id:
149
+ case uptoPermit2.id:
150
+ instrument = { by: "single-use", network, signer: lower(ref["payer"]), value: permit2Nonce(presented["nonce"]), scope: PERMIT2.toLowerCase() };
151
+ keep = lapse(ref["deadline"]);
152
+ break;
153
+ case authCaptureEip3009.id:
154
+ instrument = { by: "single-use", network, signer: lower(ref["payer"]), value: lower(ref["signatureNonce"]), scope: lower(ref["asset"]) };
155
+ keep = lapse(ref["expiry"]);
156
+ break;
157
+ case authCapturePermit2.id:
158
+ instrument = { by: "single-use", network, signer: lower(ref["payer"]), value: permit2Nonce(ref["signatureNonce"]), scope: PERMIT2.toLowerCase() };
159
+ keep = lapse(ref["expiry"]);
160
+ break;
161
+ default:
162
+ return digest();
163
+ }
164
+ return { pairing: a.pairing, instrument, nonce, keep };
165
+ }
166
+ /**
167
+ * lcp's read of an admitted payment, by the pairing's search, at the final mark `finalized`, as the act `payment`: the
168
+ * value an agreement signs stands in H's place in its reference, so the search for it is the search for that value.
169
+ * `at.search` resumes an earlier search. `at.transaction` is the transaction the settler's record holds for the
170
+ * payment, which the reference names as the transaction a settler names: read beside the search, and on a level that
171
+ * signs no H (`x402/exact/eip155/erc7710`) the only way the read finds the payment. A batch settlement's payment that
172
+ * is no opening has no reference and no read of its own: `pending`, `search-incomplete`, live.
173
+ */
174
+ export async function readOf(reader, a, at) {
175
+ if (a.ref === undefined)
176
+ return outcomeOf({ state: "pending", reason: "search-incomplete", foreign: [] });
177
+ const ref = at.transaction === undefined ? a.ref : { ...a.ref, transaction: at.transaction.toLowerCase() };
178
+ const query = at.search === undefined
179
+ ? { act: "payment", finality: "finalized" }
180
+ : { act: "payment", finality: "finalized", search: at.search };
181
+ return outcomeOf(await CODEC[a.pairing].status(ref, reader, query));
182
+ }
@@ -0,0 +1,40 @@
1
+ import type { PendingSettlementStore } from "@x402/core/facilitator";
2
+ import { type AuthCaptureFacilitatorConfig } from "@x402/evm/auth-capture/facilitator";
3
+ import type { FacilitatorEvmSigner } from "@x402/evm";
4
+ import type { FeeMeter, FeeNeeds, Module, ModuleStarter } from "../../module.js";
5
+ import { type EvmScheme } from "./forms.js";
6
+ /** One `eip155` network the `evm` module serves. */
7
+ export interface EvmConfig {
8
+ /** The network, `eip155:<chain id>`: one module per scheme on it. */
9
+ readonly network: `eip155:${number}`;
10
+ /** The seller's node, an EVM JSON-RPC endpoint, which lcp's reads and the fee's read go through. */
11
+ readonly rpc: string;
12
+ /**
13
+ * The seller's gas key, as x402's EVM classes take it (`toFacilitatorEvmSigner` of a client over the same node): it
14
+ * sends every transaction the module submits and pays its gas.
15
+ */
16
+ readonly signer: FacilitatorEvmSigner;
17
+ /** The schemes registered on the network; every one of the four where absent. */
18
+ readonly schemes?: readonly EvmScheme[];
19
+ /** ERC-6492 factories `exact` and `batch-settlement` may call to deploy a payer's wallet; none where absent. */
20
+ readonly eip6492AllowedFactories?: readonly string[];
21
+ /** `auth-capture`'s own configuration (fee terms, operators, its authorizers), passed to its class unchanged. */
22
+ readonly authCapture?: AuthCaptureFacilitatorConfig;
23
+ }
24
+ /** A module whose key pays the fee of what it sends, with the read of each transaction's fee. */
25
+ export type EvmModule = Module & {
26
+ readonly fees: Required<FeeNeeds>;
27
+ };
28
+ /**
29
+ * The `evm` module's schemes on one network, each x402's class with what the core needs beside it, the gas key counted
30
+ * by `meter`, the network's fee meter. `pending` is where `exact`, `upto` and `batch-settlement` keep a settlement they
31
+ * sent and the chain does not yet show, so that a retried settle reconciles against it; each class keeps its own in
32
+ * memory where absent.
33
+ */
34
+ export declare function evmModules(c: EvmConfig, meter: FeeMeter, pending?: PendingSettlementStore): EvmModule[];
35
+ /**
36
+ * How the core starts the module: the configuration's `evm` member lists the networks, one entry each, and each
37
+ * configured scheme on a network is one registration of x402's class, whose pending settlements are kept in the
38
+ * settler's database. The `erc7710` module offers itself to the `exact` registration made here.
39
+ */
40
+ export declare const starter: ModuleStarter<readonly EvmConfig[]>;