@baliola/smart-account-sdk 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ import { n as ISmartAccount, r as SigningAccount, t as Call } from "../types-CD0TvpY4.js";
2
+ import { n as MacChainName } from "../index-BVqNo3O0.js";
3
+ import { Account, Hex, PublicClient, Transport } from "viem";
4
+
5
+ //#region src/accounts/encodeCalls.d.ts
6
+ declare function encodeCalls(calls: Call[]): Hex;
7
+ //#endregion
8
+ //#region src/accounts/toSmartAccount.d.ts
9
+ type OwnerInput = Account | Hex;
10
+ interface ToSmartAccountParams {
11
+ owner: OwnerInput;
12
+ chain: MacChainName;
13
+ salt?: bigint;
14
+ nonceKey?: bigint;
15
+ transport?: Transport;
16
+ publicClient?: PublicClient;
17
+ }
18
+ declare function toSmartAccount(params: ToSmartAccountParams): Promise<ISmartAccount>;
19
+ //#endregion
20
+ export { Call, ISmartAccount, SigningAccount, ToSmartAccountParams, encodeCalls, toSmartAccount };
@@ -0,0 +1,2 @@
1
+ import { n as encodeCalls, t as toSmartAccount } from "../accounts-Bw0IrOJ1.js";
2
+ export { encodeCalls, toSmartAccount };
@@ -0,0 +1,229 @@
1
+ import { n as simpleAccountAbi, r as simpleAccountFactoryAbi, t as entryPointAbi } from "./abi-ziHt832n.js";
2
+ import { t as deployments } from "./deployments-D4U_osAQ.js";
3
+ import { resolveChain } from "./chains/index.js";
4
+ import { concat, createPublicClient, encodeAbiParameters, encodeFunctionData, http, isHex, keccak256, pad, toHex } from "viem";
5
+ import { privateKeyToAccount } from "viem/accounts";
6
+ //#region src/accounts/encodeCalls.ts
7
+ function encodeCalls(calls) {
8
+ if (calls.length === 0) throw new Error("encodeCalls requires at least one call");
9
+ if (calls.length === 1) {
10
+ const call = calls[0];
11
+ return encodeFunctionData({
12
+ abi: simpleAccountAbi,
13
+ functionName: "execute",
14
+ args: [
15
+ call.to,
16
+ call.value ?? 0n,
17
+ call.data ?? "0x"
18
+ ]
19
+ });
20
+ }
21
+ return encodeFunctionData({
22
+ abi: simpleAccountAbi,
23
+ functionName: "executeBatch",
24
+ args: [
25
+ calls.map((c) => c.to),
26
+ calls.map((c) => c.value ?? 0n),
27
+ calls.map((c) => c.data ?? "0x")
28
+ ]
29
+ });
30
+ }
31
+ //#endregion
32
+ //#region ../shared/src/user-op/hash.ts
33
+ /**
34
+ * v0.7 EntryPoint.getUserOpHash equivalent:
35
+ *
36
+ * inner = keccak256(abi.encode(
37
+ * sender, nonce,
38
+ * keccak256(initCode), keccak256(callData),
39
+ * accountGasLimits, preVerificationGas, gasFees,
40
+ * keccak256(paymasterAndData)
41
+ * ))
42
+ * userOpHash = keccak256(abi.encode(inner, entryPoint, chainId))
43
+ */
44
+ function userOpHash(op, entryPoint, chainId) {
45
+ return keccak256(encodeAbiParameters([
46
+ {
47
+ name: "inner",
48
+ type: "bytes32"
49
+ },
50
+ {
51
+ name: "entryPoint",
52
+ type: "address"
53
+ },
54
+ {
55
+ name: "chainId",
56
+ type: "uint256"
57
+ }
58
+ ], [
59
+ keccak256(encodeAbiParameters([
60
+ {
61
+ name: "sender",
62
+ type: "address"
63
+ },
64
+ {
65
+ name: "nonce",
66
+ type: "uint256"
67
+ },
68
+ {
69
+ name: "hashInitCode",
70
+ type: "bytes32"
71
+ },
72
+ {
73
+ name: "hashCallData",
74
+ type: "bytes32"
75
+ },
76
+ {
77
+ name: "accountGasLimits",
78
+ type: "bytes32"
79
+ },
80
+ {
81
+ name: "preVerificationGas",
82
+ type: "uint256"
83
+ },
84
+ {
85
+ name: "gasFees",
86
+ type: "bytes32"
87
+ },
88
+ {
89
+ name: "hashPaymasterAndData",
90
+ type: "bytes32"
91
+ }
92
+ ], [
93
+ op.sender,
94
+ op.nonce,
95
+ keccak256(op.initCode),
96
+ keccak256(op.callData),
97
+ op.accountGasLimits,
98
+ op.preVerificationGas,
99
+ op.gasFees,
100
+ keccak256(op.paymasterAndData)
101
+ ])),
102
+ entryPoint,
103
+ chainId
104
+ ]));
105
+ }
106
+ //#endregion
107
+ //#region ../shared/src/user-op/pack.ts
108
+ const UINT128_MASK = (1n << 128n) - 1n;
109
+ function packUints(high, low) {
110
+ if (high < 0n || high > UINT128_MASK) throw new Error(`high out of uint128 range: ${high}`);
111
+ if (low < 0n || low > UINT128_MASK) throw new Error(`low out of uint128 range: ${low}`);
112
+ return concat([pad(toHex(high), { size: 16 }), pad(toHex(low), { size: 16 })]);
113
+ }
114
+ function packInitCode(factory, factoryData) {
115
+ if (!factory || factory === "0x") return "0x";
116
+ return concat([factory, factoryData ?? "0x"]);
117
+ }
118
+ function packPaymasterAndData(paymaster, verificationGasLimit, postOpGasLimit, data) {
119
+ if (!paymaster || paymaster === "0x") return "0x";
120
+ const vgl = pad(toHex(verificationGasLimit ?? 0n), { size: 16 });
121
+ const pog = pad(toHex(postOpGasLimit ?? 0n), { size: 16 });
122
+ const extra = data && data !== "0x" ? data : "0x";
123
+ return extra === "0x" ? concat([
124
+ paymaster,
125
+ vgl,
126
+ pog
127
+ ]) : concat([
128
+ paymaster,
129
+ vgl,
130
+ pog,
131
+ extra
132
+ ]);
133
+ }
134
+ function pack(op) {
135
+ return {
136
+ sender: op.sender,
137
+ nonce: op.nonce,
138
+ initCode: packInitCode(op.factory, op.factoryData),
139
+ callData: op.callData,
140
+ accountGasLimits: packUints(op.verificationGasLimit, op.callGasLimit),
141
+ preVerificationGas: op.preVerificationGas,
142
+ gasFees: packUints(op.maxPriorityFeePerGas, op.maxFeePerGas),
143
+ paymasterAndData: packPaymasterAndData(op.paymaster, op.paymasterVerificationGasLimit, op.paymasterPostOpGasLimit, op.paymasterData),
144
+ signature: op.signature
145
+ };
146
+ }
147
+ //#endregion
148
+ //#region src/accounts/toSmartAccount.ts
149
+ const PRIVATE_KEY_HEX_LENGTH = 66;
150
+ function lookupDeployment(chainId) {
151
+ const chainDeployments = deployments[chainId];
152
+ if (!chainDeployments) throw new Error(`toSmartAccount: no deployment found for chain id ${chainId}`);
153
+ const entryPoint = chainDeployments["01-EntryPoint"]?.EntryPoint;
154
+ const factory = chainDeployments["02-AccountFactory"]?.SimpleAccountFactory;
155
+ if (!entryPoint || !factory) throw new Error(`toSmartAccount: chain ${chainId} is missing EntryPoint or SimpleAccountFactory`);
156
+ return {
157
+ factory,
158
+ entryPoint
159
+ };
160
+ }
161
+ function resolveOwner(input) {
162
+ const account = typeof input === "string" ? fromPrivateKeyHex(input) : input;
163
+ if (!account.signMessage) throw new Error("toSmartAccount: owner Account must implement signMessage");
164
+ return account;
165
+ }
166
+ function fromPrivateKeyHex(input) {
167
+ if (!isHex(input) || input.length !== PRIVATE_KEY_HEX_LENGTH) throw new Error("toSmartAccount: owner hex must be a 32-byte 0x-prefixed private key");
168
+ return privateKeyToAccount(input);
169
+ }
170
+ async function toSmartAccount(params) {
171
+ const chain = resolveChain(params.chain);
172
+ const salt = params.salt ?? 0n;
173
+ const nonceKey = params.nonceKey ?? 0n;
174
+ const owner = resolveOwner(params.owner);
175
+ const { factory, entryPoint } = lookupDeployment(chain.id);
176
+ const address = await (params.publicClient ?? createPublicClient({
177
+ chain,
178
+ transport: params.transport ?? http()
179
+ })).readContract({
180
+ address: factory,
181
+ abi: simpleAccountFactoryAbi,
182
+ functionName: "getAddress",
183
+ args: [owner.address, salt]
184
+ });
185
+ const factoryData = encodeFunctionData({
186
+ abi: simpleAccountFactoryAbi,
187
+ functionName: "createAccount",
188
+ args: [owner.address, salt]
189
+ });
190
+ let deployedCache = false;
191
+ return {
192
+ address,
193
+ owner,
194
+ factory,
195
+ factoryData,
196
+ entryPoint,
197
+ nonceKey,
198
+ chainId: chain.id,
199
+ async isDeployed(client) {
200
+ if (deployedCache) return true;
201
+ const code = await client.getCode({ address });
202
+ if (code && code !== "0x") {
203
+ deployedCache = true;
204
+ return true;
205
+ }
206
+ return false;
207
+ },
208
+ markDeployed() {
209
+ deployedCache = true;
210
+ },
211
+ async signUserOperation(op) {
212
+ const hash = userOpHash(pack(op), entryPoint, BigInt(chain.id));
213
+ return owner.signMessage({ message: { raw: hash } });
214
+ },
215
+ encodeCalls(calls) {
216
+ return encodeCalls(calls);
217
+ },
218
+ async getNonce(client) {
219
+ return await client.readContract({
220
+ address: entryPoint,
221
+ abi: entryPointAbi,
222
+ functionName: "getNonce",
223
+ args: [address, nonceKey]
224
+ });
225
+ }
226
+ };
227
+ }
228
+ //#endregion
229
+ export { encodeCalls as n, toSmartAccount as t };
@@ -0,0 +1,37 @@
1
+ import { i as IUserOperation, t as Call } from "../types-CD0TvpY4.js";
2
+ import { _ as EstimateUserOperationGasParams, a as WriteContractOverrides, b as SmartAccountActionContext, c as UnwatchFn, d as watchUserOperations, f as WaitForUserOperationReceiptParams, g as sliceUserOpLogs, h as getUserOperationReceipt, i as WriteContractInput, l as UserOperationEventMatch, m as GetUserOperationReceiptParams, n as RawCall, o as bindWriteContract, p as waitForUserOperationReceipt, r as TypedCall, s as writeContract, t as BoundWriteContract, u as WatchUserOperationsParams, v as estimateUserOpGasRaw, x as UserOperationGasEstimate, y as estimateUserOperationGas } from "../writeContract-CdcmYmx0.js";
3
+ import { Hex } from "viem";
4
+
5
+ //#region src/actions/buildDraft.d.ts
6
+ declare const DRAFT_GAS_ANCHORS: {
7
+ readonly callGasLimit: 200000n;
8
+ readonly verificationGasLimit: 900000n;
9
+ readonly preVerificationGas: 150000n;
10
+ readonly paymasterVerificationGasLimit: 200000n;
11
+ readonly paymasterPostOpGasLimit: 100000n;
12
+ };
13
+ /**
14
+ * 65-byte dummy signature used during `eth_estimateUserOperationGas`.
15
+ *
16
+ * SimpleAccount's `_validateSignature` calls OpenZeppelin 5.0.2's
17
+ * `ECDSA.recover(hash, signature)`, which enforces EIP-2 low-`s` (reverts
18
+ * when `s > n/2`) and rejects zero-recovery. A naive dummy like `0xfa * 64`
19
+ * has a high `s` and causes the simulation to revert before the account
20
+ * can return `SIG_VALIDATION_FAILED`.
21
+ *
22
+ * This dummy uses `r = 1`, `s = 1`, `v = 27` — all within OZ's accepted
23
+ * ranges. `ecrecover` returns a valid, non-zero address that almost
24
+ * certainly is not the owner, so the account returns
25
+ * `SIG_VALIDATION_FAILED` cleanly and the simulator produces gas numbers.
26
+ */
27
+ declare const DUMMY_SIGNATURE: Hex;
28
+ /**
29
+ * Build an unsigned, un-paymastered, pre-estimate UserOperation from raw
30
+ * calls. Gas limits are seeded to generous defaults so the bundler's
31
+ * estimator can simulate through MAC's Frontier EVM and return precise
32
+ * values; fee fields default to the chain's `gasPrice` (MAC reports legacy
33
+ * pricing, so `maxFee` and `maxPriorityFee` are equal).
34
+ */
35
+ declare function buildDraftUserOp(ctx: SmartAccountActionContext, calls: Call[], overrides?: Partial<IUserOperation>): Promise<IUserOperation>;
36
+ //#endregion
37
+ export { BoundWriteContract, DRAFT_GAS_ANCHORS, DUMMY_SIGNATURE, EstimateUserOperationGasParams, GetUserOperationReceiptParams, RawCall, SmartAccountActionContext, TypedCall, UnwatchFn, UserOperationEventMatch, UserOperationGasEstimate, WaitForUserOperationReceiptParams, WatchUserOperationsParams, WriteContractInput, WriteContractOverrides, bindWriteContract, buildDraftUserOp, estimateUserOpGasRaw, estimateUserOperationGas, getUserOperationReceipt, sliceUserOpLogs, waitForUserOperationReceipt, watchUserOperations, writeContract };
@@ -0,0 +1,2 @@
1
+ import { a as getUserOperationReceipt, c as estimateUserOperationGas, d as DRAFT_GAS_ANCHORS, f as DUMMY_SIGNATURE, i as waitForUserOperationReceipt, n as writeContract, o as sliceUserOpLogs, p as buildDraftUserOp, r as watchUserOperations, s as estimateUserOpGasRaw, t as bindWriteContract } from "../writeContract-AyQox2dQ.js";
2
+ export { DRAFT_GAS_ANCHORS, DUMMY_SIGNATURE, bindWriteContract, buildDraftUserOp, estimateUserOpGasRaw, estimateUserOperationGas, getUserOperationReceipt, sliceUserOpLogs, waitForUserOperationReceipt, watchUserOperations, writeContract };
@@ -0,0 +1,35 @@
1
+ import { n as MacChainName } from "../index-BVqNo3O0.js";
2
+ import { n as ApiKeyInvalidReason, r as ApiKeyQuota, t as ApiKeyInfo } from "../types-BcsdeCby.js";
3
+
4
+ //#region src/auth/authUrls.d.ts
5
+ /**
6
+ * Default baliola-auth base URLs per MAC chain. The SDK appends
7
+ * `/api/api-keys/validate` to whatever URL is configured.
8
+ */
9
+ declare const DEFAULT_AUTH_URLS: Record<MacChainName, string>;
10
+ /**
11
+ * Resolve the auth base URL for a chain, honoring an optional override
12
+ * (e.g. `http://localhost:8000` during dev). Trailing slashes are stripped
13
+ * so the caller can append a path safely.
14
+ */
15
+ declare function resolveAuthUrl(chainName: MacChainName, override?: string): string;
16
+ //#endregion
17
+ //#region src/auth/validateApiKey.d.ts
18
+ interface ValidateApiKeyParams {
19
+ /** Auth base URL — `<baliola-auth host>`, without `/api/...`. */
20
+ authUrl: string;
21
+ /** Customer key (`baliola_key_…` or `baliola_secret_…`). */
22
+ apiKey: string;
23
+ }
24
+ /**
25
+ * Validate a customer API key against `baliola-auth` and return the resolved
26
+ * key info on success. Throws `ApiKeyInvalidError` on a structured rejection
27
+ * (`valid: false` or `401`), and `BaliolaAuthUnreachableError` on network /
28
+ * transport failures (fetch rejection, non-2xx 5xx, unparseable body).
29
+ *
30
+ * One successful call charges one quota unit against the key — callers should
31
+ * cache the resulting client rather than re-invoking the factory.
32
+ */
33
+ declare function validateApiKey(params: ValidateApiKeyParams): Promise<ApiKeyInfo>;
34
+ //#endregion
35
+ export { ApiKeyInfo, ApiKeyInvalidReason, ApiKeyQuota, DEFAULT_AUTH_URLS, ValidateApiKeyParams, resolveAuthUrl, validateApiKey };
@@ -0,0 +1,2 @@
1
+ import { n as DEFAULT_AUTH_URLS, r as resolveAuthUrl, t as validateApiKey } from "../validateApiKey-lUfEM5W0.js";
2
+ export { DEFAULT_AUTH_URLS, resolveAuthUrl, validateApiKey };
@@ -0,0 +1,104 @@
1
+ //#region src/errors/base.ts
2
+ /**
3
+ * Root class for every error thrown from inside the SDK.
4
+ *
5
+ * **Opinionated message convention**: `err.message` is always written for an
6
+ * end user — short, polite, and safe to surface directly in product UI. The
7
+ * machine-readable discriminators live on:
8
+ * - `err.code` — internal tag or AA-code string
9
+ * - `err.reason` — typed enum on errors that have one
10
+ * - `err.detail` — optional technical sentence for developer logs
11
+ * - `err.cause` — the underlying transport / library error
12
+ *
13
+ * Translate or rebrand `err.message` only when you need a different tone or
14
+ * locale; you can always rebuild your own copy from `err.code` / `err.reason`.
15
+ */
16
+ var SmartAccountSDKError = class extends Error {
17
+ code;
18
+ detail;
19
+ userOp;
20
+ cause;
21
+ constructor(message, options) {
22
+ super(message);
23
+ this.name = new.target.name;
24
+ this.code = options.code;
25
+ if (options.detail !== void 0) this.detail = options.detail;
26
+ if (options.userOp !== void 0) this.userOp = options.userOp;
27
+ if (options.cause !== void 0) this.cause = options.cause;
28
+ }
29
+ };
30
+ var UserOperationReceiptTimeoutError = class extends SmartAccountSDKError {
31
+ userOpHash;
32
+ timeoutMs;
33
+ constructor(userOpHash, timeoutMs) {
34
+ super("Your transaction is taking longer than expected. Please check the block explorer or try again.", {
35
+ code: "RECEIPT_TIMEOUT",
36
+ detail: `Timed out after ${timeoutMs}ms waiting for ${userOpHash}`
37
+ });
38
+ this.userOpHash = userOpHash;
39
+ this.timeoutMs = timeoutMs;
40
+ }
41
+ };
42
+ const PAYMASTER_CONFIG_MESSAGES = {
43
+ invalid_address: "Gas sponsorship address is invalid. Please contact support.",
44
+ zero_address: "Gas sponsorship address is invalid. Please contact support.",
45
+ no_registered_paymaster: "Gas sponsorship isn't available for this network. Please contact support."
46
+ };
47
+ /**
48
+ * Thrown at SDK construction when the paymaster configuration is unusable.
49
+ * The user-facing message is generic; `reason` + `detail` carry the dev info.
50
+ */
51
+ var PaymasterConfigError = class extends SmartAccountSDKError {
52
+ reason;
53
+ constructor(reason, detail) {
54
+ super(PAYMASTER_CONFIG_MESSAGES[reason], {
55
+ code: "PAYMASTER_CONFIG",
56
+ detail
57
+ });
58
+ this.reason = reason;
59
+ }
60
+ };
61
+ const API_KEY_MESSAGES = {
62
+ not_found: "Invalid API key. Please check your credentials.",
63
+ revoked: "This API key has been revoked. Please generate a new one.",
64
+ expired: "This API key has expired. Please generate a new one.",
65
+ wrong_module: "This API key isn't authorized for this app.",
66
+ module_inactive: "This service is currently unavailable. Please try again later.",
67
+ origin_not_allowed: "This domain isn't allowed to use this API key.",
68
+ quota_exceeded: "You've hit the request limit. Please try again later.",
69
+ rate_limited: "Too many requests. Please slow down and try again."
70
+ };
71
+ /**
72
+ * Thrown by `createSmartAccountClient` when baliola-auth rejects the API key.
73
+ * `reason` is the strict enum string; `message` is the matching user copy.
74
+ */
75
+ var ApiKeyInvalidError = class extends SmartAccountSDKError {
76
+ reason;
77
+ retryAfterSeconds;
78
+ constructor(reason, retryAfterSeconds) {
79
+ super(API_KEY_MESSAGES[reason], {
80
+ code: "API_KEY_INVALID",
81
+ detail: `baliola-auth rejected the key (reason=${reason})`
82
+ });
83
+ this.reason = reason;
84
+ if (retryAfterSeconds !== void 0) this.retryAfterSeconds = retryAfterSeconds;
85
+ }
86
+ };
87
+ /**
88
+ * Thrown when baliola-auth is unreachable — fetch rejection, 5xx, or
89
+ * unparseable body. Distinct from `ApiKeyInvalidError`, which covers
90
+ * structured rejections.
91
+ */
92
+ var BaliolaAuthUnreachableError = class extends SmartAccountSDKError {
93
+ url;
94
+ constructor(url, cause) {
95
+ super("Authentication service is temporarily unavailable. Please try again in a moment.", {
96
+ code: "AUTH_UNREACHABLE",
97
+ detail: `Failed to reach baliola-auth at ${url}`,
98
+ cause
99
+ });
100
+ this.url = url;
101
+ }
102
+ };
103
+ //#endregion
104
+ export { UserOperationReceiptTimeoutError as a, SmartAccountSDKError as i, BaliolaAuthUnreachableError as n, PaymasterConfigError as r, ApiKeyInvalidError as t };
@@ -0,0 +1,2 @@
1
+ import { a as resolveChain, i as macTestnet, n as MacChainName, r as macMainnet, t as MAC_CHAINS } from "../index-BVqNo3O0.js";
2
+ export { MAC_CHAINS, MacChainName, macMainnet, macTestnet, resolveChain };
@@ -0,0 +1,33 @@
1
+ import { defineChain } from "viem";
2
+ //#region src/chains/index.ts
3
+ const macTestnet = defineChain({
4
+ id: 20017,
5
+ name: "MAC Testnet",
6
+ nativeCurrency: {
7
+ name: "Kepeng Testnet",
8
+ symbol: "KPGBT",
9
+ decimals: 18
10
+ },
11
+ rpcUrls: { default: { http: ["https://collator1.baliola.dev"] } },
12
+ testnet: true
13
+ });
14
+ const macMainnet = defineChain({
15
+ id: 20016,
16
+ name: "MAC",
17
+ nativeCurrency: {
18
+ name: "Kepeng",
19
+ symbol: "KPGB",
20
+ decimals: 18
21
+ },
22
+ rpcUrls: { default: { http: ["https://collator4-mac.baliola.io"] } },
23
+ testnet: false
24
+ });
25
+ const MAC_CHAINS = {
26
+ macTestnet,
27
+ macMainnet
28
+ };
29
+ function resolveChain(name) {
30
+ return MAC_CHAINS[name];
31
+ }
32
+ //#endregion
33
+ export { MAC_CHAINS, macMainnet, macTestnet, resolveChain };
@@ -0,0 +1,161 @@
1
+ import { i as SmartAccountSDKError } from "./base-v7RyiDFz.js";
2
+ //#region src/errors/bundlerError.ts
3
+ /** Base class for every error originating from the bundler's JSON-RPC surface. */
4
+ var BundlerRpcError = class extends SmartAccountSDKError {
5
+ constructor(message, options) {
6
+ super(message, options);
7
+ }
8
+ };
9
+ /** `-32602` — bundler rejected the params (invalid UserOp shape, fee too low, etc.). */
10
+ var InvalidUserOperationError = class extends BundlerRpcError {};
11
+ /** `-32500` and kin — bundler accepted the shape but dropped the op on submit. */
12
+ var UserOperationRejectedError = class extends BundlerRpcError {};
13
+ /** Network or transport failure reaching the bundler — not an on-chain rejection. */
14
+ var BundlerUnreachableError = class extends BundlerRpcError {};
15
+ //#endregion
16
+ //#region src/errors/aaError.ts
17
+ /**
18
+ * Base class for errors produced when the EntryPoint or one of its
19
+ * validation partners rejects a UserOperation. The `code` is the AA-code
20
+ * string from the bundler (e.g. "AA24"); subclasses narrow by bucket.
21
+ */
22
+ var UserOperationRevertError = class extends SmartAccountSDKError {
23
+ constructor(message, options) {
24
+ super(message, options);
25
+ }
26
+ };
27
+ /** AA1x — Smart Account factory / `initCode` deployment failures. */
28
+ var AccountFactoryError = class extends UserOperationRevertError {};
29
+ /** AA2x — account's `validateUserOp` rejection (prefund, signature, nonce). */
30
+ var AccountValidationError = class extends UserOperationRevertError {};
31
+ /** AA3x — Gas Allowance Pool's `validatePaymasterUserOp` rejection. */
32
+ var PaymasterValidationError = class extends UserOperationRevertError {};
33
+ /** AA9x — EntryPoint bundle-frame invariants. Rarely reached by app code. */
34
+ var BundleFrameError = class extends UserOperationRevertError {};
35
+ //#endregion
36
+ //#region src/errors/mapAaCode.ts
37
+ const AA_CODE = /AA\d\d/;
38
+ const KNOWN_CODES = {
39
+ AA10: AccountFactoryError,
40
+ AA13: AccountFactoryError,
41
+ AA14: AccountFactoryError,
42
+ AA15: AccountFactoryError,
43
+ AA21: AccountValidationError,
44
+ AA22: AccountValidationError,
45
+ AA23: AccountValidationError,
46
+ AA24: AccountValidationError,
47
+ AA25: AccountValidationError,
48
+ AA26: AccountValidationError,
49
+ AA31: PaymasterValidationError,
50
+ AA32: PaymasterValidationError,
51
+ AA33: PaymasterValidationError,
52
+ AA34: PaymasterValidationError,
53
+ AA36: PaymasterValidationError,
54
+ AA90: BundleFrameError,
55
+ AA91: BundleFrameError,
56
+ AA92: BundleFrameError,
57
+ AA93: BundleFrameError,
58
+ AA94: BundleFrameError,
59
+ AA95: BundleFrameError,
60
+ AA96: BundleFrameError
61
+ };
62
+ /**
63
+ * Classify a bundler revert message by its AA code. Returns both the
64
+ * matched code string and the concrete subclass constructor, or `null`
65
+ * when the message has no AA code at all. Callers instantiate `ctor`
66
+ * with their own message/context and set `err.code = code`.
67
+ */
68
+ function mapAaCode(message) {
69
+ const match = AA_CODE.exec(message);
70
+ if (!match) return null;
71
+ const code = match[0];
72
+ return {
73
+ code,
74
+ ctor: KNOWN_CODES[code] ?? UserOperationRevertError
75
+ };
76
+ }
77
+ //#endregion
78
+ //#region src/errors/classifyBundlerError.ts
79
+ /** Walk the `cause` chain and return the first numeric `code` found. */
80
+ function findRpcCode(err) {
81
+ let cur = err;
82
+ while (cur !== null && cur !== void 0) {
83
+ const e = cur;
84
+ if (typeof e.code === "number") return e.code;
85
+ cur = e.cause;
86
+ }
87
+ return null;
88
+ }
89
+ /** Walk the `cause` chain for a network-level failure indicator. */
90
+ function isNetworkFailure(err) {
91
+ let cur = err;
92
+ while (cur !== null && cur !== void 0) {
93
+ const e = cur;
94
+ if (e.name === "HttpRequestError") return true;
95
+ if (e.name === "TimeoutError") return true;
96
+ if (typeof e.code === "string") {
97
+ const c = e.code;
98
+ if (c === "ECONNREFUSED" || c === "UND_ERR_CONNECT_TIMEOUT" || c === "ECONNRESET") return true;
99
+ }
100
+ cur = e.cause;
101
+ }
102
+ return false;
103
+ }
104
+ function extractMessage(err) {
105
+ if (err instanceof Error) return err.message;
106
+ return String(err);
107
+ }
108
+ /**
109
+ * Bucket-level, end-user-displayable copy for each AA code. The technical
110
+ * revert reason is preserved in `err.cause.message` and the specific code
111
+ * is on `err.code`.
112
+ */
113
+ function userMessageForAaCode(aaCode) {
114
+ if (aaCode.startsWith("AA1")) return "We couldn't set up your smart account. Please try again.";
115
+ if (aaCode.startsWith("AA2")) return "Your transaction couldn't be authorized. Please try again.";
116
+ if (aaCode.startsWith("AA3")) return "Gas sponsorship was declined for this transaction. Please try again later.";
117
+ if (aaCode.startsWith("AA9")) return "Something went wrong submitting your transaction. Please try again.";
118
+ return "Your transaction couldn't be completed. Please try again.";
119
+ }
120
+ const USER_MESSAGE_INVALID_PARAMS = "Your transaction was rejected before submission. Please try again.";
121
+ const USER_MESSAGE_REJECTED = "Your transaction was rejected by the network. Please try again.";
122
+ const USER_MESSAGE_UNREACHABLE = "Couldn't reach the network. Please check your connection and try again.";
123
+ const USER_MESSAGE_GENERIC_RPC = "Something went wrong submitting your transaction. Please try again.";
124
+ /**
125
+ * Classify a raw error from the bundler transport into a typed SDK error.
126
+ *
127
+ * - JSON-RPC `-32602` (invalid params) → `InvalidUserOperationError`
128
+ * - JSON-RPC `-32500` (op rejected) → `UserOperationRejectedError`
129
+ * - AA-code revert messages → corresponding `UserOperationRevertError` subclass
130
+ * - Network failures (fetch error, timeout) → `BundlerUnreachableError`
131
+ * - Anything else → `BundlerRpcError` base
132
+ *
133
+ * Returned errors carry an end-user-displayable `.message`; the original
134
+ * technical message stays on `.cause.message`, and the typed `code` /
135
+ * AA code is on `.code`.
136
+ */
137
+ function classifyBundlerError(err, userOp) {
138
+ const technicalMessage = extractMessage(err);
139
+ const code = findRpcCode(err);
140
+ const codeStr = code !== null ? String(code) : "UNKNOWN";
141
+ const userOpCtx = userOp !== void 0 ? { userOp } : {};
142
+ const aa = mapAaCode(technicalMessage);
143
+ if (aa) return new aa.ctor(userMessageForAaCode(aa.code), {
144
+ code: aa.code,
145
+ detail: technicalMessage,
146
+ cause: err,
147
+ ...userOpCtx
148
+ });
149
+ const rpcBase = {
150
+ code: codeStr,
151
+ detail: technicalMessage,
152
+ cause: err,
153
+ ...userOpCtx
154
+ };
155
+ if (code === -32602) return new InvalidUserOperationError(USER_MESSAGE_INVALID_PARAMS, rpcBase);
156
+ if (code === -32500) return new UserOperationRejectedError(USER_MESSAGE_REJECTED, rpcBase);
157
+ if (isNetworkFailure(err)) return new BundlerUnreachableError(USER_MESSAGE_UNREACHABLE, rpcBase);
158
+ return new BundlerRpcError(USER_MESSAGE_GENERIC_RPC, rpcBase);
159
+ }
160
+ //#endregion
161
+ export { BundleFrameError as a, BundlerRpcError as c, UserOperationRejectedError as d, AccountValidationError as i, BundlerUnreachableError as l, mapAaCode as n, PaymasterValidationError as o, AccountFactoryError as r, UserOperationRevertError as s, classifyBundlerError as t, InvalidUserOperationError as u };