@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/wallet/index.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 - Wallet module\n// HD wallet derivation, session keys, transaction batching, embedded wallets\n//\n// Consumers that only need wallet features (without the full client layer) can\n// use the lighter @cfxdevkit/wallet package which re-exports from here.\n\n// Transaction Batching\nexport { TransactionBatcher } from './batching/batcher.js';\n// ── HD Wallet Derivation (BIP32/BIP39) ─────────────────────────────────────\nexport {\n deriveAccount,\n deriveAccounts,\n deriveFaucetAccount,\n generateMnemonic,\n getDerivationPath,\n validateMnemonic,\n} from './derivation.js';\n// Embedded Wallets\nexport { EmbeddedWalletManager } from './embedded/custody.js';\n\n// ── Advanced Wallet Abstractions ────────────────────────────────────────────\n// Session Keys\nexport { SessionKeyManager } from './session-keys/manager.js';\n// Shared wallet types — includes interfaces and error classes\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 './types/index.js';\n// Wallet error classes (concrete values, not just types)\nexport {\n BatcherError,\n EmbeddedWalletError,\n SessionKeyError,\n WalletError,\n} from './types/index.js';\nexport type {\n DerivationOptions,\n DerivedAccount,\n MnemonicValidation,\n} from './types.js';\nexport {\n COIN_TYPES,\n CORE_NETWORK_IDS,\n} from './types.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\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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC+MO,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YACE,SACO,MACA,SACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAAN,cAA8B,YAAY;AAAA,EAC/C,YAAY,SAAiB,SAAmC;AAC9D,UAAM,SAAS,qBAAqB,OAAO;AAC3C,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,eAAN,cAA2B,YAAY;AAAA,EAC5C,YAAY,SAAiB,SAAmC;AAC9D,UAAM,SAAS,iBAAiB,OAAO;AACvC,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,sBAAN,cAAkC,YAAY;AAAA,EACnD,YAAY,SAAiB,SAAmC;AAC9D,UAAM,SAAS,yBAAyB,OAAO;AAC/C,SAAK,OAAO;AAAA,EACd;AACF;;;AChLO,IAAM,qBAAN,MAAyB;AAAA,EACtB,YAAgC,CAAC;AAAA,EACjC,WAA+B,CAAC;AAAA,EAChC,mBAA0C;AAAA,EAC1C;AAAA,EAER,YAAY,UAA0B,CAAC,GAAG;AACxC,SAAK,UAAU;AAAA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onic","validateBip39Mnemonic","civePrivateKeyToAccount","viemPrivateKeyToAccount","import_accounts","import_accounts"]}