@introspectivelabs/x402-evm 0.1.0-beta.17 → 0.1.0-beta.18
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.
- package/dist/cjs/exact/client/index.d.ts +3 -3
- package/dist/cjs/exact/client/index.js +107 -49
- package/dist/cjs/exact/client/index.js.map +1 -1
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +107 -49
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/{userOpHash-Bzusu9T7.d.ts → userOpHash-CLhOwl2X.d.ts} +46 -27
- package/dist/esm/{chunk-XA674MVY.mjs → chunk-HNYBFTTM.mjs} +108 -50
- package/dist/esm/chunk-HNYBFTTM.mjs.map +1 -0
- package/dist/esm/exact/client/index.d.mts +3 -3
- package/dist/esm/exact/client/index.mjs +1 -1
- package/dist/esm/index.d.mts +1 -1
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/{userOpHash-Cz7aBb3Q.d.mts → userOpHash-CjJpllAn.d.mts} +46 -27
- package/package.json +1 -1
- package/dist/esm/chunk-XA674MVY.mjs.map +0 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { U as UserOperationSigner, P as PreparedUserOperation } from '../../userOpHash-
|
|
2
|
-
export { B as BundlerClient, f as BundlerClientConfig, j as ERC20_TRANSFER_ABI, b as ExactEvmSchemeEIP3009, c as ExactEvmSchemeEIP3009Config, E as ExactEvmSchemeERC4337, a as ExactEvmSchemeERC4337Config, G as GasEstimate, l as PackedUserOp, g as UserOperationCall, V as ViemBundlerClient, h as ViemBundlerClientConfig, i as buildERC20TransferCallData, k as computeUserOpHash, d as createP256SafeMessageSigner, e as createWebAuthnSafeMessageSigner, u as userOpToJson } from '../../userOpHash-
|
|
1
|
+
import { U as UserOperationSigner, P as PreparedUserOperation } from '../../userOpHash-CLhOwl2X.js';
|
|
2
|
+
export { B as BundlerClient, f as BundlerClientConfig, j as ERC20_TRANSFER_ABI, b as ExactEvmSchemeEIP3009, c as ExactEvmSchemeEIP3009Config, E as ExactEvmSchemeERC4337, a as ExactEvmSchemeERC4337Config, G as GasEstimate, l as PackedUserOp, g as UserOperationCall, V as ViemBundlerClient, h as ViemBundlerClientConfig, i as buildERC20TransferCallData, k as computeUserOpHash, d as createP256SafeMessageSigner, e as createWebAuthnSafeMessageSigner, u as userOpToJson } from '../../userOpHash-CLhOwl2X.js';
|
|
3
3
|
import { SmartAccount } from 'viem/account-abstraction';
|
|
4
4
|
import 'viem';
|
|
5
|
-
import '../../types-Dk5U6Xnw.js';
|
|
6
5
|
import '../../types-lO5B0FRc.js';
|
|
7
6
|
import '@x402/core/types';
|
|
7
|
+
import '../../types-Dk5U6Xnw.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Adapter to make a SmartAccount (e.g., Safe account) work as a UserOperationSigner.
|
|
@@ -53,15 +53,13 @@ var import_viem5 = require("viem");
|
|
|
53
53
|
// src/exact/client/bundler/viem.ts
|
|
54
54
|
var import_viem = require("viem");
|
|
55
55
|
var import_account_abstraction = require("viem/account-abstraction");
|
|
56
|
+
function bigintToHex(n) {
|
|
57
|
+
return `0x${n.toString(16)}`;
|
|
58
|
+
}
|
|
56
59
|
var ViemBundlerClient = class {
|
|
57
|
-
/**
|
|
58
|
-
* Creates a new ViemBundlerClient instance.
|
|
59
|
-
*
|
|
60
|
-
* @param config - Configuration for the bundler client
|
|
61
|
-
*/
|
|
62
60
|
constructor(config) {
|
|
63
61
|
this.account = config.account;
|
|
64
|
-
this.
|
|
62
|
+
this.usePaymaster = config.paymaster === true;
|
|
65
63
|
this.bundlerClient = (0, import_account_abstraction.createBundlerClient)({
|
|
66
64
|
client: config.publicClient,
|
|
67
65
|
chain: config.chain,
|
|
@@ -70,13 +68,91 @@ var ViemBundlerClient = class {
|
|
|
70
68
|
});
|
|
71
69
|
}
|
|
72
70
|
/**
|
|
73
|
-
* Prepares an unsigned user operation
|
|
71
|
+
* Prepares an unsigned user operation using raw RPC calls.
|
|
74
72
|
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
73
|
+
* When paymaster is enabled, uses pm_sponsorUserOperation to get paymaster
|
|
74
|
+
* data and gas estimates in a single call (Pimlico-compatible).
|
|
75
|
+
* The returned UserOp has final paymaster data ready for hash computation and signing.
|
|
78
76
|
*/
|
|
79
|
-
async prepareUserOperation(calls,
|
|
77
|
+
async prepareUserOperation(calls, entryPoint) {
|
|
78
|
+
if (!this.usePaymaster) {
|
|
79
|
+
return this.prepareWithoutPaymaster(calls);
|
|
80
|
+
}
|
|
81
|
+
const callData = await this.account.encodeCalls(
|
|
82
|
+
calls.map((call) => ({
|
|
83
|
+
to: call.to,
|
|
84
|
+
value: call.value,
|
|
85
|
+
data: call.data
|
|
86
|
+
}))
|
|
87
|
+
);
|
|
88
|
+
const nonce = await this.account.getNonce();
|
|
89
|
+
const sender = await this.account.getAddress();
|
|
90
|
+
const gasPriceResult = await this.bundlerClient.request({
|
|
91
|
+
method: "pimlico_getUserOperationGasPrice",
|
|
92
|
+
params: []
|
|
93
|
+
});
|
|
94
|
+
const maxFeePerGas = BigInt(gasPriceResult.fast.maxFeePerGas);
|
|
95
|
+
const maxPriorityFeePerGas = BigInt(gasPriceResult.fast.maxPriorityFeePerGas);
|
|
96
|
+
const stubSignature = await this.account.getStubSignature();
|
|
97
|
+
{
|
|
98
|
+
const userOpForEstimation = {
|
|
99
|
+
sender,
|
|
100
|
+
nonce: `0x${nonce.toString(16)}`,
|
|
101
|
+
callData,
|
|
102
|
+
signature: stubSignature,
|
|
103
|
+
callGasLimit: bigintToHex(500000n),
|
|
104
|
+
verificationGasLimit: bigintToHex(500000n),
|
|
105
|
+
preVerificationGas: bigintToHex(100000n),
|
|
106
|
+
maxFeePerGas: bigintToHex(maxFeePerGas),
|
|
107
|
+
maxPriorityFeePerGas: bigintToHex(maxPriorityFeePerGas)
|
|
108
|
+
};
|
|
109
|
+
const sponsorResult = await this.bundlerClient.request({
|
|
110
|
+
method: "pm_sponsorUserOperation",
|
|
111
|
+
params: [userOpForEstimation, entryPoint]
|
|
112
|
+
});
|
|
113
|
+
const callGasLimit = BigInt(sponsorResult.callGasLimit);
|
|
114
|
+
const verificationGasLimit = BigInt(sponsorResult.verificationGasLimit);
|
|
115
|
+
const preVerificationGas = BigInt(sponsorResult.preVerificationGas);
|
|
116
|
+
let paymaster;
|
|
117
|
+
let paymasterData;
|
|
118
|
+
let paymasterVerificationGasLimit;
|
|
119
|
+
let paymasterPostOpGasLimit;
|
|
120
|
+
if (sponsorResult.paymaster) {
|
|
121
|
+
paymaster = sponsorResult.paymaster;
|
|
122
|
+
paymasterData = sponsorResult.paymasterData ?? "0x";
|
|
123
|
+
paymasterVerificationGasLimit = BigInt(sponsorResult.paymasterVerificationGasLimit ?? "0x0");
|
|
124
|
+
paymasterPostOpGasLimit = BigInt(sponsorResult.paymasterPostOpGasLimit ?? "0x0");
|
|
125
|
+
} else if (sponsorResult.paymasterAndData && sponsorResult.paymasterAndData !== "0x") {
|
|
126
|
+
const packed = sponsorResult.paymasterAndData;
|
|
127
|
+
paymaster = `0x${packed.slice(2, 42)}`;
|
|
128
|
+
paymasterVerificationGasLimit = BigInt(`0x${packed.slice(42, 74)}`);
|
|
129
|
+
paymasterPostOpGasLimit = BigInt(`0x${packed.slice(74, 106)}`);
|
|
130
|
+
paymasterData = `0x${packed.slice(106)}`;
|
|
131
|
+
}
|
|
132
|
+
return {
|
|
133
|
+
sender,
|
|
134
|
+
nonce,
|
|
135
|
+
// Include factory/factoryData keys so that downstream signers (e.g. permissionless
|
|
136
|
+
// Safe signUserOperation) detect v0.7 format and correctly pack paymasterAndData
|
|
137
|
+
// from the separate v0.7 fields. Without these keys, permissionless defaults to
|
|
138
|
+
// paymasterAndData: "0x" causing SafeOp hash mismatch (AA24).
|
|
139
|
+
factory: void 0,
|
|
140
|
+
factoryData: void 0,
|
|
141
|
+
callData,
|
|
142
|
+
callGasLimit,
|
|
143
|
+
verificationGasLimit,
|
|
144
|
+
preVerificationGas,
|
|
145
|
+
maxFeePerGas,
|
|
146
|
+
maxPriorityFeePerGas,
|
|
147
|
+
...paymaster ? { paymaster } : {},
|
|
148
|
+
...paymasterData ? { paymasterData } : {},
|
|
149
|
+
...paymasterVerificationGasLimit != null ? { paymasterVerificationGasLimit } : {},
|
|
150
|
+
...paymasterPostOpGasLimit != null ? { paymasterPostOpGasLimit } : {},
|
|
151
|
+
signature: stubSignature
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
async prepareWithoutPaymaster(calls) {
|
|
80
156
|
const prepared = await this.bundlerClient.prepareUserOperation({
|
|
81
157
|
account: this.account,
|
|
82
158
|
calls: calls.map((call) => ({
|
|
@@ -89,31 +165,20 @@ var ViemBundlerClient = class {
|
|
|
89
165
|
return {
|
|
90
166
|
sender: prepared.sender,
|
|
91
167
|
nonce: prepared.nonce,
|
|
168
|
+
// Always include factory/factoryData keys for v0.7 format detection by signers
|
|
169
|
+
factory: p.factory ?? void 0,
|
|
170
|
+
factoryData: p.factoryData ?? void 0,
|
|
92
171
|
callData: prepared.callData,
|
|
93
172
|
callGasLimit: prepared.callGasLimit,
|
|
94
173
|
verificationGasLimit: prepared.verificationGasLimit,
|
|
95
174
|
preVerificationGas: prepared.preVerificationGas,
|
|
96
175
|
maxFeePerGas: prepared.maxFeePerGas,
|
|
97
176
|
maxPriorityFeePerGas: prepared.maxPriorityFeePerGas,
|
|
98
|
-
// v0.7 factory fields (for account deployment)
|
|
99
|
-
...p.factory ? { factory: p.factory } : {},
|
|
100
|
-
...p.factoryData ? { factoryData: p.factoryData } : {},
|
|
101
|
-
// v0.7 paymaster fields (separate, not paymasterAndData)
|
|
102
|
-
...p.paymaster ? { paymaster: p.paymaster } : {},
|
|
103
|
-
...p.paymasterData ? { paymasterData: p.paymasterData } : {},
|
|
104
|
-
...p.paymasterVerificationGasLimit != null ? { paymasterVerificationGasLimit: p.paymasterVerificationGasLimit } : {},
|
|
105
|
-
...p.paymasterPostOpGasLimit != null ? { paymasterPostOpGasLimit: p.paymasterPostOpGasLimit } : {},
|
|
106
177
|
signature: prepared.signature
|
|
107
178
|
};
|
|
108
179
|
}
|
|
109
180
|
/**
|
|
110
|
-
*
|
|
111
|
-
* Note: This is typically done as part of prepareUserOperation,
|
|
112
|
-
* but is available as a separate method for flexibility.
|
|
113
|
-
*
|
|
114
|
-
* @param _userOp - The user operation to estimate gas for
|
|
115
|
-
* @param _entryPoint - The entry point address
|
|
116
|
-
* @returns Promise resolving to gas estimates
|
|
181
|
+
* @deprecated Gas estimation is done as part of prepareUserOperation
|
|
117
182
|
*/
|
|
118
183
|
async estimateGas(_userOp, _entryPoint) {
|
|
119
184
|
throw new Error(
|
|
@@ -121,26 +186,15 @@ var ViemBundlerClient = class {
|
|
|
121
186
|
);
|
|
122
187
|
}
|
|
123
188
|
/**
|
|
124
|
-
* Sends a user operation to the bundler.
|
|
189
|
+
* Sends a signed user operation to the bundler via raw eth_sendUserOperation RPC.
|
|
125
190
|
*
|
|
126
|
-
*
|
|
127
|
-
*
|
|
128
|
-
* @returns Promise resolving to the user operation hash
|
|
191
|
+
* Bypasses viem's middleware to avoid re-calling paymaster RPCs which would
|
|
192
|
+
* change paymaster fields and invalidate the signature.
|
|
129
193
|
*/
|
|
130
|
-
async sendUserOperation(userOp,
|
|
131
|
-
const hash = await this.bundlerClient.
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
nonce: BigInt(userOp.nonce),
|
|
135
|
-
callData: userOp.callData,
|
|
136
|
-
callGasLimit: BigInt(userOp.callGasLimit),
|
|
137
|
-
verificationGasLimit: BigInt(userOp.verificationGasLimit),
|
|
138
|
-
preVerificationGas: BigInt(userOp.preVerificationGas),
|
|
139
|
-
maxFeePerGas: BigInt(userOp.maxFeePerGas),
|
|
140
|
-
maxPriorityFeePerGas: BigInt(userOp.maxPriorityFeePerGas),
|
|
141
|
-
// Combine paymaster and paymasterData into paymasterAndData
|
|
142
|
-
paymasterAndData: userOp.paymaster && userOp.paymasterData ? userOp.paymaster + userOp.paymasterData.slice(2) : userOp.paymaster ? userOp.paymaster : "0x",
|
|
143
|
-
signature: userOp.signature
|
|
194
|
+
async sendUserOperation(userOp, entryPoint) {
|
|
195
|
+
const hash = await this.bundlerClient.request({
|
|
196
|
+
method: "eth_sendUserOperation",
|
|
197
|
+
params: [userOp, entryPoint]
|
|
144
198
|
});
|
|
145
199
|
return hash;
|
|
146
200
|
}
|
|
@@ -253,6 +307,7 @@ function userOpToJson(userOp) {
|
|
|
253
307
|
const json = {};
|
|
254
308
|
for (const [key, value] of Object.entries(userOp)) {
|
|
255
309
|
if (key === "account") continue;
|
|
310
|
+
if (value === void 0) continue;
|
|
256
311
|
if (typeof value === "bigint") {
|
|
257
312
|
json[key] = toRpcHex(value);
|
|
258
313
|
} else if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
@@ -458,6 +513,7 @@ var ExactEvmSchemeERC4337 = class {
|
|
|
458
513
|
this.publicClient = config.publicClient;
|
|
459
514
|
this.entrypoint = config.entrypoint;
|
|
460
515
|
this.bundlerUrl = config.bundlerUrl;
|
|
516
|
+
this.paymaster = config.paymaster;
|
|
461
517
|
if (!this.bundlerClient && !this.account) {
|
|
462
518
|
throw new Error(
|
|
463
519
|
"Either bundlerClient or account must be provided. If bundlerClient is not provided, account (SmartAccount) is required for dynamic bundlerClient creation."
|
|
@@ -497,6 +553,9 @@ var ExactEvmSchemeERC4337 = class {
|
|
|
497
553
|
*/
|
|
498
554
|
async createPaymentPayload(x402Version, paymentRequirements) {
|
|
499
555
|
const capability = extractUserOperationCapability(paymentRequirements);
|
|
556
|
+
const chain = resolveChain(paymentRequirements.network);
|
|
557
|
+
const configBundlerUrl = typeof this.bundlerUrl === "function" ? this.bundlerUrl(chain.id, paymentRequirements.network) : this.bundlerUrl;
|
|
558
|
+
const bundlerUrl = configBundlerUrl ?? capability?.bundlerUrl;
|
|
500
559
|
let bundlerClient;
|
|
501
560
|
if (this.bundlerClient) {
|
|
502
561
|
bundlerClient = this.bundlerClient;
|
|
@@ -506,8 +565,7 @@ var ExactEvmSchemeERC4337 = class {
|
|
|
506
565
|
"Account (SmartAccount) is required when bundlerClient is not provided. Either provide bundlerClient in config or account for dynamic creation."
|
|
507
566
|
);
|
|
508
567
|
}
|
|
509
|
-
|
|
510
|
-
if (!bundlerUrl2) {
|
|
568
|
+
if (!bundlerUrl) {
|
|
511
569
|
throw new PaymentCreationError(
|
|
512
570
|
"Bundler URL not provided",
|
|
513
571
|
{
|
|
@@ -517,13 +575,14 @@ var ExactEvmSchemeERC4337 = class {
|
|
|
517
575
|
}
|
|
518
576
|
);
|
|
519
577
|
}
|
|
520
|
-
const chain = resolveChain(paymentRequirements.network);
|
|
521
578
|
const publicClient = this.publicClient ?? createDefaultPublicClient(paymentRequirements.network);
|
|
579
|
+
const paymaster = this.paymaster ?? true;
|
|
522
580
|
bundlerClient = new ViemBundlerClient({
|
|
523
581
|
publicClient,
|
|
524
582
|
account: this.account,
|
|
525
583
|
chain,
|
|
526
|
-
bundlerUrl
|
|
584
|
+
bundlerUrl,
|
|
585
|
+
paymaster
|
|
527
586
|
});
|
|
528
587
|
}
|
|
529
588
|
const entryPoint = this.entrypoint ?? capability?.entrypoint;
|
|
@@ -537,7 +596,6 @@ var ExactEvmSchemeERC4337 = class {
|
|
|
537
596
|
}
|
|
538
597
|
);
|
|
539
598
|
}
|
|
540
|
-
const bundlerUrl = this.bundlerUrl ?? capability?.bundlerUrl;
|
|
541
599
|
if (!bundlerUrl) {
|
|
542
600
|
throw new PaymentCreationError(
|
|
543
601
|
"Bundler URL not provided",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/exact/client/index.ts","../../../../src/exact/client/schemes/erc4337.ts","../../../../src/exact/client/bundler/viem.ts","../../../../src/exact/client/signers/safeAccountSigner.ts","../../../../src/exact/client/signers/safeMessageSigners.ts","../../../../src/exact/utils.ts","../../../../src/exact/client/utils/callData.ts","../../../../src/exact/client/utils/userOperation.ts","../../../../src/exact/client/errors.ts","../../../../src/networks/registry.ts","../../../../src/networks/helpers.ts","../../../../src/exact/client/schemes/eip3009.ts","../../../../src/accounts/encodeContractSignature.ts","../../../../src/accounts/computeSafeMessageHash.ts","../../../../src/exact/client/utils/userOpHash.ts","../../../../src/constants.ts"],"sourcesContent":["export * from \"./schemes\";\nexport * from \"./signers\";\nexport { PaymentCreationError, parseAAError } from \"./errors\";\nexport type { PaymentCreationPhase } from \"./errors\";\nexport * from \"./bundler\";\nexport * from \"./utils\";\n","import type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from \"@x402/core/types\";\nimport {\n getAddress,\n createPublicClient,\n http,\n type Chain,\n type PublicClient,\n type Transport,\n Hex,\n} from \"viem\";\nimport * as allChains from \"viem/chains\";\nimport { defineChain } from \"viem\";\nimport type { SmartAccount } from \"viem/account-abstraction\";\nimport type { BundlerClient } from \"../bundler\";\nimport { ViemBundlerClient } from \"../bundler/viem\";\nimport type { UserOperationSigner } from \"../signers\";\nimport { SafeAccountSigner } from \"../signers\";\nimport { extractUserOperationCapability } from \"../../utils\";\nimport type { Erc4337Payload } from \"../../facilitator/types\";\nimport { buildERC20TransferCallData } from \"../utils/callData\";\nimport { userOpToJson } from \"../utils/userOperation\";\nimport { PaymentCreationError, parseAAError } from \"../errors\";\nimport { resolveChainId } from \"../../../networks\";\n\n/**\n * Base configuration properties shared by all configuration variants\n */\ninterface ExactEvmSchemeERC4337ConfigBase {\n /**\n * Entry point address (EntryPoint v0.7)\n * Optional - can be provided in payment requirements if not set here\n */\n entrypoint?: Hex;\n\n /**\n * Bundler URL (optional, can be provided in payment requirements)\n */\n bundlerUrl?: string;\n}\n\n/**\n * Configuration variant when bundlerClient is explicitly provided.\n * Account and publicClient are NOT needed when bundlerClient is used.\n * Signer is required when using bundlerClient.\n */\ntype ExactEvmSchemeERC4337ConfigWithBundler = ExactEvmSchemeERC4337ConfigBase & {\n /**\n * Bundler client for preparing and sending user operations.\n */\n bundlerClient: BundlerClient;\n /**\n * Signer for signing user operations (required when bundlerClient is provided).\n */\n signer: UserOperationSigner;\n} & {\n /**\n * Account must not be provided when bundlerClient is used.\n * Using `never` type prevents this property from being set.\n */\n account?: never;\n /**\n * Public client must not be provided when bundlerClient is used.\n * The bundlerClient already has its own publicClient configured.\n */\n publicClient?: never;\n};\n\n/**\n * Configuration variant when bundlerClient is not provided.\n * Account is required for dynamic bundlerClient creation.\n * Signer is optional - will be auto-created from account if not provided.\n * PublicClient is optional - will create a default from network if not provided.\n */\ntype ExactEvmSchemeERC4337ConfigWithAccount = ExactEvmSchemeERC4337ConfigBase & {\n /**\n * Bundler client is not provided - will be created dynamically from PaymentRequirements.\n * Using `never` type prevents this property from being set.\n */\n bundlerClient?: never;\n} & {\n /**\n * Smart account for user operation preparation.\n * Required when bundlerClient is not provided.\n */\n account: SmartAccount;\n /**\n * Signer for signing user operations.\n * Optional - will be auto-created from account using SafeAccountSigner if not provided.\n * The account must support signUserOperation method for auto-creation to work.\n */\n signer?: UserOperationSigner;\n /**\n * Public client for blockchain interactions.\n * Optional - will create a default from network if not provided.\n */\n publicClient?: PublicClient<Transport, Chain>;\n};\n\n/**\n * Configuration for the ERC-4337 client scheme.\n *\n * This is a discriminated union that enforces type-safe combinations:\n * - Either `bundlerClient` is provided (account and publicClient must NOT be provided)\n * - Or `account` is provided when bundlerClient is not (for dynamic creation, publicClient optional)\n *\n * @example\n * ```typescript\n * // Minimal config (just account - signer auto-created)\n * const scheme1 = new ExactEvmSchemeERC4337({\n * account: myAccount,\n * // signer will be auto-created from account\n * // bundlerClient will be created dynamically from PaymentRequirements\n * });\n *\n * // With account and custom signer\n * const scheme2 = new ExactEvmSchemeERC4337({\n * account: myAccount,\n * signer: myCustomSigner,\n * publicClient: myPublicClient, // Optional\n * });\n *\n * // With explicit bundlerClient (backward compatible)\n * const scheme3 = new ExactEvmSchemeERC4337({\n * bundlerClient: myBundlerClient,\n * signer: mySigner, // Required when bundlerClient is provided\n * // account and publicClient must NOT be provided (bundlerClient has its own)\n * });\n * ```\n */\nexport type ExactEvmSchemeERC4337Config =\n | ExactEvmSchemeERC4337ConfigWithBundler\n | ExactEvmSchemeERC4337ConfigWithAccount;\n\n/**\n * Resolves a network string to a Chain object.\n * Handles both CAIP-2 format (\"eip155:84532\") and v1 plain names (\"base-sepolia\").\n *\n * @param network - Network string in CAIP-2 or v1 plain name format\n * @returns The Chain object\n */\nfunction resolveChain(network: string): Chain {\n const chainId = resolveChainId(network);\n\n const known = Object.values(allChains).find((c: Chain) => c.id === chainId);\n if (known) return known;\n\n return defineChain({\n id: chainId,\n name: network,\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n rpcUrls: { default: { http: [] } },\n });\n}\n\n/**\n * Creates a default public client from a network string.\n *\n * @param network - The network string in CAIP-2 format (e.g., \"eip155:84532\")\n * @returns A PublicClient instance\n */\nfunction createDefaultPublicClient(network: string): PublicClient<Transport, Chain> {\n const chain = resolveChain(network);\n return createPublicClient({\n chain,\n transport: http(),\n });\n}\n\n/**\n * EVM client implementation for the Exact payment scheme using ERC-4337 UserOperations.\n *\n * This implementation creates payment payloads by building and signing UserOperations\n * that execute ERC20 transfers. The UserOperations are prepared using a bundler client\n * and signed using a user operation signer (e.g., Safe account, EOA).\n *\n * Supports minimal configuration: when bundlerClient is not provided and\n * PaymentRequirements.extra.userOperation.supported is true, a ViemBundlerClient\n * will be created dynamically from the payment requirements.\n *\n * @example\n * ```typescript\n * // Minimal config (just account - signer and bundlerClient auto-created)\n * import { ExactEvmSchemeERC4337 } from '@introspectivelabs/x402-evm/exact/client';\n * import { x402Client } from '@x402/core/client';\n *\n * const scheme = new ExactEvmSchemeERC4337({\n * account: safeAccount, // SmartAccount - signer will be auto-created\n * });\n *\n * // With custom signer\n * const scheme2 = new ExactEvmSchemeERC4337({\n * account: safeAccount,\n * signer: customSigner, // Optional - overrides auto-creation\n * });\n *\n * // Explicit config (backward compatible)\n * import { ViemBundlerClient } from '@introspectivelabs/x402-evm/exact/client/bundler';\n *\n * const bundlerClient = new ViemBundlerClient({\n * publicClient,\n * account,\n * chain,\n * bundlerUrl: 'https://bundler.example.com',\n * });\n *\n * const scheme3 = new ExactEvmSchemeERC4337({\n * bundlerClient,\n * signer: account, // Required when bundlerClient is provided\n * });\n *\n * const client = new x402Client();\n * client.register('eip155:84532', scheme);\n * ```\n */\nexport class ExactEvmSchemeERC4337 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n private readonly bundlerClient?: BundlerClient;\n private readonly account?: SmartAccount;\n private readonly publicClient?: PublicClient<Transport, Chain>;\n private readonly signer: UserOperationSigner;\n private readonly entrypoint?: Hex;\n private readonly bundlerUrl?: string;\n\n /**\n * Creates a new ExactEvmSchemeERC4337 instance.\n *\n * @param config - Configuration for the scheme (type-safe: either bundlerClient or account must be provided)\n * @throws Error if bundlerClient is not provided and account is also not provided (runtime safety check)\n * @throws Error if signer is not provided and account doesn't support signUserOperation\n */\n constructor(config: ExactEvmSchemeERC4337Config) {\n this.bundlerClient = config.bundlerClient;\n this.account = config.account;\n this.publicClient = config.publicClient;\n this.entrypoint = config.entrypoint;\n this.bundlerUrl = config.bundlerUrl;\n\n // Validate: if bundlerClient is not provided, account must be provided\n if (!this.bundlerClient && !this.account) {\n throw new Error(\n \"Either bundlerClient or account must be provided. \" +\n \"If bundlerClient is not provided, account (SmartAccount) is required for dynamic bundlerClient creation.\",\n );\n }\n\n // Handle signer: use provided signer or auto-create from account\n if (config.signer) {\n this.signer = config.signer;\n } else if (this.account) {\n // Auto-create signer from account if not provided\n if (!this.account.signUserOperation) {\n throw new Error(\n \"Account does not support signUserOperation. \" +\n \"Either provide a signer explicitly or use an account that supports signUserOperation.\",\n );\n }\n this.signer = new SafeAccountSigner(this.account);\n } else {\n // This should not happen due to type system, but add runtime check for safety\n throw new Error(\n \"Signer is required when bundlerClient is provided. \" +\n \"Either provide a signer explicitly or use account-based configuration.\",\n );\n }\n }\n\n /**\n * Creates a payment payload for the Exact scheme using ERC-4337 UserOperations.\n *\n * This method:\n * 1. Extracts user operation capability from payment requirements\n * 2. Creates bundlerClient dynamically if not provided (when userOperation.supported is true)\n * 3. Builds ERC20 transfer call data\n * 4. Prepares the user operation using the bundler client\n * 5. Signs the user operation\n * 6. Converts to JSON-RPC format\n * 7. Returns the x402 payment payload\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n * @throws Error if user operation capability is not found or required fields are missing\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, \"x402Version\" | \"payload\">> {\n // Extract user operation capability (optional - config defaults used when missing)\n const capability = extractUserOperationCapability(paymentRequirements);\n\n // Determine which bundlerClient to use\n let bundlerClient: BundlerClient;\n\n if (this.bundlerClient) {\n // Use provided bundlerClient (explicit config, backward compatible)\n bundlerClient = this.bundlerClient;\n } else {\n // Create bundlerClient dynamically from PaymentRequirements\n if (!this.account) {\n throw new Error(\n \"Account (SmartAccount) is required when bundlerClient is not provided. \" +\n \"Either provide bundlerClient in config or account for dynamic creation.\",\n );\n }\n\n // Get bundler URL (prioritize config defaults over PaymentRequirements)\n const bundlerUrl = this.bundlerUrl ?? capability?.bundlerUrl;\n if (!bundlerUrl) {\n throw new PaymentCreationError(\n \"Bundler URL not provided\",\n {\n phase: \"validation\",\n reason: \"Set bundlerUrl in ExactEvmSchemeERC4337Config or in payment requirements extra.userOperation.bundlerUrl\",\n network: paymentRequirements.network,\n },\n );\n }\n\n // Derive chain from network (supports both CAIP-2 and v1 plain names)\n const chain = resolveChain(paymentRequirements.network);\n\n // Use provided publicClient or create default from network\n const publicClient =\n this.publicClient ?? createDefaultPublicClient(paymentRequirements.network);\n\n // Create ViemBundlerClient dynamically\n bundlerClient = new ViemBundlerClient({\n publicClient,\n account: this.account,\n chain,\n bundlerUrl,\n });\n }\n\n // Get entry point (prioritize config defaults over PaymentRequirements)\n const entryPoint = this.entrypoint ?? (capability?.entrypoint as `0x${string}` | undefined);\n\n if (!entryPoint) {\n throw new PaymentCreationError(\n \"Entry point not provided\",\n {\n phase: \"validation\",\n reason: \"Set entrypoint in ExactEvmSchemeERC4337Config or in payment requirements extra.userOperation.entrypoint\",\n network: paymentRequirements.network,\n },\n );\n }\n\n // Get bundler URL (prioritize config defaults over PaymentRequirements)\n const bundlerUrl = this.bundlerUrl ?? capability?.bundlerUrl;\n if (!bundlerUrl) {\n throw new PaymentCreationError(\n \"Bundler URL not provided\",\n {\n phase: \"validation\",\n reason: \"Set bundlerUrl in ExactEvmSchemeERC4337Config or in payment requirements extra.userOperation.bundlerUrl\",\n network: paymentRequirements.network,\n },\n );\n }\n\n // Normalize addresses\n const token = getAddress(paymentRequirements.asset);\n const payTo = getAddress(paymentRequirements.payTo);\n // Handle both v2 (amount) and v1 (maxAmountRequired) fields\n const amountStr =\n paymentRequirements.amount ??\n ((paymentRequirements as Record<string, unknown>).maxAmountRequired as string | undefined);\n if (!amountStr) {\n throw new Error(\"Payment requirements missing amount (v2) or maxAmountRequired (v1)\");\n }\n const amount = BigInt(amountStr);\n\n // Build ERC20 transfer call data\n const callData = buildERC20TransferCallData(token, payTo, amount);\n\n // Prepare user operation (unsigned)\n let unsignedUserOp;\n try {\n unsignedUserOp = await bundlerClient.prepareUserOperation(\n [\n {\n to: token,\n value: BigInt(0), // ERC20 transfers don't send ETH\n data: callData,\n },\n ],\n entryPoint,\n );\n } catch (error) {\n const aaError = parseAAError(error);\n throw new PaymentCreationError(\n aaError\n ? `Payment preparation failed: ${aaError.reason}`\n : `Payment preparation failed: ${error instanceof Error ? error.message : String(error)}`,\n {\n phase: \"preparation\",\n reason: aaError?.reason ?? (error instanceof Error ? error.message : String(error)),\n network: paymentRequirements.network,\n code: aaError?.code,\n cause: error,\n },\n );\n }\n\n // Sign the user operation\n let signature;\n try {\n signature = await this.signer.signUserOperation(unsignedUserOp);\n } catch (error) {\n const aaError = parseAAError(error);\n throw new PaymentCreationError(\n aaError\n ? `Payment signing failed: ${aaError.reason}`\n : `Payment signing failed: ${error instanceof Error ? error.message : String(error)}`,\n {\n phase: \"signing\",\n reason: aaError?.reason ?? (error instanceof Error ? error.message : String(error)),\n network: paymentRequirements.network,\n code: aaError?.code,\n cause: error,\n },\n );\n }\n\n // Create signed user operation\n const signedUserOp = {\n ...unsignedUserOp,\n signature,\n };\n\n // Convert to JSON-RPC format (bigint -> hex)\n const jsonUserOp = userOpToJson(signedUserOp);\n\n // Build the ERC-4337 payload\n const payload: Erc4337Payload = {\n type: \"erc4337\",\n entryPoint,\n bundlerRpcUrl: bundlerUrl,\n userOperation: jsonUserOp,\n };\n\n return {\n x402Version,\n // v1 requires scheme and network at top level\n ...(x402Version === 1\n ? { scheme: this.scheme, network: paymentRequirements.network }\n : {}),\n payload,\n };\n }\n}\n","import type { Chain, PublicClient, Transport } from \"viem\";\nimport { http } from \"viem\";\nimport type { SmartAccount } from \"viem/account-abstraction\";\nimport { createBundlerClient as createViemBundlerClient } from \"viem/account-abstraction\";\nimport type {\n BundlerClient,\n BundlerClientConfig,\n GasEstimate,\n PreparedUserOperation,\n UserOperationCall,\n} from \"./client\";\nimport type { UserOperation07Json } from \"../../facilitator/types\";\n\n/**\n * Configuration for creating a viem-based bundler client\n */\nexport interface ViemBundlerClientConfig extends BundlerClientConfig {\n /**\n * Viem public client for blockchain interactions\n */\n publicClient: PublicClient<Transport, Chain>;\n\n /**\n * Smart account for user operation preparation (must be a SmartAccount, not a regular Account)\n */\n account: SmartAccount;\n\n /**\n * Chain configuration\n */\n chain: Chain;\n\n /**\n * Bundler RPC URL\n */\n bundlerUrl: string;\n}\n\n/**\n * Viem-based implementation of BundlerClient.\n * Uses viem's account-abstraction utilities for user operation handling.\n */\nexport class ViemBundlerClient implements BundlerClient {\n private readonly bundlerClient: ReturnType<typeof createViemBundlerClient>;\n private readonly account: SmartAccount;\n private readonly entryPoint: `0x${string}`;\n\n /**\n * Creates a new ViemBundlerClient instance.\n *\n * @param config - Configuration for the bundler client\n */\n constructor(config: ViemBundlerClientConfig) {\n this.account = config.account;\n this.entryPoint = \"0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789\" as `0x${string}`; // EntryPoint v0.7\n\n // Create viem bundler client with bundler-specific transport\n this.bundlerClient = createViemBundlerClient({\n client: config.publicClient,\n chain: config.chain,\n account: config.account,\n transport: http(config.bundlerUrl),\n });\n }\n\n /**\n * Prepares an unsigned user operation for the given calls.\n *\n * @param calls - Array of calls to execute in the user operation\n * @param _entryPoint - The entry point address (unused, viem uses the configured entry point)\n * @returns Promise resolving to a prepared (unsigned) user operation\n */\n async prepareUserOperation(\n calls: UserOperationCall[],\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _entryPoint: `0x${string}`,\n ): Promise<PreparedUserOperation> {\n const prepared = await this.bundlerClient.prepareUserOperation({\n account: this.account,\n calls: calls.map(call => ({\n to: call.to,\n value: call.value,\n data: call.data,\n })),\n });\n\n // viem v2 EntryPoint v0.7 returns separate fields (not v0.6 paymasterAndData)\n const p = prepared as Record<string, unknown>;\n\n return {\n sender: prepared.sender,\n nonce: prepared.nonce,\n callData: prepared.callData,\n callGasLimit: prepared.callGasLimit,\n verificationGasLimit: prepared.verificationGasLimit,\n preVerificationGas: prepared.preVerificationGas,\n maxFeePerGas: prepared.maxFeePerGas,\n maxPriorityFeePerGas: prepared.maxPriorityFeePerGas,\n // v0.7 factory fields (for account deployment)\n ...(p.factory ? { factory: p.factory as `0x${string}` } : {}),\n ...(p.factoryData ? { factoryData: p.factoryData as `0x${string}` } : {}),\n // v0.7 paymaster fields (separate, not paymasterAndData)\n ...(p.paymaster ? { paymaster: p.paymaster as `0x${string}` } : {}),\n ...(p.paymasterData ? { paymasterData: p.paymasterData as `0x${string}` } : {}),\n ...(p.paymasterVerificationGasLimit != null\n ? { paymasterVerificationGasLimit: p.paymasterVerificationGasLimit as bigint }\n : {}),\n ...(p.paymasterPostOpGasLimit != null\n ? { paymasterPostOpGasLimit: p.paymasterPostOpGasLimit as bigint }\n : {}),\n signature: prepared.signature,\n } as PreparedUserOperation;\n }\n\n /**\n * Estimates gas for a user operation.\n * Note: This is typically done as part of prepareUserOperation,\n * but is available as a separate method for flexibility.\n *\n * @param _userOp - The user operation to estimate gas for\n * @param _entryPoint - The entry point address\n * @returns Promise resolving to gas estimates\n */\n async estimateGas(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _userOp: UserOperation07Json,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _entryPoint: `0x${string}`,\n ): Promise<GasEstimate> {\n // Note: Gas estimation is typically done as part of prepareUserOperation\n // This method is provided for flexibility but may not be used in practice\n // The return type from estimateUserOperationGas doesn't include maxFeePerGas/maxPriorityFeePerGas\n // as those are determined by the network, not the bundler\n throw new Error(\n \"estimateGas should be called through prepareUserOperation, which includes gas estimation\",\n );\n }\n\n /**\n * Sends a user operation to the bundler.\n *\n * @param userOp - The signed user operation to send\n * @param _entryPoint - The entry point address (unused, viem uses the configured entry point)\n * @returns Promise resolving to the user operation hash\n */\n async sendUserOperation(\n userOp: UserOperation07Json,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _entryPoint: `0x${string}`,\n ): Promise<string> {\n // Convert JSON user operation to format expected by viem\n // viem's sendUserOperation accepts UserOperation fields directly (not nested)\n const hash = await this.bundlerClient.sendUserOperation({\n account: this.account,\n sender: userOp.sender as `0x${string}`,\n nonce: BigInt(userOp.nonce),\n callData: userOp.callData as `0x${string}`,\n callGasLimit: BigInt(userOp.callGasLimit),\n verificationGasLimit: BigInt(userOp.verificationGasLimit),\n preVerificationGas: BigInt(userOp.preVerificationGas),\n maxFeePerGas: BigInt(userOp.maxFeePerGas),\n maxPriorityFeePerGas: BigInt(userOp.maxPriorityFeePerGas),\n // Combine paymaster and paymasterData into paymasterAndData\n paymasterAndData:\n userOp.paymaster && userOp.paymasterData\n ? ((userOp.paymaster + userOp.paymasterData.slice(2)) as `0x${string}`)\n : userOp.paymaster\n ? (userOp.paymaster as `0x${string}`)\n : (\"0x\" as `0x${string}`),\n signature: userOp.signature as `0x${string}`,\n });\n\n return hash;\n }\n}\n","import type { SmartAccount } from \"viem/account-abstraction\";\nimport type { PreparedUserOperation } from \"../bundler\";\nimport type { UserOperationSigner } from \"./types\";\n\n/**\n * Adapter to make a SmartAccount (e.g., Safe account) work as a UserOperationSigner.\n *\n * This class wraps a SmartAccount that supports `signUserOperation` and adapts it\n * to the UserOperationSigner interface required by the x402 ERC-4337 scheme.\n *\n * @example\n * ```typescript\n * import { SafeAccountSigner } from \"@introspectivelabs/x402-evm/exact/client\";\n * import { toSafeSmartAccount } from \"permissionless/accounts\";\n *\n * const safeAccount = await toSafeSmartAccount({ ... });\n * const signer = new SafeAccountSigner(safeAccount);\n *\n * const scheme = new ExactEvmSchemeERC4337({\n * bundlerClient,\n * signer,\n * });\n * ```\n */\nexport class SafeAccountSigner implements UserOperationSigner {\n readonly address: `0x${string}`;\n\n /**\n * Creates a new SafeAccountSigner instance.\n *\n * @param account - The SmartAccount instance (e.g., from permissionless/accounts)\n * @throws Error if the account is not initialized or missing an address\n */\n constructor(private readonly account: SmartAccount) {\n if (!account?.address) {\n throw new Error(\"Smart account not initialized\");\n }\n this.address = account.address as `0x${string}`;\n }\n\n /**\n * Signs a prepared (unsigned) user operation.\n *\n * @param userOp - The prepared user operation to sign\n * @returns Promise resolving to the signature\n * @throws Error if the account does not support signUserOperation\n */\n async signUserOperation(userOp: PreparedUserOperation): Promise<`0x${string}`> {\n if (!this.account?.signUserOperation) {\n throw new Error(\"Smart account does not support signUserOperation\");\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await this.account.signUserOperation(userOp as any);\n }\n}\n","import { type Hex, concat, encodeAbiParameters } from \"viem\";\nimport type { WebAuthnAccount } from \"viem/account-abstraction\";\nimport type { P256Signer, SafeMessageSigner } from \"../../../accounts/types\";\n\n/**\n * Creates a SafeMessageSigner from a P256Signer.\n * The sign method returns concat([r, s]) (64 bytes raw P256 signature).\n */\nexport function createP256SafeMessageSigner(\n p256Signer: P256Signer,\n): SafeMessageSigner {\n return {\n ownerAddress: p256Signer.p256OwnerAddress,\n async sign(safeMessageHash: Hex): Promise<Hex> {\n const { r, s } = await p256Signer.sign(safeMessageHash);\n return concat([r, s]);\n },\n };\n}\n\n/**\n * Creates a SafeMessageSigner from a WebAuthnAccount.\n * The sign method triggers navigator.credentials.get() and returns\n * ABI-encoded WebAuthn struct compatible with Safe's verifier.\n *\n * @param webAuthnAccount - viem WebAuthnAccount (wraps credential + getFn)\n * @param deployedSignerAddress - Address of the per-credential signer deployed\n * via SafeWebAuthnSignerFactory (NOT the SharedSigner)\n */\nexport function createWebAuthnSafeMessageSigner(\n webAuthnAccount: WebAuthnAccount,\n deployedSignerAddress: Hex,\n): SafeMessageSigner {\n return {\n ownerAddress: deployedSignerAddress,\n async sign(safeMessageHash: Hex): Promise<Hex> {\n return encodeWebAuthnSignature(webAuthnAccount, safeMessageHash);\n },\n };\n}\n\n/**\n * Encodes a WebAuthn signature from raw sign() output into the ABI format\n * expected by Safe's WebAuthn verifier:\n * `(bytes authenticatorData, string clientDataFields, uint256[2] signature)`\n */\nasync function encodeWebAuthnSignature(\n owner: WebAuthnAccount,\n hash: Hex,\n): Promise<Hex> {\n const { signature: signatureData, webauthn } = await owner.sign({ hash });\n\n const sigBytes = signatureData.slice(2);\n const r = BigInt(\"0x\" + sigBytes.slice(0, 64));\n const s = BigInt(\"0x\" + sigBytes.slice(64, 128));\n\n const match = webauthn.clientDataJSON.match(\n /^\\{\"type\":\"webauthn.get\",\"challenge\":\"[A-Za-z0-9\\-_]{43}\",(.*)\\}$/,\n );\n const clientDataFields = match ? match[1] : \"\";\n\n return encodeAbiParameters(\n [\n { name: \"authenticatorData\", type: \"bytes\" },\n { name: \"clientDataFields\", type: \"string\" },\n { name: \"signature\", type: \"uint256[2]\" },\n ],\n [webauthn.authenticatorData, clientDataFields, [r, s]],\n );\n}\n","import { PaymentRequirements } from \"@x402/core/types\";\nimport { UserOperationCapability } from \"./types\";\n\n/**\n * Extracts the user operation capability from the payment requirements.\n *\n * @param requirements - The payment requirements\n * @returns The user operation capability\n */\nexport function extractUserOperationCapability(\n requirements: PaymentRequirements,\n): UserOperationCapability | undefined {\n const userOpExtra = requirements.extra?.userOperation;\n if (\n userOpExtra &&\n typeof userOpExtra === \"object\" &&\n \"supported\" in userOpExtra &&\n userOpExtra.supported === true\n ) {\n return userOpExtra as UserOperationCapability;\n }\n return undefined;\n}\n","import { encodeFunctionData } from \"viem\";\n\n/**\n * Standard ERC20 transfer function ABI\n */\nexport const ERC20_TRANSFER_ABI = [\n {\n type: \"function\",\n name: \"transfer\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ name: \"success\", type: \"bool\" }],\n },\n] as const;\n\n/**\n * Builds ERC20 transfer call data.\n *\n * @param token - The ERC20 token contract address\n * @param to - The recipient address\n * @param amount - The amount to transfer (in token's smallest unit)\n * @returns The encoded call data for the transfer function\n */\nexport function buildERC20TransferCallData(\n token: `0x${string}`,\n to: `0x${string}`,\n amount: bigint,\n): `0x${string}` {\n return encodeFunctionData({\n abi: ERC20_TRANSFER_ABI,\n functionName: \"transfer\",\n args: [to, amount],\n });\n}\n","import type { Hex } from \"viem\";\nimport type { UserOperation07Json } from \"../../facilitator/types\";\n\n/**\n * Converts a bigint value to a hex string in JSON-RPC format.\n *\n * @param value - The bigint value to convert\n * @returns The hex string representation\n */\nfunction toRpcHex(value: bigint): Hex {\n return `0x${value.toString(16)}` as Hex;\n}\n\n/**\n * Converts a user operation with bigint values to JSON-RPC compatible format.\n * This recursively converts all bigint values to hex strings.\n *\n * @param userOp - The user operation object (may contain bigints)\n * @returns The user operation in JSON-RPC format (all bigints converted to hex)\n */\nexport function userOpToJson(userOp: Record<string, unknown>): UserOperation07Json {\n const json: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(userOp)) {\n // Skip internal viem fields that bundlers reject\n if (key === \"account\") continue;\n\n if (typeof value === \"bigint\") {\n json[key] = toRpcHex(value);\n } else if (value && typeof value === \"object\" && !Array.isArray(value)) {\n // Recursively handle nested objects with bigints\n const inner: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n inner[k] = typeof v === \"bigint\" ? toRpcHex(v) : v;\n }\n json[key] = inner;\n } else {\n json[key] = value;\n }\n }\n\n return json as UserOperation07Json;\n}\n","export type PaymentCreationPhase = \"preparation\" | \"signing\" | \"validation\";\n\nconst AA_ERROR_MESSAGES: Record<string, string> = {\n AA10: \"Sender already constructed\",\n AA13: \"InitCode failed or OOG\",\n AA14: \"InitCode must return sender\",\n AA15: \"InitCode must create sender\",\n AA20: \"Account not deployed\",\n AA21: \"Insufficient funds for gas prefund\",\n AA22: \"Expired or not due\",\n AA23: \"Reverted (or OOG)\",\n AA24: \"Signature validation failed\",\n AA25: \"Nonce validation failed\",\n AA26: \"Account accessed global state\",\n AA30: \"Paymaster not deployed\",\n AA31: \"Paymaster deposit too low\",\n AA32: \"Paymaster expired or not due\",\n AA33: \"Paymaster reverted (or OOG)\",\n AA34: \"Paymaster context reverted\",\n AA40: \"Over verification gas limit\",\n AA41: \"Over max fee per gas\",\n AA50: \"Over max priority fee per gas\",\n AA51: \"Prefund below actualGasCost\",\n};\n\n/**\n * Extracts an AA error code (e.g. \"AA21\") from an error and returns\n * a human-readable reason. Returns null if no AA code is found.\n */\nexport function parseAAError(error: unknown): { code: string; reason: string } | null {\n const message = error instanceof Error ? error.message : String(error);\n const match = message.match(/\\b(AA[0-9]{2})\\b/);\n if (!match) return null;\n const code = match[1];\n const reason = AA_ERROR_MESSAGES[code] ?? \"Unknown AA error\";\n return { code, reason };\n}\n\nexport class PaymentCreationError extends Error {\n readonly phase: PaymentCreationPhase;\n readonly reason: string;\n readonly safeAddress?: string;\n readonly network?: string;\n readonly code?: string;\n readonly cause?: unknown;\n\n constructor(\n message: string,\n options: {\n phase: PaymentCreationPhase;\n reason: string;\n safeAddress?: string;\n network?: string;\n code?: string;\n cause?: unknown;\n },\n ) {\n super(message);\n this.name = \"PaymentCreationError\";\n if (options.cause !== undefined) {\n this.cause = options.cause;\n }\n this.phase = options.phase;\n this.reason = options.reason;\n this.safeAddress = options.safeAddress;\n this.network = options.network;\n this.code = options.code;\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n phase: this.phase,\n reason: this.reason,\n ...(this.code && { code: this.code }),\n ...(this.safeAddress && { safeAddress: this.safeAddress }),\n ...(this.network && { network: this.network }),\n };\n }\n}\n","import type { ChainInfo } from \"./types\";\n\nexport const SUPPORTED_CHAINS: Record<number, ChainInfo> = {\n 8453: {\n chainId: 8453,\n name: \"Base\",\n v1Name: \"base\",\n caip2: \"eip155:8453\",\n rpcUrl: \"https://mainnet.base.org\",\n blockExplorerUrl: \"https://basescan.org\",\n usdcAddress: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n safeTransactionServiceUrl: \"https://safe-transaction-base.safe.global\",\n testnet: false,\n },\n 84532: {\n chainId: 84532,\n name: \"Base Sepolia\",\n v1Name: \"base-sepolia\",\n caip2: \"eip155:84532\",\n rpcUrl: \"https://sepolia.base.org\",\n blockExplorerUrl: \"https://sepolia.basescan.org\",\n usdcAddress: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-base-sepolia.safe.global\",\n testnet: true,\n },\n 10: {\n chainId: 10,\n name: \"Optimism\",\n v1Name: \"optimism\",\n caip2: \"eip155:10\",\n rpcUrl: \"https://mainnet.optimism.io\",\n blockExplorerUrl: \"https://optimistic.etherscan.io\",\n usdcAddress: \"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-optimism.safe.global\",\n testnet: false,\n },\n 11155420: {\n chainId: 11155420,\n name: \"Optimism Sepolia\",\n v1Name: \"optimism-sepolia\",\n caip2: \"eip155:11155420\",\n rpcUrl: \"https://sepolia.optimism.io\",\n blockExplorerUrl: \"https://sepolia-optimistic.etherscan.io\",\n usdcAddress: \"0x5fd84259d66Cd46123540766Be93DFE6D43130D7\",\n safeTransactionServiceUrl: undefined,\n testnet: true,\n },\n 42161: {\n chainId: 42161,\n name: \"Arbitrum One\",\n v1Name: \"arbitrum\",\n caip2: \"eip155:42161\",\n rpcUrl: \"https://arb1.arbitrum.io/rpc\",\n blockExplorerUrl: \"https://arbiscan.io\",\n usdcAddress: \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-arbitrum.safe.global\",\n testnet: false,\n },\n 421614: {\n chainId: 421614,\n name: \"Arbitrum Sepolia\",\n v1Name: \"arbitrum-sepolia\",\n caip2: \"eip155:421614\",\n rpcUrl: \"https://sepolia-rollup.arbitrum.io/rpc\",\n blockExplorerUrl: \"https://sepolia.arbiscan.io\",\n usdcAddress: \"0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d\",\n safeTransactionServiceUrl: undefined,\n testnet: true,\n },\n};\n\nexport const V1_NAME_INDEX: Map<string, ChainInfo> = new Map(\n Object.values(SUPPORTED_CHAINS).map((chain) => [chain.v1Name, chain]),\n);\n","import type { CAIP2Identifier, ChainInfo, NetworkInput } from \"./types\";\nimport { SUPPORTED_CHAINS, V1_NAME_INDEX } from \"./registry\";\n\nexport function parseCAIP2(caip2: string): number {\n const match = caip2.match(/^eip155:(\\d+)$/);\n if (!match) {\n throw new Error(\n `Invalid CAIP-2 identifier: ${caip2}. Expected format: eip155:{chainId}`,\n );\n }\n return parseInt(match[1], 10);\n}\n\nexport function toCAIP2(chainId: number): CAIP2Identifier {\n return `eip155:${chainId}` as CAIP2Identifier;\n}\n\nexport function resolveChainId(network: NetworkInput): number {\n if (typeof network === \"number\") {\n return network;\n }\n if (network.startsWith(\"eip155:\")) {\n return parseCAIP2(network);\n }\n const chain = V1_NAME_INDEX.get(network);\n if (!chain) {\n throw new Error(\n `Unknown network: ${network}. Expected CAIP-2 (eip155:chainId), a known v1 name, or a numeric chain ID.`,\n );\n }\n return chain.chainId;\n}\n\nexport function getV1Name(chainId: number): string | undefined {\n return SUPPORTED_CHAINS[chainId]?.v1Name;\n}\n\nexport function getV1Names(chainId: number): string[] {\n const name = getV1Name(chainId);\n return name ? [name] : [];\n}\n\nexport function isSupported(chainId: number): boolean {\n return chainId in SUPPORTED_CHAINS;\n}\n\nexport function getChainById(chainId: number): ChainInfo | undefined {\n return SUPPORTED_CHAINS[chainId];\n}\n\nexport function getChain(network: NetworkInput): ChainInfo {\n const chainId = resolveChainId(network);\n const chain = SUPPORTED_CHAINS[chainId];\n if (!chain) {\n throw new Error(\n `Chain ${chainId} is not in the supported chains registry.`,\n );\n }\n return chain;\n}\n\nexport function getSupportedChains(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS);\n}\n\nexport function getMainnets(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS).filter((c) => !c.testnet);\n}\n\nexport function getTestnets(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS).filter((c) => c.testnet);\n}\n","import type {\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport {\n type Hex,\n getAddress,\n hashTypedData,\n toHex,\n} from \"viem\";\nimport type { SafeMessageSigner } from \"../../../accounts/types\";\nimport { encodeContractSignature } from \"../../../accounts/encodeContractSignature\";\nimport { computeSafeMessageHash } from \"../../../accounts/computeSafeMessageHash\";\nimport { resolveChainId } from \"../../../networks\";\n\nconst 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\nfunction createNonce(): Hex {\n const cryptoObj = globalThis.crypto;\n if (!cryptoObj) throw new Error(\"Crypto API not available\");\n return toHex(cryptoObj.getRandomValues(new Uint8Array(32)));\n}\n\nexport interface ExactEvmSchemeEIP3009Config {\n safeAddress: Hex;\n signer: SafeMessageSigner;\n}\n\n/**\n * EVM client scheme that produces standard EIP-3009 `{ authorization, signature }`\n * payloads from a Safe Smart Account using EIP-1271 contract signatures.\n *\n * Unlike ExactEvmSchemeERC4337 (which creates UserOperation payloads), this scheme\n * creates payloads compatible with any standard x402 facilitator. The facilitator\n * verifies via `verifyTypedData` (which falls back to EIP-1271 for contract addresses)\n * and settles via `transferWithAuthorization(bytes)` (which uses SignatureChecker).\n *\n * Signing flow:\n * 1. Build EIP-3009 authorization (from=Safe, to=payTo, value, nonce, etc.)\n * 2. Compute EIP-712 hash of the authorization\n * 3. Wrap in Safe's message hash (what isValidSignature expects)\n * 4. Sign the Safe message hash via SafeMessageSigner (P256 or WebAuthn)\n * 5. Encode as Safe contract signature (v=0 format)\n *\n * Prerequisites:\n * - Safe must be deployed (EIP-1271 requires on-chain code)\n * - Safe must hold USDC balance (EIP-3009 transfers directly)\n * - USDC must support transferWithAuthorization(bytes) overload (v2.2+)\n */\nexport class ExactEvmSchemeEIP3009 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n private readonly safeAddress: Hex;\n private readonly signer: SafeMessageSigner;\n\n constructor(config: ExactEvmSchemeEIP3009Config) {\n this.safeAddress = config.safeAddress;\n this.signer = config.signer;\n }\n\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, \"x402Version\" | \"payload\">> {\n const chainId = resolveChainId(paymentRequirements.network);\n\n // v1 uses maxAmountRequired, v2 uses amount\n const amount =\n paymentRequirements.amount ??\n ((paymentRequirements as Record<string, unknown>).maxAmountRequired as string | undefined);\n\n if (!amount) {\n throw new Error(\"Payment requirements missing amount (v2) or maxAmountRequired (v1)\");\n }\n\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization = {\n from: getAddress(this.safeAddress),\n to: getAddress(paymentRequirements.payTo),\n value: amount,\n validAfter: (now - 600).toString(),\n validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n // Build EIP-712 domain from payment requirements extra fields\n const extra = paymentRequirements.extra as Record<string, unknown> | undefined;\n if (!extra?.name || !extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${paymentRequirements.asset}`,\n );\n }\n\n const domain = {\n name: extra.name as string,\n version: extra.version as string,\n chainId,\n verifyingContract: getAddress(paymentRequirements.asset) as Hex,\n };\n\n const message = {\n from: getAddress(authorization.from) as Hex,\n to: getAddress(authorization.to) as Hex,\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce as Hex,\n };\n\n // Step 1: Compute the EIP-712 typed data hash\n const eip712Hash = hashTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n\n // Step 2: Wrap in Safe's message hash (what Safe.isValidSignature expects)\n const safeMessageHash = computeSafeMessageHash(\n this.safeAddress,\n chainId,\n eip712Hash,\n );\n\n // Step 3: Sign the Safe message hash (P256 or WebAuthn)\n const innerSignature = await this.signer.sign(safeMessageHash);\n\n // Step 4: Encode as Safe contract signature (v=0)\n const signature = encodeContractSignature(\n this.signer.ownerAddress,\n innerSignature,\n );\n\n const payload = { authorization, signature };\n\n return {\n x402Version,\n ...(x402Version === 1\n ? { scheme: this.scheme, network: paymentRequirements.network }\n : {}),\n payload,\n };\n }\n}\n","import { type Hex, concat, pad, toHex } from \"viem\";\n\n/**\n * Encodes a signature in Safe's contract signature format (v=0).\n *\n * Safe's `checkNSignatures` expects this layout for contract owners:\n *\n * Static part (65 bytes):\n * - r (32 bytes): owner address padded to 32 bytes\n * - s (32 bytes): offset to dynamic data (relative to start of signatures)\n * - v (1 byte): 0x00 (indicates contract signature)\n *\n * Dynamic part (at the offset):\n * - length (32 bytes): length of the signature data\n * - data (variable): the actual signature bytes\n *\n * For a single signer, the static part is 65 bytes, so the dynamic data\n * starts at offset 65.\n */\nexport function encodeContractSignature(ownerAddress: Hex, signatureData: Hex): Hex {\n // Static part: r = address padded to 32 bytes\n const r = pad(ownerAddress, { size: 32 });\n\n // For a single signature, dynamic data starts right after the 65-byte static part\n const dynamicOffset = 65;\n const s = pad(toHex(dynamicOffset), { size: 32 });\n\n // v = 0x00 for contract signature\n const v = \"0x00\" as Hex;\n\n // Dynamic part: length-prefixed signature data\n const signatureBytes = (signatureData.length - 2) / 2;\n const length = pad(toHex(signatureBytes), { size: 32 });\n\n return concat([r, s, v, length, signatureData]);\n}\n","import {\n type Hex,\n encodeAbiParameters,\n encodePacked,\n keccak256,\n} from \"viem\";\n\nconst DOMAIN_SEPARATOR_TYPEHASH = keccak256(\n encodePacked(\n [\"string\"],\n [\"EIP712Domain(uint256 chainId,address verifyingContract)\"],\n ),\n);\n\nconst SAFE_MSG_TYPEHASH = keccak256(\n encodePacked([\"string\"], [\"SafeMessage(bytes message)\"]),\n);\n\n/**\n * Computes the Safe message hash for EIP-1271 signature verification.\n *\n * This is what Safe's `isValidSignature(hash, sig)` expects: the hash is\n * first wrapped in Safe's EIP-712 domain before `checkNSignatures` runs.\n *\n * Flow: keccak256(0x19 || 0x01 || domainSeparator || structHash)\n * where structHash = keccak256(SAFE_MSG_TYPEHASH || keccak256(abi.encode(messageHash)))\n */\nexport function computeSafeMessageHash(\n safeAddress: Hex,\n chainId: number,\n messageHash: Hex,\n): Hex {\n const domainSeparator = keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"uint256\" }, { type: \"address\" }],\n [DOMAIN_SEPARATOR_TYPEHASH, BigInt(chainId), safeAddress],\n ),\n );\n\n const encodedMessage = encodeAbiParameters(\n [{ type: \"bytes32\" }],\n [messageHash],\n );\n const messageHashInner = keccak256(encodedMessage);\n\n const structHash = keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"bytes32\" }],\n [SAFE_MSG_TYPEHASH, messageHashInner],\n ),\n );\n\n return keccak256(\n encodePacked(\n [\"bytes1\", \"bytes1\", \"bytes32\", \"bytes32\"],\n [\"0x19\", \"0x01\", domainSeparator, structHash],\n ),\n );\n}\n","import { encodeAbiParameters, keccak256, type Hex } from \"viem\";\nimport { entryPoint07Address } from \"../../../constants\";\n\nexport interface PackedUserOp {\n sender: Hex;\n nonce: bigint;\n initCode: Hex;\n callData: Hex;\n accountGasLimits: Hex;\n preVerificationGas: bigint;\n gasFees: Hex;\n paymasterAndData: Hex;\n}\n\n/**\n * Compute the UserOperation hash for EntryPoint v0.7 packed format.\n *\n * The hash is computed as:\n * keccak256(abi.encode(keccak256(pack(userOp)), entryPoint, chainId))\n *\n * where pack(userOp) encodes the UserOp fields with initCode, callData,\n * and paymasterAndData replaced by their keccak256 hashes.\n */\nexport function computeUserOpHash(\n packedUserOp: PackedUserOp,\n chainId: number,\n entrypoint: Hex = entryPoint07Address,\n): Hex {\n const encoded = encodeAbiParameters(\n [\n { type: \"address\" },\n { type: \"uint256\" },\n { type: \"bytes32\" },\n { type: \"bytes32\" },\n { type: \"bytes32\" },\n { type: \"uint256\" },\n { type: \"bytes32\" },\n { type: \"bytes32\" },\n ],\n [\n packedUserOp.sender,\n packedUserOp.nonce,\n keccak256(packedUserOp.initCode),\n keccak256(packedUserOp.callData),\n packedUserOp.accountGasLimits,\n packedUserOp.preVerificationGas,\n packedUserOp.gasFees,\n keccak256(packedUserOp.paymasterAndData),\n ],\n );\n\n const innerHash = keccak256(encoded);\n\n return keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"address\" }, { type: \"uint256\" }],\n [innerHash, entrypoint, BigInt(chainId)],\n ),\n );\n}\n","import type { Hex } from \"viem\";\nimport { entryPoint07Address } from \"viem/account-abstraction\";\n\nexport { entryPoint07Address };\n\nexport const SAFE_4337_MODULE_ADDRESS =\n \"0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226\" as const satisfies Hex;\n\nexport const SAFE_WEBAUTHN_SHARED_SIGNER =\n \"0x94a4F6affBd8975951142c3999aEAB7ecee555c2\" as const satisfies Hex;\n\nexport const FCL_P256_VERIFIER =\n \"0xA86e0054C51E4894D88762a017ECc5E5235f5DBA\" as const satisfies Hex;\n\nexport const P256_OWNER_FACTORY =\n \"0x349c03Eb61e26528cbf79F5D3Ba071FcA2aE82cB\" as const satisfies Hex;\n\nexport const WEBAUTHN_SIGNER_FACTORY =\n \"0xF7488fFbe67327ac9f37D5F722d83Fc900852Fbf\" as const satisfies Hex;\n\nexport const GUARD_FACTORY =\n \"0x35E2B487b682029e363BA7f06fD7392834A83077\" as const satisfies Hex;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,IAAAA,eAQO;AACP,gBAA2B;AAC3B,IAAAA,eAA4B;;;ACV5B,kBAAqB;AAErB,iCAA+D;AAuCxD,IAAM,oBAAN,MAAiD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUtD,YAAY,QAAiC;AAC3C,SAAK,UAAU,OAAO;AACtB,SAAK,aAAa;AAGlB,SAAK,oBAAgB,2BAAAC,qBAAwB;AAAA,MAC3C,QAAQ,OAAO;AAAA,MACf,OAAO,OAAO;AAAA,MACd,SAAS,OAAO;AAAA,MAChB,eAAW,kBAAK,OAAO,UAAU;AAAA,IACnC,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,qBACJ,OAEA,aACgC;AAChC,UAAM,WAAW,MAAM,KAAK,cAAc,qBAAqB;AAAA,MAC7D,SAAS,KAAK;AAAA,MACd,OAAO,MAAM,IAAI,WAAS;AAAA,QACxB,IAAI,KAAK;AAAA,QACT,OAAO,KAAK;AAAA,QACZ,MAAM,KAAK;AAAA,MACb,EAAE;AAAA,IACJ,CAAC;AAGD,UAAM,IAAI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AClB,EAAE,MAAM,UAAU;AAAA,MAClB,EAAE,MAAM,UAAU;AAAA,IACpB;AAAA,IACA;AAAA,MACE,aAAa;AAAA,MACb,aAAa;AAAA,UACb,yBAAU,aAAa,QAAQ;AAAA,UAC/B,yBAAU,aAAa,QAAQ;AAAA,MAC/B,aAAa;AAAA,MACb,aAAa;AAAA,MACb,aAAa;AAAA,UACb,yBAAU,aAAa,gBAAgB;AAAA,IACzC;AAAA,EACF;AAEA,QAAM,gBAAY,yBAAU,OAAO;AAEnC,aAAO;AAAA,QACL;AAAA,MACE,CAAC,EAAE,MAAM,UAAU,GAAG,EAAE,MAAM,UAAU,GAAG,EAAE,MAAM,UAAU,CAAC;AAAA,MAC9D,CAAC,WAAW,YAAY,OAAO,OAAO,CAAC;AAAA,IACzC;AAAA,EACF;AACF;","names":["import_viem","createViemBundlerClient","import_viem","import_viem","bundlerUrl","import_viem","import_viem","import_viem","import_viem","import_account_abstraction"]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/exact/client/index.ts","../../../../src/exact/client/schemes/erc4337.ts","../../../../src/exact/client/bundler/viem.ts","../../../../src/exact/client/signers/safeAccountSigner.ts","../../../../src/exact/client/signers/safeMessageSigners.ts","../../../../src/exact/utils.ts","../../../../src/exact/client/utils/callData.ts","../../../../src/exact/client/utils/userOperation.ts","../../../../src/exact/client/errors.ts","../../../../src/networks/registry.ts","../../../../src/networks/helpers.ts","../../../../src/exact/client/schemes/eip3009.ts","../../../../src/accounts/encodeContractSignature.ts","../../../../src/accounts/computeSafeMessageHash.ts","../../../../src/exact/client/utils/userOpHash.ts","../../../../src/constants.ts"],"sourcesContent":["export * from \"./schemes\";\nexport * from \"./signers\";\nexport { PaymentCreationError, parseAAError } from \"./errors\";\nexport type { PaymentCreationPhase } from \"./errors\";\nexport * from \"./bundler\";\nexport * from \"./utils\";\n","import type { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from \"@x402/core/types\";\nimport {\n getAddress,\n createPublicClient,\n http,\n type Chain,\n type PublicClient,\n type Transport,\n Hex,\n} from \"viem\";\nimport * as allChains from \"viem/chains\";\nimport { defineChain } from \"viem\";\nimport type { SmartAccount } from \"viem/account-abstraction\";\nimport type { BundlerClient } from \"../bundler\";\nimport { ViemBundlerClient, type ViemBundlerClientConfig } from \"../bundler/viem\";\nimport type { UserOperationSigner } from \"../signers\";\nimport { SafeAccountSigner } from \"../signers\";\nimport { extractUserOperationCapability } from \"../../utils\";\nimport type { Erc4337Payload } from \"../../facilitator/types\";\nimport { buildERC20TransferCallData } from \"../utils/callData\";\nimport { userOpToJson } from \"../utils/userOperation\";\nimport { PaymentCreationError, parseAAError } from \"../errors\";\nimport { resolveChainId } from \"../../../networks\";\n\n/**\n * Base configuration properties shared by all configuration variants\n */\ninterface ExactEvmSchemeERC4337ConfigBase {\n /**\n * Entry point address (EntryPoint v0.7)\n * Optional - can be provided in payment requirements if not set here\n */\n entrypoint?: Hex;\n\n /**\n * Bundler URL (optional, can be provided in payment requirements).\n * Can be a string or a function that receives the chain ID (number) and\n * the network string (e.g., \"eip155:84532\") and returns the URL.\n * Useful when payments may target different chains.\n */\n bundlerUrl?: string | ((chainId: number, network: string) => string);\n\n /**\n * Paymaster configuration passed to the bundler client.\n * Defaults to `true` (viem calls pm_getPaymasterStubData/pm_getPaymasterData on the bundler).\n * Set to a custom paymaster client to override.\n */\n paymaster?: ViemBundlerClientConfig[\"paymaster\"];\n}\n\n/**\n * Configuration variant when bundlerClient is explicitly provided.\n * Account and publicClient are NOT needed when bundlerClient is used.\n * Signer is required when using bundlerClient.\n */\ntype ExactEvmSchemeERC4337ConfigWithBundler = ExactEvmSchemeERC4337ConfigBase & {\n /**\n * Bundler client for preparing and sending user operations.\n */\n bundlerClient: BundlerClient;\n /**\n * Signer for signing user operations (required when bundlerClient is provided).\n */\n signer: UserOperationSigner;\n} & {\n /**\n * Account must not be provided when bundlerClient is used.\n * Using `never` type prevents this property from being set.\n */\n account?: never;\n /**\n * Public client must not be provided when bundlerClient is used.\n * The bundlerClient already has its own publicClient configured.\n */\n publicClient?: never;\n};\n\n/**\n * Configuration variant when bundlerClient is not provided.\n * Account is required for dynamic bundlerClient creation.\n * Signer is optional - will be auto-created from account if not provided.\n * PublicClient is optional - will create a default from network if not provided.\n */\ntype ExactEvmSchemeERC4337ConfigWithAccount = ExactEvmSchemeERC4337ConfigBase & {\n /**\n * Bundler client is not provided - will be created dynamically from PaymentRequirements.\n * Using `never` type prevents this property from being set.\n */\n bundlerClient?: never;\n} & {\n /**\n * Smart account for user operation preparation.\n * Required when bundlerClient is not provided.\n */\n account: SmartAccount;\n /**\n * Signer for signing user operations.\n * Optional - will be auto-created from account using SafeAccountSigner if not provided.\n * The account must support signUserOperation method for auto-creation to work.\n */\n signer?: UserOperationSigner;\n /**\n * Public client for blockchain interactions.\n * Optional - will create a default from network if not provided.\n */\n publicClient?: PublicClient<Transport, Chain>;\n};\n\n/**\n * Configuration for the ERC-4337 client scheme.\n *\n * This is a discriminated union that enforces type-safe combinations:\n * - Either `bundlerClient` is provided (account and publicClient must NOT be provided)\n * - Or `account` is provided when bundlerClient is not (for dynamic creation, publicClient optional)\n *\n * @example\n * ```typescript\n * // Minimal config (just account - signer auto-created)\n * const scheme1 = new ExactEvmSchemeERC4337({\n * account: myAccount,\n * // signer will be auto-created from account\n * // bundlerClient will be created dynamically from PaymentRequirements\n * });\n *\n * // With account and custom signer\n * const scheme2 = new ExactEvmSchemeERC4337({\n * account: myAccount,\n * signer: myCustomSigner,\n * publicClient: myPublicClient, // Optional\n * });\n *\n * // With explicit bundlerClient (backward compatible)\n * const scheme3 = new ExactEvmSchemeERC4337({\n * bundlerClient: myBundlerClient,\n * signer: mySigner, // Required when bundlerClient is provided\n * // account and publicClient must NOT be provided (bundlerClient has its own)\n * });\n * ```\n */\nexport type ExactEvmSchemeERC4337Config =\n | ExactEvmSchemeERC4337ConfigWithBundler\n | ExactEvmSchemeERC4337ConfigWithAccount;\n\n/**\n * Resolves a network string to a Chain object.\n * Handles both CAIP-2 format (\"eip155:84532\") and v1 plain names (\"base-sepolia\").\n *\n * @param network - Network string in CAIP-2 or v1 plain name format\n * @returns The Chain object\n */\nfunction resolveChain(network: string): Chain {\n const chainId = resolveChainId(network);\n\n const known = Object.values(allChains).find((c: Chain) => c.id === chainId);\n if (known) return known;\n\n return defineChain({\n id: chainId,\n name: network,\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n rpcUrls: { default: { http: [] } },\n });\n}\n\n/**\n * Creates a default public client from a network string.\n *\n * @param network - The network string in CAIP-2 format (e.g., \"eip155:84532\")\n * @returns A PublicClient instance\n */\nfunction createDefaultPublicClient(network: string): PublicClient<Transport, Chain> {\n const chain = resolveChain(network);\n return createPublicClient({\n chain,\n transport: http(),\n });\n}\n\n/**\n * EVM client implementation for the Exact payment scheme using ERC-4337 UserOperations.\n *\n * This implementation creates payment payloads by building and signing UserOperations\n * that execute ERC20 transfers. The UserOperations are prepared using a bundler client\n * and signed using a user operation signer (e.g., Safe account, EOA).\n *\n * Supports minimal configuration: when bundlerClient is not provided and\n * PaymentRequirements.extra.userOperation.supported is true, a ViemBundlerClient\n * will be created dynamically from the payment requirements.\n *\n * @example\n * ```typescript\n * // Minimal config (just account - signer and bundlerClient auto-created)\n * import { ExactEvmSchemeERC4337 } from '@introspectivelabs/x402-evm/exact/client';\n * import { x402Client } from '@x402/core/client';\n *\n * const scheme = new ExactEvmSchemeERC4337({\n * account: safeAccount, // SmartAccount - signer will be auto-created\n * });\n *\n * // With custom signer\n * const scheme2 = new ExactEvmSchemeERC4337({\n * account: safeAccount,\n * signer: customSigner, // Optional - overrides auto-creation\n * });\n *\n * // Explicit config (backward compatible)\n * import { ViemBundlerClient } from '@introspectivelabs/x402-evm/exact/client/bundler';\n *\n * const bundlerClient = new ViemBundlerClient({\n * publicClient,\n * account,\n * chain,\n * bundlerUrl: 'https://bundler.example.com',\n * });\n *\n * const scheme3 = new ExactEvmSchemeERC4337({\n * bundlerClient,\n * signer: account, // Required when bundlerClient is provided\n * });\n *\n * const client = new x402Client();\n * client.register('eip155:84532', scheme);\n * ```\n */\nexport class ExactEvmSchemeERC4337 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n private readonly bundlerClient?: BundlerClient;\n private readonly account?: SmartAccount;\n private readonly publicClient?: PublicClient<Transport, Chain>;\n private readonly signer: UserOperationSigner;\n private readonly entrypoint?: Hex;\n private readonly bundlerUrl?: string | ((chainId: number, network: string) => string);\n private readonly paymaster?: ViemBundlerClientConfig[\"paymaster\"];\n\n /**\n * Creates a new ExactEvmSchemeERC4337 instance.\n *\n * @param config - Configuration for the scheme (type-safe: either bundlerClient or account must be provided)\n * @throws Error if bundlerClient is not provided and account is also not provided (runtime safety check)\n * @throws Error if signer is not provided and account doesn't support signUserOperation\n */\n constructor(config: ExactEvmSchemeERC4337Config) {\n this.bundlerClient = config.bundlerClient;\n this.account = config.account;\n this.publicClient = config.publicClient;\n this.entrypoint = config.entrypoint;\n this.bundlerUrl = config.bundlerUrl;\n this.paymaster = config.paymaster;\n\n // Validate: if bundlerClient is not provided, account must be provided\n if (!this.bundlerClient && !this.account) {\n throw new Error(\n \"Either bundlerClient or account must be provided. \" +\n \"If bundlerClient is not provided, account (SmartAccount) is required for dynamic bundlerClient creation.\",\n );\n }\n\n // Handle signer: use provided signer or auto-create from account\n if (config.signer) {\n this.signer = config.signer;\n } else if (this.account) {\n // Auto-create signer from account if not provided\n if (!this.account.signUserOperation) {\n throw new Error(\n \"Account does not support signUserOperation. \" +\n \"Either provide a signer explicitly or use an account that supports signUserOperation.\",\n );\n }\n this.signer = new SafeAccountSigner(this.account);\n } else {\n // This should not happen due to type system, but add runtime check for safety\n throw new Error(\n \"Signer is required when bundlerClient is provided. \" +\n \"Either provide a signer explicitly or use account-based configuration.\",\n );\n }\n }\n\n /**\n * Creates a payment payload for the Exact scheme using ERC-4337 UserOperations.\n *\n * This method:\n * 1. Extracts user operation capability from payment requirements\n * 2. Creates bundlerClient dynamically if not provided (when userOperation.supported is true)\n * 3. Builds ERC20 transfer call data\n * 4. Prepares the user operation using the bundler client\n * 5. Signs the user operation\n * 6. Converts to JSON-RPC format\n * 7. Returns the x402 payment payload\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n * @throws Error if user operation capability is not found or required fields are missing\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, \"x402Version\" | \"payload\">> {\n // Extract user operation capability (optional - config defaults used when missing)\n const capability = extractUserOperationCapability(paymentRequirements);\n\n // Resolve chain from network (needed for bundlerUrl function and dynamic client)\n const chain = resolveChain(paymentRequirements.network);\n\n // Resolve bundler URL (prioritize config defaults over PaymentRequirements)\n // When bundlerUrl is a function, call it with the target chain's ID and network string\n const configBundlerUrl = typeof this.bundlerUrl === \"function\"\n ? this.bundlerUrl(chain.id, paymentRequirements.network)\n : this.bundlerUrl;\n const bundlerUrl = configBundlerUrl ?? capability?.bundlerUrl;\n\n // Determine which bundlerClient to use\n let bundlerClient: BundlerClient;\n\n if (this.bundlerClient) {\n // Use provided bundlerClient (explicit config, backward compatible)\n bundlerClient = this.bundlerClient;\n } else {\n // Create bundlerClient dynamically from PaymentRequirements\n if (!this.account) {\n throw new Error(\n \"Account (SmartAccount) is required when bundlerClient is not provided. \" +\n \"Either provide bundlerClient in config or account for dynamic creation.\",\n );\n }\n\n if (!bundlerUrl) {\n throw new PaymentCreationError(\n \"Bundler URL not provided\",\n {\n phase: \"validation\",\n reason: \"Set bundlerUrl in ExactEvmSchemeERC4337Config or in payment requirements extra.userOperation.bundlerUrl\",\n network: paymentRequirements.network,\n },\n );\n }\n\n // Use provided publicClient or create default from network\n const publicClient =\n this.publicClient ?? createDefaultPublicClient(paymentRequirements.network);\n\n // Resolve paymaster: default to true (Pimlico-compatible bundlers support PM RPC methods)\n const paymaster = this.paymaster ?? true;\n\n // Create ViemBundlerClient dynamically\n bundlerClient = new ViemBundlerClient({\n publicClient,\n account: this.account,\n chain,\n bundlerUrl,\n paymaster,\n });\n }\n\n // Get entry point (prioritize config defaults over PaymentRequirements)\n const entryPoint = this.entrypoint ?? (capability?.entrypoint as `0x${string}` | undefined);\n\n if (!entryPoint) {\n throw new PaymentCreationError(\n \"Entry point not provided\",\n {\n phase: \"validation\",\n reason: \"Set entrypoint in ExactEvmSchemeERC4337Config or in payment requirements extra.userOperation.entrypoint\",\n network: paymentRequirements.network,\n },\n );\n }\n\n if (!bundlerUrl) {\n throw new PaymentCreationError(\n \"Bundler URL not provided\",\n {\n phase: \"validation\",\n reason: \"Set bundlerUrl in ExactEvmSchemeERC4337Config or in payment requirements extra.userOperation.bundlerUrl\",\n network: paymentRequirements.network,\n },\n );\n }\n\n // Normalize addresses\n const token = getAddress(paymentRequirements.asset);\n const payTo = getAddress(paymentRequirements.payTo);\n // Handle both v2 (amount) and v1 (maxAmountRequired) fields\n const amountStr =\n paymentRequirements.amount ??\n ((paymentRequirements as Record<string, unknown>).maxAmountRequired as string | undefined);\n if (!amountStr) {\n throw new Error(\"Payment requirements missing amount (v2) or maxAmountRequired (v1)\");\n }\n const amount = BigInt(amountStr);\n\n // Build ERC20 transfer call data\n const callData = buildERC20TransferCallData(token, payTo, amount);\n\n // Prepare user operation (unsigned)\n let unsignedUserOp;\n try {\n unsignedUserOp = await bundlerClient.prepareUserOperation(\n [\n {\n to: token,\n value: BigInt(0), // ERC20 transfers don't send ETH\n data: callData,\n },\n ],\n entryPoint,\n );\n } catch (error) {\n const aaError = parseAAError(error);\n throw new PaymentCreationError(\n aaError\n ? `Payment preparation failed: ${aaError.reason}`\n : `Payment preparation failed: ${error instanceof Error ? error.message : String(error)}`,\n {\n phase: \"preparation\",\n reason: aaError?.reason ?? (error instanceof Error ? error.message : String(error)),\n network: paymentRequirements.network,\n code: aaError?.code,\n cause: error,\n },\n );\n }\n\n // Sign the user operation\n let signature;\n try {\n signature = await this.signer.signUserOperation(unsignedUserOp);\n } catch (error) {\n const aaError = parseAAError(error);\n throw new PaymentCreationError(\n aaError\n ? `Payment signing failed: ${aaError.reason}`\n : `Payment signing failed: ${error instanceof Error ? error.message : String(error)}`,\n {\n phase: \"signing\",\n reason: aaError?.reason ?? (error instanceof Error ? error.message : String(error)),\n network: paymentRequirements.network,\n code: aaError?.code,\n cause: error,\n },\n );\n }\n\n // Create signed user operation\n const signedUserOp = {\n ...unsignedUserOp,\n signature,\n };\n\n // Convert to JSON-RPC format (bigint -> hex)\n const jsonUserOp = userOpToJson(signedUserOp);\n\n // Build the ERC-4337 payload\n const payload: Erc4337Payload = {\n type: \"erc4337\",\n entryPoint,\n bundlerRpcUrl: bundlerUrl,\n userOperation: jsonUserOp,\n };\n\n return {\n x402Version,\n // v1 requires scheme and network at top level\n ...(x402Version === 1\n ? { scheme: this.scheme, network: paymentRequirements.network }\n : {}),\n payload,\n };\n }\n}\n","import { type Chain, type Hex, type PublicClient, type Transport } from \"viem\";\nimport { http } from \"viem\";\nimport type { SmartAccount } from \"viem/account-abstraction\";\nimport { createBundlerClient as createViemBundlerClient } from \"viem/account-abstraction\";\nimport type {\n BundlerClient,\n BundlerClientConfig,\n GasEstimate,\n PreparedUserOperation,\n UserOperationCall,\n} from \"./client\";\nimport type { UserOperation07Json } from \"../../facilitator/types\";\n\nfunction bigintToHex(n: bigint): Hex {\n return `0x${n.toString(16)}` as Hex;\n}\n\n/**\n * Configuration for creating a viem-based bundler client\n */\nexport interface ViemBundlerClientConfig extends BundlerClientConfig {\n /**\n * Viem public client for blockchain interactions\n */\n publicClient: PublicClient<Transport, Chain>;\n\n /**\n * Smart account for user operation preparation (must be a SmartAccount, not a regular Account)\n */\n account: SmartAccount;\n\n /**\n * Chain configuration\n */\n chain: Chain;\n\n /**\n * Bundler RPC URL\n */\n bundlerUrl: string;\n\n /**\n * Paymaster configuration. When `true`, calls pm_sponsorUserOperation on the bundler URL\n * to get paymaster sponsorship (Pimlico-compatible). The paymaster data is included in the\n * UserOp hash computation before signing.\n */\n paymaster?: true | { getPaymasterData: (...args: any[]) => any; getPaymasterStubData: (...args: any[]) => any };\n}\n\n/**\n * Paymaster sponsorship result from pm_sponsorUserOperation (Pimlico)\n */\ninterface PaymasterSponsorResult {\n paymaster?: Hex;\n paymasterData?: Hex;\n paymasterVerificationGasLimit?: Hex;\n paymasterPostOpGasLimit?: Hex;\n paymasterAndData?: Hex;\n callGasLimit: Hex;\n verificationGasLimit: Hex;\n preVerificationGas: Hex;\n}\n\n/**\n * Viem-based implementation of BundlerClient.\n *\n * Uses raw RPC calls for paymaster sponsorship (pm_sponsorUserOperation) to maintain\n * full control over the UserOp lifecycle. This avoids viem's middleware which can\n * re-call paymaster RPCs between preparation and signing, causing hash mismatches.\n *\n * Flow (matching the proven playground approach):\n * 1. Build callData via account.encodeCalls()\n * 2. Get nonce via account.getNonce()\n * 3. Get gas prices via pimlico_getUserOperationGasPrice\n * 4. Build estimation UserOp with dummy signature\n * 5. Call pm_sponsorUserOperation for paymaster data + gas estimates\n * 6. Return PreparedUserOperation with final paymaster data (ready for signing)\n */\nexport class ViemBundlerClient implements BundlerClient {\n private readonly bundlerClient: ReturnType<typeof createViemBundlerClient>;\n private readonly account: SmartAccount;\n private readonly usePaymaster: boolean;\n\n constructor(config: ViemBundlerClientConfig) {\n this.account = config.account;\n this.usePaymaster = config.paymaster === true;\n\n // Create viem bundler client for RPC transport (used for raw requests)\n // Do NOT pass paymaster to avoid viem middleware interference\n this.bundlerClient = createViemBundlerClient({\n client: config.publicClient,\n chain: config.chain,\n account: config.account,\n transport: http(config.bundlerUrl),\n });\n }\n\n /**\n * Prepares an unsigned user operation using raw RPC calls.\n *\n * When paymaster is enabled, uses pm_sponsorUserOperation to get paymaster\n * data and gas estimates in a single call (Pimlico-compatible).\n * The returned UserOp has final paymaster data ready for hash computation and signing.\n */\n async prepareUserOperation(\n calls: UserOperationCall[],\n entryPoint: `0x${string}`,\n ): Promise<PreparedUserOperation> {\n if (!this.usePaymaster) {\n // No paymaster: delegate to viem's prepareUserOperation (no middleware issues)\n return this.prepareWithoutPaymaster(calls);\n }\n\n // Paymaster flow: use raw RPC calls for full control\n const callData = await this.account.encodeCalls(\n calls.map(call => ({\n to: call.to,\n value: call.value,\n data: call.data,\n })),\n );\n\n const nonce = await this.account.getNonce();\n const sender = await this.account.getAddress();\n\n // Get gas prices from bundler\n const gasPriceResult = await this.bundlerClient.request({\n method: \"pimlico_getUserOperationGasPrice\" as any,\n params: [] as any,\n }) as { fast: { maxFeePerGas: Hex; maxPriorityFeePerGas: Hex } };\n\n const maxFeePerGas = BigInt(gasPriceResult.fast.maxFeePerGas);\n const maxPriorityFeePerGas = BigInt(gasPriceResult.fast.maxPriorityFeePerGas);\n\n const stubSignature = await this.account.getStubSignature();\n\n {\n // Build estimation UserOp with placeholder gas values\n const userOpForEstimation = {\n sender,\n nonce: `0x${nonce.toString(16)}` as Hex,\n callData,\n signature: stubSignature,\n callGasLimit: bigintToHex(500_000n),\n verificationGasLimit: bigintToHex(500_000n),\n preVerificationGas: bigintToHex(100_000n),\n maxFeePerGas: bigintToHex(maxFeePerGas),\n maxPriorityFeePerGas: bigintToHex(maxPriorityFeePerGas),\n };\n\n // 6. Get paymaster sponsorship (single call for data + gas)\n const sponsorResult = await this.bundlerClient.request({\n method: \"pm_sponsorUserOperation\" as any,\n params: [userOpForEstimation, entryPoint] as any,\n }) as PaymasterSponsorResult;\n\n // Extract gas limits from sponsor result\n const callGasLimit = BigInt(sponsorResult.callGasLimit);\n const verificationGasLimit = BigInt(sponsorResult.verificationGasLimit);\n const preVerificationGas = BigInt(sponsorResult.preVerificationGas);\n\n // Build paymaster fields\n let paymaster: Hex | undefined;\n let paymasterData: Hex | undefined;\n let paymasterVerificationGasLimit: bigint | undefined;\n let paymasterPostOpGasLimit: bigint | undefined;\n\n if (sponsorResult.paymaster) {\n // v0.7 separate fields\n paymaster = sponsorResult.paymaster;\n paymasterData = sponsorResult.paymasterData ?? \"0x\";\n paymasterVerificationGasLimit = BigInt(sponsorResult.paymasterVerificationGasLimit ?? \"0x0\");\n paymasterPostOpGasLimit = BigInt(sponsorResult.paymasterPostOpGasLimit ?? \"0x0\");\n } else if (sponsorResult.paymasterAndData && sponsorResult.paymasterAndData !== \"0x\") {\n // v0.6 packed format: paymaster(20) || pmVerificationGas(16) || pmPostOpGas(16) || pmData\n const packed = sponsorResult.paymasterAndData;\n paymaster = `0x${packed.slice(2, 42)}` as Hex;\n paymasterVerificationGasLimit = BigInt(`0x${packed.slice(42, 74)}`);\n paymasterPostOpGasLimit = BigInt(`0x${packed.slice(74, 106)}`);\n paymasterData = `0x${packed.slice(106)}` as Hex;\n }\n\n return {\n sender,\n nonce,\n // Include factory/factoryData keys so that downstream signers (e.g. permissionless\n // Safe signUserOperation) detect v0.7 format and correctly pack paymasterAndData\n // from the separate v0.7 fields. Without these keys, permissionless defaults to\n // paymasterAndData: \"0x\" causing SafeOp hash mismatch (AA24).\n factory: undefined,\n factoryData: undefined,\n callData,\n callGasLimit,\n verificationGasLimit,\n preVerificationGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n ...(paymaster ? { paymaster } : {}),\n ...(paymasterData ? { paymasterData } : {}),\n ...(paymasterVerificationGasLimit != null ? { paymasterVerificationGasLimit } : {}),\n ...(paymasterPostOpGasLimit != null ? { paymasterPostOpGasLimit } : {}),\n signature: stubSignature,\n };\n }\n\n }\n\n private async prepareWithoutPaymaster(\n calls: UserOperationCall[],\n ): Promise<PreparedUserOperation> {\n const prepared = await this.bundlerClient.prepareUserOperation({\n account: this.account,\n calls: calls.map(call => ({\n to: call.to,\n value: call.value,\n data: call.data,\n })),\n });\n\n const p = prepared as Record<string, unknown>;\n\n return {\n sender: prepared.sender,\n nonce: prepared.nonce,\n // Always include factory/factoryData keys for v0.7 format detection by signers\n factory: (p.factory as `0x${string}`) ?? undefined,\n factoryData: (p.factoryData as `0x${string}`) ?? undefined,\n callData: prepared.callData,\n callGasLimit: prepared.callGasLimit,\n verificationGasLimit: prepared.verificationGasLimit,\n preVerificationGas: prepared.preVerificationGas,\n maxFeePerGas: prepared.maxFeePerGas,\n maxPriorityFeePerGas: prepared.maxPriorityFeePerGas,\n signature: prepared.signature,\n } as PreparedUserOperation;\n }\n\n /**\n * @deprecated Gas estimation is done as part of prepareUserOperation\n */\n async estimateGas(\n _userOp: UserOperation07Json,\n _entryPoint: `0x${string}`,\n ): Promise<GasEstimate> {\n throw new Error(\n \"estimateGas should be called through prepareUserOperation, which includes gas estimation\",\n );\n }\n\n /**\n * Sends a signed user operation to the bundler via raw eth_sendUserOperation RPC.\n *\n * Bypasses viem's middleware to avoid re-calling paymaster RPCs which would\n * change paymaster fields and invalidate the signature.\n */\n async sendUserOperation(\n userOp: UserOperation07Json,\n entryPoint: `0x${string}`,\n ): Promise<string> {\n const hash = await this.bundlerClient.request({\n method: \"eth_sendUserOperation\",\n params: [userOp as any, entryPoint],\n });\n\n return hash as string;\n }\n}\n","import type { SmartAccount } from \"viem/account-abstraction\";\nimport type { PreparedUserOperation } from \"../bundler\";\nimport type { UserOperationSigner } from \"./types\";\n\n/**\n * Adapter to make a SmartAccount (e.g., Safe account) work as a UserOperationSigner.\n *\n * This class wraps a SmartAccount that supports `signUserOperation` and adapts it\n * to the UserOperationSigner interface required by the x402 ERC-4337 scheme.\n *\n * @example\n * ```typescript\n * import { SafeAccountSigner } from \"@introspectivelabs/x402-evm/exact/client\";\n * import { toSafeSmartAccount } from \"permissionless/accounts\";\n *\n * const safeAccount = await toSafeSmartAccount({ ... });\n * const signer = new SafeAccountSigner(safeAccount);\n *\n * const scheme = new ExactEvmSchemeERC4337({\n * bundlerClient,\n * signer,\n * });\n * ```\n */\nexport class SafeAccountSigner implements UserOperationSigner {\n readonly address: `0x${string}`;\n\n /**\n * Creates a new SafeAccountSigner instance.\n *\n * @param account - The SmartAccount instance (e.g., from permissionless/accounts)\n * @throws Error if the account is not initialized or missing an address\n */\n constructor(private readonly account: SmartAccount) {\n if (!account?.address) {\n throw new Error(\"Smart account not initialized\");\n }\n this.address = account.address as `0x${string}`;\n }\n\n /**\n * Signs a prepared (unsigned) user operation.\n *\n * @param userOp - The prepared user operation to sign\n * @returns Promise resolving to the signature\n * @throws Error if the account does not support signUserOperation\n */\n async signUserOperation(userOp: PreparedUserOperation): Promise<`0x${string}`> {\n if (!this.account?.signUserOperation) {\n throw new Error(\"Smart account does not support signUserOperation\");\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await this.account.signUserOperation(userOp as any);\n }\n}\n","import { type Hex, concat, encodeAbiParameters } from \"viem\";\nimport type { WebAuthnAccount } from \"viem/account-abstraction\";\nimport type { P256Signer, SafeMessageSigner } from \"../../../accounts/types\";\n\n/**\n * Creates a SafeMessageSigner from a P256Signer.\n * The sign method returns concat([r, s]) (64 bytes raw P256 signature).\n */\nexport function createP256SafeMessageSigner(\n p256Signer: P256Signer,\n): SafeMessageSigner {\n return {\n ownerAddress: p256Signer.p256OwnerAddress,\n async sign(safeMessageHash: Hex): Promise<Hex> {\n const { r, s } = await p256Signer.sign(safeMessageHash);\n return concat([r, s]);\n },\n };\n}\n\n/**\n * Creates a SafeMessageSigner from a WebAuthnAccount.\n * The sign method triggers navigator.credentials.get() and returns\n * ABI-encoded WebAuthn struct compatible with Safe's verifier.\n *\n * @param webAuthnAccount - viem WebAuthnAccount (wraps credential + getFn)\n * @param deployedSignerAddress - Address of the per-credential signer deployed\n * via SafeWebAuthnSignerFactory (NOT the SharedSigner)\n */\nexport function createWebAuthnSafeMessageSigner(\n webAuthnAccount: WebAuthnAccount,\n deployedSignerAddress: Hex,\n): SafeMessageSigner {\n return {\n ownerAddress: deployedSignerAddress,\n async sign(safeMessageHash: Hex): Promise<Hex> {\n return encodeWebAuthnSignature(webAuthnAccount, safeMessageHash);\n },\n };\n}\n\n/**\n * Encodes a WebAuthn signature from raw sign() output into the ABI format\n * expected by Safe's WebAuthn verifier:\n * `(bytes authenticatorData, string clientDataFields, uint256[2] signature)`\n */\nasync function encodeWebAuthnSignature(\n owner: WebAuthnAccount,\n hash: Hex,\n): Promise<Hex> {\n const { signature: signatureData, webauthn } = await owner.sign({ hash });\n\n const sigBytes = signatureData.slice(2);\n const r = BigInt(\"0x\" + sigBytes.slice(0, 64));\n const s = BigInt(\"0x\" + sigBytes.slice(64, 128));\n\n const match = webauthn.clientDataJSON.match(\n /^\\{\"type\":\"webauthn.get\",\"challenge\":\"[A-Za-z0-9\\-_]{43}\",(.*)\\}$/,\n );\n const clientDataFields = match ? match[1] : \"\";\n\n return encodeAbiParameters(\n [\n { name: \"authenticatorData\", type: \"bytes\" },\n { name: \"clientDataFields\", type: \"string\" },\n { name: \"signature\", type: \"uint256[2]\" },\n ],\n [webauthn.authenticatorData, clientDataFields, [r, s]],\n );\n}\n","import { PaymentRequirements } from \"@x402/core/types\";\nimport { UserOperationCapability } from \"./types\";\n\n/**\n * Extracts the user operation capability from the payment requirements.\n *\n * @param requirements - The payment requirements\n * @returns The user operation capability\n */\nexport function extractUserOperationCapability(\n requirements: PaymentRequirements,\n): UserOperationCapability | undefined {\n const userOpExtra = requirements.extra?.userOperation;\n if (\n userOpExtra &&\n typeof userOpExtra === \"object\" &&\n \"supported\" in userOpExtra &&\n userOpExtra.supported === true\n ) {\n return userOpExtra as UserOperationCapability;\n }\n return undefined;\n}\n","import { encodeFunctionData } from \"viem\";\n\n/**\n * Standard ERC20 transfer function ABI\n */\nexport const ERC20_TRANSFER_ABI = [\n {\n type: \"function\",\n name: \"transfer\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ name: \"success\", type: \"bool\" }],\n },\n] as const;\n\n/**\n * Builds ERC20 transfer call data.\n *\n * @param token - The ERC20 token contract address\n * @param to - The recipient address\n * @param amount - The amount to transfer (in token's smallest unit)\n * @returns The encoded call data for the transfer function\n */\nexport function buildERC20TransferCallData(\n token: `0x${string}`,\n to: `0x${string}`,\n amount: bigint,\n): `0x${string}` {\n return encodeFunctionData({\n abi: ERC20_TRANSFER_ABI,\n functionName: \"transfer\",\n args: [to, amount],\n });\n}\n","import type { Hex } from \"viem\";\nimport type { UserOperation07Json } from \"../../facilitator/types\";\n\n/**\n * Converts a bigint value to a hex string in JSON-RPC format.\n *\n * @param value - The bigint value to convert\n * @returns The hex string representation\n */\nfunction toRpcHex(value: bigint): Hex {\n return `0x${value.toString(16)}` as Hex;\n}\n\n/**\n * Converts a user operation with bigint values to JSON-RPC compatible format.\n * This recursively converts all bigint values to hex strings.\n *\n * @param userOp - The user operation object (may contain bigints)\n * @returns The user operation in JSON-RPC format (all bigints converted to hex)\n */\nexport function userOpToJson(userOp: Record<string, unknown>): UserOperation07Json {\n const json: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(userOp)) {\n // Skip internal viem fields that bundlers reject\n if (key === \"account\") continue;\n // Skip undefined values (e.g., factory: undefined used for v0.7 format detection)\n if (value === undefined) continue;\n\n if (typeof value === \"bigint\") {\n json[key] = toRpcHex(value);\n } else if (value && typeof value === \"object\" && !Array.isArray(value)) {\n // Recursively handle nested objects with bigints\n const inner: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n inner[k] = typeof v === \"bigint\" ? toRpcHex(v) : v;\n }\n json[key] = inner;\n } else {\n json[key] = value;\n }\n }\n\n return json as UserOperation07Json;\n}\n","export type PaymentCreationPhase = \"preparation\" | \"signing\" | \"validation\";\n\nconst AA_ERROR_MESSAGES: Record<string, string> = {\n AA10: \"Sender already constructed\",\n AA13: \"InitCode failed or OOG\",\n AA14: \"InitCode must return sender\",\n AA15: \"InitCode must create sender\",\n AA20: \"Account not deployed\",\n AA21: \"Insufficient funds for gas prefund\",\n AA22: \"Expired or not due\",\n AA23: \"Reverted (or OOG)\",\n AA24: \"Signature validation failed\",\n AA25: \"Nonce validation failed\",\n AA26: \"Account accessed global state\",\n AA30: \"Paymaster not deployed\",\n AA31: \"Paymaster deposit too low\",\n AA32: \"Paymaster expired or not due\",\n AA33: \"Paymaster reverted (or OOG)\",\n AA34: \"Paymaster context reverted\",\n AA40: \"Over verification gas limit\",\n AA41: \"Over max fee per gas\",\n AA50: \"Over max priority fee per gas\",\n AA51: \"Prefund below actualGasCost\",\n};\n\n/**\n * Extracts an AA error code (e.g. \"AA21\") from an error and returns\n * a human-readable reason. Returns null if no AA code is found.\n */\nexport function parseAAError(error: unknown): { code: string; reason: string } | null {\n const message = error instanceof Error ? error.message : String(error);\n const match = message.match(/\\b(AA[0-9]{2})\\b/);\n if (!match) return null;\n const code = match[1];\n const reason = AA_ERROR_MESSAGES[code] ?? \"Unknown AA error\";\n return { code, reason };\n}\n\nexport class PaymentCreationError extends Error {\n readonly phase: PaymentCreationPhase;\n readonly reason: string;\n readonly safeAddress?: string;\n readonly network?: string;\n readonly code?: string;\n readonly cause?: unknown;\n\n constructor(\n message: string,\n options: {\n phase: PaymentCreationPhase;\n reason: string;\n safeAddress?: string;\n network?: string;\n code?: string;\n cause?: unknown;\n },\n ) {\n super(message);\n this.name = \"PaymentCreationError\";\n if (options.cause !== undefined) {\n this.cause = options.cause;\n }\n this.phase = options.phase;\n this.reason = options.reason;\n this.safeAddress = options.safeAddress;\n this.network = options.network;\n this.code = options.code;\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n phase: this.phase,\n reason: this.reason,\n ...(this.code && { code: this.code }),\n ...(this.safeAddress && { safeAddress: this.safeAddress }),\n ...(this.network && { network: this.network }),\n };\n }\n}\n","import type { ChainInfo } from \"./types\";\n\nexport const SUPPORTED_CHAINS: Record<number, ChainInfo> = {\n 8453: {\n chainId: 8453,\n name: \"Base\",\n v1Name: \"base\",\n caip2: \"eip155:8453\",\n rpcUrl: \"https://mainnet.base.org\",\n blockExplorerUrl: \"https://basescan.org\",\n usdcAddress: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n safeTransactionServiceUrl: \"https://safe-transaction-base.safe.global\",\n testnet: false,\n },\n 84532: {\n chainId: 84532,\n name: \"Base Sepolia\",\n v1Name: \"base-sepolia\",\n caip2: \"eip155:84532\",\n rpcUrl: \"https://sepolia.base.org\",\n blockExplorerUrl: \"https://sepolia.basescan.org\",\n usdcAddress: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-base-sepolia.safe.global\",\n testnet: true,\n },\n 10: {\n chainId: 10,\n name: \"Optimism\",\n v1Name: \"optimism\",\n caip2: \"eip155:10\",\n rpcUrl: \"https://mainnet.optimism.io\",\n blockExplorerUrl: \"https://optimistic.etherscan.io\",\n usdcAddress: \"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-optimism.safe.global\",\n testnet: false,\n },\n 11155420: {\n chainId: 11155420,\n name: \"Optimism Sepolia\",\n v1Name: \"optimism-sepolia\",\n caip2: \"eip155:11155420\",\n rpcUrl: \"https://sepolia.optimism.io\",\n blockExplorerUrl: \"https://sepolia-optimistic.etherscan.io\",\n usdcAddress: \"0x5fd84259d66Cd46123540766Be93DFE6D43130D7\",\n safeTransactionServiceUrl: undefined,\n testnet: true,\n },\n 42161: {\n chainId: 42161,\n name: \"Arbitrum One\",\n v1Name: \"arbitrum\",\n caip2: \"eip155:42161\",\n rpcUrl: \"https://arb1.arbitrum.io/rpc\",\n blockExplorerUrl: \"https://arbiscan.io\",\n usdcAddress: \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\",\n safeTransactionServiceUrl:\n \"https://safe-transaction-arbitrum.safe.global\",\n testnet: false,\n },\n 421614: {\n chainId: 421614,\n name: \"Arbitrum Sepolia\",\n v1Name: \"arbitrum-sepolia\",\n caip2: \"eip155:421614\",\n rpcUrl: \"https://sepolia-rollup.arbitrum.io/rpc\",\n blockExplorerUrl: \"https://sepolia.arbiscan.io\",\n usdcAddress: \"0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d\",\n safeTransactionServiceUrl: undefined,\n testnet: true,\n },\n};\n\nexport const V1_NAME_INDEX: Map<string, ChainInfo> = new Map(\n Object.values(SUPPORTED_CHAINS).map((chain) => [chain.v1Name, chain]),\n);\n","import type { CAIP2Identifier, ChainInfo, NetworkInput } from \"./types\";\nimport { SUPPORTED_CHAINS, V1_NAME_INDEX } from \"./registry\";\n\nexport function parseCAIP2(caip2: string): number {\n const match = caip2.match(/^eip155:(\\d+)$/);\n if (!match) {\n throw new Error(\n `Invalid CAIP-2 identifier: ${caip2}. Expected format: eip155:{chainId}`,\n );\n }\n return parseInt(match[1], 10);\n}\n\nexport function toCAIP2(chainId: number): CAIP2Identifier {\n return `eip155:${chainId}` as CAIP2Identifier;\n}\n\nexport function resolveChainId(network: NetworkInput): number {\n if (typeof network === \"number\") {\n return network;\n }\n if (network.startsWith(\"eip155:\")) {\n return parseCAIP2(network);\n }\n const chain = V1_NAME_INDEX.get(network);\n if (!chain) {\n throw new Error(\n `Unknown network: ${network}. Expected CAIP-2 (eip155:chainId), a known v1 name, or a numeric chain ID.`,\n );\n }\n return chain.chainId;\n}\n\nexport function getV1Name(chainId: number): string | undefined {\n return SUPPORTED_CHAINS[chainId]?.v1Name;\n}\n\nexport function getV1Names(chainId: number): string[] {\n const name = getV1Name(chainId);\n return name ? [name] : [];\n}\n\nexport function isSupported(chainId: number): boolean {\n return chainId in SUPPORTED_CHAINS;\n}\n\nexport function getChainById(chainId: number): ChainInfo | undefined {\n return SUPPORTED_CHAINS[chainId];\n}\n\nexport function getChain(network: NetworkInput): ChainInfo {\n const chainId = resolveChainId(network);\n const chain = SUPPORTED_CHAINS[chainId];\n if (!chain) {\n throw new Error(\n `Chain ${chainId} is not in the supported chains registry.`,\n );\n }\n return chain;\n}\n\nexport function getSupportedChains(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS);\n}\n\nexport function getMainnets(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS).filter((c) => !c.testnet);\n}\n\nexport function getTestnets(): ChainInfo[] {\n return Object.values(SUPPORTED_CHAINS).filter((c) => c.testnet);\n}\n","import type {\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"@x402/core/types\";\nimport {\n type Hex,\n getAddress,\n hashTypedData,\n toHex,\n} from \"viem\";\nimport type { SafeMessageSigner } from \"../../../accounts/types\";\nimport { encodeContractSignature } from \"../../../accounts/encodeContractSignature\";\nimport { computeSafeMessageHash } from \"../../../accounts/computeSafeMessageHash\";\nimport { resolveChainId } from \"../../../networks\";\n\nconst 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\nfunction createNonce(): Hex {\n const cryptoObj = globalThis.crypto;\n if (!cryptoObj) throw new Error(\"Crypto API not available\");\n return toHex(cryptoObj.getRandomValues(new Uint8Array(32)));\n}\n\nexport interface ExactEvmSchemeEIP3009Config {\n safeAddress: Hex;\n signer: SafeMessageSigner;\n}\n\n/**\n * EVM client scheme that produces standard EIP-3009 `{ authorization, signature }`\n * payloads from a Safe Smart Account using EIP-1271 contract signatures.\n *\n * Unlike ExactEvmSchemeERC4337 (which creates UserOperation payloads), this scheme\n * creates payloads compatible with any standard x402 facilitator. The facilitator\n * verifies via `verifyTypedData` (which falls back to EIP-1271 for contract addresses)\n * and settles via `transferWithAuthorization(bytes)` (which uses SignatureChecker).\n *\n * Signing flow:\n * 1. Build EIP-3009 authorization (from=Safe, to=payTo, value, nonce, etc.)\n * 2. Compute EIP-712 hash of the authorization\n * 3. Wrap in Safe's message hash (what isValidSignature expects)\n * 4. Sign the Safe message hash via SafeMessageSigner (P256 or WebAuthn)\n * 5. Encode as Safe contract signature (v=0 format)\n *\n * Prerequisites:\n * - Safe must be deployed (EIP-1271 requires on-chain code)\n * - Safe must hold USDC balance (EIP-3009 transfers directly)\n * - USDC must support transferWithAuthorization(bytes) overload (v2.2+)\n */\nexport class ExactEvmSchemeEIP3009 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n private readonly safeAddress: Hex;\n private readonly signer: SafeMessageSigner;\n\n constructor(config: ExactEvmSchemeEIP3009Config) {\n this.safeAddress = config.safeAddress;\n this.signer = config.signer;\n }\n\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, \"x402Version\" | \"payload\">> {\n const chainId = resolveChainId(paymentRequirements.network);\n\n // v1 uses maxAmountRequired, v2 uses amount\n const amount =\n paymentRequirements.amount ??\n ((paymentRequirements as Record<string, unknown>).maxAmountRequired as string | undefined);\n\n if (!amount) {\n throw new Error(\"Payment requirements missing amount (v2) or maxAmountRequired (v1)\");\n }\n\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization = {\n from: getAddress(this.safeAddress),\n to: getAddress(paymentRequirements.payTo),\n value: amount,\n validAfter: (now - 600).toString(),\n validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n // Build EIP-712 domain from payment requirements extra fields\n const extra = paymentRequirements.extra as Record<string, unknown> | undefined;\n if (!extra?.name || !extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${paymentRequirements.asset}`,\n );\n }\n\n const domain = {\n name: extra.name as string,\n version: extra.version as string,\n chainId,\n verifyingContract: getAddress(paymentRequirements.asset) as Hex,\n };\n\n const message = {\n from: getAddress(authorization.from) as Hex,\n to: getAddress(authorization.to) as Hex,\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce as Hex,\n };\n\n // Step 1: Compute the EIP-712 typed data hash\n const eip712Hash = hashTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n\n // Step 2: Wrap in Safe's message hash (what Safe.isValidSignature expects)\n const safeMessageHash = computeSafeMessageHash(\n this.safeAddress,\n chainId,\n eip712Hash,\n );\n\n // Step 3: Sign the Safe message hash (P256 or WebAuthn)\n const innerSignature = await this.signer.sign(safeMessageHash);\n\n // Step 4: Encode as Safe contract signature (v=0)\n const signature = encodeContractSignature(\n this.signer.ownerAddress,\n innerSignature,\n );\n\n const payload = { authorization, signature };\n\n return {\n x402Version,\n ...(x402Version === 1\n ? { scheme: this.scheme, network: paymentRequirements.network }\n : {}),\n payload,\n };\n }\n}\n","import { type Hex, concat, pad, toHex } from \"viem\";\n\n/**\n * Encodes a signature in Safe's contract signature format (v=0).\n *\n * Safe's `checkNSignatures` expects this layout for contract owners:\n *\n * Static part (65 bytes):\n * - r (32 bytes): owner address padded to 32 bytes\n * - s (32 bytes): offset to dynamic data (relative to start of signatures)\n * - v (1 byte): 0x00 (indicates contract signature)\n *\n * Dynamic part (at the offset):\n * - length (32 bytes): length of the signature data\n * - data (variable): the actual signature bytes\n *\n * For a single signer, the static part is 65 bytes, so the dynamic data\n * starts at offset 65.\n */\nexport function encodeContractSignature(ownerAddress: Hex, signatureData: Hex): Hex {\n // Static part: r = address padded to 32 bytes\n const r = pad(ownerAddress, { size: 32 });\n\n // For a single signature, dynamic data starts right after the 65-byte static part\n const dynamicOffset = 65;\n const s = pad(toHex(dynamicOffset), { size: 32 });\n\n // v = 0x00 for contract signature\n const v = \"0x00\" as Hex;\n\n // Dynamic part: length-prefixed signature data\n const signatureBytes = (signatureData.length - 2) / 2;\n const length = pad(toHex(signatureBytes), { size: 32 });\n\n return concat([r, s, v, length, signatureData]);\n}\n","import {\n type Hex,\n encodeAbiParameters,\n encodePacked,\n keccak256,\n} from \"viem\";\n\nconst DOMAIN_SEPARATOR_TYPEHASH = keccak256(\n encodePacked(\n [\"string\"],\n [\"EIP712Domain(uint256 chainId,address verifyingContract)\"],\n ),\n);\n\nconst SAFE_MSG_TYPEHASH = keccak256(\n encodePacked([\"string\"], [\"SafeMessage(bytes message)\"]),\n);\n\n/**\n * Computes the Safe message hash for EIP-1271 signature verification.\n *\n * This is what Safe's `isValidSignature(hash, sig)` expects: the hash is\n * first wrapped in Safe's EIP-712 domain before `checkNSignatures` runs.\n *\n * Flow: keccak256(0x19 || 0x01 || domainSeparator || structHash)\n * where structHash = keccak256(SAFE_MSG_TYPEHASH || keccak256(abi.encode(messageHash)))\n */\nexport function computeSafeMessageHash(\n safeAddress: Hex,\n chainId: number,\n messageHash: Hex,\n): Hex {\n const domainSeparator = keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"uint256\" }, { type: \"address\" }],\n [DOMAIN_SEPARATOR_TYPEHASH, BigInt(chainId), safeAddress],\n ),\n );\n\n const encodedMessage = encodeAbiParameters(\n [{ type: \"bytes32\" }],\n [messageHash],\n );\n const messageHashInner = keccak256(encodedMessage);\n\n const structHash = keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"bytes32\" }],\n [SAFE_MSG_TYPEHASH, messageHashInner],\n ),\n );\n\n return keccak256(\n encodePacked(\n [\"bytes1\", \"bytes1\", \"bytes32\", \"bytes32\"],\n [\"0x19\", \"0x01\", domainSeparator, structHash],\n ),\n );\n}\n","import { encodeAbiParameters, keccak256, type Hex } from \"viem\";\nimport { entryPoint07Address } from \"../../../constants\";\n\nexport interface PackedUserOp {\n sender: Hex;\n nonce: bigint;\n initCode: Hex;\n callData: Hex;\n accountGasLimits: Hex;\n preVerificationGas: bigint;\n gasFees: Hex;\n paymasterAndData: Hex;\n}\n\n/**\n * Compute the UserOperation hash for EntryPoint v0.7 packed format.\n *\n * The hash is computed as:\n * keccak256(abi.encode(keccak256(pack(userOp)), entryPoint, chainId))\n *\n * where pack(userOp) encodes the UserOp fields with initCode, callData,\n * and paymasterAndData replaced by their keccak256 hashes.\n */\nexport function computeUserOpHash(\n packedUserOp: PackedUserOp,\n chainId: number,\n entrypoint: Hex = entryPoint07Address,\n): Hex {\n const encoded = encodeAbiParameters(\n [\n { type: \"address\" },\n { type: \"uint256\" },\n { type: \"bytes32\" },\n { type: \"bytes32\" },\n { type: \"bytes32\" },\n { type: \"uint256\" },\n { type: \"bytes32\" },\n { type: \"bytes32\" },\n ],\n [\n packedUserOp.sender,\n packedUserOp.nonce,\n keccak256(packedUserOp.initCode),\n keccak256(packedUserOp.callData),\n packedUserOp.accountGasLimits,\n packedUserOp.preVerificationGas,\n packedUserOp.gasFees,\n keccak256(packedUserOp.paymasterAndData),\n ],\n );\n\n const innerHash = keccak256(encoded);\n\n return keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"address\" }, { type: \"uint256\" }],\n [innerHash, entrypoint, BigInt(chainId)],\n ),\n );\n}\n","import type { Hex } from \"viem\";\nimport { entryPoint07Address } from \"viem/account-abstraction\";\n\nexport { entryPoint07Address };\n\nexport const SAFE_4337_MODULE_ADDRESS =\n \"0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226\" as const satisfies Hex;\n\nexport const SAFE_WEBAUTHN_SHARED_SIGNER =\n \"0x94a4F6affBd8975951142c3999aEAB7ecee555c2\" as const satisfies Hex;\n\nexport const FCL_P256_VERIFIER =\n \"0xA86e0054C51E4894D88762a017ECc5E5235f5DBA\" as const satisfies Hex;\n\nexport const P256_OWNER_FACTORY =\n \"0x349c03Eb61e26528cbf79F5D3Ba071FcA2aE82cB\" as const satisfies Hex;\n\nexport const WEBAUTHN_SIGNER_FACTORY =\n \"0xF7488fFbe67327ac9f37D5F722d83Fc900852Fbf\" as const satisfies Hex;\n\nexport const GUARD_FACTORY =\n \"0x35E2B487b682029e363BA7f06fD7392834A83077\" as const satisfies Hex;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,IAAAA,eAQO;AACP,gBAA2B;AAC3B,IAAAA,eAA4B;;;ACV5B,kBAAqB;AAErB,iCAA+D;AAU/D,SAAS,YAAY,GAAgB;AACnC,SAAO,KAAK,EAAE,SAAS,EAAE,CAA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AW,YAAY,OAAO,OAAO,CAAC;AAAA,IACzC;AAAA,EACF;AACF;","names":["import_viem","createViemBundlerClient","import_viem","import_viem","import_viem","import_viem","import_viem","import_viem","import_account_abstraction"]}
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { RoutesConfig, RouteConfig } from '@x402/core/server';
|
|
|
5
5
|
import { ExactEvmSchemeERC4337 } from './exact/server/index.js';
|
|
6
6
|
export { BundlerError, ExactEvmSchemeNetworkERC4337, ExactEvmSchemeNetworkERC4337Config, BundlerClient as FacilitatorBundlerClient, BundlerClientConfig as FacilitatorBundlerClientConfig, GasEstimate as FacilitatorGasEstimate, UserOperationReceipt } from './exact/facilitator/index.js';
|
|
7
7
|
export { E as Erc4337Payload, U as UserOperation07Json } from './types-Dk5U6Xnw.js';
|
|
8
|
-
export { B as ClientBundlerClient, f as ClientBundlerClientConfig, G as ClientGasEstimate, j as ERC20_TRANSFER_ABI, b as ExactEvmSchemeEIP3009, c as ExactEvmSchemeEIP3009Config, E as ExactEvmSchemeERC4337Client, a as ExactEvmSchemeERC4337Config, l as PackedUserOp, P as PreparedUserOperation, g as UserOperationCall, U as UserOperationSigner, V as ViemBundlerClient, h as ViemBundlerClientConfig, i as buildERC20TransferCallData, k as computeUserOpHash, d as createP256SafeMessageSigner, e as createWebAuthnSafeMessageSigner, u as userOpToJson } from './userOpHash-
|
|
8
|
+
export { B as ClientBundlerClient, f as ClientBundlerClientConfig, G as ClientGasEstimate, j as ERC20_TRANSFER_ABI, b as ExactEvmSchemeEIP3009, c as ExactEvmSchemeEIP3009Config, E as ExactEvmSchemeERC4337Client, a as ExactEvmSchemeERC4337Config, l as PackedUserOp, P as PreparedUserOperation, g as UserOperationCall, U as UserOperationSigner, V as ViemBundlerClient, h as ViemBundlerClientConfig, i as buildERC20TransferCallData, k as computeUserOpHash, d as createP256SafeMessageSigner, e as createWebAuthnSafeMessageSigner, u as userOpToJson } from './userOpHash-CLhOwl2X.js';
|
|
9
9
|
export { entryPoint07Address } from 'viem/account-abstraction';
|
|
10
10
|
export { SafeOpHashParams, ToP256ExecutorModuleAccountParams, ToWebAuthnSafeSmartAccountParams, computeSafeOpHash, encodeContractSignature, extractPasskeyCoordinates, toP256ExecutorModuleAccount, toP256SafeSmartAccount, toSafeSmartAccount, toWebAuthnSafeSmartAccount } from './accounts/index.js';
|
|
11
11
|
export { P as P256Signer, S as SafeMessageSigner, a as SignerConfig, T as ToP256SafeSmartAccountParams, b as ToSafeSmartAccountParams } from './types-lO5B0FRc.js';
|