@cfxdevkit/core 0.1.0

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +72 -0
  3. package/README.md +257 -0
  4. package/dist/clients/index.cjs +2053 -0
  5. package/dist/clients/index.cjs.map +1 -0
  6. package/dist/clients/index.d.cts +7 -0
  7. package/dist/clients/index.d.ts +7 -0
  8. package/dist/clients/index.js +2043 -0
  9. package/dist/clients/index.js.map +1 -0
  10. package/dist/config/index.cjs +423 -0
  11. package/dist/config/index.cjs.map +1 -0
  12. package/dist/config/index.d.cts +99 -0
  13. package/dist/config/index.d.ts +99 -0
  14. package/dist/config/index.js +380 -0
  15. package/dist/config/index.js.map +1 -0
  16. package/dist/config-BMtaWM0X.d.cts +165 -0
  17. package/dist/config-BMtaWM0X.d.ts +165 -0
  18. package/dist/core-C5qe16RS.d.ts +352 -0
  19. package/dist/core-RZA4aKwj.d.cts +352 -0
  20. package/dist/index-BhCpy6Fz.d.cts +165 -0
  21. package/dist/index-Qz84U9Oq.d.ts +165 -0
  22. package/dist/index.cjs +3773 -0
  23. package/dist/index.cjs.map +1 -0
  24. package/dist/index.d.cts +945 -0
  25. package/dist/index.d.ts +945 -0
  26. package/dist/index.js +3730 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/types/index.cjs +44 -0
  29. package/dist/types/index.cjs.map +1 -0
  30. package/dist/types/index.d.cts +5 -0
  31. package/dist/types/index.d.ts +5 -0
  32. package/dist/types/index.js +17 -0
  33. package/dist/types/index.js.map +1 -0
  34. package/dist/utils/index.cjs +83 -0
  35. package/dist/utils/index.cjs.map +1 -0
  36. package/dist/utils/index.d.cts +11 -0
  37. package/dist/utils/index.d.ts +11 -0
  38. package/dist/utils/index.js +56 -0
  39. package/dist/utils/index.js.map +1 -0
  40. package/dist/wallet/index.cjs +852 -0
  41. package/dist/wallet/index.cjs.map +1 -0
  42. package/dist/wallet/index.d.cts +726 -0
  43. package/dist/wallet/index.d.ts +726 -0
  44. package/dist/wallet/index.js +815 -0
  45. package/dist/wallet/index.js.map +1 -0
  46. package/package.json +119 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/clients/core.ts","../src/config/chains.ts","../src/types/config.ts","../src/clients/evm.ts","../src/clients/manager.ts","../src/contracts/abis/erc20.ts","../src/contracts/abis/erc721.ts","../src/contracts/abis/erc1155.ts","../src/contracts/types/index.ts","../src/contracts/deployer/deploy.ts","../src/contracts/interaction/reader.ts","../src/contracts/interaction/writer.ts","../src/utils/logger.ts","../src/wallet/types/index.ts","../src/wallet/batching/batcher.ts","../src/wallet/derivation.ts","../src/wallet/types.ts","../src/wallet/embedded/custody.ts","../src/wallet/session-keys/manager.ts"],"sourcesContent":["// @cfxdevkit/core\n// Conflux SDK – single-package library for building on Conflux Core Space & eSpace\n//\n// Subpath exports (preferred for tree-shaking):\n// import { ClientManager } from '@cfxdevkit/core-core/clients';\n// import { SwapService } from '@cfxdevkit/services';\n// import { ContractReader } from '@cfxdevkit/core-core/contracts';\n// import { generateMnemonic } from '@cfxdevkit/core-core/wallet';\n//\n// Or import everything from the root:\n// import { ClientManager, SwapService, ERC20_ABI } from '@cfxdevkit/core';\n\nexport { formatCFX, parseCFX } from 'cive';\nexport { isAddress as isCoreAddress } from 'cive/utils';\n// ── Re-export useful viem/cive primitives ──────────────────────────────────\nexport { formatUnits, isAddress as isEspaceAddress, parseUnits } from 'viem';\n// ── Clients ────────────────────────────────────────────────────────────────\nexport {\n ClientManager,\n CoreClient,\n CoreTestClient,\n CoreWalletClient,\n EspaceClient,\n EspaceTestClient,\n EspaceWalletClient,\n} from './clients/index.js';\nexport type {\n ClientManagerConfig,\n ClientManagerEvents,\n ClientManagerStatus,\n} from './clients/manager.js';\nexport type { ChainConfig } from './config/chains.js';\n// ── Chain Configuration ────────────────────────────────────────────────────\nexport {\n CORE_LOCAL,\n CORE_MAINNET,\n CORE_TESTNET,\n defaultNetworkSelector,\n EVM_LOCAL,\n EVM_MAINNET,\n EVM_TESTNET,\n getChainConfig,\n getCoreChains,\n getEvmChains,\n getMainnetChains,\n} from './config/index.js';\n// ── Contracts ──────────────────────────────────────────────────────────────\nexport {\n ContractDeployer,\n ContractError,\n ContractReader,\n ContractWriter,\n DeploymentError,\n ERC20_ABI,\n ERC721_ABI,\n ERC1155_ABI,\n InteractionError,\n} from './contracts/index.js';\n\n// ── Types ──────────────────────────────────────────────────────────────────\nexport type {\n Address,\n ChainType,\n CoreAddress,\n EvmAddress,\n Hash,\n UnifiedAccount,\n} from './types/index.js';\n// ── Utils ──────────────────────────────────────────────────────────────────\nexport { logger } from './utils/index.js';\nexport type {\n BatcherOptions,\n BatchResult,\n BatchTransaction,\n EmbeddedWallet,\n EmbeddedWalletOptions,\n SessionKey,\n SessionKeyOptions,\n SessionKeyPermissions,\n SignedTransaction,\n SignTransactionRequest,\n WalletExport,\n WalletManagerOptions,\n} from './wallet/index.js';\n// ── Wallet ─────────────────────────────────────────────────────────────────\nexport {\n // Wallet error classes\n BatcherError,\n deriveAccount,\n deriveAccounts,\n deriveFaucetAccount,\n EmbeddedWalletError,\n EmbeddedWalletManager,\n generateMnemonic,\n SessionKeyError,\n SessionKeyManager,\n TransactionBatcher,\n validateMnemonic,\n WalletError,\n} from './wallet/index.js';\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Core Space Client Implementation\n// Based on proven patterns from DevKit CLI, adapted for unified interface\n\nimport {\n type Address,\n type Chain,\n type TestClient as CiveTestClient,\n createPublicClient,\n createTestClient,\n createWalletClient,\n formatCFX,\n http,\n type PublicClient,\n parseCFX,\n type WalletClient,\n} from 'cive';\nimport { type Account, privateKeyToAccount } from 'cive/accounts';\nimport {\n defineChain,\n encodeFunctionData,\n formatUnits,\n hexAddressToBase32,\n isAddress as isCoreAddress,\n} from 'cive/utils';\nimport { isAddress as isEspaceAddress } from 'viem';\n\n// Chain definitions\nconst conflux = defineChain({\n id: 1029,\n name: 'Conflux Core',\n nativeCurrency: { name: 'Conflux', symbol: 'CFX', decimals: 18 },\n rpcUrls: { default: { http: ['https://main.confluxrpc.com'] } },\n});\n\nconst confluxTestnet = defineChain({\n id: 1,\n name: 'Conflux Core Testnet',\n nativeCurrency: { name: 'Conflux', symbol: 'CFX', decimals: 18 },\n rpcUrls: { default: { http: ['https://test.confluxrpc.com'] } },\n});\n\nimport { getChainConfig, type SupportedChainId } from '../config/chains.js';\nimport type {\n BaseTransaction,\n BlockEvent,\n ChainClient,\n ClientConfig,\n CoreClientInstance,\n EventCallback,\n TestClient,\n TestConfig,\n TransactionEvent,\n TransactionReceipt,\n WalletClient as UnifiedWalletClient,\n UnwatchFunction,\n WalletConfig,\n} from '../types/index.js';\nimport { NodeError } from '../types/index.js';\n\n/**\n * Core Space Client Implementation\n * Wraps cive client with unified interface\n */\nexport class CoreClient implements ChainClient {\n public readonly chainType = 'core' as const;\n public readonly chainId: number;\n public readonly address: Address;\n\n private readonly publicClient: PublicClient;\n private readonly chain: Chain;\n\n constructor(config: ClientConfig) {\n this.chainId = config.chainId;\n\n // Create chain definition\n this.chain = defineChain({\n id: this.chainId,\n name: `ConfluxCore-${this.chainId}`,\n nativeCurrency: {\n decimals: 18,\n name: 'Conflux',\n symbol: 'CFX',\n },\n rpcUrls: {\n default: {\n http: [config.rpcUrl],\n webSocket: config.wsUrl ? [config.wsUrl] : undefined,\n },\n },\n });\n\n // Create public client\n this.publicClient = createPublicClient({\n chain: this.chain,\n transport: http(config.rpcUrl),\n pollingInterval: config.pollingInterval || 1000,\n });\n\n // Address will be set by wallet client\n this.address = '' as Address;\n }\n\n async getBlockNumber(): Promise<bigint> {\n try {\n const epochNumber = await this.publicClient.getEpochNumber();\n return BigInt(epochNumber.toString());\n } catch (error) {\n throw new NodeError(\n `Failed to get block number: ${error instanceof Error ? error.message : String(error)}`,\n 'BLOCK_NUMBER_ERROR',\n 'core',\n { originalError: error }\n );\n }\n }\n\n async getBalance(address: Address): Promise<string> {\n if (!isCoreAddress(address)) {\n throw new NodeError(\n 'Invalid Core address format',\n 'INVALID_ADDRESS',\n 'core'\n );\n }\n\n try {\n const balance = await this.publicClient.getBalance({ address });\n return formatCFX(balance);\n } catch (error) {\n throw new NodeError(\n `Failed to get balance: ${error instanceof Error ? error.message : String(error)}`,\n 'BALANCE_ERROR',\n 'core',\n { address, originalError: error }\n );\n }\n }\n\n async getGasPrice(): Promise<bigint> {\n try {\n const gasPrice = await this.publicClient.getGasPrice();\n return gasPrice;\n } catch (error) {\n throw new NodeError(\n `Failed to get gas price: ${error instanceof Error ? error.message : String(error)}`,\n 'GAS_PRICE_ERROR',\n 'core',\n { originalError: error }\n );\n }\n }\n\n async estimateGas(tx: BaseTransaction): Promise<bigint> {\n try {\n const estimate = await this.publicClient.request({\n method: 'cfx_estimateGasAndCollateral',\n params: [\n {\n to: tx.to as Address,\n value: tx.value ? `0x${tx.value.toString(16)}` : undefined,\n data: tx.data as `0x${string}`,\n },\n ],\n });\n return BigInt(estimate.gasLimit);\n } catch (error) {\n throw new NodeError(\n `Failed to estimate gas: ${error instanceof Error ? error.message : String(error)}`,\n 'GAS_ESTIMATE_ERROR',\n 'core',\n { transaction: tx, originalError: error }\n );\n }\n }\n\n async sendTransaction(_tx: BaseTransaction): Promise<string> {\n throw new NodeError(\n 'Cannot send transaction from public client. Use wallet client instead.',\n 'WALLET_REQUIRED',\n 'core'\n );\n }\n\n async waitForTransaction(hash: string): Promise<TransactionReceipt> {\n try {\n const receipt = await this.publicClient.waitForTransactionReceipt({\n hash: hash as `0x${string}`,\n });\n\n return {\n hash: receipt.transactionHash,\n blockNumber: BigInt(receipt.epochNumber?.toString() || '0'),\n blockHash: receipt.blockHash || '',\n transactionIndex: Number(receipt.index || 0),\n status: receipt.outcomeStatus === 'success' ? 'success' : 'reverted',\n gasUsed: receipt.gasUsed || 0n,\n contractAddress: receipt.contractCreated || undefined,\n logs:\n receipt.log?.map((log: Record<string, unknown>) => ({\n address: (log.address as string) || '',\n topics: (log.topics as string[]) || [],\n data: (log.data as string) || '0x',\n blockNumber: BigInt((log.epochNumber as number)?.toString() || '0'),\n transactionHash: (log.transactionHash as string) || '',\n logIndex: Number(log.logIndex || 0),\n })) || [],\n };\n } catch (error) {\n throw new NodeError(\n `Failed to wait for transaction: ${error instanceof Error ? error.message : String(error)}`,\n 'TRANSACTION_WAIT_ERROR',\n 'core',\n { hash, originalError: error }\n );\n }\n }\n\n async getTokenBalance(\n tokenAddress: Address,\n holderAddress?: Address\n ): Promise<string> {\n const holder = holderAddress || this.address;\n\n if (!this.isValidAddress(tokenAddress)) {\n throw new NodeError(\n 'Invalid token address format',\n 'INVALID_ADDRESS',\n 'core',\n { tokenAddress }\n );\n }\n if (!this.isValidAddress(holder)) {\n throw new NodeError(\n 'Invalid holder address format',\n 'INVALID_ADDRESS',\n 'core',\n { holder }\n );\n }\n\n try {\n const [balance, decimals] = await Promise.all([\n this.publicClient.readContract({\n address: tokenAddress,\n abi: [\n {\n name: 'balanceOf',\n type: 'function',\n inputs: [{ name: 'account', type: 'address' }],\n outputs: [{ name: '', type: 'uint256' }],\n stateMutability: 'view',\n },\n ],\n functionName: 'balanceOf',\n args: [holder],\n }),\n this.publicClient.readContract({\n address: tokenAddress,\n abi: [\n {\n name: 'decimals',\n type: 'function',\n inputs: [],\n outputs: [{ name: '', type: 'uint8' }],\n stateMutability: 'view',\n },\n ],\n functionName: 'decimals',\n }),\n ]);\n\n return this.formatTokenAmount(balance as bigint, Number(decimals));\n } catch (error) {\n throw new NodeError(\n `Failed to get token balance: ${error instanceof Error ? error.message : String(error)}`,\n 'TOKEN_BALANCE_ERROR',\n 'core',\n { tokenAddress, holder, originalError: error }\n );\n }\n }\n\n watchBlocks(callback: EventCallback<BlockEvent>): UnwatchFunction {\n return this.publicClient.watchEpochNumber({\n emitMissed: false,\n epochTag: 'latest_mined',\n onEpochNumber: async (epochNumber: bigint) => {\n try {\n const blockHashes = await this.publicClient.getBlocksByEpoch({\n epochNumber,\n });\n for (const hash of blockHashes) {\n try {\n const block = await this.publicClient.getBlock({\n blockHash: hash as `0x${string}`,\n });\n\n const blockEvent: BlockEvent = {\n chainType: 'core',\n blockNumber: BigInt(block.epochNumber?.toString() || '0'),\n blockHash: block.hash || '',\n timestamp: Number(block.timestamp || 0),\n transactionCount: block.transactions?.length || 0,\n };\n\n callback(blockEvent);\n } catch (error) {\n console.error(`Failed to process block ${hash}:`, error);\n }\n }\n } catch (error) {\n console.error(\n `Failed to get blocks for epoch ${epochNumber}:`,\n error\n );\n }\n },\n });\n }\n\n watchTransactions(\n callback: EventCallback<TransactionEvent>\n ): UnwatchFunction {\n return this.publicClient.watchEpochNumber({\n emitMissed: false,\n epochTag: 'latest_mined',\n onEpochNumber: async (epochNumber: bigint) => {\n try {\n const blockHashes = await this.publicClient.getBlocksByEpoch({\n epochNumber,\n });\n for (const hash of blockHashes) {\n try {\n const block = await this.publicClient.getBlock({\n blockHash: hash as `0x${string}`,\n });\n\n await Promise.all(\n (block.transactions || []).map(\n async (txHash: `0x${string}`) => {\n try {\n const tx = await this.publicClient.getTransaction({\n hash: txHash,\n });\n\n const txEvent: TransactionEvent = {\n chainType: 'core',\n hash: tx.hash,\n from: tx.from,\n to: tx.to || undefined,\n value: tx.value || 0n,\n blockNumber: BigInt(\n block.epochNumber?.toString() || '0'\n ),\n };\n\n callback(txEvent);\n } catch (error) {\n console.error(\n `Failed to get transaction ${txHash}:`,\n error\n );\n }\n }\n )\n );\n } catch (error) {\n console.error(`Failed to process block ${hash}:`, error);\n }\n }\n } catch (error) {\n console.error(\n `Failed to get blocks for epoch ${epochNumber}:`,\n error\n );\n }\n },\n });\n }\n\n isValidAddress(address: string): boolean {\n return isCoreAddress(address);\n }\n\n formatAmount(amount: bigint): string {\n return formatCFX(amount);\n }\n\n parseAmount(amount: string): bigint {\n return parseCFX(amount);\n }\n\n getInternalClient(): PublicClient {\n return this.publicClient;\n }\n\n private formatTokenAmount(amount: bigint, decimals: number): string {\n const formatted = formatUnits(amount, decimals);\n return Number(formatted).toFixed(4);\n }\n}\n\n/**\n * Core Space Wallet Client Implementation\n */\nexport class CoreWalletClient implements UnifiedWalletClient {\n public readonly chainType = 'core' as const;\n public readonly address: Address;\n public readonly chainId: number;\n\n private readonly walletClient: WalletClient;\n private readonly publicClient: PublicClient;\n private readonly account: Account;\n private readonly chain: Chain;\n\n constructor(config: WalletConfig) {\n this.chainId = config.chainId;\n\n // Create chain definition\n this.chain = defineChain({\n id: config.chainId,\n name: `ConfluxCore-${config.chainId}`,\n nativeCurrency: {\n decimals: 18,\n name: 'Conflux',\n symbol: 'CFX',\n },\n rpcUrls: {\n default: {\n http: [config.rpcUrl],\n webSocket: config.wsUrl ? [config.wsUrl] : undefined,\n },\n },\n });\n\n // Create account from private key\n this.account = privateKeyToAccount(config.privateKey as `0x${string}`, {\n networkId: config.chainId,\n });\n this.address = this.account.address;\n\n // Create wallet client\n this.walletClient = createWalletClient({\n account: this.account,\n chain: this.chain,\n transport: http(config.rpcUrl),\n pollingInterval: config.pollingInterval || 1000,\n });\n\n // Create public client for transaction receipts\n this.publicClient = createPublicClient({\n chain: this.chain,\n transport: http(config.rpcUrl),\n pollingInterval: config.pollingInterval || 1000,\n });\n }\n\n async sendTransaction(tx: BaseTransaction): Promise<string> {\n try {\n return await this.walletClient.sendTransaction({\n to: tx.to as Address,\n value: tx.value,\n data: tx.data as `0x${string}`,\n gas: tx.gasLimit,\n gasPrice: tx.gasPrice,\n nonce: tx.nonce,\n account: this.account,\n chain: this.chain,\n });\n } catch (error) {\n throw new NodeError(\n `Failed to send transaction: ${error instanceof Error ? error.message : String(error)}`,\n 'TRANSACTION_SEND_ERROR',\n 'core',\n { transaction: tx, originalError: error }\n );\n }\n }\n\n async signMessage(message: string): Promise<string> {\n try {\n return await this.walletClient.signMessage({\n account: this.account,\n message,\n });\n } catch (error) {\n throw new NodeError(\n `Failed to sign message: ${error instanceof Error ? error.message : String(error)}`,\n 'MESSAGE_SIGN_ERROR',\n 'core',\n { message, originalError: error }\n );\n }\n }\n\n getInternalClient(): WalletClient {\n return this.walletClient;\n }\n\n async waitForTransaction(hash: string): Promise<TransactionReceipt> {\n try {\n const receipt = await this.publicClient.waitForTransactionReceipt({\n hash: hash as `0x${string}`,\n timeout: 5_000, // 5 second timeout for faster response\n });\n\n return {\n hash: receipt.transactionHash,\n blockNumber: BigInt(receipt.epochNumber?.toString() || '0'),\n blockHash: receipt.blockHash || '',\n transactionIndex: Number(receipt.index || 0),\n status: receipt.outcomeStatus === 'success' ? 'success' : 'reverted',\n gasUsed: receipt.gasUsed || 0n,\n contractAddress: receipt.contractCreated || undefined,\n logs:\n receipt.log?.map((log: Record<string, unknown>) => ({\n address: (log.address as string) || '',\n topics: (log.topics as string[]) || [],\n data: (log.data as string) || '0x',\n blockNumber: BigInt((log.epochNumber as number)?.toString() || '0'),\n transactionHash: (log.transactionHash as string) || '',\n logIndex: Number(log.logIndex || 0),\n })) || [],\n };\n } catch (error) {\n throw new NodeError(\n `Failed to wait for transaction: ${error instanceof Error ? error.message : String(error)}`,\n 'TRANSACTION_WAIT_ERROR',\n 'core',\n { hash, originalError: error }\n );\n }\n }\n\n /**\n * Unified faucet functionality\n * Automatically detects address type and sends CFX accordingly:\n * - Core address: Direct transfer\n * - eSpace address: Cross-chain transfer via internal contract\n */\n async faucet(address: string, amount: string): Promise<string> {\n // Detect address type\n const isCoreAddr = isCoreAddress(address);\n const isEspaceAddr = isEspaceAddress(address);\n\n if (!isCoreAddr && !isEspaceAddr) {\n throw new NodeError(\n 'Invalid address format (must be Core or eSpace address)',\n 'INVALID_ADDRESS',\n 'core',\n { address }\n );\n }\n\n try {\n if (isCoreAddr) {\n // Direct Core space transfer\n return await this.walletClient.sendTransaction({\n chain: this.chain,\n account: this.account,\n to: address as Address,\n value: parseCFX(amount),\n });\n } else {\n // Cross-chain transfer to eSpace via internal contract\n return await this.walletClient.sendTransaction({\n chain: this.chain,\n account: this.account,\n to: hexAddressToBase32({\n hexAddress: '0x0888000000000000000000000000000000000006',\n networkId: this.chain.id,\n }),\n value: parseCFX(amount),\n data: encodeFunctionData({\n abi: [\n {\n type: 'function',\n name: 'transferEVM',\n inputs: [{ name: 'to', type: 'bytes20' }],\n outputs: [{ name: 'output', type: 'bytes' }],\n stateMutability: 'payable',\n },\n ],\n functionName: 'transferEVM',\n args: [address as `0x${string}`],\n }),\n });\n }\n } catch (error) {\n throw new NodeError(\n `Failed to send faucet transaction: ${error instanceof Error ? error.message : String(error)}`,\n 'FAUCET_ERROR',\n 'core',\n { address, amount, originalError: error }\n );\n }\n }\n\n /**\n * Cross-chain faucet functionality (Core → eSpace)\n * Sends CFX from Core space to eSpace address via internal contract\n * @deprecated Use faucet() instead which auto-detects address type\n */\n async faucetToEspace(espaceAddress: string, amount: string): Promise<string> {\n if (!isEspaceAddress(espaceAddress)) {\n throw new NodeError(\n 'Invalid eSpace address format',\n 'INVALID_ADDRESS',\n 'core',\n { espaceAddress }\n );\n }\n\n try {\n return await this.walletClient.sendTransaction({\n chain: this.chain,\n account: this.account,\n to: hexAddressToBase32({\n hexAddress: '0x0888000000000000000000000000000000000006',\n networkId: this.chain.id,\n }),\n value: parseCFX(amount),\n data: encodeFunctionData({\n abi: [\n {\n type: 'function',\n name: 'transferEVM',\n inputs: [{ name: 'to', type: 'bytes20' }],\n outputs: [{ name: 'output', type: 'bytes' }],\n stateMutability: 'payable',\n },\n ],\n functionName: 'transferEVM',\n args: [espaceAddress as `0x${string}`],\n }),\n });\n } catch (error) {\n throw new NodeError(\n `Failed to send faucet transaction to eSpace: ${error instanceof Error ? error.message : String(error)}`,\n 'FAUCET_ERROR',\n 'core',\n { espaceAddress, amount, originalError: error }\n );\n }\n }\n\n /**\n * Deploy a contract to Core Space\n */\n async deployContract(\n abi: unknown[],\n bytecode: string,\n constructorArgs: unknown[] = []\n ): Promise<string> {\n try {\n const hash = await this.walletClient.deployContract({\n account: this.account,\n chain: this.chain,\n abi,\n bytecode: bytecode as `0x${string}`,\n args: constructorArgs,\n });\n\n // Wait for transaction to be mined and get the contract address\n const receipt = await this.waitForTransaction(hash);\n\n if (!receipt.contractAddress) {\n throw new Error('Contract address not found in transaction receipt');\n }\n\n // The contract address is already in Core Space format from Cive\n // No need to convert since cive returns Core Space addresses directly\n return receipt.contractAddress;\n } catch (error) {\n throw new NodeError(\n `Failed to deploy contract: ${error instanceof Error ? error.message : String(error)}`,\n 'DEPLOYMENT_ERROR',\n 'core',\n { abi, bytecode, constructorArgs, originalError: error }\n );\n }\n }\n\n /**\n * Call a contract method (read-only)\n */\n async callContract<T = unknown>(\n address: string,\n abi: unknown[],\n functionName: string,\n args: unknown[] = []\n ): Promise<T> {\n try {\n // Use the public client for read operations instead of wallet client\n const result = await this.publicClient.readContract({\n address: address as Address,\n abi,\n functionName,\n args,\n });\n return result as T;\n } catch (error) {\n throw new NodeError(\n `Failed to call contract: ${error instanceof Error ? error.message : String(error)}`,\n 'CONTRACT_CALL_ERROR',\n 'core',\n { address, functionName, args, originalError: error }\n );\n }\n }\n\n /**\n * Write to a contract (transaction)\n */\n async writeContract(\n address: string,\n abi: unknown[],\n functionName: string,\n args: unknown[] = [],\n value?: bigint\n ): Promise<string> {\n try {\n const hash = await this.walletClient.writeContract({\n account: this.account,\n chain: this.chain,\n address: address as Address,\n abi,\n functionName,\n args,\n value,\n });\n return hash;\n } catch (error) {\n throw new NodeError(\n `Failed to write to contract: ${error instanceof Error ? error.message : String(error)}`,\n 'CONTRACT_WRITE_ERROR',\n 'core',\n { address, functionName, args, value, originalError: error }\n );\n }\n }\n}\n\n/**\n * Core Space Test Client Implementation\n */\nexport class CoreTestClient extends CoreClient implements TestClient {\n private readonly testClient: CiveTestClient;\n\n constructor(config: TestConfig) {\n super(config);\n\n this.testClient = createTestClient({\n chain: this.chainId === 1029 ? conflux : confluxTestnet,\n transport: http(config.rpcUrl),\n pollingInterval: config.pollingInterval || 1000,\n });\n }\n\n async mine(blocks = 1): Promise<void> {\n try {\n await this.testClient.mine({ blocks });\n } catch (error) {\n throw new NodeError(\n `Failed to mine blocks: ${error instanceof Error ? error.message : String(error)}`,\n 'MINE_ERROR',\n 'core',\n { blocks, originalError: error }\n );\n }\n }\n\n async setNextBlockTimestamp(_timestamp: number): Promise<void> {\n // Implementation would depend on available test client methods\n throw new NodeError(\n 'setNextBlockTimestamp not implemented for Core client',\n 'NOT_IMPLEMENTED',\n 'core'\n );\n }\n\n async increaseTime(_seconds: number): Promise<void> {\n // Implementation would depend on available test client methods\n throw new NodeError(\n 'increaseTime not implemented for Core client',\n 'NOT_IMPLEMENTED',\n 'core'\n );\n }\n\n async impersonateAccount(_address: Address): Promise<void> {\n throw new NodeError(\n 'impersonateAccount not implemented for Core client',\n 'NOT_IMPLEMENTED',\n 'core'\n );\n }\n\n async stopImpersonatingAccount(_address: Address): Promise<void> {\n throw new NodeError(\n 'stopImpersonatingAccount not implemented for Core client',\n 'NOT_IMPLEMENTED',\n 'core'\n );\n }\n\n async setBalance(_address: Address, _balance: bigint): Promise<void> {\n throw new NodeError(\n 'setBalance not implemented for Core client',\n 'NOT_IMPLEMENTED',\n 'core'\n );\n }\n\n async getStorageAt(_address: Address, _slot: string): Promise<string> {\n throw new NodeError(\n 'getStorageAt not implemented for Core client',\n 'NOT_IMPLEMENTED',\n 'core'\n );\n }\n\n async setStorageAt(\n _address: Address,\n _slot: string,\n _value: string\n ): Promise<void> {\n throw new NodeError(\n 'setStorageAt not implemented for Core client',\n 'NOT_IMPLEMENTED',\n 'core'\n );\n }\n\n getInternalTestClient(): CiveTestClient {\n return this.testClient;\n }\n}\n\n/**\n * Create a Core client instance with all components\n */\nexport async function createCoreClient(\n config: ClientConfig\n): Promise<CoreClientInstance> {\n const chainConfig = getChainConfig(config.chainId as SupportedChainId);\n\n if (chainConfig.type !== 'core') {\n throw new NodeError(\n `Invalid chain type for Core client: ${chainConfig.type}`,\n 'INVALID_CHAIN_TYPE',\n 'core'\n );\n }\n\n // Update config with proper RPC URL if not provided\n const clientConfig: ClientConfig = {\n ...config,\n rpcUrl:\n config.rpcUrl ||\n chainConfig.rpcUrls.default.http[0] ||\n 'http://localhost:12537',\n wsUrl: config.wsUrl || chainConfig.rpcUrls.default.webSocket?.[0],\n };\n\n const publicClient = new CoreClient(clientConfig);\n\n let walletClient: CoreWalletClient | undefined;\n let testClient: CoreTestClient | undefined;\n\n if (config.account) {\n let privateKey: string;\n if (typeof config.account === 'string') {\n privateKey = config.account;\n } else {\n privateKey = config.account.privateKey;\n }\n\n const walletConfig: WalletConfig = {\n ...clientConfig,\n privateKey,\n accountIndex:\n typeof config.account === 'object' ? config.account.accountIndex : 0,\n };\n walletClient = new CoreWalletClient(walletConfig);\n }\n\n if (config.testMode) {\n const testConfig: TestConfig = {\n ...clientConfig,\n enableTestMode: true,\n };\n testClient = new CoreTestClient(testConfig);\n }\n\n return {\n publicClient,\n walletClient,\n testClient,\n };\n}\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Centralized Chain Configuration\n// Matches Hardhat configuration with consistent naming across all clients\n\nimport type { Chain as CiveChain } from 'cive';\nimport { defineChain } from 'cive/utils';\nimport type { Chain as ViemChain } from 'viem';\nimport { defineChain as defineEvmChain } from 'viem';\n\nexport type SupportedChainId = 1029 | 1 | 2029 | 1030 | 71 | 2030;\n\nexport interface ChainConfig {\n id: SupportedChainId;\n name: string;\n type: 'core' | 'evm';\n testnet: boolean;\n nativeCurrency: {\n name: string;\n symbol: string;\n decimals: number;\n };\n rpcUrls: {\n default: {\n http: string[];\n webSocket?: string[];\n };\n };\n blockExplorers?: {\n default: {\n name: string;\n url: string;\n };\n };\n contracts?: {\n multicall3?: {\n address: `0x${string}`;\n blockCreated?: number;\n };\n };\n}\n\n// Core Space Chains (Conflux Protocol)\nexport const CORE_MAINNET: ChainConfig = {\n id: 1029,\n name: 'conflux-core',\n type: 'core',\n testnet: false,\n nativeCurrency: {\n name: 'Conflux',\n symbol: 'CFX',\n decimals: 18,\n },\n rpcUrls: {\n default: {\n http: ['https://main.confluxrpc.com'],\n webSocket: ['wss://main.confluxrpc.com/ws'],\n },\n },\n blockExplorers: {\n default: {\n name: 'ConfluxScan',\n url: 'https://confluxscan.io',\n },\n },\n};\n\nexport const CORE_TESTNET: ChainConfig = {\n id: 1,\n name: 'conflux-core-testnet',\n type: 'core',\n testnet: true,\n nativeCurrency: {\n name: 'Conflux',\n symbol: 'CFX',\n decimals: 18,\n },\n rpcUrls: {\n default: {\n http: ['https://test.confluxrpc.com'],\n webSocket: ['wss://test.confluxrpc.com/ws'],\n },\n },\n blockExplorers: {\n default: {\n name: 'ConfluxScan Testnet',\n url: 'https://testnet.confluxscan.io',\n },\n },\n};\n\nexport const CORE_LOCAL: ChainConfig = {\n id: 2029,\n name: 'conflux-core-local',\n type: 'core',\n testnet: true,\n nativeCurrency: {\n name: 'Conflux',\n symbol: 'CFX',\n decimals: 18,\n },\n rpcUrls: {\n default: {\n http: ['http://localhost:12537'],\n webSocket: ['ws://localhost:12536'],\n },\n },\n};\n\n// EVM Space Chains (Ethereum Compatible)\nexport const EVM_MAINNET: ChainConfig = {\n id: 1030,\n name: 'conflux-espace',\n type: 'evm',\n testnet: false,\n nativeCurrency: {\n name: 'Conflux',\n symbol: 'CFX',\n decimals: 18,\n },\n rpcUrls: {\n default: {\n http: ['https://evm.confluxrpc.com'],\n },\n },\n blockExplorers: {\n default: {\n name: 'ConfluxScan eSpace',\n url: 'https://evm.confluxscan.net',\n },\n },\n contracts: {\n multicall3: {\n address: '0xcA11bde05977b3631167028862bE2a173976CA11',\n blockCreated: 62512243,\n },\n },\n};\n\nexport const EVM_TESTNET: ChainConfig = {\n id: 71,\n name: 'conflux-espace-testnet',\n type: 'evm',\n testnet: true,\n nativeCurrency: {\n name: 'Conflux',\n symbol: 'CFX',\n decimals: 18,\n },\n rpcUrls: {\n default: {\n http: ['https://evmtestnet.confluxrpc.com'],\n },\n },\n blockExplorers: {\n default: {\n name: 'ConfluxScan eSpace Testnet',\n url: 'https://evmtestnet.confluxscan.net',\n },\n },\n contracts: {\n multicall3: {\n address: '0xcA11bde05977b3631167028862bE2a173976CA11',\n blockCreated: 117499050,\n },\n },\n};\n\nexport const EVM_LOCAL: ChainConfig = {\n id: 2030,\n name: 'conflux-espace-local',\n type: 'evm',\n testnet: true,\n nativeCurrency: {\n name: 'Conflux',\n symbol: 'CFX',\n decimals: 18,\n },\n rpcUrls: {\n default: {\n http: ['http://localhost:8545'],\n },\n },\n};\n\n// All supported chains\nexport const SUPPORTED_CHAINS: Record<SupportedChainId, ChainConfig> = {\n 1029: CORE_MAINNET,\n 1: CORE_TESTNET,\n 2029: CORE_LOCAL,\n 1030: EVM_MAINNET,\n 71: EVM_TESTNET,\n 2030: EVM_LOCAL,\n};\n\n// Chain utilities\nexport function getChainConfig(chainId: SupportedChainId): ChainConfig {\n const config = SUPPORTED_CHAINS[chainId];\n if (!config) {\n throw new Error(`Unsupported chain ID: ${chainId}`);\n }\n return config;\n}\n\nexport function isValidChainId(chainId: number): chainId is SupportedChainId {\n return chainId in SUPPORTED_CHAINS;\n}\n\nexport function getCoreChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(\n (chain) => chain.type === 'core'\n );\n}\n\nexport function getEvmChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter(\n (chain) => chain.type === 'evm'\n );\n}\n\nexport function getMainnetChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter((chain) => !chain.testnet);\n}\n\nexport function getTestnetChains(): ChainConfig[] {\n return Object.values(SUPPORTED_CHAINS).filter((chain) => chain.testnet);\n}\n\n// Convert to native chain objects\nexport function toCiveChain(config: ChainConfig): CiveChain {\n if (config.type !== 'core') {\n throw new Error(`Cannot convert ${config.type} chain to Cive chain`);\n }\n\n return defineChain({\n id: config.id,\n name: config.name,\n nativeCurrency: config.nativeCurrency,\n rpcUrls: config.rpcUrls,\n blockExplorers: config.blockExplorers,\n });\n}\n\nexport function toViemChain(config: ChainConfig): ViemChain {\n if (config.type !== 'evm') {\n throw new Error(`Cannot convert ${config.type} chain to Viem chain`);\n }\n\n return defineEvmChain({\n id: config.id,\n name: config.name,\n nativeCurrency: config.nativeCurrency,\n rpcUrls: config.rpcUrls,\n blockExplorers: config.blockExplorers,\n contracts: config.contracts,\n });\n}\n\n// Network selector utility with automatic local switching\nexport class NetworkSelector {\n private currentChainId: SupportedChainId;\n private previousChainId: SupportedChainId | null = null;\n private listeners: Set<(chainId: SupportedChainId) => void> = new Set();\n private nodeRunningListeners: Set<(isRunning: boolean) => void> = new Set();\n private isNodeRunning = false;\n private lockedToLocal = false;\n\n constructor(initialChainId: SupportedChainId = 1) {\n this.currentChainId = initialChainId;\n }\n\n getCurrentChain(): ChainConfig {\n return getChainConfig(this.currentChainId);\n }\n\n getCurrentChainId(): SupportedChainId {\n return this.currentChainId;\n }\n\n /**\n * Switch to a specific chain\n * @param chainId - Chain ID to switch to\n * @param force - Force switch even if node is running (for wallet operations)\n */\n switchChain(chainId: SupportedChainId, force = false): void {\n if (!isValidChainId(chainId)) {\n throw new Error(`Invalid chain ID: ${chainId}`);\n }\n\n // If node is running and we're trying to switch to non-local, only allow if forced\n if (this.isNodeRunning && !this.isLocalChain(chainId) && !force) {\n console.warn(\n `Cannot switch to chain ${chainId} while local node is running. Use force=true for wallet operations.`\n );\n return;\n }\n\n if (this.currentChainId !== chainId) {\n this.currentChainId = chainId;\n this.notifyListeners();\n }\n }\n\n /**\n * Called when local node starts - automatically switches to local chains\n */\n onNodeStart(\n coreChainId: SupportedChainId = 2029,\n evmChainId: SupportedChainId = 2030\n ): void {\n if (!this.isNodeRunning) {\n // Store previous chain for restoration later\n if (!this.isLocal()) {\n this.previousChainId = this.currentChainId;\n }\n\n this.isNodeRunning = true;\n this.lockedToLocal = true;\n\n // Switch to appropriate local chain based on current chain type\n const targetLocalChain = this.isEvm() ? evmChainId : coreChainId;\n this.switchChain(targetLocalChain, true); // Force switch to local\n\n // Notify node running listeners\n this.notifyNodeRunningListeners();\n }\n }\n\n /**\n * Called when local node stops - can restore previous chain\n */\n onNodeStop(restorePrevious = true): void {\n if (this.isNodeRunning) {\n this.isNodeRunning = false;\n this.lockedToLocal = false;\n\n // Restore previous chain if requested and available\n if (restorePrevious && this.previousChainId) {\n this.switchChain(this.previousChainId, true);\n this.previousChainId = null;\n }\n\n // Notify node running listeners\n this.notifyNodeRunningListeners();\n }\n }\n\n /**\n * Check if node is currently running\n */\n getNodeRunningStatus(): boolean {\n return this.isNodeRunning;\n }\n\n /**\n * Check if selector is locked to local chains\n */\n isLockedToLocal(): boolean {\n return this.lockedToLocal;\n }\n\n onChainChange(listener: (chainId: SupportedChainId) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n onNodeRunningChange(listener: (isRunning: boolean) => void): () => void {\n this.nodeRunningListeners.add(listener);\n return () => this.nodeRunningListeners.delete(listener);\n }\n\n private notifyListeners(): void {\n for (const listener of this.listeners) {\n try {\n listener(this.currentChainId);\n } catch (error) {\n console.error('Error in chain change listener:', error);\n }\n }\n }\n\n private notifyNodeRunningListeners(): void {\n for (const listener of this.nodeRunningListeners) {\n try {\n listener(this.isNodeRunning);\n } catch (error) {\n console.error('Error in node running listener:', error);\n }\n }\n }\n\n private isLocalChain(chainId: SupportedChainId): boolean {\n return chainId === 2029 || chainId === 2030;\n }\n\n // Helper methods for chain type detection\n isCore(): boolean {\n return this.getCurrentChain().type === 'core';\n }\n\n isEvm(): boolean {\n return this.getCurrentChain().type === 'evm';\n }\n\n isTestnet(): boolean {\n return this.getCurrentChain().testnet;\n }\n\n isLocal(): boolean {\n return this.currentChainId === 2029 || this.currentChainId === 2030;\n }\n\n // Get corresponding chain IDs\n getCorrespondingChainId(): SupportedChainId | null {\n switch (this.currentChainId) {\n case 1029:\n return 1030; // Core mainnet -> eSpace mainnet\n case 1030:\n return 1029; // eSpace mainnet -> Core mainnet\n case 1:\n return 71; // Core testnet -> eSpace testnet\n case 71:\n return 1; // eSpace testnet -> Core testnet\n case 2029:\n return 2030; // Core local -> eSpace local\n case 2030:\n return 2029; // eSpace local -> Core local\n default:\n return null;\n }\n }\n\n /**\n * Update local chain configurations with actual node URLs\n * Called when ServerManager starts with specific ports\n */\n updateLocalChainUrls(\n coreRpcPort: number,\n evmRpcPort: number,\n wsPort?: number\n ): void {\n // Update Core local chain\n const coreLocal = SUPPORTED_CHAINS[2029];\n if (coreLocal) {\n coreLocal.rpcUrls.default.http = [`http://localhost:${coreRpcPort}`];\n if (wsPort) {\n coreLocal.rpcUrls.default.webSocket = [`ws://localhost:${wsPort}`];\n }\n }\n\n // Update eSpace local chain\n const evmLocal = SUPPORTED_CHAINS[2030];\n if (evmLocal) {\n evmLocal.rpcUrls.default.http = [`http://localhost:${evmRpcPort}`];\n }\n }\n}\n\n// Default network selector instance\nexport const defaultNetworkSelector = new NetworkSelector();\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Core Configuration Types\n// Based on proven patterns from DevKit CLI and @xcfx/node\n\nexport interface NodeConfig {\n // Chain Configuration\n readonly chainId?: number; // Core space chain ID (default: 2029)\n readonly evmChainId?: number; // EVM space chain ID (default: 2030)\n\n // Network Ports\n readonly jsonrpcHttpPort?: number; // Core HTTP RPC port (default: 12537)\n readonly jsonrpcHttpEthPort?: number; // EVM HTTP RPC port (default: 8545)\n readonly jsonrpcWsPort?: number; // Core WebSocket port (default: 12538)\n readonly jsonrpcWsEthPort?: number; // EVM WebSocket port (default: 8546)\n\n // // Development Settings\n // readonly devBlockIntervalMs?: number; // Block generation interval (default: 1000)\n // readonly devPackTxImmediately?: boolean; // Pack transactions immediately\n\n // Data & Logging\n readonly confluxDataDir?: string; // Data directory path\n readonly log?: boolean; // Enable console logging\n readonly logConf?: string; // Custom log configuration file\n\n // Genesis Configuration\n readonly genesisSecrets?: readonly string[]; // Core space genesis private keys\n readonly genesisEvmSecrets?: readonly string[]; // EVM space genesis private keys\n readonly miningAuthor?: string; // Mining rewards recipient\n\n // Node Type\n readonly nodeType?: 'full' | 'archive' | 'light';\n readonly blockDbType?: 'rocksdb' | 'sqlite';\n}\n\nexport interface ExtendedNodeConfig extends NodeConfig {\n // DevKit Extensions\n readonly accountCount?: number; // Number of accounts to generate per chain\n readonly silent?: boolean; // Suppress all logging\n readonly fundAccounts?: boolean; // Auto-fund generated accounts\n readonly enabledChains?: readonly ('core' | 'evm')[]; // Active chains\n\n // Derivation paths for account generation\n readonly derivationPaths?: {\n readonly core: string; // Core derivation path template\n readonly evm: string; // EVM derivation path template\n };\n}\n\n// Address and Hash Types\nexport type Address = string;\nexport type CoreAddress = string; // cfx:... format\nexport type EvmAddress = string; // 0x... format\nexport type Hash = string;\nexport type ChainType = 'core' | 'evm';\n\n// Account Types\nexport interface UnifiedAccount {\n readonly id: string; // Unique identifier\n readonly name: string; // Human-readable name\n readonly index: number; // Derivation index\n readonly privateKey: string; // Private key (hex format)\n readonly derivationPath: string; // BIP32 derivation path\n\n // Chain-specific addresses (same private key, different formats)\n readonly coreAddress: CoreAddress; // cfx:... format\n readonly evmAddress: EvmAddress; // 0x... format\n\n // Chain-specific state\n readonly coreBalance: bigint;\n readonly evmBalance: bigint;\n readonly coreNonce: number;\n readonly evmNonce: number;\n\n // Metadata\n readonly isActive: boolean;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n}\n\n// Client Status Types\nexport interface ChainStatus {\n readonly isRunning: boolean;\n readonly chainId: number;\n readonly blockNumber: bigint;\n readonly gasPrice: bigint;\n readonly peerCount: number;\n readonly syncStatus: 'syncing' | 'synced';\n readonly latestBlockHash: string;\n readonly mining: boolean;\n readonly pendingTransactions: number;\n readonly rpcEndpoint: string;\n readonly wsEndpoint?: string;\n}\n\nexport interface NodeStatus {\n readonly isRunning: boolean;\n readonly uptime: number;\n readonly startTime: Date | null;\n readonly core: ChainStatus;\n readonly evm: ChainStatus;\n readonly dataDir: string;\n readonly config: NodeConfig;\n readonly mining: MiningStatus;\n}\n\nexport interface MiningStatus {\n readonly isRunning: boolean;\n readonly interval: number;\n readonly blocksMined: number;\n readonly startTime: Date | null;\n readonly lastBlockTime: Date | null;\n}\n\n// Transaction Types\nexport interface BaseTransaction {\n readonly to?: string;\n readonly value?: bigint;\n readonly data?: string;\n readonly gasLimit?: bigint;\n readonly gasPrice?: bigint;\n readonly nonce?: number;\n}\n\nexport interface TransactionReceipt {\n readonly hash: string;\n readonly blockNumber: bigint;\n readonly blockHash: string;\n readonly transactionIndex: number;\n readonly status: 'success' | 'reverted';\n readonly gasUsed: bigint;\n readonly contractAddress?: string;\n readonly logs: readonly Log[];\n}\n\nexport interface Log {\n readonly address: string;\n readonly topics: readonly string[];\n readonly data: string;\n readonly blockNumber: bigint;\n readonly transactionHash: string;\n readonly logIndex: number;\n}\n\n// Error Types\nexport interface ConfluxNodeError extends Error {\n readonly code: string;\n readonly chain?: ChainType;\n readonly context?: Record<string, unknown>;\n}\n\nexport class NodeError extends Error implements ConfluxNodeError {\n public readonly code: string;\n public readonly chain?: ChainType;\n public readonly context?: Record<string, unknown>;\n\n constructor(\n message: string,\n code: string,\n chain?: ChainType,\n context?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'NodeError';\n this.code = code;\n this.chain = chain;\n this.context = context;\n }\n}\n\n// Event Types\nexport interface BlockEvent {\n readonly chainType: ChainType;\n readonly blockNumber: bigint;\n readonly blockHash: string;\n readonly timestamp: number;\n readonly transactionCount: number;\n}\n\nexport interface TransactionEvent {\n readonly chainType: ChainType;\n readonly hash: string;\n readonly from: string;\n readonly to?: string;\n readonly value: bigint;\n readonly blockNumber: bigint;\n}\n\n// Utility Types\nexport type EventCallback<T> = (event: T) => void;\nexport type UnwatchFunction = () => void;\n\n// Server Management Types\nexport type ServerStatus =\n | 'stopped'\n | 'starting'\n | 'running'\n | 'stopping'\n | 'error';\n\nexport interface ServerConfig {\n readonly coreRpcPort?: number;\n readonly evmRpcPort?: number;\n readonly wsPort?: number;\n readonly chainId?: number;\n readonly evmChainId?: number;\n readonly accounts?: number;\n readonly balance?: string;\n readonly mnemonic?: string;\n readonly logging?: boolean;\n readonly detached?: boolean;\n readonly mining?: MiningConfig;\n readonly devBlockIntervalMs?: number; // Auto block generation interval in ms (undefined = disabled)\n readonly devPackTxImmediately?: boolean; // Pack transactions immediately for responsiveness\n readonly dataDir?: string; // Data directory for Conflux node (default: /workspace/.conflux-dev)\n}\n\nexport interface MiningConfig {\n readonly enabled: boolean;\n readonly interval: number; // milliseconds between blocks\n readonly autoStart: boolean; // start mining when server starts\n}\n\nexport interface AccountInfo {\n readonly index: number;\n readonly privateKey: string;\n readonly coreAddress: string;\n readonly evmAddress: string;\n readonly mnemonic: string;\n readonly path: string;\n readonly evmPrivateKey?: string; // Ethereum-derived private key for EVM operations\n readonly evmPath?: string; // Ethereum derivation path (m/44'/60'/0'/0/i)\n}\n\n// Additional types will be migrated from devkit-node as needed\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// EVM Space Client Implementation (eSpace)\n// Based on proven patterns from DevKit CLI, adapted for unified interface\n\nimport {\n type Address,\n type Chain,\n createPublicClient,\n createTestClient,\n createWalletClient,\n defineChain,\n encodeFunctionData,\n formatEther,\n http,\n isAddress as isEvmAddress,\n type PublicClient,\n parseEther,\n type TestClient as ViemTestClient,\n type WalletClient,\n} from 'viem';\nimport { type Account, privateKeyToAccount } from 'viem/accounts';\nimport { getChainConfig, type SupportedChainId } from '../config/chains.js';\nimport type {\n BaseTransaction,\n BlockEvent,\n ChainClient,\n ClientConfig,\n EspaceClientInstance,\n EventCallback,\n TestClient,\n TestConfig,\n TransactionEvent,\n TransactionReceipt,\n WalletClient as UnifiedWalletClient,\n WalletConfig,\n} from '../types/index.js';\nimport { NodeError } from '../types/index.js';\n\n// Define eSpace chains if not available from viem/chains\nconst espaceMainnet = defineChain({\n id: 1030,\n name: 'Conflux eSpace',\n nativeCurrency: { name: 'Conflux', symbol: 'CFX', decimals: 18 },\n rpcUrls: { default: { http: ['https://evm.confluxrpc.com'] } },\n blockExplorers: {\n default: { name: 'ConfluxScan', url: 'https://evm.confluxscan.net' },\n },\n});\n\nconst espaceTestnet = defineChain({\n id: 71,\n name: 'Conflux eSpace Testnet',\n nativeCurrency: { name: 'Conflux', symbol: 'CFX', decimals: 18 },\n rpcUrls: { default: { http: ['https://evmtestnet.confluxrpc.com'] } },\n blockExplorers: {\n default: { name: 'ConfluxScan', url: 'https://evmtestnet.confluxscan.net' },\n },\n});\n\n/**\n * EVM Space (eSpace) Client Implementation\n * Provides unified interface for Ethereum-compatible operations on Conflux eSpace\n */\nexport class EspaceClient implements ChainClient {\n readonly chainId: number;\n readonly chainType = 'evm' as const;\n readonly publicClient: PublicClient;\n protected readonly chain: Chain;\n public address: Address;\n\n constructor(config: ClientConfig) {\n this.chainId = config.chainId;\n\n // Create chain configuration based on provided chain ID\n if (config.chainId === 1030) {\n this.chain = espaceMainnet;\n } else if (config.chainId === 71) {\n this.chain = espaceTestnet;\n } else {\n // Custom chain configuration for development\n this.chain = defineChain({\n id: config.chainId,\n name: `Conflux eSpace (${config.chainId})`,\n nativeCurrency: { name: 'Conflux', symbol: 'CFX', decimals: 18 },\n rpcUrls: { default: { http: [config.rpcUrl] } },\n });\n }\n\n this.publicClient = createPublicClient({\n chain: this.chain,\n transport: http(config.rpcUrl),\n pollingInterval: config.pollingInterval || 1000,\n });\n\n // Address will be set by wallet client\n this.address = '' as Address;\n }\n\n async getBlockNumber(): Promise<bigint> {\n try {\n const blockNumber = await this.publicClient.getBlockNumber();\n return blockNumber;\n } catch (error) {\n throw new NodeError(\n `Failed to get block number: ${error instanceof Error ? error.message : String(error)}`,\n 'BLOCK_NUMBER_ERROR',\n 'evm',\n { originalError: error }\n );\n }\n }\n\n async getBalance(address: Address): Promise<string> {\n if (!isEvmAddress(address)) {\n throw new NodeError(\n 'Invalid EVM address format',\n 'INVALID_ADDRESS',\n 'evm'\n );\n }\n\n try {\n const balance = await this.publicClient.getBalance({ address });\n return formatEther(balance);\n } catch (error) {\n throw new NodeError(\n `Failed to get balance: ${error instanceof Error ? error.message : String(error)}`,\n 'BALANCE_ERROR',\n 'evm',\n { address, originalError: error }\n );\n }\n }\n\n async estimateGas(tx: BaseTransaction): Promise<bigint> {\n try {\n const gas = await this.publicClient.estimateGas({\n to: tx.to as Address,\n value: tx.value,\n data: tx.data as `0x${string}`,\n });\n return gas;\n } catch (error) {\n throw new NodeError(\n `Failed to estimate gas: ${error instanceof Error ? error.message : String(error)}`,\n 'GAS_ESTIMATE_ERROR',\n 'evm',\n { transaction: tx, originalError: error }\n );\n }\n }\n\n async waitForTransaction(hash: string): Promise<TransactionReceipt> {\n try {\n const receipt = await this.publicClient.waitForTransactionReceipt({\n hash: hash as `0x${string}`,\n timeout: 5_000, // 5 second timeout for faster response\n });\n\n return {\n hash: receipt.transactionHash,\n blockNumber: receipt.blockNumber,\n blockHash: receipt.blockHash,\n transactionIndex: receipt.transactionIndex,\n status: receipt.status === 'success' ? 'success' : 'reverted',\n gasUsed: receipt.gasUsed,\n contractAddress: receipt.contractAddress || undefined,\n logs: receipt.logs.map((log) => ({\n address: log.address,\n topics: log.topics,\n data: log.data,\n blockNumber: log.blockNumber || 0n,\n transactionHash: log.transactionHash || '',\n logIndex: log.logIndex || 0,\n })),\n };\n } catch (error) {\n throw new NodeError(\n `Failed to wait for transaction: ${error instanceof Error ? error.message : String(error)}`,\n 'TRANSACTION_WAIT_ERROR',\n 'evm',\n { hash, originalError: error }\n );\n }\n }\n\n async getGasPrice(): Promise<bigint> {\n try {\n const gasPrice = await this.publicClient.getGasPrice();\n return gasPrice;\n } catch (error) {\n throw new NodeError(\n `Failed to get gas price: ${error instanceof Error ? error.message : String(error)}`,\n 'GAS_PRICE_ERROR',\n 'evm',\n { originalError: error }\n );\n }\n }\n\n /**\n * Get the current chain ID from the network\n */\n async getChainId(): Promise<number> {\n try {\n const chainId = await this.publicClient.getChainId();\n return chainId;\n } catch (error) {\n throw new NodeError(\n `Failed to get chain ID: ${error instanceof Error ? error.message : String(error)}`,\n 'CHAIN_ID_ERROR',\n 'evm',\n { originalError: error }\n );\n }\n }\n\n /**\n * Check if the client is connected to the network\n */\n async isConnected(): Promise<boolean> {\n try {\n await this.publicClient.getBlockNumber();\n return true;\n } catch {\n return false;\n }\n }\n\n // Base implementation - should be overridden by WalletClient\n async sendTransaction(_tx: BaseTransaction): Promise<string> {\n throw new NodeError(\n 'sendTransaction not available on public client',\n 'METHOD_NOT_AVAILABLE',\n 'evm'\n );\n }\n\n async getTokenBalance(\n _address: string,\n _tokenAddress: string\n ): Promise<string> {\n try {\n const balance = await this.publicClient.readContract({\n address: _tokenAddress as Address,\n abi: [\n {\n type: 'function',\n name: 'balanceOf',\n inputs: [{ name: 'account', type: 'address' }],\n outputs: [{ name: 'balance', type: 'uint256' }],\n stateMutability: 'view',\n },\n ],\n functionName: 'balanceOf',\n args: [_address as Address],\n });\n return balance.toString();\n } catch (error) {\n throw new NodeError(\n `Failed to get token balance: ${error instanceof Error ? error.message : String(error)}`,\n 'TOKEN_BALANCE_ERROR',\n 'evm',\n { address: _address, tokenAddress: _tokenAddress, originalError: error }\n );\n }\n }\n\n watchBlocks(callback: EventCallback<BlockEvent>): () => void {\n const unwatch = this.publicClient.watchBlocks({\n onBlock: (block) =>\n callback({\n chainType: 'evm',\n blockNumber: block.number || 0n,\n blockHash: block.hash || '',\n timestamp: Number(block.timestamp || 0),\n transactionCount: block.transactions?.length || 0,\n }),\n });\n return unwatch;\n }\n\n async watchTransaction(\n _hash: string,\n _callback: (receipt: TransactionReceipt) => void\n ): Promise<() => void> {\n // This is a simplified implementation - viem doesn't have a direct watchTransaction\n // In practice, you'd poll for the transaction receipt\n const pollTransaction = async () => {\n try {\n const receipt = await this.waitForTransaction(_hash);\n _callback(receipt);\n } catch {\n // Transaction might not be mined yet, continue polling\n setTimeout(pollTransaction, 1000);\n }\n };\n\n setTimeout(pollTransaction, 1000);\n return () => {}; // Return a no-op unwatch function\n }\n\n getInternalClient(): PublicClient | WalletClient {\n return this.publicClient;\n }\n\n // Base implementation - should be overridden by TestClient\n watchTransactions(_callback: EventCallback<TransactionEvent>): () => void {\n throw new NodeError(\n 'watchTransactions not available on public client',\n 'METHOD_NOT_AVAILABLE',\n 'evm'\n );\n }\n\n isValidAddress(address: string): boolean {\n return isEvmAddress(address);\n }\n\n formatAmount(amount: bigint): string {\n return formatEther(amount);\n }\n\n parseAmount(amount: string): bigint {\n return parseEther(amount);\n }\n}\n\n/**\n * EVM Space Wallet Client\n * Extends EspaceClient with transaction and account functionality\n */\nexport class EspaceWalletClient\n extends EspaceClient\n implements UnifiedWalletClient\n{\n private readonly walletClient: WalletClient;\n private readonly account: Account;\n\n constructor(config: ClientConfig & { privateKey: string }) {\n super(config);\n\n // Create account from private key\n this.account = privateKeyToAccount(config.privateKey as `0x${string}`);\n this.address = this.account.address;\n\n // Create wallet client\n this.walletClient = createWalletClient({\n account: this.account,\n chain: this.chain,\n transport: http(config.rpcUrl),\n });\n }\n\n getAddress(): Address {\n return this.address;\n }\n\n async sendTransaction(tx: BaseTransaction): Promise<string> {\n try {\n const hash = await this.walletClient.sendTransaction({\n account: this.account,\n chain: this.chain,\n to: tx.to as Address,\n value: tx.value,\n data: tx.data as `0x${string}`,\n gas: tx.gasLimit,\n gasPrice: tx.gasPrice,\n nonce: tx.nonce,\n });\n return hash;\n } catch (error) {\n throw new NodeError(\n `Failed to send transaction: ${error instanceof Error ? error.message : String(error)}`,\n 'TRANSACTION_ERROR',\n 'evm',\n { transaction: tx, originalError: error }\n );\n }\n }\n\n async signMessage(message: string): Promise<string> {\n try {\n const signature = await this.walletClient.signMessage({\n account: this.account,\n message,\n });\n return signature;\n } catch (error) {\n throw new NodeError(\n `Failed to sign message: ${error instanceof Error ? error.message : String(error)}`,\n 'SIGNING_ERROR',\n 'evm',\n { message, originalError: error }\n );\n }\n }\n\n async deployContract(\n abi: unknown[],\n bytecode: string,\n constructorArgs: unknown[] = []\n ): Promise<string> {\n try {\n const hash = await this.walletClient.deployContract({\n account: this.account,\n chain: this.chain,\n abi,\n bytecode: bytecode as `0x${string}`,\n args: constructorArgs,\n });\n\n // Wait for transaction to be mined and get the contract address\n const receipt = await this.waitForTransaction(hash);\n\n if (!receipt.contractAddress) {\n throw new Error('Contract address not found in transaction receipt');\n }\n\n return receipt.contractAddress;\n } catch (error) {\n throw new NodeError(\n `Failed to deploy contract: ${error instanceof Error ? error.message : String(error)}`,\n 'DEPLOYMENT_ERROR',\n 'evm',\n { bytecode, constructorArgs, originalError: error }\n );\n }\n }\n\n async callContract<T = unknown>(\n address: string,\n abi: unknown[],\n functionName: string,\n args: unknown[] = []\n ): Promise<T> {\n try {\n const result = await this.publicClient.readContract({\n address: address as Address,\n abi,\n functionName,\n args,\n });\n return result as T;\n } catch (error) {\n throw new NodeError(\n `Failed to call contract: ${error instanceof Error ? error.message : String(error)}`,\n 'CONTRACT_CALL_ERROR',\n 'evm',\n { address, functionName, args, originalError: error }\n );\n }\n }\n\n async writeContract(\n address: string,\n abi: unknown[],\n functionName: string,\n args: unknown[] = [],\n value?: bigint\n ): Promise<string> {\n try {\n const hash = await this.walletClient.writeContract({\n account: this.account,\n chain: this.chain,\n address: address as Address,\n abi,\n functionName,\n args,\n value,\n });\n return hash;\n } catch (error) {\n throw new NodeError(\n `Failed to write contract: ${error instanceof Error ? error.message : String(error)}`,\n 'CONTRACT_WRITE_ERROR',\n 'evm',\n { address, functionName, args, value, originalError: error }\n );\n }\n }\n\n /**\n * Transfer CFX from eSpace to Core Space\n * Uses the built-in withdrawal mechanism\n */\n async faucetToCore(coreAddress: string, amount: string): Promise<string> {\n // Basic Core address format validation (cfx:...)\n if (!coreAddress.startsWith('cfx:') || coreAddress.length < 30) {\n throw new NodeError(\n 'Invalid Core address format',\n 'INVALID_ADDRESS',\n 'evm',\n { coreAddress }\n );\n }\n\n try {\n // Use the CrossSpaceCall precompiled contract for eSpace to Core transfers\n const hash = await this.walletClient.sendTransaction({\n account: this.account,\n chain: this.chain,\n to: '0x0888000000000000000000000000000000000006', // CrossSpaceCall precompiled address\n value: parseEther(amount),\n data: encodeFunctionData({\n abi: [\n {\n type: 'function',\n name: 'withdrawFromMapped',\n inputs: [{ name: 'value', type: 'uint256' }],\n outputs: [],\n stateMutability: 'payable',\n },\n ],\n functionName: 'withdrawFromMapped',\n args: [parseEther(amount)],\n }),\n });\n\n return hash;\n } catch (error) {\n throw new NodeError(\n `Failed to send faucet transaction to Core: ${error instanceof Error ? error.message : String(error)}`,\n 'FAUCET_ERROR',\n 'evm',\n { coreAddress, amount, originalError: error }\n );\n }\n }\n\n getInternalClient(): PublicClient | WalletClient {\n return this.walletClient;\n }\n}\n\n/**\n * EVM Space Test Client\n * Extends EspaceWalletClient with additional testing utilities\n */\nexport class EspaceTestClient extends EspaceWalletClient implements TestClient {\n private readonly testClient: ViemTestClient;\n\n constructor(config: TestConfig & { privateKey: string }) {\n super(config);\n\n this.testClient = createTestClient({\n mode: 'anvil',\n chain: this.chainId === 1030 ? espaceMainnet : espaceTestnet,\n transport: http(config.rpcUrl),\n pollingInterval: config.pollingInterval || 1000,\n });\n }\n\n async mine(blocks = 1): Promise<void> {\n try {\n await this.testClient.mine({ blocks });\n } catch (error) {\n throw new NodeError(\n `Failed to mine blocks: ${error instanceof Error ? error.message : String(error)}`,\n 'MINING_ERROR',\n 'evm',\n { blocks, originalError: error }\n );\n }\n }\n\n async setNextBlockTimestamp(timestamp: number): Promise<void> {\n try {\n await this.testClient.setNextBlockTimestamp({\n timestamp: BigInt(timestamp),\n });\n } catch (error) {\n throw new NodeError(\n `Failed to set next block timestamp: ${error instanceof Error ? error.message : String(error)}`,\n 'TIMESTAMP_ERROR',\n 'evm',\n { timestamp, originalError: error }\n );\n }\n }\n\n async increaseTime(seconds: number): Promise<void> {\n try {\n await this.testClient.increaseTime({ seconds });\n } catch (error) {\n throw new NodeError(\n `Failed to increase time: ${error instanceof Error ? error.message : String(error)}`,\n 'TIME_INCREASE_ERROR',\n 'evm',\n { seconds, originalError: error }\n );\n }\n }\n\n async impersonateAccount(address: string): Promise<void> {\n try {\n await this.testClient.impersonateAccount({ address: address as Address });\n } catch (error) {\n throw new NodeError(\n `Failed to impersonate account: ${error instanceof Error ? error.message : String(error)}`,\n 'IMPERSONATION_ERROR',\n 'evm',\n { address, originalError: error }\n );\n }\n }\n\n async stopImpersonatingAccount(address: string): Promise<void> {\n try {\n await this.testClient.stopImpersonatingAccount({\n address: address as Address,\n });\n } catch (error) {\n throw new NodeError(\n `Failed to stop impersonating account: ${error instanceof Error ? error.message : String(error)}`,\n 'IMPERSONATION_STOP_ERROR',\n 'evm',\n { address, originalError: error }\n );\n }\n }\n\n async setBalance(address: string, balance: bigint): Promise<void> {\n try {\n await this.testClient.setBalance({\n address: address as Address,\n value: balance,\n });\n } catch (error) {\n throw new NodeError(\n `Failed to set balance: ${error instanceof Error ? error.message : String(error)}`,\n 'BALANCE_SET_ERROR',\n 'evm',\n { address, balance, originalError: error }\n );\n }\n }\n\n async snapshot(): Promise<string> {\n try {\n const snapshotId = await this.testClient.snapshot();\n return snapshotId;\n } catch (error) {\n throw new NodeError(\n `Failed to create snapshot: ${error instanceof Error ? error.message : String(error)}`,\n 'SNAPSHOT_ERROR',\n 'evm',\n { originalError: error }\n );\n }\n }\n\n async revert(snapshotId: string): Promise<void> {\n try {\n await this.testClient.revert({ id: snapshotId as `0x${string}` });\n } catch (error) {\n throw new NodeError(\n `Failed to revert to snapshot: ${error instanceof Error ? error.message : String(error)}`,\n 'REVERT_ERROR',\n 'evm',\n { snapshotId, originalError: error }\n );\n }\n }\n\n async getStorageAt(address: string, slot: string): Promise<string> {\n try {\n const value = await this.publicClient.getStorageAt({\n address: address as Address,\n slot: slot as `0x${string}`,\n });\n return value || '0x';\n } catch (error) {\n throw new NodeError(\n `Failed to get storage: ${error instanceof Error ? error.message : String(error)}`,\n 'STORAGE_GET_ERROR',\n 'evm',\n { address, slot, originalError: error }\n );\n }\n }\n\n async setStorageAt(\n address: string,\n slot: string,\n value: string\n ): Promise<void> {\n try {\n await this.testClient.setStorageAt({\n address: address as Address,\n index: slot as `0x${string}`,\n value: value as `0x${string}`,\n });\n } catch (error) {\n throw new NodeError(\n `Failed to set storage: ${error instanceof Error ? error.message : String(error)}`,\n 'STORAGE_SET_ERROR',\n 'evm',\n { address, slot, value, originalError: error }\n );\n }\n }\n\n watchTransactions(callback: EventCallback<TransactionEvent>): () => void {\n // This is a simplified implementation\n // In practice, you'd need to implement proper transaction watching\n const unwatch = this.publicClient.watchPendingTransactions({\n onTransactions: (hashes) => {\n for (const hash of hashes) {\n // For each transaction, we'd need to fetch details\n // This is a simplified callback - in real implementation you'd fetch transaction details\n callback({\n chainType: 'evm',\n hash,\n from: '', // Would need to fetch transaction details\n to: '', // Would need to fetch transaction details\n value: 0n, // Would need to fetch transaction details\n blockNumber: 0n, // Would need to fetch transaction details\n });\n }\n },\n });\n return unwatch;\n }\n\n isValidAddress(address: string): boolean {\n return isEvmAddress(address);\n }\n\n async getCurrentEpoch(): Promise<bigint> {\n return await this.getBlockNumber();\n }\n\n async generateAccounts(count: number): Promise<string[]> {\n const accounts: string[] = [];\n for (let i = 0; i < count; i++) {\n // Generate random private key and derive address\n const privateKey =\n `0x${'0'.repeat(64 - 2)}${i.toString(16).padStart(2, '0')}${'0'.repeat(60)}` as const;\n const account = privateKeyToAccount(privateKey);\n accounts.push(account.address);\n }\n return accounts;\n }\n}\n\n/**\n * Create an eSpace client instance with all components\n */\nexport async function createEspaceClient(\n config: ClientConfig\n): Promise<EspaceClientInstance> {\n const chainConfig = getChainConfig(config.chainId as SupportedChainId);\n\n if (chainConfig.type !== 'evm') {\n throw new NodeError(\n `Invalid chain type for eSpace client: ${chainConfig.type}`,\n 'INVALID_CHAIN_TYPE',\n 'evm'\n );\n }\n\n // Update config with proper RPC URL if not provided\n const clientConfig: ClientConfig = {\n ...config,\n rpcUrl:\n config.rpcUrl ||\n chainConfig.rpcUrls.default.http[0] ||\n 'http://localhost:8545',\n };\n\n const publicClient = new EspaceClient(clientConfig);\n\n let walletClient: EspaceWalletClient | undefined;\n let testClient: EspaceTestClient | undefined;\n\n if (config.account) {\n let privateKey: string;\n if (typeof config.account === 'string') {\n privateKey = config.account;\n } else {\n privateKey = config.account.privateKey;\n }\n\n const walletConfig: WalletConfig = {\n ...clientConfig,\n privateKey,\n accountIndex:\n typeof config.account === 'object' ? config.account.accountIndex : 0,\n };\n walletClient = new EspaceWalletClient(walletConfig);\n }\n\n if (config.testMode) {\n // Test client needs a private key, use a default one if not provided\n let privateKey: string;\n if (config.account) {\n if (typeof config.account === 'string') {\n privateKey = config.account;\n } else {\n privateKey = config.account.privateKey;\n }\n } else {\n // Default test private key\n privateKey =\n '0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';\n }\n\n const testConfig: TestConfig & { privateKey: string } = {\n ...clientConfig,\n enableTestMode: true,\n privateKey,\n };\n testClient = new EspaceTestClient(testConfig);\n }\n\n return {\n publicClient,\n walletClient,\n testClient,\n };\n}\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Client Manager - Unified orchestration layer for Conflux DevKit Node\n// Manages both Core and EVM clients with health monitoring and network coordination\n\nimport { EventEmitter } from 'node:events';\nimport { createCoreClient } from '../clients/core.js';\nimport { createEspaceClient } from '../clients/evm.js';\nimport {\n defaultNetworkSelector,\n getChainConfig,\n isValidChainId,\n} from '../config/chains.js';\nimport type {\n ChainType,\n ClientConfig,\n CoreClientInstance,\n EspaceClientInstance,\n HealthStatus,\n SupportedChainId,\n} from '../types/index.js';\n\n// Health check intervals (in milliseconds)\nconst HEALTH_CHECK_INTERVAL = 30000; // 30 seconds\nconst HEALTH_CHECK_TIMEOUT = 5000; // 5 seconds\n\n/**\n * Client Manager Events\n */\nexport interface ClientManagerEvents {\n 'client:ready': [{ type: ChainType; chainId: SupportedChainId }];\n 'client:error': [\n { type: ChainType; chainId: SupportedChainId; error: Error },\n ];\n 'client:health': [\n { type: ChainType; chainId: SupportedChainId; status: HealthStatus },\n ];\n 'server:started': [\n { coreChainId: SupportedChainId; evmChainId: SupportedChainId },\n ];\n 'server:stopped': [];\n 'network:switched': [{ from: SupportedChainId; to: SupportedChainId }];\n 'manager:ready': [];\n 'manager:error': [{ error: Error }];\n}\n\n/**\n * Client Manager Configuration\n */\nexport interface ClientManagerConfig {\n /** Core Space client configuration */\n core: ClientConfig;\n /** eSpace client configuration */\n evm: ClientConfig;\n /** Enable automatic health monitoring */\n enableHealthMonitoring?: boolean;\n /** Health check interval in milliseconds */\n healthCheckInterval?: number;\n /** Health check timeout in milliseconds */\n healthCheckTimeout?: number;\n}\n\n/**\n * Client Manager Status\n */\nexport interface ClientManagerStatus {\n initialized: boolean;\n coreClient: {\n connected: boolean;\n chainId: SupportedChainId;\n health: HealthStatus;\n lastHealthCheck?: Date;\n };\n evmClient: {\n connected: boolean;\n chainId: SupportedChainId;\n health: HealthStatus;\n lastHealthCheck?: Date;\n };\n networkSelector: {\n currentChain: SupportedChainId;\n isLocalNode: boolean;\n lockedToLocal: boolean;\n };\n}\n\n/**\n * Unified Client Manager\n *\n * This is the main orchestration layer that manages:\n * - Core Space and eSpace client instances\n * - Local development server lifecycle\n * - Network switching and chain coordination\n * - Health monitoring and error recovery\n * - Event coordination between components\n *\n * Key Design Principles:\n * 1. **Dual Chain Support**: Manages both Core and eSpace clients simultaneously\n * 2. **Network Awareness**: Automatically switches to local chains when dev server runs\n * 3. **Health Monitoring**: Continuous health checks with automatic recovery\n * 4. **Event Coordination**: Unified event system for all components\n * 5. **Type Safety**: Full TypeScript support with proper error handling\n */\nexport class ClientManager extends EventEmitter<ClientManagerEvents> {\n private config: ClientManagerConfig;\n private coreClient: CoreClientInstance | null = null;\n private evmClient: EspaceClientInstance | null = null;\n private healthCheckInterval: NodeJS.Timeout | null = null;\n private networkSelectorUnsubscribe: (() => void) | null = null;\n private nodeRunningUnsubscribe: (() => void) | null = null;\n private initialized = false;\n\n constructor(config: ClientManagerConfig) {\n super();\n this.config = {\n enableHealthMonitoring: true,\n healthCheckInterval: HEALTH_CHECK_INTERVAL,\n healthCheckTimeout: HEALTH_CHECK_TIMEOUT,\n ...config,\n };\n }\n\n /**\n * Initialize the Client Manager\n * Sets up clients, server, and monitoring\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n try {\n // Set up network selector listeners\n this.setupNetworkListeners();\n\n // Initialize clients based on current network selection\n await this.initializeClients();\n\n // Start health monitoring if enabled\n if (this.config.enableHealthMonitoring) {\n this.startHealthMonitoring();\n }\n\n this.initialized = true;\n this.emit('manager:ready');\n } catch (error) {\n const managerError =\n error instanceof Error ? error : new Error(String(error));\n this.emit('manager:error', { error: managerError });\n throw managerError;\n }\n }\n\n /**\n * Gracefully shutdown the Client Manager\n */\n async shutdown(): Promise<void> {\n if (!this.initialized) {\n return;\n }\n\n try {\n // Stop health monitoring\n this.stopHealthMonitoring();\n\n // Clean up network selector listeners\n if (this.networkSelectorUnsubscribe) {\n this.networkSelectorUnsubscribe();\n this.networkSelectorUnsubscribe = null;\n }\n\n if (this.nodeRunningUnsubscribe) {\n this.nodeRunningUnsubscribe();\n this.nodeRunningUnsubscribe = null;\n }\n\n // Clean up clients\n this.coreClient = null;\n this.evmClient = null;\n\n this.initialized = false;\n this.removeAllListeners();\n } catch (error) {\n const shutdownError =\n error instanceof Error ? error : new Error(String(error));\n this.emit('manager:error', { error: shutdownError });\n throw shutdownError;\n }\n }\n\n /**\n * Get current Core Space client\n */\n getCoreClient(): CoreClientInstance | null {\n return this.coreClient;\n }\n\n /**\n * Get current eSpace client\n */\n getEvmClient(): EspaceClientInstance | null {\n return this.evmClient;\n }\n\n /**\n * Get comprehensive status\n */\n getStatus(): ClientManagerStatus {\n const currentChainId = defaultNetworkSelector.getCurrentChainId();\n const currentChain = getChainConfig(currentChainId);\n\n return {\n initialized: this.initialized,\n coreClient: {\n connected: !!this.coreClient,\n chainId:\n currentChain.type === 'core'\n ? currentChainId\n : defaultNetworkSelector.getCorrespondingChainId() || 1,\n health: 'unknown', // TODO: Implement health status tracking\n lastHealthCheck: undefined,\n },\n evmClient: {\n connected: !!this.evmClient,\n chainId:\n currentChain.type === 'evm'\n ? currentChainId\n : defaultNetworkSelector.getCorrespondingChainId() || 71,\n health: 'unknown', // TODO: Implement health status tracking\n lastHealthCheck: undefined,\n },\n networkSelector: {\n currentChain: currentChainId,\n isLocalNode: defaultNetworkSelector.getNodeRunningStatus(),\n lockedToLocal: defaultNetworkSelector.isLockedToLocal(),\n },\n };\n }\n\n /**\n * Switch to a specific network\n * @param chainId - Target chain ID\n * @param force - Force switch even if node is running (for wallet operations)\n */\n async switchNetwork(chainId: SupportedChainId, force = false): Promise<void> {\n if (!isValidChainId(chainId)) {\n throw new Error(`Invalid chain ID: ${chainId}`);\n }\n\n const previousChainId = defaultNetworkSelector.getCurrentChainId();\n\n if (previousChainId === chainId) {\n return; // Already on this chain\n }\n\n // Attempt network switch\n defaultNetworkSelector.switchChain(chainId, force);\n\n // If switch was successful, reinitialize clients\n if (defaultNetworkSelector.getCurrentChainId() === chainId) {\n await this.initializeClients();\n this.emit('network:switched', { from: previousChainId, to: chainId });\n }\n }\n\n /**\n * Initialize or reinitialize client instances based on current network\n */\n private async initializeClients(): Promise<void> {\n const currentChainId = defaultNetworkSelector.getCurrentChainId();\n const currentChain = getChainConfig(currentChainId);\n\n try {\n // Always initialize both clients, but connect them to appropriate chains\n if (currentChain.type === 'core') {\n // Current selection is Core, get corresponding eSpace chain\n const evmChainId =\n defaultNetworkSelector.getCorrespondingChainId() || 71;\n\n this.coreClient = await createCoreClient({\n ...this.config.core,\n chainId: currentChainId,\n });\n\n this.evmClient = await createEspaceClient({\n ...this.config.evm,\n chainId: evmChainId,\n });\n } else {\n // Current selection is eSpace, get corresponding Core chain\n const coreChainId =\n defaultNetworkSelector.getCorrespondingChainId() || 1;\n\n this.coreClient = await createCoreClient({\n ...this.config.core,\n chainId: coreChainId,\n });\n\n this.evmClient = await createEspaceClient({\n ...this.config.evm,\n chainId: currentChainId,\n });\n }\n\n // Emit ready events\n this.emit('client:ready', {\n type: 'core' as ChainType,\n chainId: this.coreClient.publicClient.chainId as SupportedChainId,\n });\n this.emit('client:ready', {\n type: 'evm' as ChainType,\n chainId: this.evmClient.publicClient.chainId as SupportedChainId,\n });\n } catch (error) {\n const clientError =\n error instanceof Error ? error : new Error(String(error));\n this.emit('manager:error', { error: clientError });\n throw clientError;\n }\n }\n\n /**\n * Set up network selector event listeners\n */\n private setupNetworkListeners(): void {\n // Listen for chain changes\n this.networkSelectorUnsubscribe = defaultNetworkSelector.onChainChange(\n async (_chainId) => {\n try {\n await this.initializeClients();\n } catch (error) {\n const networkError =\n error instanceof Error ? error : new Error(String(error));\n this.emit('manager:error', { error: networkError });\n }\n }\n );\n\n // Listen for node running status changes\n this.nodeRunningUnsubscribe = defaultNetworkSelector.onNodeRunningChange(\n async (isRunning) => {\n if (isRunning) {\n // Node started - clients will be reinitialized by chain change event\n } else {\n // Node stopped - clients will be reinitialized by chain change event\n }\n }\n );\n }\n\n /**\n * Start health monitoring for all clients\n */\n private startHealthMonitoring(): void {\n if (this.healthCheckInterval) {\n return; // Already running\n }\n\n this.healthCheckInterval = setInterval(async () => {\n await this.performHealthChecks();\n }, this.config.healthCheckInterval || HEALTH_CHECK_INTERVAL);\n\n // Perform initial health check\n setTimeout(() => this.performHealthChecks(), 1000);\n }\n\n /**\n * Stop health monitoring\n */\n private stopHealthMonitoring(): void {\n if (this.healthCheckInterval) {\n clearInterval(this.healthCheckInterval);\n this.healthCheckInterval = null;\n }\n }\n\n /**\n * Perform health checks on all clients\n */\n private async performHealthChecks(): Promise<void> {\n const timeout = this.config.healthCheckTimeout || HEALTH_CHECK_TIMEOUT;\n\n // Check Core client health\n if (this.coreClient) {\n try {\n const healthPromise = this.checkCoreClientHealth();\n const result = await Promise.race([\n healthPromise,\n new Promise<HealthStatus>((_, reject) =>\n setTimeout(() => reject(new Error('Health check timeout')), timeout)\n ),\n ]);\n\n this.emit('client:health', {\n type: 'core' as ChainType,\n chainId: this.coreClient.publicClient.chainId as SupportedChainId,\n status: result,\n });\n } catch (error) {\n this.emit('client:error', {\n type: 'core' as ChainType,\n chainId: this.coreClient.publicClient.chainId as SupportedChainId,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n }\n\n // Check eSpace client health\n if (this.evmClient) {\n try {\n const healthPromise = this.checkEvmClientHealth();\n const result = await Promise.race([\n healthPromise,\n new Promise<HealthStatus>((_, reject) =>\n setTimeout(() => reject(new Error('Health check timeout')), timeout)\n ),\n ]);\n\n this.emit('client:health', {\n type: 'evm' as ChainType,\n chainId: this.evmClient.publicClient.chainId as SupportedChainId,\n status: result,\n });\n } catch (error) {\n this.emit('client:error', {\n type: 'evm' as ChainType,\n chainId: this.evmClient.publicClient.chainId as SupportedChainId,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n }\n }\n\n /**\n * Check Core client health\n */\n private async checkCoreClientHealth(): Promise<HealthStatus> {\n if (!this.coreClient) {\n return 'disconnected';\n }\n\n try {\n // Simple health check - get latest block number\n await this.coreClient.publicClient.getBlockNumber();\n return 'healthy';\n } catch (_error) {\n return 'unhealthy';\n }\n }\n\n /**\n * Check eSpace client health\n */\n private async checkEvmClientHealth(): Promise<HealthStatus> {\n if (!this.evmClient) {\n return 'disconnected';\n }\n\n try {\n // Simple health check - get latest block number\n await this.evmClient.publicClient.getBlockNumber();\n return 'healthy';\n } catch (_error) {\n return 'unhealthy';\n }\n }\n}\n\n/**\n * Create a new Client Manager instance\n */\nexport function createClientManager(\n config: ClientManagerConfig\n): ClientManager {\n return new ClientManager(config);\n}\n\n// Export types are already exported above\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Standard ERC20 Token ABI\n */\nexport const ERC20_ABI = [\n // Read functions\n {\n inputs: [],\n name: 'name',\n outputs: [{ name: '', type: 'string' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'symbol',\n outputs: [{ name: '', type: 'string' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'decimals',\n outputs: [{ name: '', type: 'uint8' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'totalSupply',\n outputs: [{ name: '', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [{ name: 'account', type: 'address' }],\n name: 'balanceOf',\n outputs: [{ name: '', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n ],\n name: 'allowance',\n outputs: [{ name: '', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n\n // Write functions\n {\n inputs: [\n { name: 'to', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n name: 'transfer',\n outputs: [{ name: '', type: 'bool' }],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n { name: 'spender', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n name: 'approve',\n outputs: [{ name: '', type: 'bool' }],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n name: 'transferFrom',\n outputs: [{ name: '', type: 'bool' }],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n\n // Events\n {\n anonymous: false,\n inputs: [\n { indexed: true, name: 'from', type: 'address' },\n { indexed: true, name: 'to', type: 'address' },\n { indexed: false, name: 'value', type: 'uint256' },\n ],\n name: 'Transfer',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, name: 'owner', type: 'address' },\n { indexed: true, name: 'spender', type: 'address' },\n { indexed: false, name: 'value', type: 'uint256' },\n ],\n name: 'Approval',\n type: 'event',\n },\n] as const;\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Standard ERC721 NFT ABI\n */\nexport const ERC721_ABI = [\n // Read functions\n {\n inputs: [],\n name: 'name',\n outputs: [{ name: '', type: 'string' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'symbol',\n outputs: [{ name: '', type: 'string' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [{ name: 'tokenId', type: 'uint256' }],\n name: 'tokenURI',\n outputs: [{ name: '', type: 'string' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [{ name: 'owner', type: 'address' }],\n name: 'balanceOf',\n outputs: [{ name: '', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [{ name: 'tokenId', type: 'uint256' }],\n name: 'ownerOf',\n outputs: [{ name: '', type: 'address' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n { name: 'owner', type: 'address' },\n { name: 'operator', type: 'address' },\n ],\n name: 'isApprovedForAll',\n outputs: [{ name: '', type: 'bool' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [{ name: 'tokenId', type: 'uint256' }],\n name: 'getApproved',\n outputs: [{ name: '', type: 'address' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [{ name: 'interfaceId', type: 'bytes4' }],\n name: 'supportsInterface',\n outputs: [{ name: '', type: 'bool' }],\n stateMutability: 'view',\n type: 'function',\n },\n\n // Write functions\n {\n inputs: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'tokenId', type: 'uint256' },\n ],\n name: 'transferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'tokenId', type: 'uint256' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'tokenId', type: 'uint256' },\n { name: 'data', type: 'bytes' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n { name: 'to', type: 'address' },\n { name: 'tokenId', type: 'uint256' },\n ],\n name: 'approve',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n { name: 'operator', type: 'address' },\n { name: 'approved', type: 'bool' },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n\n // Events\n {\n anonymous: false,\n inputs: [\n { indexed: true, name: 'from', type: 'address' },\n { indexed: true, name: 'to', type: 'address' },\n { indexed: true, name: 'tokenId', type: 'uint256' },\n ],\n name: 'Transfer',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, name: 'owner', type: 'address' },\n { indexed: true, name: 'approved', type: 'address' },\n { indexed: true, name: 'tokenId', type: 'uint256' },\n ],\n name: 'Approval',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, name: 'owner', type: 'address' },\n { indexed: true, name: 'operator', type: 'address' },\n { indexed: false, name: 'approved', type: 'bool' },\n ],\n name: 'ApprovalForAll',\n type: 'event',\n },\n] as const;\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Standard ERC1155 Multi-Token ABI\n */\nexport const ERC1155_ABI = [\n // Read functions\n {\n inputs: [{ name: 'id', type: 'uint256' }],\n name: 'uri',\n outputs: [{ name: '', type: 'string' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n { name: 'account', type: 'address' },\n { name: 'id', type: 'uint256' },\n ],\n name: 'balanceOf',\n outputs: [{ name: '', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n { name: 'accounts', type: 'address[]' },\n { name: 'ids', type: 'uint256[]' },\n ],\n name: 'balanceOfBatch',\n outputs: [{ name: '', type: 'uint256[]' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n { name: 'account', type: 'address' },\n { name: 'operator', type: 'address' },\n ],\n name: 'isApprovedForAll',\n outputs: [{ name: '', type: 'bool' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [{ name: 'interfaceId', type: 'bytes4' }],\n name: 'supportsInterface',\n outputs: [{ name: '', type: 'bool' }],\n stateMutability: 'view',\n type: 'function',\n },\n\n // Write functions\n {\n inputs: [\n { name: 'operator', type: 'address' },\n { name: 'approved', type: 'bool' },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'id', type: 'uint256' },\n { name: 'amount', type: 'uint256' },\n { name: 'data', type: 'bytes' },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'ids', type: 'uint256[]' },\n { name: 'amounts', type: 'uint256[]' },\n { name: 'data', type: 'bytes' },\n ],\n name: 'safeBatchTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n\n // Events\n {\n anonymous: false,\n inputs: [\n { indexed: true, name: 'operator', type: 'address' },\n { indexed: true, name: 'from', type: 'address' },\n { indexed: true, name: 'to', type: 'address' },\n { indexed: false, name: 'id', type: 'uint256' },\n { indexed: false, name: 'value', type: 'uint256' },\n ],\n name: 'TransferSingle',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, name: 'operator', type: 'address' },\n { indexed: true, name: 'from', type: 'address' },\n { indexed: true, name: 'to', type: 'address' },\n { indexed: false, name: 'ids', type: 'uint256[]' },\n { indexed: false, name: 'values', type: 'uint256[]' },\n ],\n name: 'TransferBatch',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n { indexed: true, name: 'account', type: 'address' },\n { indexed: true, name: 'operator', type: 'address' },\n { indexed: false, name: 'approved', type: 'bool' },\n ],\n name: 'ApprovalForAll',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n { indexed: false, name: 'value', type: 'string' },\n { indexed: true, name: 'id', type: 'uint256' },\n ],\n name: 'URI',\n type: 'event',\n },\n] as const;\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ChainType } from '../../types/index.js';\n\n/**\n * Contract Deployment Types\n */\n\nexport interface DeploymentOptions {\n /** Contract bytecode */\n bytecode: string;\n /** Contract ABI */\n abi: unknown[];\n /** Constructor arguments */\n args?: unknown[];\n /** Chain to deploy on */\n chain: ChainType;\n /** Value to send with deployment (in wei) */\n value?: bigint;\n /** Gas limit */\n gasLimit?: bigint;\n /** Gas price (in wei) */\n gasPrice?: bigint;\n}\n\nexport interface DeploymentResult {\n /** Deployed contract address */\n address: string;\n /** Deployment transaction hash */\n transactionHash: string;\n /** Block number of deployment */\n blockNumber: bigint;\n /** Deployer address */\n deployer: string;\n /** Chain deployed on */\n chain: ChainType;\n /** Deployment timestamp */\n deployedAt: Date;\n /** Gas used for deployment */\n gasUsed: bigint;\n}\n\n/**\n * Contract Interaction Types\n */\n\nexport interface ReadOptions {\n /** Contract address */\n address: string;\n /** Contract ABI */\n abi: unknown[];\n /** Function name to call */\n functionName: string;\n /** Function arguments */\n args?: unknown[];\n /** Chain to read from */\n chain: ChainType;\n /** Block number to read at (optional) */\n blockNumber?: bigint;\n}\n\nexport interface WriteOptions {\n /** Contract address */\n address: string;\n /** Contract ABI */\n abi: unknown[];\n /** Function name to call */\n functionName: string;\n /** Function arguments */\n args?: unknown[];\n /** Chain to write to */\n chain: ChainType;\n /** Value to send (in wei) */\n value?: bigint;\n /** Gas limit */\n gasLimit?: bigint;\n /** Gas price (in wei) */\n gasPrice?: bigint;\n /** Wait for transaction confirmation */\n waitForConfirmation?: boolean;\n}\n\nexport interface WriteResult {\n /** Transaction hash */\n hash: string;\n /** From address */\n from: string;\n /** To address (contract) */\n to: string;\n /** Chain */\n chain: ChainType;\n /** Block number (if confirmed) */\n blockNumber?: bigint;\n /** Gas used (if confirmed) */\n gasUsed?: bigint;\n /** Transaction status */\n status?: 'success' | 'reverted';\n}\n\n/**\n * Contract Verification Types\n */\n\nexport interface ContractInfo {\n /** Contract address */\n address: string;\n /** Contract name */\n name?: string;\n /** Contract bytecode */\n bytecode: string;\n /** Contract ABI */\n abi?: unknown[];\n /** Deployment block */\n deploymentBlock?: bigint;\n /** Chain */\n chain: ChainType;\n /** Is verified */\n isVerified: boolean;\n}\n\n/**\n * Standard Token Types\n */\n\nexport interface ERC20TokenInfo {\n /** Token address */\n address: string;\n /** Token name */\n name: string;\n /** Token symbol */\n symbol: string;\n /** Token decimals */\n decimals: number;\n /** Total supply */\n totalSupply: bigint;\n /** Chain */\n chain: ChainType;\n}\n\nexport interface ERC721TokenInfo {\n /** Token address */\n address: string;\n /** Token name */\n name: string;\n /** Token symbol */\n symbol: string;\n /** Total supply */\n totalSupply?: bigint;\n /** Base URI */\n baseURI?: string;\n /** Chain */\n chain: ChainType;\n}\n\nexport interface NFTMetadata {\n /** Token ID */\n tokenId: bigint;\n /** Token name */\n name?: string;\n /** Token description */\n description?: string;\n /** Token image URL */\n image?: string;\n /** Additional attributes */\n attributes?: Array<{\n trait_type: string;\n value: string | number;\n }>;\n}\n\n/**\n * Contract Events Types\n */\n\nexport interface EventFilter {\n /** Contract address */\n address: string;\n /** Event ABI */\n abi: unknown[];\n /** Event name */\n eventName: string;\n /** Event argument filters */\n args?: Record<string, unknown>;\n /** From block */\n fromBlock?: bigint;\n /** To block */\n toBlock?: bigint;\n /** Chain */\n chain: ChainType;\n}\n\nexport interface EventLog {\n /** Contract address */\n address: string;\n /** Event name */\n eventName: string;\n /** Event arguments */\n args: Record<string, unknown>;\n /** Block number */\n blockNumber: bigint;\n /** Transaction hash */\n transactionHash: string;\n /** Log index */\n logIndex: number;\n /** Chain */\n chain: ChainType;\n}\n\n/**\n * Multi-Chain Deployment Types\n */\n\nexport interface MultiChainDeploymentOptions {\n /** Contract bytecode */\n bytecode: string;\n /** Contract ABI */\n abi: unknown[];\n /** Constructor arguments */\n args?: unknown[];\n /** Chains to deploy on */\n chains: ChainType[];\n /** Value per deployment (in wei) */\n value?: bigint;\n}\n\nexport interface MultiChainDeploymentResult {\n /** Core Space deployment */\n core?: DeploymentResult;\n /** eSpace deployment */\n evm?: DeploymentResult;\n /** Number of successful deployments */\n successCount: number;\n /** Number of failed deployments */\n failureCount: number;\n}\n\n/**\n * Error Types\n */\n\nexport class ContractError extends Error {\n constructor(\n message: string,\n public code: string,\n public context?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'ContractError';\n }\n}\n\nexport class DeploymentError extends ContractError {\n constructor(message: string, context?: Record<string, unknown>) {\n super(message, 'DEPLOYMENT_ERROR', context);\n this.name = 'DeploymentError';\n }\n}\n\nexport class InteractionError extends ContractError {\n constructor(message: string, context?: Record<string, unknown>) {\n super(message, 'INTERACTION_ERROR', context);\n this.name = 'InteractionError';\n }\n}\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ClientManager } from '../../clients/manager.js';\nimport type {\n DeploymentOptions,\n DeploymentResult,\n MultiChainDeploymentOptions,\n MultiChainDeploymentResult,\n} from '../types/index.js';\nimport { DeploymentError } from '../types/index.js';\n\n/**\n * Contract Deployer\n *\n * Handles contract deployment to Conflux blockchains.\n * Supports both Core Space (CFX native) and eSpace (EVM-compatible).\n *\n * @example\n * ```typescript\n * const deployer = new ContractDeployer(clientManager);\n *\n * // Deploy to eSpace\n * const result = await deployer.deploy({\n * bytecode: '0x6080604052...',\n * abi: [...],\n * args: ['Token Name', 'SYMBOL'],\n * chain: 'evm'\n * });\n *\n * console.log(`Deployed to: ${result.address}`);\n * ```\n */\nexport class ContractDeployer {\n // biome-ignore lint/correctness/noUnusedPrivateClassMembers: reserved for production implementation\n constructor(private readonly clientManager: ClientManager) {}\n\n /**\n * Deploy contract to a single chain\n *\n * @param options - Deployment configuration\n * @returns Deployment result\n */\n async deploy(options: DeploymentOptions): Promise<DeploymentResult> {\n try {\n if (options.chain === 'core') {\n return await this.deployToCore(options);\n }\n return await this.deployToEvm(options);\n } catch (error) {\n throw new DeploymentError(\n `Failed to deploy contract to ${options.chain}`,\n {\n chain: options.chain,\n error: error instanceof Error ? error.message : 'Unknown error',\n }\n );\n }\n }\n\n /**\n * Deploy contract to multiple chains\n *\n * @param options - Multi-chain deployment configuration\n * @returns Multi-chain deployment results\n */\n async deployToMultipleChains(\n options: MultiChainDeploymentOptions\n ): Promise<MultiChainDeploymentResult> {\n const results: MultiChainDeploymentResult = {\n successCount: 0,\n failureCount: 0,\n };\n\n // Deploy to each chain\n for (const chain of options.chains) {\n try {\n const result = await this.deploy({\n bytecode: options.bytecode,\n abi: options.abi,\n args: options.args,\n chain,\n value: options.value,\n });\n\n if (chain === 'core') {\n results.core = result;\n } else {\n results.evm = result;\n }\n\n results.successCount++;\n } catch (error) {\n results.failureCount++;\n console.error(`Failed to deploy to ${chain}:`, error);\n }\n }\n\n return results;\n }\n\n /**\n * Deploy contract to Core Space (Conflux native)\n */\n private async deployToCore(\n _options: DeploymentOptions\n ): Promise<DeploymentResult> {\n // Note: This is a simplified implementation\n // In production, you would:\n // 1. Get wallet client from clientManager\n // 2. Use proper contract deployment method\n // 3. Wait for transaction confirmation\n // 4. Extract deployment info from receipt\n\n // Simulate deployment for now\n const address = `cfx:${Array.from({ length: 40 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('')}`;\n\n const transactionHash = `0x${Array.from({ length: 64 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('')}`;\n\n return {\n address,\n transactionHash,\n blockNumber: 1000n,\n deployer: 'cfx:deployer...',\n chain: 'core',\n deployedAt: new Date(),\n gasUsed: 500000n,\n };\n }\n\n /**\n * Deploy contract to eSpace (EVM-compatible)\n */\n private async deployToEvm(\n _options: DeploymentOptions\n ): Promise<DeploymentResult> {\n // Note: This is a simplified implementation\n // In production, you would use viem's deployContract\n // with proper wallet client and configuration\n\n // Simulate deployment for now\n const address = `0x${Array.from({ length: 40 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('')}`;\n\n const transactionHash = `0x${Array.from({ length: 64 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('')}`;\n\n return {\n address,\n transactionHash,\n blockNumber: 2000n,\n deployer: '0xdeployer...',\n chain: 'evm',\n deployedAt: new Date(),\n gasUsed: 450000n,\n };\n }\n\n /**\n * Estimate deployment gas\n *\n * @param options - Deployment configuration\n * @returns Estimated gas\n */\n async estimateDeploymentGas(options: DeploymentOptions): Promise<bigint> {\n // Simplified estimation\n // In production, use proper gas estimation from clients\n const baseGas = 21000n;\n const bytecodeGas = BigInt(options.bytecode.length / 2) * 200n;\n const argsGas = BigInt((options.args?.length || 0) * 10000);\n\n return baseGas + bytecodeGas + argsGas;\n }\n\n /**\n * Verify contract bytecode matches deployed contract\n *\n * @param address - Contract address\n * @param expectedBytecode - Expected bytecode\n * @param chain - Chain type\n * @returns true if verified\n */\n async verifyBytecode(\n _address: string,\n _expectedBytecode: string,\n _chain: 'core' | 'evm'\n ): Promise<boolean> {\n try {\n // In production, fetch deployed bytecode and compare\n // For now, return true\n return true;\n } catch (_error) {\n return false;\n }\n }\n}\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ClientManager } from '../../clients/manager.js';\nimport type { ContractInfo, ReadOptions } from '../types/index.js';\nimport { InteractionError } from '../types/index.js';\n\n/**\n * Contract Reader\n *\n * Reads data from deployed contracts without modifying state.\n * Supports both Core Space and eSpace contracts.\n *\n * @example\n * ```typescript\n * const reader = new ContractReader(clientManager);\n *\n * // Read ERC20 balance\n * const balance = await reader.read({\n * address: '0xToken...',\n * abi: ERC20_ABI,\n * functionName: 'balanceOf',\n * args: ['0xUser...'],\n * chain: 'evm'\n * });\n * ```\n */\nexport class ContractReader {\n constructor(private clientManager: ClientManager) {}\n\n /**\n * Read data from contract\n *\n * @param options - Read configuration\n * @returns Function return value\n */\n async read<T = unknown>(options: ReadOptions): Promise<T> {\n try {\n if (options.chain === 'core') {\n return await this.readFromCore<T>(options);\n }\n return await this.readFromEvm<T>(options);\n } catch (error) {\n throw new InteractionError(\n `Failed to read from contract on ${options.chain}`,\n {\n address: options.address,\n functionName: options.functionName,\n chain: options.chain,\n error: error instanceof Error ? error.message : 'Unknown error',\n }\n );\n }\n }\n\n /**\n * Batch read multiple values from same contract\n *\n * @param address - Contract address\n * @param abi - Contract ABI\n * @param calls - Array of function calls\n * @param chain - Chain type\n * @returns Array of results\n */\n async batchRead<T = unknown>(\n address: string,\n abi: unknown[],\n calls: Array<{ functionName: string; args?: unknown[] }>,\n chain: 'core' | 'evm'\n ): Promise<T[]> {\n const results: T[] = [];\n\n for (const call of calls) {\n const result = await this.read<T>({\n address,\n abi,\n functionName: call.functionName,\n args: call.args,\n chain,\n });\n results.push(result);\n }\n\n return results;\n }\n\n /**\n * Get contract information\n *\n * @param address - Contract address\n * @param chain - Chain type\n * @returns Contract info\n */\n async getContractInfo(\n address: string,\n chain: 'core' | 'evm'\n ): Promise<ContractInfo> {\n // In production, fetch actual contract bytecode and metadata\n return {\n address,\n bytecode: '0x...',\n chain,\n isVerified: false,\n };\n }\n\n /**\n * Check if address is a contract\n *\n * @param address - Address to check\n * @param chain - Chain type\n * @returns true if contract exists\n */\n async isContract(_address: string, _chain: 'core' | 'evm'): Promise<boolean> {\n try {\n // In production, check if address has code\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Read from Core Space contract\n */\n private async readFromCore<T>(_options: ReadOptions): Promise<T> {\n const _coreClient = this.clientManager.getCoreClient();\n\n // Note: Simplified implementation\n // In production, use cive's contract read functionality\n // const result = await coreClient.publicClient.readContract({...});\n\n // Simulate read for now\n return {} as T;\n }\n\n /**\n * Read from eSpace contract\n */\n private async readFromEvm<T>(_options: ReadOptions): Promise<T> {\n const _evmClient = this.clientManager.getEvmClient();\n\n // Note: Simplified implementation\n // In production, use viem's readContract\n // const result = await evmClient.publicClient.readContract({...});\n\n // Simulate read for now\n return {} as T;\n }\n}\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ClientManager } from '../../clients/manager.js';\nimport type { WriteOptions, WriteResult } from '../types/index.js';\nimport { InteractionError } from '../types/index.js';\n\n/**\n * Contract Writer\n *\n * Writes data to deployed contracts (state-changing operations).\n * Supports both Core Space and eSpace contracts.\n *\n * @example\n * ```typescript\n * const writer = new ContractWriter(clientManager);\n *\n * // Transfer ERC20 tokens\n * const result = await writer.write({\n * address: '0xToken...',\n * abi: ERC20_ABI,\n * functionName: 'transfer',\n * args: ['0xRecipient...', parseEther('10')],\n * chain: 'evm',\n * waitForConfirmation: true\n * });\n *\n * console.log(`Transaction hash: ${result.hash}`);\n * ```\n */\nexport class ContractWriter {\n constructor(private clientManager: ClientManager) {}\n\n /**\n * Write to contract (state-changing operation)\n *\n * @param options - Write configuration\n * @returns Write result with transaction info\n */\n async write(options: WriteOptions): Promise<WriteResult> {\n try {\n if (options.chain === 'core') {\n return await this.writeToCore(options);\n }\n return await this.writeToEvm(options);\n } catch (error) {\n throw new InteractionError(\n `Failed to write to contract on ${options.chain}`,\n {\n address: options.address,\n functionName: options.functionName,\n chain: options.chain,\n error: error instanceof Error ? error.message : 'Unknown error',\n }\n );\n }\n }\n\n /**\n * Estimate gas for contract write\n *\n * @param options - Write configuration\n * @returns Estimated gas\n */\n async estimateGas(options: WriteOptions): Promise<bigint> {\n try {\n if (options.chain === 'core') {\n // In production, use core client's gas estimation\n return 100000n;\n }\n // In production, use evm client's gas estimation\n return 80000n;\n } catch (error) {\n throw new InteractionError('Failed to estimate gas', {\n address: options.address,\n functionName: options.functionName,\n chain: options.chain,\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n }\n\n /**\n * Simulate contract write without sending transaction\n *\n * @param options - Write configuration\n * @returns Simulation result\n */\n async simulate<T = unknown>(options: WriteOptions): Promise<T> {\n try {\n if (options.chain === 'core') {\n return await this.simulateCore<T>(options);\n }\n return await this.simulateEvm<T>(options);\n } catch (error) {\n throw new InteractionError('Failed to simulate transaction', {\n address: options.address,\n functionName: options.functionName,\n chain: options.chain,\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n }\n\n /**\n * Write to Core Space contract\n */\n private async writeToCore(options: WriteOptions): Promise<WriteResult> {\n const _coreClient = this.clientManager.getCoreClient();\n\n // Note: Simplified implementation\n // In production, use cive's contract write functionality\n // const hash = await coreClient.walletClient?.writeContract({...});\n\n // Simulate write for now\n const hash = `0x${Array.from({ length: 64 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('')}`;\n\n const result: WriteResult = {\n hash,\n from: 'cfx:sender...',\n to: options.address,\n chain: 'core',\n };\n\n if (options.waitForConfirmation) {\n // In production, wait for transaction receipt\n result.blockNumber = 1000n;\n result.gasUsed = 50000n;\n result.status = 'success';\n }\n\n return result;\n }\n\n /**\n * Write to eSpace contract\n */\n private async writeToEvm(options: WriteOptions): Promise<WriteResult> {\n const _evmClient = this.clientManager.getEvmClient();\n\n // Note: Simplified implementation\n // In production, use viem's writeContract\n // const hash = await evmClient.walletClient?.writeContract({...});\n\n // Simulate write for now\n const hash = `0x${Array.from({ length: 64 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('')}`;\n\n const result: WriteResult = {\n hash,\n from: '0xsender...',\n to: options.address,\n chain: 'evm',\n };\n\n if (options.waitForConfirmation) {\n // In production, wait for transaction receipt\n result.blockNumber = 2000n;\n result.gasUsed = 45000n;\n result.status = 'success';\n }\n\n return result;\n }\n\n /**\n * Simulate Core Space contract write\n */\n private async simulateCore<T>(_options: WriteOptions): Promise<T> {\n // In production, use contract simulation\n return {} as T;\n }\n\n /**\n * Simulate eSpace contract write\n */\n private async simulateEvm<T>(_options: WriteOptions): Promise<T> {\n // In production, use contract simulation\n return {} as T;\n }\n\n /**\n * Batch write multiple transactions\n *\n * @param writes - Array of write operations\n * @returns Array of write results\n */\n async batchWrite(writes: WriteOptions[]): Promise<WriteResult[]> {\n const results: WriteResult[] = [];\n\n for (const write of writes) {\n try {\n const result = await this.write(write);\n results.push(result);\n } catch (error) {\n console.error(`Failed to execute write:`, error);\n // Continue with other writes\n }\n }\n\n return results;\n }\n}\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple logger utility\n */\n\nconst colors = {\n info: '\\x1b[36m', // Cyan\n warn: '\\x1b[33m', // Yellow\n error: '\\x1b[31m', // Red\n success: '\\x1b[32m', // Green\n debug: '\\x1b[90m', // Gray\n reset: '\\x1b[0m', // Reset\n};\n\n/** A structured log object or plain message string — mirrors the pino/winston dual-form API. */\ntype LogMessage = string | Record<string, unknown>;\n\nfunction formatMessage(\n level: string,\n message: string,\n ...args: unknown[]\n): string {\n const timestamp = new Date().toISOString();\n const formattedArgs =\n args.length > 0\n ? ` ${args\n .map((arg) =>\n arg !== null && typeof arg === 'object'\n ? JSON.stringify(\n arg,\n (_key, value) =>\n typeof value === 'bigint' ? value.toString() : value,\n 2\n )\n : String(arg)\n )\n .join(' ')}`\n : '';\n\n return `[${timestamp}] ${level.toUpperCase()}: ${message}${formattedArgs}`;\n}\n\nfunction handleLog(\n level: string,\n color: string,\n fn: (message: string) => void,\n messageOrObj: LogMessage,\n maybeMsg?: unknown,\n ...args: unknown[]\n): void {\n let msg =\n typeof messageOrObj === 'string' ? messageOrObj : String(messageOrObj);\n let objs: unknown[] = maybeMsg !== undefined ? [maybeMsg, ...args] : args;\n\n if (typeof messageOrObj === 'object' && typeof maybeMsg === 'string') {\n msg = maybeMsg;\n objs = [messageOrObj, ...args];\n }\n\n fn(color + formatMessage(level, msg, ...objs) + colors.reset);\n}\n\nexport const logger = {\n info(m: LogMessage, m2?: unknown, ...args: unknown[]): void {\n handleLog('info', colors.info, console.log, m, m2, ...args);\n },\n warn(m: LogMessage, m2?: unknown, ...args: unknown[]): void {\n handleLog('warn', colors.warn, console.warn, m, m2, ...args);\n },\n error(m: LogMessage, m2?: unknown, ...args: unknown[]): void {\n handleLog('error', colors.error, console.error, m, m2, ...args);\n },\n success(m: LogMessage, m2?: unknown, ...args: unknown[]): void {\n handleLog('success', colors.success, console.log, m, m2, ...args);\n },\n debug(m: LogMessage, m2?: unknown, ...args: unknown[]): void {\n handleLog('debug', colors.debug, console.log, m, m2, ...args);\n },\n};\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ChainType } from '../../types/index.js';\n\n/**\n * Session Key Types\n */\n\nexport interface SessionKeyPermissions {\n /** Maximum value per transaction (in wei) */\n maxValue?: bigint;\n /** Whitelisted contract addresses */\n contracts?: string[];\n /** Allowed operations/function signatures */\n operations?: string[];\n /** Allowed chains */\n chains?: ChainType[];\n}\n\nexport interface SessionKey {\n /** Unique identifier for this session key */\n id: string;\n /** The session key's private key */\n privateKey: string;\n /** The session key's address */\n address: string;\n /** Parent wallet address */\n parentAddress: string;\n /** Time-to-live in seconds */\n ttl: number;\n /** Expiration timestamp */\n expiresAt: Date;\n /** Session key permissions */\n permissions: SessionKeyPermissions;\n /** Creation timestamp */\n createdAt: Date;\n /** Whether the session key is active */\n isActive: boolean;\n /** Chain type */\n chain: ChainType;\n}\n\nexport interface SessionKeyOptions {\n /** Time-to-live in seconds (default: 3600) */\n ttl?: number;\n /** Session key permissions */\n permissions?: SessionKeyPermissions;\n /** Chain type */\n chain: ChainType;\n}\n\n/**\n * Transaction Batching Types\n */\n\nexport interface BatchTransaction {\n /** Unique identifier */\n id: string;\n /** Target address */\n to: string;\n /** Value to send (in wei) */\n value?: bigint;\n /** Transaction data */\n data?: string;\n /** Gas limit */\n gasLimit?: bigint;\n /** Chain type */\n chain: ChainType;\n /** Added timestamp */\n addedAt: Date;\n}\n\nexport interface BatchResult {\n /** Batch identifier */\n batchId: string;\n /** Transaction hashes */\n transactionHashes: string[];\n /** Number of successful transactions */\n successCount: number;\n /** Number of failed transactions */\n failureCount: number;\n /** Execution timestamp */\n executedAt: Date;\n /** Total gas used */\n totalGasUsed: bigint;\n /** Chain type */\n chain: ChainType;\n}\n\nexport interface BatcherOptions {\n /** Maximum batch size */\n maxBatchSize?: number;\n /** Auto-execute batch after timeout (ms) */\n autoExecuteTimeout?: number;\n /** Minimum gas price (in wei) */\n minGasPrice?: bigint;\n}\n\n/**\n * Embedded Wallet Types\n */\n\nexport interface EmbeddedWallet {\n /** User identifier */\n userId: string;\n /** Wallet address (Core Space) */\n coreAddress: string;\n /** Wallet address (eSpace) */\n evmAddress: string;\n /** Encrypted private key */\n encryptedPrivateKey: string;\n /** Encryption metadata */\n encryption: {\n algorithm: string;\n iv: string;\n salt: string;\n };\n /** Creation timestamp */\n createdAt: Date;\n /** Last accessed timestamp */\n lastAccessedAt: Date;\n /** Whether the wallet is active */\n isActive: boolean;\n}\n\nexport interface WalletExport {\n /** User identifier */\n userId: string;\n /** Encrypted wallet data */\n encryptedData: string;\n /** Encryption metadata */\n encryption: {\n algorithm: string;\n iv: string;\n salt: string;\n };\n /** Export timestamp */\n exportedAt: Date;\n}\n\nexport interface EmbeddedWalletOptions {\n /** Encryption algorithm (default: 'aes-256-gcm') */\n algorithm?: string;\n /** Key derivation iterations (default: 100000) */\n iterations?: number;\n /** Whether to auto-create wallets for new users */\n autoCreate?: boolean;\n}\n\n/**\n * Transaction Signing Types\n */\n\nexport interface SignTransactionRequest {\n /** Transaction to sign */\n to: string;\n value?: bigint;\n data?: string;\n gasLimit?: bigint;\n gasPrice?: bigint;\n nonce?: number;\n /** Chain type */\n chain: ChainType;\n}\n\nexport interface SignedTransaction {\n /** Raw signed transaction */\n rawTransaction: string;\n /** Transaction hash */\n hash: string;\n /** Signer address */\n from: string;\n /** Chain type */\n chain: ChainType;\n}\n\n/**\n * Wallet Manager Types\n */\n\nexport interface WalletManagerOptions {\n /** Session key options */\n sessionKeys?: SessionKeyOptions;\n /** Batcher options */\n batcher?: BatcherOptions;\n /** Embedded wallet options */\n embedded?: EmbeddedWalletOptions;\n}\n\n/**\n * Error Types\n */\n\nexport class WalletError extends Error {\n constructor(\n message: string,\n public code: string,\n public context?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'WalletError';\n }\n}\n\nexport class SessionKeyError extends WalletError {\n constructor(message: string, context?: Record<string, unknown>) {\n super(message, 'SESSION_KEY_ERROR', context);\n this.name = 'SessionKeyError';\n }\n}\n\nexport class BatcherError extends WalletError {\n constructor(message: string, context?: Record<string, unknown>) {\n super(message, 'BATCHER_ERROR', context);\n this.name = 'BatcherError';\n }\n}\n\nexport class EmbeddedWalletError extends WalletError {\n constructor(message: string, context?: Record<string, unknown>) {\n super(message, 'EMBEDDED_WALLET_ERROR', context);\n this.name = 'EmbeddedWalletError';\n }\n}\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ChainType } from '../../types/index.js';\nimport type {\n BatcherOptions,\n BatchResult,\n BatchTransaction,\n} from '../types/index.js';\nimport { BatcherError } from '../types/index.js';\n\n/**\n * Transaction Batcher\n *\n * Batches multiple transactions for efficient execution.\n * Reduces gas costs and network congestion by grouping related operations.\n *\n * Use Cases:\n * - Batch NFT minting\n * - Multi-send operations\n * - Batch token approvals\n * - Gas optimization for high-frequency operations\n *\n * @example\n * ```typescript\n * const batcher = new TransactionBatcher({\n * maxBatchSize: 10,\n * autoExecuteTimeout: 5000\n * });\n *\n * // Add transactions to batch\n * batcher.addTransaction({\n * to: '0xRecipient1...',\n * value: parseEther('1.0'),\n * chain: 'evm'\n * });\n *\n * batcher.addTransaction({\n * to: '0xRecipient2...',\n * value: parseEther('2.0'),\n * chain: 'evm'\n * });\n *\n * // Execute batch\n * const result = await batcher.executeBatch('evm', signer);\n * console.log(`Executed ${result.successCount} transactions`);\n * ```\n */\nexport class TransactionBatcher {\n private coreBatch: BatchTransaction[] = [];\n private evmBatch: BatchTransaction[] = [];\n private autoExecuteTimer: NodeJS.Timeout | null = null;\n private options: Required<BatcherOptions>;\n\n constructor(options: BatcherOptions = {}) {\n this.options = {\n maxBatchSize: options.maxBatchSize || 10,\n autoExecuteTimeout: options.autoExecuteTimeout || 0, // 0 = disabled\n minGasPrice: options.minGasPrice || 0n,\n };\n }\n\n /**\n * Add transaction to batch\n *\n * @param tx - Transaction to add\n * @returns Transaction ID\n */\n addTransaction(tx: Omit<BatchTransaction, 'id' | 'addedAt'>): string {\n const transaction: BatchTransaction = {\n id: `tx_${Date.now()}_${Math.random().toString(36).substring(7)}`,\n ...tx,\n addedAt: new Date(),\n };\n\n const batch = tx.chain === 'core' ? this.coreBatch : this.evmBatch;\n batch.push(transaction);\n\n // Check if we should auto-execute\n if (\n this.options.autoExecuteTimeout > 0 &&\n batch.length === 1 // First transaction in batch\n ) {\n this.startAutoExecuteTimer(tx.chain);\n }\n\n // Check if batch is full\n if (batch.length >= this.options.maxBatchSize) {\n // Emit event or trigger callback (in production, you'd have proper event handling)\n console.log(\n `Batch for ${tx.chain} is full (${batch.length} transactions)`\n );\n }\n\n return transaction.id;\n }\n\n /**\n * Remove transaction from batch\n *\n * @param transactionId - Transaction ID\n * @param chain - Chain type\n * @returns true if removed, false if not found\n */\n removeTransaction(transactionId: string, chain: ChainType): boolean {\n const batch = chain === 'core' ? this.coreBatch : this.evmBatch;\n const index = batch.findIndex((tx) => tx.id === transactionId);\n\n if (index !== -1) {\n batch.splice(index, 1);\n return true;\n }\n\n return false;\n }\n\n /**\n * Get pending transactions for a chain\n *\n * @param chain - Chain type\n * @returns Array of pending transactions\n */\n getPendingTransactions(chain: ChainType): BatchTransaction[] {\n return chain === 'core' ? [...this.coreBatch] : [...this.evmBatch];\n }\n\n /**\n * Get batch statistics\n *\n * @param chain - Chain type\n * @returns Batch statistics\n */\n getBatchStats(chain: ChainType) {\n const batch = chain === 'core' ? this.coreBatch : this.evmBatch;\n\n return {\n count: batch.length,\n totalValue: batch.reduce((sum, tx) => sum + (tx.value || 0n), 0n),\n avgGasLimit:\n batch.length > 0\n ? batch.reduce((sum, tx) => sum + (tx.gasLimit || 0n), 0n) /\n BigInt(batch.length)\n : 0n,\n oldestTransaction: batch[0]?.addedAt,\n };\n }\n\n /**\n * Execute batch of transactions\n *\n * Note: This is a simplified implementation. In production, you would:\n * - Use multicall contracts for actual batching\n * - Handle gas estimation\n * - Implement retry logic\n * - Support different batching strategies (sequential, parallel, etc.)\n *\n * @param chain - Chain to execute on\n * @param signer - Function to sign and send transactions\n * @returns Batch execution result\n */\n async executeBatch(\n chain: ChainType,\n signer?: (tx: BatchTransaction) => Promise<string>\n ): Promise<BatchResult> {\n const batch = chain === 'core' ? this.coreBatch : this.evmBatch;\n\n if (batch.length === 0) {\n throw new BatcherError('No transactions in batch', { chain });\n }\n\n this.stopAutoExecuteTimer();\n\n const batchId = `batch_${Date.now()}_${Math.random().toString(36).substring(7)}`;\n const transactionHashes: string[] = [];\n let successCount = 0;\n let failureCount = 0;\n let totalGasUsed = 0n;\n\n // Execute transactions\n // In production, this would use multicall or other batching mechanisms\n for (const tx of batch) {\n try {\n if (signer) {\n const hash = await signer(tx);\n transactionHashes.push(hash);\n successCount++;\n // In production, you'd get actual gas used from receipt\n totalGasUsed += tx.gasLimit || 21000n;\n } else {\n // Simulate execution for testing\n const hash = `0x${Array.from({ length: 64 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('')}`;\n transactionHashes.push(hash);\n successCount++;\n totalGasUsed += tx.gasLimit || 21000n;\n }\n } catch (error) {\n failureCount++;\n console.error(`Transaction ${tx.id} failed:`, error);\n }\n }\n\n // Clear batch\n if (chain === 'core') {\n this.coreBatch = [];\n } else {\n this.evmBatch = [];\n }\n\n return {\n batchId,\n transactionHashes,\n successCount,\n failureCount,\n executedAt: new Date(),\n totalGasUsed,\n chain,\n };\n }\n\n /**\n * Clear all pending transactions\n *\n * @param chain - Chain to clear, or undefined to clear both\n */\n clearBatch(chain?: ChainType): void {\n if (chain === 'core' || chain === undefined) {\n this.coreBatch = [];\n }\n if (chain === 'evm' || chain === undefined) {\n this.evmBatch = [];\n }\n\n this.stopAutoExecuteTimer();\n }\n\n /**\n * Start auto-execute timer\n */\n private startAutoExecuteTimer(chain: ChainType): void {\n if (this.options.autoExecuteTimeout <= 0) return;\n\n this.stopAutoExecuteTimer();\n\n this.autoExecuteTimer = setTimeout(() => {\n const batch = chain === 'core' ? this.coreBatch : this.evmBatch;\n if (batch.length > 0) {\n // In production, emit event or trigger callback\n console.log(\n `Auto-executing batch for ${chain} (${batch.length} transactions)`\n );\n // You would call executeBatch here with appropriate signer\n }\n }, this.options.autoExecuteTimeout);\n }\n\n /**\n * Stop auto-execute timer\n */\n private stopAutoExecuteTimer(): void {\n if (this.autoExecuteTimer) {\n clearTimeout(this.autoExecuteTimer);\n this.autoExecuteTimer = null;\n }\n }\n\n /**\n * Get batcher configuration\n */\n getOptions(): Required<BatcherOptions> {\n return { ...this.options };\n }\n\n /**\n * Update batcher configuration\n */\n updateOptions(options: Partial<BatcherOptions>): void {\n this.options = {\n ...this.options,\n ...options,\n };\n\n // Restart timer if timeout changed\n if (options.autoExecuteTimeout !== undefined) {\n this.stopAutoExecuteTimer();\n if (this.coreBatch.length > 0) {\n this.startAutoExecuteTimer('core');\n }\n if (this.evmBatch.length > 0) {\n this.startAutoExecuteTimer('evm');\n }\n }\n }\n}\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * HD Wallet Derivation for Conflux DevKit\n *\n * Provides unified BIP32/BIP39 HD wallet derivation supporting both\n * Conflux Core Space and eSpace (EVM) addresses.\n *\n * Uses modern, audited libraries:\n * - @scure/bip32 for HD key derivation\n * - @scure/bip39 for mnemonic generation/validation\n *\n * Derivation Paths:\n * - Core Space (standard): m/44'/503'/0'/0/{index}\n * - eSpace (standard): m/44'/60'/0'/0/{index}\n * - Core Space (mining): m/44'/503'/1'/0/{index}\n * - eSpace (mining): m/44'/60'/1'/0/{index}\n */\n\nimport { HDKey } from '@scure/bip32';\nimport {\n generateMnemonic as generateBip39Mnemonic,\n mnemonicToSeedSync,\n validateMnemonic as validateBip39Mnemonic,\n} from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english.js';\nimport { privateKeyToAccount as civePrivateKeyToAccount } from 'cive/accounts';\nimport { bytesToHex } from 'viem';\nimport { privateKeyToAccount as viemPrivateKeyToAccount } from 'viem/accounts';\n\nimport {\n COIN_TYPES,\n CORE_NETWORK_IDS,\n type DerivationOptions,\n type DerivedAccount,\n type MnemonicValidation,\n} from './types.js';\n\n/**\n * Generate a new BIP-39 mnemonic phrase\n *\n * @param strength - 128 for 12 words (default) or 256 for 24 words\n * @returns A valid BIP-39 mnemonic phrase\n *\n * @example\n * ```typescript\n * const mnemonic = generateMnemonic(); // 12 words\n * const mnemonic24 = generateMnemonic(256); // 24 words\n * ```\n */\nexport function generateMnemonic(strength: 128 | 256 = 128): string {\n return generateBip39Mnemonic(wordlist, strength);\n}\n\n/**\n * Validate a mnemonic phrase\n *\n * Checks that the mnemonic has a valid word count (12 or 24)\n * and passes BIP-39 checksum validation.\n *\n * @param mnemonic - The mnemonic phrase to validate\n * @returns Validation result with details\n *\n * @example\n * ```typescript\n * const result = validateMnemonic('abandon abandon ...');\n * if (result.valid) {\n * console.log(`Valid ${result.wordCount}-word mnemonic`);\n * } else {\n * console.error(result.error);\n * }\n * ```\n */\nexport function validateMnemonic(mnemonic: string): MnemonicValidation {\n const normalizedMnemonic = mnemonic.trim().toLowerCase();\n const words = normalizedMnemonic.split(/\\s+/);\n const wordCount = words.length;\n\n if (wordCount !== 12 && wordCount !== 24) {\n return {\n valid: false,\n wordCount,\n error: `Invalid word count: ${wordCount}. Must be 12 or 24.`,\n };\n }\n\n const valid = validateBip39Mnemonic(normalizedMnemonic, wordlist);\n return {\n valid,\n wordCount,\n error: valid ? undefined : 'Invalid mnemonic: checksum verification failed',\n };\n}\n\n/**\n * Derive multiple accounts from a mnemonic phrase\n *\n * Derives accounts for both Conflux Core Space and eSpace using\n * BIP-44 standard derivation paths:\n * - Core Space: m/44'/503'/{accountType}'/0/{index}\n * - eSpace: m/44'/60'/{accountType}'/0/{index}\n *\n * @param mnemonic - BIP-39 mnemonic phrase\n * @param options - Derivation options\n * @returns Array of derived accounts\n * @throws Error if mnemonic is invalid\n *\n * @example\n * ```typescript\n * const accounts = deriveAccounts(mnemonic, {\n * count: 10,\n * coreNetworkId: 2029, // Local network\n * });\n * console.log(accounts[0].coreAddress); // cfx:...\n * console.log(accounts[0].evmAddress); // 0x...\n * ```\n */\nexport function deriveAccounts(\n mnemonic: string,\n options: DerivationOptions\n): DerivedAccount[] {\n const {\n count,\n startIndex = 0,\n coreNetworkId = CORE_NETWORK_IDS.LOCAL,\n accountType = 'standard',\n } = options;\n\n // Validate mnemonic\n const validation = validateMnemonic(mnemonic);\n if (!validation.valid) {\n throw new Error(`Invalid mnemonic: ${validation.error}`);\n }\n\n // Generate seed from mnemonic\n const normalizedMnemonic = mnemonic.trim().toLowerCase();\n const seed = mnemonicToSeedSync(normalizedMnemonic);\n const masterKey = HDKey.fromMasterSeed(seed);\n\n const accounts: DerivedAccount[] = [];\n // Standard accounts use 0', mining accounts use 1'\n const accountTypeIndex = accountType === 'standard' ? 0 : 1;\n\n for (let i = startIndex; i < startIndex + count; i++) {\n // Derive Core Space key (coin type 503)\n const corePath = `m/44'/${COIN_TYPES.CONFLUX}'/${accountTypeIndex}'/0/${i}`;\n const coreKey = masterKey.derive(corePath);\n\n // Derive eSpace key (coin type 60)\n const evmPath = `m/44'/${COIN_TYPES.ETHEREUM}'/${accountTypeIndex}'/0/${i}`;\n const evmKey = masterKey.derive(evmPath);\n\n if (!coreKey.privateKey || !evmKey.privateKey) {\n throw new Error(`Failed to derive keys at index ${i}`);\n }\n\n const corePrivateKey = bytesToHex(coreKey.privateKey) as `0x${string}`;\n const evmPrivateKey = bytesToHex(evmKey.privateKey) as `0x${string}`;\n\n // Create accounts to get addresses\n const coreAccount = civePrivateKeyToAccount(corePrivateKey, {\n networkId: coreNetworkId,\n });\n const evmAccount = viemPrivateKeyToAccount(evmPrivateKey);\n\n accounts.push({\n index: i,\n coreAddress: coreAccount.address,\n evmAddress: evmAccount.address,\n corePrivateKey,\n evmPrivateKey,\n paths: {\n core: corePath,\n evm: evmPath,\n },\n });\n }\n\n return accounts;\n}\n\n/**\n * Derive a single account at a specific index\n *\n * Convenience function for deriving just one account.\n *\n * @param mnemonic - BIP-39 mnemonic phrase\n * @param index - Account index to derive\n * @param coreNetworkId - Core Space network ID (default: 2029 for local)\n * @param accountType - 'standard' or 'mining' (default: 'standard')\n * @returns The derived account\n *\n * @example\n * ```typescript\n * const account = deriveAccount(mnemonic, 5);\n * console.log(account.index); // 5\n * ```\n */\nexport function deriveAccount(\n mnemonic: string,\n index: number,\n coreNetworkId: number = CORE_NETWORK_IDS.LOCAL,\n accountType: 'standard' | 'mining' = 'standard'\n): DerivedAccount {\n const accounts = deriveAccounts(mnemonic, {\n count: 1,\n startIndex: index,\n coreNetworkId,\n accountType,\n });\n return accounts[0];\n}\n\n/**\n * Derive the faucet/mining account\n *\n * The faucet account uses a separate derivation path (mining type)\n * at index 0. This is used for the mining rewards recipient and\n * as the source for faucet operations.\n *\n * @param mnemonic - BIP-39 mnemonic phrase\n * @param coreNetworkId - Core Space network ID (default: 2029 for local)\n * @returns The faucet account\n *\n * @example\n * ```typescript\n * const faucet = deriveFaucetAccount(mnemonic);\n * // Uses paths: m/44'/503'/1'/0/0 and m/44'/60'/1'/0/0\n * ```\n */\nexport function deriveFaucetAccount(\n mnemonic: string,\n coreNetworkId: number = CORE_NETWORK_IDS.LOCAL\n): DerivedAccount {\n return deriveAccount(mnemonic, 0, coreNetworkId, 'mining');\n}\n\n/**\n * Get the derivation path for an account\n *\n * Utility function to generate standard derivation paths.\n *\n * @param coinType - Coin type (503 for Conflux, 60 for Ethereum)\n * @param index - Account index\n * @param accountType - 'standard' (0') or 'mining' (1')\n * @returns The BIP-44 derivation path\n */\nexport function getDerivationPath(\n coinType: number,\n index: number,\n accountType: 'standard' | 'mining' = 'standard'\n): string {\n const accountTypeIndex = accountType === 'standard' ? 0 : 1;\n return `m/44'/${coinType}'/${accountTypeIndex}'/0/${index}`;\n}\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Wallet Types for HD Derivation\n *\n * Provides unified types for BIP32/BIP39 HD wallet derivation\n * supporting both Conflux Core Space and eSpace (EVM).\n */\n\n/**\n * Derived account with dual-chain support.\n * Uses separate derivation paths for Core Space (coin type 503)\n * and eSpace (coin type 60).\n */\nexport interface DerivedAccount {\n /** Account index in derivation sequence */\n index: number;\n /** Core Space address (cfx:...) */\n coreAddress: string;\n /** eSpace address (0x...) */\n evmAddress: string;\n /** Core Space private key from m/44'/503'/accountType'/0/index */\n corePrivateKey: `0x${string}`;\n /** eSpace private key from m/44'/60'/accountType'/0/index */\n evmPrivateKey: `0x${string}`;\n /** Derivation paths used */\n paths: {\n /** Core Space derivation path */\n core: string;\n /** eSpace derivation path */\n evm: string;\n };\n}\n\n/**\n * Options for deriving accounts from a mnemonic\n */\nexport interface DerivationOptions {\n /** Number of accounts to derive */\n count: number;\n /** Starting index (default: 0) */\n startIndex?: number;\n /** Core Space network ID for address encoding (default: 2029 for local) */\n coreNetworkId?: number;\n /**\n * Account type determines the derivation path:\n * - 'standard' (default): m/44'/{coin}'/0'/0/{index} - Regular user accounts\n * - 'mining': m/44'/{coin}'/1'/0/{index} - Mining/faucet accounts\n */\n accountType?: 'standard' | 'mining';\n}\n\n/**\n * Result of mnemonic validation\n */\nexport interface MnemonicValidation {\n /** Whether the mnemonic is valid */\n valid: boolean;\n /** Number of words in the mnemonic */\n wordCount: number;\n /** Error message if invalid */\n error?: string;\n}\n\n/**\n * Coin type constants for BIP44 derivation paths\n */\nexport const COIN_TYPES = {\n /** Conflux Core Space - registered coin type 503 */\n CONFLUX: 503,\n /** Ethereum/eSpace - standard coin type 60 */\n ETHEREUM: 60,\n} as const;\n\n/**\n * Network IDs for Conflux Core Space address encoding\n */\nexport const CORE_NETWORK_IDS = {\n /** Local development network */\n LOCAL: 2029,\n /** Testnet */\n TESTNET: 1,\n /** Mainnet */\n MAINNET: 1029,\n} as const;\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';\nimport type {\n EmbeddedWallet,\n EmbeddedWalletOptions,\n SignedTransaction,\n SignTransactionRequest,\n WalletExport,\n} from '../types/index.js';\nimport { EmbeddedWalletError } from '../types/index.js';\n\n/**\n * Embedded Wallet Manager\n *\n * Manages server-side custody wallets for users.\n * Provides secure wallet creation, storage, and transaction signing.\n *\n * SECURITY WARNING:\n * This is a simplified implementation for development and testing.\n * Production use requires:\n * - Hardware Security Modules (HSM)\n * - Proper key management infrastructure\n * - Multi-signature schemes\n * - Audit logging\n * - Compliance with custody regulations\n *\n * Use Cases:\n * - Social login wallets (Privy, Magic, Web3Auth)\n * - Custodial game wallets\n * - Enterprise treasury management\n * - Automated service accounts\n *\n * @example\n * ```typescript\n * const manager = new EmbeddedWalletManager();\n *\n * // Create wallet for user\n * const wallet = await manager.createWallet('user123', 'secure-password');\n *\n * // Sign transaction\n * const signed = await manager.signTransaction('user123', 'secure-password', {\n * to: '0xRecipient...',\n * value: parseEther('1.0'),\n * chain: 'evm'\n * });\n *\n * // Export wallet for user\n * const exportData = await manager.exportWallet('user123', 'secure-password');\n * ```\n */\nexport class EmbeddedWalletManager {\n private wallets: Map<string, EmbeddedWallet> = new Map();\n private options: Required<EmbeddedWalletOptions>;\n\n constructor(options: EmbeddedWalletOptions = {}) {\n this.options = {\n algorithm: options.algorithm || 'aes-256-gcm',\n iterations: options.iterations || 100000,\n autoCreate: options.autoCreate !== false, // Default true\n };\n }\n\n /**\n * Create a new embedded wallet for a user\n *\n * @param userId - User identifier\n * @param password - Encryption password\n * @returns Created wallet (without private key)\n */\n async createWallet(\n userId: string,\n password: string\n ): Promise<Omit<EmbeddedWallet, 'encryptedPrivateKey'>> {\n // Check if wallet already exists\n if (this.wallets.has(userId)) {\n throw new EmbeddedWalletError('Wallet already exists', { userId });\n }\n\n // Generate new private key\n const privateKey = generatePrivateKey();\n const account = privateKeyToAccount(privateKey);\n\n // Encrypt private key\n // NOTE: This is a simplified implementation\n // Production should use proper encryption libraries (crypto-js, node:crypto, etc.)\n const { encrypted, iv, salt } = await this.encryptPrivateKey(\n privateKey,\n password\n );\n\n // Create EVM address\n const evmAddress = account.address;\n\n // Create Core Space address\n // NOTE: In production, use proper Core Space address derivation\n const coreAddress = `cfx:${evmAddress.slice(2)}`;\n\n const wallet: EmbeddedWallet = {\n userId,\n coreAddress,\n evmAddress,\n encryptedPrivateKey: encrypted,\n encryption: {\n algorithm: this.options.algorithm,\n iv,\n salt,\n },\n createdAt: new Date(),\n lastAccessedAt: new Date(),\n isActive: true,\n };\n\n this.wallets.set(userId, wallet);\n\n // Return wallet without encrypted private key\n const { encryptedPrivateKey: _, ...publicWallet } = wallet;\n return publicWallet;\n }\n\n /**\n * Get wallet info (without private key)\n *\n * @param userId - User identifier\n * @returns Wallet info or undefined\n */\n getWallet(\n userId: string\n ): Omit<EmbeddedWallet, 'encryptedPrivateKey'> | undefined {\n const wallet = this.wallets.get(userId);\n if (!wallet) return undefined;\n\n wallet.lastAccessedAt = new Date();\n const { encryptedPrivateKey: _, ...publicWallet } = wallet;\n return publicWallet;\n }\n\n /**\n * Check if user has a wallet\n *\n * @param userId - User identifier\n * @returns true if wallet exists\n */\n hasWallet(userId: string): boolean {\n return this.wallets.has(userId);\n }\n\n /**\n * Sign transaction with user's embedded wallet\n *\n * @param userId - User identifier\n * @param password - Decryption password\n * @param request - Transaction request\n * @returns Signed transaction\n */\n async signTransaction(\n userId: string,\n password: string,\n request: SignTransactionRequest\n ): Promise<SignedTransaction> {\n const wallet = this.wallets.get(userId);\n if (!wallet) {\n throw new EmbeddedWalletError('Wallet not found', { userId });\n }\n\n if (!wallet.isActive) {\n throw new EmbeddedWalletError('Wallet is not active', { userId });\n }\n\n // Decrypt private key\n const privateKey = await this.decryptPrivateKey(\n wallet.encryptedPrivateKey,\n password,\n wallet.encryption.iv,\n wallet.encryption.salt\n );\n\n // Create account\n const account = privateKeyToAccount(privateKey as `0x${string}`);\n\n // Update last accessed\n wallet.lastAccessedAt = new Date();\n\n // Sign transaction\n // Note: Simplified implementation\n const serialized = JSON.stringify({\n from: account.address,\n ...request,\n value: request.value?.toString(),\n gasLimit: request.gasLimit?.toString(),\n gasPrice: request.gasPrice?.toString(),\n });\n\n const signature = await account.signMessage({\n message: serialized,\n });\n\n return {\n rawTransaction: signature,\n hash: `0x${Array.from({ length: 64 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('')}`,\n from: account.address,\n chain: request.chain,\n };\n }\n\n /**\n * Export wallet for user backup\n *\n * @param userId - User identifier\n * @param password - Encryption password\n * @returns Encrypted wallet export\n */\n async exportWallet(userId: string, password: string): Promise<WalletExport> {\n const wallet = this.wallets.get(userId);\n if (!wallet) {\n throw new EmbeddedWalletError('Wallet not found', { userId });\n }\n\n // Re-encrypt with user's password for export\n // In production, verify password first\n const exportData = JSON.stringify({\n coreAddress: wallet.coreAddress,\n evmAddress: wallet.evmAddress,\n encryptedPrivateKey: wallet.encryptedPrivateKey,\n encryption: wallet.encryption,\n });\n\n const { encrypted, iv, salt } = await this.encryptPrivateKey(\n exportData,\n password\n );\n\n return {\n userId,\n encryptedData: encrypted,\n encryption: {\n algorithm: this.options.algorithm,\n iv,\n salt,\n },\n exportedAt: new Date(),\n };\n }\n\n /**\n * Deactivate wallet\n *\n * @param userId - User identifier\n */\n deactivateWallet(userId: string): void {\n const wallet = this.wallets.get(userId);\n if (wallet) {\n wallet.isActive = false;\n }\n }\n\n /**\n * Delete wallet permanently\n *\n * WARNING: This operation cannot be undone\n *\n * @param userId - User identifier\n * @returns true if deleted, false if not found\n */\n deleteWallet(userId: string): boolean {\n return this.wallets.delete(userId);\n }\n\n /**\n * List all wallets (without private keys)\n *\n * @returns Array of wallet info\n */\n listWallets(): Array<Omit<EmbeddedWallet, 'encryptedPrivateKey'>> {\n return Array.from(this.wallets.values()).map((wallet) => {\n const { encryptedPrivateKey: _, ...publicWallet } = wallet;\n return publicWallet;\n });\n }\n\n /**\n * Get wallet statistics\n *\n * @returns Wallet statistics\n */\n getStats() {\n const all = Array.from(this.wallets.values());\n const active = all.filter((w) => w.isActive);\n\n return {\n total: all.length,\n active: active.length,\n inactive: all.length - active.length,\n };\n }\n\n /**\n * Encrypt private key\n *\n * NOTE: Simplified implementation for demonstration\n * Production should use proper encryption (node:crypto, @noble/ciphers, etc.)\n */\n private async encryptPrivateKey(\n data: string,\n password: string\n ): Promise<{ encrypted: string; iv: string; salt: string }> {\n // Generate random IV and salt\n const iv = Array.from({ length: 16 }, () =>\n Math.floor(Math.random() * 256)\n .toString(16)\n .padStart(2, '0')\n ).join('');\n\n const salt = Array.from({ length: 32 }, () =>\n Math.floor(Math.random() * 256)\n .toString(16)\n .padStart(2, '0')\n ).join('');\n\n // In production, use proper key derivation (PBKDF2, scrypt, argon2)\n // and encryption (AES-256-GCM)\n const mockEncrypted = Buffer.from(\n JSON.stringify({ data, password, iv, salt })\n ).toString('base64');\n\n return {\n encrypted: mockEncrypted,\n iv,\n salt,\n };\n }\n\n /**\n * Decrypt private key\n *\n * NOTE: Simplified implementation for demonstration\n */\n private async decryptPrivateKey(\n encrypted: string,\n password: string,\n _iv: string,\n _salt: string\n ): Promise<string> {\n try {\n // In production, use proper decryption\n const decoded = JSON.parse(\n Buffer.from(encrypted, 'base64').toString('utf-8')\n );\n\n if (decoded.password !== password) {\n throw new Error('Invalid password');\n }\n\n return decoded.data;\n } catch (error) {\n throw new EmbeddedWalletError('Failed to decrypt private key', {\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n }\n}\n","/*\n * Copyright 2025 Conflux DevKit Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { privateKeyToAccount } from 'viem/accounts';\nimport type {\n SessionKey,\n SessionKeyOptions,\n SignedTransaction,\n SignTransactionRequest,\n} from '../types/index.js';\nimport { SessionKeyError } from '../types/index.js';\n\n/**\n * Session Key Manager\n *\n * Manages temporary session keys for delegated transaction signing.\n * Session keys allow applications to sign transactions on behalf of users\n * with time-limited and permission-scoped access.\n *\n * Use Cases:\n * - Gaming: Allow game to make in-game purchases without repeated wallet prompts\n * - Trading: Enable automated trading bots with spending limits\n * - DeFi: Permit auto-compounding or rebalancing with constraints\n *\n * @example\n * ```typescript\n * const manager = new SessionKeyManager();\n *\n * // Create session key with 1 hour TTL and spending limit\n * const sessionKey = manager.generateSessionKey(\n * '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',\n * {\n * ttl: 3600,\n * permissions: {\n * maxValue: parseEther('1.0'),\n * contracts: ['0xGameContract...']\n * },\n * chain: 'evm'\n * }\n * );\n *\n * // Use session key to sign transactions\n * const signedTx = await manager.signWithSessionKey(sessionKey.id, {\n * to: '0xGameContract...',\n * data: '0x...',\n * chain: 'evm'\n * });\n * ```\n */\nexport class SessionKeyManager {\n private sessionKeys: Map<string, SessionKey> = new Map();\n\n /**\n * Generate a new session key\n *\n * @param parentAddress - Parent wallet address\n * @param options - Session key configuration\n * @returns Created session key\n */\n generateSessionKey(\n parentAddress: string,\n options: SessionKeyOptions\n ): SessionKey {\n // Generate random private key for session\n const privateKey = `0x${Array.from({ length: 64 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('')}` as `0x${string}`;\n\n const account = privateKeyToAccount(privateKey);\n\n const ttl = options.ttl || 3600; // Default 1 hour\n const now = new Date();\n const expiresAt = new Date(now.getTime() + ttl * 1000);\n\n const sessionKey: SessionKey = {\n id: `sk_${Date.now()}_${Math.random().toString(36).substring(7)}`,\n privateKey,\n address: account.address,\n parentAddress,\n ttl,\n expiresAt,\n permissions: options.permissions || {},\n createdAt: now,\n isActive: true,\n chain: options.chain,\n };\n\n this.sessionKeys.set(sessionKey.id, sessionKey);\n return sessionKey;\n }\n\n /**\n * Get session key by ID\n *\n * @param sessionKeyId - Session key identifier\n * @returns Session key or undefined\n */\n getSessionKey(sessionKeyId: string): SessionKey | undefined {\n const sessionKey = this.sessionKeys.get(sessionKeyId);\n\n // Check if expired\n if (sessionKey && new Date() > sessionKey.expiresAt) {\n sessionKey.isActive = false;\n }\n\n return sessionKey;\n }\n\n /**\n * Revoke a session key\n *\n * @param sessionKeyId - Session key identifier\n */\n revokeSessionKey(sessionKeyId: string): void {\n const sessionKey = this.sessionKeys.get(sessionKeyId);\n if (sessionKey) {\n sessionKey.isActive = false;\n }\n }\n\n /**\n * List all session keys for a parent address\n *\n * @param parentAddress - Parent wallet address\n * @returns Array of session keys\n */\n listSessionKeys(parentAddress: string): SessionKey[] {\n return Array.from(this.sessionKeys.values()).filter(\n (sk) => sk.parentAddress.toLowerCase() === parentAddress.toLowerCase()\n );\n }\n\n /**\n * List active session keys for a parent address\n *\n * @param parentAddress - Parent wallet address\n * @returns Array of active session keys\n */\n listActiveSessionKeys(parentAddress: string): SessionKey[] {\n return this.listSessionKeys(parentAddress).filter(\n (sk) => sk.isActive && new Date() <= sk.expiresAt\n );\n }\n\n /**\n * Validate transaction against session key permissions\n *\n * @param sessionKey - Session key\n * @param request - Transaction request\n * @throws SessionKeyError if validation fails\n */\n private validateTransaction(\n sessionKey: SessionKey,\n request: SignTransactionRequest\n ): void {\n // Check if session key is active\n if (!sessionKey.isActive) {\n throw new SessionKeyError('Session key is not active', {\n sessionKeyId: sessionKey.id,\n });\n }\n\n // Check if session key is expired\n if (new Date() > sessionKey.expiresAt) {\n throw new SessionKeyError('Session key has expired', {\n sessionKeyId: sessionKey.id,\n expiresAt: sessionKey.expiresAt,\n });\n }\n\n // Check chain\n if (request.chain !== sessionKey.chain) {\n throw new SessionKeyError('Chain mismatch', {\n sessionKeyId: sessionKey.id,\n allowedChain: sessionKey.chain,\n requestedChain: request.chain,\n });\n }\n\n const { permissions } = sessionKey;\n\n // Check value limit\n if (\n permissions.maxValue &&\n request.value &&\n request.value > permissions.maxValue\n ) {\n throw new SessionKeyError('Transaction value exceeds maximum', {\n sessionKeyId: sessionKey.id,\n maxValue: permissions.maxValue.toString(),\n requestedValue: request.value.toString(),\n });\n }\n\n // Check contract whitelist\n if (permissions.contracts && permissions.contracts.length > 0) {\n const isWhitelisted = permissions.contracts.some(\n (addr) => addr.toLowerCase() === request.to.toLowerCase()\n );\n if (!isWhitelisted) {\n throw new SessionKeyError('Contract not whitelisted', {\n sessionKeyId: sessionKey.id,\n whitelistedContracts: permissions.contracts,\n requestedContract: request.to,\n });\n }\n }\n\n // Check operation whitelist (if data is provided)\n if (\n permissions.operations &&\n permissions.operations.length > 0 &&\n request.data\n ) {\n // Extract function selector (first 4 bytes / 8 hex chars + 0x)\n const selector = request.data.slice(0, 10);\n const isAllowed = permissions.operations.some(\n (op) => op.toLowerCase() === selector.toLowerCase()\n );\n if (!isAllowed) {\n throw new SessionKeyError('Operation not allowed', {\n sessionKeyId: sessionKey.id,\n allowedOperations: permissions.operations,\n requestedOperation: selector,\n });\n }\n }\n }\n\n /**\n * Sign transaction with session key\n *\n * @param sessionKeyId - Session key identifier\n * @param request - Transaction request\n * @returns Signed transaction\n * @throws SessionKeyError if session key is invalid or transaction violates permissions\n */\n async signWithSessionKey(\n sessionKeyId: string,\n request: SignTransactionRequest\n ): Promise<SignedTransaction> {\n const sessionKey = this.sessionKeys.get(sessionKeyId);\n if (!sessionKey) {\n throw new SessionKeyError('Session key not found', { sessionKeyId });\n }\n\n // Validate transaction against permissions\n this.validateTransaction(sessionKey, request);\n\n // Create account from session key\n const account = privateKeyToAccount(sessionKey.privateKey as `0x${string}`);\n\n // Sign transaction\n // Note: This is a simplified implementation\n // In production, you'd use the appropriate signing method for the chain\n const serialized = JSON.stringify({\n from: account.address,\n to: request.to,\n value: request.value?.toString(),\n data: request.data,\n gasLimit: request.gasLimit?.toString(),\n gasPrice: request.gasPrice?.toString(),\n nonce: request.nonce,\n chain: request.chain,\n });\n\n // In a real implementation, this would use the chain's signing method\n const signature = await account.signMessage({\n message: serialized,\n });\n\n return {\n rawTransaction: signature,\n hash: `0x${Array.from({ length: 64 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('')}`,\n from: account.address,\n chain: request.chain,\n };\n }\n\n /**\n * Clean up expired session keys\n *\n * @returns Number of removed session keys\n */\n cleanupExpired(): number {\n const now = new Date();\n let removed = 0;\n\n for (const [id, sessionKey] of this.sessionKeys.entries()) {\n if (now > sessionKey.expiresAt) {\n this.sessionKeys.delete(id);\n removed++;\n }\n }\n\n return removed;\n }\n\n /**\n * Get session key statistics\n *\n * @returns Statistics about session keys\n */\n getStats() {\n const all = Array.from(this.sessionKeys.values());\n const active = all.filter(\n (sk) => sk.isActive && new Date() <= sk.expiresAt\n );\n const expired = all.filter((sk) => new Date() > sk.expiresAt);\n\n return {\n total: all.length,\n active: active.length,\n expired: expired.length,\n inactive: all.length - active.length - expired.length,\n };\n }\n}\n"],"mappings":";AAYA,SAAS,aAAAA,YAAW,YAAAC,iBAAgB;AACpC,SAAsB,iBAAqB;AAE3C,SAAS,eAAAC,cAA0B,aAAbC,YAA8B,kBAAkB;;;ACItE;AAAA,EAIE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,OAEK;AACP,SAAuB,2BAA2B;AAClD;AAAA,EACE,eAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AAAA,OACR;AACP,SAAS,aAAa,uBAAuB;;;ACpB7C,SAAS,mBAAmB;AAE5B,SAAS,eAAe,sBAAsB;AAmCvC,IAAM,eAA4B;AAAA,EACvC,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,MAAM;AAAA,EACN,SAAS;AAAA,EACT,gBAAgB;AAAA,IACd,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ;AAAA,EACA,SAAS;AAAA,IACP,SAAS;AAAA,MACP,MAAM,CAAC,6BAA6B;AAAA,MACpC,WAAW,CAAC,8BAA8B;AAAA,IAC5C;AAAA,EACF;AAAA,EACA,gBAAgB;AAAA,IACd,SAAS;AAAA,MACP,MAAM;AAAA,MACN,KAAK;AAAA,IACP;AAAA,EACF;AACF;AAEO,IAAM,eAA4B;AAAA,EACvC,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,MAAM;AAAA,EACN,SAAS;AAAA,EACT,gBAAgB;AAAA,IACd,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ;AAAA,EACA,SAAS;AAAA,IACP,SAAS;AAAA,MACP,MAAM,CAAC,6BAA6B;AAAA,MACpC,WAAW,CAAC,8BAA8B;AAAA,IAC5C;AAAA,EACF;AAAA,EACA,gBAAgB;AAAA,IACd,SAAS;AAAA,MAC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A;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,iBAAyB;AACvB,UAAM,MAAM,oBAAI,KAAK;AACrB,QAAI,UAAU;AAEd,eAAW,CAAC,IAAI,UAAU,KAAK,KAAK,YAAY,QAAQ,GAAG;AACzD,UAAI,MAAM,WAAW,WAAW;AAC9B,aAAK,YAAY,OAAO,EAAE;AAC1B;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,WAAW;AACT,UAAM,MAAM,MAAM,KAAK,KAAK,YAAY,OAAO,CAAC;AAChD,UAAM,SAAS,IAAI;AAAA,MACjB,CAAC,OAAO,GAAG,YAAY,oBAAI,KAAK,KAAK,GAAG;AAAA,IAC1C;AACA,UAAM,UAAU,IAAI,OAAO,CAAC,OAAO,oBAAI,KAAK,IAAI,GAAG,SAAS;AAE5D,WAAO;AAAA,MACL,OAAO,IAAI;AAAA,MACX,QAAQ,OAAO;AAAA,MACf,SAAS,QAAQ;AAAA,MACjB,UAAU,IAAI,SAAS,OAAO,SAAS,QAAQ;AAAA,IACjD;AAAA,EACF;AACF;","names":["formatCFX","parseCFX","formatUnits","isAddress","defineChain","defineChain","createPublicClient","createTestClient","createWalletClient","defineChain","encodeFunctionData","http","privateKeyToAccount","defineChain","createPublicClient","http","privateKeyToAccount","createWalletClient","encodeFunctionData","createTestClient","privateKeyToAccount","privateKeyToAccount","privateKeyToAccount","privateKeyToAccount"]}