phala 1.0.18 → 1.1.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -3
- package/dist/_esm-2SSTGT5A.js +10 -0
- package/dist/_esm-2SSTGT5A.js.map +1 -0
- package/dist/api/index.d.ts +312 -14
- package/dist/api/index.js +1 -1
- package/dist/ccip-V5MAMPAX.js +2 -0
- package/dist/ccip-V5MAMPAX.js.map +1 -0
- package/dist/chunk-KC2EQH4K.js +2 -0
- package/dist/chunk-KC2EQH4K.js.map +1 -0
- package/dist/chunk-WITLSA6W.js +42 -0
- package/dist/chunk-WITLSA6W.js.map +1 -0
- package/dist/chunk-ZUJB7PGQ.js +58 -0
- package/dist/chunk-ZUJB7PGQ.js.map +1 -0
- package/dist/index.js +34 -26
- package/dist/index.js.map +1 -1
- package/package.json +6 -2
- package/dist/chunk-6GN3UXCF.js +0 -58
- package/dist/chunk-6GN3UXCF.js.map +0 -1
package/dist/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils/banner.ts","../src/commands/auth/index.ts","../src/commands/auth/login.ts","../src/commands/auth/logout.ts","../src/commands/auth/status.ts","../src/commands/docker/index.ts","../src/commands/docker/login.ts","../src/utils/docker.ts","../src/utils/prompts.ts","../src/utils/simulator.ts","../src/commands/docker/build.ts","../src/commands/docker/push.ts","../src/commands/docker/generate.ts","../src/commands/simulator/index.ts","../src/commands/simulator/start.ts","../src/commands/simulator/stop.ts","../src/commands/cvms/index.ts","../src/commands/cvms/list.ts","../src/commands/cvms/get.ts","../src/utils/cvms.ts","../src/commands/cvms/start.ts","../src/commands/cvms/stop.ts","../src/commands/cvms/restart.ts","../src/commands/cvms/attestation.ts","../src/commands/cvms/create.ts","../src/utils/secrets.ts","../src/commands/cvms/delete.ts","../src/commands/cvms/upgrade.ts","../src/commands/cvms/resize.ts","../src/commands/cvms/list-node.ts","../src/commands/cvms/replicate.ts","../src/commands/join.ts","../src/commands/demo/index.ts","../src/utils/demo.ts","../src/commands/nodes/index.ts","../src/commands/nodes/list.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from \"commander\";\nimport { logo } from \"./utils/banner\";\nimport { authCommands } from \"./commands/auth\";\nimport { dockerCommands } from \"./commands/docker\";\nimport { simulatorCommands } from \"./commands/simulator\";\nimport { logger } from \"./utils/logger\";\nimport { cvmsCommand } from \"./commands/cvms\";\nimport { joinCommand } from \"./commands/join\";\nimport { demoCommands } from \"./commands/demo\";\nimport { nodesCommand } from \"./commands/nodes\";\n\nprocess.on(\"SIGINT\", () => process.exit(0));\nprocess.on(\"SIGTERM\", () => process.exit(0));\n\nasync function main() {\n const program = new Command()\n\t\t\t.name(\"phala\")\n\t\t\t.alias(\"pha\")\n\t\t\t.description(\n\t\t\t\t`${logo}\\nPhala Cloud CLI - Manage your Phala Cloud Deployments`,\n\t\t\t)\n\t\t\t.version(\"v1.0.15\")\n\t\t\t.addCommand(authCommands)\n\t\t\t.addCommand(cvmsCommand)\n\t\t\t.addCommand(dockerCommands)\n\t\t\t.addCommand(simulatorCommands)\n\t\t\t.addCommand(demoCommands)\n\t\t\t.addCommand(joinCommand)\n\t\t\t.addCommand(nodesCommand);\n\n\tprogram.parse(process.argv);\n}\n\nmain().catch((error) => {\n\tlogger.error(\"An error occurred:\", error);\n\tprocess.exit(1);\n});\n","import chalk from 'chalk';\nconst logoColor = chalk.hex('#cdfa50');\nexport const logo = logoColor(`\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣠⣤⣤⣤⣀⡀⠀⢀⣀⣤⣤⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⡿⠛⠉⠁⠀⠈⠉⠛⠿⠛⠉⠉⠉⠉⠙⠷⣄⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣧⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣆⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⠞⠛⠉⠙⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠛⢶⣄⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣦⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⣿⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣿⣷⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣴⣿⣿⡿⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠀⠀⣀⣴⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠻⠿⠿⠿⠿⠃⠀⢀⣾⣿⣿⣿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠛⠋⠁⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣿⡿⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡤⠤⠤⠴⠒⠒⠒⠒⠒⢿⡿⠓⠒⠒⠢⠤⠤⠤⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣯⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁⠀⠀⠀⠀⠀⠀⠀⣀⣨⣿⣦⣤⣀⡀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣶⣶⣶⣶⣶⣶⣶⣶⣶⣶⣶⣶⣾⣿⣿⣿⣿⣿⡏⠉⠛⣿⣆⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⣀⣀⣀⣀⡸⠿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⣸⡿⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⣿⣿⣿⣿⣿⣿⣿⠀⢸⣿⣿⣿⣿⡇⠀⣿⣿⣿⣿⣿⣿⠃⢀⣠⣴⡿⠃⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⣿⣿⣿⣿⣿⣿⠿⢇⣀⣀⣀⣀⣸⣿⣿⣿⣿⣿⡿⠿⠿⠛⠛⠁⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⡠⠀⠀⠀⠀⠈⠻⢿⣿⣿⣿⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀⠠⣄⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⢸⣆⠀⠀⠀⠀⠀⠀⠀⠉⠛⠿⠿⣿⣿⣿⣿⣿⠿⠟⠋⠁⠀⠀⠀⠀⠀⠀⣀⣾⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠙⠻⢶⣦⣤⣄⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣀⣤⣴⣶⠿⠛⠁⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠙⠛⠻⠿⠿⠿⠿⢿⣿⣿⣿⠿⠿⠿⠿⠟⠛⠛⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n`);\n\nexport const smallLogo = logoColor(`\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣠⣤⣤⣤⣀⡀⠀⢀⣀⣤⣤⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⡿⠛⠉⠁⠀⠈⠉⠛⠿⠛⠉⠉⠉⠉⠙⠷⣄⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣧⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣆⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⠞⠛⠉⠙⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠛⢶⣄⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣦⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⣿⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣿⣷⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣴⣿⣿⡿⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠀⠀⣀⣴⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠻⠿⠿⠿⠿⠃⠀⢀⣾⣿⣿⣿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠛⠋⠁⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣿⡿⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡤⠤⠤⠴⠒⠒⠒⠒⠒⢿⡿⠓⠒⠒⠢⠤⠤⠤⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣯⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁⠀⠀⠀⠀⠀⠀⠀⣀⣨⣿⣦⣤⣀⡀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣶⣶⣶⣶⣶⣶⣶⣶⣶⣶⣶⣶⣾⣿⣿⣿⣿⣿⡏⠉⠛⣿⣆⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⣀⣀⣀⣀⡸⠿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⣸⡿⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⣿⣿⣿⣿⣿⣿⣿⠀⢸⣿⣿⣿⣿⡇⠀⣿⣿⣿⣿⣿⣿⠃⢀⣠⣴⡿⠃⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⣿⣿⣿⣿⣿⣿⠿⢇⣀⣀⣀⣀⣸⣿⣿⣿⣿⣿⡿⠿⠿⠛⠛⠁⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⡠⠀⠀⠀⠀⠈⠻⢿⣿⣿⣿⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀⠠⣄⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⢸⣆⠀⠀⠀⠀⠀⠀⠀⠉⠛⠿⠿⣿⣿⣿⣿⣿⠿⠟⠋⠁⠀⠀⠀⠀⠀⠀⣀⣾⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠙⠻⢶⣦⣤⣄⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣀⣤⣴⣶⠿⠛⠁⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠙⠛⠻⠿⠿⠿⠿⢿⣿⣿⣿⠿⠿⠿⠿⠟⠛⠛⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n`);\n\nexport const minimalLogo = chalk.cyan('PHALA TEE CLOUD CLI');","import { Command } from 'commander';\nimport { loginCommand } from './login';\nimport { logoutCommand } from './logout';\nimport { statusCommand } from './status';\n\nexport const authCommands = new Command()\n .name('auth')\n .description('Authenticate with Phala Cloud')\n .addCommand(loginCommand)\n .addCommand(logoutCommand)\n .addCommand(statusCommand);\n","import { Command } from 'commander';\nimport { removeApiKey, saveApiKey } from '@/src/utils/credentials';\nimport { logger } from '@/src/utils/logger';\nimport prompts from 'prompts';\nimport { getUserInfo } from '@/src/api/auth';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nexport const loginCommand = new Command()\n .name('login')\n .description('Set the API key for authentication')\n .argument('[api-key]', 'Phala Cloud API key to set')\n .action(async (apiKey?: string) => {\n try {\n let checkUserInfo;\n // If no API key is provided, prompt for it\n if (!apiKey) {\n const response = await prompts({\n type: 'password',\n name: 'apiKey',\n message: 'Enter your API key:',\n validate: async (value) => {\n if (value.length === 0) {\n return 'API key cannot be empty';\n }\n try {\n await saveApiKey(value);\n checkUserInfo = await getUserInfo();\n if (!checkUserInfo.username) {\n await removeApiKey();\n return 'Invalid API key';\n }\n } catch (error) {\n return 'Invalid API key';\n }\n return true;\n }\n });\n \n apiKey = response.apiKey;\n } else {\n await saveApiKey(apiKey);\n // Validate the API key\n checkUserInfo = await getUserInfo();\n if (!checkUserInfo.username) {\n await removeApiKey();\n return 'Invalid API key';\n }\n }\n \n logger.success(`Welcome ${checkUserInfo.username}! API key validated and saved successfully`);\n logger.break();\n logger.info(`Open in Web UI at ${CLOUD_URL}/dashboard/`);\n } catch (error) {\n logger.error(`Failed to set API key: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { removeApiKey } from '@/src/utils/credentials';\nimport { logger } from '@/src/utils/logger';\n\nexport const logoutCommand = new Command()\n .name('logout')\n .description('Remove the stored API key')\n .action(async () => {\n try {\n await removeApiKey();\n logger.success('API key removed successfully');\n } catch (error) {\n logger.error(`Failed to remove API key: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { getApiKey } from '@/src/utils/credentials';\nimport { getUserInfo } from '@/src/api/auth';\nimport { logger } from '@/src/utils/logger';\n\nexport const statusCommand = new Command()\n .name('status')\n .description('Check authentication status')\n .option('-j, --json', 'Output in JSON format')\n .option('-d, --debug', 'Enable debug output')\n .action(async (options) => {\n try {\n // Enable debug mode if requested\n if (options.debug) {\n process.env.DEBUG = 'true';\n }\n \n const apiKey = await getApiKey();\n \n if (!apiKey) {\n logger.warn('Not authenticated. Please set an API key with \"phala auth login\"');\n return;\n }\n \n logger.debug(`Using API key: ${apiKey.substring(0, 5)}...`);\n const spinner = logger.startSpinner('Checking authentication status');\n \n try {\n const userInfo = await getUserInfo();\n spinner.stop(true);\n \n if (options.json) {\n console.log(JSON.stringify(userInfo, null, 2));\n return;\n }\n \n logger.break();\n logger.success(`Authenticated as ${userInfo.username}`);\n \n // Create a simple object\n const tableData = {\n 'Username': userInfo.username,\n 'Email': userInfo.email,\n 'Role': userInfo.role,\n 'Team': `${userInfo.team_name} (${userInfo.team_tier})`,\n 'Credits': `$${(userInfo.credits + userInfo.granted_credits).toFixed(2)}`\n };\n \n if (userInfo.trial_ended_at) {\n tableData['Trial Ended At'] = userInfo.trial_ended_at;\n }\n \n // Display the table\n logger.keyValueTable(tableData, {\n borderStyle: 'rounded'\n });\n } catch (error) {\n spinner.stop(false);\n logger.error('Authentication failed. Your API key may be invalid or expired.');\n logger.info('Please set a new API key with \"phala auth login\"');\n \n if (options.debug) {\n logger.debug(`Error details: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n } catch (error) {\n logger.error(`Failed to check authentication status: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { loginCommand } from './login';\nimport { buildCommand } from './build';\nimport { pushCommand } from './push';\nimport { generateCommand } from './generate';\n\nexport const dockerCommands = new Command()\n .name('docker')\n .description('Login to Docker Hub and manage Docker images')\n .addCommand(loginCommand)\n .addCommand(buildCommand)\n .addCommand(pushCommand)\n .addCommand(generateCommand);\n","import { Command } from 'commander';\nimport { DockerService } from '@/src/utils/docker';\nimport { saveDockerCredentials } from '@/src/utils/credentials';\nimport { logger } from '@/src/utils/logger';\nimport prompts from 'prompts';\n\nexport const loginCommand = new Command()\n .name('login')\n .description('Login to Docker Hub')\n .option('-u, --username <username>', 'Docker Hub username')\n .option('-p, --password <password>', 'Docker Hub password')\n .option('-r, --registry <registry>', 'Docker registry URL')\n .action(async (options) => {\n try {\n let username = options.username;\n let password = options.password;\n const registry = options.registry;\n \n // If no username is provided, prompt for it\n if (!username) {\n logger.info('First we need your Docker Hub username to check if you are already logged in.');\n\n const response = await prompts({\n type: 'text',\n name: 'username',\n message: 'Enter your Docker Hub username:',\n validate: value => value.length > 0 ? true : 'Username cannot be empty'\n });\n \n if (!response.username) {\n logger.error('Username is required');\n process.exit(1);\n }\n \n username = response.username;\n }\n\n // Check if Docker is already logged in\n const dockerService = new DockerService('', username, registry);\n const loggedIn = await dockerService.login(username);\n if (loggedIn) {\n logger.success(`${username} is logged in to Docker Hub`);\n // Save credentials\n await saveDockerCredentials({\n username,\n registry: registry || null,\n });\n return;\n }\n \n // If no password is provided, prompt for it\n if (!password) {\n const response = await prompts({\n type: 'password',\n name: 'password',\n message: 'Enter your Docker Hub password:',\n validate: value => value.length > 0 ? true : 'Password cannot be empty'\n });\n \n if (!response.password) {\n logger.error('Password is required');\n process.exit(1);\n }\n \n password = response.password;\n }\n \n // Login to Docker Hub\n const success = await dockerService.login(username, password, registry);\n \n if (!success) {\n logger.error('Failed to login to Docker Hub');\n process.exit(1);\n }\n \n // Save credentials\n await saveDockerCredentials({\n username,\n registry: registry || null\n });\n \n logger.success('Logged in to Docker Hub successfully');\n } catch (error) {\n logger.error(`Failed to login to Docker Hub: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { execa } from 'execa';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from './logger';\nimport { DOCKER_COMPOSE_BASIC_TEMPLATE, DOCKER_COMPOSE_ELIZA_V2_TEMPLATE } from './constants';\nimport { getDockerCredentials } from './credentials';\nimport Handlebars from 'handlebars';\nimport { exec, spawn } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport os from 'node:os';\nimport { validateFileExists } from './prompts';\nimport { ComposeTemplateSchema } from './types';\nimport { deleteSimulatorEndpointEnv, setSimulatorEndpointEnv } from './simulator';\nconst execAsync = promisify(exec);\n\nconst LOGS_DIR = '.phala-cloud/logs';\nconst COMPOSE_FILES_DIR = '.phala-cloud/compose';\nconst MAX_CONSOLE_LINES = 10;\n\nexport class DockerService {\n private username: string;\n private image: string;\n private registry: string;\n\n constructor(image: string, username?: string, registry?: string) {\n this.image = image;\n this.username = username || '';\n this.registry = registry || '';\n }\n\n private ensureLogsDir(): void {\n const logsPath = path.resolve(LOGS_DIR);\n if (!fs.existsSync(logsPath)) {\n fs.mkdirSync(logsPath, { recursive: true });\n }\n }\n\n private getLogFilePath(operation: string, image?: string): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n return path.resolve(LOGS_DIR, `${image || this.image}-${operation}-${timestamp}.log`);\n }\n\n private getSystemArchitecture(): string {\n const arch = os.arch();\n switch (arch) {\n case 'arm':\n case 'arm64':\n return 'arm64';\n case 'x64':\n return 'amd64';\n default:\n return arch;\n }\n }\n\n private spawnProcess(command: string, args: string[], operation: string, image?: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const proc = spawn(command, args);\n // Ensure logs directory exists before creating write stream\n this.ensureLogsDir();\n\n const logFile = this.getLogFilePath(operation, image);\n\n const logStream = fs.createWriteStream(logFile, { flags: 'a' });\n const consoleBuffer: string[] = [];\n\n const processOutput = (data: Buffer, isError = false) => {\n const lines = data.toString().split('\\n');\n\n // Write to log file\n logStream.write(data);\n\n // Update console buffer\n for (const line of lines) {\n if (line.trim()) {\n consoleBuffer.push(line);\n // Keep only the last MAX_CONSOLE_LINES lines\n if (consoleBuffer.length > MAX_CONSOLE_LINES) {\n consoleBuffer.shift();\n }\n\n // Clear console and print the buffer\n console.clear();\n console.log(`Latest ${MAX_CONSOLE_LINES} lines (full log at ${logFile}):`);\n console.log('-'.repeat(50));\n for (const bufferedLine of consoleBuffer) {\n if (isError) {\n console.error(bufferedLine);\n } else {\n console.log(bufferedLine);\n }\n }\n }\n }\n };\n\n proc.stdout.on('data', (data) => processOutput(data));\n proc.stderr.on('data', (data) => processOutput(data, true));\n\n proc.on('close', (code) => {\n logStream.end();\n if (code === 0) {\n console.log(`\\nOperation completed. Full log available at: ${logFile}`);\n resolve();\n } else {\n reject(new Error(`Process exited with code ${code}. Check log file: ${logFile}`));\n }\n });\n\n proc.on('error', (err) => {\n logStream.end();\n reject(err);\n });\n });\n }\n\n /**\n * Set Docker credentials\n * @param username Docker username\n * @param registry Docker registry\n */\n setCredentials(username: string, registry?: string): void {\n this.username = username;\n if (registry) {\n this.registry = registry;\n }\n }\n\n /**\n * Build a Docker image\n * @param dockerfile Path to Dockerfile\n * @param tag Tag for the image\n * @returns Success status\n */\n async buildImage(dockerfile: string, tag: string): Promise<boolean> {\n try {\n const arch = this.getSystemArchitecture();\n const fullImageName = `${this.username}/${this.image}:${tag}`;\n\n const spinner = logger.startSpinner(`Building Docker image ${this.username}/${this.image}:${tag}`);\n\n // Ensure the Dockerfile exists\n validateFileExists(dockerfile);\n\n const buildArgs = ['build', '-t', fullImageName, '-f', dockerfile];\n\n if (arch === 'arm64') {\n console.log('Detected arm64 architecture, using --platform linux/amd64');\n buildArgs.push('--platform', 'linux/amd64');\n }\n\n // Build the image\n buildArgs.push('.');\n\n await this.spawnProcess('docker', buildArgs, 'build', this.image);\n\n spinner.stop(true, `Docker image ${fullImageName} built successfully`);\n return true;\n } catch (error) {\n logger.error(`Failed to build Docker image: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n /**\n * Push a Docker image to Docker Hub\n * @param imageName Full image name (e.g. username/image:tag)\n * @returns Success status\n */\n async pushImage(imageName: string): Promise<boolean> {\n try {\n const spinner = logger.startSpinner(`Pushing Docker image ${imageName} to Docker Hub`);\n\n // Check if user is logged in\n const credentials = await getDockerCredentials();\n if (!credentials) {\n spinner.stop(false);\n throw new Error('Docker credentials not found. Please log in first with \"phala docker login\"');\n }\n\n const fullImageName = imageName;\n console.log(`Pushing image ${fullImageName} to Docker Hub...`);\n\n await this.spawnProcess('docker', ['push', fullImageName], 'push', imageName.replace(/.*\\/+([\\w-]+):.*$/g, '$1'));\n\n spinner.stop(true, `Docker image ${fullImageName} pushed successfully`);\n return true;\n } catch (error) {\n logger.error(`Failed to push Docker image: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n\n /**\n * Login to Docker Hub\n * @param username Docker username\n * @param password Docker password\n * @param registry Docker registry\n * @returns Success status\n */\n async login(username: string, password?: string, registry?: string): Promise<boolean> {\n try {\n const spinner = logger.startSpinner(`Logging in to Docker Hub as ${username}`);\n\n // Check if already logged in\n const loggedIn = await this.checkLogin();\n if (loggedIn) {\n spinner.stop(true, 'Already logged in to Docker Hub');\n this.setCredentials(username, registry);\n return true;\n }\n\n // Verify password was provided\n if (!password) {\n spinner.stop(false);\n throw new Error('Password is required for Docker login');\n }\n\n // Login to Docker with timeout protection\n try {\n const loginProcess = execa('docker', [\n 'login',\n ...(registry ? [registry] : []),\n '-u',\n username,\n '--password-stdin'\n ], {\n input: password,\n timeout: 10000 // 10 second timeout\n });\n\n await loginProcess;\n } catch (loginError) {\n if (loginError.timedOut) {\n spinner.stop(false);\n throw new Error('Docker login timed out. Please check your credentials and try again.');\n }\n throw loginError;\n }\n\n spinner.stop(true, 'Logged in to Docker Hub successfully');\n this.setCredentials(username, registry);\n return true;\n } catch (error) {\n logger.error(`Failed to login to Docker Hub: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n /**\n * Check if Docker is logged in\n * @returns Success status\n */\n async checkLogin(): Promise<boolean> {\n try {\n // Instead of checking via \"docker login\" which is interactive,\n // check if the Docker config.json file exists and contains auth data\n const homeDir = os.homedir();\n const dockerConfigPath = path.join(homeDir, '.docker', 'config.json');\n \n if (!fs.existsSync(dockerConfigPath)) {\n return false;\n }\n \n // Read the docker config file\n const dockerConfig = JSON.parse(fs.readFileSync(dockerConfigPath, 'utf-8'));\n \n // Check if the config has auths data\n return !!(dockerConfig?.auths && Object.keys(dockerConfig.auths).length > 0);\n } catch (error) {\n logger.debug(`Docker login check failed: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n /**\n * Build a Docker Compose file\n * @param imageName Name of the image\n * @param envFile Optional path to environment file\n * @param version Version of the template to use\n * @returns Path to the generated Docker Compose file\n */\n async buildComposeFile(imageName: string, envFile?: string, templateType?: string): Promise<string> {\n if (!this.username) {\n throw new Error('Docker Hub username is required for building compose file');\n }\n\n const template = (templateType === 'eliza') ? DOCKER_COMPOSE_ELIZA_V2_TEMPLATE : DOCKER_COMPOSE_BASIC_TEMPLATE;\n\n // Validate template structure\n const validatedTemplate = ComposeTemplateSchema.parse({ template });\n\n // Ensure compose files directory exists\n const composePath = path.resolve(COMPOSE_FILES_DIR);\n \n // Create directory if it doesn't exist\n if (!fs.existsSync(composePath)) {\n logger.info(`Creating directory: ${composePath}`);\n fs.mkdirSync(composePath, { recursive: true });\n }\n\n let envVars: string[] = [];\n \n // Only parse env file if it's provided\n if (envFile) {\n // Parse env file to get variable names\n const envContent = fs.readFileSync(envFile, 'utf-8');\n envVars = envContent\n .split('\\n')\n .filter(line => line && !line.startsWith('#'))\n .map(line => {\n // Remove inline comments\n const commentIndex = line.indexOf('#');\n if (commentIndex > 0) {\n line = line.substring(0, commentIndex).trim();\n }\n return line.trim();\n })\n .filter(line => line.includes('='))\n .map(line => {\n const [key, value] = line.split('=', 2);\n const trimmedKey = key.trim();\n const trimmedValue = value ? value.trim() : '';\n\n // Skip empty values\n if (trimmedValue === '') {\n return null;\n }\n\n // Keep the original key without any transformation\n return `${trimmedKey}=${trimmedKey}`; // Create KEY=KEY format\n })\n .filter(Boolean as unknown as ((value: string | null) => value is string)); // Remove null entries\n }\n\n // Create full image name with username\n const fullImageName = imageName;\n\n // Compile template with data\n const compiledTemplate = Handlebars.compile(validatedTemplate.template, { noEscape: true });\n const composeContent = compiledTemplate({\n imageName: fullImageName,\n envVars: envVars.map(env => env.replace(/=.*/, `=\\${${env.split('=')[0]}}`))\n });\n\n // Write the docker-compose file with standardized name in the compose directory\n const composeFile = path.join(\n composePath,\n `${imageName.replace(/.*\\/+([\\w-]+):.*$/g, \"$1\")}-tee-compose.yaml`,\n );\n fs.writeFileSync(composeFile, composeContent);\n\n logger.success(`Backup of docker compose file created at: ${composeFile}`);\n return composeFile;\n }\n\n /**\n * Run a Docker Compose file locally\n * @param composePath Path to Docker Compose file\n * @param envFile Path to environment file\n * @returns Success status\n */\n async runComposeLocally(composePath: string, envFile?: string): Promise<boolean> {\n try {\n // TODO: Update log when optimized simulator is implemented\n const spinner = logger.startSpinner(`Running Docker Compose file at ${composePath}`);\n\n // Ensure the Docker Compose file exists\n validateFileExists(composePath);\n\n // Build the command arguments\n const composeArgs = [\n '-f',\n composePath,\n 'up',\n '-d'\n ];\n\n // Only add env-file if it's provided\n if (envFile) {\n // Ensure the environment file exists\n validateFileExists(envFile);\n composeArgs.splice(2, 0, '--env-file', envFile);\n }\n\n // Run the Docker Compose file\n await execAsync(`docker compose ${composeArgs.join(' ')}`);\n\n spinner.stop(true, 'Docker Compose file running successfully');\n return true;\n } catch (error) {\n logger.error(`Failed to run Docker Compose file: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n /**\n * Run the TEE simulator\n * @param image Simulator image\n * @returns Success status\n */\n async runSimulator(image: string, port: string): Promise<boolean> {\n try {\n logger.info(`Running TEE simulator with image ${image}`);\n\n logger.info('Pulling latest simulator image...');\n await execAsync(`docker pull ${image}`);\n\n logger.info('Starting simulator in background...');\n const { stdout } = await execAsync(`docker run -d --name tee-simulator --rm -p ${port}:${port} ${image}`);\n const containerId = stdout.trim();\n\n logger.success(`TEE simulator running successfully. Container ID: ${containerId}`);\n logger.break();\n logger.break();\n logger.info('Useful commands:');\n logger.info(`- View logs: docker logs -f ${containerId}`);\n logger.info(`- Stop simulator: docker stop ${containerId}`);\n\n setSimulatorEndpointEnv(`http://localhost:${port}`);\n \n return true;\n } catch (error) {\n logger.error(`Failed to run TEE simulator: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n /**\n * Stop the TEE simulator\n * @returns Success status\n */\n async stopSimulator(): Promise<boolean> {\n try {\n const spinner = logger.startSpinner('Stopping TEE simulator...');\n\n // Stop the simulator\n await execAsync('docker stop tee-simulator');\n await deleteSimulatorEndpointEnv();\n\n spinner.stop(true, 'TEE simulator stopped successfully');\n return true;\n } catch (error) {\n logger.error(`Failed to stop TEE simulator: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n /**\n * List local Docker images and their tags\n * @returns Array of objects with image name and tag\n */\n static async listLocalImages(): Promise<Array<{ imageName: string}>> {\n try {\n // Query Docker for local images in format that outputs repository and tag\n const { stdout } = await execAsync('docker images --format \"{{.Repository}}:{{.Tag}}\"');\n const credentials = await getDockerCredentials();\n const username = credentials?.username;\n // Parse the output and filter out any <none> tags or images\n const imageList = stdout.split('\\n')\n .filter(line => line && !line.includes('<none>'))\n .filter(line => line.includes(`${username}/`))\n .map(line => {\n const imageName = line;\n return { imageName };\n });\n\n return imageList;\n } catch (error) {\n logger.error(`Failed to list local Docker images: ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n }\n}\n\n","import inquirer from 'inquirer';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from './logger';\n\n/**\n * Validates that a file exists at the given path\n * @param filePath Path to the file to validate\n * @param basePath Optional base path to resolve relative paths against (defaults to process.cwd())\n * @returns True if the file exists, throws an error if not\n * @throws Error if the file does not exist\n */\nexport function validateFileExists(\n filePath: string,\n basePath: string = process.cwd()\n): boolean {\n const resolvedPath = path.resolve(basePath, filePath);\n if (!fs.existsSync(resolvedPath)) {\n throw new Error(`File not found at ${resolvedPath}`);\n }\n return true;\n}\n\n/**\n * Prompts the user for a file path and validates that the file exists\n * @param message The prompt message to display\n * @param defaultValue The default value for the prompt\n * @param name The name of the prompt (used as property name in the returned object)\n * @param basePath Optional base path to resolve relative paths against (defaults to process.cwd())\n * @returns The validated file path\n */\nexport async function promptForFile(\n message: string,\n defaultValue: string,\n name = 'file',\n basePath: string = process.cwd()\n): Promise<string> {\n const response = await inquirer.prompt([\n {\n type: 'input',\n name,\n message,\n default: defaultValue,\n validate: (input) => {\n const filePath = path.resolve(basePath, input);\n if (!fs.existsSync(filePath)) {\n return `File not found at ${filePath}`;\n }\n return true;\n }\n }\n ]);\n\n return response[name];\n}\n\nexport function detectFileInCurrentDir(\n possibleFiles: string[],\n logMessage?: string\n): string | undefined {\n for (const file of possibleFiles) {\n const filePath = path.join(process.cwd(), file);\n if (fs.existsSync(filePath)) {\n if (logMessage) {\n logger.info(logMessage.replace('{path}', filePath));\n } else {\n logger.info(`File detected: ${filePath}`);\n }\n return file;\n }\n }\n return undefined;\n}","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as os from 'node:os';\nimport { execSync, spawn, type StdioOptions } from 'node:child_process';\nimport * as net from 'node:net';\nimport { logger } from './logger';\n\n// Configuration for simulator\nconst SIMULATOR_CONFIG = {\n version: '0.1.4',\n baseUrl: 'https://github.com/Leechael/tappd-simulator/releases/download/v0.1.4',\n installDir: path.join(os.homedir(), '.phala-cloud', 'tappd-simulator'),\n // Default log file path\n defaultLogPath: path.join(os.homedir(), '.phala-cloud', 'logs', 'tappd-simulator.log'),\n platforms: {\n darwin: {\n filename: 'tappd-simulator-0.1.4-aarch64-apple-darwin.tgz',\n extractedFolder: 'tappd-simulator-0.1.4-aarch64-apple-darwin',\n socketArg: 'unix:/tmp/tappd.sock'\n },\n linux: {\n filename: 'tappd-simulator-0.1.4-x86_64-linux-musl.tgz',\n extractedFolder: 'tappd-simulator-0.1.4-x86_64-linux-musl',\n socketArg: 'unix:/tmp/tappd.sock'\n },\n win32: {\n filename: 'tappd-simulator-0.1.4-x86_64-pc-windows-msvc.tgz',\n extractedFolder: 'tappd-simulator-0.1.4-x86_64-pc-windows-msvc',\n socketArg: '127.0.0.1:8090'\n }\n }\n};\n\n/**\n * Check if the simulator is already installed\n * @returns boolean indicating if simulator is installed\n */\nexport function isSimulatorInstalled(): boolean {\n try {\n // Check if the main installation directory exists\n if (!fs.existsSync(SIMULATOR_CONFIG.installDir)) {\n return false;\n }\n\n // Get platform-specific folder name\n const platform = os.platform() as 'darwin' | 'linux' | 'win32';\n if (!SIMULATOR_CONFIG.platforms[platform]) {\n throw new Error(`Unsupported platform: ${platform}`);\n }\n\n const extractedFolderPath = path.join(\n SIMULATOR_CONFIG.installDir,\n SIMULATOR_CONFIG.platforms[platform].extractedFolder\n );\n\n // Check if the extracted folder exists\n if (!fs.existsSync(extractedFolderPath)) {\n return false;\n }\n\n // Check if the executable exists\n const executableName = platform === 'win32' ? 'tappd-simulator.exe' : 'tappd-simulator';\n const executablePath = path.join(extractedFolderPath, executableName);\n return fs.existsSync(executablePath);\n } catch (error) {\n logger.error('Error checking if simulator is installed:', error);\n return false;\n }\n}\n\n/**\n * Get the current platform\n * @returns The current platform: 'darwin', 'linux', or 'win32'\n * @throws Error if the platform is not supported\n */\nexport function getPlatform(): 'darwin' | 'linux' | 'win32' {\n const platform = os.platform() as 'darwin' | 'linux' | 'win32';\n if (!SIMULATOR_CONFIG.platforms[platform]) {\n throw new Error(`Unsupported platform: ${platform}. Only darwin, linux, and win32 are supported.`);\n }\n return platform;\n}\n\n/**\n * Install the simulator based on the current platform\n * @param progressCallback Optional callback to report progress\n * @returns Promise that resolves when installation is complete\n */\nexport async function installSimulator(\n progressCallback?: (message: string) => void\n): Promise<void> {\n const log = (message: string) => {\n logger.info(message);\n if (progressCallback) progressCallback(message);\n };\n\n try {\n const platform = getPlatform();\n const platformConfig = SIMULATOR_CONFIG.platforms[platform];\n \n // Create installation directory if it doesn't exist\n if (!fs.existsSync(SIMULATOR_CONFIG.installDir)) {\n logger.info(`Creating installation directory at ${SIMULATOR_CONFIG.installDir}`);\n fs.mkdirSync(SIMULATOR_CONFIG.installDir, { recursive: true });\n }\n\n // Change to the installation directory\n process.chdir(SIMULATOR_CONFIG.installDir);\n \n // Download the simulator\n const downloadUrl = `${SIMULATOR_CONFIG.baseUrl}/${platformConfig.filename}`;\n logger.info(`Downloading simulator from ${downloadUrl}`);\n execSync(`wget ${downloadUrl}`, { stdio: 'inherit' });\n \n // Extract the archive\n logger.info(`Extracting ${platformConfig.filename}`);\n execSync(`tar -xvf ${platformConfig.filename}`, { stdio: 'inherit' });\n \n logger.success('Simulator installation completed successfully');\n } catch (error) {\n logger.error('Error installing simulator:', error);\n throw new Error(`Failed to install simulator: ${error}`);\n }\n}\n\n/**\n * Run the simulator\n * @param options Configuration options for running the simulator\n * @returns A child process representing the running simulator\n */\nexport async function runSimulator(options: {\n background?: boolean;\n logToFile?: boolean;\n logFilePath?: string;\n} = {}): Promise<ReturnType<typeof spawn>> {\n try {\n const platform = getPlatform();\n const platformConfig = SIMULATOR_CONFIG.platforms[platform];\n const extractedFolderPath = path.join(\n SIMULATOR_CONFIG.installDir,\n platformConfig.extractedFolder\n );\n \n // Change to the extracted folder directory\n process.chdir(extractedFolderPath);\n \n // Start the simulator\n const executableName = platform === 'win32' ? 'tappd-simulator.exe' : './tappd-simulator';\n \n // Default options\n const runOptions = {\n background: options.background ?? true,\n logToFile: options.logToFile ?? true,\n logFilePath: options.logFilePath ?? SIMULATOR_CONFIG.defaultLogPath\n };\n \n // Create log directory if it doesn't exist\n if (runOptions.logToFile) {\n const logDir = path.dirname(runOptions.logFilePath);\n if (!fs.existsSync(logDir)) {\n fs.mkdirSync(logDir, { recursive: true });\n }\n logger.info(`Simulator logs will be written to: ${runOptions.logFilePath}`);\n }\n \n logger.info(`Starting simulator with: ${executableName} -l ${platformConfig.socketArg}`);\n \n // Configure stdio based on logging preferences\n let stdio: StdioOptions = 'inherit';\n let outputStream: fs.WriteStream = null;\n \n if (runOptions.logToFile) {\n // Create/open the log file for appending\n outputStream = fs.createWriteStream(runOptions.logFilePath, { flags: 'a' });\n \n // Use the stream for both stdout and stderr\n stdio = ['ignore', outputStream, outputStream];\n }\n \n // Run the simulator\n const simulatorProcess = spawn(executableName, ['-l', platformConfig.socketArg], {\n stdio,\n shell: platform === 'win32', // Use shell on Windows\n detached: runOptions.background // Detach process when running in background\n });\n \n // Write startup entry to log file with timestamp\n if (outputStream) {\n const timestamp = new Date().toISOString();\n outputStream.write(`\\n[${timestamp}] Simulator started\\n`);\n }\n \n // If running in background, unref to allow the parent process to exit\n if (runOptions.background) {\n simulatorProcess.unref();\n logger.success('Simulator is running in the background');\n }\n \n await setSimulatorEndpointEnv();\n return simulatorProcess;\n } catch (error) {\n logger.error('Error running simulator:', error);\n throw new Error(`Failed to run simulator: ${error}`);\n }\n}\n\n/**\n * Ensures the simulator is installed and running\n * @param options Configuration options for running the simulator\n * @returns A promise that resolves to a child process representing the running simulator\n */\nexport async function ensureSimulatorRunning(options: {\n background?: boolean;\n logToFile?: boolean;\n logFilePath?: string;\n} = {}): Promise<ReturnType<typeof spawn>> {\n if (!isSimulatorInstalled()) {\n logger.info('Simulator not installed. Installing now...');\n await installSimulator((message) => logger.info(`Installation progress: ${message}`));\n }\n \n if (await isSimulatorRunning()) {\n logger.info('Simulator is already running');\n return null;\n }\n \n logger.info('Starting simulator...');\n return await runSimulator(options);\n}\n\n/**\n * Check if the simulator is currently running\n * For Unix platforms (Darwin/Linux), checks if the Unix socket exists and is accessible\n * For Windows, tries to connect to the TCP port the simulator should be listening on\n * @returns Promise<boolean> indicating if the simulator is running\n */\nexport async function isSimulatorRunning(): Promise<boolean> {\n try {\n const platform = getPlatform();\n const platformConfig = SIMULATOR_CONFIG.platforms[platform];\n \n if (platform === 'darwin' || platform === 'linux') {\n // For Unix platforms, check if the socket file exists and is accessible\n const socketPath = '/tmp/tappd.sock';\n \n // Check if the socket file exists\n if (!fs.existsSync(socketPath)) {\n return false;\n }\n \n // Try to connect to the socket to verify it's active\n return new Promise<boolean>((resolve) => {\n const client = net.createConnection({ path: socketPath })\n .on('connect', () => {\n client.end();\n resolve(true);\n })\n .on('error', () => {\n resolve(false);\n });\n \n // Set timeout to avoid hanging if socket exists but nothing is listening\n setTimeout(() => {\n client.end();\n resolve(false);\n }, 1000);\n });\n } \n if (platform === 'win32') {\n // For Windows, try to connect to the TCP port\n const host = '127.0.0.1';\n const port = 8090;\n \n return new Promise<boolean>((resolve) => {\n const client = net.createConnection({ host, port })\n .on('connect', () => {\n client.end();\n resolve(true);\n })\n .on('error', () => {\n resolve(false);\n });\n \n // Set timeout to avoid hanging\n setTimeout(() => {\n client.end();\n resolve(false);\n }, 1000);\n });\n }\n \n return false;\n } catch (error) {\n logger.error('Error checking if simulator is running:', error);\n return false;\n }\n}\n\n/**\n * Stops the simulator if it's running\n * @returns Promise<boolean> indicating if the simulator was successfully stopped\n */\nexport async function stopSimulator(): Promise<boolean> {\n try {\n const platform = getPlatform();\n \n if (!await isSimulatorRunning()) {\n logger.info('Simulator is not running');\n return true;\n }\n \n logger.info('Stopping simulator...');\n \n if (platform === 'win32') {\n // For Windows, find the process listening on port 8080 and kill it\n execSync('for /f \"tokens=5\" %a in (\\'netstat -ano ^| findstr :8080\\') do taskkill /F /PID %a', { stdio: 'inherit' });\n } else {\n // For Unix platforms, find and kill the tappd-simulator process\n execSync('pkill -f tappd-simulator', { stdio: 'inherit' });\n }\n \n // Verify the simulator has stopped\n const stopped = !(await isSimulatorRunning());\n if (stopped) {\n logger.success('Simulator stopped successfully');\n } else {\n logger.error('Failed to stop simulator');\n }\n \n await deleteSimulatorEndpointEnv();\n return stopped;\n } catch (error) {\n logger.error('Error stopping simulator:', error);\n return false;\n }\n}\n\n/**\n * Gets the path to the simulator log file\n * @param customPath Optional custom log file path\n * @returns The path to the log file\n */\nexport function getSimulatorLogPath(customPath?: string): string {\n return customPath ?? SIMULATOR_CONFIG.defaultLogPath;\n}\n\n/**\n * Reads the recent logs from the simulator log file\n * @param options Options for reading logs\n * @returns Recent log content or null if log file doesn't exist\n */\nexport function getSimulatorLogs(options: {\n logFilePath?: string;\n maxLines?: number;\n} = {}): string | null {\n const logFilePath = options.logFilePath ?? SIMULATOR_CONFIG.defaultLogPath;\n const maxLines = options.maxLines ?? 100;\n \n try {\n if (!fs.existsSync(logFilePath)) {\n return null;\n }\n \n // Read the log file\n const logContent = fs.readFileSync(logFilePath, 'utf8');\n \n // Split by lines and get the most recent ones\n const lines = logContent.split('\\n');\n return lines.slice(-maxLines).join('\\n');\n } catch (error) {\n logger.error('Error reading simulator logs:', error);\n return null;\n }\n}\n\n/**\n * Gets the simulator endpoint URL based on the current platform\n * @returns The endpoint URL for the simulator\n */\nexport function getSimulatorEndpoint(): string {\n const platform = getPlatform();\n \n if (platform === 'win32') {\n return 'http://127.0.0.1:8090';\n }\n\n return 'unix:///tmp/tappd.sock';\n}\n\n/**\n * Sets the DSTACK_SIMULATOR_ENDPOINT environment variable based on the current platform\n * @param options Configuration options for setting the environment variable\n * @returns The endpoint URL that was set\n */\nexport async function setSimulatorEndpointEnv(endpoint?: string): Promise<string> {\n try {\n const simulatorEndpoint = getSimulatorEndpoint();\n // Set for the current Node.js process\n const envEndpoint = (endpoint) ? endpoint : simulatorEndpoint;\n await execSync(`export DSTACK_SIMULATOR_ENDPOINT=${envEndpoint}`);\n logger.success(`Setting DSTACK_SIMULATOR_ENDPOINT=${envEndpoint} for current process`);\n \n return endpoint;\n } catch (error) {\n logger.error('Error setting simulator endpoint environment variable:', error);\n throw new Error(`Failed to set simulator endpoint: ${error}`);\n }\n}\n\n/**\n * Deletes the DSTACK_SIMULATOR_ENDPOINT environment variable\n * @returns boolean indicating if deletion was successful\n */\nexport async function deleteSimulatorEndpointEnv(): Promise<boolean> {\n await execSync('unset DSTACK_SIMULATOR_ENDPOINT');\n logger.debug('Deleted DSTACK_SIMULATOR_ENDPOINT from current process');\n return true;\n}\n","import { Command } from 'commander';\nimport { DockerService } from '@/src/utils/docker';\nimport { getDockerCredentials } from '@/src/utils/credentials';\nimport { logger } from '@/src/utils/logger';\nimport path from 'node:path';\nimport inquirer from 'inquirer';\nimport fs from 'node:fs';\nimport { promptForFile } from '@/src/utils/prompts';\n\nexport const buildCommand = new Command()\n .name('build')\n .description('Build a Docker image')\n .option('-i, --image <image>', 'Image name')\n .option('-t, --tag <tag>', 'Image tag')\n .option('-f, --file <file>', 'Path to Dockerfile', 'Dockerfile')\n .action(async (options) => {\n try {\n // Get Docker credentials\n const credentials = await getDockerCredentials();\n \n if (!credentials) {\n logger.error('Docker information not found. Please login first with \"phala docker login\"');\n process.exit(1);\n }\n \n // Prompt for image name if not provided\n if (!options.image) {\n const response = await inquirer.prompt([\n {\n type: 'input',\n name: 'image',\n message: 'Enter the Docker image name:',\n validate: (input) => {\n if (!input.trim()) {\n return 'Image name is required';\n }\n return true;\n }\n }\n ]);\n \n options.image = response.image;\n }\n\n if (!options.tag) {\n const response = await inquirer.prompt([\n {\n type: 'input',\n name: 'tag',\n message: 'Enter the Docker image tag:',\n default: 'latest', // Add random hash later\n validate: (input) => {\n if (!input.trim()) {\n return 'Tag is required';\n }\n return true;\n }\n }\n ]);\n\n options.tag = response.tag;\n }\n\n // Prompt for Dockerfile path if the default doesn't exist\n const defaultPath = path.resolve(process.cwd(), options.file);\n if (!fs.existsSync(defaultPath)) {\n logger.info(`Default Dockerfile not found at ${defaultPath}`);\n \n options.file = await promptForFile(\n 'Enter the path to your Dockerfile:',\n 'Dockerfile',\n 'file'\n );\n }\n \n // Resolve the Dockerfile path\n const dockerfilePath = path.resolve(process.cwd(), options.file);\n \n // Build the image\n const dockerService = new DockerService(options.image, credentials.username, credentials.registry);\n const success = await dockerService.buildImage(dockerfilePath, options.tag);\n \n if (!success) {\n logger.error('Failed to build Docker image');\n process.exit(1);\n }\n \n logger.success(`Docker image ${credentials.username}/${options.image}:${options.tag} built successfully`);\n } catch (error) {\n logger.error(`Failed to build Docker image: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { DockerService } from '@/src/utils/docker';\nimport { getDockerCredentials } from '@/src/utils/credentials';\nimport { logger } from '@/src/utils/logger';\nimport inquirer from 'inquirer';\n\nexport const pushCommand = new Command()\n .name('push')\n .description('Push a Docker image to Docker Hub')\n .option('-i, --image <image>', 'Full image name (e.g. username/image:tag)')\n .action(async (options) => {\n try {\n // Get Docker credentials\n const credentials = await getDockerCredentials();\n \n if (!credentials) {\n logger.error('Docker information not found. Please login first with \"phala docker login\"');\n process.exit(1);\n }\n\n let imageName = options.image;\n\n // If image name is not provided, list local images and prompt user to select\n if (!imageName) {\n const localImages = await DockerService.listLocalImages();\n \n if (localImages.length === 0) {\n logger.error('No local Docker images found. Please build an image first with \"phala docker build\"');\n process.exit(1);\n }\n\n // If no image specified, prompt to select from available images\n if (!imageName) {\n // Get unique image names\n const uniqueImageNames = Array.from(new Set(localImages.map(img => img.imageName)));\n \n const { selectedImage } = await inquirer.prompt([\n {\n type: 'list',\n name: 'selectedImage',\n message: 'Select an image to push:',\n choices: uniqueImageNames\n }\n ]);\n \n imageName = selectedImage;\n }\n }\n \n // Push the image\n const dockerService = new DockerService('', credentials.username, credentials.registry);\n const success = await dockerService.pushImage(imageName);\n \n if (!success) {\n logger.error('Failed to push Docker image');\n process.exit(1);\n }\n \n logger.success(`Docker image ${imageName} pushed successfully`);\n } catch (error) {\n logger.error(`Failed to push Docker image: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { DockerService } from '@/src/utils/docker';\nimport { getDockerCredentials } from '@/src/utils/credentials';\nimport { logger } from '@/src/utils/logger';\nimport inquirer from 'inquirer';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { validateFileExists } from '@/src/utils/prompts';\n\nexport const generateCommand = new Command()\n .name('generate')\n .description('Generate a Docker Compose file')\n .option('-i, --image <imageName>', 'Docker image name to use in the compose file (e.g. phala/phala-cloud)')\n .option('-e, --env-file <envFile>', 'Path to environment variables file')\n .option('-o, --output <output>', 'Output path for generated docker-compose.yml')\n .option('--template <template>', 'Template to use for the generated docker-compose.yml', )\n .action(async (options) => {\n try {\n // Get Docker credentials to create the Docker service\n const credentials = await getDockerCredentials();\n if (!credentials || !credentials.username) {\n logger.error('Docker Hub username not found. Please login first with `phala docker login`');\n process.exit(1);\n }\n\n let imageName = options.image;\n\n if (!imageName) {\n // If image name is not provided, list local images and prompt user to select\n const localImages = await DockerService.listLocalImages();\n\n if (localImages.length === 0) {\n logger.error(\n 'No local Docker images found. Please build an image first with \"phala docker build\"',\n );\n process.exit(1);\n }\n\n // If no image specified, prompt to select from available images\n if (!imageName) {\n // Get unique image names\n const uniqueImageNames = Array.from(\n new Set(localImages.map((img) => img.imageName)),\n );\n\n const { selectedImage } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"selectedImage\",\n message: \"Select an image to use in the compose file:\",\n choices: uniqueImageNames,\n },\n ]);\n\n imageName = selectedImage;\n }\n }\n \n // Get environment file path from options or prompt\n let envFilePath = options.envFile;\n if (!envFilePath) {\n // Check if .env exists in current directory\n const defaultEnvPath = path.join(process.cwd(), '.env');\n const hasDefaultEnv = fs.existsSync(defaultEnvPath);\n\n if (hasDefaultEnv) {\n const { useDefault } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'useDefault',\n message: 'Use .env file in current directory?',\n default: true\n }\n ]);\n\n if (useDefault) {\n envFilePath = defaultEnvPath;\n }\n }\n\n // If still no env file path, prompt for it\n if (!envFilePath) {\n const { envPath } = await inquirer.prompt([\n {\n type: 'input',\n name: 'envPath',\n message: 'Enter path to environment variables file:',\n validate: (input) => {\n try {\n validateFileExists(input);\n return true;\n } catch (error) {\n return `File not found: ${input}`;\n }\n }\n }\n ]);\n envFilePath = envPath;\n }\n } else {\n // Validate the provided env file path\n try {\n validateFileExists(envFilePath);\n } catch (error) {\n logger.error(`File not found: ${envFilePath}`);\n process.exit(1);\n }\n }\n\n // Get output path from options or set default\n let outputPath = options.output;\n if (!outputPath) {\n outputPath = path.join(process.cwd(), 'docker-compose.yml');\n \n // If file already exists, confirm overwrite\n if (fs.existsSync(outputPath)) {\n const { confirmOverwrite } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirmOverwrite',\n message: `File ${outputPath} already exists. Overwrite?`,\n default: false\n }\n ]);\n if (!confirmOverwrite) {\n const { customPath } = await inquirer.prompt([\n {\n type: 'input',\n name: 'customPath',\n message: 'Enter alternative output path:',\n default: path.join(process.cwd(), 'docker-generated-compose.yml')\n }\n ]);\n outputPath = customPath;\n }\n }\n }\n \n // Create a DockerService instance\n const dockerService = new DockerService('', credentials.username, credentials.registry);\n\n // Generate the Docker Compose file\n if (envFilePath) {\n logger.info(`Generating Docker Compose file for ${imageName} using env file: ${envFilePath}`);\n } else {\n logger.info(`Generating Docker Compose file for ${imageName} without env file`);\n }\n const composePath = await dockerService.buildComposeFile(imageName, envFilePath, options.template);\n \n // Copy the generated file to the output path if needed\n if (composePath !== outputPath) {\n // Ensure the output directory exists\n const outputDir = path.dirname(outputPath);\n if (!fs.existsSync(outputDir)) {\n logger.info(`Creating directory: ${outputDir}`);\n fs.mkdirSync(outputDir, { recursive: true });\n }\n \n fs.copyFileSync(composePath, outputPath);\n }\n \n logger.success(`Docker Compose file generated successfully: ${outputPath}`);\n } catch (error) {\n logger.error(`Failed to generate Docker Compose file: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { startCommand } from './start';\nimport { stopCommand } from './stop';\n\nexport const simulatorCommands = new Command()\n .name('simulator')\n .description('TEE simulator commands')\n .addCommand(startCommand)\n .addCommand(stopCommand);\n","import { Command } from 'commander';\nimport { DockerService } from '@/src/utils/docker';\nimport { logger } from '@/src/utils/logger';\nimport { TEE_SIMULATOR } from '@/src/utils/constants';\nimport { installSimulator, isSimulatorInstalled, isSimulatorRunning, runSimulator } from '@/src/utils/simulator';\n\nexport const startCommand = new Command()\n .name('start')\n .description('Start the TEE simulator')\n .option('-i, --image <image>', 'Simulator image', TEE_SIMULATOR)\n .option('-p, --port <port>', 'Simulator port (default: 8090)', '8090')\n .option('-t, --type <type>', 'Simulator type (docker, native)', 'docker')\n .action(async (options) => {\n try {\n if (options.type === 'docker') {\n // Start the simulator\n const dockerService = new DockerService('');\n const success = await dockerService.runSimulator(options.image, options.port);\n \n if (!success) {\n logger.error('Failed to start TEE simulator');\n process.exit(1);\n }\n } else if (options.type === 'native') {\n if (!isSimulatorInstalled()) {\n await installSimulator();\n }\n const running = await isSimulatorRunning();\n if (running) {\n logger.success('TEE simulator is already running');\n return;\n } else {\n const simulatorProcess = runSimulator();\n logger.success('TEE simulator started successfully');\n }\n } else {\n logger.error('Invalid simulator type');\n process.exit(1);\n }\n } catch (error) {\n logger.error(`Failed to start TEE simulator: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { DockerService } from '../../utils/docker';\nimport { logger } from '../../utils/logger';\nimport { stopSimulator } from '@/src/utils/simulator';\n\nexport const stopCommand = new Command()\n .name('stop')\n .description('Stop the TEE simulator')\n .option('-t, --type <type>', 'Simulator type (docker, native)', 'docker')\n .action(async (options) => {\n try {\n if (options.type === 'docker') {\n // Stop the simulator\n const dockerService = new DockerService('');\n const success = await dockerService.stopSimulator();\n\n if (!success) {\n logger.error('Failed to stop TEE simulator');\n process.exit(1);\n }\n } else if (options.type === 'native') {\n // Stop the native simulator\n const success = await stopSimulator();\n \n if (!success) {\n logger.error('Failed to stop TEE simulator');\n process.exit(1);\n }\n } else {\n logger.error('Invalid simulator type');\n process.exit(1);\n }\n } catch (error) {\n logger.error(`Failed to stop TEE simulator: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n });","import { Command } from 'commander';\nimport { listCommand } from './list';\nimport { getCommand } from './get';\nimport { startCommand } from './start';\nimport { stopCommand } from './stop';\nimport { restartCommand } from './restart';\nimport { attestationCommand } from './attestation';\nimport { createCommand } from './create';\nimport { deleteCommand } from './delete';\nimport { upgradeCommand } from './upgrade';\nimport { resizeCommand } from './resize';\nimport { listNodesCommand } from './list-node';\nimport { replicateCommand } from './replicate';\n\nexport const cvmsCommand = new Command()\n .name('cvms')\n .description('Manage Phala Confidential Virtual Machines (CVMs)')\n .addCommand(attestationCommand)\n .addCommand(createCommand)\n .addCommand(deleteCommand)\n .addCommand(getCommand)\n .addCommand(listCommand)\n .addCommand(startCommand)\n .addCommand(stopCommand)\n .addCommand(resizeCommand)\n .addCommand(restartCommand)\n .addCommand(upgradeCommand)\n .addCommand(listNodesCommand)\n .addCommand(replicateCommand);\n ","import { Command } from 'commander';\nimport { getCvms } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { CLOUD_URL } from '@/src/utils/constants';\nimport chalk from 'chalk';\n\nexport const listCommand = new Command()\n .name('list')\n .alias('ls')\n .description('List all CVMs')\n .option('-j, --json', 'Output in JSON format')\n .action(async (options) => {\n try {\n const spinner = logger.startSpinner('Fetching CVMs');\n \n const cvms = await getCvms();\n \n spinner.stop(true);\n \n if (!cvms || cvms.length === 0) {\n logger.info('No CVMs found');\n return;\n }\n \n if (options.json) {\n console.log(JSON.stringify(cvms, null, 2));\n return;\n }\n \n for (const cvm of cvms) {\n logger.keyValueTable({\n Name: cvm.name,\n \"App ID\": `app_${cvm.hosted.app_id}`,\n \"CVM ID\": cvm.hosted.id.replace(/-/g, ''),\n \"Region\": cvm.node.region_identifier,\n Status:\n cvm.status === \"running\"\n ? chalk.green(cvm.status)\n : cvm.status === \"stopped\"\n ? chalk.red(cvm.status)\n : chalk.yellow(cvm.status),\n \"Node Info URL\": cvm.hosted.app_url,\n \"App URL\": `${CLOUD_URL}/dashboard/cvms/${cvm.hosted.id.replace(/-/g, '')}`,\n });\n logger.break();\n }\n logger.success(`Found ${cvms.length} CVMs`);\n logger.break();\n logger.info(`Go to ${CLOUD_URL}/dashboard/ to view your CVMs`);\n } catch (error) {\n logger.error(`Failed to list CVMs: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { checkCvmExists, getCvmByAppId, getCvms, selectCvm } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { CLOUD_URL } from '@/src/utils/constants';\nimport chalk from 'chalk';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\n\nexport const getCommand = new Command()\n .name('get')\n .description('Get details of a CVM')\n .argument('[app-id]', 'App ID of the CVM (optional)')\n .option('-j, --json', 'Output in JSON format')\n .action(async (appId, options) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n \n const spinner = logger.startSpinner(`Fetching CVM with App ID app_${resolvedAppId}`);\n \n const cvm = await getCvmByAppId(resolvedAppId);\n \n spinner.stop(true);\n logger.break();\n \n if (!cvm) {\n logger.error(`CVM with App ID app_${resolvedAppId} not found`);\n process.exit(1);\n }\n \n if (options.json) {\n console.log(JSON.stringify(cvm, null, 2));\n return;\n }\n \n // Display additional details if available\n logger.keyValueTable({\n 'Name': cvm.name,\n 'App ID': `app_${cvm.app_id}`,\n 'Status': (cvm.status === 'running') ? chalk.green(cvm.status) : (cvm.status === 'stopped') ? chalk.red(cvm.status) : chalk.yellow(cvm.status),\n 'vCPU': cvm.vcpu,\n 'Memory': `${cvm.memory} MB`,\n 'Disk Size': `${cvm.disk_size} GB`,\n 'Dstack Image': cvm.base_image,\n 'App URL': `${CLOUD_URL}/dashboard/cvms/app_${cvm.app_id}`\n });\n } catch (error) {\n logger.error(`Failed to get CVM details: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { selectCvm, checkCvmExists } from \"@/src/api/cvms\";\nimport { logger } from \"./logger\";\n\n/**\n * Resolves a CVM App ID either by prompting the user to select one if none is provided,\n * or by validating the provided App ID exists.\n *\n * @param appId Optional App ID to resolve\n * @returns The resolved App ID or undefined if none was selected/found\n */\nexport async function resolveCvmAppId(\n\tappId?: string,\n): Promise<string | undefined> {\n\tif (!appId) {\n\t\t// If no app ID is provided, prompt user to select one\n\t\tconst selectedCvm = await selectCvm();\n\t\tif (!selectedCvm) {\n\t\t\treturn undefined; // No CVMs found or user canceled\n\t\t}\n\t\treturn selectedCvm;\n\t}\n\t// Verify the provided App ID exists\n\treturn await checkCvmExists(appId);\n}","import { Command } from 'commander';\nimport { startCvm, selectCvm, checkCvmExists } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nexport const startCommand = new Command()\n .name('start')\n .description('Start a stopped CVM')\n .argument('[app-id]', 'App ID of the CVM (if not provided, a selection prompt will appear)')\n .action(async (appId) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n \n const spinner = logger.startSpinner(`Starting CVM with App ID app_${resolvedAppId}`);\n \n const response = await startCvm(resolvedAppId);\n \n spinner.stop(true);\n logger.break();\n \n const tableData = {\n 'CVM ID': response.id,\n 'Name': response.name,\n 'Status': response.status,\n 'App ID': `app_${response.app_id}`,\n };\n logger.keyValueTable(tableData, {\n borderStyle: 'rounded'\n });\n \n logger.break();\n logger.success(\n `Your CVM is being started. You can check the dashboard for more details:\\n${CLOUD_URL}/dashboard/cvms/app_${response.app_id}`);\n } catch (error) {\n logger.error(`Failed to start CVM: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { stopCvm, selectCvm, checkCvmExists } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nexport const stopCommand = new Command()\n .name('stop')\n .description('Stop a running CVM')\n .argument('[app-id]', 'App ID of the CVM (if not provided, a selection prompt will appear)')\n .action(async (appId) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n\n const spinner = logger.startSpinner(\n `Stopping CVM with App ID app_${resolvedAppId}`,\n );\n\n const response = await stopCvm(resolvedAppId);\n\n spinner.stop(true);\n logger.break();\n\n const tableData = {\n 'CVM ID': response.id,\n 'Name': response.name,\n 'Status': response.status,\n 'App ID': `app_${response.app_id}`,\n };\n logger.keyValueTable(tableData, {\n borderStyle: 'rounded'\n });\n\n logger.break();\n logger.success(\n `Your CVM is being stopped. You can check the dashboard for more details:\\n${CLOUD_URL}/dashboard/cvms/app_${response.app_id}`);\n \n } catch (error) {\n logger.error(`Failed to stop CVM: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { checkCvmExists, restartCvm, selectCvm } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nexport const restartCommand = new Command()\n .name('restart')\n .description('Restart a CVM')\n .argument('[app-id]', 'App ID of the CVM (if not provided, a selection prompt will appear)')\n .action(async (appId) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n\n const spinner = logger.startSpinner(\n `Restarting CVM with App ID app_${resolvedAppId}`,\n );\n\n const response = await restartCvm(resolvedAppId);\n\n spinner.stop(true);\n logger.break();\n\n const tableData = {\n 'CVM ID': response.id,\n 'Name': response.name,\n 'Status': response.status,\n 'App ID': `app_${response.app_id}`,\n 'App URL': response.app_url\n ? response.app_url\n : `${CLOUD_URL}/dashboard/cvms/app_${response.app_id}`,\n };\n logger.keyValueTable(tableData, {\n borderStyle: \"rounded\",\n });\n\n logger.break();\n logger.success(\n `Your CVM is being restarted. You can check the dashboard for more details:\\n${CLOUD_URL}/dashboard/cvms/app_${response.app_id}`);\n } catch (error) {\n logger.error(`Failed to restart CVM: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { checkCvmExists, getCvmAttestation, selectCvm } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport chalk from 'chalk';\nimport type { CvmAttestationResponse } from '@/src/api/types';\n\nexport const attestationCommand = new Command()\n .name('attestation')\n .description('Get attestation information for a CVM')\n .argument('[app-id]', 'CVM app ID (will prompt for selection if not provided)')\n .option('-j, --json', 'Output in JSON format')\n .action(async (appId?: string, options?: { json?: boolean }) => {\n try {\n let resolvedAppId: string;\n \n if (!appId) {\n logger.info('No CVM specified, fetching available CVMs...');\n const selectedCvm = await selectCvm();\n if (!selectedCvm) {\n return;\n }\n resolvedAppId = selectedCvm;\n } else {\n resolvedAppId = await checkCvmExists(appId);\n }\n\n const spinner = logger.startSpinner(`Fetching attestation information for CVM app_${resolvedAppId}...`);\n\n try {\n const attestationData: CvmAttestationResponse = await getCvmAttestation(resolvedAppId);\n spinner.stop(true);\n\n if (!attestationData || Object.keys(attestationData).length === 0) {\n logger.info('No attestation information found');\n return;\n }\n\n // If JSON output is requested, just print the raw response\n if (options?.json) {\n logger.info(JSON.stringify(attestationData, null, 2));\n return;\n }\n\n // Display the attestation summary\n logger.success('Attestation Summary:');\n const summaryData = {\n 'Status': attestationData.is_online ? chalk.green('Online') : chalk.red('Offline'),\n 'Public Access': attestationData.is_public ? chalk.green('Enabled') : chalk.yellow('Disabled'),\n 'Error': attestationData.error || 'None',\n 'Certificates': `${attestationData.app_certificates?.length || 0} found`\n };\n \n logger.keyValueTable(summaryData, {\n borderStyle: 'rounded'\n });\n\n // Display certificate information\n if (attestationData.app_certificates && attestationData.app_certificates.length > 0) {\n \n attestationData.app_certificates.forEach((cert, index) => {\n logger.break();\n logger.success(`Certificate #${index + 1} (${cert.position_in_chain === 0 ? 'End Entity' : 'CA'}):`);\n \n const certData = {\n 'Subject': `${cert.subject.common_name || 'Unknown'}${cert.subject.organization ? ` (${cert.subject.organization})` : ''}`,\n 'Issuer': `${cert.issuer.common_name || 'Unknown'}${cert.issuer.organization ? ` (${cert.issuer.organization})` : ''}`,\n 'Serial Number': cert.serial_number,\n 'Validity': `${new Date(cert.not_before).toLocaleString()} to ${new Date(cert.not_after).toLocaleString()}`,\n 'Fingerprint': cert.fingerprint,\n 'Signature Algorithm': cert.signature_algorithm,\n 'Is CA': cert.is_ca ? 'Yes' : 'No',\n 'Position in Chain': cert.position_in_chain\n };\n \n logger.keyValueTable(certData, {\n borderStyle: 'rounded'\n });\n \n // Skip displaying the quote as it's very large and mostly binary data\n });\n }\n\n // Display TCB info if available\n if (attestationData.tcb_info) {\n logger.break();\n logger.success('Trusted Computing Base (TCB) Information:');\n \n // Create a formatted version of the TCB info without the event log\n const tcbBasicInfo = {\n 'Mrtd': attestationData.tcb_info.mrtd,\n 'Rootfs Hash': attestationData.tcb_info.rootfs_hash,\n 'Rtmr0': attestationData.tcb_info.rtmr0,\n 'Rtmr1': attestationData.tcb_info.rtmr1,\n 'Rtmr2': attestationData.tcb_info.rtmr2,\n 'Rtmr3': attestationData.tcb_info.rtmr3,\n 'Event Log Entries': `${attestationData.tcb_info.event_log.length} entries`\n };\n \n // Display basic TCB info\n logger.keyValueTable(tcbBasicInfo, {\n borderStyle: 'rounded'\n });\n \n // Display event log entries separately if they exist\n if (attestationData.tcb_info.event_log && attestationData.tcb_info.event_log.length > 0) {\n logger.break();\n logger.success('Event Log (Showing entries to reproduce RTMR3):');\n \n // Show the first 5 entries\n const maxEntriesToShow = 5;\n const entries = attestationData.tcb_info.event_log\n .filter(entry => entry.event !== null && entry.event !== \"\")\n .map((entry) => ({\n 'Event': entry.event,\n 'IMR': entry.imr.toString(),\n 'Event Type': entry.event_type.toString(),\n 'Payload': entry.event_payload,\n }));\n \n // Display entries in a table format\n logger.table(entries, [\n { key: \"Event\", header: \"Event\", minWidth: 8 },\n { key: \"IMR\", header: \"IMR\", minWidth: 3 },\n { key: \"Event Type\", header: \"Type\", minWidth: 8 },\n { key: \"Payload\", header: \"Payload\", minWidth: 25 },\n ]);\n \n if (attestationData.tcb_info.event_log.length > maxEntriesToShow) {\n logger.info('To see all full attestation data, use --json');\n }\n logger.break();\n logger.success('To reproduce RTMR3, use the tool at https://rtmr3-calculator.vercel.app/');\n }\n }\n } catch (error) {\n spinner.stop(false);\n throw error;\n }\n } catch (error) {\n logger.error(`Failed to get attestation information: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n","import { Command } from 'commander';\nimport { createCvm, getPubkeyFromCvm } from '@/src/api/cvms';\nimport { getTeepods } from '@/src/api/teepods';\nimport { logger } from '@/src/utils/logger';\nimport type { TEEPod, Image } from '@/src/api/types';\nimport { DEFAULT_VCPU, DEFAULT_MEMORY, DEFAULT_DISK_SIZE, CLOUD_URL, DEFAULT_IMAGE } from '@/src/utils/constants';\nimport { encryptEnvVars } from '@phala/dstack-sdk/encrypt-env-vars';\nimport type { EnvVar } from '@phala/dstack-sdk/encrypt-env-vars';\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport inquirer from 'inquirer';\nimport { parseEnv } from '@/src/utils/secrets';\nimport { detectFileInCurrentDir, promptForFile } from '@/src/utils/prompts';\nimport { deleteSimulatorEndpointEnv } from '@/src/utils/simulator';\n\nexport const createCommand = new Command()\n .name('create')\n .description('Create a new CVM')\n .option('-n, --name <name>', 'Name of the CVM')\n .option('-c, --compose <compose>', 'Path to Docker Compose file')\n .option('--vcpu <vcpu>', `Number of vCPUs, default is ${DEFAULT_VCPU}`)\n .option('--memory <memory>', `Memory in MB, default is ${DEFAULT_MEMORY}`)\n .option('--disk-size <diskSize>', `Disk size in GB, default is ${DEFAULT_DISK_SIZE}`)\n .option('--teepod-id <teepodId>', 'TEEPod ID to use. If not provided, it will be selected from the list of available TEEPods.')\n .option('--image <image>', 'Version of dstack image to use. If not provided, it will be selected from the list of available images for the selected TEEPod.')\n .option('-e, --env-file <envFile>', 'Path to environment file')\n .option('--skip-env', 'Skip environment variable prompt', false)\n .option('--debug', 'Enable debug mode', false)\n .action(async (options) => {\n try {\n // Prompt for required options if not provided\n if (!options.name) {\n const { name } = await inquirer.prompt([\n {\n type: 'input',\n name: 'name',\n message: 'Enter a name for the CVM:',\n validate: (input) => {\n if (!input.trim()) {\n return 'CVM name is required';\n }\n if (input.trim().length > 20) {\n return 'CVM name must be less than 20 characters';\n } \n if (input.trim().length < 3) {\n return 'CVM name must be at least 3 characters';\n } \n if (!/^[a-zA-Z0-9_-]+$/.test(input)) {\n return 'CVM name must contain only letters, numbers, underscores, and hyphens';\n }\n return true;\n }\n }\n ]);\n options.name = name;\n }\n\n // If compose path not provided, prompt with examples\n if (!options.compose) {\n const possibleFiles = ['docker-compose.yml', 'docker-compose.yaml'];\n const composeFileName = detectFileInCurrentDir(possibleFiles, 'Detected docker compose file: {path}');\n\n options.compose = await promptForFile(\n 'Enter the path to your Docker Compose file:',\n composeFileName,\n 'file'\n );\n }\n\n const composePath = path.resolve(options.compose);\n if (!fs.existsSync(composePath)) {\n logger.error(`Docker Compose file not found: ${composePath}`);\n process.exit(1);\n }\n const composeString = fs.readFileSync(composePath, 'utf8');\n\n // Delete DSTACK_SIMULATOR_ENDPOINT environment variable\n await deleteSimulatorEndpointEnv();\n\n // Print if they are using a private registry\n if (process.env.DSTACK_DOCKER_USERNAME && process.env.DSTACK_DOCKER_PASSWORD) {\n logger.info(\"🔐 Using private DockerHub registry credentials...\");\n } else if (process.env.DSTACK_AWS_ACCESS_KEY_ID && process.env.DSTACK_AWS_SECRET_ACCESS_KEY && process.env.DSTACK_AWS_REGION && process.env.DSTACK_AWS_ECR_REGISTRY) {\n logger.info(`🔐 Using private AWS ECR registry: ${process.env.DSTACK_AWS_ECR_REGISTRY}`);\n } else {\n logger.info(\"🔐 Using public DockerHub registry...\");\n }\n\n // Process environment variables\n let envs: EnvVar[] = [];\n\n // Process environment variables from file\n if (options.envFile) {\n try {\n envs = parseEnv([], options.envFile);\n } catch (error) {\n logger.error(`Failed to read environment file: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n } else if (!options.skipEnv) {\n // Prompt to input env file or skip\n const { shouldSkip } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'shouldSkip',\n message: 'Do you want to skip environment variable prompt?',\n default: true\n }\n ]);\n \n if (shouldSkip) {\n logger.info('Skipping environment variable prompt');\n } else {\n const envVars = await promptForFile(\n 'Enter the path to your environment file:',\n '.env',\n 'file',\n );\n envs = parseEnv([], envVars);\n }\n }\n\n const vcpu = Number(options.vcpu) || DEFAULT_VCPU;\n const memory = Number(options.memory) || DEFAULT_MEMORY;\n const diskSize = Number(options.diskSize) || DEFAULT_DISK_SIZE;\n\n if (Number.isNaN(vcpu) || vcpu <= 0) {\n logger.error(`Invalid number of vCPUs: ${vcpu}`);\n process.exit(1);\n }\n\n if (Number.isNaN(memory) || memory <= 0) {\n logger.error(`Invalid memory: ${memory}`);\n process.exit(1);\n }\n\n if (Number.isNaN(diskSize) || diskSize <= 0) {\n logger.error(`Invalid disk size: ${diskSize}`);\n process.exit(1);\n }\n\n const teepodsSpinner = logger.startSpinner('Fetching available TEEPods');\n const teepods = await getTeepods();\n teepodsSpinner.stop(true);\n if (teepods.nodes.length === 0) {\n logger.error('No TEEPods available. Please try again later.');\n process.exit(1);\n }\n\n let selectedTeepod: TEEPod;\n // Fetch available TEEPods\n if (!options.teepodId) {\n selectedTeepod = teepods.nodes[0];\n if (!selectedTeepod) {\n logger.error('Failed to find default TEEPod');\n process.exit(1);\n }\n } else {\n selectedTeepod = teepods.nodes.find(pod => pod.teepod_id === Number(options.teepodId));\n if (!selectedTeepod) {\n logger.error('Failed to find selected TEEPod');\n process.exit(1);\n }\n }\n\n let selectedImage: Image;\n if (!options.image) {\n selectedImage = selectedTeepod.images?.find(image => image.name === DEFAULT_IMAGE);\n if (!selectedImage) {\n logger.error(`Failed to find default image ${DEFAULT_IMAGE}`);\n process.exit(1);\n }\n } else {\n selectedImage = selectedTeepod.images?.find(image => image.name === options.image);\n if (!selectedImage) {\n logger.error(`Failed to find selected image: ${options.image}`);\n process.exit(1);\n }\n }\n\n // Prepare VM configuration\n const vmConfig = {\n teepod_id: selectedTeepod.teepod_id,\n name: options.name,\n image: selectedImage.name,\n vcpu: vcpu,\n memory: memory,\n disk_size: diskSize,\n compose_manifest: {\n docker_compose_file: composeString,\n docker_config: {\n url: '',\n username: '',\n password: '',\n },\n features: ['kms', 'tproxy-net'],\n kms_enabled: true,\n manifest_version: 2,\n name: options.name,\n public_logs: true,\n public_sysinfo: true,\n tproxy_enabled: true,\n },\n listed: false,\n };\n\n // Get public key from CVM\n const spinner = logger.startSpinner('Getting public key from CVM');\n const pubkey = await getPubkeyFromCvm(vmConfig);\n spinner.stop(true);\n\n if (!pubkey) {\n logger.error('Failed to get public key from CVM');\n process.exit(1);\n }\n\n // Encrypt environment variables\n const encryptSpinner = logger.startSpinner('Encrypting environment variables');\n const encrypted_env = await encryptEnvVars(envs, pubkey.app_env_encrypt_pubkey);\n encryptSpinner.stop(true);\n\n if (options.debug) {\n logger.debug('Public key:', pubkey.app_env_encrypt_pubkey);\n logger.debug('Encrypted environment variables:', encrypted_env);\n logger.debug('Environment variables:', JSON.stringify(envs));\n }\n\n // Create the CVM\n const createSpinner = logger.startSpinner('Creating CVM');\n const response = await createCvm({\n ...vmConfig,\n encrypted_env,\n app_env_encrypt_pubkey: pubkey.app_env_encrypt_pubkey,\n app_id_salt: pubkey.app_id_salt,\n });\n createSpinner.stop(true);\n\n if (!response) {\n logger.error('Failed to create CVM');\n process.exit(1);\n }\n\n logger.success('CVM created successfully');\n logger.break();\n const tableData = {\n 'CVM ID': response.id,\n 'Name': response.name,\n 'Status': response.status,\n 'App ID': `app_${response.app_id}`,\n 'App URL': response.app_url ? response.app_url : `${CLOUD_URL}/dashboard/cvms/app_${response.app_id}`,\n };\n logger.keyValueTable(tableData, {\n borderStyle: 'rounded'\n });\n\n logger.info('');\n logger.success(`Your CVM is being created. You can check its status with:\\nphala cvms get app_${response.app_id}`);\n } catch (error) {\n logger.error(`Failed to create CVM: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import * as fs from 'node:fs';\nimport type { EnvVar } from '@phala/dstack-sdk/encrypt-env-vars';\n\nexport const parseEnv = (envs: string[], envFile: string): EnvVar[] => {\n const envVars: Record<string, string> = {};\n\n // Process environment variables passed directly\n if (envs) {\n for (const env of envs) {\n if (env.includes(\"=\")) {\n const [key, ...valueParts] = env.split(\"=\");\n const value = valueParts.join(\"=\"); // Handle cases where value might contain '='\n if (key) { // Allow empty value\n envVars[key] = value;\n }\n }\n }\n }\n\n if (envFile) {\n const envFileContent = fs.readFileSync(envFile, \"utf8\");\n for (const line of envFileContent.split(\"\\n\")) {\n // Skip empty lines\n if (!line.trim()) {\n continue;\n }\n\n // Skip comments\n if (line.trim().startsWith('#')) {\n continue;\n }\n\n // Find the first '=' that is not part of an inline comment\n let delimiterIndex = -1;\n let inQuotes = false;\n let quoteChar = '';\n\n for (let i = 0; i < line.length; i++) {\n if ((line[i] === '\"' || line[i] === \"'\" || line[i] === '`') && (i === 0 || line[i-1] !== '\\\\')) {\n if (inQuotes && line[i] === quoteChar) {\n inQuotes = false;\n quoteChar = '';\n } else if (!inQuotes) {\n inQuotes = true;\n quoteChar = line[i];\n }\n } else if (line[i] === '=' && !inQuotes) {\n delimiterIndex = i;\n break;\n } else if (line[i] === '#' && !inQuotes) {\n // If a comment starts before any '=', treat the whole line as a comment if no '=' found yet\n // Or, if '=' is found, this part is an inline comment.\n if (delimiterIndex === -1) { // No '=' encountered yet, so this is a full-line comment essentially or malformed\n // We already skip lines starting with #, this handles cases like \" #comment\"\n // or \"KEY #comment\" (which is not a valid assignment according to rules)\n // However, the rule \" # marks the beginning of a comment (unless when the value is wrapped in quotes)\"\n // implies that \"KEY=value #comment\" is valid.\n // The current logic handles inline comments on the value side later.\n // If # appears before =, it's either a full comment (handled) or part of the key (unusual, but let it pass to split)\n }\n break; // Stop processing at the comment marker for the key or if it's an inline comment for the value\n }\n }\n\n\n if (delimiterIndex === -1) {\n // Handles lines without '=' or lines that are effectively comments.\n if (!line.trim().startsWith('#')) {\n // It's not a comment line, but has no '='.\n // According to \"EMPTY= becomes {EMPTY: ''}\", lines like \"ONLYKEY\" are not defined.\n // So we can skip them or treat as an error. Skipping for now.\n }\n continue;\n }\n\n const key = line.substring(0, delimiterIndex).trim();\n let value = line.substring(delimiterIndex + 1);\n\n // Remove inline comments from the value part\n // A comment starts with ' #' (space followed by #)\n // unless the # is within quotes.\n let valueInQuotes = false;\n let valueQuoteChar = '';\n let commentStartIndex = -1;\n\n for (let i = 0; i < value.length; i++) {\n if ((value[i] === '\"' || value[i] === \"'\" || value[i] === '`') && (i === 0 || value[i-1] !== '\\\\')) {\n if (valueInQuotes && value[i] === valueQuoteChar) {\n valueInQuotes = false;\n valueQuoteChar = '';\n } else if (!valueInQuotes) {\n valueInQuotes = true;\n valueQuoteChar = value[i];\n }\n } else if (value[i] === '#' && !valueInQuotes && i > 0 && value[i-1] === ' ') {\n commentStartIndex = i -1; // Start of \" #\"\n break;\n } else if (value[i] === '#' && !valueInQuotes && i === 0) { // Value starts directly with #\n commentStartIndex = i;\n break;\n }\n }\n\n if (commentStartIndex !== -1) {\n value = value.substring(0, commentStartIndex);\n }\n\n\n // Handle empty values: EMPTY= becomes {EMPTY: ''}\n if (value === undefined) { // Should not happen if split correctly\n value = '';\n }\n\n\n // Trim whitespace for unquoted values, preserve for quoted\n const firstChar = value.charAt(0);\n const lastChar = value.charAt(value.length - 1);\n\n if ((firstChar === '\"' && lastChar === '\"') ||\n (firstChar === \"'\" && lastChar === \"'\") ||\n (firstChar === '`' && lastChar === '`')) {\n // Quoted value, remove the outer quotes\n value = value.substring(1, value.length - 1);\n\n // Expand newlines for double-quoted values\n if (firstChar === '\"') {\n value = value.replace(/\\\\\\\\n/g, '\\n');\n }\n // Unescape inner quotes for single and backtick quotes if they were escaped like \\\\' or \\\\`\n // The rules state \"inner quotes are maintained (think JSON)\"\n // and \"single and double quoted values are escaped\"\n // This implies that within a string like SINGLE_QUOTE='value with \\\\' quote'\n // the result should be \"value with ' quote\"\n // For JSON example: JSON={\"foo\": \"bar\"} becomes {JSON:\"{\\\"foo\\\": \\\"bar\\\"}\"}\n // This needs careful handling. The current approach of just slicing quotes might be too simple.\n // Let's assume the provided examples are the source of truth.\n // \"JSON={\"foo\": \"bar\"}\" -> JSON: \"{\\\"foo\\\": \\\"bar\\\"}\"\n // This means the quotes *around* the JSON are stripped, but the inner quotes *within* the JSON string literal itself are preserved.\n // The rule \"single and double quoted values are escaped (SINGLE_QUOTE='quoted' becomes {SINGLE_QUOTE: \"quoted\"})\"\n // seems to imply that the outer quotes are removed, and the content becomes a JS string.\n // The parsing engine should output a JS object, so values will be JS strings.\n // SINGLE_QUOTE='quoted' -> {SINGLE_QUOTE: 'quoted'} (JS string)\n // FOO=\" some value \" -> {FOO: ' some value '} (JS string)\n // JSON={\"foo\": \"bar\"} -> {JSON: '{\"foo\": \"bar\"}'} (JS string)\n // MULTILINE=\"new\\\\nline\" -> {MULTILINE: 'new\\\\nline'} (JS string with literal \\n)\n // The rule says: MULTILINE=\"new\\\\nline\" becomes {MULTILINE: 'new\\nline'} (with actual newline)\n // So, my previous .replace(/\\\\n/g, '\\n') for double quotes is correct.\n\n // For single quotes and backticks, the rules don't explicitly state escaped char handling other than `\\\\n` for double quotes.\n // \"inner quotes are maintained (think JSON)\" - this is key for JSON={\"foo\": \"bar\"}\n // Let's ensure that if a value is `'{\"key\": \"value\"}'`, it becomes `{\"key\": \"value\"}`.\n // The current `substring(1, value.length - 1)` does this.\n // Let's consider BACKTICK_KEY=`This has 'single' and \"double\" quotes inside of it.`\n // This should become {BACKTICK_KEY: \"This has 'single' and \\\"double\\\" quotes inside of it.\"}\n // The current slicing handles this correctly. Escaped backticks like \\` needs to be considered if they should be unescaped.\n // The rules do not specify un-escaping for \\\\', \\\\\", or \\\\` within their respective quotes.\n // So, 'it\\'s a test' would become \"it\\'s a test\". If it should be \"it's a test\", then un-escaping is needed.\n // Given \"single and double quoted values are escaped\", it seems like what's inside the quotes is the literal string value.\n // Let's stick to the examples: SINGLE_QUOTE='quoted' becomes {SINGLE_QUOTE: \"quoted\"}. This means the value is 'quoted'.\n } else {\n // Unquoted value, trim whitespace\n value = value.trim();\n }\n\n\n if (key) { // Ensure key is not empty\n envVars[key] = value;\n }\n }\n }\n\n // Add environment variables to the payload\n return Object.entries(envVars).map(([key, value]) => ({\n key,\n value,\n }));\n};","import { Command } from 'commander';\nimport { checkCvmExists, deleteCvm, selectCvm } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport inquirer from 'inquirer';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\n\nexport const deleteCommand = new Command()\n .name('delete')\n .description('Delete a CVM')\n .argument('[app-id]', 'App ID of the CVM to delete (if not provided, a selection prompt will appear)')\n .option('-f, --force', 'Skip confirmation prompt', false)\n .action(async (appId, options) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n \n // Confirm deletion unless force option is used\n if (!options.force) {\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirm',\n message: `Are you sure you want to delete CVM with App ID app_${resolvedAppId}? This action cannot be undone.`,\n default: false,\n },\n ]);\n \n if (!confirm) {\n logger.info('Deletion cancelled');\n return;\n }\n }\n \n // Delete the CVM\n const spinner = logger.startSpinner(`Deleting CVM app_${resolvedAppId}`);\n const success = await deleteCvm(resolvedAppId);\n spinner.stop(true);\n \n if (!success) {\n logger.error(`Failed to delete CVM app_${resolvedAppId}`);\n process.exit(1);\n }\n\n\t\tlogger.success(`CVM app_${resolvedAppId} deleted successfully`);\n\t} catch (error) {\n\t\tlogger.error(\n\t\t\t`Failed to delete CVM: ${error instanceof Error ? error.message : String(error)}`\n\t\t);\n\t\tprocess.exit(1);\n\t}\n }); ","import { Command } from 'commander';\nimport { upgradeCvm, getCvmByAppId, selectCvm, checkCvmExists } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport fs from 'node:fs';\nimport { detectFileInCurrentDir, promptForFile } from '@/src/utils/prompts';\nimport { parseEnv } from '@/src/utils/secrets';\nimport { encryptEnvVars, type EnvVar } from '@phala/dstack-sdk/encrypt-env-vars';\nimport { deleteSimulatorEndpointEnv } from '@/src/utils/simulator';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nexport const upgradeCommand = new Command()\n .name('upgrade')\n .description('Upgrade a CVM to a new version')\n .argument('[app-id]', 'CVM app ID to upgrade (will prompt for selection if not provided)')\n .option('-c, --compose <compose>', 'Path to new Docker Compose file')\n .option('-e, --env-file <envFile>', 'Path to environment file')\n .option('--debug', 'Enable debug mode', false)\n .action(async (appId, options) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n\n // Get current CVM configuration\n const spinner = logger.startSpinner(`Fetching current configuration for CVM app_${resolvedAppId}`);\n const currentCvm = await getCvmByAppId(resolvedAppId);\n spinner.stop(true);\n \n if (!currentCvm) {\n logger.error(`CVM with App ID app_${resolvedAppId} not found`);\n process.exit(1);\n }\n \n // If compose path not provided, prompt with examples\n if (!options.compose) {\n const possibleFiles = ['docker-compose.yml', 'docker-compose.yaml'];\n const composeFileName = detectFileInCurrentDir(possibleFiles, 'Detected docker compose file: {path}');\n \n options.compose = await promptForFile(\n 'Enter the path to your Docker Compose file:',\n composeFileName,\n 'file'\n );\n }\n \n // Update Docker Compose file if provided\n let composeString = '';\n if (options.compose) {\n try {\n composeString = fs.readFileSync(options.compose, 'utf8');\n } catch (error) {\n logger.error(`Failed to read Docker Compose file: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }\n \n // Delete DSTACK_SIMULATOR_ENDPOINT environment variable\n await deleteSimulatorEndpointEnv();\n // Print if they are using a private registry\n if (process.env.DSTACK_DOCKER_USERNAME && process.env.DSTACK_DOCKER_PASSWORD) {\n logger.info(\"🔐 Using private DockerHub registry credentials...\");\n } else if (process.env.DSTACK_AWS_ACCESS_KEY_ID && process.env.DSTACK_AWS_SECRET_ACCESS_KEY && process.env.DSTACK_AWS_REGION && process.env.DSTACK_AWS_ECR_REGISTRY) {\n logger.info(`🔐 Using private AWS ECR registry: ${process.env.DSTACK_AWS_ECR_REGISTRY}`);\n } else {\n logger.info(\"🔐 Using public DockerHub registry...\");\n }\n\n // Process environment variables if provided\n let encrypted_env = \"\";\n if (options.envFile) {\n let envs: EnvVar[] = [];\n \n // Process environment variables from file\n if (options.envFile) {\n try {\n envs = parseEnv([], options.envFile);\n encrypted_env = await encryptEnvVars(envs, currentCvm.encrypted_env_pubkey);\n } catch (error) {\n logger.error(`Failed to read environment file: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }\n \n }\n\n const vm_config = {\n compose_manifest: {\n docker_compose_file: composeString,\n manifest_version: 1,\n runner: \"docker-compose\",\n version: \"1.0.0\",\n features: [\"kms\", \"tproxy-net\"],\n name: `app_${resolvedAppId}`,\n },\n encrypted_env,\n allow_restart: true,\n };\n \n // Upgrade the CVM\n const upgradeSpinner = logger.startSpinner(`Upgrading CVM app_${resolvedAppId}`);\n const response = await upgradeCvm(resolvedAppId, vm_config);\n \n if (!response) {\n upgradeSpinner.stop(false);\n logger.error('Failed to upgrade CVM');\n process.exit(1);\n }\n upgradeSpinner.stop(true);\n\n if (response.detail) {\n logger.info(`Details: ${response.detail}`);\n }\n\n logger.break();\n logger.success(\n `Your CVM is being upgraded. You can check the dashboard for more details:\\n${CLOUD_URL}/dashboard/cvms/app_${resolvedAppId}`\n );\n } catch (error) {\n logger.error(`Failed to upgrade CVM: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { checkCvmExists, getCvmByAppId, resizeCvm, selectCvm } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport inquirer from 'inquirer';\nimport chalk from 'chalk';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nexport const resizeCommand = new Command()\n .name('resize')\n .description('Resize resources for a CVM')\n .argument('[app-id]', 'App ID of the CVM (if not provided, a selection prompt will appear)')\n .option('-v, --vcpu <vcpu>', 'Number of virtual CPUs')\n .option('-m, --memory <memory>', 'Memory size in MB')\n .option('-d, --disk-size <diskSize>', 'Disk size in GB')\n .option('-r, --allow-restart <allowRestart>', 'Allow restart of the CVM if needed for resizing')\n .option('-y, --yes', 'Automatically confirm the resize operation')\n .action(async (appId, options) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n\n const cvm = await getCvmByAppId(resolvedAppId);\n \n // Initialize parameters\n let vcpu: number | undefined = options.vcpu;\n let memory: number | undefined = options.memory;\n let diskSize: number | undefined = options.diskSize;\n let allowRestart: boolean | undefined = options.allowRestart;\n // Prompt for vCPU if selected\n if (!vcpu) {\n const response = await inquirer.prompt([\n {\n type: 'input',\n name: 'vcpu',\n message: 'Enter number of vCPUs:',\n validate: (input) => {\n const num = parseInt(input);\n if (isNaN(num) || num < 0) {\n return 'Please enter a valid non-negative number';\n }\n return true;\n },\n default: cvm.vcpu,\n filter: (input) => parseInt(input)\n }\n ]);\n vcpu = response.vcpu;\n }\n \n // Prompt for memory\n if (!memory) {\n const response = await inquirer.prompt([\n {\n type: 'input',\n name: 'memory',\n message: 'Enter memory in MB:',\n validate: (input) => {\n const num = parseInt(input);\n if (isNaN(num) || num < 0) {\n return 'Please enter a valid non-negative number';\n }\n return true;\n },\n default: cvm.memory,\n filter: (input) => parseInt(input)\n }\n ]);\n memory = response.memory;\n }\n \n // Prompt for disk size\n if (!diskSize) {\n const response = await inquirer.prompt([\n {\n type: 'input',\n name: 'diskSize',\n message: 'Enter disk size in GB:',\n validate: (input) => {\n const num = parseInt(input);\n if (isNaN(num) || num < 0) {\n return 'Please enter a valid non-negative number';\n }\n return true;\n },\n default: cvm.disk_size,\n filter: (input) => parseInt(input)\n }\n ]);\n diskSize = response.diskSize;\n }\n \n // Ask about restart permission\n if (!allowRestart) {\n const response = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'allowRestart',\n message: 'Allow restart of the CVM if needed for resizing?',\n default: false\n }\n ]);\n allowRestart = response.allowRestart;\n }\n \n // Prepare confirmation message\n const confirmMessage = `Are you sure you want to resize CVM app_${resolvedAppId} with the following changes:\\n`;\n logger.keyValueTable(\n { 'vCPUs': cvm.vcpu !== vcpu ? `${chalk.red(cvm.vcpu)} -> ${chalk.green(vcpu)}` : cvm.vcpu,\n 'Memory': cvm.memory !== memory ? `${chalk.red(cvm.memory)} MB -> ${chalk.green(memory)} MB` : cvm.memory,\n 'Disk Size': cvm.disk_size !== diskSize ? `${chalk.red(cvm.disk_size)} GB -> ${chalk.green(diskSize)} GB` : cvm.disk_size,\n 'Allow Restart': allowRestart ? chalk.green('Yes') : chalk.red('No') }\n );\n \n // Confirm the resize operation\n if (!options.yes) {\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirm',\n message: confirmMessage,\n default: false\n }\n ]);\n \n if (!confirm) {\n logger.info('Resize operation cancelled');\n return;\n }\n }\n \n const spinner = logger.startSpinner(`Resizing CVM with App ID app_${resolvedAppId}`);\n \n // Convert boolean to number (0 or 1) as expected by the API\n const allowRestartValue = allowRestart ? 1 : 0;\n \n await resizeCvm(resolvedAppId, vcpu, memory, diskSize, allowRestartValue);\n\n spinner.stop(true);\n logger.break();\n logger.success(\n `Your CVM is being resized. You can check the dashboard for more details:\\n${CLOUD_URL}/dashboard/cvms/app_${resolvedAppId}`\n );\n } catch (error) {\n logger.error(\n `Failed to resize CVM: ${error instanceof Error ? error.message : String(error)}`\n );\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { getTeepods } from '@/src/api/teepods';\nimport { logger } from '@/src/utils/logger';\nimport { KmsListItem, TEEPod } from '@/src/api/types';\n\nexport const listNodesCommand = new Command()\n .name('list-nodes')\n .description('List all available worker nodes.')\n .action(async () => {\n try {\n const { nodes: teepods, kms_list: kmsList } = await getTeepods();\n\n if (teepods.length === 0) {\n logger.info('No available nodes found.');\n return;\n }\n\n logger.info('Available Nodes:');\n teepods.forEach((teepod: TEEPod) => {\n logger.info('----------------------------------------');\n logger.info(` ID: ${teepod.teepod_id}`);\n logger.info(` Name: ${teepod.name}`);\n logger.info(` Region: ${teepod.region_identifier}`);\n logger.info(` FMSPC: ${teepod.fmspc || 'N/A'}`);\n logger.info(` Device ID: ${teepod.device_id || 'N/A'}`);\n logger.info(` Support Onchain KMS: ${teepod.support_onchain_kms}`);\n logger.info(' Images:');\n if (teepod.images && teepod.images.length > 0) {\n teepod.images.forEach(img => {\n logger.info(` - ${img.name}`);\n logger.info(` Hash: ${img.os_image_hash || 'N/A'}`);\n });\n } else {\n logger.info(' N/A');\n }\n });\n\n if (kmsList && kmsList.length > 0) {\n logger.info('\\nAvailable KMS Instances:');\n kmsList.forEach((kms: KmsListItem) => {\n logger.info('----------------------------------------');\n logger.info(` ID: ${kms.id}`);\n logger.info(` URL: ${kms.url}`);\n logger.info(` Version: ${kms.version}`);\n logger.info(` Chain ID: ${kms.chain_id}`);\n logger.info(` Contract Address: ${kms.kms_contract_address}`);\n logger.info(` Gateway App ID: ${kms.gateway_app_id}`);\n });\n }\n } catch (error) {\n logger.error(`Failed to list available nodes: ${error instanceof Error ? error.message : String(error)}`);\n }\n });","import { Command } from 'commander';\nimport { replicateCvm, getCvmComposeConfig } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { encryptEnvVars } from '@phala/dstack-sdk/encrypt-env-vars';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nexport const replicateCommand = new Command()\n .name('replicate')\n .description('Create a replica of an existing CVM')\n .argument('<cvm-id>', 'UUID of the CVM to replicate')\n .option('--teepod-id <teepodId>', 'TEEPod ID to use for the replica')\n .option('-e, --env-file <envFile>', 'Path to environment file')\n .action(async (cvmId, options) => {\n try {\n let encryptedEnv: string | undefined;\n cvmId = cvmId.replace(/-/g, '');\n\n // Handle environment variables if provided\n if (options.envFile) {\n const envPath = path.resolve(process.cwd(), options.envFile);\n if (!fs.existsSync(envPath)) {\n throw new Error(`Environment file not found: ${envPath}`);\n }\n\n // Read and parse the environment file\n const envContent = fs.readFileSync(envPath, 'utf-8');\n const envVars = envContent\n .split('\\n')\n .filter(line => line.trim() !== '' && !line.trim().startsWith('#'))\n .map(line => {\n const [key, ...value] = line.split('=');\n return {\n key: key.trim(),\n value: value.join('=').trim()\n };\n });\n\n // Get CVM compose config which includes the public key\n const cvmConfig = await getCvmComposeConfig(cvmId);\n\n // Encrypt the environment variables\n logger.info('Encrypting environment variables...');\n const encryptedVars = await encryptEnvVars(\n envVars,\n cvmConfig.env_pubkey\n );\n encryptedEnv = encryptedVars;\n }\n\n // Prepare the request body\n const requestBody: {\n teepod_id?: number;\n encrypted_env?: string;\n } = {};\n\n if (options.teepodId) {\n requestBody.teepod_id = parseInt(options.teepodId, 10);\n }\n if (encryptedEnv) {\n requestBody.encrypted_env = encryptedEnv;\n }\n\n // Call the API to create the replica\n const replica = await replicateCvm(cvmId, requestBody);\n\n logger.success(`Successfully created replica of CVM UUID: ${cvmId} with App ID: ${replica.app_id}`);\n\n const tableData = {\n 'CVM UUID': replica.vm_uuid.replace(/-/g, ''),\n 'App ID': replica.app_id,\n 'Name': replica.name,\n 'Status': replica.status,\n 'TEEPod': `${replica.teepod.name} (ID: ${replica.teepod_id})`,\n 'vCPUs': replica.vcpu,\n 'Memory': `${replica.memory} MB`,\n 'Disk Size': `${replica.disk_size} GB`,\n 'App URL': replica.app_url || `${process.env.CLOUD_URL || 'https://cloud.phala.network'}/dashboard/cvms/${replica.vm_uuid.replace(/-/g, '')}`\n };\n\n logger.keyValueTable(tableData, {\n borderStyle: 'rounded'\n });\n logger.success(`Your CVM replica is being created. You can check its status with:\\nphala cvms get ${replica.app_id}`);\n } catch (error) {\n logger.error('Failed to create CVM replica:', error instanceof Error ? error.message : error);\n process.exit(1);\n }\n });\n","import { Command } from 'commander';\nimport { logger } from '@/src/utils/logger';\nimport { execSync } from 'node:child_process';\nimport * as os from 'node:os';\nimport { logo } from '../utils/banner';\n\n\n/**\n * Opens a URL in the default web browser based on the current operating system\n * @param url The URL to open\n */\nfunction openBrowser(url: string): void {\n const platform = os.platform();\n \n try {\n switch (platform) {\n case 'darwin': // macOS\n execSync(`open \"${url}\"`);\n break;\n case 'win32': // Windows\n execSync(`start \"\" \"${url}\"`);\n break;\n case 'linux': // Linux\n // Try different commands in order\n try {\n execSync(`xdg-open \"${url}\"`);\n } catch (error) {\n try {\n execSync(`gnome-open \"${url}\"`);\n } catch (error) {\n execSync(`kde-open \"${url}\"`);\n }\n }\n break;\n default:\n throw new Error(`Unsupported platform: ${platform}`);\n }\n logger.success(`Opened URL in your default browser: ${url}`);\n } catch (error) {\n logger.error(`Failed to open URL: ${error instanceof Error ? error.message : String(error)}`);\n logger.info(`Please manually open this URL in your browser: ${url}`);\n }\n}\n\n/**\n * Pauses execution for the specified number of milliseconds\n * @param {number} ms - Time to sleep in milliseconds\n * @returns {Promise} Promise that resolves after the specified time\n */\nfunction sleep(ms) {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport const joinCommand = new Command()\n .name('join')\n .alias('free')\n .description('Join Phala Cloud! Get an account and deploy a CVM for FREE')\n .action(async () => {\n try {\n const inviteUrl = 'https://cloud.phala.network/register?invite=beta';\n const spinner =logger.startSpinner('Brewing a fresh cup of TEE 🍵');\n await sleep(2000);\n spinner.stop(true);\n logger.break();\n logger.break();\n console.log(logo);\n logger.info('TEE is served! Opening Phala Cloud registration page...');\n await sleep(1000);\n logger.break()\n openBrowser(inviteUrl);\n } catch (error) {\n logger.error(`Error: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from \"commander\";\nimport { logger } from \"@/src/utils/logger\";\nimport { getApiKey } from \"@/src/utils/credentials\";\nimport { getUserInfo } from \"@/src/api/auth\";\nimport { createCvm, getPubkeyFromCvm } from \"@/src/api/cvms\";\nimport { DEFAULT_IMAGE, CLOUD_URL } from \"@/src/utils/constants\";\nimport { demoTemplates } from \"@/src/utils/demo\";\nimport {\n\tencryptEnvVars,\n\ttype EnvVar,\n} from \"@phala/dstack-sdk/encrypt-env-vars\";\nimport inquirer from \"inquirer\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport crypto from \"node:crypto\";\nimport { parseEnv } from \"@/src/utils/secrets\";\n\nexport const demoCommands = new Command()\n .name(\"demo\")\n .description(\"Demo commands to launch a demo on Phala Cloud\")\n .action(async () => {\n try {\n // 1. Check if the user is logged in\n const apiKey = await getApiKey();\n if (!apiKey) {\n logger.error(\"You need to be logged in to use the demo command\");\n logger.info(\"Please login with: phala auth login\");\n process.exit(1);\n }\n\n // Verify user credentials\n try {\n const spinner = logger.startSpinner(\"Verifying your credentials\");\n const userInfo = await getUserInfo();\n spinner.stop(true);\n logger.success(`Logged in as ${userInfo.username}`);\n } catch (error) {\n logger.error(\"Authentication failed. Your API key may be invalid or expired.\");\n logger.info(\"Please set a new API key with: phala auth login\");\n process.exit(1);\n }\n\n // 2. Get list of available templates\n const templates = Object.values(demoTemplates);\n\n if (templates.length === 0) {\n logger.error(\"No template files found in the templates directory\");\n process.exit(1);\n }\n\n // 3. Prompt user to select a template\n const { selectedTemplate } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"selectedTemplate\",\n message: \"Select a template to deploy:\",\n choices: templates.map(t => ({\n name: t.name,\n value: t\n }))\n }\n ]);\n\n // 4. Read the selected template\n const templateContent = selectedTemplate.compose;\n logger.success(`Selected template: ${selectedTemplate.name}`);\n\n // 5. Generate a random token for services that might need it\n const token = crypto.randomBytes(16).toString(\"hex\");\n const envVars = parseEnv([`TOKEN=${token}`], \"\");\n \n \n // 6. Ask for CVM name\n const { cvmName } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"cvmName\",\n message: \"Enter a name for your CVM:\",\n default: `${selectedTemplate.name.replace(\" \", \"-\")}`,\n validate: (input) => {\n if (!input.trim()) {\n return \"CVM name is required\";\n }\n return true;\n }\n }\n ]);\n\n // 7. Deploy the CVM with the specified resources\n logger.info(\"Preparing to deploy your CVM...\");\n \n // Prepare VM configuration with specified resources\n const vmConfig = {\n teepod_id: 3,\n name: cvmName,\n image: DEFAULT_IMAGE,\n vcpu: 2,\n memory: 2048,\n disk_size: 20,\n compose_manifest: {\n docker_compose_file: templateContent,\n docker_config: {\n url: \"\",\n username: \"\",\n password: \"\",\n },\n features: [\"kms\", \"tproxy-net\"],\n kms_enabled: true,\n manifest_version: 2,\n name: cvmName,\n public_logs: true,\n public_sysinfo: true,\n tproxy_enabled: true,\n },\n listed: false,\n };\n\n // Get public key from CVM for the API call structure\n const spinner = logger.startSpinner(\"Preparing CVM configuration\");\n const pubkey = await getPubkeyFromCvm(vmConfig);\n spinner.stop(true);\n \n if (!pubkey) {\n logger.error(\"Failed to prepare CVM configuration\");\n process.exit(1);\n }\n\n const encrypted_env = await encryptEnvVars(\n\t\t\t\t\t\t\tenvVars,\n\t\t\t\t\t\t\tpubkey.app_env_encrypt_pubkey,\n\t\t\t\t\t\t);\n\n logger.debug(\"Public key:\", pubkey.app_env_encrypt_pubkey);\n logger.debug(\"Encrypted environment variables:\", encrypted_env);\n // Create the CVM\n const createSpinner = logger.startSpinner(\"Creating your demo CVM\");\n const response = await createCvm({\n ...vmConfig,\n encrypted_env,\n app_env_encrypt_pubkey: pubkey.app_env_encrypt_pubkey,\n app_id_salt: pubkey.app_id_salt,\n });\n createSpinner.stop(true);\n\n if (!response) {\n logger.error(\"Failed to create demo CVM\");\n process.exit(1);\n }\n\n logger.success(\"Demo CVM created successfully! 🎉\");\n logger.break();\n \n const tableData = {\n \"CVM ID\": response.id,\n \"Name\": response.name,\n \"Status\": response.status,\n \"App ID\": `app_${response.app_id}`,\n \"App URL\": response.app_url ? response.app_url : `${CLOUD_URL}/dashboard/cvms/app_${response.app_id}`,\n \"Template\": selectedTemplate.name,\n \"Resources\": \"2 vCPUs, 2GB RAM, 20GB Storage\",\n };\n \n if (selectedTemplate.name.includes(\"Jupyter Notebook\")) {\n tableData[\"Jupyter Token\"] = token;\n tableData[\"Access Instructions\"] = \"Access your Jupyter notebook using the token above. Go to 'Network' tab to see the public URL.\";\n }\n \n logger.keyValueTable(tableData, {\n borderStyle: \"rounded\"\n });\n\n logger.break();\n logger.success(`Your demo is being created. You can check its status with:\\nphala cvms get app_${response.app_id}`);\n\n } catch (error) {\n logger.error(`Failed to launch demo: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n });\n","const jupyterCompose = `version: '3'\nservices:\n jupyter:\n image: quay.io/jupyter/base-notebook\n ports:\n - 8080:8888\n volumes:\n - /var/run/tappd.sock:/var/run/tappd.sock\n environment:\n - GRANT_SUDO=yes\n user: root\n command: \"start-notebook.sh --NotebookApp.token=\\${TOKEN}\"\n`;\n\nexport const httpbinCompose = `version: '3'\nservices:\n httpbin:\n image: kennethreitz/httpbin:latest\n ports:\n - \"80:80\"\n`;\n\n\nexport const demoTemplates = {\n jupyter: {\n compose: jupyterCompose,\n name: \"Jupyter Notebook\",\n },\n httpbin: {\n compose: httpbinCompose,\n name: \"HTTPBin\",\n },\n};\n","import { Command } from 'commander';\nimport { listNodes } from './list.js';\n\nexport const nodesCommand = new Command()\n .name('nodes')\n .description('List and manage TEE nodes')\n .action(listNodes)\n .addCommand(\n new Command('list')\n .description('List all available worker nodes')\n .alias('ls')\n .action(listNodes)\n );\n","import { getTeepods } from '@/src/api/teepods';\nimport { logger } from '@/src/utils/logger';\nimport { KmsListItem, TEEPod } from '@/src/api/types';\n\nexport async function listNodes() {\n try {\n const { nodes: teepods, kms_list: kmsList } = await getTeepods();\n\n if (teepods.length === 0) {\n logger.info('No available nodes found.');\n return;\n }\n\n logger.info('Available Nodes:');\n teepods.forEach((teepod: TEEPod) => {\n logger.info('----------------------------------------');\n logger.info(` ID: ${teepod.teepod_id}`);\n logger.info(` Name: ${teepod.name}`);\n logger.info(` Region: ${teepod.region_identifier}`);\n logger.info(` FMSPC: ${teepod.fmspc || 'N/A'}`);\n logger.info(` Device ID: ${teepod.device_id || 'N/A'}`);\n logger.info(` Support Onchain KMS: ${teepod.support_onchain_kms}`);\n \n logger.info(' Images:');\n if (teepod.images && teepod.images.length > 0) {\n teepod.images.forEach(img => {\n logger.info(` - ${img.name}`);\n logger.info(` Hash: ${img.os_image_hash || 'N/A'}`);\n });\n } else {\n logger.info(' N/A');\n }\n });\n\n if (kmsList && kmsList.length > 0) {\n logger.info('\\nAvailable KMS Instances:');\n kmsList.forEach((kms: KmsListItem) => {\n logger.info('----------------------------------------');\n logger.info(` ID: ${kms.id}`);\n logger.info(` URL: ${kms.url}`);\n logger.info(` Version: ${kms.version}`);\n logger.info(` Chain ID: ${kms.chain_id}`);\n logger.info(` Contract Address: ${kms.kms_contract_address}`);\n logger.info(` Gateway App ID: ${kms.gateway_app_id}`);\n });\n }\n } catch (error) {\n logger.error(`Failed to list available nodes: ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n}\n"],"mappings":";yRACA,OAAS,WAAAA,OAAe,YCDxB,OAAOC,OAAW,QAClB,IAAMC,GAAYD,GAAM,IAAI,SAAS,EACxBE,EAAOD,GAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAsB7B,EAEYE,GAAYF,GAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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AAK,EAAE,MAAOU,GAAU,CACvBC,EAAO,MAAM,qBAAsBD,CAAK,EACxC,QAAQ,KAAK,CAAC,CACf,CAAC","names":["Command","chalk","logoColor","logo","smallLogo","minimalLogo","Command","Command","prompts","loginCommand","Command","apiKey","checkUserInfo","prompts","value","saveApiKey","getUserInfo","removeApiKey","logger","CLOUD_URL","error","Command","logoutCommand","Command","removeApiKey","logger","error","Command","statusCommand","Command","options","apiKey","getApiKey","logger","spinner","userInfo","getUserInfo","tableData","error","authCommands","Command","loginCommand","logoutCommand","statusCommand","Command","Command","execa","fs","path","Handlebars","exec","spawn","promisify","os","inquirer","fs","path","validateFileExists","filePath","basePath","resolvedPath","path","fs","promptForFile","message","defaultValue","name","inquirer","input","detectFileInCurrentDir","possibleFiles","logMessage","file","logger","fs","path","os","execSync","spawn","net","SIMULATOR_CONFIG","isSimulatorInstalled","platform","extractedFolderPath","executablePath","error","logger","getPlatform","installSimulator","progressCallback","log","message","platformConfig","downloadUrl","execSync","runSimulator","options","executableName","runOptions","logDir","stdio","outputStream","simulatorProcess","spawn","timestamp","setSimulatorEndpointEnv","isSimulatorRunning","platform","getPlatform","platformConfig","SIMULATOR_CONFIG","socketPath","resolve","client","host","error","logger","stopSimulator","execSync","stopped","deleteSimulatorEndpointEnv","getSimulatorEndpoint","getPlatform","setSimulatorEndpointEnv","endpoint","simulatorEndpoint","envEndpoint","execSync","logger","error","deleteSimulatorEndpointEnv","execAsync","promisify","exec","LOGS_DIR","COMPOSE_FILES_DIR","MAX_CONSOLE_LINES","DockerService","image","username","registry","logsPath","path","fs","operation","timestamp","arch","os","command","args","resolve","reject","proc","spawn","logFile","logStream","consoleBuffer","processOutput","data","isError","lines","line","bufferedLine","code","err","dockerfile","tag","fullImageName","spinner","logger","validateFileExists","buildArgs","error","imageName","getDockerCredentials","password","execa","loginError","homeDir","dockerConfigPath","dockerConfig","envFile","templateType","template","DOCKER_COMPOSE_ELIZA_V2_TEMPLATE","DOCKER_COMPOSE_BASIC_TEMPLATE","validatedTemplate","ComposeTemplateSchema","composePath","envVars","commentIndex","key","value","trimmedKey","composeContent","Handlebars","env","composeFile","composeArgs","port","stdout","containerId","setSimulatorEndpointEnv","deleteSimulatorEndpointEnv","prompts","loginCommand","Command","options","username","password","registry","logger","response","value","dockerService","DockerService","saveDockerCredentials","error","Command","path","inquirer","fs","buildCommand","Command","options","credentials","getDockerCredentials","logger","response","inquirer","input","defaultPath","path","fs","promptForFile","dockerfilePath","DockerService","error","Command","inquirer","pushCommand","Command","options","credentials","getDockerCredentials","logger","imageName","localImages","DockerService","uniqueImageNames","img","selectedImage","error","Command","inquirer","fs","path","generateCommand","Command","options","credentials","getDockerCredentials","logger","imageName","localImages","DockerService","uniqueImageNames","img","selectedImage","inquirer","envFilePath","validateFileExists","defaultEnvPath","path","fs","useDefault","envPath","input","outputPath","confirmOverwrite","customPath","dockerService","composePath","outputDir","error","dockerCommands","Command","loginCommand","buildCommand","pushCommand","generateCommand","Command","Command","startCommand","Command","TEE_SIMULATOR","options","DockerService","logger","isSimulatorInstalled","installSimulator","isSimulatorRunning","simulatorProcess","runSimulator","error","Command","stopCommand","Command","options","DockerService","logger","stopSimulator","error","simulatorCommands","Command","startCommand","stopCommand","Command","Command","chalk","listCommand","Command","options","spinner","logger","cvms","getCvms","cvm","CLOUD_URL","error","Command","chalk","resolveCvmAppId","appId","selectedCvm","selectCvm","checkCvmExists","getCommand","Command","appId","options","resolvedAppId","resolveCvmAppId","spinner","logger","cvm","getCvmByAppId","chalk","CLOUD_URL","error","Command","startCommand","Command","appId","resolvedAppId","resolveCvmAppId","spinner","logger","response","startCvm","tableData","CLOUD_URL","error","Command","stopCommand","Command","appId","resolvedAppId","resolveCvmAppId","spinner","logger","response","stopCvm","tableData","CLOUD_URL","error","Command","restartCommand","Command","appId","resolvedAppId","resolveCvmAppId","spinner","logger","response","restartCvm","tableData","CLOUD_URL","error","Command","chalk","attestationCommand","Command","appId","options","resolvedAppId","checkCvmExists","logger","selectedCvm","selectCvm","spinner","attestationData","getCvmAttestation","summaryData","cert","index","certData","tcbBasicInfo","maxEntriesToShow","entries","entry","error","Command","encryptEnvVars","fs","path","inquirer","fs","parseEnv","envs","envFile","envVars","env","key","valueParts","value","envFileContent","line","delimiterIndex","inQuotes","quoteChar","i","valueInQuotes","valueQuoteChar","commentStartIndex","firstChar","lastChar","createCommand","Command","DEFAULT_VCPU","DEFAULT_MEMORY","DEFAULT_DISK_SIZE","options","name","inquirer","input","composeFileName","detectFileInCurrentDir","promptForFile","composePath","path","fs","logger","composeString","deleteSimulatorEndpointEnv","envs","parseEnv","error","shouldSkip","envVars","vcpu","memory","diskSize","teepodsSpinner","teepods","getTeepods","selectedTeepod","pod","selectedImage","image","DEFAULT_IMAGE","vmConfig","spinner","pubkey","getPubkeyFromCvm","encryptSpinner","encrypted_env","encryptEnvVars","createSpinner","response","createCvm","tableData","CLOUD_URL","Command","inquirer","deleteCommand","Command","appId","options","resolvedAppId","resolveCvmAppId","confirm","inquirer","logger","spinner","success","deleteCvm","error","Command","fs","encryptEnvVars","upgradeCommand","Command","appId","options","resolvedAppId","resolveCvmAppId","spinner","logger","currentCvm","getCvmByAppId","composeFileName","detectFileInCurrentDir","promptForFile","composeString","fs","error","deleteSimulatorEndpointEnv","encrypted_env","envs","parseEnv","encryptEnvVars","vm_config","upgradeSpinner","response","upgradeCvm","CLOUD_URL","Command","inquirer","chalk","resizeCommand","Command","appId","options","resolvedAppId","resolveCvmAppId","cvm","getCvmByAppId","vcpu","memory","diskSize","allowRestart","inquirer","input","num","confirmMessage","logger","chalk","confirm","spinner","resizeCvm","CLOUD_URL","error","Command","listNodesCommand","Command","teepods","kmsList","getTeepods","logger","teepod","img","kms","error","Command","encryptEnvVars","fs","path","replicateCommand","Command","cvmId","options","encryptedEnv","envPath","envVars","line","key","value","cvmConfig","getCvmComposeConfig","logger","requestBody","replica","replicateCvm","tableData","error","cvmsCommand","Command","attestationCommand","createCommand","deleteCommand","getCommand","listCommand","startCommand","stopCommand","resizeCommand","restartCommand","upgradeCommand","listNodesCommand","replicateCommand","Command","execSync","os","openBrowser","url","platform","execSync","logger","error","sleep","ms","resolve","joinCommand","Command","inviteUrl","spinner","logo","Command","jupyterCompose","httpbinCompose","demoTemplates","encryptEnvVars","inquirer","crypto","demoCommands","Command","getApiKey","logger","spinner","userInfo","getUserInfo","templates","demoTemplates","selectedTemplate","inquirer","t","templateContent","token","crypto","envVars","parseEnv","cvmName","input","vmConfig","DEFAULT_IMAGE","pubkey","getPubkeyFromCvm","encrypted_env","encryptEnvVars","createSpinner","response","createCvm","tableData","CLOUD_URL","error","Command","listNodes","teepods","kmsList","getTeepods","logger","teepod","img","kms","error","nodesCommand","Command","listNodes","main","Command","logo","authCommands","cvmsCommand","dockerCommands","simulatorCommands","demoCommands","joinCommand","nodesCommand","error","logger"]}
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils/banner.ts","../src/commands/auth/index.ts","../src/commands/auth/login.ts","../src/commands/auth/logout.ts","../src/commands/auth/status.ts","../src/commands/docker/index.ts","../src/commands/docker/login.ts","../src/utils/docker.ts","../src/utils/prompts.ts","../src/utils/simulator.ts","../src/commands/docker/build.ts","../src/commands/docker/push.ts","../src/commands/docker/generate.ts","../src/commands/simulator/index.ts","../src/commands/simulator/start.ts","../src/commands/simulator/stop.ts","../src/commands/cvms/index.ts","../src/commands/cvms/list.ts","../src/commands/cvms/get.ts","../src/utils/cvms.ts","../src/commands/cvms/start.ts","../src/commands/cvms/stop.ts","../src/commands/cvms/restart.ts","../src/commands/cvms/attestation.ts","../src/commands/cvms/create.ts","../src/utils/secrets.ts","../src/commands/cvms/delete.ts","../src/commands/cvms/upgrade.ts","../node_modules/viem/utils/getAction.ts","../node_modules/viem/errors/log.ts","../node_modules/viem/utils/abi/encodeEventTopics.ts","../node_modules/viem/utils/filters/createFilterRequestScope.ts","../node_modules/viem/actions/public/createContractEventFilter.ts","../node_modules/viem/utils/errors/getContractError.ts","../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../node_modules/viem/utils/signature/recoverPublicKey.ts","../node_modules/viem/utils/signature/recoverAddress.ts","../node_modules/viem/utils/encoding/toRlp.ts","../node_modules/viem/experimental/eip7702/utils/hashAuthorization.ts","../node_modules/viem/experimental/eip7702/utils/recoverAuthorizationAddress.ts","../node_modules/viem/errors/estimateGas.ts","../node_modules/viem/utils/errors/getEstimateGasError.ts","../node_modules/viem/errors/fee.ts","../node_modules/viem/errors/block.ts","../node_modules/viem/utils/formatters/transaction.ts","../node_modules/viem/utils/formatters/block.ts","../node_modules/viem/actions/public/getBlock.ts","../node_modules/viem/actions/public/getGasPrice.ts","../node_modules/viem/actions/public/estimateMaxPriorityFeePerGas.ts","../node_modules/viem/actions/public/estimateFeesPerGas.ts","../node_modules/viem/actions/public/getTransactionCount.ts","../node_modules/viem/utils/blob/blobsToCommitments.ts","../node_modules/viem/utils/blob/blobsToProofs.ts","../node_modules/@noble/hashes/src/_md.ts","../node_modules/@noble/hashes/src/sha256.ts","../node_modules/viem/utils/hash/sha256.ts","../node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../node_modules/viem/utils/blob/commitmentsToVersionedHashes.ts","../node_modules/viem/errors/blob.ts","../node_modules/viem/utils/blob/toBlobs.ts","../node_modules/viem/utils/blob/toBlobSidecars.ts","../node_modules/viem/utils/transaction/getTransactionType.ts","../node_modules/viem/actions/public/getChainId.ts","../node_modules/viem/actions/wallet/prepareTransactionRequest.ts","../node_modules/viem/actions/public/getBalance.ts","../node_modules/viem/actions/public/estimateGas.ts","../node_modules/viem/actions/public/estimateContractGas.ts","../node_modules/viem/utils/abi/decodeEventLog.ts","../node_modules/viem/utils/abi/parseEventLogs.ts","../node_modules/viem/utils/formatters/log.ts","../node_modules/viem/actions/public/getLogs.ts","../node_modules/viem/actions/public/getContractEvents.ts","../node_modules/viem/actions/public/readContract.ts","../node_modules/viem/actions/public/simulateContract.ts","../node_modules/viem/utils/observe.ts","../node_modules/viem/utils/wait.ts","../node_modules/viem/utils/poll.ts","../node_modules/viem/utils/promise/withCache.ts","../node_modules/viem/actions/public/getBlockNumber.ts","../node_modules/viem/actions/public/getFilterChanges.ts","../node_modules/viem/actions/public/uninstallFilter.ts","../node_modules/viem/actions/public/watchContractEvent.ts","../node_modules/viem/actions/wallet/sendRawTransaction.ts","../node_modules/viem/errors/eip712.ts","../node_modules/viem/actions/public/getEip712Domain.ts","../node_modules/viem/utils/uid.ts","../node_modules/viem/clients/createClient.ts","../node_modules/viem/utils/promise/withDedupe.ts","../node_modules/viem/utils/promise/withRetry.ts","../node_modules/viem/utils/buildRequest.ts","../node_modules/viem/clients/transports/createTransport.ts","../node_modules/viem/errors/transport.ts","../node_modules/viem/utils/promise/withTimeout.ts","../node_modules/viem/utils/rpc/id.ts","../node_modules/viem/utils/rpc/http.ts","../node_modules/viem/clients/transports/http.ts","../node_modules/viem/utils/ens/errors.ts","../node_modules/viem/utils/ens/encodedLabelToLabelhash.ts","../node_modules/viem/utils/ens/namehash.ts","../node_modules/viem/utils/ens/encodeLabelhash.ts","../node_modules/viem/utils/ens/labelhash.ts","../node_modules/viem/utils/ens/packetToBytes.ts","../node_modules/viem/actions/ens/getEnsAddress.ts","../node_modules/viem/errors/ens.ts","../node_modules/viem/utils/ens/avatar/utils.ts","../node_modules/viem/utils/ens/avatar/parseAvatarRecord.ts","../node_modules/viem/actions/ens/getEnsText.ts","../node_modules/viem/actions/ens/getEnsAvatar.ts","../node_modules/viem/actions/ens/getEnsName.ts","../node_modules/viem/actions/ens/getEnsResolver.ts","../node_modules/viem/actions/public/createAccessList.ts","../node_modules/viem/actions/public/createBlockFilter.ts","../node_modules/viem/actions/public/createEventFilter.ts","../node_modules/viem/actions/public/createPendingTransactionFilter.ts","../node_modules/viem/actions/public/getBlobBaseFee.ts","../node_modules/viem/actions/public/getBlockTransactionCount.ts","../node_modules/viem/actions/public/getCode.ts","../node_modules/viem/utils/formatters/feeHistory.ts","../node_modules/viem/actions/public/getFeeHistory.ts","../node_modules/viem/actions/public/getFilterLogs.ts","../node_modules/viem/utils/chain/defineChain.ts","../node_modules/viem/errors/typedData.ts","../node_modules/viem/utils/signature/hashTypedData.ts","../node_modules/viem/utils/typedData.ts","../node_modules/viem/utils/formatters/transactionReceipt.ts","../node_modules/viem/constants/strings.ts","../node_modules/viem/utils/signature/toPrefixedMessage.ts","../node_modules/viem/utils/signature/hashMessage.ts","../node_modules/viem/constants/bytes.ts","../node_modules/viem/utils/signature/isErc6492Signature.ts","../node_modules/viem/utils/signature/serializeErc6492Signature.ts","../node_modules/viem/utils/transaction/assertTransaction.ts","../node_modules/viem/experimental/eip7702/utils/serializeAuthorizationList.ts","../node_modules/viem/utils/transaction/serializeAccessList.ts","../node_modules/viem/utils/transaction/serializeTransaction.ts","../node_modules/viem/utils/formatters/proof.ts","../node_modules/viem/actions/public/getProof.ts","../node_modules/viem/actions/public/getStorageAt.ts","../node_modules/viem/actions/public/getTransaction.ts","../node_modules/viem/actions/public/getTransactionConfirmations.ts","../node_modules/viem/actions/public/getTransactionReceipt.ts","../node_modules/viem/actions/public/multicall.ts","../node_modules/ox/core/Hex.ts","../node_modules/ox/core/Bytes.ts","../node_modules/ox/core/version.ts","../node_modules/ox/core/internal/errors.ts","../node_modules/ox/core/Errors.ts","../node_modules/ox/core/Json.ts","../node_modules/ox/core/internal/bytes.ts","../node_modules/ox/core/internal/hex.ts","../node_modules/ox/core/Withdrawal.ts","../node_modules/ox/core/BlockOverrides.ts","../node_modules/viem/actions/public/simulateBlocks.ts","../node_modules/ox/core/Hash.ts","../node_modules/ox/core/internal/lru.ts","../node_modules/ox/core/Caches.ts","../node_modules/ox/core/Address.ts","../node_modules/ox/core/internal/abiItem.ts","../node_modules/ox/core/AbiItem.ts","../node_modules/ox/core/Solidity.ts","../node_modules/ox/core/internal/abiParameters.ts","../node_modules/ox/core/AbiParameters.ts","../node_modules/ox/core/AbiConstructor.ts","../node_modules/ox/core/AbiFunction.ts","../node_modules/viem/constants/address.ts","../node_modules/viem/actions/public/simulateCalls.ts","../node_modules/viem/utils/signature/serializeSignature.ts","../node_modules/viem/actions/public/verifyHash.ts","../node_modules/viem/actions/public/verifyMessage.ts","../node_modules/viem/actions/public/verifyTypedData.ts","../node_modules/viem/actions/public/watchBlockNumber.ts","../node_modules/viem/actions/public/waitForTransactionReceipt.ts","../node_modules/viem/actions/public/watchBlocks.ts","../node_modules/viem/actions/public/watchEvent.ts","../node_modules/viem/actions/public/watchPendingTransactions.ts","../node_modules/viem/utils/siwe/parseSiweMessage.ts","../node_modules/viem/utils/siwe/validateSiweMessage.ts","../node_modules/viem/actions/siwe/verifySiweMessage.ts","../node_modules/viem/clients/decorators/public.ts","../node_modules/viem/clients/createPublicClient.ts","../src/utils/blockchain.ts","../node_modules/viem/op-stack/contracts.ts","../node_modules/viem/op-stack/formatters.ts","../node_modules/viem/op-stack/serializers.ts","../node_modules/viem/op-stack/chainConfig.ts","../node_modules/viem/chains/definitions/anvil.ts","../node_modules/viem/chains/definitions/base.ts","../node_modules/viem/chains/definitions/mainnet.ts","../node_modules/viem/chains/definitions/sepolia.ts","../src/commands/cvms/resize.ts","../src/commands/cvms/replicate.ts","../src/commands/cvms/commit-provision.ts","../src/api/kms.ts","../src/commands/cvms/provision.ts","../src/utils/units.ts","../src/commands/cvms/upgrade-provision.ts","../src/commands/cvms/upgrade-commit.ts","../src/commands/join.ts","../src/commands/demo/index.ts","../src/utils/demo.ts","../src/commands/nodes/index.ts","../src/commands/nodes/list.ts","../src/commands/kms/index.ts","../src/commands/kms/deploy.ts","../src/commands/deploy/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from \"commander\";\nimport { logo } from \"./utils/banner\";\nimport { authCommands } from \"./commands/auth\";\nimport { dockerCommands } from \"./commands/docker\";\nimport { simulatorCommands } from \"./commands/simulator\";\nimport { logger } from \"./utils/logger\";\nimport { cvmsCommand } from \"./commands/cvms\";\nimport { joinCommand } from \"./commands/join\";\nimport { demoCommands } from \"./commands/demo\";\nimport { nodesCommand } from \"./commands/nodes\";\nimport { kmsCommand } from \"./commands/kms\";\nimport { deployCommand } from \"./commands/deploy\";\nimport { setApiKey } from './utils/context';\n\nprocess.on(\"SIGINT\", () => process.exit(0));\nprocess.on(\"SIGTERM\", () => process.exit(0));\n\nasync function main() {\n const program = new Command()\n\t\t\t.name(\"phala\")\n\t\t\t.alias(\"pha\")\n\t\t\t.description(\n\t\t\t\t`${logo}\\nPhala Cloud CLI - Manage your Phala Cloud Deployments`,\n\t\t\t)\n\t\t\t.version(\"v1.0.15\")\n\t\t\t.option('--api-key <key>', 'API key to use for the command')\n\t\t\t.addCommand(authCommands)\n\t\t\t.addCommand(cvmsCommand)\n\t\t\t.addCommand(dockerCommands)\n\t\t\t.addCommand(simulatorCommands)\n\t\t\t.addCommand(demoCommands)\n\t\t\t.addCommand(joinCommand)\n\t\t\t.addCommand(kmsCommand)\n\t\t\t.addCommand(nodesCommand)\n\t\t\t.addCommand(deployCommand);\n\n\tprogram.hook('preAction', (thisCommand) => {\n\t\tconst opts = thisCommand.opts();\n\t\tif (opts.apiKey) {\n\t\t\tsetApiKey(opts.apiKey);\n\t\t}\n\t});\n\n\tprogram.parse(process.argv);\n}\n\nmain().catch((error) => {\n\tlogger.error(\"An error occurred:\", error);\n\tprocess.exit(1);\n});\n","import chalk from 'chalk';\nconst logoColor = chalk.hex('#cdfa50');\nexport const logo = logoColor(`\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣠⣤⣤⣤⣀⡀⠀⢀⣀⣤⣤⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⡿⠛⠉⠁⠀⠈⠉⠛⠿⠛⠉⠉⠉⠉⠙⠷⣄⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣧⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣆⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⠞⠛⠉⠙⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠛⢶⣄⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣦⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⣿⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣿⣷⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣴⣿⣿⡿⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠀⠀⣀⣴⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠻⠿⠿⠿⠿⠃⠀⢀⣾⣿⣿⣿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠛⠋⠁⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣿⡿⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡤⠤⠤⠴⠒⠒⠒⠒⠒⢿⡿⠓⠒⠒⠢⠤⠤⠤⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣯⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁⠀⠀⠀⠀⠀⠀⠀⣀⣨⣿⣦⣤⣀⡀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣶⣶⣶⣶⣶⣶⣶⣶⣶⣶⣶⣶⣾⣿⣿⣿⣿⣿⡏⠉⠛⣿⣆⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⣀⣀⣀⣀⡸⠿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⣸⡿⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⣿⣿⣿⣿⣿⣿⣿⠀⢸⣿⣿⣿⣿⡇⠀⣿⣿⣿⣿⣿⣿⠃⢀⣠⣴⡿⠃⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⣿⣿⣿⣿⣿⣿⠿⢇⣀⣀⣀⣀⣸⣿⣿⣿⣿⣿⡿⠿⠿⠛⠛⠁⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⡠⠀⠀⠀⠀⠈⠻⢿⣿⣿⣿⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀⠠⣄⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⢸⣆⠀⠀⠀⠀⠀⠀⠀⠉⠛⠿⠿⣿⣿⣿⣿⣿⠿⠟⠋⠁⠀⠀⠀⠀⠀⠀⣀⣾⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠙⠻⢶⣦⣤⣄⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣀⣤⣴⣶⠿⠛⠁⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠙⠛⠻⠿⠿⠿⠿⢿⣿⣿⣿⠿⠿⠿⠿⠟⠛⠛⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n`);\n\nexport const smallLogo = logoColor(`\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣠⣤⣤⣤⣀⡀⠀⢀⣀⣤⣤⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⡿⠛⠉⠁⠀⠈⠉⠛⠿⠛⠉⠉⠉⠉⠙⠷⣄⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣧⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣆⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⠞⠛⠉⠙⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠛⢶⣄⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣦⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣿⣿⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣿⣷⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣴⣿⣿⡿⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠀⠀⣀⣴⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠻⠿⠿⠿⠿⠃⠀⢀⣾⣿⣿⣿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠛⠋⠁⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣿⡿⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡤⠤⠤⠴⠒⠒⠒⠒⠒⢿⡿⠓⠒⠒⠢⠤⠤⠤⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣯⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁⠀⠀⠀⠀⠀⠀⠀⣀⣨⣿⣦⣤⣀⡀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣶⣶⣶⣶⣶⣶⣶⣶⣶⣶⣶⣶⣾⣿⣿⣿⣿⣿⡏⠉⠛⣿⣆⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⣀⣀⣀⣀⡸⠿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⣸⡿⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⣿⣿⣿⣿⣿⣿⣿⠀⢸⣿⣿⣿⣿⡇⠀⣿⣿⣿⣿⣿⣿⠃⢀⣠⣴⡿⠃⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⣿⣿⣿⣿⣿⣿⠿⢇⣀⣀⣀⣀⣸⣿⣿⣿⣿⣿⡿⠿⠿⠛⠛⠁⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⡠⠀⠀⠀⠀⠈⠻⢿⣿⣿⣿⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀⠠⣄⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⢸⣆⠀⠀⠀⠀⠀⠀⠀⠉⠛⠿⠿⣿⣿⣿⣿⣿⠿⠟⠋⠁⠀⠀⠀⠀⠀⠀⣀⣾⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠙⠻⢶⣦⣤⣄⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣀⣤⣴⣶⠿⠛⠁⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠙⠛⠻⠿⠿⠿⠿⢿⣿⣿⣿⠿⠿⠿⠿⠟⠛⠛⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n`);\n\nexport const minimalLogo = chalk.cyan('PHALA TEE CLOUD CLI');","import { Command } from 'commander';\nimport { loginCommand } from './login';\nimport { logoutCommand } from './logout';\nimport { statusCommand } from './status';\n\nexport const authCommands = new Command()\n .name('auth')\n .description('Authenticate with Phala Cloud')\n .addCommand(loginCommand)\n .addCommand(logoutCommand)\n .addCommand(statusCommand);\n","import { Command } from 'commander';\nimport { removeApiKey, saveApiKey } from '@/src/utils/credentials';\nimport { logger } from '@/src/utils/logger';\nimport prompts from 'prompts';\nimport { getUserInfo } from '@/src/api/auth';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nexport const loginCommand = new Command()\n .name('login')\n .description('Set the API key for authentication')\n .argument('[api-key]', 'Phala Cloud API key to set')\n .action(async (apiKey?: string) => {\n try {\n let checkUserInfo;\n // If no API key is provided, prompt for it\n if (!apiKey) {\n const response = await prompts({\n type: 'password',\n name: 'apiKey',\n message: 'Enter your API key:',\n validate: async (value) => {\n if (value.length === 0) {\n return 'API key cannot be empty';\n }\n try {\n await saveApiKey(value);\n checkUserInfo = await getUserInfo();\n if (!checkUserInfo.username) {\n await removeApiKey();\n return 'Invalid API key';\n }\n } catch (error) {\n return 'Invalid API key';\n }\n return true;\n }\n });\n \n apiKey = response.apiKey;\n } else {\n await saveApiKey(apiKey);\n // Validate the API key\n checkUserInfo = await getUserInfo();\n if (!checkUserInfo.username) {\n await removeApiKey();\n return 'Invalid API key';\n }\n }\n \n logger.success(`Welcome ${checkUserInfo.username}! API key validated and saved successfully`);\n logger.break();\n logger.info(`Open in Web UI at ${CLOUD_URL}/dashboard/`);\n } catch (error) {\n logger.error(`Failed to set API key: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { removeApiKey } from '@/src/utils/credentials';\nimport { logger } from '@/src/utils/logger';\n\nexport const logoutCommand = new Command()\n .name('logout')\n .description('Remove the stored API key')\n .action(async () => {\n try {\n await removeApiKey();\n logger.success('API key removed successfully');\n } catch (error) {\n logger.error(`Failed to remove API key: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { getApiKey } from '@/src/utils/credentials';\nimport { getUserInfo } from '@/src/api/auth';\nimport { logger } from '@/src/utils/logger';\n\nexport const statusCommand = new Command()\n .name('status')\n .description('Check authentication status')\n .option('-j, --json', 'Output in JSON format')\n .option('-d, --debug', 'Enable debug output')\n .action(async (options) => {\n try {\n // Enable debug mode if requested\n if (options.debug) {\n process.env.DEBUG = 'true';\n }\n \n const apiKey = await getApiKey();\n \n if (!apiKey) {\n logger.warn('Not authenticated. Please set an API key with \"phala auth login\"');\n return;\n }\n \n logger.debug(`Using API key: ${apiKey.substring(0, 5)}...`);\n const spinner = logger.startSpinner('Checking authentication status');\n \n try {\n const userInfo = await getUserInfo();\n spinner.stop(true);\n \n if (options.json) {\n console.log(JSON.stringify(userInfo, null, 2));\n return;\n }\n \n logger.break();\n logger.success(`Authenticated as ${userInfo.username}`);\n \n // Create a simple object\n const tableData = {\n 'Username': userInfo.username,\n 'Email': userInfo.email,\n 'Role': userInfo.role,\n 'Team': `${userInfo.team_name} (${userInfo.team_tier})`,\n 'Credits': `$${(userInfo.credits + userInfo.granted_credits).toFixed(2)}`\n };\n \n if (userInfo.trial_ended_at) {\n tableData['Trial Ended At'] = userInfo.trial_ended_at;\n }\n \n // Display the table\n logger.keyValueTable(tableData, {\n borderStyle: 'rounded'\n });\n } catch (error) {\n spinner.stop(false);\n logger.error('Authentication failed. Your API key may be invalid or expired.');\n logger.info('Please set a new API key with \"phala auth login\"');\n \n if (options.debug) {\n logger.debug(`Error details: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n } catch (error) {\n logger.error(`Failed to check authentication status: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { loginCommand } from './login';\nimport { buildCommand } from './build';\nimport { pushCommand } from './push';\nimport { generateCommand } from './generate';\n\nexport const dockerCommands = new Command()\n .name('docker')\n .description('Login to Docker Hub and manage Docker images')\n .addCommand(loginCommand)\n .addCommand(buildCommand)\n .addCommand(pushCommand)\n .addCommand(generateCommand);\n","import { Command } from 'commander';\nimport { DockerService } from '@/src/utils/docker';\nimport { saveDockerCredentials } from '@/src/utils/credentials';\nimport { logger } from '@/src/utils/logger';\nimport prompts from 'prompts';\n\nexport const loginCommand = new Command()\n .name('login')\n .description('Login to Docker Hub')\n .option('-u, --username <username>', 'Docker Hub username')\n .option('-p, --password <password>', 'Docker Hub password')\n .option('-r, --registry <registry>', 'Docker registry URL')\n .action(async (options) => {\n try {\n let username = options.username;\n let password = options.password;\n const registry = options.registry;\n \n // If no username is provided, prompt for it\n if (!username) {\n logger.info('First we need your Docker Hub username to check if you are already logged in.');\n\n const response = await prompts({\n type: 'text',\n name: 'username',\n message: 'Enter your Docker Hub username:',\n validate: value => value.length > 0 ? true : 'Username cannot be empty'\n });\n \n if (!response.username) {\n logger.error('Username is required');\n process.exit(1);\n }\n \n username = response.username;\n }\n\n // Check if Docker is already logged in\n const dockerService = new DockerService('', username, registry);\n const loggedIn = await dockerService.login(username);\n if (loggedIn) {\n logger.success(`${username} is logged in to Docker Hub`);\n // Save credentials\n await saveDockerCredentials({\n username,\n registry: registry || null,\n });\n return;\n }\n \n // If no password is provided, prompt for it\n if (!password) {\n const response = await prompts({\n type: 'password',\n name: 'password',\n message: 'Enter your Docker Hub password:',\n validate: value => value.length > 0 ? true : 'Password cannot be empty'\n });\n \n if (!response.password) {\n logger.error('Password is required');\n process.exit(1);\n }\n \n password = response.password;\n }\n \n // Login to Docker Hub\n const success = await dockerService.login(username, password, registry);\n \n if (!success) {\n logger.error('Failed to login to Docker Hub');\n process.exit(1);\n }\n \n // Save credentials\n await saveDockerCredentials({\n username,\n registry: registry || null\n });\n \n logger.success('Logged in to Docker Hub successfully');\n } catch (error) {\n logger.error(`Failed to login to Docker Hub: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { execa } from 'execa';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from './logger';\nimport { DOCKER_COMPOSE_BASIC_TEMPLATE, DOCKER_COMPOSE_ELIZA_V2_TEMPLATE } from './constants';\nimport { getDockerCredentials } from './credentials';\nimport Handlebars from 'handlebars';\nimport { exec, spawn } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport os from 'node:os';\nimport { validateFileExists } from './prompts';\nimport { ComposeTemplateSchema } from './types';\nimport { deleteSimulatorEndpointEnv, setSimulatorEndpointEnv } from './simulator';\nconst execAsync = promisify(exec);\n\nconst LOGS_DIR = '.phala-cloud/logs';\nconst COMPOSE_FILES_DIR = '.phala-cloud/compose';\nconst MAX_CONSOLE_LINES = 10;\n\nexport class DockerService {\n private username: string;\n private image: string;\n private registry: string;\n\n constructor(image: string, username?: string, registry?: string) {\n this.image = image;\n this.username = username || '';\n this.registry = registry || '';\n }\n\n private ensureLogsDir(): void {\n const logsPath = path.resolve(LOGS_DIR);\n if (!fs.existsSync(logsPath)) {\n fs.mkdirSync(logsPath, { recursive: true });\n }\n }\n\n private getLogFilePath(operation: string, image?: string): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n return path.resolve(LOGS_DIR, `${image || this.image}-${operation}-${timestamp}.log`);\n }\n\n private getSystemArchitecture(): string {\n const arch = os.arch();\n switch (arch) {\n case 'arm':\n case 'arm64':\n return 'arm64';\n case 'x64':\n return 'amd64';\n default:\n return arch;\n }\n }\n\n private spawnProcess(command: string, args: string[], operation: string, image?: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const proc = spawn(command, args);\n // Ensure logs directory exists before creating write stream\n this.ensureLogsDir();\n\n const logFile = this.getLogFilePath(operation, image);\n\n const logStream = fs.createWriteStream(logFile, { flags: 'a' });\n const consoleBuffer: string[] = [];\n\n const processOutput = (data: Buffer, isError = false) => {\n const lines = data.toString().split('\\n');\n\n // Write to log file\n logStream.write(data);\n\n // Update console buffer\n for (const line of lines) {\n if (line.trim()) {\n consoleBuffer.push(line);\n // Keep only the last MAX_CONSOLE_LINES lines\n if (consoleBuffer.length > MAX_CONSOLE_LINES) {\n consoleBuffer.shift();\n }\n\n // Clear console and print the buffer\n console.clear();\n console.log(`Latest ${MAX_CONSOLE_LINES} lines (full log at ${logFile}):`);\n console.log('-'.repeat(50));\n for (const bufferedLine of consoleBuffer) {\n if (isError) {\n console.error(bufferedLine);\n } else {\n console.log(bufferedLine);\n }\n }\n }\n }\n };\n\n proc.stdout.on('data', (data) => processOutput(data));\n proc.stderr.on('data', (data) => processOutput(data, true));\n\n proc.on('close', (code) => {\n logStream.end();\n if (code === 0) {\n console.log(`\\nOperation completed. Full log available at: ${logFile}`);\n resolve();\n } else {\n reject(new Error(`Process exited with code ${code}. Check log file: ${logFile}`));\n }\n });\n\n proc.on('error', (err) => {\n logStream.end();\n reject(err);\n });\n });\n }\n\n /**\n * Set Docker credentials\n * @param username Docker username\n * @param registry Docker registry\n */\n setCredentials(username: string, registry?: string): void {\n this.username = username;\n if (registry) {\n this.registry = registry;\n }\n }\n\n /**\n * Build a Docker image\n * @param dockerfile Path to Dockerfile\n * @param tag Tag for the image\n * @returns Success status\n */\n async buildImage(dockerfile: string, tag: string): Promise<boolean> {\n try {\n const arch = this.getSystemArchitecture();\n const fullImageName = `${this.username}/${this.image}:${tag}`;\n\n const spinner = logger.startSpinner(`Building Docker image ${this.username}/${this.image}:${tag}`);\n\n // Ensure the Dockerfile exists\n validateFileExists(dockerfile);\n\n const buildArgs = ['build', '-t', fullImageName, '-f', dockerfile];\n\n if (arch === 'arm64') {\n console.log('Detected arm64 architecture, using --platform linux/amd64');\n buildArgs.push('--platform', 'linux/amd64');\n }\n\n // Build the image\n buildArgs.push('.');\n\n await this.spawnProcess('docker', buildArgs, 'build', this.image);\n\n spinner.stop(true, `Docker image ${fullImageName} built successfully`);\n return true;\n } catch (error) {\n logger.error(`Failed to build Docker image: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n /**\n * Push a Docker image to Docker Hub\n * @param imageName Full image name (e.g. username/image:tag)\n * @returns Success status\n */\n async pushImage(imageName: string): Promise<boolean> {\n try {\n const spinner = logger.startSpinner(`Pushing Docker image ${imageName} to Docker Hub`);\n\n // Check if user is logged in\n const credentials = await getDockerCredentials();\n if (!credentials) {\n spinner.stop(false);\n throw new Error('Docker credentials not found. Please log in first with \"phala docker login\"');\n }\n\n const fullImageName = imageName;\n console.log(`Pushing image ${fullImageName} to Docker Hub...`);\n\n await this.spawnProcess('docker', ['push', fullImageName], 'push', imageName.replace(/.*\\/+([\\w-]+):.*$/g, '$1'));\n\n spinner.stop(true, `Docker image ${fullImageName} pushed successfully`);\n return true;\n } catch (error) {\n logger.error(`Failed to push Docker image: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n\n /**\n * Login to Docker Hub\n * @param username Docker username\n * @param password Docker password\n * @param registry Docker registry\n * @returns Success status\n */\n async login(username: string, password?: string, registry?: string): Promise<boolean> {\n try {\n const spinner = logger.startSpinner(`Logging in to Docker Hub as ${username}`);\n\n // Check if already logged in\n const loggedIn = await this.checkLogin();\n if (loggedIn) {\n spinner.stop(true, 'Already logged in to Docker Hub');\n this.setCredentials(username, registry);\n return true;\n }\n\n // Verify password was provided\n if (!password) {\n spinner.stop(false);\n throw new Error('Password is required for Docker login');\n }\n\n // Login to Docker with timeout protection\n try {\n const loginProcess = execa('docker', [\n 'login',\n ...(registry ? [registry] : []),\n '-u',\n username,\n '--password-stdin'\n ], {\n input: password,\n timeout: 10000 // 10 second timeout\n });\n\n await loginProcess;\n } catch (loginError) {\n if (loginError.timedOut) {\n spinner.stop(false);\n throw new Error('Docker login timed out. Please check your credentials and try again.');\n }\n throw loginError;\n }\n\n spinner.stop(true, 'Logged in to Docker Hub successfully');\n this.setCredentials(username, registry);\n return true;\n } catch (error) {\n logger.error(`Failed to login to Docker Hub: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n /**\n * Check if Docker is logged in\n * @returns Success status\n */\n async checkLogin(): Promise<boolean> {\n try {\n // Instead of checking via \"docker login\" which is interactive,\n // check if the Docker config.json file exists and contains auth data\n const homeDir = os.homedir();\n const dockerConfigPath = path.join(homeDir, '.docker', 'config.json');\n \n if (!fs.existsSync(dockerConfigPath)) {\n return false;\n }\n \n // Read the docker config file\n const dockerConfig = JSON.parse(fs.readFileSync(dockerConfigPath, 'utf-8'));\n \n // Check if the config has auths data\n return !!(dockerConfig?.auths && Object.keys(dockerConfig.auths).length > 0);\n } catch (error) {\n logger.debug(`Docker login check failed: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n /**\n * Build a Docker Compose file\n * @param imageName Name of the image\n * @param envFile Optional path to environment file\n * @param version Version of the template to use\n * @returns Path to the generated Docker Compose file\n */\n async buildComposeFile(imageName: string, envFile?: string, templateType?: string): Promise<string> {\n if (!this.username) {\n throw new Error('Docker Hub username is required for building compose file');\n }\n\n const template = (templateType === 'eliza') ? DOCKER_COMPOSE_ELIZA_V2_TEMPLATE : DOCKER_COMPOSE_BASIC_TEMPLATE;\n\n // Validate template structure\n const validatedTemplate = ComposeTemplateSchema.parse({ template });\n\n // Ensure compose files directory exists\n const composePath = path.resolve(COMPOSE_FILES_DIR);\n \n // Create directory if it doesn't exist\n if (!fs.existsSync(composePath)) {\n logger.info(`Creating directory: ${composePath}`);\n fs.mkdirSync(composePath, { recursive: true });\n }\n\n let envVars: string[] = [];\n \n // Only parse env file if it's provided\n if (envFile) {\n // Parse env file to get variable names\n const envContent = fs.readFileSync(envFile, 'utf-8');\n envVars = envContent\n .split('\\n')\n .filter(line => line && !line.startsWith('#'))\n .map(line => {\n // Remove inline comments\n const commentIndex = line.indexOf('#');\n if (commentIndex > 0) {\n line = line.substring(0, commentIndex).trim();\n }\n return line.trim();\n })\n .filter(line => line.includes('='))\n .map(line => {\n const [key, value] = line.split('=', 2);\n const trimmedKey = key.trim();\n const trimmedValue = value ? value.trim() : '';\n\n // Skip empty values\n if (trimmedValue === '') {\n return null;\n }\n\n // Keep the original key without any transformation\n return `${trimmedKey}=${trimmedKey}`; // Create KEY=KEY format\n })\n .filter(Boolean as unknown as ((value: string | null) => value is string)); // Remove null entries\n }\n\n // Create full image name with username\n const fullImageName = imageName;\n\n // Compile template with data\n const compiledTemplate = Handlebars.compile(validatedTemplate.template, { noEscape: true });\n const composeContent = compiledTemplate({\n imageName: fullImageName,\n envVars: envVars.map(env => env.replace(/=.*/, `=\\${${env.split('=')[0]}}`))\n });\n\n // Write the docker-compose file with standardized name in the compose directory\n const composeFile = path.join(\n composePath,\n `${imageName.replace(/.*\\/+([\\w-]+):.*$/g, \"$1\")}-tee-compose.yaml`,\n );\n fs.writeFileSync(composeFile, composeContent);\n\n logger.success(`Backup of docker compose file created at: ${composeFile}`);\n return composeFile;\n }\n\n /**\n * Run a Docker Compose file locally\n * @param composePath Path to Docker Compose file\n * @param envFile Path to environment file\n * @returns Success status\n */\n async runComposeLocally(composePath: string, envFile?: string): Promise<boolean> {\n try {\n // TODO: Update log when optimized simulator is implemented\n const spinner = logger.startSpinner(`Running Docker Compose file at ${composePath}`);\n\n // Ensure the Docker Compose file exists\n validateFileExists(composePath);\n\n // Build the command arguments\n const composeArgs = [\n '-f',\n composePath,\n 'up',\n '-d'\n ];\n\n // Only add env-file if it's provided\n if (envFile) {\n // Ensure the environment file exists\n validateFileExists(envFile);\n composeArgs.splice(2, 0, '--env-file', envFile);\n }\n\n // Run the Docker Compose file\n await execAsync(`docker compose ${composeArgs.join(' ')}`);\n\n spinner.stop(true, 'Docker Compose file running successfully');\n return true;\n } catch (error) {\n logger.error(`Failed to run Docker Compose file: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n /**\n * Run the TEE simulator\n * @param image Simulator image\n * @returns Success status\n */\n async runSimulator(image: string, port: string): Promise<boolean> {\n try {\n logger.info(`Running TEE simulator with image ${image}`);\n\n logger.info('Pulling latest simulator image...');\n await execAsync(`docker pull ${image}`);\n\n logger.info('Starting simulator in background...');\n const { stdout } = await execAsync(`docker run -d --name tee-simulator --rm -p ${port}:${port} ${image}`);\n const containerId = stdout.trim();\n\n logger.success(`TEE simulator running successfully. Container ID: ${containerId}`);\n logger.break();\n logger.break();\n logger.info('Useful commands:');\n logger.info(`- View logs: docker logs -f ${containerId}`);\n logger.info(`- Stop simulator: docker stop ${containerId}`);\n\n setSimulatorEndpointEnv(`http://localhost:${port}`);\n \n return true;\n } catch (error) {\n logger.error(`Failed to run TEE simulator: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n /**\n * Stop the TEE simulator\n * @returns Success status\n */\n async stopSimulator(): Promise<boolean> {\n try {\n const spinner = logger.startSpinner('Stopping TEE simulator...');\n\n // Stop the simulator\n await execAsync('docker stop tee-simulator');\n await deleteSimulatorEndpointEnv();\n\n spinner.stop(true, 'TEE simulator stopped successfully');\n return true;\n } catch (error) {\n logger.error(`Failed to stop TEE simulator: ${error instanceof Error ? error.message : String(error)}`);\n return false;\n }\n }\n\n /**\n * List local Docker images and their tags\n * @returns Array of objects with image name and tag\n */\n static async listLocalImages(): Promise<Array<{ imageName: string}>> {\n try {\n // Query Docker for local images in format that outputs repository and tag\n const { stdout } = await execAsync('docker images --format \"{{.Repository}}:{{.Tag}}\"');\n const credentials = await getDockerCredentials();\n const username = credentials?.username;\n // Parse the output and filter out any <none> tags or images\n const imageList = stdout.split('\\n')\n .filter(line => line && !line.includes('<none>'))\n .filter(line => line.includes(`${username}/`))\n .map(line => {\n const imageName = line;\n return { imageName };\n });\n\n return imageList;\n } catch (error) {\n logger.error(`Failed to list local Docker images: ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n }\n}\n\n","import inquirer from 'inquirer';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from './logger';\n\n/**\n * Validates that a file exists at the given path\n * @param filePath Path to the file to validate\n * @param basePath Optional base path to resolve relative paths against (defaults to process.cwd())\n * @returns True if the file exists, throws an error if not\n * @throws Error if the file does not exist\n */\nexport function validateFileExists(\n filePath: string,\n basePath: string = process.cwd()\n): boolean {\n const resolvedPath = path.resolve(basePath, filePath);\n if (!fs.existsSync(resolvedPath)) {\n throw new Error(`File not found at ${resolvedPath}`);\n }\n return true;\n}\n\n/**\n * Prompts the user for a file path and validates that the file exists\n * @param message The prompt message to display\n * @param defaultValue The default value for the prompt\n * @param name The name of the prompt (used as property name in the returned object)\n * @param basePath Optional base path to resolve relative paths against (defaults to process.cwd())\n * @returns The validated file path\n */\nexport async function promptForFile(\n message: string,\n defaultValue: string,\n name = 'file',\n basePath: string = process.cwd()\n): Promise<string> {\n const response = await inquirer.prompt([\n {\n type: 'input',\n name,\n message,\n default: defaultValue,\n validate: (input) => {\n const filePath = path.resolve(basePath, input);\n if (!fs.existsSync(filePath)) {\n return `File not found at ${filePath}`;\n }\n return true;\n }\n }\n ]);\n\n return response[name];\n}\n\nexport function detectFileInCurrentDir(\n possibleFiles: string[],\n logMessage?: string\n): string | undefined {\n for (const file of possibleFiles) {\n const filePath = path.join(process.cwd(), file);\n if (fs.existsSync(filePath)) {\n if (logMessage) {\n logger.info(logMessage.replace('{path}', filePath));\n } else {\n logger.info(`File detected: ${filePath}`);\n }\n return file;\n }\n }\n return undefined;\n}","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as os from 'node:os';\nimport { execSync, spawn, type StdioOptions } from 'node:child_process';\nimport * as net from 'node:net';\nimport { logger } from './logger';\n\n// Configuration for simulator\nconst SIMULATOR_CONFIG = {\n version: '0.1.4',\n baseUrl: 'https://github.com/Leechael/tappd-simulator/releases/download/v0.1.4',\n installDir: path.join(os.homedir(), '.phala-cloud', 'tappd-simulator'),\n // Default log file path\n defaultLogPath: path.join(os.homedir(), '.phala-cloud', 'logs', 'tappd-simulator.log'),\n platforms: {\n darwin: {\n filename: 'tappd-simulator-0.1.4-aarch64-apple-darwin.tgz',\n extractedFolder: 'tappd-simulator-0.1.4-aarch64-apple-darwin',\n socketArg: 'unix:/tmp/tappd.sock'\n },\n linux: {\n filename: 'tappd-simulator-0.1.4-x86_64-linux-musl.tgz',\n extractedFolder: 'tappd-simulator-0.1.4-x86_64-linux-musl',\n socketArg: 'unix:/tmp/tappd.sock'\n },\n win32: {\n filename: 'tappd-simulator-0.1.4-x86_64-pc-windows-msvc.tgz',\n extractedFolder: 'tappd-simulator-0.1.4-x86_64-pc-windows-msvc',\n socketArg: '127.0.0.1:8090'\n }\n }\n};\n\n/**\n * Check if the simulator is already installed\n * @returns boolean indicating if simulator is installed\n */\nexport function isSimulatorInstalled(): boolean {\n try {\n // Check if the main installation directory exists\n if (!fs.existsSync(SIMULATOR_CONFIG.installDir)) {\n return false;\n }\n\n // Get platform-specific folder name\n const platform = os.platform() as 'darwin' | 'linux' | 'win32';\n if (!SIMULATOR_CONFIG.platforms[platform]) {\n throw new Error(`Unsupported platform: ${platform}`);\n }\n\n const extractedFolderPath = path.join(\n SIMULATOR_CONFIG.installDir,\n SIMULATOR_CONFIG.platforms[platform].extractedFolder\n );\n\n // Check if the extracted folder exists\n if (!fs.existsSync(extractedFolderPath)) {\n return false;\n }\n\n // Check if the executable exists\n const executableName = platform === 'win32' ? 'tappd-simulator.exe' : 'tappd-simulator';\n const executablePath = path.join(extractedFolderPath, executableName);\n return fs.existsSync(executablePath);\n } catch (error) {\n logger.error('Error checking if simulator is installed:', error);\n return false;\n }\n}\n\n/**\n * Get the current platform\n * @returns The current platform: 'darwin', 'linux', or 'win32'\n * @throws Error if the platform is not supported\n */\nexport function getPlatform(): 'darwin' | 'linux' | 'win32' {\n const platform = os.platform() as 'darwin' | 'linux' | 'win32';\n if (!SIMULATOR_CONFIG.platforms[platform]) {\n throw new Error(`Unsupported platform: ${platform}. Only darwin, linux, and win32 are supported.`);\n }\n return platform;\n}\n\n/**\n * Install the simulator based on the current platform\n * @param progressCallback Optional callback to report progress\n * @returns Promise that resolves when installation is complete\n */\nexport async function installSimulator(\n progressCallback?: (message: string) => void\n): Promise<void> {\n const log = (message: string) => {\n logger.info(message);\n if (progressCallback) progressCallback(message);\n };\n\n try {\n const platform = getPlatform();\n const platformConfig = SIMULATOR_CONFIG.platforms[platform];\n \n // Create installation directory if it doesn't exist\n if (!fs.existsSync(SIMULATOR_CONFIG.installDir)) {\n logger.info(`Creating installation directory at ${SIMULATOR_CONFIG.installDir}`);\n fs.mkdirSync(SIMULATOR_CONFIG.installDir, { recursive: true });\n }\n\n // Change to the installation directory\n process.chdir(SIMULATOR_CONFIG.installDir);\n \n // Download the simulator\n const downloadUrl = `${SIMULATOR_CONFIG.baseUrl}/${platformConfig.filename}`;\n logger.info(`Downloading simulator from ${downloadUrl}`);\n execSync(`wget ${downloadUrl}`, { stdio: 'inherit' });\n \n // Extract the archive\n logger.info(`Extracting ${platformConfig.filename}`);\n execSync(`tar -xvf ${platformConfig.filename}`, { stdio: 'inherit' });\n \n logger.success('Simulator installation completed successfully');\n } catch (error) {\n logger.error('Error installing simulator:', error);\n throw new Error(`Failed to install simulator: ${error}`);\n }\n}\n\n/**\n * Run the simulator\n * @param options Configuration options for running the simulator\n * @returns A child process representing the running simulator\n */\nexport async function runSimulator(options: {\n background?: boolean;\n logToFile?: boolean;\n logFilePath?: string;\n} = {}): Promise<ReturnType<typeof spawn>> {\n try {\n const platform = getPlatform();\n const platformConfig = SIMULATOR_CONFIG.platforms[platform];\n const extractedFolderPath = path.join(\n SIMULATOR_CONFIG.installDir,\n platformConfig.extractedFolder\n );\n \n // Change to the extracted folder directory\n process.chdir(extractedFolderPath);\n \n // Start the simulator\n const executableName = platform === 'win32' ? 'tappd-simulator.exe' : './tappd-simulator';\n \n // Default options\n const runOptions = {\n background: options.background ?? true,\n logToFile: options.logToFile ?? true,\n logFilePath: options.logFilePath ?? SIMULATOR_CONFIG.defaultLogPath\n };\n \n // Create log directory if it doesn't exist\n if (runOptions.logToFile) {\n const logDir = path.dirname(runOptions.logFilePath);\n if (!fs.existsSync(logDir)) {\n fs.mkdirSync(logDir, { recursive: true });\n }\n logger.info(`Simulator logs will be written to: ${runOptions.logFilePath}`);\n }\n \n logger.info(`Starting simulator with: ${executableName} -l ${platformConfig.socketArg}`);\n \n // Configure stdio based on logging preferences\n let stdio: StdioOptions = 'inherit';\n let outputStream: fs.WriteStream = null;\n \n if (runOptions.logToFile) {\n // Create/open the log file for appending\n outputStream = fs.createWriteStream(runOptions.logFilePath, { flags: 'a' });\n \n // Use the stream for both stdout and stderr\n stdio = ['ignore', outputStream, outputStream];\n }\n \n // Run the simulator\n const simulatorProcess = spawn(executableName, ['-l', platformConfig.socketArg], {\n stdio,\n shell: platform === 'win32', // Use shell on Windows\n detached: runOptions.background // Detach process when running in background\n });\n \n // Write startup entry to log file with timestamp\n if (outputStream) {\n const timestamp = new Date().toISOString();\n outputStream.write(`\\n[${timestamp}] Simulator started\\n`);\n }\n \n // If running in background, unref to allow the parent process to exit\n if (runOptions.background) {\n simulatorProcess.unref();\n logger.success('Simulator is running in the background');\n }\n \n await setSimulatorEndpointEnv();\n return simulatorProcess;\n } catch (error) {\n logger.error('Error running simulator:', error);\n throw new Error(`Failed to run simulator: ${error}`);\n }\n}\n\n/**\n * Ensures the simulator is installed and running\n * @param options Configuration options for running the simulator\n * @returns A promise that resolves to a child process representing the running simulator\n */\nexport async function ensureSimulatorRunning(options: {\n background?: boolean;\n logToFile?: boolean;\n logFilePath?: string;\n} = {}): Promise<ReturnType<typeof spawn>> {\n if (!isSimulatorInstalled()) {\n logger.info('Simulator not installed. Installing now...');\n await installSimulator((message) => logger.info(`Installation progress: ${message}`));\n }\n \n if (await isSimulatorRunning()) {\n logger.info('Simulator is already running');\n return null;\n }\n \n logger.info('Starting simulator...');\n return await runSimulator(options);\n}\n\n/**\n * Check if the simulator is currently running\n * For Unix platforms (Darwin/Linux), checks if the Unix socket exists and is accessible\n * For Windows, tries to connect to the TCP port the simulator should be listening on\n * @returns Promise<boolean> indicating if the simulator is running\n */\nexport async function isSimulatorRunning(): Promise<boolean> {\n try {\n const platform = getPlatform();\n const platformConfig = SIMULATOR_CONFIG.platforms[platform];\n \n if (platform === 'darwin' || platform === 'linux') {\n // For Unix platforms, check if the socket file exists and is accessible\n const socketPath = '/tmp/tappd.sock';\n \n // Check if the socket file exists\n if (!fs.existsSync(socketPath)) {\n return false;\n }\n \n // Try to connect to the socket to verify it's active\n return new Promise<boolean>((resolve) => {\n const client = net.createConnection({ path: socketPath })\n .on('connect', () => {\n client.end();\n resolve(true);\n })\n .on('error', () => {\n resolve(false);\n });\n \n // Set timeout to avoid hanging if socket exists but nothing is listening\n setTimeout(() => {\n client.end();\n resolve(false);\n }, 1000);\n });\n } \n if (platform === 'win32') {\n // For Windows, try to connect to the TCP port\n const host = '127.0.0.1';\n const port = 8090;\n \n return new Promise<boolean>((resolve) => {\n const client = net.createConnection({ host, port })\n .on('connect', () => {\n client.end();\n resolve(true);\n })\n .on('error', () => {\n resolve(false);\n });\n \n // Set timeout to avoid hanging\n setTimeout(() => {\n client.end();\n resolve(false);\n }, 1000);\n });\n }\n \n return false;\n } catch (error) {\n logger.error('Error checking if simulator is running:', error);\n return false;\n }\n}\n\n/**\n * Stops the simulator if it's running\n * @returns Promise<boolean> indicating if the simulator was successfully stopped\n */\nexport async function stopSimulator(): Promise<boolean> {\n try {\n const platform = getPlatform();\n \n if (!await isSimulatorRunning()) {\n logger.info('Simulator is not running');\n return true;\n }\n \n logger.info('Stopping simulator...');\n \n if (platform === 'win32') {\n // For Windows, find the process listening on port 8080 and kill it\n execSync('for /f \"tokens=5\" %a in (\\'netstat -ano ^| findstr :8080\\') do taskkill /F /PID %a', { stdio: 'inherit' });\n } else {\n // For Unix platforms, find and kill the tappd-simulator process\n execSync('pkill -f tappd-simulator', { stdio: 'inherit' });\n }\n \n // Verify the simulator has stopped\n const stopped = !(await isSimulatorRunning());\n if (stopped) {\n logger.success('Simulator stopped successfully');\n } else {\n logger.error('Failed to stop simulator');\n }\n \n await deleteSimulatorEndpointEnv();\n return stopped;\n } catch (error) {\n logger.error('Error stopping simulator:', error);\n return false;\n }\n}\n\n/**\n * Gets the path to the simulator log file\n * @param customPath Optional custom log file path\n * @returns The path to the log file\n */\nexport function getSimulatorLogPath(customPath?: string): string {\n return customPath ?? SIMULATOR_CONFIG.defaultLogPath;\n}\n\n/**\n * Reads the recent logs from the simulator log file\n * @param options Options for reading logs\n * @returns Recent log content or null if log file doesn't exist\n */\nexport function getSimulatorLogs(options: {\n logFilePath?: string;\n maxLines?: number;\n} = {}): string | null {\n const logFilePath = options.logFilePath ?? SIMULATOR_CONFIG.defaultLogPath;\n const maxLines = options.maxLines ?? 100;\n \n try {\n if (!fs.existsSync(logFilePath)) {\n return null;\n }\n \n // Read the log file\n const logContent = fs.readFileSync(logFilePath, 'utf8');\n \n // Split by lines and get the most recent ones\n const lines = logContent.split('\\n');\n return lines.slice(-maxLines).join('\\n');\n } catch (error) {\n logger.error('Error reading simulator logs:', error);\n return null;\n }\n}\n\n/**\n * Gets the simulator endpoint URL based on the current platform\n * @returns The endpoint URL for the simulator\n */\nexport function getSimulatorEndpoint(): string {\n const platform = getPlatform();\n \n if (platform === 'win32') {\n return 'http://127.0.0.1:8090';\n }\n\n return 'unix:///tmp/tappd.sock';\n}\n\n/**\n * Sets the DSTACK_SIMULATOR_ENDPOINT environment variable based on the current platform\n * @param options Configuration options for setting the environment variable\n * @returns The endpoint URL that was set\n */\nexport async function setSimulatorEndpointEnv(endpoint?: string): Promise<string> {\n try {\n const simulatorEndpoint = getSimulatorEndpoint();\n // Set for the current Node.js process\n const envEndpoint = (endpoint) ? endpoint : simulatorEndpoint;\n await execSync(`export DSTACK_SIMULATOR_ENDPOINT=${envEndpoint}`);\n logger.success(`Setting DSTACK_SIMULATOR_ENDPOINT=${envEndpoint} for current process`);\n \n return endpoint;\n } catch (error) {\n logger.error('Error setting simulator endpoint environment variable:', error);\n throw new Error(`Failed to set simulator endpoint: ${error}`);\n }\n}\n\n/**\n * Deletes the DSTACK_SIMULATOR_ENDPOINT environment variable\n * @returns boolean indicating if deletion was successful\n */\nexport async function deleteSimulatorEndpointEnv(): Promise<boolean> {\n await execSync('unset DSTACK_SIMULATOR_ENDPOINT');\n logger.debug('Deleted DSTACK_SIMULATOR_ENDPOINT from current process');\n return true;\n}\n","import { Command } from 'commander';\nimport { DockerService } from '@/src/utils/docker';\nimport { getDockerCredentials } from '@/src/utils/credentials';\nimport { logger } from '@/src/utils/logger';\nimport path from 'node:path';\nimport inquirer from 'inquirer';\nimport fs from 'node:fs';\nimport { promptForFile } from '@/src/utils/prompts';\n\nexport const buildCommand = new Command()\n .name('build')\n .description('Build a Docker image')\n .option('-i, --image <image>', 'Image name')\n .option('-t, --tag <tag>', 'Image tag')\n .option('-f, --file <file>', 'Path to Dockerfile', 'Dockerfile')\n .action(async (options) => {\n try {\n // Get Docker credentials\n const credentials = await getDockerCredentials();\n \n if (!credentials) {\n logger.error('Docker information not found. Please login first with \"phala docker login\"');\n process.exit(1);\n }\n \n // Prompt for image name if not provided\n if (!options.image) {\n const response = await inquirer.prompt([\n {\n type: 'input',\n name: 'image',\n message: 'Enter the Docker image name:',\n validate: (input) => {\n if (!input.trim()) {\n return 'Image name is required';\n }\n return true;\n }\n }\n ]);\n \n options.image = response.image;\n }\n\n if (!options.tag) {\n const response = await inquirer.prompt([\n {\n type: 'input',\n name: 'tag',\n message: 'Enter the Docker image tag:',\n default: 'latest', // Add random hash later\n validate: (input) => {\n if (!input.trim()) {\n return 'Tag is required';\n }\n return true;\n }\n }\n ]);\n\n options.tag = response.tag;\n }\n\n // Prompt for Dockerfile path if the default doesn't exist\n const defaultPath = path.resolve(process.cwd(), options.file);\n if (!fs.existsSync(defaultPath)) {\n logger.info(`Default Dockerfile not found at ${defaultPath}`);\n \n options.file = await promptForFile(\n 'Enter the path to your Dockerfile:',\n 'Dockerfile',\n 'file'\n );\n }\n \n // Resolve the Dockerfile path\n const dockerfilePath = path.resolve(process.cwd(), options.file);\n \n // Build the image\n const dockerService = new DockerService(options.image, credentials.username, credentials.registry);\n const success = await dockerService.buildImage(dockerfilePath, options.tag);\n \n if (!success) {\n logger.error('Failed to build Docker image');\n process.exit(1);\n }\n \n logger.success(`Docker image ${credentials.username}/${options.image}:${options.tag} built successfully`);\n } catch (error) {\n logger.error(`Failed to build Docker image: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { DockerService } from '@/src/utils/docker';\nimport { getDockerCredentials } from '@/src/utils/credentials';\nimport { logger } from '@/src/utils/logger';\nimport inquirer from 'inquirer';\n\nexport const pushCommand = new Command()\n .name('push')\n .description('Push a Docker image to Docker Hub')\n .option('-i, --image <image>', 'Full image name (e.g. username/image:tag)')\n .action(async (options) => {\n try {\n // Get Docker credentials\n const credentials = await getDockerCredentials();\n \n if (!credentials) {\n logger.error('Docker information not found. Please login first with \"phala docker login\"');\n process.exit(1);\n }\n\n let imageName = options.image;\n\n // If image name is not provided, list local images and prompt user to select\n if (!imageName) {\n const localImages = await DockerService.listLocalImages();\n \n if (localImages.length === 0) {\n logger.error('No local Docker images found. Please build an image first with \"phala docker build\"');\n process.exit(1);\n }\n\n // If no image specified, prompt to select from available images\n if (!imageName) {\n // Get unique image names\n const uniqueImageNames = Array.from(new Set(localImages.map(img => img.imageName)));\n \n const { selectedImage } = await inquirer.prompt([\n {\n type: 'list',\n name: 'selectedImage',\n message: 'Select an image to push:',\n choices: uniqueImageNames\n }\n ]);\n \n imageName = selectedImage;\n }\n }\n \n // Push the image\n const dockerService = new DockerService('', credentials.username, credentials.registry);\n const success = await dockerService.pushImage(imageName);\n \n if (!success) {\n logger.error('Failed to push Docker image');\n process.exit(1);\n }\n \n logger.success(`Docker image ${imageName} pushed successfully`);\n } catch (error) {\n logger.error(`Failed to push Docker image: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { DockerService } from '@/src/utils/docker';\nimport { getDockerCredentials } from '@/src/utils/credentials';\nimport { logger } from '@/src/utils/logger';\nimport inquirer from 'inquirer';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { validateFileExists } from '@/src/utils/prompts';\n\nexport const generateCommand = new Command()\n .name('generate')\n .description('Generate a Docker Compose file')\n .option('-i, --image <imageName>', 'Docker image name to use in the compose file (e.g. phala/phala-cloud)')\n .option('-e, --env-file <envFile>', 'Path to environment variables file')\n .option('-o, --output <output>', 'Output path for generated docker-compose.yml')\n .option('--template <template>', 'Template to use for the generated docker-compose.yml', )\n .action(async (options) => {\n try {\n // Get Docker credentials to create the Docker service\n const credentials = await getDockerCredentials();\n if (!credentials || !credentials.username) {\n logger.error('Docker Hub username not found. Please login first with `phala docker login`');\n process.exit(1);\n }\n\n let imageName = options.image;\n\n if (!imageName) {\n // If image name is not provided, list local images and prompt user to select\n const localImages = await DockerService.listLocalImages();\n\n if (localImages.length === 0) {\n logger.error(\n 'No local Docker images found. Please build an image first with \"phala docker build\"',\n );\n process.exit(1);\n }\n\n // If no image specified, prompt to select from available images\n if (!imageName) {\n // Get unique image names\n const uniqueImageNames = Array.from(\n new Set(localImages.map((img) => img.imageName)),\n );\n\n const { selectedImage } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"selectedImage\",\n message: \"Select an image to use in the compose file:\",\n choices: uniqueImageNames,\n },\n ]);\n\n imageName = selectedImage;\n }\n }\n \n // Get environment file path from options or prompt\n let envFilePath = options.envFile;\n if (!envFilePath) {\n // Check if .env exists in current directory\n const defaultEnvPath = path.join(process.cwd(), '.env');\n const hasDefaultEnv = fs.existsSync(defaultEnvPath);\n\n if (hasDefaultEnv) {\n const { useDefault } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'useDefault',\n message: 'Use .env file in current directory?',\n default: true\n }\n ]);\n\n if (useDefault) {\n envFilePath = defaultEnvPath;\n }\n }\n\n // If still no env file path, prompt for it\n if (!envFilePath) {\n const { envPath } = await inquirer.prompt([\n {\n type: 'input',\n name: 'envPath',\n message: 'Enter path to environment variables file:',\n validate: (input) => {\n try {\n validateFileExists(input);\n return true;\n } catch (error) {\n return `File not found: ${input}`;\n }\n }\n }\n ]);\n envFilePath = envPath;\n }\n } else {\n // Validate the provided env file path\n try {\n validateFileExists(envFilePath);\n } catch (error) {\n logger.error(`File not found: ${envFilePath}`);\n process.exit(1);\n }\n }\n\n // Get output path from options or set default\n let outputPath = options.output;\n if (!outputPath) {\n outputPath = path.join(process.cwd(), 'docker-compose.yml');\n \n // If file already exists, confirm overwrite\n if (fs.existsSync(outputPath)) {\n const { confirmOverwrite } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirmOverwrite',\n message: `File ${outputPath} already exists. Overwrite?`,\n default: false\n }\n ]);\n if (!confirmOverwrite) {\n const { customPath } = await inquirer.prompt([\n {\n type: 'input',\n name: 'customPath',\n message: 'Enter alternative output path:',\n default: path.join(process.cwd(), 'docker-generated-compose.yml')\n }\n ]);\n outputPath = customPath;\n }\n }\n }\n \n // Create a DockerService instance\n const dockerService = new DockerService('', credentials.username, credentials.registry);\n\n // Generate the Docker Compose file\n if (envFilePath) {\n logger.info(`Generating Docker Compose file for ${imageName} using env file: ${envFilePath}`);\n } else {\n logger.info(`Generating Docker Compose file for ${imageName} without env file`);\n }\n const composePath = await dockerService.buildComposeFile(imageName, envFilePath, options.template);\n \n // Copy the generated file to the output path if needed\n if (composePath !== outputPath) {\n // Ensure the output directory exists\n const outputDir = path.dirname(outputPath);\n if (!fs.existsSync(outputDir)) {\n logger.info(`Creating directory: ${outputDir}`);\n fs.mkdirSync(outputDir, { recursive: true });\n }\n \n fs.copyFileSync(composePath, outputPath);\n }\n \n logger.success(`Docker Compose file generated successfully: ${outputPath}`);\n } catch (error) {\n logger.error(`Failed to generate Docker Compose file: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { startCommand } from './start';\nimport { stopCommand } from './stop';\n\nexport const simulatorCommands = new Command()\n .name('simulator')\n .description('TEE simulator commands')\n .addCommand(startCommand)\n .addCommand(stopCommand);\n","import { Command } from 'commander';\nimport { DockerService } from '@/src/utils/docker';\nimport { logger } from '@/src/utils/logger';\nimport { TEE_SIMULATOR } from '@/src/utils/constants';\nimport { installSimulator, isSimulatorInstalled, isSimulatorRunning, runSimulator } from '@/src/utils/simulator';\n\nexport const startCommand = new Command()\n .name('start')\n .description('Start the TEE simulator')\n .option('-i, --image <image>', 'Simulator image', TEE_SIMULATOR)\n .option('-p, --port <port>', 'Simulator port (default: 8090)', '8090')\n .option('-t, --type <type>', 'Simulator type (docker, native)', 'docker')\n .action(async (options) => {\n try {\n if (options.type === 'docker') {\n // Start the simulator\n const dockerService = new DockerService('');\n const success = await dockerService.runSimulator(options.image, options.port);\n \n if (!success) {\n logger.error('Failed to start TEE simulator');\n process.exit(1);\n }\n } else if (options.type === 'native') {\n if (!isSimulatorInstalled()) {\n await installSimulator();\n }\n const running = await isSimulatorRunning();\n if (running) {\n logger.success('TEE simulator is already running');\n return;\n } else {\n const simulatorProcess = runSimulator();\n logger.success('TEE simulator started successfully');\n }\n } else {\n logger.error('Invalid simulator type');\n process.exit(1);\n }\n } catch (error) {\n logger.error(`Failed to start TEE simulator: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { DockerService } from '../../utils/docker';\nimport { logger } from '../../utils/logger';\nimport { stopSimulator } from '@/src/utils/simulator';\n\nexport const stopCommand = new Command()\n .name('stop')\n .description('Stop the TEE simulator')\n .option('-t, --type <type>', 'Simulator type (docker, native)', 'docker')\n .action(async (options) => {\n try {\n if (options.type === 'docker') {\n // Stop the simulator\n const dockerService = new DockerService('');\n const success = await dockerService.stopSimulator();\n\n if (!success) {\n logger.error('Failed to stop TEE simulator');\n process.exit(1);\n }\n } else if (options.type === 'native') {\n // Stop the native simulator\n const success = await stopSimulator();\n \n if (!success) {\n logger.error('Failed to stop TEE simulator');\n process.exit(1);\n }\n } else {\n logger.error('Invalid simulator type');\n process.exit(1);\n }\n } catch (error) {\n logger.error(`Failed to stop TEE simulator: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n });","import { Command } from 'commander';\nimport { listCommand } from './list';\nimport { getCommand } from './get';\nimport { startCommand } from './start';\nimport { stopCommand } from './stop';\nimport { restartCommand } from './restart';\nimport { attestationCommand } from './attestation';\nimport { createCommand } from './create';\nimport { deleteCommand } from './delete';\nimport { upgradeCommand } from './upgrade';\nimport { resizeCommand } from './resize';\nimport { replicateCommand } from './replicate';\nimport { commitProvisionCommand } from './commit-provision';\nimport { provisionCommand } from './provision';\nimport { upgradeProvisionCommand } from './upgrade-provision';\nimport { upgradeCommitCommand } from './upgrade-commit';\n\nexport const cvmsCommand = new Command()\n .name('cvms')\n .description('Manage Phala Confidential Virtual Machines (CVMs)')\n .addCommand(attestationCommand)\n .addCommand(createCommand)\n .addCommand(deleteCommand)\n .addCommand(getCommand)\n .addCommand(listCommand)\n .addCommand(startCommand)\n .addCommand(stopCommand)\n .addCommand(resizeCommand)\n .addCommand(restartCommand)\n .addCommand(upgradeCommand)\n .addCommand(replicateCommand)\n .addCommand(commitProvisionCommand)\n .addCommand(provisionCommand)\n .addCommand(upgradeProvisionCommand)\n .addCommand(upgradeCommitCommand);","import { Command } from 'commander';\nimport { getCvms } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { CLOUD_URL } from '@/src/utils/constants';\nimport chalk from 'chalk';\n\nexport const listCommand = new Command()\n .name('list')\n .alias('ls')\n .description('List all CVMs')\n .option('-j, --json', 'Output in JSON format')\n .action(async (options) => {\n try {\n const spinner = logger.startSpinner('Fetching CVMs');\n \n const cvms = await getCvms();\n \n spinner.stop(true);\n \n if (!cvms || cvms.length === 0) {\n logger.info('No CVMs found');\n return;\n }\n \n if (options.json) {\n console.log(JSON.stringify(cvms, null, 2));\n return;\n }\n \n for (const cvm of cvms) {\n logger.keyValueTable({\n Name: cvm.name,\n \"App ID\": `app_${cvm.hosted.app_id}`,\n \"CVM ID\": cvm.hosted.id.replace(/-/g, ''),\n \"Region\": cvm.node.region_identifier,\n Status:\n cvm.status === \"running\"\n ? chalk.green(cvm.status)\n : cvm.status === \"stopped\"\n ? chalk.red(cvm.status)\n : chalk.yellow(cvm.status),\n \"Node Info URL\": cvm.hosted.app_url,\n \"App URL\": `${CLOUD_URL}/dashboard/cvms/${cvm.hosted.id.replace(/-/g, '')}`,\n });\n logger.break();\n }\n logger.success(`Found ${cvms.length} CVMs`);\n logger.break();\n logger.info(`Go to ${CLOUD_URL}/dashboard/ to view your CVMs`);\n } catch (error) {\n logger.error(`Failed to list CVMs: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { checkCvmExists, getCvmByAppId, getCvms, selectCvm } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { CLOUD_URL } from '@/src/utils/constants';\nimport chalk from 'chalk';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\n\nexport const getCommand = new Command()\n .name('get')\n .description('Get details of a CVM')\n .argument('[app-id]', 'App ID of the CVM (optional)')\n .option('-j, --json', 'Output in JSON format')\n .action(async (appId, options) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n \n const spinner = logger.startSpinner(`Fetching CVM with App ID app_${resolvedAppId}`);\n \n const cvm = await getCvmByAppId(resolvedAppId);\n \n spinner.stop(true);\n logger.break();\n \n if (!cvm) {\n logger.error(`CVM with App ID app_${resolvedAppId} not found`);\n process.exit(1);\n }\n \n if (options.json) {\n console.log(JSON.stringify(cvm, null, 2));\n return;\n }\n \n // Display additional details if available\n logger.keyValueTable({\n 'Name': cvm.name,\n 'App ID': `app_${cvm.app_id}`,\n 'Status': (cvm.status === 'running') ? chalk.green(cvm.status) : (cvm.status === 'stopped') ? chalk.red(cvm.status) : chalk.yellow(cvm.status),\n 'vCPU': cvm.vcpu,\n 'Memory': `${cvm.memory} MB`,\n 'Disk Size': `${cvm.disk_size} GB`,\n 'Dstack Image': cvm.base_image,\n 'App URL': `${CLOUD_URL}/dashboard/cvms/app_${cvm.app_id}`\n });\n } catch (error) {\n logger.error(`Failed to get CVM details: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { selectCvm, checkCvmExists } from \"@/src/api/cvms\";\nimport { logger } from \"./logger\";\n\n/**\n * Resolves a CVM App ID either by prompting the user to select one if none is provided,\n * or by validating the provided App ID exists.\n *\n * @param appId Optional App ID to resolve\n * @returns The resolved App ID or undefined if none was selected/found\n */\nexport async function resolveCvmAppId(\n\tappId?: string,\n): Promise<string | undefined> {\n\tif (!appId) {\n\t\t// If no app ID is provided, prompt user to select one\n\t\tconst selectedCvm = await selectCvm();\n\t\tif (!selectedCvm) {\n\t\t\treturn undefined; // No CVMs found or user canceled\n\t\t}\n\t\treturn selectedCvm;\n\t}\n\t// Verify the provided App ID exists\n\treturn await checkCvmExists(appId);\n}","import { Command } from 'commander';\nimport { startCvm, selectCvm, checkCvmExists } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nexport const startCommand = new Command()\n .name('start')\n .description('Start a stopped CVM')\n .argument('[app-id]', 'App ID of the CVM (if not provided, a selection prompt will appear)')\n .action(async (appId) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n \n const spinner = logger.startSpinner(`Starting CVM with App ID app_${resolvedAppId}`);\n \n const response = await startCvm(resolvedAppId);\n \n spinner.stop(true);\n logger.break();\n \n const tableData = {\n 'CVM ID': response.id,\n 'Name': response.name,\n 'Status': response.status,\n 'App ID': `app_${response.app_id}`,\n };\n logger.keyValueTable(tableData, {\n borderStyle: 'rounded'\n });\n \n logger.break();\n logger.success(\n `Your CVM is being started. You can check the dashboard for more details:\\n${CLOUD_URL}/dashboard/cvms/app_${response.app_id}`);\n } catch (error) {\n logger.error(`Failed to start CVM: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { stopCvm, selectCvm, checkCvmExists } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nexport const stopCommand = new Command()\n .name('stop')\n .description('Stop a running CVM')\n .argument('[app-id]', 'App ID of the CVM (if not provided, a selection prompt will appear)')\n .action(async (appId) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n\n const spinner = logger.startSpinner(\n `Stopping CVM with App ID app_${resolvedAppId}`,\n );\n\n const response = await stopCvm(resolvedAppId);\n\n spinner.stop(true);\n logger.break();\n\n const tableData = {\n 'CVM ID': response.id,\n 'Name': response.name,\n 'Status': response.status,\n 'App ID': `app_${response.app_id}`,\n };\n logger.keyValueTable(tableData, {\n borderStyle: 'rounded'\n });\n\n logger.break();\n logger.success(\n `Your CVM is being stopped. You can check the dashboard for more details:\\n${CLOUD_URL}/dashboard/cvms/app_${response.app_id}`);\n \n } catch (error) {\n logger.error(`Failed to stop CVM: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { checkCvmExists, restartCvm, selectCvm } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nexport const restartCommand = new Command()\n .name('restart')\n .description('Restart a CVM')\n .argument('[app-id]', 'App ID of the CVM (if not provided, a selection prompt will appear)')\n .action(async (appId) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n\n const spinner = logger.startSpinner(\n `Restarting CVM with App ID app_${resolvedAppId}`,\n );\n\n const response = await restartCvm(resolvedAppId);\n\n spinner.stop(true);\n logger.break();\n\n const tableData = {\n 'CVM ID': response.id,\n 'Name': response.name,\n 'Status': response.status,\n 'App ID': `app_${response.app_id}`,\n 'App URL': response.app_url\n ? response.app_url\n : `${CLOUD_URL}/dashboard/cvms/app_${response.app_id}`,\n };\n logger.keyValueTable(tableData, {\n borderStyle: \"rounded\",\n });\n\n logger.break();\n logger.success(\n `Your CVM is being restarted. You can check the dashboard for more details:\\n${CLOUD_URL}/dashboard/cvms/app_${response.app_id}`);\n } catch (error) {\n logger.error(`Failed to restart CVM: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { checkCvmExists, getCvmAttestation, selectCvm } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport chalk from 'chalk';\nimport type { CvmAttestationResponse } from '@/src/api/types';\n\nexport const attestationCommand = new Command()\n .name('attestation')\n .description('Get attestation information for a CVM')\n .argument('[app-id]', 'CVM app ID (will prompt for selection if not provided)')\n .option('-j, --json', 'Output in JSON format')\n .action(async (appId?: string, options?: { json?: boolean }) => {\n try {\n let resolvedAppId: string;\n \n if (!appId) {\n logger.info('No CVM specified, fetching available CVMs...');\n const selectedCvm = await selectCvm();\n if (!selectedCvm) {\n return;\n }\n resolvedAppId = selectedCvm;\n } else {\n resolvedAppId = await checkCvmExists(appId);\n }\n\n const spinner = logger.startSpinner(`Fetching attestation information for CVM app_${resolvedAppId}...`);\n\n try {\n const attestationData: CvmAttestationResponse = await getCvmAttestation(resolvedAppId);\n spinner.stop(true);\n\n if (!attestationData || Object.keys(attestationData).length === 0) {\n logger.info('No attestation information found');\n return;\n }\n\n // If JSON output is requested, just print the raw response\n if (options?.json) {\n logger.info(JSON.stringify(attestationData, null, 2));\n return;\n }\n\n // Display the attestation summary\n logger.success('Attestation Summary:');\n const summaryData = {\n 'Status': attestationData.is_online ? chalk.green('Online') : chalk.red('Offline'),\n 'Public Access': attestationData.is_public ? chalk.green('Enabled') : chalk.yellow('Disabled'),\n 'Error': attestationData.error || 'None',\n 'Certificates': `${attestationData.app_certificates?.length || 0} found`\n };\n \n logger.keyValueTable(summaryData, {\n borderStyle: 'rounded'\n });\n\n // Display certificate information\n if (attestationData.app_certificates && attestationData.app_certificates.length > 0) {\n \n attestationData.app_certificates.forEach((cert, index) => {\n logger.break();\n logger.success(`Certificate #${index + 1} (${cert.position_in_chain === 0 ? 'End Entity' : 'CA'}):`);\n \n const certData = {\n 'Subject': `${cert.subject.common_name || 'Unknown'}${cert.subject.organization ? ` (${cert.subject.organization})` : ''}`,\n 'Issuer': `${cert.issuer.common_name || 'Unknown'}${cert.issuer.organization ? ` (${cert.issuer.organization})` : ''}`,\n 'Serial Number': cert.serial_number,\n 'Validity': `${new Date(cert.not_before).toLocaleString()} to ${new Date(cert.not_after).toLocaleString()}`,\n 'Fingerprint': cert.fingerprint,\n 'Signature Algorithm': cert.signature_algorithm,\n 'Is CA': cert.is_ca ? 'Yes' : 'No',\n 'Position in Chain': cert.position_in_chain\n };\n \n logger.keyValueTable(certData, {\n borderStyle: 'rounded'\n });\n \n // Skip displaying the quote as it's very large and mostly binary data\n });\n }\n\n // Display TCB info if available\n if (attestationData.tcb_info) {\n logger.break();\n logger.success('Trusted Computing Base (TCB) Information:');\n \n // Create a formatted version of the TCB info without the event log\n const tcbBasicInfo = {\n 'Mrtd': attestationData.tcb_info.mrtd,\n 'Rootfs Hash': attestationData.tcb_info.rootfs_hash,\n 'Rtmr0': attestationData.tcb_info.rtmr0,\n 'Rtmr1': attestationData.tcb_info.rtmr1,\n 'Rtmr2': attestationData.tcb_info.rtmr2,\n 'Rtmr3': attestationData.tcb_info.rtmr3,\n 'Event Log Entries': `${attestationData.tcb_info.event_log.length} entries`\n };\n \n // Display basic TCB info\n logger.keyValueTable(tcbBasicInfo, {\n borderStyle: 'rounded'\n });\n \n // Display event log entries separately if they exist\n if (attestationData.tcb_info.event_log && attestationData.tcb_info.event_log.length > 0) {\n logger.break();\n logger.success('Event Log (Showing entries to reproduce RTMR3):');\n \n // Show the first 5 entries\n const maxEntriesToShow = 5;\n const entries = attestationData.tcb_info.event_log\n .filter(entry => entry.event !== null && entry.event !== \"\")\n .map((entry) => ({\n 'Event': entry.event,\n 'IMR': entry.imr.toString(),\n 'Event Type': entry.event_type.toString(),\n 'Payload': entry.event_payload,\n }));\n \n // Display entries in a table format\n logger.table(entries, [\n { key: \"Event\", header: \"Event\", minWidth: 8 },\n { key: \"IMR\", header: \"IMR\", minWidth: 3 },\n { key: \"Event Type\", header: \"Type\", minWidth: 8 },\n { key: \"Payload\", header: \"Payload\", minWidth: 25 },\n ]);\n \n if (attestationData.tcb_info.event_log.length > maxEntriesToShow) {\n logger.info('To see all full attestation data, use --json');\n }\n logger.break();\n logger.success('To reproduce RTMR3, use the tool at https://rtmr3-calculator.vercel.app/');\n }\n }\n } catch (error) {\n spinner.stop(false);\n throw error;\n }\n } catch (error) {\n logger.error(`Failed to get attestation information: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n","import { Command } from 'commander';\nimport { createCvm, getPubkeyFromCvm } from '@/src/api/cvms';\nimport { getTeepods } from '@/src/api/teepods';\nimport { logger } from '@/src/utils/logger';\nimport type { TEEPod, Image } from '@/src/api/types';\nimport { DEFAULT_VCPU, DEFAULT_MEMORY, DEFAULT_DISK_SIZE, CLOUD_URL, DEFAULT_IMAGE } from '@/src/utils/constants';\nimport { encryptEnvVars } from '@phala/dstack-sdk/encrypt-env-vars';\nimport type { EnvVar } from '@phala/dstack-sdk/encrypt-env-vars';\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport inquirer from 'inquirer';\nimport { parseEnv } from '@/src/utils/secrets';\nimport { detectFileInCurrentDir, promptForFile } from '@/src/utils/prompts';\nimport { deleteSimulatorEndpointEnv } from '@/src/utils/simulator';\n\nexport const createCommand = new Command()\n .name('create')\n .description('Create a new CVM')\n .option('-n, --name <name>', 'Name of the CVM')\n .option('-c, --compose <compose>', 'Path to Docker Compose file')\n .option('--vcpu <vcpu>', `Number of vCPUs, default is ${DEFAULT_VCPU}`)\n .option('--memory <memory>', `Memory in MB, default is ${DEFAULT_MEMORY}`)\n .option('--disk-size <diskSize>', `Disk size in GB, default is ${DEFAULT_DISK_SIZE}`)\n .option('--teepod-id <teepodId>', 'TEEPod ID to use. If not provided, it will be selected from the list of available TEEPods.')\n .option('--image <image>', 'Version of dstack image to use. If not provided, it will be selected from the list of available images for the selected TEEPod.')\n .option('-e, --env-file <envFile>', 'Path to environment file')\n .option('--skip-env', 'Skip environment variable prompt', false)\n .option('--debug', 'Enable debug mode', false)\n .action(async (options) => {\n try {\n // Prompt for required options if not provided\n if (!options.name) {\n const { name } = await inquirer.prompt([\n {\n type: 'input',\n name: 'name',\n message: 'Enter a name for the CVM:',\n validate: (input) => {\n if (!input.trim()) {\n return 'CVM name is required';\n }\n if (input.trim().length > 20) {\n return 'CVM name must be less than 20 characters';\n } \n if (input.trim().length < 3) {\n return 'CVM name must be at least 3 characters';\n } \n if (!/^[a-zA-Z0-9_-]+$/.test(input)) {\n return 'CVM name must contain only letters, numbers, underscores, and hyphens';\n }\n return true;\n }\n }\n ]);\n options.name = name;\n }\n\n // If compose path not provided, prompt with examples\n if (!options.compose) {\n const possibleFiles = ['docker-compose.yml', 'docker-compose.yaml'];\n const composeFileName = detectFileInCurrentDir(possibleFiles, 'Detected docker compose file: {path}');\n\n options.compose = await promptForFile(\n 'Enter the path to your Docker Compose file:',\n composeFileName,\n 'file'\n );\n }\n\n const composePath = path.resolve(options.compose);\n if (!fs.existsSync(composePath)) {\n logger.error(`Docker Compose file not found: ${composePath}`);\n process.exit(1);\n }\n const composeString = fs.readFileSync(composePath, 'utf8');\n\n // Delete DSTACK_SIMULATOR_ENDPOINT environment variable\n await deleteSimulatorEndpointEnv();\n\n // Print if they are using a private registry\n if (process.env.DSTACK_DOCKER_USERNAME && process.env.DSTACK_DOCKER_PASSWORD) {\n logger.info(\"🔐 Using private DockerHub registry credentials...\");\n } else if (process.env.DSTACK_AWS_ACCESS_KEY_ID && process.env.DSTACK_AWS_SECRET_ACCESS_KEY && process.env.DSTACK_AWS_REGION && process.env.DSTACK_AWS_ECR_REGISTRY) {\n logger.info(`🔐 Using private AWS ECR registry: ${process.env.DSTACK_AWS_ECR_REGISTRY}`);\n } else {\n logger.info(\"🔐 Using public DockerHub registry...\");\n }\n\n // Process environment variables\n let envs: EnvVar[] = [];\n\n // Process environment variables from file\n if (options.envFile) {\n try {\n envs = parseEnv([], options.envFile);\n } catch (error) {\n logger.error(`Failed to read environment file: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n } else if (!options.skipEnv) {\n // Prompt to input env file or skip\n const { shouldSkip } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'shouldSkip',\n message: 'Do you want to skip environment variable prompt?',\n default: true\n }\n ]);\n \n if (shouldSkip) {\n logger.info('Skipping environment variable prompt');\n } else {\n const envVars = await promptForFile(\n 'Enter the path to your environment file:',\n '.env',\n 'file',\n );\n envs = parseEnv([], envVars);\n }\n }\n\n const vcpu = Number(options.vcpu) || DEFAULT_VCPU;\n const memory = Number(options.memory) || DEFAULT_MEMORY;\n const diskSize = Number(options.diskSize) || DEFAULT_DISK_SIZE;\n\n if (Number.isNaN(vcpu) || vcpu <= 0) {\n logger.error(`Invalid number of vCPUs: ${vcpu}`);\n process.exit(1);\n }\n\n if (Number.isNaN(memory) || memory <= 0) {\n logger.error(`Invalid memory: ${memory}`);\n process.exit(1);\n }\n\n if (Number.isNaN(diskSize) || diskSize <= 0) {\n logger.error(`Invalid disk size: ${diskSize}`);\n process.exit(1);\n }\n\n const teepodsSpinner = logger.startSpinner('Fetching available TEEPods');\n const teepods = await getTeepods();\n teepodsSpinner.stop(true);\n if (teepods.nodes.length === 0) {\n logger.error('No TEEPods available. Please try again later.');\n process.exit(1);\n }\n\n let selectedTeepod: TEEPod;\n // Fetch available TEEPods\n if (!options.teepodId) {\n selectedTeepod = teepods.nodes[0];\n if (!selectedTeepod) {\n logger.error('Failed to find default TEEPod');\n process.exit(1);\n }\n } else {\n selectedTeepod = teepods.nodes.find(pod => pod.teepod_id === Number(options.teepodId));\n if (!selectedTeepod) {\n logger.error('Failed to find selected TEEPod');\n process.exit(1);\n }\n }\n\n let selectedImage: Image;\n if (!options.image) {\n selectedImage = selectedTeepod.images?.find(image => image.name === DEFAULT_IMAGE);\n if (!selectedImage) {\n logger.error(`Failed to find default image ${DEFAULT_IMAGE}`);\n process.exit(1);\n }\n } else {\n selectedImage = selectedTeepod.images?.find(image => image.name === options.image);\n if (!selectedImage) {\n logger.error(`Failed to find selected image: ${options.image}`);\n process.exit(1);\n }\n }\n\n // Prepare VM configuration\n const vmConfig = {\n teepod_id: selectedTeepod.teepod_id,\n name: options.name,\n image: selectedImage.name,\n vcpu: vcpu,\n memory: memory,\n disk_size: diskSize,\n compose_manifest: {\n docker_compose_file: composeString,\n docker_config: {\n url: '',\n username: '',\n password: '',\n },\n features: ['kms', 'tproxy-net'],\n kms_enabled: true,\n manifest_version: 2,\n name: options.name,\n public_logs: true,\n public_sysinfo: true,\n tproxy_enabled: true,\n },\n listed: false,\n };\n\n // Get public key from CVM\n const spinner = logger.startSpinner('Getting public key from CVM');\n const pubkey = await getPubkeyFromCvm(vmConfig);\n spinner.stop(true);\n\n if (!pubkey) {\n logger.error('Failed to get public key from CVM');\n process.exit(1);\n }\n\n // Encrypt environment variables\n const encryptSpinner = logger.startSpinner('Encrypting environment variables');\n const encrypted_env = await encryptEnvVars(envs, pubkey.app_env_encrypt_pubkey);\n encryptSpinner.stop(true);\n\n if (options.debug) {\n logger.debug('Public key:', pubkey.app_env_encrypt_pubkey);\n logger.debug('Encrypted environment variables:', encrypted_env);\n logger.debug('Environment variables:', JSON.stringify(envs));\n }\n\n // Create the CVM\n const createSpinner = logger.startSpinner('Creating CVM');\n const response = await createCvm({\n ...vmConfig,\n encrypted_env,\n app_env_encrypt_pubkey: pubkey.app_env_encrypt_pubkey,\n app_id_salt: pubkey.app_id_salt,\n });\n createSpinner.stop(true);\n\n if (!response) {\n logger.error('Failed to create CVM');\n process.exit(1);\n }\n\n logger.success('CVM created successfully');\n logger.break();\n const tableData = {\n 'CVM ID': response.id,\n 'Name': response.name,\n 'Status': response.status,\n 'App ID': `app_${response.app_id}`,\n 'App URL': response.app_url ? response.app_url : `${CLOUD_URL}/dashboard/cvms/app_${response.app_id}`,\n };\n logger.keyValueTable(tableData, {\n borderStyle: 'rounded'\n });\n\n logger.info('');\n logger.success(`Your CVM is being created. You can check its status with:\\nphala cvms get app_${response.app_id}`);\n } catch (error) {\n logger.error(`Failed to create CVM: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import * as fs from 'node:fs';\nimport type { EnvVar } from '@phala/dstack-sdk/encrypt-env-vars';\n\nexport const parseEnv = (envs: string[], envFile: string): EnvVar[] => {\n const envVars: Record<string, string> = {};\n\n // Process environment variables passed directly\n if (envs) {\n for (const env of envs) {\n if (env.includes(\"=\")) {\n const [key, ...valueParts] = env.split(\"=\");\n const value = valueParts.join(\"=\"); // Handle cases where value might contain '='\n if (key) { // Allow empty value\n envVars[key] = value;\n }\n }\n }\n }\n\n if (envFile) {\n const envFileContent = fs.readFileSync(envFile, \"utf8\");\n for (const line of envFileContent.split(\"\\n\")) {\n // Skip empty lines\n if (!line.trim()) {\n continue;\n }\n\n // Skip comments\n if (line.trim().startsWith('#')) {\n continue;\n }\n\n // Find the first '=' that is not part of an inline comment\n let delimiterIndex = -1;\n let inQuotes = false;\n let quoteChar = '';\n\n for (let i = 0; i < line.length; i++) {\n if ((line[i] === '\"' || line[i] === \"'\" || line[i] === '`') && (i === 0 || line[i-1] !== '\\\\')) {\n if (inQuotes && line[i] === quoteChar) {\n inQuotes = false;\n quoteChar = '';\n } else if (!inQuotes) {\n inQuotes = true;\n quoteChar = line[i];\n }\n } else if (line[i] === '=' && !inQuotes) {\n delimiterIndex = i;\n break;\n } else if (line[i] === '#' && !inQuotes) {\n // If a comment starts before any '=', treat the whole line as a comment if no '=' found yet\n // Or, if '=' is found, this part is an inline comment.\n if (delimiterIndex === -1) { // No '=' encountered yet, so this is a full-line comment essentially or malformed\n // We already skip lines starting with #, this handles cases like \" #comment\"\n // or \"KEY #comment\" (which is not a valid assignment according to rules)\n // However, the rule \" # marks the beginning of a comment (unless when the value is wrapped in quotes)\"\n // implies that \"KEY=value #comment\" is valid.\n // The current logic handles inline comments on the value side later.\n // If # appears before =, it's either a full comment (handled) or part of the key (unusual, but let it pass to split)\n }\n break; // Stop processing at the comment marker for the key or if it's an inline comment for the value\n }\n }\n\n\n if (delimiterIndex === -1) {\n // Handles lines without '=' or lines that are effectively comments.\n if (!line.trim().startsWith('#')) {\n // It's not a comment line, but has no '='.\n // According to \"EMPTY= becomes {EMPTY: ''}\", lines like \"ONLYKEY\" are not defined.\n // So we can skip them or treat as an error. Skipping for now.\n }\n continue;\n }\n\n const key = line.substring(0, delimiterIndex).trim();\n let value = line.substring(delimiterIndex + 1);\n\n // Remove inline comments from the value part\n // A comment starts with ' #' (space followed by #)\n // unless the # is within quotes.\n let valueInQuotes = false;\n let valueQuoteChar = '';\n let commentStartIndex = -1;\n\n for (let i = 0; i < value.length; i++) {\n if ((value[i] === '\"' || value[i] === \"'\" || value[i] === '`') && (i === 0 || value[i-1] !== '\\\\')) {\n if (valueInQuotes && value[i] === valueQuoteChar) {\n valueInQuotes = false;\n valueQuoteChar = '';\n } else if (!valueInQuotes) {\n valueInQuotes = true;\n valueQuoteChar = value[i];\n }\n } else if (value[i] === '#' && !valueInQuotes && i > 0 && value[i-1] === ' ') {\n commentStartIndex = i -1; // Start of \" #\"\n break;\n } else if (value[i] === '#' && !valueInQuotes && i === 0) { // Value starts directly with #\n commentStartIndex = i;\n break;\n }\n }\n\n if (commentStartIndex !== -1) {\n value = value.substring(0, commentStartIndex);\n }\n\n\n // Handle empty values: EMPTY= becomes {EMPTY: ''}\n if (value === undefined) { // Should not happen if split correctly\n value = '';\n }\n\n\n // Trim whitespace for unquoted values, preserve for quoted\n const firstChar = value.charAt(0);\n const lastChar = value.charAt(value.length - 1);\n\n if ((firstChar === '\"' && lastChar === '\"') ||\n (firstChar === \"'\" && lastChar === \"'\") ||\n (firstChar === '`' && lastChar === '`')) {\n // Quoted value, remove the outer quotes\n value = value.substring(1, value.length - 1);\n\n // Expand newlines for double-quoted values\n if (firstChar === '\"') {\n value = value.replace(/\\\\\\\\n/g, '\\n');\n }\n // Unescape inner quotes for single and backtick quotes if they were escaped like \\\\' or \\\\`\n // The rules state \"inner quotes are maintained (think JSON)\"\n // and \"single and double quoted values are escaped\"\n // This implies that within a string like SINGLE_QUOTE='value with \\\\' quote'\n // the result should be \"value with ' quote\"\n // For JSON example: JSON={\"foo\": \"bar\"} becomes {JSON:\"{\\\"foo\\\": \\\"bar\\\"}\"}\n // This needs careful handling. The current approach of just slicing quotes might be too simple.\n // Let's assume the provided examples are the source of truth.\n // \"JSON={\"foo\": \"bar\"}\" -> JSON: \"{\\\"foo\\\": \\\"bar\\\"}\"\n // This means the quotes *around* the JSON are stripped, but the inner quotes *within* the JSON string literal itself are preserved.\n // The rule \"single and double quoted values are escaped (SINGLE_QUOTE='quoted' becomes {SINGLE_QUOTE: \"quoted\"})\"\n // seems to imply that the outer quotes are removed, and the content becomes a JS string.\n // The parsing engine should output a JS object, so values will be JS strings.\n // SINGLE_QUOTE='quoted' -> {SINGLE_QUOTE: 'quoted'} (JS string)\n // FOO=\" some value \" -> {FOO: ' some value '} (JS string)\n // JSON={\"foo\": \"bar\"} -> {JSON: '{\"foo\": \"bar\"}'} (JS string)\n // MULTILINE=\"new\\\\nline\" -> {MULTILINE: 'new\\\\nline'} (JS string with literal \\n)\n // The rule says: MULTILINE=\"new\\\\nline\" becomes {MULTILINE: 'new\\nline'} (with actual newline)\n // So, my previous .replace(/\\\\n/g, '\\n') for double quotes is correct.\n\n // For single quotes and backticks, the rules don't explicitly state escaped char handling other than `\\\\n` for double quotes.\n // \"inner quotes are maintained (think JSON)\" - this is key for JSON={\"foo\": \"bar\"}\n // Let's ensure that if a value is `'{\"key\": \"value\"}'`, it becomes `{\"key\": \"value\"}`.\n // The current `substring(1, value.length - 1)` does this.\n // Let's consider BACKTICK_KEY=`This has 'single' and \"double\" quotes inside of it.`\n // This should become {BACKTICK_KEY: \"This has 'single' and \\\"double\\\" quotes inside of it.\"}\n // The current slicing handles this correctly. Escaped backticks like \\` needs to be considered if they should be unescaped.\n // The rules do not specify un-escaping for \\\\', \\\\\", or \\\\` within their respective quotes.\n // So, 'it\\'s a test' would become \"it\\'s a test\". If it should be \"it's a test\", then un-escaping is needed.\n // Given \"single and double quoted values are escaped\", it seems like what's inside the quotes is the literal string value.\n // Let's stick to the examples: SINGLE_QUOTE='quoted' becomes {SINGLE_QUOTE: \"quoted\"}. This means the value is 'quoted'.\n } else {\n // Unquoted value, trim whitespace\n value = value.trim();\n }\n\n\n if (key) { // Ensure key is not empty\n envVars[key] = value;\n }\n }\n }\n\n // Add environment variables to the payload\n return Object.entries(envVars).map(([key, value]) => ({\n key,\n value,\n }));\n};","import { Command } from 'commander';\nimport { checkCvmExists, deleteCvm, selectCvm } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport inquirer from 'inquirer';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\n\nexport const deleteCommand = new Command()\n .name('delete')\n .description('Delete a CVM')\n .argument('[app-id]', 'App ID of the CVM to delete (if not provided, a selection prompt will appear)')\n .option('-f, --force', 'Skip confirmation prompt', false)\n .action(async (appId, options) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n \n // Confirm deletion unless force option is used\n if (!options.force) {\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirm',\n message: `Are you sure you want to delete CVM with App ID app_${resolvedAppId}? This action cannot be undone.`,\n default: false,\n },\n ]);\n \n if (!confirm) {\n logger.info('Deletion cancelled');\n return;\n }\n }\n \n // Delete the CVM\n const spinner = logger.startSpinner(`Deleting CVM app_${resolvedAppId}`);\n const success = await deleteCvm(resolvedAppId);\n spinner.stop(true);\n \n if (!success) {\n logger.error(`Failed to delete CVM app_${resolvedAppId}`);\n process.exit(1);\n }\n\n\t\tlogger.success(`CVM app_${resolvedAppId} deleted successfully`);\n\t} catch (error) {\n\t\tlogger.error(\n\t\t\t`Failed to delete CVM: ${error instanceof Error ? error.message : String(error)}`\n\t\t);\n\t\tprocess.exit(1);\n\t}\n }); ","import { Command } from 'commander';\nimport { getCvmByAppId, getCvmComposeFile, updateCvmCompose, updatePatchCvmCompose } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport fs from 'node:fs';\nimport { detectFileInCurrentDir, promptForFile } from '@/src/utils/prompts';\nimport { parseEnv } from '@/src/utils/secrets';\nimport { encryptEnvVars, type EnvVar } from '@phala/dstack-sdk/encrypt-env-vars';\nimport { deleteSimulatorEndpointEnv } from '@/src/utils/simulator';\nimport { CLOUD_URL } from '@/src/utils/constants';\nimport inquirer from 'inquirer';\nimport { ethers } from 'ethers';\nimport { createPublicClient, http } from 'viem';\nimport { getChainConfig, getNetworkConfig } from '@/src/utils/blockchain';\n\nasync function gatherUpdateInputs(cvmId: string, options: any): Promise<any> {\n if (!cvmId) {\n if (!options.interactive) {\n logger.error('CVM ID is required. Use --app-id to enter it');\n process.exit(1);\n } else {\n const { id } = await inquirer.prompt([{ type: 'input', name: 'id', message: 'Enter the CVM ID to update:' }]);\n cvmId = id;\n }\n }\n\n const spinner = logger.startSpinner(`Fetching current configuration for CVM ${cvmId}`);\n const currentCvm = await getCvmByAppId(cvmId);\n spinner.stop(true);\n\n if (!currentCvm) {\n logger.error(`CVM with CVM ID ${cvmId} not found`);\n process.exit(1);\n }\n\n if (!options.compose) {\n if (!options.interactive) {\n logger.error('Docker Compose file is required. Use --compose to select it');\n process.exit(1);\n } else {\n const possibleFiles = ['docker-compose.yml', 'docker-compose.yaml'];\n const composeFileName = detectFileInCurrentDir(possibleFiles, 'Detected docker compose file: {path}');\n options.compose = await promptForFile('Enter the path to your new Docker Compose file:', composeFileName, 'file');\n }\n }\n\n let envs: EnvVar[] = [];\n let allowedEnvs: string[] = [];\n\n if (!options.skipEnv) {\n // If envFile is not provided, try to find one automatically\n let envFilePath = options.envFile;\n\n if (!envFilePath) {\n // Check for environment files in order of priority\n const envFiles = ['.env.production', '.env.prod', '.env'];\n for (const file of envFiles) {\n if (fs.existsSync(file)) {\n envFilePath = file;\n logger.info(`Using environment file: ${envFilePath}`);\n break;\n }\n }\n\n // If no env file found, ask user if they want to provide one\n if (!envFilePath) {\n if (options.interactive) {\n envFilePath = await promptForFile('Enter the path to your environment file:', '.env', 'file');\n }\n }\n }\n\n if (envFilePath) {\n try {\n // Read and parse environment variables\n envs = parseEnv([], envFilePath);\n\n // Extract just the keys for allowed_envs\n allowedEnvs = envs.map(env => env.key);\n\n if (allowedEnvs.length > 0) {\n logger.info(`Using environment variables from ${envFilePath}`);\n logger.debug(`Allowed environment variables: ${allowedEnvs.join(', ')}`);\n } else {\n logger.warn(`No environment variables found in ${envFilePath}`);\n }\n } catch (error) {\n logger.error(`Error reading environment file ${envFilePath}:`, error);\n }\n }\n }\n\n return { ...options, cvmId: currentCvm.vm_uuid.replace(/-/g, ''), currentCvm, allowedEnvs };\n}\n\nasync function prepareUpdatePayload(options: any, currentCvm: any): Promise<{ composeString: string; encryptedEnv: string }> {\n const composeString = fs.readFileSync(options.compose, 'utf8');\n\n let encryptedEnv = '';\n let envs: EnvVar[] = [];\n if (options.envFile) {\n try {\n envs = parseEnv([], options.envFile);\n } catch (error) {\n logger.error(`Failed to process environment file: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n } else if (options.interactive) {\n const { useEnvFile } = await inquirer.prompt([{\n type: 'confirm',\n name: 'useEnvFile',\n message: 'Do you want to use an environment file?',\n default: false,\n }]);\n if (useEnvFile) {\n const envFilePath = await promptForFile('Enter the path to your environment file:', '.env', 'file');\n envs = parseEnv([], envFilePath);\n }\n }\n\n if (envs.length > 0) {\n if (!currentCvm.encrypted_env_pubkey) {\n logger.error('Could not find public key to encrypt environment variables for this CVM.');\n process.exit(1);\n }\n encryptedEnv = await encryptEnvVars(envs, currentCvm.encrypted_env_pubkey);\n }\n\n return { composeString, encryptedEnv };\n}\n\nasync function registerComposeHash(\n composeHash: string,\n appId: string,\n wallet: ethers.Wallet,\n kmsContractAddress: string,\n rawRpcUrl: string,\n chainId: number,\n options: { json?: boolean } = {}\n): Promise<void> {\n const spinner = logger.startSpinner('Adding compose hash for on-chain KMS...');\n let appAuthAddress: any;\n try {\n // Get network config which will handle chain validation and RPC URL resolution\n const { rpcUrl } = await getNetworkConfig({ rpcUrl: rawRpcUrl }, chainId);\n\n // Get the chain config\n const chain = getChainConfig(chainId);\n\n // Initialize public client with the appropriate chain and RPC URL\n const publicClient = createPublicClient({\n chain,\n transport: http(rpcUrl)\n });\n\n // KMS Auth ABI for reading app registration details\n const kmsAuthAbi = [\n {\n inputs: [{ name: 'app', type: 'address' }],\n name: 'apps',\n outputs: [\n { name: 'isRegistered', type: 'bool' },\n { name: 'controller', type: 'address' },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n ] as const;\n\n try {\n // Ensure the KMS contract address is valid\n if (!ethers.isAddress(kmsContractAddress)) {\n throw new Error(`Invalid KMS contract address: ${kmsContractAddress}`);\n }\n\n if (!ethers.isAddress(appId)) {\n throw new Error(`Invalid custom App ID: ${appId}`);\n }\n\n // Ensure customAppId has 0x prefix\n const customAppId = appId.startsWith('0x')\n ? appId\n : `0x${appId}`;\n\n // Query the KMS contract for app registration details\n const [isRegistered, controllerAddress] = await publicClient.readContract({\n address: kmsContractAddress as `0x${string}`,\n abi: kmsAuthAbi,\n functionName: 'apps',\n args: [customAppId as `0x${string}`]\n });\n\n // Validate the response\n if (!isRegistered) {\n throw new Error(`App ${appId} is not registered in KMS contract ${kmsContractAddress}`);\n }\n\n if (!controllerAddress || controllerAddress === ethers.ZeroAddress) {\n throw new Error(`Invalid controller address for app ${appId}`);\n }\n\n logger.info(`Successfully verified AppAuth contract at ${controllerAddress}`);\n\n appAuthAddress = controllerAddress;\n } catch (error) {\n throw new Error(`Failed to verify custom App ID: ${error instanceof Error ? error.message : String(error)}`);\n }\n const appAuthAbi = ['function addComposeHash(bytes32 composeHash)', 'event ComposeHashAdded(bytes32 composeHash)'];\n const appAuthContract = new ethers.Contract(appAuthAddress, appAuthAbi, wallet);\n\n const formattedHash = composeHash.startsWith('0x') ? composeHash : `0x${composeHash}`;\n const tx = await appAuthContract.addComposeHash(formattedHash);\n const receipt = await tx.wait();\n\n spinner.stop(true);\n \n const appAuthInterface = new ethers.Interface(appAuthAbi);\n const eventTopic = appAuthInterface.getEvent('ComposeHashAdded').topicHash;\n const log = receipt.logs.find((l: any) => l.topics[0] === eventTopic);\n let composeHashEvent = null;\n\n if (log) {\n const parsedLog = appAuthInterface.parseLog({ topics: Array.from(log.topics), data: log.data });\n composeHashEvent = parsedLog.args.composeHash;\n }\n\n if (options?.json !== false) {\n console.log(JSON.stringify({\n success: true,\n data: {\n transaction_hash: tx.hash,\n compose_hash_event: composeHashEvent,\n event_found: !!log\n }\n }, null, 2));\n } else {\n logger.success('Compose hash added successfully!');\n logger.info(`Transaction hash: ${tx.hash}`);\n if (log) {\n logger.info(` - Compose Hash: ${composeHashEvent}`);\n } else {\n logger.warn('Could not find ComposeHashAdded event to extract Compose Hash.');\n }\n }\n } catch (error) {\n spinner.stop(false);\n throw error;\n }\n}\n\nasync function applyUpdate(\n cvmId: string,\n composeHash: string,\n encryptedEnv: string,\n options: { json?: boolean } = {}\n): Promise<void> {\n const spinner = logger.startSpinner('Applying update...');\n try {\n const payload = { compose_hash: composeHash, encrypted_env: encryptedEnv };\n const response = await updatePatchCvmCompose(cvmId, payload);\n spinner.stop(true);\n\n if (response === null) {\n if (options?.json !== false) {\n console.log(JSON.stringify({\n success: true,\n data: {\n message: 'Update applied successfully',\n cvm_id: cvmId,\n compose_hash: composeHash\n }\n }, null, 2));\n } else {\n logger.success('Update applied successfully!');\n }\n } else {\n const errorMessage = `Failed to apply update: ${JSON.stringify(response.detail, null, 2)}`;\n if (options?.json !== false) {\n console.error(JSON.stringify({\n success: false,\n error: errorMessage\n }, null, 2));\n } else {\n logger.error(errorMessage);\n }\n process.exit(1);\n }\n } catch (error) {\n spinner.stop(false);\n throw error;\n }\n}\n\nexport const upgradeCommand = new Command()\n .name('upgrade')\n .description('Upgrade a CVM to a new version')\n .argument('[app-id]', 'CVM app ID to upgrade')\n .option('-c, --compose <compose>', 'Path to new Docker Compose file')\n .option('-e, --env-file <envFile>', 'Path to environment file')\n .option('--private-key <privateKey>', 'Private key for signing transactions')\n .option('--debug', 'Enable debug mode', false)\n .option('-i, --interactive', 'Enable interactive mode for required parameters', false)\n .option('--rpc-url <rpcUrl>', 'RPC URL for the blockchain.')\n .option('--json', 'Output in JSON format (default: true)', true)\n .option('--no-json', 'Disable JSON output format')\n .action(async (appId, options) => {\n try {\n const { cvmId: finalCvmId, currentCvm, ...gatheredOptions } = await gatherUpdateInputs(appId, options);\n\n const { composeString, encryptedEnv } = await prepareUpdatePayload(gatheredOptions, currentCvm);\n // Delete DSTACK_SIMULATOR_ENDPOINT environment variable\n await deleteSimulatorEndpointEnv();\n // Only show registry info in non-JSON mode\n if (options.json === false) {\n if (process.env.DSTACK_DOCKER_USERNAME && process.env.DSTACK_DOCKER_PASSWORD) {\n logger.info(\"🔐 Using private DockerHub registry credentials...\");\n } else if (process.env.DSTACK_AWS_ACCESS_KEY_ID && process.env.DSTACK_AWS_SECRET_ACCESS_KEY && process.env.DSTACK_AWS_REGION && process.env.DSTACK_AWS_ECR_REGISTRY) {\n logger.info(`🔐 Using private AWS ECR registry: ${process.env.DSTACK_AWS_ECR_REGISTRY}`);\n } else {\n logger.info(\"🔐 Using public DockerHub registry...\");\n }\n }\n\n const spinner = logger.startSpinner(`Updating CVM ${finalCvmId}`);\n const currentComposeFile = await getCvmComposeFile(finalCvmId);\n currentComposeFile.docker_compose_file = composeString;\n currentComposeFile.allowed_envs = gatheredOptions.allowedEnvs;\n const response = await updateCvmCompose(finalCvmId, currentComposeFile);\n spinner.stop(true);\n\n if (!response || !response.compose_hash) {\n logger.error('Failed to initiate CVM update or get compose hash.');\n process.exit(1);\n }\n\n if (options.json !== false) {\n console.log(JSON.stringify({\n success: true,\n data: {\n cvm_id: currentCvm.vm_uuid.replace(/-/g, ''),\n app_id: finalCvmId,\n compose_hash: response.compose_hash,\n dashboard_url: `${CLOUD_URL}/dashboard/cvms/${currentCvm.vm_uuid.replace(/-/g, '')}`,\n raw: response\n }\n }, null, 2));\n } else {\n logger.success(`CVM update has been provisioned. New compose hash: ${response.compose_hash}`);\n logger.info(`Dashboard: ${CLOUD_URL}/dashboard/cvms/${currentCvm.vm_uuid.replace(/-/g, '')}`);\n }\n\n if (currentCvm.kms_info) {\n // Check for private key in options or environment variables\n const privateKey = options.privateKey || process.env.PRIVATE_KEY;\n if (!privateKey) {\n throw new Error('Private key is required for on-chain KMS operations. Please provide it via --private-key or PRIVATE_KEY environment variable');\n }\n \n const { wallet } = await getNetworkConfig({ privateKey, rpcUrl: options.rpcUrl }, currentCvm.kms_info.chain_id);\n if (options.json !== false) {\n console.log(JSON.stringify({\n success: true,\n data: {\n wallet_address: wallet.address\n }\n }, null, 2));\n } else {\n logger.info(`Using wallet: ${wallet.address}`);\n }\n if (options.json === false) {\n logger.info('This CVM uses on-chain KMS. Registering the new compose hash...');\n }\n await registerComposeHash(\n response.compose_hash, \n appId, \n wallet, \n currentCvm.kms_info.kms_contract_address, \n options.rpcUrl, \n currentCvm.kms_info.chain_id,\n { json: options.json }\n );\n }\n\n await applyUpdate(finalCvmId, response.compose_hash, encryptedEnv, { json: options.json });\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n if (options.json !== false) {\n console.error(JSON.stringify({\n success: false,\n error: errorMessage,\n stack: options.debug && error instanceof Error ? error.stack : undefined\n }, null, 2));\n } else {\n logger.error(`Failed to upgrade CVM: ${errorMessage}`);\n }\n process.exit(1);\n }\n }); ","import type { Client } from '../clients/createClient.js'\nimport type { PublicActions } from '../clients/decorators/public.js'\nimport type { WalletActions } from '../clients/decorators/wallet.js'\nimport type { Transport } from '../clients/transports/createTransport.js'\nimport type { Account } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { RpcSchema } from '../types/eip1193.js'\n\n/**\n * Retrieves and returns an action from the client (if exists), and falls\n * back to the tree-shakable action.\n *\n * Useful for extracting overridden actions from a client (ie. if a consumer\n * wants to override the `sendTransaction` implementation).\n */\nexport function getAction<\n transport extends Transport,\n chain extends Chain | undefined,\n account extends Account | undefined,\n rpcSchema extends RpcSchema | undefined,\n extended extends { [key: string]: unknown },\n client extends Client<transport, chain, account, rpcSchema, extended>,\n parameters,\n returnType,\n>(\n client: client,\n actionFn: (_: any, parameters: parameters) => returnType,\n // Some minifiers drop `Function.prototype.name`, or replace it with short letters,\n // meaning that `actionFn.name` will not always work. For that case, the consumer\n // needs to pass the name explicitly.\n name: keyof PublicActions | keyof WalletActions | (string & {}),\n): (parameters: parameters) => returnType {\n const action_implicit = client[actionFn.name]\n if (typeof action_implicit === 'function')\n return action_implicit as (params: parameters) => returnType\n\n const action_explicit = client[name]\n if (typeof action_explicit === 'function')\n return action_explicit as (params: parameters) => returnType\n\n return (params) => actionFn(client, params)\n}\n","import { BaseError } from './base.js'\n\nexport type FilterTypeNotSupportedErrorType = FilterTypeNotSupportedError & {\n name: 'FilterTypeNotSupportedError'\n}\nexport class FilterTypeNotSupportedError extends BaseError {\n constructor(type: string) {\n super(`Filter type \"${type}\" is not supported.`, {\n name: 'FilterTypeNotSupportedError',\n })\n }\n}\n","import type {\n Abi,\n AbiParameter,\n AbiParameterToPrimitiveType,\n ExtractAbiEvents,\n} from 'abitype'\n\nimport {\n AbiEventNotFoundError,\n type AbiEventNotFoundErrorType,\n} from '../../errors/abi.js'\nimport {\n FilterTypeNotSupportedError,\n type FilterTypeNotSupportedErrorType,\n} from '../../errors/log.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type ToEventSelectorErrorType,\n toEventSelector,\n} from '../hash/toEventSelector.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeEventTopics'\n\nexport type EncodeEventTopicsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined = ContractEventName<abi>,\n ///\n hasEvents = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiEvents<abi>] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractEventArgs<\n abi,\n eventName extends ContractEventName<abi>\n ? eventName\n : ContractEventName<abi>\n >,\n allErrorNames = ContractEventName<abi>,\n> = {\n abi: abi\n args?: allArgs | undefined\n} & UnionEvaluate<\n IsNarrowable<abi, Abi> extends true\n ? abi['length'] extends 1\n ? { eventName?: eventName | allErrorNames | undefined }\n : { eventName: eventName | allErrorNames }\n : { eventName?: eventName | allErrorNames | undefined }\n> &\n (hasEvents extends true ? unknown : never)\n\nexport type EncodeEventTopicsReturnType = [Hex, ...(Hex | Hex[] | null)[]]\n\nexport type EncodeEventTopicsErrorType =\n | AbiEventNotFoundErrorType\n | EncodeArgErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToEventSelectorErrorType\n | ErrorType\n\nexport function encodeEventTopics<\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi> | undefined = undefined,\n>(\n parameters: EncodeEventTopicsParameters<abi, eventName>,\n): EncodeEventTopicsReturnType {\n const { abi, eventName, args } = parameters as EncodeEventTopicsParameters\n\n let abiItem = abi[0]\n if (eventName) {\n const item = getAbiItem({ abi, name: eventName })\n if (!item) throw new AbiEventNotFoundError(eventName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'event')\n throw new AbiEventNotFoundError(undefined, { docsPath })\n\n const definition = formatAbiItem(abiItem)\n const signature = toEventSelector(definition as EventDefinition)\n\n let topics: (Hex | Hex[] | null)[] = []\n if (args && 'inputs' in abiItem) {\n const indexedInputs = abiItem.inputs?.filter(\n (param) => 'indexed' in param && param.indexed,\n )\n const args_ = Array.isArray(args)\n ? args\n : Object.values(args).length > 0\n ? (indexedInputs?.map((x: any) => (args as any)[x.name]) ?? [])\n : []\n\n if (args_.length > 0) {\n topics =\n indexedInputs?.map((param, i) => {\n if (Array.isArray(args_[i]))\n return args_[i].map((_: any, j: number) =>\n encodeArg({ param, value: args_[i][j] }),\n )\n return typeof args_[i] !== 'undefined' && args_[i] !== null\n ? encodeArg({ param, value: args_[i] })\n : null\n }) ?? []\n }\n }\n return [signature, ...topics]\n}\n\nexport type EncodeArgErrorType =\n | Keccak256ErrorType\n | ToBytesErrorType\n | EncodeAbiParametersErrorType\n | FilterTypeNotSupportedErrorType\n | ErrorType\n\nfunction encodeArg({\n param,\n value,\n}: { param: AbiParameter; value: AbiParameterToPrimitiveType<AbiParameter> }) {\n if (param.type === 'string' || param.type === 'bytes')\n return keccak256(toBytes(value as string))\n if (param.type === 'tuple' || param.type.match(/^(.*)\\[(\\d+)?\\]$/))\n throw new FilterTypeNotSupportedError(param.type)\n return encodeAbiParameters([param], [value])\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { OnResponseFn } from '../../clients/transports/fallback.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { PublicRpcSchema } from '../../types/eip1193.js'\nimport type { EIP1193RequestFn } from '../../types/eip1193.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Filter } from '../../types/utils.js'\n\ntype CreateFilterRequestScopeParameters = {\n method:\n | 'eth_newFilter'\n | 'eth_newPendingTransactionFilter'\n | 'eth_newBlockFilter'\n}\n\ntype FilterRpcSchema = Filter<\n PublicRpcSchema,\n { Method: 'eth_getFilterLogs' | 'eth_getFilterChanges' }\n>\n\ntype CreateFilterRequestScopeReturnType = (\n id: Hex,\n) => EIP1193RequestFn<FilterRpcSchema>\n\n/**\n * Scopes `request` to the filter ID. If the client is a fallback, it will\n * listen for responses and scope the child transport `request` function\n * to the successful filter ID.\n */\nexport function createFilterRequestScope<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { method }: CreateFilterRequestScopeParameters,\n): CreateFilterRequestScopeReturnType {\n const requestMap: Record<Hex, EIP1193RequestFn> = {}\n\n if (client.transport.type === 'fallback')\n client.transport.onResponse?.(\n ({\n method: method_,\n response: id,\n status,\n transport,\n }: Parameters<OnResponseFn>[0]) => {\n if (status === 'success' && method === method_)\n requestMap[id as Hex] = transport.request\n },\n )\n\n return ((id) =>\n requestMap[id] || client.request) as CreateFilterRequestScopeReturnType\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateContractEventFilterParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined = undefined,\n args extends\n | MaybeExtractEventArgsFromAbi<abi, eventName>\n | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n address?: Address | Address[] | undefined\n abi: abi\n eventName?: eventName | ContractEventName<abi> | undefined\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments in the event ABI item.\n * @default false\n */\n strict?: strict | boolean | undefined\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n} & (undefined extends eventName\n ? {\n args?: undefined\n }\n : MaybeExtractEventArgsFromAbi<abi, eventName> extends infer eventFilterArgs\n ? {\n args?:\n | eventFilterArgs\n | (args extends eventFilterArgs ? args : never)\n | undefined\n }\n : {\n args?: undefined\n })\n\nexport type CreateContractEventFilterReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined = undefined,\n args extends\n | MaybeExtractEventArgsFromAbi<abi, eventName>\n | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = Filter<'event', abi, eventName, args, strict, fromBlock, toBlock>\n\nexport type CreateContractEventFilterErrorType =\n | EncodeEventTopicsErrorType\n | RequestErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).\n *\n * - Docs: https://viem.sh/docs/contract/createContractEventFilter\n *\n * @param client - Client to use\n * @param parameters - {@link CreateContractEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateContractEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * })\n */\nexport async function createContractEventFilter<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi> | undefined,\n args extends MaybeExtractEventArgsFromAbi<abi, eventName> | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client<Transport, chain>,\n parameters: CreateContractEventFilterParameters<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n> {\n const { address, abi, args, eventName, fromBlock, strict, toBlock } =\n parameters as CreateContractEventFilterParameters\n\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newFilter',\n })\n\n const topics = eventName\n ? encodeEventTopics({\n abi,\n args,\n eventName,\n } as unknown as EncodeEventTopicsParameters)\n : undefined\n const id: Hex = await client.request({\n method: 'eth_newFilter',\n params: [\n {\n address,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n topics,\n },\n ],\n })\n\n return {\n abi,\n args,\n eventName,\n id,\n request: getRequest(id),\n strict: Boolean(strict),\n type: 'event',\n } as unknown as CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ContractFunctionExecutionError,\n type ContractFunctionExecutionErrorType,\n ContractFunctionRevertedError,\n type ContractFunctionRevertedErrorType,\n ContractFunctionZeroDataError,\n type ContractFunctionZeroDataErrorType,\n RawContractError,\n} from '../../errors/contract.js'\nimport { RpcRequestError } from '../../errors/request.js'\nimport { InternalRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\nconst EXECUTION_REVERTED_ERROR_CODE = 3\n\nexport type GetContractErrorReturnType<cause = ErrorType> = Omit<\n ContractFunctionExecutionErrorType,\n 'cause'\n> & {\n cause:\n | cause\n | ContractFunctionZeroDataErrorType\n | ContractFunctionRevertedErrorType\n}\n\nexport function getContractError<err extends ErrorType<string>>(\n err: err,\n {\n abi,\n address,\n args,\n docsPath,\n functionName,\n sender,\n }: {\n abi: Abi\n args: any\n address?: Address | undefined\n docsPath?: string | undefined\n functionName: string\n sender?: Address | undefined\n },\n): GetContractErrorReturnType {\n const error = (\n err instanceof RawContractError\n ? err\n : err instanceof BaseError\n ? err.walk((err) => 'data' in (err as Error)) || err.walk()\n : {}\n ) as BaseError\n const { code, data, details, message, shortMessage } =\n error as RawContractError\n\n const cause = (() => {\n if (err instanceof AbiDecodingZeroDataError)\n return new ContractFunctionZeroDataError({ functionName })\n if (\n [EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) &&\n (data || details || message || shortMessage)\n ) {\n return new ContractFunctionRevertedError({\n abi,\n data: typeof data === 'object' ? data.data : data,\n functionName,\n message:\n error instanceof RpcRequestError\n ? details\n : (shortMessage ?? message),\n })\n }\n return err\n })()\n\n return new ContractFunctionExecutionError(cause as BaseError, {\n abi,\n args,\n contractAddress: address,\n docsPath,\n functionName,\n sender,\n }) as GetContractErrorReturnType\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\n\nexport type PublicKeyToAddressErrorType =\n | ChecksumAddressErrorType\n | Keccak256ErrorType\n | ErrorType\n\n/**\n * @description Converts an ECDSA public key to an address.\n *\n * @param publicKey The public key to convert.\n *\n * @returns The address.\n */\nexport function publicKeyToAddress(publicKey: Hex): Address {\n const address = keccak256(`0x${publicKey.substring(4)}`).substring(26)\n return checksumAddress(`0x${address}`) as Address\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport {\n type HexToNumberErrorType,\n hexToBigInt,\n hexToNumber,\n} from '../encoding/fromHex.js'\nimport { toHex } from '../encoding/toHex.js'\n\nexport type RecoverPublicKeyParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverPublicKeyReturnType = Hex\n\nexport type RecoverPublicKeyErrorType =\n | HexToNumberErrorType\n | IsHexErrorType\n | ErrorType\n\nexport async function recoverPublicKey({\n hash,\n signature,\n}: RecoverPublicKeyParameters): Promise<RecoverPublicKeyReturnType> {\n const hashHex = isHex(hash) ? hash : toHex(hash)\n\n const { secp256k1 } = await import('@noble/curves/secp256k1')\n const signature_ = (() => {\n // typeof signature: `Signature`\n if (typeof signature === 'object' && 'r' in signature && 's' in signature) {\n const { r, s, v, yParity } = signature\n const yParityOrV = Number(yParity ?? v)!\n const recoveryBit = toRecoveryBit(yParityOrV)\n return new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).addRecoveryBit(recoveryBit)\n }\n\n // typeof signature: `Hex | ByteArray`\n const signatureHex = isHex(signature) ? signature : toHex(signature)\n const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`)\n const recoveryBit = toRecoveryBit(yParityOrV)\n return secp256k1.Signature.fromCompact(\n signatureHex.substring(2, 130),\n ).addRecoveryBit(recoveryBit)\n })()\n\n const publicKey = signature_\n .recoverPublicKey(hashHex.substring(2))\n .toHex(false)\n return `0x${publicKey}`\n}\n\nfunction toRecoveryBit(yParityOrV: number) {\n if (yParityOrV === 0 || yParityOrV === 1) return yParityOrV\n if (yParityOrV === 27) return 0\n if (yParityOrV === 28) return 1\n throw new Error('Invalid yParityOrV value')\n}\n","import type { Address } from 'abitype'\n\nimport { publicKeyToAddress } from '../../accounts/utils/publicKeyToAddress.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { recoverPublicKey } from './recoverPublicKey.js'\n\nexport type RecoverAddressParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverAddressReturnType = Address\n\nexport type RecoverAddressErrorType = ErrorType\n\nexport async function recoverAddress({\n hash,\n signature,\n}: RecoverAddressParameters): Promise<RecoverAddressReturnType> {\n return publicKeyToAddress(await recoverPublicKey({ hash: hash, signature }))\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type RecursiveArray<T> = T | readonly RecursiveArray<T>[]\n\ntype To = 'hex' | 'bytes'\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor): void\n}\n\nexport type ToRlpReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type ToRlpErrorType =\n | CreateCursorErrorType\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\nexport function toRlp<to extends To = 'hex'>(\n bytes: RecursiveArray<ByteArray> | RecursiveArray<Hex>,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType<to> {\n const encodable = getEncodable(bytes)\n const cursor = createCursor(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (to === 'hex') return bytesToHex(cursor.bytes) as ToRlpReturnType<to>\n return cursor.bytes as ToRlpReturnType<to>\n}\n\nexport type BytesToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function bytesToRlp<to extends To = 'bytes'>(\n bytes: RecursiveArray<ByteArray>,\n to: to | To | undefined = 'bytes',\n): ToRlpReturnType<to> {\n return toRlp(bytes, to)\n}\n\nexport type HexToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function hexToRlp<to extends To = 'hex'>(\n hex: RecursiveArray<Hex>,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType<to> {\n return toRlp(hex, to)\n}\n\nfunction getEncodable(\n bytes: RecursiveArray<ByteArray> | RecursiveArray<Hex>,\n): Encodable {\n if (Array.isArray(bytes))\n return getEncodableList(bytes.map((x) => getEncodable(x)))\n return getEncodableBytes(bytes as any)\n}\n\nfunction getEncodableList(list: Encodable[]): Encodable {\n const bodyLength = list.reduce((acc, x) => acc + x.length, 0)\n\n const sizeOfBodyLength = getSizeOfLength(bodyLength)\n const length = (() => {\n if (bodyLength <= 55) return 1 + bodyLength\n return 1 + sizeOfBodyLength + bodyLength\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bodyLength <= 55) {\n cursor.pushByte(0xc0 + bodyLength)\n } else {\n cursor.pushByte(0xc0 + 55 + sizeOfBodyLength)\n if (sizeOfBodyLength === 1) cursor.pushUint8(bodyLength)\n else if (sizeOfBodyLength === 2) cursor.pushUint16(bodyLength)\n else if (sizeOfBodyLength === 3) cursor.pushUint24(bodyLength)\n else cursor.pushUint32(bodyLength)\n }\n for (const { encode } of list) {\n encode(cursor)\n }\n },\n }\n}\n\nfunction getEncodableBytes(bytesOrHex: ByteArray | Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex\n\n const sizeOfBytesLength = getSizeOfLength(bytes.length)\n const length = (() => {\n if (bytes.length === 1 && bytes[0] < 0x80) return 1\n if (bytes.length <= 55) return 1 + bytes.length\n return 1 + sizeOfBytesLength + bytes.length\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bytes.length === 1 && bytes[0] < 0x80) {\n cursor.pushBytes(bytes)\n } else if (bytes.length <= 55) {\n cursor.pushByte(0x80 + bytes.length)\n cursor.pushBytes(bytes)\n } else {\n cursor.pushByte(0x80 + 55 + sizeOfBytesLength)\n if (sizeOfBytesLength === 1) cursor.pushUint8(bytes.length)\n else if (sizeOfBytesLength === 2) cursor.pushUint16(bytes.length)\n else if (sizeOfBytesLength === 3) cursor.pushUint24(bytes.length)\n else cursor.pushUint32(bytes.length)\n cursor.pushBytes(bytes)\n }\n },\n }\n}\n\nfunction getSizeOfLength(length: number) {\n if (length < 2 ** 8) return 1\n if (length < 2 ** 16) return 2\n if (length < 2 ** 24) return 3\n if (length < 2 ** 32) return 4\n throw new BaseError('Length is too large.')\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../../types/misc.js'\nimport {\n type ConcatHexErrorType,\n concatHex,\n} from '../../../utils/data/concat.js'\nimport {\n type HexToBytesErrorType,\n hexToBytes,\n} from '../../../utils/encoding/toBytes.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../../utils/encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../../../utils/encoding/toRlp.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../../utils/hash/keccak256.js'\nimport type { Authorization } from '../types/authorization.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters<to extends To> = Authorization & {\n /** Output format. @default \"hex\" */\n to?: to | To | undefined\n}\n\nexport type HashAuthorizationReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashAuthorizationErrorType =\n | Keccak256ErrorType\n | ConcatHexErrorType\n | ToRlpErrorType\n | NumberToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Computes an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport function hashAuthorization<to extends To = 'hex'>(\n parameters: HashAuthorizationParameters<to>,\n): HashAuthorizationReturnType<to> {\n const { chainId, contractAddress, nonce, to } = parameters\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n chainId ? numberToHex(chainId) : '0x',\n contractAddress,\n nonce ? numberToHex(nonce) : '0x',\n ]),\n ]),\n )\n if (to === 'bytes') return hexToBytes(hash) as HashAuthorizationReturnType<to>\n return hash as HashAuthorizationReturnType<to>\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../../types/misc.js'\nimport type { OneOf } from '../../../types/utils.js'\nimport {\n type RecoverAddressErrorType,\n recoverAddress,\n} from '../../../utils/signature/recoverAddress.js'\nimport type {\n Authorization,\n SignedAuthorization,\n} from '../types/authorization.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from './hashAuthorization.js'\n\nexport type RecoverAuthorizationAddressParameters<\n authorization extends OneOf<Authorization | SignedAuthorization> = OneOf<\n Authorization | SignedAuthorization\n >,\n //\n _signature = Hex | ByteArray | OneOf<Signature | SignedAuthorization>,\n> = {\n /**\n * The Authorization object.\n *\n * - If an unsigned `authorization` is provided, the `signature` property is required.\n * - If a signed `authorization` is provided, the `signature` property does not need to be provided.\n */\n authorization: authorization | OneOf<Authorization | SignedAuthorization>\n} & (authorization extends SignedAuthorization\n ? {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature?: _signature | undefined\n }\n : {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature: _signature\n })\n\nexport type RecoverAuthorizationAddressReturnType = Address\n\nexport type RecoverAuthorizationAddressErrorType =\n | HashAuthorizationErrorType\n | RecoverAddressErrorType\n | ErrorType\n\nexport async function recoverAuthorizationAddress<\n const authorization extends OneOf<Authorization | SignedAuthorization>,\n>(\n parameters: RecoverAuthorizationAddressParameters<authorization>,\n): Promise<RecoverAuthorizationAddressReturnType> {\n const { authorization, signature } = parameters\n\n return recoverAddress({\n hash: hashAuthorization(authorization as Authorization),\n signature: (signature ?? authorization) as Signature,\n })\n}\n","import type { Account } from '../accounts/types.js'\nimport type { EstimateGasParameters } from '../actions/public/estimateGas.js'\nimport type { Chain } from '../types/chain.js'\nimport { formatEther } from '../utils/unit/formatEther.js'\nimport { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { BaseError } from './base.js'\nimport { prettyPrint } from './transaction.js'\n\nexport type EstimateGasExecutionErrorType = EstimateGasExecutionError & {\n name: 'EstimateGasExecutionError'\n}\nexport class EstimateGasExecutionError extends BaseError {\n override cause: BaseError\n\n constructor(\n cause: BaseError,\n {\n account,\n docsPath,\n chain,\n data,\n gas,\n gasPrice,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n }: Omit<EstimateGasParameters<any>, 'account'> & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n ) {\n const prettyArgs = prettyPrint({\n from: account?.address,\n to,\n value:\n typeof value !== 'undefined' &&\n `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n data,\n gas,\n gasPrice:\n typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n maxFeePerGas:\n typeof maxFeePerGas !== 'undefined' &&\n `${formatGwei(maxFeePerGas)} gwei`,\n maxPriorityFeePerGas:\n typeof maxPriorityFeePerGas !== 'undefined' &&\n `${formatGwei(maxPriorityFeePerGas)} gwei`,\n nonce,\n })\n\n super(cause.shortMessage, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Estimate Gas Arguments:',\n prettyArgs,\n ].filter(Boolean) as string[],\n name: 'EstimateGasExecutionError',\n })\n this.cause = cause\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { EstimateGasParameters } from '../../actions/public/estimateGas.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n EstimateGasExecutionError,\n type EstimateGasExecutionErrorType,\n} from '../../errors/estimateGas.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\n\nimport {\n type GetNodeErrorParameters,\n type GetNodeErrorReturnType,\n getNodeError,\n} from './getNodeError.js'\n\nexport type GetEstimateGasErrorReturnType<cause = ErrorType> = Omit<\n EstimateGasExecutionErrorType,\n 'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getEstimateGasError<err extends ErrorType<string>>(\n err: err,\n {\n docsPath,\n ...args\n }: Omit<EstimateGasParameters, 'account'> & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n): GetEstimateGasErrorReturnType<err> {\n const cause = (() => {\n const cause = getNodeError(\n err as {} as BaseError,\n args as GetNodeErrorParameters,\n )\n if (cause instanceof UnknownNodeError) return err as {} as BaseError\n return cause\n })()\n return new EstimateGasExecutionError(cause, {\n docsPath,\n ...args,\n }) as GetEstimateGasErrorReturnType<err>\n}\n","import { formatGwei } from '../utils/unit/formatGwei.js'\nimport { BaseError } from './base.js'\n\nexport type BaseFeeScalarErrorType = BaseFeeScalarError & {\n name: 'BaseFeeScalarError'\n}\nexport class BaseFeeScalarError extends BaseError {\n constructor() {\n super('`baseFeeMultiplier` must be greater than 1.', {\n name: 'BaseFeeScalarError',\n })\n }\n}\n\nexport type Eip1559FeesNotSupportedErrorType = Eip1559FeesNotSupportedError & {\n name: 'Eip1559FeesNotSupportedError'\n}\nexport class Eip1559FeesNotSupportedError extends BaseError {\n constructor() {\n super('Chain does not support EIP-1559 fees.', {\n name: 'Eip1559FeesNotSupportedError',\n })\n }\n}\n\nexport type MaxFeePerGasTooLowErrorType = MaxFeePerGasTooLowError & {\n name: 'MaxFeePerGasTooLowError'\n}\nexport class MaxFeePerGasTooLowError extends BaseError {\n constructor({ maxPriorityFeePerGas }: { maxPriorityFeePerGas: bigint }) {\n super(\n `\\`maxFeePerGas\\` cannot be less than the \\`maxPriorityFeePerGas\\` (${formatGwei(\n maxPriorityFeePerGas,\n )} gwei).`,\n { name: 'MaxFeePerGasTooLowError' },\n )\n }\n}\n","import type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlockNotFoundErrorType = BlockNotFoundError & {\n name: 'BlockNotFoundError'\n}\nexport class BlockNotFoundError extends BaseError {\n constructor({\n blockHash,\n blockNumber,\n }: {\n blockHash?: Hash | undefined\n blockNumber?: bigint | undefined\n }) {\n let identifier = 'Block'\n if (blockHash) identifier = `Block at hash \"${blockHash}\"`\n if (blockNumber) identifier = `Block at number \"${blockNumber}\"`\n super(`${identifier} could not be found.`, { name: 'BlockNotFoundError' })\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { SignedAuthorizationList } from '../../experimental/eip7702/types/authorization.js'\nimport type { RpcAuthorizationList } from '../../experimental/eip7702/types/rpc.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RpcTransaction } from '../../types/rpc.js'\nimport type { Transaction, TransactionType } from '../../types/transaction.js'\nimport type { ExactPartial, UnionLooseOmit } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\ntype TransactionPendingDependencies =\n | 'blockHash'\n | 'blockNumber'\n | 'transactionIndex'\n\nexport type FormattedTransaction<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'transaction',\n Transaction\n >,\n _ExcludedPendingDependencies extends string = TransactionPendingDependencies &\n ExtractChainFormatterExclude<chain, 'transaction'>,\n> = UnionLooseOmit<_FormatterReturnType, TransactionPendingDependencies> & {\n [_K in _ExcludedPendingDependencies]: never\n} & Pick<\n Transaction<bigint, number, blockTag extends 'pending' ? true : false>,\n TransactionPendingDependencies\n >\n\nexport const transactionType = {\n '0x0': 'legacy',\n '0x1': 'eip2930',\n '0x2': 'eip1559',\n '0x3': 'eip4844',\n '0x4': 'eip7702',\n} as const satisfies Record<Hex, TransactionType>\n\nexport type FormatTransactionErrorType = ErrorType\n\nexport function formatTransaction(transaction: ExactPartial<RpcTransaction>) {\n const transaction_ = {\n ...transaction,\n blockHash: transaction.blockHash ? transaction.blockHash : null,\n blockNumber: transaction.blockNumber\n ? BigInt(transaction.blockNumber)\n : null,\n chainId: transaction.chainId ? hexToNumber(transaction.chainId) : undefined,\n gas: transaction.gas ? BigInt(transaction.gas) : undefined,\n gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : undefined,\n maxFeePerBlobGas: transaction.maxFeePerBlobGas\n ? BigInt(transaction.maxFeePerBlobGas)\n : undefined,\n maxFeePerGas: transaction.maxFeePerGas\n ? BigInt(transaction.maxFeePerGas)\n : undefined,\n maxPriorityFeePerGas: transaction.maxPriorityFeePerGas\n ? BigInt(transaction.maxPriorityFeePerGas)\n : undefined,\n nonce: transaction.nonce ? hexToNumber(transaction.nonce) : undefined,\n to: transaction.to ? transaction.to : null,\n transactionIndex: transaction.transactionIndex\n ? Number(transaction.transactionIndex)\n : null,\n type: transaction.type\n ? (transactionType as any)[transaction.type]\n : undefined,\n typeHex: transaction.type ? transaction.type : undefined,\n value: transaction.value ? BigInt(transaction.value) : undefined,\n v: transaction.v ? BigInt(transaction.v) : undefined,\n } as Transaction\n\n if (transaction.authorizationList)\n transaction_.authorizationList = formatAuthorizationList(\n transaction.authorizationList,\n )\n\n transaction_.yParity = (() => {\n // If `yParity` is provided, we will use it.\n if (transaction.yParity) return Number(transaction.yParity)\n\n // If no `yParity` provided, try derive from `v`.\n if (typeof transaction_.v === 'bigint') {\n if (transaction_.v === 0n || transaction_.v === 27n) return 0\n if (transaction_.v === 1n || transaction_.v === 28n) return 1\n if (transaction_.v >= 35n) return transaction_.v % 2n === 0n ? 1 : 0\n }\n\n return undefined\n })()\n\n if (transaction_.type === 'legacy') {\n delete transaction_.accessList\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n delete transaction_.yParity\n }\n if (transaction_.type === 'eip2930') {\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n }\n if (transaction_.type === 'eip1559') {\n delete transaction_.maxFeePerBlobGas\n }\n return transaction_\n}\n\nexport type DefineTransactionErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineTransaction = /*#__PURE__*/ defineFormatter(\n 'transaction',\n formatTransaction,\n)\n\n//////////////////////////////////////////////////////////////////////////////\n\nfunction formatAuthorizationList(\n authorizationList: RpcAuthorizationList,\n): SignedAuthorizationList {\n return authorizationList.map((authorization) => ({\n contractAddress: (authorization as any).address,\n chainId: Number(authorization.chainId),\n nonce: Number(authorization.nonce),\n r: authorization.r,\n s: authorization.s,\n yParity: Number(authorization.yParity),\n })) as SignedAuthorizationList\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { ExactPartial, Prettify } from '../../types/utils.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { type FormattedTransaction, formatTransaction } from './transaction.js'\n\ntype BlockPendingDependencies = 'hash' | 'logsBloom' | 'nonce' | 'number'\n\nexport type FormattedBlock<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = boolean,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'block',\n Block<bigint, includeTransactions>\n >,\n _ExcludedPendingDependencies extends string = BlockPendingDependencies &\n ExtractChainFormatterExclude<chain, 'block'>,\n _Formatted = Omit<_FormatterReturnType, BlockPendingDependencies> & {\n [_key in _ExcludedPendingDependencies]: never\n } & Pick<\n Block<bigint, includeTransactions, blockTag>,\n BlockPendingDependencies\n >,\n _Transactions = includeTransactions extends true\n ? Prettify<FormattedTransaction<chain, blockTag>>[]\n : Hash[],\n> = Omit<_Formatted, 'transactions'> & {\n transactions: _Transactions\n}\n\nexport type FormatBlockErrorType = ErrorType\n\nexport function formatBlock(block: ExactPartial<RpcBlock>) {\n const transactions = (block.transactions ?? []).map((transaction) => {\n if (typeof transaction === 'string') return transaction\n return formatTransaction(transaction)\n })\n return {\n ...block,\n baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,\n blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : undefined,\n difficulty: block.difficulty ? BigInt(block.difficulty) : undefined,\n excessBlobGas: block.excessBlobGas\n ? BigInt(block.excessBlobGas)\n : undefined,\n gasLimit: block.gasLimit ? BigInt(block.gasLimit) : undefined,\n gasUsed: block.gasUsed ? BigInt(block.gasUsed) : undefined,\n hash: block.hash ? block.hash : null,\n logsBloom: block.logsBloom ? block.logsBloom : null,\n nonce: block.nonce ? block.nonce : null,\n number: block.number ? BigInt(block.number) : null,\n size: block.size ? BigInt(block.size) : undefined,\n timestamp: block.timestamp ? BigInt(block.timestamp) : undefined,\n transactions,\n totalDifficulty: block.totalDifficulty\n ? BigInt(block.totalDifficulty)\n : null,\n } as Block\n}\n\nexport type DefineBlockErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineBlock = /*#__PURE__*/ defineFormatter('block', formatBlock)\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n BlockNotFoundError,\n type BlockNotFoundErrorType,\n} from '../../errors/block.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormattedBlock,\n formatBlock,\n} from '../../utils/formatters/block.js'\n\nexport type GetBlockParameters<\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = {\n /** Whether or not to include transaction data in the response. */\n includeTransactions?: includeTransactions | undefined\n} & (\n | {\n /** Hash of the block. */\n blockHash?: Hash | undefined\n blockNumber?: undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /**\n * The block tag.\n * @default 'latest'\n */\n blockTag?: blockTag | BlockTag | undefined\n }\n)\n\nexport type GetBlockReturnType<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = Prettify<FormattedBlock<chain, includeTransactions, blockTag>>\n\nexport type GetBlockErrorType =\n | BlockNotFoundErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a block at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlock\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockParameters}\n * @returns Information about the block. {@link GetBlockReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlock } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await getBlock(client)\n */\nexport async function getBlock<\n chain extends Chain | undefined,\n account extends Account | undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client<Transport, chain, account>,\n {\n blockHash,\n blockNumber,\n blockTag: blockTag_,\n includeTransactions: includeTransactions_,\n }: GetBlockParameters<includeTransactions, blockTag> = {},\n): Promise<GetBlockReturnType<chain, includeTransactions, blockTag>> {\n const blockTag = blockTag_ ?? 'latest'\n const includeTransactions = includeTransactions_ ?? false\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let block: RpcBlock | null = null\n if (blockHash) {\n block = await client.request(\n {\n method: 'eth_getBlockByHash',\n params: [blockHash, includeTransactions],\n },\n { dedupe: true },\n )\n } else {\n block = await client.request(\n {\n method: 'eth_getBlockByNumber',\n params: [blockNumberHex || blockTag, includeTransactions],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n if (!block) throw new BlockNotFoundError({ blockHash, blockNumber })\n\n const format = client.chain?.formatters?.block?.format || formatBlock\n return format(block)\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetGasPriceReturnType = bigint\n\nexport type GetGasPriceErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the current price of gas (in wei).\n *\n * - Docs: https://viem.sh/docs/actions/public/getGasPrice\n * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n *\n * @param client - Client to use\n * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getGasPrice } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasPrice = await getGasPrice(client)\n */\nexport async function getGasPrice<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client<Transport, chain, account>): Promise<GetGasPriceReturnType> {\n const gasPrice = await client.request({\n method: 'eth_gasPrice',\n })\n return BigInt(gasPrice)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type { Chain, ChainFeesFnParameters } from '../../types/chain.js'\nimport type { GetChainParameter } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToBigIntErrorType,\n hexToBigInt,\n} from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateMaxPriorityFeePerGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n> = GetChainParameter<chain, chainOverride>\n\nexport type EstimateMaxPriorityFeePerGasReturnType = bigint\n\nexport type EstimateMaxPriorityFeePerGasErrorType =\n | GetBlockErrorType\n | HexToBigIntErrorType\n | RequestErrorType\n | GetBlockErrorType\n | GetGasPriceErrorType\n | Eip1559FeesNotSupportedErrorType\n | ErrorType\n\n/**\n * Returns an estimate for the max priority fee per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.defaultPriorityFee`](/docs/clients/chains#fees-defaultpriorityfee) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas\n *\n * @param client - Client to use\n * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateMaxPriorityFeePerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateMaxPriorityFeePerGas(client)\n * // 10000000n\n */\nexport async function estimateMaxPriorityFeePerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n>(\n client: Client<Transport, chain>,\n args?:\n | EstimateMaxPriorityFeePerGasParameters<chain, chainOverride>\n | undefined,\n): Promise<EstimateMaxPriorityFeePerGasReturnType> {\n return internal_estimateMaxPriorityFeePerGas(client, args as any)\n}\n\nexport async function internal_estimateMaxPriorityFeePerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n>(\n client: Client<Transport, chain>,\n args: EstimateMaxPriorityFeePerGasParameters<chain, chainOverride> & {\n block?: Block | undefined\n request?:\n | PrepareTransactionRequestParameters<\n chain,\n Account | undefined,\n chainOverride\n >\n | undefined\n },\n): Promise<EstimateMaxPriorityFeePerGasReturnType> {\n const { block: block_, chain = client.chain, request } = args || {}\n\n try {\n const maxPriorityFeePerGas =\n chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee\n\n if (typeof maxPriorityFeePerGas === 'function') {\n const block =\n block_ || (await getAction(client, getBlock, 'getBlock')({}))\n const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({\n block,\n client,\n request,\n } as ChainFeesFnParameters)\n if (maxPriorityFeePerGas_ === null) throw new Error()\n return maxPriorityFeePerGas_\n }\n\n if (typeof maxPriorityFeePerGas !== 'undefined') return maxPriorityFeePerGas\n\n const maxPriorityFeePerGasHex = await client.request({\n method: 'eth_maxPriorityFeePerGas',\n })\n return hexToBigInt(maxPriorityFeePerGasHex)\n } catch {\n // If the RPC Provider does not support `eth_maxPriorityFeePerGas`\n // fall back to calculating it manually via `gasPrice - baseFeePerGas`.\n // See: https://github.com/ethereum/pm/issues/328#:~:text=eth_maxPriorityFeePerGas%20after%20London%20will%20effectively%20return%20eth_gasPrice%20%2D%20baseFee\n const [block, gasPrice] = await Promise.all([\n block_\n ? Promise.resolve(block_)\n : getAction(client, getBlock, 'getBlock')({}),\n getAction(client, getGasPrice, 'getGasPrice')({}),\n ])\n\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas\n\n if (maxPriorityFeePerGas < 0n) return 0n\n return maxPriorityFeePerGas\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n BaseFeeScalarError,\n type BaseFeeScalarErrorType,\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n ChainEstimateFeesPerGasFnParameters,\n ChainFeesFnParameters,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesLegacy,\n FeeValuesType,\n} from '../../types/fee.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport {\n type EstimateMaxPriorityFeePerGasErrorType,\n internal_estimateMaxPriorityFeePerGas,\n} from './estimateMaxPriorityFeePerGas.js'\nimport { getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateFeesPerGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n type extends FeeValuesType = FeeValuesType,\n> = {\n /**\n * The type of fee values to return.\n *\n * - `legacy`: Returns the legacy gas price.\n * - `eip1559`: Returns the max fee per gas and max priority fee per gas.\n *\n * @default 'eip1559'\n */\n type?: type | FeeValuesType | undefined\n} & GetChainParameter<chain, chainOverride>\n\nexport type EstimateFeesPerGasReturnType<\n type extends FeeValuesType = FeeValuesType,\n> =\n | (type extends 'legacy' ? FeeValuesLegacy : never)\n | (type extends 'eip1559' ? FeeValuesEIP1559 : never)\n\nexport type EstimateFeesPerGasErrorType =\n | BaseFeeScalarErrorType\n | EstimateMaxPriorityFeePerGasErrorType\n | GetGasPriceErrorType\n | Eip1559FeesNotSupportedErrorType\n | ErrorType\n\n/**\n * Returns an estimate for the fees per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.estimateFeesPerGas`](/docs/clients/chains#fees-estimatefeespergas) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateFeesPerGasParameters}\n * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateFeesPerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateFeesPerGas(client)\n * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n */\nexport async function estimateFeesPerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n type extends FeeValuesType = 'eip1559',\n>(\n client: Client<Transport, chain>,\n args?: EstimateFeesPerGasParameters<chain, chainOverride, type> | undefined,\n): Promise<EstimateFeesPerGasReturnType<type>> {\n return internal_estimateFeesPerGas(client, args as any)\n}\n\nexport async function internal_estimateFeesPerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n type extends FeeValuesType = 'eip1559',\n>(\n client: Client<Transport, chain>,\n args: EstimateFeesPerGasParameters<chain, chainOverride, type> & {\n block?: Block | undefined\n request?: PrepareTransactionRequestParameters<Chain, Account> | undefined\n },\n): Promise<EstimateFeesPerGasReturnType<type>> {\n const {\n block: block_,\n chain = client.chain,\n request,\n type = 'eip1559',\n } = args || {}\n\n const baseFeeMultiplier = await (async () => {\n if (typeof chain?.fees?.baseFeeMultiplier === 'function')\n return chain.fees.baseFeeMultiplier({\n block: block_ as Block,\n client,\n request,\n } as ChainFeesFnParameters)\n return chain?.fees?.baseFeeMultiplier ?? 1.2\n })()\n if (baseFeeMultiplier < 1) throw new BaseFeeScalarError()\n\n const decimals = baseFeeMultiplier.toString().split('.')[1]?.length ?? 0\n const denominator = 10 ** decimals\n const multiply = (base: bigint) =>\n (base * BigInt(Math.ceil(baseFeeMultiplier * denominator))) /\n BigInt(denominator)\n\n const block = block_\n ? block_\n : await getAction(client, getBlock, 'getBlock')({})\n\n if (typeof chain?.fees?.estimateFeesPerGas === 'function') {\n const fees = (await chain.fees.estimateFeesPerGas({\n block: block_ as Block,\n client,\n multiply,\n request,\n type,\n } as ChainEstimateFeesPerGasFnParameters)) as unknown as EstimateFeesPerGasReturnType<type>\n\n if (fees !== null) return fees\n }\n\n if (type === 'eip1559') {\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas =\n typeof request?.maxPriorityFeePerGas === 'bigint'\n ? request.maxPriorityFeePerGas\n : await internal_estimateMaxPriorityFeePerGas(\n client as Client<Transport, Chain>,\n {\n block: block as Block,\n chain,\n request,\n },\n )\n\n const baseFeePerGas = multiply(block.baseFeePerGas)\n const maxFeePerGas =\n request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas\n\n return {\n maxFeePerGas,\n maxPriorityFeePerGas,\n } as EstimateFeesPerGasReturnType<type>\n }\n\n const gasPrice =\n request?.gasPrice ??\n multiply(await getAction(client, getGasPrice, 'getGasPrice')({}))\n return {\n gasPrice,\n } as EstimateFeesPerGasReturnType<type>\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetTransactionCountParameters = {\n /** The account address. */\n address: Address\n} & (\n | {\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /** The block tag. Defaults to 'latest'. */\n blockTag?: BlockTag | undefined\n }\n)\nexport type GetTransactionCountReturnType = number\n\nexport type GetTransactionCountErrorType =\n | RequestErrorType\n | NumberToHexErrorType\n | HexToNumberErrorType\n | ErrorType\n\n/**\n * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms#transaction) an Account has sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount\n * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionCountParameters}\n * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionCount = await getTransactionCount(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function getTransactionCount<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n { address, blockTag = 'latest', blockNumber }: GetTransactionCountParameters,\n): Promise<GetTransactionCountReturnType> {\n const count = await client.request(\n {\n method: 'eth_getTransactionCount',\n params: [address, blockNumber ? numberToHex(blockNumber) : blockTag],\n },\n { dedupe: Boolean(blockNumber) },\n )\n return hexToNumber(count)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type BlobsToCommitmentsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[] =\n | readonly ByteArray[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Blobs to transform into commitments. */\n blobs: blobs | readonly ByteArray[] | readonly Hex[]\n /** KZG implementation. */\n kzg: Pick<Kzg, 'blobToKzgCommitment'>\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type BlobsToCommitmentsReturnType<to extends To> =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type BlobsToCommitmentsErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Compute commitments from a list of blobs.\n *\n * @example\n * ```ts\n * import { blobsToCommitments, toBlobs } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * ```\n */\nexport function blobsToCommitments<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: BlobsToCommitmentsParameters<blobs, to>,\n): BlobsToCommitmentsReturnType<to> {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n\n const commitments: ByteArray[] = []\n for (const blob of blobs)\n commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)))\n\n return (to === 'bytes'\n ? commitments\n : commitments.map((x) =>\n bytesToHex(x),\n )) as {} as BlobsToCommitmentsReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type blobsToProofsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[],\n commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Blobs to transform into proofs. */\n blobs: blobs\n /** Commitments for the blobs. */\n commitments: commitments &\n (commitments extends _blobsType\n ? {}\n : `commitments must be the same type as blobs`)\n /** KZG implementation. */\n kzg: Pick<Kzg, 'computeBlobKzgProof'>\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type blobsToProofsReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray[] : never)\n | (to extends 'hex' ? Hex[] : never)\n\nexport type blobsToProofsErrorType =\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Compute the proofs for a list of blobs and their commitments.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n * ```\n */\nexport function blobsToProofs<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n const commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: blobsToProofsParameters<blobs, commitments, to>,\n): blobsToProofsReturnType<to> {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n const commitments = (\n typeof parameters.commitments[0] === 'string'\n ? parameters.commitments.map((x) => hexToBytes(x as any))\n : parameters.commitments\n ) as ByteArray[]\n\n const proofs: ByteArray[] = []\n for (let i = 0; i < blobs.length; i++) {\n const blob = blobs[i]\n const commitment = commitments[i]\n proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)))\n }\n\n return (to === 'bytes'\n ? proofs\n : proofs.map((x) => bytesToHex(x))) as {} as blobsToProofsReturnType<to>\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { aexists, aoutput } from './_assert.js';\nimport { type Input, Hash, createView, toBytes } from './utils.js';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.js';\nimport { type CHash, rotr, wrapConstructor } from './utils.js';\n\n/** Round constants: first 32 bits of fractional parts of the cube roots of the first 64 primes 2..311). */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Initial state: first 32 bits of fractional parts of the square roots of the first 8 primes 2..19. */\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n/**\n * Temporary buffer, not used to store anything between runs.\n * Named this way because it matches specification.\n */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n SHA256_W.fill(0);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n\n/**\n * Constants taken from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf.\n */\nclass SHA224 extends SHA256 {\n protected A = 0xc1059ed8 | 0;\n protected B = 0x367cd507 | 0;\n protected C = 0x3070dd17 | 0;\n protected D = 0xf70e5939 | 0;\n protected E = 0xffc00b31 | 0;\n protected F = 0x68581511 | 0;\n protected G = 0x64f98fa7 | 0;\n protected H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/** SHA2-256 hash function */\nexport const sha256: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/** SHA2-224 hash function */\nexport const sha224: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","import { sha256 as noble_sha256 } from '@noble/hashes/sha256'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type Sha256Hash<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type Sha256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function sha256<to extends To = 'hex'>(\n value: Hex | ByteArray,\n to_?: to | undefined,\n): Sha256Hash<to> {\n const to = to_ || 'hex'\n const bytes = noble_sha256(\n isHex(value, { strict: false }) ? toBytes(value) : value,\n )\n if (to === 'bytes') return bytes as Sha256Hash<to>\n return toHex(bytes) as Sha256Hash<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Sha256ErrorType, sha256 } from '../hash/sha256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentToVersionedHashParameters<\n commitment extends Uint8Array | Hex = Uint8Array | Hex,\n to extends To | undefined = undefined,\n> = {\n /** Commitment from blob. */\n commitment: commitment | Uint8Array | Hex\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hash. */\n version?: number | undefined\n}\n\nexport type CommitmentToVersionedHashReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type CommitmentToVersionedHashErrorType =\n | Sha256ErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Transform a commitment to it's versioned hash.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentToVersionedHash,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const [commitment] = blobsToCommitments({ blobs, kzg })\n * const versionedHash = commitmentToVersionedHash({ commitment })\n * ```\n */\nexport function commitmentToVersionedHash<\n const commitment extends Hex | ByteArray,\n to extends To =\n | (commitment extends Hex ? 'hex' : never)\n | (commitment extends ByteArray ? 'bytes' : never),\n>(\n parameters: CommitmentToVersionedHashParameters<commitment, to>,\n): CommitmentToVersionedHashReturnType<to> {\n const { commitment, version = 1 } = parameters\n const to = parameters.to ?? (typeof commitment === 'string' ? 'hex' : 'bytes')\n\n const versionedHash = sha256(commitment, 'bytes')\n versionedHash.set([version], 0)\n return (\n to === 'bytes' ? versionedHash : bytesToHex(versionedHash)\n ) as CommitmentToVersionedHashReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CommitmentToVersionedHashErrorType,\n commitmentToVersionedHash,\n} from './commitmentToVersionedHash.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentsToVersionedHashesParameters<\n commitments extends readonly Uint8Array[] | readonly Hex[] =\n | readonly Uint8Array[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Commitments from blobs. */\n commitments: commitments | readonly Uint8Array[] | readonly Hex[]\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hashes. */\n version?: number | undefined\n}\n\nexport type CommitmentsToVersionedHashesReturnType<to extends To> =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type CommitmentsToVersionedHashesErrorType =\n | CommitmentToVersionedHashErrorType\n | ErrorType\n\n/**\n * Transform a list of commitments to their versioned hashes.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentsToVersionedHashes,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const versionedHashes = commitmentsToVersionedHashes({ commitments })\n * ```\n */\nexport function commitmentsToVersionedHashes<\n const commitments extends readonly Uint8Array[] | readonly Hex[],\n to extends To =\n | (commitments extends readonly Hex[] ? 'hex' : never)\n | (commitments extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: CommitmentsToVersionedHashesParameters<commitments, to>,\n): CommitmentsToVersionedHashesReturnType<to> {\n const { commitments, version } = parameters\n\n const to =\n parameters.to ?? (typeof commitments[0] === 'string' ? 'hex' : 'bytes')\n\n const hashes: Uint8Array[] | Hex[] = []\n for (const commitment of commitments) {\n hashes.push(\n commitmentToVersionedHash({\n commitment,\n to,\n version,\n }) as any,\n )\n }\n return hashes as any\n}\n","import { versionedHashVersionKzg } from '../constants/kzg.js'\nimport type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlobSizeTooLargeErrorType = BlobSizeTooLargeError & {\n name: 'BlobSizeTooLargeError'\n}\nexport class BlobSizeTooLargeError extends BaseError {\n constructor({ maxSize, size }: { maxSize: number; size: number }) {\n super('Blob size is too large.', {\n metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size} bytes`],\n name: 'BlobSizeTooLargeError',\n })\n }\n}\n\nexport type EmptyBlobErrorType = EmptyBlobError & {\n name: 'EmptyBlobError'\n}\nexport class EmptyBlobError extends BaseError {\n constructor() {\n super('Blob data must not be empty.', { name: 'EmptyBlobError' })\n }\n}\n\nexport type InvalidVersionedHashSizeErrorType =\n InvalidVersionedHashSizeError & {\n name: 'InvalidVersionedHashSizeError'\n }\nexport class InvalidVersionedHashSizeError extends BaseError {\n constructor({\n hash,\n size,\n }: {\n hash: Hash\n size: number\n }) {\n super(`Versioned hash \"${hash}\" size is invalid.`, {\n metaMessages: ['Expected: 32', `Received: ${size}`],\n name: 'InvalidVersionedHashSizeError',\n })\n }\n}\n\nexport type InvalidVersionedHashVersionErrorType =\n InvalidVersionedHashVersionError & {\n name: 'InvalidVersionedHashVersionError'\n }\nexport class InvalidVersionedHashVersionError extends BaseError {\n constructor({\n hash,\n version,\n }: {\n hash: Hash\n version: number\n }) {\n super(`Versioned hash \"${hash}\" version is invalid.`, {\n metaMessages: [\n `Expected: ${versionedHashVersionKzg}`,\n `Received: ${version}`,\n ],\n name: 'InvalidVersionedHashVersionError',\n })\n }\n}\n","import {\n bytesPerBlob,\n bytesPerFieldElement,\n fieldElementsPerBlob,\n maxBytesPerTransaction,\n} from '../../constants/blob.js'\nimport {\n BlobSizeTooLargeError,\n type BlobSizeTooLargeErrorType,\n EmptyBlobError,\n type EmptyBlobErrorType,\n} from '../../errors/blob.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type CreateCursorErrorType, createCursor } from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobsParameters<\n data extends Hex | ByteArray = Hex | ByteArray,\n to extends To | undefined = undefined,\n> = {\n /** Data to transform to a blob. */\n data: data | Hex | ByteArray\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type ToBlobsReturnType<to extends To> =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type ToBlobsErrorType =\n | BlobSizeTooLargeErrorType\n | BytesToHexErrorType\n | CreateCursorErrorType\n | EmptyBlobErrorType\n | HexToBytesErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data to blobs.\n *\n * @example\n * ```ts\n * import { toBlobs, stringToHex } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * ```\n */\nexport function toBlobs<\n const data extends Hex | ByteArray,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never),\n>(parameters: ToBlobsParameters<data, to>): ToBlobsReturnType<to> {\n const to =\n parameters.to ?? (typeof parameters.data === 'string' ? 'hex' : 'bytes')\n const data = (\n typeof parameters.data === 'string'\n ? hexToBytes(parameters.data)\n : parameters.data\n ) as ByteArray\n\n const size_ = size(data)\n if (!size_) throw new EmptyBlobError()\n if (size_ > maxBytesPerTransaction)\n throw new BlobSizeTooLargeError({\n maxSize: maxBytesPerTransaction,\n size: size_,\n })\n\n const blobs = []\n\n let active = true\n let position = 0\n while (active) {\n const blob = createCursor(new Uint8Array(bytesPerBlob))\n\n let size = 0\n while (size < fieldElementsPerBlob) {\n const bytes = data.slice(position, position + (bytesPerFieldElement - 1))\n\n // Push a zero byte so the field element doesn't overflow the BLS modulus.\n blob.pushByte(0x00)\n\n // Push the current segment of data bytes.\n blob.pushBytes(bytes)\n\n // If we detect that the current segment of data bytes is less than 31 bytes,\n // we can stop processing and push a terminator byte to indicate the end of the blob.\n if (bytes.length < 31) {\n blob.pushByte(0x80)\n active = false\n break\n }\n\n size++\n position += 31\n }\n\n blobs.push(blob)\n }\n\n return (\n to === 'bytes'\n ? blobs.map((x) => x.bytes)\n : blobs.map((x) => bytesToHex(x.bytes))\n ) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { BlobSidecars } from '../../types/eip4844.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from './blobsToCommitments.js'\nimport { blobsToProofs, type blobsToProofsErrorType } from './blobsToProofs.js'\nimport { type ToBlobsErrorType, toBlobs } from './toBlobs.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobSidecarsParameters<\n data extends Hex | ByteArray | undefined = undefined,\n blobs extends readonly Hex[] | readonly ByteArray[] | undefined = undefined,\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Return type. */\n to?: to | To | undefined\n} & OneOf<\n | {\n /** Data to transform into blobs. */\n data: data | Hex | ByteArray\n /** KZG implementation. */\n kzg: Kzg\n }\n | {\n /** Blobs. */\n blobs: blobs | readonly Hex[] | readonly ByteArray[]\n /** Commitment for each blob. */\n commitments: _blobsType | readonly Hex[] | readonly ByteArray[]\n /** Proof for each blob. */\n proofs: _blobsType | readonly Hex[] | readonly ByteArray[]\n }\n>\n\nexport type ToBlobSidecarsReturnType<to extends To> =\n | (to extends 'bytes' ? BlobSidecars<ByteArray> : never)\n | (to extends 'hex' ? BlobSidecars<Hex> : never)\n\nexport type ToBlobSidecarsErrorType =\n | BlobsToCommitmentsErrorType\n | ToBlobsErrorType\n | blobsToProofsErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data (or blobs, commitments, & proofs) into a sidecar array.\n *\n * @example\n * ```ts\n * import { toBlobSidecars, stringToHex } from 'viem'\n *\n * const sidecars = toBlobSidecars({ data: stringToHex('hello world') })\n * ```\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs,\n * blobsToProofs,\n * toBlobSidecars,\n * stringToHex\n * } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n *\n * const sidecars = toBlobSidecars({ blobs, commitments, proofs })\n * ```\n */\nexport function toBlobSidecars<\n const data extends Hex | ByteArray | undefined = undefined,\n const blobs extends\n | readonly Hex[]\n | readonly ByteArray[]\n | undefined = undefined,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never)\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: ToBlobSidecarsParameters<data, blobs, to>,\n): ToBlobSidecarsReturnType<to> {\n const { data, kzg, to } = parameters\n const blobs = parameters.blobs ?? toBlobs({ data: data!, to })\n const commitments =\n parameters.commitments ?? blobsToCommitments({ blobs, kzg: kzg!, to })\n const proofs =\n parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg: kzg!, to })\n\n const sidecars: BlobSidecars = []\n for (let i = 0; i < blobs.length; i++)\n sidecars.push({\n blob: blobs[i],\n commitment: commitments[i],\n proof: proofs[i],\n })\n\n return sidecars as ToBlobSidecarsReturnType<to>\n}\n","import {\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n} from '../../index.js'\nimport type {\n TransactionRequestGeneric,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n} from '../../types/transaction.js'\nimport type { Assign, ExactPartial, IsNever, OneOf } from '../../types/utils.js'\n\nexport type GetTransactionType<\n transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n > = TransactionSerializableGeneric,\n result =\n | (transaction extends LegacyProperties ? 'legacy' : never)\n | (transaction extends EIP1559Properties ? 'eip1559' : never)\n | (transaction extends EIP2930Properties ? 'eip2930' : never)\n | (transaction extends EIP4844Properties ? 'eip4844' : never)\n | (transaction extends EIP7702Properties ? 'eip7702' : never)\n | (transaction['type'] extends TransactionSerializableGeneric['type']\n ? Extract<transaction['type'], string>\n : never),\n> = IsNever<keyof transaction> extends true\n ? string\n : IsNever<result> extends false\n ? result\n : string\n\nexport type GetTransactionTypeErrorType =\n | InvalidSerializableTransactionErrorType\n | ErrorType\n\nexport function getTransactionType<\n const transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n >,\n>(transaction: transaction): GetTransactionType<transaction> {\n if (transaction.type)\n return transaction.type as GetTransactionType<transaction>\n\n if (typeof transaction.authorizationList !== 'undefined')\n return 'eip7702' as any\n\n if (\n typeof transaction.blobs !== 'undefined' ||\n typeof transaction.blobVersionedHashes !== 'undefined' ||\n typeof transaction.maxFeePerBlobGas !== 'undefined' ||\n typeof transaction.sidecars !== 'undefined'\n )\n return 'eip4844' as any\n\n if (\n typeof transaction.maxFeePerGas !== 'undefined' ||\n typeof transaction.maxPriorityFeePerGas !== 'undefined'\n ) {\n return 'eip1559' as any\n }\n\n if (typeof transaction.gasPrice !== 'undefined') {\n if (typeof transaction.accessList !== 'undefined') return 'eip2930' as any\n return 'legacy' as any\n }\n\n throw new InvalidSerializableTransactionError({ transaction })\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// Types\n\ntype BaseProperties = {\n accessList?: undefined\n authorizationList?: undefined\n blobs?: undefined\n blobVersionedHashes?: undefined\n gasPrice?: undefined\n maxFeePerBlobGas?: undefined\n maxFeePerGas?: undefined\n maxPriorityFeePerGas?: undefined\n sidecars?: undefined\n}\n\ntype LegacyProperties = Assign<BaseProperties, FeeValuesLegacy>\ntype EIP1559Properties = Assign<\n BaseProperties,\n OneOf<\n | {\n maxFeePerGas: FeeValuesEIP1559['maxFeePerGas']\n }\n | {\n maxPriorityFeePerGas: FeeValuesEIP1559['maxPriorityFeePerGas']\n },\n FeeValuesEIP1559\n > & {\n accessList?: TransactionSerializableEIP2930['accessList'] | undefined\n }\n>\ntype EIP2930Properties = Assign<\n ExactPartial<LegacyProperties>,\n {\n accessList: TransactionSerializableEIP2930['accessList']\n }\n>\ntype EIP4844Properties = Assign<\n ExactPartial<EIP1559Properties>,\n ExactPartial<FeeValuesEIP4844> &\n OneOf<\n | {\n blobs: TransactionSerializableEIP4844['blobs']\n }\n | {\n blobVersionedHashes: TransactionSerializableEIP4844['blobVersionedHashes']\n }\n | {\n sidecars: TransactionSerializableEIP4844['sidecars']\n },\n TransactionSerializableEIP4844\n >\n>\ntype EIP7702Properties = Assign<\n ExactPartial<EIP1559Properties>,\n {\n authorizationList: TransactionSerializableEIP7702['authorizationList']\n }\n>\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\n\nexport type GetChainIdReturnType = number\n\nexport type GetChainIdErrorType =\n | HexToNumberErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @param client - Client to use\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getChainId } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const chainId = await getChainId(client)\n * // 1\n */\nexport async function getChainId<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client<Transport, chain, account>): Promise<GetChainIdReturnType> {\n const chainIdHex = await client.request(\n {\n method: 'eth_chainId',\n },\n { dedupe: true },\n )\n return hexToNumber(chainIdHex)\n}\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport {\n type EstimateFeesPerGasErrorType,\n internal_estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n type EstimateGasErrorType,\n type EstimateGasParameters,\n estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n type GetBlockErrorType,\n getBlock as getBlock_,\n} from '../../actions/public/getBlock.js'\nimport {\n type GetTransactionCountErrorType,\n getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { AccountNotFoundErrorType } from '../../errors/account.js'\nimport {\n Eip1559FeesNotSupportedError,\n MaxFeePerGasTooLowError,\n} from '../../errors/fee.js'\nimport type { DeriveAccount, GetAccountParameter } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type { Chain, DeriveChain } from '../../types/chain.js'\nimport type { GetChainParameter } from '../../types/chain.js'\nimport type { GetTransactionRequestKzgParameter } from '../../types/kzg.js'\nimport type {\n TransactionRequest,\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestLegacy,\n TransactionSerializable,\n} from '../../types/transaction.js'\nimport type {\n ExactPartial,\n IsNever,\n Prettify,\n UnionOmit,\n UnionRequiredBy,\n} from '../../types/utils.js'\nimport { blobsToCommitments } from '../../utils/blob/blobsToCommitments.js'\nimport { blobsToProofs } from '../../utils/blob/blobsToProofs.js'\nimport { commitmentsToVersionedHashes } from '../../utils/blob/commitmentsToVersionedHashes.js'\nimport { toBlobSidecars } from '../../utils/blob/toBlobSidecars.js'\nimport type { FormattedTransactionRequest } from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { NonceManager } from '../../utils/nonceManager.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type GetTransactionType,\n getTransactionType,\n} from '../../utils/transaction/getTransactionType.js'\nimport { getChainId as getChainId_ } from '../public/getChainId.js'\n\nexport const defaultParameters = [\n 'blobVersionedHashes',\n 'chainId',\n 'fees',\n 'gas',\n 'nonce',\n 'type',\n] as const\n\n/** @internal */\nexport const eip1559NetworkCache = /*#__PURE__*/ new Map<string, boolean>()\n\nexport type PrepareTransactionRequestParameterType =\n | 'blobVersionedHashes'\n | 'chainId'\n | 'fees'\n | 'gas'\n | 'nonce'\n | 'sidecars'\n | 'type'\ntype ParameterTypeToParameters<\n parameterType extends PrepareTransactionRequestParameterType,\n> = parameterType extends 'fees'\n ? 'maxFeePerGas' | 'maxPriorityFeePerGas' | 'gasPrice'\n : parameterType\n\nexport type PrepareTransactionRequestRequest<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,\n> = UnionOmit<FormattedTransactionRequest<_derivedChain>, 'from'> &\n GetTransactionRequestKzgParameter & {\n /**\n * Nonce manager to use for the transaction request.\n */\n nonceManager?: NonceManager | undefined\n /**\n * Parameters to prepare for the transaction request.\n *\n * @default ['blobVersionedHashes', 'chainId', 'fees', 'gas', 'nonce', 'type']\n */\n parameters?: readonly PrepareTransactionRequestParameterType[] | undefined\n }\n\nexport type PrepareTransactionRequestParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest<chain, chainOverride>,\n> = request &\n GetAccountParameter<account, accountOverride, false, true> &\n GetChainParameter<chain, chainOverride> &\n GetTransactionRequestKzgParameter<request> & { chainId?: number | undefined }\n\nexport type PrepareTransactionRequestReturnType<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest<chain, chainOverride>,\n ///\n _derivedAccount extends Account | Address | undefined = DeriveAccount<\n account,\n accountOverride\n >,\n _derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,\n _transactionType = request['type'] extends string | undefined\n ? request['type']\n : GetTransactionType<request> extends 'legacy'\n ? unknown\n : GetTransactionType<request>,\n _transactionRequest extends TransactionRequest =\n | (_transactionType extends 'legacy' ? TransactionRequestLegacy : never)\n | (_transactionType extends 'eip1559' ? TransactionRequestEIP1559 : never)\n | (_transactionType extends 'eip2930' ? TransactionRequestEIP2930 : never)\n | (_transactionType extends 'eip4844' ? TransactionRequestEIP4844 : never)\n | (_transactionType extends 'eip7702' ? TransactionRequestEIP7702 : never),\n> = Prettify<\n UnionRequiredBy<\n Extract<\n UnionOmit<FormattedTransactionRequest<_derivedChain>, 'from'> &\n (_derivedChain extends Chain\n ? { chain: _derivedChain }\n : { chain?: undefined }) &\n (_derivedAccount extends Account\n ? { account: _derivedAccount; from: Address }\n : { account?: undefined; from?: undefined }),\n IsNever<_transactionRequest> extends true\n ? unknown\n : ExactPartial<_transactionRequest>\n > & { chainId?: number | undefined },\n ParameterTypeToParameters<\n request['parameters'] extends readonly PrepareTransactionRequestParameterType[]\n ? request['parameters'][number]\n : (typeof defaultParameters)[number]\n >\n > &\n (unknown extends request['kzg'] ? {} : Pick<request, 'kzg'>)\n>\n\nexport type PrepareTransactionRequestErrorType =\n | AccountNotFoundErrorType\n | AssertRequestErrorType\n | ParseAccountErrorType\n | GetBlockErrorType\n | GetTransactionCountErrorType\n | EstimateGasErrorType\n | EstimateFeesPerGasErrorType\n\n/**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\nexport async function prepareTransactionRequest<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends PrepareTransactionRequestRequest<chain, chainOverride>,\n accountOverride extends Account | Address | undefined = undefined,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n): Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n> {\n const {\n account: account_ = client.account,\n blobs,\n chain,\n gas,\n kzg,\n nonce,\n nonceManager,\n parameters = defaultParameters,\n type,\n } = args\n const account = account_ ? parseAccount(account_) : account_\n\n const request = { ...args, ...(account ? { from: account?.address } : {}) }\n\n let block: Block | undefined\n async function getBlock(): Promise<Block> {\n if (block) return block\n block = await getAction(\n client,\n getBlock_,\n 'getBlock',\n )({ blockTag: 'latest' })\n return block\n }\n\n let chainId: number | undefined\n async function getChainId(): Promise<number> {\n if (chainId) return chainId\n if (chain) return chain.id\n if (typeof args.chainId !== 'undefined') return args.chainId\n const chainId_ = await getAction(client, getChainId_, 'getChainId')({})\n chainId = chainId_\n return chainId\n }\n\n if (parameters.includes('nonce') && typeof nonce === 'undefined' && account) {\n if (nonceManager) {\n const chainId = await getChainId()\n request.nonce = await nonceManager.consume({\n address: account.address,\n chainId,\n client,\n })\n } else {\n request.nonce = await getAction(\n client,\n getTransactionCount,\n 'getTransactionCount',\n )({\n address: account.address,\n blockTag: 'pending',\n })\n }\n }\n\n if (\n (parameters.includes('blobVersionedHashes') ||\n parameters.includes('sidecars')) &&\n blobs &&\n kzg\n ) {\n const commitments = blobsToCommitments({ blobs, kzg })\n\n if (parameters.includes('blobVersionedHashes')) {\n const versionedHashes = commitmentsToVersionedHashes({\n commitments,\n to: 'hex',\n })\n request.blobVersionedHashes = versionedHashes\n }\n if (parameters.includes('sidecars')) {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n const sidecars = toBlobSidecars({\n blobs,\n commitments,\n proofs,\n to: 'hex',\n })\n request.sidecars = sidecars\n }\n }\n\n if (parameters.includes('chainId')) request.chainId = await getChainId()\n\n if (\n (parameters.includes('fees') || parameters.includes('type')) &&\n typeof type === 'undefined'\n ) {\n try {\n request.type = getTransactionType(\n request as TransactionSerializable,\n ) as any\n } catch {\n let isEip1559Network = eip1559NetworkCache.get(client.uid)\n if (typeof isEip1559Network === 'undefined') {\n const block = await getBlock()\n isEip1559Network = typeof block?.baseFeePerGas === 'bigint'\n eip1559NetworkCache.set(client.uid, isEip1559Network)\n }\n request.type = isEip1559Network ? 'eip1559' : 'legacy'\n }\n }\n\n if (parameters.includes('fees')) {\n // TODO(4844): derive blob base fees once https://github.com/ethereum/execution-apis/pull/486 is merged.\n\n if (request.type !== 'legacy' && request.type !== 'eip2930') {\n // EIP-1559 fees\n if (\n typeof request.maxFeePerGas === 'undefined' ||\n typeof request.maxPriorityFeePerGas === 'undefined'\n ) {\n const block = await getBlock()\n const { maxFeePerGas, maxPriorityFeePerGas } =\n await internal_estimateFeesPerGas(client, {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n })\n\n if (\n typeof args.maxPriorityFeePerGas === 'undefined' &&\n args.maxFeePerGas &&\n args.maxFeePerGas < maxPriorityFeePerGas\n )\n throw new MaxFeePerGasTooLowError({\n maxPriorityFeePerGas,\n })\n\n request.maxPriorityFeePerGas = maxPriorityFeePerGas\n request.maxFeePerGas = maxFeePerGas\n }\n } else {\n // Legacy fees\n if (\n typeof args.maxFeePerGas !== 'undefined' ||\n typeof args.maxPriorityFeePerGas !== 'undefined'\n )\n throw new Eip1559FeesNotSupportedError()\n\n if (typeof args.gasPrice === 'undefined') {\n const block = await getBlock()\n const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(\n client,\n {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n type: 'legacy',\n },\n )\n request.gasPrice = gasPrice_\n }\n }\n }\n\n if (parameters.includes('gas') && typeof gas === 'undefined')\n request.gas = await getAction(\n client,\n estimateGas,\n 'estimateGas',\n )({\n ...request,\n account: account\n ? { address: account.address, type: 'json-rpc' }\n : account,\n } as EstimateGasParameters)\n\n assertRequest(request as AssertRequestParameters)\n\n delete request.parameters\n\n return request as any\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetBalanceParameters = {\n /** The address of the account. */\n address: Address\n} & (\n | {\n /** The balance of the account at a block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /** The balance of the account at a block tag. */\n blockTag?: BlockTag | undefined\n }\n)\n\nexport type GetBalanceReturnType = bigint\n\nexport type GetBalanceErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the balance of an address in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBalance\n * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n *\n * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther).\n *\n * ```ts\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * blockTag: 'safe'\n * })\n * const balanceAsEther = formatEther(balance)\n * // \"6.942\"\n * ```\n *\n * @param client - Client to use\n * @param parameters - {@link GetBalanceParameters}\n * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBalance } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n * // 10000000000000000000000n (wei)\n */\nexport async function getBalance<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { address, blockNumber, blockTag = 'latest' }: GetBalanceParameters,\n): Promise<GetBalanceReturnType> {\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n\n const balance = await client.request({\n method: 'eth_getBalance',\n params: [address, blockNumberHex || blockTag],\n })\n return BigInt(balance)\n}\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n recoverAuthorizationAddress,\n} from '../../experimental/eip7702/utils/recoverAuthorizationAddress.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type GetEstimateGasErrorReturnType,\n getEstimateGasError,\n} from '../../utils/errors/getEstimateGasError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { serializeStateOverride } from '../../utils/stateOverride.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type PrepareTransactionRequestParameters,\n prepareTransactionRequest,\n} from '../wallet/prepareTransactionRequest.js'\nimport { getBalance } from './getBalance.js'\n\nexport type EstimateGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit<FormattedEstimateGas<chain>, 'from'> & {\n account?: Account | Address | undefined\n stateOverride?: StateOverride | undefined\n} & (\n | {\n /** The balance of the account at a block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The balance of the account at a block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n )\ntype FormattedEstimateGas<chain extends Chain | undefined = Chain | undefined> =\n FormattedTransactionRequest<chain>\n\nexport type EstimateGasReturnType = bigint\n\nexport type EstimateGasErrorType = GetEstimateGasErrorReturnType<\n | ParseAccountErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | RecoverAuthorizationAddressErrorType\n | AssertRequestErrorType\n>\n\n/**\n * Estimates the gas necessary to complete a transaction without submitting it to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateGas\n * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateGas } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasEstimate = await estimateGas(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\nexport async function estimateGas<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n args: EstimateGasParameters<chain>,\n): Promise<EstimateGasReturnType> {\n const { account: account_ = client.account } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n try {\n const {\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n blockNumber,\n blockTag,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n value,\n stateOverride,\n ...rest\n } = (await prepareTransactionRequest(client, {\n ...args,\n parameters:\n // Some RPC Providers do not compute versioned hashes from blobs. We will need\n // to compute them.\n account?.type === 'local' ? undefined : ['blobVersionedHashes'],\n } as PrepareTransactionRequestParameters)) as EstimateGasParameters\n\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcStateOverride = serializeStateOverride(stateOverride)\n\n const to = await (async () => {\n // If `to` exists on the parameters, use that.\n if (rest.to) return rest.to\n\n // If no `to` exists, and we are sending a EIP-7702 transaction, use the\n // address of the first authorization in the list.\n if (authorizationList && authorizationList.length > 0)\n return await recoverAuthorizationAddress({\n authorization: authorizationList[0],\n }).catch(() => {\n throw new BaseError(\n '`to` is required. Could not infer from `authorizationList`',\n )\n })\n\n // Otherwise, we are sending a deployment transaction.\n return undefined\n })()\n\n assertRequest(args as AssertRequestParameters)\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format({\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n from: account?.address,\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n } as TransactionRequest)\n\n function estimateGas_rpc(parameters: {\n block: any\n request: any\n rpcStateOverride: any\n }) {\n const { block, request, rpcStateOverride } = parameters\n return client.request({\n method: 'eth_estimateGas',\n params: rpcStateOverride\n ? [request, block ?? 'latest', rpcStateOverride]\n : block\n ? [request, block]\n : [request],\n })\n }\n\n let estimate = BigInt(\n await estimateGas_rpc({ block, request, rpcStateOverride }),\n )\n\n // TODO(7702): Remove this once https://github.com/ethereum/execution-apis/issues/561 is resolved.\n // Authorization list schema is not implemented on JSON-RPC spec yet, so we need to\n // manually estimate the gas.\n if (authorizationList) {\n const value = await getBalance(client, { address: request.from })\n const estimates = await Promise.all(\n authorizationList.map(async (authorization) => {\n const { contractAddress } = authorization\n const estimate = await estimateGas_rpc({\n block,\n request: {\n authorizationList: undefined,\n data,\n from: account?.address,\n to: contractAddress,\n value: numberToHex(value),\n },\n rpcStateOverride,\n }).catch(() => 100_000n)\n return 2n * BigInt(estimate)\n }),\n )\n estimate += estimates.reduce((acc, curr) => acc + curr, 0n)\n }\n\n return estimate\n } catch (err) {\n throw getEstimateGasError(err as BaseError, {\n ...args,\n account,\n chain: client.chain,\n })\n }\n}\n","import type { Abi } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n GetValue,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type EstimateGasErrorType,\n type EstimateGasParameters,\n estimateGas,\n} from './estimateGas.js'\n\nexport type EstimateContractGasParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs<abi, 'nonpayable' | 'payable', functionName>,\n chain extends Chain | undefined = Chain | undefined,\n> = ContractFunctionParameters<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n> &\n UnionOmit<EstimateGasParameters<chain>, 'data' | 'to' | 'value'> &\n GetValue<\n abi,\n functionName,\n EstimateGasParameters<chain> extends EstimateGasParameters\n ? EstimateGasParameters<chain>['value']\n : EstimateGasParameters['value']\n > & {\n /** Data to append to the end of the calldata. Useful for adding a [\"domain\" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */\n dataSuffix?: Hex | undefined\n }\n\nexport type EstimateContractGasReturnType = bigint\n\nexport type EstimateContractGasErrorType = GetContractErrorReturnType<\n EncodeFunctionDataErrorType | EstimateGasErrorType | ParseAccountErrorType\n>\n\n/**\n * Estimates the gas required to successfully execute a contract write function call.\n *\n * - Docs: https://viem.sh/docs/contract/estimateContractGas\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateContractGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateContractGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateContractGas } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gas = await estimateContractGas(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint() public']),\n * functionName: 'mint',\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * })\n */\nexport async function estimateContractGas<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n args extends ContractFunctionArgs<abi, 'pure' | 'view', functionName>,\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: EstimateContractGasParameters<abi, functionName, args, chain>,\n): Promise<EstimateContractGasReturnType> {\n const { abi, address, args, functionName, dataSuffix, ...request } =\n parameters as EstimateContractGasParameters\n const data = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n try {\n const gas = await getAction(\n client,\n estimateGas,\n 'estimateGas',\n )({\n data: `${data}${dataSuffix ? dataSuffix.replace('0x', '') : ''}`,\n to: address,\n ...request,\n } as unknown as EstimateGasParameters)\n return gas\n } catch (error) {\n const account = request.account ? parseAccount(request.account) : undefined\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/estimateContractGas',\n functionName,\n sender: account?.address,\n })\n }\n}\n","import type { Abi, AbiParameter } from 'abitype'\n\nimport {\n AbiDecodingDataSizeTooSmallError,\n type AbiDecodingDataSizeTooSmallErrorType,\n AbiEventSignatureEmptyTopicsError,\n type AbiEventSignatureEmptyTopicsErrorType,\n AbiEventSignatureNotFoundError,\n type AbiEventSignatureNotFoundErrorType,\n DecodeLogDataMismatch,\n type DecodeLogDataMismatchErrorType,\n DecodeLogTopicsMismatch,\n type DecodeLogTopicsMismatchErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractEventArgsFromTopics,\n ContractEventName,\n EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n IsNarrowable,\n Prettify,\n UnionEvaluate,\n} from '../../types/utils.js'\nimport { size } from '../data/size.js'\nimport {\n type ToEventSelectorErrorType,\n toEventSelector,\n} from '../hash/toEventSelector.js'\n\nimport { PositionOutOfBoundsError } from '../../errors/cursor.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeEventLogParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined = ContractEventName<abi>,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n> = {\n abi: abi\n data?: data | undefined\n eventName?: eventName | ContractEventName<abi> | undefined\n strict?: strict | boolean | undefined\n topics: [signature: Hex, ...args: topics] | []\n}\n\nexport type DecodeEventLogReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined = ContractEventName<abi>,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n ///\n allEventNames extends\n ContractEventName<abi> = eventName extends ContractEventName<abi>\n ? eventName\n : ContractEventName<abi>,\n> = IsNarrowable<abi, Abi> extends true\n ? {\n [name in allEventNames]: Prettify<\n {\n eventName: name\n } & UnionEvaluate<\n ContractEventArgsFromTopics<abi, name, strict> extends infer allArgs\n ? topics extends readonly []\n ? data extends undefined\n ? { args?: undefined }\n : { args?: allArgs | undefined }\n : { args: allArgs }\n : never\n >\n >\n }[allEventNames]\n : {\n eventName: eventName\n args: readonly unknown[] | undefined\n }\n\nexport type DecodeEventLogErrorType =\n | AbiDecodingDataSizeTooSmallErrorType\n | AbiEventSignatureEmptyTopicsErrorType\n | AbiEventSignatureNotFoundErrorType\n | DecodeAbiParametersErrorType\n | DecodeLogTopicsMismatchErrorType\n | DecodeLogDataMismatchErrorType\n | FormatAbiItemErrorType\n | ToEventSelectorErrorType\n | ErrorType\n\nconst docsPath = '/docs/contract/decodeEventLog'\n\nexport function decodeEventLog<\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi> | undefined = undefined,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n>(\n parameters: DecodeEventLogParameters<abi, eventName, topics, data, strict>,\n): DecodeEventLogReturnType<abi, eventName, topics, data, strict> {\n const {\n abi,\n data,\n strict: strict_,\n topics,\n } = parameters as DecodeEventLogParameters\n\n const strict = strict_ ?? true\n const [signature, ...argTopics] = topics\n if (!signature) throw new AbiEventSignatureEmptyTopicsError({ docsPath })\n\n const abiItem = (() => {\n if (abi.length === 1) return abi[0]\n return abi.find(\n (x) =>\n x.type === 'event' &&\n signature === toEventSelector(formatAbiItem(x) as EventDefinition),\n )\n })()\n\n if (!(abiItem && 'name' in abiItem) || abiItem.type !== 'event')\n throw new AbiEventSignatureNotFoundError(signature, { docsPath })\n\n const { name, inputs } = abiItem\n const isUnnamed = inputs?.some((x) => !('name' in x && x.name))\n\n let args: any = isUnnamed ? [] : {}\n\n // Decode topics (indexed args).\n const indexedInputs = inputs.filter((x) => 'indexed' in x && x.indexed)\n for (let i = 0; i < indexedInputs.length; i++) {\n const param = indexedInputs[i]\n const topic = argTopics[i]\n if (!topic)\n throw new DecodeLogTopicsMismatch({\n abiItem,\n param: param as AbiParameter & { indexed: boolean },\n })\n args[isUnnamed ? i : param.name || i] = decodeTopic({ param, value: topic })\n }\n\n // Decode data (non-indexed args).\n const nonIndexedInputs = inputs.filter((x) => !('indexed' in x && x.indexed))\n if (nonIndexedInputs.length > 0) {\n if (data && data !== '0x') {\n try {\n const decodedData = decodeAbiParameters(nonIndexedInputs, data)\n if (decodedData) {\n if (isUnnamed) args = [...args, ...decodedData]\n else {\n for (let i = 0; i < nonIndexedInputs.length; i++) {\n args[nonIndexedInputs[i].name!] = decodedData[i]\n }\n }\n }\n } catch (err) {\n if (strict) {\n if (\n err instanceof AbiDecodingDataSizeTooSmallError ||\n err instanceof PositionOutOfBoundsError\n )\n throw new DecodeLogDataMismatch({\n abiItem,\n data: data,\n params: nonIndexedInputs,\n size: size(data),\n })\n throw err\n }\n }\n } else if (strict) {\n throw new DecodeLogDataMismatch({\n abiItem,\n data: '0x',\n params: nonIndexedInputs,\n size: 0,\n })\n }\n }\n\n return {\n eventName: name,\n args: Object.values(args).length > 0 ? args : undefined,\n } as unknown as DecodeEventLogReturnType<abi, eventName, topics, data, strict>\n}\n\nfunction decodeTopic({ param, value }: { param: AbiParameter; value: Hex }) {\n if (\n param.type === 'string' ||\n param.type === 'bytes' ||\n param.type === 'tuple' ||\n param.type.match(/^(.*)\\[(\\d+)?\\]$/)\n )\n return value\n const decodedArg = decodeAbiParameters([param], value) || []\n return decodedArg[0]\n}\n","// TODO(v3): checksum address.\n\nimport type { Abi, AbiEvent, AbiEventParameter, Address } from 'abitype'\nimport {\n AbiEventSignatureNotFoundError,\n DecodeLogDataMismatch,\n DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ContractEventName, GetEventArgs } from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport { isAddressEqual } from '../address/isAddressEqual.js'\nimport { toBytes } from '../encoding/toBytes.js'\nimport { keccak256 } from '../hash/keccak256.js'\nimport { toEventSelector } from '../hash/toEventSelector.js'\nimport {\n type DecodeEventLogErrorType,\n decodeEventLog,\n} from './decodeEventLog.js'\n\nexport type ParseEventLogsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends\n | ContractEventName<abi>\n | ContractEventName<abi>[]\n | undefined = ContractEventName<abi>,\n strict extends boolean | undefined = boolean | undefined,\n ///\n allArgs = GetEventArgs<\n abi,\n eventName extends ContractEventName<abi>\n ? eventName\n : ContractEventName<abi>,\n {\n EnableUnion: true\n IndexedOnly: false\n Required: false\n }\n >,\n> = {\n /** Contract ABI. */\n abi: abi\n /** Arguments for the event. */\n args?: allArgs | undefined\n /** Contract event. */\n eventName?:\n | eventName\n | ContractEventName<abi>\n | ContractEventName<abi>[]\n | undefined\n /** List of logs. */\n logs: (Log | RpcLog)[]\n strict?: strict | boolean | undefined\n}\n\nexport type ParseEventLogsReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends\n | ContractEventName<abi>\n | ContractEventName<abi>[]\n | undefined = ContractEventName<abi>,\n strict extends boolean | undefined = boolean | undefined,\n ///\n derivedEventName extends\n | ContractEventName<abi>\n | undefined = eventName extends ContractEventName<abi>[]\n ? eventName[number]\n : eventName,\n> = Log<bigint, number, false, undefined, strict, abi, derivedEventName>[]\n\nexport type ParseEventLogsErrorType = DecodeEventLogErrorType | ErrorType\n\n/**\n * Extracts & decodes logs matching the provided signature(s) (`abi` + optional `eventName`)\n * from a set of opaque logs.\n *\n * @param parameters - {@link ParseEventLogsParameters}\n * @returns The logs. {@link ParseEventLogsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { parseEventLogs } from 'viem/op-stack'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const receipt = await getTransactionReceipt(client, {\n * hash: '0xec23b2ba4bc59ba61554507c1b1bc91649e6586eb2dd00c728e8ed0db8bb37ea',\n * })\n *\n * const logs = parseEventLogs({ logs: receipt.logs })\n * // [{ args: { ... }, eventName: 'TransactionDeposited', ... }, ...]\n */\nexport function parseEventLogs<\n abi extends Abi | readonly unknown[],\n strict extends boolean | undefined = true,\n eventName extends\n | ContractEventName<abi>\n | ContractEventName<abi>[]\n | undefined = undefined,\n>(\n parameters: ParseEventLogsParameters<abi, eventName, strict>,\n): ParseEventLogsReturnType<abi, eventName, strict> {\n const { abi, args, logs, strict = true } = parameters\n\n const eventName = (() => {\n if (!parameters.eventName) return undefined\n if (Array.isArray(parameters.eventName)) return parameters.eventName\n return [parameters.eventName as string]\n })()\n\n return logs\n .map((log) => {\n try {\n const abiItem = (abi as Abi).find(\n (abiItem) =>\n abiItem.type === 'event' &&\n log.topics[0] === toEventSelector(abiItem),\n ) as AbiEvent\n if (!abiItem) return null\n\n const event = decodeEventLog({\n ...log,\n abi: [abiItem],\n strict,\n })\n\n // Check that the decoded event name matches the provided event name.\n if (eventName && !eventName.includes(event.eventName)) return null\n\n // Check that the decoded event args match the provided args.\n if (\n !includesArgs({\n args: event.args,\n inputs: abiItem.inputs,\n matchArgs: args,\n })\n )\n return null\n\n return { ...event, ...log }\n } catch (err) {\n let eventName: string | undefined\n let isUnnamed: boolean | undefined\n\n if (err instanceof AbiEventSignatureNotFoundError) return null\n if (\n err instanceof DecodeLogDataMismatch ||\n err instanceof DecodeLogTopicsMismatch\n ) {\n // If strict mode is on, and log data/topics do not match event definition, skip.\n if (strict) return null\n eventName = err.abiItem.name\n isUnnamed = err.abiItem.inputs?.some((x) => !('name' in x && x.name))\n }\n\n // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n return { ...log, args: isUnnamed ? [] : {}, eventName }\n }\n })\n .filter(Boolean) as unknown as ParseEventLogsReturnType<\n abi,\n eventName,\n strict\n >\n}\n\nfunction includesArgs(parameters: {\n args: unknown\n inputs: AbiEvent['inputs']\n matchArgs: unknown\n}) {\n const { args, inputs, matchArgs } = parameters\n\n if (!matchArgs) return true\n if (!args) return false\n\n function isEqual(input: AbiEventParameter, value: unknown, arg: unknown) {\n try {\n if (input.type === 'address')\n return isAddressEqual(value as Address, arg as Address)\n if (input.type === 'string' || input.type === 'bytes')\n return keccak256(toBytes(value as string)) === arg\n return value === arg\n } catch {\n return false\n }\n }\n\n if (Array.isArray(args) && Array.isArray(matchArgs)) {\n return matchArgs.every((value, index) => {\n if (value === null || value === undefined) return true\n const input = inputs[index]\n if (!input) return false\n const value_ = Array.isArray(value) ? value : [value]\n return value_.some((value) => isEqual(input, value, args[index]))\n })\n }\n\n if (\n typeof args === 'object' &&\n !Array.isArray(args) &&\n typeof matchArgs === 'object' &&\n !Array.isArray(matchArgs)\n )\n return Object.entries(matchArgs).every(([key, value]) => {\n if (value === null || value === undefined) return true\n const input = inputs.find((input) => input.name === key)\n if (!input) return false\n const value_ = Array.isArray(value) ? value : [value]\n return value_.some((value) =>\n isEqual(input, value, (args as Record<string, unknown>)[key]),\n )\n })\n\n return false\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { ExactPartial } from '../../types/utils.js'\n\nexport type FormatLogErrorType = ErrorType\n\nexport function formatLog(\n log: ExactPartial<RpcLog>,\n {\n args,\n eventName,\n }: { args?: unknown | undefined; eventName?: string | undefined } = {},\n) {\n return {\n ...log,\n blockHash: log.blockHash ? log.blockHash : null,\n blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,\n logIndex: log.logIndex ? Number(log.logIndex) : null,\n transactionHash: log.transactionHash ? log.transactionHash : null,\n transactionIndex: log.transactionIndex\n ? Number(log.transactionIndex)\n : null,\n ...(eventName ? { args, eventName } : {}),\n } as Log\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash, LogTopic } from '../../types/misc.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetLogsParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName<abiEvent>,\n> = {\n /** Address or list of addresses from which logs originated */\n address?: Address | Address[] | undefined\n} & (\n | {\n event: abiEvent\n events?: undefined\n args?: MaybeExtractEventArgsFromAbi<abiEvents, _eventName> | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events: abiEvents\n args?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: undefined\n args?: undefined\n strict?: undefined\n }\n) &\n (\n | {\n /** Block number or tag after which to include logs */\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /** Block number or tag before which to include logs */\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n blockHash?: undefined\n }\n | {\n fromBlock?: undefined\n toBlock?: undefined\n /** Hash of block to include logs from */\n blockHash?: Hash | undefined\n }\n )\n\nexport type GetLogsReturnType<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName<abiEvent>,\n _pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log<bigint, number, _pending, abiEvent, strict, abiEvents, _eventName>[]\n\nexport type GetLogsErrorType =\n | DecodeEventLogErrorType\n | EncodeEventTopicsErrorType\n | FormatLogErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs matching the provided parameters.\n *\n * - Docs: https://viem.sh/docs/actions/public/getLogs\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/logs_event-logs\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetLogsParameters}\n * @returns A list of event logs. {@link GetLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await getLogs(client)\n */\nexport async function getLogs<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client<Transport, chain>,\n {\n address,\n blockHash,\n fromBlock,\n toBlock,\n event,\n events: events_,\n args,\n strict: strict_,\n }: GetLogsParameters<abiEvent, abiEvents, strict, fromBlock, toBlock> = {},\n): Promise<GetLogsReturnType<abiEvent, abiEvents, strict, fromBlock, toBlock>> {\n const strict = strict_ ?? false\n const events = events_ ?? (event ? [event] : undefined)\n\n let topics: LogTopic[] = []\n if (events) {\n const encoded = (events as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args: events_ ? undefined : args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n let logs: RpcLog[]\n if (blockHash) {\n logs = await client.request({\n method: 'eth_getLogs',\n params: [{ address, topics, blockHash }],\n })\n } else {\n logs = await client.request({\n method: 'eth_getLogs',\n params: [\n {\n address,\n topics,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n },\n ],\n })\n }\n\n const formattedLogs = logs.map((log) => formatLog(log))\n if (!events)\n return formattedLogs as GetLogsReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: events,\n args: args as any,\n logs: formattedLogs,\n strict,\n }) as unknown as GetLogsReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from '../../utils/abi/getAbiItem.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type GetLogsErrorType,\n type GetLogsParameters,\n getLogs,\n} from './getLogs.js'\n\nexport type GetContractEventsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined =\n | ContractEventName<abi>\n | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Contract ABI. */\n abi: abi\n args?:\n | ContractEventArgs<\n abi,\n eventName extends ContractEventName<abi>\n ? eventName\n : ContractEventName<abi>\n >\n | undefined\n /** Contract event. */\n eventName?: eventName | ContractEventName<abi> | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | boolean | undefined\n} & (\n | {\n /** Block number or tag after which to include logs */\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /** Block number or tag before which to include logs */\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n blockHash?: undefined\n }\n | {\n fromBlock?: undefined\n toBlock?: undefined\n /** Hash of block to include logs from */\n blockHash?: Hash | undefined\n }\n)\n\nexport type GetContractEventsReturnType<\n abi extends Abi | readonly unknown[] = readonly unknown[],\n eventName extends ContractEventName<abi> | undefined =\n | ContractEventName<abi>\n | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n ///\n isPending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log<bigint, number, isPending, undefined, strict, abi, eventName>[]\n\nexport type GetContractEventsErrorType =\n | GetAbiItemErrorType\n | GetLogsErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs emitted by a contract.\n *\n * - Docs: https://viem.sh/docs/contract/getContractEvents#getcontractevents\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetContractEventsParameters}\n * @returns A list of event logs. {@link GetContractEventsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getContractEvents } from 'viem/public'\n * import { wagmiAbi } from './abi'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await getContractEvents(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: wagmiAbi,\n * eventName: 'Transfer'\n * })\n */\nexport async function getContractEvents<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi> | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client<Transport, chain>,\n parameters: GetContractEventsParameters<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n GetContractEventsReturnType<abi, eventName, strict, fromBlock, toBlock>\n> {\n const {\n abi,\n address,\n args,\n blockHash,\n eventName,\n fromBlock,\n toBlock,\n strict,\n } = parameters\n const event = eventName\n ? getAbiItem({ abi, name: eventName } as GetAbiItemParameters)\n : undefined\n const events = !event\n ? (abi as Abi).filter((x) => x.type === 'event')\n : undefined\n return getAction(\n client,\n getLogs,\n 'getLogs',\n )({\n address,\n args,\n blockHash,\n event,\n events,\n fromBlock,\n toBlock,\n strict,\n } as {} as GetLogsParameters) as unknown as GetContractEventsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Abi } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n} from '../../types/contract.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type ReadContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName<abi, 'pure' | 'view'>,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs<abi, 'pure' | 'view', functionName>,\n> = UnionEvaluate<\n Pick<\n CallParameters,\n | 'account'\n | 'blockNumber'\n | 'blockTag'\n | 'factory'\n | 'factoryData'\n | 'stateOverride'\n >\n> &\n ContractFunctionParameters<abi, 'pure' | 'view', functionName, args, boolean>\n\nexport type ReadContractReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName<abi, 'pure' | 'view'>,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs<abi, 'pure' | 'view', functionName>,\n> = ContractFunctionReturnType<abi, 'pure' | 'view', functionName, args>\n\nexport type ReadContractErrorType = GetContractErrorReturnType<\n CallErrorType | EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n>\n\n/**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts\n *\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await readContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\nexport async function readContract<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, 'pure' | 'view'>,\n const args extends ContractFunctionArgs<abi, 'pure' | 'view', functionName>,\n>(\n client: Client<Transport, chain>,\n parameters: ReadContractParameters<abi, functionName, args>,\n): Promise<ReadContractReturnType<abi, functionName, args>> {\n const { abi, address, args, functionName, ...rest } =\n parameters as ReadContractParameters\n const calldata = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n try {\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n ...(rest as CallParameters),\n data: calldata,\n to: address!,\n })\n return decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n }) as ReadContractReturnType<abi, functionName>\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/readContract',\n functionName,\n })\n }\n}\n","import type { Abi, AbiFunction, AbiStateMutability, Address } from 'abitype'\n\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account, ParseAccount } from '../../types/account.js'\nimport type { Chain, DeriveChain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n ExtractAbiFunctionForArgs,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n IsNarrowable,\n NoInfer,\n Prettify,\n UnionEvaluate,\n UnionOmit,\n} from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport type { WriteContractParameters } from '../wallet/writeContract.js'\n\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type GetMutabilityAwareValue<\n abi extends Abi | readonly unknown[],\n mutability extends AbiStateMutability = AbiStateMutability,\n functionName extends ContractFunctionName<\n abi,\n mutability\n > = ContractFunctionName<abi, mutability>,\n valueType = TransactionRequest['value'],\n args extends ContractFunctionArgs<\n abi,\n mutability,\n functionName\n > = ContractFunctionArgs<abi, mutability, functionName>,\n abiFunction extends AbiFunction = abi extends Abi\n ? ExtractAbiFunctionForArgs<abi, mutability, functionName, args>\n : AbiFunction,\n _Narrowable extends boolean = IsNarrowable<abi, Abi>,\n> = _Narrowable extends true\n ? abiFunction['stateMutability'] extends 'payable'\n ? { value?: NoInfer<valueType> | undefined }\n : abiFunction['payable'] extends true\n ? { value?: NoInfer<valueType> | undefined }\n : { value?: undefined }\n : { value?: NoInfer<valueType> | undefined }\n\nexport type SimulateContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs<abi, 'nonpayable' | 'payable', functionName>,\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | null | undefined = undefined,\n ///\n derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,\n> = {\n account?: accountOverride | null | undefined\n chain?: chainOverride | undefined\n /** Data to append to the end of the calldata. Useful for adding a [\"domain\" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */\n dataSuffix?: Hex | undefined\n} & ContractFunctionParameters<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n> &\n UnionOmit<\n CallParameters<derivedChain>,\n | 'account'\n | 'batch'\n | 'code'\n | 'to'\n | 'data'\n | 'factory'\n | 'factoryData'\n | 'value'\n > &\n GetMutabilityAwareValue<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n CallParameters<derivedChain> extends CallParameters\n ? CallParameters<derivedChain>['value']\n : CallParameters['value'],\n args\n >\n\nexport type SimulateContractReturnType<\n out abi extends Abi | readonly unknown[] = Abi,\n in out functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n in out args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs<abi, 'nonpayable' | 'payable', functionName>,\n /** @ts-expect-error cast variance */\n out chain extends Chain | undefined = Chain | undefined,\n out account extends Account | undefined = Account | undefined,\n out chainOverride extends Chain | undefined = Chain | undefined,\n out accountOverride extends Account | Address | null | undefined =\n | Account\n | Address\n | null\n | undefined,\n ///\n in out minimizedAbi extends Abi = readonly [\n ExtractAbiFunctionForArgs<\n abi extends Abi ? abi : Abi,\n 'nonpayable' | 'payable',\n functionName,\n args\n >,\n ],\n out resolvedAccount extends\n | Account\n | null\n | undefined = accountOverride extends Account | Address | null\n ? ParseAccount<accountOverride>\n : account,\n> = {\n result: ContractFunctionReturnType<\n minimizedAbi,\n 'nonpayable' | 'payable',\n functionName,\n args\n >\n request: Prettify<\n UnionEvaluate<\n UnionOmit<\n WriteContractParameters<\n minimizedAbi,\n functionName,\n args,\n chain,\n undefined,\n chainOverride\n >,\n 'account' | 'abi' | 'args' | 'chain' | 'functionName'\n >\n > &\n ContractFunctionParameters<\n minimizedAbi,\n 'nonpayable' | 'payable',\n functionName,\n args\n > & {\n chain: DeriveChain<chain, chainOverride>\n } & (resolvedAccount extends Account | null\n ? { account: resolvedAccount }\n : { account?: undefined })\n >\n}\n\nexport type SimulateContractErrorType =\n | ParseAccountErrorType\n | EncodeFunctionDataErrorType\n | GetContractErrorReturnType<CallErrorType | DecodeFunctionResultErrorType>\n | ErrorType\n\n/**\n * Simulates/validates a contract interaction. This is useful for retrieving **return data** and **revert reasons** of contract write functions.\n *\n * - Docs: https://viem.sh/docs/contract/simulateContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts\n *\n * This function does not require gas to execute and _**does not**_ change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract), but also supports contract write functions.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link SimulateContractParameters}\n * @returns The simulation result and write request. {@link SimulateContractReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { simulateContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await simulateContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32) view returns (uint32)']),\n * functionName: 'mint',\n * args: ['69420'],\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function simulateContract<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n const args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | null | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: SimulateContractParameters<\n abi,\n functionName,\n args,\n chain,\n chainOverride,\n accountOverride\n >,\n): Promise<\n SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n> {\n const { abi, address, args, dataSuffix, functionName, ...callRequest } =\n parameters as SimulateContractParameters\n\n const account = callRequest.account\n ? parseAccount(callRequest.account)\n : client.account\n const calldata = encodeFunctionData({ abi, args, functionName })\n try {\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n batch: false,\n data: `${calldata}${dataSuffix ? dataSuffix.replace('0x', '') : ''}`,\n to: address,\n ...callRequest,\n account,\n })\n const result = decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n })\n const minimizedAbi = abi.filter(\n (abiItem) =>\n 'name' in abiItem && abiItem.name === parameters.functionName,\n )\n return {\n result,\n request: {\n abi: minimizedAbi,\n address,\n args,\n dataSuffix,\n functionName,\n ...callRequest,\n account,\n },\n } as unknown as SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/simulateContract',\n functionName,\n sender: account?.address,\n })\n }\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport type { MaybePromise } from '../types/utils.js'\n\ntype Callback = ((...args: any[]) => any) | undefined\ntype Callbacks = Record<string, Callback>\n\nexport type ObserveErrorType = ErrorType\n\n/** @internal */\nexport const listenersCache = /*#__PURE__*/ new Map<\n string,\n { id: number; fns: Callbacks }[]\n>()\n/** @internal */\nexport const cleanupCache = /*#__PURE__*/ new Map<string, () => void>()\n\ntype EmitFunction<callbacks extends Callbacks> = (\n emit: callbacks,\n) => MaybePromise<void | (() => void)>\n\nlet callbackCount = 0\n\n/**\n * @description Sets up an observer for a given function. If another function\n * is set up under the same observer id, the function will only be called once\n * for both instances of the observer.\n */\nexport function observe<callbacks extends Callbacks>(\n observerId: string,\n callbacks: callbacks,\n fn: EmitFunction<callbacks>,\n) {\n const callbackId = ++callbackCount\n\n const getListeners = () => listenersCache.get(observerId) || []\n\n const unsubscribe = () => {\n const listeners = getListeners()\n listenersCache.set(\n observerId,\n listeners.filter((cb: any) => cb.id !== callbackId),\n )\n }\n\n const unwatch = () => {\n const listeners = getListeners()\n if (!listeners.some((cb: any) => cb.id === callbackId)) return\n const cleanup = cleanupCache.get(observerId)\n if (listeners.length === 1 && cleanup) cleanup()\n unsubscribe()\n }\n\n const listeners = getListeners()\n listenersCache.set(observerId, [\n ...listeners,\n { id: callbackId, fns: callbacks },\n ])\n\n if (listeners && listeners.length > 0) return unwatch\n\n const emit: callbacks = {} as callbacks\n for (const key in callbacks) {\n emit[key] = ((\n ...args: Parameters<NonNullable<callbacks[keyof callbacks]>>\n ) => {\n const listeners = getListeners()\n if (listeners.length === 0) return\n for (const listener of listeners) listener.fns[key]?.(...args)\n }) as callbacks[Extract<keyof callbacks, string>]\n }\n\n const cleanup = fn(emit)\n if (typeof cleanup === 'function') cleanupCache.set(observerId, cleanup)\n\n return unwatch\n}\n","export async function wait(time: number) {\n return new Promise((res) => setTimeout(res, time))\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport { wait } from './wait.js'\n\ntype PollOptions<data> = {\n // Whether or not to emit when the polling starts.\n emitOnBegin?: boolean | undefined\n // The initial wait time (in ms) before polling.\n initialWaitTime?: ((data: data | void) => Promise<number>) | undefined\n // The interval (in ms).\n interval: number\n}\n\nexport type PollErrorType = ErrorType\n\n/**\n * @description Polls a function at a specified interval.\n */\nexport function poll<data>(\n fn: ({ unpoll }: { unpoll: () => void }) => Promise<data | void>,\n { emitOnBegin, initialWaitTime, interval }: PollOptions<data>,\n) {\n let active = true\n\n const unwatch = () => (active = false)\n\n const watch = async () => {\n let data: data | void = undefined\n if (emitOnBegin) data = await fn({ unpoll: unwatch })\n\n const initialWait = (await initialWaitTime?.(data)) ?? interval\n await wait(initialWait)\n\n const poll = async () => {\n if (!active) return\n await fn({ unpoll: unwatch })\n await wait(interval)\n poll()\n }\n\n poll()\n }\n watch()\n\n return unwatch\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new Map()\n/** @internal */\nexport const responseCache = /*#__PURE__*/ new Map()\n\nexport type GetCacheErrorType = ErrorType\n\nexport function getCache<data>(cacheKey: string) {\n const buildCache = <data>(cacheKey: string, cache: Map<string, data>) => ({\n clear: () => cache.delete(cacheKey),\n get: () => cache.get(cacheKey),\n set: (data: data) => cache.set(cacheKey, data),\n })\n\n const promise = buildCache<Promise<data>>(cacheKey, promiseCache)\n const response = buildCache<{ created: Date; data: data }>(\n cacheKey,\n responseCache,\n )\n\n return {\n clear: () => {\n promise.clear()\n response.clear()\n },\n promise,\n response,\n }\n}\n\ntype WithCacheParameters = {\n /** The key to cache the data against. */\n cacheKey: string\n /** The time that cached data will remain in memory. Default: Infinity (no expiry) */\n cacheTime?: number | undefined\n}\n\n/**\n * @description Returns the result of a given promise, and caches the result for\n * subsequent invocations against a provided cache key.\n */\nexport async function withCache<data>(\n fn: () => Promise<data>,\n { cacheKey, cacheTime = Number.POSITIVE_INFINITY }: WithCacheParameters,\n) {\n const cache = getCache<data>(cacheKey)\n\n // If a response exists in the cache, and it's not expired, return it\n // and do not invoke the promise.\n // If the max age is 0, the cache is disabled.\n const response = cache.response.get()\n if (response && cacheTime > 0) {\n const age = new Date().getTime() - response.created.getTime()\n if (age < cacheTime) return response.data\n }\n\n let promise = cache.promise.get()\n if (!promise) {\n promise = fn()\n\n // Store the promise in the cache so that subsequent invocations\n // will wait for the same promise to resolve (deduping).\n cache.promise.set(promise)\n }\n\n try {\n const data = await promise\n\n // Store the response in the cache so that subsequent invocations\n // will return the same response.\n cache.response.set({ created: new Date(), data })\n\n return data\n } finally {\n // Clear the promise cache so that subsequent invocations will\n // invoke the promise again.\n cache.promise.clear()\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type GetCacheErrorType,\n getCache,\n withCache,\n} from '../../utils/promise/withCache.js'\n\nexport type GetBlockNumberParameters = {\n /** Time (in ms) that cached block number will remain in memory. */\n cacheTime?: number | undefined\n}\n\nexport type GetBlockNumberReturnType = bigint\n\nexport type GetBlockNumberErrorType = RequestErrorType | ErrorType\n\nconst cacheKey = (id: string) => `blockNumber.${id}`\n\n/** @internal */\nexport type GetBlockNumberCacheErrorType = GetCacheErrorType | ErrorType\n\n/** @internal */\nexport function getBlockNumberCache(id: string) {\n return getCache(cacheKey(id))\n}\n\n/**\n * Returns the number of the most recent block seen.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockNumberParameters}\n * @returns The number of the block. {@link GetBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockNumber } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blockNumber = await getBlockNumber(client)\n * // 69420n\n */\nexport async function getBlockNumber<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { cacheTime = client.cacheTime }: GetBlockNumberParameters = {},\n): Promise<GetBlockNumberReturnType> {\n const blockNumberHex = await withCache(\n () =>\n client.request({\n method: 'eth_blockNumber',\n }),\n { cacheKey: cacheKey(client.uid), cacheTime },\n )\n return BigInt(blockNumberHex)\n}\n","import type { Abi, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcLog } from '../../index.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter, FilterType } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterChangesParameters<\n filterType extends FilterType = FilterType,\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n filter: Filter<filterType, abi, eventName, any, strict, fromBlock, toBlock>\n}\n\nexport type GetFilterChangesReturnType<\n filterType extends FilterType = FilterType,\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _AbiEvent extends AbiEvent | undefined = abi extends Abi\n ? eventName extends string\n ? ExtractAbiEvent<abi, eventName>\n : undefined\n : undefined,\n _Pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = filterType extends 'event'\n ? Log<bigint, number, _Pending, _AbiEvent, strict, abi, eventName>[]\n : Hash[]\n\nexport type GetFilterChangesErrorType =\n | RequestErrorType\n | DecodeEventLogErrorType\n | FormatLogErrorType\n | ErrorType\n\n/**\n * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterChanges\n * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n *\n * A Filter can be created from the following actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * Depending on the type of filter, the return value will be different:\n *\n * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterChangesParameters}\n * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n *\n * @example\n * // Blocks\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n *\n * @example\n * // Contract Events\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * eventName: 'Transfer',\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Raw Events\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Transactions\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n */\nexport async function getFilterChanges<\n transport extends Transport,\n chain extends Chain | undefined,\n filterType extends FilterType,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n _client: Client<transport, chain>,\n {\n filter,\n }: GetFilterChangesParameters<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n> {\n const strict = 'strict' in filter && filter.strict\n\n const logs = await filter.request({\n method: 'eth_getFilterChanges',\n params: [filter.id],\n })\n\n if (typeof logs[0] === 'string')\n return logs as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n\n const formattedLogs = logs.map((log) => formatLog(log as RpcLog))\n if (!('abi' in filter) || !filter.abi)\n return formattedLogs as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: filter.abi,\n logs: formattedLogs,\n strict,\n }) as unknown as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type UninstallFilterParameters = {\n filter: Filter<any>\n}\nexport type UninstallFilterReturnType = boolean\n\nexport type UninstallFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Destroys a [`Filter`](https://viem.sh/docs/glossary/types#filter).\n *\n * - Docs: https://viem.sh/docs/actions/public/uninstallFilter\n * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n *\n * Destroys a Filter that was created from one of the following Actions:\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * @param client - Client to use\n * @param parameters - {@link UninstallFilterParameters}\n * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n *\n * const filter = await createPendingTransactionFilter(client)\n * const uninstalled = await uninstallFilter(client, { filter })\n * // true\n */\nexport async function uninstallFilter<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n _client: Client<transport, chain>,\n { filter }: UninstallFilterParameters,\n): Promise<UninstallFilterReturnType> {\n return filter.request({\n method: 'eth_uninstallFilter',\n params: [filter.id],\n })\n}\n","import type { Abi, Address, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\n\nimport {\n DecodeLogDataMismatch,\n DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber } from '../../types/block.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n} from '../../types/contract.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { decodeEventLog } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\nimport { createContractEventFilter } from './createContractEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport {\n type GetContractEventsParameters,\n getContractEvents,\n} from './getContractEvents.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type WatchContractEventOnLogsParameter<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> = ContractEventName<abi>,\n strict extends boolean | undefined = undefined,\n> = abi extends Abi\n ? Abi extends abi\n ? Log[]\n : Log<bigint, number, false, ExtractAbiEvent<abi, eventName>, strict>[]\n : Log[]\n\nexport type WatchContractEventOnLogsFn<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> = ContractEventName<abi>,\n strict extends boolean | undefined = undefined,\n> = (logs: WatchContractEventOnLogsParameter<abi, eventName, strict>) => void\n\nexport type WatchContractEventParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined = ContractEventName<abi>,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Contract ABI. */\n abi: abi\n args?:\n | ContractEventArgs<\n abi,\n eventName extends ContractEventName<abi>\n ? eventName\n : ContractEventName<abi>\n >\n | undefined\n /** Contract event. */\n eventName?: eventName | ContractEventName<abi> | undefined\n /** Block to start listening from. */\n fromBlock?: BlockNumber<bigint> | undefined\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new event logs are received. */\n onLogs: WatchContractEventOnLogsFn<\n abi,\n eventName extends ContractEventName<abi>\n ? eventName\n : ContractEventName<abi>,\n strict\n >\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | boolean | undefined\n} & GetPollOptions<transport>\n\nexport type WatchContractEventReturnType = () => void\n\nexport type WatchContractEventErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns emitted contract event logs.\n *\n * - Docs: https://viem.sh/docs/contract/watchContractEvent\n *\n * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent#onLogs).\n *\n * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchContractEventParameters}\n * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchContractEvent } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchContractEvent(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n * eventName: 'Transfer',\n * args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n * onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchContractEvent<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi> | undefined = undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n>(\n client: Client<transport, chain>,\n parameters: WatchContractEventParameters<abi, eventName, strict, transport>,\n): WatchContractEventReturnType {\n const {\n abi,\n address,\n args,\n batch = true,\n eventName,\n fromBlock,\n onError,\n onLogs,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n strict: strict_,\n } = parameters\n\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (typeof fromBlock === 'bigint') return true\n if (client.transport.type === 'webSocket') return false\n if (\n client.transport.type === 'fallback' &&\n client.transport.transports[0].config.type === 'webSocket'\n )\n return false\n return true\n })()\n\n const pollContractEvent = () => {\n const strict = strict_ ?? false\n const observerId = stringify([\n 'watchContractEvent',\n address,\n args,\n batch,\n client.uid,\n eventName,\n pollingInterval,\n strict,\n fromBlock,\n ])\n\n return observe(observerId, { onLogs, onError }, (emit) => {\n let previousBlockNumber: bigint\n if (fromBlock !== undefined) previousBlockNumber = fromBlock - 1n\n let filter: Filter<'event', abi, eventName> | undefined\n let initialized = false\n\n const unwatch = poll(\n async () => {\n if (!initialized) {\n try {\n filter = (await getAction(\n client,\n createContractEventFilter,\n 'createContractEventFilter',\n )({\n abi,\n address,\n args: args as any,\n eventName: eventName as any,\n strict: strict as any,\n fromBlock,\n })) as Filter<'event', abi, eventName>\n } catch {}\n initialized = true\n return\n }\n\n try {\n let logs: Log[]\n if (filter) {\n logs = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n } else {\n // If the filter doesn't exist, we will fall back to use `getLogs`.\n // The fall back exists because some RPC Providers do not support filters.\n\n // Fetch the block number to use for `getLogs`.\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({})\n\n // If the block number has changed, we will need to fetch the logs.\n // If the block number doesn't exist, we are yet to reach the first poll interval,\n // so do not emit any logs.\n if (previousBlockNumber && previousBlockNumber < blockNumber) {\n logs = await getAction(\n client,\n getContractEvents,\n 'getContractEvents',\n )({\n abi,\n address,\n args,\n eventName,\n fromBlock: previousBlockNumber + 1n,\n toBlock: blockNumber,\n strict,\n } as {} as GetContractEventsParameters)\n } else {\n logs = []\n }\n previousBlockNumber = blockNumber\n }\n\n if (logs.length === 0) return\n if (batch) emit.onLogs(logs as any)\n else for (const log of logs) emit.onLogs([log] as any)\n } catch (err) {\n // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n // Reinitialize the filter when this occurs\n if (filter && err instanceof InvalidInputRpcError)\n initialized = false\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribeContractEvent = () => {\n const strict = strict_ ?? false\n const observerId = stringify([\n 'watchContractEvent',\n address,\n args,\n batch,\n client.uid,\n eventName,\n pollingInterval,\n strict,\n ])\n\n let active = true\n let unsubscribe = () => (active = false)\n return observe(observerId, { onLogs, onError }, (emit) => {\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType<Transport>) =>\n transport.config.type === 'webSocket',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const topics: LogTopic[] = eventName\n ? encodeEventTopics({\n abi: abi,\n eventName: eventName,\n args,\n } as EncodeEventTopicsParameters)\n : []\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['logs', { address, topics }],\n onData(data: any) {\n if (!active) return\n const log = data.result\n try {\n const { eventName, args } = decodeEventLog({\n abi: abi,\n data: log.data,\n topics: log.topics as any,\n strict: strict_,\n })\n const formatted = formatLog(log, {\n args,\n eventName: eventName as string,\n })\n emit.onLogs([formatted] as any)\n } catch (err) {\n let eventName: string | undefined\n let isUnnamed: boolean | undefined\n if (\n err instanceof DecodeLogDataMismatch ||\n err instanceof DecodeLogTopicsMismatch\n ) {\n // If strict mode is on, and log data/topics do not match event definition, skip.\n if (strict_) return\n eventName = err.abiItem.name\n isUnnamed = err.abiItem.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n }\n\n // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n const formatted = formatLog(log, {\n args: isUnnamed ? [] : {},\n eventName,\n })\n emit.onLogs([formatted] as any)\n }\n },\n onError(error: Error) {\n emit.onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n })\n }\n\n return enablePolling ? pollContractEvent() : subscribeContractEvent()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { TransactionSerializedGeneric } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type SendRawTransactionParameters = {\n /** The signed serialized transaction. */\n serializedTransaction: TransactionSerializedGeneric\n}\n\nexport type SendRawTransactionReturnType = Hash\n\nexport type SendRawTransactionErrorType = RequestErrorType | ErrorType\n\n/**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const hash = await sendRawTransaction(client, {\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\nexport async function sendRawTransaction<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { serializedTransaction }: SendRawTransactionParameters,\n): Promise<SendRawTransactionReturnType> {\n return client.request(\n {\n method: 'eth_sendRawTransaction',\n params: [serializedTransaction],\n },\n { retryCount: 0 },\n )\n}\n","import type { Address } from 'abitype'\nimport { BaseError } from './base.js'\n\nexport type Eip712DomainNotFoundErrorType = Eip712DomainNotFoundError & {\n name: 'Eip712DomainNotFoundError'\n}\nexport class Eip712DomainNotFoundError extends BaseError {\n constructor({ address }: { address: Address }) {\n super(`No EIP-712 domain found on contract \"${address}\".`, {\n metaMessages: [\n 'Ensure that:',\n `- The contract is deployed at the address \"${address}\".`,\n '- `eip712Domain()` function exists on the contract.',\n '- `eip712Domain()` function matches signature to ERC-5267 specification.',\n ],\n name: 'Eip712DomainNotFoundError',\n })\n }\n}\n","import type { Address, TypedDataDomain } from 'abitype'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n Eip712DomainNotFoundError,\n type Eip712DomainNotFoundErrorType,\n} from '../../errors/eip712.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RequiredBy } from '../../types/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from './readContract.js'\n\nexport type GetEip712DomainParameters = {\n address: Address\n} & Pick<ReadContractParameters, 'factory' | 'factoryData'>\n\nexport type GetEip712DomainReturnType = {\n domain: RequiredBy<\n TypedDataDomain,\n 'chainId' | 'name' | 'verifyingContract' | 'salt' | 'version'\n >\n fields: Hex\n extensions: readonly bigint[]\n}\n\nexport type GetEip712DomainErrorType =\n | Eip712DomainNotFoundErrorType\n | ReadContractErrorType\n | ErrorType\n\n/**\n * Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.\n *\n * @param client - A {@link Client} instance.\n * @param parameters - The parameters of the action. {@link GetEip712DomainParameters}\n * @returns The EIP-712 domain, fields, and extensions. {@link GetEip712DomainReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http, getEip712Domain } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const domain = await getEip712Domain(client, {\n * address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * })\n * // {\n * // domain: {\n * // name: 'ExampleContract',\n * // version: '1',\n * // chainId: 1,\n * // verifyingContract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * // },\n * // fields: '0x0f',\n * // extensions: [],\n * // }\n * ```\n */\nexport async function getEip712Domain(\n client: Client<Transport>,\n parameters: GetEip712DomainParameters,\n): Promise<GetEip712DomainReturnType> {\n const { address, factory, factoryData } = parameters\n\n try {\n const [\n fields,\n name,\n version,\n chainId,\n verifyingContract,\n salt,\n extensions,\n ] = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n abi,\n address,\n functionName: 'eip712Domain',\n factory,\n factoryData,\n })\n\n return {\n domain: {\n name,\n version,\n chainId: Number(chainId),\n verifyingContract,\n salt,\n },\n extensions,\n fields,\n }\n } catch (e) {\n const error = e as ReadContractErrorType\n if (\n error.name === 'ContractFunctionExecutionError' &&\n error.cause.name === 'ContractFunctionZeroDataError'\n ) {\n throw new Eip712DomainNotFoundError({ address })\n }\n throw error\n }\n}\n\nconst abi = [\n {\n inputs: [],\n name: 'eip712Domain',\n outputs: [\n { name: 'fields', type: 'bytes1' },\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n { name: 'salt', type: 'bytes32' },\n { name: 'extensions', type: 'uint256[]' },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n] as const\n","const size = 256\nlet index = size\nlet buffer: string\n\nexport function uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = ''\n index = 0\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1)\n }\n }\n return buffer.substring(index, index++ + length)\n}\n","import type { Address } from 'abitype'\n\nimport type { JsonRpcAccount } from '../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../accounts/utils/parseAccount.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type {\n EIP1193RequestFn,\n EIP1474Methods,\n RpcSchema,\n} from '../types/eip1193.js'\nimport type { ExactPartial, Prettify } from '../types/utils.js'\nimport type {\n CcipRequestParameters,\n CcipRequestReturnType,\n} from '../utils/ccip.js'\nimport { uid } from '../utils/uid.js'\nimport type { PublicActions } from './decorators/public.js'\nimport type { WalletActions } from './decorators/wallet.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type ClientConfig<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account to use for the Client. This will be used for Actions that require an account as an argument. */\n account?: accountOrAddress | Account | Address | undefined\n /** Flags for batch settings. */\n batch?:\n | {\n /** Toggle to enable `eth_call` multicall aggregation. */\n multicall?: boolean | Prettify<MulticallBatchOptions> | undefined\n }\n | undefined\n /**\n * Time (in ms) that cached data will remain in memory.\n * @default 4_000\n */\n cacheTime?: number | undefined\n /**\n * [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration.\n * If `false`, the client will not support offchain CCIP lookups.\n */\n ccipRead?:\n | {\n /**\n * A function that will be called to make the offchain CCIP lookup request.\n * @see https://eips.ethereum.org/EIPS/eip-3668#client-lookup-protocol\n */\n request?: (\n parameters: CcipRequestParameters,\n ) => Promise<CcipRequestReturnType>\n }\n | false\n | undefined\n /** Chain for the client. */\n chain?: Chain | undefined | chain\n /** A key for the client. */\n key?: string | undefined\n /** A name for the client. */\n name?: string | undefined\n /**\n * Frequency (in ms) for polling enabled actions & events.\n * @default 4_000\n */\n pollingInterval?: number | undefined\n /**\n * Typed JSON-RPC schema for the client.\n */\n rpcSchema?: rpcSchema | undefined\n /** The RPC transport */\n transport: transport\n /** The type of client. */\n type?: string | undefined\n}\n\n// Actions that are used internally by other Actions (ie. `call` is used by `readContract`).\n// They are allowed to be extended, but must conform to their parameter & return type interfaces.\n// Example: an extended `call` action must accept `CallParameters` as parameters,\n// and conform to the `CallReturnType` return type.\ntype ExtendableProtectedActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = Pick<\n PublicActions<transport, chain, account>,\n | 'call'\n | 'createContractEventFilter'\n | 'createEventFilter'\n | 'estimateContractGas'\n | 'estimateGas'\n | 'getBlock'\n | 'getBlockNumber'\n | 'getChainId'\n | 'getContractEvents'\n | 'getEnsText'\n | 'getFilterChanges'\n | 'getGasPrice'\n | 'getLogs'\n | 'getTransaction'\n | 'getTransactionCount'\n | 'getTransactionReceipt'\n | 'prepareTransactionRequest'\n | 'readContract'\n | 'sendRawTransaction'\n | 'simulateContract'\n | 'uninstallFilter'\n | 'watchBlockNumber'\n | 'watchContractEvent'\n> &\n Pick<WalletActions<chain, account>, 'sendTransaction' | 'writeContract'>\n\n// TODO: Move `transport` to slot index 2 since `chain` and `account` used more frequently.\n// Otherwise, we end up with a lot of `Client<Transport, chain, account>` in actions.\nexport type Client<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n extended extends Extended | undefined = Extended | undefined,\n> = Client_Base<transport, chain, account, rpcSchema> &\n (extended extends Extended ? extended : unknown) & {\n extend: <\n const client extends Extended &\n ExactPartial<ExtendableProtectedActions<transport, chain, account>>,\n >(\n fn: (\n client: Client<transport, chain, account, rpcSchema, extended>,\n ) => client,\n ) => Client<\n transport,\n chain,\n account,\n rpcSchema,\n Prettify<client> & (extended extends Extended ? extended : unknown)\n >\n }\n\ntype Client_Base<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account of the Client. */\n account: account\n /** Flags for batch settings. */\n batch?: ClientConfig['batch'] | undefined\n /** Time (in ms) that cached data will remain in memory. */\n cacheTime: number\n /** [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration. */\n ccipRead?: ClientConfig['ccipRead'] | undefined\n /** Chain for the client. */\n chain: chain\n /** A key for the client. */\n key: string\n /** A name for the client. */\n name: string\n /** Frequency (in ms) for polling enabled actions & events. Defaults to 4_000 milliseconds. */\n pollingInterval: number\n /** Request function wrapped with friendly error handling */\n request: EIP1193RequestFn<\n rpcSchema extends undefined ? EIP1474Methods : rpcSchema\n >\n /** The RPC transport */\n transport: ReturnType<transport>['config'] & ReturnType<transport>['value']\n /** The type of client. */\n type: string\n /** A unique ID for the client. */\n uid: string\n}\n\ntype Extended = Prettify<\n // disallow redefining base properties\n { [_ in keyof Client_Base]?: undefined } & {\n [key: string]: unknown\n }\n>\n\nexport type MulticallBatchOptions = {\n /** The maximum size (in bytes) for each calldata chunk. @default 1_024 */\n batchSize?: number | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n}\n\nexport type CreateClientErrorType = ParseAccountErrorType | ErrorType\n\nexport function createClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: ClientConfig<transport, chain, accountOrAddress, rpcSchema>,\n): Prettify<\n Client<\n transport,\n chain,\n accountOrAddress extends Address\n ? Prettify<JsonRpcAccount<accountOrAddress>>\n : accountOrAddress,\n rpcSchema\n >\n>\n\nexport function createClient(parameters: ClientConfig): Client {\n const {\n batch,\n cacheTime = parameters.pollingInterval ?? 4_000,\n ccipRead,\n key = 'base',\n name = 'Base Client',\n pollingInterval = 4_000,\n type = 'base',\n } = parameters\n\n const chain = parameters.chain\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n const { config, request, value } = parameters.transport({\n chain,\n pollingInterval,\n })\n const transport = { ...config, ...value }\n\n const client = {\n account,\n batch,\n cacheTime,\n ccipRead,\n chain,\n key,\n name,\n pollingInterval,\n request,\n transport,\n type,\n uid: uid(),\n }\n\n function extend(base: typeof client) {\n type ExtendFn = (base: typeof client) => unknown\n return (extendFn: ExtendFn) => {\n const extended = extendFn(base) as Extended\n for (const key in client) delete extended[key]\n const combined = { ...base, ...extended }\n return Object.assign(combined, { extend: extend(combined as any) })\n }\n }\n\n return Object.assign(client, { extend: extend(client) as any })\n}\n\n/**\n * Defines a typed JSON-RPC schema for the client.\n * Note: This is a runtime noop function.\n */\nexport function rpcSchema<rpcSchema extends RpcSchema>(): rpcSchema {\n return null as any\n}\n","import { LruMap } from '../lru.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new LruMap<Promise<any>>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n}\n\n/** Deduplicates in-flight promises. */\nexport function withDedupe<data>(\n fn: () => Promise<data>,\n { enabled = true, id }: WithDedupeOptions,\n): Promise<data> {\n if (!enabled || !id) return fn()\n if (promiseCache.get(id)) return promiseCache.get(id)!\n const promise = fn().finally(() => promiseCache.delete(id))\n promiseCache.set(id, promise)\n return promise\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { wait } from '../wait.js'\n\nexport type WithRetryParameters = {\n // The delay (in ms) between retries.\n delay?:\n | ((config: { count: number; error: Error }) => number)\n | number\n | undefined\n // The max number of times to retry.\n retryCount?: number | undefined\n // Whether or not to retry when an error is thrown.\n shouldRetry?:\n | (({\n count,\n error,\n }: {\n count: number\n error: Error\n }) => Promise<boolean> | boolean)\n | undefined\n}\n\nexport type WithRetryErrorType = ErrorType\n\nexport function withRetry<data>(\n fn: () => Promise<data>,\n {\n delay: delay_ = 100,\n retryCount = 2,\n shouldRetry = () => true,\n }: WithRetryParameters = {},\n) {\n return new Promise<data>((resolve, reject) => {\n const attemptRetry = async ({ count = 0 } = {}) => {\n const retry = async ({ error }: { error: Error }) => {\n const delay =\n typeof delay_ === 'function' ? delay_({ count, error }) : delay_\n if (delay) await wait(delay)\n attemptRetry({ count: count + 1 })\n }\n\n try {\n const data = await fn()\n resolve(data)\n } catch (err) {\n if (\n count < retryCount &&\n (await shouldRetry({ count, error: err as Error }))\n )\n return retry({ error: err as Error })\n reject(err)\n }\n }\n attemptRetry()\n })\n}\n","import { BaseError } from '../errors/base.js'\nimport {\n HttpRequestError,\n type HttpRequestErrorType,\n type RpcRequestErrorType,\n type TimeoutErrorType,\n type WebSocketRequestErrorType,\n} from '../errors/request.js'\nimport {\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n InternalRpcError,\n type InternalRpcErrorType,\n InvalidInputRpcError,\n type InvalidInputRpcErrorType,\n InvalidParamsRpcError,\n type InvalidParamsRpcErrorType,\n InvalidRequestRpcError,\n type InvalidRequestRpcErrorType,\n JsonRpcVersionUnsupportedError,\n type JsonRpcVersionUnsupportedErrorType,\n LimitExceededRpcError,\n type LimitExceededRpcErrorType,\n MethodNotFoundRpcError,\n type MethodNotFoundRpcErrorType,\n MethodNotSupportedRpcError,\n type MethodNotSupportedRpcErrorType,\n ParseRpcError,\n type ParseRpcErrorType,\n ProviderDisconnectedError,\n type ProviderDisconnectedErrorType,\n type ProviderRpcErrorCode,\n ResourceNotFoundRpcError,\n type ResourceNotFoundRpcErrorType,\n ResourceUnavailableRpcError,\n type ResourceUnavailableRpcErrorType,\n type RpcError,\n type RpcErrorCode,\n type RpcErrorType,\n SwitchChainError,\n type SwitchChainErrorType,\n TransactionRejectedRpcError,\n type TransactionRejectedRpcErrorType,\n UnauthorizedProviderError,\n type UnauthorizedProviderErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n} from '../errors/rpc.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n EIP1193RequestFn,\n EIP1193RequestOptions,\n} from '../types/eip1193.js'\nimport { stringToHex } from './encoding/toHex.js'\nimport type { CreateBatchSchedulerErrorType } from './promise/createBatchScheduler.js'\nimport { withDedupe } from './promise/withDedupe.js'\nimport { type WithRetryErrorType, withRetry } from './promise/withRetry.js'\nimport type { GetSocketRpcClientErrorType } from './rpc/socket.js'\nimport { stringify } from './stringify.js'\n\nexport type RequestErrorType =\n | ChainDisconnectedErrorType\n | CreateBatchSchedulerErrorType\n | HttpRequestErrorType\n | InternalRpcErrorType\n | InvalidInputRpcErrorType\n | InvalidParamsRpcErrorType\n | InvalidRequestRpcErrorType\n | GetSocketRpcClientErrorType\n | JsonRpcVersionUnsupportedErrorType\n | LimitExceededRpcErrorType\n | MethodNotFoundRpcErrorType\n | MethodNotSupportedRpcErrorType\n | ParseRpcErrorType\n | ProviderDisconnectedErrorType\n | ResourceNotFoundRpcErrorType\n | ResourceUnavailableRpcErrorType\n | RpcErrorType\n | RpcRequestErrorType\n | SwitchChainErrorType\n | TimeoutErrorType\n | TransactionRejectedRpcErrorType\n | UnauthorizedProviderErrorType\n | UnknownRpcErrorType\n | UnsupportedProviderMethodErrorType\n | UserRejectedRequestErrorType\n | WebSocketRequestErrorType\n | WithRetryErrorType\n | ErrorType\n\nexport function buildRequest<request extends (args: any) => Promise<any>>(\n request: request,\n options: EIP1193RequestOptions = {},\n): EIP1193RequestFn {\n return async (args, overrideOptions = {}) => {\n const {\n dedupe = false,\n methods,\n retryDelay = 150,\n retryCount = 3,\n uid,\n } = {\n ...options,\n ...overrideOptions,\n }\n\n const { method } = args\n if (methods?.exclude?.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n })\n if (methods?.include && !methods.include.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n })\n\n const requestId = dedupe\n ? stringToHex(`${uid}.${stringify(args)}`)\n : undefined\n return withDedupe(\n () =>\n withRetry(\n async () => {\n try {\n return await request(args)\n } catch (err_) {\n const err = err_ as unknown as RpcError<\n RpcErrorCode | ProviderRpcErrorCode\n >\n switch (err.code) {\n // -32700\n case ParseRpcError.code:\n throw new ParseRpcError(err)\n // -32600\n case InvalidRequestRpcError.code:\n throw new InvalidRequestRpcError(err)\n // -32601\n case MethodNotFoundRpcError.code:\n throw new MethodNotFoundRpcError(err, { method: args.method })\n // -32602\n case InvalidParamsRpcError.code:\n throw new InvalidParamsRpcError(err)\n // -32603\n case InternalRpcError.code:\n throw new InternalRpcError(err)\n // -32000\n case InvalidInputRpcError.code:\n throw new InvalidInputRpcError(err)\n // -32001\n case ResourceNotFoundRpcError.code:\n throw new ResourceNotFoundRpcError(err)\n // -32002\n case ResourceUnavailableRpcError.code:\n throw new ResourceUnavailableRpcError(err)\n // -32003\n case TransactionRejectedRpcError.code:\n throw new TransactionRejectedRpcError(err)\n // -32004\n case MethodNotSupportedRpcError.code:\n throw new MethodNotSupportedRpcError(err, {\n method: args.method,\n })\n // -32005\n case LimitExceededRpcError.code:\n throw new LimitExceededRpcError(err)\n // -32006\n case JsonRpcVersionUnsupportedError.code:\n throw new JsonRpcVersionUnsupportedError(err)\n // 4001\n case UserRejectedRequestError.code:\n throw new UserRejectedRequestError(err)\n // 4100\n case UnauthorizedProviderError.code:\n throw new UnauthorizedProviderError(err)\n // 4200\n case UnsupportedProviderMethodError.code:\n throw new UnsupportedProviderMethodError(err)\n // 4900\n case ProviderDisconnectedError.code:\n throw new ProviderDisconnectedError(err)\n // 4901\n case ChainDisconnectedError.code:\n throw new ChainDisconnectedError(err)\n // 4902\n case SwitchChainError.code:\n throw new SwitchChainError(err)\n // CAIP-25: User Rejected Error\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25\n case 5000:\n throw new UserRejectedRequestError(err)\n default:\n if (err_ instanceof BaseError) throw err_\n throw new UnknownRpcError(err as Error)\n }\n }\n },\n {\n delay: ({ count, error }) => {\n // If we find a Retry-After header, let's retry after the given time.\n if (error && error instanceof HttpRequestError) {\n const retryAfter = error?.headers?.get('Retry-After')\n if (retryAfter?.match(/\\d/))\n return Number.parseInt(retryAfter) * 1000\n }\n\n // Otherwise, let's retry with an exponential backoff.\n return ~~(1 << count) * retryDelay\n },\n retryCount,\n shouldRetry: ({ error }) => shouldRetry(error),\n },\n ),\n { enabled: dedupe, id: requestId },\n )\n }\n}\n\n/** @internal */\nexport function shouldRetry(error: Error) {\n if ('code' in error && typeof error.code === 'number') {\n if (error.code === -1) return true // Unknown error\n if (error.code === LimitExceededRpcError.code) return true\n if (error.code === InternalRpcError.code) return true\n return false\n }\n if (error instanceof HttpRequestError && error.status) {\n // Forbidden\n if (error.status === 403) return true\n // Request Timeout\n if (error.status === 408) return true\n // Request Entity Too Large\n if (error.status === 413) return true\n // Too Many Requests\n if (error.status === 429) return true\n // Internal Server Error\n if (error.status === 500) return true\n // Bad Gateway\n if (error.status === 502) return true\n // Service Unavailable\n if (error.status === 503) return true\n // Gateway Timeout\n if (error.status === 504) return true\n return false\n }\n return true\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn } from '../../types/eip1193.js'\nimport type { OneOf } from '../../types/utils.js'\nimport { buildRequest } from '../../utils/buildRequest.js'\nimport { uid as uid_ } from '../../utils/uid.js'\nimport type { ClientConfig } from '../createClient.js'\n\nexport type TransportConfig<\n type extends string = string,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = {\n /** The name of the transport. */\n name: string\n /** The key of the transport. */\n key: string\n /** Methods to include or exclude from executing RPC requests. */\n methods?:\n | OneOf<\n | {\n include?: string[] | undefined\n }\n | {\n exclude?: string[] | undefined\n }\n >\n | undefined\n /** The JSON-RPC request function that matches the EIP-1193 request spec. */\n request: eip1193RequestFn\n /** The base delay (in ms) between retries. */\n retryDelay?: number | undefined\n /** The max number of times to retry. */\n retryCount?: number | undefined\n /** The timeout (in ms) for requests. */\n timeout?: number | undefined\n /** The type of the transport. */\n type: type\n}\n\nexport type Transport<\n type extends string = string,\n rpcAttributes = Record<string, any>,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = <chain extends Chain | undefined = Chain>({\n chain,\n}: {\n chain?: chain | undefined\n pollingInterval?: ClientConfig['pollingInterval'] | undefined\n retryCount?: TransportConfig['retryCount'] | undefined\n timeout?: TransportConfig['timeout'] | undefined\n}) => {\n config: TransportConfig<type>\n request: eip1193RequestFn\n value?: rpcAttributes | undefined\n}\n\nexport type CreateTransportErrorType = ErrorType\n\n/**\n * @description Creates an transport intended to be used with a client.\n */\nexport function createTransport<\n type extends string,\n rpcAttributes extends Record<string, any>,\n>(\n {\n key,\n methods,\n name,\n request,\n retryCount = 3,\n retryDelay = 150,\n timeout,\n type,\n }: TransportConfig<type>,\n value?: rpcAttributes | undefined,\n): ReturnType<Transport<type, rpcAttributes>> {\n const uid = uid_()\n return {\n config: {\n key,\n methods,\n name,\n request,\n retryCount,\n retryDelay,\n timeout,\n type,\n },\n request: buildRequest(request, { methods, retryCount, retryDelay, uid }),\n value,\n }\n}\n","import { BaseError } from './base.js'\n\nexport type UrlRequiredErrorType = UrlRequiredError & {\n name: 'UrlRequiredError'\n}\nexport class UrlRequiredError extends BaseError {\n constructor() {\n super(\n 'No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.',\n {\n docsPath: '/docs/clients/intro',\n name: 'UrlRequiredError',\n },\n )\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\nexport type WithTimeoutErrorType = ErrorType\n\nexport function withTimeout<data>(\n fn: ({\n signal,\n }: { signal: AbortController['signal'] | null }) => Promise<data>,\n {\n errorInstance = new Error('timed out'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n },\n): Promise<data> {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n try {\n const controller = new AbortController()\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') reject(errorInstance)\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n","function createIdStore() {\n return {\n current: 0,\n take() {\n return this.current++\n },\n reset() {\n this.current = 0\n },\n }\n}\n\nexport const idCache = /*#__PURE__*/ createIdStore()\n","import {\n HttpRequestError,\n type HttpRequestErrorType as HttpRequestErrorType_,\n TimeoutError,\n type TimeoutErrorType,\n} from '../../errors/request.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcRequest, RpcResponse } from '../../types/rpc.js'\nimport type { MaybePromise } from '../../types/utils.js'\nimport {\n type WithTimeoutErrorType,\n withTimeout,\n} from '../promise/withTimeout.js'\nimport { stringify } from '../stringify.js'\nimport { idCache } from './id.js'\n\nexport type HttpRpcClientOptions = {\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: Omit<RequestInit, 'body'> | undefined\n /** A callback to handle the request. */\n onRequest?:\n | ((\n request: Request,\n init: RequestInit,\n ) => MaybePromise<\n void | undefined | (RequestInit & { url?: string | undefined })\n >)\n | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise<void> | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: number | undefined\n}\n\nexport type HttpRequestParameters<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = {\n /** The RPC request body. */\n body: body\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response. */\n onRequest?:\n | ((\n request: Request,\n init: RequestInit,\n ) => MaybePromise<\n void | undefined | (RequestInit & { url?: string | undefined })\n >)\n | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise<void> | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: HttpRpcClientOptions['timeout'] | undefined\n}\n\nexport type HttpRequestReturnType<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = body extends RpcRequest[] ? RpcResponse[] : RpcResponse\n\nexport type HttpRequestErrorType =\n | HttpRequestErrorType_\n | TimeoutErrorType\n | WithTimeoutErrorType\n | ErrorType\n\nexport type HttpRpcClient = {\n request<body extends RpcRequest | RpcRequest[]>(\n params: HttpRequestParameters<body>,\n ): Promise<HttpRequestReturnType<body>>\n}\n\nexport function getHttpRpcClient(\n url: string,\n options: HttpRpcClientOptions = {},\n): HttpRpcClient {\n return {\n async request(params) {\n const {\n body,\n onRequest = options.onRequest,\n onResponse = options.onResponse,\n timeout = options.timeout ?? 10_000,\n } = params\n\n const fetchOptions = {\n ...(options.fetchOptions ?? {}),\n ...(params.fetchOptions ?? {}),\n }\n\n const { headers, method, signal: signal_ } = fetchOptions\n\n try {\n const response = await withTimeout(\n async ({ signal }) => {\n const init: RequestInit = {\n ...fetchOptions,\n body: Array.isArray(body)\n ? stringify(\n body.map((body) => ({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n })),\n )\n : stringify({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n }),\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n method: method || 'POST',\n signal: signal_ || (timeout > 0 ? signal : null),\n }\n const request = new Request(url, init)\n const args = (await onRequest?.(request, init)) ?? { ...init, url }\n const response = await fetch(args.url ?? url, args)\n return response\n },\n {\n errorInstance: new TimeoutError({ body, url }),\n timeout,\n signal: true,\n },\n )\n\n if (onResponse) await onResponse(response)\n\n let data: any\n if (\n response.headers.get('Content-Type')?.startsWith('application/json')\n )\n data = await response.json()\n else {\n data = await response.text()\n try {\n data = JSON.parse(data || '{}')\n } catch (err) {\n if (response.ok) throw err\n data = { error: data }\n }\n }\n\n if (!response.ok) {\n throw new HttpRequestError({\n body,\n details: stringify(data.error) || response.statusText,\n headers: response.headers,\n status: response.status,\n url,\n })\n }\n\n return data\n } catch (err) {\n if (err instanceof HttpRequestError) throw err\n if (err instanceof TimeoutError) throw err\n throw new HttpRequestError({\n body,\n cause: err as Error,\n url,\n })\n }\n },\n }\n}\n","import { RpcRequestError } from '../../errors/request.js'\nimport {\n UrlRequiredError,\n type UrlRequiredErrorType,\n} from '../../errors/transport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { EIP1193RequestFn, RpcSchema } from '../../types/eip1193.js'\nimport type { RpcRequest } from '../../types/rpc.js'\nimport { createBatchScheduler } from '../../utils/promise/createBatchScheduler.js'\nimport {\n type HttpRpcClientOptions,\n getHttpRpcClient,\n} from '../../utils/rpc/http.js'\n\nimport {\n type CreateTransportErrorType,\n type Transport,\n type TransportConfig,\n createTransport,\n} from './createTransport.js'\n\nexport type HttpTransportConfig<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n> = {\n /**\n * Whether to enable Batch JSON-RPC.\n * @link https://www.jsonrpc.org/specification#batch\n */\n batch?:\n | boolean\n | {\n /** The maximum number of JSON-RPC requests to send in a batch. @default 1_000 */\n batchSize?: number | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n }\n | undefined\n /**\n * Request configuration to pass to `fetch`.\n * @link https://developer.mozilla.org/en-US/docs/Web/API/fetch\n */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchRequest?: HttpRpcClientOptions['onRequest'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchResponse?: HttpRpcClientOptions['onResponse'] | undefined\n /** The key of the HTTP transport. */\n key?: TransportConfig['key'] | undefined\n /** Methods to include or exclude from executing RPC requests. */\n methods?: TransportConfig['methods'] | undefined\n /** The name of the HTTP transport. */\n name?: TransportConfig['name'] | undefined\n /** Whether to return JSON RPC errors as responses instead of throwing. */\n raw?: raw | boolean | undefined\n /** The max number of times to retry. */\n retryCount?: TransportConfig['retryCount'] | undefined\n /** The base delay (in ms) between retries. */\n retryDelay?: TransportConfig['retryDelay'] | undefined\n /** Typed JSON-RPC schema for the transport. */\n rpcSchema?: rpcSchema | RpcSchema | undefined\n /** The timeout (in ms) for the HTTP request. Default: 10_000 */\n timeout?: TransportConfig['timeout'] | undefined\n}\n\nexport type HttpTransport<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n> = Transport<\n 'http',\n {\n fetchOptions?: HttpTransportConfig['fetchOptions'] | undefined\n url?: string | undefined\n },\n EIP1193RequestFn<rpcSchema, raw>\n>\n\nexport type HttpTransportErrorType =\n | CreateTransportErrorType\n | UrlRequiredErrorType\n | ErrorType\n\n/**\n * @description Creates a HTTP transport that connects to a JSON-RPC API.\n */\nexport function http<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n>(\n /** URL of the JSON-RPC API. Defaults to the chain's public RPC URL. */\n url?: string | undefined,\n config: HttpTransportConfig<rpcSchema, raw> = {},\n): HttpTransport<rpcSchema, raw> {\n const {\n batch,\n fetchOptions,\n key = 'http',\n methods,\n name = 'HTTP JSON-RPC',\n onFetchRequest,\n onFetchResponse,\n retryDelay,\n raw,\n } = config\n return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => {\n const { batchSize = 1000, wait = 0 } =\n typeof batch === 'object' ? batch : {}\n const retryCount = config.retryCount ?? retryCount_\n const timeout = timeout_ ?? config.timeout ?? 10_000\n const url_ = url || chain?.rpcUrls.default.http[0]\n if (!url_) throw new UrlRequiredError()\n\n const rpcClient = getHttpRpcClient(url_, {\n fetchOptions,\n onRequest: onFetchRequest,\n onResponse: onFetchResponse,\n timeout,\n })\n\n return createTransport(\n {\n key,\n methods,\n name,\n async request({ method, params }) {\n const body = { method, params }\n\n const { schedule } = createBatchScheduler({\n id: url_,\n wait,\n shouldSplitBatch(requests) {\n return requests.length > batchSize\n },\n fn: (body: RpcRequest[]) =>\n rpcClient.request({\n body,\n }),\n sort: (a, b) => a.id - b.id,\n })\n\n const fn = async (body: RpcRequest) =>\n batch\n ? schedule(body)\n : [\n await rpcClient.request({\n body,\n }),\n ]\n\n const [{ error, result }] = await fn(body)\n\n if (raw) return { error, result }\n if (error)\n throw new RpcRequestError({\n body,\n error,\n url: url_,\n })\n return result\n },\n retryCount,\n retryDelay,\n timeout,\n type: 'http',\n },\n {\n fetchOptions,\n url: url_,\n },\n )\n }\n}\n","import { panicReasons } from '../../constants/solidity.js'\nimport { BaseError } from '../../errors/base.js'\nimport { ContractFunctionRevertedError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport type IsNullUniversalResolverErrorErrorType = ErrorType\n\n/*\n * @description Checks if error is a valid null result UniversalResolver error\n */\nexport function isNullUniversalResolverError(\n err: unknown,\n callType: 'resolve' | 'reverse',\n): boolean {\n if (!(err instanceof BaseError)) return false\n const cause = err.walk((e) => e instanceof ContractFunctionRevertedError)\n if (!(cause instanceof ContractFunctionRevertedError)) return false\n if (cause.data?.errorName === 'ResolverNotFound') return true\n if (cause.data?.errorName === 'ResolverWildcardNotSupported') return true\n if (cause.data?.errorName === 'ResolverNotContract') return true\n if (cause.data?.errorName === 'ResolverError') return true\n if (cause.data?.errorName === 'HttpError') return true\n // Backwards compatibility for older UniversalResolver contracts\n if (\n cause.reason?.includes(\n 'Wildcard on non-extended resolvers is not supported',\n )\n )\n return true\n // No primary name set for address.\n if (callType === 'reverse' && cause.reason === panicReasons[50]) return true\n return false\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\n\nexport type EncodedLabelToLabelhashErrorType = IsHexErrorType | ErrorType\n\nexport function encodedLabelToLabelhash(label: string): Hex | null {\n if (label.length !== 66) return null\n if (label.indexOf('[') !== 0) return null\n if (label.indexOf(']') !== 65) return null\n const hash = `0x${label.slice(1, 65)}`\n if (!isHex(hash)) return null\n return hash\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport {\n type StringToBytesErrorType,\n type ToBytesErrorType,\n stringToBytes,\n toBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type EncodedLabelToLabelhashErrorType,\n encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type NamehashErrorType =\n | BytesToHexErrorType\n | EncodedLabelToLabelhashErrorType\n | ToBytesErrorType\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ConcatErrorType\n | ErrorType\n\n/**\n * @description Hashes ENS name\n *\n * - Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `namehash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @example\n * namehash('wevm.eth')\n * '0xf246651c1b9a6b141d19c2604e9a58f567973833990f830d882534a747801359'\n *\n * @link https://eips.ethereum.org/EIPS/eip-137\n */\nexport function namehash(name: string) {\n let result = new Uint8Array(32).fill(0)\n if (!name) return bytesToHex(result)\n\n const labels = name.split('.')\n // Iterate in reverse order building up hash\n for (let i = labels.length - 1; i >= 0; i -= 1) {\n const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i])\n const hashed = hashFromEncodedLabel\n ? toBytes(hashFromEncodedLabel)\n : keccak256(stringToBytes(labels[i]), 'bytes')\n result = keccak256(concat([result, hashed]), 'bytes')\n }\n\n return bytesToHex(result)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\n\nexport type EncodeLabelhashErrorType = ErrorType\n\nexport function encodeLabelhash(hash: Hex): `[${string}]` {\n return `[${hash.slice(2)}]`\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type EncodedLabelToLabelhashErrorType,\n encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type LabelhashErrorType =\n | BytesToHexErrorType\n | EncodedLabelToLabelhashErrorType\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\n/**\n * @description Hashes ENS label\n *\n * - Since ENS labels prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS labels](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `labelhash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @example\n * labelhash('eth')\n * '0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0'\n */\nexport function labelhash(label: string) {\n const result = new Uint8Array(32).fill(0)\n if (!label) return bytesToHex(result)\n return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label))\n}\n","// Adapted from https://github.com/mafintosh/dns-packet\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport {\n type EncodeLabelhashErrorType,\n encodeLabelhash,\n} from './encodeLabelhash.js'\nimport { type LabelhashErrorType, labelhash } from './labelhash.js'\n\nexport type PacketToBytesErrorType =\n | EncodeLabelhashErrorType\n | LabelhashErrorType\n | StringToBytesErrorType\n | ErrorType\n\n/*\n * @description Encodes a DNS packet into a ByteArray containing a UDP payload.\n *\n * @example\n * packetToBytes('awkweb.eth')\n * '0x0661776b7765620365746800'\n *\n * @see https://docs.ens.domains/resolution/names#dns\n *\n */\nexport function packetToBytes(packet: string): ByteArray {\n // strip leading and trailing `.`\n const value = packet.replace(/^\\.|\\.$/gm, '')\n if (value.length === 0) return new Uint8Array(1)\n\n const bytes = new Uint8Array(stringToBytes(value).byteLength + 2)\n\n let offset = 0\n const list = value.split('.')\n for (let i = 0; i < list.length; i++) {\n let encoded = stringToBytes(list[i])\n // if the length is > 255, make the encoded label value a labelhash\n // this is compatible with the universal resolver\n if (encoded.byteLength > 255)\n encoded = stringToBytes(encodeLabelhash(labelhash(list[i])))\n bytes[offset] = encoded.length\n bytes.set(encoded, offset + 1)\n offset += encoded.length + 1\n }\n\n if (bytes.byteLength !== offset + 1) return bytes.slice(0, offset + 1)\n\n return bytes\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n addressResolverAbi,\n universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type TrimErrorType, trim } from '../../utils/data/trim.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsAddressParameters = Prettify<\n Pick<ReadContractParameters, 'blockNumber' | 'blockTag'> & {\n /** ENSIP-9 compliant coinType used to resolve addresses for other chains */\n coinType?: number | undefined\n /** Universal Resolver gateway URLs to use for resolving CCIP-read requests. */\n gatewayUrls?: string[] | undefined\n /** Name to get the address for. */\n name: string\n /** Whether or not to throw errors propagated from the ENS Universal Resolver Contract. */\n strict?: boolean | undefined\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsAddressReturnType = Address | null\n\nexport type GetEnsAddressErrorType =\n | GetChainContractAddressErrorType\n | EncodeFunctionDataErrorType\n | NamehashErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | DecodeFunctionResultErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Gets address for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAddressParameters}\n * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAddress, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAddress = await getEnsAddress(client, {\n * name: normalize('wevm.eth'),\n * })\n * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n */\nexport async function getEnsAddress<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n {\n blockNumber,\n blockTag,\n coinType,\n name,\n gatewayUrls,\n strict,\n universalResolverAddress: universalResolverAddress_,\n }: GetEnsAddressParameters,\n): Promise<GetEnsAddressReturnType> {\n let universalResolverAddress = universalResolverAddress_\n if (!universalResolverAddress) {\n if (!client.chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n\n universalResolverAddress = getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'ensUniversalResolver',\n })\n }\n\n try {\n const functionData = encodeFunctionData({\n abi: addressResolverAbi,\n functionName: 'addr',\n ...(coinType != null\n ? { args: [namehash(name), BigInt(coinType)] }\n : { args: [namehash(name)] }),\n })\n\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverResolveAbi,\n functionName: 'resolve',\n args: [toHex(packetToBytes(name)), functionData],\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const res = gatewayUrls\n ? await readContractAction({\n ...readContractParameters,\n args: [...readContractParameters.args, gatewayUrls],\n })\n : await readContractAction(readContractParameters)\n\n if (res[0] === '0x') return null\n\n const address = decodeFunctionResult({\n abi: addressResolverAbi,\n args: coinType != null ? [namehash(name), BigInt(coinType)] : undefined,\n functionName: 'addr',\n data: res[0],\n })\n\n if (address === '0x') return null\n if (trim(address) === '0x00') return null\n return address\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err, 'resolve')) return null\n throw err\n }\n}\n","import { BaseError } from './base.js'\n\nexport type EnsAvatarInvalidMetadataErrorType =\n EnsAvatarInvalidMetadataError & {\n name: 'EnsAvatarInvalidMetadataError'\n }\nexport class EnsAvatarInvalidMetadataError extends BaseError {\n constructor({ data }: { data: any }) {\n super(\n 'Unable to extract image from metadata. The metadata may be malformed or invalid.',\n {\n metaMessages: [\n '- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.',\n '',\n `Provided data: ${JSON.stringify(data)}`,\n ],\n name: 'EnsAvatarInvalidMetadataError',\n },\n )\n }\n}\n\nexport type EnsAvatarInvalidNftUriErrorType = EnsAvatarInvalidNftUriError & {\n name: 'EnsAvatarInvalidNftUriError'\n}\nexport class EnsAvatarInvalidNftUriError extends BaseError {\n constructor({ reason }: { reason: string }) {\n super(`ENS NFT avatar URI is invalid. ${reason}`, {\n name: 'EnsAvatarInvalidNftUriError',\n })\n }\n}\n\nexport type EnsAvatarUriResolutionErrorType = EnsAvatarUriResolutionError & {\n name: 'EnsAvatarUriResolutionError'\n}\nexport class EnsAvatarUriResolutionError extends BaseError {\n constructor({ uri }: { uri: string }) {\n super(\n `Unable to resolve ENS avatar URI \"${uri}\". The URI may be malformed, invalid, or does not respond with a valid image.`,\n { name: 'EnsAvatarUriResolutionError' },\n )\n }\n}\n\nexport type EnsAvatarUnsupportedNamespaceErrorType =\n EnsAvatarUnsupportedNamespaceError & {\n name: 'EnsAvatarUnsupportedNamespaceError'\n }\nexport class EnsAvatarUnsupportedNamespaceError extends BaseError {\n constructor({ namespace }: { namespace: string }) {\n super(\n `ENS NFT avatar namespace \"${namespace}\" is not supported. Must be \"erc721\" or \"erc1155\".`,\n { name: 'EnsAvatarUnsupportedNamespaceError' },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nimport {\n type ReadContractErrorType,\n readContract,\n} from '../../../actions/public/readContract.js'\nimport type { Client } from '../../../clients/createClient.js'\nimport type { Transport } from '../../../clients/transports/createTransport.js'\nimport {\n EnsAvatarInvalidMetadataError,\n type EnsAvatarInvalidMetadataErrorType,\n EnsAvatarInvalidNftUriError,\n type EnsAvatarInvalidNftUriErrorType,\n EnsAvatarUnsupportedNamespaceError,\n type EnsAvatarUnsupportedNamespaceErrorType,\n EnsAvatarUriResolutionError,\n type EnsAvatarUriResolutionErrorType,\n} from '../../../errors/ens.js'\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { Chain } from '../../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../../types/ens.js'\n\ntype UriItem = {\n uri: string\n isOnChain: boolean\n isEncoded: boolean\n}\n\nconst networkRegex =\n /(?<protocol>https?:\\/\\/[^\\/]*|ipfs:\\/|ipns:\\/|ar:\\/)?(?<root>\\/)?(?<subpath>ipfs\\/|ipns\\/)?(?<target>[\\w\\-.]+)(?<subtarget>\\/.*)?/\nconst ipfsHashRegex =\n /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\\/(?<target>[\\w\\-.]+))?(?<subtarget>\\/.*)?$/\nconst base64Regex = /^data:([a-zA-Z\\-/+]*);base64,([^\"].*)/\nconst dataURIRegex = /^data:([a-zA-Z\\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/\n\ntype IsImageUriErrorType = ErrorType\n\n/** @internal */\nexport async function isImageUri(uri: string) {\n try {\n const res = await fetch(uri, { method: 'HEAD' })\n // retrieve content type header to check if content is image\n if (res.status === 200) {\n const contentType = res.headers.get('content-type')\n return contentType?.startsWith('image/')\n }\n return false\n } catch (error: any) {\n // if error is not cors related then fail\n if (typeof error === 'object' && typeof error.response !== 'undefined') {\n return false\n }\n // fail in NodeJS, since the error is not cors but any other network issue\n // biome-ignore lint/suspicious/noPrototypeBuiltins:\n if (!globalThis.hasOwnProperty('Image')) return false\n // in case of cors, use image api to validate if given url is an actual image\n return new Promise((resolve) => {\n const img = new Image()\n img.onload = () => {\n resolve(true)\n }\n img.onerror = () => {\n resolve(false)\n }\n img.src = uri\n })\n }\n}\n\ntype GetGatewayErrorType = ErrorType\n\n/** @internal */\nexport function getGateway(custom: string | undefined, defaultGateway: string) {\n if (!custom) return defaultGateway\n if (custom.endsWith('/')) return custom.slice(0, -1)\n return custom\n}\n\nexport type ResolveAvatarUriErrorType =\n | GetGatewayErrorType\n | EnsAvatarUriResolutionErrorType\n | ErrorType\n\nexport function resolveAvatarUri({\n uri,\n gatewayUrls,\n}: {\n uri: string\n gatewayUrls?: AssetGatewayUrls | undefined\n}): UriItem {\n const isEncoded = base64Regex.test(uri)\n if (isEncoded) return { uri, isOnChain: true, isEncoded }\n\n const ipfsGateway = getGateway(gatewayUrls?.ipfs, 'https://ipfs.io')\n const arweaveGateway = getGateway(gatewayUrls?.arweave, 'https://arweave.net')\n\n const networkRegexMatch = uri.match(networkRegex)\n const {\n protocol,\n subpath,\n target,\n subtarget = '',\n } = networkRegexMatch?.groups || {}\n\n const isIPNS = protocol === 'ipns:/' || subpath === 'ipns/'\n const isIPFS =\n protocol === 'ipfs:/' || subpath === 'ipfs/' || ipfsHashRegex.test(uri)\n\n if (uri.startsWith('http') && !isIPNS && !isIPFS) {\n let replacedUri = uri\n if (gatewayUrls?.arweave)\n replacedUri = uri.replace(/https:\\/\\/arweave.net/g, gatewayUrls?.arweave)\n return { uri: replacedUri, isOnChain: false, isEncoded: false }\n }\n\n if ((isIPNS || isIPFS) && target) {\n return {\n uri: `${ipfsGateway}/${isIPNS ? 'ipns' : 'ipfs'}/${target}${subtarget}`,\n isOnChain: false,\n isEncoded: false,\n }\n }\n\n if (protocol === 'ar:/' && target) {\n return {\n uri: `${arweaveGateway}/${target}${subtarget || ''}`,\n isOnChain: false,\n isEncoded: false,\n }\n }\n\n let parsedUri = uri.replace(dataURIRegex, '')\n if (parsedUri.startsWith('<svg')) {\n // if svg, base64 encode\n parsedUri = `data:image/svg+xml;base64,${btoa(parsedUri)}`\n }\n\n if (parsedUri.startsWith('data:') || parsedUri.startsWith('{')) {\n return {\n uri: parsedUri,\n isOnChain: true,\n isEncoded: false,\n }\n }\n\n throw new EnsAvatarUriResolutionError({ uri })\n}\n\nexport type GetJsonImageErrorType =\n | EnsAvatarInvalidMetadataErrorType\n | ErrorType\n\nexport function getJsonImage(data: any) {\n // validation check for json data, must include one of theses properties\n if (\n typeof data !== 'object' ||\n (!('image' in data) && !('image_url' in data) && !('image_data' in data))\n ) {\n throw new EnsAvatarInvalidMetadataError({ data })\n }\n\n return data.image || data.image_url || data.image_data\n}\n\nexport type GetMetadataAvatarUriErrorType =\n | EnsAvatarUriResolutionErrorType\n | ParseAvatarUriErrorType\n | GetJsonImageErrorType\n | ErrorType\n\nexport async function getMetadataAvatarUri({\n gatewayUrls,\n uri,\n}: {\n gatewayUrls?: AssetGatewayUrls | undefined\n uri: string\n}): Promise<string> {\n try {\n const res = await fetch(uri).then((res) => res.json())\n const image = await parseAvatarUri({\n gatewayUrls,\n uri: getJsonImage(res),\n })\n return image\n } catch {\n throw new EnsAvatarUriResolutionError({ uri })\n }\n}\n\nexport type ParseAvatarUriErrorType =\n | ResolveAvatarUriErrorType\n | IsImageUriErrorType\n | EnsAvatarUriResolutionErrorType\n | ErrorType\n\nexport async function parseAvatarUri({\n gatewayUrls,\n uri,\n}: {\n gatewayUrls?: AssetGatewayUrls | undefined\n uri: string\n}): Promise<string> {\n const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls })\n if (isOnChain) return resolvedURI\n\n // check if resolvedURI is an image, if it is return the url\n const isImage = await isImageUri(resolvedURI)\n if (isImage) return resolvedURI\n\n throw new EnsAvatarUriResolutionError({ uri })\n}\n\ntype ParsedNft = {\n chainID: number\n namespace: string\n contractAddress: Address\n tokenID: string\n}\n\nexport type ParseNftUriErrorType = EnsAvatarInvalidNftUriErrorType | ErrorType\n\nexport function parseNftUri(uri_: string): ParsedNft {\n let uri = uri_\n // parse valid nft spec (CAIP-22/CAIP-29)\n // @see: https://github.com/ChainAgnostic/CAIPs/tree/master/CAIPs\n if (uri.startsWith('did:nft:')) {\n // convert DID to CAIP\n uri = uri.replace('did:nft:', '').replace(/_/g, '/')\n }\n\n const [reference, asset_namespace, tokenID] = uri.split('/')\n const [eip_namespace, chainID] = reference.split(':')\n const [erc_namespace, contractAddress] = asset_namespace.split(':')\n\n if (!eip_namespace || eip_namespace.toLowerCase() !== 'eip155')\n throw new EnsAvatarInvalidNftUriError({ reason: 'Only EIP-155 supported' })\n if (!chainID)\n throw new EnsAvatarInvalidNftUriError({ reason: 'Chain ID not found' })\n if (!contractAddress)\n throw new EnsAvatarInvalidNftUriError({\n reason: 'Contract address not found',\n })\n if (!tokenID)\n throw new EnsAvatarInvalidNftUriError({ reason: 'Token ID not found' })\n if (!erc_namespace)\n throw new EnsAvatarInvalidNftUriError({ reason: 'ERC namespace not found' })\n\n return {\n chainID: Number.parseInt(chainID),\n namespace: erc_namespace.toLowerCase(),\n contractAddress: contractAddress as Address,\n tokenID,\n }\n}\n\nexport type GetNftTokenUriErrorType =\n | ReadContractErrorType\n | EnsAvatarUnsupportedNamespaceErrorType\n | ErrorType\n\nexport async function getNftTokenUri<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { nft }: { nft: ParsedNft },\n) {\n if (nft.namespace === 'erc721') {\n return readContract(client, {\n address: nft.contractAddress,\n abi: [\n {\n name: 'tokenURI',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'tokenId', type: 'uint256' }],\n outputs: [{ name: '', type: 'string' }],\n },\n ],\n functionName: 'tokenURI',\n args: [BigInt(nft.tokenID)],\n })\n }\n if (nft.namespace === 'erc1155') {\n return readContract(client, {\n address: nft.contractAddress,\n abi: [\n {\n name: 'uri',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: '_id', type: 'uint256' }],\n outputs: [{ name: '', type: 'string' }],\n },\n ],\n functionName: 'uri',\n args: [BigInt(nft.tokenID)],\n })\n }\n throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace })\n}\n","import type { Client } from '../../../clients/createClient.js'\nimport type { Transport } from '../../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { Chain } from '../../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../../types/ens.js'\n\nimport {\n type GetJsonImageErrorType,\n type GetMetadataAvatarUriErrorType,\n type GetNftTokenUriErrorType,\n type ParseAvatarUriErrorType,\n type ParseNftUriErrorType,\n type ResolveAvatarUriErrorType,\n getJsonImage,\n getMetadataAvatarUri,\n getNftTokenUri,\n parseAvatarUri,\n parseNftUri,\n resolveAvatarUri,\n} from './utils.js'\n\nexport type ParseAvatarRecordErrorType =\n | ParseNftAvatarUriErrorType\n | ParseAvatarUriErrorType\n | ErrorType\n\n/*\n * @description Parses an ENS avatar record.\n *\n * @example\n * parseAvatarRecord('eip155:1/erc1155:0xb32979486938aa9694bfc898f35dbed459f44424/10063')\n * 'https://ipfs.io/ipfs/QmSP4nq9fnN9dAiCj42ug9Wa79rqmQerZXZch82VqpiH7U/image.gif'\n *\n * @see https://docs.ens.domains/web/avatars\n *\n */\nexport async function parseAvatarRecord<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n {\n gatewayUrls,\n record,\n }: {\n gatewayUrls?: AssetGatewayUrls | undefined\n record: string\n },\n): Promise<string> {\n if (/eip155:/i.test(record))\n return parseNftAvatarUri(client, { gatewayUrls, record })\n return parseAvatarUri({ uri: record, gatewayUrls })\n}\n\ntype ParseNftAvatarUriErrorType =\n | ParseNftUriErrorType\n | GetNftTokenUriErrorType\n | ResolveAvatarUriErrorType\n | ParseAvatarUriErrorType\n | GetJsonImageErrorType\n | GetMetadataAvatarUriErrorType\n | ErrorType\n\nasync function parseNftAvatarUri<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n {\n gatewayUrls,\n record,\n }: {\n gatewayUrls?: AssetGatewayUrls | undefined\n record: string\n },\n): Promise<string> {\n // parse NFT URI into properties\n const nft = parseNftUri(record)\n // fetch tokenURI from the NFT contract\n const nftUri = await getNftTokenUri(client, { nft })\n // resolve the URI from the fetched tokenURI\n const {\n uri: resolvedNftUri,\n isOnChain,\n isEncoded,\n } = resolveAvatarUri({ uri: nftUri, gatewayUrls })\n\n // if the resolved URI is on chain, return the data\n if (\n isOnChain &&\n (resolvedNftUri.includes('data:application/json;base64,') ||\n resolvedNftUri.startsWith('{'))\n ) {\n const encodedJson = isEncoded\n ? // if it is encoded, decode it\n atob(resolvedNftUri.replace('data:application/json;base64,', ''))\n : // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is)\n resolvedNftUri\n\n const decoded = JSON.parse(encodedJson)\n return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls })\n }\n\n let uriTokenId = nft.tokenID\n if (nft.namespace === 'erc1155')\n uriTokenId = uriTokenId.replace('0x', '').padStart(64, '0')\n\n return getMetadataAvatarUri({\n gatewayUrls,\n uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId),\n })\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n textResolverAbi,\n universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsTextParameters = Prettify<\n Pick<ReadContractParameters, 'blockNumber' | 'blockTag'> & {\n /** ENS name to get Text for. */\n name: string\n /** Universal Resolver gateway URLs to use for resolving CCIP-read requests. */\n gatewayUrls?: string[] | undefined\n /** Text record to retrieve. */\n key: string\n /** Whether or not to throw errors propagated from the ENS Universal Resolver Contract. */\n strict?: boolean | undefined\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsTextReturnType = string | null\n\nexport type GetEnsTextErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | EncodeFunctionDataErrorType\n | NamehashErrorType\n | DecodeFunctionResultErrorType\n\n/**\n * Gets a text record for specified ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsTextParameters}\n * @returns Address for ENS resolver. {@link GetEnsTextReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsText, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const twitterRecord = await getEnsText(client, {\n * name: normalize('wevm.eth'),\n * key: 'com.twitter',\n * })\n * // 'wevm_dev'\n */\nexport async function getEnsText<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n {\n blockNumber,\n blockTag,\n name,\n key,\n gatewayUrls,\n strict,\n universalResolverAddress: universalResolverAddress_,\n }: GetEnsTextParameters,\n): Promise<GetEnsTextReturnType> {\n let universalResolverAddress = universalResolverAddress_\n if (!universalResolverAddress) {\n if (!client.chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n\n universalResolverAddress = getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'ensUniversalResolver',\n })\n }\n\n try {\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverResolveAbi,\n functionName: 'resolve',\n args: [\n toHex(packetToBytes(name)),\n encodeFunctionData({\n abi: textResolverAbi,\n functionName: 'text',\n args: [namehash(name), key],\n }),\n ],\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const res = gatewayUrls\n ? await readContractAction({\n ...readContractParameters,\n args: [...readContractParameters.args, gatewayUrls],\n })\n : await readContractAction(readContractParameters)\n\n if (res[0] === '0x') return null\n\n const record = decodeFunctionResult({\n abi: textResolverAbi,\n functionName: 'text',\n data: res[0],\n })\n\n return record === '' ? null : record\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err, 'resolve')) return null\n throw err\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../types/ens.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type ParseAvatarRecordErrorType,\n parseAvatarRecord,\n} from '../../utils/ens/avatar/parseAvatarRecord.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport {\n type GetEnsTextErrorType,\n type GetEnsTextParameters,\n getEnsText,\n} from './getEnsText.js'\n\nexport type GetEnsAvatarParameters = Prettify<\n Omit<GetEnsTextParameters, 'key'> & {\n /** Gateway urls to resolve IPFS and/or Arweave assets. */\n assetGatewayUrls?: AssetGatewayUrls | undefined\n }\n>\n\nexport type GetEnsAvatarReturnType = string | null\n\nexport type GetEnsAvatarErrorType =\n | GetEnsTextErrorType\n | ParseAvatarRecordErrorType\n | ErrorType\n\n/**\n * Gets the avatar of an ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAvatar\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText) with `key` set to `'avatar'`.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAvatarParameters}\n * @returns Avatar URI or `null` if not found. {@link GetEnsAvatarReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAvatar, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAvatar = await getEnsAvatar(client, {\n * name: normalize('wevm.eth'),\n * })\n * // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'\n */\nexport async function getEnsAvatar<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n {\n blockNumber,\n blockTag,\n assetGatewayUrls,\n name,\n gatewayUrls,\n strict,\n universalResolverAddress,\n }: GetEnsAvatarParameters,\n): Promise<GetEnsAvatarReturnType> {\n const record = await getAction(\n client,\n getEnsText,\n 'getEnsText',\n )({\n blockNumber,\n blockTag,\n key: 'avatar',\n name,\n universalResolverAddress,\n gatewayUrls,\n strict,\n })\n if (!record) return null\n try {\n return await parseAvatarRecord(client, {\n record,\n gatewayUrls: assetGatewayUrls,\n })\n } catch {\n return null\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { universalResolverReverseAbi } from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractErrorType,\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsNameParameters = Prettify<\n Pick<ReadContractParameters, 'blockNumber' | 'blockTag'> & {\n /** Address to get ENS name for. */\n address: Address\n /** Universal Resolver gateway URLs to use for resolving CCIP-read requests. */\n gatewayUrls?: string[] | undefined\n /** Whether or not to throw errors propagated from the ENS Universal Resolver Contract. */\n strict?: boolean | undefined\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsNameReturnType = string | null\n\nexport type GetEnsNameErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | ErrorType\n\n/**\n * Gets primary name for specified address.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsName\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsNameParameters}\n * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsName } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensName = await getEnsName(client, {\n * address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n * })\n * // 'wevm.eth'\n */\nexport async function getEnsName<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n {\n address,\n blockNumber,\n blockTag,\n gatewayUrls,\n strict,\n universalResolverAddress: universalResolverAddress_,\n }: GetEnsNameParameters,\n): Promise<GetEnsNameReturnType> {\n let universalResolverAddress = universalResolverAddress_\n if (!universalResolverAddress) {\n if (!client.chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n\n universalResolverAddress = getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'ensUniversalResolver',\n })\n }\n\n const reverseNode = `${address.toLowerCase().substring(2)}.addr.reverse`\n try {\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverReverseAbi,\n functionName: 'reverse',\n args: [toHex(packetToBytes(reverseNode))],\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const [name, resolvedAddress] = gatewayUrls\n ? await readContractAction({\n ...readContractParameters,\n args: [...readContractParameters.args, gatewayUrls],\n })\n : await readContractAction(readContractParameters)\n\n if (address.toLowerCase() !== resolvedAddress.toLowerCase()) return null\n return name\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err, 'reverse')) return null\n throw err\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsResolverParameters = Prettify<\n Pick<ReadContractParameters, 'blockNumber' | 'blockTag'> & {\n /** Name to get the address for. */\n name: string\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsResolverReturnType = Address\n\nexport type GetEnsResolverErrorType =\n | GetChainContractAddressErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | ErrorType\n\n/**\n * Gets resolver for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsResolverParameters}\n * @returns Address for ENS resolver. {@link GetEnsResolverReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsResolver, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const resolverAddress = await getEnsResolver(client, {\n * name: normalize('wevm.eth'),\n * })\n * // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'\n */\nexport async function getEnsResolver<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n {\n blockNumber,\n blockTag,\n name,\n universalResolverAddress: universalResolverAddress_,\n }: GetEnsResolverParameters,\n) {\n let universalResolverAddress = universalResolverAddress_\n if (!universalResolverAddress) {\n if (!client.chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n\n universalResolverAddress = getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'ensUniversalResolver',\n })\n }\n\n const [resolverAddress] = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n address: universalResolverAddress,\n abi: [\n {\n inputs: [{ type: 'bytes' }],\n name: 'findResolver',\n outputs: [{ type: 'address' }, { type: 'bytes32' }],\n stateMutability: 'view',\n type: 'function',\n },\n ],\n functionName: 'findResolver',\n args: [toHex(packetToBytes(name))],\n blockNumber,\n blockTag,\n })\n return resolverAddress\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { AccessList, TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial, Prettify, UnionOmit } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type GetCallErrorReturnType,\n getCallError,\n} from '../../utils/errors/getCallError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormatTransactionRequestErrorType,\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport type {\n AssertRequestErrorType,\n AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\n\nexport type CreateAccessListParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit<\n FormattedTransactionRequest<chain>,\n 'from' | 'nonce' | 'accessList'\n> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | undefined\n} & (\n | {\n /** The balance of the account at a block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The balance of the account at a block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n )\n\nexport type CreateAccessListReturnType = Prettify<{\n accessList: AccessList\n gasUsed: bigint\n}>\n\nexport type CreateAccessListErrorType = GetCallErrorReturnType<\n | ParseAccountErrorType\n | AssertRequestErrorType\n | NumberToHexErrorType\n | FormatTransactionRequestErrorType\n | RequestErrorType\n>\n\n/**\n * Creates an EIP-2930 access list.\n *\n * - Docs: https://viem.sh/docs/actions/public/createAccessList\n * - JSON-RPC Methods: `eth_createAccessList`\n *\n * @param client - Client to use\n * @param parameters - {@link CreateAccessListParameters}\n * @returns The access list. {@link CreateAccessListReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createAccessList } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const data = await createAccessList(client, {\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\nexport async function createAccessList<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n args: CreateAccessListParameters<chain>,\n): Promise<CreateAccessListReturnType> {\n const {\n account: account_ = client.account,\n blockNumber,\n blockTag = 'latest',\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n value,\n ...rest\n } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n try {\n assertRequest(args as AssertRequestParameters)\n\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format({\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n from: account?.address,\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n value,\n } as TransactionRequest) as TransactionRequest\n\n const response = await client.request({\n method: 'eth_createAccessList',\n params: [request as ExactPartial<RpcTransactionRequest>, block],\n })\n return {\n accessList: response.accessList,\n gasUsed: BigInt(response.gasUsed),\n }\n } catch (err) {\n throw getCallError(err as ErrorType, {\n ...args,\n account,\n chain: client.chain,\n })\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateBlockFilterReturnType = Filter<'block'>\n\nexport type CreateBlockFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new block hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createBlockFilter\n * - JSON-RPC Methods: [`eth_newBlockFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter)\n *\n * @param client - Client to use\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'block' }\n */\nexport async function createBlockFilter<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n): Promise<CreateBlockFilterReturnType> {\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newBlockFilter',\n })\n const id = await client.request({\n method: 'eth_newBlockFilter',\n })\n return { id, request: getRequest(id), type: 'block' }\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex, LogTopic } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateEventFilterParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName<abiEvent>,\n _args extends\n | MaybeExtractEventArgsFromAbi<abiEvents, _eventName>\n | undefined = undefined,\n> = {\n address?: Address | Address[] | undefined\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n} & (MaybeExtractEventArgsFromAbi<\n abiEvents,\n _eventName\n> extends infer eventFilterArgs\n ?\n | {\n args:\n | eventFilterArgs\n | (_args extends eventFilterArgs ? _args : never)\n event: abiEvent\n events?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: abiEvent | undefined\n events?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: undefined\n events: abiEvents | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n args?: undefined\n event?: undefined\n events?: undefined\n strict?: undefined\n }\n : {\n args?: undefined\n event?: undefined\n events?: undefined\n strict?: undefined\n })\n\nexport type CreateEventFilterReturnType<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _eventName extends string | undefined = MaybeAbiEventName<abiEvent>,\n _args extends\n | MaybeExtractEventArgsFromAbi<abiEvents, _eventName>\n | undefined = undefined,\n> = Prettify<\n Filter<'event', abiEvents, _eventName, _args, strict, fromBlock, toBlock>\n>\n\nexport type CreateEventFilterErrorType =\n | EncodeEventTopicsErrorType\n | RequestErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new events that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createEventFilter\n * - JSON-RPC Methods: [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter)\n *\n * @param client - Client to use\n * @param parameters - {@link CreateEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * })\n */\nexport async function createEventFilter<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber<bigint> | BlockTag | undefined = undefined,\n toBlock extends BlockNumber<bigint> | BlockTag | undefined = undefined,\n _eventName extends string | undefined = MaybeAbiEventName<abiEvent>,\n _args extends\n | MaybeExtractEventArgsFromAbi<abiEvents, _eventName>\n | undefined = undefined,\n>(\n client: Client<Transport, chain>,\n {\n address,\n args,\n event,\n events: events_,\n fromBlock,\n strict,\n toBlock,\n }: CreateEventFilterParameters<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n > = {} as any,\n): Promise<\n CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n >\n> {\n const events = events_ ?? (event ? [event] : undefined)\n\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newFilter',\n })\n\n let topics: LogTopic[] = []\n if (events) {\n const encoded = (events as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n const id: Hex = await client.request({\n method: 'eth_newFilter',\n params: [\n {\n address,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n ...(topics.length ? { topics } : {}),\n },\n ],\n })\n\n return {\n abi: events,\n args,\n eventName: event ? (event as AbiEvent).name : undefined,\n fromBlock,\n id,\n request: getRequest(id),\n strict: Boolean(strict),\n toBlock,\n type: 'event',\n } as unknown as CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _eventName,\n _args\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreatePendingTransactionFilterReturnType = Filter<'transaction'>\n\nexport type CreatePendingTransactionFilterErrorType =\n | RequestErrorType\n | ErrorType\n\n/**\n * Creates a Filter to listen for new pending transaction hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter\n * - JSON-RPC Methods: [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter)\n *\n * @param client - Client to use\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'transaction' }\n */\nexport async function createPendingTransactionFilter<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n client: Client<transport, chain>,\n): Promise<CreatePendingTransactionFilterReturnType> {\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newPendingTransactionFilter',\n })\n const id = await client.request({\n method: 'eth_newPendingTransactionFilter',\n })\n return { id, request: getRequest(id), type: 'transaction' }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetBlobBaseFeeReturnType = bigint\n\nexport type GetBlobBaseFeeErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the base fee per blob gas in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlobBaseFee\n * - JSON-RPC Methods: [`eth_blobBaseFee`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blobBaseFee)\n *\n * @param client - Client to use\n * @returns The blob base fee (in wei). {@link GetBlobBaseFeeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlobBaseFee } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blobBaseFee = await getBlobBaseFee(client)\n */\nexport async function getBlobBaseFee<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n): Promise<GetBlobBaseFeeReturnType> {\n const baseFee = await client.request({\n method: 'eth_blobBaseFee',\n })\n return BigInt(baseFee)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Quantity } from '../../types/rpc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetBlockTransactionCountParameters =\n | {\n /** Hash of the block. */\n blockHash?: Hash | undefined\n blockNumber?: undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /** The block tag. Defaults to 'latest'. */\n blockTag?: BlockTag | undefined\n }\n\nexport type GetBlockTransactionCountReturnType = number\n\nexport type GetBlockTransactionCountErrorType =\n | NumberToHexErrorType\n | HexToNumberErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the number of Transactions at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockTransactionCountByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockTransactionCountByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockTransactionCountParameters}\n * @returns The block transaction count. {@link GetBlockTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const count = await getBlockTransactionCount(client)\n */\nexport async function getBlockTransactionCount<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n {\n blockHash,\n blockNumber,\n blockTag = 'latest',\n }: GetBlockTransactionCountParameters = {},\n): Promise<GetBlockTransactionCountReturnType> {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let count: Quantity\n if (blockHash) {\n count = await client.request(\n {\n method: 'eth_getBlockTransactionCountByHash',\n params: [blockHash],\n },\n { dedupe: true },\n )\n } else {\n count = await client.request(\n {\n method: 'eth_getBlockTransactionCountByNumber',\n params: [blockNumberHex || blockTag],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n return hexToNumber(count)\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetCodeParameters = {\n address: Address\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetCodeReturnType = Hex | undefined\n\nexport type GetCodeErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Retrieves the bytecode at an address.\n *\n * - Docs: https://viem.sh/docs/contract/getCode\n * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n *\n * @param client - Client to use\n * @param parameters - {@link GetCodeParameters}\n * @returns The contract's bytecode. {@link GetCodeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getCode } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await getCode(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * })\n */\nexport async function getCode<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { address, blockNumber, blockTag = 'latest' }: GetCodeParameters,\n): Promise<GetCodeReturnType> {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n const hex = await client.request(\n {\n method: 'eth_getCode',\n params: [address, blockNumberHex || blockTag],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n if (hex === '0x') return undefined\n return hex\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { FeeHistory } from '../../types/fee.js'\nimport type { RpcFeeHistory } from '../../types/rpc.js'\n\nexport type FormatFeeHistoryErrorType = ErrorType\n\nexport function formatFeeHistory(feeHistory: RpcFeeHistory): FeeHistory {\n return {\n baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)),\n gasUsedRatio: feeHistory.gasUsedRatio,\n oldestBlock: BigInt(feeHistory.oldestBlock),\n reward: feeHistory.reward?.map((reward) =>\n reward.map((value) => BigInt(value)),\n ),\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { FeeHistory } from '../../types/fee.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatFeeHistoryErrorType,\n formatFeeHistory,\n} from '../../utils/formatters/feeHistory.js'\n\nexport type GetFeeHistoryParameters = {\n /**\n * Number of blocks in the requested range. Between 1 and 1024 blocks can be requested in a single query. Less than requested may be returned if not all blocks are available.\n */\n blockCount: number\n /**\n * A monotonically increasing list of percentile values to sample from each block's effective priority fees per gas in ascending order, weighted by gas used.\n */\n rewardPercentiles: number[]\n} & (\n | {\n blockNumber?: undefined\n /**\n * Highest number block of the requested range.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n | {\n /** Highest number block of the requested range. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\nexport type GetFeeHistoryReturnType = FeeHistory\n\nexport type GetFeeHistoryErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | FormatFeeHistoryErrorType\n\n/**\n * Returns a collection of historical gas information.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFeeHistory\n * - JSON-RPC Methods: [`eth_feeHistory`](https://docs.alchemy.com/reference/eth-feehistory)\n *\n * @param client - Client to use\n * @param parameters - {@link GetFeeHistoryParameters}\n * @returns The gas estimate (in wei). {@link GetFeeHistoryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getFeeHistory } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const feeHistory = await getFeeHistory(client, {\n * blockCount: 4,\n * rewardPercentiles: [25, 75],\n * })\n */\nexport async function getFeeHistory<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n {\n blockCount,\n blockNumber,\n blockTag = 'latest',\n rewardPercentiles,\n }: GetFeeHistoryParameters,\n): Promise<GetFeeHistoryReturnType> {\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n const feeHistory = await client.request(\n {\n method: 'eth_feeHistory',\n params: [\n numberToHex(blockCount),\n blockNumberHex || blockTag,\n rewardPercentiles,\n ],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n return formatFeeHistory(feeHistory)\n}\n","import type { Abi, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterLogsParameters<\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n filter: Filter<'event', abi, eventName, any, strict, fromBlock, toBlock>\n}\nexport type GetFilterLogsReturnType<\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _AbiEvent extends AbiEvent | undefined = abi extends Abi\n ? eventName extends string\n ? ExtractAbiEvent<abi, eventName>\n : undefined\n : undefined,\n _Pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log<bigint, number, _Pending, _AbiEvent, strict, abi, eventName>[]\n\nexport type GetFilterLogsErrorType =\n | RequestErrorType\n | DecodeEventLogErrorType\n | FormatLogErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs since the filter was created.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterLogs\n * - JSON-RPC Methods: [`eth_getFilterLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs)\n *\n * `getFilterLogs` is only compatible with **event filters**.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterLogsParameters}\n * @returns A list of event logs. {@link GetFilterLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterLogs(client, { filter })\n */\nexport async function getFilterLogs<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n _client: Client<Transport, chain>,\n {\n filter,\n }: GetFilterLogsParameters<abi, eventName, strict, fromBlock, toBlock>,\n): Promise<\n GetFilterLogsReturnType<abi, eventName, strict, fromBlock, toBlock>\n> {\n const strict = filter.strict ?? false\n\n const logs = await filter.request({\n method: 'eth_getFilterLogs',\n params: [filter.id],\n })\n\n const formattedLogs = logs.map((log) => formatLog(log))\n if (!filter.abi)\n return formattedLogs as GetFilterLogsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: filter.abi,\n logs: formattedLogs,\n strict,\n }) as unknown as GetFilterLogsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Chain, ChainFormatters } from '../../types/chain.js'\nimport type { Assign, Prettify } from '../../types/utils.js'\n\nexport function defineChain<\n formatters extends ChainFormatters,\n const chain extends Chain<formatters>,\n>(chain: chain): Prettify<Assign<Chain<undefined>, chain>> {\n return {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n } as Assign<Chain<undefined>, chain>\n}\n","import type { TypedData } from 'abitype'\n\nimport { stringify } from '../utils/stringify.js'\nimport { BaseError } from './base.js'\n\nexport type InvalidDomainErrorType = InvalidDomainError & {\n name: 'InvalidDomainError'\n}\nexport class InvalidDomainError extends BaseError {\n constructor({ domain }: { domain: unknown }) {\n super(`Invalid domain \"${stringify(domain)}\".`, {\n metaMessages: ['Must be a valid EIP-712 domain.'],\n })\n }\n}\n\nexport type InvalidPrimaryTypeErrorType = InvalidPrimaryTypeError & {\n name: 'InvalidPrimaryTypeError'\n}\nexport class InvalidPrimaryTypeError extends BaseError {\n constructor({\n primaryType,\n types,\n }: { primaryType: string; types: TypedData | Record<string, unknown> }) {\n super(\n `Invalid primary type \\`${primaryType}\\` must be one of \\`${JSON.stringify(Object.keys(types))}\\`.`,\n {\n docsPath: '/api/glossary/Errors#typeddatainvalidprimarytypeerror',\n metaMessages: ['Check that the primary type is a key in `types`.'],\n },\n )\n }\n}\n\nexport type InvalidStructTypeErrorType = InvalidStructTypeError & {\n name: 'InvalidStructTypeError'\n}\nexport class InvalidStructTypeError extends BaseError {\n constructor({ type }: { type: string }) {\n super(`Struct type \"${type}\" is invalid.`, {\n metaMessages: ['Struct type must not be a Solidity type.'],\n name: 'InvalidStructTypeError',\n })\n }\n}\n","// Implementation forked and adapted from https://github.com/MetaMask/eth-sig-util/blob/main/src/sign-typed-data.ts\n\nimport type { AbiParameter, TypedData, TypedDataDomain } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from '../abi/encodeAbiParameters.js'\nimport { concat } from '../data/concat.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type GetTypesForEIP712DomainErrorType,\n type ValidateTypedDataErrorType,\n getTypesForEIP712Domain,\n validateTypedData,\n} from '../typedData.js'\n\ntype MessageTypeProperty = {\n name: string\n type: string\n}\n\nexport type HashTypedDataParameters<\n typedData extends TypedData | Record<string, unknown> = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition<typedData, primaryType>\n\nexport type HashTypedDataReturnType = Hex\n\nexport type HashTypedDataErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | HashStructErrorType\n | ValidateTypedDataErrorType\n | ErrorType\n\nexport function hashTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: HashTypedDataParameters<typedData, primaryType>,\n): HashTypedDataReturnType {\n const {\n domain = {},\n message,\n primaryType,\n } = parameters as HashTypedDataParameters\n const types = {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n ...parameters.types,\n }\n\n // Need to do a runtime validation check on addresses, byte ranges, integer ranges, etc\n // as we can't statically check this with TypeScript.\n validateTypedData({\n domain,\n message,\n primaryType,\n types,\n })\n\n const parts: Hex[] = ['0x1901']\n if (domain)\n parts.push(\n hashDomain({\n domain,\n types: types as Record<string, MessageTypeProperty[]>,\n }),\n )\n\n if (primaryType !== 'EIP712Domain')\n parts.push(\n hashStruct({\n data: message,\n primaryType,\n types: types as Record<string, MessageTypeProperty[]>,\n }),\n )\n\n return keccak256(concat(parts))\n}\n\nexport type HashDomainErrorType = HashStructErrorType | ErrorType\n\nexport function hashDomain({\n domain,\n types,\n}: {\n domain: TypedDataDomain\n types: Record<string, MessageTypeProperty[]>\n}) {\n return hashStruct({\n data: domain,\n primaryType: 'EIP712Domain',\n types,\n })\n}\n\nexport type HashStructErrorType =\n | EncodeDataErrorType\n | Keccak256ErrorType\n | ErrorType\n\nexport function hashStruct({\n data,\n primaryType,\n types,\n}: {\n data: Record<string, unknown>\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n}) {\n const encoded = encodeData({\n data,\n primaryType,\n types,\n })\n return keccak256(encoded)\n}\n\ntype EncodeDataErrorType =\n | EncodeAbiParametersErrorType\n | EncodeFieldErrorType\n | HashTypeErrorType\n | ErrorType\n\nfunction encodeData({\n data,\n primaryType,\n types,\n}: {\n data: Record<string, unknown>\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n}) {\n const encodedTypes: AbiParameter[] = [{ type: 'bytes32' }]\n const encodedValues: unknown[] = [hashType({ primaryType, types })]\n\n for (const field of types[primaryType]) {\n const [type, value] = encodeField({\n types,\n name: field.name,\n type: field.type,\n value: data[field.name],\n })\n encodedTypes.push(type)\n encodedValues.push(value)\n }\n\n return encodeAbiParameters(encodedTypes, encodedValues)\n}\n\ntype HashTypeErrorType =\n | ToHexErrorType\n | EncodeTypeErrorType\n | Keccak256ErrorType\n | ErrorType\n\nfunction hashType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n}) {\n const encodedHashType = toHex(encodeType({ primaryType, types }))\n return keccak256(encodedHashType)\n}\n\ntype EncodeTypeErrorType = FindTypeDependenciesErrorType\n\nexport function encodeType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n}) {\n let result = ''\n const unsortedDeps = findTypeDependencies({ primaryType, types })\n unsortedDeps.delete(primaryType)\n\n const deps = [primaryType, ...Array.from(unsortedDeps).sort()]\n for (const type of deps) {\n result += `${type}(${types[type]\n .map(({ name, type: t }) => `${t} ${name}`)\n .join(',')})`\n }\n\n return result\n}\n\ntype FindTypeDependenciesErrorType = ErrorType\n\nfunction findTypeDependencies(\n {\n primaryType: primaryType_,\n types,\n }: {\n primaryType: string\n types: Record<string, readonly MessageTypeProperty[]>\n },\n results: Set<string> = new Set(),\n): Set<string> {\n const match = primaryType_.match(/^\\w*/u)\n const primaryType = match?.[0]!\n if (results.has(primaryType) || types[primaryType] === undefined) {\n return results\n }\n\n results.add(primaryType)\n\n for (const field of types[primaryType]) {\n findTypeDependencies({ primaryType: field.type, types }, results)\n }\n return results\n}\n\ntype EncodeFieldErrorType =\n | Keccak256ErrorType\n | EncodeAbiParametersErrorType\n | ToHexErrorType\n | ErrorType\n\nfunction encodeField({\n types,\n name,\n type,\n value,\n}: {\n types: Record<string, readonly MessageTypeProperty[]>\n name: string\n type: string\n value: any\n}): [type: AbiParameter, value: any] {\n if (types[type] !== undefined) {\n return [\n { type: 'bytes32' },\n keccak256(encodeData({ data: value, primaryType: type, types })),\n ]\n }\n\n if (type === 'bytes') {\n const prepend = value.length % 2 ? '0' : ''\n value = `0x${prepend + value.slice(2)}`\n return [{ type: 'bytes32' }, keccak256(value)]\n }\n\n if (type === 'string') return [{ type: 'bytes32' }, keccak256(toHex(value))]\n\n if (type.lastIndexOf(']') === type.length - 1) {\n const parsedType = type.slice(0, type.lastIndexOf('['))\n const typeValuePairs = (value as [AbiParameter, any][]).map((item) =>\n encodeField({\n name,\n type: parsedType,\n types,\n value: item,\n }),\n )\n return [\n { type: 'bytes32' },\n keccak256(\n encodeAbiParameters(\n typeValuePairs.map(([t]) => t),\n typeValuePairs.map(([, v]) => v),\n ),\n ),\n ]\n }\n\n return [{ type }, value]\n}\n","import type { TypedData, TypedDataDomain, TypedDataParameter } from 'abitype'\n\nimport { BytesSizeMismatchError } from '../errors/abi.js'\nimport { InvalidAddressError } from '../errors/address.js'\nimport {\n InvalidDomainError,\n InvalidPrimaryTypeError,\n InvalidStructTypeError,\n} from '../errors/typedData.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport type { TypedDataDefinition } from '../types/typedData.js'\nimport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nimport { type SizeErrorType, size } from './data/size.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\nimport { bytesRegex, integerRegex } from './regex.js'\nimport {\n type HashDomainErrorType,\n hashDomain,\n} from './signature/hashTypedData.js'\nimport { stringify } from './stringify.js'\n\nexport type SerializeTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function serializeTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition<typedData, primaryType>) {\n const {\n domain: domain_,\n message: message_,\n primaryType,\n types,\n } = parameters as unknown as TypedDataDefinition\n\n const normalizeData = (\n struct: readonly TypedDataParameter[],\n data_: Record<string, unknown>,\n ) => {\n const data = { ...data_ }\n for (const param of struct) {\n const { name, type } = param\n if (type === 'address') data[name] = (data[name] as string).toLowerCase()\n }\n return data\n }\n\n const domain = (() => {\n if (!types.EIP712Domain) return {}\n if (!domain_) return {}\n return normalizeData(types.EIP712Domain, domain_)\n })()\n\n const message = (() => {\n if (primaryType === 'EIP712Domain') return undefined\n return normalizeData(types[primaryType], message_)\n })()\n\n return stringify({ domain, message, primaryType, types })\n}\n\nexport type ValidateTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function validateTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition<typedData, primaryType>) {\n const { domain, message, primaryType, types } =\n parameters as unknown as TypedDataDefinition\n\n const validateData = (\n struct: readonly TypedDataParameter[],\n data: Record<string, unknown>,\n ) => {\n for (const param of struct) {\n const { name, type } = param\n const value = data[name]\n\n const integerMatch = type.match(integerRegex)\n if (\n integerMatch &&\n (typeof value === 'number' || typeof value === 'bigint')\n ) {\n const [_type, base, size_] = integerMatch\n // If number cannot be cast to a sized hex value, it is out of range\n // and will throw.\n numberToHex(value, {\n signed: base === 'int',\n size: Number.parseInt(size_) / 8,\n })\n }\n\n if (type === 'address' && typeof value === 'string' && !isAddress(value))\n throw new InvalidAddressError({ address: value })\n\n const bytesMatch = type.match(bytesRegex)\n if (bytesMatch) {\n const [_type, size_] = bytesMatch\n if (size_ && size(value as Hex) !== Number.parseInt(size_))\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size_),\n givenSize: size(value as Hex),\n })\n }\n\n const struct = types[type]\n if (struct) {\n validateReference(type)\n validateData(struct, value as Record<string, unknown>)\n }\n }\n }\n\n // Validate domain types.\n if (types.EIP712Domain && domain) {\n if (typeof domain !== 'object') throw new InvalidDomainError({ domain })\n validateData(types.EIP712Domain, domain)\n }\n\n // Validate message types.\n if (primaryType !== 'EIP712Domain') {\n if (types[primaryType]) validateData(types[primaryType], message)\n else throw new InvalidPrimaryTypeError({ primaryType, types })\n }\n}\n\nexport type GetTypesForEIP712DomainErrorType = ErrorType\n\nexport function getTypesForEIP712Domain({\n domain,\n}: { domain?: TypedDataDomain | undefined }): TypedDataParameter[] {\n return [\n typeof domain?.name === 'string' && { name: 'name', type: 'string' },\n domain?.version && { name: 'version', type: 'string' },\n (typeof domain?.chainId === 'number' ||\n typeof domain?.chainId === 'bigint') && {\n name: 'chainId',\n type: 'uint256',\n },\n domain?.verifyingContract && {\n name: 'verifyingContract',\n type: 'address',\n },\n domain?.salt && { name: 'salt', type: 'bytes32' },\n ].filter(Boolean) as TypedDataParameter[]\n}\n\nexport type DomainSeparatorErrorType =\n | GetTypesForEIP712DomainErrorType\n | HashDomainErrorType\n | ErrorType\n\nexport function domainSeparator({ domain }: { domain: TypedDataDomain }): Hex {\n return hashDomain({\n domain,\n types: {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n },\n })\n}\n\n/** @internal */\nfunction validateReference(type: string) {\n // Struct type must not be a Solidity type.\n if (\n type === 'address' ||\n type === 'bool' ||\n type === 'string' ||\n type.startsWith('bytes') ||\n type.startsWith('uint') ||\n type.startsWith('int')\n )\n throw new InvalidStructTypeError({ type })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Chain,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { RpcTransactionReceipt } from '../../types/rpc.js'\nimport type { TransactionReceipt } from '../../types/transaction.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { formatLog } from './log.js'\nimport { transactionType } from './transaction.js'\n\nexport type FormattedTransactionReceipt<\n chain extends Chain | undefined = undefined,\n> = ExtractChainFormatterReturnType<\n chain,\n 'transactionReceipt',\n TransactionReceipt\n>\n\nexport const receiptStatuses = {\n '0x0': 'reverted',\n '0x1': 'success',\n} as const\n\nexport type FormatTransactionReceiptErrorType = ErrorType\n\nexport function formatTransactionReceipt(\n transactionReceipt: ExactPartial<RpcTransactionReceipt>,\n) {\n const receipt = {\n ...transactionReceipt,\n blockNumber: transactionReceipt.blockNumber\n ? BigInt(transactionReceipt.blockNumber)\n : null,\n contractAddress: transactionReceipt.contractAddress\n ? transactionReceipt.contractAddress\n : null,\n cumulativeGasUsed: transactionReceipt.cumulativeGasUsed\n ? BigInt(transactionReceipt.cumulativeGasUsed)\n : null,\n effectiveGasPrice: transactionReceipt.effectiveGasPrice\n ? BigInt(transactionReceipt.effectiveGasPrice)\n : null,\n gasUsed: transactionReceipt.gasUsed\n ? BigInt(transactionReceipt.gasUsed)\n : null,\n logs: transactionReceipt.logs\n ? transactionReceipt.logs.map((log) => formatLog(log))\n : null,\n to: transactionReceipt.to ? transactionReceipt.to : null,\n transactionIndex: transactionReceipt.transactionIndex\n ? hexToNumber(transactionReceipt.transactionIndex)\n : null,\n status: transactionReceipt.status\n ? receiptStatuses[transactionReceipt.status]\n : null,\n type: transactionReceipt.type\n ? transactionType[\n transactionReceipt.type as keyof typeof transactionType\n ] || transactionReceipt.type\n : null,\n } as TransactionReceipt\n\n if (transactionReceipt.blobGasPrice)\n receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice)\n if (transactionReceipt.blobGasUsed)\n receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed)\n\n return receipt\n}\n\nexport type DefineTransactionReceiptErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionReceipt = /*#__PURE__*/ defineFormatter(\n 'transactionReceipt',\n formatTransactionReceipt,\n)\n","export const presignMessagePrefix = '\\x19Ethereum Signed Message:\\n'\n","import { presignMessagePrefix } from '../../constants/strings.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport { size } from '../data/size.js'\nimport {\n type BytesToHexErrorType,\n type StringToHexErrorType,\n bytesToHex,\n stringToHex,\n} from '../encoding/toHex.js'\n\nexport type ToPrefixedMessageErrorType =\n | ConcatErrorType\n | StringToHexErrorType\n | BytesToHexErrorType\n | ErrorType\n\nexport function toPrefixedMessage(message_: SignableMessage): Hex {\n const message = (() => {\n if (typeof message_ === 'string') return stringToHex(message_)\n if (typeof message_.raw === 'string') return message_.raw\n return bytesToHex(message_.raw)\n })()\n const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`)\n return concat([prefix, message])\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, SignableMessage } from '../../types/misc.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport { toPrefixedMessage } from './toPrefixedMessage.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashMessageReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashMessageErrorType = Keccak256ErrorType | ErrorType\n\nexport function hashMessage<to extends To = 'hex'>(\n message: SignableMessage,\n to_?: to | undefined,\n): HashMessageReturnType<to> {\n return keccak256(toPrefixedMessage(message), to_)\n}\n","export const erc6492MagicBytes =\n '0x6492649264926492649264926492649264926492649264926492649264926492' as const\n\nexport const zeroHash =\n '0x0000000000000000000000000000000000000000000000000000000000000000' as const\n","import { erc6492MagicBytes } from '../../constants/bytes.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type SliceHexErrorType, sliceHex } from '../data/slice.js'\n\nexport type IsErc6492SignatureParameters = Hex\nexport type IsErc6492SignatureReturnType = boolean\nexport type IsErc6492SignatureErrorType = SliceHexErrorType | ErrorType\n\n/** Whether or not the signature is an ERC-6492 formatted signature. */\nexport function isErc6492Signature(\n signature: IsErc6492SignatureParameters,\n): IsErc6492SignatureReturnType {\n return sliceHex(signature, -32) === erc6492MagicBytes\n}\n","import type { Address } from 'abitype'\nimport { erc6492MagicBytes } from '../../constants/bytes.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { encodeAbiParameters } from '../abi/encodeAbiParameters.js'\nimport { concatHex } from '../data/concat.js'\nimport { hexToBytes } from '../encoding/toBytes.js'\n\ntype To = 'bytes' | 'hex'\n\nexport type SerializeErc6492SignatureParameters<to extends To = 'hex'> = {\n /** The ERC-4337 Account Factory address to use for counterfactual verification. */\n address: Address\n /** Calldata to pass to deploy account (if not deployed) for counterfactual verification. */\n data: Hex\n /** The original signature. */\n signature: Hex\n to?: to | To | undefined\n}\n\nexport type SerializeErc6492SignatureReturnType<to extends To = 'hex'> =\n | (to extends 'hex' ? Hex : never)\n | (to extends 'bytes' ? ByteArray : never)\n\nexport type SerializeErc6492SignatureErrorType = ErrorType\n\n/**\n * @description Serializes a ERC-6492 flavoured signature into hex format.\n *\n * @param signature ERC-6492 signature in object format.\n * @returns ERC-6492 signature in hex format.\n *\n * @example\n * serializeSignature({ address: '0x...', data: '0x...', signature: '0x...' })\n * // '0x000000000000000000000000cafebabecafebabecafebabecafebabecafebabe000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000004deadbeef000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000041a461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b000000000000000000000000000000000000000000000000000000000000006492649264926492649264926492649264926492649264926492649264926492'\n */\nexport function serializeErc6492Signature<to extends To = 'hex'>(\n parameters: SerializeErc6492SignatureParameters<to>,\n): SerializeErc6492SignatureReturnType<to> {\n const { address, data, signature, to = 'hex' } = parameters\n const signature_ = concatHex([\n encodeAbiParameters(\n [{ type: 'address' }, { type: 'bytes' }, { type: 'bytes' }],\n [address, data, signature],\n ),\n erc6492MagicBytes,\n ])\n\n if (to === 'hex') return signature_ as SerializeErc6492SignatureReturnType<to>\n return hexToBytes(signature_) as SerializeErc6492SignatureReturnType<to>\n}\n","import { versionedHashVersionKzg } from '../../constants/kzg.js'\nimport { maxUint256 } from '../../constants/number.js'\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport { BaseError, type BaseErrorType } from '../../errors/base.js'\nimport {\n EmptyBlobError,\n type EmptyBlobErrorType,\n InvalidVersionedHashSizeError,\n type InvalidVersionedHashSizeErrorType,\n InvalidVersionedHashVersionError,\n type InvalidVersionedHashVersionErrorType,\n} from '../../errors/blob.js'\nimport {\n InvalidChainIdError,\n type InvalidChainIdErrorType,\n} from '../../errors/chain.js'\nimport {\n FeeCapTooHighError,\n type FeeCapTooHighErrorType,\n TipAboveFeeCapError,\n type TipAboveFeeCapErrorType,\n} from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableLegacy,\n} from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { size } from '../data/size.js'\nimport { slice } from '../data/slice.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nexport type AssertTransactionEIP7702ErrorType =\n | AssertTransactionEIP1559ErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | ErrorType\n\nexport function assertTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n) {\n const { authorizationList } = transaction\n if (authorizationList) {\n for (const authorization of authorizationList) {\n const { contractAddress, chainId } = authorization\n if (!isAddress(contractAddress))\n throw new InvalidAddressError({ address: contractAddress })\n if (chainId < 0) throw new InvalidChainIdError({ chainId })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP4844ErrorType =\n | AssertTransactionEIP1559ErrorType\n | EmptyBlobErrorType\n | InvalidVersionedHashSizeErrorType\n | InvalidVersionedHashVersionErrorType\n | ErrorType\n\nexport function assertTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n) {\n const { blobVersionedHashes } = transaction\n if (blobVersionedHashes) {\n if (blobVersionedHashes.length === 0) throw new EmptyBlobError()\n for (const hash of blobVersionedHashes) {\n const size_ = size(hash)\n const version = hexToNumber(slice(hash, 0, 1))\n if (size_ !== 32)\n throw new InvalidVersionedHashSizeError({ hash, size: size_ })\n if (version !== versionedHashVersionKzg)\n throw new InvalidVersionedHashVersionError({\n hash,\n version,\n })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP1559ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | TipAboveFeeCapErrorType\n | ErrorType\n\nexport function assertTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n) {\n const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxFeePerGas && maxFeePerGas > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas })\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n\nexport type AssertTransactionEIP2930ErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n\nexport type AssertTransactionLegacyErrorType =\n | BaseErrorType\n | IsAddressErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | FeeCapTooHighErrorType\n | ErrorType\n\nexport function assertTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n) {\n const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n transaction\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (typeof chainId !== 'undefined' && chainId <= 0)\n throw new InvalidChainIdError({ chainId })\n if (maxPriorityFeePerGas || maxFeePerGas)\n throw new BaseError(\n '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.',\n )\n if (gasPrice && gasPrice > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport { toHex } from '../../../utils/encoding/toHex.js'\nimport { toYParitySignatureArray } from '../../../utils/transaction/serializeTransaction.js'\nimport type {\n AuthorizationList,\n SerializedAuthorizationList,\n} from '../types/authorization.js'\n\nexport type SerializeAuthorizationListReturnType = SerializedAuthorizationList\n\nexport type SerializeAuthorizationListErrorType = ErrorType\n\n/*\n * Serializes an EIP-7702 authorization list.\n */\nexport function serializeAuthorizationList(\n authorizationList?: AuthorizationList<number, true> | undefined,\n): SerializeAuthorizationListReturnType {\n if (!authorizationList || authorizationList.length === 0) return []\n\n const serializedAuthorizationList = []\n for (const authorization of authorizationList) {\n const { contractAddress, chainId, nonce, ...signature } = authorization\n serializedAuthorizationList.push([\n chainId ? toHex(chainId) : '0x',\n contractAddress,\n nonce ? toHex(nonce) : '0x',\n ...toYParitySignatureArray({}, signature),\n ])\n }\n\n return serializedAuthorizationList as {} as SerializeAuthorizationListReturnType\n}\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport {\n InvalidStorageKeySizeError,\n type InvalidStorageKeySizeErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { AccessList } from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport type { RecursiveArray } from '../encoding/toRlp.js'\n\nexport type SerializeAccessListErrorType =\n | InvalidStorageKeySizeErrorType\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\n/*\n * Serialize an EIP-2930 access list\n * @remarks\n * Use to create a transaction serializer with support for EIP-2930 access lists\n *\n * @param accessList - Array of objects of address and arrays of Storage Keys\n * @throws InvalidAddressError, InvalidStorageKeySizeError\n * @returns Array of hex strings\n */\nexport function serializeAccessList(\n accessList?: AccessList | undefined,\n): RecursiveArray<Hex> {\n if (!accessList || accessList.length === 0) return []\n\n const serializedAccessList = []\n for (let i = 0; i < accessList.length; i++) {\n const { address, storageKeys } = accessList[i]\n\n for (let j = 0; j < storageKeys.length; j++) {\n if (storageKeys[j].length - 2 !== 64) {\n throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] })\n }\n }\n\n if (!isAddress(address, { strict: false })) {\n throw new InvalidAddressError({ address })\n }\n\n serializedAccessList.push([address, storageKeys])\n }\n return serializedAccessList\n}\n","import {\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ByteArray,\n Hex,\n Signature,\n SignatureLegacy,\n} from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedLegacy,\n TransactionType,\n} from '../../types/transaction.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from '../blob/blobsToCommitments.js'\nimport {\n blobsToProofs,\n type blobsToProofsErrorType,\n} from '../blob/blobsToProofs.js'\nimport {\n type CommitmentsToVersionedHashesErrorType,\n commitmentsToVersionedHashes,\n} from '../blob/commitmentsToVersionedHashes.js'\nimport {\n type ToBlobSidecarsErrorType,\n toBlobSidecars,\n} from '../blob/toBlobSidecars.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { trim } from '../data/trim.js'\nimport { type ToHexErrorType, bytesToHex, toHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\nimport {\n type SerializeAuthorizationListErrorType,\n serializeAuthorizationList,\n} from '../../experimental/eip7702/utils/serializeAuthorizationList.js'\nimport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionEIP4844ErrorType,\n type AssertTransactionEIP7702ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionEIP4844,\n assertTransactionEIP7702,\n assertTransactionLegacy,\n} from './assertTransaction.js'\nimport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './getTransactionType.js'\nimport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './serializeAccessList.js'\n\nexport type SerializedTransactionReturnType<\n transaction extends TransactionSerializable = TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType<transaction>,\n> = TransactionSerialized<_transactionType>\n\nexport type SerializeTransactionFn<\n transaction extends TransactionSerializableGeneric = TransactionSerializable,\n ///\n _transactionType extends TransactionType = never,\n> = typeof serializeTransaction<\n OneOf<TransactionSerializable | transaction>,\n _transactionType\n>\n\nexport type SerializeTransactionErrorType =\n | GetTransactionTypeErrorType\n | SerializeTransactionEIP1559ErrorType\n | SerializeTransactionEIP2930ErrorType\n | SerializeTransactionEIP4844ErrorType\n | SerializeTransactionEIP7702ErrorType\n | SerializeTransactionLegacyErrorType\n | ErrorType\n\nexport function serializeTransaction<\n const transaction extends TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType<transaction>,\n>(\n transaction: transaction,\n signature?: Signature | undefined,\n): SerializedTransactionReturnType<transaction, _transactionType> {\n const type = getTransactionType(transaction) as GetTransactionType\n\n if (type === 'eip1559')\n return serializeTransactionEIP1559(\n transaction as TransactionSerializableEIP1559,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n if (type === 'eip2930')\n return serializeTransactionEIP2930(\n transaction as TransactionSerializableEIP2930,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n if (type === 'eip4844')\n return serializeTransactionEIP4844(\n transaction as TransactionSerializableEIP4844,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n if (type === 'eip7702')\n return serializeTransactionEIP7702(\n transaction as TransactionSerializableEIP7702,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n return serializeTransactionLegacy(\n transaction as TransactionSerializableLegacy,\n signature as SignatureLegacy,\n ) as SerializedTransactionReturnType<transaction>\n}\n\ntype SerializeTransactionEIP7702ErrorType =\n | AssertTransactionEIP7702ErrorType\n | SerializeAuthorizationListErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n signature?: Signature | undefined,\n): TransactionSerializedEIP7702 {\n const {\n authorizationList,\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP7702(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n const serializedAuthorizationList =\n serializeAuthorizationList(authorizationList)\n\n return concatHex([\n '0x04',\n toRlp([\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n serializedAuthorizationList,\n ...toYParitySignatureArray(transaction, signature),\n ]),\n ]) as TransactionSerializedEIP7702\n}\n\ntype SerializeTransactionEIP4844ErrorType =\n | AssertTransactionEIP4844ErrorType\n | BlobsToCommitmentsErrorType\n | CommitmentsToVersionedHashesErrorType\n | blobsToProofsErrorType\n | ToBlobSidecarsErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n signature?: Signature | undefined,\n): TransactionSerializedEIP4844 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP4844(transaction)\n\n let blobVersionedHashes = transaction.blobVersionedHashes\n let sidecars = transaction.sidecars\n // If `blobs` are passed, we will need to compute the KZG commitments & proofs.\n if (\n transaction.blobs &&\n (typeof blobVersionedHashes === 'undefined' ||\n typeof sidecars === 'undefined')\n ) {\n const blobs = (\n typeof transaction.blobs[0] === 'string'\n ? transaction.blobs\n : (transaction.blobs as ByteArray[]).map((x) => bytesToHex(x))\n ) as Hex[]\n const kzg = transaction.kzg!\n const commitments = blobsToCommitments({\n blobs,\n kzg,\n })\n\n if (typeof blobVersionedHashes === 'undefined')\n blobVersionedHashes = commitmentsToVersionedHashes({\n commitments,\n })\n if (typeof sidecars === 'undefined') {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n sidecars = toBlobSidecars({ blobs, commitments, proofs })\n }\n }\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : '0x',\n blobVersionedHashes ?? [],\n ...toYParitySignatureArray(transaction, signature),\n ] as const\n\n const blobs: Hex[] = []\n const commitments: Hex[] = []\n const proofs: Hex[] = []\n if (sidecars)\n for (let i = 0; i < sidecars.length; i++) {\n const { blob, commitment, proof } = sidecars[i]\n blobs.push(blob)\n commitments.push(commitment)\n proofs.push(proof)\n }\n\n return concatHex([\n '0x03',\n sidecars\n ? // If sidecars are enabled, envelope turns into a \"wrapper\":\n toRlp([serializedTransaction, blobs, commitments, proofs])\n : // If sidecars are disabled, standard envelope is used:\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP4844\n}\n\ntype SerializeTransactionEIP1559ErrorType =\n | AssertTransactionEIP1559ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n signature?: Signature | undefined,\n): TransactionSerializedEIP1559 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP1559(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x02',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP1559\n}\n\ntype SerializeTransactionEIP2930ErrorType =\n | AssertTransactionEIP2930ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n signature?: Signature | undefined,\n): TransactionSerializedEIP2930 {\n const { chainId, gas, data, nonce, to, value, accessList, gasPrice } =\n transaction\n\n assertTransactionEIP2930(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n toHex(chainId),\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x01',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP2930\n}\n\ntype SerializeTransactionLegacyErrorType =\n | AssertTransactionLegacyErrorType\n | InvalidLegacyVErrorType\n | ToHexErrorType\n | ToRlpErrorType\n | ErrorType\n\nfunction serializeTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n signature?: SignatureLegacy | undefined,\n): TransactionSerializedLegacy {\n const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction\n\n assertTransactionLegacy(transaction)\n\n let serializedTransaction = [\n nonce ? toHex(nonce) : '0x',\n gasPrice ? toHex(gasPrice) : '0x',\n gas ? toHex(gas) : '0x',\n to ?? '0x',\n value ? toHex(value) : '0x',\n data ?? '0x',\n ]\n\n if (signature) {\n const v = (() => {\n // EIP-155 (inferred chainId)\n if (signature.v >= 35n) {\n const inferredChainId = (signature.v - 35n) / 2n\n if (inferredChainId > 0) return signature.v\n return 27n + (signature.v === 35n ? 0n : 1n)\n }\n\n // EIP-155 (explicit chainId)\n if (chainId > 0)\n return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n)\n\n // Pre-EIP-155 (no chainId)\n const v = 27n + (signature.v === 27n ? 0n : 1n)\n if (signature.v !== v) throw new InvalidLegacyVError({ v: signature.v })\n return v\n })()\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n serializedTransaction = [\n ...serializedTransaction,\n toHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ]\n } else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n toHex(chainId),\n '0x',\n '0x',\n ]\n }\n\n return toRlp(serializedTransaction) as TransactionSerializedLegacy\n}\n\nexport function toYParitySignatureArray(\n transaction: TransactionSerializableGeneric,\n signature_?: Signature | undefined,\n) {\n const signature = signature_ ?? transaction\n const { v, yParity } = signature\n\n if (typeof signature.r === 'undefined') return []\n if (typeof signature.s === 'undefined') return []\n if (typeof v === 'undefined' && typeof yParity === 'undefined') return []\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n const yParity_ = (() => {\n if (typeof yParity === 'number') return yParity ? toHex(1) : '0x'\n if (v === 0n) return '0x'\n if (v === 1n) return toHex(1)\n\n return v === 27n ? '0x' : toHex(1)\n })()\n\n return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s]\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Proof } from '../../types/proof.js'\nimport type { RpcProof } from '../../types/rpc.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { hexToNumber } from '../index.js'\n\nexport type FormatProofErrorType = ErrorType\n\nfunction formatStorageProof(storageProof: RpcProof['storageProof']) {\n return storageProof.map((proof) => ({\n ...proof,\n value: BigInt(proof.value),\n }))\n}\n\nexport function formatProof(proof: ExactPartial<RpcProof>) {\n return {\n ...proof,\n balance: proof.balance ? BigInt(proof.balance) : undefined,\n nonce: proof.nonce ? hexToNumber(proof.nonce) : undefined,\n storageProof: proof.storageProof\n ? formatStorageProof(proof.storageProof)\n : undefined,\n } as Proof\n}\n","import type { Address } from 'abitype'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Proof } from '../../types/proof.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatProofErrorType,\n formatProof,\n} from '../../utils/formatters/proof.js'\n\nexport type GetProofParameters = {\n /** Account address. */\n address: Address\n /** Array of storage-keys that should be proofed and included. */\n storageKeys: Hash[]\n} & (\n | {\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n)\n\nexport type GetProofReturnType = Proof\n\nexport type GetProofErrorType =\n | NumberToHexErrorType\n | FormatProofErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the account and storage values of the specified account including the Merkle-proof.\n *\n * - Docs: https://viem.sh/docs/actions/public/getProof\n * - JSON-RPC Methods:\n * - Calls [`eth_getProof`](https://eips.ethereum.org/EIPS/eip-1186)\n *\n * @param client - Client to use\n * @param parameters - {@link GetProofParameters}\n * @returns Proof data. {@link GetProofReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getProof } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await getProof(client, {\n * address: '0x...',\n * storageKeys: ['0x...'],\n * })\n */\nexport async function getProof<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n {\n address,\n blockNumber,\n blockTag: blockTag_,\n storageKeys,\n }: GetProofParameters,\n): Promise<GetProofReturnType> {\n const blockTag = blockTag_ ?? 'latest'\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n const proof = await client.request({\n method: 'eth_getProof',\n params: [address, storageKeys, blockNumberHex || blockTag],\n })\n\n return formatProof(proof)\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetStorageAtParameters = {\n address: Address\n slot: Hex\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetStorageAtReturnType = Hex | undefined\n\nexport type GetStorageAtErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the value from a storage slot at a given address.\n *\n * - Docs: https://viem.sh/docs/contract/getStorageAt\n * - JSON-RPC Methods: [`eth_getStorageAt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat)\n *\n * @param client - Client to use\n * @param parameters - {@link GetStorageAtParameters}\n * @returns The value of the storage slot. {@link GetStorageAtReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getStorageAt } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await getStorageAt(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * slot: toHex(0),\n * })\n */\nexport async function getStorageAt<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { address, blockNumber, blockTag = 'latest', slot }: GetStorageAtParameters,\n): Promise<GetStorageAtReturnType> {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n const data = await client.request({\n method: 'eth_getStorageAt',\n params: [address, slot, blockNumberHex || blockTag],\n })\n return data\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n TransactionNotFoundError,\n type TransactionNotFoundErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcTransaction } from '../../types/rpc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormattedTransaction,\n formatTransaction,\n} from '../../utils/formatters/transaction.js'\n\nexport type GetTransactionParameters<blockTag extends BlockTag = 'latest'> =\n | {\n /** The block hash */\n blockHash: Hash\n blockNumber?: undefined\n blockTag?: undefined\n hash?: undefined\n /** The index of the transaction on the block. */\n index: number\n }\n | {\n blockHash?: undefined\n /** The block number */\n blockNumber: bigint\n blockTag?: undefined\n hash?: undefined\n /** The index of the transaction on the block. */\n index: number\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /** The block tag. */\n blockTag: blockTag | BlockTag\n hash?: undefined\n /** The index of the transaction on the block. */\n index: number\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n blockTag?: undefined\n /** The hash of the transaction. */\n hash: Hash\n index?: number | undefined\n }\n\nexport type GetTransactionReturnType<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = 'latest',\n> = Prettify<FormattedTransaction<chain, blockTag>>\n\nexport type GetTransactionErrorType =\n | TransactionNotFoundErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionParameters}\n * @returns The transaction information. {@link GetTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransaction } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transaction = await getTransaction(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransaction<\n chain extends Chain | undefined,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client<Transport, chain>,\n {\n blockHash,\n blockNumber,\n blockTag: blockTag_,\n hash,\n index,\n }: GetTransactionParameters<blockTag>,\n): Promise<GetTransactionReturnType<chain, blockTag>> {\n const blockTag = blockTag_ || 'latest'\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let transaction: RpcTransaction | null = null\n if (hash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByHash',\n params: [hash],\n },\n { dedupe: true },\n )\n } else if (blockHash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockHashAndIndex',\n params: [blockHash, numberToHex(index)],\n },\n { dedupe: true },\n )\n } else if (blockNumberHex || blockTag) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockNumberAndIndex',\n params: [blockNumberHex || blockTag, numberToHex(index)],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n if (!transaction)\n throw new TransactionNotFoundError({\n blockHash,\n blockNumber,\n blockTag,\n hash,\n index,\n })\n\n const format =\n client.chain?.formatters?.transaction?.format || formatTransaction\n return format(transaction)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { FormattedTransactionReceipt } from '../../utils/formatters/transactionReceipt.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport {\n type GetBlockNumberErrorType,\n getBlockNumber,\n} from './getBlockNumber.js'\nimport {\n type GetTransactionErrorType,\n getTransaction,\n} from './getTransaction.js'\n\nexport type GetTransactionConfirmationsParameters<\n chain extends Chain | undefined = Chain,\n> =\n | {\n /** The transaction hash. */\n hash: Hash\n transactionReceipt?: undefined\n }\n | {\n hash?: undefined\n /** The transaction receipt. */\n transactionReceipt: FormattedTransactionReceipt<chain>\n }\n\nexport type GetTransactionConfirmationsReturnType = bigint\n\nexport type GetTransactionConfirmationsErrorType =\n | GetBlockNumberErrorType\n | GetTransactionErrorType\n | ErrorType\n\n/**\n * Returns the number of blocks passed (confirmations) since the transaction was processed on a block.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionConfirmations`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionConfirmationsParameters}\n * @returns The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. {@link GetTransactionConfirmationsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionConfirmations } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const confirmations = await getTransactionConfirmations(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionConfirmations<\n chain extends Chain | undefined,\n>(\n client: Client<Transport, chain>,\n { hash, transactionReceipt }: GetTransactionConfirmationsParameters<chain>,\n): Promise<GetTransactionConfirmationsReturnType> {\n const [blockNumber, transaction] = await Promise.all([\n getAction(client, getBlockNumber, 'getBlockNumber')({}),\n hash\n ? getAction(client, getTransaction, 'getTransaction')({ hash })\n : undefined,\n ])\n const transactionBlockNumber =\n transactionReceipt?.blockNumber || transaction?.blockNumber\n if (!transactionBlockNumber) return 0n\n return blockNumber - transactionBlockNumber! + 1n\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n TransactionReceiptNotFoundError,\n type TransactionReceiptNotFoundErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormattedTransactionReceipt,\n formatTransactionReceipt,\n} from '../../utils/formatters/transactionReceipt.js'\n\nexport type GetTransactionReceiptParameters = {\n /** The hash of the transaction. */\n hash: Hash\n}\n\nexport type GetTransactionReceiptReturnType<\n chain extends Chain | undefined = undefined,\n> = FormattedTransactionReceipt<chain>\n\nexport type GetTransactionReceiptErrorType =\n | RequestErrorType\n | TransactionReceiptNotFoundErrorType\n | ErrorType\n\n/**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactionreceipt)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionReceiptParameters}\n * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionReceipt } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await getTransactionReceipt(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionReceipt<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { hash }: GetTransactionReceiptParameters,\n) {\n const receipt = await client.request(\n {\n method: 'eth_getTransactionReceipt',\n params: [hash],\n },\n { dedupe: true },\n )\n\n if (!receipt) throw new TransactionReceiptNotFoundError({ hash })\n\n const format =\n client.chain?.formatters?.transactionReceipt?.format ||\n formatTransactionReceipt\n return format(receipt) as GetTransactionReceiptReturnType<chain>\n}\n","import type { AbiStateMutability, Address, Narrow } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ContractFunctionParameters } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n MulticallContracts,\n MulticallResults,\n} from '../../types/multicall.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { CallParameters } from './call.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type MulticallParameters<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n optional?: boolean\n properties?: Record<string, any>\n } = {},\n> = Pick<CallParameters, 'blockNumber' | 'blockTag' | 'stateOverride'> & {\n allowFailure?: allowFailure | boolean | undefined\n batchSize?: number | undefined\n contracts: MulticallContracts<\n Narrow<contracts>,\n { mutability: AbiStateMutability } & options\n >\n multicallAddress?: Address | undefined\n}\n\nexport type MulticallReturnType<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n error?: Error\n } = { error: Error },\n> = MulticallResults<\n Narrow<contracts>,\n allowFailure,\n { mutability: AbiStateMutability } & options\n>\n\nexport type MulticallErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | GetContractErrorReturnType<\n EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n >\n | ErrorType\n\n/**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall\n *\n * @param client - Client to use\n * @param parameters - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { multicall } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const abi = parseAbi([\n * 'function balanceOf(address) view returns (uint256)',\n * 'function totalSupply() view returns (uint256)',\n * ])\n * const results = await multicall(client, {\n * contracts: [\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * },\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'totalSupply',\n * },\n * ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\nexport async function multicall<\n const contracts extends readonly unknown[],\n chain extends Chain | undefined,\n allowFailure extends boolean = true,\n>(\n client: Client<Transport, chain>,\n parameters: MulticallParameters<contracts, allowFailure>,\n): Promise<MulticallReturnType<contracts, allowFailure>> {\n const {\n allowFailure = true,\n batchSize: batchSize_,\n blockNumber,\n blockTag,\n multicallAddress: multicallAddress_,\n stateOverride,\n } = parameters\n const contracts = parameters.contracts as ContractFunctionParameters[]\n\n const batchSize =\n batchSize_ ??\n ((typeof client.batch?.multicall === 'object' &&\n client.batch.multicall.batchSize) ||\n 1_024)\n\n let multicallAddress = multicallAddress_\n if (!multicallAddress) {\n if (!client.chain)\n throw new Error(\n 'client chain not configured. multicallAddress is required.',\n )\n\n multicallAddress = getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n })\n }\n\n type Aggregate3Calls = {\n allowFailure: boolean\n callData: Hex\n target: Address\n }[]\n\n const chunkedCalls: Aggregate3Calls[] = [[]]\n let currentChunk = 0\n let currentChunkSize = 0\n for (let i = 0; i < contracts.length; i++) {\n const { abi, address, args, functionName } = contracts[i]\n try {\n const callData = encodeFunctionData({ abi, args, functionName })\n\n currentChunkSize += (callData.length - 2) / 2\n // Check to see if we need to create a new chunk.\n if (\n // Check if batching is enabled.\n batchSize > 0 &&\n // Check if the current size of the batch exceeds the size limit.\n currentChunkSize > batchSize &&\n // Check if the current chunk is not already empty.\n chunkedCalls[currentChunk].length > 0\n ) {\n currentChunk++\n currentChunkSize = (callData.length - 2) / 2\n chunkedCalls[currentChunk] = []\n }\n\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData,\n target: address,\n },\n ]\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n })\n if (!allowFailure) throw error\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData: '0x' as Hex,\n target: address,\n },\n ]\n }\n }\n\n const aggregate3Results = await Promise.allSettled(\n chunkedCalls.map((calls) =>\n getAction(\n client,\n readContract,\n 'readContract',\n )({\n abi: multicall3Abi,\n address: multicallAddress!,\n args: [calls],\n blockNumber,\n blockTag,\n functionName: 'aggregate3',\n stateOverride,\n }),\n ),\n )\n\n const results = []\n for (let i = 0; i < aggregate3Results.length; i++) {\n const result = aggregate3Results[i]\n\n // If an error occurred in a `readContract` invocation (ie. network error),\n // then append the failure reason to each contract result.\n if (result.status === 'rejected') {\n if (!allowFailure) throw result.reason\n for (let j = 0; j < chunkedCalls[i].length; j++) {\n results.push({\n status: 'failure',\n error: result.reason,\n result: undefined,\n })\n }\n continue\n }\n\n // If the `readContract` call was successful, then decode the results.\n const aggregate3Result = result.value\n for (let j = 0; j < aggregate3Result.length; j++) {\n // Extract the response from `readContract`\n const { returnData, success } = aggregate3Result[j]\n\n // Extract the request call data from the original call.\n const { callData } = chunkedCalls[i][j]\n\n // Extract the contract config for this call from the `contracts` argument\n // for decoding.\n const { abi, address, functionName, args } = contracts[\n results.length\n ] as ContractFunctionParameters\n\n try {\n if (callData === '0x') throw new AbiDecodingZeroDataError()\n if (!success) throw new RawContractError({ data: returnData })\n const result = decodeFunctionResult({\n abi,\n args,\n data: returnData,\n functionName,\n })\n results.push(allowFailure ? { result, status: 'success' } : result)\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n })\n if (!allowFailure) throw error\n results.push({ error, result: undefined, status: 'failure' })\n }\n }\n }\n\n if (results.length !== contracts.length)\n throw new BaseError('multicall results mismatch')\n return results as MulticallReturnType<contracts, allowFailure>\n}\n","import { equalBytes } from '@noble/curves/abstract/utils'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Json from './Json.js'\nimport * as internal_bytes from './internal/bytes.js'\nimport * as internal from './internal/hex.js'\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) =>\n i.toString(16).padStart(2, '0'),\n)\n\n/** Root type for a Hex string. */\nexport type Hex = `0x${string}`\n\n/**\n * Asserts if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('abc')\n * // @error: InvalidHexValueTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid hex type.\n * // @error: Hex types must be represented as `\"0x\\${string}\"`.\n * ```\n *\n * @param value - The value to assert.\n * @param options - Options.\n */\nexport function assert(\n value: unknown,\n options: assert.Options = {},\n): asserts value is Hex {\n const { strict = false } = options\n if (!value) throw new InvalidHexTypeError(value)\n if (typeof value !== 'string') throw new InvalidHexTypeError(value)\n if (strict) {\n if (!/^0x[0-9a-fA-F]*$/.test(value)) throw new InvalidHexValueError(value)\n }\n if (!value.startsWith('0x')) throw new InvalidHexValueError(value)\n}\n\nexport declare namespace assert {\n type Options = {\n /** Checks if the {@link ox#Hex.Hex} value contains invalid hexadecimal characters. @default false */\n strict?: boolean | undefined\n }\n\n type ErrorType =\n | InvalidHexTypeError\n | InvalidHexValueError\n | Errors.GlobalErrorType\n}\n\n/**\n * Concatenates two or more {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.concat('0x123', '0x456')\n * // @log: '0x123456'\n * ```\n *\n * @param values - The {@link ox#Hex.Hex} values to concatenate.\n * @returns The concatenated {@link ox#Hex.Hex} value.\n */\nexport function concat(...values: readonly Hex[]): Hex {\n return `0x${(values as Hex[]).reduce((acc, x) => acc + x.replace('0x', ''), '')}`\n}\n\nexport declare namespace concat {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a {@link ox#Hex.Hex} value from a hex string or {@link ox#Bytes.Bytes} value.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Hex.fromBoolean`\n *\n * - `Hex.fromString`\n *\n * - `Hex.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.from('0x48656c6c6f20576f726c6421')\n * // @log: '0x48656c6c6f20576f726c6421'\n *\n * Hex.from(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function from(value: Hex | Bytes.Bytes | readonly number[]): Hex {\n if (value instanceof Uint8Array) return fromBytes(value)\n if (Array.isArray(value)) return fromBytes(new Uint8Array(value))\n return value as never\n}\n\nexport declare namespace from {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType = fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a boolean into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromBoolean(true)\n * // @log: '0x1'\n *\n * Hex.fromBoolean(false)\n * // @log: '0x0'\n *\n * Hex.fromBoolean(true, { size: 32 })\n * // @log: '0x0000000000000000000000000000000000000000000000000000000000000001'\n * ```\n *\n * @param value - The boolean value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBoolean(\n value: boolean,\n options: fromBoolean.Options = {},\n): Hex {\n const hex: Hex = `0x${Number(value)}`\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size)\n return padLeft(hex, options.size)\n }\n return hex\n}\n\nexport declare namespace fromBoolean {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.fromBytes(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBytes(\n value: Bytes.Bytes,\n options: fromBytes.Options = {},\n): Hex {\n let string = ''\n for (let i = 0; i < value.length; i++) string += hexes[value[i]!]\n const hex = `0x${string}` as const\n\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size)\n return padRight(hex, options.size)\n }\n return hex\n}\n\nexport declare namespace fromBytes {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a number or bigint into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420)\n * // @log: '0x1a4'\n *\n * Hex.fromNumber(420, { size: 32 })\n * // @log: '0x00000000000000000000000000000000000000000000000000000000000001a4'\n * ```\n *\n * @param value - The number or bigint value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromNumber(\n value: number | bigint,\n options: fromNumber.Options = {},\n): Hex {\n const { signed, size } = options\n\n const value_ = BigInt(value)\n\n let maxValue: bigint | number | undefined\n if (size) {\n if (signed) maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n\n else maxValue = 2n ** (BigInt(size) * 8n) - 1n\n } else if (typeof value === 'number') {\n maxValue = BigInt(Number.MAX_SAFE_INTEGER)\n }\n\n const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0\n\n if ((maxValue && value_ > maxValue) || value_ < minValue) {\n const suffix = typeof value === 'bigint' ? 'n' : ''\n throw new IntegerOutOfRangeError({\n max: maxValue ? `${maxValue}${suffix}` : undefined,\n min: `${minValue}${suffix}`,\n signed,\n size,\n value: `${value}${suffix}`,\n })\n }\n\n const stringValue = (\n signed && value_ < 0 ? (1n << BigInt(size * 8)) + BigInt(value_) : value_\n ).toString(16)\n\n const hex = `0x${stringValue}` as Hex\n if (size) return padLeft(hex, size) as Hex\n return hex\n}\n\nexport declare namespace fromNumber {\n type Options =\n | {\n /** Whether or not the number of a signed representation. */\n signed?: boolean | undefined\n /** The size (in bytes) of the output hex value. */\n size: number\n }\n | {\n signed?: undefined\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | IntegerOutOfRangeError\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a string into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n * Hex.fromString('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * Hex.fromString('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n * ```\n *\n * @param value - The string value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromString(\n value: string,\n options: fromString.Options = {},\n): Hex {\n return fromBytes(encoder.encode(value), options)\n}\n\nexport declare namespace fromString {\n type Options = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\n type ErrorType = fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Hex.Hex} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.isEqual('0xdeadbeef', '0xdeadbeef')\n * // @log: true\n *\n * Hex.isEqual('0xda', '0xba')\n * // @log: false\n * ```\n *\n * @param hexA - The first {@link ox#Hex.Hex} value.\n * @param hexB - The second {@link ox#Hex.Hex} value.\n * @returns `true` if the two {@link ox#Hex.Hex} values are equal, `false` otherwise.\n */\nexport function isEqual(hexA: Hex, hexB: Hex) {\n return equalBytes(Bytes.fromHex(hexA), Bytes.fromHex(hexB))\n}\n\nexport declare namespace isEqual {\n type ErrorType = Bytes.fromHex.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Hex.Hex} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1234', 4)\n * // @log: '0x00001234'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padLeft(\n value: Hex,\n size?: number | undefined,\n): padLeft.ReturnType {\n return internal.pad(value, { dir: 'left', size })\n}\n\nexport declare namespace padLeft {\n type ReturnType = Hex\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Hex.Hex} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts\n * import { Hex } from 'ox'\n *\n * Hex.padRight('0x1234', 4)\n * // @log: '0x12340000'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padRight(\n value: Hex,\n size?: number | undefined,\n): padRight.ReturnType {\n return internal.pad(value, { dir: 'right', size })\n}\n\nexport declare namespace padRight {\n type ReturnType = Hex\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Generates a random {@link ox#Hex.Hex} value of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const hex = Hex.random(32)\n * // @log: '0x...'\n * ```\n *\n * @returns Random {@link ox#Hex.Hex} value.\n */\nexport function random(length: number): Hex {\n return fromBytes(Bytes.random(length))\n}\n\nexport declare namespace random {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 1, 4)\n * // @log: '0x234567'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to slice.\n * @param start - The start offset (in bytes).\n * @param end - The end offset (in bytes).\n * @param options - Options.\n * @returns The sliced {@link ox#Hex.Hex} value.\n */\nexport function slice(\n value: Hex,\n start?: number | undefined,\n end?: number | undefined,\n options: slice.Options = {},\n): Hex {\n const { strict } = options\n internal.assertStartOffset(value, start)\n const value_ = `0x${value\n .replace('0x', '')\n .slice((start ?? 0) * 2, (end ?? value.length) * 2)}` as const\n if (strict) internal.assertEndOffset(value_, start, end)\n return value_\n}\n\nexport declare namespace slice {\n type Options = {\n /** Asserts that the sliced value is the same size as the given start/end offsets. */\n strict?: boolean | undefined\n }\n\n type ErrorType =\n | internal.assertStartOffset.ErrorType\n | internal.assertEndOffset.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Retrieves the size of a {@link ox#Hex.Hex} value (in bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.size('0xdeadbeef')\n * // @log: 4\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to get the size of.\n * @returns The size of the {@link ox#Hex.Hex} value (in bytes).\n */\nexport function size(value: Hex): number {\n return Math.ceil((value.length - 2) / 2)\n}\n\nexport declare namespace size {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Trims leading zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimLeft('0x00000000deadbeef')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimLeft(value: Hex): trimLeft.ReturnType {\n return internal.trim(value, { dir: 'left' })\n}\n\nexport declare namespace trimLeft {\n type ReturnType = Hex\n\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Trims trailing zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimRight('0xdeadbeef00000000')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimRight(value: Hex): trimRight.ReturnType {\n return internal.trim(value, { dir: 'right' })\n}\n\nexport declare namespace trimRight {\n type ReturnType = Hex\n\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a BigInt.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBigInt('0x1a4')\n * // @log: 420n\n *\n * Hex.toBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420n\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded BigInt.\n */\nexport function toBigInt(hex: Hex, options: toBigInt.Options = {}): bigint {\n const { signed } = options\n\n if (options.size) internal.assertSize(hex, options.size)\n\n const value = BigInt(hex)\n if (!signed) return value\n\n const size = (hex.length - 2) / 2\n\n const max_unsigned = (1n << (BigInt(size) * 8n)) - 1n\n const max_signed = max_unsigned >> 1n\n\n if (value <= max_signed) return value\n return value - max_unsigned - 1n\n}\n\nexport declare namespace toBigInt {\n type Options = {\n /** Whether or not the number of a signed representation. */\n signed?: boolean | undefined\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType = internal.assertSize.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0x01')\n * // @log: true\n *\n * Hex.toBoolean('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // @log: true\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded boolean.\n */\nexport function toBoolean(hex: Hex, options: toBoolean.Options = {}): boolean {\n if (options.size) internal.assertSize(hex, options.size)\n const hex_ = trimLeft(hex)\n if (hex_ === '0x') return false\n if (hex_ === '0x1') return true\n throw new InvalidHexBooleanError(hex)\n}\n\nexport declare namespace toBoolean {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | trimLeft.ErrorType\n | InvalidHexBooleanError\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const data = Hex.toBytes('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded {@link ox#Bytes.Bytes}.\n */\nexport function toBytes(hex: Hex, options: toBytes.Options = {}): Bytes.Bytes {\n return Bytes.fromHex(hex, options)\n}\n\nexport declare namespace toBytes {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType = Bytes.fromHex.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a number.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toNumber('0x1a4')\n * // @log: 420\n *\n * Hex.toNumber('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded number.\n */\nexport function toNumber(hex: Hex, options: toNumber.Options = {}): number {\n const { signed, size } = options\n if (!signed && !size) return Number(hex)\n return Number(toBigInt(hex, options))\n}\n\nexport declare namespace toNumber {\n type Options = toBigInt.Options\n\n type ErrorType = toBigInt.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Hex.Hex} value into a string.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toString('0x48656c6c6f20576f726c6421')\n * // @log: 'Hello world!'\n *\n * Hex.toString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // @log: 'Hello world'\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded string.\n */\nexport function toString(hex: Hex, options: toString.Options = {}): string {\n const { size } = options\n\n let bytes = Bytes.fromHex(hex)\n if (size) {\n internal_bytes.assertSize(bytes, size)\n bytes = Bytes.trimRight(bytes)\n }\n return new TextDecoder().decode(bytes)\n}\n\nexport declare namespace toString {\n type Options = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal_bytes.assertSize.ErrorType\n | Bytes.fromHex.ErrorType\n | Bytes.trimRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.validate('0xdeadbeef')\n * // @log: true\n *\n * Hex.validate(Bytes.from([1, 2, 3]))\n * // @log: false\n * ```\n *\n * @param value - The value to check.\n * @param options - Options.\n * @returns `true` if the value is a {@link ox#Hex.Hex}, `false` otherwise.\n */\nexport function validate(\n value: unknown,\n options: validate.Options = {},\n): value is Hex {\n const { strict = false } = options\n try {\n assert(value, { strict })\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Checks if the {@link ox#Hex.Hex} value contains invalid hexadecimal characters. @default false */\n strict?: boolean | undefined\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when the provided integer is out of range, and cannot be represented as a hex value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420182738912731283712937129)\n * // @error: Hex.IntegerOutOfRangeError: Number \\`4.2018273891273126e+26\\` is not in safe unsigned integer range (`0` to `9007199254740991`)\n * ```\n */\nexport class IntegerOutOfRangeError extends Errors.BaseError {\n override readonly name = 'Hex.IntegerOutOfRangeError'\n\n constructor({\n max,\n min,\n signed,\n size,\n value,\n }: {\n max?: string | undefined\n min: string\n signed?: boolean | undefined\n size?: number | undefined\n value: string\n }) {\n super(\n `Number \\`${value}\\` is not in safe${\n size ? ` ${size * 8}-bit` : ''\n }${signed ? ' signed' : ' unsigned'} integer range ${max ? `(\\`${min}\\` to \\`${max}\\`)` : `(above \\`${min}\\`)`}`,\n )\n }\n}\n\n/**\n * Thrown when the provided hex value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0xa')\n * // @error: Hex.InvalidHexBooleanError: Hex value `\"0xa\"` is not a valid boolean.\n * // @error: The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).\n * ```\n */\nexport class InvalidHexBooleanError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexBooleanError'\n\n constructor(hex: Hex) {\n super(`Hex value \\`\"${hex}\"\\` is not a valid boolean.`, {\n metaMessages: [\n 'The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).',\n ],\n })\n }\n}\n\n/**\n * Thrown when the provided value is not a valid hex type.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert(1)\n * // @error: Hex.InvalidHexTypeError: Value `1` of type `number` is an invalid hex type.\n * ```\n */\nexport class InvalidHexTypeError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexTypeError'\n\n constructor(value: unknown) {\n super(\n `Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid hex type.`,\n {\n metaMessages: ['Hex types must be represented as `\"0x${string}\"`.'],\n },\n )\n }\n}\n\n/**\n * Thrown when the provided hex value is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('0x0123456789abcdefg')\n * // @error: Hex.InvalidHexValueError: Value `0x0123456789abcdefg` is an invalid hex value.\n * // @error: Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).\n * ```\n */\nexport class InvalidHexValueError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidHexValueError'\n\n constructor(value: unknown) {\n super(`Value \\`${value}\\` is an invalid hex value.`, {\n metaMessages: [\n 'Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).',\n ],\n })\n }\n}\n\n/**\n * Thrown when the provided hex value is an odd length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromHex('0xabcde')\n * // @error: Hex.InvalidLengthError: Hex value `\"0xabcde\"` is an odd length (5 nibbles).\n * ```\n */\nexport class InvalidLengthError extends Errors.BaseError {\n override readonly name = 'Hex.InvalidLengthError'\n\n constructor(value: Hex) {\n super(\n `Hex value \\`\"${value}\"\\` is an odd length (${value.length - 2} nibbles).`,\n {\n metaMessages: ['It must be an even length.'],\n },\n )\n }\n}\n\n/**\n * Thrown when the size of the value exceeds the expected max size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromString('Hello World!', { size: 8 })\n * // @error: Hex.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n override readonly name = 'Hex.SizeOverflowError'\n\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`,\n )\n }\n}\n\n/**\n * Thrown when the slice offset exceeds the bounds of the value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 6)\n * // @error: Hex.SliceOffsetOutOfBoundsError: Slice starting at offset `6` is out-of-bounds (size: `5`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Hex.SliceOffsetOutOfBoundsError'\n\n constructor({\n offset,\n position,\n size,\n }: { offset: number; position: 'start' | 'end'; size: number }) {\n super(\n `Slice ${\n position === 'start' ? 'starting' : 'ending'\n } at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`,\n )\n }\n}\n\n/**\n * Thrown when the size of the value exceeds the pad size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1a4e12a45a21323123aaa87a897a897a898a6567a578a867a98778a667a85a875a87a6a787a65a675a6a9', 32)\n * // @error: Hex.SizeExceedsPaddingSizeError: Hex size (`43`) exceeds padding size (`32`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n override readonly name = 'Hex.SizeExceedsPaddingSizeError'\n\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'Hex' | 'Bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`,\n )\n }\n}\n","import { equalBytes } from '@noble/curves/abstract/utils'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Json from './Json.js'\nimport * as internal from './internal/bytes.js'\nimport * as internal_hex from './internal/hex.js'\n\nconst decoder = /*#__PURE__*/ new TextDecoder()\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\n/** Root type for a Bytes array. */\nexport type Bytes = Uint8Array\n\n/**\n * Asserts if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.assert('abc')\n * // @error: Bytes.InvalidBytesTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid Bytes value.\n * // @error: Bytes values must be of type `Uint8Array`.\n * ```\n *\n * @param value - Value to assert.\n */\nexport function assert(value: unknown): asserts value is Bytes {\n if (value instanceof Uint8Array) return\n if (!value) throw new InvalidBytesTypeError(value)\n if (typeof value !== 'object') throw new InvalidBytesTypeError(value)\n if (!('BYTES_PER_ELEMENT' in value)) throw new InvalidBytesTypeError(value)\n if (value.BYTES_PER_ELEMENT !== 1 || value.constructor.name !== 'Uint8Array')\n throw new InvalidBytesTypeError(value)\n}\n\nexport declare namespace assert {\n type ErrorType = InvalidBytesTypeError | Errors.GlobalErrorType\n}\n\n/**\n * Concatenates two or more {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.concat(\n * Bytes.from([1]),\n * Bytes.from([69]),\n * Bytes.from([420, 69]),\n * )\n * // @log: Uint8Array [ 1, 69, 420, 69 ]\n * ```\n *\n * @param values - Values to concatenate.\n * @returns Concatenated {@link ox#Bytes.Bytes}.\n */\nexport function concat(...values: readonly Bytes[]): Bytes {\n let length = 0\n for (const arr of values) {\n length += arr.length\n }\n const result = new Uint8Array(length)\n for (let i = 0, index = 0; i < values.length; i++) {\n const arr = values[i]\n result.set(arr!, index)\n index += arr!.length\n }\n return result\n}\n\nexport declare namespace concat {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a {@link ox#Bytes.Bytes} value from a `Uint8Array`, a hex string, or an array of unsigned 8-bit integers.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Bytes.fromBoolean`\n *\n * - `Bytes.fromString`\n *\n * - `Bytes.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.from([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n *\n * const data = Bytes.from('0xdeadbeef')\n * // @log: Uint8Array([222, 173, 190, 239])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function from(value: Hex.Hex | Bytes | readonly number[]): Bytes {\n if (value instanceof Uint8Array) return value\n if (typeof value === 'string') return fromHex(value)\n return fromArray(value)\n}\n\nexport declare namespace from {\n type ErrorType =\n | fromHex.ErrorType\n | fromArray.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts an array of unsigned 8-bit integers into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromArray([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function fromArray(value: readonly number[] | Uint8Array): Bytes {\n return value instanceof Uint8Array ? value : new Uint8Array(value)\n}\n\nexport declare namespace fromArray {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Encodes a boolean value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true)\n * // @log: Uint8Array([1])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true, { size: 32 })\n * // @log: Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n * ```\n *\n * @param value - Boolean value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromBoolean(value: boolean, options: fromBoolean.Options = {}) {\n const { size } = options\n const bytes = new Uint8Array(1)\n bytes[0] = Number(value)\n if (typeof size === 'number') {\n internal.assertSize(bytes, size)\n return padLeft(bytes, size)\n }\n return bytes\n}\n\nexport declare namespace fromBoolean {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Hex.Hex} value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421', { size: 32 })\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n * ```\n *\n * @param value - {@link ox#Hex.Hex} value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromHex(value: Hex.Hex, options: fromHex.Options = {}): Bytes {\n const { size } = options\n\n let hex = value\n if (size) {\n internal_hex.assertSize(value, size)\n hex = Hex.padRight(value, size)\n }\n\n let hexString = hex.slice(2) as string\n if (hexString.length % 2) hexString = `0${hexString}`\n\n const length = hexString.length / 2\n const bytes = new Uint8Array(length)\n for (let index = 0, j = 0; index < length; index++) {\n const nibbleLeft = internal.charCodeToBase16(hexString.charCodeAt(j++))\n const nibbleRight = internal.charCodeToBase16(hexString.charCodeAt(j++))\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new Errors.BaseError(\n `Invalid byte sequence (\"${hexString[j - 2]}${hexString[j - 1]}\" in \"${hexString}\").`,\n )\n }\n bytes[index] = nibbleLeft * 16 + nibbleRight\n }\n return bytes\n}\n\nexport declare namespace fromHex {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal_hex.assertSize.ErrorType\n | Hex.padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a number value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420)\n * // @log: Uint8Array([1, 164])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420, { size: 4 })\n * // @log: Uint8Array([0, 0, 1, 164])\n * ```\n *\n * @param value - Number value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromNumber(\n value: bigint | number,\n options?: fromNumber.Options | undefined,\n) {\n const hex = Hex.fromNumber(value, options)\n return fromHex(hex)\n}\n\nexport declare namespace fromNumber {\n export type Options = Hex.fromNumber.Options\n\n export type ErrorType =\n | Hex.fromNumber.ErrorType\n | fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a string into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!', { size: 32 })\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n * ```\n *\n * @param value - String to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromString(\n value: string,\n options: fromString.Options = {},\n): Bytes {\n const { size } = options\n\n const bytes = encoder.encode(value)\n if (typeof size === 'number') {\n internal.assertSize(bytes, size)\n return padRight(bytes, size)\n }\n return bytes\n}\n\nexport declare namespace fromString {\n type Options = {\n /** Size of the output bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | padRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Bytes.Bytes} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([1]))\n * // @log: true\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([2]))\n * // @log: false\n * ```\n *\n * @param bytesA - First {@link ox#Bytes.Bytes} value.\n * @param bytesB - Second {@link ox#Bytes.Bytes} value.\n * @returns `true` if the two values are equal, otherwise `false`.\n */\nexport function isEqual(bytesA: Bytes, bytesB: Bytes) {\n return equalBytes(bytesA, bytesB)\n}\n\nexport declare namespace isEqual {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.from([1]), 4)\n * // @log: Uint8Array([0, 0, 0, 1])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padLeft(\n value: Bytes,\n size?: number | undefined,\n): padLeft.ReturnType {\n return internal.pad(value, { dir: 'left', size })\n}\n\nexport declare namespace padLeft {\n type ReturnType = internal.pad.ReturnType\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padRight(Bytes.from([1]), 4)\n * // @log: Uint8Array([1, 0, 0, 0])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padRight(\n value: Bytes,\n size?: number | undefined,\n): padRight.ReturnType {\n return internal.pad(value, { dir: 'right', size })\n}\n\nexport declare namespace padRight {\n type ReturnType = internal.pad.ReturnType\n type ErrorType = internal.pad.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Generates random {@link ox#Bytes.Bytes} of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.random(32)\n * // @log: Uint8Array([... x32])\n * ```\n *\n * @param length - Length of the random {@link ox#Bytes.Bytes} to generate.\n * @returns Random {@link ox#Bytes.Bytes} of the specified length.\n */\nexport function random(length: number): Bytes {\n return crypto.getRandomValues(new Uint8Array(length))\n}\n\nexport declare namespace random {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Retrieves the size of a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.size(Bytes.from([1, 2, 3, 4]))\n * // @log: 4\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Size of the {@link ox#Bytes.Bytes} value.\n */\nexport function size(value: Bytes): number {\n return value.length\n}\n\nexport declare namespace size {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(\n * Bytes.from([1, 2, 3, 4, 5, 6, 7, 8, 9]),\n * 1,\n * 4,\n * )\n * // @log: Uint8Array([2, 3, 4])\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value.\n * @param start - Start offset.\n * @param end - End offset.\n * @param options - Slice options.\n * @returns Sliced {@link ox#Bytes.Bytes} value.\n */\nexport function slice(\n value: Bytes,\n start?: number | undefined,\n end?: number | undefined,\n options: slice.Options = {},\n): Bytes {\n const { strict } = options\n internal.assertStartOffset(value, start)\n const value_ = value.slice(start, end)\n if (strict) internal.assertEndOffset(value_, start, end)\n return value_\n}\n\nexport declare namespace slice {\n type Options = {\n /** Asserts that the sliced value is the same size as the given start/end offsets. */\n strict?: boolean | undefined\n }\n\n export type ErrorType =\n | internal.assertStartOffset.ErrorType\n | internal.assertEndOffset.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a bigint.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBigInt(Bytes.from([1, 164]))\n * // @log: 420n\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded bigint.\n */\nexport function toBigInt(bytes: Bytes, options: toBigInt.Options = {}): bigint {\n const { size } = options\n if (typeof size !== 'undefined') internal.assertSize(bytes, size)\n const hex = Hex.fromBytes(bytes, options)\n return Hex.toBigInt(hex, options)\n}\n\nexport declare namespace toBigInt {\n type Options = {\n /** Whether or not the number of a signed representation. */\n signed?: boolean | undefined\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Hex.toBigInt.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a boolean.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([1]))\n * // @log: true\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded boolean.\n */\nexport function toBoolean(\n bytes: Bytes,\n options: toBoolean.Options = {},\n): boolean {\n const { size } = options\n let bytes_ = bytes\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size)\n bytes_ = trimLeft(bytes_)\n }\n if (bytes_.length > 1 || bytes_[0]! > 1)\n throw new InvalidBytesBooleanError(bytes_)\n return Boolean(bytes_[0])\n}\n\nexport declare namespace toBoolean {\n type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | internal.assertSize.ErrorType\n | trimLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toHex(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded {@link ox#Hex.Hex} value.\n */\nexport function toHex(value: Bytes, options: toHex.Options = {}): Hex.Hex {\n return Hex.fromBytes(value, options)\n}\n\nexport declare namespace toHex {\n type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n type ErrorType = Hex.fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a number.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toNumber(Bytes.from([1, 164]))\n * // @log: 420\n * ```\n */\nexport function toNumber(bytes: Bytes, options: toNumber.Options = {}): number {\n const { size } = options\n if (typeof size !== 'undefined') internal.assertSize(bytes, size)\n const hex = Hex.fromBytes(bytes, options)\n return Hex.toNumber(hex, options)\n}\n\nexport declare namespace toNumber {\n type Options = {\n /** Whether or not the number of a signed representation. */\n signed?: boolean | undefined\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Hex.toNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a string.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.toString(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: 'Hello world'\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded string.\n */\nexport function toString(bytes: Bytes, options: toString.Options = {}): string {\n const { size } = options\n\n let bytes_ = bytes\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size)\n bytes_ = trimRight(bytes_)\n }\n return decoder.decode(bytes_)\n}\n\nexport declare namespace toString {\n export type Options = {\n /** Size of the bytes. */\n size?: number | undefined\n }\n\n export type ErrorType =\n | internal.assertSize.ErrorType\n | trimRight.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Trims leading zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimLeft(Bytes.from([0, 0, 0, 0, 1, 2, 3]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimLeft(value: Bytes): Bytes {\n return internal.trim(value, { dir: 'left' })\n}\n\nexport declare namespace trimLeft {\n type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Trims trailing zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimRight(Bytes.from([1, 2, 3, 0, 0, 0, 0]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimRight(value: Bytes): Bytes {\n return internal.trim(value, { dir: 'right' })\n}\n\nexport declare namespace trimRight {\n export type ErrorType = internal.trim.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.validate('0x')\n * // @log: false\n *\n * Bytes.validate(Bytes.from([1, 2, 3]))\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns `true` if the value is {@link ox#Bytes.Bytes}, otherwise `false`.\n */\nexport function validate(value: unknown): value is Bytes {\n try {\n assert(value)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when the bytes value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([5]))\n * // @error: Bytes.InvalidBytesBooleanError: Bytes value `[5]` is not a valid boolean.\n * // @error: The bytes array must contain a single byte of either a `0` or `1` value.\n * ```\n */\nexport class InvalidBytesBooleanError extends Errors.BaseError {\n override readonly name = 'Bytes.InvalidBytesBooleanError'\n\n constructor(bytes: Bytes) {\n super(`Bytes value \\`${bytes}\\` is not a valid boolean.`, {\n metaMessages: [\n 'The bytes array must contain a single byte of either a `0` or `1` value.',\n ],\n })\n }\n}\n\n/**\n * Thrown when a value cannot be converted to bytes.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * Bytes.from('foo')\n * // @error: Bytes.InvalidBytesTypeError: Value `foo` of type `string` is an invalid Bytes value.\n * ```\n */\nexport class InvalidBytesTypeError extends Errors.BaseError {\n override readonly name = 'Bytes.InvalidBytesTypeError'\n\n constructor(value: unknown) {\n super(\n `Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid Bytes value.`,\n {\n metaMessages: ['Bytes values must be of type `Bytes`.'],\n },\n )\n }\n}\n\n/**\n * Thrown when a size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromString('Hello World!', { size: 8 })\n * // @error: Bytes.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n override readonly name = 'Bytes.SizeOverflowError'\n\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`,\n )\n }\n}\n\n/**\n * Thrown when a slice offset is out-of-bounds.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(Bytes.from([1, 2, 3]), 4)\n * // @error: Bytes.SliceOffsetOutOfBoundsError: Slice starting at offset `4` is out-of-bounds (size: `3`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Bytes.SliceOffsetOutOfBoundsError'\n\n constructor({\n offset,\n position,\n size,\n }: { offset: number; position: 'start' | 'end'; size: number }) {\n super(\n `Slice ${\n position === 'start' ? 'starting' : 'ending'\n } at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`,\n )\n }\n}\n\n/**\n * Thrown when a the padding size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.fromString('Hello World!'), 8)\n * // @error: [Bytes.SizeExceedsPaddingSizeError: Bytes size (`12`) exceeds padding size (`8`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n override readonly name = 'Bytes.SizeExceedsPaddingSizeError'\n\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'Hex' | 'Bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`,\n )\n }\n}\n","/** @internal */\nexport const version = '0.1.1'\n","import { version } from '../version.js'\n\n/** @internal */\nexport function getUrl(url: string) {\n return url\n}\n\n/** @internal */\nexport function getVersion() {\n return version\n}\n\n/** @internal */\nexport function prettyPrint(args: unknown) {\n if (!args) return ''\n const entries = Object.entries(args)\n .map(([key, value]) => {\n if (value === undefined || value === false) return null\n return [key, value]\n })\n .filter(Boolean) as [string, string][]\n const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0)\n return entries\n .map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`)\n .join('\\n')\n}\n","import { getVersion } from './internal/errors.js'\n\nexport type GlobalErrorType<name extends string = 'Error'> = Error & {\n name: name\n}\n\n/**\n * Base error class inherited by all errors thrown by ox.\n *\n * @example\n * ```ts\n * import { Errors } from 'ox'\n * throw new Errors.BaseError('An error occurred')\n * ```\n */\nexport class BaseError<\n cause extends Error | undefined = undefined,\n> extends Error {\n details: string\n docs?: string | undefined\n docsPath?: string | undefined\n shortMessage: string\n\n override cause: cause\n override name = 'BaseError'\n\n version = `ox@${getVersion()}`\n\n constructor(shortMessage: string, options: BaseError.Options<cause> = {}) {\n const details = (() => {\n if (options.cause instanceof BaseError) {\n if (options.cause.details) return options.cause.details\n if (options.cause.shortMessage) return options.cause.shortMessage\n }\n if (options.cause?.message) return options.cause.message\n return options.details!\n })()\n const docsPath = (() => {\n if (options.cause instanceof BaseError)\n return options.cause.docsPath || options.docsPath\n return options.docsPath\n })()\n\n const docsBaseUrl = 'https://oxlib.sh'\n const docs = `${docsBaseUrl}${docsPath ?? ''}`\n\n const message = [\n shortMessage || 'An error occurred.',\n ...(options.metaMessages ? ['', ...options.metaMessages] : []),\n ...(details || docsPath\n ? [\n '',\n details ? `Details: ${details}` : undefined,\n docsPath ? `See: ${docs}` : undefined,\n ]\n : []),\n ]\n .filter((x) => typeof x === 'string')\n .join('\\n')\n\n super(message, options.cause ? { cause: options.cause } : undefined)\n\n this.cause = options.cause as any\n this.details = details\n this.docs = docs\n this.docsPath = docsPath\n this.shortMessage = shortMessage\n }\n\n walk(): Error\n walk(fn: (err: unknown) => boolean): Error | null\n walk(fn?: any): any {\n return walk(this, fn)\n }\n}\n\nexport declare namespace BaseError {\n type Options<cause extends Error | undefined = Error | undefined> = {\n cause?: cause | undefined\n details?: string | undefined\n docsPath?: string | undefined\n metaMessages?: (string | undefined)[] | undefined\n }\n}\n\n/** @internal */\nfunction walk(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err\n if (err && typeof err === 'object' && 'cause' in err && err.cause)\n return walk(err.cause, fn)\n return fn ? null : err\n}\n","import type * as Errors from './Errors.js'\n\nconst bigIntSuffix = '#__bigint'\n\n/**\n * Parses a JSON string, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.parse('{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}')\n * // @log: {\n * // @log: foo: 'bar',\n * // @log: baz: 69420694206942069420694206942069420694206942069420n\n * // @log: }\n * ```\n *\n * @param string - The value to parse.\n * @param reviver - A function that transforms the results.\n * @returns The parsed value.\n */\nexport function parse(\n string: string,\n reviver?: ((this: any, key: string, value: any) => any) | undefined,\n) {\n return JSON.parse(string, (key, value_) => {\n const value = value_\n if (typeof value === 'string' && value.endsWith(bigIntSuffix))\n return BigInt(value.slice(0, -bigIntSuffix.length))\n return typeof reviver === 'function' ? reviver(key, value) : value\n })\n}\n\nexport declare namespace parse {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Stringifies a value to its JSON representation, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.stringify({\n * foo: 'bar',\n * baz: 69420694206942069420694206942069420694206942069420n,\n * })\n * // @log: '{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}'\n * ```\n *\n * @param value - The value to stringify.\n * @param replacer - A function that transforms the results. It is passed the key and value of the property, and must return the value to be used in the JSON string. If this function returns `undefined`, the property is not included in the resulting JSON string.\n * @param space - A string or number that determines the indentation of the JSON string. If it is a number, it indicates the number of spaces to use as indentation; if it is a string (e.g. `'\\t'`), it uses the string as the indentation character.\n * @returns The JSON string.\n */\nexport function stringify(\n value: any,\n replacer?: ((this: any, key: string, value: any) => any) | null | undefined,\n space?: string | number | undefined,\n) {\n return JSON.stringify(\n value,\n (key, value) => {\n if (typeof replacer === 'function') return replacer(key, value)\n if (typeof value === 'bigint') return value.toString() + bigIntSuffix\n return value\n },\n space,\n )\n}\n\nexport declare namespace stringify {\n type ErrorType = Errors.GlobalErrorType\n}\n","import * as Bytes from '../Bytes.js'\nimport type * as Errors from '../Errors.js'\n\n/** @internal */\nexport function assertSize(bytes: Bytes.Bytes, size_: number): void {\n if (Bytes.size(bytes) > size_)\n throw new Bytes.SizeOverflowError({\n givenSize: Bytes.size(bytes),\n maxSize: size_,\n })\n}\n\n/** @internal */\nexport declare namespace assertSize {\n type ErrorType =\n | Bytes.size.ErrorType\n | Bytes.SizeOverflowError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertStartOffset(\n value: Bytes.Bytes,\n start?: number | undefined,\n) {\n if (typeof start === 'number' && start > 0 && start > Bytes.size(value) - 1)\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Bytes.size(value),\n })\n}\n\nexport declare namespace assertStartOffset {\n export type ErrorType =\n | Bytes.SliceOffsetOutOfBoundsError\n | Bytes.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertEndOffset(\n value: Bytes.Bytes,\n start?: number | undefined,\n end?: number | undefined,\n) {\n if (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Bytes.size(value) !== end - start\n ) {\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Bytes.size(value),\n })\n }\n}\n\n/** @internal */\nexport declare namespace assertEndOffset {\n type ErrorType =\n | Bytes.SliceOffsetOutOfBoundsError\n | Bytes.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport const charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n} as const\n\n/** @internal */\nexport function charCodeToBase16(char: number) {\n if (char >= charCodeMap.zero && char <= charCodeMap.nine)\n return char - charCodeMap.zero\n if (char >= charCodeMap.A && char <= charCodeMap.F)\n return char - (charCodeMap.A - 10)\n if (char >= charCodeMap.a && char <= charCodeMap.f)\n return char - (charCodeMap.a - 10)\n return undefined\n}\n\n/** @internal */\nexport function pad(bytes: Bytes.Bytes, options: pad.Options = {}) {\n const { dir, size = 32 } = options\n if (size === 0) return bytes\n if (bytes.length > size)\n throw new Bytes.SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'Bytes',\n })\n const paddedBytes = new Uint8Array(size)\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right'\n paddedBytes[padEnd ? i : size - i - 1] =\n bytes[padEnd ? i : bytes.length - i - 1]!\n }\n return paddedBytes\n}\n\n/** @internal */\nexport declare namespace pad {\n type Options = {\n dir?: 'left' | 'right' | undefined\n size?: number | undefined\n }\n\n type ReturnType = Bytes.Bytes\n\n type ErrorType = Bytes.SizeExceedsPaddingSizeError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function trim(\n value: Bytes.Bytes,\n options: trim.Options = {},\n): trim.ReturnType {\n const { dir = 'left' } = options\n\n let data = value\n\n let sliceLength = 0\n for (let i = 0; i < data.length - 1; i++) {\n if (data[dir === 'left' ? i : data.length - i - 1]!.toString() === '0')\n sliceLength++\n else break\n }\n data =\n dir === 'left'\n ? data.slice(sliceLength)\n : data.slice(0, data.length - sliceLength)\n\n return data as trim.ReturnType\n}\n\n/** @internal */\nexport declare namespace trim {\n type Options = {\n dir?: 'left' | 'right' | undefined\n }\n\n type ReturnType = Bytes.Bytes\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Errors from '../Errors.js'\nimport * as Hex from '../Hex.js'\n\n/** @internal */\nexport function assertSize(hex: Hex.Hex, size_: number): void {\n if (Hex.size(hex) > size_)\n throw new Hex.SizeOverflowError({\n givenSize: Hex.size(hex),\n maxSize: size_,\n })\n}\n\n/** @internal */\nexport declare namespace assertSize {\n type ErrorType =\n | Hex.size.ErrorType\n | Hex.SizeOverflowError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertStartOffset(value: Hex.Hex, start?: number | undefined) {\n if (typeof start === 'number' && start > 0 && start > Hex.size(value) - 1)\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Hex.size(value),\n })\n}\n\nexport declare namespace assertStartOffset {\n type ErrorType =\n | Hex.SliceOffsetOutOfBoundsError\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function assertEndOffset(\n value: Hex.Hex,\n start?: number | undefined,\n end?: number | undefined,\n) {\n if (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Hex.size(value) !== end - start\n ) {\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Hex.size(value),\n })\n }\n}\n\nexport declare namespace assertEndOffset {\n type ErrorType =\n | Hex.SliceOffsetOutOfBoundsError\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function pad(hex_: Hex.Hex, options: pad.Options = {}) {\n const { dir, size = 32 } = options\n\n if (size === 0) return hex_\n\n const hex = hex_.replace('0x', '')\n if (hex.length > size * 2)\n throw new Hex.SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'Hex',\n })\n\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}` as Hex.Hex\n}\n\n/** @internal */\nexport declare namespace pad {\n type Options = {\n dir?: 'left' | 'right' | undefined\n size?: number | undefined\n }\n type ErrorType = Hex.SizeExceedsPaddingSizeError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function trim(\n value: Hex.Hex,\n options: trim.Options = {},\n): trim.ReturnType {\n const { dir = 'left' } = options\n\n let data = value.replace('0x', '')\n\n let sliceLength = 0\n for (let i = 0; i < data.length - 1; i++) {\n if (data[dir === 'left' ? i : data.length - i - 1]!.toString() === '0')\n sliceLength++\n else break\n }\n data =\n dir === 'left'\n ? data.slice(sliceLength)\n : data.slice(0, data.length - sliceLength)\n\n if (data === '0') return '0x'\n if (dir === 'right' && data.length % 2 === 1) return `0x${data}0`\n return `0x${data}` as trim.ReturnType\n}\n\n/** @internal */\nexport declare namespace trim {\n type Options = {\n dir?: 'left' | 'right' | undefined\n }\n\n type ReturnType = Hex.Hex\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\n\n/** A Withdrawal as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/withdrawal.yaml). */\nexport type Withdrawal<bigintType = bigint, numberType = number> = {\n address: Hex.Hex\n amount: bigintType\n index: numberType\n validatorIndex: numberType\n}\n\n/** An RPC Withdrawal as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/withdrawal.yaml). */\nexport type Rpc = Withdrawal<Hex.Hex, Hex.Hex>\n\n/**\n * Converts a {@link ox#Withdrawal.Rpc} to an {@link ox#Withdrawal.Withdrawal}.\n *\n * @example\n * ```ts twoslash\n * import { Withdrawal } from 'ox'\n *\n * const withdrawal = Withdrawal.fromRpc({\n * address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * amount: '0x620323',\n * index: '0x0',\n * validatorIndex: '0x1',\n * })\n * // @log: {\n * // @log: address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * // @log: amount: 6423331n,\n * // @log: index: 0,\n * // @log: validatorIndex: 1\n * // @log: }\n * ```\n *\n * @param withdrawal - The RPC withdrawal to convert.\n * @returns An instantiated {@link ox#Withdrawal.Withdrawal}.\n */\nexport function fromRpc(withdrawal: Rpc): Withdrawal {\n return {\n ...withdrawal,\n amount: BigInt(withdrawal.amount),\n index: Number(withdrawal.index),\n validatorIndex: Number(withdrawal.validatorIndex),\n }\n}\n\nexport declare namespace fromRpc {\n export type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Withdrawal.Withdrawal} to an {@link ox#Withdrawal.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Withdrawal } from 'ox'\n *\n * const withdrawal = Withdrawal.toRpc({\n * address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * amount: 6423331n,\n * index: 0,\n * validatorIndex: 1,\n * })\n * // @log: {\n * // @log: address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * // @log: amount: '0x620323',\n * // @log: index: '0x0',\n * // @log: validatorIndex: '0x1',\n * // @log: }\n * ```\n *\n * @param withdrawal - The Withdrawal to convert.\n * @returns An RPC Withdrawal.\n */\nexport function toRpc(withdrawal: Withdrawal): Rpc {\n return {\n address: withdrawal.address,\n amount: Hex.fromNumber(withdrawal.amount),\n index: Hex.fromNumber(withdrawal.index),\n validatorIndex: Hex.fromNumber(withdrawal.validatorIndex),\n }\n}\n\nexport declare namespace toRpc {\n export type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Address from './Address.js'\nimport * as Hex from './Hex.js'\nimport * as Withdrawal from './Withdrawal.js'\n\n/**\n * Block overrides.\n */\nexport type BlockOverrides<bigintType = bigint, numberType = number> = {\n /** Base fee per gas. */\n baseFeePerGas?: bigintType | undefined\n /** Blob base fee. */\n blobBaseFee?: bigintType | undefined\n /** Fee recipient (also known as coinbase). */\n feeRecipient?: Address.Address | undefined\n /** Gas limit. */\n gasLimit?: bigintType | undefined\n /** Block number. */\n number?: bigintType | undefined\n /** The previous value of randomness beacon. */\n prevRandao?: bigintType | undefined\n /** Block timestamp. */\n time?: bigintType | undefined\n /** Withdrawals made by validators. */\n withdrawals?: Withdrawal.Withdrawal<bigintType, numberType>[] | undefined\n}\n\n/**\n * RPC block overrides.\n */\nexport type Rpc = BlockOverrides<Hex.Hex, Hex.Hex>\n\n/**\n * Converts an {@link ox#BlockOverrides.Rpc} to an {@link ox#BlockOverrides.BlockOverrides}.\n *\n * @example\n * ```ts twoslash\n * import { BlockOverrides } from 'ox'\n *\n * const blockOverrides = BlockOverrides.fromRpc({\n * baseFeePerGas: '0x1',\n * blobBaseFee: '0x2',\n * feeRecipient: '0x0000000000000000000000000000000000000000',\n * gasLimit: '0x4',\n * number: '0x5',\n * prevRandao: '0x6',\n * time: '0x1234567890',\n * withdrawals: [\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * amount: '0x1',\n * index: '0x0',\n * validatorIndex: '0x1',\n * },\n * ],\n * })\n * ```\n *\n * @param rpcBlockOverrides - The RPC block overrides to convert.\n * @returns An instantiated {@link ox#BlockOverrides.BlockOverrides}.\n */\nexport function fromRpc(rpcBlockOverrides: Rpc): BlockOverrides {\n return {\n ...(rpcBlockOverrides.baseFeePerGas && {\n baseFeePerGas: BigInt(rpcBlockOverrides.baseFeePerGas),\n }),\n ...(rpcBlockOverrides.blobBaseFee && {\n blobBaseFee: BigInt(rpcBlockOverrides.blobBaseFee),\n }),\n ...(rpcBlockOverrides.feeRecipient && {\n feeRecipient: rpcBlockOverrides.feeRecipient,\n }),\n ...(rpcBlockOverrides.gasLimit && {\n gasLimit: BigInt(rpcBlockOverrides.gasLimit),\n }),\n ...(rpcBlockOverrides.number && {\n number: BigInt(rpcBlockOverrides.number),\n }),\n ...(rpcBlockOverrides.prevRandao && {\n prevRandao: BigInt(rpcBlockOverrides.prevRandao),\n }),\n ...(rpcBlockOverrides.time && {\n time: BigInt(rpcBlockOverrides.time),\n }),\n ...(rpcBlockOverrides.withdrawals && {\n withdrawals: rpcBlockOverrides.withdrawals.map(Withdrawal.fromRpc),\n }),\n }\n}\n\n/**\n * Converts an {@link ox#BlockOverrides.BlockOverrides} to an {@link ox#BlockOverrides.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { BlockOverrides } from 'ox'\n *\n * const blockOverrides = BlockOverrides.toRpc({\n * baseFeePerGas: 1n,\n * blobBaseFee: 2n,\n * feeRecipient: '0x0000000000000000000000000000000000000000',\n * gasLimit: 4n,\n * number: 5n,\n * prevRandao: 6n,\n * time: 78187493520n,\n * withdrawals: [\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * amount: 1n,\n * index: 0,\n * validatorIndex: 1,\n * },\n * ],\n * })\n * ```\n *\n * @param blockOverrides - The block overrides to convert.\n * @returns An instantiated {@link ox#BlockOverrides.Rpc}.\n */\nexport function toRpc(blockOverrides: BlockOverrides): Rpc {\n return {\n ...(typeof blockOverrides.baseFeePerGas === 'bigint' && {\n baseFeePerGas: Hex.fromNumber(blockOverrides.baseFeePerGas),\n }),\n ...(typeof blockOverrides.blobBaseFee === 'bigint' && {\n blobBaseFee: Hex.fromNumber(blockOverrides.blobBaseFee),\n }),\n ...(typeof blockOverrides.feeRecipient === 'string' && {\n feeRecipient: blockOverrides.feeRecipient,\n }),\n ...(typeof blockOverrides.gasLimit === 'bigint' && {\n gasLimit: Hex.fromNumber(blockOverrides.gasLimit),\n }),\n ...(typeof blockOverrides.number === 'bigint' && {\n number: Hex.fromNumber(blockOverrides.number),\n }),\n ...(typeof blockOverrides.prevRandao === 'bigint' && {\n prevRandao: Hex.fromNumber(blockOverrides.prevRandao),\n }),\n ...(typeof blockOverrides.time === 'bigint' && {\n time: Hex.fromNumber(blockOverrides.time),\n }),\n ...(blockOverrides.withdrawals && {\n withdrawals: blockOverrides.withdrawals.map(Withdrawal.toRpc),\n }),\n }\n}\n","import type { Abi, AbiStateMutability, Address, Narrow } from 'abitype'\nimport * as BlockOverrides from 'ox/BlockOverrides'\n\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type { Call, Calls } from '../../types/calls.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { MulticallResults } from '../../types/multicall.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial, UnionOmit } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getContractError } from '../../utils/errors/getContractError.js'\nimport {\n type GetNodeErrorReturnType,\n getNodeError,\n} from '../../utils/errors/getNodeError.js'\nimport {\n type FormatBlockErrorType,\n formatBlock,\n} from '../../utils/formatters/block.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport {\n type FormatTransactionRequestErrorType,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport {\n type SerializeStateOverrideErrorType,\n serializeStateOverride,\n} from '../../utils/stateOverride.js'\nimport {\n type AssertRequestErrorType,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\n\ntype CallExtraProperties = ExactPartial<\n UnionOmit<\n TransactionRequest,\n 'blobs' | 'data' | 'kzg' | 'to' | 'sidecars' | 'value'\n >\n> & {\n /** Account attached to the call (msg.sender). */\n account?: Account | Address | undefined\n}\n\nexport type SimulateBlocksParameters<\n calls extends readonly unknown[] = readonly unknown[],\n> = {\n /** Blocks to simulate. */\n blocks: readonly {\n /** Block overrides. */\n blockOverrides?: BlockOverrides.BlockOverrides | undefined\n /** Calls to execute. */\n calls: Calls<Narrow<calls>, CallExtraProperties>\n /** State overrides. */\n stateOverrides?: StateOverride | undefined\n }[]\n /** Whether to return the full transactions. */\n returnFullTransactions?: boolean | undefined\n /** Whether to trace transfers. */\n traceTransfers?: boolean | undefined\n /** Whether to enable validation mode. */\n validation?: boolean | undefined\n} & (\n | {\n /** The balance of the account at a block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The balance of the account at a block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n)\n\nexport type SimulateBlocksReturnType<\n calls extends readonly unknown[] = readonly unknown[],\n> = readonly (Block & {\n calls: MulticallResults<\n Narrow<calls>,\n true,\n {\n extraProperties: {\n data: Hex\n gasUsed: bigint\n logs?: Log[] | undefined\n }\n error: Error\n mutability: AbiStateMutability\n }\n >\n})[]\n\nexport type SimulateBlocksErrorType =\n | AssertRequestErrorType\n | DecodeFunctionResultErrorType\n | EncodeFunctionDataErrorType\n | FormatBlockErrorType\n | FormatTransactionRequestErrorType\n | GetNodeErrorReturnType\n | ParseAccountErrorType\n | SerializeStateOverrideErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Simulates a set of calls on block(s) with optional block and state overrides.\n *\n * @example\n * ```ts\n * import { createClient, http, parseEther } from 'viem'\n * import { simulate } from 'viem/actions'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await simulate(client, {\n * blocks: [{\n * blockOverrides: {\n * number: 69420n,\n * },\n * calls: [{\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * }],\n * stateOverrides: [{\n * address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * balance: parseEther('10'),\n * }],\n * }]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateBlocksParameters}\n * @returns Simulated blocks. {@link SimulateBlocksReturnType}\n */\nexport async function simulateBlocks<\n chain extends Chain | undefined,\n const calls extends readonly unknown[],\n>(\n client: Client<Transport, chain>,\n parameters: SimulateBlocksParameters<calls>,\n): Promise<SimulateBlocksReturnType<calls>> {\n const {\n blockNumber,\n blockTag = 'latest',\n blocks,\n returnFullTransactions,\n traceTransfers,\n validation,\n } = parameters\n\n try {\n const blockStateCalls = []\n for (const block of blocks) {\n const blockOverrides = block.blockOverrides\n ? BlockOverrides.toRpc(block.blockOverrides)\n : undefined\n const calls = block.calls.map((call_) => {\n const call = call_ as Call<unknown, CallExtraProperties>\n const account = call.account ? parseAccount(call.account) : undefined\n const request = {\n ...call,\n data: call.abi ? encodeFunctionData(call) : call.data,\n from: call.from ?? account?.address,\n } as const\n assertRequest(request)\n return formatTransactionRequest(request)\n })\n const stateOverrides = block.stateOverrides\n ? serializeStateOverride(block.stateOverrides)\n : undefined\n\n blockStateCalls.push({\n blockOverrides,\n calls,\n stateOverrides,\n })\n }\n\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const result = await client.request({\n method: 'eth_simulateV1',\n params: [\n { blockStateCalls, returnFullTransactions, traceTransfers, validation },\n block,\n ],\n })\n\n return result.map((block, i) => ({\n ...formatBlock(block),\n calls: block.calls.map((call, j) => {\n const { abi, args, functionName, to } = blocks[i].calls[j] as Call<\n unknown,\n CallExtraProperties\n >\n\n const data = call.error?.data ?? call.returnData\n const gasUsed = BigInt(call.gasUsed)\n const logs = call.logs?.map((log) => formatLog(log))\n const status = call.status === '0x1' ? 'success' : 'failure'\n\n const result =\n abi && status === 'success'\n ? decodeFunctionResult({\n abi,\n data,\n functionName,\n })\n : null\n\n const error = (() => {\n if (status === 'success') return undefined\n\n let error = undefined\n if (call.error?.data === '0x') error = new AbiDecodingZeroDataError()\n else if (call.error) error = new RawContractError(call.error)\n\n if (!error) return undefined\n return getContractError(error, {\n abi: (abi ?? []) as Abi,\n address: to,\n args,\n functionName: functionName ?? '<unknown>',\n })\n })()\n\n return {\n data,\n gasUsed,\n logs,\n status,\n ...(status === 'success'\n ? {\n result,\n }\n : {\n error,\n }),\n }\n }),\n })) as unknown as SimulateBlocksReturnType<calls>\n } catch (e) {\n const cause = e as BaseError\n const error = getNodeError(cause, {})\n if (error instanceof UnknownNodeError) throw cause\n throw error\n }\n}\n","import { ripemd160 as noble_ripemd160 } from '@noble/hashes/ripemd160'\nimport { keccak_256 as noble_keccak256 } from '@noble/hashes/sha3'\nimport { sha256 as noble_sha256 } from '@noble/hashes/sha256'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\n\n/**\n * Calculates the [Keccak256](https://en.wikipedia.org/wiki/SHA-3) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `keccak_256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef')\n * // @log: '0xd4fd4e189132273036449fc9e11198c739161b4c0116a9a2dccdfa1c492006f1'\n * ```\n *\n * @example\n * ### Calculate Hash of a String\n *\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.keccak256(Hex.fromString('hello world'))\n * // @log: '0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0'\n * ```\n *\n * @example\n * ### Configure Return Type\n *\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef', { as: 'Bytes' })\n * // @log: Uint8Array [...]\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Keccak256 hash.\n */\nexport function keccak256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: keccak256.Options<as> = {},\n): keccak256.ReturnType<as> {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_keccak256(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace keccak256 {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [Ripemd160](https://en.wikipedia.org/wiki/RIPEMD) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `ripemd160` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.ripemd160('0xdeadbeef')\n * // '0x226821c2f5423e11fe9af68bd285c249db2e4b5a'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Ripemd160 hash.\n */\nexport function ripemd160<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: ripemd160.Options<as> = {},\n): ripemd160.ReturnType<as> {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_ripemd160(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace ripemd160 {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [Sha256](https://en.wikipedia.org/wiki/SHA-256) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `sha256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.sha256('0xdeadbeef')\n * // '0x5f78c33274e43fa9de5659265c1d917e25c03722dcb0b8d27db8d5feaa813953'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Sha256 hash.\n */\nexport function sha256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: sha256.Options<as> = {},\n): sha256.ReturnType<as> {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_sha256(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace sha256 {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex'> = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes' = 'Hex'> =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if a string is a valid hash value.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.validate('0x')\n * // @log: false\n *\n * Hash.validate('0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0')\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns Whether the value is a valid hash.\n */\nexport function validate(value: string): value is Hex.Hex {\n return Hex.validate(value) && Hex.size(value) === 32\n}\n\nexport declare namespace validate {\n type ErrorType =\n | Hex.validate.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n","/**\n * @internal\n *\n * Map with a LRU (Least recently used) policy.\n * @see https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap<value = unknown> extends Map<string, value> {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override get(key: string) {\n const value = super.get(key)\n\n if (super.has(key) && value !== undefined) {\n this.delete(key)\n super.set(key, value)\n }\n\n return value\n }\n\n override set(key: string, value: value) {\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value\n if (firstKey) this.delete(firstKey)\n }\n return this\n }\n}\n","import type * as Address from './Address.js'\nimport { LruMap } from './internal/lru.js'\n\nconst caches = {\n checksum: /*#__PURE__*/ new LruMap<Address.Address>(8192),\n}\n\nexport const checksum = caches.checksum\n\n/**\n * Clears all global caches.\n *\n * @example\n * ```ts\n * import { Caches } from 'ox'\n * Caches.clear()\n * ```\n */\nexport function clear() {\n for (const cache of Object.values(caches)) cache.clear()\n}\n","import type { Address as abitype_Address } from 'abitype'\nimport * as Bytes from './Bytes.js'\nimport * as Caches from './Caches.js'\nimport * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as PublicKey from './PublicKey.js'\n\nconst addressRegex = /*#__PURE__*/ /^0x[a-fA-F0-9]{40}$/\n\n/** Root type for Address. */\nexport type Address = abitype_Address\n\n/**\n * Asserts that the given value is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xdeadbeef')\n * // @error: InvalidAddressError: Address \"0xdeadbeef\" is invalid.\n * ```\n *\n * @param value - Value to assert if it is a valid address.\n * @param options - Assertion options.\n */\nexport function assert(\n value: string,\n options: assert.Options = {},\n): asserts value is Address {\n const { strict = true } = options\n\n if (!addressRegex.test(value))\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidInputError(),\n })\n\n if (strict) {\n if (value.toLowerCase() === value) return\n if (checksum(value as Address) !== value)\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidChecksumError(),\n })\n }\n}\n\nexport declare namespace assert {\n type Options = {\n /**\n * Enables strict mode. Whether or not to compare the address against its checksum.\n *\n * @default true\n */\n strict?: boolean | undefined\n }\n\n type ErrorType = InvalidAddressError | Errors.GlobalErrorType\n}\n\n/**\n * Computes the checksum address for the given {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.checksum('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @param address - The address to compute the checksum for.\n * @returns The checksummed address.\n */\nexport function checksum(address: string): Address {\n if (Caches.checksum.has(address)) return Caches.checksum.get(address)!\n\n assert(address, { strict: false })\n\n const hexAddress = address.substring(2).toLowerCase()\n const hash = Hash.keccak256(Bytes.fromString(hexAddress), { as: 'Bytes' })\n\n const characters = hexAddress.split('')\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1]! >> 4 >= 8 && characters[i]) {\n characters[i] = characters[i]!.toUpperCase()\n }\n if ((hash[i >> 1]! & 0x0f) >= 8 && characters[i + 1]) {\n characters[i + 1] = characters[i + 1]!.toUpperCase()\n }\n }\n\n const result = `0x${characters.join('')}` as const\n Caches.checksum.set(address, result)\n return result\n}\n\nexport declare namespace checksum {\n type ErrorType =\n | assert.ErrorType\n | Hash.keccak256.ErrorType\n | Bytes.fromString.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a stringified address to a typed (checksummed) {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e', {\n * checksum: false\n * })\n * // @log: '0xa0cf798816d4b9b9866b5330eea46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('hello')\n * // @error: InvalidAddressError: Address \"0xa\" is invalid.\n * ```\n *\n * @param address - An address string to convert to a typed Address.\n * @param options - Conversion options.\n * @returns The typed Address.\n */\nexport function from(address: string, options: from.Options = {}): Address {\n const { checksum: checksumVal = false } = options\n assert(address)\n if (checksumVal) return checksum(address)\n return address as Address\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether to checksum the address.\n *\n * @default false\n */\n checksum?: boolean | undefined\n }\n\n type ErrorType =\n | assert.ErrorType\n | checksum.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts an ECDSA public key to an {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address, PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from(\n * '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5',\n * )\n * const address = Address.fromPublicKey(publicKey)\n * // @log: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'\n * ```\n *\n * @param publicKey - The ECDSA public key to convert to an {@link ox#Address.Address}.\n * @param options - Conversion options.\n * @returns The {@link ox#Address.Address} corresponding to the public key.\n */\nexport function fromPublicKey(\n publicKey: PublicKey.PublicKey,\n options: fromPublicKey.Options = {},\n): Address {\n const address = Hash.keccak256(\n `0x${PublicKey.toHex(publicKey).slice(4)}`,\n ).substring(26)\n return from(`0x${address}`, options)\n}\n\nexport declare namespace fromPublicKey {\n type Options = {\n /**\n * Whether to checksum the address.\n *\n * @default false\n */\n checksum?: boolean | undefined\n }\n\n type ErrorType =\n | Hash.keccak256.ErrorType\n | PublicKey.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Address.Address} are equal.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * )\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251f'\n * )\n * // @log: false\n * ```\n *\n * @param addressA - The first address to compare.\n * @param addressB - The second address to compare.\n * @returns Whether the addresses are equal.\n */\nexport function isEqual(addressA: Address, addressB: Address): boolean {\n assert(addressA, { strict: false })\n assert(addressB, { strict: false })\n return addressA.toLowerCase() === addressB.toLowerCase()\n}\n\nexport declare namespace isEqual {\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given address is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param address - Value to check if it is a valid address.\n * @param options - Check options.\n * @returns Whether the address is a valid address.\n */\nexport function validate(\n address: string,\n options: validate.Options = {},\n): address is Address {\n const { strict = true } = options ?? {}\n try {\n assert(address, { strict })\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /**\n * Enables strict mode. Whether or not to compare the address against its checksum.\n *\n * @default true\n */\n strict?: boolean | undefined\n }\n}\n\n/**\n * Thrown when an address is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0x123')\n * // @error: Address.InvalidAddressError: Address `0x123` is invalid.\n * ```\n */\nexport class InvalidAddressError<\n cause extends InvalidInputError | InvalidChecksumError =\n | InvalidInputError\n | InvalidChecksumError,\n> extends Errors.BaseError<cause> {\n override readonly name = 'Address.InvalidAddressError'\n\n constructor({ address, cause }: { address: string; cause: cause }) {\n super(`Address \"${address}\" is invalid.`, {\n cause,\n })\n }\n}\n\n/** Thrown when an address is not a 20 byte (40 hexadecimal character) value. */\nexport class InvalidInputError extends Errors.BaseError {\n override readonly name = 'Address.InvalidInputError'\n\n constructor() {\n super('Address is not a 20 byte (40 hexadecimal character) value.')\n }\n}\n\n/** Thrown when an address does not match its checksum counterpart. */\nexport class InvalidChecksumError extends Errors.BaseError {\n override readonly name = 'Address.InvalidChecksumError'\n\n constructor() {\n super('Address does not match its checksum counterpart.')\n }\n}\n","import type * as abitype from 'abitype'\nimport type * as Abi from '../Abi.js'\nimport type * as AbiItem from '../AbiItem.js'\nimport type * as AbiParameters from '../AbiParameters.js'\nimport * as Address from '../Address.js'\nimport * as Errors from '../Errors.js'\nimport type {\n Compute,\n IsNever,\n IsUnion,\n TypeErrorMessage,\n UnionToTuple,\n} from './types.js'\n\n/** @internal */\nexport type ExtractArgs<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends AbiItem.Name<abi> = AbiItem.Name<abi>,\n> = abitype.AbiParametersToPrimitiveTypes<\n AbiItem.FromAbi<abi extends Abi.Abi ? abi : Abi.Abi, name>['inputs'],\n 'inputs'\n> extends infer args\n ? [args] extends [never]\n ? readonly unknown[]\n : args\n : readonly unknown[]\n\n/** @internal */\nexport type ExtractForArgs<\n abi extends Abi.Abi,\n name extends AbiItem.Name<abi>,\n args extends ExtractArgs<abi, name>,\n> = IsUnion<name> extends true\n ? {\n [key in keyof abi]: abi[key] extends { name: name } ? abi[key] : never\n }[number]\n : AbiItem.FromAbi<abi, name> extends infer abiItem extends AbiItem.AbiItem & {\n inputs: readonly abitype.AbiParameter[]\n }\n ? IsUnion<abiItem> extends true // narrow overloads using `args` by converting to tuple and filtering out overloads that don't match\n ? UnionToTuple<abiItem> extends infer abiItems extends\n readonly (AbiItem.AbiItem & {\n inputs: readonly abitype.AbiParameter[]\n })[]\n ? IsNever<TupleToUnion<abiItems, abi, name, args>> extends true\n ? Compute<\n abiItems[0] & {\n readonly overloads: UnionToTuple<\n Exclude<abiItems[number], abiItems[0]>\n >\n }\n >\n : TupleToUnion<abiItems, abi, name, args> // convert back to union (removes `never` tuple entries: `['foo', never, 'bar'][number]` => `'foo' | 'bar'`)\n : never\n : abiItem\n : never\n\n/** @internal */\nexport type TupleToUnion<\n abiItems extends readonly {\n inputs: readonly abitype.AbiParameter[]\n }[],\n abi extends Abi.Abi,\n name extends AbiItem.Name<abi>,\n args extends ExtractArgs<abi, name>,\n> = {\n [k in keyof abiItems]: (\n readonly [] extends args\n ? readonly [] // fallback to `readonly []` if `args` has no value (e.g. `args` property not provided)\n : args\n ) extends abitype.AbiParametersToPrimitiveTypes<\n abiItems[k]['inputs'],\n 'inputs'\n >\n ? abiItems[k]\n : never\n}[number]\n\n/** @internal */\nexport type ErrorSignature<\n name extends string = string,\n parameters extends string = string,\n> = `error ${name}(${parameters})`\n\n/** @internal */\nexport type IsErrorSignature<signature extends string> =\n signature extends ErrorSignature<infer name> ? IsName<name> : false\n\n/** @internal */\nexport type EventSignature<\n name extends string = string,\n parameters extends string = string,\n> = `event ${name}(${parameters})`\n\n/** @internal */\nexport type IsEventSignature<signature extends string> =\n signature extends EventSignature<infer name> ? IsName<name> : false\n\n/** @internal */\nexport type FunctionSignature<\n name extends string = string,\n tail extends string = string,\n> = `function ${name}(${tail}`\nexport type IsFunctionSignature<signature> =\n signature extends FunctionSignature<infer name>\n ? IsName<name> extends true\n ? signature extends ValidFunctionSignatures\n ? true\n : // Check that `Parameters` is not absorbing other types (e.g. `returns`)\n signature extends `function ${string}(${infer parameters})`\n ? parameters extends InvalidFunctionParameters\n ? false\n : true\n : false\n : false\n : false\n/** @internal */\nexport type Scope = 'public' | 'external' // `internal` or `private` functions wouldn't make it to ABI so can ignore\n\n/** @internal */\nexport type Returns = `returns (${string})` | `returns(${string})`\n\n// Almost all valid function signatures, except `function ${string}(${infer parameters})` since `parameters` can absorb returns\n/** @internal */\nexport type ValidFunctionSignatures =\n | `function ${string}()`\n // basic\n | `function ${string}() ${Returns}`\n | `function ${string}() ${abitype.AbiStateMutability}`\n | `function ${string}() ${Scope}`\n // combinations\n | `function ${string}() ${abitype.AbiStateMutability} ${Returns}`\n | `function ${string}() ${Scope} ${Returns}`\n | `function ${string}() ${Scope} ${abitype.AbiStateMutability}`\n | `function ${string}() ${Scope} ${abitype.AbiStateMutability} ${Returns}`\n // Parameters\n | `function ${string}(${string}) ${Returns}`\n | `function ${string}(${string}) ${abitype.AbiStateMutability}`\n | `function ${string}(${string}) ${Scope}`\n | `function ${string}(${string}) ${abitype.AbiStateMutability} ${Returns}`\n | `function ${string}(${string}) ${Scope} ${Returns}`\n | `function ${string}(${string}) ${Scope} ${abitype.AbiStateMutability}`\n | `function ${string}(${string}) ${Scope} ${abitype.AbiStateMutability} ${Returns}`\n\n/** @internal */\nexport type StructSignature<\n name extends string = string,\n properties extends string = string,\n> = `struct ${name} {${properties}}`\n\n/** @internal */\nexport type IsStructSignature<signature extends string> =\n signature extends StructSignature<infer name> ? IsName<name> : false\n\n/** @internal */\nexport type ConstructorSignature<tail extends string = string> =\n `constructor(${tail}`\n\n/** @internal */\nexport type IsConstructorSignature<signature> =\n signature extends ConstructorSignature\n ? signature extends ValidConstructorSignatures\n ? true\n : false\n : false\n\n/** @internal */\nexport type ValidConstructorSignatures =\n | `constructor(${string})`\n | `constructor(${string}) payable`\n\n/** @internal */\nexport type FallbackSignature<abiStateMutability extends '' | ' payable' = ''> =\n `fallback() external${abiStateMutability}`\n\n/** @internal */\nexport type ReceiveSignature = 'receive() external payable'\n\n// TODO: Maybe use this for signature validation one day\n// https://twitter.com/devanshj__/status/1610423724708343808\n/** @internal */\nexport type IsSignature<type extends string> =\n | (IsErrorSignature<type> extends true ? true : never)\n | (IsEventSignature<type> extends true ? true : never)\n | (IsFunctionSignature<type> extends true ? true : never)\n | (IsStructSignature<type> extends true ? true : never)\n | (IsConstructorSignature<type> extends true ? true : never)\n | (type extends FallbackSignature ? true : never)\n | (type extends ReceiveSignature ? true : never) extends infer condition\n ? [condition] extends [never]\n ? false\n : true\n : false\n\n/** @internal */\nexport type Signature<\n string1 extends string,\n string2 extends string | unknown = unknown,\n> = IsSignature<string1> extends true\n ? string1\n : string extends string1 // if exactly `string` (not narrowed), then pass through as valid\n ? string1\n : TypeErrorMessage<`Signature \"${string1}\" is invalid${string2 extends string\n ? ` at position ${string2}`\n : ''}.`>\n\n/** @internal */\nexport type Signatures<signatures extends readonly string[]> = {\n [key in keyof signatures]: Signature<signatures[key], key>\n}\n\n/** @internal */\nexport type IsName<name extends string> = name extends ''\n ? false\n : ValidateName<name> extends name\n ? true\n : false\n\n/** @internal */\nexport type ValidateName<\n name extends string,\n checkCharacters extends boolean = false,\n> = name extends `${string}${' '}${string}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot contain whitespace.`>\n : IsSolidityKeyword<name> extends true\n ? TypeErrorMessage<`\"${name}\" is a protected Solidity keyword.`>\n : name extends `${number}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot be a number string.`>\n : name extends `${number}${string}`\n ? TypeErrorMessage<`Identifier \"${name}\" cannot start with a number.`>\n : checkCharacters extends true\n ? IsValidCharacter<name> extends true\n ? name\n : TypeErrorMessage<`\"${name}\" contains invalid character.`>\n : name\n\n/** @internal */\nexport type IsSolidityKeyword<type extends string> =\n type extends SolidityKeywords ? true : false\n\n/** @internal */\nexport type SolidityKeywords =\n | 'after'\n | 'alias'\n | 'anonymous'\n | 'apply'\n | 'auto'\n | 'byte'\n | 'calldata'\n | 'case'\n | 'catch'\n | 'constant'\n | 'copyof'\n | 'default'\n | 'defined'\n | 'error'\n | 'event'\n | 'external'\n | 'false'\n | 'final'\n | 'function'\n | 'immutable'\n | 'implements'\n | 'in'\n | 'indexed'\n | 'inline'\n | 'internal'\n | 'let'\n | 'mapping'\n | 'match'\n | 'memory'\n | 'mutable'\n | 'null'\n | 'of'\n | 'override'\n | 'partial'\n | 'private'\n | 'promise'\n | 'public'\n | 'pure'\n | 'reference'\n | 'relocatable'\n | 'return'\n | 'returns'\n | 'sizeof'\n | 'static'\n | 'storage'\n | 'struct'\n | 'super'\n | 'supports'\n | 'switch'\n | 'this'\n | 'true'\n | 'try'\n | 'typedef'\n | 'typeof'\n | 'var'\n | 'view'\n | 'virtual'\n | `address${`[${string}]` | ''}`\n | `bool${`[${string}]` | ''}`\n | `string${`[${string}]` | ''}`\n | `tuple${`[${string}]` | ''}`\n | `bytes${number | ''}${`[${string}]` | ''}`\n | `${'u' | ''}int${number | ''}${`[${string}]` | ''}`\n\n/** @internal */\nexport type IsValidCharacter<character extends string> =\n character extends `${ValidCharacters}${infer tail}`\n ? tail extends ''\n ? true\n : IsValidCharacter<tail>\n : false\n\n// biome-ignore format: no formatting\n/** @internal */\nexport type ValidCharacters =\n // uppercase letters\n | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z'\n // lowercase letters\n | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z'\n // numbers\n | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'\n // special characters\n | '_' | '$'\n\n// Template string inference can absorb `returns`:\n// type Result = `function foo(string) return s (uint256)` extends `function ${string}(${infer Parameters})` ? Parameters : never\n// // ^? type Result = \"string ) return s (uint256\"\n// So we need to validate against `returns` keyword with all combinations of whitespace\n/** @internal */\nexport type InvalidFunctionParameters =\n | `${string}${MangledReturns} (${string}`\n | `${string}) ${MangledReturns}${string}`\n | `${string})${string}${MangledReturns}${string}(${string}`\n\n// r_e_t_u_r_n_s\n/** @internal */\nexport type MangledReturns =\n // Single\n | `r${string}eturns`\n | `re${string}turns`\n | `ret${string}urns`\n | `retu${string}rns`\n | `retur${string}ns`\n | `return${string}s`\n // Double\n // `r_e*`\n | `r${string}e${string}turns`\n | `r${string}et${string}urns`\n | `r${string}etu${string}rns`\n | `r${string}etur${string}ns`\n | `r${string}eturn${string}s`\n // `re_t*`\n | `re${string}t${string}urns`\n | `re${string}tu${string}rns`\n | `re${string}tur${string}ns`\n | `re${string}turn${string}s`\n // `ret_u*`\n | `ret${string}u${string}rns`\n | `ret${string}ur${string}ns`\n | `ret${string}urn${string}s`\n // `retu_r*`\n | `retu${string}r${string}ns`\n | `retu${string}rn${string}s`\n // `retur_n*`\n | `retur${string}n${string}s`\n // Triple\n // `r_e_t*`\n | `r${string}e${string}t${string}urns`\n | `r${string}e${string}tu${string}rns`\n | `r${string}e${string}tur${string}ns`\n | `r${string}e${string}turn${string}s`\n // `re_t_u*`\n | `re${string}t${string}u${string}rns`\n | `re${string}t${string}ur${string}ns`\n | `re${string}t${string}urn${string}s`\n // `ret_u_r*`\n | `ret${string}u${string}r${string}ns`\n | `ret${string}u${string}rn${string}s`\n // `retu_r_n*`\n | `retu${string}r${string}n${string}s`\n // Quadruple\n // `r_e_t_u*`\n | `r${string}e${string}t${string}u${string}rns`\n | `r${string}e${string}t${string}ur${string}ns`\n | `r${string}e${string}t${string}urn${string}s`\n // `re_t_u_r*`\n | `re${string}t${string}u${string}r${string}ns`\n | `re${string}t${string}u${string}rn${string}s`\n // `ret_u_r_n*`\n | `ret${string}u${string}r${string}n${string}s`\n // Quintuple\n // `r_e_t_u_r*`\n | `r${string}e${string}t${string}u${string}r${string}ns`\n | `r${string}e${string}t${string}u${string}rn${string}s`\n // `re_t_u_r_n*`\n | `re${string}t${string}u${string}r${string}n${string}s`\n // Sextuple\n // `r_e_t_u_r_n_s`\n | `r${string}e${string}t${string}u${string}r${string}n${string}s`\n\n/** @internal */\nexport type Widen<type> =\n | ([unknown] extends [type] ? unknown : never)\n | (type extends Function ? type : never)\n | (type extends abitype.ResolvedRegister['bigIntType'] ? bigint : never)\n | (type extends boolean ? boolean : never)\n | (type extends abitype.ResolvedRegister['intType'] ? number : never)\n | (type extends string\n ? type extends abitype.ResolvedRegister['addressType']\n ? abitype.ResolvedRegister['addressType']\n : type extends abitype.ResolvedRegister['bytesType']['inputs']\n ? abitype.ResolvedRegister['bytesType']\n : string\n : never)\n | (type extends readonly [] ? readonly [] : never)\n | (type extends Record<string, unknown>\n ? { [K in keyof type]: Widen<type[K]> }\n : never)\n | (type extends { length: number }\n ? {\n [K in keyof type]: Widen<type[K]>\n } extends infer Val extends readonly unknown[]\n ? readonly [...Val]\n : never\n : never)\n\n/** @internal */\nexport function normalizeSignature(signature: string): string {\n let active = true\n let current = ''\n let level = 0\n let result = ''\n let valid = false\n\n for (let i = 0; i < signature.length; i++) {\n const char = signature[i]!\n\n // If the character is a separator, we want to reactivate.\n if (['(', ')', ','].includes(char)) active = true\n\n // If the character is a \"level\" token, we want to increment/decrement.\n if (char === '(') level++\n if (char === ')') level--\n\n // If we aren't active, we don't want to mutate the result.\n if (!active) continue\n\n // If level === 0, we are at the definition level.\n if (level === 0) {\n if (char === ' ' && ['event', 'function', 'error', ''].includes(result))\n result = ''\n else {\n result += char\n\n // If we are at the end of the definition, we must be finished.\n if (char === ')') {\n valid = true\n break\n }\n }\n\n continue\n }\n\n // Ignore spaces\n if (char === ' ') {\n // If the previous character is a separator, and the current section isn't empty, we want to deactivate.\n if (signature[i - 1] !== ',' && current !== ',' && current !== ',(') {\n current = ''\n active = false\n }\n continue\n }\n\n result += char\n current += char\n }\n\n if (!valid) throw new Errors.BaseError('Unable to normalize signature.')\n\n return result\n}\n\n/** @internal */\nexport declare namespace normalizeSignature {\n export type ErrorType = Errors.BaseError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function isArgOfType(\n arg: unknown,\n abiParameter: AbiParameters.Parameter,\n): boolean {\n const argType = typeof arg\n const abiParameterType = abiParameter.type\n switch (abiParameterType) {\n case 'address':\n return Address.validate(arg as Address.Address, { strict: false })\n case 'bool':\n return argType === 'boolean'\n case 'function':\n return argType === 'string'\n case 'string':\n return argType === 'string'\n default: {\n if (abiParameterType === 'tuple' && 'components' in abiParameter)\n return Object.values(abiParameter.components).every(\n (component, index) => {\n return isArgOfType(\n Object.values(arg as unknown[] | Record<string, unknown>)[index],\n component as AbiParameters.Parameter,\n )\n },\n )\n\n // `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`\n // https://regexr.com/6v8hp\n if (\n /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(\n abiParameterType,\n )\n )\n return argType === 'number' || argType === 'bigint'\n\n // `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`\n // https://regexr.com/6va55\n if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType))\n return argType === 'string' || arg instanceof Uint8Array\n\n // fixed-length (`<type>[M]`) and dynamic (`<type>[]`) arrays\n // https://regexr.com/6va6i\n if (/[a-z]+[1-9]{0,3}(\\[[0-9]{0,}\\])+$/.test(abiParameterType)) {\n return (\n Array.isArray(arg) &&\n arg.every((x: unknown) =>\n isArgOfType(x, {\n ...abiParameter,\n // Pop off `[]` or `[M]` from end of type\n type: abiParameterType.replace(/(\\[[0-9]{0,}\\])$/, ''),\n } as AbiParameters.Parameter),\n )\n )\n }\n\n return false\n }\n }\n}\n\n/** @internal */\nexport function getAmbiguousTypes(\n sourceParameters: readonly AbiParameters.Parameter[],\n targetParameters: readonly AbiParameters.Parameter[],\n args: ExtractArgs,\n): AbiParameters.Parameter['type'][] | undefined {\n for (const parameterIndex in sourceParameters) {\n const sourceParameter = sourceParameters[parameterIndex]!\n const targetParameter = targetParameters[parameterIndex]!\n\n if (\n sourceParameter.type === 'tuple' &&\n targetParameter.type === 'tuple' &&\n 'components' in sourceParameter &&\n 'components' in targetParameter\n )\n return getAmbiguousTypes(\n sourceParameter.components,\n targetParameter.components,\n (args as any)[parameterIndex],\n )\n\n const types = [sourceParameter.type, targetParameter.type]\n\n const ambiguous = (() => {\n if (types.includes('address') && types.includes('bytes20')) return true\n if (types.includes('address') && types.includes('string'))\n return Address.validate(args[parameterIndex] as Address.Address, {\n strict: false,\n })\n if (types.includes('address') && types.includes('bytes'))\n return Address.validate(args[parameterIndex] as Address.Address, {\n strict: false,\n })\n return false\n })()\n\n if (ambiguous) return types\n }\n\n return\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/abiItem.js'\nimport type { UnionCompute } from './internal/types.js'\n\n/** Root type for an item on an {@link ox#Abi.Abi}. */\nexport type AbiItem = Abi.Abi[number]\n\n/**\n * Extracts an {@link ox#AbiItem.AbiItem} item from an {@link ox#Abi.Abi}, given a name.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'error Foo(string)',\n * 'function foo(string)',\n * 'event Bar(uint256)',\n * ])\n *\n * type Foo = AbiItem.FromAbi<typeof abi, 'Foo'>\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n */\nexport type FromAbi<\n abi extends Abi.Abi,\n name extends ExtractNames<abi>,\n> = Extract<abi[number], { name: name }>\n\n/**\n * Extracts the names of all {@link ox#AbiItem.AbiItem} items in an {@link ox#Abi.Abi}.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'error Foo(string)',\n * 'function foo(string)',\n * 'event Bar(uint256)',\n * ])\n *\n * type names = AbiItem.Name<typeof abi>\n * // ^?\n *\n * ```\n */\nexport type Name<abi extends Abi.Abi | readonly unknown[] = Abi.Abi> =\n abi extends Abi.Abi ? ExtractNames<abi> : string\n\nexport type ExtractNames<abi extends Abi.Abi> = Extract<\n abi[number],\n { name: string }\n>['name']\n\n/**\n * Formats an {@link ox#AbiItem.AbiItem} into a **Human Readable ABI Item**.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const formatted = AbiItem.format({\n * type: 'function',\n * name: 'approve',\n * stateMutability: 'nonpayable',\n * inputs: [\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ],\n * outputs: [{ type: 'bool' }],\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiItem - The ABI Item to format.\n * @returns The formatted ABI Item .\n */\nexport function format<const abiItem extends AbiItem>(\n abiItem: abiItem | AbiItem,\n): abitype.FormatAbiItem<abiItem> {\n return abitype.formatAbiItem(abiItem) as never\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses an arbitrary **JSON ABI Item** or **Human Readable ABI Item** into a typed {@link ox#AbiItem.AbiItem}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from({\n * type: 'function',\n * name: 'approve',\n * stateMutability: 'nonpayable',\n * inputs: [\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ],\n * outputs: [{ type: 'bool' }],\n * })\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from(\n * 'function approve(address spender, uint256 amount) returns (bool)' // [!code hl]\n * )\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const abiItem = AbiItem.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'function approve(Foo foo) returns (bool)',\n * ])\n *\n * abiItem\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiItem - The ABI Item to parse.\n * @returns The typed ABI Item.\n */\nexport function from<\n const abiItem extends AbiItem | string | readonly string[],\n>(\n abiItem: (abiItem | AbiItem | string | readonly string[]) &\n (\n | (abiItem extends string ? internal.Signature<abiItem> : never)\n | (abiItem extends readonly string[]\n ? internal.Signatures<abiItem>\n : never)\n | AbiItem\n ),\n options: from.Options = {},\n): from.ReturnType<abiItem> {\n const { prepare = true } = options\n const item = (() => {\n if (Array.isArray(abiItem)) return abitype.parseAbiItem(abiItem)\n if (typeof abiItem === 'string')\n return abitype.parseAbiItem(abiItem as never)\n return abiItem\n })() as AbiItem\n return {\n ...item,\n ...(prepare ? { hash: getSignatureHash(item) } : {}),\n } as never\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether or not to prepare the extracted item (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n }\n\n type ReturnType<abiItem extends AbiItem | string | readonly string[]> =\n abiItem extends string\n ? abitype.ParseAbiItem<abiItem>\n : abiItem extends readonly string[]\n ? abitype.ParseAbiItem<abiItem>\n : abiItem\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Extracts an {@link ox#AbiItem.AbiItem} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ABI Items can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiItem.fromAbi(abi, 'Transfer') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Extracting by Selector\n *\n * ABI Items can be extract by their selector when {@link ox#Hex.Hex} is provided to `name`.\n *\n * ```ts twoslash\n * import { Abi, AbiItem } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n * const item = AbiItem.fromAbi(abi, '0x095ea7b3') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * :::note\n *\n * Extracting via a hex selector is useful when extracting an ABI Item from an `eth_call` RPC response,\n * a Transaction `input`, or from Event Log `topics`.\n *\n * :::\n *\n * @param abi - The ABI to extract from.\n * @param name - The name (or selector) of the ABI item to extract.\n * @param options - Extraction options.\n * @returns The ABI item.\n */\nexport function fromAbi<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name<abi>,\n const args extends internal.ExtractArgs<abi, name> | undefined = undefined,\n //\n allNames = Name<abi>,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n options?: fromAbi.Options<abi, name, args>,\n): fromAbi.ReturnType<abi, name, args> {\n const { args = [], prepare = true } = (options ??\n {}) as unknown as fromAbi.Options\n\n const isSelector = Hex.validate(name, { strict: false })\n const abiItems = (abi as Abi.Abi).filter((abiItem) => {\n if (isSelector) {\n if (abiItem.type === 'function' || abiItem.type === 'error')\n return getSelector(abiItem) === Hex.slice(name, 0, 4)\n if (abiItem.type === 'event') return getSignatureHash(abiItem) === name\n return false\n }\n return 'name' in abiItem && abiItem.name === name\n })\n\n if (abiItems.length === 0) throw new NotFoundError({ name: name as string })\n if (abiItems.length === 1)\n return {\n ...abiItems[0],\n ...(prepare ? { hash: getSignatureHash(abiItems[0]!) } : {}),\n } as never\n\n let matchedAbiItem: AbiItem | undefined = undefined\n for (const abiItem of abiItems) {\n if (!('inputs' in abiItem)) continue\n if (!args || args.length === 0) {\n if (!abiItem.inputs || abiItem.inputs.length === 0)\n return {\n ...abiItem,\n ...(prepare ? { hash: getSignatureHash(abiItem) } : {}),\n } as never\n continue\n }\n if (!abiItem.inputs) continue\n if (abiItem.inputs.length === 0) continue\n if (abiItem.inputs.length !== args.length) continue\n const matched = args.every((arg, index) => {\n const abiParameter = 'inputs' in abiItem && abiItem.inputs![index]\n if (!abiParameter) return false\n return internal.isArgOfType(arg, abiParameter)\n })\n if (matched) {\n // Check for ambiguity against already matched parameters (e.g. `address` vs `bytes20`).\n if (\n matchedAbiItem &&\n 'inputs' in matchedAbiItem &&\n matchedAbiItem.inputs\n ) {\n const ambiguousTypes = internal.getAmbiguousTypes(\n abiItem.inputs,\n matchedAbiItem.inputs,\n args as readonly unknown[],\n )\n if (ambiguousTypes)\n throw new AmbiguityError(\n {\n abiItem,\n type: ambiguousTypes[0]!,\n },\n {\n abiItem: matchedAbiItem,\n type: ambiguousTypes[1]!,\n },\n )\n }\n\n matchedAbiItem = abiItem\n }\n }\n\n const abiItem = (() => {\n if (matchedAbiItem) return matchedAbiItem\n const [abiItem, ...overloads] = abiItems\n return { ...abiItem!, overloads }\n })()\n\n if (!abiItem) throw new NotFoundError({ name: name as string })\n return {\n ...abiItem,\n ...(prepare ? { hash: getSignatureHash(abiItem) } : {}),\n } as never\n}\n\nexport declare namespace fromAbi {\n type Options<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends Name<abi> = Name<abi>,\n args extends\n | internal.ExtractArgs<abi, name>\n | undefined = internal.ExtractArgs<abi, name>,\n ///\n allArgs = internal.ExtractArgs<abi, name>,\n > = {\n /**\n * Whether or not to prepare the extracted item (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n } & UnionCompute<\n readonly [] extends allArgs\n ? {\n args?:\n | allArgs // show all options\n // infer value, widen inferred value of `args` conditionally to match `allArgs`\n | (abi extends Abi.Abi\n ? args extends allArgs\n ? internal.Widen<args>\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (internal.Widen<args> & (args extends allArgs ? unknown : never)) // infer value, widen inferred value of `args` match `allArgs` (e.g. avoid union `args: readonly [123n] | readonly [bigint]`)\n | undefined\n }\n >\n\n type ReturnType<\n abi extends Abi.Abi | readonly unknown[] = Abi.Abi,\n name extends Name<abi> = Name<abi>,\n args extends\n | internal.ExtractArgs<abi, name>\n | undefined = internal.ExtractArgs<abi, name>,\n fallback = AbiItem,\n > = abi extends Abi.Abi\n ? Abi.Abi extends abi\n ? fallback\n : internal.ExtractForArgs<\n abi,\n name,\n args extends internal.ExtractArgs<abi, name>\n ? args\n : internal.ExtractArgs<abi, name>\n >\n : fallback\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes the [4-byte selector](https://solidity-by-example.org/function-selector/) for an {@link ox#AbiItem.AbiItem}.\n *\n * Useful for computing function selectors for calldata.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const selector = AbiItem.getSelector('function ownerOf(uint256 tokenId)')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const selector = AbiItem.getSelector({\n * inputs: [{ type: 'uint256' }],\n * name: 'ownerOf',\n * outputs: [],\n * stateMutability: 'view',\n * type: 'function'\n * })\n * // @log: '0x6352211e'\n * ```\n *\n * @param abiItem - The ABI item to compute the selector for. Can be a signature or an ABI item for an error, event, function, etc.\n * @returns The first 4 bytes of the {@link ox#Hash.(keccak256:function)} hash of the function signature.\n */\nexport function getSelector(abiItem: string | AbiItem): Hex.Hex {\n return Hex.slice(getSignatureHash(abiItem), 0, 4)\n}\n\nexport declare namespace getSelector {\n type ErrorType =\n | getSignatureHash.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the stringified signature for a given {@link ox#AbiItem.AbiItem}.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const signature = AbiItem.getSignature('function ownerOf(uint256 tokenId)')\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const signature = AbiItem.getSignature({\n * name: 'ownerOf',\n * type: 'function',\n * inputs: [{ name: 'tokenId', type: 'uint256' }],\n * outputs: [],\n * stateMutability: 'view',\n * })\n * // @log: 'ownerOf(uint256)'\n * ```\n *\n * @param abiItem - The ABI Item to compute the signature for.\n * @returns The stringified signature of the ABI Item.\n */\nexport function getSignature(abiItem: string | AbiItem): string {\n const signature = (() => {\n if (typeof abiItem === 'string') return abiItem\n return abitype.formatAbiItem(abiItem)\n })()\n return internal.normalizeSignature(signature)\n}\n\nexport declare namespace getSignature {\n type ErrorType =\n | internal.normalizeSignature.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the signature hash for an {@link ox#AbiItem.AbiItem}.\n *\n * Useful for computing Event Topic values.\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const hash = AbiItem.getSignatureHash('event Transfer(address indexed from, address indexed to, uint256 amount)')\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiItem } from 'ox'\n *\n * const hash = AbiItem.getSignatureHash({\n * name: 'Transfer',\n * type: 'event',\n * inputs: [\n * { name: 'from', type: 'address', indexed: true },\n * { name: 'to', type: 'address', indexed: true },\n * { name: 'amount', type: 'uint256', indexed: false },\n * ],\n * })\n * // @log: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n * ```\n *\n * @param abiItem - The ABI Item to compute the signature hash for.\n * @returns The {@link ox#Hash.(keccak256:function)} hash of the ABI item's signature.\n */\nexport function getSignatureHash(abiItem: string | AbiItem): Hex.Hex {\n if (typeof abiItem !== 'string' && 'hash' in abiItem && abiItem.hash)\n return abiItem.hash as Hex.Hex\n return Hash.keccak256(Hex.fromString(getSignature(abiItem)))\n}\n\nexport declare namespace getSignatureHash {\n type ErrorType =\n | getSignature.ErrorType\n | Hash.keccak256.ErrorType\n | Hex.fromString.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Throws when ambiguous types are found on overloaded ABI items.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from(['function foo(address)', 'function foo(bytes20)'])\n * AbiFunction.fromAbi(foo, 'foo', {\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // @error: AbiItem.AmbiguityError: Found ambiguous types in overloaded ABI Items.\n * // @error: `bytes20` in `foo(bytes20)`, and\n * // @error: `address` in `foo(address)`\n * // @error: These types encode differently and cannot be distinguished at runtime.\n * // @error: Remove one of the ambiguous items in the ABI.\n * ```\n *\n * ### Solution\n *\n * Remove one of the ambiguous types from the ABI.\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function foo(bytes20)' // [!code --]\n * ])\n * AbiFunction.fromAbi(foo, 'foo', {\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // @error: AbiItem.AmbiguityError: Found ambiguous types in overloaded ABI Items.\n * // @error: `bytes20` in `foo(bytes20)`, and\n * // @error: `address` in `foo(address)`\n * // @error: These types encode differently and cannot be distinguished at runtime.\n * // @error: Remove one of the ambiguous items in the ABI.\n * ```\n */\nexport class AmbiguityError extends Errors.BaseError {\n override readonly name = 'AbiItem.AmbiguityError'\n constructor(\n x: { abiItem: Abi.Abi[number]; type: string },\n y: { abiItem: Abi.Abi[number]; type: string },\n ) {\n super('Found ambiguous types in overloaded ABI Items.', {\n metaMessages: [\n // TODO: abitype to add support for signature-formatted ABI items.\n `\\`${x.type}\\` in \\`${internal.normalizeSignature(abitype.formatAbiItem(x.abiItem))}\\`, and`,\n `\\`${y.type}\\` in \\`${internal.normalizeSignature(abitype.formatAbiItem(y.abiItem))}\\``,\n '',\n 'These types encode differently and cannot be distinguished at runtime.',\n 'Remove one of the ambiguous items in the ABI.',\n ],\n })\n }\n}\n\n/**\n * Throws when an ABI item is not found in the ABI.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, 'baz')\n * // @error: AbiItem.NotFoundError: ABI function with name \"baz\" not found.\n * ```\n *\n * ### Solution\n *\n * Ensure the ABI item exists on the ABI.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)',\n * 'function baz(bool)' // [!code ++]\n * ])\n * AbiFunction.fromAbi(foo, 'baz')\n * ```\n */\nexport class NotFoundError extends Errors.BaseError {\n override readonly name = 'AbiItem.NotFoundError'\n constructor({\n name,\n data,\n type = 'item',\n }: {\n name?: string | undefined\n data?: Hex.Hex | undefined\n type?: string | undefined\n }) {\n const selector = (() => {\n if (name) return ` with name \"${name}\"`\n if (data) return ` with data \"${data}\"`\n return ''\n })()\n super(`ABI ${type}${selector} not found.`)\n }\n}\n\n/**\n * Throws when the selector size is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, '0xaaa')\n * // @error: AbiItem.InvalidSelectorSizeError: Selector size is invalid. Expected 4 bytes. Received 2 bytes (\"0xaaa\").\n * ```\n *\n * ### Solution\n *\n * Ensure the selector size is 4 bytes.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const foo = Abi.from([\n * 'function foo(address)',\n * 'function bar(uint)'\n * ])\n * AbiFunction.fromAbi(foo, '0x7af82b1a')\n * ```\n */\nexport class InvalidSelectorSizeError extends Errors.BaseError {\n override readonly name = 'AbiItem.InvalidSelectorSizeError'\n constructor({ data }: { data: Hex.Hex }) {\n super(\n `Selector size is invalid. Expected 4 bytes. Received ${Hex.size(data)} bytes (\"${data}\").`,\n )\n }\n}\n","export const arrayRegex = /^(.*)\\[([0-9]*)\\]$/\n\n// `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`\n// https://regexr.com/6va55\nexport const bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/\n\n// `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`\n// https://regexr.com/6v8hp\nexport const integerRegex =\n /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/\n\nexport const maxInt8 = 2n ** (8n - 1n) - 1n\nexport const maxInt16 = 2n ** (16n - 1n) - 1n\nexport const maxInt24 = 2n ** (24n - 1n) - 1n\nexport const maxInt32 = 2n ** (32n - 1n) - 1n\nexport const maxInt40 = 2n ** (40n - 1n) - 1n\nexport const maxInt48 = 2n ** (48n - 1n) - 1n\nexport const maxInt56 = 2n ** (56n - 1n) - 1n\nexport const maxInt64 = 2n ** (64n - 1n) - 1n\nexport const maxInt72 = 2n ** (72n - 1n) - 1n\nexport const maxInt80 = 2n ** (80n - 1n) - 1n\nexport const maxInt88 = 2n ** (88n - 1n) - 1n\nexport const maxInt96 = 2n ** (96n - 1n) - 1n\nexport const maxInt104 = 2n ** (104n - 1n) - 1n\nexport const maxInt112 = 2n ** (112n - 1n) - 1n\nexport const maxInt120 = 2n ** (120n - 1n) - 1n\nexport const maxInt128 = 2n ** (128n - 1n) - 1n\nexport const maxInt136 = 2n ** (136n - 1n) - 1n\nexport const maxInt144 = 2n ** (144n - 1n) - 1n\nexport const maxInt152 = 2n ** (152n - 1n) - 1n\nexport const maxInt160 = 2n ** (160n - 1n) - 1n\nexport const maxInt168 = 2n ** (168n - 1n) - 1n\nexport const maxInt176 = 2n ** (176n - 1n) - 1n\nexport const maxInt184 = 2n ** (184n - 1n) - 1n\nexport const maxInt192 = 2n ** (192n - 1n) - 1n\nexport const maxInt200 = 2n ** (200n - 1n) - 1n\nexport const maxInt208 = 2n ** (208n - 1n) - 1n\nexport const maxInt216 = 2n ** (216n - 1n) - 1n\nexport const maxInt224 = 2n ** (224n - 1n) - 1n\nexport const maxInt232 = 2n ** (232n - 1n) - 1n\nexport const maxInt240 = 2n ** (240n - 1n) - 1n\nexport const maxInt248 = 2n ** (248n - 1n) - 1n\nexport const maxInt256 = 2n ** (256n - 1n) - 1n\n\nexport const minInt8 = -(2n ** (8n - 1n))\nexport const minInt16 = -(2n ** (16n - 1n))\nexport const minInt24 = -(2n ** (24n - 1n))\nexport const minInt32 = -(2n ** (32n - 1n))\nexport const minInt40 = -(2n ** (40n - 1n))\nexport const minInt48 = -(2n ** (48n - 1n))\nexport const minInt56 = -(2n ** (56n - 1n))\nexport const minInt64 = -(2n ** (64n - 1n))\nexport const minInt72 = -(2n ** (72n - 1n))\nexport const minInt80 = -(2n ** (80n - 1n))\nexport const minInt88 = -(2n ** (88n - 1n))\nexport const minInt96 = -(2n ** (96n - 1n))\nexport const minInt104 = -(2n ** (104n - 1n))\nexport const minInt112 = -(2n ** (112n - 1n))\nexport const minInt120 = -(2n ** (120n - 1n))\nexport const minInt128 = -(2n ** (128n - 1n))\nexport const minInt136 = -(2n ** (136n - 1n))\nexport const minInt144 = -(2n ** (144n - 1n))\nexport const minInt152 = -(2n ** (152n - 1n))\nexport const minInt160 = -(2n ** (160n - 1n))\nexport const minInt168 = -(2n ** (168n - 1n))\nexport const minInt176 = -(2n ** (176n - 1n))\nexport const minInt184 = -(2n ** (184n - 1n))\nexport const minInt192 = -(2n ** (192n - 1n))\nexport const minInt200 = -(2n ** (200n - 1n))\nexport const minInt208 = -(2n ** (208n - 1n))\nexport const minInt216 = -(2n ** (216n - 1n))\nexport const minInt224 = -(2n ** (224n - 1n))\nexport const minInt232 = -(2n ** (232n - 1n))\nexport const minInt240 = -(2n ** (240n - 1n))\nexport const minInt248 = -(2n ** (248n - 1n))\nexport const minInt256 = -(2n ** (256n - 1n))\n\nexport const maxUint8 = 2n ** 8n - 1n\nexport const maxUint16 = 2n ** 16n - 1n\nexport const maxUint24 = 2n ** 24n - 1n\nexport const maxUint32 = 2n ** 32n - 1n\nexport const maxUint40 = 2n ** 40n - 1n\nexport const maxUint48 = 2n ** 48n - 1n\nexport const maxUint56 = 2n ** 56n - 1n\nexport const maxUint64 = 2n ** 64n - 1n\nexport const maxUint72 = 2n ** 72n - 1n\nexport const maxUint80 = 2n ** 80n - 1n\nexport const maxUint88 = 2n ** 88n - 1n\nexport const maxUint96 = 2n ** 96n - 1n\nexport const maxUint104 = 2n ** 104n - 1n\nexport const maxUint112 = 2n ** 112n - 1n\nexport const maxUint120 = 2n ** 120n - 1n\nexport const maxUint128 = 2n ** 128n - 1n\nexport const maxUint136 = 2n ** 136n - 1n\nexport const maxUint144 = 2n ** 144n - 1n\nexport const maxUint152 = 2n ** 152n - 1n\nexport const maxUint160 = 2n ** 160n - 1n\nexport const maxUint168 = 2n ** 168n - 1n\nexport const maxUint176 = 2n ** 176n - 1n\nexport const maxUint184 = 2n ** 184n - 1n\nexport const maxUint192 = 2n ** 192n - 1n\nexport const maxUint200 = 2n ** 200n - 1n\nexport const maxUint208 = 2n ** 208n - 1n\nexport const maxUint216 = 2n ** 216n - 1n\nexport const maxUint224 = 2n ** 224n - 1n\nexport const maxUint232 = 2n ** 232n - 1n\nexport const maxUint240 = 2n ** 240n - 1n\nexport const maxUint248 = 2n ** 248n - 1n\nexport const maxUint256 = 2n ** 256n - 1n\n","import type {\n AbiParameter,\n AbiParameterKind,\n AbiParameterToPrimitiveType,\n AbiParametersToPrimitiveTypes,\n} from 'abitype'\nimport * as AbiParameters from '../AbiParameters.js'\nimport * as Address from '../Address.js'\nimport * as Bytes from '../Bytes.js'\nimport * as Errors from '../Errors.js'\nimport * as Hex from '../Hex.js'\nimport { integerRegex } from '../Solidity.js'\nimport type * as Cursor from './cursor.js'\nimport type { Compute, IsNarrowable, UnionToIntersection } from './types.js'\n\n/** @internal */\nexport type ParameterToPrimitiveType<\n abiParameter extends AbiParameter | { name: string; type: unknown },\n abiParameterKind extends AbiParameterKind = AbiParameterKind,\n> = AbiParameterToPrimitiveType<abiParameter, abiParameterKind>\n\n/** @internal */\nexport type PreparedParameter = { dynamic: boolean; encoded: Hex.Hex }\n\n/** @internal */\nexport type ToObject<\n parameters extends readonly AbiParameter[],\n kind extends AbiParameterKind = AbiParameterKind,\n> = IsNarrowable<parameters, AbiParameters.AbiParameters> extends true\n ? Compute<\n UnionToIntersection<\n {\n [index in keyof parameters]: parameters[index] extends {\n name: infer name extends string\n }\n ? {\n [key in name]: AbiParameterToPrimitiveType<\n parameters[index],\n kind\n >\n }\n : {\n [key in index]: AbiParameterToPrimitiveType<\n parameters[index],\n kind\n >\n }\n }[number]\n >\n >\n : unknown\n\n/** @internal */\nexport type ToPrimitiveTypes<\n abiParameters extends readonly AbiParameter[],\n abiParameterKind extends AbiParameterKind = AbiParameterKind,\n> = AbiParametersToPrimitiveTypes<abiParameters, abiParameterKind>\n\n/** @internal */\nexport type Tuple = ParameterToPrimitiveType<TupleAbiParameter>\n\n/** @internal */\nexport function decodeParameter(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n options: { checksumAddress?: boolean | undefined; staticPosition: number },\n) {\n const { checksumAddress, staticPosition } = options\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return decodeArray(\n cursor,\n { ...param, type },\n { checksumAddress, length, staticPosition },\n )\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param as TupleAbiParameter, {\n checksumAddress,\n staticPosition,\n })\n if (param.type === 'address')\n return decodeAddress(cursor, { checksum: checksumAddress })\n if (param.type === 'bool') return decodeBool(cursor)\n if (param.type.startsWith('bytes'))\n return decodeBytes(cursor, param, { staticPosition })\n if (param.type.startsWith('uint') || param.type.startsWith('int'))\n return decodeNumber(cursor, param)\n if (param.type === 'string') return decodeString(cursor, { staticPosition })\n throw new AbiParameters.InvalidTypeError(param.type)\n}\n\nexport declare namespace decodeParameter {\n type ErrorType =\n | decodeArray.ErrorType\n | decodeTuple.ErrorType\n | decodeAddress.ErrorType\n | decodeBool.ErrorType\n | decodeBytes.ErrorType\n | decodeNumber.ErrorType\n | decodeString.ErrorType\n | AbiParameters.InvalidTypeError\n | Errors.GlobalErrorType\n}\n\nconst sizeOfLength = 32\nconst sizeOfOffset = 32\n\n/** @internal */\nexport function decodeAddress(\n cursor: Cursor.Cursor,\n options: { checksum?: boolean | undefined } = {},\n) {\n const { checksum = false } = options\n const value = cursor.readBytes(32)\n const wrap = (address: Hex.Hex) =>\n checksum ? Address.checksum(address) : address\n return [wrap(Hex.fromBytes(Bytes.slice(value, -20))), 32]\n}\n\nexport declare namespace decodeAddress {\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Bytes.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeArray(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n options: {\n checksumAddress?: boolean | undefined\n length: number | null\n staticPosition: number\n },\n) {\n const { checksumAddress, length, staticPosition } = options\n\n // If the length of the array is not known in advance (dynamic array),\n // this means we will need to wonder off to the pointer and decode.\n if (!length) {\n // Dealing with a dynamic type, so get the offset of the array data.\n const offset = Bytes.toNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n const startOfData = start + sizeOfLength\n\n // Get the length of the array from the offset.\n cursor.setPosition(start)\n const length = Bytes.toNumber(cursor.readBytes(sizeOfLength))\n\n // Check if the array has any dynamic children.\n const dynamicChild = hasDynamicChild(param)\n\n let consumed = 0\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n // If any of the children is dynamic, then all elements will be offset pointer, thus size of one slot (32 bytes).\n // Otherwise, elements will be the size of their encoding (consumed bytes).\n cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed))\n const [data, consumed_] = decodeParameter(cursor, param, {\n checksumAddress,\n staticPosition: startOfData,\n })\n consumed += consumed_\n value.push(data)\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\n }\n\n // If the length of the array is known in advance,\n // and the length of an element deeply nested in the array is not known,\n // we need to decode the offset of the array data.\n if (hasDynamicChild(param)) {\n // Dealing with dynamic types, so get the offset of the array data.\n const offset = Bytes.toNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n // Move cursor along to the next slot (next offset pointer).\n cursor.setPosition(start + i * 32)\n const [data] = decodeParameter(cursor, param, {\n checksumAddress,\n staticPosition: start,\n })\n value.push(data)\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\n }\n\n // If the length of the array is known in advance and the array is deeply static,\n // then we can just decode each element in sequence.\n let consumed = 0\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n const [data, consumed_] = decodeParameter(cursor, param, {\n checksumAddress,\n staticPosition: staticPosition + consumed,\n })\n consumed += consumed_\n value.push(data)\n }\n return [value, consumed]\n}\n\nexport declare namespace decodeArray {\n type ErrorType = Bytes.toNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeBool(cursor: Cursor.Cursor) {\n return [Bytes.toBoolean(cursor.readBytes(32), { size: 32 }), 32]\n}\n\nexport declare namespace decodeBool {\n type ErrorType = Bytes.toBoolean.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeBytes(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n { staticPosition }: { staticPosition: number },\n) {\n const [_, size] = param.type.split('bytes')\n if (!size) {\n // Dealing with dynamic types, so get the offset of the bytes data.\n const offset = Bytes.toNumber(cursor.readBytes(32))\n\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset)\n\n const length = Bytes.toNumber(cursor.readBytes(32))\n\n // If there is no length, we have zero data.\n if (length === 0) {\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return ['0x', 32]\n }\n\n const data = cursor.readBytes(length)\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [Hex.fromBytes(data), 32]\n }\n\n const value = Hex.fromBytes(cursor.readBytes(Number.parseInt(size), 32))\n return [value, 32]\n}\n\nexport declare namespace decodeBytes {\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Bytes.toNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeNumber(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n) {\n const signed = param.type.startsWith('int')\n const size = Number.parseInt(param.type.split('int')[1] || '256')\n const value = cursor.readBytes(32)\n return [\n size > 48\n ? Bytes.toBigInt(value, { signed })\n : Bytes.toNumber(value, { signed }),\n 32,\n ]\n}\n\nexport declare namespace decodeNumber {\n type ErrorType =\n | Bytes.toNumber.ErrorType\n | Bytes.toBigInt.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport type TupleAbiParameter = AbiParameters.Parameter & {\n components: readonly AbiParameters.Parameter[]\n}\n\n/** @internal */\nexport function decodeTuple(\n cursor: Cursor.Cursor,\n param: TupleAbiParameter,\n options: { checksumAddress?: boolean | undefined; staticPosition: number },\n) {\n const { checksumAddress, staticPosition } = options\n\n // Tuples can have unnamed components (i.e. they are arrays), so we must\n // determine whether the tuple is named or unnamed. In the case of a named\n // tuple, the value will be an object where each property is the name of the\n // component. In the case of an unnamed tuple, the value will be an array.\n const hasUnnamedChild =\n param.components.length === 0 || param.components.some(({ name }) => !name)\n\n // Initialize the value to an object or an array, depending on whether the\n // tuple is named or unnamed.\n const value: any = hasUnnamedChild ? [] : {}\n let consumed = 0\n\n // If the tuple has a dynamic child, we must first decode the offset to the\n // tuple data.\n if (hasDynamicChild(param)) {\n // Dealing with dynamic types, so get the offset of the tuple data.\n const offset = Bytes.toNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of referencing slot + offset.\n const start = staticPosition + offset\n\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i]!\n cursor.setPosition(start + consumed)\n const [data, consumed_] = decodeParameter(cursor, component, {\n checksumAddress,\n staticPosition: start,\n })\n consumed += consumed_\n value[hasUnnamedChild ? i : component?.name!] = data\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\n }\n\n // If the tuple has static children, we can just decode each component\n // in sequence.\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i]!\n const [data, consumed_] = decodeParameter(cursor, component, {\n checksumAddress,\n staticPosition,\n })\n value[hasUnnamedChild ? i : component?.name!] = data\n consumed += consumed_\n }\n return [value, consumed]\n}\n\nexport declare namespace decodeTuple {\n type ErrorType = Bytes.toNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeString(\n cursor: Cursor.Cursor,\n { staticPosition }: { staticPosition: number },\n) {\n // Get offset to start of string data.\n const offset = Bytes.toNumber(cursor.readBytes(32))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n cursor.setPosition(start)\n\n const length = Bytes.toNumber(cursor.readBytes(32))\n\n // If there is no length, we have zero data (empty string).\n if (length === 0) {\n cursor.setPosition(staticPosition + 32)\n return ['', 32]\n }\n\n const data = cursor.readBytes(length, 32)\n const value = Bytes.toString(Bytes.trimLeft(data))\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n\n return [value, 32]\n}\n\nexport declare namespace decodeString {\n type ErrorType =\n | Bytes.toNumber.ErrorType\n | Bytes.toString.ErrorType\n | Bytes.trimLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function prepareParameters<\n const parameters extends AbiParameters.AbiParameters,\n>({\n checksumAddress,\n parameters,\n values,\n}: {\n checksumAddress?: boolean | undefined\n parameters: parameters\n values: parameters extends AbiParameters.AbiParameters\n ? ToPrimitiveTypes<parameters>\n : never\n}) {\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < parameters.length; i++) {\n preparedParameters.push(\n prepareParameter({\n checksumAddress,\n parameter: parameters[i]!,\n value: values[i],\n }),\n )\n }\n return preparedParameters\n}\n\n/** @internal */\nexport declare namespace prepareParameters {\n type ErrorType = prepareParameter.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function prepareParameter<\n const parameter extends AbiParameters.Parameter,\n>({\n checksumAddress = false,\n parameter: parameter_,\n value,\n}: {\n parameter: parameter\n value: parameter extends AbiParameters.Parameter\n ? ParameterToPrimitiveType<parameter>\n : never\n checksumAddress?: boolean | undefined\n}): PreparedParameter {\n const parameter = parameter_ as AbiParameters.Parameter\n\n const arrayComponents = getArrayComponents(parameter.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return encodeArray(value, {\n checksumAddress,\n length,\n parameter: {\n ...parameter,\n type,\n },\n })\n }\n if (parameter.type === 'tuple') {\n return encodeTuple(value as unknown as Tuple, {\n checksumAddress,\n parameter: parameter as TupleAbiParameter,\n })\n }\n if (parameter.type === 'address') {\n return encodeAddress(value as unknown as Hex.Hex, {\n checksum: checksumAddress,\n })\n }\n if (parameter.type === 'bool') {\n return encodeBoolean(value as unknown as boolean)\n }\n if (parameter.type.startsWith('uint') || parameter.type.startsWith('int')) {\n const signed = parameter.type.startsWith('int')\n const [, , size = '256'] = integerRegex.exec(parameter.type) ?? []\n return encodeNumber(value as unknown as number, {\n signed,\n size: Number(size),\n })\n }\n if (parameter.type.startsWith('bytes')) {\n return encodeBytes(value as unknown as Hex.Hex, { type: parameter.type })\n }\n if (parameter.type === 'string') {\n return encodeString(value as unknown as string)\n }\n throw new AbiParameters.InvalidTypeError(parameter.type)\n}\n\n/** @internal */\nexport declare namespace prepareParameter {\n type ErrorType =\n | encodeArray.ErrorType\n | encodeTuple.ErrorType\n | encodeAddress.ErrorType\n | encodeBoolean.ErrorType\n | encodeBytes.ErrorType\n | encodeString.ErrorType\n | AbiParameters.InvalidTypeError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encode(preparedParameters: PreparedParameter[]): Hex.Hex {\n // 1. Compute the size of the static part of the parameters.\n let staticSize = 0\n for (let i = 0; i < preparedParameters.length; i++) {\n const { dynamic, encoded } = preparedParameters[i]!\n if (dynamic) staticSize += 32\n else staticSize += Hex.size(encoded)\n }\n\n // 2. Split the parameters into static and dynamic parts.\n const staticParameters: Hex.Hex[] = []\n const dynamicParameters: Hex.Hex[] = []\n let dynamicSize = 0\n for (let i = 0; i < preparedParameters.length; i++) {\n const { dynamic, encoded } = preparedParameters[i]!\n if (dynamic) {\n staticParameters.push(\n Hex.fromNumber(staticSize + dynamicSize, { size: 32 }),\n )\n dynamicParameters.push(encoded)\n dynamicSize += Hex.size(encoded)\n } else {\n staticParameters.push(encoded)\n }\n }\n\n // 3. Concatenate static and dynamic parts.\n return Hex.concat(...staticParameters, ...dynamicParameters)\n}\n\n/** @internal */\nexport declare namespace encode {\n type ErrorType =\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeAddress(\n value: Hex.Hex,\n options: { checksum: boolean },\n): PreparedParameter {\n const { checksum = false } = options\n Address.assert(value, { strict: checksum })\n return {\n dynamic: false,\n encoded: Hex.padLeft(value.toLowerCase() as Hex.Hex),\n }\n}\n\n/** @internal */\nexport declare namespace encodeAddress {\n type ErrorType =\n | Address.assert.ErrorType\n | Hex.padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeArray<const parameter extends AbiParameters.Parameter>(\n value: ParameterToPrimitiveType<parameter>,\n options: {\n checksumAddress?: boolean | undefined\n length: number | null\n parameter: parameter\n },\n): PreparedParameter {\n const { checksumAddress, length, parameter } = options\n\n const dynamic = length === null\n\n if (!Array.isArray(value)) throw new AbiParameters.InvalidArrayError(value)\n if (!dynamic && value.length !== length)\n throw new AbiParameters.ArrayLengthMismatchError({\n expectedLength: length!,\n givenLength: value.length,\n type: `${parameter.type}[${length}]`,\n })\n\n let dynamicChild = false\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < value.length; i++) {\n const preparedParam = prepareParameter({\n checksumAddress,\n parameter,\n value: value[i],\n })\n if (preparedParam.dynamic) dynamicChild = true\n preparedParameters.push(preparedParam)\n }\n\n if (dynamic || dynamicChild) {\n const data = encode(preparedParameters)\n if (dynamic) {\n const length = Hex.fromNumber(preparedParameters.length, { size: 32 })\n return {\n dynamic: true,\n encoded:\n preparedParameters.length > 0 ? Hex.concat(length, data) : length,\n }\n }\n if (dynamicChild) return { dynamic: true, encoded: data }\n }\n return {\n dynamic: false,\n encoded: Hex.concat(...preparedParameters.map(({ encoded }) => encoded)),\n }\n}\n\n/** @internal */\nexport declare namespace encodeArray {\n type ErrorType =\n | AbiParameters.InvalidArrayError\n | AbiParameters.ArrayLengthMismatchError\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeBytes(\n value: Hex.Hex,\n { type }: { type: string },\n): PreparedParameter {\n const [, parametersize] = type.split('bytes')\n const bytesSize = Hex.size(value)\n if (!parametersize) {\n let value_ = value\n // If the size is not divisible by 32 bytes, pad the end\n // with empty bytes to the ceiling 32 bytes.\n if (bytesSize % 32 !== 0)\n value_ = Hex.padRight(value_, Math.ceil((value.length - 2) / 2 / 32) * 32)\n return {\n dynamic: true,\n encoded: Hex.concat(\n Hex.padLeft(Hex.fromNumber(bytesSize, { size: 32 })),\n value_,\n ),\n }\n }\n if (bytesSize !== Number.parseInt(parametersize))\n throw new AbiParameters.BytesSizeMismatchError({\n expectedSize: Number.parseInt(parametersize),\n value,\n })\n return { dynamic: false, encoded: Hex.padRight(value) }\n}\n\n/** @internal */\nexport declare namespace encodeBytes {\n type ErrorType =\n | Hex.padLeft.ErrorType\n | Hex.padRight.ErrorType\n | Hex.fromNumber.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeBoolean(value: boolean): PreparedParameter {\n if (typeof value !== 'boolean')\n throw new Errors.BaseError(\n `Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`,\n )\n return { dynamic: false, encoded: Hex.padLeft(Hex.fromBoolean(value)) }\n}\n\n/** @internal */\nexport declare namespace encodeBoolean {\n type ErrorType =\n | Hex.padLeft.ErrorType\n | Hex.fromBoolean.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeNumber(\n value: number,\n { signed, size }: { signed: boolean; size: number },\n): PreparedParameter {\n if (typeof size === 'number') {\n const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n\n const min = signed ? -max - 1n : 0n\n if (value > max || value < min)\n throw new Hex.IntegerOutOfRangeError({\n max: max.toString(),\n min: min.toString(),\n signed,\n size: size / 8,\n value: value.toString(),\n })\n }\n return {\n dynamic: false,\n encoded: Hex.fromNumber(value, {\n size: 32,\n signed,\n }),\n }\n}\n\n/** @internal */\nexport declare namespace encodeNumber {\n type ErrorType = Hex.fromNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeString(value: string): PreparedParameter {\n const hexValue = Hex.fromString(value)\n const partsLength = Math.ceil(Hex.size(hexValue) / 32)\n const parts: Hex.Hex[] = []\n for (let i = 0; i < partsLength; i++) {\n parts.push(Hex.padRight(Hex.slice(hexValue, i * 32, (i + 1) * 32)))\n }\n return {\n dynamic: true,\n encoded: Hex.concat(\n Hex.padRight(Hex.fromNumber(Hex.size(hexValue), { size: 32 })),\n ...parts,\n ),\n }\n}\n\n/** @internal */\nexport declare namespace encodeString {\n type ErrorType =\n | Hex.fromNumber.ErrorType\n | Hex.padRight.ErrorType\n | Hex.slice.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeTuple<\n const parameter extends AbiParameters.Parameter & {\n components: readonly AbiParameters.Parameter[]\n },\n>(\n value: ParameterToPrimitiveType<parameter>,\n options: {\n checksumAddress?: boolean | undefined\n parameter: parameter\n },\n): PreparedParameter {\n const { checksumAddress, parameter } = options\n\n let dynamic = false\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < parameter.components.length; i++) {\n const param_ = parameter.components[i]!\n const index = Array.isArray(value) ? i : param_.name\n const preparedParam = prepareParameter({\n checksumAddress,\n parameter: param_,\n value: (value as any)[index!] as readonly unknown[],\n })\n preparedParameters.push(preparedParam)\n if (preparedParam.dynamic) dynamic = true\n }\n return {\n dynamic,\n encoded: dynamic\n ? encode(preparedParameters)\n : Hex.concat(...preparedParameters.map(({ encoded }) => encoded)),\n }\n}\n\n/** @internal */\nexport declare namespace encodeTuple {\n type ErrorType = Hex.concat.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function getArrayComponents(\n type: string,\n): [length: number | null, innerType: string] | undefined {\n const matches = type.match(/^(.*)\\[(\\d+)?\\]$/)\n return matches\n ? // Return `null` if the array is dynamic.\n [matches[2]! ? Number(matches[2]!) : null, matches[1]!]\n : undefined\n}\n\n/** @internal */\nexport function hasDynamicChild(param: AbiParameters.Parameter) {\n const { type } = param\n if (type === 'string') return true\n if (type === 'bytes') return true\n if (type.endsWith('[]')) return true\n\n if (type === 'tuple') return (param as any).components?.some(hasDynamicChild)\n\n const arrayComponents = getArrayComponents(param.type)\n if (\n arrayComponents &&\n hasDynamicChild({\n ...param,\n type: arrayComponents[1],\n } as AbiParameters.Parameter)\n )\n return true\n\n return false\n}\n","import * as abitype from 'abitype'\nimport * as Address from './Address.js'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Solidity from './Solidity.js'\nimport * as internal from './internal/abiParameters.js'\nimport * as Cursor from './internal/cursor.js'\n\n/** Root type for ABI parameters. */\nexport type AbiParameters = readonly abitype.AbiParameter[]\n\n/** A parameter on an {@link ox#AbiParameters.AbiParameters}. */\nexport type Parameter = abitype.AbiParameter\n\n/** A packed ABI type. */\nexport type PackedAbiType =\n | abitype.SolidityAddress\n | abitype.SolidityBool\n | abitype.SolidityBytes\n | abitype.SolidityInt\n | abitype.SolidityString\n | abitype.SolidityArrayWithoutTuple\n\n/**\n * Decodes ABI-encoded data into its respective primitive values based on ABI Parameters.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.decode(\n * AbiParameters.from(['string', 'uint', 'bool']),\n * '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000',\n * )\n * // @log: ['wagmi', 420n, true]\n * ```\n *\n * @example\n * ### JSON Parameters\n *\n * You can pass **JSON ABI** Parameters:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.decode(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' },\n * ],\n * '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000',\n * )\n * // @log: ['wagmi', 420n, true]\n * ```\n *\n * @param parameters - The set of ABI parameters to decode, in the shape of the `inputs` or `outputs` attribute of an ABI Item. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/latest/types.html).\n * @param data - ABI encoded data.\n * @param options - Decoding options.\n * @returns Array of decoded values.\n */\nexport function decode<\n const parameters extends AbiParameters,\n as extends 'Object' | 'Array' = 'Array',\n>(\n parameters: parameters,\n data: Bytes.Bytes | Hex.Hex,\n options?: decode.Options<as>,\n): decode.ReturnType<parameters, as>\n\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decode(\n parameters: AbiParameters,\n data: Bytes.Bytes | Hex.Hex,\n options: {\n as?: 'Array' | 'Object' | undefined\n checksumAddress?: boolean | undefined\n } = {},\n): readonly unknown[] | Record<string, unknown> {\n const { as = 'Array', checksumAddress = false } = options\n\n const bytes = typeof data === 'string' ? Bytes.fromHex(data) : data\n const cursor = Cursor.create(bytes)\n\n if (Bytes.size(bytes) === 0 && parameters.length > 0)\n throw new ZeroDataError()\n if (Bytes.size(bytes) && Bytes.size(bytes) < 32)\n throw new DataSizeTooSmallError({\n data: typeof data === 'string' ? data : Hex.fromBytes(data),\n parameters: parameters as readonly Parameter[],\n size: Bytes.size(bytes),\n })\n\n let consumed = 0\n const values: any = as === 'Array' ? [] : {}\n for (let i = 0; i < parameters.length; ++i) {\n const param = parameters[i] as Parameter\n cursor.setPosition(consumed)\n const [data, consumed_] = internal.decodeParameter(cursor, param, {\n checksumAddress,\n staticPosition: 0,\n })\n consumed += consumed_\n if (as === 'Array') values.push(data)\n else values[param.name ?? i] = data\n }\n return values\n}\n\nexport declare namespace decode {\n type Options<as extends 'Object' | 'Array'> = {\n /**\n * Whether the decoded values should be returned as an `Object` or `Array`.\n *\n * @default \"Array\"\n */\n as?: as | 'Object' | 'Array' | undefined\n /**\n * Whether decoded addresses should be checksummed.\n *\n * @default false\n */\n checksumAddress?: boolean | undefined\n }\n\n type ReturnType<\n parameters extends AbiParameters = AbiParameters,\n as extends 'Object' | 'Array' = 'Array',\n > = parameters extends readonly []\n ? as extends 'Object'\n ? {}\n : []\n : as extends 'Object'\n ? internal.ToObject<parameters>\n : internal.ToPrimitiveTypes<parameters>\n\n type ErrorType =\n | Bytes.fromHex.ErrorType\n | internal.decodeParameter.ErrorType\n | ZeroDataError\n | DataSizeTooSmallError\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes primitive values into ABI encoded data as per the [Application Binary Interface (ABI) Specification](https://docs.soliditylang.org/en/latest/abi-spec).\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.encode(\n * AbiParameters.from(['string', 'uint', 'bool']),\n * ['wagmi', 420n, true],\n * )\n * ```\n *\n * @example\n * ### JSON Parameters\n *\n * Specify **JSON ABI** Parameters as schema:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.encode(\n * [\n * { type: 'string', name: 'name' },\n * { type: 'uint', name: 'age' },\n * { type: 'bool', name: 'isOwner' },\n * ],\n * ['wagmi', 420n, true],\n * )\n * ```\n *\n * @param parameters - The set of ABI parameters to encode, in the shape of the `inputs` or `outputs` attribute of an ABI Item. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/latest/types.html).\n * @param values - The set of primitive values that correspond to the ABI types defined in `parameters`.\n * @returns ABI encoded data.\n */\nexport function encode<\n const parameters extends AbiParameters | readonly unknown[],\n>(\n parameters: parameters,\n values: parameters extends AbiParameters\n ? internal.ToPrimitiveTypes<parameters>\n : never,\n options?: encode.Options,\n): Hex.Hex {\n const { checksumAddress = false } = options ?? {}\n\n if (parameters.length !== values.length)\n throw new LengthMismatchError({\n expectedLength: parameters.length as number,\n givenLength: values.length as any,\n })\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParameters = internal.prepareParameters({\n checksumAddress,\n parameters: parameters as readonly Parameter[],\n values: values as any,\n })\n const data = internal.encode(preparedParameters)\n if (data.length === 0) return '0x'\n return data\n}\n\nexport declare namespace encode {\n type ErrorType =\n | LengthMismatchError\n | internal.encode.ErrorType\n | internal.prepareParameters.ErrorType\n | Errors.GlobalErrorType\n\n type Options = {\n /**\n * Whether addresses should be checked against their checksum.\n *\n * @default false\n */\n checksumAddress?: boolean | undefined\n }\n}\n\n/**\n * Encodes an array of primitive values to a [packed ABI encoding](https://docs.soliditylang.org/en/latest/abi-spec.html#non-standard-packed-mode).\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const encoded = AbiParameters.encodePacked(\n * ['address', 'string'],\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 'hello world'],\n * )\n * // @log: '0xd8da6bf26964af9d7eed9e03e53415d37aa9604568656c6c6f20776f726c64'\n * ```\n *\n * @param types - Set of ABI types to pack encode.\n * @param values - The set of primitive values that correspond to the ABI types defined in `types`.\n * @returns The encoded packed data.\n */\nexport function encodePacked<\n const packedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n>(types: packedAbiTypes, values: encodePacked.Values<packedAbiTypes>): Hex.Hex {\n if (types.length !== values.length)\n throw new LengthMismatchError({\n expectedLength: types.length as number,\n givenLength: values.length as number,\n })\n\n const data: Hex.Hex[] = []\n for (let i = 0; i < (types as unknown[]).length; i++) {\n const type = types[i]\n const value = values[i]\n data.push(encodePacked.encode(type, value))\n }\n return Hex.concat(...data)\n}\n\nexport namespace encodePacked {\n export type ErrorType =\n | Hex.concat.ErrorType\n | LengthMismatchError\n | Errors.GlobalErrorType\n\n export type Values<\n packedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n > = {\n [key in keyof packedAbiTypes]: packedAbiTypes[key] extends abitype.AbiType\n ? abitype.AbiParameterToPrimitiveType<{ type: packedAbiTypes[key] }>\n : unknown\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc\n export function encode<const packedAbiType extends PackedAbiType | unknown>(\n type: packedAbiType,\n value: Values<[packedAbiType]>[0],\n isArray = false,\n ): Hex.Hex {\n if (type === 'address') {\n const address = value as Address.Address\n Address.assert(address)\n return Hex.padLeft(\n address.toLowerCase() as Hex.Hex,\n isArray ? 32 : 0,\n ) as Address.Address\n }\n if (type === 'string') return Hex.fromString(value as string)\n if (type === 'bytes') return value as Hex.Hex\n if (type === 'bool')\n return Hex.padLeft(Hex.fromBoolean(value as boolean), isArray ? 32 : 1)\n\n const intMatch = (type as string).match(Solidity.integerRegex)\n if (intMatch) {\n const [_type, baseType, bits = '256'] = intMatch\n const size = Number.parseInt(bits) / 8\n return Hex.fromNumber(value as number, {\n size: isArray ? 32 : size,\n signed: baseType === 'int',\n })\n }\n\n const bytesMatch = (type as string).match(Solidity.bytesRegex)\n if (bytesMatch) {\n const [_type, size] = bytesMatch\n if (Number.parseInt(size!) !== ((value as Hex.Hex).length - 2) / 2)\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size!),\n value: value as Hex.Hex,\n })\n return Hex.padRight(value as Hex.Hex, isArray ? 32 : 0) as Hex.Hex\n }\n\n const arrayMatch = (type as string).match(Solidity.arrayRegex)\n if (arrayMatch && Array.isArray(value)) {\n const [_type, childType] = arrayMatch\n const data: Hex.Hex[] = []\n for (let i = 0; i < value.length; i++) {\n data.push(encode(childType, value[i], true))\n }\n if (data.length === 0) return '0x'\n return Hex.concat(...data)\n }\n\n throw new InvalidTypeError(type as string)\n }\n}\n\n/**\n * Formats {@link ox#AbiParameters.AbiParameters} into **Human Readable ABI Parameters**.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const formatted = AbiParameters.format([\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ])\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param parameters - The ABI Parameters to format.\n * @returns The formatted ABI Parameters .\n */\nexport function format<\n const parameters extends readonly [\n Parameter | abitype.AbiEventParameter,\n ...(readonly (Parameter | abitype.AbiEventParameter)[]),\n ],\n>(\n parameters:\n | parameters\n | readonly [\n Parameter | abitype.AbiEventParameter,\n ...(readonly (Parameter | abitype.AbiEventParameter)[]),\n ],\n): abitype.FormatAbiParameters<parameters> {\n return abitype.formatAbiParameters(parameters)\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses arbitrary **JSON ABI Parameters** or **Human Readable ABI Parameters** into typed {@link ox#AbiParameters.AbiParameters}.\n *\n * @example\n * ### JSON Parameters\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from([\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ])\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable Parameters\n *\n * Human Readable ABI Parameters can be parsed into a typed {@link ox#AbiParameters.AbiParameters}:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from('address spender, uint256 amount')\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'Foo foo, address bar',\n * ])\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param parameters - The ABI Parameters to parse.\n * @returns The typed ABI Parameters.\n */\nexport function from<\n const parameters extends AbiParameters | string | readonly string[],\n>(\n parameters: parameters | AbiParameters | string | readonly string[],\n): from.ReturnType<parameters> {\n if (Array.isArray(parameters) && typeof parameters[0] === 'string')\n return abitype.parseAbiParameters(parameters) as never\n if (typeof parameters === 'string')\n return abitype.parseAbiParameters(parameters) as never\n return parameters as never\n}\n\nexport declare namespace from {\n type ReturnType<\n parameters extends AbiParameters | string | readonly string[],\n > = parameters extends string\n ? abitype.ParseAbiParameters<parameters>\n : parameters extends readonly string[]\n ? abitype.ParseAbiParameters<parameters>\n : parameters\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Throws when the data size is too small for the given parameters.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x010f')\n * // ↑ ❌ 2 bytes\n * // @error: AbiParameters.DataSizeTooSmallError: Data size of 2 bytes is too small for given parameters.\n * // @error: Params: (uint256)\n * // @error: Data: 0x010f (2 bytes)\n * ```\n *\n * ### Solution\n *\n * Pass a valid data size.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ✅ 32 bytes\n * ```\n */\nexport class DataSizeTooSmallError extends Errors.BaseError {\n override readonly name = 'AbiParameters.DataSizeTooSmallError'\n constructor({\n data,\n parameters,\n size,\n }: { data: Hex.Hex; parameters: readonly Parameter[]; size: number }) {\n super(`Data size of ${size} bytes is too small for given parameters.`, {\n metaMessages: [\n `Params: (${abitype.formatAbiParameters(parameters as readonly [Parameter])})`,\n `Data: ${data} (${size} bytes)`,\n ],\n })\n }\n}\n\n/**\n * Throws when zero data is provided, but data is expected.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x')\n * // ↑ ❌ zero data\n * // @error: AbiParameters.DataSizeTooSmallError: Data size of 2 bytes is too small for given parameters.\n * // @error: Params: (uint256)\n * // @error: Data: 0x010f (2 bytes)\n * ```\n *\n * ### Solution\n *\n * Pass valid data.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ✅ 32 bytes\n * ```\n */\nexport class ZeroDataError extends Errors.BaseError {\n override readonly name = 'AbiParameters.ZeroDataError'\n constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.')\n }\n}\n\n/**\n * The length of the array value does not match the length specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from('uint256[3]'), [[69n, 420n]])\n * // ↑ expected: 3 ↑ ❌ length: 2\n * // @error: AbiParameters.ArrayLengthMismatchError: ABI encoding array length mismatch\n * // @error: for type `uint256[3]`. Expected: `3`. Given: `2`.\n * ```\n *\n * ### Solution\n *\n * Pass an array of the correct length.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['uint256[3]']), [[69n, 420n, 69n]])\n * // ↑ ✅ length: 3\n * ```\n */\nexport class ArrayLengthMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.ArrayLengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n type,\n }: { expectedLength: number; givenLength: number; type: string }) {\n super(\n `Array length mismatch for type \\`${type}\\`. Expected: \\`${expectedLength}\\`. Given: \\`${givenLength}\\`.`,\n )\n }\n}\n\n/**\n * The size of the bytes value does not match the size specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from('bytes8'), [['0xdeadbeefdeadbeefdeadbeef']])\n * // ↑ expected: 8 bytes ↑ ❌ size: 12 bytes\n * // @error: BytesSizeMismatchError: Size of bytes \"0xdeadbeefdeadbeefdeadbeef\"\n * // @error: (bytes12) does not match expected size (bytes8).\n * ```\n *\n * ### Solution\n *\n * Pass a bytes value of the correct size.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['bytes8']), ['0xdeadbeefdeadbeef'])\n * // ↑ ✅ size: 8 bytes\n * ```\n */\nexport class BytesSizeMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.BytesSizeMismatchError'\n constructor({\n expectedSize,\n value,\n }: { expectedSize: number; value: Hex.Hex }) {\n super(\n `Size of bytes \"${value}\" (bytes${Hex.size(\n value,\n )}) does not match expected size (bytes${expectedSize}).`,\n )\n }\n}\n\n/**\n * The length of the values to encode does not match the length of the ABI parameters.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['string', 'uint256']), ['hello'])\n * // @error: LengthMismatchError: ABI encoding params/values length mismatch.\n * // @error: Expected length (params): 2\n * // @error: Given length (values): 1\n * ```\n *\n * ### Solution\n *\n * Pass the correct number of values to encode.\n *\n * ### Solution\n *\n * Pass a [valid ABI type](https://docs.soliditylang.org/en/develop/abi-spec.html#types).\n */\nexport class LengthMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.LengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n }: { expectedLength: number; givenLength: number }) {\n super(\n [\n 'ABI encoding parameters/values length mismatch.',\n `Expected length (parameters): ${expectedLength}`,\n `Given length (values): ${givenLength}`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * The value provided is not a valid array as specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['uint256[3]']), [69])\n * ```\n *\n * ### Solution\n *\n * Pass an array value.\n */\nexport class InvalidArrayError extends Errors.BaseError {\n override readonly name = 'AbiParameters.InvalidArrayError'\n constructor(value: unknown) {\n super(`Value \\`${value}\\` is not a valid array.`)\n }\n}\n\n/**\n * Throws when the ABI parameter type is invalid.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'lol' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ❌ invalid type\n * // @error: AbiParameters.InvalidTypeError: Type `lol` is not a valid ABI Type.\n * ```\n */\nexport class InvalidTypeError extends Errors.BaseError {\n override readonly name = 'AbiParameters.InvalidTypeError'\n constructor(type: string) {\n super(`Type \\`${type}\\` is not a valid ABI Type.`)\n }\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as AbiItem from './AbiItem.js'\nimport * as AbiParameters from './AbiParameters.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type * as internal from './internal/abiConstructor.js'\nimport type { IsNarrowable } from './internal/types.js'\n\n/** Root type for an {@link ox#AbiItem.AbiItem} with a `constructor` type. */\nexport type AbiConstructor = abitype.AbiConstructor\n\n/** @internal */\nexport function decode<const abiConstructor extends AbiConstructor>(\n abiConstructor: abiConstructor,\n options: decode.Options,\n): decode.ReturnType<abiConstructor>\n/**\n * ABI-decodes the provided constructor input (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from('constructor(address, uint256)')\n *\n * const bytecode = '0x...'\n *\n * const data = AbiConstructor.encode(constructor, {\n * bytecode,\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * const decoded = AbiConstructor.decode(constructor, { // [!code focus]\n * bytecode, // [!code focus]\n * data, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param abiConstructor - The ABI Constructor to decode.\n * @param options - Decoding options.\n * @returns The decoded constructor inputs.\n */\nexport function decode(\n abiConstructor: AbiConstructor,\n options: decode.Options,\n): readonly unknown[] | undefined\n/** @internal */\nexport function decode(\n abiConstructor: AbiConstructor,\n options: decode.Options,\n): decode.ReturnType {\n const { bytecode } = options\n if (abiConstructor.inputs.length === 0) return undefined\n const data = options.data.replace(bytecode, '0x') as Hex.Hex\n return AbiParameters.decode(abiConstructor.inputs, data)\n}\n\nexport declare namespace decode {\n interface Options {\n /** The bytecode of the contract. */\n bytecode: Hex.Hex\n /** The encoded constructor. */\n data: Hex.Hex\n }\n\n type ReturnType<abiConstructor extends AbiConstructor = AbiConstructor> =\n | (abiConstructor['inputs']['length'] extends 0\n ? undefined\n : abitype.AbiParametersToPrimitiveTypes<abiConstructor['inputs']>)\n | (IsNarrowable<abiConstructor, AbiConstructor> extends true\n ? never\n : undefined)\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes the provided constructor input (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from('constructor(address, uint256)')\n *\n * const data = AbiConstructor.encode(constructor, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiConstructor.encode` to encode the constructor of a contract and deploy it.\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { AbiConstructor, Hex } from 'ox'\n *\n * // 1. Instantiate the ABI Constructor.\n * const constructor = AbiConstructor.from(\n * 'constructor(address owner, uint256 amount)',\n * )\n *\n * // 2. Encode the ABI Constructor.\n * const data = AbiConstructor.encode(constructor, {\n * bytecode: '0x...',\n * args: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 123n],\n * })\n *\n * // 3. Deploy the contract.\n * const hash = await window.ethereum!.request({\n * method: 'eth_sendTransaction',\n * params: [{ data }],\n * })\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiConstructor - The ABI Constructor to encode.\n * @param options - Encoding options.\n * @returns The encoded constructor.\n */\nexport function encode<const abiConstructor extends AbiConstructor>(\n abiConstructor: abiConstructor,\n options: encode.Options<abiConstructor>,\n): encode.ReturnType {\n const { bytecode, args } = options\n return Hex.concat(\n bytecode,\n abiConstructor.inputs?.length && args?.length\n ? AbiParameters.encode(abiConstructor.inputs, args as readonly unknown[])\n : '0x',\n )\n}\n\nexport declare namespace encode {\n type Options<\n abiConstructor extends AbiConstructor = AbiConstructor,\n ///\n args extends abitype.AbiParametersToPrimitiveTypes<\n abiConstructor['inputs']\n > = abitype.AbiParametersToPrimitiveTypes<abiConstructor['inputs']>,\n > = {\n /** The bytecode of the contract. */\n bytecode: Hex.Hex\n /** The constructor arguments to encode. */\n args?: args | undefined\n } & (readonly [] extends args\n ? {}\n : {\n /** The constructor arguments to encode. */\n args: args\n })\n\n type ReturnType = Hex.Hex\n\n type ErrorType =\n | Hex.concat.ErrorType\n | AbiParameters.encode.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function format<const abiConstructor extends AbiConstructor>(\n abiConstructor: abiConstructor,\n): format.ReturnType<abiConstructor>\n/**\n * Formats an {@link ox#AbiConstructor.AbiConstructor} into a **Human Readable ABI Function**.\n *\n * @example\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const formatted = AbiConstructor.format({\n * inputs: [\n * { name: 'owner', type: 'address' },\n * ],\n * payable: false,\n * stateMutability: 'nonpayable',\n * type: 'constructor',\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiConstructor - The ABI Constructor to format.\n * @returns The formatted ABI Constructor.\n */\nexport function format(abiConstructor: AbiConstructor): string\n/** @internal */\nexport function format(abiConstructor: AbiConstructor): format.ReturnType {\n return abitype.formatAbiItem(abiConstructor)\n}\n\nexport declare namespace format {\n type ReturnType<abiConstructor extends AbiConstructor = AbiConstructor> =\n abitype.FormatAbiItem<abiConstructor>\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function from<\n const abiConstructor extends AbiConstructor | string | readonly string[],\n>(\n abiConstructor: (abiConstructor | string | readonly string[]) &\n (\n | (abiConstructor extends string\n ? internal.Signature<abiConstructor>\n : never)\n | (abiConstructor extends readonly string[]\n ? internal.Signatures<abiConstructor>\n : never)\n | AbiConstructor\n ),\n): from.ReturnType<abiConstructor>\n/**\n * Parses an arbitrary **JSON ABI Constructor** or **Human Readable ABI Constructor** into a typed {@link ox#AbiConstructor.AbiConstructor}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from({\n * inputs: [\n * { name: 'owner', type: 'address' },\n * ],\n * payable: false,\n * stateMutability: 'nonpayable',\n * type: 'constructor',\n * })\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from(\n * 'constructor(address owner)' // [!code hl]\n * )\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiConstructor } from 'ox'\n *\n * const constructor = AbiConstructor.from([\n * 'struct Foo { address owner; uint256 amount; }', // [!code hl]\n * 'constructor(Foo foo)',\n * ])\n *\n * constructor\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiConstructor - The ABI Constructor to parse.\n * @returns Typed ABI Constructor.\n */\nexport function from(\n abiConstructor: AbiConstructor | string | readonly string[],\n): AbiConstructor\n/** @internal */\nexport function from(\n abiConstructor: AbiConstructor | string | readonly string[],\n): from.ReturnType {\n return AbiItem.from(abiConstructor as AbiConstructor)\n}\n\nexport declare namespace from {\n type ReturnType<\n abiConstructor extends\n | AbiConstructor\n | string\n | readonly string[] = AbiConstructor,\n > = AbiItem.from.ReturnType<abiConstructor>\n\n type ErrorType = AbiItem.from.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function fromAbi<const abi extends Abi.Abi | readonly unknown[]>(\n abi: abi | Abi.Abi | readonly unknown[],\n): fromAbi.ReturnType<abi>\n/**\n * Extracts an {@link ox#AbiConstructor.AbiConstructor} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ### Extracting by Name\n *\n * ABI Events can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiConstructor } from 'ox'\n *\n * const abi = Abi.from([\n * 'constructor(address owner)',\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiConstructor.fromAbi(abi) // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @returns The ABI constructor.\n */\nexport function fromAbi(abi: Abi.Abi | readonly unknown[]): AbiConstructor\n/** @internal */\nexport function fromAbi(abi: Abi.Abi | readonly unknown[]): fromAbi.ReturnType {\n const item = (abi as Abi.Abi).find((item) => item.type === 'constructor')\n if (!item) throw new AbiItem.NotFoundError({ name: 'constructor' })\n return item\n}\n\nexport declare namespace fromAbi {\n type ReturnType<abi extends Abi.Abi | readonly unknown[] = Abi.Abi> = Extract<\n abi[number],\n { type: 'constructor' }\n >\n\n type ErrorType = AbiItem.NotFoundError | Errors.GlobalErrorType\n}\n","import * as abitype from 'abitype'\nimport type * as Abi from './Abi.js'\nimport * as AbiItem from './AbiItem.js'\nimport * as AbiParameters from './AbiParameters.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type * as internal from './internal/abiFunction.js'\nimport type * as AbiItem_internal from './internal/abiItem.js'\nimport type * as AbiParameters_internal from './internal/abiParameters.js'\nimport type { IsNarrowable } from './internal/types.js'\n\n/** Root type for an {@link ox#AbiItem.AbiItem} with a `function` type. */\nexport type AbiFunction = abitype.AbiFunction & {\n hash?: Hex.Hex | undefined\n overloads?: readonly AbiFunction[] | undefined\n}\n\n/**\n * Extracts an {@link ox#AbiFunction.AbiFunction} item from an {@link ox#Abi.Abi}, given a name.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo(string)',\n * 'function bar(uint256)',\n * ])\n *\n * type Foo = AbiFunction.FromAbi<typeof abi, 'foo'>\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n */\nexport type FromAbi<\n abi extends Abi.Abi,\n name extends ExtractNames<abi>,\n> = abitype.ExtractAbiFunction<abi, name>\n\n/**\n * Extracts the names of all {@link ox#AbiFunction.AbiFunction} items in an {@link ox#Abi.Abi}.\n *\n * @example\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo(string)',\n * 'function bar(uint256)',\n * ])\n *\n * type names = AbiFunction.Name<typeof abi>\n * // ^?\n *\n *\n * ```\n */\nexport type Name<abi extends Abi.Abi | readonly unknown[] = Abi.Abi> =\n abi extends Abi.Abi ? ExtractNames<abi> : string\n\nexport type ExtractNames<\n abi extends Abi.Abi,\n abiStateMutability extends\n abitype.AbiStateMutability = abitype.AbiStateMutability,\n> = abitype.ExtractAbiFunctionNames<abi, abiStateMutability>\n\n/**\n * ABI-decodes function arguments according to the ABI Item's input types (`inputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from('function approve(address, uint256)')\n *\n * const data = AbiFunction.encodeData(\n * approve,\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * // '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n *\n * const input = AbiFunction.decodeData(approve, data) // [!code focus]\n * // @log: ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * ```\n *\n * @param abiFunction - The ABI Item to decode.\n * @param data - The data to decode.\n */\nexport function decodeData<const abiItem extends AbiFunction>(\n abiFunction: abiItem | AbiFunction,\n data: Hex.Hex,\n): decodeData.ReturnType<abiItem> {\n const { overloads } = abiFunction\n\n if (Hex.size(data) < 4) throw new AbiItem.InvalidSelectorSizeError({ data })\n if (abiFunction.inputs.length === 0) return undefined\n\n const item = overloads\n ? fromAbi([abiFunction, ...overloads], data as never)\n : abiFunction\n\n if (Hex.size(data) <= 4) return undefined\n return AbiParameters.decode(item.inputs, Hex.slice(data, 4))\n}\n\nexport declare namespace decodeData {\n type ReturnType<abiFunction extends AbiFunction = AbiFunction> = IsNarrowable<\n abiFunction,\n AbiFunction\n > extends true\n ? abiFunction['inputs'] extends readonly []\n ? undefined\n :\n | AbiParameters_internal.ToPrimitiveTypes<abiFunction['inputs']>\n | (abiFunction['overloads'] extends readonly AbiFunction[]\n ? AbiParameters_internal.ToPrimitiveTypes<\n abiFunction['overloads'][number]['inputs']\n >\n : never)\n : unknown\n\n type ErrorType =\n | fromAbi.ErrorType\n | AbiParameters.decode.ErrorType\n | Hex.size.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * ABI-decodes a function's result according to the ABI Item's output types (`outputs`).\n *\n * :::tip\n *\n * This function is typically used to decode contract function return values (e.g. the response of an `eth_call` or the `input` property of a Transaction).\n *\n * See the [End-to-end Example](#end-to-end).\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)')\n *\n * const output = AbiFunction.decodeResult(totalSupply, data)\n * // @log: 42n\n * ```\n *\n * @example\n * You can extract an ABI Function from a JSON ABI with {@link ox#AbiFunction.(fromAbi:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const data = '0x000000000000000000000000000000000000000000000000000000000000002a'\n *\n * const erc20Abi = Abi.from([...]) // [!code hl]\n * const totalSupply = AbiFunction.fromAbi(erc20Abi, 'totalSupply') // [!code hl]\n *\n * const output = AbiFunction.decodeResult(totalSupply, data)\n * // @log: 42n\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiFunction.decodeResult` to decode the result of a `balanceOf` contract call on the [Wagmi Mint Example contract](https://etherscan.io/address/0xfba3912ca04dd458c843e2ee08967fc04f3579c2).\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { Abi, AbiFunction } from 'ox'\n *\n * // 1. Extract the Function from the Contract's ABI.\n * const abi = Abi.from([\n * // ...\n * {\n * name: 'balanceOf',\n * type: 'function',\n * inputs: [{ name: 'account', type: 'address' }],\n * outputs: [{ name: 'balance', type: 'uint256' }],\n * stateMutability: 'view',\n * },\n * // ...\n * ])\n * const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf')\n *\n * // 2. Encode the Function Input.\n * const data = AbiFunction.encodeData(\n * balanceOf,\n * ['0xd2135CfB216b74109775236E36d4b433F1DF507B']\n * )\n *\n * // 3. Perform the Contract Call.\n * const response = await window.ethereum!.request({\n * method: 'eth_call',\n * params: [\n * {\n * data,\n * to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * },\n * ],\n * })\n *\n * // 4. Decode the Function Output. // [!code focus]\n * const balance = AbiFunction.decodeResult(balanceOf, response) // [!code focus]\n * // @log: 42n\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiFunction - ABI Function to decode\n * @param data - ABI-encoded function output\n * @param options - Decoding options\n * @returns Decoded function output\n */\nexport function decodeResult<\n const abiFunction extends AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abiFunction: abiFunction | AbiFunction,\n data: Hex.Hex,\n options: decodeResult.Options<as> = {},\n): decodeResult.ReturnType<abiFunction, as> {\n const values = AbiParameters.decode(abiFunction.outputs, data, options)\n if (values && Object.keys(values).length === 0) return undefined\n if (values && Object.keys(values).length === 1) {\n if (Array.isArray(values)) return values[0]\n return Object.values(values)[0]\n }\n return values\n}\n\nexport declare namespace decodeResult {\n type Options<as extends 'Object' | 'Array'> = {\n /**\n * Whether the decoded values should be returned as an `Object` or `Array`.\n *\n * @default \"Array\"\n */\n as?: as | 'Array' | 'Object' | undefined\n }\n\n type ReturnType<\n abiFunction extends AbiFunction = AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n > = IsNarrowable<abiFunction, AbiFunction> extends true\n ? abiFunction['outputs'] extends readonly []\n ? undefined\n : abiFunction['outputs'] extends readonly [\n infer type extends abitype.AbiParameter,\n ]\n ? abitype.AbiParameterToPrimitiveType<type>\n : AbiParameters.decode.ReturnType<\n abiFunction['outputs'],\n as\n > extends infer types\n ? types extends readonly []\n ? undefined\n : types extends readonly [infer type]\n ? type\n : types\n : never\n : unknown\n\n type ErrorType = AbiParameters.decode.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes function arguments (`inputs`), prefixed with the 4 byte function selector.\n *\n * :::tip\n *\n * This function is typically used to encode a contract function and its arguments for contract calls (e.g. `data` parameter of an `eth_call` or `eth_sendTransaction`).\n *\n * See the [End-to-end Example](#end-to-end).\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from('function approve(address, uint256)')\n *\n * const data = AbiFunction.encodeData( // [!code focus]\n * approve, // [!code focus]\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n] // [!code focus]\n * ) // [!code focus]\n * // @log: '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n * ```\n *\n * @example\n * You can extract an ABI Function from a JSON ABI with {@link ox#AbiFunction.(fromAbi:function)}:\n *\n * ```ts twoslash\n * // @noErrors\n * import { Abi, AbiFunction } from 'ox'\n *\n * const erc20Abi = Abi.from([...]) // [!code hl]\n * const approve = AbiFunction.fromAbi(erc20Abi, 'approve') // [!code hl]\n *\n * const data = AbiFunction.encodeData(\n * approve,\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 69420n]\n * )\n * // @log: '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000010f2c'\n * ```\n *\n * @example\n * ### End-to-end\n *\n * Below is an end-to-end example of using `AbiFunction.encodeData` to encode the input of a `balanceOf` contract call on the [Wagmi Mint Example contract](https://etherscan.io/address/0xfba3912ca04dd458c843e2ee08967fc04f3579c2).\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { Abi, AbiFunction } from 'ox'\n *\n * // 1. Extract the Function from the Contract's ABI.\n * const abi = Abi.from([\n * // ...\n * {\n * name: 'balanceOf',\n * type: 'function',\n * inputs: [{ name: 'account', type: 'address' }],\n * outputs: [{ name: 'balance', type: 'uint256' }],\n * stateMutability: 'view',\n * },\n * // ...\n * ])\n * const balanceOf = AbiFunction.fromAbi(abi, 'balanceOf')\n *\n * // 2. Encode the Function Input. // [!code focus]\n * const data = AbiFunction.encodeData( // [!code focus]\n * balanceOf, // [!code focus]\n * ['0xd2135CfB216b74109775236E36d4b433F1DF507B'] // [!code focus]\n * ) // [!code focus]\n *\n * // 3. Perform the Contract Call.\n * const response = await window.ethereum!.request({\n * method: 'eth_call',\n * params: [\n * {\n * data,\n * to: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * },\n * ],\n * })\n *\n * // 4. Decode the Function Output.\n * const balance = AbiFunction.decodeResult(balanceOf, response)\n * ```\n *\n * :::note\n *\n * For simplicity, the above example uses `window.ethereum.request`, but you can use any\n * type of JSON-RPC interface.\n *\n * :::\n *\n * @param abiFunction - ABI Function to encode\n * @param args - Function arguments\n * @returns ABI-encoded function name and arguments\n */\nexport function encodeData<const abiFunction extends AbiFunction>(\n abiFunction: abiFunction | AbiFunction,\n ...args: encodeData.Args<abiFunction>\n): Hex.Hex {\n const { overloads } = abiFunction\n\n const item = overloads\n ? (fromAbi([abiFunction as AbiFunction, ...overloads], abiFunction.name, {\n args: (args as any)[0],\n }) as AbiFunction)\n : abiFunction\n\n const selector = getSelector(item)\n\n const data =\n args.length > 0\n ? AbiParameters.encode(item.inputs, (args as any)[0])\n : undefined\n\n return data ? Hex.concat(selector, data) : selector\n}\n\nexport declare namespace encodeData {\n type Args<abiFunction extends AbiFunction = AbiFunction> = IsNarrowable<\n abiFunction,\n AbiFunction\n > extends true\n ?\n | (abitype.AbiParametersToPrimitiveTypes<\n abiFunction['inputs']\n > extends readonly []\n ? []\n : [abitype.AbiParametersToPrimitiveTypes<abiFunction['inputs']>])\n | (abiFunction['overloads'] extends readonly AbiFunction[]\n ? [\n abitype.AbiParametersToPrimitiveTypes<\n abiFunction['overloads'][number]['inputs']\n >,\n ]\n : [])\n : readonly unknown[]\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * ABI-encodes a function's result (`outputs`).\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const totalSupply = AbiFunction.from('function totalSupply() returns (uint256)')\n * const output = AbiFunction.decodeResult(totalSupply, '0x000000000000000000000000000000000000000000000000000000000000002a')\n * // 42n\n *\n * const data = AbiFunction.encodeResult(totalSupply, 42n) // [!code focus]\n * // @log: '0x000000000000000000000000000000000000000000000000000000000000002a'\n * ```\n *\n * @param abiFunction - The ABI item to encode the function output for.\n * @param output - The function output to encode.\n * @param options - Encoding options.\n * @returns The encoded function output.\n */\nexport function encodeResult<\n const abiFunction extends AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n>(\n abiFunction: abiFunction | AbiFunction,\n output: encodeResult.Output<abiFunction, as>,\n options: encodeResult.Options<as> = {},\n): Hex.Hex {\n const { as = 'Array' } = options\n\n const values = (() => {\n if (abiFunction.outputs.length === 1) return [output]\n if (Array.isArray(output)) return output\n if (as === 'Object') return Object.values(output as any)\n return [output]\n })()\n\n return AbiParameters.encode(abiFunction.outputs, values)\n}\n\nexport declare namespace encodeResult {\n type Output<\n abiFunction extends AbiFunction = AbiFunction,\n as extends 'Object' | 'Array' = 'Array',\n > = abiFunction['outputs'] extends readonly []\n ? never\n : abiFunction['outputs']['length'] extends 1\n ? AbiParameters_internal.ToPrimitiveTypes<abiFunction['outputs']>[0]\n : as extends 'Object'\n ? AbiParameters_internal.ToObject<abiFunction['outputs']>\n : AbiParameters_internal.ToPrimitiveTypes<abiFunction['outputs']>\n\n type Options<as extends 'Object' | 'Array'> = {\n as?: as | 'Object' | 'Array' | undefined\n }\n\n type ErrorType = AbiParameters.encode.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Formats an {@link ox#AbiFunction.AbiFunction} into a **Human Readable ABI Function**.\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const formatted = AbiFunction.format({\n * type: 'function',\n * name: 'approve',\n * stateMutability: 'nonpayable',\n * inputs: [\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ],\n * outputs: [{ type: 'bool' }],\n * })\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param abiFunction - The ABI Function to format.\n * @returns The formatted ABI Function.\n */\nexport function format<const abiFunction extends AbiFunction>(\n abiFunction: abiFunction | AbiFunction,\n): abitype.FormatAbiItem<abiFunction> {\n return abitype.formatAbiItem(abiFunction) as never\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses an arbitrary **JSON ABI Function** or **Human Readable ABI Function** into a typed {@link ox#AbiFunction.AbiFunction}.\n *\n * @example\n * ### JSON ABIs\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from({\n * type: 'function',\n * name: 'approve',\n * stateMutability: 'nonpayable',\n * inputs: [\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ],\n * outputs: [{ type: 'bool' }],\n * })\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable ABIs\n *\n * A Human Readable ABI can be parsed into a typed ABI object:\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from(\n * 'function approve(address spender, uint256 amount) returns (bool)' // [!code hl]\n * )\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const approve = AbiFunction.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'function approve(Foo foo) returns (bool)',\n * ])\n *\n * approve\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param abiFunction - The ABI Function to parse.\n * @returns Typed ABI Function.\n */\nexport function from<\n const abiFunction extends AbiFunction | string | readonly string[],\n>(\n abiFunction: (abiFunction | AbiFunction | string | readonly string[]) &\n (\n | (abiFunction extends string ? internal.Signature<abiFunction> : never)\n | (abiFunction extends readonly string[]\n ? internal.Signatures<abiFunction>\n : never)\n | AbiFunction\n ),\n options: from.Options = {},\n): from.ReturnType<abiFunction> {\n return AbiItem.from(abiFunction as AbiFunction, options) as never\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether or not to prepare the extracted function (optimization for encoding performance).\n * When `true`, the `hash` property is computed and included in the returned value.\n *\n * @default true\n */\n prepare?: boolean | undefined\n }\n\n type ReturnType<\n abiFunction extends AbiFunction | string | readonly string[],\n > = AbiItem.from.ReturnType<abiFunction>\n\n type ErrorType = AbiItem.from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Extracts an {@link ox#AbiFunction.AbiFunction} from an {@link ox#Abi.Abi} given a name and optional arguments.\n *\n * @example\n * ### Extracting by Name\n *\n * ABI Functions can be extracted by their name using the `name` option:\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n *\n * const item = AbiFunction.fromAbi(abi, 'foo') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Extracting by Selector\n *\n * ABI Functions can be extract by their selector when {@link ox#Hex.Hex} is provided to `name`.\n *\n * ```ts twoslash\n * import { Abi, AbiFunction } from 'ox'\n *\n * const abi = Abi.from([\n * 'function foo()',\n * 'event Transfer(address owner, address to, uint256 tokenId)',\n * 'function bar(string a) returns (uint256 x)',\n * ])\n * const item = AbiFunction.fromAbi(abi, '0x095ea7b3') // [!code focus]\n * // ^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * :::note\n *\n * Extracting via a hex selector is useful when extracting an ABI Function from an `eth_call` RPC response or\n * from a Transaction `input`.\n *\n * :::\n *\n * @param abi - The ABI to extract from.\n * @param name - The name (or selector) of the ABI item to extract.\n * @param options - Extraction options.\n * @returns The ABI item.\n */\nexport function fromAbi<\n const abi extends Abi.Abi | readonly unknown[],\n name extends Name<abi>,\n const args extends\n | AbiItem_internal.ExtractArgs<abi, name>\n | undefined = undefined,\n //\n allNames = Name<abi>,\n>(\n abi: abi | Abi.Abi | readonly unknown[],\n name: Hex.Hex | (name extends allNames ? name : never),\n options?: AbiItem.fromAbi.Options<\n abi,\n name,\n args,\n AbiItem_internal.ExtractArgs<abi, name>\n >,\n): AbiItem.fromAbi.ReturnType<abi, name, args, AbiFunction> {\n const item = AbiItem.fromAbi(abi, name, options as any)\n if (item.type !== 'function')\n throw new AbiItem.NotFoundError({ name, type: 'function' })\n return item as never\n}\n\nexport declare namespace fromAbi {\n type ErrorType = AbiItem.fromAbi.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Computes the [4-byte selector](https://solidity-by-example.org/function-selector/) for an {@link ox#AbiFunction.AbiFunction}.\n *\n * Useful for computing function selectors for calldata.\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const selector = AbiFunction.getSelector('function ownerOf(uint256 tokenId)')\n * // @log: '0x6352211e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { AbiFunction } from 'ox'\n *\n * const selector = AbiFunction.getSelector({\n * inputs: [{ type: 'uint256' }],\n * name: 'ownerOf',\n * outputs: [],\n * stateMutability: 'view',\n * type: 'function'\n * })\n * // @log: '0x6352211e'\n * ```\n *\n * @param abiItem - The ABI item to compute the selector for.\n * @returns The first 4 bytes of the {@link ox#Hash.(keccak256:function)} hash of the function signature.\n */\nexport function getSelector(abiItem: string | AbiFunction): Hex.Hex {\n return AbiItem.getSelector(abiItem)\n}\n\nexport declare namespace getSelector {\n type ErrorType = AbiItem.getSelector.ErrorType | Errors.GlobalErrorType\n}\n","export const entryPoint06Address =\n '0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789' as const\nexport const entryPoint07Address =\n '0x0000000071727De22E5E9d8BAf0edAc6f37da032' as const\n\nexport const ethAddress = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' as const\n\nexport const zeroAddress = '0x0000000000000000000000000000000000000000' as const\n","import type { AbiStateMutability, Address, Narrow } from 'abitype'\nimport * as AbiConstructor from 'ox/AbiConstructor'\nimport * as AbiFunction from 'ox/AbiFunction'\n\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { ethAddress, zeroAddress } from '../../constants/address.js'\nimport { deploylessCallViaBytecodeBytecode } from '../../constants/contracts.js'\nimport { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type { Call, Calls } from '../../types/calls.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { MulticallResults } from '../../types/multicall.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { Mutable } from '../../types/utils.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport { hexToBigInt } from '../../utils/index.js'\nimport {\n type CreateAccessListErrorType,\n createAccessList,\n} from './createAccessList.js'\nimport {\n type SimulateBlocksErrorType,\n type SimulateBlocksParameters,\n simulateBlocks,\n} from './simulateBlocks.js'\n\nconst getBalanceCode =\n '0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033'\n\nexport type SimulateCallsParameters<\n calls extends readonly unknown[] = readonly unknown[],\n account extends Account | Address | undefined = Account | Address | undefined,\n> = Omit<SimulateBlocksParameters, 'blocks' | 'returnFullTransactions'> & {\n /** Account attached to the calls (msg.sender). */\n account?: account | undefined\n /** Calls to simulate. */\n calls: Calls<Narrow<calls>>\n /** State overrides. */\n stateOverrides?: StateOverride | undefined\n /** Whether to trace asset changes. */\n traceAssetChanges?: boolean | undefined\n}\n\nexport type SimulateCallsReturnType<\n calls extends readonly unknown[] = readonly unknown[],\n> = {\n /** Asset changes. */\n assetChanges: readonly {\n token: {\n address: Address\n decimals?: number | undefined\n symbol?: string | undefined\n }\n value: { pre: bigint; post: bigint; diff: bigint }\n }[]\n /** Block results. */\n block: Block\n /** Call results. */\n results: MulticallResults<\n Narrow<calls>,\n true,\n {\n extraProperties: {\n data: Hex\n gasUsed: bigint\n logs?: Log[] | undefined\n }\n error: Error\n mutability: AbiStateMutability\n }\n >\n}\n\nexport type SimulateCallsErrorType =\n | AbiFunction.encodeData.ErrorType\n | AbiFunction.from.ErrorType\n | CreateAccessListErrorType\n | EncodeFunctionDataErrorType\n | SimulateBlocksErrorType\n | ErrorType\n\n/**\n * Simulates execution of a batch of calls.\n *\n * @param client - Client to use\n * @param parameters - {@link SimulateCallsParameters}\n * @returns Results. {@link SimulateCallsReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { simulateCalls } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await simulateCalls(client, {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * calls: [{\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * ]\n * })\n * ```\n */\nexport async function simulateCalls<\n const calls extends readonly unknown[],\n chain extends Chain | undefined,\n account extends Account | Address | undefined = undefined,\n>(\n client: Client<Transport, chain>,\n parameters: SimulateCallsParameters<calls, account>,\n): Promise<SimulateCallsReturnType<calls>> {\n const {\n blockNumber,\n blockTag,\n calls,\n stateOverrides,\n traceAssetChanges,\n traceTransfers,\n validation,\n } = parameters\n\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n\n if (traceAssetChanges && !account)\n throw new BaseError(\n '`account` is required when `traceAssetChanges` is true',\n )\n\n // Derive bytecode to extract ETH balance via a contract call.\n const getBalanceData = account\n ? AbiConstructor.encode(AbiConstructor.from('constructor(bytes, bytes)'), {\n bytecode: deploylessCallViaBytecodeBytecode,\n args: [\n getBalanceCode,\n AbiFunction.encodeData(\n AbiFunction.from('function getBalance(address)'),\n [account.address],\n ),\n ],\n })\n : undefined\n\n // Fetch ERC20/721 addresses that were \"touched\" from the calls.\n const assetAddresses = traceAssetChanges\n ? await Promise.all(\n parameters.calls.map(async (call: any) => {\n if (!call.data && !call.abi) return\n const { accessList } = await createAccessList(client, {\n account: account!.address,\n ...call,\n data: call.abi ? encodeFunctionData(call) : call.data,\n })\n return accessList.map(({ address, storageKeys }) =>\n storageKeys.length > 0 ? address : null,\n )\n }),\n ).then((x) => x.flat().filter(Boolean))\n : []\n\n const resultsStateOverrides = stateOverrides?.map((override) => {\n if (override.address === account?.address)\n return {\n ...override,\n nonce: 0,\n }\n return override\n })\n\n const blocks = await simulateBlocks(client, {\n blockNumber,\n blockTag: blockTag as undefined,\n blocks: [\n ...(traceAssetChanges\n ? [\n // ETH pre balances\n {\n calls: [{ data: getBalanceData }],\n stateOverrides,\n },\n\n // Asset pre balances\n {\n calls: assetAddresses.map((address, i) => ({\n abi: [\n AbiFunction.from(\n 'function balanceOf(address) returns (uint256)',\n ),\n ],\n functionName: 'balanceOf',\n args: [account!.address],\n to: address,\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n ]\n : []),\n\n {\n calls: [...calls, {}].map((call, index) => ({\n ...(call as Call),\n from: account?.address,\n nonce: index,\n })) as any,\n stateOverrides: resultsStateOverrides,\n },\n\n ...(traceAssetChanges\n ? [\n // ETH post balances\n {\n calls: [{ data: getBalanceData }],\n },\n\n // Asset post balances\n {\n calls: assetAddresses.map((address, i) => ({\n abi: [\n AbiFunction.from(\n 'function balanceOf(address) returns (uint256)',\n ),\n ],\n functionName: 'balanceOf',\n args: [account!.address],\n to: address,\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Decimals\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [\n AbiFunction.from('function decimals() returns (uint256)'),\n ],\n functionName: 'decimals',\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Token URI\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [\n AbiFunction.from(\n 'function tokenURI(uint256) returns (string)',\n ),\n ],\n functionName: 'tokenURI',\n args: [0n],\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n\n // Symbols\n {\n calls: assetAddresses.map((address, i) => ({\n to: address,\n abi: [AbiFunction.from('function symbol() returns (string)')],\n functionName: 'symbol',\n from: zeroAddress,\n nonce: i,\n })),\n stateOverrides: [\n {\n address: zeroAddress,\n nonce: 0,\n },\n ],\n },\n ]\n : []),\n ],\n traceTransfers,\n validation,\n })\n\n const block_results = traceAssetChanges ? blocks[2] : blocks[0]\n const [\n block_ethPre,\n block_assetsPre,\n ,\n block_ethPost,\n block_assetsPost,\n block_decimals,\n block_tokenURI,\n block_symbols,\n ] = traceAssetChanges ? blocks : []\n\n // Extract call results from the simulation.\n const { calls: block_calls, ...block } = block_results\n const results = block_calls.slice(0, -1) ?? []\n\n // Extract pre-execution ETH and asset balances.\n const ethPre = block_ethPre?.calls ?? []\n const assetsPre = block_assetsPre?.calls ?? []\n const balancesPre = [...ethPre, ...assetsPre].map((call) =>\n call.status === 'success' ? hexToBigInt(call.data) : null,\n )\n\n // Extract post-execution ETH and asset balances.\n const ethPost = block_ethPost?.calls ?? []\n const assetsPost = block_assetsPost?.calls ?? []\n const balancesPost = [...ethPost, ...assetsPost].map((call) =>\n call.status === 'success' ? hexToBigInt(call.data) : null,\n )\n\n // Extract asset symbols & decimals.\n const decimals = (block_decimals?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (number | null)[]\n const symbols = (block_symbols?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (string | null)[]\n const tokenURI = (block_tokenURI?.calls ?? []).map((x) =>\n x.status === 'success' ? x.result : null,\n ) as (string | null)[]\n\n const changes: Mutable<SimulateCallsReturnType<calls>['assetChanges']> = []\n for (const [i, balancePost] of balancesPost.entries()) {\n const balancePre = balancesPre[i]\n\n if (typeof balancePost !== 'bigint') continue\n if (typeof balancePre !== 'bigint') continue\n\n const decimals_ = decimals[i - 1]\n const symbol_ = symbols[i - 1]\n const tokenURI_ = tokenURI[i - 1]\n\n const token = (() => {\n if (i === 0)\n return {\n address: ethAddress,\n decimals: 18,\n symbol: 'ETH',\n }\n\n return {\n address: assetAddresses[i - 1]! as Address,\n decimals: tokenURI_ || decimals_ ? Number(decimals_ ?? 1) : undefined,\n symbol: symbol_ ?? undefined,\n }\n })()\n\n if (changes.some((change) => change.token.address === token.address))\n continue\n\n changes.push({\n token,\n value: {\n pre: balancePre,\n post: balancePost,\n diff: balancePost - balancePre,\n },\n })\n }\n\n return {\n assetChanges: changes,\n block,\n results,\n } as unknown as SimulateCallsReturnType<calls>\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type HexToBigIntErrorType, hexToBigInt } from '../encoding/fromHex.js'\nimport { hexToBytes } from '../encoding/toBytes.js'\nimport type { ToHexErrorType } from '../encoding/toHex.js'\n\ntype To = 'bytes' | 'hex'\n\nexport type SerializeSignatureParameters<to extends To = 'hex'> = Signature & {\n to?: to | To | undefined\n}\n\nexport type SerializeSignatureReturnType<to extends To = 'hex'> =\n | (to extends 'hex' ? Hex : never)\n | (to extends 'bytes' ? ByteArray : never)\n\nexport type SerializeSignatureErrorType =\n | HexToBigIntErrorType\n | ToHexErrorType\n | ErrorType\n\n/**\n * @description Converts a signature into hex format.\n *\n * @param signature The signature to convert.\n * @returns The signature in hex format.\n *\n * @example\n * serializeSignature({\n * r: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf',\n * s: '0x4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8',\n * yParity: 1\n * })\n * // \"0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c\"\n */\nexport function serializeSignature<to extends To = 'hex'>({\n r,\n s,\n to = 'hex',\n v,\n yParity,\n}: SerializeSignatureParameters<to>): SerializeSignatureReturnType<to> {\n const yParity_ = (() => {\n if (yParity === 0 || yParity === 1) return yParity\n if (v && (v === 27n || v === 28n || v >= 35n)) return v % 2n === 0n ? 1 : 0\n throw new Error('Invalid `v` or `yParity` value')\n })()\n const signature = `0x${new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).toCompactHex()}${yParity_ === 0 ? '1b' : '1c'}` as const\n\n if (to === 'hex') return signature as SerializeSignatureReturnType<to>\n return hexToBytes(signature) as SerializeSignatureReturnType<to>\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { universalSignatureValidatorAbi } from '../../constants/abis.js'\nimport { universalSignatureValidatorByteCode } from '../../constants/contracts.js'\nimport { CallExecutionError } from '../../errors/contract.js'\nimport type { InvalidHexBooleanError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type EncodeDeployDataErrorType,\n encodeDeployData,\n} from '../../utils/abi/encodeDeployData.js'\nimport { getAddress } from '../../utils/address/getAddress.js'\nimport { isAddressEqual } from '../../utils/address/isAddressEqual.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { type ToHexErrorType, bytesToHex } from '../../utils/encoding/toHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { encodeFunctionData, hexToBool } from '../../utils/index.js'\nimport { isErc6492Signature } from '../../utils/signature/isErc6492Signature.js'\nimport { recoverAddress } from '../../utils/signature/recoverAddress.js'\nimport { serializeErc6492Signature } from '../../utils/signature/serializeErc6492Signature.js'\nimport { serializeSignature } from '../../utils/signature/serializeSignature.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type VerifyHashParameters = Pick<\n CallParameters,\n 'blockNumber' | 'blockTag'\n> & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex | ByteArray | Signature\n universalSignatureVerifierAddress?: Address | undefined\n} & OneOf<{ factory: Address; factoryData: Hex } | {}>\n\nexport type VerifyHashReturnType = boolean\n\nexport type VerifyHashErrorType =\n | CallErrorType\n | IsHexErrorType\n | ToHexErrorType\n | InvalidHexBooleanError\n | EncodeDeployDataErrorType\n | ErrorType\n\n/**\n * Verifies a message hash onchain using ERC-6492.\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyHashParameters}\n * @returns Whether or not the signature is valid. {@link VerifyHashReturnType}\n */\nexport async function verifyHash<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: VerifyHashParameters,\n): Promise<VerifyHashReturnType> {\n const {\n address,\n factory,\n factoryData,\n hash,\n signature,\n universalSignatureVerifierAddress = client.chain?.contracts\n ?.universalSignatureVerifier?.address,\n ...rest\n } = parameters\n\n const signatureHex = (() => {\n if (isHex(signature)) return signature\n if (typeof signature === 'object' && 'r' in signature && 's' in signature)\n return serializeSignature(signature)\n return bytesToHex(signature)\n })()\n\n const wrappedSignature = await (async () => {\n // If no `factory` or `factoryData` is provided, it is assumed that the\n // address is not a Smart Account, or the Smart Account is already deployed.\n if (!factory && !factoryData) return signatureHex\n\n // If the signature is already wrapped, return the signature.\n if (isErc6492Signature(signatureHex)) return signatureHex\n\n // If the Smart Account is not deployed, wrap the signature with a 6492 wrapper\n // to perform counterfactual validation.\n return serializeErc6492Signature({\n address: factory!,\n data: factoryData!,\n signature: signatureHex,\n })\n })()\n\n try {\n const args = universalSignatureVerifierAddress\n ? ({\n to: universalSignatureVerifierAddress,\n data: encodeFunctionData({\n abi: universalSignatureValidatorAbi,\n functionName: 'isValidSig',\n args: [address, hash, wrappedSignature],\n }),\n ...rest,\n } as unknown as CallParameters)\n : ({\n data: encodeDeployData({\n abi: universalSignatureValidatorAbi,\n args: [address, hash, wrappedSignature],\n bytecode: universalSignatureValidatorByteCode,\n }),\n ...rest,\n } as unknown as CallParameters)\n\n const { data } = await getAction(client, call, 'call')(args)\n\n return hexToBool(data ?? '0x0')\n } catch (error) {\n // Fallback attempt to verify the signature via ECDSA recovery.\n try {\n const verified = isAddressEqual(\n getAddress(address),\n await recoverAddress({ hash, signature }),\n )\n if (verified) return true\n } catch {}\n\n if (error instanceof CallExecutionError) {\n // if the execution fails, the signature was not valid and an internal method inside of the validator reverted\n // this can happen for many reasons, for example if signer can not be recovered from the signature\n // or if the signature has no valid format\n return false\n }\n\n throw error\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ByteArray,\n Hex,\n SignableMessage,\n Signature,\n} from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport { hashMessage } from '../../utils/signature/hashMessage.js'\nimport type { HashMessageErrorType } from '../../utils/signature/hashMessage.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from './verifyHash.js'\n\nexport type VerifyMessageParameters = Prettify<\n Omit<VerifyHashParameters, 'hash'> & {\n /** The address that signed the original message. */\n address: Address\n /** The message to be verified. */\n message: SignableMessage\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex | ByteArray | Signature\n }\n>\n\nexport type VerifyMessageReturnType = boolean\n\nexport type VerifyMessageErrorType =\n | HashMessageErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verify that a message was signed by the provided address.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyMessage}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifyMessageReturnType}\n */\nexport async function verifyMessage<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n {\n address,\n message,\n factory,\n factoryData,\n signature,\n ...callRequest\n }: VerifyMessageParameters,\n): Promise<VerifyMessageReturnType> {\n const hash = hashMessage(message)\n return verifyHash(client, {\n address,\n factory: factory!,\n factoryData: factoryData!,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Address, TypedData } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n type HashTypedDataErrorType,\n hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from './verifyHash.js'\n\nexport type VerifyTypedDataParameters<\n typedData extends TypedData | Record<string, unknown> = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = Omit<VerifyHashParameters, 'hash'> &\n TypedDataDefinition<typedData, primaryType> & {\n /** The address to verify the typed data for. */\n address: Address\n /** The signature to verify */\n signature: Hex | ByteArray | Signature\n }\n\nexport type VerifyTypedDataReturnType = boolean\n\nexport type VerifyTypedDataErrorType =\n | HashTypedDataErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verify that typed data was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyTypedData}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyTypedDataParameters}\n * @returns Whether or not the signature is valid. {@link VerifyTypedDataReturnType}\n */\nexport async function verifyTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n chain extends Chain | undefined,\n>(\n client: Client<Transport, chain>,\n parameters: VerifyTypedDataParameters<typedData, primaryType>,\n): Promise<VerifyTypedDataReturnType> {\n const {\n address,\n factory,\n factoryData,\n signature,\n message,\n primaryType,\n types,\n domain,\n ...callRequest\n } = parameters as VerifyTypedDataParameters\n const hash = hashTypedData({ message, primaryType, types, domain })\n return verifyHash(client, {\n address,\n factory: factory!,\n factoryData: factoryData!,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { HasTransportType } from '../../types/transport.js'\nimport { hexToBigInt } from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport {\n type GetBlockNumberReturnType,\n getBlockNumber,\n} from './getBlockNumber.js'\n\nexport type OnBlockNumberParameter = GetBlockNumberReturnType\nexport type OnBlockNumberFn = (\n blockNumber: OnBlockNumberParameter,\n prevBlockNumber: OnBlockNumberParameter | undefined,\n) => void\n\nexport type WatchBlockNumberParameters<\n transport extends Transport = Transport,\n> = {\n /** The callback to call when a new block number is received. */\n onBlockNumber: OnBlockNumberFn\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n} & (\n | (HasTransportType<transport, 'webSocket'> extends true\n ? {\n emitMissed?: undefined\n emitOnBegin?: undefined\n /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n poll?: false | undefined\n pollingInterval?: undefined\n }\n : never)\n | {\n /** Whether or not to emit the missed block numbers to the callback. */\n emitMissed?: boolean | undefined\n /** Whether or not to emit the latest block number to the callback when the subscription opens. */\n emitOnBegin?: boolean | undefined\n poll?: true | undefined\n /** Polling frequency (in ms). Defaults to Client's pollingInterval config. */\n pollingInterval?: number | undefined\n }\n)\n\nexport type WatchBlockNumberReturnType = () => void\n\nexport type WatchBlockNumberErrorType = PollErrorType | ErrorType\n\n/**\n * Watches and returns incoming block numbers.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlockNumberParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, watchBlockNumber, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchBlockNumber(client, {\n * onBlockNumber: (blockNumber) => console.log(blockNumber),\n * })\n */\nexport function watchBlockNumber<\n chain extends Chain | undefined,\n transport extends Transport,\n>(\n client: Client<transport, chain>,\n {\n emitOnBegin = false,\n emitMissed = false,\n onBlockNumber,\n onError,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchBlockNumberParameters<transport>,\n): WatchBlockNumberReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (client.transport.type === 'webSocket') return false\n if (\n client.transport.type === 'fallback' &&\n client.transport.transports[0].config.type === 'webSocket'\n )\n return false\n return true\n })()\n\n let prevBlockNumber: GetBlockNumberReturnType | undefined\n\n const pollBlockNumber = () => {\n const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n pollingInterval,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) =>\n poll(\n async () => {\n try {\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({ cacheTime: 0 })\n\n if (prevBlockNumber) {\n // If the current block number is the same as the previous,\n // we can skip.\n if (blockNumber === prevBlockNumber) return\n\n // If we have missed out on some previous blocks, and the\n // `emitMissed` flag is truthy, let's emit those blocks.\n if (blockNumber - prevBlockNumber > 1 && emitMissed) {\n for (let i = prevBlockNumber + 1n; i < blockNumber; i++) {\n emit.onBlockNumber(i, prevBlockNumber)\n prevBlockNumber = i\n }\n }\n }\n\n // If the next block number is greater than the previous,\n // it is not in the past, and we can emit the new block number.\n if (!prevBlockNumber || blockNumber > prevBlockNumber) {\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n }\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin,\n interval: pollingInterval,\n },\n ),\n )\n }\n\n const subscribeBlockNumber = () => {\n const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType<Transport>) =>\n transport.config.type === 'webSocket',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['newHeads'],\n onData(data: any) {\n if (!active) return\n const blockNumber = hexToBigInt(data.result?.number)\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n },\n onError(error: Error) {\n emit.onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n })\n }\n\n return enablePolling ? pollBlockNumber() : subscribeBlockNumber()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { BlockNotFoundError } from '../../errors/block.js'\nimport {\n TransactionNotFoundError,\n TransactionReceiptNotFoundError,\n WaitForTransactionReceiptTimeoutError,\n type WaitForTransactionReceiptTimeoutErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Transaction } from '../../types/transaction.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { withResolvers } from '../../utils/promise/withResolvers.js'\nimport {\n type WithRetryParameters,\n withRetry,\n} from '../../utils/promise/withRetry.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport {\n type GetTransactionErrorType,\n type GetTransactionReturnType,\n getTransaction,\n} from './getTransaction.js'\nimport {\n type GetTransactionReceiptErrorType,\n type GetTransactionReceiptReturnType,\n getTransactionReceipt,\n} from './getTransactionReceipt.js'\nimport {\n type WatchBlockNumberErrorType,\n watchBlockNumber,\n} from './watchBlockNumber.js'\n\nexport type ReplacementReason = 'cancelled' | 'replaced' | 'repriced'\nexport type ReplacementReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n reason: ReplacementReason\n replacedTransaction: Transaction\n transaction: Transaction\n transactionReceipt: GetTransactionReceiptReturnType<chain>\n}\n\nexport type WaitForTransactionReceiptReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = GetTransactionReceiptReturnType<chain>\n\nexport type WaitForTransactionReceiptParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n /**\n * The number of confirmations (blocks that have passed) to wait before resolving.\n * @default 1\n */\n confirmations?: number | undefined\n /** The hash of the transaction. */\n hash: Hash\n /** Optional callback to emit if the transaction has been replaced. */\n onReplaced?: ((response: ReplacementReturnType<chain>) => void) | undefined\n /**\n * Polling frequency (in ms). Defaults to the client's pollingInterval config.\n * @default client.pollingInterval\n */\n pollingInterval?: number | undefined\n /**\n * Number of times to retry if the transaction or block is not found.\n * @default 6 (exponential backoff)\n */\n retryCount?: WithRetryParameters['retryCount'] | undefined\n /**\n * Time to wait (in ms) between retries.\n * @default `({ count }) => ~~(1 << count) * 200` (exponential backoff)\n */\n retryDelay?: WithRetryParameters['delay'] | undefined\n /**\n * Optional timeout (in milliseconds) to wait before stopping polling.\n * @default 180_000\n */\n timeout?: number | undefined\n}\n\nexport type WaitForTransactionReceiptErrorType =\n | ObserveErrorType\n | GetBlockErrorType\n | GetTransactionErrorType\n | GetTransactionReceiptErrorType\n | WatchBlockNumberErrorType\n | WaitForTransactionReceiptTimeoutErrorType\n | ErrorType\n\n/**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt).\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_sending-transactions\n * - JSON-RPC Methods:\n * - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n * - If a Transaction has been replaced:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n * - Checks if one of the Transactions is a replacement\n * - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n *\n * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n *\n * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n *\n * There are 3 types of Transaction Replacement reasons:\n *\n * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n *\n * @param client - Client to use\n * @param parameters - {@link WaitForTransactionReceiptParameters}\n * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, waitForTransactionReceipt, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await waitForTransactionReceipt(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function waitForTransactionReceipt<\n chain extends Chain | undefined,\n>(\n client: Client<Transport, chain>,\n {\n confirmations = 1,\n hash,\n onReplaced,\n pollingInterval = client.pollingInterval,\n retryCount = 6,\n retryDelay = ({ count }) => ~~(1 << count) * 200, // exponential backoff\n timeout = 180_000,\n }: WaitForTransactionReceiptParameters<chain>,\n): Promise<WaitForTransactionReceiptReturnType<chain>> {\n const observerId = stringify(['waitForTransactionReceipt', client.uid, hash])\n\n let transaction: GetTransactionReturnType<chain> | undefined\n let replacedTransaction: GetTransactionReturnType<chain> | undefined\n let receipt: GetTransactionReceiptReturnType<chain>\n let retrying = false\n\n const { promise, resolve, reject } =\n withResolvers<WaitForTransactionReceiptReturnType<chain>>()\n\n const timer = timeout\n ? setTimeout(\n () => reject(new WaitForTransactionReceiptTimeoutError({ hash })),\n timeout,\n )\n : undefined\n\n const _unobserve = observe(\n observerId,\n { onReplaced, resolve, reject },\n (emit) => {\n const _unwatch = getAction(\n client,\n watchBlockNumber,\n 'watchBlockNumber',\n )({\n emitMissed: true,\n emitOnBegin: true,\n poll: true,\n pollingInterval,\n async onBlockNumber(blockNumber_) {\n const done = (fn: () => void) => {\n clearTimeout(timer)\n _unwatch()\n fn()\n _unobserve()\n }\n\n let blockNumber = blockNumber_\n\n if (retrying) return\n\n try {\n // If we already have a valid receipt, let's check if we have enough\n // confirmations. If we do, then we can resolve.\n if (receipt) {\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n done(() => emit.resolve(receipt))\n return\n }\n\n // Get the transaction to check if it's been replaced.\n // We need to retry as some RPC Providers may be slow to sync\n // up mined transactions.\n if (!transaction) {\n retrying = true\n await withRetry(\n async () => {\n transaction = (await getAction(\n client,\n getTransaction,\n 'getTransaction',\n )({ hash })) as GetTransactionReturnType<chain>\n if (transaction.blockNumber)\n blockNumber = transaction.blockNumber\n },\n {\n delay: retryDelay,\n retryCount,\n },\n )\n retrying = false\n }\n\n // Get the receipt to check if it's been processed.\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({ hash })\n\n // Check if we have enough confirmations. If not, continue polling.\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n done(() => emit.resolve(receipt))\n } catch (err) {\n // If the receipt is not found, the transaction will be pending.\n // We need to check if it has potentially been replaced.\n if (\n err instanceof TransactionNotFoundError ||\n err instanceof TransactionReceiptNotFoundError\n ) {\n if (!transaction) {\n retrying = false\n return\n }\n\n try {\n replacedTransaction = transaction\n\n // Let's retrieve the transactions from the current block.\n // We need to retry as some RPC Providers may be slow to sync\n // up mined blocks.\n retrying = true\n const block = await withRetry(\n () =>\n getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber,\n includeTransactions: true,\n }),\n {\n delay: retryDelay,\n retryCount,\n shouldRetry: ({ error }) =>\n error instanceof BlockNotFoundError,\n },\n )\n retrying = false\n\n const replacementTransaction = (\n block.transactions as {} as Transaction[]\n ).find(\n ({ from, nonce }) =>\n from === replacedTransaction!.from &&\n nonce === replacedTransaction!.nonce,\n )\n\n // If we couldn't find a replacement transaction, continue polling.\n if (!replacementTransaction) return\n\n // If we found a replacement transaction, return it's receipt.\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({\n hash: replacementTransaction.hash,\n })\n\n // Check if we have enough confirmations. If not, continue polling.\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n let reason: ReplacementReason = 'replaced'\n if (\n replacementTransaction.to === replacedTransaction.to &&\n replacementTransaction.value === replacedTransaction.value &&\n replacementTransaction.input === replacedTransaction.input\n ) {\n reason = 'repriced'\n } else if (\n replacementTransaction.from === replacementTransaction.to &&\n replacementTransaction.value === 0n\n ) {\n reason = 'cancelled'\n }\n\n done(() => {\n emit.onReplaced?.({\n reason,\n replacedTransaction: replacedTransaction! as any,\n transaction: replacementTransaction,\n transactionReceipt: receipt,\n })\n emit.resolve(receipt)\n })\n } catch (err_) {\n done(() => emit.reject(err_))\n }\n } else {\n done(() => emit.reject(err))\n }\n }\n },\n })\n },\n )\n\n return promise\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { HasTransportType } from '../../types/transport.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockReturnType, getBlock } from './getBlock.js'\n\nexport type OnBlockParameter<\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = GetBlockReturnType<chain, includeTransactions, blockTag>\n\nexport type OnBlock<\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = (\n block: OnBlockParameter<chain, includeTransactions, blockTag>,\n prevBlock: OnBlockParameter<chain, includeTransactions, blockTag> | undefined,\n) => void\n\nexport type WatchBlocksParameters<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = {\n /** The callback to call when a new block is received. */\n onBlock: OnBlock<chain, includeTransactions, blockTag>\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n} & (\n | (HasTransportType<transport, 'webSocket'> extends true\n ? {\n blockTag?: undefined\n emitMissed?: undefined\n emitOnBegin?: undefined\n includeTransactions?: undefined\n /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n poll?: false | undefined\n pollingInterval?: undefined\n }\n : never)\n | {\n /** The block tag. Defaults to \"latest\". */\n blockTag?: blockTag | BlockTag | undefined\n /** Whether or not to emit the missed blocks to the callback. */\n emitMissed?: boolean | undefined\n /** Whether or not to emit the block to the callback when the subscription opens. */\n emitOnBegin?: boolean | undefined\n /** Whether or not to include transaction data in the response. */\n includeTransactions?: includeTransactions | undefined\n poll?: true | undefined\n /** Polling frequency (in ms). Defaults to the client's pollingInterval config. */\n pollingInterval?: number | undefined\n }\n)\n\nexport type WatchBlocksReturnType = () => void\n\nexport type WatchBlocksErrorType =\n | StringifyErrorType\n | PollErrorType\n | ErrorType\n\n/**\n * Watches and returns information for incoming blocks.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlocks\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlocksParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlocksReturnType}\n *\n * @example\n * import { createPublicClient, watchBlocks, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchBlocks(client, {\n * onBlock: (block) => console.log(block),\n * })\n */\nexport function watchBlocks<\n transport extends Transport,\n chain extends Chain | undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client<transport, chain>,\n {\n blockTag = 'latest',\n emitMissed = false,\n emitOnBegin = false,\n onBlock,\n onError,\n includeTransactions: includeTransactions_,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchBlocksParameters<transport, chain, includeTransactions, blockTag>,\n): WatchBlocksReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (client.transport.type === 'webSocket') return false\n if (\n client.transport.type === 'fallback' &&\n client.transport.transports[0].config.type === 'webSocket'\n )\n return false\n return true\n })()\n const includeTransactions = includeTransactions_ ?? false\n\n let prevBlock:\n | GetBlockReturnType<chain, false | includeTransactions, 'latest'>\n | undefined\n\n const pollBlocks = () => {\n const observerId = stringify([\n 'watchBlocks',\n client.uid,\n blockTag,\n emitMissed,\n emitOnBegin,\n includeTransactions,\n pollingInterval,\n ])\n\n return observe(observerId, { onBlock, onError }, (emit) =>\n poll(\n async () => {\n try {\n const block = await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockTag,\n includeTransactions,\n })\n if (block.number && prevBlock?.number) {\n // If the current block number is the same as the previous,\n // we can skip.\n if (block.number === prevBlock.number) return\n\n // If we have missed out on some previous blocks, and the\n // `emitMissed` flag is truthy, let's emit those blocks.\n if (block.number - prevBlock.number > 1 && emitMissed) {\n for (let i = prevBlock?.number + 1n; i < block.number; i++) {\n const block = (await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber: i,\n includeTransactions,\n })) as GetBlockReturnType<chain>\n emit.onBlock(block as any, prevBlock as any)\n prevBlock = block\n }\n }\n }\n\n if (\n // If no previous block exists, emit.\n !prevBlock?.number ||\n // If the block tag is \"pending\" with no block number, emit.\n (blockTag === 'pending' && !block?.number) ||\n // If the next block number is greater than the previous block number, emit.\n // We don't want to emit blocks in the past.\n (block.number && block.number > prevBlock.number)\n ) {\n emit.onBlock(block as any, prevBlock as any)\n prevBlock = block as any\n }\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin,\n interval: pollingInterval,\n },\n ),\n )\n }\n\n const subscribeBlocks = () => {\n let active = true\n let emitFetched = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n if (emitOnBegin) {\n getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockTag,\n includeTransactions,\n }).then((block) => {\n if (!active) return\n if (!emitFetched) return\n onBlock(block as any, undefined)\n emitFetched = false\n })\n }\n\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType<Transport>) =>\n transport.config.type === 'webSocket',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['newHeads'],\n async onData(data: any) {\n if (!active) return\n const block = (await getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber: data.blockNumber,\n includeTransactions,\n }).catch(() => {})) as GetBlockReturnType<chain>\n if (!active) return\n onBlock(block as any, prevBlock as any)\n emitFetched = false\n prevBlock = block\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling ? pollBlocks() : subscribeBlocks()\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport {\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport {\n DecodeLogDataMismatch,\n DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber } from '../../types/block.js'\nimport { decodeEventLog } from '../../utils/abi/decodeEventLog.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type CreateEventFilterParameters,\n createEventFilter,\n} from './createEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { type GetLogsParameters, getLogs } from './getLogs.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type WatchEventOnLogsParameter<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n eventName extends string | undefined = MaybeAbiEventName<abiEvent>,\n> = Log<bigint, number, false, abiEvent, strict, abiEvents, eventName>[]\nexport type WatchEventOnLogsFn<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName<abiEvent>,\n> = (\n logs: WatchEventOnLogsParameter<abiEvent, abiEvents, strict, _eventName>,\n) => void\n\nexport type WatchEventParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n //\n _eventName extends string | undefined = MaybeAbiEventName<abiEvent>,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Block to start listening from. */\n fromBlock?: BlockNumber<bigint> | undefined\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new event logs are received. */\n onLogs: WatchEventOnLogsFn<abiEvent, abiEvents, strict, _eventName>\n} & GetPollOptions<transport> &\n (\n | {\n event: abiEvent\n events?: undefined\n args?: MaybeExtractEventArgsFromAbi<abiEvents, _eventName> | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: abiEvents | undefined\n args?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: undefined\n args?: undefined\n strict?: undefined\n }\n )\n\nexport type WatchEventReturnType = () => void\n\nexport type WatchEventErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns emitted [Event Logs](https://viem.sh/docs/glossary/terms#event-log).\n *\n * - Docs: https://viem.sh/docs/actions/public/watchEvent\n * - JSON-RPC Methods:\n * - **RPC Provider supports `eth_newFilter`:**\n * - Calls [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) to create a filter (called on initialize).\n * - On a polling interval, it will call [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges).\n * - **RPC Provider does not support `eth_newFilter`:**\n * - Calls [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) for each block between the polling interval.\n *\n * This Action will batch up all the Event Logs found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/actions/public/watchEvent#onLogs).\n *\n * `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/actions/public/createEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchEventParameters}\n * @returns A function that can be invoked to stop watching for new Event Logs. {@link WatchEventReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchEvent } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchEvent(client, {\n * onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchEvent<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n _eventName extends string | undefined = undefined,\n>(\n client: Client<transport, chain>,\n {\n address,\n args,\n batch = true,\n event,\n events,\n fromBlock,\n onError,\n onLogs,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n strict: strict_,\n }: WatchEventParameters<abiEvent, abiEvents, strict, transport>,\n): WatchEventReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (typeof fromBlock === 'bigint') return true\n if (client.transport.type === 'webSocket') return false\n if (\n client.transport.type === 'fallback' &&\n client.transport.transports[0].config.type === 'webSocket'\n )\n return false\n return true\n })()\n const strict = strict_ ?? false\n\n const pollEvent = () => {\n const observerId = stringify([\n 'watchEvent',\n address,\n args,\n batch,\n client.uid,\n event,\n pollingInterval,\n fromBlock,\n ])\n\n return observe(observerId, { onLogs, onError }, (emit) => {\n let previousBlockNumber: bigint\n if (fromBlock !== undefined) previousBlockNumber = fromBlock - 1n\n let filter: Filter<'event', abiEvents, _eventName, any>\n let initialized = false\n\n const unwatch = poll(\n async () => {\n if (!initialized) {\n try {\n filter = (await getAction(\n client,\n createEventFilter as any,\n 'createEventFilter',\n )({\n address,\n args,\n event: event!,\n events,\n strict,\n fromBlock,\n } as unknown as CreateEventFilterParameters)) as unknown as Filter<\n 'event',\n abiEvents,\n _eventName\n >\n } catch {}\n initialized = true\n return\n }\n\n try {\n let logs: Log[]\n if (filter) {\n logs = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n } else {\n // If the filter doesn't exist, we will fall back to use `getLogs`.\n // The fall back exists because some RPC Providers do not support filters.\n\n // Fetch the block number to use for `getLogs`.\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({})\n\n // If the block number has changed, we will need to fetch the logs.\n // If the block number doesn't exist, we are yet to reach the first poll interval,\n // so do not emit any logs.\n if (previousBlockNumber && previousBlockNumber !== blockNumber) {\n logs = await getAction(\n client,\n getLogs,\n 'getLogs',\n )({\n address,\n args,\n event: event!,\n events,\n fromBlock: previousBlockNumber + 1n,\n toBlock: blockNumber,\n } as unknown as GetLogsParameters)\n } else {\n logs = []\n }\n previousBlockNumber = blockNumber\n }\n\n if (logs.length === 0) return\n if (batch) emit.onLogs(logs as any)\n else for (const log of logs) emit.onLogs([log] as any)\n } catch (err) {\n // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n // Reinitialize the filter when this occurs\n if (filter && err instanceof InvalidInputRpcError)\n initialized = false\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribeEvent = () => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType<Transport>) =>\n transport.config.type === 'webSocket',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const events_ = events ?? (event ? [event] : undefined)\n let topics: LogTopic[] = []\n if (events_) {\n const encoded = (events_ as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['logs', { address, topics }],\n onData(data: any) {\n if (!active) return\n const log = data.result\n try {\n const { eventName, args } = decodeEventLog({\n abi: events_ ?? [],\n data: log.data,\n topics: log.topics,\n strict,\n })\n const formatted = formatLog(log, { args, eventName })\n onLogs([formatted] as any)\n } catch (err) {\n let eventName: string | undefined\n let isUnnamed: boolean | undefined\n if (\n err instanceof DecodeLogDataMismatch ||\n err instanceof DecodeLogTopicsMismatch\n ) {\n // If strict mode is on, and log data/topics do not match event definition, skip.\n if (strict_) return\n eventName = err.abiItem.name\n isUnnamed = err.abiItem.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n }\n\n // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n const formatted = formatLog(log, {\n args: isUnnamed ? [] : {},\n eventName,\n })\n onLogs([formatted] as any)\n }\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling ? pollEvent() : subscribeEvent()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport { createPendingTransactionFilter } from './createPendingTransactionFilter.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type OnTransactionsParameter = Hash[]\nexport type OnTransactionsFn = (transactions: OnTransactionsParameter) => void\n\nexport type WatchPendingTransactionsParameters<\n transport extends Transport = Transport,\n> = {\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new transactions are received. */\n onTransactions: OnTransactionsFn\n} & GetPollOptions<transport>\n\nexport type WatchPendingTransactionsReturnType = () => void\n\nexport type WatchPendingTransactionsErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns pending transaction hashes.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchPendingTransactions\n * - JSON-RPC Methods:\n * - When `poll: true`\n * - Calls [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) to initialize the filter.\n * - Calls [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newPendingTransactions\"` event.\n *\n * This Action will batch up all the pending transactions found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchPendingTransactions#pollinginterval-optional), and invoke them via [`onTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions#ontransactions).\n *\n * @param client - Client to use\n * @param parameters - {@link WatchPendingTransactionsParameters}\n * @returns A function that can be invoked to stop watching for new pending transaction hashes. {@link WatchPendingTransactionsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchPendingTransactions } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await watchPendingTransactions(client, {\n * onTransactions: (hashes) => console.log(hashes),\n * })\n */\nexport function watchPendingTransactions<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n client: Client<transport, chain>,\n {\n batch = true,\n onError,\n onTransactions,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchPendingTransactionsParameters<transport>,\n) {\n const enablePolling =\n typeof poll_ !== 'undefined' ? poll_ : client.transport.type !== 'webSocket'\n\n const pollPendingTransactions = () => {\n const observerId = stringify([\n 'watchPendingTransactions',\n client.uid,\n batch,\n pollingInterval,\n ])\n return observe(observerId, { onTransactions, onError }, (emit) => {\n let filter: Filter<'transaction'>\n\n const unwatch = poll(\n async () => {\n try {\n if (!filter) {\n try {\n filter = await getAction(\n client,\n createPendingTransactionFilter,\n 'createPendingTransactionFilter',\n )({})\n return\n } catch (err) {\n unwatch()\n throw err\n }\n }\n\n const hashes = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n if (hashes.length === 0) return\n if (batch) emit.onTransactions(hashes)\n else for (const hash of hashes) emit.onTransactions([hash])\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribePendingTransactions = () => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({\n params: ['newPendingTransactions'],\n onData(data: any) {\n if (!active) return\n const transaction = data.result\n onTransactions([transaction])\n },\n onError(error: Error) {\n onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n }\n\n return enablePolling\n ? pollPendingTransactions()\n : subscribePendingTransactions()\n}\n","import type { Address } from 'abitype'\n\nimport type { ExactPartial, Prettify } from '../../types/utils.js'\nimport type { SiweMessage } from './types.js'\n\n/**\n * @description Parses EIP-4361 formatted message into message fields object.\n *\n * @see https://eips.ethereum.org/EIPS/eip-4361\n *\n * @returns EIP-4361 fields object\n */\nexport function parseSiweMessage(\n message: string,\n): Prettify<ExactPartial<SiweMessage>> {\n const { scheme, statement, ...prefix } = (message.match(prefixRegex)\n ?.groups ?? {}) as {\n address: Address\n domain: string\n scheme?: string\n statement?: string\n }\n const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } =\n (message.match(suffixRegex)?.groups ?? {}) as {\n chainId: string\n expirationTime?: string\n issuedAt?: string\n nonce: string\n notBefore?: string\n requestId?: string\n uri: string\n version: '1'\n }\n const resources = message.split('Resources:')[1]?.split('\\n- ').slice(1)\n return {\n ...prefix,\n ...suffix,\n ...(chainId ? { chainId: Number(chainId) } : {}),\n ...(expirationTime ? { expirationTime: new Date(expirationTime) } : {}),\n ...(issuedAt ? { issuedAt: new Date(issuedAt) } : {}),\n ...(notBefore ? { notBefore: new Date(notBefore) } : {}),\n ...(requestId ? { requestId } : {}),\n ...(resources ? { resources } : {}),\n ...(scheme ? { scheme } : {}),\n ...(statement ? { statement } : {}),\n }\n}\n\n// https://regexr.com/80gdj\nconst prefixRegex =\n /^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\\/\\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\\n)(?<address>0x[a-fA-F0-9]{40})\\n\\n(?:(?<statement>.*)\\n\\n)?/\n\n// https://regexr.com/80gf9\nconst suffixRegex =\n /(?:URI: (?<uri>.+))\\n(?:Version: (?<version>.+))\\n(?:Chain ID: (?<chainId>\\d+))\\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\\n(?:Issued At: (?<issuedAt>.+))(?:\\nExpiration Time: (?<expirationTime>.+))?(?:\\nNot Before: (?<notBefore>.+))?(?:\\nRequest ID: (?<requestId>.+))?/\n","import type { Address } from 'abitype'\n\nimport type { ExactPartial } from '../../types/utils.js'\nimport { isAddressEqual } from '../address/isAddressEqual.js'\nimport type { SiweMessage } from './types.js'\n\nexport type ValidateSiweMessageParameters = {\n /**\n * Ethereum address to check against.\n */\n address?: Address | undefined\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.\n */\n domain?: string | undefined\n /**\n * EIP-4361 message fields.\n */\n message: ExactPartial<SiweMessage>\n /**\n * Random string to check against.\n */\n nonce?: string | undefined\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.\n */\n scheme?: string | undefined\n /**\n * Current time to check optional `expirationTime` and `notBefore` fields.\n *\n * @default new Date()\n */\n time?: Date | undefined\n}\n\nexport type ValidateSiweMessageReturnType = boolean\n\n/**\n * @description Validates EIP-4361 message.\n *\n * @see https://eips.ethereum.org/EIPS/eip-4361\n */\nexport function validateSiweMessage(\n parameters: ValidateSiweMessageParameters,\n): ValidateSiweMessageReturnType {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n time = new Date(),\n } = parameters\n\n if (domain && message.domain !== domain) return false\n if (nonce && message.nonce !== nonce) return false\n if (scheme && message.scheme !== scheme) return false\n\n if (message.expirationTime && time >= message.expirationTime) return false\n if (message.notBefore && time < message.notBefore) return false\n\n try {\n if (!message.address) return false\n if (address && !isAddressEqual(message.address, address)) return false\n } catch {\n return false\n }\n\n return true\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport { hashMessage } from '../../utils/signature/hashMessage.js'\nimport type { HashMessageErrorType } from '../../utils/signature/hashMessage.js'\nimport { parseSiweMessage } from '../../utils/siwe/parseSiweMessage.js'\nimport {\n type ValidateSiweMessageParameters,\n validateSiweMessage,\n} from '../../utils/siwe/validateSiweMessage.js'\nimport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n verifyHash,\n} from '../public/verifyHash.js'\n\nexport type VerifySiweMessageParameters = Prettify<\n Pick<VerifyHashParameters, 'blockNumber' | 'blockTag'> &\n Pick<\n ValidateSiweMessageParameters,\n 'address' | 'domain' | 'nonce' | 'scheme' | 'time'\n > & {\n /**\n * EIP-4361 formatted message.\n */\n message: string\n /**\n * Signature to check against.\n */\n signature: Hex\n }\n>\n\nexport type VerifySiweMessageReturnType = boolean\n\nexport type VerifySiweMessageErrorType =\n | HashMessageErrorType\n | VerifyHashErrorType\n | ErrorType\n\n/**\n * Verifies [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message was signed.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/siwe/actions/verifySiweMessage}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifySiweMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiweMessageReturnType}\n */\nexport async function verifySiweMessage<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: VerifySiweMessageParameters,\n): Promise<VerifySiweMessageReturnType> {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n signature,\n time = new Date(),\n ...callRequest\n } = parameters\n\n const parsed = parseSiweMessage(message)\n if (!parsed.address) return false\n\n const isValid = validateSiweMessage({\n address,\n domain,\n message: parsed,\n nonce,\n scheme,\n time,\n })\n if (!isValid) return false\n\n const hash = hashMessage(message)\n return verifyHash(client, {\n address: parsed.address,\n hash,\n signature,\n ...callRequest,\n })\n}\n","import type { Abi, AbiEvent, Address } from 'abitype'\n\nimport {\n type GetEnsAddressParameters,\n type GetEnsAddressReturnType,\n getEnsAddress,\n} from '../../actions/ens/getEnsAddress.js'\nimport {\n type GetEnsAvatarParameters,\n type GetEnsAvatarReturnType,\n getEnsAvatar,\n} from '../../actions/ens/getEnsAvatar.js'\nimport {\n type GetEnsNameParameters,\n type GetEnsNameReturnType,\n getEnsName,\n} from '../../actions/ens/getEnsName.js'\nimport {\n type GetEnsResolverParameters,\n type GetEnsResolverReturnType,\n getEnsResolver,\n} from '../../actions/ens/getEnsResolver.js'\nimport {\n type GetEnsTextParameters,\n type GetEnsTextReturnType,\n getEnsText,\n} from '../../actions/ens/getEnsText.js'\nimport {\n type CallParameters,\n type CallReturnType,\n call,\n} from '../../actions/public/call.js'\nimport {\n type CreateAccessListParameters,\n type CreateAccessListReturnType,\n createAccessList,\n} from '../../actions/public/createAccessList.js'\nimport {\n type CreateBlockFilterReturnType,\n createBlockFilter,\n} from '../../actions/public/createBlockFilter.js'\nimport {\n type CreateContractEventFilterParameters,\n type CreateContractEventFilterReturnType,\n createContractEventFilter,\n} from '../../actions/public/createContractEventFilter.js'\nimport {\n type CreateEventFilterParameters,\n type CreateEventFilterReturnType,\n createEventFilter,\n} from '../../actions/public/createEventFilter.js'\nimport {\n type CreatePendingTransactionFilterReturnType,\n createPendingTransactionFilter,\n} from '../../actions/public/createPendingTransactionFilter.js'\nimport {\n type EstimateContractGasParameters,\n type EstimateContractGasReturnType,\n estimateContractGas,\n} from '../../actions/public/estimateContractGas.js'\nimport {\n type EstimateFeesPerGasParameters,\n type EstimateFeesPerGasReturnType,\n estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n type EstimateGasParameters,\n type EstimateGasReturnType,\n estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n type EstimateMaxPriorityFeePerGasParameters,\n type EstimateMaxPriorityFeePerGasReturnType,\n estimateMaxPriorityFeePerGas,\n} from '../../actions/public/estimateMaxPriorityFeePerGas.js'\nimport {\n type GetBalanceParameters,\n type GetBalanceReturnType,\n getBalance,\n} from '../../actions/public/getBalance.js'\nimport {\n type GetBlobBaseFeeReturnType,\n getBlobBaseFee,\n} from '../../actions/public/getBlobBaseFee.js'\nimport {\n type GetBlockParameters,\n type GetBlockReturnType,\n getBlock,\n} from '../../actions/public/getBlock.js'\nimport {\n type GetBlockNumberParameters,\n type GetBlockNumberReturnType,\n getBlockNumber,\n} from '../../actions/public/getBlockNumber.js'\nimport {\n type GetBlockTransactionCountParameters,\n type GetBlockTransactionCountReturnType,\n getBlockTransactionCount,\n} from '../../actions/public/getBlockTransactionCount.js'\nimport {\n type GetChainIdReturnType,\n getChainId,\n} from '../../actions/public/getChainId.js'\nimport {\n type GetCodeParameters,\n type GetCodeReturnType,\n getCode,\n} from '../../actions/public/getCode.js'\nimport {\n type GetContractEventsParameters,\n type GetContractEventsReturnType,\n getContractEvents,\n} from '../../actions/public/getContractEvents.js'\nimport {\n type GetEip712DomainParameters,\n type GetEip712DomainReturnType,\n getEip712Domain,\n} from '../../actions/public/getEip712Domain.js'\nimport {\n type GetFeeHistoryParameters,\n type GetFeeHistoryReturnType,\n getFeeHistory,\n} from '../../actions/public/getFeeHistory.js'\nimport {\n type GetFilterChangesParameters,\n type GetFilterChangesReturnType,\n getFilterChanges,\n} from '../../actions/public/getFilterChanges.js'\nimport {\n type GetFilterLogsParameters,\n type GetFilterLogsReturnType,\n getFilterLogs,\n} from '../../actions/public/getFilterLogs.js'\nimport {\n type GetGasPriceReturnType,\n getGasPrice,\n} from '../../actions/public/getGasPrice.js'\nimport {\n type GetLogsParameters,\n type GetLogsReturnType,\n getLogs,\n} from '../../actions/public/getLogs.js'\nimport {\n type GetProofParameters,\n type GetProofReturnType,\n getProof,\n} from '../../actions/public/getProof.js'\nimport {\n type GetStorageAtParameters,\n type GetStorageAtReturnType,\n getStorageAt,\n} from '../../actions/public/getStorageAt.js'\nimport {\n type GetTransactionParameters,\n type GetTransactionReturnType,\n getTransaction,\n} from '../../actions/public/getTransaction.js'\nimport {\n type GetTransactionConfirmationsParameters,\n type GetTransactionConfirmationsReturnType,\n getTransactionConfirmations,\n} from '../../actions/public/getTransactionConfirmations.js'\nimport {\n type GetTransactionCountParameters,\n type GetTransactionCountReturnType,\n getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport {\n type GetTransactionReceiptParameters,\n type GetTransactionReceiptReturnType,\n getTransactionReceipt,\n} from '../../actions/public/getTransactionReceipt.js'\nimport {\n type MulticallParameters,\n type MulticallReturnType,\n multicall,\n} from '../../actions/public/multicall.js'\nimport {\n type ReadContractParameters,\n type ReadContractReturnType,\n readContract,\n} from '../../actions/public/readContract.js'\nimport {\n type SimulateBlocksParameters,\n type SimulateBlocksReturnType,\n simulateBlocks,\n} from '../../actions/public/simulateBlocks.js'\nimport {\n type SimulateCallsParameters,\n type SimulateCallsReturnType,\n simulateCalls,\n} from '../../actions/public/simulateCalls.js'\nimport {\n type SimulateContractParameters,\n type SimulateContractReturnType,\n simulateContract,\n} from '../../actions/public/simulateContract.js'\nimport {\n type UninstallFilterParameters,\n type UninstallFilterReturnType,\n uninstallFilter,\n} from '../../actions/public/uninstallFilter.js'\nimport {\n type VerifyMessageParameters,\n type VerifyMessageReturnType,\n verifyMessage,\n} from '../../actions/public/verifyMessage.js'\nimport {\n type VerifyTypedDataParameters,\n type VerifyTypedDataReturnType,\n verifyTypedData,\n} from '../../actions/public/verifyTypedData.js'\nimport {\n type WaitForTransactionReceiptParameters,\n type WaitForTransactionReceiptReturnType,\n waitForTransactionReceipt,\n} from '../../actions/public/waitForTransactionReceipt.js'\nimport {\n type WatchBlockNumberParameters,\n type WatchBlockNumberReturnType,\n watchBlockNumber,\n} from '../../actions/public/watchBlockNumber.js'\nimport {\n type WatchBlocksParameters,\n type WatchBlocksReturnType,\n watchBlocks,\n} from '../../actions/public/watchBlocks.js'\nimport {\n type WatchContractEventParameters,\n type WatchContractEventReturnType,\n watchContractEvent,\n} from '../../actions/public/watchContractEvent.js'\nimport {\n type WatchEventParameters,\n type WatchEventReturnType,\n watchEvent,\n} from '../../actions/public/watchEvent.js'\nimport {\n type WatchPendingTransactionsParameters,\n type WatchPendingTransactionsReturnType,\n watchPendingTransactions,\n} from '../../actions/public/watchPendingTransactions.js'\nimport {\n type VerifySiweMessageParameters,\n type VerifySiweMessageReturnType,\n verifySiweMessage,\n} from '../../actions/siwe/verifySiweMessage.js'\nimport {\n type PrepareTransactionRequestParameters,\n type PrepareTransactionRequestRequest,\n type PrepareTransactionRequestReturnType,\n prepareTransactionRequest,\n} from '../../actions/wallet/prepareTransactionRequest.js'\nimport {\n type SendRawTransactionParameters,\n type SendRawTransactionReturnType,\n sendRawTransaction,\n} from '../../actions/wallet/sendRawTransaction.js'\nimport type { Account } from '../../types/account.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventName,\n ContractFunctionArgs,\n ContractFunctionName,\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { FeeValuesType } from '../../types/fee.js'\nimport type { FilterType } from '../../types/filter.js'\nimport type { Client } from '../createClient.js'\nimport type { Transport } from '../transports/createTransport.js'\n\nexport type PublicActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = {\n /**\n * Executes a new message call immediately without submitting a transaction to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/call\n * - JSON-RPC Methods: [`eth_call`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_call)\n *\n * @param args - {@link CallParameters}\n * @returns The call data. {@link CallReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const data = await client.call({\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\n call: (parameters: CallParameters<chain>) => Promise<CallReturnType>\n /**\n * Creates an EIP-2930 access list that you can include in a transaction.\n *\n * - Docs: https://viem.sh/docs/actions/public/createAccessList\n * - JSON-RPC Methods: `eth_createAccessList`\n *\n * @param args - {@link CreateAccessListParameters}\n * @returns The call data. {@link CreateAccessListReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const data = await client.createAccessList({\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\n createAccessList: (\n parameters: CreateAccessListParameters<chain>,\n ) => Promise<CreateAccessListReturnType>\n /**\n * Creates a Filter to listen for new block hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createBlockFilter\n * - JSON-RPC Methods: [`eth_newBlockFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter)\n *\n * @returns Filter. {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, createBlockFilter, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'block' }\n */\n createBlockFilter: () => Promise<CreateBlockFilterReturnType>\n /**\n * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).\n *\n * - Docs: https://viem.sh/docs/contract/createContractEventFilter\n *\n * @param args - {@link CreateContractEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateContractEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createContractEventFilter({\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * })\n */\n createContractEventFilter: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi> | undefined,\n args extends MaybeExtractEventArgsFromAbi<abi, eventName> | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: CreateContractEventFilterParameters<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n >\n /**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types#filter) to listen for new events that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createEventFilter\n * - JSON-RPC Methods: [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter)\n *\n * @param args - {@link CreateEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * })\n */\n createEventFilter: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _EventName extends string | undefined = MaybeAbiEventName<abiEvent>,\n _Args extends\n | MaybeExtractEventArgsFromAbi<abiEvents, _EventName>\n | undefined = undefined,\n >(\n args?:\n | CreateEventFilterParameters<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _EventName,\n _Args\n >\n | undefined,\n ) => Promise<\n CreateEventFilterReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock,\n _EventName,\n _Args\n >\n >\n /**\n * Creates a Filter to listen for new pending transaction hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges).\n *\n * - Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter\n * - JSON-RPC Methods: [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter)\n *\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createPendingTransactionFilter()\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'transaction' }\n */\n createPendingTransactionFilter: () => Promise<CreatePendingTransactionFilterReturnType>\n /**\n * Estimates the gas required to successfully execute a contract write function call.\n *\n * - Docs: https://viem.sh/docs/contract/estimateContractGas\n *\n * @remarks\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link EstimateContractGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateContractGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gas = await client.estimateContractGas({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint() public']),\n * functionName: 'mint',\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * })\n */\n estimateContractGas: <\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n >(\n args: EstimateContractGasParameters<abi, functionName, args, chain>,\n ) => Promise<EstimateContractGasReturnType>\n /**\n * Estimates the gas necessary to complete a transaction without submitting it to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateGas\n * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n *\n * @param args - {@link EstimateGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasEstimate = await client.estimateGas({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\n estimateGas: (\n args: EstimateGasParameters<chain>,\n ) => Promise<EstimateGasReturnType>\n /**\n * Returns the balance of an address in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBalance\n * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n *\n * @remarks\n * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther).\n *\n * ```ts\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * blockTag: 'safe'\n * })\n * const balanceAsEther = formatEther(balance)\n * // \"6.942\"\n * ```\n *\n * @param args - {@link GetBalanceParameters}\n * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const balance = await client.getBalance({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n * // 10000000000000000000000n (wei)\n */\n getBalance: (args: GetBalanceParameters) => Promise<GetBalanceReturnType>\n /**\n * Returns the base fee per blob gas in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlobBaseFee\n * - JSON-RPC Methods: [`eth_blobBaseFee`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blobBaseFee)\n *\n * @param client - Client to use\n * @returns The blob base fee (in wei). {@link GetBlobBaseFeeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlobBaseFee } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blobBaseFee = await client.getBlobBaseFee()\n */\n getBlobBaseFee: () => Promise<GetBlobBaseFeeReturnType>\n /**\n * Returns information about a block at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlock\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n *\n * @param args - {@link GetBlockParameters}\n * @returns Information about the block. {@link GetBlockReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await client.getBlock()\n */\n getBlock: <\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n >(\n args?: GetBlockParameters<includeTransactions, blockTag> | undefined,\n ) => Promise<GetBlockReturnType<chain, includeTransactions, blockTag>>\n /**\n * Returns the number of the most recent block seen.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_fetching-blocks\n * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n *\n * @param args - {@link GetBlockNumberParameters}\n * @returns The number of the block. {@link GetBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blockNumber = await client.getBlockNumber()\n * // 69420n\n */\n getBlockNumber: (\n args?: GetBlockNumberParameters | undefined,\n ) => Promise<GetBlockNumberReturnType>\n /**\n * Returns the number of Transactions at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockTransactionCountByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockTransactionCountByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) for `blockHash`.\n *\n * @param args - {@link GetBlockTransactionCountParameters}\n * @returns The block transaction count. {@link GetBlockTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const count = await client.getBlockTransactionCount()\n */\n getBlockTransactionCount: (\n args?: GetBlockTransactionCountParameters | undefined,\n ) => Promise<GetBlockTransactionCountReturnType>\n /** @deprecated Use `getCode` instead. */\n getBytecode: (args: GetCodeParameters) => Promise<GetCodeReturnType>\n /**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const chainId = await client.getChainId()\n * // 1\n */\n getChainId: () => Promise<GetChainIdReturnType>\n /**\n * Retrieves the bytecode at an address.\n *\n * - Docs: https://viem.sh/docs/contract/getCode\n * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n *\n * @param args - {@link GetBytecodeParameters}\n * @returns The contract's bytecode. {@link GetBytecodeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await client.getCode({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * })\n */\n getCode: (args: GetCodeParameters) => Promise<GetCodeReturnType>\n /**\n * Returns a list of event logs emitted by a contract.\n *\n * - Docs: https://viem.sh/docs/actions/public/getContractEvents\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetContractEventsParameters}\n * @returns A list of event logs. {@link GetContractEventsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { wagmiAbi } from './abi'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await client.getContractEvents(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: wagmiAbi,\n * eventName: 'Transfer'\n * })\n */\n getContractEvents: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi> | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetContractEventsParameters<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n GetContractEventsReturnType<abi, eventName, strict, fromBlock, toBlock>\n >\n /**\n * Reads the EIP-712 domain from a contract, based on the ERC-5267 specification.\n *\n * @param client - A {@link Client} instance.\n * @param parameters - The parameters of the action. {@link GetEip712DomainParameters}\n * @returns The EIP-712 domain, fields, and extensions. {@link GetEip712DomainReturnType}\n *\n * @example\n * ```ts\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const domain = await client.getEip712Domain({\n * address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * })\n * // {\n * // domain: {\n * // name: 'ExampleContract',\n * // version: '1',\n * // chainId: 1,\n * // verifyingContract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n * // },\n * // fields: '0x0f',\n * // extensions: [],\n * // }\n * ```\n */\n getEip712Domain: (\n args: GetEip712DomainParameters,\n ) => Promise<GetEip712DomainReturnType>\n /**\n * Gets address for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsAddressParameters}\n * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAddress = await client.getEnsAddress({\n * name: normalize('wevm.eth'),\n * })\n * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n */\n getEnsAddress: (\n args: GetEnsAddressParameters,\n ) => Promise<GetEnsAddressReturnType>\n /**\n * Gets the avatar of an ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAvatar\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText) with `key` set to `'avatar'`.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsAvatarParameters}\n * @returns Avatar URI or `null` if not found. {@link GetEnsAvatarReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAvatar = await client.getEnsAvatar({\n * name: normalize('wevm.eth'),\n * })\n * // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'\n */\n getEnsAvatar: (\n args: GetEnsAvatarParameters,\n ) => Promise<GetEnsAvatarReturnType>\n /**\n * Gets primary name for specified address.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsName\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n *\n * @param args - {@link GetEnsNameParameters}\n * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensName = await client.getEnsName({\n * address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n * })\n * // 'wevm.eth'\n */\n getEnsName: (args: GetEnsNameParameters) => Promise<GetEnsNameReturnType>\n /**\n * Gets resolver for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsResolverParameters}\n * @returns Address for ENS resolver. {@link GetEnsResolverReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const resolverAddress = await client.getEnsResolver({\n * name: normalize('wevm.eth'),\n * })\n * // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'\n */\n getEnsResolver: (\n args: GetEnsResolverParameters,\n ) => Promise<GetEnsResolverReturnType>\n /**\n * Gets a text record for specified ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * @remarks\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param args - {@link GetEnsTextParameters}\n * @returns Address for ENS resolver. {@link GetEnsTextReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const twitterRecord = await client.getEnsText({\n * name: normalize('wevm.eth'),\n * key: 'com.twitter',\n * })\n * // 'wevm_dev'\n */\n getEnsText: (args: GetEnsTextParameters) => Promise<GetEnsTextReturnType>\n /**\n * Returns a collection of historical gas information.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFeeHistory\n * - JSON-RPC Methods: [`eth_feeHistory`](https://docs.alchemy.com/reference/eth-feehistory)\n *\n * @param args - {@link GetFeeHistoryParameters}\n * @returns The gas estimate (in wei). {@link GetFeeHistoryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const feeHistory = await client.getFeeHistory({\n * blockCount: 4,\n * rewardPercentiles: [25, 75],\n * })\n */\n getFeeHistory: (\n args: GetFeeHistoryParameters,\n ) => Promise<GetFeeHistoryReturnType>\n /**\n * Returns an estimate for the fees per gas for a transaction to be included\n * in the next block.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateFeesPerGasParameters}\n * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await client.estimateFeesPerGas()\n * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n */\n estimateFeesPerGas: <\n chainOverride extends Chain | undefined = undefined,\n type extends FeeValuesType = 'eip1559',\n >(\n args?: EstimateFeesPerGasParameters<chain, chainOverride, type> | undefined,\n ) => Promise<EstimateFeesPerGasReturnType<type>>\n /**\n * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterChanges\n * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n *\n * @remarks\n * A Filter can be created from the following actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * Depending on the type of filter, the return value will be different:\n *\n * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n *\n * @param args - {@link GetFilterChangesParameters}\n * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n *\n * @example\n * // Blocks\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createBlockFilter()\n * const hashes = await client.getFilterChanges({ filter })\n *\n * @example\n * // Contract Events\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createContractEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * eventName: 'Transfer',\n * })\n * const logs = await client.getFilterChanges({ filter })\n *\n * @example\n * // Raw Events\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await client.getFilterChanges({ filter })\n *\n * @example\n * // Transactions\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createPendingTransactionFilter()\n * const hashes = await client.getFilterChanges({ filter })\n */\n getFilterChanges: <\n filterType extends FilterType,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetFilterChangesParameters<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n ) => Promise<\n GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n >\n /**\n * Returns a list of event logs since the filter was created.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterLogs\n * - JSON-RPC Methods: [`eth_getFilterLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs)\n *\n * @remarks\n * `getFilterLogs` is only compatible with **event filters**.\n *\n * @param args - {@link GetFilterLogsParameters}\n * @returns A list of event logs. {@link GetFilterLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await client.createEventFilter({\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await client.getFilterLogs({ filter })\n */\n getFilterLogs: <\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args: GetFilterLogsParameters<abi, eventName, strict, fromBlock, toBlock>,\n ) => Promise<\n GetFilterLogsReturnType<abi, eventName, strict, fromBlock, toBlock>\n >\n /**\n * Returns the current price of gas (in wei).\n *\n * - Docs: https://viem.sh/docs/actions/public/getGasPrice\n * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n *\n * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasPrice = await client.getGasPrice()\n */\n getGasPrice: () => Promise<GetGasPriceReturnType>\n /**\n * Returns a list of event logs matching the provided parameters.\n *\n * - Docs: https://viem.sh/docs/actions/public/getLogs\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/logs_event-logs\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param args - {@link GetLogsParameters}\n * @returns A list of event logs. {@link GetLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await client.getLogs()\n */\n getLogs: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n >(\n args?:\n | GetLogsParameters<abiEvent, abiEvents, strict, fromBlock, toBlock>\n | undefined,\n ) => Promise<\n GetLogsReturnType<abiEvent, abiEvents, strict, fromBlock, toBlock>\n >\n /**\n * Returns the account and storage values of the specified account including the Merkle-proof.\n *\n * - Docs: https://viem.sh/docs/actions/public/getProof\n * - JSON-RPC Methods:\n * - Calls [`eth_getProof`](https://eips.ethereum.org/EIPS/eip-1186)\n *\n * @param client - Client to use\n * @param parameters - {@link GetProofParameters}\n * @returns Proof data. {@link GetProofReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await client.getProof({\n * address: '0x...',\n * storageKeys: ['0x...'],\n * })\n */\n getProof: (args: GetProofParameters) => Promise<GetProofReturnType>\n /**\n * Returns an estimate for the max priority fee per gas (in wei) for a transaction\n * to be included in the next block.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas\n *\n * @param client - Client to use\n * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await client.estimateMaxPriorityFeePerGas()\n * // 10000000n\n */\n estimateMaxPriorityFeePerGas: <\n chainOverride extends Chain | undefined = undefined,\n >(\n args?:\n | EstimateMaxPriorityFeePerGasParameters<chain, chainOverride>\n | undefined,\n ) => Promise<EstimateMaxPriorityFeePerGasReturnType>\n /**\n * Returns the value from a storage slot at a given address.\n *\n * - Docs: https://viem.sh/docs/contract/getStorageAt\n * - JSON-RPC Methods: [`eth_getStorageAt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat)\n *\n * @param args - {@link GetStorageAtParameters}\n * @returns The value of the storage slot. {@link GetStorageAtReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getStorageAt } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await client.getStorageAt({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * slot: toHex(0),\n * })\n */\n getStorageAt: (\n args: GetStorageAtParameters,\n ) => Promise<GetStorageAtReturnType>\n /**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n *\n * @param args - {@link GetTransactionParameters}\n * @returns The transaction information. {@link GetTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transaction = await client.getTransaction({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransaction: <blockTag extends BlockTag = 'latest'>(\n args: GetTransactionParameters<blockTag>,\n ) => Promise<GetTransactionReturnType<chain, blockTag>>\n /**\n * Returns the number of blocks passed (confirmations) since the transaction was processed on a block.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionConfirmations`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations)\n *\n * @param args - {@link GetTransactionConfirmationsParameters}\n * @returns The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. {@link GetTransactionConfirmationsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const confirmations = await client.getTransactionConfirmations({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransactionConfirmations: (\n args: GetTransactionConfirmationsParameters<chain>,\n ) => Promise<GetTransactionConfirmationsReturnType>\n /**\n * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms#transaction) an Account has broadcast / sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount\n * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n *\n * @param args - {@link GetTransactionCountParameters}\n * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionCount = await client.getTransactionCount({\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n getTransactionCount: (\n args: GetTransactionCountParameters,\n ) => Promise<GetTransactionCountReturnType>\n /**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt)\n *\n * @param args - {@link GetTransactionReceiptParameters}\n * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await client.getTransactionReceipt({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n getTransactionReceipt: (\n args: GetTransactionReceiptParameters,\n ) => Promise<GetTransactionReceiptReturnType<chain>>\n /**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall\n *\n * @param args - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const abi = parseAbi([\n * 'function balanceOf(address) view returns (uint256)',\n * 'function totalSupply() view returns (uint256)',\n * ])\n * const result = await client.multicall({\n * contracts: [\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * },\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'totalSupply',\n * },\n * ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\n multicall: <\n const contracts extends readonly unknown[],\n allowFailure extends boolean = true,\n >(\n args: MulticallParameters<contracts, allowFailure>,\n ) => Promise<MulticallReturnType<contracts, allowFailure>>\n /**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\n prepareTransactionRequest: <\n const request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n >,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n ) => Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n >\n /**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts\n *\n * @remarks\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.readContract({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\n readContract: <\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, 'pure' | 'view'>,\n const args extends ContractFunctionArgs<abi, 'pure' | 'view', functionName>,\n >(\n args: ReadContractParameters<abi, functionName, args>,\n ) => Promise<ReadContractReturnType<abi, functionName, args>>\n /**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const hash = await client.sendRawTransaction({\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\n sendRawTransaction: (\n args: SendRawTransactionParameters,\n ) => Promise<SendRawTransactionReturnType>\n /**\n * @deprecated Use `simulateBlocks` instead.\n */\n simulate: <const calls extends readonly unknown[]>(\n args: SimulateBlocksParameters<calls>,\n ) => Promise<SimulateBlocksReturnType<calls>>\n /**\n * Simulates a set of calls on block(s) with optional block and state overrides.\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await client.simulateBlocks({\n * blocks: [{\n * blockOverrides: {\n * number: 69420n,\n * },\n * calls: [{\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * }],\n * stateOverrides: [{\n * address: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * balance: parseEther('10'),\n * }],\n * }]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateParameters}\n * @returns Simulated blocks. {@link SimulateReturnType}\n */\n simulateBlocks: <const calls extends readonly unknown[]>(\n args: SimulateBlocksParameters<calls>,\n ) => Promise<SimulateBlocksReturnType<calls>>\n /**\n * Simulates a set of calls.\n *\n * @example\n * ```ts\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const result = await client.simulateCalls({\n * account: '0x5a0b54d5dc17e482fe8b0bdca5320161b95fb929',\n * calls: [{\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * },\n * ]\n * })\n * ```\n *\n * @param client - Client to use.\n * @param parameters - {@link SimulateCallsParameters}\n * @returns Results. {@link SimulateCallsReturnType}\n */\n simulateCalls: <const calls extends readonly unknown[]>(\n args: SimulateCallsParameters<calls>,\n ) => Promise<SimulateCallsReturnType<calls>>\n /**\n * Simulates/validates a contract interaction. This is useful for retrieving **return data** and **revert reasons** of contract write functions.\n *\n * - Docs: https://viem.sh/docs/contract/simulateContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_writing-to-contracts\n *\n * @remarks\n * This function does not require gas to execute and _**does not**_ change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract), but also supports contract write functions.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param args - {@link SimulateContractParameters}\n * @returns The simulation result and write request. {@link SimulateContractReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await client.simulateContract({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32) view returns (uint32)']),\n * functionName: 'mint',\n * args: ['69420'],\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n simulateContract: <\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n const args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: SimulateContractParameters<\n abi,\n functionName,\n args,\n chain,\n chainOverride,\n accountOverride\n >,\n ) => Promise<\n SimulateContractReturnType<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride,\n accountOverride\n >\n >\n /**\n * Verify that a message was signed by the provided address.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyMessage}\n *\n * @param parameters - {@link VerifyMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifyMessageReturnType}\n */\n verifyMessage: (\n args: VerifyMessageParameters,\n ) => Promise<VerifyMessageReturnType>\n /**\n * Verifies [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message was signed.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/siwe/actions/verifySiweMessage}\n *\n * @param parameters - {@link VerifySiweMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiweMessageReturnType}\n */\n verifySiweMessage: (\n args: VerifySiweMessageParameters,\n ) => Promise<VerifySiweMessageReturnType>\n /**\n * Verify that typed data was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyTypedData}\n *\n * @param parameters - {@link VerifyTypedDataParameters}\n * @returns Whether or not the signature is valid. {@link VerifyTypedDataReturnType}\n */\n verifyTypedData: (\n args: VerifyTypedDataParameters,\n ) => Promise<VerifyTypedDataReturnType>\n /**\n * Destroys a Filter that was created from one of the following Actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * - Docs: https://viem.sh/docs/actions/public/uninstallFilter\n * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n *\n * @param args - {@link UninstallFilterParameters}\n * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n *\n * const filter = await client.createPendingTransactionFilter()\n * const uninstalled = await client.uninstallFilter({ filter })\n * // true\n */\n uninstallFilter: (\n args: UninstallFilterParameters,\n ) => Promise<UninstallFilterReturnType>\n /**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt). If the Transaction reverts, then the action will throw an error.\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_sending-transactions\n * - JSON-RPC Methods:\n * - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n * - If a Transaction has been replaced:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n * - Checks if one of the Transactions is a replacement\n * - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n *\n * @remarks\n * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n *\n * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n *\n * There are 3 types of Transaction Replacement reasons:\n *\n * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n *\n * @param args - {@link WaitForTransactionReceiptParameters}\n * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await client.waitForTransactionReceipt({\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\n waitForTransactionReceipt: (\n args: WaitForTransactionReceiptParameters<chain>,\n ) => Promise<WaitForTransactionReceiptReturnType<chain>>\n /**\n * Watches and returns incoming block numbers.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param args - {@link WatchBlockNumberParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchBlockNumber({\n * onBlockNumber: (blockNumber) => console.log(blockNumber),\n * })\n */\n watchBlockNumber: (\n args: WatchBlockNumberParameters,\n ) => WatchBlockNumberReturnType\n /**\n * Watches and returns information for incoming blocks.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlocks\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks_watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param args - {@link WatchBlocksParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlocksReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchBlocks({\n * onBlock: (block) => console.log(block),\n * })\n */\n watchBlocks: <\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n >(\n args: WatchBlocksParameters<\n transport,\n chain,\n includeTransactions,\n blockTag\n >,\n ) => WatchBlocksReturnType\n /**\n * Watches and returns emitted contract event logs.\n *\n * - Docs: https://viem.sh/docs/contract/watchContractEvent\n *\n * @remarks\n * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent#onLogs).\n *\n * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param args - {@link WatchContractEventParameters}\n * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = client.watchContractEvent({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n * eventName: 'Transfer',\n * args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n * onLogs: (logs) => console.log(logs),\n * })\n */\n watchContractEvent: <\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi>,\n strict extends boolean | undefined = undefined,\n >(\n args: WatchContractEventParameters<abi, eventName, strict, transport>,\n ) => WatchContractEventReturnType\n /**\n * Watches and returns emitted [Event Logs](https://viem.sh/docs/glossary/terms#event-log).\n *\n * - Docs: https://viem.sh/docs/actions/public/watchEvent\n * - JSON-RPC Methods:\n * - **RPC Provider supports `eth_newFilter`:**\n * - Calls [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) to create a filter (called on initialize).\n * - On a polling interval, it will call [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges).\n * - **RPC Provider does not support `eth_newFilter`:**\n * - Calls [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) for each block between the polling interval.\n *\n * @remarks\n * This Action will batch up all the Event Logs found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/actions/public/watchEvent#onLogs).\n *\n * `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/actions/public/createEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param args - {@link WatchEventParameters}\n * @returns A function that can be invoked to stop watching for new Event Logs. {@link WatchEventReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = client.watchEvent({\n * onLogs: (logs) => console.log(logs),\n * })\n */\n watchEvent: <\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n >(\n args: WatchEventParameters<abiEvent, abiEvents, strict, transport>,\n ) => WatchEventReturnType\n /**\n * Watches and returns pending transaction hashes.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchPendingTransactions\n * - JSON-RPC Methods:\n * - When `poll: true`\n * - Calls [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) to initialize the filter.\n * - Calls [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newPendingTransactions\"` event.\n *\n * @remarks\n * This Action will batch up all the pending transactions found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchPendingTransactions#pollinginterval-optional), and invoke them via [`onTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions#ontransactions).\n *\n * @param args - {@link WatchPendingTransactionsParameters}\n * @returns A function that can be invoked to stop watching for new pending transaction hashes. {@link WatchPendingTransactionsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = await client.watchPendingTransactions({\n * onTransactions: (hashes) => console.log(hashes),\n * })\n */\n watchPendingTransactions: (\n args: WatchPendingTransactionsParameters<transport>,\n ) => WatchPendingTransactionsReturnType\n}\n\nexport function publicActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n>(\n client: Client<transport, chain, account>,\n): PublicActions<transport, chain, account> {\n return {\n call: (args) => call(client, args),\n createAccessList: (args) => createAccessList(client, args),\n createBlockFilter: () => createBlockFilter(client),\n createContractEventFilter: (args) =>\n createContractEventFilter(client, args),\n createEventFilter: (args) => createEventFilter(client, args),\n createPendingTransactionFilter: () =>\n createPendingTransactionFilter(client),\n estimateContractGas: (args) => estimateContractGas(client, args as any),\n estimateGas: (args) => estimateGas(client, args),\n getBalance: (args) => getBalance(client, args),\n getBlobBaseFee: () => getBlobBaseFee(client),\n getBlock: (args) => getBlock(client, args),\n getBlockNumber: (args) => getBlockNumber(client, args),\n getBlockTransactionCount: (args) => getBlockTransactionCount(client, args),\n getBytecode: (args) => getCode(client, args),\n getChainId: () => getChainId(client),\n getCode: (args) => getCode(client, args),\n getContractEvents: (args) => getContractEvents(client, args),\n getEip712Domain: (args) => getEip712Domain(client, args),\n getEnsAddress: (args) => getEnsAddress(client, args),\n getEnsAvatar: (args) => getEnsAvatar(client, args),\n getEnsName: (args) => getEnsName(client, args),\n getEnsResolver: (args) => getEnsResolver(client, args),\n getEnsText: (args) => getEnsText(client, args),\n getFeeHistory: (args) => getFeeHistory(client, args),\n estimateFeesPerGas: (args) => estimateFeesPerGas(client, args),\n getFilterChanges: (args) => getFilterChanges(client, args),\n getFilterLogs: (args) => getFilterLogs(client, args),\n getGasPrice: () => getGasPrice(client),\n getLogs: (args) => getLogs(client, args as any),\n getProof: (args) => getProof(client, args),\n estimateMaxPriorityFeePerGas: (args) =>\n estimateMaxPriorityFeePerGas(client, args),\n getStorageAt: (args) => getStorageAt(client, args),\n getTransaction: (args) => getTransaction(client, args),\n getTransactionConfirmations: (args) =>\n getTransactionConfirmations(client, args),\n getTransactionCount: (args) => getTransactionCount(client, args),\n getTransactionReceipt: (args) => getTransactionReceipt(client, args),\n multicall: (args) => multicall(client, args),\n prepareTransactionRequest: (args) =>\n prepareTransactionRequest(client as any, args as any) as any,\n readContract: (args) => readContract(client, args),\n sendRawTransaction: (args) => sendRawTransaction(client, args),\n simulate: (args) => simulateBlocks(client, args),\n simulateBlocks: (args) => simulateBlocks(client, args),\n simulateCalls: (args) => simulateCalls(client, args),\n simulateContract: (args) => simulateContract(client, args),\n verifyMessage: (args) => verifyMessage(client, args),\n verifySiweMessage: (args) => verifySiweMessage(client, args),\n verifyTypedData: (args) => verifyTypedData(client, args),\n uninstallFilter: (args) => uninstallFilter(client, args),\n waitForTransactionReceipt: (args) =>\n waitForTransactionReceipt(client, args),\n watchBlocks: (args) => watchBlocks(client, args),\n watchBlockNumber: (args) => watchBlockNumber(client, args),\n watchContractEvent: (args) => watchContractEvent(client, args),\n watchEvent: (args) => watchEvent(client, args),\n watchPendingTransactions: (args) => watchPendingTransactions(client, args),\n }\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account, ParseAccount } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { PublicRpcSchema, RpcSchema } from '../types/eip1193.js'\nimport type { Prettify } from '../types/utils.js'\nimport {\n type Client,\n type ClientConfig,\n type CreateClientErrorType,\n createClient,\n} from './createClient.js'\nimport { type PublicActions, publicActions } from './decorators/public.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type PublicClientConfig<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = Prettify<\n Pick<\n ClientConfig<transport, chain, accountOrAddress, rpcSchema>,\n | 'batch'\n | 'cacheTime'\n | 'ccipRead'\n | 'chain'\n | 'key'\n | 'name'\n | 'pollingInterval'\n | 'rpcSchema'\n | 'transport'\n >\n>\n\nexport type PublicClient<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = Prettify<\n Client<\n transport,\n chain,\n accountOrAddress,\n rpcSchema extends RpcSchema\n ? [...PublicRpcSchema, ...rpcSchema]\n : PublicRpcSchema,\n PublicActions<transport, chain>\n >\n>\n\nexport type CreatePublicClientErrorType = CreateClientErrorType | ErrorType\n\n/**\n * Creates a Public Client with a given [Transport](https://viem.sh/docs/clients/intro) configured for a [Chain](https://viem.sh/docs/clients/chains).\n *\n * - Docs: https://viem.sh/docs/clients/public\n *\n * A Public Client is an interface to \"public\" [JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).\n *\n * @param config - {@link PublicClientConfig}\n * @returns A Public Client. {@link PublicClient}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n */\nexport function createPublicClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: PublicClientConfig<transport, chain, accountOrAddress, rpcSchema>,\n): PublicClient<transport, chain, ParseAccount<accountOrAddress>, rpcSchema> {\n const { key = 'public', name = 'Public Client' } = parameters\n const client = createClient({\n ...parameters,\n key,\n name,\n type: 'publicClient',\n })\n return client.extend(publicActions) as any\n}\n","import { ethers, Wallet } from 'ethers';\nimport path from 'node:path';\nimport inquirer from 'inquirer';\nimport { logger } from './logger';\nimport dotenv from 'dotenv';\nimport { execSync } from 'child_process';\nimport fs from 'fs-extra';\nimport { defineChain, type Chain } from 'viem';\nimport { base, mainnet, sepolia, anvil } from 'viem/chains';\ndotenv.config({ path: path.join(process.cwd(), '.env') });\n\n// Helper to ensure a hex string has a '0x' prefix\nexport const ensureHexPrefix = (hex: string) => hex.startsWith('0x') ? hex : `0x${hex}`;\n\nexport interface NetworkConfig {\n wallet: Wallet;\n rpcUrl: string;\n}\n\nexport interface AppAuthResult {\n appId: string;\n proxyAddress: string;\n deployerAddress: string;\n}\n\nexport const SUPPORTED_CHAINS: Record<number, Chain> = {\n [mainnet.id]: mainnet,\n [sepolia.id]: sepolia,\n [base.id]: base,\n 15107: defineChain({\n id: 15107,\n name: \"T16Z\",\n nativeCurrency: {\n name: \"ETH\",\n symbol: \"ETH\",\n decimals: 18,\n },\n rpcUrls: {\n default: {\n http: [\"https://rpc.t16z.com\"],\n },\n },\n }),\n [anvil.id]: {\n ...anvil,\n rpcUrls: {\n default: {\n http: [\"http://127.0.0.1:8545\"],\n },\n },\n },\n};\n/**\n * Configures the blockchain network connection, including RPC URL and wallet.\n */\nexport function getChainConfig(chainId: number): Chain {\n const chain = SUPPORTED_CHAINS[chainId];\n if (!chain) {\n throw new Error(`Unsupported chain ID: ${chainId}`);\n }\n return chain;\n}\n\nexport async function getNetworkConfig(options: any, chainId?: number, interactive?: boolean): Promise<NetworkConfig> {\n let { rpcUrl, privateKey } = options;\n\n if (!rpcUrl && chainId) {\n const chain = getChainConfig(chainId);\n rpcUrl = chain.rpcUrls.default.http[0];\n }\n if (!privateKey) {\n // Check for PRIVATE_KEY environment variable\n if (process.env.PRIVATE_KEY) {\n privateKey = process.env.PRIVATE_KEY;\n logger.debug('Using private key from PRIVATE_KEY environment variable');\n } else if (interactive) {\n const { key } = await inquirer.prompt([{\n type: 'password',\n name: 'key',\n message: 'Enter the private key for signing:',\n validate: (input) => !!input || 'Private key is required. You can also set the PRIVATE_KEY environment variable.',\n }]);\n privateKey = key;\n }\n }\n\n const provider = new ethers.JsonRpcProvider(rpcUrl);\n const wallet = new ethers.Wallet(ensureHexPrefix(privateKey), provider);\n logger.success(`Connected to RPC at ${rpcUrl}. Using wallet ${wallet.address}`);\n return { wallet, rpcUrl };\n}\n\nconst KMS_AUTH_ABI = [\n 'function registerApp(address app)',\n 'event AppRegistered(address appId)',\n 'function setAppAuthImplementation(address _implementation)',\n 'function deployAndRegisterApp(address,bool,bool,bytes32,bytes32) returns (address, address)',\n 'event AppDeployedViaFactory(address indexed appId, address indexed proxyAddress, address indexed deployer)',\n];\n\nasync function determineAction(options: any): Promise<{ action: 'register' | 'deployCustom' | 'deployDefault', appAuthAddress?: string, appAuthContractPath?: string }> {\n if (options.appAuthAddress) {\n return { action: 'register', appAuthAddress: options.appAuthAddress };\n }\n if (options.appAuthContractPath) {\n return { action: 'deployCustom', appAuthContractPath: options.appAuthContractPath };\n }\n if (options.useDefaultAppAuth) {\n return { action: 'deployDefault' };\n }\n\n // Interactive prompt if no flags are provided\n const { actionType } = await inquirer.prompt([{\n type: 'list',\n name: 'actionType',\n message: 'What would you like to do?',\n choices: [\n { name: 'Register a pre-deployed AppAuth contract', value: 'register' },\n { name: 'Deploy a new AppAuth contract from a custom file', value: 'deployCustom' },\n { name: 'Deploy the default AppAuth contract via factory', value: 'deployDefault' },\n ],\n }]);\n\n if (actionType === 'register') {\n const { addr } = await inquirer.prompt([{\n type: 'input',\n name: 'addr',\n message: 'Enter the address of your pre-deployed AppAuth contract:',\n validate: (input) => ethers.isAddress(input) || 'Please enter a valid Ethereum address.',\n }]);\n return { action: 'register', appAuthAddress: addr };\n }\n\n if (actionType === 'deployCustom') {\n const { p } = await inquirer.prompt([{\n type: 'input',\n name: 'p',\n message: 'Enter the path to your custom AppAuth contract file:',\n validate: (input) => fs.existsSync(input) && fs.statSync(input).isFile() || 'Please enter a valid file path.',\n }]);\n return { action: 'deployCustom', appAuthContractPath: p };\n }\n\n return { action: 'deployDefault' };\n}\n\nasync function gatherDeploymentInputs(options: any, wallet: Wallet): Promise<{ deployerAddress: string, initialDeviceId: string, composeHash: string }> {\n const answers = await inquirer.prompt([\n {\n type: 'input',\n name: 'initialDeviceId',\n message: 'Enter the initial device ID (32-byte hex):',\n when: !options.initialDeviceId,\n default: ethers.ZeroHash,\n validate: (input) => (input.length === 66 && input.startsWith('0x')) || 'Please enter a valid 32-byte hex string (0x...).',\n },\n {\n type: 'input',\n name: 'composeHash',\n message: 'Enter the initial compose hash (32-byte hex):',\n when: !options.composeHash,\n default: ethers.ZeroHash,\n validate: (input) => (input.length === 66 && input.startsWith('0x')) || 'Please enter a valid 32-byte hex string (0x...).',\n }\n ]);\n\n return {\n deployerAddress: wallet.address,\n initialDeviceId: options.initialDeviceId || answers.initialDeviceId,\n composeHash: options.composeHash || answers.composeHash,\n };\n}\n\nasync function registerAppAuth(kmsContractAddress: string, appAuthAddress: string, wallet: Wallet): Promise<AppAuthResult> {\n const spinner = logger.startSpinner(`Registering AppAuth contract ${appAuthAddress}...`);\n const kmsAuthContract = new ethers.Contract(kmsContractAddress, KMS_AUTH_ABI, wallet);\n const tx = await kmsAuthContract.registerApp(appAuthAddress, { nonce: await wallet.getNonce() });\n const receipt = await tx.wait();\n spinner.stop(true);\n\n const kmsAuthInterface = new ethers.Interface(KMS_AUTH_ABI);\n const log = receipt.logs.find(l => l.topics[0] === kmsAuthInterface.getEvent('AppRegistered').topicHash);\n\n if (log) {\n const { appId } = kmsAuthInterface.parseLog({ topics: Array.from(log.topics), data: log.data }).args;\n logger.success('AppAuth contract registered successfully!');\n logger.keyValueTable({ 'App ID (Contract Address)': appId, 'Transaction Hash': tx.hash });\n return { appId, proxyAddress: appAuthAddress, deployerAddress: wallet.address };\n } else {\n logger.warn('Could not find AppRegistered event to confirm registration.');\n throw new Error('Registration failed: Event not found.');\n }\n}\n\nasync function deployCustomAppAuth(kmsContractAddress: string, contractPath: string, deployerAddress: string, initialDeviceId: string, composeHash: string, wallet: Wallet): Promise<AppAuthResult> {\n logger.info(`Using custom contract from: ${contractPath}`);\n let spinner = logger.startSpinner('Compiling custom contract with Hardhat...');\n execSync('npx hardhat compile', { stdio: 'pipe' });\n spinner.stop(true);\n\n spinner = logger.startSpinner('Deploying custom AppAuth contract...');\n const relativePath = path.relative(process.cwd(), path.resolve(contractPath));\n const contractName = path.basename(relativePath, '.sol');\n const artifactPath = path.resolve(process.cwd(), 'artifacts', relativePath, `${contractName}.json`);\n if (!fs.existsSync(artifactPath)) throw new Error(`Could not find artifact at ${artifactPath}`);\n \n const artifact = await fs.readJson(artifactPath);\n const factory = new ethers.ContractFactory(artifact.abi, artifact.bytecode, wallet);\n const contract = await factory.deploy(); // Assumes no constructor args for custom contract\n await contract.waitForDeployment();\n const contractAddress = await contract.getAddress();\n spinner.stop(true);\n logger.success(`Custom AppAuth contract deployed at: ${contractAddress}`);\n\n return await registerAppAuth(kmsContractAddress, contractAddress, wallet);\n}\n\nasync function deployDefaultAppAuth(kmsContractAddress: string, deployerAddress: string, initialDeviceId: string, composeHash: string, wallet: Wallet): Promise<AppAuthResult> {\n const spinner = logger.startSpinner(`Deploying AppAuth instance via KmsAuth factory at ${kmsContractAddress}...`);\n const kmsAuthContract = new ethers.Contract(kmsContractAddress, KMS_AUTH_ABI, wallet);\n const tx = await kmsAuthContract.deployAndRegisterApp(deployerAddress, false, true, ensureHexPrefix(initialDeviceId), ensureHexPrefix(composeHash));\n const receipt = await tx.wait();\n spinner.stop(true);\n\n const kmsAuthInterface = new ethers.Interface(KMS_AUTH_ABI);\n const log = receipt.logs.find(l => l.topics[0] === kmsAuthInterface.getEvent('AppDeployedViaFactory').topicHash);\n\n if (log) {\n const { appId, proxyAddress } = kmsAuthInterface.parseLog({ topics: Array.from(log.topics), data: log.data }).args;\n logger.success('AppAuth instance deployed and registered successfully!');\n logger.keyValueTable({ 'App ID': appId, 'Proxy Address': proxyAddress, 'Transaction Hash': tx.hash });\n return { appId, proxyAddress, deployerAddress };\n } else {\n logger.warn('Could not find AppDeployedViaFactory event to extract details.');\n throw new Error('Deployment failed: Event not found.');\n }\n}\n\nexport async function handleAppAuthDeployment(options: any, wallet: Wallet, kmsContractAddress: string): Promise<AppAuthResult> {\n // const { action, appAuthAddress, appAuthContractPath } = await determineAction(options);\n\n if (!options.kmsId) {\n throw new Error('KMS ID is required.');\n }\n\n if (!kmsContractAddress) {\n throw new Error('KMS Contract Address is required.');\n }\n\n // if (action === 'register') {\n // if (!appAuthAddress) throw new Error('AppAuth address is required for registration.');\n // return await registerAppAuth(options.kmsContractAddress, appAuthAddress, wallet);\n // }\n\n const params = await gatherDeploymentInputs(options, wallet);\n\n // if (action === 'deployCustom') {\n // if (!appAuthContractPath) throw new Error('AppAuth contract path is required for custom deployment.');\n // return await deployCustomAppAuth(options.kmsContractAddress, appAuthContractPath, params.deployerAddress, params.initialDeviceId, params.composeHash, wallet);\n // }\n\n return await deployDefaultAppAuth(kmsContractAddress, params.deployerAddress, params.initialDeviceId, params.composeHash, wallet);\n}\n","import type { Chain } from '../types/chain.js'\n\n/**\n * Predeploy contracts for OP Stack.\n * @see https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md\n */\nexport const contracts = {\n gasPriceOracle: { address: '0x420000000000000000000000000000000000000F' },\n l1Block: { address: '0x4200000000000000000000000000000000000015' },\n l2CrossDomainMessenger: {\n address: '0x4200000000000000000000000000000000000007',\n },\n l2Erc721Bridge: { address: '0x4200000000000000000000000000000000000014' },\n l2StandardBridge: { address: '0x4200000000000000000000000000000000000010' },\n l2ToL1MessagePasser: {\n address: '0x4200000000000000000000000000000000000016',\n },\n} as const satisfies Chain['contracts']\n","import type { ChainFormatters } from '../types/chain.js'\nimport type { RpcTransaction } from '../types/rpc.js'\nimport { hexToBigInt } from '../utils/encoding/fromHex.js'\nimport { defineBlock } from '../utils/formatters/block.js'\nimport {\n defineTransaction,\n formatTransaction,\n} from '../utils/formatters/transaction.js'\nimport { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js'\nimport type { OpStackBlock, OpStackRpcBlock } from './types/block.js'\nimport type {\n OpStackRpcTransaction,\n OpStackRpcTransactionReceipt,\n OpStackTransaction,\n OpStackTransactionReceipt,\n} from './types/transaction.js'\n\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args: OpStackRpcBlock): OpStackBlock {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string') return transaction\n const formatted = formatTransaction(\n transaction as RpcTransaction,\n ) as OpStackTransaction\n if (formatted.typeHex === '0x7e') {\n formatted.isSystemTx = transaction.isSystemTx\n formatted.mint = transaction.mint\n ? hexToBigInt(transaction.mint)\n : undefined\n formatted.sourceHash = transaction.sourceHash\n formatted.type = 'deposit'\n }\n return formatted\n })\n return {\n transactions,\n stateRoot: args.stateRoot,\n } as OpStackBlock\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args: OpStackRpcTransaction): OpStackTransaction {\n const transaction = {} as OpStackTransaction\n if (args.type === '0x7e') {\n transaction.isSystemTx = args.isSystemTx\n transaction.mint = args.mint ? hexToBigInt(args.mint) : undefined\n transaction.sourceHash = args.sourceHash\n transaction.type = 'deposit'\n }\n return transaction\n },\n }),\n transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({\n format(args: OpStackRpcTransactionReceipt): OpStackTransactionReceipt {\n return {\n l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,\n l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,\n l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,\n l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null,\n } as OpStackTransactionReceipt\n },\n }),\n} as const satisfies ChainFormatters\n","import { InvalidAddressError } from '../errors/address.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ChainSerializers } from '../types/chain.js'\nimport type { Hex, Signature } from '../types/misc.js'\nimport type { TransactionSerializable } from '../types/transaction.js'\nimport type { RequiredBy } from '../types/utils.js'\nimport { isAddress } from '../utils/address/isAddress.js'\nimport { concatHex } from '../utils/data/concat.js'\nimport { toHex } from '../utils/encoding/toHex.js'\nimport { toRlp } from '../utils/encoding/toRlp.js'\nimport {\n type SerializeTransactionErrorType as SerializeTransactionErrorType_,\n serializeTransaction as serializeTransaction_,\n} from '../utils/transaction/serializeTransaction.js'\nimport type {\n OpStackTransactionSerializable,\n TransactionSerializableDeposit,\n TransactionSerializedDeposit,\n} from './types/transaction.js'\n\nexport type SerializeTransactionReturnType = ReturnType<\n typeof serializeTransaction\n>\n\nexport type SerializeTransactionErrorType =\n | SerializeTransactionErrorType_\n | ErrorType\n\nexport function serializeTransaction(\n transaction: OpStackTransactionSerializable,\n signature?: Signature,\n) {\n if (isDeposit(transaction)) return serializeTransactionDeposit(transaction)\n return serializeTransaction_(\n transaction as TransactionSerializable,\n signature,\n )\n}\n\nexport const serializers = {\n transaction: serializeTransaction,\n} as const satisfies ChainSerializers\n\n//////////////////////////////////////////////////////////////////////////////\n// Serializers\n\nexport type SerializeTransactionDepositReturnType = TransactionSerializedDeposit\n\nfunction serializeTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n): SerializeTransactionDepositReturnType {\n assertTransactionDeposit(transaction)\n\n const { sourceHash, data, from, gas, isSystemTx, mint, to, value } =\n transaction\n\n const serializedTransaction: Hex[] = [\n sourceHash,\n from,\n to ?? '0x',\n mint ? toHex(mint) : '0x',\n value ? toHex(value) : '0x',\n gas ? toHex(gas) : '0x',\n isSystemTx ? '0x1' : '0x',\n data ?? '0x',\n ]\n\n return concatHex([\n '0x7e',\n toRlp(serializedTransaction),\n ]) as SerializeTransactionDepositReturnType\n}\n\nfunction isDeposit(\n transaction: OpStackTransactionSerializable,\n): transaction is RequiredBy<TransactionSerializableDeposit, 'type'> {\n if (transaction.type === 'deposit') return true\n if (typeof transaction.sourceHash !== 'undefined') return true\n return false\n}\n\nexport function assertTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n) {\n const { from, to } = transaction\n if (from && !isAddress(from)) throw new InvalidAddressError({ address: from })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n}\n","import { contracts } from './contracts.js'\nimport { formatters } from './formatters.js'\nimport { serializers } from './serializers.js'\n\nexport const chainConfig = {\n contracts,\n formatters,\n serializers,\n} as const\n","import { defineChain } from '../../utils/chain/defineChain.js'\n\nexport const anvil = /*#__PURE__*/ defineChain({\n id: 31_337,\n name: 'Anvil',\n nativeCurrency: {\n decimals: 18,\n name: 'Ether',\n symbol: 'ETH',\n },\n rpcUrls: {\n default: {\n http: ['http://127.0.0.1:8545'],\n webSocket: ['ws://127.0.0.1:8545'],\n },\n },\n})\n","import { chainConfig } from '../../op-stack/chainConfig.js'\nimport { defineChain } from '../../utils/chain/defineChain.js'\n\nconst sourceId = 1 // mainnet\n\nexport const base = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 8453,\n name: 'Base',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.base.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Basescan',\n url: 'https://basescan.org',\n apiUrl: 'https://api.basescan.org/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0x56315b90c40730925ec5485cf004d835058518A0',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 5022,\n },\n portal: {\n [sourceId]: {\n address: '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e',\n blockCreated: 17482143,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x3154Cf16ccdb4C6d922629664174b904d80F2C35',\n blockCreated: 17482143,\n },\n },\n },\n sourceId,\n})\n","import { defineChain } from '../../utils/chain/defineChain.js'\n\nexport const mainnet = /*#__PURE__*/ defineChain({\n id: 1,\n name: 'Ethereum',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://eth.merkle.io'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Etherscan',\n url: 'https://etherscan.io',\n apiUrl: 'https://api.etherscan.io/api',\n },\n },\n contracts: {\n ensRegistry: {\n address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',\n },\n ensUniversalResolver: {\n address: '0xce01f8eee7E479C928F8919abD53E553a36CeF67',\n blockCreated: 19_258_213,\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 14_353_601,\n },\n },\n})\n","import { defineChain } from '../../utils/chain/defineChain.js'\n\nexport const sepolia = /*#__PURE__*/ defineChain({\n id: 11_155_111,\n name: 'Sepolia',\n nativeCurrency: { name: 'Sepolia Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://sepolia.drpc.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Etherscan',\n url: 'https://sepolia.etherscan.io',\n apiUrl: 'https://api-sepolia.etherscan.io/api',\n },\n },\n contracts: {\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 751532,\n },\n ensRegistry: { address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e' },\n ensUniversalResolver: {\n address: '0xc8Af999e38273D658BE1b921b88A9Ddf005769cC',\n blockCreated: 5_317_080,\n },\n },\n testnet: true,\n})\n","import { Command } from 'commander';\nimport { checkCvmExists, getCvmByAppId, resizeCvm, selectCvm } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport inquirer from 'inquirer';\nimport chalk from 'chalk';\nimport { resolveCvmAppId } from '@/src/utils/cvms';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nexport const resizeCommand = new Command()\n .name('resize')\n .description('Resize resources for a CVM')\n .argument('[app-id]', 'App ID of the CVM (if not provided, a selection prompt will appear)')\n .option('-v, --vcpu <vcpu>', 'Number of virtual CPUs')\n .option('-m, --memory <memory>', 'Memory size in MB')\n .option('-d, --disk-size <diskSize>', 'Disk size in GB')\n .option('-r, --allow-restart <allowRestart>', 'Allow restart of the CVM if needed for resizing')\n .option('-y, --yes', 'Automatically confirm the resize operation')\n .action(async (appId, options) => {\n try {\n const resolvedAppId = await resolveCvmAppId(appId);\n\n const cvm = await getCvmByAppId(resolvedAppId);\n \n // Initialize parameters\n let vcpu: number | undefined = options.vcpu;\n let memory: number | undefined = options.memory;\n let diskSize: number | undefined = options.diskSize;\n let allowRestart: boolean | undefined = options.allowRestart;\n // Prompt for vCPU if selected\n if (!vcpu) {\n const response = await inquirer.prompt([\n {\n type: 'input',\n name: 'vcpu',\n message: 'Enter number of vCPUs:',\n validate: (input) => {\n const num = parseInt(input);\n if (isNaN(num) || num < 0) {\n return 'Please enter a valid non-negative number';\n }\n return true;\n },\n default: cvm.vcpu.toString(),\n filter: (input) => parseInt(input)\n }\n ]);\n vcpu = response.vcpu;\n }\n \n // Prompt for memory\n if (!memory) {\n const response = await inquirer.prompt([\n {\n type: 'input',\n name: 'memory',\n message: 'Enter memory in MB:',\n validate: (input) => {\n const num = parseInt(input);\n if (isNaN(num) || num < 0) {\n return 'Please enter a valid non-negative number';\n }\n return true;\n },\n default: cvm.memory.toString(),\n filter: (input) => parseInt(input)\n }\n ]);\n memory = response.memory;\n }\n \n // Prompt for disk size\n if (!diskSize) {\n const response = await inquirer.prompt([\n {\n type: 'input',\n name: 'diskSize',\n message: 'Enter disk size in GB:',\n validate: (input) => {\n const num = parseInt(input);\n if (isNaN(num) || num < 0) {\n return 'Please enter a valid non-negative number';\n }\n return true;\n },\n default: cvm.disk_size.toString(),\n filter: (input) => parseInt(input)\n }\n ]);\n diskSize = response.diskSize;\n }\n \n // Ask about restart permission\n if (!allowRestart) {\n const response = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'allowRestart',\n message: 'Allow restart of the CVM if needed for resizing?',\n default: false\n }\n ]);\n allowRestart = response.allowRestart;\n }\n \n // Prepare confirmation message\n const confirmMessage = `Are you sure you want to resize CVM app_${resolvedAppId} with the following changes:\\n`;\n logger.keyValueTable(\n { 'vCPUs': cvm.vcpu !== vcpu ? `${chalk.red(cvm.vcpu)} -> ${chalk.green(vcpu)}` : cvm.vcpu,\n 'Memory': cvm.memory !== memory ? `${chalk.red(cvm.memory)} MB -> ${chalk.green(memory)} MB` : cvm.memory,\n 'Disk Size': cvm.disk_size !== diskSize ? `${chalk.red(cvm.disk_size)} GB -> ${chalk.green(diskSize)} GB` : cvm.disk_size,\n 'Allow Restart': allowRestart ? chalk.green('Yes') : chalk.red('No') }\n );\n \n // Confirm the resize operation\n if (!options.yes) {\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirm',\n message: confirmMessage,\n default: false\n }\n ]);\n \n if (!confirm) {\n logger.info('Resize operation cancelled');\n return;\n }\n }\n \n const spinner = logger.startSpinner(`Resizing CVM with App ID app_${resolvedAppId}`);\n \n // Convert boolean to number (0 or 1) as expected by the API\n const allowRestartValue = allowRestart ? 1 : 0;\n \n await resizeCvm(resolvedAppId, vcpu, memory, diskSize, allowRestartValue);\n\n spinner.stop(true);\n logger.break();\n logger.success(\n `Your CVM is being resized. You can check the dashboard for more details:\\n${CLOUD_URL}/dashboard/cvms/app_${resolvedAppId}`\n );\n } catch (error) {\n logger.error(\n `Failed to resize CVM: ${error instanceof Error ? error.message : String(error)}`\n );\n process.exit(1);\n }\n }); ","import { Command } from 'commander';\nimport { replicateCvm, getCvmComposeConfig } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { encryptEnvVars } from '@phala/dstack-sdk/encrypt-env-vars';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nexport const replicateCommand = new Command()\n .name('replicate')\n .description('Create a replica of an existing CVM')\n .argument('<cvm-id>', 'UUID of the CVM to replicate')\n .option('--node-id <nodeId>', 'Node ID to use for the replica')\n .option('-e, --env-file <envFile>', 'Path to environment file')\n .option('--json', 'Output in JSON format (default: true)', true)\n .option('--no-json', 'Disable JSON output format')\n .option('--debug', 'Enable debug logging', false)\n .action(async (cvmId, options) => {\n try {\n let encryptedEnv: string | undefined;\n cvmId = cvmId.replace(/-/g, '');\n\n // Handle environment variables if provided\n if (options.envFile) {\n const envPath = path.resolve(process.cwd(), options.envFile);\n if (!fs.existsSync(envPath)) {\n throw new Error(`Environment file not found: ${envPath}`);\n }\n\n // Read and parse the environment file\n const envContent = fs.readFileSync(envPath, 'utf-8');\n const envVars = envContent\n .split('\\n')\n .filter(line => line.trim() !== '' && !line.trim().startsWith('#'))\n .map(line => {\n const [key, ...value] = line.split('=');\n return {\n key: key.trim(),\n value: value.join('=').trim()\n };\n });\n\n // Get CVM compose config which includes the public key\n const cvmConfig = await getCvmComposeConfig(cvmId);\n\n // Encrypt the environment variables\n logger.info('Encrypting environment variables...');\n const encryptedVars = await encryptEnvVars(\n envVars,\n cvmConfig.env_pubkey\n );\n encryptedEnv = encryptedVars;\n }\n\n // Prepare the request body\n const requestBody: {\n teepod_id?: number;\n encrypted_env?: string;\n } = {};\n\n if (options.nodeId) {\n requestBody.teepod_id = parseInt(options.nodeId, 10);\n }\n if (encryptedEnv) {\n requestBody.encrypted_env = encryptedEnv;\n }\n\n // Call the API to create the replica\n const replica = await replicateCvm(cvmId, requestBody);\n\n if (options.json !== false) {\n console.log(JSON.stringify({\n success: true,\n data: {\n vm_uuid: replica.vm_uuid.replace(/-/g, ''),\n app_id: replica.app_id,\n name: replica.name,\n status: replica.status,\n node: {\n id: replica.teepod_id,\n name: replica.teepod?.name\n },\n vcpus: replica.vcpu,\n memory_mb: replica.memory,\n disk_size_gb: replica.disk_size,\n app_url: replica.app_url || `${process.env.CLOUD_URL || 'https://cloud.phala.network'}/dashboard/cvms/${replica.vm_uuid.replace(/-/g, '')}`,\n raw: replica\n }\n }, null, 2));\n } else {\n logger.success(`Successfully created replica of CVM UUID: ${cvmId} with App ID: ${replica.app_id}`);\n\n const tableData = {\n 'CVM UUID': replica.vm_uuid.replace(/-/g, ''),\n 'App ID': replica.app_id,\n 'Name': replica.name,\n 'Status': replica.status,\n 'Node': `${replica.teepod?.name || 'N/A'} (ID: ${replica.teepod_id || 'N/A'})`,\n 'vCPUs': replica.vcpu,\n 'Memory': `${replica.memory} MB`,\n 'Disk Size': `${replica.disk_size} GB`,\n 'App URL': replica.app_url || `${process.env.CLOUD_URL || 'https://cloud.phala.network'}/dashboard/cvms/${replica.vm_uuid.replace(/-/g, '')}`\n };\n\n logger.keyValueTable(tableData, {\n borderStyle: 'rounded'\n });\n logger.success(`Your CVM replica is being created. You can check its status with:\\nphala cvms get ${replica.app_id}`);\n }\n } catch (error) {\n const errorMessage = `Failed to create CVM replica: ${error instanceof Error ? error.message : String(error)}`;\n if (options.json !== false) {\n console.error(JSON.stringify({\n success: false,\n error: errorMessage,\n stack: options.debug && error instanceof Error ? error.stack : undefined\n }, null, 2));\n } else {\n logger.error(errorMessage);\n }\n process.exit(1);\n }\n });\n","import { Command } from 'commander';\nimport { logger } from '@/src/utils/logger';\nimport { encryptEnvVars } from '@phala/dstack-sdk/encrypt-env-vars';\nimport type { EnvVar } from '@phala/dstack-sdk/encrypt-env-vars';\nimport { getKmsPubkey, getKmsPubkeyDirectly } from '@/src/api/kms';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nimport { parseEnv } from '@/src/utils/secrets';\nimport { promptForFile } from '@/src/utils/prompts';\nimport { createCvmOnChainKms } from '@/src/api/cvms';\nimport fs from 'fs-extra';\nimport inquirer from 'inquirer';\nimport { getTeepods } from '@/src/api/teepods';\nimport { createPublicClient, http } from 'viem';\nimport { ethers } from 'ethers';\nimport { getChainConfig, getNetworkConfig } from '@/src/utils/blockchain';\n\nasync function getAndEncryptEnvs(options: any): Promise<string> {\n let envs: EnvVar[] = [];\n if (!options.skipEnv) {\n // If envFile is not provided, try to find one automatically\n let envFilePath = options.envFile;\n\n if (!envFilePath) {\n // Check for environment files in order of priority\n const envFiles = ['.env.production', '.env.prod', '.env'];\n for (const file of envFiles) {\n if (fs.existsSync(file)) {\n envFilePath = file;\n logger.info(`Using environment file: ${envFilePath}`);\n break;\n }\n }\n\n // If no env file found, ask user if they want to provide one\n if (!envFilePath) {\n if (!options.interactive) {\n logger.error('Environment file is required. Use --env-file to select it');\n process.exit(1);\n } else {\n envFilePath = await promptForFile('Enter the path to your environment file:', '.env', 'file');\n }\n }\n }\n if (envFilePath) {\n try {\n // Read and parse environment variables\n envs = parseEnv([], envFilePath);\n } catch (error) {\n logger.error(`Error reading environment file ${envFilePath}:`, error);\n }\n }\n }\n\n if (envs.length === 0) {\n return '';\n }\n\n if (!options.appId) {\n if (!options.interactive) {\n throw new Error('To encrypt environment variables, --app-id is required.');\n } else {\n options.appId = await inquirer.prompt([\n {\n type: 'input',\n name: 'appId',\n message: 'Enter the App ID for the CVM:',\n }\n ]);\n }\n }\n\n const spinner = logger.startSpinner('Fetching public key from KMS...');\n let kmsResponse;\n if (!options.kmsId) {\n kmsResponse = await getKmsPubkeyDirectly(options.appId);\n } else {\n kmsResponse = await getKmsPubkey(options.kmsId, options.appId);\n }\n const pubkey = kmsResponse.public_key;\n spinner.stop(true);\n\n if (!pubkey) {\n throw new Error('Failed to retrieve public key from KMS.');\n }\n\n const encryptSpinner = logger.startSpinner('Encrypting environment variables');\n const encrypted_env = await encryptEnvVars(envs, pubkey);\n encryptSpinner.stop(true);\n\n return encrypted_env;\n}\n\nasync function buildVmConfig(options: any, encryptedEnv: string): Promise<any> {\n logger.info(`Using custom App ID: ${options.customAppId}, fetching AppAuth details from KMS...`);\n let kmsInfo;\n let kmsContractAddress;\n let appAuthContractAddress;\n // Get KMS list from the teepods response (it's at the root level, not in individual teepods)\n const teepodsSpinner = logger.startSpinner('Fetching available Nodes');\n const teepods = await getTeepods();\n teepodsSpinner.stop(true);\n if (teepods.nodes.length === 0) {\n throw new Error('No Nodes available.');\n }\n const allKmsInfos = teepods.kms_list || [];\n kmsInfo = allKmsInfos.find(kms => kms.id === options.kmsId);\n\n if (!kmsInfo) {\n throw new Error(`No KMS found with ID: ${options.kmsId} in the available Nodes`);\n }\n\n kmsContractAddress = kmsInfo.kms_contract_address;\n logger.info(`Using KMS contract address: ${kmsContractAddress} from KMS ID: ${options.kmsId}`);\n\n // Get the first available KMS to determine the chain\n // TODO: when multiple KMS are available, how to choose one?\n const kms = teepods.kms_list?.[0];\n if (!kms) {\n throw new Error('No KMS available');\n }\n\n // Get the chain config\n const chain = getChainConfig(kms.chain_id);\n const rpcUrl = options.rpcUrl || chain.rpcUrls.default.http[0];\n \n // Initialize public client with the appropriate chain and RPC URL\n const publicClient = createPublicClient({\n chain,\n transport: http(rpcUrl)\n });\n\n // KMS Auth ABI for reading app registration details\n const kmsAuthAbi = [\n {\n inputs: [{ name: 'app', type: 'address' }],\n name: 'apps',\n outputs: [\n { name: 'isRegistered', type: 'bool' },\n { name: 'controller', type: 'address' },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n ] as const;\n\n try {\n // Ensure the KMS contract address is valid\n if (!ethers.isAddress(kmsContractAddress)) {\n throw new Error(`Invalid KMS contract address: ${kmsContractAddress}`);\n }\n\n if (!ethers.isAddress(options.appId)) {\n throw new Error(`Invalid custom App ID: ${options.appId}`);\n }\n\n // Ensure customAppId has 0x prefix\n const customAppId = options.appId.startsWith('0x')\n ? options.appId\n : `0x${options.appId}`;\n\n // Query the KMS contract for app registration details\n const [isRegistered, controllerAddress] = await publicClient.readContract({\n address: kmsContractAddress as `0x${string}`,\n abi: kmsAuthAbi,\n functionName: 'apps',\n args: [customAppId as `0x${string}`]\n });\n\n // Validate the response\n if (!isRegistered) {\n throw new Error(`App ${options.appId} is not registered in KMS contract ${kmsContractAddress}`);\n }\n\n if (!controllerAddress || controllerAddress === ethers.ZeroAddress) {\n throw new Error(`Invalid controller address for app ${options.appId}`);\n }\n\n logger.info(`Successfully verified AppAuth contract at ${controllerAddress}`);\n appAuthContractAddress = controllerAddress;\n\n } catch (error) {\n throw new Error(`Failed to verify custom App ID: ${error instanceof Error ? error.message : String(error)}`);\n }\n return {\n app_id: options.appId,\n compose_hash: options.composeHash,\n contract_address: appAuthContractAddress,\n deployer_address: '',\n encrypted_env: encryptedEnv,\n kms_id: options.kmsId,\n };\n}\n\nfunction displayProvisionResult(response: any, options: any): void {\n logger.success('CVM provisioned successfully');\n logger.break();\n if (options.json !== false) {\n // Output as JSON for script consumption\n const jsonOutput = {\n success: true,\n data: {\n cvm_id: response.vm_uuid.replace(/-/g, ''),\n name: response.name,\n status: response.status,\n app_id: response.app_id,\n endpoint: `${CLOUD_URL}/dashboard/cvms/${response.vm_uuid.replace(/-/g, '')}`,\n }\n };\n console.log(JSON.stringify(jsonOutput, null, 2));\n } else {\n // Human-readable output\n const tableData = {\n 'CVM ID': response.vm_uuid.replace(/-/g, ''),\n 'Name': response.name,\n 'Status': response.status,\n 'App ID': response.app_id,\n 'Endpoint': `${CLOUD_URL}/dashboard/cvms/${response.vm_uuid.replace(/-/g, '')}`,\n };\n logger.keyValueTable(tableData);\n }\n}\n\nexport const commitProvisionCommand = new Command()\n .name('commit-provision')\n .description('Provision a new CVM with on-chain KMS integration.')\n .option('-i, --interactive', 'Enable interactive mode for required parameters', false)\n .option('--app-id <appId>', 'App ID for the CVM (with 0x prefix for on-chain KMS).')\n .option('--compose-hash <composeHash>', 'Compose hash for the CVM (SHA-256 hex string).')\n .option('--kms-id <kmsId>', 'KMS ID for API-based public key retrieval.')\n .option('--deployer-address <deployerAddress>', 'Deployer address for the CVM.')\n .option('-e, --env-file <envFile>', 'Path to environment file.')\n .option('--skip-env', 'Skip environment variable prompt.', false)\n .option('--debug', 'Enable debug mode', false)\n .option('-c, --compose <compose>', 'Path to Docker Compose file')\n .option('--json', 'Output in JSON format (default: true)', true)\n .option('--no-json', 'Disable JSON output format')\n .option('--rpc-url <rpcUrl>', 'RPC URL for the blockchain.')\n .action(async (options) => {\n try {\n const encryptedEnv = await getAndEncryptEnvs(options);\n const vmConfig = await buildVmConfig(options, encryptedEnv);\n\n const createSpinner = logger.startSpinner('Provisioning CVM...');\n if (options.debug) {\n logger.info(`Provisioning with config: ${JSON.stringify(vmConfig, null, 2)}`);\n }\n const response = await createCvmOnChainKms(vmConfig);\n createSpinner.stop(true);\n\n if (!response) {\n throw new Error('Failed to provision CVM. The API returned an empty response.');\n }\n\n displayProvisionResult(response, options);\n\n } catch (error) {\n // Spinners are stopped within their respective functions on success or failure.\n // We just need to log the final error here.\n const errorMessage = error instanceof Error ? error.message : String(error);\n if (options.json !== false) {\n console.error(JSON.stringify({\n success: false,\n error: errorMessage,\n stack: options.debug && error instanceof Error ? error.stack : undefined\n }, null, 2));\n } else {\n logger.error(`Failed to provision CVM: ${errorMessage}`);\n if (options.debug && error.stack) {\n logger.error(error.stack);\n }\n }\n process.exit(1);\n }\n });\n","import { apiClient } from './client';\nimport { execSync } from 'child_process';\nimport { logger } from '@/src/utils/logger';\nimport { API_ENDPOINTS } from '@/src/utils/constants';\nimport { CvmComposeConfig, cvmComposeConfigSchema, kmsPubkeyResponseSchema, type KmsPubkeyResponse } from './types';\nimport { recoverSignerPublicKey } from '@/src/utils/signature';\n\n/**\n * Get public key from the KMS API for a given app ID.\n * @param kmsId The KMS ID.\n * @param appId The application ID.\n * @returns The public key and signature.\n * TODO: need to verify the response signature\n */\nexport async function getKmsPubkey(kmsId: string, appId: string): Promise<KmsPubkeyResponse> {\n try {\n const response = await apiClient.get<KmsPubkeyResponse>(\n API_ENDPOINTS.KMS_PUBKEY(kmsId, appId)\n );\n const parsedResponse = kmsPubkeyResponseSchema.parse(response);\n\n // const recoveredSigner = recoverSignerPublicKey(\n // parsedResponse.public_key,\n // parsedResponse.signature,\n // appId\n // );\n\n // // Verify that the public key in the response is the same as the one recovered from the signature.\n // // This proves that the sender owns the private key for the given public key.\n // if (\n // !recoveredSigner ||\n // recoveredSigner.toLowerCase() !== parsedResponse.public_key.toLowerCase()\n // ) {\n // throw new Error(\n // 'Signature verification failed: The public key in the response does not match the signer.'\n // );\n // }\n\n // logger.info('KMS public key signature verified successfully.');\n return parsedResponse;\n } catch (error) {\n throw new Error(\n `Failed to get public key from KMS: ${error instanceof Error ? error.message : String(error)\n }`\n );\n }\n}\n\n/**\n * Get public key directly from KMS node for a given app ID using curl.\n * This is the default method when a kmsId is not available.\n * @param appId The application ID.\n * @returns The public key and signature.\n * TODO: This API is wrong, need to be fixed\n */\nexport async function getKmsPubkeyDirectly(appId: string): Promise<KmsPubkeyResponse> {\n try {\n const response = await apiClient.get<CvmComposeConfig>(\n API_ENDPOINTS.CVM_COMPOSE(appId)\n );\n const parsedResponse = cvmComposeConfigSchema.parse(response);\n return {\n public_key: parsedResponse.env_pubkey,\n signature: '',\n };\n } catch (error) {\n logger.error(`Failed to get public key directly from KMS: ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n}\n","import { Command } from 'commander';\nimport { createCvm, createCvmOnChainKms, getPubkeyFromCvm, provisionCvm } from '@/src/api/cvms';\nimport { getTeepods } from '@/src/api/teepods';\nimport { logger } from '@/src/utils/logger';\nimport type { TEEPod } from '@/src/api/types';\nimport { DEFAULT_VCPU, DEFAULT_MEMORY, DEFAULT_DISK_SIZE, CLOUD_URL } from '@/src/utils/constants';\nimport { encryptEnvVars } from '@phala/dstack-sdk/encrypt-env-vars';\nimport type { EnvVar } from '@phala/dstack-sdk/encrypt-env-vars';\nimport { parseMemoryInput, parseDiskSizeInput } from '@/src/utils/units';\n\nimport fs from 'fs-extra';\nimport path from 'node:path';\nimport inquirer from 'inquirer';\nimport { detectFileInCurrentDir, promptForFile } from '@/src/utils/prompts';\nimport { parseEnv } from '@/src/utils/secrets';\n\n/**\n * Gathers and validates all necessary configurations for creating a CVM.\n */\nasync function gatherCvmConfig(options: any) {\n if (!options.name) {\n if (!options.interactive) {\n const folderName = path.basename(process.cwd()).toLowerCase().replace(/[^a-z0-9_-]/g, '-');\n options.name = folderName;\n } else {\n // Use current directory name as default\n const folderName = path.basename(process.cwd()).toLowerCase().replace(/[^a-z0-9_-]/g, '-');\n\n const { name } = await inquirer.prompt([\n {\n type: 'input',\n name: 'name',\n message: 'Enter a name for the CVM:',\n default: folderName,\n validate: (input) => {\n if (!input.trim()) return 'CVM name is required';\n if (input.trim().length > 20) return 'CVM name must be less than 20 characters';\n if (input.trim().length < 3) return 'CVM name must be at least 3 characters';\n if (!/^[a-zA-Z0-9_-]+$/.test(input)) return 'CVM name must contain only letters, numbers, underscores, and hyphens';\n return true;\n }\n }\n ]);\n options.name = name;\n }\n }\n\n if (!options.compose) {\n if (!options.interactive) {\n logger.error('Docker Compose file is required. Use --compose or --interactive to select it');\n process.exit(1);\n } else {\n const possibleFiles = ['docker-compose.yml', 'docker-compose.yaml'];\n const composeFileName = detectFileInCurrentDir(possibleFiles, 'Detected docker compose file: {path}');\n options.compose = await promptForFile('Enter the path to your Docker Compose file:', composeFileName, 'file');\n }\n }\n\n const composePath = path.resolve(options.compose);\n if (!fs.existsSync(composePath)) {\n throw new Error(`Docker Compose file not found: ${composePath}`);\n }\n const composeString = fs.readFileSync(composePath, 'utf8');\n\n // Handle environment variables\n let envs: EnvVar[] = [];\n let allowedEnvs: string[] = [];\n\n if (!options.skipEnv) {\n // If envFile is not provided, try to find one automatically\n let envFilePath = options.envFile;\n\n if (!envFilePath) {\n // Check for environment files in order of priority\n const envFiles = ['.env.production', '.env.prod', '.env'];\n for (const file of envFiles) {\n if (fs.existsSync(file)) {\n envFilePath = file;\n logger.info(`Using environment file: ${envFilePath}`);\n break;\n }\n }\n\n // If no env file found, ask user if they want to provide one\n if (!envFilePath) {\n if (!options.interactive) {\n logger.error('Environment file is required. Use --env-file to select it');\n process.exit(1);\n } else {\n envFilePath = await promptForFile('Enter the path to your environment file:', '.env', 'file');\n }\n }\n }\n\n if (envFilePath) {\n try {\n // Read and parse environment variables\n envs = parseEnv([], envFilePath);\n\n // Extract just the keys for allowed_envs\n allowedEnvs = envs.map(env => env.key);\n\n if (allowedEnvs.length > 0) {\n logger.info(`Using environment variables from ${envFilePath}`);\n logger.debug(`Allowed environment variables: ${allowedEnvs.join(', ')}`);\n } else {\n logger.warn(`No environment variables found in ${envFilePath}`);\n }\n } catch (error) {\n logger.error(`Error reading environment file ${envFilePath}:`, error);\n }\n }\n }\n\n const teepodsSpinner = logger.startSpinner('Fetching available Nodes');\n const teepods = await getTeepods();\n teepodsSpinner.stop(true);\n if (teepods.nodes.length === 0) {\n throw new Error('No Nodes available.');\n }\n\n // Filter TEEpods based on on-chain KMS support\n let availableTeepods = teepods.nodes.filter(teepod =>\n options.kmsId ? teepod.support_onchain_kms : !teepod.support_onchain_kms\n );\n\n if (availableTeepods.length === 0) {\n const errorMessage = options.kmsId\n ? 'No Nodes available that support on-chain KMS.'\n : 'No Nodes available that does not support on-chain KMS.';\n throw new Error(errorMessage);\n }\n\n // If kms-id is provided, find the corresponding KMS info\n let kmsInfo;\n let kmsContractAddress;\n if (options.kmsId) {\n // Get KMS list from the teepods response (it's at the root level, not in individual teepods)\n const allKmsInfos = teepods.kms_list || [];\n kmsInfo = allKmsInfos.find(kms => kms.id === options.kmsId);\n\n if (!kmsInfo) {\n throw new Error(`No KMS found with ID: ${options.kmsId} in the available Nodes`);\n }\n\n kmsContractAddress = kmsInfo.kms_contract_address;\n logger.info(`Using KMS contract address: ${kmsContractAddress} from KMS ID: ${options.kmsId}`);\n }\n\n let selectedTeepod: TEEPod;\n if (options.nodeId) {\n selectedTeepod = availableTeepods.find(pod => pod.teepod_id === Number(options.nodeId));\n if (!selectedTeepod) {\n throw new Error(`Selected Node with ID ${options.nodeId} is not available or does not support on-chain KMS.`);\n }\n } else {\n if (!options.interactive) {\n logger.error('Node is required. Use --node-id to select it');\n process.exit(1);\n } else {\n const { node } = await inquirer.prompt([{ type: 'list', name: 'node', message: 'Select a Node to use:', choices: availableTeepods.map(t => ({ name: `${t.name} (Region: ${t.region_identifier})`, value: t })) }]);\n selectedTeepod = node;\n }\n }\n\n let selectedImage;\n if (options.image) {\n selectedImage = selectedTeepod.images?.find(image => image.name === options.image);\n if (!selectedImage) throw new Error(`Failed to find selected image '${options.image}' for the selected Node.`);\n } else {\n selectedImage = selectedTeepod.images?.[0];\n if (!selectedImage) {\n throw new Error('No images found for the selected Node.');\n }\n logger.info(`Using image: ${selectedImage.name}`);\n }\n\n // allowedEnvs is already set above from the env file parsing\n\n const composeFile: any = {\n docker_compose_file: composeString,\n allowed_envs: allowedEnvs,\n features: ['kms', 'tproxy-net'],\n kms_enabled: true,\n manifest_version: 2,\n name: options.name,\n public_logs: true,\n public_sysinfo: true,\n tproxy_enabled: true,\n };\n\n if (options.preLaunchScript) {\n composeFile.pre_launch_script = options.preLaunchScript;\n }\n\n // Parse memory and disk size with units\n let memoryMB = DEFAULT_MEMORY;\n if (options.memory) {\n try {\n memoryMB = parseMemoryInput(options.memory);\n logger.info(`Using memory: ${memoryMB}MB (parsed from: ${options.memory})`);\n } catch (error) {\n logger.warn(`Invalid memory format '${options.memory}'. Using default: ${DEFAULT_MEMORY}MB`);\n }\n }\n\n let diskSizeGB = DEFAULT_DISK_SIZE;\n if (options.diskSize) {\n try {\n diskSizeGB = parseDiskSizeInput(options.diskSize);\n logger.info(`Using disk size: ${diskSizeGB}GB (parsed from: ${options.diskSize})`);\n } catch (error) {\n logger.warn(`Invalid disk size format '${options.diskSize}'. Using default: ${DEFAULT_DISK_SIZE}GB`);\n }\n }\n\n const vmConfig: any = {\n teepod_id: selectedTeepod.teepod_id,\n name: options.name,\n image: selectedImage.name,\n vcpu: Number(options.vcpu) || DEFAULT_VCPU,\n memory: memoryMB,\n disk_size: diskSizeGB,\n listed: false,\n };\n\n // Use compose_manifest for standard flow, compose_file for on-chain KMS\n if (options.kmsId) {\n vmConfig.compose_file = composeFile;\n } else {\n vmConfig.compose_manifest = composeFile;\n }\n\n return { vmConfig, envs, teepods, kmsContractAddress };\n}\n\n/**\n * Provisions the CVM and logs the result.\n */\nasync function provisionAndLogCvm(vmConfig: any, options: any) {\n const provisionSpinner = logger.startSpinner('Provisioning CVM for on-chain KMS...');\n const provisionResponse = await provisionCvm(vmConfig);\n provisionSpinner.stop(true);\n\n if (!provisionResponse) {\n throw new Error('Failed to provision CVM for on-chain KMS');\n }\n\n if (options.json !== false) {\n console.log(JSON.stringify({\n success: true,\n data: {\n app_id: provisionResponse.app_id,\n device_id: provisionResponse.device_id,\n compose_hash: provisionResponse.compose_hash,\n os_image_hash: provisionResponse.os_image_hash,\n raw: provisionResponse\n }\n }, null, 2));\n } else {\n logger.success('CVM provisioned successfully!');\n logger.keyValueTable({\n 'App ID': provisionResponse.app_id,\n 'Device ID': provisionResponse.device_id,\n 'Compose Hash': provisionResponse.compose_hash,\n 'OS Image Hash': provisionResponse.os_image_hash,\n });\n }\n\n return provisionResponse;\n}\n\n\nasync function executeStandardCreation(vmConfig: any, envs: EnvVar[], options: any) {\n const spinner = logger.startSpinner('Getting public key from CVM');\n const pubkey = await getPubkeyFromCvm(vmConfig);\n spinner.stop(true);\n if (!pubkey) throw new Error('Failed to get public key from CVM');\n\n const encryptSpinner = logger.startSpinner('Encrypting environment variables');\n const encrypted_env = await encryptEnvVars(envs, pubkey.app_env_encrypt_pubkey);\n encryptSpinner.stop(true);\n\n const createSpinner = logger.startSpinner('Provisioning CVM');\n const response = await createCvm({ ...vmConfig, encrypted_env, app_env_encrypt_pubkey: pubkey.app_env_encrypt_pubkey, app_id_salt: pubkey.app_id_salt });\n createSpinner.stop(true);\n if (!response) throw new Error('Failed to create CVM');\n\n if (options.json !== false) {\n const jsonOutput: any = {\n success: true,\n data: {\n cvm_id: response.vm_uuid.replace(/-/g, ''),\n app_id: response.app_id,\n name: response.name,\n status: response.status,\n endpoint: `${CLOUD_URL}/dashboard/cvms/${response.vm_uuid.replace(/-/g, '')}`,\n created_at: response.created_at,\n raw: response\n }\n };\n if (response.kms_contract_address) jsonOutput.data.kms_contract_address = response.kms_contract_address;\n if (response.kms_owner_address) jsonOutput.data.kms_owner_address = response.kms_owner_address;\n console.log(JSON.stringify(jsonOutput, null, 2));\n } else {\n logger.success('CVM created successfully');\n logger.break();\n const tableData: { [key: string]: any } = {\n 'CVM ID': response.vm_uuid.replace(/-/g, ''),\n 'App ID': response.app_id,\n 'Name': response.name,\n 'Status': response.status,\n 'Endpoint': `${CLOUD_URL}/dashboard/cvms/${response.vm_uuid.replace(/-/g, '')}`,\n 'Created At': new Date(response.created_at).toLocaleString(),\n };\n if (response.kms_contract_address) tableData['KMS Contract Address'] = response.kms_contract_address;\n if (response.kms_owner_address) tableData['KMS Owner Address'] = response.kms_owner_address;\n logger.keyValueTable(tableData);\n }\n}\n\nexport const provisionCommand = new Command()\n .name('provision')\n .description('Provision a new CVM, with optional on-chain KMS integration.')\n // CVM options\n .option('-n, --name <name>', 'Name of the CVM')\n .option('-c, --compose <compose>', 'Path to Docker Compose file')\n .option('--vcpu <vcpu>', `Number of vCPUs, default is ${DEFAULT_VCPU}`)\n .option('--memory <memory>', `Memory with optional unit (e.g., 2G, 500MB, 1024), default is ${DEFAULT_MEMORY}MB`)\n .option('--disk-size <diskSize>', `Disk size with optional unit (e.g., 50G, 1T, 100), default is ${DEFAULT_DISK_SIZE}GB`)\n .option('--image <image>', 'Version of dstack image to use')\n .option('--node-id <nodeId>', 'Node ID to use')\n .option('-e, --env-file <envFile>', 'Path to environment file')\n .option('--skip-env', 'Skip environment variable prompt', false)\n .option('-i, --interactive', 'Enable interactive mode for required parameters', false)\n .option('--kms-id <kmsId>', 'KMS ID to use.')\n .option('--pre-launch-script <preLaunchScript>', 'Path to pre-launch script')\n .option('--json', 'Output in JSON format (default: true)', true)\n .option('--no-json', 'Disable JSON output format')\n .action(async (options) => {\n try {\n // Step 1: Gather CVM configuration\n logger.info('Step 1: Preparing CVM configuration...');\n const { vmConfig, envs } = await gatherCvmConfig(options);\n\n // If no KMS ID is provided, use standard creation\n if (!options.kmsId) {\n logger.info('\\nStep 2: Creating CVM...');\n await executeStandardCreation(vmConfig, envs, options);\n return;\n }\n // Step 2: Provision the CVM\n logger.info('\\nStep 2: Provisioning CVM...');\n await provisionAndLogCvm(vmConfig, options);\n\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n if (options.json !== false) {\n console.error(JSON.stringify({\n success: false,\n error: errorMessage,\n stack: options.debug && error instanceof Error ? error.stack : undefined\n }, null, 2));\n } else {\n logger.error(`Failed to create CVM: ${errorMessage}`);\n }\n process.exit(1);\n }\n });\n","/**\n * Parse a string with optional unit into bytes\n * @param input The input string (e.g., '2G', '500MB', '1T')\n * @param defaultUnit Default unit to use if none specified (e.g., 'B', 'KB', 'MB', 'GB', 'TB')\n * @returns Number of bytes\n */\nexport function parseSizeWithUnit(input: string, defaultUnit: 'B' | 'KB' | 'MB' | 'GB' | 'TB' = 'B'): number {\n // Handle empty or invalid input\n if (!input || typeof input !== 'string') {\n throw new Error('Invalid input: must be a non-empty string');\n }\n\n // Extract numeric value and unit using regex\n const match = input.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*([KkMmGgTt][Bb]?)?$/);\n \n if (!match) {\n throw new Error(`Invalid format: ${input}. Expected format: <number>[unit] (e.g., 2G, 500MB, 1T)`);\n }\n\n const value = parseFloat(match[1]);\n const unit = (match[2] || defaultUnit).toUpperCase().replace('B', '');\n \n // Convert to bytes based on unit\n const units: Record<string, number> = {\n 'K': 1024, // Kilo\n 'M': 1024 * 1024, // Mega\n 'G': 1024 * 1024 * 1024, // Giga\n 'T': 1024 * 1024 * 1024 * 1024, // Tera\n '': 1 // No unit (bytes)\n };\n\n\n if (!(unit in units)) {\n throw new Error(`Unsupported unit: ${unit}. Supported units: B, K/KB, M/MB, G/GB, T/TB`);\n }\n\n return Math.round(value * units[unit]);\n}\n\n/**\n * Parse memory input (default unit: MB)\n * @param input The input string (e.g., '2G', '500MB', '1024')\n * @returns Memory in MB (always a multiple of 1024MB = 1GB)\n * @throws If the value is not a multiple of 1GB\n */\nexport function parseMemoryInput(input: string): number {\n const bytes = parseSizeWithUnit(input, 'MB');\n const memoryMB = Math.round(bytes / (1024 * 1024)); // Convert to MB\n \n // Ensure memory is a multiple of 1GB (1024MB)\n if (memoryMB % 1024 !== 0) {\n throw new Error(`Memory must be a multiple of 1GB (1024MB). Got: ${memoryMB}MB`);\n }\n \n return memoryMB;\n}\n\n/**\n * Parse disk size input (default unit: GB)\n * @param input The input string (e.g., '50G', '1T', '100')\n * @returns Disk size in GB (always a multiple of 1GB, max 250GB)\n * @throws If the value is not a multiple of 1GB or exceeds 250GB\n */\nexport function parseDiskSizeInput(input: string): number {\n const bytes = parseSizeWithUnit(input, 'GB');\n const diskSizeGB = Math.round(bytes / (1024 * 1024 * 1024)); // Convert to GB\n \n // Ensure disk size is a multiple of 1GB\n if (diskSizeGB % 1 !== 0) {\n throw new Error(`Disk size must be a multiple of 1GB. Got: ${diskSizeGB}GB`);\n }\n \n // Ensure disk size doesn't exceed 250GB\n // TODO: once the default disk size limitation removed in DStack, we should remove this as well.\n const MAX_DISK_SIZE_GB = 250;\n if (diskSizeGB > MAX_DISK_SIZE_GB) {\n throw new Error(`Maximum disk size is ${MAX_DISK_SIZE_GB}GB. Got: ${diskSizeGB}GB`);\n }\n \n return diskSizeGB;\n}\n","import { Command } from 'commander';\nimport { getCvmByAppId, updateCvmCompose, getCvmComposeFile } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { parseEnv } from '@/src/utils/secrets';\nimport { promptForFile } from '@/src/utils/prompts';\nimport { CLOUD_URL } from '@/src/utils/constants';\nimport fs from 'fs-extra';\nimport inquirer from 'inquirer';\nimport { detectFileInCurrentDir } from '@/src/utils/prompts';\nimport { encryptEnvVars, type EnvVar } from '@phala/dstack-sdk/encrypt-env-vars';\n\n\nasync function gatherUpdateInputs(cvmId: string, options: any): Promise<any> {\n if (!cvmId) {\n if (!options.interactive) {\n logger.error('CVM ID is required. Use --app-id to enter it');\n process.exit(1);\n } else {\n const { id } = await inquirer.prompt([{ type: 'input', name: 'id', message: 'Enter the CVM ID to update:' }]);\n cvmId = id;\n }\n }\n\n const spinner = logger.startSpinner(`Fetching current configuration for CVM ${cvmId}`);\n const currentCvm = await getCvmByAppId(cvmId);\n spinner.stop(true);\n\n if (!currentCvm) {\n logger.error(`CVM with CVM ID ${cvmId} not found`);\n process.exit(1);\n }\n\n if (!options.compose) {\n if (!options.interactive) {\n logger.error('Docker Compose file is required. Use --compose to select it');\n process.exit(1);\n } else {\n const possibleFiles = ['docker-compose.yml', 'docker-compose.yaml'];\n const composeFileName = detectFileInCurrentDir(possibleFiles, 'Detected docker compose file: {path}');\n options.compose = await promptForFile('Enter the path to your new Docker Compose file:', composeFileName, 'file');\n }\n }\n\n let envs: EnvVar[] = [];\n let allowedEnvs: string[] = [];\n\n if (!options.skipEnv) {\n // If envFile is not provided, try to find one automatically\n let envFilePath = options.envFile;\n\n if (!envFilePath) {\n // Check for environment files in order of priority\n const envFiles = ['.env.production', '.env.prod', '.env'];\n for (const file of envFiles) {\n if (fs.existsSync(file)) {\n envFilePath = file;\n logger.info(`Using environment file: ${envFilePath}`);\n break;\n }\n }\n\n // If no env file found, ask user if they want to provide one\n if (!envFilePath) {\n if (options.interactive) {\n envFilePath = await promptForFile('Enter the path to your environment file:', '.env', 'file');\n }\n }\n }\n\n if (envFilePath) {\n try {\n // Read and parse environment variables\n envs = parseEnv([], envFilePath);\n\n // Extract just the keys for allowed_envs\n allowedEnvs = envs.map(env => env.key);\n\n if (allowedEnvs.length > 0) {\n logger.info(`Using environment variables from ${envFilePath}`);\n logger.debug(`Allowed environment variables: ${allowedEnvs.join(', ')}`);\n } else {\n logger.warn(`No environment variables found in ${envFilePath}`);\n }\n } catch (error) {\n logger.error(`Error reading environment file ${envFilePath}:`, error);\n }\n }\n }\n\n return { ...options, cvmId: currentCvm.vm_uuid.replace(/-/g, ''), currentCvm, allowedEnvs };\n}\n\nasync function prepareUpdatePayload(options: any, currentCvm: any): Promise<{ composeString: string; encryptedEnv: string }> {\n const composeString = fs.readFileSync(options.compose, 'utf8');\n\n let encryptedEnv = '';\n let envs: EnvVar[] = [];\n if (options.envFile) {\n try {\n envs = parseEnv([], options.envFile);\n } catch (error) {\n logger.error(`Failed to process environment file: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n } else if (options.interactive) {\n const { useEnvFile } = await inquirer.prompt([{\n type: 'confirm',\n name: 'useEnvFile',\n message: 'Do you want to use an environment file?',\n default: false,\n }]);\n if (useEnvFile) {\n const envFilePath = await promptForFile('Enter the path to your environment file:', '.env', 'file');\n envs = parseEnv([], envFilePath);\n }\n }\n\n if (envs.length > 0) {\n if (!currentCvm.encrypted_env_pubkey) {\n logger.error('Could not find public key to encrypt environment variables for this CVM.');\n process.exit(1);\n }\n encryptedEnv = await encryptEnvVars(envs, currentCvm.encrypted_env_pubkey);\n }\n\n return { composeString, encryptedEnv };\n}\n\nexport const upgradeProvisionCommand = new Command()\n .name('upgrade-provision')\n .description('Provision a CVM upgrade with a new compose file')\n .argument('<cvm-id>', 'ID of the CVM to upgrade')\n .option('-c, --compose <compose>', 'Path to new Docker Compose file')\n .option('-e, --env-file <envFile>', 'Path to environment file')\n .option('--skip-env', 'Skip environment variable prompt', false)\n .option('--debug', 'Enable debug logging', false)\n .option('-i, --interactive', 'Enable interactive mode', false)\n .option('--json', 'Output in JSON format (default: true)', true)\n .option('--no-json', 'Disable JSON output format')\n .action(async (cvmId: string, options) => {\n try {\n const { cvmId: finalCvmId, currentCvm, ...gatheredOptions } = await gatherUpdateInputs(cvmId, options);\n const { composeString, encryptedEnv } = await prepareUpdatePayload(gatheredOptions, currentCvm);\n\n const spinner = logger.startSpinner(`Updating CVM ${finalCvmId}`);\n const currentComposeFile = await getCvmComposeFile(finalCvmId);\n currentComposeFile.docker_compose_file = composeString;\n currentComposeFile.allowed_envs = gatheredOptions.allowedEnvs;\n const response = await updateCvmCompose(finalCvmId, currentComposeFile);\n spinner.stop(true);\n\n if (!response || !response.compose_hash) {\n logger.error('Failed to initiate CVM update or get compose hash.');\n process.exit(1);\n }\n\n logger.info(`CVM UUID: ${currentCvm.vm_uuid.replace(/-/g, '')}`);\n logger.info(`App ID: ${currentCvm.app_id}`);\n\n if (options.json !== false) {\n console.log(JSON.stringify({\n success: true,\n data: {\n cvm_id: currentCvm.vm_uuid.replace(/-/g, ''),\n app_id: finalCvmId,\n compose_hash: response.compose_hash,\n dashboard_url: `${CLOUD_URL}/dashboard/cvms/${currentCvm.vm_uuid.replace(/-/g, '')}`,\n raw: response\n }\n }, null, 2));\n } else {\n logger.success(`CVM update has been provisioned. New compose hash: ${response.compose_hash}`);\n logger.info(`Dashboard: ${CLOUD_URL}/dashboard/cvms/${currentCvm.vm_uuid.replace(/-/g, '')}`);\n }\n\n } catch (error) {\n const errorMessage = `Failed to provision CVM upgrade: ${error instanceof Error ? error.message : String(error)}`;\n if (options.json !== false) {\n console.error(JSON.stringify({\n success: false,\n error: errorMessage,\n stack: options.debug && error instanceof Error ? error.stack : undefined\n }, null, 2));\n } else {\n logger.error(errorMessage);\n }\n process.exit(1);\n }\n });\n","import { Command } from 'commander';\nimport { updatePatchCvmCompose, getCvmByAppId } from '@/src/api/cvms';\nimport { logger } from '@/src/utils/logger';\nimport { parseEnv } from '@/src/utils/secrets';\nimport { encryptEnvVars, type EnvVar } from '@phala/dstack-sdk/encrypt-env-vars';\nimport inquirer from 'inquirer';\nimport { promptForFile } from '@/src/utils/prompts';\nimport { CLOUD_URL } from '@/src/utils/constants';\n\nasync function applyUpdate(cvmId: string, composeHash: string, encryptedEnv: string, options: any = {}): Promise<void> {\n const spinner = logger.startSpinner('Applying update...');\n try {\n const payload = { compose_hash: composeHash, encrypted_env: encryptedEnv };\n const response = await updatePatchCvmCompose(cvmId, payload);\n\n if (response === null) {\n spinner.stop(true);\n if (options && options.json !== false) {\n console.log(JSON.stringify({\n success: true,\n data: {\n cvm_id: cvmId,\n message: 'Update applied successfully',\n dashboard_url: `${CLOUD_URL}/dashboard/cvms/${cvmId.replace(/-/g, '')}`\n }\n }, null, 2));\n } else {\n logger.success('Update applied successfully!');\n logger.info(`Dashboard: ${CLOUD_URL}/dashboard/cvms/${cvmId.replace(/-/g, '')}`);\n }\n } else {\n spinner.stop(false);\n const errorMessage = `Failed to apply update: ${JSON.stringify(response.detail, null, 2)}`;\n if (options && options.json !== false) {\n console.error(JSON.stringify({\n success: false,\n error: errorMessage\n }, null, 2));\n } else {\n logger.error(errorMessage);\n }\n process.exit(1);\n }\n } catch (error) {\n spinner.stop(false);\n throw error;\n }\n}\n\nasync function prepareUpdatePayload(options: any, currentCvm: any): Promise<{ encryptedEnv: string }> {\n\n let encryptedEnv = '';\n let envs: EnvVar[] = [];\n if (options.envFile) {\n try {\n envs = parseEnv([], options.envFile);\n } catch (error) {\n logger.error(`Failed to process environment file: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n } else if (options.interactive) {\n const { useEnvFile } = await inquirer.prompt([{\n type: 'confirm',\n name: 'useEnvFile',\n message: 'Do you want to use an environment file?',\n default: false,\n }]);\n if (useEnvFile) {\n const envFilePath = await promptForFile('Enter the path to your environment file:', '.env', 'file');\n envs = parseEnv([], envFilePath);\n }\n }\n\n if (envs.length > 0) {\n if (!currentCvm.encrypted_env_pubkey) {\n logger.error('Could not find public key to encrypt environment variables for this CVM.');\n process.exit(1);\n }\n encryptedEnv = await encryptEnvVars(envs, currentCvm.encrypted_env_pubkey);\n }\n\n return { encryptedEnv };\n}\n\nexport const upgradeCommitCommand = new Command()\n .name('upgrade-commit')\n .description('Commit a provisioned CVM upgrade')\n .argument('<cvm-id>', 'ID of the CVM to upgrade')\n .requiredOption('--compose-hash <composeHash>', 'Compose hash from the provision step')\n .option('-e, --env-file <envFile>', 'Path to environment file')\n .option('--skip-env', 'Skip environment variable prompt', false)\n .option('--json', 'Output in JSON format (default: true)', true)\n .option('--no-json', 'Disable JSON output format')\n .action(async (cvmId: string, options) => {\n try {\n const spinner = logger.startSpinner(`Fetching current configuration for CVM ${cvmId}`);\n const currentCvm = await getCvmByAppId(cvmId);\n logger.info(`\\nCVM UUID: ${currentCvm.vm_uuid.replace(/-/g, '')}`);\n logger.info(`App ID: ${currentCvm.app_id}`);\n spinner.stop(true);\n if (!currentCvm) {\n logger.error(`CVM with CVM ID ${cvmId} not found`);\n process.exit(1);\n }\n const { encryptedEnv } = await prepareUpdatePayload(options, currentCvm);\n await applyUpdate(currentCvm.vm_uuid.replace(/-/g, ''), options.composeHash, encryptedEnv, options);\n } catch (error) {\n const errorMessage = `Failed to commit CVM upgrade: ${error instanceof Error ? error.message : String(error)}`;\n if (options.json !== false) {\n console.error(JSON.stringify({\n success: false,\n error: errorMessage,\n stack: options.debug && error instanceof Error ? error.stack : undefined\n }, null, 2));\n } else {\n logger.error(errorMessage);\n }\n process.exit(1);\n }\n });\n","import { Command } from 'commander';\nimport { logger } from '@/src/utils/logger';\nimport { execSync } from 'node:child_process';\nimport * as os from 'node:os';\nimport { logo } from '../utils/banner';\n\n\n/**\n * Opens a URL in the default web browser based on the current operating system\n * @param url The URL to open\n */\nfunction openBrowser(url: string): void {\n const platform = os.platform();\n \n try {\n switch (platform) {\n case 'darwin': // macOS\n execSync(`open \"${url}\"`);\n break;\n case 'win32': // Windows\n execSync(`start \"\" \"${url}\"`);\n break;\n case 'linux': // Linux\n // Try different commands in order\n try {\n execSync(`xdg-open \"${url}\"`);\n } catch (error) {\n try {\n execSync(`gnome-open \"${url}\"`);\n } catch (error) {\n execSync(`kde-open \"${url}\"`);\n }\n }\n break;\n default:\n throw new Error(`Unsupported platform: ${platform}`);\n }\n logger.success(`Opened URL in your default browser: ${url}`);\n } catch (error) {\n logger.error(`Failed to open URL: ${error instanceof Error ? error.message : String(error)}`);\n logger.info(`Please manually open this URL in your browser: ${url}`);\n }\n}\n\n/**\n * Pauses execution for the specified number of milliseconds\n * @param {number} ms - Time to sleep in milliseconds\n * @returns {Promise} Promise that resolves after the specified time\n */\nfunction sleep(ms) {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport const joinCommand = new Command()\n .name('join')\n .alias('free')\n .description('Join Phala Cloud! Get an account and deploy a CVM for FREE')\n .action(async () => {\n try {\n const inviteUrl = 'https://cloud.phala.network/register?invite=beta';\n const spinner =logger.startSpinner('Brewing a fresh cup of TEE 🍵');\n await sleep(2000);\n spinner.stop(true);\n logger.break();\n logger.break();\n console.log(logo);\n logger.info('TEE is served! Opening Phala Cloud registration page...');\n await sleep(1000);\n logger.break()\n openBrowser(inviteUrl);\n } catch (error) {\n logger.error(`Error: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n }); ","import { Command } from \"commander\";\nimport { logger } from \"@/src/utils/logger\";\nimport { getApiKey } from \"@/src/utils/credentials\";\nimport { getUserInfo } from \"@/src/api/auth\";\nimport { createCvm, getPubkeyFromCvm } from \"@/src/api/cvms\";\nimport { DEFAULT_IMAGE, CLOUD_URL } from \"@/src/utils/constants\";\nimport { demoTemplates } from \"@/src/utils/demo\";\nimport {\n\tencryptEnvVars,\n\ttype EnvVar,\n} from \"@phala/dstack-sdk/encrypt-env-vars\";\nimport inquirer from \"inquirer\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport crypto from \"node:crypto\";\nimport { parseEnv } from \"@/src/utils/secrets\";\n\nexport const demoCommands = new Command()\n .name(\"demo\")\n .description(\"Demo commands to launch a demo on Phala Cloud\")\n .action(async () => {\n try {\n // 1. Check if the user is logged in\n const apiKey = await getApiKey();\n if (!apiKey) {\n logger.error(\"You need to be logged in to use the demo command\");\n logger.info(\"Please login with: phala auth login\");\n process.exit(1);\n }\n\n // Verify user credentials\n try {\n const spinner = logger.startSpinner(\"Verifying your credentials\");\n const userInfo = await getUserInfo();\n spinner.stop(true);\n logger.success(`Logged in as ${userInfo.username}`);\n } catch (error) {\n logger.error(\"Authentication failed. Your API key may be invalid or expired.\");\n logger.info(\"Please set a new API key with: phala auth login\");\n process.exit(1);\n }\n\n // 2. Get list of available templates\n const templates = Object.values(demoTemplates);\n\n if (templates.length === 0) {\n logger.error(\"No template files found in the templates directory\");\n process.exit(1);\n }\n\n // 3. Prompt user to select a template\n const { selectedTemplate } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"selectedTemplate\",\n message: \"Select a template to deploy:\",\n choices: templates.map(t => ({\n name: t.name,\n value: t\n }))\n }\n ]);\n\n // 4. Read the selected template\n const templateContent = selectedTemplate.compose;\n logger.success(`Selected template: ${selectedTemplate.name}`);\n\n // 5. Generate a random token for services that might need it\n const token = crypto.randomBytes(16).toString(\"hex\");\n const envVars = parseEnv([`TOKEN=${token}`], \"\");\n \n \n // 6. Ask for CVM name\n const { cvmName } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"cvmName\",\n message: \"Enter a name for your CVM:\",\n default: `${selectedTemplate.name.replace(\" \", \"-\")}`,\n validate: (input) => {\n if (!input.trim()) {\n return \"CVM name is required\";\n }\n return true;\n }\n }\n ]);\n\n // 7. Deploy the CVM with the specified resources\n logger.info(\"Preparing to deploy your CVM...\");\n \n // Prepare VM configuration with specified resources\n const vmConfig = {\n teepod_id: 3,\n name: cvmName,\n image: DEFAULT_IMAGE,\n vcpu: 2,\n memory: 2048,\n disk_size: 20,\n compose_manifest: {\n docker_compose_file: templateContent,\n docker_config: {\n url: \"\",\n username: \"\",\n password: \"\",\n },\n features: [\"kms\", \"tproxy-net\"],\n kms_enabled: true,\n manifest_version: 2,\n name: cvmName,\n public_logs: true,\n public_sysinfo: true,\n tproxy_enabled: true,\n },\n listed: false,\n };\n\n // Get public key from CVM for the API call structure\n const spinner = logger.startSpinner(\"Preparing CVM configuration\");\n const pubkey = await getPubkeyFromCvm(vmConfig);\n spinner.stop(true);\n \n if (!pubkey) {\n logger.error(\"Failed to prepare CVM configuration\");\n process.exit(1);\n }\n\n const encrypted_env = await encryptEnvVars(\n\t\t\t\t\t\t\tenvVars,\n\t\t\t\t\t\t\tpubkey.app_env_encrypt_pubkey,\n\t\t\t\t\t\t);\n\n logger.debug(\"Public key:\", pubkey.app_env_encrypt_pubkey);\n logger.debug(\"Encrypted environment variables:\", encrypted_env);\n // Create the CVM\n const createSpinner = logger.startSpinner(\"Creating your demo CVM\");\n const response = await createCvm({\n ...vmConfig,\n encrypted_env,\n app_env_encrypt_pubkey: pubkey.app_env_encrypt_pubkey,\n app_id_salt: pubkey.app_id_salt,\n });\n createSpinner.stop(true);\n\n if (!response) {\n logger.error(\"Failed to create demo CVM\");\n process.exit(1);\n }\n\n logger.success(\"Demo CVM created successfully! 🎉\");\n logger.break();\n \n const tableData = {\n \"CVM ID\": response.id,\n \"Name\": response.name,\n \"Status\": response.status,\n \"App ID\": `app_${response.app_id}`,\n \"App URL\": response.app_url ? response.app_url : `${CLOUD_URL}/dashboard/cvms/app_${response.app_id}`,\n \"Template\": selectedTemplate.name,\n \"Resources\": \"2 vCPUs, 2GB RAM, 20GB Storage\",\n };\n \n if (selectedTemplate.name.includes(\"Jupyter Notebook\")) {\n tableData[\"Jupyter Token\"] = token;\n tableData[\"Access Instructions\"] = \"Access your Jupyter notebook using the token above. Go to 'Network' tab to see the public URL.\";\n }\n \n logger.keyValueTable(tableData, {\n borderStyle: \"rounded\"\n });\n\n logger.break();\n logger.success(`Your demo is being created. You can check its status with:\\nphala cvms get app_${response.app_id}`);\n\n } catch (error) {\n logger.error(`Failed to launch demo: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n });\n","const jupyterCompose = `version: '3'\nservices:\n jupyter:\n image: quay.io/jupyter/base-notebook\n ports:\n - 8080:8888\n volumes:\n - /var/run/tappd.sock:/var/run/tappd.sock\n environment:\n - GRANT_SUDO=yes\n user: root\n command: \"start-notebook.sh --NotebookApp.token=\\${TOKEN}\"\n`;\n\nexport const httpbinCompose = `version: '3'\nservices:\n httpbin:\n image: kennethreitz/httpbin:latest\n ports:\n - \"80:80\"\n`;\n\n\nexport const demoTemplates = {\n jupyter: {\n compose: jupyterCompose,\n name: \"Jupyter Notebook\",\n },\n httpbin: {\n compose: httpbinCompose,\n name: \"HTTPBin\",\n },\n};\n","import { Command } from 'commander';\nimport { listNodes } from './list.js';\n\nexport const nodesCommand = new Command()\n .name('nodes')\n .description('List and manage TEE nodes')\n .action(listNodes)\n .addCommand(\n new Command('list')\n .description('List all available worker nodes')\n .alias('ls')\n .action(listNodes)\n );\n","import { getTeepods } from '@/src/api/teepods';\nimport { logger } from '@/src/utils/logger';\nimport { KmsListItem, TEEPod } from '@/src/api/types';\n\nexport async function listNodes() {\n try {\n const { nodes: teepods, kms_list: kmsList } = await getTeepods();\n\n if (teepods.length === 0) {\n logger.info('No available nodes found.');\n return;\n }\n\n logger.info('Available Nodes:');\n teepods.forEach((teepod: TEEPod) => {\n logger.info('----------------------------------------');\n logger.info(` ID: ${teepod.teepod_id}`);\n logger.info(` Name: ${teepod.name}`);\n logger.info(` Region: ${teepod.region_identifier}`);\n logger.info(` FMSPC: ${teepod.fmspc || 'N/A'}`);\n logger.info(` Device ID: ${teepod.device_id || 'N/A'}`);\n logger.info(` Support Onchain KMS: ${teepod.support_onchain_kms}`);\n \n logger.info(' Images:');\n if (teepod.images && teepod.images.length > 0) {\n teepod.images.forEach(img => {\n logger.info(` - ${img.name}`);\n logger.info(` Hash: ${img.os_image_hash || 'N/A'}`);\n });\n } else {\n logger.info(' N/A');\n }\n });\n\n if (kmsList && kmsList.length > 0) {\n logger.info('\\nAvailable KMS Instances:');\n kmsList.forEach((kms: KmsListItem) => {\n logger.info('----------------------------------------');\n logger.info(` ID: ${kms.id}`);\n logger.info(` URL: ${kms.url}`);\n logger.info(` Version: ${kms.version}`);\n logger.info(` Chain ID: ${kms.chain_id}`);\n logger.info(` Contract Address: ${kms.kms_contract_address}`);\n logger.info(` Gateway App ID: ${kms.gateway_app_id}`);\n });\n }\n } catch (error) {\n logger.error(`Failed to list available nodes: ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n}\n","import { Command } from 'commander';\nimport { deployCommand } from './deploy';\n\nexport const kmsCommand = new Command()\n .name('kms')\n .description('Manage On-Chain Key Management Service (KMS) components.')\n .addCommand(deployCommand);\n","import { Command } from 'commander';\nimport { logger } from '@/src/utils/logger';\nimport { getNetworkConfig, handleAppAuthDeployment } from '@/src/utils/blockchain';\nimport inquirer from 'inquirer';\nimport { ethers } from 'ethers';\n\nexport const deployCommand = new Command()\n .name('deploy')\n .description('Deploy or register an AppAuth contract for on-chain KMS.')\n .option('--kms-contract-address <kmsContractAddress>', 'Address of the main KmsAuth contract.')\n .option('--private-key <privateKey>', 'Private key for signing transactions.')\n .option('--network <network>', 'The network to deploy to (e.g., hardhat, phala, sepolia, test)')\n .option('--rpc-url <rpcUrl>', 'RPC URL for the blockchain.')\n .option('--app-auth-address <appAuthAddress>', 'Register a pre-deployed AppAuth contract.')\n .option('--app-auth-contract-path <appAuthContractPath>', 'Path to a custom AppAuth contract file.')\n .option('--use-default-app-auth', 'Deploy the default AppAuth contract via factory.', false)\n .option('--deployer-address <deployerAddress>', 'Address of the owner for the new AppAuth instance.')\n .option('--initial-device-id <initialDeviceId>', 'Initial device ID for the new AppAuth instance.')\n .option('--compose-hash <composeHash>', 'Initial compose hash for the new AppAuth instance.')\n .action(async (options) => {\n try {\n const providedOptionsCount = [options.appAuthAddress, options.appAuthContractPath, options.useDefaultAppAuth].filter(Boolean).length;\n if (providedOptionsCount > 1) {\n throw new Error('Cannot use --app-auth-address, --app-auth-contract-path, and --use-default-app-auth at the same time.');\n }\n\n const { wallet, ...networkConfig } = await getNetworkConfig(options);\n const finalOptions = { ...options, ...networkConfig };\n\n if (!finalOptions.kmsContractAddress) {\n const { addr } = await inquirer.prompt([{\n type: 'input',\n name: 'addr',\n message: 'Enter the address of the main KmsAuth contract:',\n validate: (input) => ethers.isAddress(input) || 'Please enter a valid Ethereum address.',\n }]);\n finalOptions.kmsContractAddress = addr;\n }\n \n await handleAppAuthDeployment(finalOptions, wallet);\n\n } catch (error) {\n logger.error(`An error occurred: ${error instanceof Error ? error.message : String(error)}`);\n if (error.stack && process.env.DEBUG) {\n logger.error(error.stack);\n }\n process.exit(1);\n }\n });\n","import { Command } from 'commander';\nimport { createCvm, createCvmOnChainKms, getPubkeyFromCvm, provisionCvm } from '@/src/api/cvms';\nimport { getTeepods } from '@/src/api/teepods';\nimport { logger } from '@/src/utils/logger';\nimport type { TEEPod, TeepodResponse } from '@/src/api/types';\nimport { DEFAULT_VCPU, DEFAULT_MEMORY, DEFAULT_DISK_SIZE, CLOUD_URL, DEFAULT_ONCHAIN_IMAGE } from '@/src/utils/constants';\nimport { encryptEnvVars } from '@phala/dstack-sdk/encrypt-env-vars';\nimport type { EnvVar } from '@phala/dstack-sdk/encrypt-env-vars';\nimport { getKmsPubkey } from '@/src/api/kms';\nimport { handleAppAuthDeployment, ensureHexPrefix, getNetworkConfig, getChainConfig } from '../../utils/blockchain';\nimport { parseMemoryInput, parseDiskSizeInput } from '@/src/utils/units';\nimport { ethers } from 'ethers';\nimport { createPublicClient, http } from 'viem';\n\nimport fs from 'fs-extra';\nimport path from 'node:path';\nimport inquirer from 'inquirer';\nimport { detectFileInCurrentDir, promptForFile } from '@/src/utils/prompts';\nimport { parseEnv } from '@/src/utils/secrets';\n\n/**\n * Gathers and validates all necessary configurations for creating a CVM.\n */\nasync function gatherCvmConfig(options: any) {\n if (!options.name) {\n if (!options.interactive) {\n const folderName = path.basename(process.cwd()).toLowerCase().replace(/[^a-z0-9_-]/g, '-');\n options.name = folderName;\n } else {\n // Use current directory name as default\n const folderName = path.basename(process.cwd()).toLowerCase().replace(/[^a-z0-9_-]/g, '-');\n\n const { name } = await inquirer.prompt([\n {\n type: 'input',\n name: 'name',\n message: 'Enter a name for the CVM:',\n default: folderName,\n validate: (input) => {\n if (!input.trim()) return 'CVM name is required';\n if (input.trim().length > 20) return 'CVM name must be less than 20 characters';\n if (input.trim().length < 3) return 'CVM name must be at least 3 characters';\n if (!/^[a-zA-Z0-9_-]+$/.test(input)) return 'CVM name must contain only letters, numbers, underscores, and hyphens';\n return true;\n }\n }\n ]);\n options.name = name;\n }\n }\n\n if (!options.compose) {\n if (!options.interactive) {\n logger.error('Docker Compose file is required. Use --compose or --interactive to select it');\n process.exit(1);\n } else {\n const possibleFiles = ['docker-compose.yml', 'docker-compose.yaml'];\n const composeFileName = detectFileInCurrentDir(possibleFiles, 'Detected docker compose file: {path}');\n options.compose = await promptForFile('Enter the path to your Docker Compose file:', composeFileName, 'file');\n }\n }\n\n const composePath = path.resolve(options.compose);\n if (!fs.existsSync(composePath)) {\n throw new Error(`Docker Compose file not found: ${composePath}`);\n }\n const composeString = fs.readFileSync(composePath, 'utf8');\n\n // Handle environment variables\n let envs: EnvVar[] = [];\n let allowedEnvs: string[] = [];\n\n if (!options.skipEnv) {\n // If envFile is not provided, try to find one automatically\n let envFilePath = options.envFile;\n\n if (!envFilePath) {\n // Check for environment files in order of priority\n const envFiles = ['.env.production', '.env.prod', '.env'];\n for (const file of envFiles) {\n if (fs.existsSync(file)) {\n envFilePath = file;\n logger.info(`Using environment file: ${envFilePath}`);\n break;\n }\n }\n\n // If no env file found, ask user if they want to provide one\n if (!envFilePath) {\n if (!options.interactive) {\n logger.error('Environment file is required. Use --env-file to select it');\n process.exit(1);\n } else {\n envFilePath = await promptForFile('Enter the path to your environment file:', '.env', 'file');\n }\n }\n }\n\n if (envFilePath) {\n try {\n // Read and parse environment variables\n envs = parseEnv([], envFilePath);\n\n // Extract just the keys for allowed_envs\n allowedEnvs = envs.map(env => env.key);\n\n if (allowedEnvs.length > 0) {\n logger.info(`Using environment variables from ${envFilePath}`);\n logger.debug(`Allowed environment variables: ${allowedEnvs.join(', ')}`);\n } else {\n logger.warn(`No environment variables found in ${envFilePath}`);\n }\n } catch (error) {\n logger.error(`Error reading environment file ${envFilePath}:`, error);\n }\n }\n }\n\n const teepodsSpinner = logger.startSpinner('Fetching available Nodes');\n const teepods = await getTeepods();\n teepodsSpinner.stop(true);\n if (teepods.nodes.length === 0) {\n throw new Error('No Nodes available.');\n }\n\n // Filter TEEpods based on on-chain KMS support\n let availableTeepods = teepods.nodes.filter(teepod =>\n options.kmsId ? teepod.support_onchain_kms : !teepod.support_onchain_kms\n );\n\n if (availableTeepods.length === 0) {\n const errorMessage = options.kmsId\n ? 'No Nodes available that support on-chain KMS.'\n : 'No Nodes available that does not support on-chain KMS.';\n throw new Error(errorMessage);\n }\n\n // If kms-id is provided, find the corresponding KMS info\n let kmsInfo;\n let kmsContractAddress;\n if (options.kmsId) {\n // Get KMS list from the teepods response (it's at the root level, not in individual teepods)\n const allKmsInfos = teepods.kms_list || [];\n kmsInfo = allKmsInfos.find(kms => kms.id === options.kmsId);\n\n if (!kmsInfo) {\n throw new Error(`No KMS found with ID: ${options.kmsId} in the available Nodes`);\n }\n\n kmsContractAddress = kmsInfo.kms_contract_address;\n logger.info(`Using KMS contract address: ${kmsContractAddress} from KMS ID: ${options.kmsId}`);\n }\n\n let selectedTeepod: TEEPod;\n if (options.nodeId) {\n selectedTeepod = availableTeepods.find(pod => pod.teepod_id === Number(options.nodeId));\n if (!selectedTeepod) {\n throw new Error(`Selected Node with ID ${options.nodeId} is not available or does not support on-chain KMS.`);\n }\n } else {\n if (!options.interactive) {\n logger.error('Node is required. Use --node-id to select it');\n process.exit(1);\n } else {\n const { node } = await inquirer.prompt([{ type: 'list', name: 'node', message: 'Select a Node to use:', choices: availableTeepods.map(t => ({ name: `${t.name} (Region: ${t.region_identifier})`, value: t })) }]);\n selectedTeepod = node;\n }\n }\n\n let selectedImage;\n if (options.image) {\n selectedImage = selectedTeepod.images?.find(image => image.name === options.image);\n if (!selectedImage) throw new Error(`Failed to find selected image '${options.image}' for the selected Node.`);\n } else {\n selectedImage = selectedTeepod.images?.[0];\n if (!selectedImage) {\n throw new Error('No images found for the selected Node.');\n }\n logger.info(`Using image: ${selectedImage.name}`);\n }\n\n // allowedEnvs is already set above from the env file parsing\n\n const composeFile: any = {\n docker_compose_file: composeString,\n allowed_envs: allowedEnvs,\n features: ['kms', 'tproxy-net'],\n kms_enabled: true,\n manifest_version: 2,\n name: options.name,\n public_logs: true,\n public_sysinfo: true,\n tproxy_enabled: true,\n };\n\n if (options.preLaunchScript) {\n composeFile.pre_launch_script = options.preLaunchScript;\n }\n\n // Parse memory and disk size with units\n let memoryMB = DEFAULT_MEMORY;\n if (options.memory) {\n try {\n memoryMB = parseMemoryInput(options.memory);\n logger.info(`Using memory: ${memoryMB}MB (parsed from: ${options.memory})`);\n } catch (error) {\n logger.warn(`Invalid memory format '${options.memory}'. Using default: ${DEFAULT_MEMORY}MB`);\n }\n }\n\n let diskSizeGB = DEFAULT_DISK_SIZE;\n if (options.diskSize) {\n try {\n diskSizeGB = parseDiskSizeInput(options.diskSize);\n logger.info(`Using disk size: ${diskSizeGB}GB (parsed from: ${options.diskSize})`);\n } catch (error) {\n logger.warn(`Invalid disk size format '${options.diskSize}'. Using default: ${DEFAULT_DISK_SIZE}GB`);\n }\n }\n\n const vmConfig = {\n teepod_id: selectedTeepod.teepod_id,\n name: options.name,\n image: selectedImage.name,\n vcpu: Number(options.vcpu) || DEFAULT_VCPU,\n memory: memoryMB,\n disk_size: diskSizeGB,\n compose_file: composeFile,\n listed: false,\n }\n\n return { vmConfig, envs, teepods, kmsContractAddress };\n}\n\n/**\n * Provisions the CVM and logs the result.\n */\nasync function provisionAndLogCvm(vmConfig: any, options: { json?: boolean } = {}) {\n const provisionSpinner = logger.startSpinner('Provisioning CVM for on-chain KMS...');\n const provisionResponse = await provisionCvm(vmConfig);\n provisionSpinner.stop(true);\n\n if (!provisionResponse) {\n throw new Error('Failed to provision CVM for on-chain KMS');\n }\n\n if (options?.json !== false) {\n console.log(JSON.stringify({\n success: true,\n data: {\n app_id: provisionResponse.app_id,\n device_id: provisionResponse.device_id,\n compose_hash: provisionResponse.compose_hash,\n os_image_hash: provisionResponse.os_image_hash,\n raw: provisionResponse\n }\n }, null, 2));\n } else {\n logger.success('CVM provisioned successfully!');\n logger.keyValueTable({\n 'App ID': provisionResponse.app_id,\n 'Device ID': provisionResponse.device_id,\n 'Compose Hash': provisionResponse.compose_hash,\n 'OS Image Hash': provisionResponse.os_image_hash,\n });\n }\n\n return provisionResponse;\n}\n\n/**\n * Creates the final CVM with encrypted environment variables.\n */\nasync function createFinalCvm(appAuthResult: any, provisionResponse: any, envs: EnvVar[], teepods: TeepodResponse, options: any) {\n logger.info('\\nStep 4: Encrypting environment variables and creating final CVM...');\n let encrypted_env = '';\n let kmsId = teepods.kms_list[0].id;\n if (options.kmsId) {\n kmsId = options.kmsId;\n logger.info(`Using custom KMS ID: ${kmsId}`);\n }\n\n // Use custom app-id if provided, otherwise use the one from appAuthResult\n const appId = options.customAppId ? options.customAppId : appAuthResult.appId;\n if (options.customAppId) {\n logger.info(`Using custom App ID: ${appId}`);\n }\n if (envs.length > 0) {\n const spinner = logger.startSpinner('Fetching public key from KMS...');\n const { public_key } = await getKmsPubkey(kmsId, appId);\n spinner.stop(true);\n if (public_key) {\n const encryptSpinner = logger.startSpinner('Encrypting environment variables...');\n encrypted_env = await encryptEnvVars(envs, public_key);\n encryptSpinner.stop(true);\n }\n }\n\n const finalVmConfig = {\n app_id: ensureHexPrefix(appId),\n compose_hash: provisionResponse.compose_hash,\n contract_address: ensureHexPrefix(appAuthResult.proxyAddress),\n deployer_address: appAuthResult.deployerAddress ? ensureHexPrefix(appAuthResult.deployerAddress) : '',\n encrypted_env: encrypted_env,\n kms_id: kmsId,\n };\n\n const createSpinner = logger.startSpinner('Creating final CVM...');\n const finalResponse = await createCvmOnChainKms(finalVmConfig);\n createSpinner.stop(true);\n\n if (!finalResponse) {\n throw new Error('Failed to create CVM');\n }\n\n if (options?.json !== false) {\n console.log(JSON.stringify({\n success: true,\n data: {\n vm_uuid: finalResponse.vm_uuid.replace(/-/g, ''),\n name: finalResponse.name,\n status: finalResponse.status,\n app_id: finalResponse.app_id,\n endpoint: `${CLOUD_URL}/dashboard/cvms/${finalResponse.vm_uuid.replace(/-/g, '')}`,\n raw: finalResponse\n }\n }, null, 2));\n } else {\n logger.success('CVM created successfully!');\n logger.break();\n logger.keyValueTable({\n 'CVM ID': finalResponse.vm_uuid.replace(/-/g, ''),\n 'Name': finalResponse.name,\n 'Status': finalResponse.status,\n 'App ID': finalResponse.app_id,\n 'Endpoint': `${CLOUD_URL}/dashboard/cvms/${finalResponse.vm_uuid.replace(/-/g, '')}`,\n });\n }\n}\n\nasync function executeStandardCreation(\n vmConfig: any,\n envs: EnvVar[],\n options: { json?: boolean; debug?: boolean } = {}\n) {\n const spinner = logger.startSpinner('Getting public key from CVM');\n const pubkey = await getPubkeyFromCvm(vmConfig);\n spinner.stop(true);\n if (!pubkey) throw new Error('Failed to get public key from CVM');\n\n const encryptSpinner = logger.startSpinner('Encrypting environment variables');\n const encrypted_env = await encryptEnvVars(envs, pubkey.app_env_encrypt_pubkey);\n encryptSpinner.stop(true);\n\n const createSpinner = logger.startSpinner('Provisioning CVM');\n const response = await createCvm({ ...vmConfig, encrypted_env, app_env_encrypt_pubkey: pubkey.app_env_encrypt_pubkey, app_id_salt: pubkey.app_id_salt });\n createSpinner.stop(true);\n if (!response) throw new Error('Failed to create CVM');\n\n if (options?.json !== false) {\n const jsonOutput: any = {\n success: true,\n data: {\n cvm_id: response.vm_uuid.replace(/-/g, ''),\n app_id: response.app_id,\n name: response.name,\n status: response.status,\n endpoint: `${CLOUD_URL}/dashboard/cvms/${response.vm_uuid.replace(/-/g, '')}`,\n created_at: response.created_at,\n raw: response\n }\n };\n if (response.kms_contract_address) jsonOutput.data.kms_contract_address = response.kms_contract_address;\n if (response.kms_owner_address) jsonOutput.data.kms_owner_address = response.kms_owner_address;\n console.log(JSON.stringify(jsonOutput, null, 2));\n } else {\n logger.success('CVM created successfully');\n logger.break();\n const tableData: { [key: string]: any } = {\n 'CVM ID': response.vm_uuid.replace(/-/g, ''),\n 'App ID': response.app_id,\n 'Name': response.name,\n 'Status': response.status,\n 'Endpoint': `${CLOUD_URL}/dashboard/cvms/${response.vm_uuid.replace(/-/g, '')}`,\n 'Created At': new Date(response.created_at).toLocaleString(),\n };\n if (response.kms_contract_address) tableData['KMS Contract Address'] = response.kms_contract_address;\n if (response.kms_owner_address) tableData['KMS Owner Address'] = response.kms_owner_address;\n logger.keyValueTable(tableData);\n }\n}\n\nexport const deployCommand = new Command()\n .command('deploy')\n .description('Create a new CVM with on-chain KMS in one step.')\n .option('--json', 'Output in JSON format (default: true)', true)\n .option('--no-json', 'Disable JSON output format')\n .option('--debug', 'Enable debug logging', false)\n // CVM options\n .option('-n, --name <name>', 'Name of the CVM')\n .option('-c, --compose <compose>', 'Path to Docker Compose file')\n .option('--vcpu <vcpu>', `Number of vCPUs, default is ${DEFAULT_VCPU}`)\n .option('--memory <memory>', `Memory with optional unit (e.g., 2G, 500MB, 1024), default is ${DEFAULT_MEMORY}MB`)\n .option('--disk-size <diskSize>', `Disk size with optional unit (e.g., 50G, 1T, 100), default is ${DEFAULT_DISK_SIZE}GB`)\n .option('--image <image>', 'Version of dstack image to use')\n .option('--node-id <nodeId>', 'Node ID to use')\n .option('-e, --env-file <envFile>', 'Path to environment file')\n .option('--skip-env', 'Skip environment variable prompt', false)\n .option('-i, --interactive', 'Enable interactive mode for required parameters', false)\n .option('--kms-id <kmsId>', 'KMS ID to use.')\n .option('--custom-app-id <customAppId>', 'Custom App ID to use.')\n .option('--pre-launch-script <preLaunchScript>', 'Path to pre-launch script')\n // Blockchain options\n .option('--private-key <privateKey>', 'Private key for signing transactions.')\n .option('--rpc-url <rpcUrl>', 'RPC URL for the blockchain.')\n .action(async (options: {\n name?: string;\n compose?: string;\n vcpu?: string;\n memory?: string;\n diskSize?: string;\n image?: string;\n nodeId?: string;\n envFile?: string;\n skipEnv?: boolean;\n interactive?: boolean;\n kmsId?: string;\n customAppId?: string;\n preLaunchScript?: string;\n privateKey?: string;\n rpcUrl?: string;\n json?: boolean;\n debug?: boolean;\n }) => {\n try {\n // Step 1: Gather CVM configuration\n logger.info('Step 1: Preparing CVM configuration...');\n const { vmConfig, envs, teepods, kmsContractAddress } = await gatherCvmConfig(options);\n\n // If no KMS ID is provided, use standard creation\n if (!options.kmsId) {\n await executeStandardCreation(vmConfig, envs, {\n json: options.json,\n debug: options.debug\n });\n return;\n }\n // Step 2: Provision the CVM\n logger.info('\\nStep 2: Provisioning CVM...');\n const provisionResponse = await provisionAndLogCvm(vmConfig);\n\n // Step 3: Configure network and handle AppAuth\n logger.info('\\nStep 3: Configuring network and setting up AppAuth...');\n\n let wallet = null;\n\n // Only create wallet if we need to deploy or register a contract\n if (!options.customAppId) {\n const privateKey = options.privateKey || process.env.PRIVATE_KEY;\n if (!privateKey) {\n throw new Error('Private key is required for on-chain KMS operations if no custom app ID is provided. Please provide it via --private-key or PRIVATE_KEY environment variable');\n }\n const networkConfig = await getNetworkConfig({ privateKey, rpcUrl: options.rpcUrl }, teepods.kms_list[0].chain_id);\n wallet = networkConfig.wallet;\n if (options.json === false) {\n logger.info(`Using wallet: ${wallet.address}`);\n }\n }\n\n const deployOptions = {\n ...options,\n initialDeviceId: provisionResponse.device_id,\n composeHash: provisionResponse.compose_hash\n };\n console.log('deployOptions', deployOptions);\n\n let appAuthResult;\n\n // Handle custom app ID case - fetch AppAuth contract details from KMS\n if (options.customAppId) {\n if (options.json === false) {\n logger.info(`Using custom App ID: ${options.customAppId}, fetching AppAuth details from KMS...`);\n }\n\n // Get the first available KMS to determine the chain\n const kms = teepods.kms_list?.[0];\n if (!kms) {\n throw new Error('No KMS available');\n }\n\n // Get network config which will handle chain validation and RPC URL resolution\n const { rpcUrl } = await getNetworkConfig({ rpcUrl: options.rpcUrl }, kms.chain_id);\n \n // Get the chain config\n const chain = getChainConfig(kms.chain_id);\n \n // Initialize public client with the appropriate chain and RPC URL\n const publicClient = createPublicClient({\n chain,\n transport: http(rpcUrl)\n });\n\n // KMS Auth ABI for reading app registration details\n const kmsAuthAbi = [\n {\n inputs: [{ name: 'app', type: 'address' }],\n name: 'apps',\n outputs: [\n { name: 'isRegistered', type: 'bool' },\n { name: 'controller', type: 'address' },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n ] as const;\n\n try {\n // Ensure the KMS contract address is valid\n if (!ethers.isAddress(kmsContractAddress)) {\n throw new Error(`Invalid KMS contract address: ${kmsContractAddress}`);\n }\n\n if (!ethers.isAddress(options.customAppId)) {\n throw new Error(`Invalid custom App ID: ${options.customAppId}`);\n }\n\n // Ensure customAppId has 0x prefix\n const customAppId = options.customAppId.startsWith('0x')\n ? options.customAppId\n : `0x${options.customAppId}`;\n\n // Query the KMS contract for app registration details\n const [isRegistered, controllerAddress] = await publicClient.readContract({\n address: kmsContractAddress as `0x${string}`,\n abi: kmsAuthAbi,\n functionName: 'apps',\n args: [customAppId as `0x${string}`]\n });\n\n // Validate the response\n if (!isRegistered) {\n throw new Error(`App ${options.customAppId} is not registered in KMS contract ${kmsContractAddress}`);\n }\n\n if (!controllerAddress || controllerAddress === ethers.ZeroAddress) {\n throw new Error(`Invalid controller address for app ${options.customAppId}`);\n }\n\n if (options.json === false) {\n logger.info(`Successfully verified AppAuth contract at ${controllerAddress}`);\n }\n\n appAuthResult = {\n appId: options.customAppId,\n proxyAddress: controllerAddress,\n deployerAddress: ''\n };\n\n } catch (error) {\n throw new Error(`Failed to verify custom App ID: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n } else {\n if (!wallet) {\n throw new Error('Wallet is required when not using a custom App ID');\n }\n appAuthResult = await handleAppAuthDeployment(deployOptions, wallet, kmsContractAddress);\n }\n\n // Step 4: Create the final CVM\n await createFinalCvm(appAuthResult, provisionResponse, envs, teepods, options);\n\n } catch (error) {\n const errorMessage = `Failed to create CVM: ${error instanceof Error ? error.message : String(error)}`;\n if (options.json !== false) {\n console.error(JSON.stringify({\n success: false,\n error: errorMessage,\n stack: options.debug && error instanceof Error ? error.stack : undefined\n }, null, 2));\n } else {\n logger.error(errorMessage);\n }\n process.exit(1);\n }\n });\n"],"mappings":";m5CACA,OAAS,WAAAA,OAAe,YCDxB,OAAOC,OAAW,QAClB,IAAMC,GAAYD,GAAM,IAAI,SAAS,EACxBE,GAAOD,GAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAsB7B,EAEYE,GAAYF,GAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAsBlC,EAEYG,GAAcJ,GAAM,KAAK,qBAAqB,EClD3D,OAAS,WAAAK,OAAe,YCAxB,OAAS,WAAAC,OAAe,YAGxB,OAAOC,OAAa,UAIb,IAAMC,GAAe,IAAIC,GAAQ,EACrC,KAAK,OAAO,EACZ,YAAY,oCAAoC,EAChD,SAAS,YAAa,4BAA4B,EAClD,OAAO,MAAOC,GAAoB,CACjC,GAAI,CACF,IAAIC,EAEJ,GAAI,CAACD,EAuBHA,GAtBiB,MAAME,GAAQ,CAC7B,KAAM,WACN,KAAM,SACN,QAAS,sBACT,SAAU,MAAOC,GAAU,CACzB,GAAIA,EAAM,SAAW,EACnB,MAAO,0BAET,GAAI,CAGF,GAFA,MAAMC,GAAWD,CAAK,EACtBF,EAAgB,MAA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AAY,EACvB,WAAWC,EAAW,EACtB,WAAWC,EAAU,EACrB,WAAWC,EAAY,EACvB,WAAWC,EAAa,EAE3BX,EAAQ,KAAK,YAAcY,GAAgB,CAC1C,IAAMC,EAAOD,EAAY,KAAK,EAC1BC,EAAK,QACRC,GAAUD,EAAK,MAAM,CAEvB,CAAC,EAEDb,EAAQ,MAAM,QAAQ,IAAI,CAC3B,CAEAD,GAAK,EAAE,MAAOgB,GAAU,CACvBC,EAAO,MAAM,qBAAsBD,CAAK,EACxC,QAAQ,KAAK,CAAC,CACf,CAAC","names":["Command","chalk","logoColor","logo","smallLogo","minimalLogo","Command","Command","prompts","loginCommand","Command","apiKey","checkUserInfo","prompts","value","saveApiKey","getUserInfo","removeApiKey","logger","CLOUD_URL","error","Command","logoutCommand","Command","removeApiKey","logger","error","Command","statusCommand","Command","options","apiKey","getApiKey","logger","spinner","userInfo","getUserInfo","tableData","error","authCommands","Command","loginCommand","logoutCommand","statusCommand","Command","Command","execa","fs","path","Handlebars","exec","spawn","promisify","os","inquirer","fs","path","validateFileExists","filePath","basePath","resolvedPath","path","fs","promptForFile","message","defaultValue","name","inquirer","input","detectFileInCurrentDir","possibleFiles","logMessage","file","logger","fs","path","os","execSync","spawn","net","SIMULATOR_CONFIG","isSimulatorInstalled","platform","extractedFolderPath","executablePath","error","logger","getPlatform","installSimulator","progressCallback","log","message","platformConfig","downloadUrl","execSync","runSimulator","options","executableName","runOptions","logDir","stdio","outputStream","simulatorProcess","spawn","timestamp","setSimulatorEndpointEnv","isSimulatorRunning","platform","getPlatform","platformConfig","SIMULATOR_CONFIG","socketPath","resolve","client","host","error","logger","stopSimulator","execSync","stopped","deleteSimulatorEndpointEnv","getSimulatorEndpoint","getPlatform","setSimulatorEndpointEnv","endpoint","simulatorEndpoint","envEndpoint","execSync","logger","error","deleteSimulatorEndpointEnv","execAsync","promisify","exec","LOGS_DIR","COMPOSE_FILES_DIR","MAX_CONSOLE_LINES","DockerService","image","username","registry","logsPath","path","fs","operation","timestamp","arch","os","command","args","resolve","reject","proc","spawn","logFile","logStream","consoleBuffer","processOutput","data","isError","lines","line","bufferedLine","code","err","dockerfile","tag","fullImageName","spinner","logger","validateFileExists","buildArgs","error","imageName","getDockerCredentials","password","execa","loginError","homeDir","dockerConfigPath","dockerConfig","envFile","templateType","template","DOCKER_COMPOSE_ELIZA_V2_TEMPLATE","DOCKER_COMPOSE_BASIC_TEMPLATE","validatedTemplate","ComposeTemplateSchema","composePath","envVars","commentIndex","key","value","trimmedKey","composeContent","Handlebars","env","composeFile","composeArgs","port","stdout","containerId","setSimulatorEndpointEnv","deleteSimulatorEndpointEnv","prompts","loginCommand","Command","options","username","password","registry","logger","response","value","dockerService","DockerService","saveDockerCredentials","error","Command","path","inquirer","fs","buildCommand","Command","options","credentials","getDockerCredentials","logger","response","inquirer","input","defaultPath","path","fs","promptForFile","dockerfilePath","DockerService","error","Command","inquirer","pushCommand","Command","options","credentials","getDockerCredentials","logger","imageName","localImages","DockerService","uniqueImageNames","img","selectedImage","error","Command","inquirer","fs","path","generateCommand","Command","options","credentials","getDockerCredentials","logger","imageName","localImages","DockerService","uniqueImageNames","img","selectedImage","inquirer","envFilePath","validateFileExists","defaultEnvPath","path","fs","useDefault","envPath","input","outputPath","confirmOverwrite","customPath","dockerService","composePath","outputDir","error","dockerCommands","Command","loginCommand","buildCommand","pushCommand","generateCommand","Command","Command","startCommand","Command","TEE_SIMULATOR","options","DockerService","logger","isSimulatorInstalled","installSimulator","isSimulatorRunning","simulatorProcess","runSimulator","error","Command","stopCommand","Command","options","DockerService","logger","stopSimulator","error","simulatorCommands","Command","startCommand","stopCommand","Command","Command","chalk","listCommand","Command","options","spinner","logger","cvms","getCvms","cvm","CLOUD_URL","error","Command","chalk","resolveCvmAppId","appId","selectedCvm","selectCvm","checkCvmExists","getCommand","Command","appId","options","resolvedAppId","resolveCvmAppId","spinner","logger","cvm","getCvmByAppId","chalk","CLOUD_URL","error","Command","startCommand","Command","appId","resolvedAppId","resolveCvmAppId","spinner","logger","response","startCvm","tableData","CLOUD_URL","error","Command","stopCommand","Command","appId","resolvedAppId","resolveCvmAppId","spinner","logger","response","stopCvm","tableData","CLOUD_URL","error","Command","restartCommand","Command","appId","resolvedAppId","resolveCvmAppId","spinner","logger","response","restartCvm","tableData","CLOUD_URL","error","Command","chalk","attestationCommand","Command","appId","options","resolvedAppId","checkCvmExists","logger","selectedCvm","selectCvm","spinner","attestationData","getCvmAttestation","summaryData","cert","index","certData","tcbBasicInfo","maxEntriesToShow","entries","entry","error","Command","encryptEnvVars","fs","path","inquirer","fs","parseEnv","envs","envFile","envVars","env","key","valueParts","value","envFileContent","line","delimiterIndex","inQuotes","quoteChar","i","valueInQuotes","valueQuoteChar","commentStartIndex","firstChar","lastChar","createCommand","Command","DEFAULT_VCPU","DEFAULT_MEMORY","DEFAULT_DISK_SIZE","options","name","inquirer","input","composeFileName","detectFileInCurrentDir","promptForFile","composePath","path","fs","logger","composeString","deleteSimulatorEndpointEnv","envs","parseEnv","error","shouldSkip","envVars","vcpu","memory","diskSize","teepodsSpinner","teepods","getTeepods","selectedTeepod","pod","selectedImage","image","DEFAULT_IMAGE","vmConfig","spinner","pubkey","getPubkeyFromCvm","encryptSpinner","encrypted_env","encryptEnvVars","createSpinner","response","createCvm","tableData","CLOUD_URL","Command","inquirer","deleteCommand","Command","appId","options","resolvedAppId","resolveCvmAppId","confirm","inquirer","logger","spinner","success","deleteCvm","error","Command","fs","encryptEnvVars","inquirer","ethers","getAction","client","actionFn","name","action_implicit","action_explicit","params","FilterTypeNotSupportedError","BaseError","type","docsPath","encodeEventTopics","parameters","abi","eventName","args","abiItem","item","getAbiItem","AbiEventNotFoundError","definition","formatAbiItem","signature","toEventSelector","topics","indexedInputs","param","args_","x","i","_","j","encodeArg","value","keccak256","toBytes","FilterTypeNotSupportedError","encodeAbiParameters","createFilterRequestScope","client","method","requestMap","method_","id","status","transport","createContractEventFilter","client","parameters","address","abi","args","eventName","fromBlock","strict","toBlock","getRequest","createFilterRequestScope","topics","encodeEventTopics","id","numberToHex","EXECUTION_REVERTED_ERROR_CODE","getContractError","err","abi","address","args","docsPath","functionName","sender","error","RawContractError","BaseError","code","data","details","message","shortMessage","cause","AbiDecodingZeroDataError","ContractFunctionZeroDataError","InternalRpcError","ContractFunctionRevertedError","RpcRequestError","ContractFunctionExecutionError","publicKeyToAddress","publicKey","address","keccak256","checksumAddress","recoverPublicKey","hash","signature","hashHex","isHex","toHex","secp256k1","r","s","v","yParity","yParityOrV","recoveryBit","toRecoveryBit","hexToBigInt","signatureHex","hexToNumber","recoverAddress","hash","signature","publicKeyToAddress","recoverPublicKey","toRlp","bytes","to","encodable","getEncodable","cursor","createCursor","bytesToHex","getEncodable","bytes","getEncodableList","x","getEncodableBytes","list","bodyLength","acc","sizeOfBodyLength","getSizeOfLength","cursor","encode","bytesOrHex","hexToBytes","sizeOfBytesLength","length","BaseError","hashAuthorization","parameters","chainId","contractAddress","nonce","to","hash","keccak256","concatHex","toRlp","numberToHex","hexToBytes","recoverAuthorizationAddress","parameters","authorization","signature","recoverAddress","hashAuthorization","EstimateGasExecutionError","BaseError","cause","account","docsPath","chain","data","gas","gasPrice","maxFeePerGas","maxPriorityFeePerGas","nonce","to","value","prettyArgs","prettyPrint","formatEther","formatGwei","getEstimateGasError","err","docsPath","args","cause","getNodeError","UnknownNodeError","EstimateGasExecutionError","BaseFeeScalarError","BaseError","Eip1559FeesNotSupportedError","MaxFeePerGasTooLowError","maxPriorityFeePerGas","formatGwei","BlockNotFoundError","BaseError","blockHash","blockNumber","identifier","transactionType","formatTransaction","transaction","transaction_","hexToNumber","formatAuthorizationList","defineTransaction","defineFormatter","authorizationList","authorization","formatBlock","block","transactions","transaction","formatTransaction","defineBlock","defineFormatter","getBlock","client","blockHash","blockNumber","blockTag_","includeTransactions_","blockTag","includeTransactions","blockNumberHex","numberToHex","block","BlockNotFoundError","formatBlock","getGasPrice","client","gasPrice","estimateMaxPriorityFeePerGas","client","args","internal_estimateMaxPriorityFeePerGas","block_","chain","request","maxPriorityFeePerGas","block","getAction","getBlock","maxPriorityFeePerGas_","maxPriorityFeePerGasHex","hexToBigInt","gasPrice","getGasPrice","Eip1559FeesNotSupportedError","estimateFeesPerGas","client","args","internal_estimateFeesPerGas","block_","chain","request","type","baseFeeMultiplier","BaseFeeScalarError","denominator","multiply","base","block","getAction","getBlock","fees","Eip1559FeesNotSupportedError","maxPriorityFeePerGas","internal_estimateMaxPriorityFeePerGas","baseFeePerGas","getGasPrice","getTransactionCount","client","address","blockTag","blockNumber","count","numberToHex","hexToNumber","blobsToCommitments","parameters","kzg","to","blobs","x","hexToBytes","commitments","blob","bytesToHex","blobsToProofs","parameters","kzg","to","blobs","x","hexToBytes","commitments","proofs","blob","commitment","bytesToHex","setBigUint64","view","byteOffset","value","isLE","_32n","_u32_max","wh","wl","h","l","Chi","a","b","c","Maj","HashMD","Hash","blockLen","outputLen","padOffset","createView","data","aexists","buffer","toBytes","len","pos","take","dataView","out","aoutput","i","oview","outLen","state","res","to","length","finished","destroyed","SHA256_K","SHA256_IV","SHA256_W","SHA256","HashMD","A","B","C","D","E","F","G","H","view","offset","i","W15","W2","s0","rotr","s1","sigma1","T1","Chi","T2","Maj","sha256","wrapConstructor","SHA256","sha256","value","to_","to","bytes","isHex","toBytes","toHex","commitmentToVersionedHash","parameters","commitment","version","to","versionedHash","sha256","bytesToHex","commitmentsToVersionedHashes","parameters","commitments","version","to","hashes","commitment","commitmentToVersionedHash","BlobSizeTooLargeError","BaseError","maxSize","size","EmptyBlobError","InvalidVersionedHashSizeError","hash","InvalidVersionedHashVersionError","version","toBlobs","parameters","to","data","hexToBytes","size_","size","EmptyBlobError","BlobSizeTooLargeError","blobs","active","position","blob","createCursor","bytes","x","bytesToHex","toBlobSidecars","parameters","data","kzg","to","blobs","toBlobs","commitments","blobsToCommitments","proofs","blobsToProofs","sidecars","i","getTransactionType","transaction","InvalidSerializableTransactionError","getChainId","client","chainIdHex","hexToNumber","defaultParameters","eip1559NetworkCache","prepareTransactionRequest","client","args","account_","blobs","chain","gas","kzg","nonce","nonceManager","parameters","type","account","parseAccount","request","block","getBlock","getAction","chainId","getChainId","getTransactionCount","commitments","blobsToCommitments","versionedHashes","commitmentsToVersionedHashes","proofs","blobsToProofs","sidecars","toBlobSidecars","getTransactionType","isEip1559Network","maxFeePerGas","maxPriorityFeePerGas","internal_estimateFeesPerGas","MaxFeePerGasTooLowError","Eip1559FeesNotSupportedError","gasPrice_","estimateGas","assertRequest","getBalance","client","address","blockNumber","blockTag","blockNumberHex","numberToHex","balance","estimateGas","client","args","account_","account","parseAccount","estimateGas_rpc","parameters","block","request","rpcStateOverride","accessList","authorizationList","blobs","blobVersionedHashes","blockNumber","blockTag","data","gas","gasPrice","maxFeePerBlobGas","maxFeePerGas","maxPriorityFeePerGas","nonce","value","stateOverride","rest","prepareTransactionRequest","numberToHex","serializeStateOverride","to","recoverAuthorizationAddress","BaseError","assertRequest","chainFormat","formatTransactionRequest","extract","estimate","getBalance","estimates","authorization","contractAddress","acc","curr","err","getEstimateGasError","estimateContractGas","client","parameters","abi","address","args","functionName","dataSuffix","request","data","encodeFunctionData","getAction","estimateGas","error","account","parseAccount","getContractError","docsPath","decodeEventLog","parameters","abi","data","strict_","topics","strict","signature","argTopics","AbiEventSignatureEmptyTopicsError","abiItem","x","toEventSelector","formatAbiItem","AbiEventSignatureNotFoundError","name","inputs","isUnnamed","args","indexedInputs","i","param","topic","DecodeLogTopicsMismatch","decodeTopic","nonIndexedInputs","decodedData","decodeAbiParameters","err","AbiDecodingDataSizeTooSmallError","PositionOutOfBoundsError","DecodeLogDataMismatch","size","value","parseEventLogs","parameters","abi","args","logs","strict","eventName","log","abiItem","toEventSelector","event","decodeEventLog","includesArgs","err","isUnnamed","AbiEventSignatureNotFoundError","DecodeLogDataMismatch","DecodeLogTopicsMismatch","x","inputs","matchArgs","isEqual","input","value","arg","isAddressEqual","keccak256","toBytes","index","key","formatLog","log","args","eventName","getLogs","client","address","blockHash","fromBlock","toBlock","event","events_","args","strict_","strict","events","topics","encodeEventTopics","logs","numberToHex","formattedLogs","log","formatLog","parseEventLogs","getContractEvents","client","parameters","abi","address","args","blockHash","eventName","fromBlock","toBlock","strict","event","getAbiItem","events","x","getAction","getLogs","readContract","client","parameters","abi","address","args","functionName","rest","calldata","encodeFunctionData","data","getAction","call","decodeFunctionResult","error","getContractError","simulateContract","client","parameters","abi","address","args","dataSuffix","functionName","callRequest","account","parseAccount","calldata","encodeFunctionData","data","getAction","call","result","decodeFunctionResult","minimizedAbi","abiItem","error","getContractError","listenersCache","cleanupCache","callbackCount","observe","observerId","callbacks","fn","callbackId","getListeners","unsubscribe","listeners","cb","unwatch","cleanup","emit","key","args","listener","wait","time","res","poll","fn","emitOnBegin","initialWaitTime","interval","active","unwatch","data","initialWait","wait","promiseCache","responseCache","getCache","cacheKey","buildCache","cache","data","promise","response","withCache","fn","cacheTime","cacheKey","id","getBlockNumber","client","cacheTime","blockNumberHex","withCache","cacheKey","getFilterChanges","_client","filter","strict","logs","formattedLogs","log","formatLog","parseEventLogs","uninstallFilter","_client","filter","watchContractEvent","client","parameters","abi","address","args","batch","eventName","fromBlock","onError","onLogs","poll_","pollingInterval","strict_","strict","observerId","stringify","observe","emit","previousBlockNumber","filter","initialized","unwatch","poll","getAction","createContractEventFilter","logs","getFilterChanges","blockNumber","getBlockNumber","getContractEvents","log","err","InvalidInputRpcError","uninstallFilter","active","unsubscribe","transport","topics","encodeEventTopics","unsubscribe_","data","decodeEventLog","formatted","formatLog","isUnnamed","DecodeLogDataMismatch","DecodeLogTopicsMismatch","x","error","sendRawTransaction","client","serializedTransaction","Eip712DomainNotFoundError","BaseError","address","getEip712Domain","client","parameters","address","factory","factoryData","fields","name","version","chainId","verifyingContract","salt","extensions","getAction","readContract","abi","e","error","Eip712DomainNotFoundError","index","buffer","uid","length","i","createClient","parameters","batch","cacheTime","ccipRead","key","name","pollingInterval","type","chain","account","parseAccount","config","request","value","transport","client","uid","extend","base","extendFn","extended","combined","promiseCache","LruMap","withDedupe","fn","enabled","id","promise","withRetry","fn","delay_","retryCount","shouldRetry","resolve","reject","attemptRetry","count","retry","error","delay","wait","data","err","buildRequest","request","options","args","overrideOptions","dedupe","methods","retryDelay","retryCount","uid","method","MethodNotSupportedRpcError","requestId","stringToHex","stringify","withDedupe","withRetry","err_","err","ParseRpcError","InvalidRequestRpcError","MethodNotFoundRpcError","InvalidParamsRpcError","InternalRpcError","InvalidInputRpcError","ResourceNotFoundRpcError","ResourceUnavailableRpcError","TransactionRejectedRpcError","LimitExceededRpcError","JsonRpcVersionUnsupportedError","UserRejectedRequestError","UnauthorizedProviderError","UnsupportedProviderMethodError","ProviderDisconnectedError","ChainDisconnectedError","SwitchChainError","BaseError","UnknownRpcError","count","error","HttpRequestError","retryAfter","shouldRetry","createTransport","key","methods","name","request","retryCount","retryDelay","timeout","type","value","uid","buildRequest","UrlRequiredError","BaseError","withTimeout","fn","errorInstance","timeout","signal","resolve","reject","timeoutId","controller","err","createIdStore","idCache","getHttpRpcClient","url","options","params","body","onRequest","onResponse","timeout","fetchOptions","headers","method","signal_","response","withTimeout","signal","init","stringify","idCache","request","args","TimeoutError","data","err","HttpRequestError","http","url","config","batch","fetchOptions","key","methods","name","onFetchRequest","onFetchResponse","retryDelay","raw","chain","retryCount_","timeout_","batchSize","wait","retryCount","timeout","url_","UrlRequiredError","rpcClient","getHttpRpcClient","createTransport","method","params","body","schedule","createBatchScheduler","requests","a","b","fn","error","result","RpcRequestError","isNullUniversalResolverError","err","callType","BaseError","cause","e","ContractFunctionRevertedError","panicReasons","encodedLabelToLabelhash","label","hash","isHex","namehash","name","result","bytesToHex","labels","i","hashFromEncodedLabel","encodedLabelToLabelhash","hashed","toBytes","keccak256","stringToBytes","concat","encodeLabelhash","hash","labelhash","label","result","encodedLabelToLabelhash","keccak256","stringToBytes","bytesToHex","packetToBytes","packet","value","bytes","stringToBytes","offset","list","i","encoded","encodeLabelhash","labelhash","getEnsAddress","client","blockNumber","blockTag","coinType","name","gatewayUrls","strict","universalResolverAddress_","universalResolverAddress","getChainContractAddress","functionData","encodeFunctionData","addressResolverAbi","namehash","readContractParameters","universalResolverResolveAbi","toHex","packetToBytes","readContractAction","getAction","readContract","res","address","decodeFunctionResult","trim","err","isNullUniversalResolverError","EnsAvatarInvalidMetadataError","BaseError","data","EnsAvatarInvalidNftUriError","reason","EnsAvatarUriResolutionError","uri","EnsAvatarUnsupportedNamespaceError","namespace","networkRegex","ipfsHashRegex","base64Regex","dataURIRegex","isImageUri","uri","res","error","resolve","img","getGateway","custom","defaultGateway","resolveAvatarUri","gatewayUrls","isEncoded","ipfsGateway","arweaveGateway","networkRegexMatch","protocol","subpath","target","subtarget","isIPNS","isIPFS","replacedUri","parsedUri","EnsAvatarUriResolutionError","getJsonImage","data","EnsAvatarInvalidMetadataError","getMetadataAvatarUri","parseAvatarUri","resolvedURI","isOnChain","parseNftUri","uri_","reference","asset_namespace","tokenID","eip_namespace","chainID","erc_namespace","contractAddress","EnsAvatarInvalidNftUriError","getNftTokenUri","client","nft","readContract","EnsAvatarUnsupportedNamespaceError","parseAvatarRecord","client","gatewayUrls","record","parseNftAvatarUri","parseAvatarUri","nft","parseNftUri","nftUri","getNftTokenUri","resolvedNftUri","isOnChain","isEncoded","resolveAvatarUri","encodedJson","decoded","getJsonImage","uriTokenId","getMetadataAvatarUri","getEnsText","client","blockNumber","blockTag","name","key","gatewayUrls","strict","universalResolverAddress_","universalResolverAddress","getChainContractAddress","readContractParameters","universalResolverResolveAbi","toHex","packetToBytes","encodeFunctionData","textResolverAbi","namehash","readContractAction","getAction","readContract","res","record","decodeFunctionResult","err","isNullUniversalResolverError","getEnsAvatar","client","blockNumber","blockTag","assetGatewayUrls","name","gatewayUrls","strict","universalResolverAddress","record","getAction","getEnsText","parseAvatarRecord","getEnsName","client","address","blockNumber","blockTag","gatewayUrls","strict","universalResolverAddress_","universalResolverAddress","getChainContractAddress","reverseNode","readContractParameters","universalResolverReverseAbi","toHex","packetToBytes","readContractAction","getAction","readContract","name","resolvedAddress","err","isNullUniversalResolverError","getEnsResolver","client","blockNumber","blockTag","name","universalResolverAddress_","universalResolverAddress","getChainContractAddress","resolverAddress","getAction","readContract","toHex","packetToBytes","createAccessList","client","args","account_","blockNumber","blockTag","blobs","data","gas","gasPrice","maxFeePerBlobGas","maxFeePerGas","maxPriorityFeePerGas","to","value","rest","account","parseAccount","assertRequest","block","numberToHex","chainFormat","request","formatTransactionRequest","extract","response","err","getCallError","createBlockFilter","client","getRequest","createFilterRequestScope","id","createEventFilter","client","address","args","event","events_","fromBlock","strict","toBlock","events","getRequest","createFilterRequestScope","topics","encodeEventTopics","id","numberToHex","createPendingTransactionFilter","client","getRequest","createFilterRequestScope","id","getBlobBaseFee","client","baseFee","getBlockTransactionCount","client","blockHash","blockNumber","blockTag","blockNumberHex","numberToHex","count","hexToNumber","getCode","client","address","blockNumber","blockTag","blockNumberHex","numberToHex","hex","formatFeeHistory","feeHistory","value","reward","getFeeHistory","client","blockCount","blockNumber","blockTag","rewardPercentiles","blockNumberHex","numberToHex","feeHistory","formatFeeHistory","getFilterLogs","_client","filter","strict","formattedLogs","log","formatLog","parseEventLogs","defineChain","chain","InvalidDomainError","BaseError","domain","stringify","InvalidPrimaryTypeError","primaryType","types","InvalidStructTypeError","type","hashTypedData","parameters","domain","message","primaryType","types","getTypesForEIP712Domain","validateTypedData","parts","hashDomain","hashStruct","keccak256","concat","data","encoded","encodeData","encodedTypes","encodedValues","hashType","field","type","value","encodeField","encodeAbiParameters","encodedHashType","toHex","encodeType","result","unsortedDeps","findTypeDependencies","deps","name","t","primaryType_","results","parsedType","typeValuePairs","item","v","validateTypedData","parameters","domain","message","primaryType","types","validateData","struct","data","param","name","type","value","integerMatch","integerRegex","_type","base","size_","numberToHex","isAddress","InvalidAddressError","bytesMatch","bytesRegex","size","BytesSizeMismatchError","validateReference","InvalidDomainError","InvalidPrimaryTypeError","getTypesForEIP712Domain","validateReference","type","InvalidStructTypeError","receiptStatuses","formatTransactionReceipt","transactionReceipt","receipt","log","formatLog","hexToNumber","transactionType","defineTransactionReceipt","defineFormatter","presignMessagePrefix","toPrefixedMessage","message_","message","stringToHex","bytesToHex","prefix","presignMessagePrefix","size","concat","hashMessage","message","to_","keccak256","toPrefixedMessage","erc6492MagicBytes","isErc6492Signature","signature","sliceHex","erc6492MagicBytes","serializeErc6492Signature","parameters","address","data","signature","to","signature_","concatHex","encodeAbiParameters","erc6492MagicBytes","hexToBytes","assertTransactionEIP7702","transaction","authorizationList","authorization","contractAddress","chainId","isAddress","InvalidAddressError","InvalidChainIdError","assertTransactionEIP1559","assertTransactionEIP4844","blobVersionedHashes","EmptyBlobError","hash","size_","size","version","hexToNumber","slice","InvalidVersionedHashSizeError","InvalidVersionedHashVersionError","maxPriorityFeePerGas","maxFeePerGas","to","maxUint256","FeeCapTooHighError","TipAboveFeeCapError","assertTransactionEIP2930","gasPrice","BaseError","assertTransactionLegacy","serializeAuthorizationList","authorizationList","serializedAuthorizationList","authorization","contractAddress","chainId","nonce","signature","toHex","toYParitySignatureArray","serializeAccessList","accessList","serializedAccessList","i","address","storageKeys","j","InvalidStorageKeySizeError","isAddress","InvalidAddressError","serializeTransaction","transaction","signature","type","getTransactionType","serializeTransactionEIP1559","serializeTransactionEIP2930","serializeTransactionEIP4844","serializeTransactionEIP7702","serializeTransactionLegacy","authorizationList","chainId","gas","nonce","to","value","maxFeePerGas","maxPriorityFeePerGas","accessList","data","assertTransactionEIP7702","serializedAccessList","serializeAccessList","serializedAuthorizationList","serializeAuthorizationList","concatHex","toRlp","toHex","toYParitySignatureArray","maxFeePerBlobGas","assertTransactionEIP4844","blobVersionedHashes","sidecars","blobs","x","bytesToHex","kzg","commitments","blobsToCommitments","commitmentsToVersionedHashes","proofs","blobsToProofs","toBlobSidecars","serializedTransaction","i","blob","commitment","proof","assertTransactionEIP1559","gasPrice","assertTransactionEIP2930","assertTransactionLegacy","v","InvalidLegacyVError","r","trim","s","signature_","yParity","formatStorageProof","storageProof","proof","formatProof","hexToNumber","getProof","client","address","blockNumber","blockTag_","storageKeys","blockTag","blockNumberHex","numberToHex","proof","formatProof","getStorageAt","client","address","blockNumber","blockTag","slot","blockNumberHex","numberToHex","getTransaction","client","blockHash","blockNumber","blockTag_","hash","index","blockTag","blockNumberHex","numberToHex","transaction","TransactionNotFoundError","formatTransaction","getTransactionConfirmations","client","hash","transactionReceipt","blockNumber","transaction","getAction","getBlockNumber","getTransaction","transactionBlockNumber","getTransactionReceipt","client","hash","receipt","TransactionReceiptNotFoundError","formatTransactionReceipt","multicall","client","parameters","allowFailure","batchSize_","blockNumber","blockTag","multicallAddress_","stateOverride","contracts","batchSize","multicallAddress","getChainContractAddress","chunkedCalls","currentChunk","currentChunkSize","i","abi","address","args","functionName","callData","encodeFunctionData","err","error","getContractError","aggregate3Results","calls","getAction","readContract","multicall3Abi","results","result","j","aggregate3Result","returnData","success","AbiDecodingZeroDataError","RawContractError","decodeFunctionResult","BaseError","equalBytes","equalBytes","version","getVersion","version","BaseError","shortMessage","options","details","docsPath","docs","message","x","getVersion","fn","walk","err","bigIntSuffix","stringify","value","replacer","space","key","bigIntSuffix","assertSize","bytes","size_","size","SizeOverflowError","charCodeMap","charCodeToBase16","char","pad","bytes","options","dir","size","SizeExceedsPaddingSizeError","paddedBytes","i","padEnd","assertSize","hex","size_","size","SizeOverflowError","assertStartOffset","value","start","SliceOffsetOutOfBoundsError","assertEndOffset","end","pad","hex_","options","dir","SizeExceedsPaddingSizeError","encoder","from","value","fromHex","fromArray","fromHex","value","options","size","hex","assertSize","padRight","hexString","length","bytes","index","j","nibbleLeft","charCodeToBase16","nibbleRight","BaseError","fromString","value","options","size","bytes","encoder","assertSize","padRight","padRight","value","size","pad","size","value","SizeOverflowError","BaseError","givenSize","maxSize","SizeExceedsPaddingSizeError","BaseError","size","targetSize","type","encoder","hexes","_v","i","assert","value","options","strict","InvalidHexTypeError","InvalidHexValueError","concat","values","acc","x","fromBoolean","value","options","hex","assertSize","padLeft","fromBytes","string","i","hexes","padRight","fromNumber","signed","size","value_","maxValue","minValue","suffix","IntegerOutOfRangeError","fromString","encoder","padLeft","value","size","pad","padRight","slice","value","start","end","options","strict","assertStartOffset","value_","assertEndOffset","size","validate","value","options","strict","assert","IntegerOutOfRangeError","BaseError","max","min","signed","size","InvalidHexTypeError","BaseError","value","stringify","InvalidHexValueError","SizeOverflowError","BaseError","givenSize","maxSize","SliceOffsetOutOfBoundsError","offset","position","size","SizeExceedsPaddingSizeError","targetSize","type","toRpc","withdrawal","fromNumber","toRpc","blockOverrides","fromNumber","simulateBlocks","client","parameters","blockNumber","blockTag","blocks","returnFullTransactions","traceTransfers","validation","blockStateCalls","block","blockOverrides","toRpc","calls","call_","call","account","parseAccount","request","encodeFunctionData","assertRequest","formatTransactionRequest","stateOverrides","serializeStateOverride","numberToHex","i","formatBlock","j","abi","args","functionName","to","data","gasUsed","logs","log","formatLog","status","result","decodeFunctionResult","error","AbiDecodingZeroDataError","RawContractError","getContractError","e","cause","getNodeError","UnknownNodeError","keccak256","value","options","as","bytes","keccak_256","from","fromBytes","LruMap","size","key","value","firstKey","caches","LruMap","checksum","addressRegex","assert","value","options","strict","InvalidAddressError","InvalidInputError","checksum","InvalidChecksumError","address","hexAddress","hash","keccak256","fromString","characters","i","result","validate","address","options","strict","assert","InvalidAddressError","BaseError","cause","InvalidInputError","InvalidChecksumError","normalizeSignature","signature","active","current","level","result","valid","char","BaseError","isArgOfType","arg","abiParameter","argType","abiParameterType","validate","component","index","x","getAmbiguousTypes","sourceParameters","targetParameters","args","parameterIndex","sourceParameter","targetParameter","types","from","abiItem","options","prepare","item","parseAbiItem","getSignatureHash","fromAbi","abi","name","args","isSelector","validate","abiItems","getSelector","slice","NotFoundError","matchedAbiItem","arg","index","abiParameter","isArgOfType","ambiguousTypes","getAmbiguousTypes","AmbiguityError","overloads","getSignature","signature","formatAbiItem","normalizeSignature","keccak256","fromString","BaseError","x","y","data","type","selector","arrayRegex","bytesRegex","integerRegex","maxInt8","maxInt16","maxInt24","maxInt32","maxInt40","maxInt48","maxInt56","maxInt64","maxInt72","maxInt80","maxInt88","maxInt96","maxInt104","maxInt112","maxInt120","maxInt128","maxInt136","maxInt144","maxInt152","maxInt160","maxInt168","maxInt176","maxInt184","maxInt192","maxInt200","maxInt208","maxInt216","maxInt224","maxInt232","maxInt240","maxInt248","maxInt256","minInt8","minInt16","minInt24","minInt32","minInt40","minInt48","minInt56","minInt64","minInt72","minInt80","minInt88","minInt96","minInt104","minInt112","minInt120","minInt128","minInt136","minInt144","minInt152","minInt160","minInt168","minInt176","minInt184","minInt192","minInt200","minInt208","minInt216","minInt224","minInt232","minInt240","minInt248","minInt256","maxUint8","maxUint16","maxUint24","maxUint32","maxUint40","maxUint48","maxUint56","maxUint64","maxUint72","maxUint80","maxUint88","maxUint96","maxUint104","maxUint112","maxUint120","maxUint128","maxUint136","maxUint144","maxUint152","maxUint160","maxUint168","maxUint176","maxUint184","maxUint192","maxUint200","maxUint208","maxUint216","maxUint224","maxUint232","maxUint240","maxUint248","maxUint256","prepareParameters","checksumAddress","parameters","values","preparedParameters","i","prepareParameter","parameter_","value","parameter","arrayComponents","getArrayComponents","length","type","encodeArray","encodeTuple","encodeAddress","encodeBoolean","signed","size","integerRegex","encodeNumber","encodeBytes","encodeString","InvalidTypeError","encode","staticSize","dynamic","encoded","staticParameters","dynamicParameters","dynamicSize","fromNumber","concat","options","checksum","assert","padLeft","InvalidArrayError","ArrayLengthMismatchError","dynamicChild","preparedParam","data","parametersize","bytesSize","value_","padRight","BytesSizeMismatchError","BaseError","fromBoolean","max","min","IntegerOutOfRangeError","hexValue","fromString","partsLength","parts","slice","param_","index","matches","encode","parameters","values","options","checksumAddress","LengthMismatchError","preparedParameters","prepareParameters","data","encodePacked","types","i","type","value","concat","isArray","address","assert","padLeft","fromString","fromBoolean","intMatch","integerRegex","_type","baseType","bits","size","fromNumber","bytesMatch","bytesRegex","BytesSizeMismatchError","padRight","arrayMatch","arrayRegex","childType","InvalidTypeError","ArrayLengthMismatchError","BaseError","expectedLength","givenLength","type","BytesSizeMismatchError","expectedSize","value","size","LengthMismatchError","InvalidArrayError","InvalidTypeError","encode","abiConstructor","options","bytecode","args","concat","from","abiConstructor","encodeData","abiFunction","args","overloads","item","fromAbi","selector","getSelector","data","encode","concat","from","abiFunction","options","fromAbi","abi","name","item","NotFoundError","getSelector","abiItem","ethAddress","zeroAddress","getBalanceCode","simulateCalls","client","parameters","blockNumber","blockTag","calls","stateOverrides","traceAssetChanges","traceTransfers","validation","account","parseAccount","BaseError","getBalanceData","encode","from","deploylessCallViaBytecodeBytecode","encodeData","assetAddresses","call","accessList","createAccessList","encodeFunctionData","address","storageKeys","x","resultsStateOverrides","override","blocks","simulateBlocks","i","zeroAddress","index","block_results","block_ethPre","block_assetsPre","block_ethPost","block_assetsPost","block_decimals","block_tokenURI","block_symbols","block_calls","block","results","ethPre","assetsPre","balancesPre","hexToBigInt","ethPost","assetsPost","balancesPost","decimals","symbols","tokenURI","changes","balancePost","balancePre","decimals_","symbol_","tokenURI_","token","ethAddress","change","secp256k1","serializeSignature","r","s","to","v","yParity","yParity_","signature","secp256k1","hexToBigInt","hexToBytes","verifyHash","client","parameters","address","factory","factoryData","hash","signature","universalSignatureVerifierAddress","rest","signatureHex","isHex","serializeSignature","bytesToHex","wrappedSignature","isErc6492Signature","serializeErc6492Signature","args","encodeFunctionData","universalSignatureValidatorAbi","encodeDeployData","universalSignatureValidatorByteCode","data","getAction","call","hexToBool","error","isAddressEqual","getAddress","recoverAddress","CallExecutionError","verifyMessage","client","address","message","factory","factoryData","signature","callRequest","hash","hashMessage","verifyHash","verifyTypedData","client","parameters","address","factory","factoryData","signature","message","primaryType","types","domain","callRequest","hash","hashTypedData","verifyHash","watchBlockNumber","client","emitOnBegin","emitMissed","onBlockNumber","onError","poll_","pollingInterval","enablePolling","prevBlockNumber","observerId","stringify","observe","emit","poll","blockNumber","getAction","getBlockNumber","i","err","active","unsubscribe","transport","unsubscribe_","data","hexToBigInt","error","waitForTransactionReceipt","client","confirmations","hash","onReplaced","pollingInterval","retryCount","retryDelay","count","timeout","observerId","stringify","transaction","replacedTransaction","receipt","retrying","promise","resolve","reject","withResolvers","timer","WaitForTransactionReceiptTimeoutError","_unobserve","observe","emit","_unwatch","getAction","watchBlockNumber","blockNumber_","done","fn","blockNumber","withRetry","getTransaction","getTransactionReceipt","err","TransactionNotFoundError","TransactionReceiptNotFoundError","block","getBlock","error","BlockNotFoundError","replacementTransaction","from","nonce","reason","err_","watchBlocks","client","blockTag","emitMissed","emitOnBegin","onBlock","onError","includeTransactions_","poll_","pollingInterval","enablePolling","includeTransactions","prevBlock","observerId","stringify","observe","emit","poll","block","getAction","getBlock","i","err","active","emitFetched","unsubscribe","transport","unsubscribe_","data","error","watchEvent","client","address","args","batch","event","events","fromBlock","onError","onLogs","poll_","pollingInterval","strict_","enablePolling","strict","observerId","stringify","observe","emit","previousBlockNumber","filter","initialized","unwatch","poll","getAction","createEventFilter","logs","getFilterChanges","blockNumber","getBlockNumber","getLogs","log","err","InvalidInputRpcError","uninstallFilter","active","unsubscribe","transport","events_","topics","encodeEventTopics","unsubscribe_","data","eventName","decodeEventLog","formatted","formatLog","isUnnamed","DecodeLogDataMismatch","DecodeLogTopicsMismatch","x","error","watchPendingTransactions","client","batch","onError","onTransactions","poll_","pollingInterval","observerId","stringify","observe","emit","filter","unwatch","poll","getAction","createPendingTransactionFilter","err","hashes","getFilterChanges","hash","uninstallFilter","active","unsubscribe","unsubscribe_","data","transaction","error","parseSiweMessage","message","scheme","statement","prefix","prefixRegex","chainId","expirationTime","issuedAt","notBefore","requestId","suffix","suffixRegex","resources","validateSiweMessage","parameters","address","domain","message","nonce","scheme","time","isAddressEqual","verifySiweMessage","client","parameters","address","domain","message","nonce","scheme","signature","time","callRequest","parsed","parseSiweMessage","validateSiweMessage","hash","hashMessage","verifyHash","publicActions","client","args","call","createAccessList","createBlockFilter","createContractEventFilter","createEventFilter","createPendingTransactionFilter","estimateContractGas","estimateGas","getBalance","getBlobBaseFee","getBlock","getBlockNumber","getBlockTransactionCount","getCode","getChainId","getContractEvents","getEip712Domain","getEnsAddress","getEnsAvatar","getEnsName","getEnsResolver","getEnsText","getFeeHistory","estimateFeesPerGas","getFilterChanges","getFilterLogs","getGasPrice","getLogs","getProof","estimateMaxPriorityFeePerGas","getStorageAt","getTransaction","getTransactionConfirmations","getTransactionCount","getTransactionReceipt","multicall","prepareTransactionRequest","readContract","sendRawTransaction","simulateBlocks","simulateCalls","simulateContract","verifyMessage","verifySiweMessage","verifyTypedData","uninstallFilter","waitForTransactionReceipt","watchBlocks","watchBlockNumber","watchContractEvent","watchEvent","watchPendingTransactions","createPublicClient","parameters","key","name","createClient","publicActions","ethers","path","inquirer","dotenv","fs","contracts","formatters","defineBlock","args","transaction","formatted","formatTransaction","hexToBigInt","defineTransaction","defineTransactionReceipt","serializeTransaction","transaction","signature","isDeposit","serializeTransactionDeposit","serializers","assertTransactionDeposit","sourceHash","data","from","gas","isSystemTx","mint","to","value","serializedTransaction","toHex","concatHex","toRlp","isAddress","InvalidAddressError","chainConfig","contracts","formatters","serializers","anvil","defineChain","sourceId","base","defineChain","chainConfig","mainnet","defineChain","sepolia","defineChain","dotenv","path","ensureHexPrefix","hex","SUPPORTED_CHAINS","mainnet","sepolia","base","defineChain","anvil","getChainConfig","chainId","chain","getNetworkConfig","options","interactive","rpcUrl","privateKey","logger","key","inquirer","input","provider","ethers","wallet","KMS_AUTH_ABI","gatherDeploymentInputs","options","wallet","answers","inquirer","ethers","input","deployDefaultAppAuth","kmsContractAddress","deployerAddress","initialDeviceId","composeHash","wallet","spinner","logger","tx","ethers","KMS_AUTH_ABI","ensureHexPrefix","receipt","kmsAuthInterface","log","l","appId","proxyAddress","handleAppAuthDeployment","options","params","gatherDeploymentInputs","gatherUpdateInputs","cvmId","options","logger","id","inquirer","spinner","currentCvm","getCvmByAppId","composeFileName","detectFileInCurrentDir","promptForFile","envs","allowedEnvs","envFilePath","envFiles","file","fs","parseEnv","env","error","prepareUpdatePayload","composeString","encryptedEnv","useEnvFile","encryptEnvVars","registerComposeHash","composeHash","appId","wallet","kmsContractAddress","rawRpcUrl","chainId","appAuthAddress","rpcUrl","getNetworkConfig","chain","getChainConfig","publicClient","createPublicClient","http","kmsAuthAbi","ethers","customAppId","isRegistered","controllerAddress","appAuthAbi","appAuthContract","formattedHash","tx","receipt","appAuthInterface","eventTopic","log","l","composeHashEvent","applyUpdate","response","updatePatchCvmCompose","errorMessage","upgradeCommand","Command","finalCvmId","gatheredOptions","deleteSimulatorEndpointEnv","currentComposeFile","getCvmComposeFile","updateCvmCompose","CLOUD_URL","privateKey","Command","inquirer","chalk","resizeCommand","Command","appId","options","resolvedAppId","resolveCvmAppId","cvm","getCvmByAppId","vcpu","memory","diskSize","allowRestart","inquirer","input","num","confirmMessage","logger","chalk","confirm","spinner","resizeCvm","CLOUD_URL","error","Command","encryptEnvVars","fs","path","replicateCommand","Command","cvmId","options","encryptedEnv","envPath","envVars","line","key","value","cvmConfig","getCvmComposeConfig","logger","requestBody","replica","replicateCvm","tableData","error","errorMessage","Command","encryptEnvVars","getKmsPubkey","kmsId","appId","response","apiClient","API_ENDPOINTS","kmsPubkeyResponseSchema","error","getKmsPubkeyDirectly","cvmComposeConfigSchema","logger","fs","inquirer","ethers","getAndEncryptEnvs","options","envs","envFilePath","envFiles","file","fs","logger","promptForFile","parseEnv","error","inquirer","spinner","kmsResponse","getKmsPubkey","getKmsPubkeyDirectly","pubkey","encryptSpinner","encrypted_env","encryptEnvVars","buildVmConfig","encryptedEnv","kmsInfo","kmsContractAddress","appAuthContractAddress","teepodsSpinner","teepods","getTeepods","kms","chain","getChainConfig","rpcUrl","publicClient","createPublicClient","http","kmsAuthAbi","ethers","customAppId","isRegistered","controllerAddress","displayProvisionResult","response","jsonOutput","CLOUD_URL","tableData","commitProvisionCommand","Command","vmConfig","createSpinner","createCvmOnChainKms","errorMessage","Command","encryptEnvVars","parseSizeWithUnit","input","defaultUnit","match","value","unit","units","parseMemoryInput","bytes","memoryMB","parseDiskSizeInput","diskSizeGB","MAX_DISK_SIZE_GB","fs","path","inquirer","gatherCvmConfig","options","folderName","path","name","inquirer","input","logger","composeFileName","detectFileInCurrentDir","promptForFile","composePath","fs","composeString","envs","allowedEnvs","envFilePath","envFiles","file","parseEnv","env","error","teepodsSpinner","teepods","getTeepods","availableTeepods","teepod","errorMessage","kmsInfo","kmsContractAddress","kms","selectedTeepod","pod","node","t","selectedImage","image","composeFile","memoryMB","DEFAULT_MEMORY","parseMemoryInput","diskSizeGB","DEFAULT_DISK_SIZE","parseDiskSizeInput","vmConfig","DEFAULT_VCPU","provisionAndLogCvm","provisionSpinner","provisionResponse","provisionCvm","executeStandardCreation","spinner","pubkey","getPubkeyFromCvm","encryptSpinner","encrypted_env","encryptEnvVars","createSpinner","response","createCvm","jsonOutput","CLOUD_URL","tableData","provisionCommand","Command","Command","fs","inquirer","encryptEnvVars","gatherUpdateInputs","cvmId","options","logger","id","inquirer","spinner","currentCvm","getCvmByAppId","composeFileName","detectFileInCurrentDir","promptForFile","envs","allowedEnvs","envFilePath","envFiles","file","fs","parseEnv","env","error","prepareUpdatePayload","composeString","encryptedEnv","useEnvFile","upgradeProvisionCommand","Command","finalCvmId","gatheredOptions","currentComposeFile","getCvmComposeFile","response","updateCvmCompose","CLOUD_URL","errorMessage","Command","encryptEnvVars","inquirer","applyUpdate","cvmId","composeHash","encryptedEnv","options","spinner","logger","response","updatePatchCvmCompose","CLOUD_URL","errorMessage","error","prepareUpdatePayload","currentCvm","envs","parseEnv","useEnvFile","inquirer","envFilePath","promptForFile","encryptEnvVars","upgradeCommitCommand","Command","getCvmByAppId","cvmsCommand","Command","attestationCommand","createCommand","deleteCommand","getCommand","listCommand","startCommand","stopCommand","resizeCommand","restartCommand","upgradeCommand","replicateCommand","commitProvisionCommand","provisionCommand","upgradeProvisionCommand","upgradeCommitCommand","Command","execSync","os","openBrowser","url","platform","execSync","logger","error","sleep","ms","resolve","joinCommand","Command","inviteUrl","spinner","logo","Command","jupyterCompose","httpbinCompose","demoTemplates","encryptEnvVars","inquirer","crypto","demoCommands","Command","getApiKey","logger","spinner","userInfo","getUserInfo","templates","demoTemplates","selectedTemplate","inquirer","t","templateContent","token","crypto","envVars","parseEnv","cvmName","input","vmConfig","DEFAULT_IMAGE","pubkey","getPubkeyFromCvm","encrypted_env","encryptEnvVars","createSpinner","response","createCvm","tableData","CLOUD_URL","error","Command","listNodes","teepods","kmsList","getTeepods","logger","teepod","img","kms","error","nodesCommand","Command","listNodes","Command","Command","inquirer","ethers","deployCommand","Command","options","wallet","networkConfig","getNetworkConfig","finalOptions","addr","input","handleAppAuthDeployment","error","logger","kmsCommand","Command","deployCommand","Command","encryptEnvVars","ethers","fs","path","inquirer","gatherCvmConfig","options","folderName","path","name","inquirer","input","logger","composeFileName","detectFileInCurrentDir","promptForFile","composePath","fs","composeString","envs","allowedEnvs","envFilePath","envFiles","file","parseEnv","env","error","teepodsSpinner","teepods","getTeepods","availableTeepods","teepod","errorMessage","kmsInfo","kmsContractAddress","kms","selectedTeepod","pod","node","t","selectedImage","image","composeFile","memoryMB","DEFAULT_MEMORY","parseMemoryInput","diskSizeGB","DEFAULT_DISK_SIZE","parseDiskSizeInput","DEFAULT_VCPU","provisionAndLogCvm","vmConfig","provisionSpinner","provisionResponse","provisionCvm","createFinalCvm","appAuthResult","encrypted_env","kmsId","appId","spinner","public_key","getKmsPubkey","encryptSpinner","encryptEnvVars","finalVmConfig","ensureHexPrefix","createSpinner","finalResponse","createCvmOnChainKms","CLOUD_URL","executeStandardCreation","pubkey","getPubkeyFromCvm","response","createCvm","jsonOutput","tableData","deployCommand","Command","wallet","privateKey","getNetworkConfig","deployOptions","rpcUrl","chain","getChainConfig","publicClient","createPublicClient","http","kmsAuthAbi","ethers","customAppId","isRegistered","controllerAddress","handleAppAuthDeployment","main","program","Command","logo","authCommands","cvmsCommand","dockerCommands","simulatorCommands","demoCommands","joinCommand","kmsCommand","nodesCommand","deployCommand","thisCommand","opts","setApiKey","error","logger"]}
|