import { n as __exportAll } from "./chunk-BEJ448es.mjs";
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { execFileSync, execSync } from "node:child_process";
//#region extensions/crypto/src/services/builder-code.ts
/**
* Pre-computed ERC-8021 data suffix for our builder code.
*
* Format: [1 byte: code length] [N bytes: UTF-8 code] [0x00] [8021 repeated 8 times]
*
* Encoding breakdown for 'bc_z92vaimh':
*   0b                         = length 11
*   62635f7a39327661696d68     = 'bc_z92vaimh' UTF-8
*   00                         = separator
*   80218021802180218021802180218021 = ERC-8021 magic (8 × 0x8021)
*/
const DATA_SUFFIX = "0x0b62635f7a39327661696d680080218021802180218021802180218021";
/** Base chain IDs where the suffix should be applied. */
const BASE_CHAIN_IDS = new Set([8453, 84532]);
/**
* Append the ERC-8021 builder code suffix to transaction data.
*
* - If data is empty/undefined (native ETH transfer), the suffix becomes the data.
* - If data exists (contract call), the suffix is appended to the end.
* - Only applies to Base chain transactions.
*
* @param data - Existing transaction data (hex string or undefined)
* @param chainId - The chain this transaction targets
* @returns The data with suffix appended, or original data if not Base
*/
function appendBuilderCode(data, chainId) {
	if (!chainId || !BASE_CHAIN_IDS.has(chainId)) return data;
	const suffixHex = DATA_SUFFIX.slice(2);
	if (!data || data === "0x") return DATA_SUFFIX;
	return "0x" + (data.startsWith("0x") ? data.slice(2) : data) + suffixHex;
}
/**
* Wrap a viem wallet client to automatically append the builder code suffix
* to all sendTransaction calls on Base.
*
* This is the main integration point. Applied once at wallet client creation
* in walletconnect-service.ts.
*
* The wrapper intercepts the `request` method on the transport, catches
* `eth_sendTransaction` calls, and appends the suffix to the data field.
*/
function wrapWithBuilderCode(walletClient, chainId) {
	if (!walletClient) return walletClient;
	const effectiveChainId = chainId ?? walletClient.chain?.id;
	if (!effectiveChainId || !BASE_CHAIN_IDS.has(effectiveChainId)) return walletClient;
	const originalSendTransaction = walletClient.sendTransaction?.bind(walletClient);
	walletClient.writeContract?.bind(walletClient);
	if (originalSendTransaction) walletClient.sendTransaction = async (args) => {
		return originalSendTransaction({
			...args,
			data: appendBuilderCode(args.data, effectiveChainId)
		});
	};
	return walletClient;
}
//#endregion
//#region extensions/crypto/src/services/keychain-wallet.ts
/**
* Keychain Wallet — local key generation with encrypted Keychain storage.
*
* Extends `private_key` mode with:
* - BIP-39 mnemonic generation via viem/accounts
* - scrypt + AES-256-GCM envelope encryption
* - macOS Keychain storage (via `security` CLI)
* - Encrypted file fallback for Linux/Docker
*
* The runtime behavior is identical to raw `private_key` mode — once we have
* a viem Account object, the same wallet client code path is used. The only
* difference is how the key is acquired (generated vs env var) and stored
* (Keychain vs plaintext env).
*
* No new dependencies. Uses:
* - viem/accounts: generateMnemonic, mnemonicToAccount
* - @scure/bip39/wordlists/english: BIP-39 English wordlist (transitive via viem)
* - @noble/hashes/scrypt: key derivation
* - node:crypto: AES-256-GCM encryption
*/
const KEYCHAIN_ACCOUNT = "eth";
const KEYCHAIN_SERVICE = "clawncher_mnemonic";
const FALLBACK_DIR = join(process.env.HOME ?? "/root", ".openclawnch");
const FALLBACK_PATH = join(FALLBACK_DIR, "wallet.enc");
const BACKUP_FILENAME = "wallet-backup.enc";
/** scrypt parameters: N=2^17, r=8, p=1. ~128MB memory, ~0.5s on modern hardware. */
const SCRYPT_N = 2 ** 17;
const SCRYPT_R = 8;
const SCRYPT_P = 1;
const SCRYPT_DKLEN = 32;
function isMacOS() {
	return process.platform === "darwin";
}
/**
* Derive an AES-256 key from a password using scrypt.
* Uses @noble/hashes for the scrypt implementation (already in dep tree via viem).
*/
async function deriveKey(password, salt) {
	const { scryptAsync } = await import("./scrypt-DrVEfRsA.mjs");
	const derived = await scryptAsync(Buffer.from(password, "utf-8"), salt, {
		N: SCRYPT_N,
		r: SCRYPT_R,
		p: SCRYPT_P,
		dkLen: SCRYPT_DKLEN
	});
	return Buffer.from(derived);
}
/**
* Encrypt a plaintext string with AES-256-GCM using a password-derived key.
*/
async function encrypt(plaintext, password) {
	const salt = randomBytes(32);
	const nonce = randomBytes(12);
	const cipher = createCipheriv("aes-256-gcm", await deriveKey(password, salt), nonce);
	const encrypted = Buffer.concat([cipher.update(plaintext, "utf-8"), cipher.final()]);
	const tag = cipher.getAuthTag();
	return {
		salt: salt.toString("hex"),
		nonce: nonce.toString("hex"),
		ciphertext: encrypted.toString("hex"),
		tag: tag.toString("hex"),
		version: 1
	};
}
/**
* Decrypt an AES-256-GCM encrypted payload using a password-derived key.
* Throws on wrong password (GCM auth tag mismatch).
*/
async function decrypt(payload, password) {
	if (payload.version !== 1) throw new Error(`Unsupported encryption version: ${payload.version}`);
	const salt = Buffer.from(payload.salt, "hex");
	const nonce = Buffer.from(payload.nonce, "hex");
	const ciphertext = Buffer.from(payload.ciphertext, "hex");
	const tag = Buffer.from(payload.tag, "hex");
	const decipher = createDecipheriv("aes-256-gcm", await deriveKey(password, salt), nonce);
	decipher.setAuthTag(tag);
	try {
		return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf-8");
	} catch {
		throw new Error("Decryption failed — wrong password or corrupted data.");
	}
}
/**
* Store an encrypted payload in macOS Keychain.
*/
function keychainStore(payload) {
	const json = JSON.stringify(payload);
	try {
		execFileSync("security", [
			"delete-generic-password",
			"-a",
			KEYCHAIN_ACCOUNT,
			"-s",
			KEYCHAIN_SERVICE,
			"login.keychain-db"
		], { stdio: "pipe" });
	} catch {}
	execFileSync("security", [
		"add-generic-password",
		"-a",
		KEYCHAIN_ACCOUNT,
		"-s",
		KEYCHAIN_SERVICE,
		"-w",
		json,
		"login.keychain-db"
	], { stdio: "pipe" });
}
/**
* Load an encrypted payload from macOS Keychain.
* Returns null if not found.
*/
function keychainLoad() {
	try {
		const raw = execFileSync("security", [
			"find-generic-password",
			"-a",
			KEYCHAIN_ACCOUNT,
			"-s",
			KEYCHAIN_SERVICE,
			"-w",
			"login.keychain-db"
		], {
			encoding: "utf-8",
			stdio: [
				"pipe",
				"pipe",
				"pipe"
			]
		}).trim();
		return JSON.parse(raw);
	} catch {
		return null;
	}
}
/**
* Check if an encrypted wallet exists in macOS Keychain.
*/
function keychainExists() {
	try {
		execFileSync("security", [
			"find-generic-password",
			"-a",
			KEYCHAIN_ACCOUNT,
			"-s",
			KEYCHAIN_SERVICE,
			"login.keychain-db"
		], { stdio: "pipe" });
		return true;
	} catch {
		return false;
	}
}
/**
* Delete the encrypted wallet from macOS Keychain.
*/
function keychainDelete() {
	try {
		execSync(`security delete-generic-password -a "${KEYCHAIN_ACCOUNT}" -s "${KEYCHAIN_SERVICE}" login.keychain-db`, { stdio: "pipe" });
		return true;
	} catch {
		return false;
	}
}
function ensureFallbackDir() {
	if (!existsSync(FALLBACK_DIR)) mkdirSync(FALLBACK_DIR, {
		recursive: true,
		mode: 448
	});
}
function fileStore(payload) {
	ensureFallbackDir();
	writeFileSync(FALLBACK_PATH, JSON.stringify(payload), { mode: 384 });
}
function fileLoad() {
	try {
		const raw = readFileSync(FALLBACK_PATH, "utf-8");
		return JSON.parse(raw);
	} catch {
		return null;
	}
}
function fileExists() {
	return existsSync(FALLBACK_PATH);
}
function fileDelete() {
	try {
		unlinkSync(FALLBACK_PATH);
		return true;
	} catch {
		return false;
	}
}
function storePayload(payload) {
	if (isMacOS()) keychainStore(payload);
	else fileStore(payload);
}
function loadPayload() {
	if (isMacOS()) return keychainLoad();
	return fileLoad();
}
/**
* Generate a new BIP-39 wallet. Returns the mnemonic and derived address.
* Does NOT store anything — call encryptAndStore() after user confirms backup.
*/
async function generateWallet() {
	const { generateMnemonic, mnemonicToAccount } = await import("./accounts-CbW6PDSZ.mjs");
	const { wordlist } = await import("./english-BzSTr2yb.mjs");
	const mnemonic = generateMnemonic(wordlist);
	return {
		mnemonic,
		address: mnemonicToAccount(mnemonic).address
	};
}
/**
* Encrypt a mnemonic with user password and store in Keychain (macOS) or
* encrypted file (Linux/Docker).
*/
async function encryptAndStore(mnemonic, password) {
	const words = mnemonic.trim().split(/\s+/);
	if (words.length !== 12 && words.length !== 24) throw new Error(`Invalid mnemonic: expected 12 or 24 words, got ${words.length}`);
	if (!password || password.length < 8) throw new Error("Password must be at least 8 characters.");
	storePayload(await encrypt(mnemonic, password));
}
/**
* Load and decrypt the stored mnemonic, then derive a viem Account.
* Returns the Account object ready for privateKeyToAccount-style usage.
*/
async function loadAndDecrypt(password) {
	const payload = loadPayload();
	if (!payload) throw new Error("No encrypted wallet found in storage.");
	const mnemonic = await decrypt(payload, password);
	const { mnemonicToAccount } = await import("./accounts-CbW6PDSZ.mjs");
	const account = mnemonicToAccount(mnemonic);
	return {
		account,
		mnemonic,
		address: account.address
	};
}
/**
* Check if an encrypted wallet exists in storage.
*/
function hasKeychainWallet() {
	if (isMacOS()) return keychainExists();
	return fileExists();
}
/**
* Delete the encrypted wallet from storage.
*/
function deleteKeychainWallet() {
	if (isMacOS()) return keychainDelete();
	return fileDelete();
}
/**
* Export encrypted backup file to a specified path (or default backup location).
* Returns the path where the backup was written.
*/
function exportBackupFile(outputDir) {
	const payload = loadPayload();
	if (!payload) throw new Error("No encrypted wallet found in storage.");
	const dir = outputDir ?? FALLBACK_DIR;
	if (!existsSync(dir)) mkdirSync(dir, {
		recursive: true,
		mode: 448
	});
	const backupPath = join(dir, BACKUP_FILENAME);
	writeFileSync(backupPath, JSON.stringify(payload, null, 2), { mode: 384 });
	return backupPath;
}
/**
* Generate 3 random word indices for mnemonic confirmation.
* Returns array of {index, word} pairs the user must confirm.
*/
function getConfirmationWords(mnemonic, count = 3) {
	const words = mnemonic.trim().split(/\s+/);
	const indices = /* @__PURE__ */ new Set();
	while (indices.size < count) {
		const idx = Math.floor(Math.random() * words.length);
		indices.add(idx);
	}
	return Array.from(indices).sort((a, b) => a - b).map((idx) => ({
		index: idx + 1,
		word: words[idx]
	}));
}
/**
* Validate that the user's confirmation words match the mnemonic.
*/
function validateConfirmation(mnemonic, confirmations) {
	const words = mnemonic.trim().split(/\s+/);
	return confirmations.every(({ index, word }) => words[index - 1]?.toLowerCase() === word.toLowerCase());
}
/**
* Get the storage backend description (for display to user).
*/
function getStorageInfo() {
	if (isMacOS()) return { backend: "keychain" };
	return {
		backend: "file",
		path: FALLBACK_PATH
	};
}
//#endregion
//#region extensions/crypto/src/services/walletconnect-service.ts
var walletconnect_service_exports = /* @__PURE__ */ __exportAll({
	addPolicy: () => addPolicy,
	clearAccountTypeCache: () => clearAccountTypeCache,
	clearPolicies: () => clearPolicies,
	detectAccountType: () => detectAccountType,
	disconnectWallet: () => disconnectWallet,
	getMevWalletClient: () => getMevWalletClient,
	getPublicClient: () => getPublicClient,
	getTransactionHistory: () => getTransactionHistory,
	getWCSigner: () => getWCSigner,
	getWalletClient: () => getWalletClient,
	getWalletState: () => getWalletState,
	initWalletService: () => initWalletService,
	isBankrMode: () => isBankrMode,
	requirePublicClient: () => requirePublicClient,
	requireWalletClient: () => requireWalletClient,
	waitForWalletSession: () => waitForWalletSession
});
/** viem WalletClient — untyped to avoid cross-package viem version conflicts */
let _walletClient = null;
/** viem PublicClient — untyped for the same reason */
let _publicClient = null;
let _wcSigner = null;
let _connectedAddress = null;
let _mode = "none";
let _transactionHistory = [];
let _bankrEvmAddress = null;
let _bankrSolAddress = null;
let _bankrClub = false;
let _accountType;
let _hasCode;
let _delegationDesignation;
/**
* Initialize the wallet service. Called at gateway startup.
* 
* Priority:
* 1. Private key env var (headless/testing)
* 2. WalletConnect (production)
* 3. Bankr API key (custodial wallet)
*/
let _initPromise = null;
async function initWalletService(config) {
	if (_initPromise) return _initPromise;
	_initPromise = _doInitWalletService(config);
	try {
		return await _initPromise;
	} finally {
		_initPromise = null;
	}
}
async function _doInitWalletService(config) {
	const { createPublicClient, http } = await import("./_esm-BKtdEVdT.mjs").then((n) => n.t);
	const { base, baseSepolia } = await import("./chains-Bx4KIVmV.mjs").then((n) => n.t);
	const chain = config.network === "sepolia" ? baseSepolia : base;
	const rpcUrl = config.rpcUrl || void 0;
	_publicClient = createPublicClient({
		chain,
		transport: http(rpcUrl)
	});
	if (config.privateKey) {
		const { createWalletClient } = await import("./_esm-BKtdEVdT.mjs").then((n) => n.t);
		const { privateKeyToAccount } = await import("./accounts-CbW6PDSZ.mjs");
		const account = privateKeyToAccount(config.privateKey);
		_walletClient = createWalletClient({
			account,
			chain,
			transport: http(rpcUrl)
		});
		_walletClient = wrapWithBuilderCode(_walletClient, chain.id);
		_connectedAddress = account.address;
		_mode = "private_key";
		return {
			mode: "private_key",
			address: account.address
		};
	}
	if (!config.privateKey && hasKeychainWallet()) {
		const walletPassword = process.env.CLAWNCHER_WALLET_PASSWORD;
		if (walletPassword) try {
			const { account: keychainAccount } = await loadAndDecrypt(walletPassword);
			const { createWalletClient } = await import("./_esm-BKtdEVdT.mjs").then((n) => n.t);
			_walletClient = createWalletClient({
				account: keychainAccount,
				chain,
				transport: http(rpcUrl)
			});
			_walletClient = wrapWithBuilderCode(_walletClient, chain.id);
			_connectedAddress = keychainAccount.address;
			_mode = "private_key";
			return {
				mode: "private_key",
				address: keychainAccount.address
			};
		} catch (err) {
			console.warn(`[wallet] Keychain wallet decrypt failed: ${err instanceof Error ? err.message : String(err)}`);
		}
		else console.info("[wallet] Keychain wallet found but CLAWNCHER_WALLET_PASSWORD not set — skipping auto-unlock. Set CLAWNCHER_WALLET_PASSWORD env var for headless mode, or use onboarding to unlock interactively.");
	}
	if (config.walletConnectProjectId) {
		const { WalletConnectSigner } = await import("./dist-DfRiIl1v.mjs").then((n) => n.t);
		const sessionPath = config.sessionPath || `${process.env.HOME ?? ""}/.openclawnch/wc-session.json`;
		_wcSigner = new WalletConnectSigner({
			projectId: config.walletConnectProjectId,
			chain,
			sessionPath,
			policies: config.policies ?? [],
			metadata: {
				name: "OpenClawnch",
				description: "OpenClaw for crypto — AI assistant with DeFi capabilities",
				url: "https://clawn.ch",
				icons: ["https://clawn.ch/icon.png"]
			},
			requestTimeout: 18e4,
			onSessionChange: (state) => {
				if (state.status === "connected") _connectedAddress = state.address;
				else if (state.status === "disconnected" || state.status === "expired") {
					_connectedAddress = null;
					_walletClient = null;
				}
				config.onSessionChange?.(state);
			},
			onTransactionQueued: (tx) => {
				_transactionHistory.push({
					id: tx.id,
					status: "pending",
					summary: tx.context?.summary ?? "Transaction submitted",
					timestamp: tx.queuedAt,
					to: tx.transaction.to,
					value: tx.transaction.value?.toString()
				});
				config.onTransactionQueued?.(tx);
			},
			onTransactionApproved: (tx, hash) => {
				const record = _transactionHistory.find((r) => r.id === tx.id);
				if (record) {
					record.status = tx.policyLabel ? "auto_approved" : "approved";
					record.hash = hash;
					record.policyLabel = tx.policyLabel;
				}
				config.onTransactionApproved?.(tx, hash);
			},
			onTransactionRejected: (tx, reason) => {
				const record = _transactionHistory.find((r) => r.id === tx.id);
				if (record) record.status = "rejected";
				config.onTransactionRejected?.(tx, reason);
			}
		});
		const { uri, restored } = await _wcSigner.connect();
		if (restored) {
			_walletClient = await _wcSigner.toWalletClient(_publicClient);
			_walletClient = wrapWithBuilderCode(_walletClient, chain.id);
			_connectedAddress = _wcSigner.address;
			_mode = "walletconnect";
			return {
				mode: "walletconnect",
				address: _connectedAddress ?? void 0
			};
		}
		if (uri) {
			_mode = "walletconnect";
			return {
				mode: "walletconnect",
				pairingUri: uri
			};
		}
	}
	if (config.bankrApiKey) try {
		const { getBankrUserInfo } = await import("./bankr-api-ClsXaFmq.mjs").then((n) => n.t);
		if (!process.env.BANKR_API_KEY) process.env.BANKR_API_KEY = config.bankrApiKey;
		const userInfo = await getBankrUserInfo();
		const { isBankrClubActive } = await import("./bankr-types-E81UZ9-c.mjs").then((n) => n.o);
		const evmWallet = userInfo.wallets.find((w) => w.chain === "evm");
		const solWallet = userInfo.wallets.find((w) => w.chain === "solana");
		_bankrEvmAddress = evmWallet?.address ?? null;
		_bankrSolAddress = solWallet?.address ?? null;
		_bankrClub = isBankrClubActive(userInfo);
		_connectedAddress = _bankrEvmAddress ?? null;
		_mode = "bankr";
		return {
			mode: "bankr",
			address: _connectedAddress ?? void 0,
			solAddress: _bankrSolAddress ?? void 0
		};
	} catch (err) {
		console.warn(`[wallet] Bankr init failed: ${err instanceof Error ? err.message : String(err)}`);
	}
	_mode = "none";
	return { mode: "none" };
}
/**
* Wait for WalletConnect session to be established (after wallet approval).
*/
async function waitForWalletSession(timeoutMs = 3e5) {
	if (!_wcSigner) throw new Error("WalletConnect not initialized. Set WALLETCONNECT_PROJECT_ID.");
	const result = await _wcSigner.waitForSession(timeoutMs);
	_walletClient = await _wcSigner.toWalletClient(_publicClient);
	_walletClient = wrapWithBuilderCode(_walletClient, _publicClient?.chain?.id);
	_connectedAddress = result.address;
	return result;
}
function getWalletClient() {
	return _walletClient;
}
function getPublicClient() {
	return _publicClient;
}
function getWCSigner() {
	return _wcSigner;
}
function getWalletState() {
	return {
		connected: _connectedAddress !== null,
		address: _connectedAddress,
		chainId: _mode === "bankr" ? 8453 : _publicClient ? _publicClient.chain?.id ?? null : null,
		mode: _mode,
		policies: _wcSigner?.getPolicies() ?? [],
		wcState: _wcSigner?.getState() ?? null,
		bankrEvmAddress: _bankrEvmAddress ?? void 0,
		bankrSolAddress: _bankrSolAddress ?? void 0,
		bankrClub: _bankrClub || void 0,
		accountType: _accountType,
		hasCode: _hasCode,
		delegationDesignation: _delegationDesignation
	};
}
/**
* Check if the wallet is in Bankr custodial mode.
*/
function isBankrMode() {
	return _mode === "bankr";
}
function getTransactionHistory() {
	return [..._transactionHistory];
}
function requireWalletClient() {
	if (!_walletClient) throw new Error("No wallet connected. Use the clawnchconnect tool with action \"connect\" first, or set CLAWNCHER_PRIVATE_KEY for headless mode.");
	return _walletClient;
}
function requirePublicClient() {
	if (!_publicClient) throw new Error("Public client not initialized. The wallet service must be started first.");
	return _publicClient;
}
/**
* Get a wallet client that routes write transactions through MEV-protected RPCs
* (Flashbots Protect, MEV Blocker) when available. Protects against sandwich
* attacks and frontrunning by bypassing the public mempool.
*
* Only effective in private_key mode — WalletConnect transactions are broadcast
* by the phone wallet (out of our control), and Bankr transactions are broadcast
* by the Bankr API.
*
* Falls back to the regular wallet client if:
* - MEV protection is disabled in RpcManager config
* - No MEV RPCs are available for the current chain
* - Mode is not private_key (WC, Bankr)
*/
async function getMevWalletClient() {
	const wallet = requireWalletClient();
	if (_mode !== "private_key") return wallet;
	try {
		const { getRpcManager } = await import("./rpc-provider-BELb8v5m.mjs").then((n) => n.n);
		const rpcManager = getRpcManager();
		const chainId = _publicClient?.chain?.id ?? 8453;
		if (!rpcManager.isMevProtectionEnabled()) return wallet;
		const mevTransport = rpcManager.getMevTransport(chainId);
		if (!mevTransport) return wallet;
		const { createWalletClient } = await import("./_esm-BKtdEVdT.mjs").then((n) => n.t);
		return wrapWithBuilderCode(createWalletClient({
			account: wallet.account,
			chain: _publicClient?.chain,
			transport: mevTransport
		}), chainId);
	} catch (err) {
		console.warn("[wallet] MEV protection unavailable, using standard RPC:", err instanceof Error ? err.message : String(err));
		return wallet;
	}
}
/**
* EIP-7702 delegation designation prefix.
* An EIP-7702 delegated EOA has code: 0xef0100 + 20-byte implementation address.
* Total bytecode length = 23 bytes = 46 hex chars + '0x' prefix = 48 chars.
*/
const EIP7702_PREFIX = "0xef0100";
const EIP7702_CODE_LENGTH = 48;
/**
* Detect the account type of the connected wallet via eth_getCode.
*
* - EOA: getCode returns '0x' (no code)
* - Smart Account: getCode returns arbitrary bytecode (not EIP-7702 prefix)
* - EIP-7702: getCode returns 0xef0100 + 20-byte implementation address
*
* Results are cached on the wallet state. Call with `force: true` to re-detect.
* Returns null if no wallet is connected or no public client is available.
*/
async function detectAccountType(opts) {
	if (!opts?.force && _accountType !== void 0) return {
		accountType: _accountType,
		hasCode: _hasCode ?? false,
		delegationDesignation: _delegationDesignation
	};
	if (!_connectedAddress || !_publicClient) return null;
	try {
		const codeHex = await _publicClient.getCode({ address: _connectedAddress }) ?? "0x";
		if (codeHex === "0x" || codeHex === "0x0") {
			_accountType = "eoa";
			_hasCode = false;
			_delegationDesignation = void 0;
		} else if (codeHex.toLowerCase().startsWith(EIP7702_PREFIX) && codeHex.length === EIP7702_CODE_LENGTH) {
			_accountType = "eip7702";
			_hasCode = true;
			_delegationDesignation = "0x" + codeHex.slice(8);
		} else {
			_accountType = "smart_account";
			_hasCode = true;
			_delegationDesignation = void 0;
		}
		return {
			accountType: _accountType,
			hasCode: _hasCode,
			delegationDesignation: _delegationDesignation
		};
	} catch {
		return null;
	}
}
/**
* Clear the cached account type detection. Called on disconnect.
*/
function clearAccountTypeCache() {
	_accountType = void 0;
	_hasCode = void 0;
	_delegationDesignation = void 0;
}
async function disconnectWallet() {
	if (_wcSigner) await _wcSigner.disconnect();
	_walletClient = null;
	_connectedAddress = null;
	_bankrEvmAddress = null;
	_bankrSolAddress = null;
	_bankrClub = false;
	_mode = "none";
	clearAccountTypeCache();
}
function addPolicy(policy) {
	_wcSigner?.addPolicy(policy);
}
function clearPolicies() {
	const policies = _wcSigner?.getPolicies() ?? [];
	for (const p of policies) _wcSigner?.removePolicy(p.label);
}
//#endregion
export { hasKeychainWallet as C, getStorageInfo as S, validateConfirmation as T, deleteKeychainWallet as _, getMevWalletClient as a, generateWallet as b, getWCSigner as c, initWalletService as d, isBankrMode as f, walletconnect_service_exports as g, waitForWalletSession as h, disconnectWallet as i, getWalletClient as l, requireWalletClient as m, clearPolicies as n, getPublicClient as o, requirePublicClient as p, detectAccountType as r, getTransactionHistory as s, addPolicy as t, getWalletState as u, encryptAndStore as v, loadAndDecrypt as w, getConfirmationWords as x, exportBackupFile as y };

//# sourceMappingURL=walletconnect-service-nx9kD9tm.mjs.map