@t402/evm 2.0.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 (63) hide show
  1. package/README.md +183 -0
  2. package/dist/cjs/exact/client/index.d.ts +53 -0
  3. package/dist/cjs/exact/client/index.js +270 -0
  4. package/dist/cjs/exact/client/index.js.map +1 -0
  5. package/dist/cjs/exact/facilitator/index.d.ts +118 -0
  6. package/dist/cjs/exact/facilitator/index.js +735 -0
  7. package/dist/cjs/exact/facilitator/index.js.map +1 -0
  8. package/dist/cjs/exact/server/index.d.ts +36 -0
  9. package/dist/cjs/exact/server/index.js +438 -0
  10. package/dist/cjs/exact/server/index.js.map +1 -0
  11. package/dist/cjs/exact/v1/client/index.d.ts +37 -0
  12. package/dist/cjs/exact/v1/client/index.js +147 -0
  13. package/dist/cjs/exact/v1/client/index.js.map +1 -0
  14. package/dist/cjs/exact/v1/facilitator/index.d.ts +62 -0
  15. package/dist/cjs/exact/v1/facilitator/index.js +401 -0
  16. package/dist/cjs/exact/v1/facilitator/index.js.map +1 -0
  17. package/dist/cjs/index.d.ts +1537 -0
  18. package/dist/cjs/index.js +2368 -0
  19. package/dist/cjs/index.js.map +1 -0
  20. package/dist/cjs/scheme-C6uD7PdY.d.ts +130 -0
  21. package/dist/cjs/scheme-OojTBKAz.d.ts +35 -0
  22. package/dist/cjs/scheme-yqGaK9rK.d.ts +130 -0
  23. package/dist/cjs/signer-BkcAzwYi.d.ts +79 -0
  24. package/dist/cjs/v1/index.d.ts +7 -0
  25. package/dist/cjs/v1/index.js +171 -0
  26. package/dist/cjs/v1/index.js.map +1 -0
  27. package/dist/esm/chunk-ACDQ5QNT.mjs +305 -0
  28. package/dist/esm/chunk-ACDQ5QNT.mjs.map +1 -0
  29. package/dist/esm/chunk-JBWWBRYY.mjs +92 -0
  30. package/dist/esm/chunk-JBWWBRYY.mjs.map +1 -0
  31. package/dist/esm/chunk-LGSG73NJ.mjs +88 -0
  32. package/dist/esm/chunk-LGSG73NJ.mjs.map +1 -0
  33. package/dist/esm/chunk-OEXW2OK2.mjs +251 -0
  34. package/dist/esm/chunk-OEXW2OK2.mjs.map +1 -0
  35. package/dist/esm/chunk-QLXM7BIB.mjs +23 -0
  36. package/dist/esm/chunk-QLXM7BIB.mjs.map +1 -0
  37. package/dist/esm/chunk-XYKAO6KJ.mjs +141 -0
  38. package/dist/esm/chunk-XYKAO6KJ.mjs.map +1 -0
  39. package/dist/esm/exact/client/index.d.mts +53 -0
  40. package/dist/esm/exact/client/index.mjs +36 -0
  41. package/dist/esm/exact/client/index.mjs.map +1 -0
  42. package/dist/esm/exact/facilitator/index.d.mts +118 -0
  43. package/dist/esm/exact/facilitator/index.mjs +324 -0
  44. package/dist/esm/exact/facilitator/index.mjs.map +1 -0
  45. package/dist/esm/exact/server/index.d.mts +36 -0
  46. package/dist/esm/exact/server/index.mjs +218 -0
  47. package/dist/esm/exact/server/index.mjs.map +1 -0
  48. package/dist/esm/exact/v1/client/index.d.mts +37 -0
  49. package/dist/esm/exact/v1/client/index.mjs +8 -0
  50. package/dist/esm/exact/v1/client/index.mjs.map +1 -0
  51. package/dist/esm/exact/v1/facilitator/index.d.mts +62 -0
  52. package/dist/esm/exact/v1/facilitator/index.mjs +8 -0
  53. package/dist/esm/exact/v1/facilitator/index.mjs.map +1 -0
  54. package/dist/esm/index.d.mts +1537 -0
  55. package/dist/esm/index.mjs +1875 -0
  56. package/dist/esm/index.mjs.map +1 -0
  57. package/dist/esm/scheme-D4mOqq9l.d.mts +35 -0
  58. package/dist/esm/scheme-yqGaK9rK.d.mts +130 -0
  59. package/dist/esm/signer-BkcAzwYi.d.mts +79 -0
  60. package/dist/esm/v1/index.d.mts +7 -0
  61. package/dist/esm/v1/index.mjs +13 -0
  62. package/dist/esm/v1/index.mjs.map +1 -0
  63. package/package.json +127 -0
@@ -0,0 +1,130 @@
1
+ import { SchemeNetworkServer, MoneyParser, Price, Network, AssetAmount, PaymentRequirements } from '@t402/core/types';
2
+
3
+ /**
4
+ * Configuration options for ExactEvmScheme
5
+ */
6
+ interface ExactEvmSchemeConfig {
7
+ /** Preferred token symbol (e.g., "USDT0", "USDC"). Defaults to network's highest priority token. */
8
+ preferredToken?: string;
9
+ }
10
+ /**
11
+ * EVM server implementation for the Exact payment scheme.
12
+ * Supports USDT0, USDC, and other EIP-3009 compatible tokens.
13
+ */
14
+ declare class ExactEvmScheme implements SchemeNetworkServer {
15
+ readonly scheme = "exact";
16
+ private moneyParsers;
17
+ private config;
18
+ constructor(config?: ExactEvmSchemeConfig);
19
+ /**
20
+ * Register a custom money parser in the parser chain.
21
+ * Multiple parsers can be registered - they will be tried in registration order.
22
+ * Each parser receives a decimal amount (e.g., 1.50 for $1.50).
23
+ * If a parser returns null, the next parser in the chain will be tried.
24
+ * The default parser is always the final fallback.
25
+ *
26
+ * @param parser - Custom function to convert amount to AssetAmount (or null to skip)
27
+ * @returns The server instance for chaining
28
+ *
29
+ * @example
30
+ * evmServer.registerMoneyParser(async (amount, network) => {
31
+ * // Custom conversion logic
32
+ * if (amount > 100) {
33
+ * // Use different token for large amounts
34
+ * return { amount: (amount * 1e18).toString(), asset: "0xCustomToken" };
35
+ * }
36
+ * return null; // Use next parser
37
+ * });
38
+ */
39
+ registerMoneyParser(parser: MoneyParser): ExactEvmScheme;
40
+ /**
41
+ * Parses a price into an asset amount.
42
+ * If price is already an AssetAmount, returns it directly.
43
+ * If price is Money (string | number), parses to decimal and tries custom parsers.
44
+ * Falls back to default conversion if all custom parsers return null.
45
+ *
46
+ * @param price - The price to parse
47
+ * @param network - The network to use
48
+ * @returns Promise that resolves to the parsed asset amount
49
+ */
50
+ parsePrice(price: Price, network: Network): Promise<AssetAmount>;
51
+ /**
52
+ * Build payment requirements for this scheme/network combination
53
+ *
54
+ * @param paymentRequirements - The base payment requirements
55
+ * @param supportedKind - The supported kind from facilitator (unused)
56
+ * @param supportedKind.t402Version - The t402 version
57
+ * @param supportedKind.scheme - The logical payment scheme
58
+ * @param supportedKind.network - The network identifier in CAIP-2 format
59
+ * @param supportedKind.extra - Optional extra metadata regarding scheme/network implementation details
60
+ * @param extensionKeys - Extension keys supported by the facilitator (unused)
61
+ * @returns Payment requirements ready to be sent to clients
62
+ */
63
+ enhancePaymentRequirements(paymentRequirements: PaymentRequirements, supportedKind: {
64
+ t402Version: number;
65
+ scheme: string;
66
+ network: Network;
67
+ extra?: Record<string, unknown>;
68
+ }, extensionKeys: string[]): Promise<PaymentRequirements>;
69
+ /**
70
+ * Parse Money (string | number) to a decimal number.
71
+ * Handles formats like "$1.50", "1.50", 1.50, etc.
72
+ *
73
+ * @param money - The money value to parse
74
+ * @returns Decimal number
75
+ */
76
+ private parseMoneyToDecimal;
77
+ /**
78
+ * Default money conversion implementation.
79
+ * Converts decimal amount to the preferred token on the specified network.
80
+ * Priority: USDT0 > USDC > other configured tokens
81
+ *
82
+ * @param amount - The decimal amount (e.g., 1.50)
83
+ * @param network - The network to use
84
+ * @returns The parsed asset amount
85
+ */
86
+ private defaultMoneyConversion;
87
+ /**
88
+ * Convert decimal amount to token units (e.g., 0.10 -> 100000 for 6-decimal tokens)
89
+ *
90
+ * @param decimalAmount - The decimal amount to convert
91
+ * @param network - The network to use
92
+ * @param decimals - Optional number of decimals (defaults to network asset decimals)
93
+ * @returns The token amount as a string
94
+ */
95
+ private convertToTokenAmount;
96
+ /**
97
+ * Get the default asset info for a network.
98
+ * Priority: configured preferredToken > USDT0 > USDC > first available
99
+ *
100
+ * @param network - The network to get asset info for
101
+ * @returns The asset information including address, name, version, and decimals
102
+ */
103
+ private getDefaultAsset;
104
+ /**
105
+ * Get asset info for a given symbol on a network
106
+ *
107
+ * @param symbol - The asset symbol (e.g., "USDT0", "USDC", "USDT")
108
+ * @param network - The network to use
109
+ * @returns The token configuration
110
+ */
111
+ private getAssetInfo;
112
+ /**
113
+ * Get the number of decimals for the asset on a network
114
+ *
115
+ * @param network - The network to use
116
+ * @param tokenAddress - Optional token address to look up
117
+ * @returns The number of decimals for the asset
118
+ */
119
+ private getAssetDecimals;
120
+ /**
121
+ * Get all supported networks
122
+ */
123
+ static getSupportedNetworks(): string[];
124
+ /**
125
+ * Check if a network is supported
126
+ */
127
+ static isNetworkSupported(network: string): boolean;
128
+ }
129
+
130
+ export { ExactEvmScheme as E, type ExactEvmSchemeConfig as a };
@@ -0,0 +1,79 @@
1
+ /**
2
+ * ClientEvmSigner - Used by t402 clients to sign payment authorizations
3
+ * This is typically a LocalAccount or wallet that holds private keys
4
+ * and can sign EIP-712 typed data for payment authorizations
5
+ */
6
+ type ClientEvmSigner = {
7
+ readonly address: `0x${string}`;
8
+ signTypedData(message: {
9
+ domain: Record<string, unknown>;
10
+ types: Record<string, unknown>;
11
+ primaryType: string;
12
+ message: Record<string, unknown>;
13
+ }): Promise<`0x${string}`>;
14
+ };
15
+ /**
16
+ * FacilitatorEvmSigner - Used by t402 facilitators to verify and settle payments
17
+ * This is typically a viem PublicClient + WalletClient combination that can
18
+ * read contract state, verify signatures, write transactions, and wait for receipts
19
+ *
20
+ * Supports multiple addresses for load balancing, key rotation, and high availability
21
+ */
22
+ type FacilitatorEvmSigner = {
23
+ /**
24
+ * Get all addresses this facilitator can use for signing
25
+ * Enables dynamic address selection for load balancing and key rotation
26
+ */
27
+ getAddresses(): readonly `0x${string}`[];
28
+ readContract(args: {
29
+ address: `0x${string}`;
30
+ abi: readonly unknown[];
31
+ functionName: string;
32
+ args?: readonly unknown[];
33
+ }): Promise<unknown>;
34
+ verifyTypedData(args: {
35
+ address: `0x${string}`;
36
+ domain: Record<string, unknown>;
37
+ types: Record<string, unknown>;
38
+ primaryType: string;
39
+ message: Record<string, unknown>;
40
+ signature: `0x${string}`;
41
+ }): Promise<boolean>;
42
+ writeContract(args: {
43
+ address: `0x${string}`;
44
+ abi: readonly unknown[];
45
+ functionName: string;
46
+ args: readonly unknown[];
47
+ }): Promise<`0x${string}`>;
48
+ sendTransaction(args: {
49
+ to: `0x${string}`;
50
+ data: `0x${string}`;
51
+ }): Promise<`0x${string}`>;
52
+ waitForTransactionReceipt(args: {
53
+ hash: `0x${string}`;
54
+ }): Promise<{
55
+ status: string;
56
+ }>;
57
+ getCode(args: {
58
+ address: `0x${string}`;
59
+ }): Promise<`0x${string}` | undefined>;
60
+ };
61
+ /**
62
+ * Converts a signer to a ClientEvmSigner
63
+ *
64
+ * @param signer - The signer to convert to a ClientEvmSigner
65
+ * @returns The converted signer
66
+ */
67
+ declare function toClientEvmSigner(signer: ClientEvmSigner): ClientEvmSigner;
68
+ /**
69
+ * Converts a viem client with single address to a FacilitatorEvmSigner
70
+ * Wraps the single address in a getAddresses() function for compatibility
71
+ *
72
+ * @param client - The client to convert (must have 'address' property)
73
+ * @returns FacilitatorEvmSigner with getAddresses() support
74
+ */
75
+ declare function toFacilitatorEvmSigner(client: Omit<FacilitatorEvmSigner, "getAddresses"> & {
76
+ address: `0x${string}`;
77
+ }): FacilitatorEvmSigner;
78
+
79
+ export { type ClientEvmSigner as C, type FacilitatorEvmSigner as F, toFacilitatorEvmSigner as a, toClientEvmSigner as t };
@@ -0,0 +1,7 @@
1
+ export { ExactEvmSchemeV1 } from '../exact/v1/client/index.js';
2
+ import '@t402/core/types';
3
+ import '../signer-BkcAzwYi.js';
4
+
5
+ declare const NETWORKS: string[];
6
+
7
+ export { NETWORKS };
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/v1/index.ts
21
+ var v1_exports = {};
22
+ __export(v1_exports, {
23
+ ExactEvmSchemeV1: () => ExactEvmSchemeV1,
24
+ NETWORKS: () => NETWORKS
25
+ });
26
+ module.exports = __toCommonJS(v1_exports);
27
+
28
+ // src/exact/v1/client/scheme.ts
29
+ var import_viem2 = require("viem");
30
+
31
+ // src/constants.ts
32
+ var authorizationTypes = {
33
+ TransferWithAuthorization: [
34
+ { name: "from", type: "address" },
35
+ { name: "to", type: "address" },
36
+ { name: "value", type: "uint256" },
37
+ { name: "validAfter", type: "uint256" },
38
+ { name: "validBefore", type: "uint256" },
39
+ { name: "nonce", type: "bytes32" }
40
+ ]
41
+ };
42
+
43
+ // src/utils.ts
44
+ var import_viem = require("viem");
45
+ function getEvmChainId(network) {
46
+ const networkMap = {
47
+ base: 8453,
48
+ "base-sepolia": 84532,
49
+ ethereum: 1,
50
+ sepolia: 11155111,
51
+ polygon: 137,
52
+ "polygon-amoy": 80002
53
+ };
54
+ return networkMap[network] || 1;
55
+ }
56
+ function createNonce() {
57
+ const cryptoObj = typeof globalThis.crypto !== "undefined" ? globalThis.crypto : globalThis.crypto;
58
+ if (!cryptoObj) {
59
+ throw new Error("Crypto API not available");
60
+ }
61
+ return (0, import_viem.toHex)(cryptoObj.getRandomValues(new Uint8Array(32)));
62
+ }
63
+
64
+ // src/exact/v1/client/scheme.ts
65
+ var ExactEvmSchemeV1 = class {
66
+ /**
67
+ * Creates a new ExactEvmClientV1 instance.
68
+ *
69
+ * @param signer - The EVM signer for client operations
70
+ */
71
+ constructor(signer) {
72
+ this.signer = signer;
73
+ this.scheme = "exact";
74
+ }
75
+ /**
76
+ * Creates a payment payload for the Exact scheme (V1).
77
+ *
78
+ * @param t402Version - The t402 protocol version
79
+ * @param paymentRequirements - The payment requirements
80
+ * @returns Promise resolving to a payment payload
81
+ */
82
+ async createPaymentPayload(t402Version, paymentRequirements) {
83
+ const selectedV1 = paymentRequirements;
84
+ const nonce = createNonce();
85
+ const now = Math.floor(Date.now() / 1e3);
86
+ const authorization = {
87
+ from: this.signer.address,
88
+ to: (0, import_viem2.getAddress)(selectedV1.payTo),
89
+ value: selectedV1.maxAmountRequired,
90
+ validAfter: (now - 600).toString(),
91
+ // 10 minutes before
92
+ validBefore: (now + selectedV1.maxTimeoutSeconds).toString(),
93
+ nonce
94
+ };
95
+ const signature = await this.signAuthorization(authorization, selectedV1);
96
+ const payload = {
97
+ authorization,
98
+ signature
99
+ };
100
+ return {
101
+ t402Version,
102
+ scheme: selectedV1.scheme,
103
+ network: selectedV1.network,
104
+ payload
105
+ };
106
+ }
107
+ /**
108
+ * Sign the EIP-3009 authorization using EIP-712
109
+ *
110
+ * @param authorization - The authorization to sign
111
+ * @param requirements - The payment requirements
112
+ * @returns Promise resolving to the signature
113
+ */
114
+ async signAuthorization(authorization, requirements) {
115
+ const chainId = getEvmChainId(requirements.network);
116
+ if (!requirements.extra?.name || !requirements.extra?.version) {
117
+ throw new Error(
118
+ `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`
119
+ );
120
+ }
121
+ const { name, version } = requirements.extra;
122
+ const domain = {
123
+ name,
124
+ version,
125
+ chainId,
126
+ verifyingContract: (0, import_viem2.getAddress)(requirements.asset)
127
+ };
128
+ const message = {
129
+ from: (0, import_viem2.getAddress)(authorization.from),
130
+ to: (0, import_viem2.getAddress)(authorization.to),
131
+ value: BigInt(authorization.value),
132
+ validAfter: BigInt(authorization.validAfter),
133
+ validBefore: BigInt(authorization.validBefore),
134
+ nonce: authorization.nonce
135
+ };
136
+ return await this.signer.signTypedData({
137
+ domain,
138
+ types: authorizationTypes,
139
+ primaryType: "TransferWithAuthorization",
140
+ message
141
+ });
142
+ }
143
+ };
144
+
145
+ // src/exact/v1/facilitator/scheme.ts
146
+ var import_viem3 = require("viem");
147
+
148
+ // src/v1/index.ts
149
+ var NETWORKS = [
150
+ "abstract",
151
+ "abstract-testnet",
152
+ "base-sepolia",
153
+ "base",
154
+ "avalanche-fuji",
155
+ "avalanche",
156
+ "iotex",
157
+ "sei",
158
+ "sei-testnet",
159
+ "polygon",
160
+ "polygon-amoy",
161
+ "peaq",
162
+ "story",
163
+ "educhain",
164
+ "skale-base-sepolia"
165
+ ];
166
+ // Annotate the CommonJS export names for ESM import in node:
167
+ 0 && (module.exports = {
168
+ ExactEvmSchemeV1,
169
+ NETWORKS
170
+ });
171
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/v1/index.ts","../../../src/exact/v1/client/scheme.ts","../../../src/constants.ts","../../../src/utils.ts","../../../src/exact/v1/facilitator/scheme.ts"],"sourcesContent":["export { ExactEvmSchemeV1 } from \"../exact/v1\";\n\nexport const NETWORKS: string[] = [\n \"abstract\",\n \"abstract-testnet\",\n \"base-sepolia\",\n \"base\",\n \"avalanche-fuji\",\n \"avalanche\",\n \"iotex\",\n \"sei\",\n \"sei-testnet\",\n \"polygon\",\n \"polygon-amoy\",\n \"peaq\",\n \"story\",\n \"educhain\",\n \"skale-base-sepolia\",\n];\n","import {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@t402/core/types\";\nimport { PaymentRequirementsV1 } from \"@t402/core/types/v1\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../../constants\";\nimport { ClientEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { createNonce, getEvmChainId } from \"../../../utils\";\n\n/**\n * EVM client implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClientV1 instance.\n *\n * @param signer - The EVM signer for client operations\n */\n constructor(private readonly signer: ClientEvmSigner) {}\n\n /**\n * Creates a payment payload for the Exact scheme (V1).\n *\n * @param t402Version - The t402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n t402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<\n Pick<PaymentPayload, \"t402Version\" | \"payload\"> & { scheme: string; network: Network }\n > {\n const selectedV1 = paymentRequirements as unknown as PaymentRequirementsV1;\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEvmPayloadV1[\"authorization\"] = {\n from: this.signer.address,\n to: getAddress(selectedV1.payTo),\n value: selectedV1.maxAmountRequired,\n validAfter: (now - 600).toString(), // 10 minutes before\n validBefore: (now + selectedV1.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n // Sign the authorization\n const signature = await this.signAuthorization(authorization, selectedV1);\n\n const payload: ExactEvmPayloadV1 = {\n authorization,\n signature,\n };\n\n return {\n t402Version,\n scheme: selectedV1.scheme,\n network: selectedV1.network,\n payload,\n };\n }\n\n /**\n * Sign the EIP-3009 authorization using EIP-712\n *\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\n private async signAuthorization(\n authorization: ExactEvmPayloadV1[\"authorization\"],\n requirements: PaymentRequirementsV1,\n ): Promise<`0x${string}`> {\n const chainId = getEvmChainId(requirements.network);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await this.signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n }\n}\n","// EIP-3009 TransferWithAuthorization types for EIP-712 signing\nexport const authorizationTypes = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n// Legacy transfer authorization types for EIP-712 signing\n// Used for tokens without EIP-3009 support (approve + transferFrom pattern)\nexport const legacyAuthorizationTypes = {\n LegacyTransferAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"spender\", type: \"address\" },\n ],\n} as const;\n\n// EIP3009 ABI for transferWithAuthorization function\nexport const eip3009ABI = [\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"v\", type: \"uint8\" },\n { name: \"r\", type: \"bytes32\" },\n { name: \"s\", type: \"bytes32\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"signature\", type: \"bytes\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"account\", type: \"address\" }],\n name: \"balanceOf\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"version\",\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\n// Standard ERC20 ABI for legacy token operations (approve + transferFrom pattern)\nexport const erc20LegacyABI = [\n {\n inputs: [{ name: \"account\", type: \"address\" }],\n name: \"balanceOf\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n ],\n name: \"allowance\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"spender\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n name: \"approve\",\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n name: \"transferFrom\",\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n] as const;\n","import { toHex } from \"viem\";\nimport { Network } from \"@t402/core/types\";\n\n/**\n * Extract chain ID from network string (e.g., \"base-sepolia\" -> 84532)\n * Used by v1 implementations\n *\n * @param network - The network identifier\n * @returns The numeric chain ID\n */\nexport function getEvmChainId(network: Network): number {\n const networkMap: Record<string, number> = {\n base: 8453,\n \"base-sepolia\": 84532,\n ethereum: 1,\n sepolia: 11155111,\n polygon: 137,\n \"polygon-amoy\": 80002,\n };\n return networkMap[network] || 1;\n}\n\n/**\n * Create a random 32-byte nonce for authorization\n *\n * @returns A hex-encoded 32-byte nonce\n */\nexport function createNonce(): `0x${string}` {\n // Use dynamic import to avoid require() in ESM context\n const cryptoObj =\n typeof globalThis.crypto !== \"undefined\"\n ? globalThis.crypto\n : (globalThis as { crypto?: Crypto }).crypto;\n\n if (!cryptoObj) {\n throw new Error(\"Crypto API not available\");\n }\n\n return toHex(cryptoObj.getRandomValues(new Uint8Array(32)));\n}\n","import {\n PaymentPayload,\n PaymentPayloadV1,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n SettleResponse,\n VerifyResponse,\n} from \"@t402/core/types\";\nimport { PaymentRequirementsV1 } from \"@t402/core/types/v1\";\nimport { getAddress, Hex, isAddressEqual, parseErc6492Signature, parseSignature } from \"viem\";\nimport { authorizationTypes, eip3009ABI } from \"../../../constants\";\nimport { FacilitatorEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { getEvmChainId } from \"../../../utils\";\n\nexport interface ExactEvmSchemeV1Config {\n /**\n * If enabled, the facilitator will deploy ERC-4337 smart wallets\n * via EIP-6492 when encountering undeployed contract signatures.\n *\n * @default false\n */\n deployERC4337WithEIP6492?: boolean;\n}\n\n/**\n * EVM facilitator implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkFacilitator {\n readonly scheme = \"exact\";\n readonly caipFamily = \"eip155:*\";\n private readonly config: Required<ExactEvmSchemeV1Config>;\n\n /**\n * Creates a new ExactEvmFacilitatorV1 instance.\n *\n * @param signer - The EVM signer for facilitator operations\n * @param config - Optional configuration for the facilitator\n */\n constructor(\n private readonly signer: FacilitatorEvmSigner,\n config?: ExactEvmSchemeV1Config,\n ) {\n this.config = {\n deployERC4337WithEIP6492: config?.deployERC4337WithEIP6492 ?? false,\n };\n }\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * For EVM, no extra data is needed.\n *\n * @param _ - The network identifier (unused for EVM)\n * @returns undefined (EVM has no extra data)\n */\n getExtra(_: string): Record<string, unknown> | undefined {\n return undefined;\n }\n\n /**\n * Get signer addresses used by this facilitator.\n * Returns all addresses this facilitator can use for signing/settling transactions.\n *\n * @param _ - The network identifier (unused for EVM, addresses are network-agnostic)\n * @returns Array of facilitator wallet addresses\n */\n getSigners(_: string): string[] {\n return [...this.signer.getAddresses()];\n }\n\n /**\n * Verifies a payment payload (V1).\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @returns Promise resolving to verification response\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n const requirementsV1 = requirements as unknown as PaymentRequirementsV1;\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n\n // Verify scheme matches\n if (payloadV1.scheme !== \"exact\" || requirements.scheme !== \"exact\") {\n return {\n isValid: false,\n invalidReason: \"unsupported_scheme\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n // Get chain configuration\n const chainId = getEvmChainId(payloadV1.network);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n return {\n isValid: false,\n invalidReason: \"missing_eip712_domain\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n const { name, version } = requirements.extra;\n const erc20Address = getAddress(requirements.asset);\n\n // Verify network matches\n if (payloadV1.network !== requirements.network) {\n return {\n isValid: false,\n invalidReason: \"network_mismatch\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n // Build typed data for signature verification\n const permitTypedData = {\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\" as const,\n domain: {\n name,\n version,\n chainId,\n verifyingContract: erc20Address,\n },\n message: {\n from: exactEvmPayload.authorization.from,\n to: exactEvmPayload.authorization.to,\n value: BigInt(exactEvmPayload.authorization.value),\n validAfter: BigInt(exactEvmPayload.authorization.validAfter),\n validBefore: BigInt(exactEvmPayload.authorization.validBefore),\n nonce: exactEvmPayload.authorization.nonce,\n },\n };\n\n // Verify signature\n try {\n const recoveredAddress = await this.signer.verifyTypedData({\n address: exactEvmPayload.authorization.from,\n ...permitTypedData,\n signature: exactEvmPayload.signature!,\n });\n\n if (!recoveredAddress) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_signature\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n } catch {\n // Signature verification failed - could be an undeployed smart wallet\n // Check if smart wallet is deployed\n const signature = exactEvmPayload.signature!;\n const signatureLength = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n const isSmartWallet = signatureLength > 130; // 65 bytes = 130 hex chars for EOA\n\n if (isSmartWallet) {\n const payerAddress = exactEvmPayload.authorization.from;\n const bytecode = await this.signer.getCode({ address: payerAddress });\n\n if (!bytecode || bytecode === \"0x\") {\n // Wallet is not deployed. Check if it's EIP-6492 with deployment info.\n // EIP-6492 signatures contain factory address and calldata needed for deployment.\n // Non-EIP-6492 undeployed wallets cannot succeed (no way to deploy them).\n const erc6492Data = parseErc6492Signature(signature);\n const hasDeploymentInfo =\n erc6492Data.address &&\n erc6492Data.data &&\n !isAddressEqual(erc6492Data.address, \"0x0000000000000000000000000000000000000000\");\n\n if (!hasDeploymentInfo) {\n // Non-EIP-6492 undeployed smart wallet - will always fail at settlement\n // since EIP-3009 requires on-chain EIP-1271 validation\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_undeployed_smart_wallet\",\n payer: payerAddress,\n };\n }\n // EIP-6492 signature with deployment info - allow through\n // Facilitators with sponsored deployment support can handle this in settle()\n } else {\n // Wallet is deployed but signature still failed - invalid signature\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_signature\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n } else {\n // EOA signature failed\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_signature\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n }\n\n // Verify payment recipient matches\n if (getAddress(exactEvmPayload.authorization.to) !== getAddress(requirements.payTo)) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_recipient_mismatch\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n // Verify validBefore is in the future (with 6 second buffer for block time)\n const now = Math.floor(Date.now() / 1000);\n if (BigInt(exactEvmPayload.authorization.validBefore) < BigInt(now + 6)) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_authorization_valid_before\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n // Verify validAfter is not in the future\n if (BigInt(exactEvmPayload.authorization.validAfter) > BigInt(now)) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_authorization_valid_after\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n // Check balance\n try {\n const balance = (await this.signer.readContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"balanceOf\",\n args: [exactEvmPayload.authorization.from],\n })) as bigint;\n\n if (BigInt(balance) < BigInt(requirementsV1.maxAmountRequired)) {\n return {\n isValid: false,\n invalidReason: \"insufficient_funds\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n } catch {\n // If we can't check balance, continue with other validations\n }\n\n // Verify amount is sufficient\n if (BigInt(exactEvmPayload.authorization.value) < BigInt(requirementsV1.maxAmountRequired)) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_authorization_value\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n /**\n * Settles a payment by executing the transfer (V1).\n *\n * @param payload - The payment payload to settle\n * @param requirements - The payment requirements\n * @returns Promise resolving to settlement response\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<SettleResponse> {\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n\n // Re-verify before settling\n const valid = await this.verify(payload, requirements);\n if (!valid.isValid) {\n return {\n success: false,\n network: payloadV1.network,\n transaction: \"\",\n errorReason: valid.invalidReason ?? \"invalid_scheme\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n try {\n // Parse ERC-6492 signature if applicable\n const parseResult = parseErc6492Signature(exactEvmPayload.signature!);\n const { signature, address: factoryAddress, data: factoryCalldata } = parseResult;\n\n // Deploy ERC-4337 smart wallet via EIP-6492 if configured and needed\n if (\n this.config.deployERC4337WithEIP6492 &&\n factoryAddress &&\n factoryCalldata &&\n !isAddressEqual(factoryAddress, \"0x0000000000000000000000000000000000000000\")\n ) {\n // Check if smart wallet is already deployed\n const payerAddress = exactEvmPayload.authorization.from;\n const bytecode = await this.signer.getCode({ address: payerAddress });\n\n if (!bytecode || bytecode === \"0x\") {\n // Wallet not deployed - attempt deployment\n try {\n console.log(`Deploying ERC-4337 smart wallet for ${payerAddress} via EIP-6492`);\n\n // Send the factory calldata directly as a transaction\n // The factoryCalldata already contains the complete encoded function call\n const deployTx = await this.signer.sendTransaction({\n to: factoryAddress as Hex,\n data: factoryCalldata as Hex,\n });\n\n // Wait for deployment transaction\n await this.signer.waitForTransactionReceipt({ hash: deployTx });\n console.log(`Successfully deployed smart wallet for ${payerAddress}`);\n } catch (deployError) {\n console.error(\"Smart wallet deployment failed:\", deployError);\n // Deployment failed - cannot proceed\n throw deployError;\n }\n } else {\n console.log(`Smart wallet for ${payerAddress} already deployed, skipping deployment`);\n }\n }\n\n // Determine if this is an ECDSA signature (EOA) or smart wallet signature\n // ECDSA signatures are exactly 65 bytes (130 hex chars without 0x)\n const signatureLength = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n const isECDSA = signatureLength === 130;\n\n let tx: Hex;\n if (isECDSA) {\n // For EOA wallets, parse signature into v, r, s and use that overload\n const parsedSig = parseSignature(signature);\n\n tx = await this.signer.writeContract({\n address: getAddress(requirements.asset),\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n getAddress(exactEvmPayload.authorization.from),\n getAddress(exactEvmPayload.authorization.to),\n BigInt(exactEvmPayload.authorization.value),\n BigInt(exactEvmPayload.authorization.validAfter),\n BigInt(exactEvmPayload.authorization.validBefore),\n exactEvmPayload.authorization.nonce,\n (parsedSig.v as number | undefined) || parsedSig.yParity,\n parsedSig.r,\n parsedSig.s,\n ],\n });\n } else {\n // For smart wallets, use the bytes signature overload\n // The signature contains WebAuthn/P256 or other ERC-1271 compatible signature data\n tx = await this.signer.writeContract({\n address: getAddress(requirements.asset),\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n getAddress(exactEvmPayload.authorization.from),\n getAddress(exactEvmPayload.authorization.to),\n BigInt(exactEvmPayload.authorization.value),\n BigInt(exactEvmPayload.authorization.validAfter),\n BigInt(exactEvmPayload.authorization.validBefore),\n exactEvmPayload.authorization.nonce,\n signature,\n ],\n });\n }\n\n // Wait for transaction confirmation\n const receipt = await this.signer.waitForTransactionReceipt({ hash: tx });\n\n if (receipt.status !== \"success\") {\n return {\n success: false,\n errorReason: \"invalid_transaction_state\",\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n return {\n success: true,\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n } catch (error) {\n console.error(\"Failed to settle transaction:\", error);\n return {\n success: false,\n errorReason: \"transaction_failed\",\n transaction: \"\",\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n }\n}\n"],"mappings":"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","names":["import_viem","import_viem"]}