@phala/cloud 0.0.10 → 0.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions/commit_cvm_compose_file_update.d.ts +15 -1
- package/dist/actions/commit_cvm_compose_file_update.d.ts.map +1 -1
- package/dist/actions/get_cvm_compose_file.d.ts +2 -70
- package/dist/actions/get_cvm_compose_file.d.ts.map +1 -1
- package/dist/actions/index.d.ts +4 -1
- package/dist/actions/index.d.ts.map +1 -1
- package/dist/actions/list-instance-types.d.ts +146 -0
- package/dist/actions/list-instance-types.d.ts.map +1 -0
- package/dist/actions/provision_cvm_compose_file_update.d.ts +77 -25
- package/dist/actions/provision_cvm_compose_file_update.d.ts.map +1 -1
- package/dist/actions/workspaces/get_workspace.d.ts +72 -0
- package/dist/actions/workspaces/get_workspace.d.ts.map +1 -0
- package/dist/actions/workspaces/list_workspaces.d.ts +219 -0
- package/dist/actions/workspaces/list_workspaces.d.ts.map +1 -0
- package/dist/index.js +240 -77
- package/dist/index.mjs +229 -76
- package/dist/types/app_compose.d.ts +37 -0
- package/dist/types/app_compose.d.ts.map +1 -0
- package/package.json +66 -56
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/client.ts","../src/client.ts","../src/utils/get_error_message.ts","../src/utils/as-hex.ts","../src/utils/validate-parameters.ts","../src/utils/network.ts","../src/utils/transaction.ts","../src/utils/client-factories.ts","../src/actions/get_current_user.ts","../src/types/kms_info.ts","../src/actions/get_available_nodes.ts","../src/actions/provision_cvm.ts","../src/actions/commit_cvm_provision.ts","../src/actions/deploy_app_auth.ts","../src/actions/add_compose_hash.ts","../src/actions/get_cvm_compose_file.ts","../src/actions/provision_cvm_compose_file_update.ts","../src/actions/commit_cvm_compose_file_update.ts","../src/actions/get_app_env_encrypt_pubkey.ts","../src/types/cvm_info.ts","../src/actions/get_cvm_info.ts","../src/actions/get_cvm_list.ts","../src/actions/get_kms_info.ts","../src/actions/get_kms_list.ts"],"names":["z","ofetch","requestError","isHex","privateKeyToAccount","createPublicClient","http","createWalletClient","custom","parseEventLogs","parseEther"],"mappings":";;;;;;;;;;AAMa,IAAA,cAAA,GAAiBA,MAAE,MAAO,CAAA;AAAA,EACrC,MAAA,EAAQA,MAAE,KAAM,CAAA;AAAA,IACdA,MAAE,MAAO,EAAA;AAAA,IACTA,KAAE,CAAA,KAAA;AAAA,MACAA,MAAE,MAAO,CAAA;AAAA,QACP,GAAA,EAAKA,MAAE,MAAO,EAAA;AAAA,QACd,IAAM,EAAAA,KAAA,CAAE,MAAO,EAAA,CAAE,QAAS,EAAA;AAAA,QAC1B,KAAKA,KAAE,CAAA,MAAA,CAAOA,MAAE,OAAQ,EAAC,EAAE,QAAS;AAAA,OACrC;AAAA,KACH;AAAA,IACAA,KAAE,CAAA,MAAA,CAAOA,KAAE,CAAA,OAAA,EAAS;AAAA,GACrB,CAAA;AAAA,EACD,IAAM,EAAAA,KAAA,CAAE,MAAO,EAAA,CAAE,QAAS,EAAA;AAAA,EAC1B,IAAM,EAAAA,KAAA,CAAE,MAAO,EAAA,CAAE,QAAS;AAC5B,CAAC;AAqBY,IAAA,YAAA,GAAN,MAAM,aAAA,SAAqB,KAA0B,CAAA;AAAA,EAiB1D,WAAA,CACE,SACA,OAcA,EAAA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAjCf,IAAA,IAAA,CAAgB,IAAO,GAAA,cAAA;AACvB,IAAA,IAAA,CAAgB,cAAiB,GAAA,IAAA;AAkC/B,IAAA,IAAA,CAAK,SAAS,OAAS,EAAA,MAAA;AACvB,IAAA,IAAA,CAAK,aAAa,OAAS,EAAA,UAAA;AAC3B,IAAA,IAAA,CAAK,OAAO,OAAS,EAAA,IAAA;AACrB,IAAA,IAAA,CAAK,UAAU,OAAS,EAAA,OAAA;AACxB,IAAA,IAAA,CAAK,WAAW,OAAS,EAA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AY,MAAU,IAAA,gBAAA;AACtC,EAAA,MAAM,gBAAmB,GAAA,MAAA,CAAO,SAAU,CAAA,UAAA,CAAW,IAAI,CAAA;AACzD,EAAO,OAAA,gBAAA;AACT","file":"index.js","sourcesContent":["import { z } from \"zod\";\nimport type { FetchError, FetchOptions, FetchRequest } from \"ofetch\";\n\n/**\n * API Error Response Schema\n */\nexport const ApiErrorSchema = z.object({\n detail: z.union([\n z.string(),\n z.array(\n z.object({\n msg: z.string(),\n type: z.string().optional(),\n ctx: z.record(z.unknown()).optional(),\n }),\n ),\n z.record(z.unknown()),\n ]),\n type: z.string().optional(),\n code: z.string().optional(),\n});\n\nexport type ApiError = z.infer<typeof ApiErrorSchema>;\n\n/**\n * Enhanced error type that includes both HTTP and validation errors\n */\nexport type SafeError = RequestError | z.ZodError;\n\n/**\n * Result type for safe operations, similar to zod's SafeParseResult\n * Enhanced to handle both HTTP and validation errors by default\n */\nexport type SafeResult<T, E = SafeError> =\n | { success: true; data: T; error?: never }\n | { success: false; data?: never; error: E };\n\n/**\n * Base error class for HTTP requests\n * Compatible with ApiError interface for Result type compatibility\n */\nexport class RequestError extends Error implements ApiError {\n public readonly name = \"RequestError\";\n public readonly isRequestError = true as const; // Type discriminator\n public readonly status?: number | undefined;\n public readonly statusText?: string | undefined;\n public readonly data?: unknown;\n public readonly request?: FetchRequest | undefined;\n public readonly response?: Response | undefined;\n\n // ApiError interface properties\n public readonly detail:\n | string\n | Record<string, unknown>\n | Array<{ msg: string; type?: string; ctx?: Record<string, unknown> }>;\n public readonly code?: string | undefined;\n public readonly type?: string | undefined;\n\n constructor(\n message: string,\n options?: {\n status?: number | undefined;\n statusText?: string | undefined;\n data?: unknown;\n request?: FetchRequest | undefined;\n response?: Response | undefined;\n cause?: unknown;\n detail?:\n | string\n | Record<string, unknown>\n | Array<{ msg: string; type?: string; ctx?: Record<string, unknown> }>;\n code?: string | undefined;\n type?: string | undefined;\n },\n ) {\n super(message);\n\n this.status = options?.status;\n this.statusText = options?.statusText;\n this.data = options?.data;\n this.request = options?.request;\n this.response = options?.response;\n this.detail = options?.detail || message;\n this.code = options?.code;\n this.type = options?.type;\n }\n\n /**\n * Create RequestError from FetchError\n */\n static fromFetchError(error: FetchError): RequestError {\n // Try to parse the error response as ApiError\n const parseResult = ApiErrorSchema.safeParse(error.data);\n\n if (parseResult.success) {\n return new RequestError(error.message, {\n status: error.status ?? undefined,\n statusText: error.statusText ?? undefined,\n data: error.data,\n request: error.request ?? undefined,\n response: error.response ?? undefined,\n detail: parseResult.data.detail as\n | string\n | Record<string, unknown>\n | Array<{\n msg: string;\n type?: string;\n ctx?: Record<string, unknown>;\n }>,\n code: parseResult.data.code ?? undefined,\n type: parseResult.data.type ?? undefined,\n });\n }\n\n // Fallback to raw error data\n return new RequestError(error.message, {\n status: error.status ?? undefined,\n statusText: error.statusText ?? undefined,\n data: error.data,\n request: error.request ?? undefined,\n response: error.response ?? undefined,\n detail: error.data?.detail || \"Unknown API error\",\n code: error.status?.toString() ?? undefined,\n });\n }\n\n /**\n * Create RequestError from generic Error\n */\n static fromError(error: Error, request?: FetchRequest): RequestError {\n return new RequestError(error.message, {\n request: request ?? undefined,\n detail: error.message,\n });\n }\n}\n\n/**\n * Client configuration - extends FetchOptions and adds predefined API-specific options\n *\n * Environment Variables:\n * - PHALA_CLOUD_API_KEY: API key for authentication\n * - PHALA_CLOUD_API_PREFIX: Base URL prefix for the API\n */\nexport interface ClientConfig extends FetchOptions {\n /**\n * API key for authentication\n * If not provided, will read from PHALA_CLOUD_API_KEY environment variable\n */\n apiKey?: string;\n\n /**\n * Base URL for the API (overrides FetchOptions baseURL)\n * If not provided, will read from PHALA_CLOUD_API_PREFIX environment variable\n * Defaults to \"https://cloud-api.phala.network/v1\"\n */\n baseURL?: string;\n\n /** Default timeout in milliseconds (overrides FetchOptions timeout) */\n timeout?: number;\n\n /**\n * API version to use\n */\n version?: string;\n}\n","import { ofetch, type FetchOptions, type FetchRequest, FetchError } from \"ofetch\";\nimport { type SafeResult, RequestError, type ClientConfig } from \"./types/client\";\nexport type { SafeResult } from \"./types/client\";\n\n// Safely access environment variables to avoid build issues\nconst getEnv = (key: string): string | undefined => {\n try {\n return typeof process !== 'undefined' && process.env ? process.env[key] : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst SUPPORTED_API_VERSIONS = [\"2025-05-31\"];\n\n/**\n * HTTP Client class with ofetch compatibility\n */\nexport class Client {\n protected fetchInstance: typeof ofetch;\n public readonly config: ClientConfig;\n\n constructor(config: ClientConfig = {}) {\n // Resolve configuration with environment variables\n const resolvedConfig: ClientConfig = {\n ...config,\n apiKey: config.apiKey || getEnv('PHALA_CLOUD_API_KEY'),\n baseURL:\n config.baseURL ||\n getEnv('PHALA_CLOUD_API_PREFIX') ||\n \"https://cloud-api.phala.network/api/v1\",\n };\n\n const version =\n resolvedConfig.version && SUPPORTED_API_VERSIONS.includes(resolvedConfig.version)\n ? resolvedConfig.version!\n : SUPPORTED_API_VERSIONS[0]!;\n\n this.config = resolvedConfig;\n\n // Validate that we have an API key\n if (!resolvedConfig.apiKey) {\n throw new Error(\n \"API key is required. Provide it via config.apiKey or set PHALA_CLOUD_API_KEY environment variable.\",\n );\n }\n\n // Extract our custom options and pass the rest to ofetch\n const { apiKey, baseURL, timeout, headers, ...fetchOptions } = resolvedConfig;\n\n this.fetchInstance = ofetch.create({\n baseURL,\n timeout: timeout || 30000,\n headers: {\n \"X-API-Key\": apiKey,\n \"X-Phala-Version\": version,\n \"Content-Type\": \"application/json\",\n ...(headers || {}),\n },\n ...fetchOptions,\n\n // Generic handlers for response error (similar to request.ts)\n onResponseError: ({ response }) => {\n console.warn(`HTTP ${response.status}: ${response.url}`);\n },\n });\n }\n\n /**\n * Get the underlying ofetch instance for advanced usage\n */\n get raw() {\n return this.fetchInstance;\n }\n\n // ===== Direct methods (throw on error) =====\n\n /**\n * Perform GET request (throws on error)\n */\n async get<T = unknown>(\n request: FetchRequest,\n options?: Omit<FetchOptions, \"method\">,\n ): Promise<T> {\n // Note: Type assertion needed due to ofetch's complex generic type system\n return this.fetchInstance<T>(request, {\n ...options,\n method: \"GET\",\n } as Parameters<typeof this.fetchInstance<T>>[1]);\n }\n\n /**\n * Perform POST request (throws on error)\n */\n async post<T = unknown>(\n request: FetchRequest,\n body?: RequestInit[\"body\"] | Record<string, unknown>,\n options?: Omit<FetchOptions, \"method\" | \"body\">,\n ): Promise<T> {\n // Note: Type assertion needed due to ofetch's complex generic type system\n return this.fetchInstance<T>(request, {\n ...options,\n method: \"POST\",\n body,\n } as Parameters<typeof this.fetchInstance<T>>[1]);\n }\n\n /**\n * Perform PUT request (throws on error)\n */\n async put<T = unknown>(\n request: FetchRequest,\n body?: RequestInit[\"body\"] | Record<string, unknown>,\n options?: Omit<FetchOptions, \"method\" | \"body\">,\n ): Promise<T> {\n // Note: Type assertion needed due to ofetch's complex generic type system\n return this.fetchInstance<T>(request, {\n ...options,\n method: \"PUT\",\n body,\n } as Parameters<typeof this.fetchInstance<T>>[1]);\n }\n\n /**\n * Perform PATCH request (throws on error)\n */\n async patch<T = unknown>(\n request: FetchRequest,\n body?: RequestInit[\"body\"] | Record<string, unknown>,\n options?: Omit<FetchOptions, \"method\" | \"body\">,\n ): Promise<T> {\n // Note: Type assertion needed due to ofetch's complex generic type system\n return this.fetchInstance<T>(request, {\n ...options,\n method: \"PATCH\",\n body,\n } as Parameters<typeof this.fetchInstance<T>>[1]);\n }\n\n /**\n * Perform DELETE request (throws on error)\n */\n async delete<T = unknown>(\n request: FetchRequest,\n options?: Omit<FetchOptions, \"method\">,\n ): Promise<T> {\n // Note: Type assertion needed due to ofetch's complex generic type system\n return this.fetchInstance<T>(request, {\n ...options,\n method: \"DELETE\",\n } as Parameters<typeof this.fetchInstance<T>>[1]);\n }\n\n // ===== Safe methods (return SafeResult) =====\n\n /**\n * Safe wrapper for any request method (zod-style result)\n */\n private async safeRequest<T>(fn: () => Promise<T>): Promise<SafeResult<T, RequestError>> {\n try {\n const data = await fn();\n return { success: true, data };\n } catch (error) {\n if (error && typeof error === \"object\" && \"data\" in error) {\n const requestError = RequestError.fromFetchError(error as FetchError);\n return { success: false, error: requestError };\n }\n if (error instanceof Error) {\n const requestError = RequestError.fromError(error);\n return { success: false, error: requestError };\n }\n const requestError = new RequestError(\"Unknown error occurred\", {\n detail: \"Unknown error occurred\",\n });\n return { success: false, error: requestError };\n }\n }\n\n /**\n * Safe GET request (returns SafeResult)\n */\n async safeGet<T = unknown>(\n request: FetchRequest,\n options?: Omit<FetchOptions, \"method\">,\n ): Promise<SafeResult<T, RequestError>> {\n return this.safeRequest(() => this.get<T>(request, options));\n }\n\n /**\n * Safe POST request (returns SafeResult)\n */\n async safePost<T = unknown>(\n request: FetchRequest,\n body?: RequestInit[\"body\"] | Record<string, unknown>,\n options?: Omit<FetchOptions, \"method\" | \"body\">,\n ): Promise<SafeResult<T, RequestError>> {\n return this.safeRequest(() => this.post<T>(request, body, options));\n }\n\n /**\n * Safe PUT request (returns SafeResult)\n */\n async safePut<T = unknown>(\n request: FetchRequest,\n body?: RequestInit[\"body\"] | Record<string, unknown>,\n options?: Omit<FetchOptions, \"method\" | \"body\">,\n ): Promise<SafeResult<T, RequestError>> {\n return this.safeRequest(() => this.put<T>(request, body, options));\n }\n\n /**\n * Safe PATCH request (returns SafeResult)\n */\n async safePatch<T = unknown>(\n request: FetchRequest,\n body?: RequestInit[\"body\"] | Record<string, unknown>,\n options?: Omit<FetchOptions, \"method\" | \"body\">,\n ): Promise<SafeResult<T, RequestError>> {\n return this.safeRequest(() => this.patch<T>(request, body, options));\n }\n\n /**\n * Safe DELETE request (returns SafeResult)\n */\n async safeDelete<T = unknown>(\n request: FetchRequest,\n options?: Omit<FetchOptions, \"method\">,\n ): Promise<SafeResult<T, RequestError>> {\n return this.safeRequest(() => this.delete<T>(request, options));\n }\n}\n\n/**\n * Create a new HTTP client instance\n *\n * Configuration can be provided via parameters or environment variables:\n * - PHALA_CLOUD_API_KEY: API key for authentication\n * - PHALA_CLOUD_API_PREFIX: Base URL prefix for the API\n *\n * @example\n * ```typescript\n * // Using explicit configuration\n * const client = createClient({\n * apiKey: 'your-api-key',\n * baseURL: 'https://custom-api.example.com'\n * })\n *\n * // Using environment variables (set PHALA_CLOUD_API_KEY)\n * const client = createClient()\n * ```\n */\nexport function createClient(config: ClientConfig = {}): Client {\n return new Client(config);\n}\n","import type { ApiError } from \"../types\";\n\nexport function getErrorMessage(error: ApiError): string {\n if (typeof error.detail === \"string\") {\n return error.detail;\n }\n\n if (Array.isArray(error.detail)) {\n if (error.detail.length > 0) {\n return error.detail[0]?.msg || \"Validation error\";\n }\n return \"Validation error\";\n }\n\n if (typeof error.detail === \"object\" && error.detail !== null) {\n return JSON.stringify(error.detail);\n }\n\n return \"Unknown error occurred\";\n}\n","import { type Hex, isHex } from \"viem\";\n\n/**\n * Converts a value to a hex string with 0x prefix.\n *\n * @param value - The value to convert to hex. Can be a string with or without 0x prefix.\n * @returns A valid hex string with 0x prefix.\n * @throws Error if the value cannot be converted to a valid hex string.\n *\n * @example\n * ```typescript\n * asHex(\"abc123\") // \"0xabc123\"\n * asHex(\"0xabc123\") // \"0xabc123\"\n * asHex(\"xyz\") // throws Error\n * ```\n */\nexport function asHex(value: unknown): Hex {\n if (typeof value === \"string\") {\n if (value.startsWith(\"0x\") && isHex(value)) {\n return value as Hex;\n } else if (isHex(`0x${value}`)) {\n return `0x${value}` as Hex;\n }\n }\n throw new Error(`Invalid hex value: ${value}`);\n}\n","import type { SafeResult } from \"../client\";\n\n/**\n * Validates action parameters, specifically the schema parameter\n *\n * @param parameters - The parameters to validate\n * @throws Error if schema parameter is invalid (for non-safe functions)\n */\nexport function validateActionParameters<T>(parameters?: { schema?: T }): void {\n if (parameters?.schema !== undefined && parameters?.schema !== false) {\n if (\n typeof parameters.schema !== \"object\" ||\n parameters.schema === null ||\n !(\"parse\" in parameters.schema) ||\n typeof parameters.schema.parse !== \"function\"\n ) {\n throw new Error(\"Invalid schema: must be a Zod schema object, false, or undefined\");\n }\n }\n}\n\n/**\n * Validates action parameters for safe functions\n *\n * @param parameters - The parameters to validate\n * @returns SafeResult with error if validation fails, undefined if validation passes\n */\nexport function safeValidateActionParameters<T, ReturnType>(parameters?: { schema?: T }):\n | SafeResult<ReturnType>\n | undefined {\n if (parameters?.schema !== undefined && parameters?.schema !== false) {\n if (\n typeof parameters.schema !== \"object\" ||\n parameters.schema === null ||\n !(\"parse\" in parameters.schema) ||\n typeof parameters.schema.parse !== \"function\"\n ) {\n return {\n success: false,\n error: {\n name: \"ZodError\",\n message: \"Invalid schema: must be a Zod schema object, false, or undefined\",\n issues: [\n {\n code: \"invalid_type\",\n expected: \"object\",\n received: typeof parameters.schema,\n path: [\"schema\"],\n message: \"Invalid schema: must be a Zod schema object, false, or undefined\",\n },\n ],\n },\n } as SafeResult<ReturnType>;\n }\n }\n return undefined;\n}\n","import {\n type Chain,\n type Address,\n type Hash,\n type PublicClient,\n type WalletClient,\n type TransactionReceipt,\n} from \"viem\";\n\n// Core types for blockchain operations\nexport interface NetworkClients {\n publicClient: PublicClient;\n walletClient: WalletClient;\n address: Address;\n chainId: number;\n}\n\n// Optional configuration types for convenience functions\nexport interface NetworkConfig {\n chainId: number;\n name: string;\n rpcUrl: string;\n blockExplorer?: string;\n}\n\nexport interface WalletConnection {\n address: Address;\n chainId: number;\n}\n\nexport interface BalanceCheckResult {\n address: Address;\n balance: bigint;\n sufficient: boolean;\n required?: bigint;\n}\n\nexport interface TransactionOptions {\n timeout?: number; // in milliseconds\n confirmations?: number;\n onSubmitted?: (hash: Hash) => void;\n onConfirmed?: (receipt: TransactionReceipt) => void;\n onError?: (error: Error, hash?: Hash) => void;\n}\n\nexport interface TransactionResult {\n hash: Hash;\n receipt: TransactionReceipt;\n success: boolean;\n}\n\n// Error types for better error handling\nexport class NetworkError extends Error {\n constructor(\n message: string,\n public code?: string,\n public details?: unknown,\n ) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\nexport class WalletError extends Error {\n constructor(\n message: string,\n public code?: string,\n public details?: unknown,\n ) {\n super(message);\n this.name = \"WalletError\";\n }\n}\n\nexport class TransactionError extends Error {\n constructor(\n message: string,\n public hash?: Hash,\n public details?: unknown,\n ) {\n super(message);\n this.name = \"TransactionError\";\n }\n}\n\n/**\n * Create a NetworkClients object from existing viem clients\n * This is the primary way to create NetworkClients - the caller provides pre-configured clients\n */\nexport function createNetworkClients(\n publicClient: PublicClient,\n walletClient: WalletClient,\n address: Address,\n chainId: number,\n): NetworkClients {\n return {\n publicClient,\n walletClient,\n address,\n chainId,\n };\n}\n\n/**\n * Check wallet connection and network status\n */\nexport async function checkNetworkStatus(\n clients: NetworkClients,\n targetChainId: number,\n): Promise<{ isCorrectNetwork: boolean; currentChainId: number }> {\n try {\n const currentChainId = await clients.walletClient.getChainId();\n return {\n isCorrectNetwork: currentChainId === targetChainId,\n currentChainId,\n };\n } catch (error) {\n throw new NetworkError(\n `Failed to check network status: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"NETWORK_CHECK_FAILED\",\n error,\n );\n }\n}\n\n/**\n * Check wallet balance\n */\nexport async function checkBalance(\n publicClient: PublicClient,\n address: Address,\n minBalance?: bigint,\n): Promise<BalanceCheckResult> {\n try {\n const balance = await publicClient.getBalance({ address });\n\n return {\n address,\n balance,\n sufficient: minBalance ? balance >= minBalance : true,\n required: minBalance,\n };\n } catch (error) {\n throw new NetworkError(\n `Failed to check balance: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"BALANCE_CHECK_FAILED\",\n error,\n );\n }\n}\n\n/**\n * Wait for transaction receipt with timeout and polling\n */\nexport async function waitForTransactionReceipt(\n publicClient: PublicClient,\n hash: Hash,\n options: {\n timeout?: number;\n pollingInterval?: number;\n confirmations?: number;\n } = {},\n): Promise<TransactionReceipt> {\n const {\n timeout = 60000, // 60 seconds default\n pollingInterval = 2000, // 2 seconds default\n confirmations = 1,\n } = options;\n\n const startTime = Date.now();\n\n return new Promise((resolve, reject) => {\n const poll = async () => {\n try {\n const receipt = await publicClient.getTransactionReceipt({ hash });\n\n if (receipt) {\n // Check if we need to wait for additional confirmations\n if (confirmations > 1) {\n const currentBlock = await publicClient.getBlockNumber();\n const confirmationCount = currentBlock - receipt.blockNumber + 1n;\n\n if (confirmationCount < BigInt(confirmations)) {\n // Not enough confirmations yet, continue polling\n const elapsed = Date.now() - startTime;\n if (elapsed >= timeout) {\n reject(\n new TransactionError(`Transaction confirmation timeout after ${timeout}ms`, hash),\n );\n return;\n }\n setTimeout(poll, pollingInterval);\n return;\n }\n }\n\n resolve(receipt);\n } else {\n // Transaction not yet mined\n const elapsed = Date.now() - startTime;\n if (elapsed >= timeout) {\n reject(new TransactionError(`Transaction receipt timeout after ${timeout}ms`, hash));\n return;\n }\n setTimeout(poll, pollingInterval);\n }\n } catch (error) {\n // Check if it's just \"transaction not found\" error, continue polling\n const elapsed = Date.now() - startTime;\n if (elapsed >= timeout) {\n reject(\n new TransactionError(`Transaction receipt timeout after ${timeout}ms`, hash, error),\n );\n return;\n }\n setTimeout(poll, pollingInterval);\n }\n };\n\n // Start polling immediately\n poll();\n });\n}\n\n/**\n * Execute a transaction with automatic receipt waiting and error handling\n */\nexport async function executeTransaction<T extends unknown[]>(\n clients: NetworkClients,\n operation: (clients: NetworkClients, ...args: T) => Promise<Hash>,\n args: T,\n options: TransactionOptions = {},\n): Promise<TransactionResult> {\n const { timeout = 60000, confirmations = 1, onSubmitted, onConfirmed, onError } = options;\n\n try {\n // Execute the transaction\n const hash = await operation(clients, ...args);\n\n onSubmitted?.(hash);\n\n // Wait for receipt\n const receipt = await waitForTransactionReceipt(clients.publicClient, hash, {\n timeout,\n confirmations,\n });\n\n const success = receipt.status === \"success\";\n\n if (success) {\n onConfirmed?.(receipt);\n } else {\n const error = new TransactionError(\"Transaction failed on-chain\", hash, receipt);\n onError?.(error, hash);\n throw error;\n }\n\n return {\n hash,\n receipt,\n success,\n };\n } catch (error) {\n const txError =\n error instanceof TransactionError\n ? error\n : new TransactionError(\n `Transaction execution failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n undefined,\n error,\n );\n\n onError?.(txError, txError.hash);\n throw txError;\n }\n}\n\n/**\n * Extract NetworkClients info from existing viem clients\n * Useful when you have existing clients and want to create a NetworkClients object\n */\nexport async function extractNetworkClients(\n publicClient: PublicClient,\n walletClient: WalletClient,\n): Promise<NetworkClients> {\n try {\n const address = walletClient.account?.address;\n if (!address) {\n throw new WalletError(\"WalletClient must have an account\", \"NO_ACCOUNT\");\n }\n\n const chainId = await walletClient.getChainId();\n\n return createNetworkClients(publicClient, walletClient, address, chainId);\n } catch (error) {\n throw new WalletError(\n `Failed to extract network clients: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"EXTRACTION_FAILED\",\n error,\n );\n }\n}\n\n/**\n * Comprehensive network validation\n */\nexport async function validateNetworkPrerequisites(\n clients: NetworkClients,\n requirements: {\n targetChainId: number;\n minBalance?: bigint;\n requiredAddress?: Address;\n },\n): Promise<{\n networkValid: boolean;\n balanceValid: boolean;\n addressValid: boolean;\n details: {\n currentChainId: number;\n balance: bigint;\n address: Address;\n };\n}> {\n const { targetChainId, minBalance, requiredAddress } = requirements;\n\n // Check network\n const networkStatus = await checkNetworkStatus(clients, targetChainId);\n\n // Check balance\n const balanceResult = await checkBalance(clients.publicClient, clients.address, minBalance);\n\n // Check address if required\n const addressValid = requiredAddress\n ? clients.address.toLowerCase() === requiredAddress.toLowerCase()\n : true;\n\n return {\n networkValid: networkStatus.isCorrectNetwork,\n balanceValid: balanceResult.sufficient,\n addressValid,\n details: {\n currentChainId: networkStatus.currentChainId,\n balance: balanceResult.balance,\n address: clients.address,\n },\n };\n}\n","import type { Hash, TransactionReceipt } from \"viem\";\nimport {\n NetworkClients,\n TransactionOptions,\n TransactionResult,\n TransactionError,\n waitForTransactionReceipt,\n} from \"./network\";\n\n// Transaction state tracking\nexport type TransactionState = \"idle\" | \"submitting\" | \"pending\" | \"success\" | \"error\" | \"timeout\";\n\nexport interface TransactionStatus {\n state: TransactionState;\n hash?: Hash;\n receipt?: TransactionReceipt;\n error?: string;\n startTime?: number;\n submitTime?: number;\n confirmTime?: number;\n aborted?: boolean;\n}\n\nexport interface TransactionTracker {\n readonly status: TransactionStatus;\n readonly isIdle: boolean;\n readonly isSubmitting: boolean;\n readonly isPending: boolean;\n readonly isSuccess: boolean;\n readonly isError: boolean;\n readonly isTimeout: boolean;\n readonly isAborted: boolean;\n readonly isComplete: boolean;\n abort(): void;\n reset(): void;\n execute<T extends unknown[]>(\n operation: (clients: NetworkClients, ...args: T) => Promise<Hash>,\n clients: NetworkClients,\n args: T,\n options?: TransactionOptions & { signal?: AbortSignal },\n ): Promise<TransactionResult>;\n}\n\n/**\n * Create a transaction tracker for monitoring transaction state\n */\nexport function createTransactionTracker(): TransactionTracker {\n let status: TransactionStatus = { state: \"idle\" };\n let timeoutHandle: NodeJS.Timeout | undefined;\n let abortController: AbortController | undefined;\n\n const updateStatus = (newStatus: Partial<TransactionStatus>) => {\n status = { ...status, ...newStatus };\n };\n\n const reset = () => {\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n timeoutHandle = undefined;\n }\n if (abortController) {\n abortController.abort();\n abortController = undefined;\n }\n status = { state: \"idle\" };\n };\n\n const abort = () => {\n if (abortController) {\n abortController.abort();\n }\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n timeoutHandle = undefined;\n }\n updateStatus({\n state: \"error\",\n aborted: true,\n error: \"Transaction aborted by user\",\n });\n };\n\n const execute = async <T extends unknown[]>(\n operation: (clients: NetworkClients, ...args: T) => Promise<Hash>,\n clients: NetworkClients,\n args: T,\n options: TransactionOptions & { signal?: AbortSignal } = {},\n ): Promise<TransactionResult> => {\n const {\n timeout = 60000,\n confirmations = 1,\n onSubmitted,\n onConfirmed,\n onError,\n signal,\n } = options;\n\n try {\n // Reset and start\n reset();\n abortController = new AbortController();\n\n // Connect external abort signal if provided\n if (signal) {\n if (signal.aborted) {\n throw new TransactionError(\"Operation was aborted before execution\");\n }\n signal.addEventListener(\"abort\", () => {\n abort();\n });\n }\n\n updateStatus({\n state: \"submitting\",\n startTime: Date.now(),\n error: undefined,\n hash: undefined,\n receipt: undefined,\n aborted: false,\n });\n\n // Check for abort before execution\n if (abortController.signal.aborted) {\n throw new TransactionError(\"Transaction aborted\");\n }\n\n // Execute the transaction\n const hash = await operation(clients, ...args);\n\n // Check for abort after submission\n if (abortController.signal.aborted) {\n throw new TransactionError(\"Transaction aborted after submission\", hash);\n }\n\n updateStatus({\n state: \"pending\",\n hash,\n submitTime: Date.now(),\n });\n\n onSubmitted?.(hash);\n\n // Set up timeout\n if (timeout > 0) {\n timeoutHandle = setTimeout(() => {\n if (status.state === \"pending\" && !abortController?.signal.aborted) {\n updateStatus({\n state: \"timeout\",\n error: `Transaction timeout after ${timeout}ms`,\n });\n }\n }, timeout);\n }\n\n // Wait for receipt with abort signal support\n const receipt = await Promise.race([\n waitForTransactionReceipt(clients.publicClient, hash, { timeout, confirmations }),\n new Promise<never>((_, reject) => {\n abortController?.signal.addEventListener(\"abort\", () => {\n reject(new TransactionError(\"Transaction aborted while waiting for receipt\", hash));\n });\n }),\n ]);\n\n // Clear timeout on success\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n timeoutHandle = undefined;\n }\n\n const success = receipt.status === \"success\";\n\n updateStatus({\n state: success ? \"success\" : \"error\",\n receipt,\n confirmTime: Date.now(),\n error: success ? undefined : \"Transaction failed on-chain\",\n });\n\n if (success) {\n onConfirmed?.(receipt);\n } else {\n const error = new TransactionError(\"Transaction failed on-chain\", hash, receipt);\n onError?.(error, hash);\n throw error;\n }\n\n return {\n hash,\n receipt,\n success,\n };\n } catch (error) {\n const txError =\n error instanceof TransactionError\n ? error\n : new TransactionError(\n `Transaction execution failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n status.hash,\n error,\n );\n\n updateStatus({\n state: \"error\",\n error: txError.message,\n });\n\n onError?.(txError, status.hash);\n throw txError;\n }\n };\n\n return {\n get status() {\n return { ...status };\n },\n get isIdle() {\n return status.state === \"idle\";\n },\n get isSubmitting() {\n return status.state === \"submitting\";\n },\n get isPending() {\n return status.state === \"pending\";\n },\n get isSuccess() {\n return status.state === \"success\";\n },\n get isError() {\n return status.state === \"error\";\n },\n get isTimeout() {\n return status.state === \"timeout\";\n },\n get isAborted() {\n return status.aborted === true;\n },\n get isComplete() {\n return [\"success\", \"error\", \"timeout\"].includes(status.state);\n },\n abort,\n reset,\n execute,\n };\n}\n\n/**\n * Batch transaction executor with sequential or parallel execution\n */\nexport interface BatchTransactionOptions {\n mode: \"sequential\" | \"parallel\";\n failFast?: boolean; // Stop on first error (sequential mode only)\n timeout?: number;\n onProgress?: (completed: number, total: number, results: (TransactionResult | Error)[]) => void;\n}\n\nexport interface BatchTransactionResult {\n results: (TransactionResult | Error)[];\n successCount: number;\n errorCount: number;\n allSuccessful: boolean;\n}\n\n/**\n * Execute multiple transactions in batch\n */\nexport async function executeBatchTransactions<T extends unknown[]>(\n operations: Array<{\n operation: (clients: NetworkClients, ...args: T) => Promise<Hash>;\n args: T;\n options?: TransactionOptions;\n }>,\n clients: NetworkClients,\n batchOptions: BatchTransactionOptions,\n): Promise<BatchTransactionResult> {\n const { mode, failFast = false, onProgress } = batchOptions;\n const results: (TransactionResult | Error)[] = [];\n\n if (mode === \"sequential\") {\n for (let i = 0; i < operations.length; i++) {\n const op = operations[i];\n if (!op) continue;\n const { operation, args, options } = op;\n\n try {\n const tracker = createTransactionTracker();\n const result = await tracker.execute(operation, clients, args, options);\n results.push(result);\n\n onProgress?.(i + 1, operations.length, results);\n } catch (error) {\n const txError = error instanceof Error ? error : new Error(String(error));\n results.push(txError);\n\n onProgress?.(i + 1, operations.length, results);\n\n if (failFast) {\n // Fill remaining slots with the same error\n for (let j = i + 1; j < operations.length; j++) {\n results.push(new Error(\"Cancelled due to previous failure\"));\n }\n break;\n }\n }\n }\n } else {\n // Parallel execution\n const promises = operations.map(async ({ operation, args, options }) => {\n try {\n const tracker = createTransactionTracker();\n return await tracker.execute(operation, clients, args, options);\n } catch (error) {\n return error instanceof Error ? error : new Error(String(error));\n }\n });\n\n const allResults = await Promise.allSettled(promises);\n results.push(...allResults.map((r) => (r.status === \"fulfilled\" ? r.value : r.reason)));\n\n onProgress?.(operations.length, operations.length, results);\n }\n\n const successCount = results.filter((r) => !(r instanceof Error)).length;\n const errorCount = results.length - successCount;\n\n return {\n results,\n successCount,\n errorCount,\n allSuccessful: errorCount === 0,\n };\n}\n\n/**\n * Transaction retry utility with exponential backoff\n */\nexport interface RetryOptions {\n maxRetries?: number;\n initialDelay?: number;\n maxDelay?: number;\n backoffFactor?: number;\n retryCondition?: (error: Error) => boolean;\n}\n\nexport async function executeTransactionWithRetry<T extends unknown[]>(\n operation: (clients: NetworkClients, ...args: T) => Promise<Hash>,\n clients: NetworkClients,\n args: T,\n options: TransactionOptions = {},\n retryOptions: RetryOptions = {},\n): Promise<TransactionResult> {\n const {\n maxRetries = 3,\n initialDelay = 1000,\n maxDelay = 10000,\n backoffFactor = 2,\n retryCondition = () => true,\n } = retryOptions;\n\n let lastError: Error;\n let delay = initialDelay;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const tracker = createTransactionTracker();\n return await tracker.execute(operation, clients, args, options);\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Don't retry on the last attempt\n if (attempt === maxRetries) {\n break;\n }\n\n // Check if we should retry this error\n if (!retryCondition(lastError)) {\n break;\n }\n\n // Wait before retry\n await new Promise((resolve) => setTimeout(resolve, delay));\n delay = Math.min(delay * backoffFactor, maxDelay);\n }\n }\n\n throw lastError!;\n}\n\n/**\n * Smart gas estimation and transaction optimization\n */\nexport interface GasEstimationOptions {\n gasLimitMultiplier?: number;\n maxFeePerGasMultiplier?: number;\n priorityFeeMultiplier?: number;\n}\n\nexport async function estimateTransactionGas(\n clients: NetworkClients,\n transaction: Parameters<typeof clients.publicClient.estimateGas>[0],\n options: GasEstimationOptions = {},\n): Promise<{\n gasLimit: bigint;\n maxFeePerGas?: bigint;\n maxPriorityFeePerGas?: bigint;\n}> {\n const {\n gasLimitMultiplier = 1.2,\n maxFeePerGasMultiplier = 1.1,\n priorityFeeMultiplier = 1.1,\n } = options;\n\n try {\n // Estimate gas limit\n const estimatedGas = await clients.publicClient.estimateGas(transaction);\n const gasLimit = BigInt(Math.ceil(Number(estimatedGas) * gasLimitMultiplier));\n\n // Get current gas prices (EIP-1559)\n let maxFeePerGas: bigint | undefined;\n let maxPriorityFeePerGas: bigint | undefined;\n\n try {\n const feeData = await clients.publicClient.estimateFeesPerGas();\n if (feeData.maxFeePerGas) {\n maxFeePerGas = BigInt(Math.ceil(Number(feeData.maxFeePerGas) * maxFeePerGasMultiplier));\n }\n if (feeData.maxPriorityFeePerGas) {\n maxPriorityFeePerGas = BigInt(\n Math.ceil(Number(feeData.maxPriorityFeePerGas) * priorityFeeMultiplier),\n );\n }\n } catch (error) {\n // EIP-1559 not supported, fallback to legacy gas price\n // maxFeePerGas and maxPriorityFeePerGas will remain undefined\n }\n\n return {\n gasLimit,\n maxFeePerGas,\n maxPriorityFeePerGas,\n };\n } catch (error) {\n throw new TransactionError(\n `Gas estimation failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n undefined,\n error,\n );\n }\n}\n","import {\n createPublicClient,\n createWalletClient,\n http,\n custom,\n type Chain,\n type Address,\n type Hash,\n} from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport {\n createNetworkClients,\n extractNetworkClients,\n WalletError,\n NetworkError,\n type NetworkClients,\n} from \"./network\";\n\n/**\n * OPTIONAL CONVENIENCE FUNCTIONS\n *\n * These functions are provided for convenience but are not required.\n * You can create your own viem clients and use createNetworkClients() directly.\n *\n * These functions demonstrate common patterns but should not limit your flexibility.\n */\n\n// Browser environment detection\nfunction isBrowser(): boolean {\n // biome-ignore lint/suspicious/noExplicitAny: window.ethereum type checking is handled separately\n return typeof window !== \"undefined\" && typeof (window as any).ethereum !== \"undefined\";\n}\n\n// EIP-1193 Provider interface for browser environments\ninterface EthereumProvider {\n request: (args: { method: string; params?: unknown[] }) => Promise<unknown>;\n on?(event: string, handler: (...args: unknown[]) => void): void;\n removeListener?(event: string, handler: (...args: unknown[]) => void): void;\n}\n\n// Get Ethereum provider in browser environment\nfunction getEthereumProvider(): EthereumProvider | null {\n if (!isBrowser()) return null;\n // biome-ignore lint/suspicious/noExplicitAny: window.ethereum type checking is handled separately\n const ethereum = (window as any).ethereum as EthereumProvider | undefined;\n return ethereum || null;\n}\n\n/**\n * CONVENIENCE: Create clients from private key (server-side)\n * You can also create your own viem clients and use createNetworkClients() directly\n */\nexport function createClientsFromPrivateKey(\n chain: Chain,\n privateKey: Hash,\n rpcUrl?: string,\n): NetworkClients {\n try {\n const account = privateKeyToAccount(privateKey);\n\n const publicClient = createPublicClient({\n chain,\n transport: http(rpcUrl || chain.rpcUrls.default.http[0]),\n });\n\n const walletClient = createWalletClient({\n account,\n chain,\n transport: http(rpcUrl || chain.rpcUrls.default.http[0]),\n });\n\n return createNetworkClients(publicClient, walletClient, account.address, chain.id);\n } catch (error) {\n throw new WalletError(\n `Failed to create clients from private key: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"CLIENT_CREATION_FAILED\",\n error,\n );\n }\n}\n\n/**\n * CONVENIENCE: Create clients from browser wallet (client-side)\n * You can also create your own viem clients and use createNetworkClients() directly\n */\nexport async function createClientsFromBrowser(\n chain: Chain,\n rpcUrl?: string,\n): Promise<NetworkClients> {\n if (!isBrowser()) {\n throw new WalletError(\n \"Browser wallet connection is only available in browser environment\",\n \"NOT_BROWSER_ENVIRONMENT\",\n );\n }\n\n const provider = getEthereumProvider();\n if (!provider) {\n throw new WalletError(\n \"No Ethereum provider found. Please install a wallet like MetaMask.\",\n \"NO_PROVIDER\",\n );\n }\n\n try {\n // Request account access\n const accounts = (await provider.request({\n method: \"eth_requestAccounts\",\n })) as string[];\n\n if (!accounts || accounts.length === 0) {\n throw new WalletError(\"No accounts available\", \"NO_ACCOUNTS\");\n }\n\n const address = accounts[0] as Address;\n\n // Get current chain ID\n const chainId = (await provider.request({ method: \"eth_chainId\" })) as string;\n const currentChainId = parseInt(chainId, 16);\n\n // Check if we need to switch networks\n if (currentChainId !== chain.id) {\n await switchToNetwork(provider, chain.id);\n }\n\n const publicClient = createPublicClient({\n chain,\n transport: http(rpcUrl || chain.rpcUrls.default.http[0]),\n });\n\n const walletClient = createWalletClient({\n account: address,\n chain,\n transport: custom(provider),\n });\n\n return createNetworkClients(publicClient, walletClient, address, chain.id);\n } catch (error) {\n if (error instanceof WalletError || error instanceof NetworkError) {\n throw error;\n }\n throw new WalletError(\n `Failed to connect browser wallet: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"BROWSER_CONNECTION_FAILED\",\n error,\n );\n }\n}\n\n/**\n * CONVENIENCE: Switch to a specific network in browser wallet\n */\nexport async function switchToNetwork(provider: EthereumProvider, chainId: number): Promise<void> {\n try {\n await provider.request({\n method: \"wallet_switchEthereumChain\",\n params: [{ chainId: `0x${chainId.toString(16)}` }],\n });\n } catch (error: unknown) {\n // Chain not found, try to add it\n const errorObj = error as { code?: number; message?: string };\n if (errorObj.code === 4902) {\n throw new NetworkError(\n `Network ${chainId} not found in wallet. Please add it manually.`,\n \"NETWORK_NOT_FOUND\",\n error,\n );\n }\n throw new NetworkError(\n `Failed to switch network: ${errorObj.message || \"Unknown error\"}`,\n \"NETWORK_SWITCH_FAILED\",\n error,\n );\n }\n}\n\n/**\n * CONVENIENCE: Add a custom network to browser wallet\n */\nexport async function addNetwork(\n provider: EthereumProvider,\n config: {\n chainId: number;\n name: string;\n rpcUrl: string;\n blockExplorer?: string;\n },\n): Promise<void> {\n try {\n await provider.request({\n method: \"wallet_addEthereumChain\",\n params: [\n {\n chainId: `0x${config.chainId.toString(16)}`,\n chainName: config.name,\n rpcUrls: [config.rpcUrl],\n blockExplorerUrls: config.blockExplorer ? [config.blockExplorer] : undefined,\n nativeCurrency: {\n name: \"ETH\",\n symbol: \"ETH\",\n decimals: 18,\n },\n },\n ],\n });\n } catch (error: unknown) {\n const errorObj = error as { message?: string };\n throw new NetworkError(\n `Failed to add network: ${errorObj.message || \"Unknown error\"}`,\n \"NETWORK_ADD_FAILED\",\n error,\n );\n }\n}\n\n/**\n * CONVENIENCE: Auto-detect environment and create clients\n * You can also create your own viem clients and use createNetworkClients() directly\n */\nexport async function autoCreateClients(\n chain: Chain,\n options: {\n privateKey?: Hash;\n rpcUrl?: string;\n preferBrowser?: boolean;\n } = {},\n): Promise<NetworkClients> {\n const { privateKey, rpcUrl, preferBrowser = false } = options;\n\n // If private key is provided, use server-side approach\n if (privateKey) {\n return createClientsFromPrivateKey(chain, privateKey, rpcUrl);\n }\n\n // If in browser and prefer browser wallet, or no private key provided\n if (isBrowser() && (preferBrowser || !privateKey)) {\n return createClientsFromBrowser(chain, rpcUrl);\n }\n\n throw new WalletError(\n \"No wallet connection method available. Provide a private key for server-side usage or use in browser environment.\",\n \"NO_CONNECTION_METHOD\",\n );\n}\n","import { z } from \"zod\";\nimport { type Client, type SafeResult } from \"../client\";\nimport { ActionParameters, ActionReturnType } from \"../types/common\";\nimport { validateActionParameters, safeValidateActionParameters } from \"../utils\";\n\n/**\n * Get current user information and validate API token\n *\n * Returns information about the current authenticated user.\n *\n * @example\n * ```typescript\n * import { createClient, getCurrentUser } from '@phala/cloud'\n *\n * const client = createClient({ apiKey: 'your-api-key' })\n * const user = await getCurrentUser(client)\n * // Output: { username: 'alice', email: 'alice@example.com', credits: 1000, ... }\n * ```\n *\n * ## Returns\n *\n * `CurrentUser | unknown`\n *\n * Information about the current user. Return type depends on schema parameter.\n *\n * ## Parameters\n *\n * ### parameters (optional)\n * - **Type:** `GetCurrentUserParameters`\n *\n * Optional behavior parameters for schema validation.\n *\n * ```typescript\n * // Use default schema\n * const user = await getCurrentUser(client)\n *\n * // Return raw data without validation\n * const raw = await getCurrentUser(client, { schema: false })\n *\n * // Use custom schema\n * const customSchema = z.object({ id: z.number(), name: z.string() })\n * const custom = await getCurrentUser(client, { schema: customSchema })\n * ```\n *\n * ## Safe Version\n *\n * Use `safeGetCurrentUser` for error handling without exceptions:\n *\n * ```typescript\n * import { safeGetCurrentUser } from '@phala/cloud'\n *\n * const result = await safeGetCurrentUser(client)\n * if (result.success) {\n * console.log(result.data.username)\n * } else {\n * if (\"isRequestError\" in result.error) {\n * console.error(`HTTP ${result.error.status}: ${result.error.message}`)\n * } else {\n * console.error(`Validation error: ${result.error.issues}`)\n * }\n * }\n * ```\n */\n\nexport const CurrentUserSchema = z\n .object({\n username: z.string(),\n email: z.string(),\n credits: z.number(),\n granted_credits: z.number(),\n avatar: z.string(),\n team_name: z.string(),\n team_tier: z.string(),\n })\n .passthrough();\n\nexport type CurrentUser = z.infer<typeof CurrentUserSchema>;\n\nexport type GetCurrentUserParameters<T = undefined> = ActionParameters<T>;\n\nexport type GetCurrentUserReturnType<T = undefined> = ActionReturnType<CurrentUser, T>;\n\nexport async function getCurrentUser<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n parameters?: GetCurrentUserParameters<T>,\n): Promise<GetCurrentUserReturnType<T>> {\n validateActionParameters(parameters);\n\n const response = await client.get(\"/auth/me\");\n\n if (parameters?.schema === false) {\n return response as GetCurrentUserReturnType<T>;\n }\n\n const schema = (parameters?.schema || CurrentUserSchema) as z.ZodSchema;\n return schema.parse(response) as GetCurrentUserReturnType<T>;\n}\n\nexport async function safeGetCurrentUser<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n parameters?: GetCurrentUserParameters<T>,\n): Promise<SafeResult<GetCurrentUserReturnType<T>>> {\n const parameterValidationError = safeValidateActionParameters(parameters);\n if (parameterValidationError) {\n return parameterValidationError as SafeResult<GetCurrentUserReturnType<T>>;\n }\n\n const httpResult = await client.safeGet(\"/auth/me\");\n if (!httpResult.success) {\n return httpResult as SafeResult<GetCurrentUserReturnType<T>>;\n }\n\n if (parameters?.schema === false) {\n return { success: true, data: httpResult.data } as SafeResult<GetCurrentUserReturnType<T>>;\n }\n\n const schema = (parameters?.schema || CurrentUserSchema) as z.ZodSchema;\n return schema.safeParse(httpResult.data) as SafeResult<GetCurrentUserReturnType<T>>;\n}\n","import type { Address, Hex } from \"viem\";\nimport { z } from \"zod\";\n\nexport const KmsInfoSchema = z\n .object({\n id: z.string(),\n slug: z.string().nullable(),\n url: z.string(),\n version: z.string(),\n chain_id: z.number().nullable(),\n kms_contract_address: z\n .string()\n .nullable()\n .transform((val) => val as Address),\n gateway_app_id: z\n .string()\n .nullable()\n .transform((val) => val as Hex),\n })\n .passthrough();\n\nexport type KmsInfo = z.infer<typeof KmsInfoSchema>;\n","import { z } from \"zod\";\nimport { type Client, type SafeResult } from \"../client\";\nimport { KmsInfoSchema } from \"../types/kms_info\";\nimport { ActionParameters, ActionReturnType } from \"../types/common\";\n\n/**\n * Get available teepods and their capacity information\n *\n * Returns a list of available teepods with their capacity and KMS information.\n *\n * @example\n * ```typescript\n * import { createClient, getAvailableNodes } from '@phala/cloud'\n *\n * const client = createClient({ apiKey: 'your-api-key' })\n * const result = await getAvailableNodes(client)\n * // Output: { tier: 'free', capacity: { ... }, nodes: [...], kms_list: [...] }\n * ```\n *\n * ## Returns\n *\n * `AvailableNodes | unknown`\n *\n * List of available teepods and their capacity. Return type depends on schema parameter.\n *\n * ## Parameters\n *\n * ### parameters (optional)\n * - **Type:** `GetAvailableNodesParameters`\n *\n * Optional behavior parameters for schema validation.\n *\n * ```typescript\n * // Use default schema\n * const result = await getAvailableNodes(client)\n *\n * // Return raw data without validation\n * const raw = await getAvailableNodes(client, { schema: false })\n *\n * // Use custom schema\n * const customSchema = z.object({ tier: z.string() })\n * const custom = await getAvailableNodes(client, { schema: customSchema })\n * ```\n *\n * ## Safe Version\n *\n * Use `safeGetAvailableNodes` for error handling without exceptions:\n *\n * ```typescript\n * import { safeGetAvailableNodes } from '@phala/cloud'\n *\n * const result = await safeGetAvailableNodes(client)\n * if (result.success) {\n * console.log(result.data.tier)\n * } else {\n * if (\"isRequestError\" in result.error) {\n * console.error(`HTTP ${result.error.status}: ${result.error.message}`)\n * } else {\n * console.error(`Validation error: ${result.error.issues}`)\n * }\n * }\n * ```\n */\n\nexport const AvailableOSImageSchema = z\n .object({\n name: z.string(),\n is_dev: z.boolean(),\n version: z.tuple([z.number(), z.number(), z.number()]),\n os_image_hash: z.string().nullable().optional(),\n })\n .passthrough();\n\nexport const TeepodCapacitySchema = z\n .object({\n teepod_id: z.number(),\n name: z.string(),\n listed: z.boolean(),\n resource_score: z.number(),\n remaining_vcpu: z.number(),\n remaining_memory: z.number(),\n remaining_cvm_slots: z.number(),\n images: z.array(AvailableOSImageSchema),\n dedicated_for_team_id: z.number().nullable().optional(),\n support_onchain_kms: z.boolean().optional(),\n fmspc: z.string().nullable().optional(),\n device_id: z.string().nullable().optional(),\n })\n .passthrough();\n\nexport const ResourceThresholdSchema = z\n .object({\n max_instances: z.number().nullable().optional(),\n max_vcpu: z.number().nullable().optional(),\n max_memory: z.number().nullable().optional(),\n max_disk: z.number().nullable().optional(),\n })\n .passthrough();\n\nexport const AvailableNodesSchema = z\n .object({\n tier: z.string(), // TeamTier is string enum\n capacity: ResourceThresholdSchema,\n nodes: z.array(TeepodCapacitySchema),\n kms_list: z.array(KmsInfoSchema),\n })\n .passthrough();\n\nexport type AvailableOSImage = z.infer<typeof AvailableOSImageSchema>;\nexport type TeepodCapacity = z.infer<typeof TeepodCapacitySchema>;\nexport type ResourceThreshold = z.infer<typeof ResourceThresholdSchema>;\nexport type AvailableNodes = z.infer<typeof AvailableNodesSchema>;\n\nexport type GetAvailableNodesParameters<T = undefined> = ActionParameters<T>;\n\nexport type GetAvailableNodesReturnType<T = undefined> = ActionReturnType<AvailableNodes, T>;\n\nexport async function getAvailableNodes<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n parameters?: GetAvailableNodesParameters<T>,\n): Promise<GetAvailableNodesReturnType<T>> {\n const response = await client.get(\"/teepods/available\");\n\n if (parameters?.schema === false) {\n return response as GetAvailableNodesReturnType<T>;\n }\n\n const schema = (parameters?.schema || AvailableNodesSchema) as z.ZodSchema;\n return schema.parse(response) as GetAvailableNodesReturnType<T>;\n}\n\nexport async function safeGetAvailableNodes<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n parameters?: GetAvailableNodesParameters<T>,\n): Promise<SafeResult<GetAvailableNodesReturnType<T>>> {\n const httpResult = await client.safeGet(\"/teepods/available\");\n\n if (!httpResult.success) {\n return httpResult as SafeResult<GetAvailableNodesReturnType<T>>;\n }\n\n if (parameters?.schema === false) {\n return { success: true, data: httpResult.data } as SafeResult<GetAvailableNodesReturnType<T>>;\n }\n\n const schema = (parameters?.schema || AvailableNodesSchema) as z.ZodSchema;\n return schema.safeParse(httpResult.data) as SafeResult<GetAvailableNodesReturnType<T>>;\n}\n","import { z } from \"zod\";\nimport { type Client, type SafeResult } from \"../client\";\nimport { ActionParameters, ActionReturnType } from \"../types/common\";\nimport { validateActionParameters, safeValidateActionParameters } from \"../utils\";\n\n/**\n * Provision a CVM (Confidential Virtual Machine)\n *\n * This action provisions a new CVM on a specified node, returning the app_id, encryption public key, and other metadata required for secure deployment.\n *\n * @example\n * ```typescript\n * import { createClient, getAvailableNodes, provisionCvm } from '@phala/cloud'\n *\n * const client = createClient();\n * const nodes = await getAvailableNodes(client);\n * const node = nodes.nodes[0];\n *\n * const docker_compose = `\n *version: '3'\n *services:\n * demo:\n * image: leechael/phala-cloud-bun-starter:latest\n * container_name: demo\n * ports:\n * - \"3000:3000\"\n * volumes:\n * - /var/run/tappd.sock:/var/run/tappd.sock\n *`;\n *\n * const app_compose = {\n * name: 'my-app',\n * node_id: node.node_id,\n * image: node.images[0].name,\n * vcpu: 1,\n * memory: 1024,\n * disk_size: 10,\n * compose_file: {\n * docker_compose_file: docker_compose,\n * name: 'my-app',\n * },\n * };\n *\n * const result = await provisionCvm(client, app_compose);\n * console.log(result.app_id);\n * ```\n *\n * ## Safe Version\n *\n * Use `safeProvisionCvm` for error handling without exceptions:\n *\n * ```typescript\n * const result = await safeProvisionCvm(client, app_compose);\n * if (result.success) {\n * console.log(result.data.app_id);\n * } else {\n * console.error('Failed to provision CVM:', result.error.message);\n * }\n * ```\n */\n\n// Zod schema definition (align with backend, use .optional()/.nullable() for optional fields)\nexport const ProvisionCvmSchema = z\n .object({\n app_id: z.string().nullable().optional(),\n app_env_encrypt_pubkey: z.string().nullable().optional(),\n compose_hash: z.string(),\n fmspc: z.string().nullable().optional(),\n device_id: z.string().nullable().optional(),\n os_image_hash: z.string().nullable().optional(),\n node_id: z.number().nullable().optional(), // Transformed from teepod_id in response\n })\n .passthrough();\n\nexport type ProvisionCvm = z.infer<typeof ProvisionCvmSchema>;\n\n// Request schema (for reference, not used directly in function signature)\nexport const ProvisionCvmRequestSchema = z\n .object({\n node_id: z.number().optional(), // recommended\n teepod_id: z.number().optional(), // deprecated, for compatibility\n name: z.string(),\n image: z.string(),\n vcpu: z.number(),\n memory: z.number(),\n disk_size: z.number(),\n compose_file: z.object({\n allowed_envs: z.array(z.string()).optional(),\n pre_launch_script: z.string().optional(),\n docker_compose_file: z.string().optional(),\n name: z.string().optional(),\n kms_enabled: z.boolean().optional(),\n public_logs: z.boolean().optional(),\n public_sysinfo: z.boolean().optional(),\n gateway_enabled: z.boolean().optional(), // recommended\n tproxy_enabled: z.boolean().optional(), // deprecated, for compatibility\n }),\n listed: z.boolean().optional(),\n instance_type: z.string().nullable().optional(),\n kms_id: z.string().optional(),\n env_keys: z.array(z.string()).optional(),\n })\n .passthrough();\n\nexport type ProvisionCvmRequest = z.infer<typeof ProvisionCvmRequestSchema> & {\n node_id?: number; // recommended\n teepod_id?: number; // deprecated\n compose_file?: {\n gateway_enabled?: boolean; // recommended\n tproxy_enabled?: boolean; // deprecated\n [key: string]: unknown;\n };\n};\n\nexport type ProvisionCvmParameters<T = undefined> = ActionParameters<T>;\n\nexport type ProvisionCvmReturnType<T = undefined> = ActionReturnType<ProvisionCvm, T>;\n\nfunction autofillComposeFileName(appCompose: ProvisionCvmRequest): ProvisionCvmRequest {\n if (appCompose.compose_file && !appCompose.compose_file.name) {\n return {\n ...appCompose,\n compose_file: {\n ...appCompose.compose_file,\n name: appCompose.name,\n },\n };\n }\n return appCompose;\n}\n\nfunction handleGatewayCompatibility(appCompose: ProvisionCvmRequest): ProvisionCvmRequest {\n if (!appCompose.compose_file) {\n return appCompose;\n }\n\n const composeFile = { ...appCompose.compose_file };\n\n // If both are provided, prefer gateway_enabled\n if (\n typeof composeFile.gateway_enabled === \"boolean\" &&\n typeof composeFile.tproxy_enabled === \"boolean\"\n ) {\n delete composeFile.tproxy_enabled;\n }\n // If only tproxy_enabled is provided, convert to gateway_enabled and warn\n else if (\n typeof composeFile.tproxy_enabled === \"boolean\" &&\n typeof composeFile.gateway_enabled === \"undefined\"\n ) {\n composeFile.gateway_enabled = composeFile.tproxy_enabled;\n delete composeFile.tproxy_enabled;\n if (typeof window !== \"undefined\" ? window.console : globalThis.console) {\n console.warn(\n \"[phala/cloud] tproxy_enabled is deprecated, please use gateway_enabled instead. See docs for migration.\",\n );\n }\n }\n\n return {\n ...appCompose,\n compose_file: composeFile,\n };\n}\n\nfunction transformResponse(data: unknown, isDefaultSchema: boolean): unknown {\n if (!isDefaultSchema || !data || typeof data !== \"object\") {\n return data;\n }\n\n if (data && typeof data === \"object\" && \"teepod_id\" in data) {\n const { teepod_id, ...rest } = data as Record<string, unknown> & { teepod_id: unknown };\n return { ...rest, node_id: teepod_id };\n }\n\n return data;\n}\n\nexport async function provisionCvm<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n appCompose: ProvisionCvmRequest,\n parameters?: ProvisionCvmParameters<T>,\n): Promise<ProvisionCvmReturnType<T>> {\n validateActionParameters(parameters);\n\n const body = handleGatewayCompatibility(autofillComposeFileName(appCompose));\n let requestBody = { ...body };\n if (typeof body.node_id === \"number\") {\n requestBody = { ...body, teepod_id: body.node_id };\n delete requestBody.node_id;\n } else if (typeof body.teepod_id === \"number\") {\n console.warn(\"[phala/cloud] teepod_id is deprecated, please use node_id instead.\");\n }\n\n const response = await client.post(\"/cvms/provision\", requestBody);\n\n const isDefaultSchema = parameters?.schema === undefined;\n const transformedData = transformResponse(response, isDefaultSchema);\n\n if (parameters?.schema === false) {\n return transformedData as ProvisionCvmReturnType<T>;\n }\n\n const usedSchema = (parameters?.schema || ProvisionCvmSchema) as z.ZodSchema;\n return usedSchema.parse(transformedData) as ProvisionCvmReturnType<T>;\n}\n\n// Safe version (returns SafeResult)\nexport async function safeProvisionCvm<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n appCompose: ProvisionCvmRequest,\n parameters?: ProvisionCvmParameters<T>,\n): Promise<SafeResult<ProvisionCvmReturnType<T>>> {\n const parameterValidationError = safeValidateActionParameters(parameters);\n if (parameterValidationError) {\n return parameterValidationError as SafeResult<ProvisionCvmReturnType<T>>;\n }\n\n const schema: z.ZodSchema | false | undefined = parameters?.schema;\n const body = handleGatewayCompatibility(autofillComposeFileName(appCompose));\n let requestBody = { ...body };\n if (typeof body.node_id === \"number\") {\n requestBody = { ...body, teepod_id: body.node_id };\n delete requestBody.node_id;\n } else if (typeof body.teepod_id === \"number\") {\n console.warn(\"[phala/cloud] teepod_id is deprecated, please use node_id instead.\");\n }\n const httpResult = await client.safePost(\"/cvms/provision\", requestBody);\n if (!httpResult.success) {\n return httpResult as SafeResult<ProvisionCvmReturnType<T>>;\n }\n\n if (schema === false) {\n return { success: true, data: httpResult.data } as SafeResult<ProvisionCvmReturnType<T>>;\n }\n\n const isDefaultSchema = !schema;\n const usedSchema = (schema || ProvisionCvmSchema) as z.ZodSchema;\n const transformResult = usedSchema.safeParse(transformResponse(httpResult.data, isDefaultSchema));\n return transformResult as SafeResult<ProvisionCvmReturnType<T>>;\n}\n","import { z } from \"zod\";\nimport { type Client, type SafeResult } from \"../client\";\nimport { isHex } from \"viem\";\nimport { ActionParameters, ActionReturnType } from \"../types/common\";\nimport { validateActionParameters, safeValidateActionParameters } from \"../utils\";\n\n/**\n * Commit CVM Provision (Create CVM from provisioned data)\n *\n * This action creates a CVM using previously provisioned data and encrypted environment variables.\n * It should be called after `provisionCvm` to complete the CVM deployment process.\n *\n * @example\n * ```typescript\n * import { createClient, provisionCvm, commitCvmProvision } from '@phala/cloud'\n *\n * const client = createClient();\n *\n * // First, provision the CVM\n * const provision = await provisionCvm(client, appCompose);\n *\n * // Then, commit the provision with encrypted environment variables\n * const cvm = await commitCvmProvision(client, {\n * encrypted_env: \"hex-encoded-encrypted-environment-data\", // String, not array\n * app_id: provision.app_id,\n * compose_hash: provision.compose_hash,\n * kms_id: \"your-kms-id\",\n * contract_address: \"0x123...\",\n * deployer_address: \"0x456...\"\n * });\n *\n * console.log(cvm.id);\n * ```\n *\n * ## Returns\n *\n * `CommitCvmProvision | unknown`\n *\n * The created CVM details including id, name, status, and other metadata. Return type depends on schema parameter.\n *\n * ## Parameters\n *\n * ### schema (optional)\n *\n * - **Type:** `ZodSchema | false`\n * - **Default:** `CommitCvmProvisionSchema`\n *\n * Schema to validate the response. Use `false` to return raw data without validation.\n *\n * ```typescript\n * // Use default schema\n * const result = await commitCvmProvision(client, payload)\n *\n * // Return raw data without validation\n * const raw = await commitCvmProvision(client, payload, { schema: false })\n *\n * // Use custom schema\n * const customSchema = z.object({ id: z.number(), name: z.string() })\n * const custom = await commitCvmProvision(client, payload, { schema: customSchema })\n * ```\n *\n * ## Safe Version\n *\n * Use `safeCommitCvmProvision` for error handling without exceptions:\n *\n * ```typescript\n * import { safeCommitCvmProvision } from '@phala/cloud'\n *\n * const result = await safeCommitCvmProvision(client, payload)\n * if (result.success) {\n * console.log(result.data)\n * } else {\n * if (\"isRequestError\" in result.error) {\n * console.error(`HTTP ${result.error.status}: ${result.error.message}`)\n * } else {\n * console.error(`Validation error: ${result.error.issues}`)\n * }\n * }\n * ```\n */\n\n// Zod schema definition (align with backend VMSchema)\nexport const CommitCvmProvisionSchema = z\n .object({\n id: z.number(),\n name: z.string(),\n status: z.string(),\n teepod_id: z.number(),\n teepod: z\n .object({\n id: z.number(),\n name: z.string(),\n })\n .nullable(),\n user_id: z.number().nullable(),\n app_id: z.string().nullable(),\n vm_uuid: z.string().nullable(),\n instance_id: z.string().nullable(),\n app_url: z.string().nullable(),\n base_image: z.string().nullable(),\n vcpu: z.number(),\n memory: z.number(),\n disk_size: z.number(),\n manifest_version: z.number().nullable(),\n version: z.string().nullable(),\n runner: z.string().nullable(),\n docker_compose_file: z.string().nullable(),\n features: z.array(z.string()).nullable(),\n created_at: z.string(),\n encrypted_env_pubkey: z.string().nullable().optional(),\n app_auth_contract_address: z.string().nullable().optional(),\n deployer_address: z.string().nullable().optional(),\n })\n .passthrough();\n\nexport type CommitCvmProvision = z.infer<typeof CommitCvmProvisionSchema>;\n\n// Request schema\nexport const CommitCvmProvisionRequestSchema = z\n .object({\n encrypted_env: z.string().optional().nullable(),\n app_id: z.string(),\n compose_hash: z.string().optional(),\n kms_id: z.string().optional(),\n contract_address: z.string().optional(),\n deployer_address: z.string().optional(),\n env_keys: z.array(z.string()).optional().nullable(),\n })\n .passthrough();\n\nexport type CommitCvmProvisionRequest = z.infer<typeof CommitCvmProvisionRequestSchema>;\n\nexport type CommitCvmProvisionParameters<T = undefined> = ActionParameters<T>;\n\nexport type CommitCvmProvisionReturnType<T = undefined> = ActionReturnType<CommitCvmProvision, T>;\n\nexport async function commitCvmProvision<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n payload: CommitCvmProvisionRequest,\n parameters?: CommitCvmProvisionParameters<T>,\n): Promise<CommitCvmProvisionReturnType<T>> {\n validateActionParameters(parameters);\n\n const response = await client.post(\"/cvms\", payload);\n\n if (parameters?.schema === false) {\n return response as CommitCvmProvisionReturnType<T>;\n }\n\n const schema = (parameters?.schema || CommitCvmProvisionSchema) as z.ZodSchema;\n return schema.parse(response) as CommitCvmProvisionReturnType<T>;\n}\n\n// Safe version (returns SafeResult)\nexport async function safeCommitCvmProvision<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n payload: CommitCvmProvisionRequest,\n parameters?: CommitCvmProvisionParameters<T>,\n): Promise<SafeResult<CommitCvmProvisionReturnType<T>>> {\n const parameterValidationError = safeValidateActionParameters(parameters);\n if (parameterValidationError) {\n return parameterValidationError as SafeResult<CommitCvmProvisionReturnType<T>>;\n }\n\n const httpResult = await client.safePost(\"/cvms\", payload);\n if (!httpResult.success) {\n return httpResult as SafeResult<CommitCvmProvisionReturnType<T>>;\n }\n\n if (parameters?.schema === false) {\n return { success: true, data: httpResult.data } as SafeResult<CommitCvmProvisionReturnType<T>>;\n }\n\n const schema = (parameters?.schema || CommitCvmProvisionSchema) as z.ZodSchema;\n const validationResult = schema.safeParse(httpResult.data);\n return validationResult as SafeResult<CommitCvmProvisionReturnType<T>>;\n}\n","import { z } from \"zod\";\nimport {\n type Chain,\n type Address,\n type Hash,\n type Hex,\n type TransactionReceipt,\n type PublicClient,\n type WalletClient,\n createPublicClient,\n createWalletClient,\n http,\n parseEventLogs,\n parseEther,\n} from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { type SafeResult } from \"../client\";\nimport {\n asHex,\n type NetworkClients,\n validateNetworkPrerequisites,\n type TransactionTracker,\n createTransactionTracker,\n type RetryOptions,\n executeTransactionWithRetry,\n type TransactionOptions,\n} from \"../utils\";\n\n/**\n * Deploy an App Auth contract through a KMS (Key Management Service) factory.\n *\n * This function enables secure deployment of App Auth contracts that are registered\n * with a TEE (Trusted Execution Environment) KMS system. The deployed contract\n * provides authentication and authorization capabilities for applications running\n * in trusted environments.\n *\n * @group Actions\n * @since 0.1.0\n *\n * ## Usage\n *\n * ```typescript\n * import { deployAppAuth, getComposeHash } from '@phala/cloud'\n * import { base } from 'viem/chains'\n *\n * // Calculate compose hash from your app compose configuration\n * const appCompose = { services: { myapp: { image: \"my-image\" } } }\n * const composeHash = getComposeHash(appCompose)\n *\n * // Mode 1: Using private key (simple)\n * const result = await deployAppAuth({\n * chain: base,\n * kmsContractAddress: \"0x1234567890abcdef1234567890abcdef12345678\",\n * privateKey: \"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef\",\n * deviceId: \"1234567890abcdef1234567890abcdef\", // Specifying deviceId automatically sets allowAnyDevice to false\n * composeHash: composeHash,\n * minBalance: \"0.01\" // Minimum ETH balance required\n * })\n *\n * // Mode 2: Using custom wallet client (multi-sig, wallet providers)\n * const result2 = await deployAppAuth({\n * chain: base, // Required to create publicClient\n * kmsContractAddress: \"0x1234567890abcdef1234567890abcdef12345678\",\n * walletClient: myMultiSigWallet, // Your custom wallet client\n * deviceId: \"1234567890abcdef1234567890abcdef\", // Specifying deviceId automatically sets allowAnyDevice to false\n * composeHash: composeHash,\n * skipPrerequisiteChecks: true // Skip if using custom wallet\n * })\n *\n * // Mode 3: Full custom (both clients provided, chain optional)\n * const result3 = await deployAppAuth({\n * // chain is optional when both clients are provided\n * kmsContractAddress: \"0x1234567890abcdef1234567890abcdef12345678\",\n * walletClient: myCustomWallet,\n * publicClient: myCustomPublicClient,\n * allowAnyDevice: true, // Allow any device when no specific deviceId is provided\n * skipPrerequisiteChecks: true\n * })\n *\n * console.log(`App deployed with ID: ${result.appId}`)\n * console.log(`Contract address: ${result.appAuthAddress}`)\n * // Output: { appId: \"0x...\", appAuthAddress: \"0x...\", transactionHash: \"0x...\" }\n * ```\n *\n * ## Returns\n *\n * `DeployAppAuth | unknown`\n *\n * Information about the deployed App Auth contract including the generated App ID,\n * contract address, and transaction hash. Return type depends on schema parameter.\n *\n * ## Parameters\n *\n * ### request (required)\n *\n * - **Type:** `DeployAppAuthRequest`\n *\n * Configuration object for the App Auth contract deployment. Contains the following fields:\n *\n * #### chain (conditionally required)\n * - **Type:** `Chain` - Viem chain configuration object\n * - **Description:** Blockchain network configuration. Required when creating publicClient or walletClient. Optional when both publicClient and walletClient are provided.\n * - **Usage:** Used to create missing clients (publicClient or walletClient) when not provided\n * - **Example:** `import { base } from 'viem/chains'`\n *\n * #### kmsContractAddress (required)\n * - **Type:** `Address` - Ethereum contract address\n * - **Description:** Address of the KMS factory contract that will deploy the App Auth contract\n * - **Example:** `\"0x1234567890abcdef1234567890abcdef12345678\"`\n *\n * #### privateKey (conditionally required)\n * - **Type:** `Hex` - Private key hex string\n * - **Description:** Private key of the deployer account (Mode 1). Either this OR `walletClient` must be provided, but not both.\n * - **Security:** Keep this secure and never expose in client-side code\n * - **Example:** `\"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef\"`\n *\n * #### walletClient (conditionally required)\n * - **Type:** `WalletClient` - Viem wallet client instance\n * - **Description:** Custom wallet client for advanced use cases (Mode 2). Supports multi-signature wallets, wallet providers, hardware wallets, etc. Either this OR `privateKey` must be provided, but not both.\n * - **Example:** Multi-sig wallet, hardware wallet, or any custom viem WalletClient\n *\n * #### publicClient (optional)\n * - **Type:** `PublicClient` - Viem public client instance\n * - **Description:** Custom public client for blockchain reads. If not provided, will create a default one using the chain configuration.\n * - **Usage:** Useful for custom RPC providers or caching strategies\n *\n * #### allowAnyDevice (optional)\n * - **Type:** `boolean` - Default: `false`\n * - **Description:** Controls device access management for app deployment. When `false`, only the specified device (via `deviceId`) can deploy applications. When `true`, any device can deploy applications.\n * - **Usage:** Automatically set to `false` when `deviceId` is specified (non-default). Set to `true` explicitly only when you want to allow any device to deploy.\n *\n * #### deviceId (optional)\n * - **Type:** `string` - 32-byte hex string (with or without 0x prefix)\n * - **Default:** `\"0000000000000000000000000000000000000000000000000000000000000000\"`\n * - **Description:** Device management identifier that controls which device is authorized to deploy applications. When specified (non-default), automatically sets `allowAnyDevice` to `false`.\n * - **Format:** Automatically converted to proper hex format using `asHex()` utility\n * - **Example:** `\"1234567890abcdef1234567890abcdef\"` → `\"0x1234567890abcdef1234567890abcdef00000000000000000000000000000000\"`\n *\n * #### composeHash (optional)\n * - **Type:** `string` - 32-byte hex string (with or without 0x prefix)\n * - **Default:** `\"0000000000000000000000000000000000000000000000000000000000000000\"`\n * - **Description:** Hash mapping of the app compose configuration version for integrity verification and version tracking. This creates a mapping between the deployed app and its specific compose configuration.\n * - **Calculation:** Can be calculated using `getComposeHash(appCompose)` utility function\n * - **Format:** Automatically converted to proper hex format using `asHex()` utility\n * - **Example:** `\"abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890\"`\n *\n * #### disableUpgrades (optional)\n * - **Type:** `boolean` - Default: `false`\n * - **Description:** Whether to disable contract upgrades after deployment\n * - **Security:** Set to `true` for immutable contracts, `false` to allow future upgrades\n *\n * #### skipPrerequisiteChecks (optional)\n * - **Type:** `boolean` - Default: `false`\n * - **Description:** Whether to skip network and balance prerequisite checks before deployment\n * - **Usage:** Set to `true` when using custom wallet clients that handle their own validation\n *\n * #### minBalance (optional)\n * - **Type:** `string` - ETH amount as string\n * - **Default:** `\"0.001\"` (0.001 ETH)\n * - **Description:** Minimum ETH balance required in the deployer account\n * - **Example:** `\"0.01\"` for 0.01 ETH minimum balance\n *\n * ### schema (optional)\n *\n * - **Type:** `ZodSchema | false`\n * - **Default:** `DeployAppAuthSchema`\n *\n * Schema to validate the response. Use `false` to return raw data without validation.\n *\n * ```typescript\n * // Use default schema\n * const result = await deployAppAuth(request)\n *\n * // Return raw data without validation\n * const raw = await deployAppAuth(request, { schema: false })\n *\n * // Use custom schema\n * const customSchema = z.object({ appId: z.string(), appAuthAddress: z.string() })\n * const custom = await deployAppAuth(request, { schema: customSchema })\n *\n * // Multi-signature wallet example\n * import { createWalletClient, custom } from 'viem'\n * const multiSigWallet = createWalletClient({\n * account: multiSigAccount,\n * chain: base,\n * transport: custom(window.ethereum)\n * })\n * const result = await deployAppAuth({\n * chain: base,\n * kmsContractAddress: \"0x...\",\n * walletClient: multiSigWallet,\n * skipPrerequisiteChecks: true\n * })\n * ```\n *\n * ## Safe Version\n *\n * Use `safeDeployAppAuth` for error handling without exceptions:\n *\n * ```typescript\n * import { safeDeployAppAuth } from '@phala/cloud'\n *\n * // Example with specific device (allowAnyDevice automatically set to false)\n * const result = await safeDeployAppAuth({\n * chain: base,\n * kmsContractAddress: \"0x...\",\n * privateKey: \"0x...\",\n * deviceId: \"1234567890abcdef1234567890abcdef\" // Automatically sets allowAnyDevice to false\n * })\n *\n * // Example allowing any device\n * const result2 = await safeDeployAppAuth({\n * chain: base,\n * kmsContractAddress: \"0x...\",\n * privateKey: \"0x...\",\n * allowAnyDevice: true // Explicitly allow any device\n * })\n *\n * if (result.success) {\n * console.log(`App Auth deployed at: ${result.data.appAuthAddress}`)\n * } else {\n * console.error(`Deployment failed: ${result.error.message}`)\n * }\n * ```\n */\n\n// KMS Auth ABI for deployAndRegisterApp function\nconst kmsAuthAbi = [\n {\n inputs: [\n { name: \"deployer\", type: \"address\" },\n { name: \"disableUpgrades\", type: \"bool\" },\n { name: \"allowAnyDevice\", type: \"bool\" },\n { name: \"deviceId\", type: \"bytes32\" },\n { name: \"composeHash\", type: \"bytes32\" },\n ],\n name: \"deployAndRegisterApp\",\n outputs: [{ name: \"\", type: \"address\" }],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"appId\", type: \"address\", indexed: true },\n { name: \"deployer\", type: \"address\", indexed: true },\n ],\n name: \"AppDeployedViaFactory\",\n type: \"event\",\n anonymous: false,\n },\n {\n inputs: [{ name: \"appId\", type: \"address\", indexed: false }],\n name: \"AppRegistered\",\n type: \"event\",\n anonymous: false,\n },\n] as const;\n\n// Basic request schema without complex transforms\nconst DeployAppAuthRequestBaseSchema = z\n .object({\n // Chain configuration (conditionally required)\n chain: z.unknown().optional(),\n\n // Contract configuration (required)\n kmsContractAddress: z.string(),\n\n // Authentication mode: either privateKey OR walletClient (required, mutually exclusive)\n privateKey: z.string().optional(),\n walletClient: z.unknown().optional(),\n\n // Public client (optional, will create default if not provided)\n publicClient: z.unknown().optional(),\n\n // App configuration (optional)\n allowAnyDevice: z.boolean().optional().default(false),\n deviceId: z\n .string()\n .optional()\n .default(\"0000000000000000000000000000000000000000000000000000000000000000\"),\n composeHash: z\n .string()\n .optional()\n .default(\"0000000000000000000000000000000000000000000000000000000000000000\"),\n disableUpgrades: z.boolean().optional().default(false),\n\n // Validation configuration (optional)\n skipPrerequisiteChecks: z.boolean().optional().default(false),\n minBalance: z.string().optional(), // ETH amount as string, e.g., \"0.01\"\n })\n .passthrough();\n\n// Request schema with validation\nexport const DeployAppAuthRequestSchema = DeployAppAuthRequestBaseSchema.refine(\n (data) => {\n // Ensure either privateKey or walletClient is provided, but not both\n const hasPrivateKey = !!data.privateKey;\n const hasWalletClient = !!data.walletClient;\n return hasPrivateKey !== hasWalletClient; // XOR: exactly one should be true\n },\n {\n message: \"Either 'privateKey' or 'walletClient' must be provided, but not both\",\n path: [\"privateKey\", \"walletClient\"],\n },\n).refine(\n (data) => {\n // If both publicClient and walletClient are provided, chain is optional\n // Otherwise, chain is required to create the missing client\n const hasPublicClient = !!data.publicClient;\n const hasWalletClient = !!data.walletClient;\n const hasChain = !!data.chain;\n\n // If we have both clients, chain is optional\n if (hasPublicClient && hasWalletClient) {\n return true;\n }\n\n // If we're missing at least one client, we need chain to create it\n return hasChain;\n },\n {\n message: \"Chain is required when publicClient or walletClient is not provided\",\n path: [\"chain\"],\n },\n);\n\nexport type DeployAppAuthRequest = {\n chain?: Chain;\n kmsContractAddress: Address;\n privateKey?: Hex;\n walletClient?: WalletClient;\n publicClient?: PublicClient;\n allowAnyDevice?: boolean;\n deviceId?: string;\n composeHash?: string;\n disableUpgrades?: boolean;\n skipPrerequisiteChecks?: boolean;\n minBalance?: string;\n // Transaction control options\n timeout?: number;\n retryOptions?: RetryOptions;\n signal?: AbortSignal;\n // Progress callbacks\n onTransactionStateChange?: (state: TransactionTracker[\"status\"]) => void;\n onTransactionSubmitted?: (hash: Hash) => void;\n onTransactionConfirmed?: (receipt: TransactionReceipt) => void;\n};\n\n// Response schema for deployment result\nexport const DeployAppAuthSchema = z\n .object({\n appId: z.string(),\n appAuthAddress: z.string(),\n deployer: z.string(),\n transactionHash: z.string(),\n blockNumber: z.bigint().optional(),\n gasUsed: z.bigint().optional(),\n })\n .passthrough();\n\nexport type DeployAppAuth = z.infer<typeof DeployAppAuthSchema>;\n\n// Parameters type for optional configuration\nexport type DeployAppAuthParameters<T = undefined> = T extends z.ZodSchema\n ? { schema: T }\n : T extends false\n ? { schema: false }\n : { schema?: z.ZodSchema | false };\n\nexport type DeployAppAuthReturnType<T = undefined> = T extends z.ZodSchema\n ? z.infer<T>\n : T extends false\n ? unknown\n : DeployAppAuth;\n\n// Helper function to parse deployment result from transaction receipt\nfunction parseDeploymentResult(\n receipt: TransactionReceipt,\n deployer: Address,\n kmsContractAddress: Address,\n): DeployAppAuth {\n try {\n // Parse AppDeployedViaFactory event\n const logs = parseEventLogs({\n abi: kmsAuthAbi,\n eventName: \"AppDeployedViaFactory\",\n logs: receipt.logs,\n strict: false,\n });\n\n if (logs.length === 0) {\n // Check if transaction actually failed\n if (receipt.status === \"reverted\") {\n throw new Error(`Transaction failed: ${receipt.transactionHash}`);\n }\n\n throw new Error(\n `Transaction ${receipt.transactionHash} has no AppDeployedViaFactory events. The deployment failed. Status: ${receipt.status}. Found ${receipt.logs.length} logs.`,\n );\n }\n\n const deploymentEvent = logs[0];\n if (!deploymentEvent?.args) {\n throw new Error(\"Event has no data\");\n }\n\n const { appId, deployer: eventDeployer } = deploymentEvent.args;\n\n if (!appId) {\n throw new Error(\"Event missing appId\");\n }\n\n return {\n appId: appId as string,\n appAuthAddress: appId as Address,\n deployer: deployer,\n transactionHash: receipt.transactionHash,\n blockNumber: receipt.blockNumber,\n gasUsed: receipt.gasUsed,\n };\n } catch (error) {\n if (error instanceof Error) {\n throw error;\n }\n throw new Error(`Parse failed: ${error}`);\n }\n}\n\n// Standard version (throws on error)\nexport async function deployAppAuth<T extends z.ZodSchema | false | undefined = undefined>(\n request: DeployAppAuthRequest,\n parameters?: DeployAppAuthParameters<T>,\n): Promise<DeployAppAuthReturnType<T>> {\n // Validate request data\n const validatedRequest = DeployAppAuthRequestSchema.parse(request);\n\n const {\n chain,\n kmsContractAddress,\n privateKey,\n walletClient: providedWalletClient,\n publicClient: providedPublicClient,\n allowAnyDevice: rawAllowAnyDevice = false,\n deviceId = \"0000000000000000000000000000000000000000000000000000000000000000\",\n composeHash = \"0000000000000000000000000000000000000000000000000000000000000000\",\n disableUpgrades = false,\n skipPrerequisiteChecks = false,\n minBalance,\n timeout = 120000, // 2 minutes default\n retryOptions,\n signal,\n onTransactionStateChange,\n onTransactionSubmitted,\n onTransactionConfirmed,\n } = validatedRequest;\n\n // Auto-determine allowAnyDevice based on deviceId\n const defaultDeviceId = \"0000000000000000000000000000000000000000000000000000000000000000\";\n const hasSpecificDevice = deviceId !== defaultDeviceId && deviceId !== \"0x\" + defaultDeviceId;\n const allowAnyDevice = hasSpecificDevice ? false : rawAllowAnyDevice;\n\n // Create or use provided clients\n let publicClient: PublicClient;\n let walletClient: WalletClient;\n let deployerAddress: Address;\n let chainId: number;\n\n if (privateKey) {\n // Mode 1: Private key authentication\n const account = privateKeyToAccount(privateKey as Hex);\n\n // Use provided publicClient or create one (chain required if creating)\n if (providedPublicClient) {\n // Type guard for publicClient\n if (typeof providedPublicClient !== \"object\" || !providedPublicClient) {\n throw new Error(\"publicClient is invalid\");\n }\n publicClient = providedPublicClient as PublicClient;\n } else {\n if (!chain) {\n throw new Error(\"Chain required for publicClient\");\n }\n publicClient = createPublicClient({\n chain: chain as Chain,\n transport: http(),\n });\n }\n\n // Create walletClient (chain required)\n if (!chain) {\n throw new Error(\"Chain required for walletClient\");\n }\n walletClient = createWalletClient({\n account,\n chain: chain as Chain,\n transport: http(),\n });\n\n deployerAddress = account.address;\n chainId = (chain as Chain).id;\n } else if (providedWalletClient) {\n // Mode 2: Custom wallet client (multi-sig, wallet providers, etc.)\n // Type guard for walletClient\n if (typeof providedWalletClient !== \"object\" || !providedWalletClient) {\n throw new Error(\"walletClient is invalid\");\n }\n walletClient = providedWalletClient as WalletClient;\n\n // Use provided publicClient or create one (chain required if creating)\n if (providedPublicClient) {\n // Type guard for publicClient\n if (typeof providedPublicClient !== \"object\" || !providedPublicClient) {\n throw new Error(\"publicClient is invalid\");\n }\n publicClient = providedPublicClient as PublicClient;\n } else {\n if (!chain) {\n throw new Error(\"Chain required for publicClient\");\n }\n publicClient = createPublicClient({\n chain: chain as Chain,\n transport: http(),\n });\n }\n\n // Get deployer address from wallet client\n if (!walletClient.account?.address) {\n throw new Error(\"WalletClient needs an account\");\n }\n deployerAddress = walletClient.account.address;\n\n // Get chainId from chain or walletClient\n if (chain) {\n chainId = (chain as Chain).id;\n } else {\n chainId = await walletClient.getChainId();\n }\n } else {\n throw new Error(\"Need privateKey or walletClient\");\n }\n\n // Create NetworkClients for prerequisite checks and transaction execution\n const networkClients: NetworkClients = {\n publicClient,\n walletClient,\n address: deployerAddress,\n chainId: chainId,\n };\n\n // Create transaction tracker for better state management\n const transactionTracker = createTransactionTracker();\n\n // Set up state change callback\n if (onTransactionStateChange && typeof onTransactionStateChange === \"function\") {\n const pollStatus = (): void => {\n (onTransactionStateChange as (state: TransactionTracker[\"status\"]) => void)(\n transactionTracker.status,\n );\n if (!transactionTracker.isComplete) {\n setTimeout(pollStatus, 100); // Poll every 100ms\n }\n };\n // Start polling after a small delay to allow tracker initialization\n setTimeout(pollStatus, 10);\n }\n\n // Perform prerequisite checks\n if (!skipPrerequisiteChecks) {\n const requirements = {\n targetChainId: chainId,\n minBalance: minBalance ? parseEther(minBalance) : parseEther(\"0.001\"), // Default 0.001 ETH\n };\n\n const validation = await validateNetworkPrerequisites(networkClients, requirements);\n\n if (!validation.networkValid) {\n throw new Error(\n `Wrong network. Need chain ${requirements.targetChainId}, got ${validation.details.currentChainId}`,\n );\n }\n\n if (!validation.balanceValid) {\n const requiredEth = Number(requirements.minBalance) / 1e18;\n const currentEth = Number(validation.details.balance) / 1e18;\n throw new Error(`Not enough ETH. Need ${requiredEth}, have ${currentEth.toFixed(6)}`);\n }\n }\n\n // Convert string parameters to proper hex format with padding\n const deviceIdHex = asHex(deviceId);\n const composeHashHex = asHex(composeHash);\n\n // Ensure 32-byte (64-character) hex strings with 0x prefix\n const deviceIdBytes = `0x${deviceIdHex.slice(2).padEnd(64, \"0\")}` as Hash;\n const composeHashBytes = `0x${composeHashHex.slice(2).padEnd(64, \"0\")}` as Hash;\n\n // Define the deployment operation\n const deployOperation = async (clients: NetworkClients): Promise<Hash> => {\n // Verify KMS contract exists at the given address\n try {\n const code = await clients.publicClient.getCode({ address: kmsContractAddress as Address });\n if (!code || code === \"0x\") {\n throw new Error(`No contract at ${kmsContractAddress}`);\n }\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"No contract at\")) {\n throw error;\n }\n // Silently continue if contract verification fails for other reasons\n // (e.g., RPC issues, network problems)\n }\n\n const contractCall = {\n address: kmsContractAddress as Address,\n abi: kmsAuthAbi,\n functionName: \"deployAndRegisterApp\" as const,\n args: [\n clients.address,\n disableUpgrades,\n allowAnyDevice,\n deviceIdBytes,\n composeHashBytes,\n ] as const,\n account: clients.walletClient.account || clients.address,\n chain: (chain as Chain) || null,\n };\n\n return await clients.walletClient.writeContract(contractCall);\n };\n\n // Execute transaction with enhanced features\n const transactionResult = retryOptions\n ? await executeTransactionWithRetry(\n deployOperation,\n networkClients,\n [],\n {\n timeout: timeout as number,\n confirmations: 1,\n onSubmitted: onTransactionSubmitted as ((hash: Hash) => void) | undefined,\n onConfirmed: onTransactionConfirmed as\n | ((receipt: TransactionReceipt) => void)\n | undefined,\n signal: signal as AbortSignal | undefined,\n } as TransactionOptions & { signal?: AbortSignal },\n retryOptions,\n )\n : await transactionTracker.execute(deployOperation, networkClients, [], {\n timeout: timeout as number,\n confirmations: 1,\n onSubmitted: onTransactionSubmitted as ((hash: Hash) => void) | undefined,\n onConfirmed: onTransactionConfirmed as ((receipt: TransactionReceipt) => void) | undefined,\n signal: signal as AbortSignal | undefined,\n } as TransactionOptions & { signal?: AbortSignal });\n\n // Parse result from receipt\n const result = parseDeploymentResult(\n transactionResult.receipt,\n deployerAddress,\n kmsContractAddress as Address,\n );\n\n if (parameters?.schema === false) {\n return result as DeployAppAuthReturnType<T>;\n }\n\n const schema = (parameters?.schema || DeployAppAuthSchema) as z.ZodSchema;\n return schema.parse(result) as DeployAppAuthReturnType<T>;\n}\n\n/**\n * Enhanced safe version with transaction tracking capabilities\n */\nexport type SafeDeployAppAuthResult<T = undefined> =\n | {\n success: true;\n data: DeployAppAuthReturnType<T>;\n }\n | {\n success: false;\n error: { isRequestError: true; message: string; status: number; detail: string };\n };\n\n// Safe version (returns SafeResult with optional transaction tracker)\nexport async function safeDeployAppAuth<T extends z.ZodSchema | false | undefined = undefined>(\n request: DeployAppAuthRequest,\n parameters?: DeployAppAuthParameters<T>,\n): Promise<SafeDeployAppAuthResult<T>> {\n try {\n const result = await deployAppAuth(request, parameters);\n return { success: true, data: result };\n } catch (error) {\n // Create a consistent error format for blockchain operations\n const errorMessage = error instanceof Error ? error.message : \"Unknown deployment error\";\n const requestError = {\n isRequestError: true as const,\n message: errorMessage,\n status: 500, // Use 500 for blockchain errors since they're not HTTP errors\n detail: errorMessage,\n };\n return {\n success: false,\n error: requestError,\n };\n }\n}\n","import { z } from \"zod\";\nimport {\n type Chain,\n type Address,\n type Hash,\n type Hex,\n type TransactionReceipt,\n type PublicClient,\n type WalletClient,\n createPublicClient,\n createWalletClient,\n http,\n parseEventLogs,\n parseEther,\n} from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { type SafeResult } from \"../client\";\nimport {\n asHex,\n type NetworkClients,\n validateNetworkPrerequisites,\n type TransactionTracker,\n createTransactionTracker,\n type RetryOptions,\n executeTransactionWithRetry,\n type TransactionOptions,\n} from \"../utils\";\n\n/**\n * Add a compose hash to an App Auth contract through KMS lookup.\n *\n * This function adds a compose hash to an existing App Auth contract by:\n * 1. Looking up the App Auth contract address from the KMS contract using the app ID\n * 2. Calling the addComposeHash function on the App Auth contract\n * 3. Handling the transaction lifecycle with progress callbacks and retry mechanisms\n *\n * @group Actions\n * @since 0.1.0\n *\n * ## Usage\n *\n * ```typescript\n * import { addComposeHash, getComposeHash } from '@phala/cloud'\n * import { base } from 'viem/chains'\n *\n * // Calculate compose hash from your app compose configuration\n * const appCompose = { services: { myapp: { image: \"my-updated-image\" } } }\n * const composeHash = getComposeHash(appCompose)\n *\n * // Mode 1: Using private key (simple)\n * const result = await addComposeHash({\n * chain: base,\n * kmsContractAddress: \"0x1234567890abcdef1234567890abcdef12345678\",\n * appId: \"0xabcdef1234567890abcdef1234567890abcdef12\",\n * privateKey: \"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef\",\n * composeHash: composeHash,\n * minBalance: \"0.01\" // Minimum ETH balance required\n * })\n *\n * // Mode 2: Using custom wallet client\n * const result2 = await addComposeHash({\n * chain: base,\n * kmsContractAddress: \"0x1234567890abcdef1234567890abcdef12345678\",\n * appId: \"0xabcdef1234567890abcdef1234567890abcdef12\",\n * walletClient: myWallet,\n * composeHash: composeHash,\n * onTransactionSubmitted: (hash) => console.log('Transaction submitted:', hash),\n * })\n *\n * // Mode 3: Full custom with retry options\n * const result3 = await addComposeHash({\n * kmsContractAddress: \"0x1234567890abcdef1234567890abcdef12345678\",\n * appId: \"0xabcdef1234567890abcdef1234567890abcdef12\",\n * walletClient: myCustomWallet,\n * publicClient: myCustomPublicClient,\n * composeHash: composeHash,\n * retryOptions: { maxRetries: 3, initialDelay: 1000 },\n * timeout: 120000\n * })\n *\n * console.log(`Compose hash added: ${result.composeHash}`)\n * console.log(`Transaction hash: ${result.transactionHash}`)\n * // Output: { composeHash: \"0x...\", appAuthAddress: \"0x...\", transactionHash: \"0x...\" }\n * ```\n *\n * ## Returns\n *\n * `AddComposeHash | unknown`\n *\n * Information about the added compose hash including the compose hash value,\n * App Auth contract address, and transaction hash. Return type depends on schema parameter.\n *\n * ## Parameters\n *\n * ### request (required)\n *\n * - **Type:** `AddComposeHashRequest`\n *\n * Configuration object for adding a compose hash. Contains the following fields:\n *\n * #### chain (conditionally required)\n * - **Type:** `Chain` - Viem chain configuration object\n * - **Description:** Blockchain network configuration. Required when creating publicClient or walletClient. Optional when both publicClient and walletClient are provided.\n * - **Usage:** Used to create missing clients (publicClient or walletClient) when not provided\n * - **Example:** `import { base } from 'viem/chains'`\n *\n * #### kmsContractAddress (required)\n * - **Type:** `Address` - Ethereum contract address\n * - **Description:** Address of the KMS contract to lookup the App Auth contract\n * - **Example:** `\"0x1234567890abcdef1234567890abcdef12345678\"`\n *\n * #### appId (required)\n * - **Type:** `Address` - Application ID\n * - **Description:** The application ID used to lookup the App Auth contract in the KMS\n * - **Example:** `\"0xabcdef1234567890abcdef1234567890abcdef12\"`\n *\n * #### composeHash (required)\n * - **Type:** `string` - 32-byte hex string (with or without 0x prefix)\n * - **Description:** Hash of the app compose configuration to add to the allowed list\n * - **Calculation:** Can be calculated using `getComposeHash(appCompose)` utility function\n * - **Format:** Automatically converted to proper hex format using `asHex()` utility\n * - **Example:** `\"abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890\"`\n *\n * #### privateKey (conditionally required)\n * - **Type:** `Hex` - Private key hex string\n * - **Description:** Private key of the account that has permission to add compose hashes (Mode 1). Either this OR `walletClient` must be provided, but not both.\n * - **Security:** Keep this secure and never expose in client-side code\n * - **Example:** `\"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef\"`\n *\n * #### walletClient (conditionally required)\n * - **Type:** `WalletClient` - Viem wallet client instance\n * - **Description:** Custom wallet client for advanced use cases (Mode 2). Either this OR `privateKey` must be provided, but not both.\n * - **Example:** Multi-sig wallet, hardware wallet, or any custom viem WalletClient\n *\n * #### publicClient (optional)\n * - **Type:** `PublicClient` - Viem public client instance\n * - **Description:** Custom public client for blockchain reads. If not provided, will create a default one using the chain configuration.\n *\n * #### skipPrerequisiteChecks (optional)\n * - **Type:** `boolean` - Default: `false`\n * - **Description:** Whether to skip network and balance prerequisite checks before transaction\n *\n * #### minBalance (optional)\n * - **Type:** `string` - ETH amount as string\n * - **Default:** `\"0.001\"` (0.001 ETH)\n * - **Description:** Minimum ETH balance required in the account\n * - **Example:** `\"0.01\"` for 0.01 ETH minimum balance\n *\n * ### schema (optional)\n *\n * - **Type:** `ZodSchema | false`\n * - **Default:** `AddComposeHashSchema`\n *\n * Schema to validate the response. Use `false` to return raw data without validation.\n *\n * ```typescript\n * // Use default schema\n * const result = await addComposeHash(request)\n *\n * // Return raw data without validation\n * const raw = await addComposeHash(request, { schema: false })\n *\n * // Use custom schema\n * const customSchema = z.object({ composeHash: z.string(), transactionHash: z.string() })\n * const custom = await addComposeHash(request, { schema: customSchema })\n * ```\n *\n * ## Safe Version\n *\n * Use `safeAddComposeHash` for error handling without exceptions:\n *\n * ```typescript\n * import { safeAddComposeHash } from '@phala/cloud'\n *\n * const result = await safeAddComposeHash(request)\n * if (result.success) {\n * console.log(`Compose hash added: ${result.data.composeHash}`)\n * } else {\n * if (\"isRequestError\" in result.error) {\n * console.error(`Transaction failed: ${result.error.message}`)\n * } else {\n * console.error(`Validation error: ${result.error.issues}`)\n * }\n * }\n * ```\n */\n\n// KMS Auth ABI for apps lookup function\nconst 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// App Auth ABI for addComposeHash function\nconst appAuthAbi = [\n {\n inputs: [{ name: \"composeHash\", type: \"bytes32\" }],\n name: \"addComposeHash\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"composeHash\", type: \"bytes32\", indexed: false }],\n name: \"ComposeHashAdded\",\n type: \"event\",\n anonymous: false,\n },\n] as const;\n\n// Request schema with conditional validation using Zod refine\nconst AddComposeHashRequestSchema = z\n .object({\n // Chain configuration (conditionally required)\n chain: z.unknown().optional(),\n\n // Contract configuration (required)\n kmsContractAddress: z.string(),\n appId: z.string(),\n composeHash: z.string(),\n\n // Authentication mode: either privateKey OR walletClient (required, mutually exclusive)\n privateKey: z.string().optional(),\n walletClient: z.unknown().optional(),\n\n // Public client (optional, will create default if not provided)\n publicClient: z.unknown().optional(),\n\n // Validation configuration (optional)\n skipPrerequisiteChecks: z.boolean().optional().default(false),\n minBalance: z.string().optional(), // ETH amount as string, e.g., \"0.01\"\n\n // Transaction control options\n timeout: z.number().optional().default(120000),\n retryOptions: z.unknown().optional(),\n signal: z.unknown().optional(),\n\n // Progress callbacks\n onTransactionStateChange: z.function().optional(),\n onTransactionSubmitted: z.function().optional(),\n onTransactionConfirmed: z.function().optional(),\n })\n .passthrough()\n .refine(\n (data) => {\n // XOR validation: exactly one auth method\n const hasPrivateKey = !!data.privateKey;\n const hasWalletClient = !!data.walletClient;\n return hasPrivateKey !== hasWalletClient;\n },\n {\n message: \"Either 'privateKey' or 'walletClient' must be provided, but not both\",\n path: [\"privateKey\", \"walletClient\"],\n },\n )\n .refine(\n (data) => {\n // Conditional chain requirement\n const hasPublicClient = !!data.publicClient;\n const hasWalletClient = !!data.walletClient;\n const hasChain = !!data.chain;\n\n // Chain optional when both clients provided\n if (hasPublicClient && hasWalletClient) return true;\n\n // Chain required to create missing client\n return hasChain;\n },\n {\n message: \"Chain is required when publicClient or walletClient is not provided\",\n path: [\"chain\"],\n },\n );\n\nexport type AddComposeHashRequest = {\n chain?: Chain;\n appId: Address;\n composeHash: string;\n privateKey?: Hex;\n walletClient?: WalletClient;\n publicClient?: PublicClient;\n\n // Validation configuration\n skipPrerequisiteChecks?: boolean;\n minBalance?: string;\n\n // Transaction control options\n timeout?: number;\n retryOptions?: RetryOptions;\n signal?: AbortSignal;\n\n // Progress callbacks\n onTransactionStateChange?: (state: TransactionTracker[\"status\"]) => void;\n onTransactionSubmitted?: (hash: Hash) => void;\n onTransactionConfirmed?: (receipt: TransactionReceipt) => void;\n};\n\n// Response schema\nexport const AddComposeHashSchema = z\n .object({\n composeHash: z.string(),\n appId: z.string(),\n transactionHash: z.string(),\n blockNumber: z.bigint().optional(),\n gasUsed: z.bigint().optional(),\n })\n .passthrough();\n\nexport type AddComposeHash = z.infer<typeof AddComposeHashSchema>;\n\n// Conditional types for intelligent type inference\nexport type AddComposeHashParameters<T = undefined> = T extends z.ZodSchema\n ? { schema: T }\n : T extends false\n ? { schema: false }\n : { schema?: z.ZodSchema | false };\n\nexport type AddComposeHashReturnType<T = undefined> = T extends z.ZodSchema\n ? z.infer<T>\n : T extends false\n ? unknown\n : AddComposeHash;\n\n// Helper function to parse result from transaction receipt\nfunction parseComposeHashResult(\n receipt: TransactionReceipt,\n composeHash: Hash,\n appAuthAddress: Address,\n appId: Address,\n): AddComposeHash {\n console.log(receipt.logs);\n try {\n // Parse ComposeHashAdded event\n const logs = parseEventLogs({\n abi: appAuthAbi,\n eventName: \"ComposeHashAdded\",\n logs: receipt.logs,\n strict: false,\n });\n\n // ComposeHashAdded event is optional - the transaction may succeed without it\n if (logs.length > 0) {\n const event = logs[0];\n if (event?.args?.composeHash !== composeHash) {\n console.warn(\n `Event compose hash (${event?.args?.composeHash}) does not match expected (${composeHash})`,\n );\n }\n }\n\n return {\n composeHash: composeHash as string,\n appAuthAddress: appAuthAddress as string,\n appId: appId as string,\n transactionHash: receipt.transactionHash,\n blockNumber: receipt.blockNumber,\n gasUsed: receipt.gasUsed,\n };\n } catch (parseError) {\n // If event parsing fails, still return basic result\n console.warn(\"Failed to parse ComposeHashAdded event, returning basic result:\", parseError);\n return {\n composeHash: composeHash as string,\n appAuthAddress: appAuthAddress as string,\n appId: appId as string,\n transactionHash: receipt.transactionHash,\n blockNumber: receipt.blockNumber,\n gasUsed: receipt.gasUsed,\n };\n }\n}\n\n// Standard version (throws on error)\nexport async function addComposeHash<T extends z.ZodSchema | false | undefined = undefined>(\n request: AddComposeHashRequest,\n parameters?: AddComposeHashParameters<T>,\n): Promise<AddComposeHashReturnType<T>> {\n const validatedRequest = AddComposeHashRequestSchema.parse(request);\n\n const {\n chain,\n appId,\n composeHash,\n privateKey,\n walletClient: providedWalletClient,\n publicClient: providedPublicClient,\n timeout = 120000,\n retryOptions,\n signal,\n onTransactionStateChange,\n onTransactionSubmitted,\n onTransactionConfirmed,\n skipPrerequisiteChecks = false,\n minBalance,\n } = validatedRequest;\n\n // Create or use provided clients\n let publicClient: PublicClient;\n let walletClient: WalletClient;\n let address: Address;\n let chainId: number;\n\n const appAuthAddress = (appId.startsWith(\"0x\") ? appId : `0x${appId}`) as Address;\n\n if (privateKey) {\n // Mode 1: Private key authentication\n const account = privateKeyToAccount(privateKey as Hex);\n\n if (providedPublicClient) {\n publicClient = providedPublicClient as PublicClient;\n } else {\n if (!chain) throw new Error(\"Chain required when creating publicClient\");\n publicClient = createPublicClient({ chain: chain as Chain, transport: http() });\n }\n\n if (!chain) throw new Error(\"Chain required when creating walletClient\");\n walletClient = createWalletClient({\n account,\n chain: chain as Chain,\n transport: http(),\n });\n\n address = account.address;\n chainId = (chain as Chain).id;\n } else if (providedWalletClient) {\n // Mode 2: Custom wallet client\n walletClient = providedWalletClient as WalletClient;\n\n if (providedPublicClient) {\n publicClient = providedPublicClient as PublicClient;\n } else {\n if (!chain) throw new Error(\"Chain required when creating publicClient\");\n publicClient = createPublicClient({ chain: chain as Chain, transport: http() });\n }\n\n if (!walletClient.account?.address) {\n throw new Error(\"WalletClient must have an account with address\");\n }\n address = walletClient.account.address;\n chainId = chain ? (chain as Chain).id : await walletClient.getChainId();\n } else {\n throw new Error(\"Either privateKey or walletClient must be provided\");\n }\n\n // Create NetworkClients for utilities\n const networkClients: NetworkClients = {\n publicClient,\n walletClient,\n address: address,\n chainId: chainId,\n };\n\n // Create transaction tracker for state management\n const transactionTracker = createTransactionTracker();\n\n // Set up state change callback\n if (onTransactionStateChange && typeof onTransactionStateChange === \"function\") {\n const pollStatus = (): void => {\n onTransactionStateChange(transactionTracker.status);\n if (!transactionTracker.isComplete) {\n setTimeout(pollStatus, 100);\n }\n };\n setTimeout(pollStatus, 10);\n }\n\n // Perform prerequisite checks using network utilities\n if (!skipPrerequisiteChecks) {\n const requirements = {\n targetChainId: chainId,\n minBalance: minBalance ? parseEther(minBalance) : parseEther(\"0.001\"),\n };\n\n const validation = await validateNetworkPrerequisites(networkClients, requirements);\n\n if (!validation.networkValid) {\n throw new Error(\n `Network mismatch: Expected chain ${requirements.targetChainId}, but wallet is on chain ${validation.details.currentChainId}`,\n );\n }\n\n if (!validation.balanceValid) {\n const requiredEth = Number(requirements.minBalance) / 1e18;\n const currentEth = Number(validation.details.balance) / 1e18;\n throw new Error(\n `Insufficient balance: Required ${requiredEth} ETH, but account has ${currentEth.toFixed(6)} ETH`,\n );\n }\n }\n\n // Define the blockchain operation\n const addComposeHashOperation = async (clients: NetworkClients): Promise<Hash> => {\n const hash = await clients.walletClient.writeContract({\n address: appAuthAddress,\n abi: appAuthAbi,\n functionName: \"addComposeHash\",\n args: [asHex(composeHash)],\n account: clients.walletClient.account || clients.address,\n chain: (chain as Chain) || null,\n });\n\n return hash;\n };\n\n // Execute transaction with enhanced features\n const transactionResult = retryOptions\n ? await executeTransactionWithRetry(\n addComposeHashOperation,\n networkClients,\n [],\n {\n timeout: timeout as number,\n confirmations: 1,\n onSubmitted: onTransactionSubmitted,\n onConfirmed: onTransactionConfirmed,\n signal: signal,\n } as TransactionOptions & { signal?: AbortSignal },\n retryOptions,\n )\n : await transactionTracker.execute(addComposeHashOperation, networkClients, [], {\n timeout: timeout as number,\n confirmations: 1,\n onSubmitted: onTransactionSubmitted,\n onConfirmed: onTransactionConfirmed,\n signal: signal,\n } as TransactionOptions & { signal?: AbortSignal });\n\n // Parse result from receipt\n const result = parseComposeHashResult(\n transactionResult.receipt,\n asHex(composeHash),\n appAuthAddress,\n appId as Address,\n );\n\n // Schema handling\n if (parameters?.schema === false) {\n return result as AddComposeHashReturnType<T>;\n }\n\n const schema = (parameters?.schema || AddComposeHashSchema) as z.ZodSchema;\n return schema.parse(result) as AddComposeHashReturnType<T>;\n}\n\n// Safe version type definition\nexport type SafeAddComposeHashResult<T = undefined> =\n | {\n success: true;\n data: AddComposeHashReturnType<T>;\n }\n | {\n success: false;\n error: { isRequestError: true; message: string; status: number; detail: string };\n };\n\n// Safe version (returns SafeResult)\nexport async function safeAddComposeHash<T extends z.ZodSchema | false | undefined = undefined>(\n request: AddComposeHashRequest,\n parameters?: AddComposeHashParameters<T>,\n): Promise<SafeAddComposeHashResult<T>> {\n try {\n const result = await addComposeHash(request, parameters);\n return { success: true, data: result };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown blockchain error\";\n return {\n success: false,\n error: {\n isRequestError: true,\n message: errorMessage,\n status: 500, // Blockchain errors use 500\n detail: errorMessage,\n },\n };\n }\n}\n","import { z } from \"zod\";\nimport { type Client, type SafeResult } from \"../client\";\nimport { ActionParameters, ActionReturnType } from \"../types/common\";\n\n/**\n * Get CVM compose file configuration\n *\n * Retrieves the current Docker Compose file configuration and metadata for a specified CVM.\n *\n * @example\n * ```typescript\n * import { createClient, getCvmComposeFile } from '@phala/cloud'\n *\n * const client = createClient({ apiKey: 'your-api-key' })\n * const composeFile = await getCvmComposeFile(client, { id: 'cvm-123' })\n * // Output: { compose_content: '...', version: '...', last_modified: '...' }\n * ```\n *\n * ## Returns\n *\n * `GetCvmComposeFileResult | unknown`\n *\n * The CVM compose file configuration including compose_content and metadata. Return type depends on schema parameter.\n *\n * ## Parameters\n *\n * ### request (required)\n * - **Type:** `GetCvmComposeFileRequest`\n *\n * Request parameters containing the CVM identifier. Can be one of:\n * - id: The CVM ID\n * - uuid: The CVM UUID\n * - appId: The App ID (40 chars)\n * - instanceId: The Instance ID (40 chars)\n *\n * ### parameters (optional)\n * - **Type:** `GetCvmComposeFileParameters`\n *\n * Optional behavior parameters for schema validation.\n *\n * ```typescript\n * // Use default schema\n * const result = await getCvmComposeFile(client, { id: 'cvm-123' })\n *\n * // Return raw data without validation\n * const raw = await getCvmComposeFile(client, { id: 'cvm-123' }, { schema: false })\n *\n * // Use custom schema\n * const customSchema = z.object({ compose_content: z.string() })\n * const custom = await getCvmComposeFile(client, { id: 'cvm-123' }, { schema: customSchema })\n * ```\n *\n * ## Safe Version\n *\n * Use `safeGetCvmComposeFile` for error handling without exceptions:\n *\n * ```typescript\n * import { safeGetCvmComposeFile } from '@phala/cloud'\n *\n * const result = await safeGetCvmComposeFile(client, { id: 'cvm-123' })\n * if (result.success) {\n * console.log(result.data.compose_content)\n * } else {\n * if (\"isRequestError\" in result.error) {\n * console.error(`HTTP ${result.error.status}: ${result.error.message}`)\n * } else {\n * console.error(`Validation error: ${result.error.issues}`)\n * }\n * }\n * ```\n */\n\nexport const GetCvmComposeFileResultSchema = z\n .object({\n allowed_envs: z.array(z.string()).optional(),\n docker_compose_file: z.string(),\n features: z.array(z.string()).optional(),\n name: z.string().optional(),\n manifest_version: z.number().optional(),\n kms_enabled: z.boolean().optional(),\n public_logs: z.boolean().optional(),\n public_sysinfo: z.boolean().optional(),\n tproxy_enabled: z.boolean().optional(),\n pre_launch_script: z.string().optional(),\n })\n .passthrough();\n\n// Legacy alias for backwards compatibility\nexport const CvmComposeFileSchema = GetCvmComposeFileResultSchema;\nexport type CvmComposeFile = z.infer<typeof CvmComposeFileSchema>;\nexport type GetCvmComposeFileResult = z.infer<typeof GetCvmComposeFileResultSchema>;\n\nexport const GetCvmComposeFileRequestSchema = z\n .object({\n id: z.string().optional(),\n uuid: z\n .string()\n .regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i)\n .optional(),\n app_id: z\n .string()\n .refine(\n (val) => !val.startsWith(\"app_\") && val.length === 40,\n \"app_id should be 40 characters without prefix\",\n )\n .transform((val) => (val.startsWith(\"app_\") ? val : `app_${val}`))\n .optional(),\n instance_id: z\n .string()\n .refine(\n (val) => !val.startsWith(\"instance_\") && val.length === 40,\n \"instance_id should be 40 characters without prefix\",\n )\n .transform((val) => (val.startsWith(\"instance_\") ? val : `instance_${val}`))\n .optional(),\n })\n .refine(\n (data) => !!(data.id || data.uuid || data.app_id || data.instance_id),\n \"One of id, uuid, app_id, or instance_id must be provided\",\n )\n .transform((data) => ({\n cvmId: data.id || data.uuid || data.app_id || data.instance_id,\n _raw: data,\n }));\n\nexport type GetCvmComposeFileRequest = {\n id?: string;\n uuid?: string;\n app_id?: string;\n instance_id?: string;\n};\n\nexport type GetCvmComposeFileParameters<T = undefined> = ActionParameters<T>;\n\nexport type GetCvmComposeFileReturnType<T = undefined> = ActionReturnType<\n GetCvmComposeFileResult,\n T\n>;\n\nexport async function getCvmComposeFile<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n request: GetCvmComposeFileRequest,\n parameters?: GetCvmComposeFileParameters<T>,\n): Promise<GetCvmComposeFileReturnType<T>> {\n const validatedRequest = GetCvmComposeFileRequestSchema.parse(request);\n\n const response = await client.get(`/cvms/${validatedRequest.cvmId}/compose_file`);\n\n if (parameters?.schema === false) {\n return response as GetCvmComposeFileReturnType<T>;\n }\n\n const schema = (parameters?.schema || GetCvmComposeFileResultSchema) as z.ZodSchema;\n return schema.parse(response) as GetCvmComposeFileReturnType<T>;\n}\n\nexport async function safeGetCvmComposeFile<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n request: GetCvmComposeFileRequest,\n parameters?: GetCvmComposeFileParameters<T>,\n): Promise<SafeResult<GetCvmComposeFileReturnType<T>>> {\n const requestValidation = GetCvmComposeFileRequestSchema.safeParse(request);\n if (!requestValidation.success) {\n return requestValidation as SafeResult<GetCvmComposeFileReturnType<T>>;\n }\n\n const httpResult = await client.safeGet(`/cvms/${requestValidation.data.cvmId}/compose_file`);\n if (!httpResult.success) {\n return httpResult as SafeResult<GetCvmComposeFileReturnType<T>>;\n }\n\n if (parameters?.schema === false) {\n return { success: true, data: httpResult.data } as SafeResult<GetCvmComposeFileReturnType<T>>;\n }\n\n const schema = (parameters?.schema || GetCvmComposeFileResultSchema) as z.ZodSchema;\n return schema.safeParse(httpResult.data) as SafeResult<GetCvmComposeFileReturnType<T>>;\n}\n","import { z } from \"zod\";\nimport { type Client, type SafeResult } from \"../client\";\nimport { ActionParameters, ActionReturnType } from \"../types/common\";\nimport { KmsInfoSchema } from \"../types/kms_info\";\n\n/**\n * Provision CVM compose file update\n *\n * Provisions a CVM compose file update by uploading the new compose file configuration.\n * Returns a compose_hash that must be used with `commitCvmComposeFileUpdate` to finalize the update.\n *\n * @example\n * ```typescript\n * import { createClient, provisionCvmComposeFileUpdate } from '@phala/cloud'\n *\n * const client = createClient({ apiKey: 'your-api-key' })\n * const result = await provisionCvmComposeFileUpdate(client, {\n * id: 'cvm-123',\n * app_compose: {\n * name: 'my-app',\n * docker_compose_file: 'version: \"3.8\"\\nservices:\\n app:\\n image: nginx'\n * }\n * })\n * console.log(`Compose hash: ${result.compose_hash}`)\n * ```\n *\n * ## Returns\n *\n * `ProvisionCvmComposeFileUpdateResult | unknown`\n *\n * Provision response including compose_hash and metadata needed for committing the update.\n * Return type depends on schema parameter.\n *\n * ## Parameters\n *\n * ### request (required)\n * - **Type:** `ProvisionCvmComposeFileUpdateRequest`\n *\n * Request parameters containing the CVM ID and compose file configuration.\n *\n * ### parameters (optional)\n * - **Type:** `ProvisionCvmComposeFileUpdateParameters`\n *\n * Optional behavior parameters for schema validation.\n *\n * ```typescript\n * // Use default schema\n * const result = await provisionCvmComposeFileUpdate(client, {\n * id: 'cvm-123',\n * app_compose: { name: 'my-app', docker_compose_file: '...' }\n * })\n *\n * // Return raw data without validation\n * const raw = await provisionCvmComposeFileUpdate(client, request, { schema: false })\n *\n * // Use custom schema\n * const customSchema = z.object({ compose_hash: z.string() })\n * const custom = await provisionCvmComposeFileUpdate(client, request, { schema: customSchema })\n * ```\n *\n * ## Safe Version\n *\n * Use `safeProvisionCvmComposeFileUpdate` for error handling without exceptions:\n *\n * ```typescript\n * import { safeProvisionCvmComposeFileUpdate } from '@phala/cloud'\n *\n * const result = await safeProvisionCvmComposeFileUpdate(client, {\n * id: 'cvm-123',\n * app_compose: { name: 'my-app', docker_compose_file: '...' }\n * })\n * if (result.success) {\n * console.log(`Compose hash: ${result.data.compose_hash}`)\n * } else {\n * if (\"isRequestError\" in result.error) {\n * console.error(`HTTP ${result.error.status}: ${result.error.message}`)\n * } else {\n * console.error(`Validation error: ${result.error.issues}`)\n * }\n * }\n * ```\n */\n\nexport const ProvisionCvmComposeFileUpdateRequestSchema = z\n .object({\n id: z.string().optional(),\n uuid: z\n .string()\n .regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i)\n .optional(),\n app_id: z\n .string()\n .refine(\n (val) => !val.startsWith(\"app_\") && val.length === 40,\n \"app_id should be 40 characters without prefix\",\n )\n .transform((val) => (val.startsWith(\"app_\") ? val : `app_${val}`))\n .optional(),\n instance_id: z\n .string()\n .refine(\n (val) => !val.startsWith(\"instance_\") && val.length === 40,\n \"instance_id should be 40 characters without prefix\",\n )\n .transform((val) => (val.startsWith(\"instance_\") ? val : `instance_${val}`))\n .optional(),\n app_compose: z.object({\n allowed_envs: z.array(z.string()).optional(),\n docker_compose_file: z.string().min(1, \"Docker compose file is required\"),\n name: z.string(),\n kms_enabled: z.boolean().optional(),\n public_logs: z.boolean().optional(),\n public_sysinfo: z.boolean().optional(),\n pre_launch_script: z.string().optional(),\n }),\n })\n .refine(\n (data) => !!(data.id || data.uuid || data.app_id || data.instance_id),\n \"One of id, uuid, app_id, or instance_id must be provided\",\n )\n .transform((data) => ({\n cvmId: data.id || data.uuid || data.app_id || data.instance_id,\n request: data.app_compose,\n _raw: data,\n }));\n\nexport const ProvisionCvmComposeFileUpdateResultSchema = z\n .object({\n app_id: z.string().nullable(),\n device_id: z.string().nullable(),\n compose_hash: z.string(),\n kms_info: KmsInfoSchema.nullable().optional(),\n })\n .passthrough();\n\nexport type ProvisionCvmComposeFileUpdateRequest = z.input<\n typeof ProvisionCvmComposeFileUpdateRequestSchema\n>;\nexport type ProvisionCvmComposeFileUpdateResult = z.infer<\n typeof ProvisionCvmComposeFileUpdateResultSchema\n>;\n\nexport type ProvisionCvmComposeFileUpdateParameters<T = undefined> = ActionParameters<T>;\nexport type ProvisionCvmComposeFileUpdateReturnType<T = undefined> = ActionReturnType<\n ProvisionCvmComposeFileUpdateResult,\n T\n>;\n\n/**\n * Provision a CVM compose file update\n *\n * @param client - The API client\n * @param request - Request parameters containing CVM ID and compose file configuration\n * @param parameters - Optional behavior parameters\n * @returns Update provision result\n */\nexport async function provisionCvmComposeFileUpdate<\n T extends z.ZodSchema | false | undefined = undefined,\n>(\n client: Client,\n request: ProvisionCvmComposeFileUpdateRequest,\n parameters?: ProvisionCvmComposeFileUpdateParameters<T>,\n): Promise<ProvisionCvmComposeFileUpdateReturnType<T>> {\n const validatedRequest = ProvisionCvmComposeFileUpdateRequestSchema.parse(request);\n\n const response = await client.post(\n `/cvms/${validatedRequest.cvmId}/compose_file/provision`,\n validatedRequest.request,\n );\n\n if (parameters?.schema === false) {\n return response as ProvisionCvmComposeFileUpdateReturnType<T>;\n }\n\n const schema = (parameters?.schema || ProvisionCvmComposeFileUpdateResultSchema) as z.ZodSchema;\n return schema.parse(response) as ProvisionCvmComposeFileUpdateReturnType<T>;\n}\n\n/**\n * Safe version of provisionCvmComposeFileUpdate that returns a Result type instead of throwing\n */\nexport async function safeProvisionCvmComposeFileUpdate<\n T extends z.ZodSchema | false | undefined = undefined,\n>(\n client: Client,\n request: ProvisionCvmComposeFileUpdateRequest,\n parameters?: ProvisionCvmComposeFileUpdateParameters<T>,\n): Promise<SafeResult<ProvisionCvmComposeFileUpdateReturnType<T>>> {\n const requestValidation = ProvisionCvmComposeFileUpdateRequestSchema.safeParse(request);\n if (!requestValidation.success) {\n return requestValidation as SafeResult<ProvisionCvmComposeFileUpdateReturnType<T>>;\n }\n\n const httpResult = await client.safePost(\n `/cvms/${requestValidation.data.cvmId}/compose_file/provision`,\n requestValidation.data.request,\n );\n if (!httpResult.success) {\n return httpResult as SafeResult<ProvisionCvmComposeFileUpdateReturnType<T>>;\n }\n\n if (parameters?.schema === false) {\n return { success: true, data: httpResult.data } as SafeResult<\n ProvisionCvmComposeFileUpdateReturnType<T>\n >;\n }\n\n const schema = (parameters?.schema || ProvisionCvmComposeFileUpdateResultSchema) as z.ZodSchema;\n return schema.safeParse(httpResult.data) as SafeResult<\n ProvisionCvmComposeFileUpdateReturnType<T>\n >;\n}\n","import { z } from \"zod\";\nimport { type Client, type SafeResult } from \"../client\";\nimport { ActionParameters, ActionReturnType } from \"../types/common\";\nimport { RequestError } from \"../types/client\";\n\n/**\n * Commit CVM compose file update\n *\n * Finalizes a CVM compose file update by committing the previously provisioned changes.\n * This should be called after `provisionCvmComposeFileUpdate` to complete the update process.\n *\n * @example\n * ```typescript\n * import { createClient, commitCvmComposeFileUpdate } from '@phala/cloud'\n *\n * const client = createClient({ apiKey: 'your-api-key' })\n * await commitCvmComposeFileUpdate(client, {\n * cvmId: 'cvm-123',\n * request: {\n * compose_hash: 'abc123...'\n * }\n * })\n * // Request accepted, update will be processed asynchronously\n * ```\n *\n * ## Returns\n *\n * `void | unknown`\n *\n * No response body (HTTP 202 Accepted). The update is processed asynchronously. Return type depends on schema parameter.\n *\n * ## Parameters\n *\n * ### request (required)\n * - **Type:** `CommitCvmComposeFileUpdateRequestData`\n *\n * Request parameters containing the CVM ID and commit request data.\n *\n * ### parameters (optional)\n * - **Type:** `CommitCvmComposeFileUpdateParameters`\n *\n * Optional behavior parameters for schema validation.\n *\n * ```typescript\n * // Use default schema (void response)\n * await commitCvmComposeFileUpdate(client, { cvmId: 'cvm-123', request: commitRequest })\n *\n * // Return raw data without validation\n * const raw = await commitCvmComposeFileUpdate(client, { cvmId: 'cvm-123', request: commitRequest }, { schema: false })\n *\n * // Use custom schema\n * const customSchema = z.object({ status: z.string() })\n * const custom = await commitCvmComposeFileUpdate(client, { cvmId: 'cvm-123', request: commitRequest }, { schema: customSchema })\n * ```\n *\n * ## Safe Version\n *\n * Use `safeCommitCvmComposeFileUpdate` for error handling without exceptions:\n *\n * ```typescript\n * import { safeCommitCvmComposeFileUpdate } from '@phala/cloud'\n *\n * const result = await safeCommitCvmComposeFileUpdate(client, { cvmId: 'cvm-123', request: commitRequest })\n * if (result.success) {\n * console.log('Compose file update committed successfully')\n * } else {\n * if (\"isRequestError\" in result.error) {\n * console.error(`HTTP ${result.error.status}: ${result.error.message}`)\n * } else {\n * console.error(`Validation error: ${result.error.issues}`)\n * }\n * }\n * ```\n */\n\nexport const CommitCvmComposeFileUpdateRequestSchema = z\n .object({\n id: z.string().optional(),\n uuid: z\n .string()\n .regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i)\n .optional(),\n app_id: z\n .string()\n .refine(\n (val) => !val.startsWith(\"app_\") && val.length === 40,\n \"app_id should be 40 characters without prefix\",\n )\n .transform((val) => (val.startsWith(\"app_\") ? val : `app_${val}`))\n .optional(),\n instance_id: z\n .string()\n .refine(\n (val) => !val.startsWith(\"instance_\") && val.length === 40,\n \"instance_id should be 40 characters without prefix\",\n )\n .transform((val) => (val.startsWith(\"instance_\") ? val : `instance_${val}`))\n .optional(),\n compose_hash: z.string().min(1, \"Compose hash is required\"),\n encrypted_env: z.string().optional(),\n env_keys: z.array(z.string()).optional(),\n })\n .refine(\n (data) => !!(data.id || data.uuid || data.app_id || data.instance_id),\n \"One of id, uuid, app_id, or instance_id must be provided\",\n )\n .transform((data) => ({\n cvmId: data.id || data.uuid || data.app_id || data.instance_id,\n compose_hash: data.compose_hash,\n encrypted_env: data.encrypted_env,\n env_keys: data.env_keys,\n _raw: data,\n }));\n\nexport const CommitCvmComposeFileUpdateSchema = z.any().transform(() => undefined);\n\nexport type CommitCvmComposeFileUpdateRequest = z.infer<\n typeof CommitCvmComposeFileUpdateRequestSchema\n>;\nexport type CommitCvmComposeFileUpdate = undefined;\n\nexport type CommitCvmComposeFileUpdateParameters<T = undefined> = ActionParameters<T>;\n\nexport type CommitCvmComposeFileUpdateReturnType<T = undefined> = ActionReturnType<\n CommitCvmComposeFileUpdate,\n T\n>;\n\nexport async function commitCvmComposeFileUpdate<\n T extends z.ZodSchema | false | undefined = undefined,\n>(\n client: Client,\n request: CommitCvmComposeFileUpdateRequest,\n parameters?: CommitCvmComposeFileUpdateParameters<T>,\n): Promise<CommitCvmComposeFileUpdateReturnType<T>> {\n const validatedRequest = CommitCvmComposeFileUpdateRequestSchema.parse(request);\n\n const response = await client.patch(`/cvms/${validatedRequest.cvmId}/compose_file`, {\n compose_hash: validatedRequest.compose_hash,\n encrypted_env: validatedRequest.encrypted_env,\n env_keys: validatedRequest.env_keys,\n });\n\n if (parameters?.schema === false) {\n return response as CommitCvmComposeFileUpdateReturnType<T>;\n }\n\n const schema = (parameters?.schema || CommitCvmComposeFileUpdateSchema) as z.ZodSchema;\n return schema.parse(response) as CommitCvmComposeFileUpdateReturnType<T>;\n}\n\nexport async function safeCommitCvmComposeFileUpdate<\n T extends z.ZodSchema | false | undefined = undefined,\n>(\n client: Client,\n request: CommitCvmComposeFileUpdateRequest,\n parameters?: CommitCvmComposeFileUpdateParameters<T>,\n): Promise<SafeResult<CommitCvmComposeFileUpdateReturnType<T>>> {\n const requestValidation = CommitCvmComposeFileUpdateRequestSchema.safeParse(request);\n if (!requestValidation.success) {\n return requestValidation as SafeResult<CommitCvmComposeFileUpdateReturnType<T>>;\n }\n\n const httpResult = await client.safePatch(`/cvms/${requestValidation.data.cvmId}/compose_file`, {\n compose_hash: requestValidation.data.compose_hash,\n encrypted_env: requestValidation.data.encrypted_env,\n env_keys: requestValidation.data.env_keys,\n });\n if (!httpResult.success) {\n return httpResult as SafeResult<CommitCvmComposeFileUpdateReturnType<T>>;\n }\n\n if (parameters?.schema === false) {\n return { success: true, data: httpResult.data } as SafeResult<\n CommitCvmComposeFileUpdateReturnType<T>\n >;\n }\n\n const schema = (parameters?.schema || CommitCvmComposeFileUpdateSchema) as z.ZodSchema;\n return schema.safeParse(httpResult.data) as SafeResult<CommitCvmComposeFileUpdateReturnType<T>>;\n}\n","import { z } from \"zod\";\nimport { type Client, type SafeResult } from \"../client\";\nimport { ActionParameters, ActionReturnType } from \"../types/common\";\nimport { validateActionParameters, safeValidateActionParameters } from \"../utils\";\n\nexport const GetAppEnvEncryptPubKeyRequestSchema = z\n .object({\n kms: z.string().min(1, \"KMS ID or slug is required\"),\n app_id: z.string().length(40, \"App ID must be exactly 40 characters\"),\n })\n .strict();\n\nexport const GetAppEnvEncryptPubKeySchema = z\n .object({\n public_key: z.string(),\n signature: z.string(),\n })\n .strict();\n\nexport type GetAppEnvEncryptPubKeyRequest = z.infer<typeof GetAppEnvEncryptPubKeyRequestSchema>;\n\nexport type GetAppEnvEncryptPubKey = z.infer<typeof GetAppEnvEncryptPubKeySchema>;\n\nexport type GetAppEnvEncryptPubKeyParameters<T = undefined> = ActionParameters<T>;\n\nexport type GetAppEnvEncryptPubKeyReturnType<T = undefined> = ActionReturnType<\n GetAppEnvEncryptPubKey,\n T\n>;\n\nexport const getAppEnvEncryptPubKey = async <T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n payload: GetAppEnvEncryptPubKeyRequest,\n parameters?: GetAppEnvEncryptPubKeyParameters<T>,\n): Promise<GetAppEnvEncryptPubKeyReturnType<T>> => {\n const validatedRequest = GetAppEnvEncryptPubKeyRequestSchema.parse(payload);\n\n validateActionParameters(parameters);\n\n const response = await client.get(\n `/kms/${validatedRequest.kms}/pubkey/${validatedRequest.app_id}`,\n );\n\n if (parameters?.schema === false) {\n return response as GetAppEnvEncryptPubKeyReturnType<T>;\n }\n\n const schema = (parameters?.schema || GetAppEnvEncryptPubKeySchema) as z.ZodSchema;\n return schema.parse(response) as GetAppEnvEncryptPubKeyReturnType<T>;\n};\n\nexport const safeGetAppEnvEncryptPubKey = async <\n T extends z.ZodSchema | false | undefined = undefined,\n>(\n client: Client,\n payload: GetAppEnvEncryptPubKeyRequest,\n parameters?: GetAppEnvEncryptPubKeyParameters<T>,\n): Promise<SafeResult<GetAppEnvEncryptPubKeyReturnType<T>>> => {\n const requestValidation = GetAppEnvEncryptPubKeyRequestSchema.safeParse(payload);\n if (!requestValidation.success) {\n return requestValidation as SafeResult<GetAppEnvEncryptPubKeyReturnType<T>>;\n }\n\n const parameterValidationError = safeValidateActionParameters(parameters);\n if (parameterValidationError) {\n return parameterValidationError as SafeResult<GetAppEnvEncryptPubKeyReturnType<T>>;\n }\n\n const httpResult = await client.safeGet(\n `/kms/${requestValidation.data.kms}/pubkey/${requestValidation.data.app_id}`,\n );\n if (!httpResult.success) {\n return httpResult as SafeResult<GetAppEnvEncryptPubKeyReturnType<T>>;\n }\n\n if (parameters?.schema === false) {\n return { success: true, data: httpResult.data } as SafeResult<\n GetAppEnvEncryptPubKeyReturnType<T>\n >;\n }\n\n const schema = (parameters?.schema || GetAppEnvEncryptPubKeySchema) as z.ZodSchema;\n return schema.safeParse(httpResult.data) as SafeResult<GetAppEnvEncryptPubKeyReturnType<T>>;\n};\n","import { z } from \"zod\";\n\nexport const VmInfoSchema = z.object({\n id: z.string(),\n name: z.string(),\n status: z.string(),\n uptime: z.string(),\n app_url: z.string().nullable(),\n app_id: z.string(),\n instance_id: z.string().nullable(),\n configuration: z.any().optional(), // TODO: add VmConfiguration schema if needed\n exited_at: z.string().nullable(),\n boot_progress: z.string().nullable(),\n boot_error: z.string().nullable(),\n shutdown_progress: z.string().nullable(),\n image_version: z.string().nullable(),\n});\n\nexport const ManagedUserSchema = z.object({\n id: z.number(),\n username: z.string(),\n});\n\nexport const CvmNodeSchema = z.object({\n id: z.number(),\n name: z.string(),\n region_identifier: z.string().optional(),\n});\n\nexport const CvmNetworkUrlsSchema = z.object({\n app: z.string(),\n instance: z.string(),\n});\n\nexport const KMSInfoSchema = z.object({\n id: z.string(), // HashedId is represented as string in JS\n slug: z.string(),\n url: z.string(),\n version: z.string(),\n chain_id: z.number().optional(),\n kms_contract_address: z.string().optional(),\n gateway_app_id: z.string().optional(),\n});\n\nexport const CvmInfoSchema = z\n .object({\n hosted: VmInfoSchema,\n name: z.string(),\n managed_user: ManagedUserSchema.optional().nullable(),\n node: CvmNodeSchema.optional().nullable(),\n listed: z.boolean().default(false),\n status: z.string(),\n in_progress: z.boolean().default(false),\n dapp_dashboard_url: z.string().nullable(),\n syslog_endpoint: z.string().nullable(),\n allow_upgrade: z.boolean().default(false),\n project_id: z.string().nullable(), // HashedId is represented as string in JS\n project_type: z.string().nullable(),\n billing_period: z.string().nullable(),\n kms_info: KMSInfoSchema.nullable(),\n vcpu: z.number().nullable(),\n memory: z.number().nullable(),\n disk_size: z.number().nullable(),\n gateway_domain: z.string().nullable(),\n public_urls: z.array(CvmNetworkUrlsSchema),\n })\n .partial();\n\nexport type CvmInfo = z.infer<typeof CvmInfoSchema>;\n","import { z } from \"zod\";\nimport { type Client, type SafeResult } from \"../client\";\nimport { CvmInfoSchema } from \"../types/cvm_info\";\nimport { ActionParameters, ActionReturnType } from \"../types/common\";\nimport { validateActionParameters, safeValidateActionParameters } from \"../utils\";\n\nexport const GetCvmInfoSchema = CvmInfoSchema;\n\nexport type GetCvmInfoResponse = z.infer<typeof GetCvmInfoSchema>;\n\nexport const GetCvmInfoRequestSchema = z\n .object({\n id: z.string().optional(),\n uuid: z\n .string()\n .regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i)\n .optional(),\n app_id: z\n .string()\n .refine(\n (val) => !val.startsWith(\"app_\") && val.length === 40,\n \"app_id should be 40 characters without prefix\",\n )\n .transform((val) => (val.startsWith(\"app_\") ? val : `app_${val}`))\n .optional(),\n instance_id: z\n .string()\n .refine(\n (val) => !val.startsWith(\"instance_\") && val.length === 40,\n \"instance_id should be 40 characters without prefix\",\n )\n .transform((val) => (val.startsWith(\"instance_\") ? val : `instance_${val}`))\n .optional(),\n })\n .refine(\n (data) => !!(data.id || data.uuid || data.app_id || data.instance_id),\n \"One of id, uuid, app_id, or instance_id must be provided\",\n )\n .transform((data) => ({\n cvmId: data.id || data.uuid || data.app_id || data.instance_id,\n _raw: data,\n }));\n\nexport type GetCvmInfoRequest = {\n id?: string;\n uuid?: string;\n app_id?: string;\n instance_id?: string;\n};\n\nexport type GetCvmInfoParameters<T = undefined> = ActionParameters<T>;\n\nexport type GetCvmInfoReturnType<T = undefined> = ActionReturnType<GetCvmInfoResponse, T>;\n\n/**\n * Get information about a specific CVM\n *\n * @param client - The API client\n * @param request - Request parameters\n * @param request.cvmId - ID of the CVM to get information for\n * @param parameters - Optional behavior parameters\n * @returns CVM information\n *\n * @example\n * ```typescript\n * const info = await getCvmInfo(client, { cvmId: \"cvm-123\" })\n * ```\n */\nexport async function getCvmInfo<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n request: GetCvmInfoRequest,\n parameters?: GetCvmInfoParameters<T>,\n): Promise<GetCvmInfoReturnType<T>> {\n const validatedRequest = GetCvmInfoRequestSchema.parse(request);\n\n validateActionParameters(parameters);\n\n const response = await client.get(`/cvms/${validatedRequest.cvmId}`);\n\n if (parameters?.schema === false) {\n return response as GetCvmInfoReturnType<T>;\n }\n const schema = (parameters?.schema || GetCvmInfoSchema) as z.ZodSchema;\n return schema.parse(response) as GetCvmInfoReturnType<T>;\n}\n\n/**\n * Safe version of getCvmInfo that returns a Result type instead of throwing\n */\nexport async function safeGetCvmInfo<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n request: GetCvmInfoRequest,\n parameters?: GetCvmInfoParameters<T>,\n): Promise<SafeResult<GetCvmInfoReturnType<T>>> {\n const requestValidation = GetCvmInfoRequestSchema.safeParse(request);\n if (!requestValidation.success) {\n return requestValidation as SafeResult<GetCvmInfoReturnType<T>>;\n }\n\n const parameterValidationError = safeValidateActionParameters(parameters);\n if (parameterValidationError) {\n return parameterValidationError as SafeResult<GetCvmInfoReturnType<T>>;\n }\n\n const httpResult = await client.safeGet(`/cvms/${requestValidation.data.cvmId}`);\n if (!httpResult.success) {\n return httpResult;\n }\n if (parameters?.schema === false) {\n return {\n success: true,\n data: httpResult.data,\n } as SafeResult<GetCvmInfoReturnType<T>>;\n }\n const schema = (parameters?.schema || GetCvmInfoSchema) as z.ZodSchema;\n const validationResult = schema.safeParse(httpResult.data);\n return validationResult as SafeResult<GetCvmInfoReturnType<T>>;\n}\n","import { z } from \"zod\";\nimport { type Client, type SafeResult } from \"../client\";\nimport { CvmInfoSchema } from \"../types/cvm_info\";\nimport { ActionParameters, ActionReturnType } from \"../types/common\";\nimport { validateActionParameters, safeValidateActionParameters } from \"../utils\";\n\nexport const GetCvmListRequestSchema = z\n .object({\n page: z.number().int().min(1).optional(),\n page_size: z.number().int().min(1).optional(),\n node_id: z.number().int().min(1).optional(),\n })\n .strict();\n\nexport const GetCvmListSchema = z\n .object({\n items: z.array(CvmInfoSchema),\n total: z.number(),\n page: z.number(),\n page_size: z.number(),\n pages: z.number(),\n })\n .strict();\n\nexport type GetCvmListRequest = z.infer<typeof GetCvmListRequestSchema>;\nexport type GetCvmListResponse = z.infer<typeof GetCvmListSchema>;\n\nexport type GetCvmListParameters<T = undefined> = ActionParameters<T>;\n\nexport type GetCvmListReturnType<T = undefined> = ActionReturnType<GetCvmListResponse, T>;\n\n/**\n * Get a paginated list of CVMs\n *\n * @param client - The API client\n * @param request - Optional request parameters for pagination and filtering\n * @param request.page - Page number (1-based)\n * @param request.page_size - Number of items per page\n * @param request.node_id - Filter by node ID\n * @param parameters - Optional behavior parameters\n * @returns Paginated list of CVMs\n *\n * @example\n * ```typescript\n * // Get first page with default size\n * const list = await getCvmList(client, { page: 1 })\n *\n * // Get with custom page size\n * const list = await getCvmList(client, { page: 1, page_size: 20 })\n *\n * // Get with custom schema\n * const list = await getCvmList(client, { page: 1 }, { schema: customSchema })\n * ```\n */\nexport async function getCvmList<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n request?: GetCvmListRequest,\n parameters?: GetCvmListParameters<T>,\n): Promise<GetCvmListReturnType<T>> {\n const validatedRequest = GetCvmListRequestSchema.parse(request ?? {});\n\n validateActionParameters(parameters);\n\n const response = await client.get(\"/cvms/paginated\", { params: validatedRequest });\n\n if (parameters?.schema === false) {\n return response as GetCvmListReturnType<T>;\n }\n\n const schema = (parameters?.schema || GetCvmListSchema) as z.ZodSchema;\n return schema.parse(response) as GetCvmListReturnType<T>;\n}\n\n/**\n * Safe version of getCvmList that returns a Result type instead of throwing\n */\nexport async function safeGetCvmList<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n request?: GetCvmListRequest,\n parameters?: GetCvmListParameters<T>,\n): Promise<SafeResult<GetCvmListReturnType<T>>> {\n const requestValidation = GetCvmListRequestSchema.safeParse(request ?? {});\n if (!requestValidation.success) {\n return requestValidation as SafeResult<GetCvmListReturnType<T>>;\n }\n\n const parameterValidationError = safeValidateActionParameters(parameters);\n if (parameterValidationError) {\n return parameterValidationError as SafeResult<GetCvmListReturnType<T>>;\n }\n\n const httpResult = await client.safeGet(\"/cvms/paginated\", { params: requestValidation.data });\n if (!httpResult.success) {\n return httpResult;\n }\n\n if (parameters?.schema === false) {\n return {\n success: true,\n data: httpResult.data,\n } as SafeResult<GetCvmListReturnType<T>>;\n }\n\n const schema = (parameters?.schema || GetCvmListSchema) as z.ZodSchema;\n const validationResult = schema.safeParse(httpResult.data);\n return validationResult as SafeResult<GetCvmListReturnType<T>>;\n}\n","import { z } from \"zod\";\nimport type { Client, SafeResult } from \"../client\";\nimport { type KmsInfo, KmsInfoSchema } from \"../types/kms_info\";\nimport { ActionParameters, ActionReturnType } from \"../types/common\";\nimport { validateActionParameters, safeValidateActionParameters } from \"../utils\";\n\nexport const GetKmsInfoRequestSchema = z.object({\n kms_id: z.string().min(1, \"KMS ID is required\"),\n});\n\nexport type GetKmsInfoRequest = z.infer<typeof GetKmsInfoRequestSchema>;\n\nexport type GetKmsInfoParameters<T = undefined> = ActionParameters<T>;\n\nexport type GetKmsInfoReturnType<T = undefined> = ActionReturnType<KmsInfo, T>;\n\n/**\n * Get information about a specific KMS\n *\n * @param client - The API client\n * @param request - Request parameters\n * @param request.kms_id - ID of the KMS to get information for\n * @param parameters - Optional behavior parameters\n * @returns KMS information\n *\n * @example\n * ```typescript\n * const info = await getKmsInfo(client, { kms_id: \"kms-123\" })\n * ```\n */\nexport async function getKmsInfo<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n request: GetKmsInfoRequest,\n parameters?: GetKmsInfoParameters<T>,\n): Promise<GetKmsInfoReturnType<T>> {\n const validatedRequest = GetKmsInfoRequestSchema.parse(request);\n\n validateActionParameters(parameters);\n\n const response = await client.get(`/kms/${validatedRequest.kms_id}`);\n if (parameters?.schema === false) {\n return response as GetKmsInfoReturnType<T>;\n }\n const schema = (parameters?.schema || KmsInfoSchema) as z.ZodSchema;\n return schema.parse(response) as GetKmsInfoReturnType<T>;\n}\n\n/**\n * Safe version of getKmsInfo that returns a Result type instead of throwing\n */\nexport async function safeGetKmsInfo<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n request: GetKmsInfoRequest,\n parameters?: GetKmsInfoParameters<T>,\n): Promise<SafeResult<GetKmsInfoReturnType<T>>> {\n const requestValidation = GetKmsInfoRequestSchema.safeParse(request);\n if (!requestValidation.success) {\n return requestValidation as SafeResult<GetKmsInfoReturnType<T>>;\n }\n\n const parameterValidationError = safeValidateActionParameters(parameters);\n if (parameterValidationError) {\n return parameterValidationError as SafeResult<GetKmsInfoReturnType<T>>;\n }\n\n const httpResult = await client.safeGet(`/kms/${requestValidation.data.kms_id}`);\n if (!httpResult.success) {\n return httpResult;\n }\n if (parameters?.schema === false) {\n return { success: true, data: httpResult.data } as SafeResult<GetKmsInfoReturnType<T>>;\n }\n const schema = (parameters?.schema || KmsInfoSchema) as z.ZodSchema;\n const validationResult = schema.safeParse(httpResult.data);\n return validationResult as SafeResult<GetKmsInfoReturnType<T>>;\n}\n","import { z } from \"zod\";\nimport { type Client, type SafeResult } from \"../client\";\nimport { KmsInfoSchema } from \"../types/kms_info\";\nimport { ActionParameters, ActionReturnType } from \"../types/common\";\nimport { validateActionParameters, safeValidateActionParameters } from \"../utils\";\n\nexport const GetKmsListRequestSchema = z\n .object({\n page: z.number().int().min(1).optional(),\n page_size: z.number().int().min(1).optional(),\n is_onchain: z.boolean().optional(),\n })\n .strict();\n\nexport const GetKmsListSchema = z\n .object({\n items: z.array(KmsInfoSchema),\n total: z.number(),\n page: z.number(),\n page_size: z.number(),\n pages: z.number(),\n })\n .strict();\n\nexport type GetKmsListRequest = z.infer<typeof GetKmsListRequestSchema>;\nexport type GetKmsListResponse = z.infer<typeof GetKmsListSchema>;\n\nexport type GetKmsListParameters<T = undefined> = ActionParameters<T>;\n\nexport type GetKmsListReturnType<T = undefined> = ActionReturnType<GetKmsListResponse, T>;\n\nexport async function getKmsList<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n request?: GetKmsListRequest,\n parameters?: GetKmsListParameters<T>,\n): Promise<GetKmsListReturnType<T>> {\n const validatedRequest = GetKmsListRequestSchema.parse(request ?? {});\n\n validateActionParameters(parameters);\n\n const response = await client.get(\"/kms\", { params: validatedRequest });\n if (parameters?.schema === false) {\n return response as GetKmsListReturnType<T>;\n }\n\n const schema = (parameters?.schema || GetKmsListSchema) as z.ZodSchema;\n return schema.parse(response) as GetKmsListReturnType<T>;\n}\n\nexport async function safeGetKmsList<T extends z.ZodSchema | false | undefined = undefined>(\n client: Client,\n request?: GetKmsListRequest,\n parameters?: GetKmsListParameters<T>,\n): Promise<SafeResult<GetKmsListReturnType<T>>> {\n const requestValidation = GetKmsListRequestSchema.safeParse(request ?? {});\n if (!requestValidation.success) {\n return requestValidation as SafeResult<GetKmsListReturnType<T>>;\n }\n\n const parameterValidationError = safeValidateActionParameters(parameters);\n if (parameterValidationError) {\n return parameterValidationError as SafeResult<GetKmsListReturnType<T>>;\n }\n\n const httpResult = await client.safeGet(\"/kms\", { params: requestValidation.data });\n if (!httpResult.success) {\n return httpResult;\n }\n\n if (parameters?.schema === false) {\n return {\n success: true,\n data: httpResult.data,\n } as SafeResult<GetKmsListReturnType<T>>;\n }\n\n const schema = (parameters?.schema || GetKmsListSchema) as z.ZodSchema;\n const validationResult = schema.safeParse(httpResult.data);\n return validationResult as SafeResult<GetKmsListReturnType<T>>;\n}\n"]}
|