@layr-labs/ecloud-sdk 0.2.1-dev → 0.3.0-dev

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/browser.ts","../src/client/common/config/environment.ts","../src/client/common/utils/validation.ts","../src/client/common/utils/helpers.ts","../src/client/common/constants.ts","../src/client/common/utils/billing.ts","../src/client/common/auth/generate.ts","../src/client/common/utils/userapi.ts","../src/client/common/utils/auth.ts","../src/client/common/contract/eip7702.ts","../src/client/common/abis/ERC7702Delegator.json","../src/client/common/contract/caller.ts","../src/client/common/abis/AppController.json","../src/client/common/contract/encoders.ts"],"sourcesContent":["/**\n * Browser-safe SDK entry point\n *\n * This module exports only code that can run in browser environments.\n * It excludes Node.js-only dependencies like:\n * - dockerode (Docker API)\n * - @napi-rs/keyring (OS keychain)\n * - fs operations (file system)\n * - @inquirer/prompts (CLI prompts)\n *\n * Use this entry point in React/Next.js/browser applications:\n * import { ... } from \"@layr-labs/ecloud-sdk/browser\"\n */\n\n// =============================================================================\n// Types (all browser-safe)\n// =============================================================================\nexport * from \"./client/common/types\";\n\n// =============================================================================\n// Environment Configuration (browser-safe)\n// =============================================================================\nexport {\n getEnvironmentConfig,\n getAvailableEnvironments,\n isEnvironmentAvailable,\n getBuildType,\n isMainnet,\n} from \"./client/common/config/environment\";\n\n// =============================================================================\n// Validation Utilities (browser-safe subset only)\n// Note: validateFilePath, validateImagePath, validateDeployParams, validateUpgradeParams\n// are excluded because they use fs/path Node.js modules\n// =============================================================================\nexport {\n // App name\n validateAppName,\n // Image reference\n validateImageReference,\n assertValidImageReference,\n extractAppNameFromImage,\n // Instance type\n validateInstanceTypeSKU,\n // Private key\n validatePrivateKeyFormat,\n assertValidPrivateKey,\n // URL validation\n validateURL,\n validateXURL,\n // Description\n validateDescription,\n // App ID\n validateAppID,\n // Log visibility\n validateLogVisibility,\n type LogVisibility,\n // Sanitization\n sanitizeString,\n sanitizeURL,\n sanitizeXURL,\n // Parameter validation (browser-safe ones only)\n validateCreateAppParams,\n validateLogsParams,\n type CreateAppParams,\n type LogsParams,\n} from \"./client/common/utils/validation\";\n\n// =============================================================================\n// Billing Utilities (browser-safe)\n// =============================================================================\nexport { isSubscriptionActive } from \"./client/common/utils/billing\";\n\n// =============================================================================\n// Key Generation (browser-safe - uses viem)\n// =============================================================================\nexport { generateNewPrivateKey, type GeneratedKey } from \"./client/common/auth/generate\";\n\n// =============================================================================\n// API Clients (browser-safe - use axios/fetch)\n// =============================================================================\nexport {\n UserApiClient,\n type AppInfo,\n type AppProfileInfo,\n type AppMetrics,\n type AppInfoResponse,\n} from \"./client/common/utils/userapi\";\n\n// =============================================================================\n// Contract Read Operations (browser-safe)\n// =============================================================================\nexport {\n // Read operations\n getAllAppsByDeveloper,\n getAppsByCreator,\n getAppsByDeveloper,\n getActiveAppCount,\n getMaxActiveAppsPerUser,\n // Gas estimation\n estimateTransactionGas,\n formatETH,\n // Types\n type GasEstimate,\n type EstimateGasOptions,\n type AppConfig,\n} from \"./client/common/contract/caller\";\n\n// =============================================================================\n// Batch Gas Estimation (browser-safe)\n// =============================================================================\nexport { estimateBatchGas, type EstimateBatchGasOptions } from \"./client/common/contract/eip7702\";\n\n// =============================================================================\n// App Action Encoders (browser-safe - pure viem encoding)\n// =============================================================================\nexport {\n encodeStartAppData,\n encodeStopAppData,\n encodeTerminateAppData,\n} from \"./client/common/contract/encoders\";\n\n// =============================================================================\n// Re-export common types\n// =============================================================================\nexport type Environment = \"sepolia\" | \"sepolia-dev\" | \"mainnet-alpha\";\n","/**\n * Environment configuration for different networks\n */\n\nimport { BillingEnvironmentConfig, EnvironmentConfig } from \"../types\";\n\n// Chain IDs\nexport const SEPOLIA_CHAIN_ID = 11155111;\nexport const MAINNET_CHAIN_ID = 1;\n\n// Common addresses across all chains\nexport const CommonAddresses: Record<string, string> = {\n ERC7702Delegator: \"0x63c0c19a282a1b52b07dd5a65b58948a07dae32b\",\n};\n\n// Addresses specific to each chain\nexport const ChainAddresses: Record<number, Record<string, string>> = {\n [MAINNET_CHAIN_ID]: {\n PermissionController: \"0x25E5F8B1E7aDf44518d35D5B2271f114e081f0E5\",\n },\n [SEPOLIA_CHAIN_ID]: {\n PermissionController: \"0x44632dfBdCb6D3E21EF613B0ca8A6A0c618F5a37\",\n },\n};\n\n// Billing environment configurations (separate from chain environments)\nconst BILLING_ENVIRONMENTS: Record<\"dev\" | \"prod\", BillingEnvironmentConfig> = {\n dev: {\n billingApiServerURL: \"https://billingapi-dev.eigencloud.xyz\",\n },\n prod: {\n billingApiServerURL: \"https://billingapi.eigencloud.xyz\",\n },\n};\n\n// Chain environment configurations\nconst ENVIRONMENTS: Record<string, Omit<EnvironmentConfig, \"chainID\">> = {\n \"sepolia-dev\": {\n name: \"sepolia\",\n build: \"dev\",\n appControllerAddress: \"0xa86DC1C47cb2518327fB4f9A1627F51966c83B92\",\n permissionControllerAddress: ChainAddresses[SEPOLIA_CHAIN_ID].PermissionController,\n erc7702DelegatorAddress: CommonAddresses.ERC7702Delegator,\n kmsServerURL: \"http://10.128.0.57:8080\",\n userApiServerURL: \"https://userapi-compute-sepolia-dev.eigencloud.xyz\",\n defaultRPCURL: \"https://ethereum-sepolia-rpc.publicnode.com\",\n },\n sepolia: {\n name: \"sepolia\",\n build: \"prod\",\n appControllerAddress: \"0x0dd810a6ffba6a9820a10d97b659f07d8d23d4E2\",\n permissionControllerAddress: ChainAddresses[SEPOLIA_CHAIN_ID].PermissionController,\n erc7702DelegatorAddress: CommonAddresses.ERC7702Delegator,\n kmsServerURL: \"http://10.128.15.203:8080\",\n userApiServerURL: \"https://userapi-compute-sepolia-prod.eigencloud.xyz\",\n defaultRPCURL: \"https://ethereum-sepolia-rpc.publicnode.com\",\n },\n \"mainnet-alpha\": {\n name: \"mainnet-alpha\",\n build: \"prod\",\n appControllerAddress: \"0xc38d35Fc995e75342A21CBd6D770305b142Fbe67\",\n permissionControllerAddress: ChainAddresses[MAINNET_CHAIN_ID].PermissionController,\n erc7702DelegatorAddress: CommonAddresses.ERC7702Delegator,\n kmsServerURL: \"http://10.128.0.2:8080\",\n userApiServerURL: \"https://userapi-compute.eigencloud.xyz\",\n defaultRPCURL: \"https://ethereum-rpc.publicnode.com\",\n },\n};\n\nconst CHAIN_ID_TO_ENVIRONMENT: Record<string, string> = {\n [SEPOLIA_CHAIN_ID.toString()]: \"sepolia\",\n [MAINNET_CHAIN_ID.toString()]: \"mainnet-alpha\",\n};\n\n/**\n * Get environment configuration\n */\nexport function getEnvironmentConfig(environment: string, chainID?: bigint): EnvironmentConfig {\n const env = ENVIRONMENTS[environment];\n if (!env) {\n throw new Error(`Unknown environment: ${environment}`);\n }\n\n // Check if environment is available in current build\n if (!isEnvironmentAvailable(environment)) {\n throw new Error(\n `Environment ${environment} is not available in this build type. ` +\n `Available environments: ${getAvailableEnvironments().join(\", \")}`,\n );\n }\n\n // If chainID provided, validate it matches\n if (chainID) {\n const expectedEnv = CHAIN_ID_TO_ENVIRONMENT[chainID.toString()];\n if (expectedEnv && expectedEnv !== environment) {\n throw new Error(`Environment ${environment} does not match chain ID ${chainID}`);\n }\n }\n\n // Determine chain ID from environment if not provided\n // Both \"sepolia\" and \"sepolia-dev\" use Sepolia chain ID\n const resolvedChainID =\n chainID ||\n (environment === \"sepolia\" || environment === \"sepolia-dev\"\n ? SEPOLIA_CHAIN_ID\n : MAINNET_CHAIN_ID);\n\n return {\n ...env,\n chainID: BigInt(resolvedChainID),\n };\n}\n\n/**\n * Get billing environment configuration\n * @param build - The build type (\"dev\" or \"prod\")\n */\nexport function getBillingEnvironmentConfig(build: \"dev\" | \"prod\"): {\n billingApiServerURL: string;\n} {\n const config = BILLING_ENVIRONMENTS[build];\n if (!config) {\n throw new Error(`Unknown billing environment: ${build}`);\n }\n return config;\n}\n\n/**\n * Detect environment from chain ID\n */\nexport function detectEnvironmentFromChainID(chainID: bigint): string | undefined {\n return CHAIN_ID_TO_ENVIRONMENT[chainID.toString()];\n}\n\n/**\n * Get build type from environment variable or build-time constant (defaults to 'prod')\n * BUILD_TYPE_BUILD_TIME is replaced at build time by tsup's define option\n */\n// @ts-ignore - BUILD_TYPE_BUILD_TIME is injected at build time by tsup\ndeclare const BUILD_TYPE_BUILD_TIME: string | undefined;\n\nexport function getBuildType(): \"dev\" | \"prod\" {\n // First check build-time constant (set by tsup define)\n // @ts-ignore - BUILD_TYPE_BUILD_TIME is injected at build time\n const buildTimeType =\n typeof BUILD_TYPE_BUILD_TIME !== \"undefined\" ? BUILD_TYPE_BUILD_TIME?.toLowerCase() : undefined;\n\n // Fall back to runtime environment variable\n const runtimeType = process.env.BUILD_TYPE?.toLowerCase();\n\n const buildType = buildTimeType || runtimeType;\n\n if (buildType === \"dev\") {\n return \"dev\";\n }\n return \"prod\";\n}\n\n/**\n * Get available environments based on build type\n * - dev: only \"sepolia-dev\"\n * - prod: \"sepolia\" and \"mainnet-alpha\"\n */\nexport function getAvailableEnvironments(): string[] {\n const buildType = getBuildType();\n\n if (buildType === \"dev\") {\n return [\"sepolia-dev\"];\n }\n\n // prod build\n return [\"sepolia\", \"mainnet-alpha\"];\n}\n\n/**\n * Check if an environment is available in the current build\n */\nexport function isEnvironmentAvailable(environment: string): boolean {\n return getAvailableEnvironments().includes(environment);\n}\n\n/**\n * Check if environment is mainnet (chain ID 1)\n */\nexport function isMainnet(environmentConfig: EnvironmentConfig): boolean {\n return environmentConfig.chainID === BigInt(MAINNET_CHAIN_ID);\n}\n","/**\n * Non-interactive validation utilities for SDK\n *\n * These functions validate parameters without any interactive prompts.\n * They either return the validated value or throw an error.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport { Address, isAddress } from \"viem\";\nimport { stripHexPrefix, addHexPrefix } from \"./helpers\";\n\n// ==================== App Name Validation ====================\n\n/**\n * Validate app name format\n * @throws Error if name is invalid\n */\nexport function validateAppName(name: string): void {\n if (!name) {\n throw new Error(\"App name cannot be empty\");\n }\n if (name.includes(\" \")) {\n throw new Error(\"App name cannot contain spaces\");\n }\n if (name.length > 50) {\n throw new Error(\"App name cannot be longer than 50 characters\");\n }\n}\n\n// ==================== Image Reference Validation ====================\n\n/**\n * Validate Docker image reference format\n * @returns true if valid, error message string if invalid\n */\nexport function validateImageReference(value: string): true | string {\n if (!value) {\n return \"Image reference cannot be empty\";\n }\n // Basic validation - should contain at least one / and optionally :\n if (!value.includes(\"/\")) {\n return \"Image reference must contain at least one /\";\n }\n return true;\n}\n\n/**\n * Validate image reference and throw if invalid\n * @throws Error if image reference is invalid\n */\nexport function assertValidImageReference(value: string): void {\n const result = validateImageReference(value);\n if (result !== true) {\n throw new Error(result);\n }\n}\n\n/**\n * Extract app name from image reference\n */\nexport function extractAppNameFromImage(imageRef: string): string {\n // Remove registry prefix if present\n const parts = imageRef.split(\"/\");\n let imageName = parts.length > 1 ? parts[parts.length - 1] : imageRef;\n\n // Split image and tag\n if (imageName.includes(\":\")) {\n imageName = imageName.split(\":\")[0];\n }\n\n return imageName;\n}\n\n// ==================== File Path Validation ====================\n\n/**\n * Validate that a file path exists\n * @returns true if valid, error message string if invalid\n */\nexport function validateFilePath(value: string): true | string {\n if (!value) {\n return \"File path cannot be empty\";\n }\n if (!fs.existsSync(value)) {\n return \"File does not exist\";\n }\n return true;\n}\n\n/**\n * Validate file path and throw if invalid\n * @throws Error if file path is invalid or doesn't exist\n */\nexport function assertValidFilePath(value: string): void {\n const result = validateFilePath(value);\n if (result !== true) {\n throw new Error(result);\n }\n}\n\n// ==================== Instance Type Validation ====================\n\n/**\n * Validate instance type SKU against available types\n * @returns the validated SKU\n * @throws Error if SKU is not in the available types list\n */\nexport function validateInstanceTypeSKU(\n sku: string,\n availableTypes: Array<{ sku: string }>,\n): string {\n if (!sku) {\n throw new Error(\"Instance type SKU cannot be empty\");\n }\n\n // Check if SKU is valid\n for (const it of availableTypes) {\n if (it.sku === sku) {\n return sku;\n }\n }\n\n // Build helpful error message with valid options\n const validSKUs = availableTypes.map((it) => it.sku).join(\", \");\n throw new Error(`Invalid instance-type value: ${sku} (must be one of: ${validSKUs})`);\n}\n\n// ==================== Private Key Validation ====================\n\n/**\n * Validate private key format\n * Matches Go's common.ValidatePrivateKey() function\n */\nexport function validatePrivateKeyFormat(key: string): boolean {\n // Remove 0x prefix if present\n const keyWithoutPrefix = stripHexPrefix(key);\n\n // Must be 64 hex characters (32 bytes)\n if (!/^[0-9a-fA-F]{64}$/.test(keyWithoutPrefix)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Validate private key and throw if invalid\n * @throws Error if private key format is invalid\n */\nexport function assertValidPrivateKey(key: string): void {\n if (!key) {\n throw new Error(\"Private key is required\");\n }\n if (!validatePrivateKeyFormat(key)) {\n throw new Error(\n \"Invalid private key format (must be 64 hex characters, optionally prefixed with 0x)\",\n );\n }\n}\n\n// ==================== URL Validation ====================\n\n/**\n * Validate URL format\n * @returns undefined if valid, error message string if invalid\n */\nexport function validateURL(rawURL: string): string | undefined {\n if (!rawURL.trim()) {\n return \"URL cannot be empty\";\n }\n\n try {\n const url = new URL(rawURL);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return \"URL scheme must be http or https\";\n }\n } catch {\n return \"Invalid URL format\";\n }\n\n return undefined;\n}\n\n/**\n * Valid X/Twitter hosts\n */\nconst VALID_X_HOSTS = [\"twitter.com\", \"www.twitter.com\", \"x.com\", \"www.x.com\"];\n\n/**\n * Validate X/Twitter URL format\n * @returns undefined if valid, error message string if invalid\n */\nexport function validateXURL(rawURL: string): string | undefined {\n // First validate as URL\n const urlErr = validateURL(rawURL);\n if (urlErr) {\n return urlErr;\n }\n\n try {\n const url = new URL(rawURL);\n const host = url.hostname.toLowerCase();\n\n // Accept twitter.com and x.com domains\n if (!VALID_X_HOSTS.includes(host)) {\n return \"URL must be a valid X/Twitter URL (x.com or twitter.com)\";\n }\n\n // Ensure it has a path (username/profile)\n if (!url.pathname || url.pathname === \"/\") {\n return \"X URL must include a username or profile path\";\n }\n } catch {\n return \"Invalid X URL format\";\n }\n\n return undefined;\n}\n\n// ==================== Description Validation ====================\n\nconst MAX_DESCRIPTION_LENGTH = 1000;\n\n/**\n * Validate description length\n * @returns undefined if valid, error message string if invalid\n */\nexport function validateDescription(description: string): string | undefined {\n if (!description.trim()) {\n return \"Description cannot be empty\";\n }\n\n if (description.length > MAX_DESCRIPTION_LENGTH) {\n return `Description cannot exceed ${MAX_DESCRIPTION_LENGTH} characters`;\n }\n\n return undefined;\n}\n\n// ==================== Image Path Validation ====================\n\nconst MAX_IMAGE_SIZE = 4 * 1024 * 1024; // 4MB\nconst VALID_IMAGE_EXTENSIONS = [\".jpg\", \".jpeg\", \".png\"];\n\n/**\n * Validate image file path\n * @returns undefined if valid, error message string if invalid\n */\nexport function validateImagePath(filePath: string): string | undefined {\n // Strip quotes that may be added by terminal drag-and-drop\n const cleanedPath = filePath.trim().replace(/^[\"']|[\"']$/g, \"\");\n\n if (!cleanedPath) {\n return \"Image path cannot be empty\";\n }\n\n // Check if file exists\n if (!fs.existsSync(cleanedPath)) {\n return `Image file not found: ${cleanedPath}`;\n }\n\n const stats = fs.statSync(cleanedPath);\n if (stats.isDirectory()) {\n return \"Path is a directory, not a file\";\n }\n\n // Check file size\n if (stats.size > MAX_IMAGE_SIZE) {\n const sizeMB = (stats.size / (1024 * 1024)).toFixed(2);\n return `Image file size (${sizeMB} MB) exceeds maximum allowed size of 4 MB`;\n }\n\n // Check file extension\n const ext = path.extname(cleanedPath).toLowerCase();\n if (!VALID_IMAGE_EXTENSIONS.includes(ext)) {\n return \"Image must be JPG or PNG format\";\n }\n\n return undefined;\n}\n\n// ==================== App ID Validation ====================\n\n/**\n * Validate and normalize app ID address\n * @param appID - App ID (must be a valid address)\n * @returns Normalized app address\n * @throws Error if app ID is not a valid address\n *\n * Note: Name resolution should be handled by CLI before calling SDK functions.\n * The SDK only accepts resolved addresses.\n */\nexport function validateAppID(appID: string | Address): Address {\n if (!appID) {\n throw new Error(\"App ID is required\");\n }\n\n // Normalize the input\n const normalized = typeof appID === \"string\" ? addHexPrefix(appID) : appID;\n\n // Check if it's a valid address\n if (isAddress(normalized)) {\n return normalized as Address;\n }\n\n throw new Error(`Invalid app ID: '${appID}' is not a valid address`);\n}\n\n// ==================== Log Visibility Validation ====================\n\nexport type LogVisibility = \"public\" | \"private\" | \"off\";\n\n/**\n * Validate and convert log visibility setting to internal format\n * @param logVisibility - Log visibility setting\n * @returns Object with logRedirect and publicLogs settings\n * @throws Error if log visibility value is invalid\n */\nexport function validateLogVisibility(logVisibility: LogVisibility): {\n logRedirect: string;\n publicLogs: boolean;\n} {\n switch (logVisibility) {\n case \"public\":\n return { logRedirect: \"always\", publicLogs: true };\n case \"private\":\n return { logRedirect: \"always\", publicLogs: false };\n case \"off\":\n return { logRedirect: \"\", publicLogs: false };\n default:\n throw new Error(\n `Invalid log-visibility value: ${logVisibility} (must be public, private, or off)`,\n );\n }\n}\n\n// ==================== Resource Usage Monitoring Validation ====================\n\nexport type ResourceUsageMonitoring = \"enable\" | \"disable\";\n\n/**\n * Validate and convert resource usage monitoring setting to internal format\n * @param resourceUsageMonitoring - Resource usage monitoring setting\n * @returns The resourceUsageAllow value for the Dockerfile label (\"always\" or \"never\")\n * @throws Error if resource usage monitoring value is invalid\n */\nexport function validateResourceUsageMonitoring(\n resourceUsageMonitoring: ResourceUsageMonitoring | undefined,\n): string {\n // Default to \"enable\" (always) if not specified\n if (!resourceUsageMonitoring) {\n return \"always\";\n }\n\n switch (resourceUsageMonitoring) {\n case \"enable\":\n return \"always\";\n case \"disable\":\n return \"never\";\n default:\n throw new Error(\n `Invalid resource-usage-monitoring value: ${resourceUsageMonitoring} (must be enable or disable)`,\n );\n }\n}\n\n// ==================== Sanitization Functions ====================\n\n/**\n * Check if URL has scheme\n */\nfunction hasScheme(rawURL: string): boolean {\n return rawURL.startsWith(\"http://\") || rawURL.startsWith(\"https://\");\n}\n\n/**\n * Sanitize string (HTML escape and trim)\n */\nexport function sanitizeString(s: string): string {\n return s\n .trim()\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/**\n * Sanitize URL (add https:// if missing, validate)\n * @throws Error if URL is invalid after sanitization\n */\nexport function sanitizeURL(rawURL: string): string {\n rawURL = rawURL.trim();\n\n // Add https:// if no scheme is present\n if (!hasScheme(rawURL)) {\n rawURL = \"https://\" + rawURL;\n }\n\n // Validate\n const err = validateURL(rawURL);\n if (err) {\n throw new Error(err);\n }\n\n return rawURL;\n}\n\n/**\n * Sanitize X/Twitter URL (handle username-only input, normalize)\n * @throws Error if URL is invalid after sanitization\n */\nexport function sanitizeXURL(rawURL: string): string {\n rawURL = rawURL.trim();\n\n // Handle username-only input (e.g., \"@username\" or \"username\")\n if (!rawURL.includes(\"://\") && !rawURL.includes(\".\")) {\n // Remove @ if present\n const username = rawURL.startsWith(\"@\") ? rawURL.slice(1) : rawURL;\n rawURL = `https://x.com/${username}`;\n } else if (!hasScheme(rawURL)) {\n // Add https:// if URL-like but missing scheme\n rawURL = \"https://\" + rawURL;\n }\n\n // Normalize twitter.com to x.com\n rawURL = rawURL.replace(/twitter\\.com/g, \"x.com\");\n rawURL = rawURL.replace(/www\\.x\\.com/g, \"x.com\");\n\n // Validate\n const err = validateXURL(rawURL);\n if (err) {\n throw new Error(err);\n }\n\n return rawURL;\n}\n\n// ==================== Deploy/Upgrade Parameter Validation ====================\n\nexport interface DeployParams {\n dockerfilePath?: string;\n imageRef?: string;\n appName: string;\n envFilePath?: string;\n instanceType: string;\n logVisibility: LogVisibility;\n}\n\n/**\n * Validate deploy parameters\n * @throws Error if required parameters are missing or invalid\n */\nexport function validateDeployParams(params: Partial<DeployParams>): void {\n // Must have either dockerfilePath or imageRef\n if (!params.dockerfilePath && !params.imageRef) {\n throw new Error(\"Either dockerfilePath or imageRef is required for deployment\");\n }\n\n // If imageRef is provided, validate it\n if (params.imageRef) {\n assertValidImageReference(params.imageRef);\n }\n\n // If dockerfilePath is provided, validate it exists\n if (params.dockerfilePath) {\n assertValidFilePath(params.dockerfilePath);\n }\n\n // App name is required\n if (!params.appName) {\n throw new Error(\"App name is required\");\n }\n validateAppName(params.appName);\n\n // Instance type is required\n if (!params.instanceType) {\n throw new Error(\"Instance type is required\");\n }\n\n // Log visibility is required\n if (!params.logVisibility) {\n throw new Error(\"Log visibility is required (public, private, or off)\");\n }\n validateLogVisibility(params.logVisibility);\n\n // Env file path is optional, but if provided, validate it exists\n if (params.envFilePath && params.envFilePath !== \"\") {\n const result = validateFilePath(params.envFilePath);\n if (result !== true) {\n throw new Error(`Invalid env file: ${result}`);\n }\n }\n}\n\nexport interface UpgradeParams {\n appID: string | Address;\n dockerfilePath?: string;\n imageRef?: string;\n envFilePath?: string;\n instanceType: string;\n logVisibility: LogVisibility;\n}\n\n/**\n * Validate upgrade parameters\n * @throws Error if required parameters are missing or invalid\n */\nexport function validateUpgradeParams(params: Partial<UpgradeParams>): void {\n // App ID is required\n if (!params.appID) {\n throw new Error(\"App ID is required for upgrade\");\n }\n // Validate app ID is a valid address (throws if not)\n validateAppID(params.appID);\n\n // Must have either dockerfilePath or imageRef\n if (!params.dockerfilePath && !params.imageRef) {\n throw new Error(\"Either dockerfilePath or imageRef is required for upgrade\");\n }\n\n // If imageRef is provided, validate it\n if (params.imageRef) {\n assertValidImageReference(params.imageRef);\n }\n\n // If dockerfilePath is provided, validate it exists\n if (params.dockerfilePath) {\n assertValidFilePath(params.dockerfilePath);\n }\n\n // Instance type is required\n if (!params.instanceType) {\n throw new Error(\"Instance type is required\");\n }\n\n // Log visibility is required\n if (!params.logVisibility) {\n throw new Error(\"Log visibility is required (public, private, or off)\");\n }\n validateLogVisibility(params.logVisibility);\n\n // Env file path is optional, but if provided, validate it exists\n if (params.envFilePath && params.envFilePath !== \"\") {\n const result = validateFilePath(params.envFilePath);\n if (result !== true) {\n throw new Error(`Invalid env file: ${result}`);\n }\n }\n}\n\nexport interface CreateAppParams {\n name: string;\n language: string;\n template?: string;\n templateVersion?: string;\n}\n\n/**\n * Validate create app parameters\n * @throws Error if required parameters are missing or invalid\n */\nexport function validateCreateAppParams(params: Partial<CreateAppParams>): void {\n if (!params.name) {\n throw new Error(\"Project name is required\");\n }\n\n // Validate project name (no spaces)\n if (params.name.includes(\" \")) {\n throw new Error(\"Project name cannot contain spaces\");\n }\n\n if (!params.language) {\n throw new Error(\"Language is required\");\n }\n}\n\nexport interface LogsParams {\n appID: string | Address;\n watch?: boolean;\n}\n\n/**\n * Validate logs parameters\n * @throws Error if required parameters are missing or invalid\n */\nexport function validateLogsParams(params: Partial<LogsParams>): void {\n if (!params.appID) {\n throw new Error(\"App ID is required for viewing logs\");\n }\n // Validate app ID is a valid address (throws if not)\n validateAppID(params.appID);\n}\n","/**\n * General utility helpers\n */\n\nimport { extractChain, createPublicClient, createWalletClient, http } from \"viem\";\nimport type { Chain, Hex, PublicClient, WalletClient } from \"viem\";\nimport { sepolia } from \"viem/chains\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { SUPPORTED_CHAINS } from \"../constants\";\n\n/**\n * Get a viem Chain object from a chain ID.\n * Supports mainnet (1) and sepolia (11155111), defaults to the fallback chain for unknown chains.\n */\nexport function getChainFromID(chainID: bigint, fallback: Chain = sepolia): Chain {\n const id = Number(chainID) as (typeof SUPPORTED_CHAINS)[number][\"id\"];\n return extractChain({ chains: SUPPORTED_CHAINS, id }) || fallback;\n}\n\n/**\n * Create viem clients from a private key\n *\n * This is a convenience helper for CLI and server applications that have direct\n * access to a private key. For browser applications using external wallets (MetaMask, etc.),\n * create the WalletClient directly using viem's createWalletClient with a custom transport.\n *\n * @example\n * // CLI usage with private key\n * const { walletClient, publicClient } = createClients({\n * privateKey: '0x...',\n * rpcUrl: 'https://sepolia.infura.io/v3/...',\n * chainId: 11155111n\n * });\n *\n * @example\n * // Browser usage with external wallet (create clients directly)\n * const walletClient = createWalletClient({\n * chain: sepolia,\n * transport: custom(window.ethereum!)\n * });\n * const publicClient = createPublicClient({\n * chain: sepolia,\n * transport: custom(window.ethereum!)\n * });\n */\nexport function createClients(options: {\n privateKey: string | Hex;\n rpcUrl: string;\n chainId: bigint;\n}): {\n walletClient: WalletClient;\n publicClient: PublicClient;\n} {\n const { privateKey, rpcUrl, chainId } = options;\n\n const privateKeyHex = addHexPrefix(privateKey);\n const account = privateKeyToAccount(privateKeyHex);\n const chain = getChainFromID(chainId);\n\n const publicClient = createPublicClient({\n chain,\n transport: http(rpcUrl),\n });\n\n const walletClient = createWalletClient({\n account,\n chain,\n transport: http(rpcUrl),\n });\n\n return { walletClient, publicClient };\n}\n\n/**\n * Ensure hex string has 0x prefix\n */\nexport function addHexPrefix(value: string): Hex {\n return (value.startsWith(\"0x\") ? value : `0x${value}`) as Hex;\n}\n\n/**\n * Remove 0x prefix from hex string if present\n */\nexport function stripHexPrefix(value: string): string {\n return value.startsWith(\"0x\") ? value.slice(2) : value;\n}\n","/**\n * Constants used throughout the SDK\n */\n\nimport { sepolia, mainnet } from \"viem/chains\";\n\nexport const SUPPORTED_CHAINS = [mainnet, sepolia] as const;\n\nexport const DOCKER_PLATFORM = \"linux/amd64\";\nexport const REGISTRY_PROPAGATION_WAIT_SECONDS = 3;\nexport const LAYERED_DOCKERFILE_NAME = \"Dockerfile.eigencompute\";\nexport const ENV_SOURCE_SCRIPT_NAME = \"compute-source-env.sh\";\nexport const KMS_CLIENT_BINARY_NAME = \"kms-client\";\nexport const KMS_ENCRYPTION_KEY_NAME = \"kms-encryption-public-key.pem\";\nexport const KMS_SIGNING_KEY_NAME = \"kms-signing-public-key.pem\";\nexport const TLS_KEYGEN_BINARY_NAME = \"tls-keygen\";\nexport const CADDYFILE_NAME = \"Caddyfile\";\nexport const TEMP_IMAGE_PREFIX = \"ecloud-temp-\";\nexport const LAYERED_BUILD_DIR_PREFIX = \"ecloud-layered-build\";\nexport const SHA256_PREFIX = \"sha256:\";\nexport const JWT_FILE_PATH = \"/run/container_launcher/attestation_verifier_claims_token\";\n","/**\n * Billing utility functions\n */\n\nimport type { SubscriptionStatus } from \"../types\";\n\n/**\n * Check if subscription status allows deploying apps\n */\nexport function isSubscriptionActive(status: SubscriptionStatus): boolean {\n return status === \"active\" || status === \"trialing\";\n}\n","/**\n * Private Key Generation\n *\n * Generate new secp256k1 private keys for Ethereum\n */\n\nimport { generatePrivateKey, privateKeyToAddress } from \"viem/accounts\";\n\nexport interface GeneratedKey {\n privateKey: string;\n address: string;\n}\n\n/**\n * Generate a new secp256k1 private key\n */\nexport function generateNewPrivateKey(): GeneratedKey {\n const privateKey = generatePrivateKey();\n const address = privateKeyToAddress(privateKey);\n\n return {\n privateKey,\n address,\n };\n}\n","import axios, { AxiosResponse } from \"axios\";\nimport { Address, Hex, type PublicClient, type WalletClient } from \"viem\";\nimport { calculatePermissionSignature } from \"./auth\";\nimport { EnvironmentConfig } from \"../types\";\nimport { stripHexPrefix } from \"./helpers\";\n\nexport interface AppProfileInfo {\n name: string;\n website?: string;\n description?: string;\n xURL?: string;\n imageURL?: string;\n}\n\nexport interface AppMetrics {\n cpu_utilization_percent?: number;\n memory_utilization_percent?: number;\n memory_used_bytes?: number;\n memory_total_bytes?: number;\n}\n\nexport interface DerivedAddress {\n address: string;\n derivationPath: string;\n}\n\nexport interface AppInfo {\n address: Address;\n status: string;\n ip: string;\n machineType: string;\n profile?: AppProfileInfo;\n metrics?: AppMetrics;\n evmAddresses: DerivedAddress[];\n solanaAddresses: DerivedAddress[];\n}\n\nexport interface AppInfoResponse {\n apps: Array<{\n addresses: {\n data: {\n evmAddresses: DerivedAddress[];\n solanaAddresses: DerivedAddress[];\n };\n signature: string;\n };\n app_status: string;\n ip: string;\n machine_type: string;\n profile?: AppProfileInfo;\n metrics?: AppMetrics;\n }>;\n}\n\n// ==================== App Releases (/apps/:id) ====================\n\ntype JsonObject = Record<string, unknown>;\n\nfunction isJsonObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction readString(obj: JsonObject, key: string): string | undefined {\n const v = obj[key];\n return typeof v === \"string\" ? v : undefined;\n}\n\nfunction readNumber(obj: JsonObject, key: string): number | undefined {\n const v = obj[key];\n return typeof v === \"number\" && Number.isFinite(v) ? v : undefined;\n}\n\nexport type AppContractStatus = \"STARTED\" | \"STOPPED\" | \"TERMINATED\" | \"SUSPENDED\" | string;\n\nexport interface AppReleaseBuild {\n buildId?: string;\n billingAddress?: string;\n repoUrl?: string;\n gitRef?: string;\n status?: string;\n buildType?: string;\n imageName?: string;\n imageDigest?: string;\n imageUrl?: string;\n provenanceJson?: unknown;\n provenanceSignature?: string;\n createdAt?: string;\n updatedAt?: string;\n errorMessage?: string;\n dependencies?: Record<string, AppReleaseBuild>;\n}\n\nexport interface AppRelease {\n appId?: string;\n rmsReleaseId?: string;\n imageDigest?: string;\n registryUrl?: string;\n publicEnv?: string;\n encryptedEnv?: string;\n upgradeByTime?: number;\n createdAt?: string;\n createdAtBlock?: string;\n build?: AppReleaseBuild;\n}\n\nexport interface AppResponse {\n id: string;\n creator?: string;\n contractStatus?: AppContractStatus;\n releases: AppRelease[];\n}\n\nconst MAX_ADDRESS_COUNT = 5;\n\n// Permission constants\nexport const CanViewAppLogsPermission = \"0x2fd3f2fe\" as Hex;\nexport const CanViewSensitiveAppInfoPermission = \"0x0e67b22f\" as Hex;\nexport const CanUpdateAppProfilePermission = \"0x036fef61\" as Hex;\n\n/**\n * SDK_VERSION_BUILD_TIME is replaced at build time by tsup's define option\n */\n// @ts-ignore - SDK_VERSION_BUILD_TIME is injected at build time by tsup\ndeclare const SDK_VERSION_BUILD_TIME: string | undefined;\n\n/**\n * Get the default client ID using the build-time version\n */\nfunction getDefaultClientId(): string {\n // @ts-ignore - SDK_VERSION_BUILD_TIME is injected at build time\n const version = typeof SDK_VERSION_BUILD_TIME !== \"undefined\" ? SDK_VERSION_BUILD_TIME : \"0.0.0\";\n return `ecloud-sdk/v${version}`;\n}\n\n/**\n * UserAPI Client for interacting with the EigenCloud UserAPI service.\n */\nexport class UserApiClient {\n private readonly clientId: string;\n\n constructor(\n private readonly config: EnvironmentConfig,\n private readonly walletClient: WalletClient,\n private readonly publicClient: PublicClient,\n clientId?: string,\n ) {\n this.clientId = clientId || getDefaultClientId();\n }\n\n /**\n * Get the address of the connected wallet\n */\n get address(): Address {\n const account = this.walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n return account.address;\n }\n\n async getInfos(appIDs: Address[], addressCount = 1): Promise<AppInfo[]> {\n const count = Math.min(addressCount, MAX_ADDRESS_COUNT);\n\n const endpoint = `${this.config.userApiServerURL}/info`;\n const url = `${endpoint}?${new URLSearchParams({ apps: appIDs.join(\",\") })}`;\n\n const res = await this.makeAuthenticatedRequest(url, CanViewSensitiveAppInfoPermission);\n const result: AppInfoResponse = await res.json();\n\n // optional: verify signatures with KMS key\n // const { signingKey } = getKMSKeysForEnvironment(this.config.name);\n\n // Truncate without mutating the original object\n // API returns apps in the same order as the request, so use appIDs[i] as the address\n return result.apps.map((app, i) => {\n // TODO: Implement signature verification\n // const valid = await verifyKMSSignature(appInfo.addresses, signingKey);\n // if (!valid) {\n // throw new Error(`Invalid signature for app ${appIDs[i]}`);\n // }\n\n // Slice derived addresses to requested count\n const evmAddresses = app.addresses?.data?.evmAddresses?.slice(0, count) || [];\n const solanaAddresses = app.addresses?.data?.solanaAddresses?.slice(0, count) || [];\n\n return {\n address: appIDs[i] as Address,\n status: app.app_status,\n ip: app.ip,\n machineType: app.machine_type,\n profile: app.profile,\n metrics: app.metrics,\n evmAddresses,\n solanaAddresses,\n };\n });\n }\n\n /**\n * Get app details from UserAPI (includes releases and build/provenance info when available).\n *\n * Endpoint: GET /apps/:appAddress\n */\n async getApp(appAddress: Address): Promise<AppResponse> {\n const endpoint = `${this.config.userApiServerURL}/apps/${appAddress}`;\n const res = await this.makeAuthenticatedRequest(endpoint);\n const raw = (await res.json()) as unknown;\n\n if (!isJsonObject(raw)) {\n throw new Error(\"Unexpected /apps/:id response: expected object\");\n }\n\n const id = readString(raw, \"id\");\n if (!id) {\n throw new Error(\"Unexpected /apps/:id response: missing 'id'\");\n }\n\n const releasesRaw = raw.releases;\n const releases = Array.isArray(releasesRaw)\n ? releasesRaw.map((r) => transformAppRelease(r)).filter((r): r is AppRelease => !!r)\n : [];\n\n return {\n id,\n creator: readString(raw, \"creator\"),\n contractStatus: (readString(raw, \"contract_status\") ?? readString(raw, \"contractStatus\")) as\n | AppContractStatus\n | undefined,\n releases,\n };\n }\n\n /**\n * Get available SKUs (instance types) from UserAPI\n */\n async getSKUs(): Promise<{\n skus: Array<{ sku: string; description: string }>;\n }> {\n const endpoint = `${this.config.userApiServerURL}/skus`;\n const response = await this.makeAuthenticatedRequest(endpoint);\n\n const result = await response.json();\n\n // Transform response to match expected format\n return {\n skus: result.skus || result.SKUs || [],\n };\n }\n\n /**\n * Get logs for an app\n */\n async getLogs(appID: Address): Promise<string> {\n const endpoint = `${this.config.userApiServerURL}/logs/${appID}`;\n const response = await this.makeAuthenticatedRequest(endpoint, CanViewAppLogsPermission);\n return await response.text();\n }\n\n /**\n * Get statuses for apps\n */\n async getStatuses(appIDs: Address[]): Promise<Array<{ address: Address; status: string }>> {\n const endpoint = `${this.config.userApiServerURL}/status`;\n const url = `${endpoint}?${new URLSearchParams({ apps: appIDs.join(\",\") })}`;\n const response = await this.makeAuthenticatedRequest(url);\n const result = await response.json();\n\n // Transform response to match expected format\n // The API returns an array of app statuses\n const apps = result.apps || result.Apps || [];\n return apps.map((app: any, i: number) => ({\n address: (app.address || appIDs[i]) as Address,\n status: app.status || app.Status || \"\",\n }));\n }\n\n /**\n * Upload app profile information with optional image\n *\n * @param appAddress - The app's contract address\n * @param name - Display name for the app\n * @param options - Optional fields including website, description, xURL, and image\n * @param options.image - Image file as Blob or File (browser: from input element, Node.js: new Blob([buffer]))\n * @param options.imageName - Filename for the image (required if image is provided)\n */\n async uploadAppProfile(\n appAddress: Address,\n name: string,\n options?: {\n website?: string;\n description?: string;\n xURL?: string;\n image?: Blob | File;\n imageName?: string;\n },\n ): Promise<{\n name: string;\n website?: string;\n description?: string;\n xURL?: string;\n imageURL?: string;\n }> {\n const endpoint = `${this.config.userApiServerURL}/apps/${appAddress}/profile`;\n\n // Build multipart form data using Web FormData API (works in browser and Node.js 18+)\n const formData = new FormData();\n\n // Add required name field\n formData.append(\"name\", name);\n\n // Add optional text fields\n if (options?.website) {\n formData.append(\"website\", options.website);\n }\n if (options?.description) {\n formData.append(\"description\", options.description);\n }\n if (options?.xURL) {\n formData.append(\"xURL\", options.xURL);\n }\n\n // Add optional image file (Blob or File)\n if (options?.image) {\n // If it's a File, use its name; otherwise require imageName\n const fileName =\n options.image instanceof File ? options.image.name : options.imageName || \"image\";\n formData.append(\"image\", options.image, fileName);\n }\n\n // Make authenticated POST request\n // Note: Don't set Content-Type header manually - axios will set it with the correct boundary\n const headers: Record<string, string> = {\n \"x-client-id\": this.clientId,\n };\n\n // Add auth headers (Authorization and X-eigenx-expiry)\n const expiry = BigInt(Math.floor(Date.now() / 1000) + 5 * 60); // 5 minutes\n const authHeaders = await this.generateAuthHeaders(CanUpdateAppProfilePermission, expiry);\n Object.assign(headers, authHeaders);\n\n try {\n // Use axios to post req\n const response: AxiosResponse = await axios.post(endpoint, formData, {\n headers,\n maxRedirects: 0,\n validateStatus: () => true, // Don't throw on any status\n maxContentLength: Infinity, // Allow large file uploads\n maxBodyLength: Infinity, // Allow large file uploads\n });\n\n const status = response.status;\n\n if (status !== 200 && status !== 201) {\n const body =\n typeof response.data === \"string\" ? response.data : JSON.stringify(response.data);\n\n // Detect Cloudflare challenge page\n if (status === 403 && body.includes(\"Cloudflare\") && body.includes(\"challenge-platform\")) {\n throw new Error(\n `Cloudflare protection is blocking the request. This is likely due to bot detection.\\n` +\n `Status: ${status}`,\n );\n }\n\n throw new Error(\n `UserAPI request failed: ${status} ${status >= 200 && status < 300 ? \"OK\" : \"Error\"} - ${body.substring(0, 500)}${body.length > 500 ? \"...\" : \"\"}`,\n );\n }\n\n return response.data;\n } catch (error: any) {\n if (\n error.message?.includes(\"fetch failed\") ||\n error.message?.includes(\"ECONNREFUSED\") ||\n error.message?.includes(\"ENOTFOUND\") ||\n error.cause\n ) {\n const cause = error.cause?.message || error.cause || error.message;\n throw new Error(\n `Failed to connect to UserAPI at ${endpoint}: ${cause}\\n` +\n `Please check:\\n` +\n `1. Your internet connection\\n` +\n `2. The API server is accessible: ${this.config.userApiServerURL}\\n` +\n `3. Firewall/proxy settings`,\n );\n }\n throw error;\n }\n }\n\n private async makeAuthenticatedRequest(\n url: string,\n permission?: Hex,\n ): Promise<{ json: () => Promise<any>; text: () => Promise<string> }> {\n const headers: Record<string, string> = {\n \"x-client-id\": this.clientId,\n };\n // Add auth headers if permission is specified\n if (permission) {\n const expiry = BigInt(Math.floor(Date.now() / 1000) + 5 * 60); // 5 minutes\n const authHeaders = await this.generateAuthHeaders(permission, expiry);\n Object.assign(headers, authHeaders);\n }\n\n try {\n // Use axios to match\n const response: AxiosResponse = await axios.get(url, {\n headers,\n maxRedirects: 0,\n validateStatus: () => true, // Don't throw on any status\n });\n\n const status = response.status;\n const statusText = status >= 200 && status < 300 ? \"OK\" : \"Error\";\n\n if (status < 200 || status >= 300) {\n const body =\n typeof response.data === \"string\" ? response.data : JSON.stringify(response.data);\n throw new Error(`UserAPI request failed: ${status} ${statusText} - ${body}`);\n }\n\n // Return Response-like object for compatibility\n return {\n json: async () => response.data,\n text: async () =>\n typeof response.data === \"string\" ? response.data : JSON.stringify(response.data),\n };\n } catch (error: any) {\n // Handle network errors (fetch failed, connection refused, etc.)\n if (\n error.message?.includes(\"fetch failed\") ||\n error.message?.includes(\"ECONNREFUSED\") ||\n error.message?.includes(\"ENOTFOUND\") ||\n error.cause\n ) {\n const cause = error.cause?.message || error.cause || error.message;\n throw new Error(\n `Failed to connect to UserAPI at ${url}: ${cause}\\n` +\n `Please check:\\n` +\n `1. Your internet connection\\n` +\n `2. The API server is accessible: ${this.config.userApiServerURL}\\n` +\n `3. Firewall/proxy settings`,\n );\n }\n // Re-throw other errors as-is\n throw error;\n }\n }\n\n /**\n * Generate authentication headers for UserAPI requests\n */\n private async generateAuthHeaders(\n permission: Hex,\n expiry: bigint,\n ): Promise<Record<string, string>> {\n // Calculate permission signature using shared auth utility\n const { signature } = await calculatePermissionSignature({\n permission,\n expiry,\n appControllerAddress: this.config.appControllerAddress,\n publicClient: this.publicClient,\n walletClient: this.walletClient,\n });\n\n // Return auth headers\n return {\n Authorization: `Bearer ${stripHexPrefix(signature)}`,\n \"X-eigenx-expiry\": expiry.toString(),\n };\n }\n}\n\nfunction transformAppReleaseBuild(raw: unknown): AppReleaseBuild | undefined {\n if (!isJsonObject(raw)) return undefined;\n\n const depsRaw = raw.dependencies;\n const deps: Record<string, AppReleaseBuild> | undefined = isJsonObject(depsRaw)\n ? Object.fromEntries(\n Object.entries(depsRaw).flatMap(([digest, depRaw]) => {\n const parsed = transformAppReleaseBuild(depRaw);\n return parsed ? ([[digest, parsed]] as const) : [];\n }),\n )\n : undefined;\n\n return {\n buildId: readString(raw, \"build_id\") ?? readString(raw, \"buildId\"),\n billingAddress: readString(raw, \"billing_address\") ?? readString(raw, \"billingAddress\"),\n repoUrl: readString(raw, \"repo_url\") ?? readString(raw, \"repoUrl\"),\n gitRef: readString(raw, \"git_ref\") ?? readString(raw, \"gitRef\"),\n status: readString(raw, \"status\"),\n buildType: readString(raw, \"build_type\") ?? readString(raw, \"buildType\"),\n imageName: readString(raw, \"image_name\") ?? readString(raw, \"imageName\"),\n imageDigest: readString(raw, \"image_digest\") ?? readString(raw, \"imageDigest\"),\n imageUrl: readString(raw, \"image_url\") ?? readString(raw, \"imageUrl\"),\n provenanceJson: raw.provenance_json ?? raw.provenanceJson,\n provenanceSignature:\n readString(raw, \"provenance_signature\") ?? readString(raw, \"provenanceSignature\"),\n createdAt: readString(raw, \"created_at\") ?? readString(raw, \"createdAt\"),\n updatedAt: readString(raw, \"updated_at\") ?? readString(raw, \"updatedAt\"),\n errorMessage: readString(raw, \"error_message\") ?? readString(raw, \"errorMessage\"),\n dependencies: deps,\n };\n}\n\nfunction transformAppRelease(raw: unknown): AppRelease | undefined {\n if (!isJsonObject(raw)) return undefined;\n\n return {\n appId: readString(raw, \"appId\") ?? readString(raw, \"app_id\"),\n rmsReleaseId: readString(raw, \"rmsReleaseId\") ?? readString(raw, \"rms_release_id\"),\n imageDigest: readString(raw, \"imageDigest\") ?? readString(raw, \"image_digest\"),\n registryUrl: readString(raw, \"registryUrl\") ?? readString(raw, \"registry_url\"),\n publicEnv: readString(raw, \"publicEnv\") ?? readString(raw, \"public_env\"),\n encryptedEnv: readString(raw, \"encryptedEnv\") ?? readString(raw, \"encrypted_env\"),\n upgradeByTime: readNumber(raw, \"upgradeByTime\") ?? readNumber(raw, \"upgrade_by_time\"),\n createdAt: readString(raw, \"createdAt\") ?? readString(raw, \"created_at\"),\n createdAtBlock: readString(raw, \"createdAtBlock\") ?? readString(raw, \"created_at_block\"),\n build: raw.build ? transformAppReleaseBuild(raw.build) : undefined,\n };\n}\n","/**\n * Shared authentication utilities for API clients\n */\n\nimport { Hex, parseAbi, type Address, type PublicClient, type WalletClient } from \"viem\";\n\n// Minimal AppController ABI for permission calculation\nconst APP_CONTROLLER_ABI = parseAbi([\n \"function calculateApiPermissionDigestHash(bytes4 permission, uint256 expiry) view returns (bytes32)\",\n]);\n\nexport interface PermissionSignatureOptions {\n permission: Hex;\n expiry: bigint;\n appControllerAddress: Address;\n publicClient: PublicClient;\n walletClient: WalletClient;\n}\n\nexport interface PermissionSignatureResult {\n signature: string;\n digest: Hex;\n}\n\n/**\n * Calculate permission digest via AppController contract and sign it with EIP-191\n *\n * Works with any WalletClient - whether backed by a local private key or external signer.\n */\nexport async function calculatePermissionSignature(\n options: PermissionSignatureOptions,\n): Promise<PermissionSignatureResult> {\n const { permission, expiry, appControllerAddress, publicClient, walletClient } = options;\n\n // Calculate permission digest hash using AppController contract\n const digest = (await publicClient.readContract({\n address: appControllerAddress,\n abi: APP_CONTROLLER_ABI,\n functionName: \"calculateApiPermissionDigestHash\",\n args: [permission, expiry],\n })) as Hex;\n\n // Get account from wallet client\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n // Sign the digest using EIP-191 (signMessage handles prefixing automatically)\n const signature = await walletClient.signMessage({\n account,\n message: { raw: digest },\n });\n\n return { signature, digest };\n}\n\nexport interface BillingAuthSignatureOptions {\n walletClient: WalletClient;\n product: string;\n expiry: bigint;\n}\n\nexport interface BillingAuthSignatureResult {\n signature: Hex;\n expiry: bigint;\n}\n\nconst generateBillingSigData = (product: string, expiry: bigint) => {\n return {\n domain: {\n name: \"EigenCloud Billing API\",\n version: \"1\",\n },\n types: {\n BillingAuth: [\n { name: \"product\", type: \"string\" },\n { name: \"expiry\", type: \"uint256\" },\n ],\n },\n primaryType: \"BillingAuth\" as const,\n message: {\n product,\n expiry,\n },\n };\n};\n\n/**\n * Sign billing authentication message using EIP-712 typed data\n */\nexport async function calculateBillingAuthSignature(\n options: BillingAuthSignatureOptions,\n): Promise<BillingAuthSignatureResult> {\n const { walletClient, product, expiry } = options;\n\n // Get account from wallet client\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n // Sign using EIP-712 typed data\n const signature = await walletClient.signTypedData({\n account,\n ...generateBillingSigData(product, expiry),\n });\n\n return { signature, expiry };\n}\n\nexport interface BuildAuthSignatureOptions {\n walletClient: WalletClient;\n expiry: bigint;\n}\n\nexport interface BuildAuthSignatureResult {\n signature: Hex;\n expiry: bigint;\n}\n\n/**\n * Sign build authentication message using EIP-712 typed data\n */\nexport async function calculateBuildAuthSignature(\n options: BuildAuthSignatureOptions,\n): Promise<BuildAuthSignatureResult> {\n const { walletClient, expiry } = options;\n\n // Get account from wallet client\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n const signature = await walletClient.signTypedData({\n account,\n domain: {\n name: \"EigenCloud Build API\",\n version: \"1\",\n },\n types: {\n BuildAuth: [{ name: \"expiry\", type: \"uint256\" }],\n },\n primaryType: \"BuildAuth\",\n message: {\n expiry,\n },\n });\n\n return { signature, expiry };\n}\n","/**\n * EIP-7702 transaction handling\n *\n * This module handles EIP-7702 delegation and batch execution.\n */\n\nimport { Address, Hex, encodeFunctionData, encodeAbiParameters, decodeErrorResult } from \"viem\";\n\nimport type {\n WalletClient,\n PublicClient,\n SendTransactionParameters,\n SignAuthorizationReturnType,\n} from \"viem\";\nimport { EnvironmentConfig, Logger } from \"../types\";\n\nimport ERC7702DelegatorABI from \"../abis/ERC7702Delegator.json\";\n\nimport { GasEstimate, formatETH } from \"./caller\";\n\n// Mode 0x01 is executeBatchMode (32 bytes, padded, big endian)\nconst EXECUTE_BATCH_MODE =\n \"0x0100000000000000000000000000000000000000000000000000000000000000\" as Hex;\n\nconst GAS_LIMIT_BUFFER_PERCENTAGE = 20n; // 20%\nconst GAS_PRICE_BUFFER_PERCENTAGE = 100n; // 100%\n\nexport type Execution = {\n target: Address;\n value: bigint;\n callData: Hex;\n};\n\n/**\n * Encode executions array and pack into execute function call data\n */\nfunction encodeExecuteBatchData(executions: Execution[]): Hex {\n const encodedExecutions = encodeAbiParameters(\n [\n {\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"callData\", type: \"bytes\" },\n ],\n },\n ],\n [executions],\n );\n\n return encodeFunctionData({\n abi: ERC7702DelegatorABI,\n functionName: \"execute\",\n args: [EXECUTE_BATCH_MODE, encodedExecutions],\n });\n}\n\n/**\n * Options for estimating batch gas\n */\nexport interface EstimateBatchGasOptions {\n publicClient: PublicClient;\n account: Address;\n executions: Execution[];\n}\n\n/**\n * Estimate gas cost for a batch transaction\n *\n * Use this to get cost estimate before prompting user for confirmation.\n */\nexport async function estimateBatchGas(options: EstimateBatchGasOptions): Promise<GasEstimate> {\n const { publicClient, account, executions } = options;\n\n const executeBatchData = encodeExecuteBatchData(executions);\n\n // EIP-7702 transactions send to self (the EOA with delegated code)\n const [gasTipCap, block, estimatedGas] = await Promise.all([\n publicClient.estimateMaxPriorityFeePerGas(),\n publicClient.getBlock(),\n publicClient.estimateGas({\n account,\n to: account,\n data: executeBatchData,\n }),\n ]);\n\n const baseFee = block.baseFeePerGas ?? 0n;\n\n // Calculate gas price with 100% buffer: (baseFee + gasTipCap) * 2\n const maxFeePerGas = ((baseFee + gasTipCap) * (100n + GAS_PRICE_BUFFER_PERCENTAGE)) / 100n;\n\n // Add 20% buffer to gas limit\n const gasLimit = (estimatedGas * (100n + GAS_LIMIT_BUFFER_PERCENTAGE)) / 100n;\n\n const maxCostWei = gasLimit * maxFeePerGas;\n\n return {\n gasLimit,\n maxFeePerGas,\n maxPriorityFeePerGas: gasTipCap,\n maxCostWei,\n maxCostEth: formatETH(maxCostWei),\n };\n}\n\nexport interface ExecuteBatchOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n executions: Execution[];\n pendingMessage: string;\n /** Optional gas params from estimation */\n gas?: GasEstimate;\n}\n\n/**\n * Check if account is delegated to ERC-7702 delegator\n */\nexport async function checkERC7702Delegation(\n publicClient: PublicClient,\n account: Address,\n delegatorAddress: Address,\n): Promise<boolean> {\n const code = await publicClient.getCode({ address: account });\n if (!code) {\n return false;\n }\n\n // Check if code matches EIP-7702 delegation pattern: 0xef0100 || delegator_address\n const expectedCode = `0xef0100${delegatorAddress.slice(2)}`;\n return code.toLowerCase() === expectedCode.toLowerCase();\n}\n\n/**\n * Execute batch of operations via EIP-7702 delegator\n */\nexport async function executeBatch(options: ExecuteBatchOptions, logger: Logger): Promise<Hex> {\n const { walletClient, publicClient, environmentConfig, executions, pendingMessage, gas } =\n options;\n\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"Wallet client must have an account\");\n }\n\n const chain = walletClient.chain;\n if (!chain) {\n throw new Error(\"Wallet client must have a chain\");\n }\n\n const executeBatchData = encodeExecuteBatchData(executions);\n\n // Check if account is delegated\n const isDelegated = await checkERC7702Delegation(\n publicClient,\n account.address,\n environmentConfig.erc7702DelegatorAddress as Address,\n );\n\n // 4. Create authorization if needed\n let authorizationList: Array<SignAuthorizationReturnType> = [];\n\n if (!isDelegated) {\n const transactionNonce = await publicClient.getTransactionCount({\n address: account.address,\n blockTag: \"pending\",\n });\n\n const chainId = await publicClient.getChainId();\n const authorizationNonce = transactionNonce + 1;\n\n logger.debug(\"Using wallet client signing for EIP-7702 authorization\");\n\n const signedAuthorization = await walletClient.signAuthorization({\n account: account.address,\n contractAddress: environmentConfig.erc7702DelegatorAddress as Address,\n chainId: chainId,\n nonce: Number(authorizationNonce),\n });\n\n authorizationList = [signedAuthorization];\n }\n\n // 5. Show pending message\n if (pendingMessage) {\n logger.info(pendingMessage);\n }\n\n const txRequest: SendTransactionParameters = {\n account: walletClient.account!,\n chain,\n to: account.address,\n data: executeBatchData,\n value: 0n,\n };\n\n if (authorizationList.length > 0) {\n txRequest.authorizationList = authorizationList;\n }\n\n // Add gas params if provided\n if (gas?.maxFeePerGas) {\n txRequest.maxFeePerGas = gas.maxFeePerGas;\n }\n if (gas?.maxPriorityFeePerGas) {\n txRequest.maxPriorityFeePerGas = gas.maxPriorityFeePerGas;\n }\n\n const hash = await walletClient.sendTransaction(txRequest);\n logger.info(`Transaction sent: ${hash}`);\n\n const receipt = await publicClient.waitForTransactionReceipt({ hash });\n\n if (receipt.status === \"reverted\") {\n let revertReason = \"Unknown reason\";\n try {\n await publicClient.call({\n to: account.address,\n data: executeBatchData,\n account: account.address,\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (callError: any) {\n if (callError.data) {\n try {\n const decoded = decodeErrorResult({\n abi: ERC7702DelegatorABI,\n data: callError.data,\n });\n revertReason = `${decoded.errorName}: ${JSON.stringify(decoded.args)}`;\n } catch {\n revertReason = callError.message || \"Unknown reason\";\n }\n } else {\n revertReason = callError.message || \"Unknown reason\";\n }\n }\n throw new Error(`Transaction reverted: ${hash}. Reason: ${revertReason}`);\n }\n\n return hash;\n}\n","[\n {\n \"type\": \"constructor\",\n \"inputs\": [\n {\n \"name\": \"_delegationManager\",\n \"type\": \"address\",\n \"internalType\": \"contractIDelegationManager\"\n },\n {\n \"name\": \"_entryPoint\",\n \"type\": \"address\",\n \"internalType\": \"contractIEntryPoint\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"receive\",\n \"stateMutability\": \"payable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"DOMAIN_VERSION\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"NAME\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"PACKED_USER_OP_TYPEHASH\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"VERSION\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"addDeposit\",\n \"inputs\": [],\n \"outputs\": [],\n \"stateMutability\": \"payable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"delegationManager\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIDelegationManager\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"disableDelegation\",\n \"inputs\": [\n {\n \"name\": \"_delegation\",\n \"type\": \"tuple\",\n \"internalType\": \"structDelegation\",\n \"components\": [\n {\n \"name\": \"delegate\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"delegator\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"authority\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"caveats\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structCaveat[]\",\n \"components\": [\n {\n \"name\": \"enforcer\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"terms\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"args\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n },\n {\n \"name\": \"salt\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"signature\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"eip712Domain\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"fields\",\n \"type\": \"bytes1\",\n \"internalType\": \"bytes1\"\n },\n {\n \"name\": \"name\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n },\n {\n \"name\": \"version\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n },\n {\n \"name\": \"chainId\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"verifyingContract\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"salt\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"extensions\",\n \"type\": \"uint256[]\",\n \"internalType\": \"uint256[]\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"enableDelegation\",\n \"inputs\": [\n {\n \"name\": \"_delegation\",\n \"type\": \"tuple\",\n \"internalType\": \"structDelegation\",\n \"components\": [\n {\n \"name\": \"delegate\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"delegator\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"authority\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"caveats\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structCaveat[]\",\n \"components\": [\n {\n \"name\": \"enforcer\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"terms\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"args\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n },\n {\n \"name\": \"salt\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"signature\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"entryPoint\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIEntryPoint\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"execute\",\n \"inputs\": [\n {\n \"name\": \"_execution\",\n \"type\": \"tuple\",\n \"internalType\": \"structExecution\",\n \"components\": [\n {\n \"name\": \"target\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"value\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"callData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"payable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"execute\",\n \"inputs\": [\n {\n \"name\": \"_mode\",\n \"type\": \"bytes32\",\n \"internalType\": \"ModeCode\"\n },\n {\n \"name\": \"_executionCalldata\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"payable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"executeFromExecutor\",\n \"inputs\": [\n {\n \"name\": \"_mode\",\n \"type\": \"bytes32\",\n \"internalType\": \"ModeCode\"\n },\n {\n \"name\": \"_executionCalldata\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"returnData_\",\n \"type\": \"bytes[]\",\n \"internalType\": \"bytes[]\"\n }\n ],\n \"stateMutability\": \"payable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getDeposit\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getDomainHash\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getNonce\",\n \"inputs\": [\n {\n \"name\": \"_key\",\n \"type\": \"uint192\",\n \"internalType\": \"uint192\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getNonce\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getPackedUserOperationHash\",\n \"inputs\": [\n {\n \"name\": \"_userOp\",\n \"type\": \"tuple\",\n \"internalType\": \"structPackedUserOperation\",\n \"components\": [\n {\n \"name\": \"sender\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"nonce\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"initCode\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"callData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"accountGasLimits\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"preVerificationGas\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"gasFees\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"paymasterAndData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"signature\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getPackedUserOperationTypedDataHash\",\n \"inputs\": [\n {\n \"name\": \"_userOp\",\n \"type\": \"tuple\",\n \"internalType\": \"structPackedUserOperation\",\n \"components\": [\n {\n \"name\": \"sender\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"nonce\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"initCode\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"callData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"accountGasLimits\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"preVerificationGas\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"gasFees\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"paymasterAndData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"signature\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"isDelegationDisabled\",\n \"inputs\": [\n {\n \"name\": \"_delegationHash\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bool\",\n \"internalType\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"isValidSignature\",\n \"inputs\": [\n {\n \"name\": \"_hash\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"_signature\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"magicValue_\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"onERC1155BatchReceived\",\n \"inputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"uint256[]\",\n \"internalType\": \"uint256[]\"\n },\n {\n \"name\": \"\",\n \"type\": \"uint256[]\",\n \"internalType\": \"uint256[]\"\n },\n {\n \"name\": \"\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"onERC1155Received\",\n \"inputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"onERC721Received\",\n \"inputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"redeemDelegations\",\n \"inputs\": [\n {\n \"name\": \"_permissionContexts\",\n \"type\": \"bytes[]\",\n \"internalType\": \"bytes[]\"\n },\n {\n \"name\": \"_modes\",\n \"type\": \"bytes32[]\",\n \"internalType\": \"ModeCode[]\"\n },\n {\n \"name\": \"_executionCallDatas\",\n \"type\": \"bytes[]\",\n \"internalType\": \"bytes[]\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"supportsExecutionMode\",\n \"inputs\": [\n {\n \"name\": \"_mode\",\n \"type\": \"bytes32\",\n \"internalType\": \"ModeCode\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bool\",\n \"internalType\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"supportsInterface\",\n \"inputs\": [\n {\n \"name\": \"_interfaceId\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bool\",\n \"internalType\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"validateUserOp\",\n \"inputs\": [\n {\n \"name\": \"_userOp\",\n \"type\": \"tuple\",\n \"internalType\": \"structPackedUserOperation\",\n \"components\": [\n {\n \"name\": \"sender\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"nonce\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"initCode\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"callData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"accountGasLimits\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"preVerificationGas\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"gasFees\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"paymasterAndData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"signature\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n },\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"_missingAccountFunds\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"validationData_\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"withdrawDeposit\",\n \"inputs\": [\n {\n \"name\": \"_withdrawAddress\",\n \"type\": \"address\",\n \"internalType\": \"addresspayable\"\n },\n {\n \"name\": \"_withdrawAmount\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"event\",\n \"name\": \"EIP712DomainChanged\",\n \"inputs\": [],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"SentPrefund\",\n \"inputs\": [\n {\n \"name\": \"sender\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"amount\",\n \"type\": \"uint256\",\n \"indexed\": false,\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"success\",\n \"type\": \"bool\",\n \"indexed\": false,\n \"internalType\": \"bool\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"SetDelegationManager\",\n \"inputs\": [\n {\n \"name\": \"newDelegationManager\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIDelegationManager\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"SetEntryPoint\",\n \"inputs\": [\n {\n \"name\": \"entryPoint\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIEntryPoint\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"TryExecuteUnsuccessful\",\n \"inputs\": [\n {\n \"name\": \"batchExecutionindex\",\n \"type\": \"uint256\",\n \"indexed\": false,\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"result\",\n \"type\": \"bytes\",\n \"indexed\": false,\n \"internalType\": \"bytes\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"error\",\n \"name\": \"ECDSAInvalidSignature\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"ECDSAInvalidSignatureLength\",\n \"inputs\": [\n {\n \"name\": \"length\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ]\n },\n {\n \"type\": \"error\",\n \"name\": \"ECDSAInvalidSignatureS\",\n \"inputs\": [\n {\n \"name\": \"s\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ]\n },\n {\n \"type\": \"error\",\n \"name\": \"ExecutionFailed\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidEIP712NameLength\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidEIP712VersionLength\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidShortString\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"NotDelegationManager\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"NotEntryPoint\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"NotEntryPointOrSelf\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"NotSelf\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"StringTooLong\",\n \"inputs\": [\n {\n \"name\": \"str\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ]\n },\n {\n \"type\": \"error\",\n \"name\": \"UnauthorizedCallContext\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"UnsupportedCallType\",\n \"inputs\": [\n {\n \"name\": \"callType\",\n \"type\": \"bytes1\",\n \"internalType\": \"CallType\"\n }\n ]\n },\n {\n \"type\": \"error\",\n \"name\": \"UnsupportedExecType\",\n \"inputs\": [\n {\n \"name\": \"execType\",\n \"type\": \"bytes1\",\n \"internalType\": \"ExecType\"\n }\n ]\n }\n]\n","/**\n * Contract interactions\n *\n * This module handles on-chain contract interactions using viem.\n *\n * Accepts viem's WalletClient and PublicClient directly, which abstract over both\n * local accounts (privateKeyToAccount) and external signers (MetaMask, etc.).\n *\n * @example\n * // CLI usage with private key\n * const { walletClient, publicClient } = createClients({ privateKey, rpcUrl, chainId });\n * await deployApp({ walletClient, publicClient, environmentConfig, ... }, logger);\n *\n * @example\n * // Browser usage with external wallet\n * const walletClient = createWalletClient({ chain, transport: custom(window.ethereum!) });\n * const publicClient = createPublicClient({ chain, transport: custom(window.ethereum!) });\n * await deployApp({ walletClient, publicClient, environmentConfig, ... }, logger);\n */\n\nimport { executeBatch, checkERC7702Delegation } from \"./eip7702\";\nimport {\n Address,\n Hex,\n encodeFunctionData,\n decodeErrorResult,\n bytesToHex,\n} from \"viem\";\nimport type { WalletClient, PublicClient } from \"viem\";\n\nimport { EnvironmentConfig, Logger, PreparedDeployData, PreparedUpgradeData } from \"../types\";\nimport { Release } from \"../types\";\nimport { getChainFromID } from \"../utils/helpers\";\n\nimport AppControllerABI from \"../abis/AppController.json\";\nimport PermissionControllerABI from \"../abis/PermissionController.json\";\n\n/**\n * Gas estimation result\n */\nexport interface GasEstimate {\n /** Estimated gas limit for the transaction */\n gasLimit: bigint;\n /** Max fee per gas (EIP-1559) */\n maxFeePerGas: bigint;\n /** Max priority fee per gas (EIP-1559) */\n maxPriorityFeePerGas: bigint;\n /** Maximum cost in wei (gasLimit * maxFeePerGas) */\n maxCostWei: bigint;\n /** Maximum cost formatted as ETH string */\n maxCostEth: string;\n}\n\n/**\n * Options for estimating transaction gas\n */\nexport interface EstimateGasOptions {\n publicClient: PublicClient;\n from: Address;\n to: Address;\n data: Hex;\n value?: bigint;\n}\n\n/**\n * Format Wei to ETH string\n */\nexport function formatETH(wei: bigint): string {\n const eth = Number(wei) / 1e18;\n const costStr = eth.toFixed(6);\n // Remove trailing zeros and decimal point if needed\n const trimmed = costStr.replace(/\\.?0+$/, \"\");\n // If result is \"0\", show \"<0.000001\" for small amounts\n if (trimmed === \"0\" && wei > 0n) {\n return \"<0.000001\";\n }\n return trimmed;\n}\n\n/**\n * Estimate gas cost for a transaction\n *\n * Use this to get cost estimate before prompting user for confirmation.\n */\nexport async function estimateTransactionGas(options: EstimateGasOptions): Promise<GasEstimate> {\n const { publicClient, from, to, data, value = 0n } = options;\n\n // Get current gas prices\n const fees = await publicClient.estimateFeesPerGas();\n\n // Estimate gas for the transaction\n const gasLimit = await publicClient.estimateGas({\n account: from,\n to,\n data,\n value,\n });\n\n const maxFeePerGas = fees.maxFeePerGas;\n const maxPriorityFeePerGas = fees.maxPriorityFeePerGas;\n const maxCostWei = gasLimit * maxFeePerGas;\n const maxCostEth = formatETH(maxCostWei);\n\n return {\n gasLimit,\n maxFeePerGas,\n maxPriorityFeePerGas,\n maxCostWei,\n maxCostEth,\n };\n}\n\n/**\n * Deploy app options\n */\nexport interface DeployAppOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n salt: Uint8Array;\n release: Release;\n publicLogs: boolean;\n imageRef: string;\n gas?: GasEstimate;\n}\n\n/**\n * Options for calculateAppID\n */\nexport interface CalculateAppIDOptions {\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n ownerAddress: Address;\n salt: Uint8Array;\n}\n\n/**\n * Prepared deploy batch ready for gas estimation and execution\n */\nexport interface PreparedDeployBatch {\n /** The app ID that will be deployed */\n appId: Address;\n /** The salt used for deployment */\n salt: Uint8Array;\n /** Batch executions to be sent */\n executions: Array<{ target: Address; value: bigint; callData: Hex }>;\n /** Wallet client for sending transaction */\n walletClient: WalletClient;\n /** Public client for reading chain state */\n publicClient: PublicClient;\n /** Environment configuration */\n environmentConfig: EnvironmentConfig;\n}\n\n/**\n * Prepared upgrade batch ready for gas estimation and execution\n */\nexport interface PreparedUpgradeBatch {\n /** The app ID being upgraded */\n appId: Address;\n /** Batch executions to be sent */\n executions: Array<{ target: Address; value: bigint; callData: Hex }>;\n /** Wallet client for sending transaction */\n walletClient: WalletClient;\n /** Public client for reading chain state */\n publicClient: PublicClient;\n /** Environment configuration */\n environmentConfig: EnvironmentConfig;\n}\n\n/**\n * Calculate app ID from owner address and salt\n */\nexport async function calculateAppID(options: CalculateAppIDOptions): Promise<Address> {\n const { publicClient, environmentConfig, ownerAddress, salt } = options;\n\n // Ensure salt is properly formatted as hex string (32 bytes = 64 hex chars)\n // bytesToHex returns 0x-prefixed string, slice(2) removes the prefix for padding\n const saltHexString = bytesToHex(salt).slice(2);\n // Pad to 64 characters if needed\n const paddedSaltHex = saltHexString.padStart(64, \"0\");\n const saltHex = `0x${paddedSaltHex}` as Hex;\n\n const appID = await publicClient.readContract({\n address: environmentConfig.appControllerAddress as Address,\n abi: AppControllerABI,\n functionName: \"calculateAppId\",\n args: [ownerAddress, saltHex],\n });\n\n return appID as Address;\n}\n\n/**\n * Options for preparing a deploy batch\n */\nexport interface PrepareDeployBatchOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n salt: Uint8Array;\n release: Release;\n publicLogs: boolean;\n imageRef: string;\n}\n\n/**\n * Prepare deploy batch - creates executions without sending transaction\n *\n * Use this to get the prepared batch for gas estimation before executing.\n */\nexport async function prepareDeployBatch(\n options: PrepareDeployBatchOptions,\n logger: Logger,\n): Promise<PreparedDeployBatch> {\n const { walletClient, publicClient, environmentConfig, salt, release, publicLogs } = options;\n\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n // 1. Calculate app ID\n logger.info(\"Calculating app ID...\");\n const appId = await calculateAppID({\n publicClient,\n environmentConfig,\n ownerAddress: account.address,\n salt,\n });\n\n // Verify the app ID calculation matches what createApp will deploy\n logger.debug(`App ID calculated: ${appId}`);\n logger.debug(`This address will be used for acceptAdmin call`);\n\n // 2. Pack create app call\n const saltHexString = bytesToHex(salt).slice(2);\n const paddedSaltHex = saltHexString.padStart(64, \"0\");\n const saltHex = `0x${paddedSaltHex}` as Hex;\n\n // Convert Release Uint8Array values to hex strings for viem\n const releaseForViem = {\n rmsRelease: {\n artifacts: release.rmsRelease.artifacts.map((artifact) => ({\n digest: `0x${bytesToHex(artifact.digest).slice(2).padStart(64, \"0\")}` as Hex,\n registry: artifact.registry,\n })),\n upgradeByTime: release.rmsRelease.upgradeByTime,\n },\n publicEnv: bytesToHex(release.publicEnv) as Hex,\n encryptedEnv: bytesToHex(release.encryptedEnv) as Hex,\n };\n\n const createData = encodeFunctionData({\n abi: AppControllerABI,\n functionName: \"createApp\",\n args: [saltHex, releaseForViem],\n });\n\n // 3. Pack accept admin call\n const acceptAdminData = encodeFunctionData({\n abi: PermissionControllerABI,\n functionName: \"acceptAdmin\",\n args: [appId],\n });\n\n // 4. Assemble executions\n // CRITICAL: Order matters! createApp must complete first\n const executions: Array<{\n target: Address;\n value: bigint;\n callData: Hex;\n }> = [\n {\n target: environmentConfig.appControllerAddress,\n value: 0n,\n callData: createData,\n },\n {\n target: environmentConfig.permissionControllerAddress as Address,\n value: 0n,\n callData: acceptAdminData,\n },\n ];\n\n // 5. Add public logs permission if requested\n if (publicLogs) {\n const anyoneCanViewLogsData = encodeFunctionData({\n abi: PermissionControllerABI,\n functionName: \"setAppointee\",\n args: [\n appId,\n \"0x493219d9949348178af1f58740655951a8cd110c\" as Address, // AnyoneCanCallAddress\n \"0x57ee1fb74c1087e26446abc4fb87fd8f07c43d8d\" as Address, // ApiPermissionsTarget\n \"0x2fd3f2fe\" as Hex, // CanViewAppLogsPermission\n ],\n });\n executions.push({\n target: environmentConfig.permissionControllerAddress as Address,\n value: 0n,\n callData: anyoneCanViewLogsData,\n });\n }\n\n return {\n appId,\n salt,\n executions,\n walletClient,\n publicClient,\n environmentConfig,\n };\n}\n\n/**\n * Execute a prepared deploy batch\n */\nexport async function executeDeployBatch(\n data: PreparedDeployData,\n context: {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n },\n gas: GasEstimate | undefined,\n logger: Logger,\n): Promise<{ appId: Address; txHash: Hex }> {\n const pendingMessage = \"Deploying new app...\";\n\n const txHash = await executeBatch(\n {\n walletClient: context.walletClient,\n publicClient: context.publicClient,\n environmentConfig: context.environmentConfig,\n executions: data.executions,\n pendingMessage,\n gas,\n },\n logger,\n );\n\n return { appId: data.appId, txHash };\n}\n\n/**\n * Deploy app on-chain (convenience wrapper that prepares and executes)\n */\nexport async function deployApp(\n options: DeployAppOptions,\n logger: Logger,\n): Promise<{ appId: Address; txHash: Hex }> {\n const prepared = await prepareDeployBatch(options, logger);\n\n // Extract data and context from prepared batch\n const data: PreparedDeployData = {\n appId: prepared.appId,\n salt: prepared.salt,\n executions: prepared.executions,\n };\n const context = {\n walletClient: prepared.walletClient,\n publicClient: prepared.publicClient,\n environmentConfig: prepared.environmentConfig,\n };\n\n return executeDeployBatch(data, context, options.gas, logger);\n}\n\n/**\n * Upgrade app options\n */\nexport interface UpgradeAppOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n appID: Address;\n release: Release;\n publicLogs: boolean;\n needsPermissionChange: boolean;\n imageRef: string;\n gas?: GasEstimate;\n}\n\n/**\n * Options for preparing an upgrade batch\n */\nexport interface PrepareUpgradeBatchOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n appID: Address;\n release: Release;\n publicLogs: boolean;\n needsPermissionChange: boolean;\n imageRef: string;\n}\n\n/**\n * Prepare upgrade batch - creates executions without sending transaction\n *\n * Use this to get the prepared batch for gas estimation before executing.\n */\nexport async function prepareUpgradeBatch(\n options: PrepareUpgradeBatchOptions,\n): Promise<PreparedUpgradeBatch> {\n const { walletClient, publicClient, environmentConfig, appID, release, publicLogs, needsPermissionChange } = options;\n\n // 1. Pack upgrade app call\n // Convert Release Uint8Array values to hex strings for viem\n const releaseForViem = {\n rmsRelease: {\n artifacts: release.rmsRelease.artifacts.map((artifact) => ({\n digest: `0x${bytesToHex(artifact.digest).slice(2).padStart(64, \"0\")}` as Hex,\n registry: artifact.registry,\n })),\n upgradeByTime: release.rmsRelease.upgradeByTime,\n },\n publicEnv: bytesToHex(release.publicEnv) as Hex,\n encryptedEnv: bytesToHex(release.encryptedEnv) as Hex,\n };\n\n const upgradeData = encodeFunctionData({\n abi: AppControllerABI,\n functionName: \"upgradeApp\",\n args: [appID, releaseForViem],\n });\n\n // 2. Start with upgrade execution\n const executions: Array<{\n target: Address;\n value: bigint;\n callData: Hex;\n }> = [\n {\n target: environmentConfig.appControllerAddress,\n value: 0n,\n callData: upgradeData,\n },\n ];\n\n // 3. Add permission transaction if needed\n if (needsPermissionChange) {\n if (publicLogs) {\n // Add public permission (private→public)\n const addLogsData = encodeFunctionData({\n abi: PermissionControllerABI,\n functionName: \"setAppointee\",\n args: [\n appID,\n \"0x493219d9949348178af1f58740655951a8cd110c\" as Address, // AnyoneCanCallAddress\n \"0x57ee1fb74c1087e26446abc4fb87fd8f07c43d8d\" as Address, // ApiPermissionsTarget\n \"0x2fd3f2fe\" as Hex, // CanViewAppLogsPermission\n ],\n });\n executions.push({\n target: environmentConfig.permissionControllerAddress as Address,\n value: 0n,\n callData: addLogsData,\n });\n } else {\n // Remove public permission (public→private)\n const removeLogsData = encodeFunctionData({\n abi: PermissionControllerABI,\n functionName: \"removeAppointee\",\n args: [\n appID,\n \"0x493219d9949348178af1f58740655951a8cd110c\" as Address, // AnyoneCanCallAddress\n \"0x57ee1fb74c1087e26446abc4fb87fd8f07c43d8d\" as Address, // ApiPermissionsTarget\n \"0x2fd3f2fe\" as Hex, // CanViewAppLogsPermission\n ],\n });\n executions.push({\n target: environmentConfig.permissionControllerAddress as Address,\n value: 0n,\n callData: removeLogsData,\n });\n }\n }\n\n return {\n appId: appID,\n executions,\n walletClient,\n publicClient,\n environmentConfig,\n };\n}\n\n/**\n * Execute a prepared upgrade batch\n */\nexport async function executeUpgradeBatch(\n data: PreparedUpgradeData,\n context: {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n },\n gas: GasEstimate | undefined,\n logger: Logger,\n): Promise<Hex> {\n const pendingMessage = `Upgrading app ${data.appId}...`;\n\n const txHash = await executeBatch(\n {\n walletClient: context.walletClient,\n publicClient: context.publicClient,\n environmentConfig: context.environmentConfig,\n executions: data.executions,\n pendingMessage,\n gas,\n },\n logger,\n );\n\n return txHash;\n}\n\n/**\n * Upgrade app on-chain (convenience wrapper that prepares and executes)\n */\nexport async function upgradeApp(options: UpgradeAppOptions, logger: Logger): Promise<Hex> {\n const prepared = await prepareUpgradeBatch(options);\n\n // Extract data and context from prepared batch\n const data: PreparedUpgradeData = {\n appId: prepared.appId,\n executions: prepared.executions,\n };\n const context = {\n walletClient: prepared.walletClient,\n publicClient: prepared.publicClient,\n environmentConfig: prepared.environmentConfig,\n };\n\n return executeUpgradeBatch(data, context, options.gas, logger);\n}\n\n/**\n * Send and wait for transaction with confirmation support\n */\nexport interface SendTransactionOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n to: Address;\n data: Hex;\n value?: bigint;\n pendingMessage: string;\n txDescription: string;\n gas?: GasEstimate;\n}\n\nexport async function sendAndWaitForTransaction(\n options: SendTransactionOptions,\n logger: Logger,\n): Promise<Hex> {\n const { walletClient, publicClient, environmentConfig, to, data, value = 0n, pendingMessage, txDescription, gas } = options;\n\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n const chain = getChainFromID(environmentConfig.chainID);\n\n // Show pending message if provided\n if (pendingMessage) {\n logger.info(`\\n${pendingMessage}`);\n }\n\n // Send transaction with optional gas params\n const hash = await walletClient.sendTransaction({\n account,\n to,\n data,\n value,\n ...(gas?.maxFeePerGas && { maxFeePerGas: gas.maxFeePerGas }),\n ...(gas?.maxPriorityFeePerGas && {\n maxPriorityFeePerGas: gas.maxPriorityFeePerGas,\n }),\n chain,\n });\n\n logger.info(`Transaction sent: ${hash}`);\n\n // Wait for receipt\n const receipt = await publicClient.waitForTransactionReceipt({ hash });\n\n if (receipt.status === \"reverted\") {\n let revertReason = \"Unknown reason\";\n try {\n await publicClient.call({\n to,\n data,\n account: account.address,\n });\n } catch (callError: any) {\n if (callError.data) {\n try {\n const decoded = decodeErrorResult({\n abi: AppControllerABI,\n data: callError.data,\n });\n const formattedError = formatAppControllerError(decoded);\n revertReason = formattedError.message;\n } catch {\n revertReason = callError.message || \"Unknown reason\";\n }\n } else {\n revertReason = callError.message || \"Unknown reason\";\n }\n }\n logger.error(`${txDescription} transaction (hash: ${hash}) reverted: ${revertReason}`);\n throw new Error(`${txDescription} transaction (hash: ${hash}) reverted: ${revertReason}`);\n }\n\n return hash;\n}\n\n/**\n * Format AppController errors to user-friendly messages\n */\nfunction formatAppControllerError(decoded: {\n errorName: string;\n args?: readonly unknown[];\n}): Error {\n const errorName = decoded.errorName;\n\n switch (errorName) {\n case \"MaxActiveAppsExceeded\":\n return new Error(\n \"you have reached your app deployment limit. To request access or increase your limit, please visit https://onboarding.eigencloud.xyz/ or reach out to the Eigen team\",\n );\n case \"GlobalMaxActiveAppsExceeded\":\n return new Error(\n \"the platform has reached the maximum number of active apps. please try again later\",\n );\n case \"InvalidPermissions\":\n return new Error(\"you don't have permission to perform this operation\");\n case \"AppAlreadyExists\":\n return new Error(\"an app with this owner and salt already exists\");\n case \"AppDoesNotExist\":\n return new Error(\"the specified app does not exist\");\n case \"InvalidAppStatus\":\n return new Error(\"the app is in an invalid state for this operation\");\n case \"MoreThanOneArtifact\":\n return new Error(\"only one artifact is allowed per release\");\n case \"InvalidSignature\":\n return new Error(\"invalid signature provided\");\n case \"SignatureExpired\":\n return new Error(\"the provided signature has expired\");\n case \"InvalidReleaseMetadataURI\":\n return new Error(\"invalid release metadata URI provided\");\n case \"InvalidShortString\":\n return new Error(\"invalid short string format\");\n default:\n return new Error(`contract error: ${errorName}`);\n }\n}\n\n/**\n * Get active app count for a user\n */\nexport async function getActiveAppCount(\n publicClient: PublicClient,\n environmentConfig: EnvironmentConfig,\n user: Address,\n): Promise<number> {\n const count = await publicClient.readContract({\n address: environmentConfig.appControllerAddress,\n abi: AppControllerABI,\n functionName: \"getActiveAppCount\",\n args: [user],\n });\n\n return Number(count);\n}\n\n/**\n * Get max active apps per user (quota limit)\n */\nexport async function getMaxActiveAppsPerUser(\n publicClient: PublicClient,\n environmentConfig: EnvironmentConfig,\n user: Address,\n): Promise<number> {\n const quota = await publicClient.readContract({\n address: environmentConfig.appControllerAddress,\n abi: AppControllerABI,\n functionName: \"getMaxActiveAppsPerUser\",\n args: [user],\n });\n\n return Number(quota);\n}\n\n/**\n * Get apps by creator (paginated)\n */\nexport interface AppConfig {\n release: any; // Release struct from contract\n status: number; // AppStatus enum\n}\n\nexport async function getAppsByCreator(\n publicClient: PublicClient,\n environmentConfig: EnvironmentConfig,\n creator: Address,\n offset: bigint,\n limit: bigint,\n): Promise<{ apps: Address[]; appConfigs: AppConfig[] }> {\n const result = (await publicClient.readContract({\n address: environmentConfig.appControllerAddress,\n abi: AppControllerABI,\n functionName: \"getAppsByCreator\",\n args: [creator, offset, limit],\n })) as [Address[], AppConfig[]];\n\n // Result is a tuple: [Address[], AppConfig[]]\n return {\n apps: result[0],\n appConfigs: result[1],\n };\n}\n\n/**\n * Get apps by developer\n */\nexport async function getAppsByDeveloper(\n publicClient: PublicClient,\n environmentConfig: EnvironmentConfig,\n developer: Address,\n offset: bigint,\n limit: bigint,\n): Promise<{ apps: Address[]; appConfigs: AppConfig[] }> {\n const result = (await publicClient.readContract({\n address: environmentConfig.appControllerAddress,\n abi: AppControllerABI,\n functionName: \"getAppsByDeveloper\",\n args: [developer, offset, limit],\n })) as [Address[], AppConfig[]];\n\n // Result is a tuple: [Address[], AppConfig[]]\n return {\n apps: result[0],\n appConfigs: result[1],\n };\n}\n\n/**\n * Fetch all apps by a developer by auto-pagination\n */\nexport async function getAllAppsByDeveloper(\n publicClient: PublicClient,\n env: EnvironmentConfig,\n developer: Address,\n pageSize: bigint = 100n,\n): Promise<{ apps: Address[]; appConfigs: AppConfig[] }> {\n let offset = 0n;\n const allApps: Address[] = [];\n const allConfigs: AppConfig[] = [];\n\n while (true) {\n const { apps, appConfigs } = await getAppsByDeveloper(publicClient, env, developer, offset, pageSize);\n\n if (apps.length === 0) break;\n\n allApps.push(...apps);\n allConfigs.push(...appConfigs);\n\n if (apps.length < Number(pageSize)) break;\n\n offset += pageSize;\n }\n\n return {\n apps: allApps,\n appConfigs: allConfigs,\n };\n}\n\n/**\n * Get latest release block numbers for multiple apps\n */\nexport async function getAppLatestReleaseBlockNumbers(\n publicClient: PublicClient,\n environmentConfig: EnvironmentConfig,\n appIDs: Address[],\n): Promise<Map<Address, number>> {\n // Fetch block numbers in parallel\n const results = await Promise.all(\n appIDs.map((appID) =>\n publicClient\n .readContract({\n address: environmentConfig.appControllerAddress,\n abi: AppControllerABI,\n functionName: \"getAppLatestReleaseBlockNumber\",\n args: [appID],\n })\n .catch(() => null),\n ),\n );\n\n const blockNumbers = new Map<Address, number>();\n for (let i = 0; i < appIDs.length; i++) {\n const result = results[i];\n if (result !== null && result !== undefined) {\n blockNumbers.set(appIDs[i], Number(result));\n }\n }\n\n return blockNumbers;\n}\n\n/**\n * Get block timestamps for multiple block numbers\n */\nexport async function getBlockTimestamps(\n publicClient: PublicClient,\n blockNumbers: number[],\n): Promise<Map<number, number>> {\n // Deduplicate block numbers\n const uniqueBlockNumbers = [...new Set(blockNumbers)].filter((n) => n > 0);\n\n const timestamps = new Map<number, number>();\n\n // Fetch blocks in parallel\n const blocks = await Promise.all(\n uniqueBlockNumbers.map((blockNumber) =>\n publicClient.getBlock({ blockNumber: BigInt(blockNumber) }).catch(() => null),\n ),\n );\n\n for (let i = 0; i < uniqueBlockNumbers.length; i++) {\n const block = blocks[i];\n if (block) {\n timestamps.set(uniqueBlockNumbers[i], Number(block.timestamp));\n }\n }\n\n return timestamps;\n}\n\n/**\n * Suspend options\n */\nexport interface SuspendOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n account: Address;\n apps: Address[];\n}\n\n/**\n * Suspend apps for an account\n */\nexport async function suspend(options: SuspendOptions, logger: Logger): Promise<Hex | false> {\n const { walletClient, publicClient, environmentConfig, account, apps } = options;\n\n const suspendData = encodeFunctionData({\n abi: AppControllerABI,\n functionName: \"suspend\",\n args: [account, apps],\n });\n\n const pendingMessage = `Suspending ${apps.length} app(s)...`;\n\n return sendAndWaitForTransaction({\n walletClient,\n publicClient,\n environmentConfig,\n to: environmentConfig.appControllerAddress as Address,\n data: suspendData,\n pendingMessage,\n txDescription: \"Suspend\",\n }, logger);\n}\n\n/**\n * Options for checking delegation status\n */\nexport interface IsDelegatedOptions {\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n address: Address;\n}\n\n/**\n * Check if account is delegated to the ERC-7702 delegator\n */\nexport async function isDelegated(options: IsDelegatedOptions): Promise<boolean> {\n const { publicClient, environmentConfig, address } = options;\n\n return checkERC7702Delegation(\n publicClient,\n address,\n environmentConfig.erc7702DelegatorAddress as Address,\n );\n}\n\n/**\n * Undelegate options\n */\nexport interface UndelegateOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n}\n\n/**\n * Undelegate account (removes EIP-7702 delegation)\n */\nexport async function undelegate(options: UndelegateOptions, logger: Logger): Promise<Hex> {\n const { walletClient, publicClient, environmentConfig } = options;\n\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n const chain = getChainFromID(environmentConfig.chainID);\n\n // Create authorization to undelegate (empty address = undelegate)\n const transactionNonce = await publicClient.getTransactionCount({\n address: account.address,\n blockTag: \"pending\",\n });\n\n const chainId = await publicClient.getChainId();\n const authorizationNonce = BigInt(transactionNonce) + 1n;\n\n logger.debug(\"Signing undelegate authorization\");\n\n const signedAuthorization = await walletClient.signAuthorization({\n contractAddress: \"0x0000000000000000000000000000000000000000\" as Address,\n chainId: chainId,\n nonce: Number(authorizationNonce),\n account: account,\n });\n\n const authorizationList = [signedAuthorization];\n\n // Send transaction with authorization list\n const hash = await walletClient.sendTransaction({\n account,\n to: account.address, // Send to self\n data: \"0x\" as Hex, // Empty data\n value: 0n,\n authorizationList,\n chain,\n });\n\n logger.info(`Transaction sent: ${hash}`);\n\n const receipt = await publicClient.waitForTransactionReceipt({ hash });\n\n if (receipt.status === \"reverted\") {\n logger.error(`Undelegate transaction (hash: ${hash}) reverted`);\n throw new Error(`Undelegate transaction (hash: ${hash}) reverted`);\n }\n\n return hash;\n}\n","[\n {\n \"type\": \"constructor\",\n \"inputs\": [\n {\n \"name\": \"_version\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n },\n {\n \"name\": \"_permissionController\",\n \"type\": \"address\",\n \"internalType\": \"contractIPermissionController\"\n },\n {\n \"name\": \"_releaseManager\",\n \"type\": \"address\",\n \"internalType\": \"contractIReleaseManager\"\n },\n {\n \"name\": \"_computeAVSRegistrar\",\n \"type\": \"address\",\n \"internalType\": \"contractIComputeAVSRegistrar\"\n },\n {\n \"name\": \"_computeOperator\",\n \"type\": \"address\",\n \"internalType\": \"contractIComputeOperator\"\n },\n {\n \"name\": \"_appBeacon\",\n \"type\": \"address\",\n \"internalType\": \"contractIBeacon\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"API_PERMISSION_TYPEHASH\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"appBeacon\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIBeacon\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"calculateApiPermissionDigestHash\",\n \"inputs\": [\n {\n \"name\": \"permission\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n },\n {\n \"name\": \"expiry\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"calculateAppId\",\n \"inputs\": [\n {\n \"name\": \"deployer\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"salt\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"computeAVSRegistrar\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIComputeAVSRegistrar\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"computeOperator\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIComputeOperator\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"createApp\",\n \"inputs\": [\n {\n \"name\": \"salt\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"release\",\n \"type\": \"tuple\",\n \"internalType\": \"structIAppController.Release\",\n \"components\": [\n {\n \"name\": \"rmsRelease\",\n \"type\": \"tuple\",\n \"internalType\": \"structIReleaseManagerTypes.Release\",\n \"components\": [\n {\n \"name\": \"artifacts\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structIReleaseManagerTypes.Artifact[]\",\n \"components\": [\n {\n \"name\": \"digest\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"registry\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ]\n },\n {\n \"name\": \"upgradeByTime\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ]\n },\n {\n \"name\": \"publicEnv\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"encryptedEnv\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"domainSeparator\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getActiveAppCount\",\n \"inputs\": [\n {\n \"name\": \"user\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppCreator\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppLatestReleaseBlockNumber\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppOperatorSetId\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppStatus\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint8\",\n \"internalType\": \"enumIAppController.AppStatus\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getApps\",\n \"inputs\": [\n {\n \"name\": \"offset\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"limit\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"apps\",\n \"type\": \"address[]\",\n \"internalType\": \"contractIApp[]\"\n },\n {\n \"name\": \"appConfigsMem\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structIAppController.AppConfig[]\",\n \"components\": [\n {\n \"name\": \"creator\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"operatorSetId\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n },\n {\n \"name\": \"latestReleaseBlockNumber\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n },\n {\n \"name\": \"status\",\n \"type\": \"uint8\",\n \"internalType\": \"enumIAppController.AppStatus\"\n }\n ]\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppsByCreator\",\n \"inputs\": [\n {\n \"name\": \"creator\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"offset\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"limit\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"apps\",\n \"type\": \"address[]\",\n \"internalType\": \"contractIApp[]\"\n },\n {\n \"name\": \"appConfigsMem\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structIAppController.AppConfig[]\",\n \"components\": [\n {\n \"name\": \"creator\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"operatorSetId\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n },\n {\n \"name\": \"latestReleaseBlockNumber\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n },\n {\n \"name\": \"status\",\n \"type\": \"uint8\",\n \"internalType\": \"enumIAppController.AppStatus\"\n }\n ]\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppsByDeveloper\",\n \"inputs\": [\n {\n \"name\": \"developer\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"offset\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"limit\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"apps\",\n \"type\": \"address[]\",\n \"internalType\": \"contractIApp[]\"\n },\n {\n \"name\": \"appConfigsMem\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structIAppController.AppConfig[]\",\n \"components\": [\n {\n \"name\": \"creator\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"operatorSetId\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n },\n {\n \"name\": \"latestReleaseBlockNumber\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n },\n {\n \"name\": \"status\",\n \"type\": \"uint8\",\n \"internalType\": \"enumIAppController.AppStatus\"\n }\n ]\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getMaxActiveAppsPerUser\",\n \"inputs\": [\n {\n \"name\": \"user\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"globalActiveAppCount\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"initialize\",\n \"inputs\": [\n {\n \"name\": \"admin\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"maxGlobalActiveApps\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"permissionController\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIPermissionController\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"releaseManager\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIReleaseManager\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"setMaxActiveAppsPerUser\",\n \"inputs\": [\n {\n \"name\": \"user\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"limit\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"setMaxGlobalActiveApps\",\n \"inputs\": [\n {\n \"name\": \"limit\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"startApp\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"stopApp\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"suspend\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"apps\",\n \"type\": \"address[]\",\n \"internalType\": \"contractIApp[]\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"terminateApp\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"terminateAppByAdmin\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"updateAppMetadataURI\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n },\n {\n \"name\": \"metadataURI\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"upgradeApp\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n },\n {\n \"name\": \"release\",\n \"type\": \"tuple\",\n \"internalType\": \"structIAppController.Release\",\n \"components\": [\n {\n \"name\": \"rmsRelease\",\n \"type\": \"tuple\",\n \"internalType\": \"structIReleaseManagerTypes.Release\",\n \"components\": [\n {\n \"name\": \"artifacts\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structIReleaseManagerTypes.Artifact[]\",\n \"components\": [\n {\n \"name\": \"digest\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"registry\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ]\n },\n {\n \"name\": \"upgradeByTime\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ]\n },\n {\n \"name\": \"publicEnv\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"encryptedEnv\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"version\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"event\",\n \"name\": \"AppCreated\",\n \"inputs\": [\n {\n \"name\": \"creator\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n },\n {\n \"name\": \"operatorSetId\",\n \"type\": \"uint32\",\n \"indexed\": false,\n \"internalType\": \"uint32\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppMetadataURIUpdated\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n },\n {\n \"name\": \"metadataURI\",\n \"type\": \"string\",\n \"indexed\": false,\n \"internalType\": \"string\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppStarted\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppStopped\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppSuspended\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppTerminated\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppTerminatedByAdmin\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppUpgraded\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n },\n {\n \"name\": \"rmsReleaseId\",\n \"type\": \"uint256\",\n \"indexed\": false,\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"release\",\n \"type\": \"tuple\",\n \"indexed\": false,\n \"internalType\": \"structIAppController.Release\",\n \"components\": [\n {\n \"name\": \"rmsRelease\",\n \"type\": \"tuple\",\n \"internalType\": \"structIReleaseManagerTypes.Release\",\n \"components\": [\n {\n \"name\": \"artifacts\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structIReleaseManagerTypes.Artifact[]\",\n \"components\": [\n {\n \"name\": \"digest\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"registry\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ]\n },\n {\n \"name\": \"upgradeByTime\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ]\n },\n {\n \"name\": \"publicEnv\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"encryptedEnv\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"GlobalMaxActiveAppsSet\",\n \"inputs\": [\n {\n \"name\": \"limit\",\n \"type\": \"uint32\",\n \"indexed\": false,\n \"internalType\": \"uint32\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"Initialized\",\n \"inputs\": [\n {\n \"name\": \"version\",\n \"type\": \"uint8\",\n \"indexed\": false,\n \"internalType\": \"uint8\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"MaxActiveAppsSet\",\n \"inputs\": [\n {\n \"name\": \"user\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"limit\",\n \"type\": \"uint32\",\n \"indexed\": false,\n \"internalType\": \"uint32\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"error\",\n \"name\": \"AccountHasActiveApps\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"AppAlreadyExists\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"AppDoesNotExist\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"GlobalMaxActiveAppsExceeded\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidAppStatus\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidPermissions\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidReleaseMetadataURI\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidShortString\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidSignature\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"MaxActiveAppsExceeded\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"MoreThanOneArtifact\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"SignatureExpired\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"StringTooLong\",\n \"inputs\": [\n {\n \"name\": \"str\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ]\n }\n]\n","/**\n * Browser-safe app action encoders\n *\n * These functions encode calldata for app lifecycle operations.\n * They only depend on viem and are safe to use in browser environments.\n */\n\nimport { parseAbi, encodeFunctionData } from \"viem\";\nimport type { AppId } from \"../types\";\n\n// Minimal ABI for app lifecycle operations\nconst CONTROLLER_ABI = parseAbi([\n \"function startApp(address appId)\",\n \"function stopApp(address appId)\",\n \"function terminateApp(address appId)\",\n]);\n\n/**\n * Encode start app call data for gas estimation or transaction\n */\nexport function encodeStartAppData(appId: AppId): `0x${string}` {\n return encodeFunctionData({\n abi: CONTROLLER_ABI,\n functionName: \"startApp\",\n args: [appId],\n });\n}\n\n/**\n * Encode stop app call data for gas estimation or transaction\n */\nexport function encodeStopAppData(appId: AppId): `0x${string}` {\n return encodeFunctionData({\n abi: CONTROLLER_ABI,\n functionName: \"stopApp\",\n args: [appId],\n });\n}\n\n/**\n * Encode terminate app call data for gas estimation or transaction\n */\nexport function encodeTerminateAppData(appId: AppId): `0x${string}` {\n return encodeFunctionData({\n abi: CONTROLLER_ABI,\n functionName: \"terminateApp\",\n args: [appId],\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOO,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AAGzB,IAAM,kBAA0C;AAAA,EACrD,kBAAkB;AACpB;AAGO,IAAM,iBAAyD;AAAA,EACpE,CAAC,gBAAgB,GAAG;AAAA,IAClB,sBAAsB;AAAA,EACxB;A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M,CAAC,WAAW,QAAQ,KAAK;AAAA,EACjC,CAAC;AAGD,SAAO;AAAA,IACL,MAAM,OAAO,CAAC;AAAA,IACd,YAAY,OAAO,CAAC;AAAA,EACtB;AACF;AAKA,eAAsB,sBACpB,cACA,KACA,WACA,WAAmB,MACoC;AACvD,MAAI,SAAS;AACb,QAAM,UAAqB,CAAC;AAC5B,QAAM,aAA0B,CAAC;AAEjC,SAAO,MAAM;AACX,UAAM,EAAE,MAAM,WAAW,IAAI,MAAM,mBAAmB,cAAc,KAAK,WAAW,QAAQ,QAAQ;AAEpG,QAAI,KAAK,WAAW,EAAG;AAEvB,YAAQ,KAAK,GAAG,IAAI;AACpB,eAAW,KAAK,GAAG,UAAU;AAE7B,QAAI,KAAK,SAAS,OAAO,QAAQ,EAAG;AAEpC,cAAU;AAAA,EACZ;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,YAAY;AAAA,EACd;AACF;;;AErwBA,IAAAC,eAA6C;AAI7C,IAAM,qBAAiB,uBAAS;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAKM,SAAS,mBAAmB,OAA6B;AAC9D,aAAO,iCAAmB;AAAA,IACxB,KAAK;AAAA,IACL,cAAc;AAAA,IACd,MAAM,CAAC,KAAK;AAAA,EACd,CAAC;AACH;AAKO,SAAS,kBAAkB,OAA6B;AAC7D,aAAO,iCAAmB;AAAA,IACxB,KAAK;AAAA,IACL,cAAc;AAAA,IACd,MAAM,CAAC,KAAK;AAAA,EACd,CAAC;AACH;AAKO,SAAS,uBAAuB,OAA6B;AAClE,aAAO,iCAAmB;AAAA,IACxB,KAAK;AAAA,IACL,cAAc;AAAA,IACd,MAAM,CAAC,KAAK;AAAA,EACd,CAAC;AACH;","names":["import_viem","import_chains","import_accounts","import_viem","axios","import_viem","import_viem","import_viem"]}
1
+ {"version":3,"sources":["../src/client/common/auth/session.ts","../src/browser.ts","../src/client/common/types/index.ts","../src/client/common/config/environment.ts","../src/client/common/utils/validation.ts","../src/client/common/utils/helpers.ts","../src/client/common/constants.ts","../src/client/common/utils/billing.ts","../src/client/common/auth/generate.ts","../src/client/common/utils/userapi.ts","../src/client/common/utils/auth.ts","../src/client/common/utils/billingapi.ts","../src/client/common/auth/billingSession.ts","../src/client/common/utils/buildapi.ts","../src/client/common/contract/eip7702.ts","../src/client/common/abis/ERC7702Delegator.json","../src/client/common/contract/caller.ts","../src/client/common/abis/AppController.json","../src/client/common/abis/PermissionController.json","../src/client/common/contract/encoders.ts","../src/client/common/auth/siwe.ts","../src/client/common/hooks/useComputeSession.ts","../src/client/common/encryption/kms.ts","../keys/mainnet-alpha/prod/kms-encryption-public-key.pem","../keys/mainnet-alpha/prod/kms-signing-public-key.pem","../keys/sepolia/dev/kms-encryption-public-key.pem","../keys/sepolia/dev/kms-signing-public-key.pem","../keys/sepolia/prod/kms-encryption-public-key.pem","../keys/sepolia/prod/kms-signing-public-key.pem","../src/client/common/utils/keys.ts"],"sourcesContent":["/**\n * Compute API Session Management\n *\n * This module provides utilities for managing authentication sessions with the compute API\n * using SIWE (Sign-In with Ethereum).\n */\n\nimport { Address, Hex } from \"viem\";\n\nexport interface ComputeApiConfig {\n /** Base URL of the compute API (e.g., \"https://api.eigencloud.xyz\") */\n baseUrl: string;\n}\n\nexport interface SessionInfo {\n /** Whether the session is authenticated */\n authenticated: boolean;\n /** Authenticated wallet address (if authenticated) */\n address?: Address;\n /** Chain ID used for authentication (if authenticated) */\n chainId?: number;\n}\n\nexport interface LoginResult {\n /** Whether login was successful */\n success: boolean;\n /** Authenticated wallet address */\n address: Address;\n}\n\nexport interface LoginRequest {\n /** SIWE message string */\n message: string;\n /** Hex-encoded signature (with or without 0x prefix) */\n signature: Hex | string;\n}\n\n/**\n * Error thrown when session operations fail\n */\nexport class SessionError extends Error {\n constructor(\n message: string,\n public readonly code:\n | \"NETWORK_ERROR\"\n | \"INVALID_SIGNATURE\"\n | \"INVALID_MESSAGE\"\n | \"SESSION_EXPIRED\"\n | \"UNAUTHORIZED\"\n | \"UNKNOWN\",\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"SessionError\";\n }\n}\n\n/**\n * Strip 0x prefix from hex string if present\n */\nfunction stripHexPrefix(hex: string): string {\n return hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n}\n\n/**\n * Parse error response body\n */\nasync function parseErrorResponse(response: Response): Promise<string> {\n try {\n const data = (await response.json()) as { error?: string };\n return data.error || response.statusText;\n } catch {\n return response.statusText;\n }\n}\n\n/**\n * Login to the compute API using SIWE\n *\n * This establishes a session with the compute API by verifying the SIWE message\n * and signature. On success, a session cookie is set in the browser.\n *\n * @param config - Compute API configuration\n * @param request - Login request containing SIWE message and signature\n * @returns Login result with the authenticated address\n *\n * @example\n * ```typescript\n * import { createSiweMessage, loginToComputeApi } from \"@layr-labs/ecloud-sdk/browser\";\n *\n * const { message } = createSiweMessage({\n * address: userAddress,\n * chainId: 11155111,\n * domain: window.location.host,\n * uri: window.location.origin,\n * });\n *\n * const signature = await signMessageAsync({ message });\n * const result = await loginToComputeApi(\n * { baseUrl: \"https://api.eigencloud.xyz\" },\n * { message, signature }\n * );\n * ```\n */\nexport async function loginToComputeApi(\n config: ComputeApiConfig,\n request: LoginRequest,\n): Promise<LoginResult> {\n let response: Response;\n\n try {\n response = await fetch(`${config.baseUrl}/auth/siwe/login`, {\n method: \"POST\",\n credentials: \"include\", // Include cookies for session management\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n message: request.message,\n signature: stripHexPrefix(request.signature),\n }),\n });\n } catch (error) {\n throw new SessionError(\n `Network error connecting to ${config.baseUrl}: ${error instanceof Error ? error.message : String(error)}`,\n \"NETWORK_ERROR\",\n );\n }\n\n if (!response.ok) {\n const errorMessage = await parseErrorResponse(response);\n const status = response.status;\n\n if (status === 400) {\n if (errorMessage.toLowerCase().includes(\"siwe\")) {\n throw new SessionError(`Invalid SIWE message: ${errorMessage}`, \"INVALID_MESSAGE\", status);\n }\n throw new SessionError(`Bad request: ${errorMessage}`, \"INVALID_MESSAGE\", status);\n }\n\n if (status === 401) {\n throw new SessionError(`Invalid signature: ${errorMessage}`, \"INVALID_SIGNATURE\", status);\n }\n\n throw new SessionError(`Login failed: ${errorMessage}`, \"UNKNOWN\", status);\n }\n\n const data = (await response.json()) as { success: boolean; address: string };\n\n return {\n success: data.success,\n address: data.address as Address,\n };\n}\n\n/**\n * Get the current session status from the compute API\n *\n * @param config - Compute API configuration\n * @returns Session information including authentication status and address\n *\n * @example\n * ```typescript\n * const session = await getComputeApiSession({ baseUrl: \"https://api.eigencloud.xyz\" });\n * if (session.authenticated) {\n * console.log(`Logged in as ${session.address}`);\n * }\n * ```\n */\nexport async function getComputeApiSession(config: ComputeApiConfig): Promise<SessionInfo> {\n let response: Response;\n\n try {\n response = await fetch(`${config.baseUrl}/auth/session`, {\n method: \"GET\",\n credentials: \"include\", // Include cookies for session management\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n } catch {\n // Network error - return unauthenticated session\n return {\n authenticated: false,\n };\n }\n\n // If we get a 401, return unauthenticated session\n if (response.status === 401) {\n return {\n authenticated: false,\n };\n }\n\n if (!response.ok) {\n const errorMessage = await parseErrorResponse(response);\n throw new SessionError(`Failed to get session: ${errorMessage}`, \"UNKNOWN\", response.status);\n }\n\n const data = (await response.json()) as {\n authenticated: boolean;\n address?: string;\n chain_id?: number;\n };\n\n return {\n authenticated: data.authenticated,\n address: data.address as Address | undefined,\n chainId: data.chain_id,\n };\n}\n\n/**\n * Logout from the compute API\n *\n * This destroys the current session and clears the session cookie.\n *\n * @param config - Compute API configuration\n *\n * @example\n * ```typescript\n * await logoutFromComputeApi({ baseUrl: \"https://api.eigencloud.xyz\" });\n * ```\n */\nexport async function logoutFromComputeApi(config: ComputeApiConfig): Promise<void> {\n let response: Response;\n\n try {\n response = await fetch(`${config.baseUrl}/auth/logout`, {\n method: \"POST\",\n credentials: \"include\", // Include cookies for session management\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n } catch (error) {\n throw new SessionError(\n `Network error connecting to ${config.baseUrl}: ${error instanceof Error ? error.message : String(error)}`,\n \"NETWORK_ERROR\",\n );\n }\n\n // Ignore 401 errors during logout (already logged out)\n if (response.status === 401) {\n return;\n }\n\n if (!response.ok) {\n const errorMessage = await parseErrorResponse(response);\n throw new SessionError(`Logout failed: ${errorMessage}`, \"UNKNOWN\", response.status);\n }\n}\n\n/**\n * Check if a session is still valid (not expired)\n *\n * This is a convenience function that checks the session status\n * and returns a boolean.\n *\n * @param config - Compute API configuration\n * @returns True if session is authenticated, false otherwise\n */\nexport async function isSessionValid(config: ComputeApiConfig): Promise<boolean> {\n const session = await getComputeApiSession(config);\n return session.authenticated;\n}\n","/**\n * Browser-safe SDK entry point\n *\n * This module exports only code that can run in browser environments.\n * It excludes Node.js-only dependencies like:\n * - dockerode (Docker API)\n * - @napi-rs/keyring (OS keychain)\n * - fs operations (file system)\n * - @inquirer/prompts (CLI prompts)\n *\n * Use this entry point in React/Next.js/browser applications:\n * import { ... } from \"@layr-labs/ecloud-sdk/browser\"\n */\n\n// =============================================================================\n// Types (all browser-safe)\n// =============================================================================\nexport * from \"./client/common/types\";\n\n// =============================================================================\n// Environment Configuration (browser-safe)\n// =============================================================================\nexport {\n getEnvironmentConfig,\n getBillingEnvironmentConfig,\n getAvailableEnvironments,\n isEnvironmentAvailable,\n getBuildType,\n isMainnet,\n} from \"./client/common/config/environment\";\n\n// =============================================================================\n// Validation Utilities (browser-safe subset only)\n// Note: validateFilePath, validateImagePath, validateDeployParams, validateUpgradeParams\n// are excluded because they use fs/path Node.js modules\n// =============================================================================\nexport {\n // App name\n validateAppName,\n // Image reference\n validateImageReference,\n assertValidImageReference,\n extractAppNameFromImage,\n // Instance type\n validateInstanceTypeSKU,\n // Private key\n validatePrivateKeyFormat,\n assertValidPrivateKey,\n // URL validation\n validateURL,\n validateXURL,\n // Description\n validateDescription,\n // App ID\n validateAppID,\n // Log visibility\n validateLogVisibility,\n type LogVisibility,\n // Sanitization\n sanitizeString,\n sanitizeURL,\n sanitizeXURL,\n // Parameter validation (browser-safe ones only)\n validateCreateAppParams,\n validateLogsParams,\n type CreateAppParams,\n type LogsParams,\n} from \"./client/common/utils/validation\";\n\n// =============================================================================\n// Billing Utilities (browser-safe)\n// =============================================================================\nexport { isSubscriptionActive } from \"./client/common/utils/billing\";\n\n// =============================================================================\n// Key Generation (browser-safe - uses viem)\n// =============================================================================\nexport { generateNewPrivateKey, type GeneratedKey } from \"./client/common/auth/generate\";\n\n// =============================================================================\n// API Clients (browser-safe - use axios)\n// =============================================================================\nexport {\n UserApiClient,\n type UserApiClientOptions,\n type AppInfo,\n type AppProfileInfo,\n type AppMetrics,\n type AppInfoResponse,\n} from \"./client/common/utils/userapi\";\n\nexport { BillingApiClient, type BillingApiClientOptions } from \"./client/common/utils/billingapi\";\n\nexport { BuildApiClient, type BuildApiClientOptions } from \"./client/common/utils/buildapi\";\n\n// =============================================================================\n// Contract Read Operations (browser-safe)\n// =============================================================================\nexport {\n // Read operations\n getAllAppsByDeveloper,\n getAppsByCreator,\n getAppsByDeveloper,\n getActiveAppCount,\n getMaxActiveAppsPerUser,\n // Gas estimation\n estimateTransactionGas,\n formatETH,\n // Deploy operations\n prepareDeployBatch,\n executeDeployBatch,\n deployApp,\n calculateAppID,\n // Sequential deployment (non-EIP-7702 fallback for browser wallets)\n executeDeploySequential,\n supportsEIP7702,\n // EIP-5792 batched deployment (sendCalls - single wallet popup for multiple calls)\n executeDeployBatched,\n supportsEIP5792,\n // Upgrade operations\n prepareUpgradeBatch,\n executeUpgradeBatch,\n upgradeApp,\n // Transaction helpers\n sendAndWaitForTransaction,\n // Delegation\n isDelegated,\n suspend,\n undelegate,\n // Types\n type GasEstimate,\n type EstimateGasOptions,\n type AppConfig,\n type DeployAppOptions,\n type UpgradeAppOptions,\n type PrepareDeployBatchOptions,\n type PrepareUpgradeBatchOptions,\n type PreparedDeployBatch,\n type PreparedUpgradeBatch,\n type CalculateAppIDOptions,\n type SendTransactionOptions,\n type SuspendOptions,\n type UndelegateOptions,\n type IsDelegatedOptions,\n type ExecuteDeploySequentialOptions,\n type ExecuteDeployBatchedOptions,\n type BatchedDeployResult,\n} from \"./client/common/contract/caller\";\n\n// =============================================================================\n// EIP-7702 Batch Execution (browser-safe)\n// =============================================================================\nexport {\n estimateBatchGas,\n executeBatch,\n checkERC7702Delegation,\n type EstimateBatchGasOptions,\n type ExecuteBatchOptions,\n type Execution,\n} from \"./client/common/contract/eip7702\";\n\n// =============================================================================\n// App Action Encoders (browser-safe - pure viem encoding)\n// =============================================================================\nexport {\n encodeStartAppData,\n encodeStopAppData,\n encodeTerminateAppData,\n} from \"./client/common/contract/encoders\";\n\n// =============================================================================\n// SIWE (Sign-In with Ethereum) Utilities (browser-safe)\n// =============================================================================\nexport {\n createSiweMessage,\n parseSiweMessage,\n generateNonce,\n isSiweMessageExpired,\n isSiweMessageNotYetValid,\n type SiweMessageParams,\n type SiweMessageResult,\n} from \"./client/common/auth/siwe\";\n\n// =============================================================================\n// Compute API Session Management (browser-safe)\n// =============================================================================\nexport {\n loginToComputeApi,\n logoutFromComputeApi,\n getComputeApiSession,\n isSessionValid,\n SessionError,\n type ComputeApiConfig,\n type SessionInfo,\n type LoginResult,\n type LoginRequest,\n} from \"./client/common/auth/session\";\n\n// =============================================================================\n// Billing API Session Management (browser-safe)\n// =============================================================================\nexport {\n loginToBillingApi,\n logoutFromBillingApi,\n getBillingApiSession,\n isBillingSessionValid,\n loginToBothApis,\n logoutFromBothApis,\n BillingSessionError,\n type BillingApiConfig,\n type BillingSessionInfo,\n type BillingLoginResult,\n type BillingLoginRequest,\n} from \"./client/common/auth/billingSession\";\n\n// =============================================================================\n// React Hooks (requires React 18+ as peer dependency)\n// =============================================================================\nexport {\n useComputeSession,\n type UseComputeSessionConfig,\n type UseComputeSessionReturn,\n} from \"./client/common/hooks\";\n\n// =============================================================================\n// Helper Utilities (browser-safe)\n// =============================================================================\nexport {\n getChainFromID,\n addHexPrefix,\n stripHexPrefix,\n} from \"./client/common/utils/helpers\";\n\n// =============================================================================\n// No-op Logger (browser-safe)\n// =============================================================================\nexport { noopLogger } from \"./client/common/types\";\n\n// =============================================================================\n// KMS Encryption Utilities (browser-safe - uses jose library)\n// =============================================================================\nexport {\n encryptRSAOAEPAndAES256GCM,\n getAppProtectedHeaders,\n} from \"./client/common/encryption/kms\";\n\nexport { getKMSKeysForEnvironment } from \"./client/common/utils/keys\";\n\n// =============================================================================\n// Re-export common types\n// =============================================================================\nexport type Environment = \"sepolia\" | \"sepolia-dev\" | \"mainnet-alpha\";\n","/**\n * Core types for ECloud SDK\n */\n\nimport { Address, Hex } from \"viem\";\nimport { GasEstimate } from \"../contract/caller\";\n\nexport type AppId = Address;\n\nexport type logVisibility = \"public\" | \"private\" | \"off\";\n\nexport interface DeployAppOpts {\n /** App name - required */\n name: string;\n /** Path to Dockerfile (if building from Dockerfile) - either this or imageRef is required */\n dockerfile?: string;\n /** Path to .env file - optional */\n envFile?: string;\n /** Image reference (registry/path:tag) - either this or dockerfile is required */\n imageRef?: string;\n /** Instance type SKU - required */\n instanceType: string;\n /** Log visibility setting - required */\n logVisibility: logVisibility;\n /** Optional gas params from estimation */\n gas?: GasEstimate;\n}\n\nexport interface UpgradeAppOpts {\n /** Path to Dockerfile (if building from Dockerfile) - either this or imageRef is required */\n dockerfile?: string;\n /** Image reference (registry/path:tag) - either this or dockerfile is required */\n imageRef?: string;\n /** Path to .env file - optional */\n envFile?: string;\n /** Instance type SKU - required */\n instanceType: string;\n /** Log visibility setting - required */\n logVisibility: logVisibility;\n gas?: GasEstimate;\n}\n\n/** Options for prepareDeploy */\nexport interface PrepareDeployOpts {\n /** App name - required */\n name: string;\n /** Path to Dockerfile (if building from Dockerfile) */\n dockerfile?: string;\n /** Path to .env file - optional */\n envFile?: string;\n /** Image reference (registry/path:tag) */\n imageRef?: string;\n /** Instance type SKU - required */\n instanceType: string;\n /** Log visibility setting - required */\n logVisibility: logVisibility;\n /** Resource usage monitoring setting - optional */\n resourceUsageMonitoring?: \"enable\" | \"disable\";\n}\n\n/** Options for prepareUpgrade */\nexport interface PrepareUpgradeOpts {\n /** Path to Dockerfile (if building from Dockerfile) */\n dockerfile?: string;\n /** Image reference (registry/path:tag) */\n imageRef?: string;\n /** Path to .env file - optional */\n envFile?: string;\n /** Instance type SKU - required */\n instanceType: string;\n /** Log visibility setting - required */\n logVisibility: logVisibility;\n /** Resource usage monitoring setting - optional */\n resourceUsageMonitoring?: \"enable\" | \"disable\";\n}\n\n/** Options for prepareDeployFromVerifiableBuild */\nexport interface PrepareDeployFromVerifiableBuildOpts {\n /** App name - required */\n name: string;\n /** Image reference (registry/path:tag) - required */\n imageRef: string;\n /** Image digest (sha256:...) - required */\n imageDigest: string;\n /** Path to .env file - optional */\n envFile?: string;\n /** Instance type SKU - required */\n instanceType: string;\n /** Log visibility setting - required */\n logVisibility: logVisibility;\n /** Resource usage monitoring setting - optional */\n resourceUsageMonitoring?: \"enable\" | \"disable\";\n}\n\n/** Options for prepareUpgradeFromVerifiableBuild */\nexport interface PrepareUpgradeFromVerifiableBuildOpts {\n /** Image reference (registry/path:tag) - required */\n imageRef: string;\n /** Image digest (sha256:...) - required */\n imageDigest: string;\n /** Path to .env file - optional */\n envFile?: string;\n /** Instance type SKU - required */\n instanceType: string;\n /** Log visibility setting - required */\n logVisibility: logVisibility;\n /** Resource usage monitoring setting - optional */\n resourceUsageMonitoring?: \"enable\" | \"disable\";\n}\n\n/** Gas options for execute functions */\nexport interface GasOpts {\n maxFeePerGas?: bigint;\n maxPriorityFeePerGas?: bigint;\n}\n\n/** Result from executeDeploy */\nexport interface ExecuteDeployResult {\n appId: AppId;\n txHash: Hex;\n appName: string;\n imageRef: string;\n}\n\n/** Result from executeUpgrade */\nexport interface ExecuteUpgradeResult {\n appId: AppId;\n txHash: Hex;\n imageRef: string;\n}\n\n/** Data-only batch for deploy (clients provided by module) */\nexport interface PreparedDeployData {\n /** The app ID that will be deployed */\n appId: AppId;\n /** The salt used for deployment */\n salt: Uint8Array;\n /** Batch executions to be sent */\n executions: Array<{ target: Address; value: bigint; callData: Hex }>;\n}\n\n/** Data-only batch for upgrade (clients provided by module) */\nexport interface PreparedUpgradeData {\n /** The app ID being upgraded */\n appId: AppId;\n /** Batch executions to be sent */\n executions: Array<{ target: Address; value: bigint; callData: Hex }>;\n}\n\n/** Prepared deployment ready for execution */\nexport interface PreparedDeploy {\n /** The prepared data (executions, appId, etc.) */\n data: PreparedDeployData;\n /** App name */\n appName: string;\n /** Final image reference */\n imageRef: string;\n}\n\n/** Prepared upgrade ready for execution */\nexport interface PreparedUpgrade {\n /** The prepared data (executions, appId, etc.) */\n data: PreparedUpgradeData;\n /** App ID being upgraded */\n appId: AppId;\n /** Final image reference */\n imageRef: string;\n}\n\nexport interface LifecycleOpts {\n gas?: GasEstimate;\n}\n\nexport interface AppRecord {\n id: AppId;\n owner: Address;\n image: string;\n status: \"starting\" | \"running\" | \"stopped\" | \"terminated\";\n createdAt: number; // epoch ms\n lastUpdatedAt: number; // epoch ms\n}\n\nexport interface DeployOptions {\n /** Private key for signing transactions (hex string with or without 0x prefix) - optional, will prompt if not provided */\n privateKey?: string;\n /** RPC URL for blockchain connection - optional, uses environment default if not provided */\n rpcUrl?: string;\n /** Environment name (e.g., 'sepolia', 'mainnet-alpha') - optional, defaults to 'sepolia' */\n environment?: string;\n /** Path to Dockerfile (if building from Dockerfile) */\n dockerfilePath?: string;\n /** Image reference (registry/path:tag) - optional, will prompt if not provided */\n imageRef?: string;\n /** Path to .env file - optional, will use .env if exists or prompt */\n envFilePath?: string;\n /** App name - optional, will prompt if not provided */\n appName?: string;\n /** Instance type - optional, will prompt if not provided */\n instanceType?: string;\n /** Log visibility setting - optional, will prompt if not provided */\n logVisibility?: logVisibility;\n}\n\nexport interface DeployResult {\n /** App ID (contract address) */\n appId: AppId;\n /** App name */\n appName: string;\n /** Final image reference */\n imageRef: string;\n /** IP address (if available) */\n ipAddress?: string;\n /** Transaction hash */\n txHash: Hex;\n}\n\nexport interface BillingEnvironmentConfig {\n billingApiServerURL: string;\n}\n\nexport interface EnvironmentConfig {\n name: string;\n build: \"dev\" | \"prod\";\n chainID: bigint;\n appControllerAddress: Address;\n permissionControllerAddress: string;\n erc7702DelegatorAddress: string;\n kmsServerURL: string;\n userApiServerURL: string;\n defaultRPCURL: string;\n}\n\nexport interface Release {\n rmsRelease: {\n artifacts: Array<{\n digest: Uint8Array; // 32 bytes\n registry: string;\n }>;\n upgradeByTime: number; // Unix timestamp\n };\n publicEnv: Uint8Array; // JSON bytes\n encryptedEnv: Uint8Array; // Encrypted string bytes\n}\n\nexport interface ParsedEnvironment {\n public: Record<string, string>;\n private: Record<string, string>;\n}\n\nexport interface ImageDigestResult {\n digest: Uint8Array; // 32 bytes\n registry: string;\n platform: string;\n}\n\nexport interface DockerImageConfig {\n cmd: string[];\n entrypoint: string[];\n user: string;\n labels: Record<string, string>;\n}\n\nexport interface Logger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n}\n\n/**\n * No-op logger for browser usage when logging is not needed\n */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/**\n * Profile information for an app\n */\nexport interface AppProfile {\n /** App name (required) */\n name: string;\n /** Website URL (optional) */\n website?: string;\n /** Description (optional) */\n description?: string;\n /** X (Twitter) URL (optional) */\n xURL?: string;\n /** Path to image file (optional) */\n image?: Blob | File;\n /** Image name (optional) */\n imageName?: string;\n}\n\n/**\n * Profile response from API\n */\nexport interface AppProfileResponse {\n name: string;\n website?: string;\n description?: string;\n xURL?: string;\n imageURL?: string;\n}\n\n// Billing types\nexport type ProductID = \"compute\";\nexport type ChainID = \"ethereum-mainnet\" | \"ethereum-sepolia\";\n\nexport type SubscriptionStatus =\n | \"incomplete\"\n | \"incomplete_expired\"\n | \"trialing\"\n | \"active\"\n | \"past_due\"\n | \"canceled\"\n | \"unpaid\"\n | \"paused\"\n | \"inactive\";\n\nexport interface SubscriptionLineItem {\n description: string;\n price: number;\n quantity: number;\n currency: string;\n subtotal: number;\n}\n\nexport interface CreateSubscriptionOptions {\n /** URL to redirect to after successful checkout */\n successUrl?: string;\n /** URL to redirect to if checkout is canceled */\n cancelUrl?: string;\n}\n\nexport interface CreateSubscriptionResponse {\n checkoutUrl: string;\n}\n\nexport interface CheckoutCreatedResponse {\n type: \"checkout_created\";\n checkoutUrl: string;\n}\n\nexport interface AlreadyActiveResponse {\n type: \"already_active\";\n status: SubscriptionStatus;\n}\n\nexport interface PaymentIssueResponse {\n type: \"payment_issue\";\n status: SubscriptionStatus;\n portalUrl?: string;\n}\n\nexport type SubscribeResponse =\n | CheckoutCreatedResponse\n | AlreadyActiveResponse\n | PaymentIssueResponse;\n\nexport interface CancelSuccessResponse {\n type: \"canceled\";\n}\n\nexport interface NoActiveSubscriptionResponse {\n type: \"no_active_subscription\";\n status: SubscriptionStatus;\n}\n\nexport type CancelResponse = CancelSuccessResponse | NoActiveSubscriptionResponse;\n\nexport interface ProductSubscriptionResponse {\n productId: ProductID;\n subscriptionStatus: SubscriptionStatus;\n currentPeriodStart?: string;\n currentPeriodEnd?: string;\n lineItems?: SubscriptionLineItem[];\n upcomingInvoiceSubtotal?: number;\n upcomingInvoiceTotal?: number;\n creditsApplied?: number;\n remainingCredits?: number;\n nextCreditExpiry?: number;\n cancelAtPeriodEnd?: boolean;\n canceledAt?: string;\n portalUrl?: string;\n}\n\nexport interface SubscriptionOpts {\n productId?: ProductID;\n /** URL to redirect to after successful checkout */\n successUrl?: string;\n /** URL to redirect to if checkout is canceled */\n cancelUrl?: string;\n}\n\n// Billing environment configuration\nexport interface BillingEnvironmentConfig {\n billingApiServerURL: string;\n}\n\n/**\n * Progress callback for sequential deployment\n * Called after each step completes\n */\nexport type DeployProgressCallback = (step: DeployStep, txHash?: Hex) => void;\n\n/**\n * Steps in sequential deployment flow\n */\nexport type DeployStep =\n | \"createApp\"\n | \"acceptAdmin\"\n | \"setPublicLogs\"\n | \"complete\";\n\n/**\n * Result from sequential deployment\n */\nexport interface SequentialDeployResult {\n appId: AppId;\n txHashes: {\n createApp: Hex;\n acceptAdmin: Hex;\n setPublicLogs?: Hex;\n };\n}\n","/**\n * Environment configuration for different networks\n */\n\nimport { BillingEnvironmentConfig, EnvironmentConfig } from \"../types\";\n\n// Chain IDs\nexport const SEPOLIA_CHAIN_ID = 11155111;\nexport const MAINNET_CHAIN_ID = 1;\n\n// Common addresses across all chains\nexport const CommonAddresses: Record<string, string> = {\n ERC7702Delegator: \"0x63c0c19a282a1b52b07dd5a65b58948a07dae32b\",\n};\n\n// Addresses specific to each chain\nexport const ChainAddresses: Record<number, Record<string, string>> = {\n [MAINNET_CHAIN_ID]: {\n PermissionController: \"0x25E5F8B1E7aDf44518d35D5B2271f114e081f0E5\",\n },\n [SEPOLIA_CHAIN_ID]: {\n PermissionController: \"0x44632dfBdCb6D3E21EF613B0ca8A6A0c618F5a37\",\n },\n};\n\n// Billing environment configurations (separate from chain environments)\nconst BILLING_ENVIRONMENTS: Record<\"dev\" | \"prod\", BillingEnvironmentConfig> = {\n dev: {\n billingApiServerURL: \"https://billingapi-dev.eigencloud.xyz\",\n },\n prod: {\n billingApiServerURL: \"https://billingapi.eigencloud.xyz\",\n },\n};\n\n// Chain environment configurations\nconst ENVIRONMENTS: Record<string, Omit<EnvironmentConfig, \"chainID\">> = {\n \"sepolia-dev\": {\n name: \"sepolia\",\n build: \"dev\",\n appControllerAddress: \"0xa86DC1C47cb2518327fB4f9A1627F51966c83B92\",\n permissionControllerAddress: ChainAddresses[SEPOLIA_CHAIN_ID].PermissionController,\n erc7702DelegatorAddress: CommonAddresses.ERC7702Delegator,\n kmsServerURL: \"http://10.128.0.57:8080\",\n userApiServerURL: \"https://userapi-compute-sepolia-dev.eigencloud.xyz\",\n defaultRPCURL: \"https://ethereum-sepolia-rpc.publicnode.com\",\n },\n sepolia: {\n name: \"sepolia\",\n build: \"prod\",\n appControllerAddress: \"0x0dd810a6ffba6a9820a10d97b659f07d8d23d4E2\",\n permissionControllerAddress: ChainAddresses[SEPOLIA_CHAIN_ID].PermissionController,\n erc7702DelegatorAddress: CommonAddresses.ERC7702Delegator,\n kmsServerURL: \"http://10.128.15.203:8080\",\n userApiServerURL: \"https://userapi-compute-sepolia-prod.eigencloud.xyz\",\n defaultRPCURL: \"https://ethereum-sepolia-rpc.publicnode.com\",\n },\n \"mainnet-alpha\": {\n name: \"mainnet-alpha\",\n build: \"prod\",\n appControllerAddress: \"0xc38d35Fc995e75342A21CBd6D770305b142Fbe67\",\n permissionControllerAddress: ChainAddresses[MAINNET_CHAIN_ID].PermissionController,\n erc7702DelegatorAddress: CommonAddresses.ERC7702Delegator,\n kmsServerURL: \"http://10.128.0.2:8080\",\n userApiServerURL: \"https://userapi-compute.eigencloud.xyz\",\n defaultRPCURL: \"https://ethereum-rpc.publicnode.com\",\n },\n};\n\nconst CHAIN_ID_TO_ENVIRONMENT: Record<string, string> = {\n [SEPOLIA_CHAIN_ID.toString()]: \"sepolia\",\n [MAINNET_CHAIN_ID.toString()]: \"mainnet-alpha\",\n};\n\n/**\n * Get environment configuration\n */\nexport function getEnvironmentConfig(environment: string, chainID?: bigint): EnvironmentConfig {\n const env = ENVIRONMENTS[environment];\n if (!env) {\n throw new Error(`Unknown environment: ${environment}`);\n }\n\n // Check if environment is available in current build\n if (!isEnvironmentAvailable(environment)) {\n throw new Error(\n `Environment ${environment} is not available in this build type. ` +\n `Available environments: ${getAvailableEnvironments().join(\", \")}`,\n );\n }\n\n // If chainID provided, validate it matches\n if (chainID) {\n const expectedEnv = CHAIN_ID_TO_ENVIRONMENT[chainID.toString()];\n if (expectedEnv && expectedEnv !== environment) {\n throw new Error(`Environment ${environment} does not match chain ID ${chainID}`);\n }\n }\n\n // Determine chain ID from environment if not provided\n // Both \"sepolia\" and \"sepolia-dev\" use Sepolia chain ID\n const resolvedChainID =\n chainID ||\n (environment === \"sepolia\" || environment === \"sepolia-dev\"\n ? SEPOLIA_CHAIN_ID\n : MAINNET_CHAIN_ID);\n\n return {\n ...env,\n chainID: BigInt(resolvedChainID),\n };\n}\n\n/**\n * Get billing environment configuration\n * @param build - The build type (\"dev\" or \"prod\")\n */\nexport function getBillingEnvironmentConfig(build: \"dev\" | \"prod\"): {\n billingApiServerURL: string;\n} {\n const config = BILLING_ENVIRONMENTS[build];\n if (!config) {\n throw new Error(`Unknown billing environment: ${build}`);\n }\n return config;\n}\n\n/**\n * Detect environment from chain ID\n */\nexport function detectEnvironmentFromChainID(chainID: bigint): string | undefined {\n return CHAIN_ID_TO_ENVIRONMENT[chainID.toString()];\n}\n\n/**\n * Get build type from environment variable or build-time constant (defaults to 'prod')\n * BUILD_TYPE_BUILD_TIME is replaced at build time by tsup's define option\n */\n// @ts-ignore - BUILD_TYPE_BUILD_TIME is injected at build time by tsup\ndeclare const BUILD_TYPE_BUILD_TIME: string | undefined;\n\nexport function getBuildType(): \"dev\" | \"prod\" {\n // First check build-time constant (set by tsup define)\n // @ts-ignore - BUILD_TYPE_BUILD_TIME is injected at build time\n const buildTimeType =\n typeof BUILD_TYPE_BUILD_TIME !== \"undefined\" ? BUILD_TYPE_BUILD_TIME?.toLowerCase() : undefined;\n\n // Fall back to runtime environment variable\n const runtimeType = process.env.BUILD_TYPE?.toLowerCase();\n\n const buildType = buildTimeType || runtimeType;\n\n if (buildType === \"dev\") {\n return \"dev\";\n }\n return \"prod\";\n}\n\n/**\n * Get available environments based on build type\n * - dev: only \"sepolia-dev\"\n * - prod: \"sepolia\" and \"mainnet-alpha\"\n */\nexport function getAvailableEnvironments(): string[] {\n const buildType = getBuildType();\n\n if (buildType === \"dev\") {\n return [\"sepolia-dev\"];\n }\n\n // prod build\n return [\"sepolia\", \"mainnet-alpha\"];\n}\n\n/**\n * Check if an environment is available in the current build\n */\nexport function isEnvironmentAvailable(environment: string): boolean {\n return getAvailableEnvironments().includes(environment);\n}\n\n/**\n * Check if environment is mainnet (chain ID 1)\n */\nexport function isMainnet(environmentConfig: EnvironmentConfig): boolean {\n return environmentConfig.chainID === BigInt(MAINNET_CHAIN_ID);\n}\n","/**\n * Non-interactive validation utilities for SDK\n *\n * These functions validate parameters without any interactive prompts.\n * They either return the validated value or throw an error.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport { Address, isAddress } from \"viem\";\nimport { stripHexPrefix, addHexPrefix } from \"./helpers\";\n\n// ==================== App Name Validation ====================\n\n/**\n * Validate app name format\n * @throws Error if name is invalid\n */\nexport function validateAppName(name: string): void {\n if (!name) {\n throw new Error(\"App name cannot be empty\");\n }\n if (name.includes(\" \")) {\n throw new Error(\"App name cannot contain spaces\");\n }\n if (name.length > 50) {\n throw new Error(\"App name cannot be longer than 50 characters\");\n }\n}\n\n// ==================== Image Reference Validation ====================\n\n/**\n * Validate Docker image reference format\n * @returns true if valid, error message string if invalid\n */\nexport function validateImageReference(value: string): true | string {\n if (!value) {\n return \"Image reference cannot be empty\";\n }\n // Basic validation - should contain at least one / and optionally :\n if (!value.includes(\"/\")) {\n return \"Image reference must contain at least one /\";\n }\n return true;\n}\n\n/**\n * Validate image reference and throw if invalid\n * @throws Error if image reference is invalid\n */\nexport function assertValidImageReference(value: string): void {\n const result = validateImageReference(value);\n if (result !== true) {\n throw new Error(result);\n }\n}\n\n/**\n * Extract app name from image reference\n */\nexport function extractAppNameFromImage(imageRef: string): string {\n // Remove registry prefix if present\n const parts = imageRef.split(\"/\");\n let imageName = parts.length > 1 ? parts[parts.length - 1] : imageRef;\n\n // Split image and tag\n if (imageName.includes(\":\")) {\n imageName = imageName.split(\":\")[0];\n }\n\n return imageName;\n}\n\n// ==================== File Path Validation ====================\n\n/**\n * Validate that a file path exists\n * @returns true if valid, error message string if invalid\n */\nexport function validateFilePath(value: string): true | string {\n if (!value) {\n return \"File path cannot be empty\";\n }\n if (!fs.existsSync(value)) {\n return \"File does not exist\";\n }\n return true;\n}\n\n/**\n * Validate file path and throw if invalid\n * @throws Error if file path is invalid or doesn't exist\n */\nexport function assertValidFilePath(value: string): void {\n const result = validateFilePath(value);\n if (result !== true) {\n throw new Error(result);\n }\n}\n\n// ==================== Instance Type Validation ====================\n\n/**\n * Validate instance type SKU against available types\n * @returns the validated SKU\n * @throws Error if SKU is not in the available types list\n */\nexport function validateInstanceTypeSKU(\n sku: string,\n availableTypes: Array<{ sku: string }>,\n): string {\n if (!sku) {\n throw new Error(\"Instance type SKU cannot be empty\");\n }\n\n // Check if SKU is valid\n for (const it of availableTypes) {\n if (it.sku === sku) {\n return sku;\n }\n }\n\n // Build helpful error message with valid options\n const validSKUs = availableTypes.map((it) => it.sku).join(\", \");\n throw new Error(`Invalid instance-type value: ${sku} (must be one of: ${validSKUs})`);\n}\n\n// ==================== Private Key Validation ====================\n\n/**\n * Validate private key format\n * Matches Go's common.ValidatePrivateKey() function\n */\nexport function validatePrivateKeyFormat(key: string): boolean {\n // Remove 0x prefix if present\n const keyWithoutPrefix = stripHexPrefix(key);\n\n // Must be 64 hex characters (32 bytes)\n if (!/^[0-9a-fA-F]{64}$/.test(keyWithoutPrefix)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Validate private key and throw if invalid\n * @throws Error if private key format is invalid\n */\nexport function assertValidPrivateKey(key: string): void {\n if (!key) {\n throw new Error(\"Private key is required\");\n }\n if (!validatePrivateKeyFormat(key)) {\n throw new Error(\n \"Invalid private key format (must be 64 hex characters, optionally prefixed with 0x)\",\n );\n }\n}\n\n// ==================== URL Validation ====================\n\n/**\n * Validate URL format\n * @returns undefined if valid, error message string if invalid\n */\nexport function validateURL(rawURL: string): string | undefined {\n if (!rawURL.trim()) {\n return \"URL cannot be empty\";\n }\n\n try {\n const url = new URL(rawURL);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return \"URL scheme must be http or https\";\n }\n } catch {\n return \"Invalid URL format\";\n }\n\n return undefined;\n}\n\n/**\n * Valid X/Twitter hosts\n */\nconst VALID_X_HOSTS = [\"twitter.com\", \"www.twitter.com\", \"x.com\", \"www.x.com\"];\n\n/**\n * Validate X/Twitter URL format\n * @returns undefined if valid, error message string if invalid\n */\nexport function validateXURL(rawURL: string): string | undefined {\n // First validate as URL\n const urlErr = validateURL(rawURL);\n if (urlErr) {\n return urlErr;\n }\n\n try {\n const url = new URL(rawURL);\n const host = url.hostname.toLowerCase();\n\n // Accept twitter.com and x.com domains\n if (!VALID_X_HOSTS.includes(host)) {\n return \"URL must be a valid X/Twitter URL (x.com or twitter.com)\";\n }\n\n // Ensure it has a path (username/profile)\n if (!url.pathname || url.pathname === \"/\") {\n return \"X URL must include a username or profile path\";\n }\n } catch {\n return \"Invalid X URL format\";\n }\n\n return undefined;\n}\n\n// ==================== Description Validation ====================\n\nconst MAX_DESCRIPTION_LENGTH = 1000;\n\n/**\n * Validate description length\n * @returns undefined if valid, error message string if invalid\n */\nexport function validateDescription(description: string): string | undefined {\n if (!description.trim()) {\n return \"Description cannot be empty\";\n }\n\n if (description.length > MAX_DESCRIPTION_LENGTH) {\n return `Description cannot exceed ${MAX_DESCRIPTION_LENGTH} characters`;\n }\n\n return undefined;\n}\n\n// ==================== Image Path Validation ====================\n\nconst MAX_IMAGE_SIZE = 4 * 1024 * 1024; // 4MB\nconst VALID_IMAGE_EXTENSIONS = [\".jpg\", \".jpeg\", \".png\"];\n\n/**\n * Validate image file path\n * @returns undefined if valid, error message string if invalid\n */\nexport function validateImagePath(filePath: string): string | undefined {\n // Strip quotes that may be added by terminal drag-and-drop\n const cleanedPath = filePath.trim().replace(/^[\"']|[\"']$/g, \"\");\n\n if (!cleanedPath) {\n return \"Image path cannot be empty\";\n }\n\n // Check if file exists\n if (!fs.existsSync(cleanedPath)) {\n return `Image file not found: ${cleanedPath}`;\n }\n\n const stats = fs.statSync(cleanedPath);\n if (stats.isDirectory()) {\n return \"Path is a directory, not a file\";\n }\n\n // Check file size\n if (stats.size > MAX_IMAGE_SIZE) {\n const sizeMB = (stats.size / (1024 * 1024)).toFixed(2);\n return `Image file size (${sizeMB} MB) exceeds maximum allowed size of 4 MB`;\n }\n\n // Check file extension\n const ext = path.extname(cleanedPath).toLowerCase();\n if (!VALID_IMAGE_EXTENSIONS.includes(ext)) {\n return \"Image must be JPG or PNG format\";\n }\n\n return undefined;\n}\n\n// ==================== App ID Validation ====================\n\n/**\n * Validate and normalize app ID address\n * @param appID - App ID (must be a valid address)\n * @returns Normalized app address\n * @throws Error if app ID is not a valid address\n *\n * Note: Name resolution should be handled by CLI before calling SDK functions.\n * The SDK only accepts resolved addresses.\n */\nexport function validateAppID(appID: string | Address): Address {\n if (!appID) {\n throw new Error(\"App ID is required\");\n }\n\n // Normalize the input\n const normalized = typeof appID === \"string\" ? addHexPrefix(appID) : appID;\n\n // Check if it's a valid address\n if (isAddress(normalized)) {\n return normalized as Address;\n }\n\n throw new Error(`Invalid app ID: '${appID}' is not a valid address`);\n}\n\n// ==================== Log Visibility Validation ====================\n\nexport type LogVisibility = \"public\" | \"private\" | \"off\";\n\n/**\n * Validate and convert log visibility setting to internal format\n * @param logVisibility - Log visibility setting\n * @returns Object with logRedirect and publicLogs settings\n * @throws Error if log visibility value is invalid\n */\nexport function validateLogVisibility(logVisibility: LogVisibility): {\n logRedirect: string;\n publicLogs: boolean;\n} {\n switch (logVisibility) {\n case \"public\":\n return { logRedirect: \"always\", publicLogs: true };\n case \"private\":\n return { logRedirect: \"always\", publicLogs: false };\n case \"off\":\n return { logRedirect: \"\", publicLogs: false };\n default:\n throw new Error(\n `Invalid log-visibility value: ${logVisibility} (must be public, private, or off)`,\n );\n }\n}\n\n// ==================== Resource Usage Monitoring Validation ====================\n\nexport type ResourceUsageMonitoring = \"enable\" | \"disable\";\n\n/**\n * Validate and convert resource usage monitoring setting to internal format\n * @param resourceUsageMonitoring - Resource usage monitoring setting\n * @returns The resourceUsageAllow value for the Dockerfile label (\"always\" or \"never\")\n * @throws Error if resource usage monitoring value is invalid\n */\nexport function validateResourceUsageMonitoring(\n resourceUsageMonitoring: ResourceUsageMonitoring | undefined,\n): string {\n // Default to \"enable\" (always) if not specified\n if (!resourceUsageMonitoring) {\n return \"always\";\n }\n\n switch (resourceUsageMonitoring) {\n case \"enable\":\n return \"always\";\n case \"disable\":\n return \"never\";\n default:\n throw new Error(\n `Invalid resource-usage-monitoring value: ${resourceUsageMonitoring} (must be enable or disable)`,\n );\n }\n}\n\n// ==================== Sanitization Functions ====================\n\n/**\n * Check if URL has scheme\n */\nfunction hasScheme(rawURL: string): boolean {\n return rawURL.startsWith(\"http://\") || rawURL.startsWith(\"https://\");\n}\n\n/**\n * Sanitize string (HTML escape and trim)\n */\nexport function sanitizeString(s: string): string {\n return s\n .trim()\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/**\n * Sanitize URL (add https:// if missing, validate)\n * @throws Error if URL is invalid after sanitization\n */\nexport function sanitizeURL(rawURL: string): string {\n rawURL = rawURL.trim();\n\n // Add https:// if no scheme is present\n if (!hasScheme(rawURL)) {\n rawURL = \"https://\" + rawURL;\n }\n\n // Validate\n const err = validateURL(rawURL);\n if (err) {\n throw new Error(err);\n }\n\n return rawURL;\n}\n\n/**\n * Sanitize X/Twitter URL (handle username-only input, normalize)\n * @throws Error if URL is invalid after sanitization\n */\nexport function sanitizeXURL(rawURL: string): string {\n rawURL = rawURL.trim();\n\n // Handle username-only input (e.g., \"@username\" or \"username\")\n if (!rawURL.includes(\"://\") && !rawURL.includes(\".\")) {\n // Remove @ if present\n const username = rawURL.startsWith(\"@\") ? rawURL.slice(1) : rawURL;\n rawURL = `https://x.com/${username}`;\n } else if (!hasScheme(rawURL)) {\n // Add https:// if URL-like but missing scheme\n rawURL = \"https://\" + rawURL;\n }\n\n // Normalize twitter.com to x.com\n rawURL = rawURL.replace(/twitter\\.com/g, \"x.com\");\n rawURL = rawURL.replace(/www\\.x\\.com/g, \"x.com\");\n\n // Validate\n const err = validateXURL(rawURL);\n if (err) {\n throw new Error(err);\n }\n\n return rawURL;\n}\n\n// ==================== Deploy/Upgrade Parameter Validation ====================\n\nexport interface DeployParams {\n dockerfilePath?: string;\n imageRef?: string;\n appName: string;\n envFilePath?: string;\n instanceType: string;\n logVisibility: LogVisibility;\n}\n\n/**\n * Validate deploy parameters\n * @throws Error if required parameters are missing or invalid\n */\nexport function validateDeployParams(params: Partial<DeployParams>): void {\n // Must have either dockerfilePath or imageRef\n if (!params.dockerfilePath && !params.imageRef) {\n throw new Error(\"Either dockerfilePath or imageRef is required for deployment\");\n }\n\n // If imageRef is provided, validate it\n if (params.imageRef) {\n assertValidImageReference(params.imageRef);\n }\n\n // If dockerfilePath is provided, validate it exists\n if (params.dockerfilePath) {\n assertValidFilePath(params.dockerfilePath);\n }\n\n // App name is required\n if (!params.appName) {\n throw new Error(\"App name is required\");\n }\n validateAppName(params.appName);\n\n // Instance type is required\n if (!params.instanceType) {\n throw new Error(\"Instance type is required\");\n }\n\n // Log visibility is required\n if (!params.logVisibility) {\n throw new Error(\"Log visibility is required (public, private, or off)\");\n }\n validateLogVisibility(params.logVisibility);\n\n // Env file path is optional, but if provided, validate it exists\n if (params.envFilePath && params.envFilePath !== \"\") {\n const result = validateFilePath(params.envFilePath);\n if (result !== true) {\n throw new Error(`Invalid env file: ${result}`);\n }\n }\n}\n\nexport interface UpgradeParams {\n appID: string | Address;\n dockerfilePath?: string;\n imageRef?: string;\n envFilePath?: string;\n instanceType: string;\n logVisibility: LogVisibility;\n}\n\n/**\n * Validate upgrade parameters\n * @throws Error if required parameters are missing or invalid\n */\nexport function validateUpgradeParams(params: Partial<UpgradeParams>): void {\n // App ID is required\n if (!params.appID) {\n throw new Error(\"App ID is required for upgrade\");\n }\n // Validate app ID is a valid address (throws if not)\n validateAppID(params.appID);\n\n // Must have either dockerfilePath or imageRef\n if (!params.dockerfilePath && !params.imageRef) {\n throw new Error(\"Either dockerfilePath or imageRef is required for upgrade\");\n }\n\n // If imageRef is provided, validate it\n if (params.imageRef) {\n assertValidImageReference(params.imageRef);\n }\n\n // If dockerfilePath is provided, validate it exists\n if (params.dockerfilePath) {\n assertValidFilePath(params.dockerfilePath);\n }\n\n // Instance type is required\n if (!params.instanceType) {\n throw new Error(\"Instance type is required\");\n }\n\n // Log visibility is required\n if (!params.logVisibility) {\n throw new Error(\"Log visibility is required (public, private, or off)\");\n }\n validateLogVisibility(params.logVisibility);\n\n // Env file path is optional, but if provided, validate it exists\n if (params.envFilePath && params.envFilePath !== \"\") {\n const result = validateFilePath(params.envFilePath);\n if (result !== true) {\n throw new Error(`Invalid env file: ${result}`);\n }\n }\n}\n\nexport interface CreateAppParams {\n name: string;\n language: string;\n template?: string;\n templateVersion?: string;\n}\n\n/**\n * Validate create app parameters\n * @throws Error if required parameters are missing or invalid\n */\nexport function validateCreateAppParams(params: Partial<CreateAppParams>): void {\n if (!params.name) {\n throw new Error(\"Project name is required\");\n }\n\n // Validate project name (no spaces)\n if (params.name.includes(\" \")) {\n throw new Error(\"Project name cannot contain spaces\");\n }\n\n if (!params.language) {\n throw new Error(\"Language is required\");\n }\n}\n\nexport interface LogsParams {\n appID: string | Address;\n watch?: boolean;\n}\n\n/**\n * Validate logs parameters\n * @throws Error if required parameters are missing or invalid\n */\nexport function validateLogsParams(params: Partial<LogsParams>): void {\n if (!params.appID) {\n throw new Error(\"App ID is required for viewing logs\");\n }\n // Validate app ID is a valid address (throws if not)\n validateAppID(params.appID);\n}\n","/**\n * General utility helpers\n */\n\nimport { extractChain, createPublicClient, createWalletClient, http } from \"viem\";\nimport type { Chain, Hex, PublicClient, WalletClient } from \"viem\";\nimport { sepolia } from \"viem/chains\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { SUPPORTED_CHAINS } from \"../constants\";\n\n/**\n * Get a viem Chain object from a chain ID.\n * Supports mainnet (1) and sepolia (11155111), defaults to the fallback chain for unknown chains.\n */\nexport function getChainFromID(chainID: bigint, fallback: Chain = sepolia): Chain {\n const id = Number(chainID) as (typeof SUPPORTED_CHAINS)[number][\"id\"];\n return extractChain({ chains: SUPPORTED_CHAINS, id }) || fallback;\n}\n\n/**\n * Create viem clients from a private key\n *\n * This is a convenience helper for CLI and server applications that have direct\n * access to a private key. For browser applications using external wallets (MetaMask, etc.),\n * create the WalletClient directly using viem's createWalletClient with a custom transport.\n *\n * @example\n * // CLI usage with private key\n * const { walletClient, publicClient } = createClients({\n * privateKey: '0x...',\n * rpcUrl: 'https://sepolia.infura.io/v3/...',\n * chainId: 11155111n\n * });\n *\n * @example\n * // Browser usage with external wallet (create clients directly)\n * const walletClient = createWalletClient({\n * chain: sepolia,\n * transport: custom(window.ethereum!)\n * });\n * const publicClient = createPublicClient({\n * chain: sepolia,\n * transport: custom(window.ethereum!)\n * });\n */\nexport function createClients(options: {\n privateKey: string | Hex;\n rpcUrl: string;\n chainId: bigint;\n}): {\n walletClient: WalletClient;\n publicClient: PublicClient;\n} {\n const { privateKey, rpcUrl, chainId } = options;\n\n const privateKeyHex = addHexPrefix(privateKey);\n const account = privateKeyToAccount(privateKeyHex);\n const chain = getChainFromID(chainId);\n\n const publicClient = createPublicClient({\n chain,\n transport: http(rpcUrl),\n });\n\n const walletClient = createWalletClient({\n account,\n chain,\n transport: http(rpcUrl),\n });\n\n return { walletClient, publicClient };\n}\n\n/**\n * Ensure hex string has 0x prefix\n */\nexport function addHexPrefix(value: string): Hex {\n return (value.startsWith(\"0x\") ? value : `0x${value}`) as Hex;\n}\n\n/**\n * Remove 0x prefix from hex string if present\n */\nexport function stripHexPrefix(value: string): string {\n return value.startsWith(\"0x\") ? value.slice(2) : value;\n}\n","/**\n * Constants used throughout the SDK\n */\n\nimport { sepolia, mainnet } from \"viem/chains\";\n\nexport const SUPPORTED_CHAINS = [mainnet, sepolia] as const;\n\nexport const DOCKER_PLATFORM = \"linux/amd64\";\nexport const REGISTRY_PROPAGATION_WAIT_SECONDS = 3;\nexport const LAYERED_DOCKERFILE_NAME = \"Dockerfile.eigencompute\";\nexport const ENV_SOURCE_SCRIPT_NAME = \"compute-source-env.sh\";\nexport const KMS_CLIENT_BINARY_NAME = \"kms-client\";\nexport const KMS_ENCRYPTION_KEY_NAME = \"kms-encryption-public-key.pem\";\nexport const KMS_SIGNING_KEY_NAME = \"kms-signing-public-key.pem\";\nexport const TLS_KEYGEN_BINARY_NAME = \"tls-keygen\";\nexport const CADDYFILE_NAME = \"Caddyfile\";\nexport const TEMP_IMAGE_PREFIX = \"ecloud-temp-\";\nexport const LAYERED_BUILD_DIR_PREFIX = \"ecloud-layered-build\";\nexport const SHA256_PREFIX = \"sha256:\";\nexport const JWT_FILE_PATH = \"/run/container_launcher/attestation_verifier_claims_token\";\n","/**\n * Billing utility functions\n */\n\nimport type { SubscriptionStatus } from \"../types\";\n\n/**\n * Check if subscription status allows deploying apps\n */\nexport function isSubscriptionActive(status: SubscriptionStatus): boolean {\n return status === \"active\" || status === \"trialing\";\n}\n","/**\n * Private Key Generation\n *\n * Generate new secp256k1 private keys for Ethereum\n */\n\nimport { generatePrivateKey, privateKeyToAddress } from \"viem/accounts\";\n\nexport interface GeneratedKey {\n privateKey: string;\n address: string;\n}\n\n/**\n * Generate a new secp256k1 private key\n */\nexport function generateNewPrivateKey(): GeneratedKey {\n const privateKey = generatePrivateKey();\n const address = privateKeyToAddress(privateKey);\n\n return {\n privateKey,\n address,\n };\n}\n","import axios, { AxiosResponse } from \"axios\";\nimport { Address, Hex, type PublicClient, type WalletClient } from \"viem\";\nimport { calculatePermissionSignature } from \"./auth\";\nimport { EnvironmentConfig } from \"../types\";\nimport { stripHexPrefix } from \"./helpers\";\nimport {\n loginToComputeApi,\n logoutFromComputeApi,\n getComputeApiSession,\n type LoginRequest,\n type LoginResult,\n type SessionInfo,\n} from \"../auth/session\";\n\nexport interface AppProfileInfo {\n name: string;\n website?: string;\n description?: string;\n xURL?: string;\n imageURL?: string;\n}\n\nexport interface AppMetrics {\n cpu_utilization_percent?: number;\n memory_utilization_percent?: number;\n memory_used_bytes?: number;\n memory_total_bytes?: number;\n}\n\nexport interface DerivedAddress {\n address: string;\n derivationPath: string;\n}\n\nexport interface AppInfo {\n address: Address;\n status: string;\n ip: string;\n machineType: string;\n profile?: AppProfileInfo;\n metrics?: AppMetrics;\n evmAddresses: DerivedAddress[];\n solanaAddresses: DerivedAddress[];\n}\n\nexport interface AppInfoResponse {\n apps: Array<{\n addresses: {\n data: {\n evmAddresses: DerivedAddress[];\n solanaAddresses: DerivedAddress[];\n };\n signature: string;\n };\n app_status: string;\n ip: string;\n machine_type: string;\n profile?: AppProfileInfo;\n metrics?: AppMetrics;\n }>;\n}\n\n// ==================== App Releases (/apps/:id) ====================\n\ntype JsonObject = Record<string, unknown>;\n\nfunction isJsonObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction readString(obj: JsonObject, key: string): string | undefined {\n const v = obj[key];\n return typeof v === \"string\" ? v : undefined;\n}\n\nfunction readNumber(obj: JsonObject, key: string): number | undefined {\n const v = obj[key];\n return typeof v === \"number\" && Number.isFinite(v) ? v : undefined;\n}\n\nexport type AppContractStatus = \"STARTED\" | \"STOPPED\" | \"TERMINATED\" | \"SUSPENDED\" | string;\n\nexport interface AppReleaseBuild {\n buildId?: string;\n billingAddress?: string;\n repoUrl?: string;\n gitRef?: string;\n status?: string;\n buildType?: string;\n imageName?: string;\n imageDigest?: string;\n imageUrl?: string;\n provenanceJson?: unknown;\n provenanceSignature?: string;\n createdAt?: string;\n updatedAt?: string;\n errorMessage?: string;\n dependencies?: Record<string, AppReleaseBuild>;\n}\n\nexport interface AppRelease {\n appId?: string;\n rmsReleaseId?: string;\n imageDigest?: string;\n registryUrl?: string;\n publicEnv?: string;\n encryptedEnv?: string;\n upgradeByTime?: number;\n createdAt?: string;\n createdAtBlock?: string;\n build?: AppReleaseBuild;\n}\n\nexport interface AppResponse {\n id: string;\n creator?: string;\n contractStatus?: AppContractStatus;\n releases: AppRelease[];\n}\n\nconst MAX_ADDRESS_COUNT = 5;\n\n// Permission constants\nexport const CanViewAppLogsPermission = \"0x2fd3f2fe\" as Hex;\nexport const CanViewSensitiveAppInfoPermission = \"0x0e67b22f\" as Hex;\nexport const CanUpdateAppProfilePermission = \"0x036fef61\" as Hex;\n\n/**\n * SDK_VERSION_BUILD_TIME is replaced at build time by tsup's define option\n */\n// @ts-ignore - SDK_VERSION_BUILD_TIME is injected at build time by tsup\ndeclare const SDK_VERSION_BUILD_TIME: string | undefined;\n\n/**\n * Get the default client ID using the build-time version\n */\nfunction getDefaultClientId(): string {\n // @ts-ignore - SDK_VERSION_BUILD_TIME is injected at build time\n const version = typeof SDK_VERSION_BUILD_TIME !== \"undefined\" ? SDK_VERSION_BUILD_TIME : \"0.0.0\";\n return `ecloud-sdk/v${version}`;\n}\n\n/**\n * Options for UserApiClient\n */\nexport interface UserApiClientOptions {\n /** Custom client ID for request tracking */\n clientId?: string;\n /**\n * Use SIWE session authentication instead of per-request signatures.\n * When true, requests rely on session cookies set by loginToComputeApi().\n * When false (default), each request is signed individually.\n */\n useSession?: boolean;\n}\n\n/**\n * UserAPI Client for interacting with the EigenCloud UserAPI service.\n */\nexport class UserApiClient {\n private readonly clientId: string;\n private readonly useSession: boolean;\n\n constructor(\n private readonly config: EnvironmentConfig,\n private readonly walletClient: WalletClient,\n private readonly publicClient: PublicClient,\n options?: UserApiClientOptions,\n ) {\n this.clientId = options?.clientId || getDefaultClientId();\n this.useSession = options?.useSession ?? false;\n }\n\n /**\n * Get the address of the connected wallet\n */\n get address(): Address {\n const account = this.walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n return account.address;\n }\n\n async getInfos(appIDs: Address[], addressCount = 1): Promise<AppInfo[]> {\n const count = Math.min(addressCount, MAX_ADDRESS_COUNT);\n\n const endpoint = `${this.config.userApiServerURL}/info`;\n const url = `${endpoint}?${new URLSearchParams({ apps: appIDs.join(\",\") })}`;\n\n const res = await this.makeAuthenticatedRequest(url, CanViewSensitiveAppInfoPermission);\n const result: AppInfoResponse = await res.json();\n\n // optional: verify signatures with KMS key\n // const { signingKey } = getKMSKeysForEnvironment(this.config.name);\n\n // Truncate without mutating the original object\n // API returns apps in the same order as the request, so use appIDs[i] as the address\n return result.apps.map((app, i) => {\n // TODO: Implement signature verification\n // const valid = await verifyKMSSignature(appInfo.addresses, signingKey);\n // if (!valid) {\n // throw new Error(`Invalid signature for app ${appIDs[i]}`);\n // }\n\n // Slice derived addresses to requested count\n const evmAddresses = app.addresses?.data?.evmAddresses?.slice(0, count) || [];\n const solanaAddresses = app.addresses?.data?.solanaAddresses?.slice(0, count) || [];\n\n return {\n address: appIDs[i] as Address,\n status: app.app_status,\n ip: app.ip,\n machineType: app.machine_type,\n profile: app.profile,\n metrics: app.metrics,\n evmAddresses,\n solanaAddresses,\n };\n });\n }\n\n /**\n * Get app details from UserAPI (includes releases and build/provenance info when available).\n *\n * Endpoint: GET /apps/:appAddress\n */\n async getApp(appAddress: Address): Promise<AppResponse> {\n const endpoint = `${this.config.userApiServerURL}/apps/${appAddress}`;\n const res = await this.makeAuthenticatedRequest(endpoint);\n const raw = (await res.json()) as unknown;\n\n if (!isJsonObject(raw)) {\n throw new Error(\"Unexpected /apps/:id response: expected object\");\n }\n\n const id = readString(raw, \"id\");\n if (!id) {\n throw new Error(\"Unexpected /apps/:id response: missing 'id'\");\n }\n\n const releasesRaw = raw.releases;\n const releases = Array.isArray(releasesRaw)\n ? releasesRaw.map((r) => transformAppRelease(r)).filter((r): r is AppRelease => !!r)\n : [];\n\n return {\n id,\n creator: readString(raw, \"creator\"),\n contractStatus: (readString(raw, \"contract_status\") ?? readString(raw, \"contractStatus\")) as\n | AppContractStatus\n | undefined,\n releases,\n };\n }\n\n /**\n * Get available SKUs (instance types) from UserAPI\n */\n async getSKUs(): Promise<{\n skus: Array<{ sku: string; description: string }>;\n }> {\n const endpoint = `${this.config.userApiServerURL}/skus`;\n const response = await this.makeAuthenticatedRequest(endpoint);\n\n const result = await response.json();\n\n // Transform response to match expected format\n return {\n skus: result.skus || result.SKUs || [],\n };\n }\n\n /**\n * Get logs for an app\n */\n async getLogs(appID: Address): Promise<string> {\n const endpoint = `${this.config.userApiServerURL}/logs/${appID}`;\n const response = await this.makeAuthenticatedRequest(endpoint, CanViewAppLogsPermission);\n return await response.text();\n }\n\n /**\n * Get statuses for apps\n */\n async getStatuses(appIDs: Address[]): Promise<Array<{ address: Address; status: string }>> {\n const endpoint = `${this.config.userApiServerURL}/status`;\n const url = `${endpoint}?${new URLSearchParams({ apps: appIDs.join(\",\") })}`;\n const response = await this.makeAuthenticatedRequest(url);\n const result = await response.json();\n\n // Transform response to match expected format\n // The API returns an array of app statuses\n const apps = result.apps || result.Apps || [];\n return apps.map((app: any, i: number) => ({\n address: (app.address || appIDs[i]) as Address,\n status: app.app_status || app.App_Status || \"\",\n }));\n }\n\n /**\n * Upload app profile information with optional image\n *\n * @param appAddress - The app's contract address\n * @param name - Display name for the app\n * @param options - Optional fields including website, description, xURL, and image\n * @param options.image - Image file as Blob or File (browser: from input element, Node.js: new Blob([buffer]))\n * @param options.imageName - Filename for the image (required if image is provided)\n */\n async uploadAppProfile(\n appAddress: Address,\n name: string,\n options?: {\n website?: string;\n description?: string;\n xURL?: string;\n image?: Blob | File;\n imageName?: string;\n },\n ): Promise<{\n name: string;\n website?: string;\n description?: string;\n xURL?: string;\n imageURL?: string;\n }> {\n const endpoint = `${this.config.userApiServerURL}/apps/${appAddress}/profile`;\n\n // Build multipart form data using Web FormData API (works in browser and Node.js 18+)\n const formData = new FormData();\n\n // Add required name field\n formData.append(\"name\", name);\n\n // Add optional text fields\n if (options?.website) {\n formData.append(\"website\", options.website);\n }\n if (options?.description) {\n formData.append(\"description\", options.description);\n }\n if (options?.xURL) {\n formData.append(\"xURL\", options.xURL);\n }\n\n // Add optional image file (Blob or File)\n if (options?.image) {\n // If it's a File, use its name; otherwise require imageName\n const fileName =\n options.image instanceof File ? options.image.name : options.imageName || \"image\";\n formData.append(\"image\", options.image, fileName);\n }\n\n // Make authenticated POST request\n // Note: Don't set Content-Type header manually - axios will set it with the correct boundary\n const headers: Record<string, string> = {\n \"x-client-id\": this.clientId,\n };\n\n // Add auth headers if not using session auth\n if (!this.useSession) {\n const expiry = BigInt(Math.floor(Date.now() / 1000) + 5 * 60); // 5 minutes\n const authHeaders = await this.generateAuthHeaders(CanUpdateAppProfilePermission, expiry);\n Object.assign(headers, authHeaders);\n }\n\n try {\n const response: AxiosResponse = await axios.post(endpoint, formData, {\n headers,\n maxRedirects: 0,\n validateStatus: () => true, // Don't throw on any status\n maxContentLength: Infinity, // Allow large file uploads\n maxBodyLength: Infinity, // Allow large file uploads\n withCredentials: true, // Include cookies for session auth\n });\n\n const status = response.status;\n\n if (status !== 200 && status !== 201) {\n const body =\n typeof response.data === \"string\" ? response.data : JSON.stringify(response.data);\n\n // Detect Cloudflare challenge page\n if (status === 403 && body.includes(\"Cloudflare\") && body.includes(\"challenge-platform\")) {\n throw new Error(\n `Cloudflare protection is blocking the request. This is likely due to bot detection.\\n` +\n `Status: ${status}`,\n );\n }\n\n throw new Error(\n `UserAPI request failed: ${status} ${status >= 200 && status < 300 ? \"OK\" : \"Error\"} - ${body.substring(0, 500)}${body.length > 500 ? \"...\" : \"\"}`,\n );\n }\n\n return response.data;\n } catch (error: any) {\n if (\n error.message?.includes(\"fetch failed\") ||\n error.message?.includes(\"ECONNREFUSED\") ||\n error.message?.includes(\"ENOTFOUND\") ||\n error.cause\n ) {\n const cause = error.cause?.message || error.cause || error.message;\n throw new Error(\n `Failed to connect to UserAPI at ${endpoint}: ${cause}\\n` +\n `Please check:\\n` +\n `1. Your internet connection\\n` +\n `2. The API server is accessible: ${this.config.userApiServerURL}\\n` +\n `3. Firewall/proxy settings`,\n );\n }\n throw error;\n }\n }\n\n private async makeAuthenticatedRequest(\n url: string,\n permission?: Hex,\n ): Promise<{ json: () => Promise<any>; text: () => Promise<string> }> {\n const headers: Record<string, string> = {\n \"x-client-id\": this.clientId,\n };\n // Add auth headers if permission is specified and not using session auth\n if (permission && !this.useSession) {\n const expiry = BigInt(Math.floor(Date.now() / 1000) + 5 * 60); // 5 minutes\n const authHeaders = await this.generateAuthHeaders(permission, expiry);\n Object.assign(headers, authHeaders);\n }\n\n try {\n const response: AxiosResponse = await axios.get(url, {\n headers,\n maxRedirects: 0,\n validateStatus: () => true, // Don't throw on any status\n withCredentials: true, // Include cookies for session auth\n });\n\n const status = response.status;\n const statusText = status >= 200 && status < 300 ? \"OK\" : \"Error\";\n\n if (status < 200 || status >= 300) {\n const body =\n typeof response.data === \"string\" ? response.data : JSON.stringify(response.data);\n throw new Error(`UserAPI request failed: ${status} ${statusText} - ${body}`);\n }\n\n // Return Response-like object for compatibility\n return {\n json: async () => response.data,\n text: async () =>\n typeof response.data === \"string\" ? response.data : JSON.stringify(response.data),\n };\n } catch (error: any) {\n // Handle network errors (fetch failed, connection refused, etc.)\n if (\n error.message?.includes(\"fetch failed\") ||\n error.message?.includes(\"ECONNREFUSED\") ||\n error.message?.includes(\"ENOTFOUND\") ||\n error.cause\n ) {\n const cause = error.cause?.message || error.cause || error.message;\n throw new Error(\n `Failed to connect to UserAPI at ${url}: ${cause}\\n` +\n `Please check:\\n` +\n `1. Your internet connection\\n` +\n `2. The API server is accessible: ${this.config.userApiServerURL}\\n` +\n `3. Firewall/proxy settings`,\n );\n }\n // Re-throw other errors as-is\n throw error;\n }\n }\n\n /**\n * Generate authentication headers for UserAPI requests\n */\n private async generateAuthHeaders(\n permission: Hex,\n expiry: bigint,\n ): Promise<Record<string, string>> {\n // Calculate permission signature using shared auth utility\n const { signature } = await calculatePermissionSignature({\n permission,\n expiry,\n appControllerAddress: this.config.appControllerAddress,\n publicClient: this.publicClient,\n walletClient: this.walletClient,\n });\n\n // Return auth headers\n return {\n Authorization: `Bearer ${stripHexPrefix(signature)}`,\n \"X-eigenx-expiry\": expiry.toString(),\n };\n }\n\n // ==========================================================================\n // SIWE Session Management\n // ==========================================================================\n\n /**\n * Login to the compute API using SIWE (Sign-In with Ethereum)\n *\n * This establishes a session with the compute API by verifying the SIWE message\n * and signature. On success, a session cookie is set in the browser.\n *\n * @param request - Login request containing SIWE message and signature\n * @returns Login result with the authenticated address\n *\n * @example\n * ```typescript\n * import { createSiweMessage } from \"@layr-labs/ecloud-sdk/browser\";\n *\n * const { message } = createSiweMessage({\n * address: userAddress,\n * chainId: 11155111,\n * domain: window.location.host,\n * uri: window.location.origin,\n * });\n *\n * const signature = await signMessageAsync({ message });\n * const result = await client.siweLogin({ message, signature });\n * ```\n */\n async siweLogin(request: LoginRequest): Promise<LoginResult> {\n return loginToComputeApi({ baseUrl: this.config.userApiServerURL }, request);\n }\n\n /**\n * Logout from the compute API\n *\n * This destroys the current session and clears the session cookie.\n *\n * @example\n * ```typescript\n * await client.siweLogout();\n * ```\n */\n async siweLogout(): Promise<void> {\n return logoutFromComputeApi({ baseUrl: this.config.userApiServerURL });\n }\n\n /**\n * Get the current SIWE session status from the compute API\n *\n * @returns Session information including authentication status and address\n *\n * @example\n * ```typescript\n * const session = await client.getSiweSession();\n * if (session.authenticated) {\n * console.log(`Logged in as ${session.address}`);\n * }\n * ```\n */\n async getSiweSession(): Promise<SessionInfo> {\n return getComputeApiSession({ baseUrl: this.config.userApiServerURL });\n }\n}\n\nfunction transformAppReleaseBuild(raw: unknown): AppReleaseBuild | undefined {\n if (!isJsonObject(raw)) return undefined;\n\n const depsRaw = raw.dependencies;\n const deps: Record<string, AppReleaseBuild> | undefined = isJsonObject(depsRaw)\n ? Object.fromEntries(\n Object.entries(depsRaw).flatMap(([digest, depRaw]) => {\n const parsed = transformAppReleaseBuild(depRaw);\n return parsed ? ([[digest, parsed]] as const) : [];\n }),\n )\n : undefined;\n\n return {\n buildId: readString(raw, \"build_id\") ?? readString(raw, \"buildId\"),\n billingAddress: readString(raw, \"billing_address\") ?? readString(raw, \"billingAddress\"),\n repoUrl: readString(raw, \"repo_url\") ?? readString(raw, \"repoUrl\"),\n gitRef: readString(raw, \"git_ref\") ?? readString(raw, \"gitRef\"),\n status: readString(raw, \"status\"),\n buildType: readString(raw, \"build_type\") ?? readString(raw, \"buildType\"),\n imageName: readString(raw, \"image_name\") ?? readString(raw, \"imageName\"),\n imageDigest: readString(raw, \"image_digest\") ?? readString(raw, \"imageDigest\"),\n imageUrl: readString(raw, \"image_url\") ?? readString(raw, \"imageUrl\"),\n provenanceJson: raw.provenance_json ?? raw.provenanceJson,\n provenanceSignature:\n readString(raw, \"provenance_signature\") ?? readString(raw, \"provenanceSignature\"),\n createdAt: readString(raw, \"created_at\") ?? readString(raw, \"createdAt\"),\n updatedAt: readString(raw, \"updated_at\") ?? readString(raw, \"updatedAt\"),\n errorMessage: readString(raw, \"error_message\") ?? readString(raw, \"errorMessage\"),\n dependencies: deps,\n };\n}\n\nfunction transformAppRelease(raw: unknown): AppRelease | undefined {\n if (!isJsonObject(raw)) return undefined;\n\n return {\n appId: readString(raw, \"appId\") ?? readString(raw, \"app_id\"),\n rmsReleaseId: readString(raw, \"rmsReleaseId\") ?? readString(raw, \"rms_release_id\"),\n imageDigest: readString(raw, \"imageDigest\") ?? readString(raw, \"image_digest\"),\n registryUrl: readString(raw, \"registryUrl\") ?? readString(raw, \"registry_url\"),\n publicEnv: readString(raw, \"publicEnv\") ?? readString(raw, \"public_env\"),\n encryptedEnv: readString(raw, \"encryptedEnv\") ?? readString(raw, \"encrypted_env\"),\n upgradeByTime: readNumber(raw, \"upgradeByTime\") ?? readNumber(raw, \"upgrade_by_time\"),\n createdAt: readString(raw, \"createdAt\") ?? readString(raw, \"created_at\"),\n createdAtBlock: readString(raw, \"createdAtBlock\") ?? readString(raw, \"created_at_block\"),\n build: raw.build ? transformAppReleaseBuild(raw.build) : undefined,\n };\n}\n","/**\n * Shared authentication utilities for API clients\n */\n\nimport { Hex, parseAbi, type Address, type PublicClient, type WalletClient } from \"viem\";\n\n// Minimal AppController ABI for permission calculation\nconst APP_CONTROLLER_ABI = parseAbi([\n \"function calculateApiPermissionDigestHash(bytes4 permission, uint256 expiry) view returns (bytes32)\",\n]);\n\nexport interface PermissionSignatureOptions {\n permission: Hex;\n expiry: bigint;\n appControllerAddress: Address;\n publicClient: PublicClient;\n walletClient: WalletClient;\n}\n\nexport interface PermissionSignatureResult {\n signature: string;\n digest: Hex;\n}\n\n/**\n * Calculate permission digest via AppController contract and sign it with EIP-191\n *\n * Works with any WalletClient - whether backed by a local private key or external signer.\n */\nexport async function calculatePermissionSignature(\n options: PermissionSignatureOptions,\n): Promise<PermissionSignatureResult> {\n const { permission, expiry, appControllerAddress, publicClient, walletClient } = options;\n\n // Calculate permission digest hash using AppController contract\n const digest = (await publicClient.readContract({\n address: appControllerAddress,\n abi: APP_CONTROLLER_ABI,\n functionName: \"calculateApiPermissionDigestHash\",\n args: [permission, expiry],\n })) as Hex;\n\n // Get account from wallet client\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n // Sign the digest using EIP-191 (signMessage handles prefixing automatically)\n const signature = await walletClient.signMessage({\n account,\n message: { raw: digest },\n });\n\n return { signature, digest };\n}\n\nexport interface BillingAuthSignatureOptions {\n walletClient: WalletClient;\n product: string;\n expiry: bigint;\n}\n\nexport interface BillingAuthSignatureResult {\n signature: Hex;\n expiry: bigint;\n}\n\nconst generateBillingSigData = (product: string, expiry: bigint) => {\n return {\n domain: {\n name: \"EigenCloud Billing API\",\n version: \"1\",\n },\n types: {\n BillingAuth: [\n { name: \"product\", type: \"string\" },\n { name: \"expiry\", type: \"uint256\" },\n ],\n },\n primaryType: \"BillingAuth\" as const,\n message: {\n product,\n expiry,\n },\n };\n};\n\n/**\n * Sign billing authentication message using EIP-712 typed data\n */\nexport async function calculateBillingAuthSignature(\n options: BillingAuthSignatureOptions,\n): Promise<BillingAuthSignatureResult> {\n const { walletClient, product, expiry } = options;\n\n // Get account from wallet client\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n // Sign using EIP-712 typed data\n const signature = await walletClient.signTypedData({\n account,\n ...generateBillingSigData(product, expiry),\n });\n\n return { signature, expiry };\n}\n\nexport interface BuildAuthSignatureOptions {\n walletClient: WalletClient;\n expiry: bigint;\n}\n\nexport interface BuildAuthSignatureResult {\n signature: Hex;\n expiry: bigint;\n}\n\n/**\n * Sign build authentication message using EIP-712 typed data\n */\nexport async function calculateBuildAuthSignature(\n options: BuildAuthSignatureOptions,\n): Promise<BuildAuthSignatureResult> {\n const { walletClient, expiry } = options;\n\n // Get account from wallet client\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n const signature = await walletClient.signTypedData({\n account,\n domain: {\n name: \"EigenCloud Build API\",\n version: \"1\",\n },\n types: {\n BuildAuth: [{ name: \"expiry\", type: \"uint256\" }],\n },\n primaryType: \"BuildAuth\",\n message: {\n expiry,\n },\n });\n\n return { signature, expiry };\n}\n","/**\n * BillingAPI Client to manage product subscriptions\n * Standalone client - does not depend on chain infrastructure\n *\n * Accepts viem's WalletClient which abstracts over both local accounts\n * (privateKeyToAccount) and external signers (MetaMask, etc.).\n *\n * Supports two authentication modes:\n * 1. EIP-712 signature auth (default) - signs each request with typed data\n * 2. Session auth (optional) - uses SIWE session cookies\n */\n\nimport axios, { AxiosResponse } from \"axios\";\nimport { Address, type WalletClient } from \"viem\";\nimport { ProductID, CreateSubscriptionOptions, CreateSubscriptionResponse, ProductSubscriptionResponse } from \"../types\";\nimport { calculateBillingAuthSignature } from \"./auth\";\nimport { BillingEnvironmentConfig } from \"../types\";\nimport {\n loginToBillingApi,\n logoutFromBillingApi,\n getBillingApiSession,\n type BillingSessionInfo,\n type BillingLoginResult,\n type BillingLoginRequest,\n} from \"../auth/billingSession\";\n\nexport interface BillingApiClientOptions {\n /**\n * Use session-based authentication instead of per-request signatures.\n * When true, the client will rely on session cookies set by SIWE login.\n * When false (default), uses EIP-712 typed data signatures for each request.\n */\n useSession?: boolean;\n}\n\n/**\n * BillingAPI Client for managing product subscriptions.\n */\nexport class BillingApiClient {\n private readonly useSession: boolean;\n\n constructor(\n private readonly config: BillingEnvironmentConfig,\n private readonly walletClient: WalletClient | null,\n private readonly options: BillingApiClientOptions = {},\n ) {\n this.useSession = options.useSession ?? false;\n\n // Validate that walletClient is provided when not using session auth\n if (!this.useSession && !walletClient) {\n throw new Error(\"WalletClient is required when not using session authentication\");\n }\n }\n\n /**\n * Get the address of the connected wallet\n * Returns undefined if using session auth without a wallet client\n */\n get address(): Address | undefined {\n const account = this.walletClient?.account;\n if (!account) {\n if (!this.useSession) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n return undefined;\n }\n return account.address;\n }\n\n /**\n * Get the base URL of the billing API\n */\n get baseUrl(): string {\n return this.config.billingApiServerURL;\n }\n\n // ==========================================================================\n // SIWE Session Methods\n // ==========================================================================\n\n /**\n * Login to the billing API using SIWE\n *\n * This establishes a session with the billing API by verifying the SIWE message\n * and signature. On success, a session cookie is set in the browser.\n *\n * @param request - Login request containing SIWE message and signature\n * @returns Login result with the authenticated address\n *\n * @example\n * ```typescript\n * const { message } = createSiweMessage({\n * address: userAddress,\n * chainId: 11155111,\n * domain: window.location.host,\n * uri: window.location.origin,\n * });\n *\n * const signature = await signMessageAsync({ message });\n * const result = await billingClient.siweLogin({ message, signature });\n * ```\n */\n async siweLogin(request: BillingLoginRequest): Promise<BillingLoginResult> {\n return loginToBillingApi({ baseUrl: this.baseUrl }, request);\n }\n\n /**\n * Logout from the billing API\n *\n * This destroys the current session and clears the session cookie.\n */\n async siweLogout(): Promise<void> {\n return logoutFromBillingApi({ baseUrl: this.baseUrl });\n }\n\n /**\n * Get the current session status from the billing API\n *\n * @returns Session information including authentication status and address\n */\n async getSession(): Promise<BillingSessionInfo> {\n return getBillingApiSession({ baseUrl: this.baseUrl });\n }\n\n /**\n * Check if there is a valid session\n *\n * @returns True if session is authenticated, false otherwise\n */\n async isSessionValid(): Promise<boolean> {\n const session = await this.getSession();\n return session.authenticated;\n }\n\n // ==========================================================================\n // Subscription Methods\n // ==========================================================================\n\n async createSubscription(productId: ProductID = \"compute\", options?: CreateSubscriptionOptions): Promise<CreateSubscriptionResponse> {\n const endpoint = `${this.config.billingApiServerURL}/products/${productId}/subscription`;\n const body = options ? {\n success_url: options.successUrl,\n cancel_url: options.cancelUrl,\n } : undefined;\n const resp = await this.makeAuthenticatedRequest(endpoint, \"POST\", productId, body);\n return resp.json();\n }\n\n async getSubscription(productId: ProductID = \"compute\"): Promise<ProductSubscriptionResponse> {\n const endpoint = `${this.config.billingApiServerURL}/products/${productId}/subscription`;\n const resp = await this.makeAuthenticatedRequest(endpoint, \"GET\", productId);\n return resp.json();\n }\n\n async cancelSubscription(productId: ProductID = \"compute\"): Promise<void> {\n const endpoint = `${this.config.billingApiServerURL}/products/${productId}/subscription`;\n await this.makeAuthenticatedRequest(endpoint, \"DELETE\", productId);\n }\n\n // ==========================================================================\n // Internal Methods\n // ==========================================================================\n\n /**\n * Make an authenticated request to the billing API\n *\n * Uses session auth if useSession is true, otherwise uses EIP-712 signature auth.\n */\n private async makeAuthenticatedRequest(\n url: string,\n method: \"GET\" | \"POST\" | \"DELETE\",\n productId: ProductID,\n body?: Record<string, unknown>,\n ): Promise<{ json: () => Promise<any>; text: () => Promise<string> }> {\n if (this.useSession) {\n return this.makeSessionAuthenticatedRequest(url, method, body);\n }\n return this.makeSignatureAuthenticatedRequest(url, method, productId, body);\n }\n\n /**\n * Make a request using session-based authentication (cookies)\n */\n private async makeSessionAuthenticatedRequest(\n url: string,\n method: \"GET\" | \"POST\" | \"DELETE\",\n body?: Record<string, unknown>,\n ): Promise<{ json: () => Promise<any>; text: () => Promise<string> }> {\n const headers: Record<string, string> = {};\n\n // Add content-type header if body is present\n if (body) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n try {\n // Use fetch with credentials: 'include' for cookie-based auth\n const response = await fetch(url, {\n method,\n credentials: \"include\", // Include cookies for session management\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n const status = response.status;\n const statusText = status >= 200 && status < 300 ? \"OK\" : \"Error\";\n\n if (status < 200 || status >= 300) {\n let errorBody: string;\n try {\n errorBody = await response.text();\n } catch {\n errorBody = statusText;\n }\n throw new Error(`BillingAPI request failed: ${status} ${statusText} - ${errorBody}`);\n }\n\n // Return Response-like object for compatibility\n const responseData = await response.json();\n return {\n json: async () => responseData,\n text: async () => JSON.stringify(responseData),\n };\n } catch (error: any) {\n // Handle network errors\n if (error.name === \"TypeError\" || error.message?.includes(\"fetch\")) {\n throw new Error(\n `Failed to connect to BillingAPI at ${url}: ${error.message}\\n` +\n `Please check:\\n` +\n `1. Your internet connection\\n` +\n `2. The API server is accessible: ${this.config.billingApiServerURL}\\n` +\n `3. Firewall/proxy settings`,\n );\n }\n // Re-throw other errors as-is\n throw error;\n }\n }\n\n /**\n * Make a request using EIP-712 signature authentication\n */\n private async makeSignatureAuthenticatedRequest(\n url: string,\n method: \"GET\" | \"POST\" | \"DELETE\",\n productId: ProductID,\n body?: Record<string, unknown>,\n ): Promise<{ json: () => Promise<any>; text: () => Promise<string> }> {\n if (!this.walletClient) {\n throw new Error(\"WalletClient is required for signature authentication\");\n }\n\n // Calculate expiry (5 minutes from now)\n const expiry = BigInt(Math.floor(Date.now() / 1000) + 5 * 60);\n\n // Use EIP-712 typed data signature for billing auth\n const { signature } = await calculateBillingAuthSignature({\n walletClient: this.walletClient,\n product: productId,\n expiry,\n });\n\n // Prepare headers\n const headers: Record<string, string> = {\n Authorization: `Bearer ${signature}`,\n \"X-Account\": this.address!,\n \"X-Expiry\": expiry.toString(),\n };\n\n // Add content-type header if body is present\n if (body) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n try {\n // Use axios to make the request\n const response: AxiosResponse = await axios({\n method,\n url,\n headers,\n data: body,\n timeout: 30_000,\n maxRedirects: 0,\n validateStatus: () => true, // Don't throw on any status\n });\n\n const status = response.status;\n const statusText = status >= 200 && status < 300 ? \"OK\" : \"Error\";\n\n if (status < 200 || status >= 300) {\n const body =\n typeof response.data === \"string\" ? response.data : JSON.stringify(response.data);\n throw new Error(`BillingAPI request failed: ${status} ${statusText} - ${body}`);\n }\n\n // Return Response-like object for compatibility\n return {\n json: async () => response.data,\n text: async () =>\n typeof response.data === \"string\" ? response.data : JSON.stringify(response.data),\n };\n } catch (error: any) {\n // Handle network errors\n if (\n error.message?.includes(\"fetch failed\") ||\n error.message?.includes(\"ECONNREFUSED\") ||\n error.message?.includes(\"ENOTFOUND\") ||\n error.cause\n ) {\n const cause = error.cause?.message || error.cause || error.message;\n throw new Error(\n `Failed to connect to BillingAPI at ${url}: ${cause}\\n` +\n `Please check:\\n` +\n `1. Your internet connection\\n` +\n `2. The API server is accessible: ${this.config.billingApiServerURL}\\n` +\n `3. Firewall/proxy settings`,\n );\n }\n // Re-throw other errors as-is\n throw error;\n }\n }\n}\n","/**\n * Billing API Session Management\n *\n * This module provides utilities for managing authentication sessions with the billing API\n * using SIWE (Sign-In with Ethereum).\n *\n * The billing API now supports the same SIWE-based session authentication as the compute API,\n * allowing users to sign once and authenticate to both APIs simultaneously.\n */\n\nimport { Address, Hex } from \"viem\";\n\nexport interface BillingApiConfig {\n /** Base URL of the billing API (e.g., \"https://billing.eigencloud.xyz\") */\n baseUrl: string;\n}\n\nexport interface BillingSessionInfo {\n /** Whether the session is authenticated */\n authenticated: boolean;\n /** Authenticated wallet address (if authenticated) */\n address?: Address;\n /** Chain ID used for authentication (if authenticated) */\n chainId?: number;\n /** Unix timestamp when authentication occurred (if authenticated) */\n authenticatedAt?: number;\n}\n\nexport interface BillingLoginResult {\n /** Whether login was successful */\n success: boolean;\n /** Authenticated wallet address */\n address: Address;\n}\n\nexport interface BillingLoginRequest {\n /** SIWE message string */\n message: string;\n /** Hex-encoded signature (with or without 0x prefix) */\n signature: Hex | string;\n}\n\n/**\n * Error thrown when billing session operations fail\n */\nexport class BillingSessionError extends Error {\n constructor(\n message: string,\n public readonly code:\n | \"NETWORK_ERROR\"\n | \"INVALID_SIGNATURE\"\n | \"INVALID_MESSAGE\"\n | \"SESSION_EXPIRED\"\n | \"UNAUTHORIZED\"\n | \"UNKNOWN\",\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"BillingSessionError\";\n }\n}\n\n/**\n * Strip 0x prefix from hex string if present\n */\nfunction stripHexPrefix(hex: string): string {\n return hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n}\n\n/**\n * Parse error response body\n */\nasync function parseErrorResponse(response: Response): Promise<string> {\n try {\n const data = (await response.json()) as { error?: string };\n return data.error || response.statusText;\n } catch {\n return response.statusText;\n }\n}\n\n/**\n * Login to the billing API using SIWE\n *\n * This establishes a session with the billing API by verifying the SIWE message\n * and signature. On success, a session cookie is set in the browser.\n *\n * The billing API accepts the same SIWE message format as the compute API,\n * so users only need to sign once and can send the same message/signature\n * to both APIs.\n *\n * @param config - Billing API configuration\n * @param request - Login request containing SIWE message and signature\n * @returns Login result with the authenticated address\n *\n * @example\n * ```typescript\n * import { createSiweMessage, loginToBillingApi } from \"@layr-labs/ecloud-sdk/browser\";\n *\n * const { message } = createSiweMessage({\n * address: userAddress,\n * chainId: 11155111,\n * domain: window.location.host,\n * uri: window.location.origin,\n * });\n *\n * const signature = await signMessageAsync({ message });\n *\n * // Can send to both APIs with the same message/signature\n * const [computeResult, billingResult] = await Promise.all([\n * loginToComputeApi({ baseUrl: computeApiUrl }, { message, signature }),\n * loginToBillingApi({ baseUrl: billingApiUrl }, { message, signature }),\n * ]);\n * ```\n */\nexport async function loginToBillingApi(\n config: BillingApiConfig,\n request: BillingLoginRequest,\n): Promise<BillingLoginResult> {\n let response: Response;\n\n try {\n response = await fetch(`${config.baseUrl}/auth/siwe/login`, {\n method: \"POST\",\n credentials: \"include\", // Include cookies for session management\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n message: request.message,\n signature: stripHexPrefix(request.signature),\n }),\n });\n } catch (error) {\n throw new BillingSessionError(\n `Network error connecting to ${config.baseUrl}: ${error instanceof Error ? error.message : String(error)}`,\n \"NETWORK_ERROR\",\n );\n }\n\n if (!response.ok) {\n const errorMessage = await parseErrorResponse(response);\n const status = response.status;\n\n if (status === 400) {\n if (errorMessage.toLowerCase().includes(\"siwe\")) {\n throw new BillingSessionError(`Invalid SIWE message: ${errorMessage}`, \"INVALID_MESSAGE\", status);\n }\n throw new BillingSessionError(`Bad request: ${errorMessage}`, \"INVALID_MESSAGE\", status);\n }\n\n if (status === 401) {\n throw new BillingSessionError(`Invalid signature: ${errorMessage}`, \"INVALID_SIGNATURE\", status);\n }\n\n throw new BillingSessionError(`Login failed: ${errorMessage}`, \"UNKNOWN\", status);\n }\n\n const data = (await response.json()) as { success: boolean; address: string };\n\n return {\n success: data.success,\n address: data.address as Address,\n };\n}\n\n/**\n * Get the current session status from the billing API\n *\n * @param config - Billing API configuration\n * @returns Session information including authentication status and address\n *\n * @example\n * ```typescript\n * const session = await getBillingApiSession({ baseUrl: \"https://billing.eigencloud.xyz\" });\n * if (session.authenticated) {\n * console.log(`Logged in as ${session.address}`);\n * }\n * ```\n */\nexport async function getBillingApiSession(config: BillingApiConfig): Promise<BillingSessionInfo> {\n let response: Response;\n\n try {\n response = await fetch(`${config.baseUrl}/auth/session`, {\n method: \"GET\",\n credentials: \"include\", // Include cookies for session management\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n } catch {\n // Network error - return unauthenticated session\n return {\n authenticated: false,\n };\n }\n\n // If we get a 401, return unauthenticated session\n if (response.status === 401) {\n return {\n authenticated: false,\n };\n }\n\n if (!response.ok) {\n const errorMessage = await parseErrorResponse(response);\n throw new BillingSessionError(`Failed to get session: ${errorMessage}`, \"UNKNOWN\", response.status);\n }\n\n const data = (await response.json()) as {\n authenticated: boolean;\n address?: string;\n chainId?: number;\n authenticatedAt?: number;\n };\n\n return {\n authenticated: data.authenticated,\n address: data.address as Address | undefined,\n chainId: data.chainId,\n authenticatedAt: data.authenticatedAt,\n };\n}\n\n/**\n * Logout from the billing API\n *\n * This destroys the current session and clears the session cookie.\n *\n * @param config - Billing API configuration\n *\n * @example\n * ```typescript\n * await logoutFromBillingApi({ baseUrl: \"https://billing.eigencloud.xyz\" });\n * ```\n */\nexport async function logoutFromBillingApi(config: BillingApiConfig): Promise<void> {\n let response: Response;\n\n try {\n response = await fetch(`${config.baseUrl}/auth/logout`, {\n method: \"POST\",\n credentials: \"include\", // Include cookies for session management\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n } catch (error) {\n throw new BillingSessionError(\n `Network error connecting to ${config.baseUrl}: ${error instanceof Error ? error.message : String(error)}`,\n \"NETWORK_ERROR\",\n );\n }\n\n // Ignore 401 errors during logout (already logged out)\n if (response.status === 401) {\n return;\n }\n\n if (!response.ok) {\n const errorMessage = await parseErrorResponse(response);\n throw new BillingSessionError(`Logout failed: ${errorMessage}`, \"UNKNOWN\", response.status);\n }\n}\n\n/**\n * Check if a billing session is still valid (not expired)\n *\n * This is a convenience function that checks the session status\n * and returns a boolean.\n *\n * @param config - Billing API configuration\n * @returns True if session is authenticated, false otherwise\n */\nexport async function isBillingSessionValid(config: BillingApiConfig): Promise<boolean> {\n const session = await getBillingApiSession(config);\n return session.authenticated;\n}\n\n/**\n * Login to both compute and billing APIs simultaneously\n *\n * This is a convenience function that sends the same SIWE message and signature\n * to both APIs in parallel, establishing sessions with both services at once.\n *\n * @param computeConfig - Compute API configuration\n * @param billingConfig - Billing API configuration\n * @param request - Login request containing SIWE message and signature\n * @returns Object containing login results for both APIs\n *\n * @example\n * ```typescript\n * import { createSiweMessage, loginToBothApis } from \"@layr-labs/ecloud-sdk/browser\";\n *\n * const { message } = createSiweMessage({\n * address: userAddress,\n * chainId: 11155111,\n * domain: window.location.host,\n * uri: window.location.origin,\n * });\n *\n * const signature = await signMessageAsync({ message });\n * const { compute, billing } = await loginToBothApis(\n * { baseUrl: computeApiUrl },\n * { baseUrl: billingApiUrl },\n * { message, signature }\n * );\n * ```\n */\nexport async function loginToBothApis(\n computeConfig: { baseUrl: string },\n billingConfig: BillingApiConfig,\n request: BillingLoginRequest,\n): Promise<{\n compute: BillingLoginResult;\n billing: BillingLoginResult;\n}> {\n // Import the compute login function dynamically to avoid circular dependencies\n const { loginToComputeApi } = await import(\"./session\");\n\n const [compute, billing] = await Promise.all([\n loginToComputeApi(computeConfig, request),\n loginToBillingApi(billingConfig, request),\n ]);\n\n return { compute, billing };\n}\n\n/**\n * Logout from both compute and billing APIs simultaneously\n *\n * @param computeConfig - Compute API configuration\n * @param billingConfig - Billing API configuration\n *\n * @example\n * ```typescript\n * await logoutFromBothApis(\n * { baseUrl: computeApiUrl },\n * { baseUrl: billingApiUrl }\n * );\n * ```\n */\nexport async function logoutFromBothApis(\n computeConfig: { baseUrl: string },\n billingConfig: BillingApiConfig,\n): Promise<void> {\n // Import the compute logout function dynamically to avoid circular dependencies\n const { logoutFromComputeApi } = await import(\"./session\");\n\n await Promise.all([\n logoutFromComputeApi(computeConfig),\n logoutFromBillingApi(billingConfig),\n ]);\n}\n","/**\n * Build API Client to manage verifiable builds and provenance\n *\n * This is a standalone HTTP client that talks to the (compute) UserAPI host.\n */\n\nimport axios, { AxiosRequestConfig, AxiosResponse } from \"axios\";\nimport { Address, type WalletClient } from \"viem\";\nimport { calculateBillingAuthSignature } from \"./auth\";\n\nconst MAX_RETRIES = 5;\nconst INITIAL_BACKOFF_MS = 1000;\nconst MAX_BACKOFF_MS = 30000;\n\nasync function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction getRetryDelay(res: AxiosResponse, attempt: number): number {\n const retryAfter = res.headers[\"retry-after\"];\n if (retryAfter) {\n const seconds = parseInt(retryAfter, 10);\n if (!isNaN(seconds)) {\n return Math.min(seconds * 1000, MAX_BACKOFF_MS);\n }\n }\n return Math.min(INITIAL_BACKOFF_MS * Math.pow(2, attempt), MAX_BACKOFF_MS);\n}\n\nasync function requestWithRetry(config: AxiosRequestConfig): Promise<AxiosResponse> {\n let lastResponse: AxiosResponse | undefined;\n\n for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {\n const res = await axios({ ...config, validateStatus: () => true });\n lastResponse = res;\n\n if (res.status !== 429) {\n return res;\n }\n\n if (attempt < MAX_RETRIES) {\n const delay = getRetryDelay(res, attempt);\n await sleep(delay);\n }\n }\n\n return lastResponse!;\n}\n\nexport interface BuildApiClientOptions {\n baseUrl: string;\n walletClient?: WalletClient;\n clientId?: string;\n /** Use session-based auth (cookies) instead of signature-based auth */\n useSession?: boolean;\n /**\n * Billing session ID (value of the billing_session cookie).\n * When provided with useSession=true, this is sent via X-Billing-Session header\n * to authenticate with the billing API for subscription verification.\n * Required for submitBuild when using session auth.\n */\n billingSessionId?: string;\n}\n\nexport class BuildApiClient {\n private readonly baseUrl: string;\n private readonly walletClient?: WalletClient;\n private readonly clientId?: string;\n private readonly useSession: boolean;\n private billingSessionId?: string;\n\n constructor(options: BuildApiClientOptions) {\n // Strip trailing slashes without regex to avoid ReDoS\n let url = options.baseUrl;\n while (url.endsWith(\"/\")) {\n url = url.slice(0, -1);\n }\n this.baseUrl = url;\n this.clientId = options.clientId;\n this.walletClient = options.walletClient;\n this.useSession = options.useSession ?? false;\n this.billingSessionId = options.billingSessionId;\n }\n\n /**\n * Update the billing session ID.\n * Call this after logging into the billing API to enable session-based auth for builds.\n */\n setBillingSessionId(sessionId: string | undefined): void {\n this.billingSessionId = sessionId;\n }\n\n /**\n * Get the address of the connected wallet\n */\n get address(): Address {\n const account = this.walletClient?.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n return account.address;\n }\n\n /**\n * Submit a new build request.\n * Supports two auth modes (session auth is tried first when billingSessionId is available):\n * 1. Session-based auth: X-Billing-Session header (forwarded billing_session cookie)\n * 2. Signature-based auth: Authorization + X-Account + X-eigenx-expiry headers (requires walletClient)\n */\n async submitBuild(payload: {\n repo_url: string;\n git_ref: string;\n dockerfile_path: string;\n caddyfile_path?: string;\n build_context_path: string;\n dependencies: string[];\n }): Promise<{ build_id: string }> {\n // Use session auth if billingSessionId is available and useSession is enabled\n if (this.useSession && this.billingSessionId) {\n return this.billingSessionAuthJsonRequest<{ build_id: string }>(\"/builds\", \"POST\", payload);\n }\n // Fall back to signature auth (requires walletClient)\n return this.signatureAuthJsonRequest<{ build_id: string }>(\"/builds\", \"POST\", payload);\n }\n\n async getBuild(buildId: string): Promise<any> {\n return this.publicJsonRequest(`/builds/${encodeURIComponent(buildId)}`);\n }\n\n async getBuildByDigest(digest: string): Promise<any> {\n return this.publicJsonRequest(`/builds/image/${encodeURIComponent(digest)}`);\n }\n\n async verify(identifier: string): Promise<any> {\n return this.publicJsonRequest(`/builds/verify/${encodeURIComponent(identifier)}`);\n }\n\n /**\n * Get build logs. Supports session auth (identity verification only, no billing check).\n */\n async getLogs(buildId: string): Promise<string> {\n return this.sessionOrSignatureTextRequest(`/builds/${encodeURIComponent(buildId)}/logs`);\n }\n\n async listBuilds(params: {\n billing_address: string;\n limit?: number;\n offset?: number;\n }): Promise<any[]> {\n const res = await requestWithRetry({\n url: `${this.baseUrl}/builds`,\n method: \"GET\",\n params,\n headers: this.clientId ? { \"x-client-id\": this.clientId } : undefined,\n timeout: 60_000,\n validateStatus: () => true,\n withCredentials: this.useSession,\n });\n if (res.status < 200 || res.status >= 300) throw buildApiHttpError(res);\n return res.data as any[];\n }\n\n private async publicJsonRequest(path: string): Promise<any> {\n const res = await requestWithRetry({\n url: `${this.baseUrl}${path}`,\n method: \"GET\",\n headers: this.clientId ? { \"x-client-id\": this.clientId } : undefined,\n timeout: 60_000,\n validateStatus: () => true,\n withCredentials: this.useSession,\n });\n if (res.status < 200 || res.status >= 300) throw buildApiHttpError(res);\n return res.data;\n }\n\n /**\n * Make a request that ALWAYS requires signature auth (for billing verification).\n * Used for endpoints like POST /builds that need to verify subscription status.\n */\n private async signatureAuthJsonRequest<T>(\n path: string,\n method: \"POST\" | \"GET\",\n body?: unknown,\n ): Promise<T> {\n if (!this.walletClient?.account) {\n throw new Error(\"WalletClient with account required for authenticated requests\");\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n if (this.clientId) headers[\"x-client-id\"] = this.clientId;\n\n // Builds API uses BillingAuth signature format (same as Billing API).\n // Keep expiry short to reduce replay window.\n const expiry = BigInt(Math.floor(Date.now() / 1000) + 60);\n const { signature } = await calculateBillingAuthSignature({\n walletClient: this.walletClient,\n product: \"compute\",\n expiry,\n });\n headers.Authorization = `Bearer ${signature}`;\n headers[\"X-eigenx-expiry\"] = expiry.toString();\n headers[\"X-Account\"] = this.address;\n\n const res = await requestWithRetry({\n url: `${this.baseUrl}${path}`,\n method,\n headers,\n data: body,\n timeout: 60_000,\n validateStatus: () => true,\n withCredentials: this.useSession,\n });\n if (res.status < 200 || res.status >= 300) throw buildApiHttpError(res);\n return res.data as T;\n }\n\n /**\n * Make a request using billing session auth (for billing verification without wallet signature).\n * Forwards the billing_session cookie value via X-Billing-Session header.\n * Used for endpoints that need to verify subscription status when using session-based auth.\n */\n private async billingSessionAuthJsonRequest<T>(\n path: string,\n method: \"POST\" | \"GET\",\n body?: unknown,\n ): Promise<T> {\n if (!this.billingSessionId) {\n throw new Error(\"billingSessionId required for session-based billing auth\");\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"X-Billing-Session\": this.billingSessionId,\n };\n if (this.clientId) headers[\"x-client-id\"] = this.clientId;\n\n const res = await requestWithRetry({\n url: `${this.baseUrl}${path}`,\n method,\n headers,\n data: body,\n timeout: 60_000,\n validateStatus: () => true,\n withCredentials: this.useSession,\n });\n if (res.status < 200 || res.status >= 300) throw buildApiHttpError(res);\n return res.data as T;\n }\n\n /**\n * Make an authenticated request that can use session OR signature auth.\n * When useSession is true, relies on cookies for identity verification.\n * Used for endpoints that only need identity verification (not billing).\n */\n private async sessionOrSignatureTextRequest(path: string): Promise<string> {\n const headers: Record<string, string> = {};\n if (this.clientId) headers[\"x-client-id\"] = this.clientId;\n\n // When using session auth, rely on cookies instead of signature headers\n if (!this.useSession) {\n if (!this.walletClient?.account) {\n throw new Error(\"WalletClient with account required for authenticated requests\");\n }\n\n const expiry = BigInt(Math.floor(Date.now() / 1000) + 60);\n const { signature } = await calculateBillingAuthSignature({\n walletClient: this.walletClient,\n product: \"compute\",\n expiry,\n });\n headers.Authorization = `Bearer ${signature}`;\n headers[\"X-eigenx-expiry\"] = expiry.toString();\n headers[\"X-Account\"] = this.address;\n }\n\n const res = await requestWithRetry({\n url: `${this.baseUrl}${path}`,\n method: \"GET\",\n headers,\n timeout: 60_000,\n responseType: \"text\",\n validateStatus: () => true,\n withCredentials: this.useSession,\n });\n if (res.status < 200 || res.status >= 300) throw buildApiHttpError(res);\n return typeof res.data === \"string\" ? res.data : JSON.stringify(res.data);\n }\n}\n\nfunction buildApiHttpError(res: AxiosResponse): Error {\n const status = res.status;\n const body = typeof res.data === \"string\" ? res.data : res.data ? JSON.stringify(res.data) : \"\";\n const url = res.config?.url ? ` ${res.config.url}` : \"\";\n return new Error(`BuildAPI request failed: ${status}${url} - ${body || \"Unknown error\"}`);\n}\n","/**\n * EIP-7702 transaction handling\n *\n * This module handles EIP-7702 delegation and batch execution.\n */\n\nimport { Address, Hex, encodeFunctionData, encodeAbiParameters, decodeErrorResult } from \"viem\";\n\nimport type {\n WalletClient,\n PublicClient,\n SendTransactionParameters,\n SignAuthorizationReturnType,\n} from \"viem\";\nimport { EnvironmentConfig, Logger, noopLogger } from \"../types\";\n\nimport ERC7702DelegatorABI from \"../abis/ERC7702Delegator.json\";\n\nimport { GasEstimate, formatETH } from \"./caller\";\n\n// Mode 0x01 is executeBatchMode (32 bytes, padded, big endian)\nconst EXECUTE_BATCH_MODE =\n \"0x0100000000000000000000000000000000000000000000000000000000000000\" as Hex;\n\nconst GAS_LIMIT_BUFFER_PERCENTAGE = 20n; // 20%\nconst GAS_PRICE_BUFFER_PERCENTAGE = 100n; // 100%\n\nexport type Execution = {\n target: Address;\n value: bigint;\n callData: Hex;\n};\n\n/**\n * Encode executions array and pack into execute function call data\n */\nfunction encodeExecuteBatchData(executions: Execution[]): Hex {\n const encodedExecutions = encodeAbiParameters(\n [\n {\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"callData\", type: \"bytes\" },\n ],\n },\n ],\n [executions],\n );\n\n return encodeFunctionData({\n abi: ERC7702DelegatorABI,\n functionName: \"execute\",\n args: [EXECUTE_BATCH_MODE, encodedExecutions],\n });\n}\n\n/**\n * Options for estimating batch gas\n */\nexport interface EstimateBatchGasOptions {\n publicClient: PublicClient;\n account: Address;\n executions: Execution[];\n}\n\n/**\n * Estimate gas cost for a batch transaction\n *\n * Use this to get cost estimate before prompting user for confirmation.\n */\nexport async function estimateBatchGas(options: EstimateBatchGasOptions): Promise<GasEstimate> {\n const { publicClient, account, executions } = options;\n\n const executeBatchData = encodeExecuteBatchData(executions);\n\n // EIP-7702 transactions send to self (the EOA with delegated code)\n const [gasTipCap, block, estimatedGas] = await Promise.all([\n publicClient.estimateMaxPriorityFeePerGas(),\n publicClient.getBlock(),\n publicClient.estimateGas({\n account,\n to: account,\n data: executeBatchData,\n }),\n ]);\n\n const baseFee = block.baseFeePerGas ?? 0n;\n\n // Calculate gas price with 100% buffer: (baseFee + gasTipCap) * 2\n const maxFeePerGas = ((baseFee + gasTipCap) * (100n + GAS_PRICE_BUFFER_PERCENTAGE)) / 100n;\n\n // Add 20% buffer to gas limit\n const gasLimit = (estimatedGas * (100n + GAS_LIMIT_BUFFER_PERCENTAGE)) / 100n;\n\n const maxCostWei = gasLimit * maxFeePerGas;\n\n return {\n gasLimit,\n maxFeePerGas,\n maxPriorityFeePerGas: gasTipCap,\n maxCostWei,\n maxCostEth: formatETH(maxCostWei),\n };\n}\n\nexport interface ExecuteBatchOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n executions: Execution[];\n pendingMessage: string;\n /** Optional gas params from estimation */\n gas?: GasEstimate;\n}\n\n/**\n * Check if account is delegated to ERC-7702 delegator\n */\nexport async function checkERC7702Delegation(\n publicClient: PublicClient,\n account: Address,\n delegatorAddress: Address,\n): Promise<boolean> {\n const code = await publicClient.getCode({ address: account });\n if (!code) {\n return false;\n }\n\n // Check if code matches EIP-7702 delegation pattern: 0xef0100 || delegator_address\n const expectedCode = `0xef0100${delegatorAddress.slice(2)}`;\n return code.toLowerCase() === expectedCode.toLowerCase();\n}\n\n/**\n * Execute batch of operations via EIP-7702 delegator\n */\nexport async function executeBatch(options: ExecuteBatchOptions, logger: Logger = noopLogger): Promise<Hex> {\n const { walletClient, publicClient, environmentConfig, executions, pendingMessage, gas } =\n options;\n\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"Wallet client must have an account\");\n }\n\n const chain = walletClient.chain;\n if (!chain) {\n throw new Error(\"Wallet client must have a chain\");\n }\n\n const executeBatchData = encodeExecuteBatchData(executions);\n\n // Check if account is delegated\n const isDelegated = await checkERC7702Delegation(\n publicClient,\n account.address,\n environmentConfig.erc7702DelegatorAddress as Address,\n );\n\n // 4. Create authorization if needed\n let authorizationList: Array<SignAuthorizationReturnType> = [];\n\n if (!isDelegated) {\n const transactionNonce = await publicClient.getTransactionCount({\n address: account.address,\n blockTag: \"pending\",\n });\n\n const chainId = await publicClient.getChainId();\n const authorizationNonce = transactionNonce + 1;\n\n logger.debug(\"Using wallet client signing for EIP-7702 authorization\");\n\n const signedAuthorization = await walletClient.signAuthorization({\n account: account.address,\n contractAddress: environmentConfig.erc7702DelegatorAddress as Address,\n chainId: chainId,\n nonce: Number(authorizationNonce),\n });\n\n authorizationList = [signedAuthorization];\n }\n\n // 5. Show pending message\n if (pendingMessage) {\n logger.info(pendingMessage);\n }\n\n const txRequest: SendTransactionParameters = {\n account: walletClient.account!,\n chain,\n to: account.address,\n data: executeBatchData,\n value: 0n,\n };\n\n if (authorizationList.length > 0) {\n txRequest.authorizationList = authorizationList;\n }\n\n // Add gas params if provided\n if (gas?.maxFeePerGas) {\n txRequest.maxFeePerGas = gas.maxFeePerGas;\n }\n if (gas?.maxPriorityFeePerGas) {\n txRequest.maxPriorityFeePerGas = gas.maxPriorityFeePerGas;\n }\n\n const hash = await walletClient.sendTransaction(txRequest);\n logger.info(`Transaction sent: ${hash}`);\n\n const receipt = await publicClient.waitForTransactionReceipt({ hash });\n\n if (receipt.status === \"reverted\") {\n let revertReason = \"Unknown reason\";\n try {\n await publicClient.call({\n to: account.address,\n data: executeBatchData,\n account: account.address,\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (callError: any) {\n if (callError.data) {\n try {\n const decoded = decodeErrorResult({\n abi: ERC7702DelegatorABI,\n data: callError.data,\n });\n revertReason = `${decoded.errorName}: ${JSON.stringify(decoded.args)}`;\n } catch {\n revertReason = callError.message || \"Unknown reason\";\n }\n } else {\n revertReason = callError.message || \"Unknown reason\";\n }\n }\n throw new Error(`Transaction reverted: ${hash}. Reason: ${revertReason}`);\n }\n\n return hash;\n}\n","[\n {\n \"type\": \"constructor\",\n \"inputs\": [\n {\n \"name\": \"_delegationManager\",\n \"type\": \"address\",\n \"internalType\": \"contractIDelegationManager\"\n },\n {\n \"name\": \"_entryPoint\",\n \"type\": \"address\",\n \"internalType\": \"contractIEntryPoint\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"receive\",\n \"stateMutability\": \"payable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"DOMAIN_VERSION\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"NAME\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"PACKED_USER_OP_TYPEHASH\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"VERSION\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"addDeposit\",\n \"inputs\": [],\n \"outputs\": [],\n \"stateMutability\": \"payable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"delegationManager\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIDelegationManager\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"disableDelegation\",\n \"inputs\": [\n {\n \"name\": \"_delegation\",\n \"type\": \"tuple\",\n \"internalType\": \"structDelegation\",\n \"components\": [\n {\n \"name\": \"delegate\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"delegator\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"authority\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"caveats\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structCaveat[]\",\n \"components\": [\n {\n \"name\": \"enforcer\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"terms\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"args\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n },\n {\n \"name\": \"salt\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"signature\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"eip712Domain\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"fields\",\n \"type\": \"bytes1\",\n \"internalType\": \"bytes1\"\n },\n {\n \"name\": \"name\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n },\n {\n \"name\": \"version\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n },\n {\n \"name\": \"chainId\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"verifyingContract\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"salt\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"extensions\",\n \"type\": \"uint256[]\",\n \"internalType\": \"uint256[]\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"enableDelegation\",\n \"inputs\": [\n {\n \"name\": \"_delegation\",\n \"type\": \"tuple\",\n \"internalType\": \"structDelegation\",\n \"components\": [\n {\n \"name\": \"delegate\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"delegator\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"authority\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"caveats\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structCaveat[]\",\n \"components\": [\n {\n \"name\": \"enforcer\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"terms\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"args\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n },\n {\n \"name\": \"salt\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"signature\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"entryPoint\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIEntryPoint\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"execute\",\n \"inputs\": [\n {\n \"name\": \"_execution\",\n \"type\": \"tuple\",\n \"internalType\": \"structExecution\",\n \"components\": [\n {\n \"name\": \"target\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"value\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"callData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"payable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"execute\",\n \"inputs\": [\n {\n \"name\": \"_mode\",\n \"type\": \"bytes32\",\n \"internalType\": \"ModeCode\"\n },\n {\n \"name\": \"_executionCalldata\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"payable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"executeFromExecutor\",\n \"inputs\": [\n {\n \"name\": \"_mode\",\n \"type\": \"bytes32\",\n \"internalType\": \"ModeCode\"\n },\n {\n \"name\": \"_executionCalldata\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"returnData_\",\n \"type\": \"bytes[]\",\n \"internalType\": \"bytes[]\"\n }\n ],\n \"stateMutability\": \"payable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getDeposit\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getDomainHash\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getNonce\",\n \"inputs\": [\n {\n \"name\": \"_key\",\n \"type\": \"uint192\",\n \"internalType\": \"uint192\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getNonce\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getPackedUserOperationHash\",\n \"inputs\": [\n {\n \"name\": \"_userOp\",\n \"type\": \"tuple\",\n \"internalType\": \"structPackedUserOperation\",\n \"components\": [\n {\n \"name\": \"sender\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"nonce\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"initCode\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"callData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"accountGasLimits\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"preVerificationGas\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"gasFees\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"paymasterAndData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"signature\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getPackedUserOperationTypedDataHash\",\n \"inputs\": [\n {\n \"name\": \"_userOp\",\n \"type\": \"tuple\",\n \"internalType\": \"structPackedUserOperation\",\n \"components\": [\n {\n \"name\": \"sender\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"nonce\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"initCode\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"callData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"accountGasLimits\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"preVerificationGas\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"gasFees\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"paymasterAndData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"signature\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"isDelegationDisabled\",\n \"inputs\": [\n {\n \"name\": \"_delegationHash\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bool\",\n \"internalType\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"isValidSignature\",\n \"inputs\": [\n {\n \"name\": \"_hash\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"_signature\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"magicValue_\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"onERC1155BatchReceived\",\n \"inputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"uint256[]\",\n \"internalType\": \"uint256[]\"\n },\n {\n \"name\": \"\",\n \"type\": \"uint256[]\",\n \"internalType\": \"uint256[]\"\n },\n {\n \"name\": \"\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"onERC1155Received\",\n \"inputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"onERC721Received\",\n \"inputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"redeemDelegations\",\n \"inputs\": [\n {\n \"name\": \"_permissionContexts\",\n \"type\": \"bytes[]\",\n \"internalType\": \"bytes[]\"\n },\n {\n \"name\": \"_modes\",\n \"type\": \"bytes32[]\",\n \"internalType\": \"ModeCode[]\"\n },\n {\n \"name\": \"_executionCallDatas\",\n \"type\": \"bytes[]\",\n \"internalType\": \"bytes[]\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"supportsExecutionMode\",\n \"inputs\": [\n {\n \"name\": \"_mode\",\n \"type\": \"bytes32\",\n \"internalType\": \"ModeCode\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bool\",\n \"internalType\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"supportsInterface\",\n \"inputs\": [\n {\n \"name\": \"_interfaceId\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bool\",\n \"internalType\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"validateUserOp\",\n \"inputs\": [\n {\n \"name\": \"_userOp\",\n \"type\": \"tuple\",\n \"internalType\": \"structPackedUserOperation\",\n \"components\": [\n {\n \"name\": \"sender\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"nonce\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"initCode\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"callData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"accountGasLimits\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"preVerificationGas\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"gasFees\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"paymasterAndData\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"signature\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n },\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"_missingAccountFunds\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"validationData_\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"withdrawDeposit\",\n \"inputs\": [\n {\n \"name\": \"_withdrawAddress\",\n \"type\": \"address\",\n \"internalType\": \"addresspayable\"\n },\n {\n \"name\": \"_withdrawAmount\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"event\",\n \"name\": \"EIP712DomainChanged\",\n \"inputs\": [],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"SentPrefund\",\n \"inputs\": [\n {\n \"name\": \"sender\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"amount\",\n \"type\": \"uint256\",\n \"indexed\": false,\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"success\",\n \"type\": \"bool\",\n \"indexed\": false,\n \"internalType\": \"bool\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"SetDelegationManager\",\n \"inputs\": [\n {\n \"name\": \"newDelegationManager\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIDelegationManager\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"SetEntryPoint\",\n \"inputs\": [\n {\n \"name\": \"entryPoint\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIEntryPoint\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"TryExecuteUnsuccessful\",\n \"inputs\": [\n {\n \"name\": \"batchExecutionindex\",\n \"type\": \"uint256\",\n \"indexed\": false,\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"result\",\n \"type\": \"bytes\",\n \"indexed\": false,\n \"internalType\": \"bytes\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"error\",\n \"name\": \"ECDSAInvalidSignature\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"ECDSAInvalidSignatureLength\",\n \"inputs\": [\n {\n \"name\": \"length\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ]\n },\n {\n \"type\": \"error\",\n \"name\": \"ECDSAInvalidSignatureS\",\n \"inputs\": [\n {\n \"name\": \"s\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ]\n },\n {\n \"type\": \"error\",\n \"name\": \"ExecutionFailed\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidEIP712NameLength\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidEIP712VersionLength\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidShortString\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"NotDelegationManager\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"NotEntryPoint\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"NotEntryPointOrSelf\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"NotSelf\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"StringTooLong\",\n \"inputs\": [\n {\n \"name\": \"str\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ]\n },\n {\n \"type\": \"error\",\n \"name\": \"UnauthorizedCallContext\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"UnsupportedCallType\",\n \"inputs\": [\n {\n \"name\": \"callType\",\n \"type\": \"bytes1\",\n \"internalType\": \"CallType\"\n }\n ]\n },\n {\n \"type\": \"error\",\n \"name\": \"UnsupportedExecType\",\n \"inputs\": [\n {\n \"name\": \"execType\",\n \"type\": \"bytes1\",\n \"internalType\": \"ExecType\"\n }\n ]\n }\n]\n","/**\n * Contract interactions\n *\n * This module handles on-chain contract interactions using viem.\n *\n * Accepts viem's WalletClient and PublicClient directly, which abstract over both\n * local accounts (privateKeyToAccount) and external signers (MetaMask, etc.).\n *\n * @example\n * // CLI usage with private key\n * const { walletClient, publicClient } = createClients({ privateKey, rpcUrl, chainId });\n * await deployApp({ walletClient, publicClient, environmentConfig, ... }, logger);\n *\n * @example\n * // Browser usage with external wallet\n * const walletClient = createWalletClient({ chain, transport: custom(window.ethereum!) });\n * const publicClient = createPublicClient({ chain, transport: custom(window.ethereum!) });\n * await deployApp({ walletClient, publicClient, environmentConfig, ... }, logger);\n */\n\nimport { executeBatch, checkERC7702Delegation } from \"./eip7702\";\nimport { Address, Hex, encodeFunctionData, decodeErrorResult, bytesToHex } from \"viem\";\nimport type { WalletClient, PublicClient } from \"viem\";\n\nimport {\n EnvironmentConfig,\n Logger,\n PreparedDeployData,\n PreparedUpgradeData,\n noopLogger,\n DeployProgressCallback,\n SequentialDeployResult,\n DeployStep,\n} from \"../types\";\nimport { Release } from \"../types\";\nimport { getChainFromID } from \"../utils/helpers\";\n\nimport AppControllerABI from \"../abis/AppController.json\";\nimport PermissionControllerABI from \"../abis/PermissionController.json\";\n\n/**\n * Gas estimation result\n */\nexport interface GasEstimate {\n /** Estimated gas limit for the transaction */\n gasLimit: bigint;\n /** Max fee per gas (EIP-1559) */\n maxFeePerGas: bigint;\n /** Max priority fee per gas (EIP-1559) */\n maxPriorityFeePerGas: bigint;\n /** Maximum cost in wei (gasLimit * maxFeePerGas) */\n maxCostWei: bigint;\n /** Maximum cost formatted as ETH string */\n maxCostEth: string;\n}\n\n/**\n * Options for estimating transaction gas\n */\nexport interface EstimateGasOptions {\n publicClient: PublicClient;\n from: Address;\n to: Address;\n data: Hex;\n value?: bigint;\n}\n\n/**\n * Format Wei to ETH string\n */\nexport function formatETH(wei: bigint): string {\n const eth = Number(wei) / 1e18;\n const costStr = eth.toFixed(6);\n // Remove trailing zeros and decimal point if needed\n const trimmed = costStr.replace(/\\.?0+$/, \"\");\n // If result is \"0\", show \"<0.000001\" for small amounts\n if (trimmed === \"0\" && wei > 0n) {\n return \"<0.000001\";\n }\n return trimmed;\n}\n\n/**\n * Estimate gas cost for a transaction\n *\n * Use this to get cost estimate before prompting user for confirmation.\n */\nexport async function estimateTransactionGas(options: EstimateGasOptions): Promise<GasEstimate> {\n const { publicClient, from, to, data, value = 0n } = options;\n\n // Get current gas prices\n const fees = await publicClient.estimateFeesPerGas();\n\n // Estimate gas for the transaction\n const gasLimit = await publicClient.estimateGas({\n account: from,\n to,\n data,\n value,\n });\n\n const maxFeePerGas = fees.maxFeePerGas;\n const maxPriorityFeePerGas = fees.maxPriorityFeePerGas;\n const maxCostWei = gasLimit * maxFeePerGas;\n const maxCostEth = formatETH(maxCostWei);\n\n return {\n gasLimit,\n maxFeePerGas,\n maxPriorityFeePerGas,\n maxCostWei,\n maxCostEth,\n };\n}\n\n/**\n * Deploy app options\n */\nexport interface DeployAppOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n salt: Uint8Array;\n release: Release;\n publicLogs: boolean;\n imageRef: string;\n gas?: GasEstimate;\n}\n\n/**\n * Options for calculateAppID\n */\nexport interface CalculateAppIDOptions {\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n ownerAddress: Address;\n salt: Uint8Array;\n}\n\n/**\n * Prepared deploy batch ready for gas estimation and execution\n */\nexport interface PreparedDeployBatch {\n /** The app ID that will be deployed */\n appId: Address;\n /** The salt used for deployment */\n salt: Uint8Array;\n /** Batch executions to be sent */\n executions: Array<{ target: Address; value: bigint; callData: Hex }>;\n /** Wallet client for sending transaction */\n walletClient: WalletClient;\n /** Public client for reading chain state */\n publicClient: PublicClient;\n /** Environment configuration */\n environmentConfig: EnvironmentConfig;\n}\n\n/**\n * Prepared upgrade batch ready for gas estimation and execution\n */\nexport interface PreparedUpgradeBatch {\n /** The app ID being upgraded */\n appId: Address;\n /** Batch executions to be sent */\n executions: Array<{ target: Address; value: bigint; callData: Hex }>;\n /** Wallet client for sending transaction */\n walletClient: WalletClient;\n /** Public client for reading chain state */\n publicClient: PublicClient;\n /** Environment configuration */\n environmentConfig: EnvironmentConfig;\n}\n\n/**\n * Calculate app ID from owner address and salt\n */\nexport async function calculateAppID(options: CalculateAppIDOptions): Promise<Address> {\n const { publicClient, environmentConfig, ownerAddress, salt } = options;\n\n // Ensure salt is properly formatted as hex string (32 bytes = 64 hex chars)\n // bytesToHex returns 0x-prefixed string, slice(2) removes the prefix for padding\n const saltHexString = bytesToHex(salt).slice(2);\n // Pad to 64 characters if needed\n const paddedSaltHex = saltHexString.padStart(64, \"0\");\n const saltHex = `0x${paddedSaltHex}` as Hex;\n\n const appID = await publicClient.readContract({\n address: environmentConfig.appControllerAddress as Address,\n abi: AppControllerABI,\n functionName: \"calculateAppId\",\n args: [ownerAddress, saltHex],\n });\n\n return appID as Address;\n}\n\n/**\n * Options for preparing a deploy batch\n */\nexport interface PrepareDeployBatchOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n salt: Uint8Array;\n release: Release;\n publicLogs: boolean;\n imageRef: string;\n}\n\n/**\n * Prepare deploy batch - creates executions without sending transaction\n *\n * Use this to get the prepared batch for gas estimation before executing.\n */\nexport async function prepareDeployBatch(\n options: PrepareDeployBatchOptions,\n logger: Logger = noopLogger,\n): Promise<PreparedDeployBatch> {\n const { walletClient, publicClient, environmentConfig, salt, release, publicLogs } = options;\n\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n // 1. Calculate app ID\n logger.info(\"Calculating app ID...\");\n const appId = await calculateAppID({\n publicClient,\n environmentConfig,\n ownerAddress: account.address,\n salt,\n });\n\n // Verify the app ID calculation matches what createApp will deploy\n logger.debug(`App ID calculated: ${appId}`);\n logger.debug(`This address will be used for acceptAdmin call`);\n\n // 2. Pack create app call\n const saltHexString = bytesToHex(salt).slice(2);\n const paddedSaltHex = saltHexString.padStart(64, \"0\");\n const saltHex = `0x${paddedSaltHex}` as Hex;\n\n // Convert Release Uint8Array values to hex strings for viem\n const releaseForViem = {\n rmsRelease: {\n artifacts: release.rmsRelease.artifacts.map((artifact) => ({\n digest: `0x${bytesToHex(artifact.digest).slice(2).padStart(64, \"0\")}` as Hex,\n registry: artifact.registry,\n })),\n upgradeByTime: release.rmsRelease.upgradeByTime,\n },\n publicEnv: bytesToHex(release.publicEnv) as Hex,\n encryptedEnv: bytesToHex(release.encryptedEnv) as Hex,\n };\n\n const createData = encodeFunctionData({\n abi: AppControllerABI,\n functionName: \"createApp\",\n args: [saltHex, releaseForViem],\n });\n\n // 3. Pack accept admin call\n const acceptAdminData = encodeFunctionData({\n abi: PermissionControllerABI,\n functionName: \"acceptAdmin\",\n args: [appId],\n });\n\n // 4. Assemble executions\n // CRITICAL: Order matters! createApp must complete first\n const executions: Array<{\n target: Address;\n value: bigint;\n callData: Hex;\n }> = [\n {\n target: environmentConfig.appControllerAddress,\n value: 0n,\n callData: createData,\n },\n {\n target: environmentConfig.permissionControllerAddress as Address,\n value: 0n,\n callData: acceptAdminData,\n },\n ];\n\n // 5. Add public logs permission if requested\n if (publicLogs) {\n const anyoneCanViewLogsData = encodeFunctionData({\n abi: PermissionControllerABI,\n functionName: \"setAppointee\",\n args: [\n appId,\n \"0x493219d9949348178af1f58740655951a8cd110c\" as Address, // AnyoneCanCallAddress\n \"0x57ee1fb74c1087e26446abc4fb87fd8f07c43d8d\" as Address, // ApiPermissionsTarget\n \"0x2fd3f2fe\" as Hex, // CanViewAppLogsPermission\n ],\n });\n executions.push({\n target: environmentConfig.permissionControllerAddress as Address,\n value: 0n,\n callData: anyoneCanViewLogsData,\n });\n }\n\n return {\n appId,\n salt,\n executions,\n walletClient,\n publicClient,\n environmentConfig,\n };\n}\n\n/**\n * Execute a prepared deploy batch\n */\nexport async function executeDeployBatch(\n data: PreparedDeployData,\n context: {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n },\n gas?: GasEstimate,\n logger: Logger = noopLogger,\n): Promise<{ appId: Address; txHash: Hex }> {\n const pendingMessage = \"Deploying new app...\";\n\n const txHash = await executeBatch(\n {\n walletClient: context.walletClient,\n publicClient: context.publicClient,\n environmentConfig: context.environmentConfig,\n executions: data.executions,\n pendingMessage,\n gas,\n },\n logger,\n );\n\n return { appId: data.appId, txHash };\n}\n\n/**\n * Deploy app on-chain (convenience wrapper that prepares and executes)\n */\nexport async function deployApp(\n options: DeployAppOptions,\n logger: Logger = noopLogger,\n): Promise<{ appId: Address; txHash: Hex }> {\n const prepared = await prepareDeployBatch(options, logger);\n\n // Extract data and context from prepared batch\n const data: PreparedDeployData = {\n appId: prepared.appId,\n salt: prepared.salt,\n executions: prepared.executions,\n };\n const context = {\n walletClient: prepared.walletClient,\n publicClient: prepared.publicClient,\n environmentConfig: prepared.environmentConfig,\n };\n\n return executeDeployBatch(data, context, options.gas, logger);\n}\n\n/**\n * Check if wallet account supports EIP-7702 signing\n *\n * Local accounts (from privateKeyToAccount) support signAuthorization.\n * JSON-RPC accounts (browser wallets like MetaMask) do not.\n */\nexport function supportsEIP7702(walletClient: WalletClient): boolean {\n const account = walletClient.account;\n if (!account) return false;\n\n // Local accounts have type \"local\", JSON-RPC accounts have type \"json-rpc\"\n // Only local accounts support signAuthorization\n return account.type === \"local\";\n}\n\n/**\n * Options for sequential deployment (non-EIP-7702)\n */\nexport interface ExecuteDeploySequentialOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n /** Prepared deployment data from prepareDeployBatch */\n data: PreparedDeployData;\n /** Whether to set public logs permission */\n publicLogs: boolean;\n /** Optional callback for progress updates */\n onProgress?: DeployProgressCallback;\n}\n\n/**\n * Execute deployment as sequential transactions (non-EIP-7702 fallback)\n *\n * Use this for browser wallets (JSON-RPC accounts) that don't support signAuthorization.\n * This requires 2-3 wallet signatures instead of 1, but works with all wallet types.\n *\n * Steps:\n * 1. createApp - Creates the app on-chain\n * 2. acceptAdmin - Accepts admin role for the app\n * 3. setAppointee (optional) - Sets public logs permission\n */\nexport async function executeDeploySequential(\n options: ExecuteDeploySequentialOptions,\n logger: Logger = noopLogger,\n): Promise<SequentialDeployResult> {\n const { walletClient, publicClient, environmentConfig, data, publicLogs, onProgress } = options;\n\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n const chain = getChainFromID(environmentConfig.chainID);\n const txHashes: { createApp: Hex; acceptAdmin: Hex; setPublicLogs?: Hex } = {\n createApp: \"0x\" as Hex,\n acceptAdmin: \"0x\" as Hex,\n };\n\n // Step 1: Create App\n logger.info(\"Step 1/3: Creating app...\");\n onProgress?.(\"createApp\");\n\n const createAppExecution = data.executions[0];\n const createAppHash = await walletClient.sendTransaction({\n account,\n to: createAppExecution.target,\n data: createAppExecution.callData,\n value: createAppExecution.value,\n chain,\n });\n\n logger.info(`createApp transaction sent: ${createAppHash}`);\n const createAppReceipt = await publicClient.waitForTransactionReceipt({ hash: createAppHash });\n\n if (createAppReceipt.status === \"reverted\") {\n throw new Error(`createApp transaction reverted: ${createAppHash}`);\n }\n\n txHashes.createApp = createAppHash;\n logger.info(`createApp confirmed in block ${createAppReceipt.blockNumber}`);\n\n // Step 2: Accept Admin\n logger.info(\"Step 2/3: Accepting admin role...\");\n onProgress?.(\"acceptAdmin\", createAppHash);\n\n const acceptAdminExecution = data.executions[1];\n const acceptAdminHash = await walletClient.sendTransaction({\n account,\n to: acceptAdminExecution.target,\n data: acceptAdminExecution.callData,\n value: acceptAdminExecution.value,\n chain,\n });\n\n logger.info(`acceptAdmin transaction sent: ${acceptAdminHash}`);\n const acceptAdminReceipt = await publicClient.waitForTransactionReceipt({\n hash: acceptAdminHash,\n });\n\n if (acceptAdminReceipt.status === \"reverted\") {\n throw new Error(`acceptAdmin transaction reverted: ${acceptAdminHash}`);\n }\n\n txHashes.acceptAdmin = acceptAdminHash;\n logger.info(`acceptAdmin confirmed in block ${acceptAdminReceipt.blockNumber}`);\n\n // Step 3: Set Public Logs (if requested and present in executions)\n if (publicLogs && data.executions.length > 2) {\n logger.info(\"Step 3/3: Setting public logs permission...\");\n onProgress?.(\"setPublicLogs\", acceptAdminHash);\n\n const setAppointeeExecution = data.executions[2];\n const setAppointeeHash = await walletClient.sendTransaction({\n account,\n to: setAppointeeExecution.target,\n data: setAppointeeExecution.callData,\n value: setAppointeeExecution.value,\n chain,\n });\n\n logger.info(`setAppointee transaction sent: ${setAppointeeHash}`);\n const setAppointeeReceipt = await publicClient.waitForTransactionReceipt({\n hash: setAppointeeHash,\n });\n\n if (setAppointeeReceipt.status === \"reverted\") {\n throw new Error(`setAppointee transaction reverted: ${setAppointeeHash}`);\n }\n\n txHashes.setPublicLogs = setAppointeeHash;\n logger.info(`setAppointee confirmed in block ${setAppointeeReceipt.blockNumber}`);\n }\n\n onProgress?.(\"complete\", txHashes.setPublicLogs || txHashes.acceptAdmin);\n\n logger.info(`Deployment complete! App ID: ${data.appId}`);\n\n return {\n appId: data.appId,\n txHashes,\n };\n}\n\n/**\n * Result from EIP-5792 batched deployment\n */\nexport interface BatchedDeployResult {\n appId: Address;\n /** Batch ID from sendCalls (can be used with getCallsStatus) */\n batchId: string;\n /** Transaction receipts from the batch */\n receipts: Array<{ transactionHash: Hex }>;\n}\n\n/**\n * Options for EIP-5792 batched deployment\n */\nexport interface ExecuteDeployBatchedOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n /** Prepared deployment data from prepareDeployBatch */\n data: PreparedDeployData;\n /** Whether to set public logs permission */\n publicLogs: boolean;\n /** Optional callback for progress updates */\n onProgress?: DeployProgressCallback;\n}\n\n/**\n * Check if wallet supports EIP-5792 (sendCalls/wallet_sendCalls)\n *\n * This checks the wallet's capabilities to see if it supports atomic batch calls.\n * MetaMask and other modern wallets are adding support for this standard.\n */\nexport async function supportsEIP5792(walletClient: WalletClient): Promise<boolean> {\n try {\n // Check if getCapabilities method exists\n if (typeof walletClient.getCapabilities !== \"function\") {\n return false;\n }\n\n const account = walletClient.account;\n if (!account) return false;\n\n // Try to get capabilities - if this works, the wallet supports EIP-5792\n const capabilities = await walletClient.getCapabilities({\n account: account.address,\n });\n\n // Check if we got any capabilities back\n return (\n capabilities !== null && capabilities !== undefined && Object.keys(capabilities).length > 0\n );\n } catch {\n // If getCapabilities fails, the wallet doesn't support EIP-5792\n return false;\n }\n}\n\n/**\n * Execute deployment using EIP-5792 sendCalls (batched wallet calls)\n *\n * This batches all deployment transactions (createApp, acceptAdmin, setPublicLogs)\n * into a single wallet interaction. Better UX than sequential transactions.\n *\n * Use this for browser wallets that support EIP-5792 but not EIP-7702.\n *\n * @returns BatchedDeployResult with appId and batch receipts\n */\nexport async function executeDeployBatched(\n options: ExecuteDeployBatchedOptions,\n logger: Logger = noopLogger,\n): Promise<BatchedDeployResult> {\n const { walletClient, environmentConfig, data, publicLogs, onProgress } = options;\n\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n const chain = getChainFromID(environmentConfig.chainID);\n\n // Build calls array for sendCalls\n const calls: Array<{ to: Address; data: Hex; value: bigint }> = data.executions.map(\n (execution) => ({\n to: execution.target,\n data: execution.callData,\n value: execution.value,\n }),\n );\n\n // If public logs is false but executions include the permission call, filter it out\n // (This shouldn't happen if prepareDeployBatch was called correctly, but be safe)\n const filteredCalls = publicLogs ? calls : calls.slice(0, 2);\n\n logger.info(`Deploying with EIP-5792 sendCalls (${filteredCalls.length} calls)...`);\n onProgress?.(\"createApp\");\n\n try {\n // Send all calls in a single batch\n const { id: batchId } = await walletClient.sendCalls({\n account,\n chain,\n calls: filteredCalls,\n forceAtomic: true,\n });\n\n logger.info(`Batch submitted with ID: ${batchId}`);\n onProgress?.(\"acceptAdmin\");\n\n // Poll for batch completion using getCallsStatus\n let status: any;\n let attempts = 0;\n const maxAttempts = 120; // 10 minutes max (5s intervals)\n\n while (attempts < maxAttempts) {\n try {\n status = await walletClient.getCallsStatus({ id: batchId });\n\n if (status.status === \"success\" || status.status === \"confirmed\") {\n logger.info(`Batch confirmed with ${status.receipts?.length || 0} receipts`);\n break;\n }\n\n if (status.status === \"failed\" || status.status === \"reverted\") {\n throw new Error(`Batch transaction failed: ${status.status}`);\n }\n } catch (statusError: any) {\n // Some wallets may not support getCallsStatus, wait and check chain\n if (statusError.message?.includes(\"not supported\")) {\n logger.warn(\"getCallsStatus not supported, waiting for chain confirmation...\");\n // Fall back to waiting a fixed time\n await new Promise((resolve) => setTimeout(resolve, 15000));\n break;\n }\n throw statusError;\n }\n\n // Wait 5 seconds before next poll\n await new Promise((resolve) => setTimeout(resolve, 5000));\n attempts++;\n }\n\n if (attempts >= maxAttempts) {\n throw new Error(\"Timeout waiting for batch confirmation\");\n }\n\n if (publicLogs) {\n onProgress?.(\"setPublicLogs\");\n }\n onProgress?.(\"complete\");\n\n // Extract transaction hashes from receipts\n const receipts = (status?.receipts || []).map((r: any) => ({\n transactionHash: r.transactionHash || r.hash,\n }));\n\n logger.info(`Deployment complete! App ID: ${data.appId}`);\n\n return {\n appId: data.appId,\n batchId,\n receipts,\n };\n } catch (error: any) {\n // Check if the error indicates sendCalls is not supported\n if (\n error.message?.includes(\"not supported\") ||\n error.message?.includes(\"wallet_sendCalls\") ||\n error.code === -32601 // Method not found\n ) {\n throw new Error(\"EIP5792_NOT_SUPPORTED\");\n }\n throw error;\n }\n}\n\n/**\n * Upgrade app options\n */\nexport interface UpgradeAppOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n appID: Address;\n release: Release;\n publicLogs: boolean;\n needsPermissionChange: boolean;\n imageRef: string;\n gas?: GasEstimate;\n}\n\n/**\n * Options for preparing an upgrade batch\n */\nexport interface PrepareUpgradeBatchOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n appID: Address;\n release: Release;\n publicLogs: boolean;\n needsPermissionChange: boolean;\n imageRef: string;\n}\n\n/**\n * Prepare upgrade batch - creates executions without sending transaction\n *\n * Use this to get the prepared batch for gas estimation before executing.\n */\nexport async function prepareUpgradeBatch(\n options: PrepareUpgradeBatchOptions,\n): Promise<PreparedUpgradeBatch> {\n const {\n walletClient,\n publicClient,\n environmentConfig,\n appID,\n release,\n publicLogs,\n needsPermissionChange,\n } = options;\n\n // 1. Pack upgrade app call\n // Convert Release Uint8Array values to hex strings for viem\n const releaseForViem = {\n rmsRelease: {\n artifacts: release.rmsRelease.artifacts.map((artifact) => ({\n digest: `0x${bytesToHex(artifact.digest).slice(2).padStart(64, \"0\")}` as Hex,\n registry: artifact.registry,\n })),\n upgradeByTime: release.rmsRelease.upgradeByTime,\n },\n publicEnv: bytesToHex(release.publicEnv) as Hex,\n encryptedEnv: bytesToHex(release.encryptedEnv) as Hex,\n };\n\n const upgradeData = encodeFunctionData({\n abi: AppControllerABI,\n functionName: \"upgradeApp\",\n args: [appID, releaseForViem],\n });\n\n // 2. Start with upgrade execution\n const executions: Array<{\n target: Address;\n value: bigint;\n callData: Hex;\n }> = [\n {\n target: environmentConfig.appControllerAddress,\n value: 0n,\n callData: upgradeData,\n },\n ];\n\n // 3. Add permission transaction if needed\n if (needsPermissionChange) {\n if (publicLogs) {\n // Add public permission (private→public)\n const addLogsData = encodeFunctionData({\n abi: PermissionControllerABI,\n functionName: \"setAppointee\",\n args: [\n appID,\n \"0x493219d9949348178af1f58740655951a8cd110c\" as Address, // AnyoneCanCallAddress\n \"0x57ee1fb74c1087e26446abc4fb87fd8f07c43d8d\" as Address, // ApiPermissionsTarget\n \"0x2fd3f2fe\" as Hex, // CanViewAppLogsPermission\n ],\n });\n executions.push({\n target: environmentConfig.permissionControllerAddress as Address,\n value: 0n,\n callData: addLogsData,\n });\n } else {\n // Remove public permission (public→private)\n const removeLogsData = encodeFunctionData({\n abi: PermissionControllerABI,\n functionName: \"removeAppointee\",\n args: [\n appID,\n \"0x493219d9949348178af1f58740655951a8cd110c\" as Address, // AnyoneCanCallAddress\n \"0x57ee1fb74c1087e26446abc4fb87fd8f07c43d8d\" as Address, // ApiPermissionsTarget\n \"0x2fd3f2fe\" as Hex, // CanViewAppLogsPermission\n ],\n });\n executions.push({\n target: environmentConfig.permissionControllerAddress as Address,\n value: 0n,\n callData: removeLogsData,\n });\n }\n }\n\n return {\n appId: appID,\n executions,\n walletClient,\n publicClient,\n environmentConfig,\n };\n}\n\n/**\n * Execute a prepared upgrade batch\n */\nexport async function executeUpgradeBatch(\n data: PreparedUpgradeData,\n context: {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n },\n gas?: GasEstimate,\n logger: Logger = noopLogger,\n): Promise<Hex> {\n const pendingMessage = `Upgrading app ${data.appId}...`;\n\n const txHash = await executeBatch(\n {\n walletClient: context.walletClient,\n publicClient: context.publicClient,\n environmentConfig: context.environmentConfig,\n executions: data.executions,\n pendingMessage,\n gas,\n },\n logger,\n );\n\n return txHash;\n}\n\n/**\n * Upgrade app on-chain (convenience wrapper that prepares and executes)\n */\nexport async function upgradeApp(\n options: UpgradeAppOptions,\n logger: Logger = noopLogger,\n): Promise<Hex> {\n const prepared = await prepareUpgradeBatch(options);\n\n // Extract data and context from prepared batch\n const data: PreparedUpgradeData = {\n appId: prepared.appId,\n executions: prepared.executions,\n };\n const context = {\n walletClient: prepared.walletClient,\n publicClient: prepared.publicClient,\n environmentConfig: prepared.environmentConfig,\n };\n\n return executeUpgradeBatch(data, context, options.gas, logger);\n}\n\n/**\n * Send and wait for transaction with confirmation support\n */\nexport interface SendTransactionOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n to: Address;\n data: Hex;\n value?: bigint;\n pendingMessage: string;\n txDescription: string;\n gas?: GasEstimate;\n}\n\nexport async function sendAndWaitForTransaction(\n options: SendTransactionOptions,\n logger: Logger = noopLogger,\n): Promise<Hex> {\n const {\n walletClient,\n publicClient,\n environmentConfig,\n to,\n data,\n value = 0n,\n pendingMessage,\n txDescription,\n gas,\n } = options;\n\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n const chain = getChainFromID(environmentConfig.chainID);\n\n // Show pending message if provided\n if (pendingMessage) {\n logger.info(`\\n${pendingMessage}`);\n }\n\n // Send transaction with optional gas params\n const hash = await walletClient.sendTransaction({\n account,\n to,\n data,\n value,\n ...(gas?.maxFeePerGas && { maxFeePerGas: gas.maxFeePerGas }),\n ...(gas?.maxPriorityFeePerGas && {\n maxPriorityFeePerGas: gas.maxPriorityFeePerGas,\n }),\n chain,\n });\n\n logger.info(`Transaction sent: ${hash}`);\n\n // Wait for receipt\n const receipt = await publicClient.waitForTransactionReceipt({ hash });\n\n if (receipt.status === \"reverted\") {\n let revertReason = \"Unknown reason\";\n try {\n await publicClient.call({\n to,\n data,\n account: account.address,\n });\n } catch (callError: any) {\n if (callError.data) {\n try {\n const decoded = decodeErrorResult({\n abi: AppControllerABI,\n data: callError.data,\n });\n const formattedError = formatAppControllerError(decoded);\n revertReason = formattedError.message;\n } catch {\n revertReason = callError.message || \"Unknown reason\";\n }\n } else {\n revertReason = callError.message || \"Unknown reason\";\n }\n }\n logger.error(`${txDescription} transaction (hash: ${hash}) reverted: ${revertReason}`);\n throw new Error(`${txDescription} transaction (hash: ${hash}) reverted: ${revertReason}`);\n }\n\n return hash;\n}\n\n/**\n * Format AppController errors to user-friendly messages\n */\nfunction formatAppControllerError(decoded: {\n errorName: string;\n args?: readonly unknown[];\n}): Error {\n const errorName = decoded.errorName;\n\n switch (errorName) {\n case \"MaxActiveAppsExceeded\":\n return new Error(\n \"you have reached your app deployment limit. To request access or increase your limit, please visit https://onboarding.eigencloud.xyz/ or reach out to the Eigen team\",\n );\n case \"GlobalMaxActiveAppsExceeded\":\n return new Error(\n \"the platform has reached the maximum number of active apps. please try again later\",\n );\n case \"InvalidPermissions\":\n return new Error(\"you don't have permission to perform this operation\");\n case \"AppAlreadyExists\":\n return new Error(\"an app with this owner and salt already exists\");\n case \"AppDoesNotExist\":\n return new Error(\"the specified app does not exist\");\n case \"InvalidAppStatus\":\n return new Error(\"the app is in an invalid state for this operation\");\n case \"MoreThanOneArtifact\":\n return new Error(\"only one artifact is allowed per release\");\n case \"InvalidSignature\":\n return new Error(\"invalid signature provided\");\n case \"SignatureExpired\":\n return new Error(\"the provided signature has expired\");\n case \"InvalidReleaseMetadataURI\":\n return new Error(\"invalid release metadata URI provided\");\n case \"InvalidShortString\":\n return new Error(\"invalid short string format\");\n default:\n return new Error(`contract error: ${errorName}`);\n }\n}\n\n/**\n * Get active app count for a user\n */\nexport async function getActiveAppCount(\n publicClient: PublicClient,\n environmentConfig: EnvironmentConfig,\n user: Address,\n): Promise<number> {\n const count = await publicClient.readContract({\n address: environmentConfig.appControllerAddress,\n abi: AppControllerABI,\n functionName: \"getActiveAppCount\",\n args: [user],\n });\n\n return Number(count);\n}\n\n/**\n * Get max active apps per user (quota limit)\n */\nexport async function getMaxActiveAppsPerUser(\n publicClient: PublicClient,\n environmentConfig: EnvironmentConfig,\n user: Address,\n): Promise<number> {\n const quota = await publicClient.readContract({\n address: environmentConfig.appControllerAddress,\n abi: AppControllerABI,\n functionName: \"getMaxActiveAppsPerUser\",\n args: [user],\n });\n\n return Number(quota);\n}\n\n/**\n * Get apps by creator (paginated)\n */\nexport interface AppConfig {\n release: any; // Release struct from contract\n status: number; // AppStatus enum\n}\n\nexport async function getAppsByCreator(\n publicClient: PublicClient,\n environmentConfig: EnvironmentConfig,\n creator: Address,\n offset: bigint,\n limit: bigint,\n): Promise<{ apps: Address[]; appConfigs: AppConfig[] }> {\n const result = (await publicClient.readContract({\n address: environmentConfig.appControllerAddress,\n abi: AppControllerABI,\n functionName: \"getAppsByCreator\",\n args: [creator, offset, limit],\n })) as [Address[], AppConfig[]];\n\n // Result is a tuple: [Address[], AppConfig[]]\n return {\n apps: result[0],\n appConfigs: result[1],\n };\n}\n\n/**\n * Get apps by developer\n */\nexport async function getAppsByDeveloper(\n publicClient: PublicClient,\n environmentConfig: EnvironmentConfig,\n developer: Address,\n offset: bigint,\n limit: bigint,\n): Promise<{ apps: Address[]; appConfigs: AppConfig[] }> {\n const result = (await publicClient.readContract({\n address: environmentConfig.appControllerAddress,\n abi: AppControllerABI,\n functionName: \"getAppsByDeveloper\",\n args: [developer, offset, limit],\n })) as [Address[], AppConfig[]];\n\n // Result is a tuple: [Address[], AppConfig[]]\n return {\n apps: result[0],\n appConfigs: result[1],\n };\n}\n\n/**\n * Fetch all apps by a developer by auto-pagination\n */\nexport async function getAllAppsByDeveloper(\n publicClient: PublicClient,\n env: EnvironmentConfig,\n developer: Address,\n pageSize: bigint = 100n,\n): Promise<{ apps: Address[]; appConfigs: AppConfig[] }> {\n let offset = 0n;\n const allApps: Address[] = [];\n const allConfigs: AppConfig[] = [];\n\n while (true) {\n const { apps, appConfigs } = await getAppsByDeveloper(\n publicClient,\n env,\n developer,\n offset,\n pageSize,\n );\n\n if (apps.length === 0) break;\n\n allApps.push(...apps);\n allConfigs.push(...appConfigs);\n\n if (apps.length < Number(pageSize)) break;\n\n offset += pageSize;\n }\n\n return {\n apps: allApps,\n appConfigs: allConfigs,\n };\n}\n\n/**\n * Get latest release block numbers for multiple apps\n */\nexport async function getAppLatestReleaseBlockNumbers(\n publicClient: PublicClient,\n environmentConfig: EnvironmentConfig,\n appIDs: Address[],\n): Promise<Map<Address, number>> {\n // Fetch block numbers in parallel\n const results = await Promise.all(\n appIDs.map((appID) =>\n publicClient\n .readContract({\n address: environmentConfig.appControllerAddress,\n abi: AppControllerABI,\n functionName: \"getAppLatestReleaseBlockNumber\",\n args: [appID],\n })\n .catch(() => null),\n ),\n );\n\n const blockNumbers = new Map<Address, number>();\n for (let i = 0; i < appIDs.length; i++) {\n const result = results[i];\n if (result !== null && result !== undefined) {\n blockNumbers.set(appIDs[i], Number(result));\n }\n }\n\n return blockNumbers;\n}\n\n/**\n * Get block timestamps for multiple block numbers\n */\nexport async function getBlockTimestamps(\n publicClient: PublicClient,\n blockNumbers: number[],\n): Promise<Map<number, number>> {\n // Deduplicate block numbers\n const uniqueBlockNumbers = [...new Set(blockNumbers)].filter((n) => n > 0);\n\n const timestamps = new Map<number, number>();\n\n // Fetch blocks in parallel\n const blocks = await Promise.all(\n uniqueBlockNumbers.map((blockNumber) =>\n publicClient.getBlock({ blockNumber: BigInt(blockNumber) }).catch(() => null),\n ),\n );\n\n for (let i = 0; i < uniqueBlockNumbers.length; i++) {\n const block = blocks[i];\n if (block) {\n timestamps.set(uniqueBlockNumbers[i], Number(block.timestamp));\n }\n }\n\n return timestamps;\n}\n\n/**\n * Suspend options\n */\nexport interface SuspendOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n account: Address;\n apps: Address[];\n}\n\n/**\n * Suspend apps for an account\n */\nexport async function suspend(\n options: SuspendOptions,\n logger: Logger = noopLogger,\n): Promise<Hex | false> {\n const { walletClient, publicClient, environmentConfig, account, apps } = options;\n\n const suspendData = encodeFunctionData({\n abi: AppControllerABI,\n functionName: \"suspend\",\n args: [account, apps],\n });\n\n const pendingMessage = `Suspending ${apps.length} app(s)...`;\n\n return sendAndWaitForTransaction(\n {\n walletClient,\n publicClient,\n environmentConfig,\n to: environmentConfig.appControllerAddress as Address,\n data: suspendData,\n pendingMessage,\n txDescription: \"Suspend\",\n },\n logger,\n );\n}\n\n/**\n * Options for checking delegation status\n */\nexport interface IsDelegatedOptions {\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n address: Address;\n}\n\n/**\n * Check if account is delegated to the ERC-7702 delegator\n */\nexport async function isDelegated(options: IsDelegatedOptions): Promise<boolean> {\n const { publicClient, environmentConfig, address } = options;\n\n return checkERC7702Delegation(\n publicClient,\n address,\n environmentConfig.erc7702DelegatorAddress as Address,\n );\n}\n\n/**\n * Undelegate options\n */\nexport interface UndelegateOptions {\n walletClient: WalletClient;\n publicClient: PublicClient;\n environmentConfig: EnvironmentConfig;\n}\n\n/**\n * Undelegate account (removes EIP-7702 delegation)\n */\nexport async function undelegate(\n options: UndelegateOptions,\n logger: Logger = noopLogger,\n): Promise<Hex> {\n const { walletClient, publicClient, environmentConfig } = options;\n\n const account = walletClient.account;\n if (!account) {\n throw new Error(\"WalletClient must have an account attached\");\n }\n\n const chain = getChainFromID(environmentConfig.chainID);\n\n // Create authorization to undelegate (empty address = undelegate)\n const transactionNonce = await publicClient.getTransactionCount({\n address: account.address,\n blockTag: \"pending\",\n });\n\n const chainId = await publicClient.getChainId();\n const authorizationNonce = BigInt(transactionNonce) + 1n;\n\n logger.debug(\"Signing undelegate authorization\");\n\n const signedAuthorization = await walletClient.signAuthorization({\n contractAddress: \"0x0000000000000000000000000000000000000000\" as Address,\n chainId: chainId,\n nonce: Number(authorizationNonce),\n account: account,\n });\n\n const authorizationList = [signedAuthorization];\n\n // Send transaction with authorization list\n const hash = await walletClient.sendTransaction({\n account,\n to: account.address, // Send to self\n data: \"0x\" as Hex, // Empty data\n value: 0n,\n authorizationList,\n chain,\n });\n\n logger.info(`Transaction sent: ${hash}`);\n\n const receipt = await publicClient.waitForTransactionReceipt({ hash });\n\n if (receipt.status === \"reverted\") {\n logger.error(`Undelegate transaction (hash: ${hash}) reverted`);\n throw new Error(`Undelegate transaction (hash: ${hash}) reverted`);\n }\n\n return hash;\n}\n","[\n {\n \"type\": \"constructor\",\n \"inputs\": [\n {\n \"name\": \"_version\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n },\n {\n \"name\": \"_permissionController\",\n \"type\": \"address\",\n \"internalType\": \"contractIPermissionController\"\n },\n {\n \"name\": \"_releaseManager\",\n \"type\": \"address\",\n \"internalType\": \"contractIReleaseManager\"\n },\n {\n \"name\": \"_computeAVSRegistrar\",\n \"type\": \"address\",\n \"internalType\": \"contractIComputeAVSRegistrar\"\n },\n {\n \"name\": \"_computeOperator\",\n \"type\": \"address\",\n \"internalType\": \"contractIComputeOperator\"\n },\n {\n \"name\": \"_appBeacon\",\n \"type\": \"address\",\n \"internalType\": \"contractIBeacon\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"API_PERMISSION_TYPEHASH\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"appBeacon\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIBeacon\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"calculateApiPermissionDigestHash\",\n \"inputs\": [\n {\n \"name\": \"permission\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n },\n {\n \"name\": \"expiry\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"calculateAppId\",\n \"inputs\": [\n {\n \"name\": \"deployer\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"salt\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"computeAVSRegistrar\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIComputeAVSRegistrar\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"computeOperator\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIComputeOperator\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"createApp\",\n \"inputs\": [\n {\n \"name\": \"salt\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"release\",\n \"type\": \"tuple\",\n \"internalType\": \"structIAppController.Release\",\n \"components\": [\n {\n \"name\": \"rmsRelease\",\n \"type\": \"tuple\",\n \"internalType\": \"structIReleaseManagerTypes.Release\",\n \"components\": [\n {\n \"name\": \"artifacts\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structIReleaseManagerTypes.Artifact[]\",\n \"components\": [\n {\n \"name\": \"digest\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"registry\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ]\n },\n {\n \"name\": \"upgradeByTime\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ]\n },\n {\n \"name\": \"publicEnv\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"encryptedEnv\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"domainSeparator\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getActiveAppCount\",\n \"inputs\": [\n {\n \"name\": \"user\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppCreator\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppLatestReleaseBlockNumber\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppOperatorSetId\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppStatus\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint8\",\n \"internalType\": \"enumIAppController.AppStatus\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getApps\",\n \"inputs\": [\n {\n \"name\": \"offset\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"limit\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"apps\",\n \"type\": \"address[]\",\n \"internalType\": \"contractIApp[]\"\n },\n {\n \"name\": \"appConfigsMem\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structIAppController.AppConfig[]\",\n \"components\": [\n {\n \"name\": \"creator\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"operatorSetId\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n },\n {\n \"name\": \"latestReleaseBlockNumber\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n },\n {\n \"name\": \"status\",\n \"type\": \"uint8\",\n \"internalType\": \"enumIAppController.AppStatus\"\n }\n ]\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppsByCreator\",\n \"inputs\": [\n {\n \"name\": \"creator\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"offset\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"limit\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"apps\",\n \"type\": \"address[]\",\n \"internalType\": \"contractIApp[]\"\n },\n {\n \"name\": \"appConfigsMem\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structIAppController.AppConfig[]\",\n \"components\": [\n {\n \"name\": \"creator\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"operatorSetId\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n },\n {\n \"name\": \"latestReleaseBlockNumber\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n },\n {\n \"name\": \"status\",\n \"type\": \"uint8\",\n \"internalType\": \"enumIAppController.AppStatus\"\n }\n ]\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppsByDeveloper\",\n \"inputs\": [\n {\n \"name\": \"developer\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"offset\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"limit\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"apps\",\n \"type\": \"address[]\",\n \"internalType\": \"contractIApp[]\"\n },\n {\n \"name\": \"appConfigsMem\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structIAppController.AppConfig[]\",\n \"components\": [\n {\n \"name\": \"creator\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"operatorSetId\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n },\n {\n \"name\": \"latestReleaseBlockNumber\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n },\n {\n \"name\": \"status\",\n \"type\": \"uint8\",\n \"internalType\": \"enumIAppController.AppStatus\"\n }\n ]\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getMaxActiveAppsPerUser\",\n \"inputs\": [\n {\n \"name\": \"user\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"globalActiveAppCount\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"initialize\",\n \"inputs\": [\n {\n \"name\": \"admin\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"maxGlobalActiveApps\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"permissionController\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIPermissionController\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"releaseManager\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\",\n \"internalType\": \"contractIReleaseManager\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"setMaxActiveAppsPerUser\",\n \"inputs\": [\n {\n \"name\": \"user\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"limit\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"setMaxGlobalActiveApps\",\n \"inputs\": [\n {\n \"name\": \"limit\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"startApp\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"stopApp\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"suspend\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"apps\",\n \"type\": \"address[]\",\n \"internalType\": \"contractIApp[]\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"terminateApp\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"terminateAppByAdmin\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"updateAppMetadataURI\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n },\n {\n \"name\": \"metadataURI\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"upgradeApp\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"internalType\": \"contractIApp\"\n },\n {\n \"name\": \"release\",\n \"type\": \"tuple\",\n \"internalType\": \"structIAppController.Release\",\n \"components\": [\n {\n \"name\": \"rmsRelease\",\n \"type\": \"tuple\",\n \"internalType\": \"structIReleaseManagerTypes.Release\",\n \"components\": [\n {\n \"name\": \"artifacts\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structIReleaseManagerTypes.Artifact[]\",\n \"components\": [\n {\n \"name\": \"digest\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"registry\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ]\n },\n {\n \"name\": \"upgradeByTime\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ]\n },\n {\n \"name\": \"publicEnv\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"encryptedEnv\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\",\n \"internalType\": \"uint256\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"version\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"event\",\n \"name\": \"AppCreated\",\n \"inputs\": [\n {\n \"name\": \"creator\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n },\n {\n \"name\": \"operatorSetId\",\n \"type\": \"uint32\",\n \"indexed\": false,\n \"internalType\": \"uint32\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppMetadataURIUpdated\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n },\n {\n \"name\": \"metadataURI\",\n \"type\": \"string\",\n \"indexed\": false,\n \"internalType\": \"string\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppStarted\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppStopped\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppSuspended\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppTerminated\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppTerminatedByAdmin\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppUpgraded\",\n \"inputs\": [\n {\n \"name\": \"app\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"contractIApp\"\n },\n {\n \"name\": \"rmsReleaseId\",\n \"type\": \"uint256\",\n \"indexed\": false,\n \"internalType\": \"uint256\"\n },\n {\n \"name\": \"release\",\n \"type\": \"tuple\",\n \"indexed\": false,\n \"internalType\": \"structIAppController.Release\",\n \"components\": [\n {\n \"name\": \"rmsRelease\",\n \"type\": \"tuple\",\n \"internalType\": \"structIReleaseManagerTypes.Release\",\n \"components\": [\n {\n \"name\": \"artifacts\",\n \"type\": \"tuple[]\",\n \"internalType\": \"structIReleaseManagerTypes.Artifact[]\",\n \"components\": [\n {\n \"name\": \"digest\",\n \"type\": \"bytes32\",\n \"internalType\": \"bytes32\"\n },\n {\n \"name\": \"registry\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ]\n },\n {\n \"name\": \"upgradeByTime\",\n \"type\": \"uint32\",\n \"internalType\": \"uint32\"\n }\n ]\n },\n {\n \"name\": \"publicEnv\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n },\n {\n \"name\": \"encryptedEnv\",\n \"type\": \"bytes\",\n \"internalType\": \"bytes\"\n }\n ]\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"GlobalMaxActiveAppsSet\",\n \"inputs\": [\n {\n \"name\": \"limit\",\n \"type\": \"uint32\",\n \"indexed\": false,\n \"internalType\": \"uint32\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"Initialized\",\n \"inputs\": [\n {\n \"name\": \"version\",\n \"type\": \"uint8\",\n \"indexed\": false,\n \"internalType\": \"uint8\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"MaxActiveAppsSet\",\n \"inputs\": [\n {\n \"name\": \"user\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"limit\",\n \"type\": \"uint32\",\n \"indexed\": false,\n \"internalType\": \"uint32\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"error\",\n \"name\": \"AccountHasActiveApps\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"AppAlreadyExists\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"AppDoesNotExist\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"GlobalMaxActiveAppsExceeded\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidAppStatus\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidPermissions\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidReleaseMetadataURI\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidShortString\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"InvalidSignature\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"MaxActiveAppsExceeded\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"MoreThanOneArtifact\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"SignatureExpired\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"StringTooLong\",\n \"inputs\": [\n {\n \"name\": \"str\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ]\n }\n]\n","[\n {\n \"type\": \"function\",\n \"name\": \"acceptAdmin\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"addPendingAdmin\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"admin\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"canCall\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"caller\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"target\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"selector\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bool\",\n \"internalType\": \"bool\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAdmins\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address[]\",\n \"internalType\": \"address[]\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppointeePermissions\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"appointee\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address[]\",\n \"internalType\": \"address[]\"\n },\n {\n \"name\": \"\",\n \"type\": \"bytes4[]\",\n \"internalType\": \"bytes4[]\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getAppointees\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"target\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"selector\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address[]\",\n \"internalType\": \"address[]\"\n }\n ],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"getPendingAdmins\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"address[]\",\n \"internalType\": \"address[]\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"isAdmin\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"caller\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bool\",\n \"internalType\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"isPendingAdmin\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"pendingAdmin\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bool\",\n \"internalType\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"function\",\n \"name\": \"removeAdmin\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"admin\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"removeAppointee\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"appointee\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"target\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"selector\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"removePendingAdmin\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"admin\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"setAppointee\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"appointee\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"target\",\n \"type\": \"address\",\n \"internalType\": \"address\"\n },\n {\n \"name\": \"selector\",\n \"type\": \"bytes4\",\n \"internalType\": \"bytes4\"\n }\n ],\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\"\n },\n {\n \"type\": \"function\",\n \"name\": \"version\",\n \"inputs\": [],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"string\",\n \"internalType\": \"string\"\n }\n ],\n \"stateMutability\": \"view\"\n },\n {\n \"type\": \"event\",\n \"name\": \"AdminRemoved\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"admin\",\n \"type\": \"address\",\n \"indexed\": false,\n \"internalType\": \"address\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AdminSet\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"admin\",\n \"type\": \"address\",\n \"indexed\": false,\n \"internalType\": \"address\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppointeeRemoved\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"appointee\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"target\",\n \"type\": \"address\",\n \"indexed\": false,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"selector\",\n \"type\": \"bytes4\",\n \"indexed\": false,\n \"internalType\": \"bytes4\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"AppointeeSet\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"appointee\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"target\",\n \"type\": \"address\",\n \"indexed\": false,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"selector\",\n \"type\": \"bytes4\",\n \"indexed\": false,\n \"internalType\": \"bytes4\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"PendingAdminAdded\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"admin\",\n \"type\": \"address\",\n \"indexed\": false,\n \"internalType\": \"address\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"event\",\n \"name\": \"PendingAdminRemoved\",\n \"inputs\": [\n {\n \"name\": \"account\",\n \"type\": \"address\",\n \"indexed\": true,\n \"internalType\": \"address\"\n },\n {\n \"name\": \"admin\",\n \"type\": \"address\",\n \"indexed\": false,\n \"internalType\": \"address\"\n }\n ],\n \"anonymous\": false\n },\n {\n \"type\": \"error\",\n \"name\": \"AdminAlreadyPending\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"AdminAlreadySet\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"AdminNotPending\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"AdminNotSet\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"AppointeeAlreadySet\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"AppointeeNotSet\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"CannotHaveZeroAdmins\",\n \"inputs\": []\n },\n {\n \"type\": \"error\",\n \"name\": \"NotAdmin\",\n \"inputs\": []\n }\n]\n","/**\n * Browser-safe app action encoders\n *\n * These functions encode calldata for app lifecycle operations.\n * They only depend on viem and are safe to use in browser environments.\n */\n\nimport { parseAbi, encodeFunctionData } from \"viem\";\nimport type { AppId } from \"../types\";\n\n// Minimal ABI for app lifecycle operations\nconst CONTROLLER_ABI = parseAbi([\n \"function startApp(address appId)\",\n \"function stopApp(address appId)\",\n \"function terminateApp(address appId)\",\n]);\n\n/**\n * Encode start app call data for gas estimation or transaction\n */\nexport function encodeStartAppData(appId: AppId): `0x${string}` {\n return encodeFunctionData({\n abi: CONTROLLER_ABI,\n functionName: \"startApp\",\n args: [appId],\n });\n}\n\n/**\n * Encode stop app call data for gas estimation or transaction\n */\nexport function encodeStopAppData(appId: AppId): `0x${string}` {\n return encodeFunctionData({\n abi: CONTROLLER_ABI,\n functionName: \"stopApp\",\n args: [appId],\n });\n}\n\n/**\n * Encode terminate app call data for gas estimation or transaction\n */\nexport function encodeTerminateAppData(appId: AppId): `0x${string}` {\n return encodeFunctionData({\n abi: CONTROLLER_ABI,\n functionName: \"terminateApp\",\n args: [appId],\n });\n}\n","/**\n * SIWE (Sign-In with Ethereum) utilities for compute API authentication\n *\n * This module provides browser-safe utilities for creating and parsing SIWE messages\n * compatible with the compute-tee API. Uses the official `siwe` package (EIP-4361).\n */\n\nimport { SiweMessage, generateNonce as siweGenerateNonce } from \"siwe\";\nimport { Address } from \"viem\";\n\nexport interface SiweMessageParams {\n /** Ethereum address (checksummed or lowercase) */\n address: Address;\n /** Chain ID (e.g., 1 for mainnet, 11155111 for sepolia) */\n chainId: number;\n /** Domain requesting the signature (e.g., \"api.eigencloud.xyz\") */\n domain: string;\n /** Full URI of the signing request (e.g., \"https://api.eigencloud.xyz\") */\n uri: string;\n /** Optional nonce for replay protection (generated if not provided) */\n nonce?: string;\n /** Optional human-readable statement */\n statement?: string;\n /** Optional expiration time (defaults to 24 hours from now) */\n expirationTime?: Date;\n /** Optional issued at time (defaults to now) */\n issuedAt?: Date;\n /** Optional not-before time */\n notBefore?: Date;\n /** Optional request ID */\n requestId?: string;\n /** Optional resources array */\n resources?: string[];\n}\n\nexport interface SiweMessageResult {\n /** Raw SIWE message string for signing */\n message: string;\n /** Parsed parameters */\n params: Required<\n Pick<SiweMessageParams, \"address\" | \"chainId\" | \"domain\" | \"uri\" | \"nonce\" | \"issuedAt\">\n > &\n Omit<SiweMessageParams, \"address\" | \"chainId\" | \"domain\" | \"uri\" | \"nonce\" | \"issuedAt\">;\n}\n\n/**\n * Re-export generateNonce from siwe package\n */\nexport const generateNonce = siweGenerateNonce;\n\n/**\n * Create a SIWE message for compute API authentication\n *\n * @param params - Parameters for the SIWE message\n * @returns The SIWE message object with the raw message string\n *\n * @example\n * ```typescript\n * const { message } = createSiweMessage({\n * address: \"0x1234...\",\n * chainId: 11155111,\n * domain: \"api.eigencloud.xyz\",\n * uri: \"https://api.eigencloud.xyz\",\n * statement: \"Sign in to EigenCloud\",\n * });\n *\n * // Sign with wagmi\n * const signature = await signMessageAsync({ message });\n * ```\n */\nexport function createSiweMessage(params: SiweMessageParams): SiweMessageResult {\n const now = new Date();\n const nonce = params.nonce || generateNonce();\n const issuedAt = params.issuedAt || now;\n const expirationTime = params.expirationTime || new Date(now.getTime() + 24 * 60 * 60 * 1000); // 24 hours\n\n // Create SIWE message using the official package\n const siweMessage = new SiweMessage({\n domain: params.domain,\n address: params.address,\n statement: params.statement,\n uri: params.uri,\n version: \"1\",\n chainId: params.chainId,\n nonce,\n issuedAt: issuedAt.toISOString(),\n expirationTime: expirationTime.toISOString(),\n notBefore: params.notBefore?.toISOString(),\n requestId: params.requestId,\n resources: params.resources,\n });\n\n return {\n message: siweMessage.prepareMessage(),\n params: {\n address: params.address,\n chainId: params.chainId,\n domain: params.domain,\n uri: params.uri,\n nonce,\n issuedAt,\n statement: params.statement,\n expirationTime,\n notBefore: params.notBefore,\n requestId: params.requestId,\n resources: params.resources,\n },\n };\n}\n\n/**\n * Parse a SIWE message string back to structured parameters\n *\n * @param message - Raw SIWE message string\n * @returns Parsed parameters or null if invalid\n */\nexport function parseSiweMessage(message: string): SiweMessageParams | null {\n try {\n const siweMessage = new SiweMessage(message);\n\n return {\n address: siweMessage.address as Address,\n chainId: siweMessage.chainId,\n domain: siweMessage.domain,\n uri: siweMessage.uri,\n nonce: siweMessage.nonce,\n statement: siweMessage.statement,\n issuedAt: siweMessage.issuedAt ? new Date(siweMessage.issuedAt) : undefined,\n expirationTime: siweMessage.expirationTime ? new Date(siweMessage.expirationTime) : undefined,\n notBefore: siweMessage.notBefore ? new Date(siweMessage.notBefore) : undefined,\n requestId: siweMessage.requestId,\n resources: siweMessage.resources,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Check if a SIWE message has expired\n */\nexport function isSiweMessageExpired(params: SiweMessageParams): boolean {\n if (!params.expirationTime) return false;\n return new Date() > params.expirationTime;\n}\n\n/**\n * Check if a SIWE message is not yet valid (notBefore)\n */\nexport function isSiweMessageNotYetValid(params: SiweMessageParams): boolean {\n if (!params.notBefore) return false;\n return new Date() < params.notBefore;\n}\n","/**\n * React Hook for Compute API Session Management\n *\n * This hook provides a convenient way to manage compute API sessions in React applications.\n * It handles session state, auto-refresh, and provides login/logout methods.\n *\n * IMPORTANT: This hook requires React 18+ as a peer dependency.\n * Make sure your application has React installed.\n */\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { Address, Hex } from \"viem\";\nimport {\n ComputeApiConfig,\n getComputeApiSession,\n loginToComputeApi,\n logoutFromComputeApi,\n SessionError,\n SessionInfo,\n} from \"../auth/session\";\nimport { createSiweMessage, SiweMessageParams } from \"../auth/siwe\";\n\nexport interface UseComputeSessionConfig extends ComputeApiConfig {\n /**\n * Interval in milliseconds to check session validity\n * Set to 0 to disable auto-refresh\n * @default 60000 (1 minute)\n */\n refreshInterval?: number;\n\n /**\n * Whether to automatically check session on mount\n * @default true\n */\n checkOnMount?: boolean;\n\n /**\n * Callback when session expires or becomes invalid\n */\n onSessionExpired?: () => void;\n\n /**\n * Callback when session is successfully refreshed/validated\n */\n onSessionRefreshed?: (session: SessionInfo) => void;\n\n /**\n * Callback when an error occurs\n */\n onError?: (error: SessionError) => void;\n}\n\nexport interface UseComputeSessionReturn {\n /** Current session information */\n session: SessionInfo | null;\n\n /** Whether the session is currently being loaded/checked */\n isLoading: boolean;\n\n /** Any error that occurred during session operations */\n error: SessionError | null;\n\n /** Whether the user is authenticated */\n isAuthenticated: boolean;\n\n /**\n * Login to compute API with SIWE\n *\n * @param params - SIWE message parameters (address, chainId required)\n * @param signMessage - Function to sign the message (from wagmi's useSignMessage)\n * @returns Login result\n */\n login: (\n params: Omit<SiweMessageParams, \"domain\" | \"uri\"> & { domain?: string; uri?: string },\n signMessage: (args: { message: string }) => Promise<Hex>,\n ) => Promise<SessionInfo>;\n\n /**\n * Logout from compute API\n */\n logout: () => Promise<void>;\n\n /**\n * Manually refresh/check session status\n */\n refresh: () => Promise<SessionInfo>;\n\n /**\n * Clear any error state\n */\n clearError: () => void;\n}\n\n/**\n * React hook for managing compute API sessions with SIWE authentication\n *\n * @param config - Configuration options including baseUrl and refresh settings\n * @returns Session state and methods for login/logout/refresh\n *\n * @example\n * ```tsx\n * import { useComputeSession } from \"@layr-labs/ecloud-sdk/browser\";\n * import { useSignMessage, useAccount } from \"wagmi\";\n *\n * function MyComponent() {\n * const { address, chainId } = useAccount();\n * const { signMessageAsync } = useSignMessage();\n *\n * const {\n * session,\n * isLoading,\n * isAuthenticated,\n * login,\n * logout,\n * error,\n * } = useComputeSession({\n * baseUrl: \"https://api.eigencloud.xyz\",\n * onSessionExpired: () => console.log(\"Session expired!\"),\n * });\n *\n * const handleLogin = async () => {\n * if (!address || !chainId) return;\n * await login(\n * { address, chainId },\n * signMessageAsync\n * );\n * };\n *\n * if (isLoading) return <div>Loading...</div>;\n *\n * return (\n * <div>\n * {isAuthenticated ? (\n * <>\n * <p>Logged in as {session?.address}</p>\n * <button onClick={logout}>Logout</button>\n * </>\n * ) : (\n * <button onClick={handleLogin}>Login</button>\n * )}\n * {error && <p>Error: {error.message}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useComputeSession(config: UseComputeSessionConfig): UseComputeSessionReturn {\n const {\n baseUrl,\n refreshInterval = 60000, // 1 minute default\n checkOnMount = true,\n onSessionExpired,\n onSessionRefreshed,\n onError,\n } = config;\n\n const [session, setSession] = useState<SessionInfo | null>(null);\n const [isLoading, setIsLoading] = useState(checkOnMount);\n const [error, setError] = useState<SessionError | null>(null);\n\n // Track if we were previously authenticated (for expiry detection)\n const wasAuthenticatedRef = useRef(false);\n // Track if component is mounted\n const isMountedRef = useRef(true);\n // Track refresh interval\n const refreshIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);\n\n const apiConfig: ComputeApiConfig = { baseUrl };\n\n /**\n * Check session status and update state\n */\n const checkSession = useCallback(async (): Promise<SessionInfo> => {\n try {\n const sessionInfo = await getComputeApiSession(apiConfig);\n\n if (!isMountedRef.current) {\n return sessionInfo;\n }\n\n setSession(sessionInfo);\n setError(null);\n\n // Detect session expiry\n if (wasAuthenticatedRef.current && !sessionInfo.authenticated) {\n onSessionExpired?.();\n }\n\n wasAuthenticatedRef.current = sessionInfo.authenticated;\n\n if (sessionInfo.authenticated) {\n onSessionRefreshed?.(sessionInfo);\n }\n\n return sessionInfo;\n } catch (err) {\n if (!isMountedRef.current) {\n throw err;\n }\n\n const sessionError =\n err instanceof SessionError\n ? err\n : new SessionError(`Failed to check session: ${String(err)}`, \"UNKNOWN\");\n\n setError(sessionError);\n onError?.(sessionError);\n\n // Return unauthenticated session on error\n const fallbackSession: SessionInfo = { authenticated: false };\n setSession(fallbackSession);\n return fallbackSession;\n }\n }, [baseUrl, onSessionExpired, onSessionRefreshed, onError]);\n\n /**\n * Refresh session (public method)\n */\n const refresh = useCallback(async (): Promise<SessionInfo> => {\n setIsLoading(true);\n try {\n return await checkSession();\n } finally {\n if (isMountedRef.current) {\n setIsLoading(false);\n }\n }\n }, [checkSession]);\n\n /**\n * Login with SIWE\n */\n const login = useCallback(\n async (\n params: Omit<SiweMessageParams, \"domain\" | \"uri\"> & { domain?: string; uri?: string },\n signMessage: (args: { message: string }) => Promise<Hex>,\n ): Promise<SessionInfo> => {\n setIsLoading(true);\n setError(null);\n\n try {\n // Determine domain and uri\n // In browser, use window.location; otherwise require explicit values\n let domain = params.domain;\n let uri = params.uri;\n\n if (typeof window !== \"undefined\") {\n domain = domain || window.location.host;\n uri = uri || window.location.origin;\n }\n\n if (!domain || !uri) {\n throw new SessionError(\n \"domain and uri are required when not in browser environment\",\n \"INVALID_MESSAGE\",\n );\n }\n\n // Create SIWE message\n const siweMessage = createSiweMessage({\n ...params,\n domain,\n uri,\n statement: params.statement || \"Sign in to EigenCloud Compute API\",\n });\n\n // Sign the message\n const signature = await signMessage({ message: siweMessage.message });\n\n // Login to compute API\n await loginToComputeApi(apiConfig, {\n message: siweMessage.message,\n signature,\n });\n\n // Fetch and return updated session\n const sessionInfo = await checkSession();\n\n if (!isMountedRef.current) {\n return sessionInfo;\n }\n\n wasAuthenticatedRef.current = sessionInfo.authenticated;\n return sessionInfo;\n } catch (err) {\n if (!isMountedRef.current) {\n throw err;\n }\n\n const sessionError =\n err instanceof SessionError\n ? err\n : new SessionError(`Login failed: ${String(err)}`, \"UNKNOWN\");\n\n setError(sessionError);\n onError?.(sessionError);\n throw sessionError;\n } finally {\n if (isMountedRef.current) {\n setIsLoading(false);\n }\n }\n },\n [baseUrl, checkSession, onError],\n );\n\n /**\n * Logout\n */\n const logout = useCallback(async (): Promise<void> => {\n setIsLoading(true);\n setError(null);\n\n try {\n await logoutFromComputeApi(apiConfig);\n\n if (!isMountedRef.current) {\n return;\n }\n\n const newSession: SessionInfo = { authenticated: false };\n setSession(newSession);\n wasAuthenticatedRef.current = false;\n } catch (err) {\n if (!isMountedRef.current) {\n throw err;\n }\n\n const sessionError =\n err instanceof SessionError\n ? err\n : new SessionError(`Logout failed: ${String(err)}`, \"UNKNOWN\");\n\n setError(sessionError);\n onError?.(sessionError);\n\n // Still clear session locally even if server logout failed\n setSession({ authenticated: false });\n wasAuthenticatedRef.current = false;\n } finally {\n if (isMountedRef.current) {\n setIsLoading(false);\n }\n }\n }, [baseUrl, onError]);\n\n /**\n * Clear error state\n */\n const clearError = useCallback(() => {\n setError(null);\n }, []);\n\n // Check session on mount\n useEffect(() => {\n isMountedRef.current = true;\n\n if (checkOnMount) {\n checkSession().finally(() => {\n if (isMountedRef.current) {\n setIsLoading(false);\n }\n });\n }\n\n return () => {\n isMountedRef.current = false;\n };\n }, [checkOnMount, checkSession]);\n\n // Set up auto-refresh interval\n useEffect(() => {\n if (refreshInterval <= 0) {\n return;\n }\n\n // Clear existing interval\n if (refreshIntervalRef.current) {\n clearInterval(refreshIntervalRef.current);\n }\n\n // Set up new interval\n refreshIntervalRef.current = setInterval(() => {\n // Only refresh if we think we're authenticated\n if (wasAuthenticatedRef.current) {\n checkSession();\n }\n }, refreshInterval);\n\n return () => {\n if (refreshIntervalRef.current) {\n clearInterval(refreshIntervalRef.current);\n refreshIntervalRef.current = null;\n }\n };\n }, [refreshInterval, checkSession]);\n\n return {\n session,\n isLoading,\n error,\n isAuthenticated: session?.authenticated ?? false,\n login,\n logout,\n refresh,\n clearError,\n };\n}\n\n// Re-export types for convenience\nexport type { SessionInfo, SessionError, ComputeApiConfig };\n","/**\n * KMS encryption utilities\n * Implements RSA-OAEP-256 + AES-256-GCM encryption using JWE format\n */\n\nimport { Buffer } from \"buffer\";\nimport { importSPKI, CompactEncrypt, type CompactJWEHeaderParameters } from \"jose\";\n\n/**\n * Get app protected headers for encryption\n */\nexport function getAppProtectedHeaders(appID: string): Record<string, string> {\n return {\n \"x-eigenx-app-id\": appID,\n };\n}\n\n/**\n * Encrypt data using RSA-OAEP-256 for key encryption and AES-256-GCM for data encryption\n * Uses jose library which properly implements JWE with RSA-OAEP-256\n */\nexport async function encryptRSAOAEPAndAES256GCM(\n encryptionKeyPEM: string | Buffer,\n plaintext: Buffer,\n protectedHeaders?: Record<string, string> | null,\n): Promise<string> {\n const pemString =\n typeof encryptionKeyPEM === \"string\" ? encryptionKeyPEM : encryptionKeyPEM.toString(\"utf-8\");\n\n // Import RSA public key from PEM format\n // jose handles both PKIX and PKCS#1 formats automatically\n const publicKey = await importSPKI(pemString, \"RSA-OAEP-256\", {\n extractable: true,\n });\n\n // Build protected header\n const header: CompactJWEHeaderParameters = {\n alg: \"RSA-OAEP-256\", // Key encryption algorithm (SHA-256)\n enc: \"A256GCM\", // Content encryption algorithm\n ...(protectedHeaders || {}), // Add custom protected headers\n };\n\n // Encrypt using JWE compact serialization\n // CompactEncrypt is a class that builds and encrypts Compact JWE strings\n // Convert Buffer to Uint8Array for jose library\n const plaintextBytes = new Uint8Array(plaintext);\n const jwe = await new CompactEncrypt(plaintextBytes)\n .setProtectedHeader(header)\n .encrypt(publicKey);\n\n return jwe;\n}\n","-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0kHU86k17ofCIGcJKDcf\nAFurFhSLeWmOL0bwWLCeVnTPG0MMHtJOq+woE0XXSWw6lzm+jzavBBTwKde1dgal\nAp91vULAZFMUpiUdd2dNUVtvU89qW0Pgf1Eu5FDj7BkY/SnyECbWJM4ga0BmpiGy\nnQwLNN9mMGhjVoVLn2zwEGZ7JzS9Nz11EZKO/k/9DcO6LaoIFm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z5ztV0znJ/Fpfs5A45FWA6pfb28fA59RGpi/DQ8RxgdCH\nnZRNvdz8dTgRaXSPgkfGXBcCFqb/QhFmad7XbWDthGzfhbPOxNPtiaGRQ1Dr/Pgq\nn0ugdLbRQLmDOAFgaQcnr0U4y1TUlWJnvoZMETkVN7gmITtXA4F324ALT7Rd+Lgk\nHikW5vG+NjAEwXfPsK0YzT+VbHd7o1lbru9UxiDlN03XVEkz/oRQi47CvSTo3FSr\n5dB4lz8kov3UUcNJfQFZolMCAwEAAQ==\n-----END PUBLIC KEY-----","-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEsk6ZdmmvBqFfKHs+1cYjIemRGN7h\n1NatIEitFRyx+3q8wmTJ9LknTE1FwWBLcCNTseJDti8Rh+SaVxfGOyJuuA==\n-----END PUBLIC KEY-----","/**\n * KMS key loading utilities\n */\n\n// Import all keys at build time\nimport mainnetAlphaProdEncryption from \"../../../../keys/mainnet-alpha/prod/kms-encryption-public-key.pem\";\nimport mainnetAlphaProdSigning from \"../../../../keys/mainnet-alpha/prod/kms-signing-public-key.pem\";\nimport sepoliaDevEncryption from \"../../../../keys/sepolia/dev/kms-encryption-public-key.pem\";\nimport sepoliaDevSigning from \"../../../../keys/sepolia/dev/kms-signing-public-key.pem\";\nimport sepoliaProdEncryption from \"../../../../keys/sepolia/prod/kms-encryption-public-key.pem\";\nimport sepoliaProdSigning from \"../../../../keys/sepolia/prod/kms-signing-public-key.pem\";\n\ntype BuildType = \"dev\" | \"prod\";\ntype KeyPair = { encryption: string; signing: string };\n\nconst KEYS = {\n \"mainnet-alpha\": {\n prod: {\n encryption: mainnetAlphaProdEncryption,\n signing: mainnetAlphaProdSigning,\n },\n },\n sepolia: {\n dev: {\n encryption: sepoliaDevEncryption,\n signing: sepoliaDevSigning,\n },\n prod: {\n encryption: sepoliaProdEncryption,\n signing: sepoliaProdSigning,\n },\n },\n} as const satisfies Record<string, Partial<Record<BuildType, KeyPair>>>;\n\n/**\n * Get KMS keys for environment\n */\nexport function getKMSKeysForEnvironment(\n environment: string,\n build: BuildType = \"prod\",\n): { encryptionKey: Buffer; signingKey: Buffer } {\n const envKeys = (KEYS as Record<string, Partial<Record<BuildType, KeyPair>>>)[environment];\n if (!envKeys) {\n throw new Error(`No keys found for environment: ${environment}`);\n }\n\n const buildKeys = envKeys[build];\n if (!buildKeys) {\n throw new Error(`No keys found for environment: ${environment}, build: ${build}`);\n }\n\n return {\n encryptionKey: Buffer.from(buildKeys.encryption),\n signingKey: Buffer.from(buildKeys.signing),\n };\n}\n\n/**\n * Check if keys exist for environment\n */\nexport function keysExistForEnvironment(environment: string, build: BuildType = \"prod\"): boolean {\n const envKeys = (KEYS as Record<string, Partial<Record<BuildType, KeyPair>>>)[environment];\n if (!envKeys) return false;\n return !!envKeys[build];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4DA,SAASA,gBAAe,KAAqB;AAC3C,SAAO,IAAI,WAAW,IAAI,IAAI,IAAI,MAAM,CAAC,IAAI;AAC/C;AAKA,eAAe,mBAAmB,UAAqC;AACrE,MAAI;AACF,UAAM,OAAQ,MAAM,SAAS,KAAK;AAClC,WAAO,KAAK,SAAS,SAAS;AAAA,EAChC,QAAQ;AACN,WAAO,SAAS;AAAA,EAClB;AACF;AA8BA,eAAsB,kBACpB,QACA,SACsB;AACtB,MAAI;AAEJ,MAAI;AACF,eAAW,MAAM,MAAM,GAAG,OAAO,OAAO,oBAAoB;AAAA,MAC1D,QAAQ;AAAA,MACR,aAAa;AAAA;AAAA,MACb,SAAS;AAAA,QACP,gBAAgB;AAAA,MAClB;AAAA,MACA,MAAM,KAAK,UAAU;AAAA,QACnB,SAAS,QAAQ;AAAA,QACjB,WAAWA,gBAAe,QAAQ,SAAS;AAAA,MAC7C,CAAC;AAAA,IACH,CAAC;AAAA,EACH,SAAS,OAAO;AACd,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M,MAAM,IAAI,2BAAe,cAAc,EAChD,mBAAmB,MAAM,EACzB,QAAQ,SAAS;AAEpB,SAAO;AACT;;;ACnDA;;;ACAA;;;ACAA,IAAAC,qCAAA;;;ACAA,IAAAC,kCAAA;;;ACAA,IAAAC,qCAAA;;;ACAA,IAAAC,kCAAA;;;ACeA,IAAM,OAAO;AAAA,EACX,iBAAiB;AAAA,IACf,MAAM;AAAA,MACJ,YAAY;AAAA,MACZ,SAAS;AAAA,IACX;AAAA,EACF;AAAA,EACA,SAAS;AAAA,IACP,KAAK;AAAA,MACH,YAAYC;AAAA,MACZ,SAASC;AAAA,IACX;AAAA,IACA,MAAM;AAAA,MACJ,YAAYD;AAAA,MACZ,SAASC;AAAA,IACX;AAAA,EACF;AACF;AAKO,SAAS,yBACd,aACA,QAAmB,QAC4B;AAC/C,QAAM,UAAW,KAA6D,WAAW;AACzF,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,kCAAkC,WAAW,EAAE;AAAA,EACjE;AAEA,QAAM,YAAY,QAAQ,KAAK;AAC/B,MAAI,CAAC,WAAW;AACd,UAAM,IAAI,MAAM,kCAAkC,WAAW,YAAY,KAAK,EAAE;AAAA,EAClF;AAEA,SAAO;AAAA,IACL,eAAe,OAAO,KAAK,UAAU,UAAU;AAAA,IAC/C,YAAY,OAAO,KAAK,UAAU,OAAO;AAAA,EAC3C;AACF;","names":["stripHexPrefix","import_viem","import_chains","import_accounts","import_viem","axios","import_axios","stripHexPrefix","parseErrorResponse","loginToComputeApi","logoutFromComputeApi","axios","body","import_axios","axios","import_viem","isDelegated","import_viem","import_viem","siweGenerateNonce","kms_encryption_public_key_default","kms_signing_public_key_default","kms_encryption_public_key_default","kms_signing_public_key_default","kms_encryption_public_key_default","kms_signing_public_key_default"]}