* Try to load a previously auto-generated wallet key from disk.
()
| 48 | * Try to load a previously auto-generated wallet key from disk. |
| 49 | */ |
| 50 | async function loadSavedWallet(): Promise<string | undefined> { |
| 51 | try { |
| 52 | const key = (await readTextFile(WALLET_FILE)).trim(); |
| 53 | if (key.startsWith("0x") && key.length === 66) { |
| 54 | console.log(`[ClawRouter] ✓ Loaded existing wallet from ${WALLET_FILE}`); |
| 55 | return key; |
| 56 | } |
| 57 | // File exists but content is wrong — do NOT silently fall through to generate a new wallet. |
| 58 | // This would silently replace a funded wallet with an empty one. |
| 59 | console.error(`[ClawRouter] ✗ CRITICAL: Wallet file exists but has invalid format!`); |
| 60 | console.error(`[ClawRouter] File: ${WALLET_FILE}`); |
| 61 | console.error(`[ClawRouter] Expected: 0x followed by 64 hex characters (66 chars total)`); |
| 62 | console.error( |
| 63 | `[ClawRouter] To fix: restore your backup key or set BLOCKRUN_WALLET_KEY env var`, |
| 64 | ); |
| 65 | throw new Error( |
| 66 | `Wallet file at ${WALLET_FILE} is corrupted or has wrong format. ` + |
| 67 | `Refusing to auto-generate new wallet to protect existing funds. ` + |
| 68 | `Restore your backup key or set BLOCKRUN_WALLET_KEY environment variable.`, |
| 69 | ); |
| 70 | } catch (err) { |
| 71 | // Re-throw corruption errors (not ENOENT) |
| 72 | if ((err as NodeJS.ErrnoException).code !== "ENOENT") { |
| 73 | // If it's our own thrown error, re-throw as-is |
| 74 | if (err instanceof Error && err.message.includes("Refusing to auto-generate")) { |
| 75 | throw err; |
| 76 | } |
| 77 | console.error( |
| 78 | `[ClawRouter] ✗ Failed to read wallet file: ${err instanceof Error ? err.message : String(err)}`, |
| 79 | ); |
| 80 | throw new Error( |
| 81 | `Cannot read wallet file at ${WALLET_FILE}: ${err instanceof Error ? err.message : String(err)}. ` + |
| 82 | `Refusing to auto-generate new wallet to protect existing funds. ` + |
| 83 | `Fix file permissions or set BLOCKRUN_WALLET_KEY environment variable.`, |
| 84 | { cause: err }, |
| 85 | ); |
| 86 | } |
| 87 | } |
| 88 | return undefined; |
| 89 | } |
| 90 | |
| 91 | /** |
| 92 | * Load mnemonic from disk if it exists. |
no test coverage detected