apow-cli 0.11.19 → 0.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -44,19 +44,27 @@ const commander_1 = require("commander");
44
44
  const viem_1 = require("viem");
45
45
  const MiningAgent_json_1 = __importDefault(require("./abi/MiningAgent.json"));
46
46
  const config_1 = require("./config");
47
- const constants_1 = require("./bridge/constants");
48
- const uniswap_1 = require("./bridge/uniswap");
49
47
  const detect_1 = require("./detect");
48
+ const errors_1 = require("./errors");
50
49
  const explorer_1 = require("./explorer");
51
50
  const fund_1 = require("./fund");
51
+ const base_funding_1 = require("./base-funding");
52
+ const wallet_recovery_1 = require("./wallet-recovery");
53
+ const llm_setup_1 = require("./llm-setup");
52
54
  const mint_1 = require("./mint");
53
55
  const miner_1 = require("./miner");
54
56
  const preflight_1 = require("./preflight");
57
+ const secure_env_1 = require("./secure-env");
58
+ const session_1 = require("./signer/session");
55
59
  const stats_1 = require("./stats");
60
+ const sweep_1 = require("./sweep");
56
61
  const update_1 = require("./update");
57
62
  const ui = __importStar(require("./ui"));
63
+ const brand_intro_1 = require("./brand-intro");
58
64
  const wallet_store_1 = require("./wallet-store");
59
65
  const wallet_1 = require("./wallet");
66
+ const context_1 = require("./policy/context");
67
+ const policy_1 = require("./policy/policy");
60
68
  const miningAgentAbi = MiningAgent_json_1.default;
61
69
  const erc20BalanceAbi = [
62
70
  {
@@ -98,44 +106,134 @@ function ensureGitignoreSafetyEntries() {
98
106
  (0, node_fs_1.writeFileSync)(gitignorePath, content, "utf8");
99
107
  ui.ok(`Updated .gitignore: added ${missing.join(", ")}`);
100
108
  }
101
- async function maybeCreateEncryptedKeystoreBackup(address, privateKey, opts = {}) {
102
- const envPassword = process.env.KEYSTORE_PASSWORD?.trim();
103
- let password = envPassword ?? "";
104
- if (!password && opts.promptIfMissingPassword && ui.isInteractiveSession()) {
105
- const createBackup = await ui.confirm("Create encrypted JSON keystore backup? (recommended)");
106
- if (!createBackup) {
107
- return null;
109
+ async function getKeystorePassword(required, confirmPassword = true) {
110
+ const configuredPassword = (0, config_1.resolveKeystorePassword)();
111
+ if (configuredPassword) {
112
+ return configuredPassword;
113
+ }
114
+ if (!ui.isInteractiveSession()) {
115
+ if (required) {
116
+ ui.error("KEYSTORE_PASSWORD is required to create or unlock an encrypted wallet in a headless session.");
117
+ ui.hint("Set KEYSTORE_PASSWORD in your shell or secret manager, not in chat or command history.");
108
118
  }
109
- const entered = await ui.promptSecret("Keystore password");
110
- const confirm = await ui.promptSecret("Confirm keystore password");
111
- if (!entered) {
112
- ui.warn("No keystore password entered — skipping encrypted backup.");
113
- return null;
119
+ return null;
120
+ }
121
+ const entered = await ui.promptSecret("Keystore password");
122
+ if (!entered) {
123
+ if (required) {
124
+ ui.error("No keystore password entered.");
114
125
  }
126
+ return null;
127
+ }
128
+ if (confirmPassword) {
129
+ const confirm = await ui.promptSecret("Confirm keystore password");
115
130
  if (entered !== confirm) {
116
- ui.warn("Keystore passwords did not match — skipping encrypted backup.");
131
+ ui.error("Keystore passwords did not match.");
117
132
  return null;
118
133
  }
119
- password = entered;
120
- }
121
- if (!password) {
122
- return null;
123
134
  }
135
+ (0, session_1.setSessionPassword)(entered);
136
+ return entered;
137
+ }
138
+ async function saveKeystoreWithPassword(address, privateKey, password) {
139
+ (0, session_1.setSessionPassword)(password);
124
140
  return (0, wallet_store_1.saveEncryptedKeystoreFile)(address, privateKey, password);
125
141
  }
126
142
  async function saveWalletArtifacts(address, privateKey, opts = {}) {
127
143
  const result = {};
128
- if (opts.createPlaintextImportFile !== false) {
129
- result.plaintextPath = (0, wallet_store_1.savePlaintextImportFile)(address, privateKey);
144
+ const password = await getKeystorePassword(opts.requireKeystore === true);
145
+ if (password) {
146
+ result.keystorePath = await saveKeystoreWithPassword(address, privateKey, password);
130
147
  }
131
- const keystorePath = await maybeCreateEncryptedKeystoreBackup(address, privateKey, {
132
- promptIfMissingPassword: opts.promptForKeystoreBackup === true,
133
- });
134
- if (keystorePath) {
135
- result.keystorePath = keystorePath;
148
+ else if (opts.requireKeystore) {
149
+ throw new Error("Encrypted keystore was not created.");
136
150
  }
137
151
  return result;
138
152
  }
153
+ async function unlockConfiguredKeystoreIfNeeded() {
154
+ if (wallet_1.account && config_1.config.privateKey) {
155
+ return true;
156
+ }
157
+ if (!config_1.config.keystorePath) {
158
+ return false;
159
+ }
160
+ const password = await getKeystorePassword(true, false);
161
+ if (!password) {
162
+ return false;
163
+ }
164
+ try {
165
+ (0, wallet_store_1.loadEncryptedKeystoreFile)(config_1.config.keystorePath, password);
166
+ (0, config_1.reloadConfig)();
167
+ (0, wallet_1.reinitClients)();
168
+ return !!wallet_1.account && !!config_1.config.privateKey;
169
+ }
170
+ catch (error) {
171
+ ui.error(`Could not unlock encrypted keystore: ${(0, errors_1.errorText)(error)}`);
172
+ return false;
173
+ }
174
+ }
175
+ function isActiveGeneratedWallet(wallet) {
176
+ return !!config_1.config.keystorePath
177
+ && (0, wallet_store_1.resolveKeystorePath)(config_1.config.keystorePath) === (0, wallet_store_1.resolveKeystorePath)(wallet.keystorePath);
178
+ }
179
+ function printGeneratedWallets(wallets) {
180
+ console.log("");
181
+ console.log(` ${ui.bold("APoW WALLETS")}`);
182
+ console.log("");
183
+ for (const [index, wallet] of wallets.entries()) {
184
+ const active = isActiveGeneratedWallet(wallet) ? ` ${ui.green("(active)")}` : "";
185
+ console.log(` ${index + 1}. ${wallet.address}${active}`);
186
+ }
187
+ console.log("");
188
+ }
189
+ function resolveGeneratedWalletSelection(wallets, selection) {
190
+ if (/^\d+$/.test(selection)) {
191
+ const index = Number(selection) - 1;
192
+ return wallets[index];
193
+ }
194
+ if (!/^0x[0-9a-fA-F]{40}$/.test(selection)) {
195
+ return undefined;
196
+ }
197
+ return wallets.find((wallet) => wallet.address.toLowerCase() === selection.toLowerCase());
198
+ }
199
+ async function unlockGeneratedWallet(wallet) {
200
+ const configuredPassword = (0, config_1.resolveKeystorePassword)();
201
+ if (configuredPassword) {
202
+ try {
203
+ const privateKey = (0, wallet_store_1.loadEncryptedKeystoreFile)(wallet.keystorePath, configuredPassword);
204
+ const { privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
205
+ if (privateKeyToAccount(privateKey).address.toLowerCase() === wallet.address.toLowerCase()) {
206
+ return configuredPassword;
207
+ }
208
+ }
209
+ catch {
210
+ // This wallet may use a different password; prompt below when interactive.
211
+ }
212
+ }
213
+ if (!ui.isInteractiveSession()) {
214
+ ui.error("Could not unlock the selected wallet in this headless session.");
215
+ ui.hint("Provide its password through KEYSTORE_PASSWORD_CMD or a shell secret manager.");
216
+ return null;
217
+ }
218
+ const password = await ui.promptSecret(`Keystore password for ${wallet.address.slice(0, 6)}...${wallet.address.slice(-4)}`);
219
+ if (!password) {
220
+ ui.error("No keystore password entered.");
221
+ return null;
222
+ }
223
+ try {
224
+ const privateKey = (0, wallet_store_1.loadEncryptedKeystoreFile)(wallet.keystorePath, password);
225
+ const { privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
226
+ if (privateKeyToAccount(privateKey).address.toLowerCase() !== wallet.address.toLowerCase()) {
227
+ ui.error("The selected keystore does not match its registered wallet address.");
228
+ return null;
229
+ }
230
+ return password;
231
+ }
232
+ catch {
233
+ ui.error("Could not unlock the selected wallet. Check the password and try again.");
234
+ return null;
235
+ }
236
+ }
139
237
  function shouldSkipUpdateCheck(argv) {
140
238
  return argv.includes("--help")
141
239
  || argv.includes("-h")
@@ -143,35 +241,70 @@ function shouldSkipUpdateCheck(argv) {
143
241
  || argv.includes("-V")
144
242
  || argv[0] === "help";
145
243
  }
146
- async function setupWizard() {
147
- console.log("");
148
- ui.banner(["APoW Agent Setup"]);
149
- console.log("");
244
+ async function setupWizard(options = {}) {
245
+ if (options.showBrandIntro !== false) {
246
+ await (0, brand_intro_1.showBrandIntro)("setup");
247
+ }
150
248
  // Mode selection
151
- console.log(` ${ui.bold("Choose an operating mode")}`);
152
- console.log("");
153
- console.log(` ${ui.cyan("1.")} Easy Mode ${ui.dim("(recommended)")}`);
154
- console.log(` ${ui.dim("No config. Wallet + x402 RPC + x402 LLM + x402 GPU grind.")}`);
155
- console.log(` ${ui.cyan("2.")} Advanced Mode`);
156
- console.log(` ${ui.dim("Choose which parts your agent manages and which credentials you supply.")}`);
157
- console.log("");
158
- const modeInput = await ui.prompt("Choice", "1");
159
- const easyMode = modeInput !== "2";
249
+ let easyMode = true;
250
+ if (options.easyMode) {
251
+ ui.ok("Easy Mode selected.");
252
+ }
253
+ else {
254
+ console.log(` ${ui.bold("Choose an operating mode")}`);
255
+ console.log("");
256
+ console.log(` ${ui.cyan("1.")} Easy Mode ${ui.dim("(recommended)")}`);
257
+ console.log(` ${ui.dim("No config. Wallet + QuickNode x402 RPC + ClawRouter x402 LLM + RunPod x402 GPU.")}`);
258
+ console.log(` ${ui.cyan("2.")} Advanced Mode`);
259
+ console.log(` ${ui.dim("Choose which parts your agent manages and which credentials you supply.")}`);
260
+ console.log("");
261
+ const modeInput = await ui.prompt("Choice", "1");
262
+ easyMode = modeInput !== "2";
263
+ }
160
264
  console.log("");
161
265
  const totalSteps = easyMode ? 2 : 4;
162
266
  const values = {};
163
267
  // Step 1: Wallet
164
268
  console.log(` ${ui.bold(`Step 1/${totalSteps}: Wallet`)}`);
165
- console.log(` ${ui.dim("Your agent can manage a wallet for you, or you can supply your own.")}`);
166
- console.log("");
167
- console.log(` ${ui.cyan("1.")} Agent-managed wallet ${ui.dim("(generate one now)")}`);
168
- console.log(` ${ui.cyan("2.")} Existing wallet ${ui.dim("(paste private key)")}`);
169
- console.log("");
170
- const walletMode = await ui.prompt("Wallet choice", "1");
171
- const useExistingWallet = walletMode === "2";
172
- let privateKey;
269
+ let walletMode = "1";
270
+ if (options.easyMode) {
271
+ console.log(` ${ui.dim("Generating one dedicated encrypted APoW wallet.")}`);
272
+ console.log("");
273
+ }
274
+ else {
275
+ console.log(` ${ui.dim("Your agent can manage a wallet for you, or you can supply your own.")}`);
276
+ console.log("");
277
+ console.log(` ${ui.cyan("1.")} Agent-managed encrypted wallet ${ui.dim("(generate one now)")}`);
278
+ console.log(` ${ui.cyan("2.")} Existing encrypted keystore`);
279
+ console.log(` ${ui.cyan("3.")} Existing private key ${ui.dim("(encrypt before saving)")}`);
280
+ console.log("");
281
+ walletMode = await ui.prompt("Wallet choice", "1");
282
+ }
173
283
  let addr;
174
- if (useExistingWallet) {
284
+ let keystorePath;
285
+ if (walletMode === "2") {
286
+ const inputPath = await ui.prompt("Keystore path", process.env.KEYSTORE_PATH ?? "");
287
+ if (!inputPath) {
288
+ ui.error("Keystore path is required.");
289
+ return;
290
+ }
291
+ const password = await getKeystorePassword(true, false);
292
+ if (!password) {
293
+ return;
294
+ }
295
+ try {
296
+ const privateKey = (0, wallet_store_1.loadEncryptedKeystoreFile)(inputPath, password);
297
+ const { privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
298
+ const walletAccount = privateKeyToAccount(privateKey);
299
+ addr = walletAccount.address;
300
+ keystorePath = (0, wallet_store_1.resolveKeystorePath)(inputPath);
301
+ }
302
+ catch (error) {
303
+ ui.error(`Could not unlock keystore: ${(0, errors_1.errorText)(error)}`);
304
+ return;
305
+ }
306
+ }
307
+ else if (walletMode === "3") {
175
308
  const inputKey = await ui.promptSecret("Private key (0x-prefixed)");
176
309
  if (!inputKey) {
177
310
  ui.error("Private key is required.");
@@ -181,69 +314,68 @@ async function setupWizard() {
181
314
  ui.error("Invalid private key format. Must be 0x + 64 hex characters.");
182
315
  return;
183
316
  }
184
- privateKey = inputKey;
185
317
  const { privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
186
- const walletAccount = privateKeyToAccount(privateKey);
318
+ const walletAccount = privateKeyToAccount(inputKey);
187
319
  addr = walletAccount.address;
320
+ const password = await getKeystorePassword(true);
321
+ if (!password) {
322
+ return;
323
+ }
324
+ keystorePath = await saveKeystoreWithPassword(addr, inputKey, password);
325
+ console.log("");
326
+ console.log(` ${ui.dim(`Encrypted keystore saved to: ${keystorePath}`)}`);
188
327
  }
189
328
  else {
329
+ const password = await getKeystorePassword(true);
330
+ if (!password) {
331
+ return;
332
+ }
190
333
  const { generatePrivateKey, privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
191
- privateKey = generatePrivateKey();
334
+ const privateKey = generatePrivateKey();
192
335
  const walletAccount = privateKeyToAccount(privateKey);
193
336
  addr = walletAccount.address;
337
+ keystorePath = await saveKeystoreWithPassword(addr, privateKey, password);
338
+ (0, wallet_store_1.registerGeneratedWallet)(addr, keystorePath);
194
339
  console.log("");
195
340
  console.log(` ${ui.bold("NEW WALLET GENERATED")}`);
196
341
  console.log("");
197
342
  console.log(` Address: ${addr}`);
198
- console.log(` Private Key: ${privateKey}`);
343
+ console.log(` Keystore: ${keystorePath}`);
199
344
  console.log("");
200
- console.log(` ${ui.yellow("⚠ SAVE YOUR PRIVATE KEY — this is the only time")}`);
201
- console.log(` ${ui.yellow(" it will be displayed. Anyone with this key")}`);
202
- console.log(` ${ui.yellow(" controls your funds.")}`);
345
+ console.log(` ${ui.dim("Back up the encrypted keystore and its password separately.")}`);
203
346
  console.log("");
204
- console.log(` ${ui.dim("Import into Phantom, MetaMask, or any EVM wallet")}`);
205
- console.log(` ${ui.dim("to view your AGENT tokens and Mining Rig NFT.")}`);
206
- console.log("");
207
- console.log(` ${ui.dim("Fund this address with ≥0.005 ETH on Base to start.")}`);
208
- console.log("");
209
- const artifacts = await saveWalletArtifacts(addr, privateKey);
210
- if (artifacts.plaintextPath) {
211
- console.log(` ${ui.dim(`Import helper saved to: ${artifacts.plaintextPath}`)}`);
212
- console.log(` ${ui.yellow("This plaintext file is easy to import, but less secure than an encrypted keystore.")}`);
213
- }
214
- if (artifacts.keystorePath) {
215
- console.log(` ${ui.dim(`Encrypted keystore saved to: ${artifacts.keystorePath}`)}`);
216
- }
217
- else {
218
- console.log(` ${ui.dim("Tip: set KEYSTORE_PASSWORD or rerun wallet export to create an encrypted JSON keystore backup.")}`);
219
- }
347
+ console.log(` ${ui.dim("Verify wallet recovery before funding. apow start calculates the ETH deposit.")}`);
220
348
  console.log("");
221
349
  }
222
- values.PRIVATE_KEY = privateKey;
350
+ values.PRIVATE_KEY = "";
351
+ if (keystorePath) {
352
+ values.KEYSTORE_PATH = keystorePath;
353
+ }
223
354
  ui.ok(`Wallet: ${addr.slice(0, 6)}...${addr.slice(-4)}`);
224
355
  console.log("");
225
356
  if (easyMode) {
226
- // Easy Mode: fully autonomous x402 stack
357
+ // Easy Mode: automated wallet-paid x402 stack
227
358
  console.log(` ${ui.bold(`Step 2/${totalSteps}: Configuration`)}`);
228
359
  values.USE_X402 = "true";
229
360
  values.USE_X402_GRIND = "true";
230
361
  values.LLM_PROVIDER = "clawrouter";
231
- values.LLM_MODEL = "blockrun/eco";
232
362
  values.ALLOW_LOCAL_FALLBACK_WITH_X402 = "false";
233
- ui.ok("RPC: QuickNode x402 (wallet-paid, no API key)");
234
- ui.ok("LLM: ClawRouter x402 (wallet-paid, no API key)");
235
- ui.ok("Grinder: x402 GPU (remote, wallet-paid, no local CPU fallback)");
363
+ ui.ok("RPC: Auto (Zero Config via QuickNode x402; wallet-paid in USDC)");
364
+ ui.ok("LLM: Auto (Zero Config via ClawRouter x402; wallet-paid in USDC)");
365
+ ui.ok("Grinder: Auto (Zero Config via RunPod x402; wallet-paid in USDC)");
236
366
  console.log(` ${ui.dim("Easy mode is agent-first: no RPC key, no LLM key, no GPU rental setup.")}`);
237
- console.log(` ${ui.dim("Fund the wallet with ETH + USDC on Base, then run: apow start")}`);
367
+ console.log(` ${ui.dim(`Deposit Base ETH only. The CLI converts the service budget to USDC. Run: apow start${options.easyMode ? " --easy" : ""}`)}`);
238
368
  }
239
369
  else {
240
370
  // Advanced: user picks which services remain autonomous
241
371
  // Step 2: RPC
242
372
  console.log(` ${ui.bold(`Step 2/${totalSteps}: RPC`)}`);
243
- console.log(` ${ui.dim("Choose whether your agent pays for RPC via x402 or you provide your own endpoint.")}`);
373
+ console.log(` ${ui.dim("Choose automatic wallet-paid RPC or provide your own Base endpoint.")}`);
244
374
  console.log("");
245
- console.log(` ${ui.cyan("1.")} Agent-managed x402 RPC ${ui.dim("(recommended)")}`);
375
+ console.log(` ${ui.cyan("1.")} Auto ${ui.dim("(recommended — Zero Config via QuickNode x402)")}`);
376
+ console.log(` ${ui.dim("No account or API key to connect.")}`);
246
377
  console.log(` ${ui.cyan("2.")} Custom RPC URL`);
378
+ console.log(` ${ui.dim("Get a free Base RPC URL from Alchemy: https://www.alchemy.com/")}`);
247
379
  console.log("");
248
380
  const rpcMode = await ui.prompt("RPC choice", "1");
249
381
  if (rpcMode === "2") {
@@ -253,42 +385,48 @@ async function setupWizard() {
253
385
  ui.ok(`RPC: Custom (${rpcUrl.slice(0, 40)}${rpcUrl.length > 40 ? "..." : ""})`);
254
386
  }
255
387
  else {
256
- ui.warn("No URL provided — using QuickNode x402");
388
+ ui.warn("No URL provided — using Auto RPC via x402");
257
389
  values.USE_X402 = "true";
258
- ui.ok("RPC: QuickNode x402");
390
+ ui.ok("RPC: Auto (Zero Config via QuickNode x402)");
259
391
  }
260
392
  }
261
393
  else {
262
394
  values.USE_X402 = "true";
263
- ui.ok("RPC: QuickNode x402 (wallet-paid)");
395
+ ui.ok("RPC: Auto (Zero Config via QuickNode x402; wallet-paid in USDC)");
264
396
  }
265
397
  console.log("");
266
398
  // Step 3: LLM (for minting)
267
399
  console.log(` ${ui.bold(`Step 3/${totalSteps}: LLM (minting only)`)}`);
268
400
  console.log(` ${ui.dim("An LLM solves the SMHL challenge when minting your Mining Rig.")}`);
269
401
  console.log(` ${ui.dim("Mining uses optimized solving — no LLM needed after minting.")}`);
270
- console.log(` ${ui.dim(" clawrouter (recommended) — wallet-paid via x402")}`);
271
- console.log(` ${ui.dim(" openai / anthropic / gemini / deepseek / qwen — API key")}`);
272
- console.log(` ${ui.dim(" ollama / claude-code / codex — local")}`);
273
- const providerInput = await ui.prompt("Provider", "clawrouter");
274
- const provider = (["clawrouter", "openai", "anthropic", "gemini", "ollama", "deepseek", "qwen", "claude-code", "codex"].includes(providerInput) ? providerInput : "clawrouter");
275
- values.LLM_PROVIDER = provider;
276
- if (provider === "clawrouter") {
277
- ui.ok("ClawRouter x402 — no API key needed, pays with USDC from your wallet");
402
+ console.log("");
403
+ console.log(` ${ui.cyan("1.")} Auto ${ui.dim("(recommended — Zero Config via ClawRouter x402)")}`);
404
+ console.log(` ${ui.dim("No account or API key to connect.")}`);
405
+ console.log(` ${ui.dim("Typical ClawRouter eco cost: $0–$0.0004 USDC per call; varies by usage.")}`);
406
+ console.log(` ${ui.cyan("2.")} API key ${ui.dim("(OpenAI, Anthropic, or Gemini; more providers available)")}`);
407
+ console.log(` ${ui.cyan("3.")} Local / subscription CLI ${ui.dim("(Ollama, Claude Code, or Codex)")}`);
408
+ console.log("");
409
+ const llmMode = (0, llm_setup_1.resolveLlmSetupMode)(await ui.prompt("LLM choice", "1"));
410
+ let provider;
411
+ if (llmMode === "x402") {
412
+ provider = "clawrouter";
413
+ values.LLM_PROVIDER = provider;
414
+ ui.ok("Auto LLM enabled — Zero Config via ClawRouter x402; wallet-paid in USDC");
278
415
  if (!values.USE_X402 && !values.RPC_URL) {
279
416
  values.USE_X402 = "true";
280
417
  ui.ok("Auto-enabled x402 RPC (same wallet, same USDC balance)");
281
418
  }
282
419
  }
283
- else if (provider === "ollama") {
284
- const ollamaUrl = await ui.prompt("Ollama URL", "http://127.0.0.1:11434");
285
- values.OLLAMA_URL = ollamaUrl;
286
- ui.ok(`Ollama at ${ollamaUrl}`);
287
- }
288
- else if (provider === "claude-code" || provider === "codex") {
289
- ui.ok(`Using local ${provider} CLI — make sure you're already authenticated`);
290
- }
291
- else {
420
+ else if (llmMode === "api-key") {
421
+ console.log("");
422
+ console.log(` ${ui.cyan("1.")} OpenAI`);
423
+ console.log(` ${ui.cyan("2.")} Anthropic`);
424
+ console.log(` ${ui.cyan("3.")} Gemini`);
425
+ console.log(` ${ui.cyan("4.")} DeepSeek`);
426
+ console.log(` ${ui.cyan("5.")} Qwen`);
427
+ console.log("");
428
+ provider = (0, llm_setup_1.resolveApiProvider)(await ui.prompt("API provider", "1"));
429
+ values.LLM_PROVIDER = provider;
292
430
  const apiKey = await ui.promptSecret("API key");
293
431
  if (apiKey) {
294
432
  values.LLM_API_KEY = apiKey;
@@ -298,38 +436,57 @@ async function setupWizard() {
298
436
  ui.fail("No API key provided");
299
437
  ui.hint("Set LLM_API_KEY in .env later");
300
438
  }
439
+ const model = await ui.prompt("Model", (0, config_1.resolveDefaultModel)(provider));
440
+ values.LLM_MODEL = model;
441
+ if ((0, config_1.isExpensiveModel)(model)) {
442
+ ui.warn(`${model} is expensive. Consider a smaller model for lower cost.`);
443
+ }
301
444
  }
302
- const defaultModel = (0, config_1.resolveDefaultModel)(provider);
303
- const model = await ui.prompt("Model", defaultModel);
304
- values.LLM_MODEL = model;
305
- if ((0, config_1.isExpensiveModel)(model)) {
306
- ui.warn(`${model} is expensive. Consider gpt-4o-mini for lower cost.`);
445
+ else {
446
+ console.log("");
447
+ console.log(` ${ui.cyan("1.")} Ollama ${ui.dim("(model runs on this machine)")}`);
448
+ console.log(` ${ui.cyan("2.")} Claude Code ${ui.dim("(hosted via your Claude subscription)")}`);
449
+ console.log(` ${ui.cyan("3.")} Codex ${ui.dim("(hosted via your ChatGPT subscription)")}`);
450
+ console.log("");
451
+ provider = (0, llm_setup_1.resolveLocalProvider)(await ui.prompt("Local / subscription provider", "1"));
452
+ values.LLM_PROVIDER = provider;
453
+ const model = (0, config_1.resolveDefaultModel)(provider);
454
+ values.LLM_MODEL = model;
455
+ if (provider === "ollama") {
456
+ const ollamaUrl = await ui.prompt("Ollama URL", "http://127.0.0.1:11434");
457
+ values.OLLAMA_URL = ollamaUrl;
458
+ values.LLM_MODEL = await ui.prompt("Ollama model", model);
459
+ ui.ok(`Ollama at ${ollamaUrl} (local inference)`);
460
+ ui.hint(`Run \`ollama pull ${values.LLM_MODEL}\` before minting.`);
461
+ }
462
+ else if (provider === "claude-code") {
463
+ ui.ok(`Claude Code subscription — ${model} auto-selected`);
464
+ ui.hint("Requires an installed, signed-in Claude Code CLI. APoW disables its tools for SMHL.");
465
+ }
466
+ else {
467
+ ui.ok(`Codex subscription — ${model} auto-selected`);
468
+ ui.hint("Requires an installed, signed-in Codex CLI. APoW uses a read-only isolated run for SMHL.");
469
+ }
307
470
  }
308
471
  console.log("");
309
472
  // Step 4: Nonce grinding strategy
310
473
  console.log(` ${ui.bold(`Step 4/${totalSteps}: GPU Grinding`)}`);
311
474
  console.log(` ${ui.dim("Choose how the miner should find nonces at current network difficulty.")}`);
312
475
  console.log("");
313
- console.log(` ${ui.cyan("1.")} Agent-managed x402 GPU ${ui.dim("(recommended, no setup)")}`);
314
- console.log(` ${ui.cyan("2.")} Local / custom grinders only`);
315
- console.log(` ${ui.cyan("3.")} Hybrid ${ui.dim("(x402 GPU + local JS fallback)")}`);
476
+ console.log(` ${ui.cyan("1.")} Auto ${ui.dim("(recommended — Zero Config via RunPod x402)")}`);
477
+ console.log(` ${ui.dim("No account, API key, or GPU rental setup to connect.")}`);
478
+ console.log(` ${ui.cyan("2.")} Local CPU/GPU`);
316
479
  console.log("");
317
480
  const grindMode = await ui.prompt("Grinding choice", "1");
318
481
  if (grindMode === "2") {
319
482
  values.USE_X402_GRIND = "false";
320
483
  values.ALLOW_LOCAL_FALLBACK_WITH_X402 = "false";
321
- ui.ok("Grinding: local/custom only");
322
- ui.hint("Configure GPU_GRINDER_PATH, CUDA_GRINDER_PATH, or VAST_* yourself if needed.");
323
- }
324
- else if (grindMode === "3") {
325
- values.USE_X402_GRIND = "true";
326
- values.ALLOW_LOCAL_FALLBACK_WITH_X402 = "true";
327
- ui.ok("Grinding: x402 GPU with local JS fallback");
484
+ ui.ok("Grinding: Local CPU/GPU");
328
485
  }
329
486
  else {
330
487
  values.USE_X402_GRIND = "true";
331
488
  values.ALLOW_LOCAL_FALLBACK_WITH_X402 = "false";
332
- ui.ok("Grinding: x402 GPU only");
489
+ ui.ok("Grinding: Auto (Zero Config via RunPod x402)");
333
490
  }
334
491
  }
335
492
  // Contract addresses
@@ -338,43 +495,58 @@ async function setupWizard() {
338
495
  console.log("");
339
496
  // Check for existing .env
340
497
  const envPath = (0, node_path_1.join)(process.cwd(), ".env");
341
- if ((0, node_fs_1.existsSync)(envPath)) {
342
- const overwrite = await ui.confirm("Overwrite existing .env?");
343
- if (!overwrite) {
498
+ if ((0, node_fs_1.existsSync)(envPath) && !options.easyMode) {
499
+ ui.hint("This updates APoW setup values, including the active wallet. Unrelated environment variables are kept.");
500
+ const update = await ui.confirm("Update existing .env with these settings?");
501
+ if (!update) {
344
502
  console.log(" Setup cancelled.");
345
503
  return;
346
504
  }
347
505
  }
348
506
  await (0, config_1.writeEnvFile)(values);
507
+ const policyFile = (0, policy_1.writeDefaultPolicyFile)();
349
508
  (0, config_1.reloadConfig)();
350
509
  (0, wallet_1.reinitClients)();
351
510
  ui.ok("Config saved to .env");
511
+ ui.ok(`Policy ready at ${policyFile}`);
352
512
  ensureGitignoreSafetyEntries();
353
- console.log("");
354
- console.log(` Next: ${ui.cyan("apow start")}`);
355
- console.log(` ${ui.dim("Guided happy path: setup -> fund -> mint -> mine")}`);
356
- console.log("");
513
+ if (!options.easyMode) {
514
+ console.log("");
515
+ console.log(` Next: ${ui.cyan("apow start")}`);
516
+ console.log(` ${ui.dim("Guided happy path: setup -> fund -> mint -> mine")}`);
517
+ console.log("");
518
+ }
519
+ }
520
+ function showFundingHandoff(address, depositEth, easyMode) {
521
+ ui.warn("Pausing for Base funding.");
522
+ ui.hint(`Send at least ${(0, viem_1.formatEther)(depositEth)} ETH on Base to ${address}.`);
523
+ ui.hint("This quote includes the current mint price, an ETH reserve, and the USDC conversion if needed. Costs can change before deposit.");
524
+ ui.hint("The CLI converts ETH to USDC within the signing policy. You do not need to send USDC.");
525
+ ui.hint(`After funds arrive, rerun \`apow start${easyMode ? " --easy" : ""}\`.`);
357
526
  }
358
- function showHeadlessFundingHandoff(address, needsEth, needsUsdc) {
359
- ui.warn("Headless session detected — pausing before funding.");
360
- ui.hint(`Send funds to ${address} on Base.`);
361
- if (needsEth) {
362
- ui.hint(`Need at least ${constants_1.MIN_ETH} ETH for gas and minting.`);
363
- }
364
- if (needsUsdc) {
365
- ui.hint(`Need at least ${constants_1.MIN_USDC} USDC for QuickNode + ClawRouter x402.`);
366
- }
367
- ui.hint("Funding routes:");
368
- ui.hint("Direct on Base: send ETH and/or USDC to this wallet");
369
- ui.hint("Bridge from Solana: apow fund --chain solana --token sol");
370
- ui.hint("Bridge from Ethereum: apow fund --chain ethereum");
371
- ui.hint("After funds arrive, rerun `apow start`.");
527
+ async function checkWalletRecovery() {
528
+ if (!wallet_1.account || !config_1.config.keystorePath)
529
+ throw new Error("Use an encrypted APoW wallet before funding.");
530
+ // A person can supply a separately retained password directly in a local terminal.
531
+ // Headless agents must use a saved secret-manager command, never process memory alone.
532
+ const password = ui.isInteractiveSession()
533
+ ? await ui.promptSecret("Re-enter your separately saved keystore password to test recovery") : undefined;
534
+ if (ui.isInteractiveSession() && !password)
535
+ throw new Error("Wallet recovery test cancelled.");
536
+ (0, wallet_recovery_1.verifyWalletRecovery)(config_1.config.keystorePath, wallet_1.account.address, password);
537
+ ui.ok(`Fresh-process unlock verified for ${wallet_1.account.address}.`);
538
+ ui.hint("Keep an independent encrypted-keystore backup and its password separately. This check does not verify host uptime or your backup.");
372
539
  }
373
- async function runStartFlow() {
540
+ async function runStartFlow(options = {}) {
541
+ await (0, brand_intro_1.showBrandIntro)("start");
542
+ const unlockedConfiguredWallet = await unlockConfiguredKeystoreIfNeeded();
543
+ if (config_1.config.keystorePath && !unlockedConfiguredWallet && !wallet_1.account) {
544
+ return;
545
+ }
374
546
  if (!config_1.config.privateKey || !wallet_1.account) {
375
547
  console.log("");
376
548
  ui.warn("No wallet configured — launching setup.");
377
- await setupWizard();
549
+ await setupWizard({ easyMode: options.easyMode === true, showBrandIntro: false });
378
550
  (0, config_1.reloadConfig)();
379
551
  (0, wallet_1.reinitClients)();
380
552
  }
@@ -382,78 +554,44 @@ async function runStartFlow() {
382
554
  ui.error("Wallet configuration did not complete.");
383
555
  return;
384
556
  }
385
- const bootstrapClient = config_1.config.useX402 && config_1.config.chainName === "base"
386
- ? (0, viem_1.createPublicClient)({ chain: config_1.config.chain, transport: (0, viem_1.http)("https://1rpc.io/base") })
387
- : wallet_1.publicClient;
388
- console.log("");
389
- ui.banner(["APoW Start"]);
390
- console.log("");
557
+ if (options.easyMode) {
558
+ const policyError = (0, policy_1.validateEasyModePolicyCaps)((0, policy_1.loadPolicy)());
559
+ if (policyError) {
560
+ ui.error(policyError);
561
+ ui.hint("Restore the default enforce-mode Easy Mode caps, then retry.");
562
+ return;
563
+ }
564
+ await (0, config_1.writeEnvFile)({ USE_X402: "true", USE_X402_GRIND: "true", LLM_PROVIDER: "clawrouter", ALLOW_LOCAL_FALLBACK_WITH_X402: "false" });
565
+ (0, config_1.reloadConfig)();
566
+ (0, wallet_1.reinitClients)();
567
+ }
568
+ await checkWalletRecovery();
569
+ const bootstrapClient = (0, wallet_1.getFundingClients)().publicClient;
391
570
  let miners = [];
392
571
  try {
393
572
  miners = await (0, detect_1.detectMinersWithClient)(bootstrapClient, wallet_1.account.address);
394
573
  }
395
574
  catch {
396
- ui.warn("Could not query wallet rigs via bootstrap RPC — continuing with funding guidance.");
575
+ throw new Error("Could not query owned rigs. Retry when the funding RPC responds; do not create a replacement wallet or rig.");
576
+ }
577
+ const funding = await (0, base_funding_1.prepareBaseFunding)(miners.length === 0, true);
578
+ if (!funding.ready) {
579
+ showFundingHandoff(wallet_1.account.address, funding.depositEth, options.easyMode === true);
580
+ return;
397
581
  }
398
582
  if (miners.length > 0) {
399
583
  const best = (0, detect_1.selectBestMiner)(miners);
400
584
  console.log(` ${ui.green("Wallet ready.")} Found ${miners.length} rig${miners.length === 1 ? "" : "s"} — starting miner #${best.tokenId}.`);
401
585
  console.log("");
402
586
  await (0, preflight_1.runPreflight)("mining");
403
- await (0, miner_1.startMining)(best.tokenId);
587
+ await (0, miner_1.startMining)(best.tokenId, { easyMode: options.easyMode === true });
404
588
  return;
405
589
  }
406
- let ethBalance = 0;
407
- let usdcBalance = 0;
408
- let balanceChecksAvailable = true;
409
- try {
410
- const [ethBalanceRaw, usdcBalanceRaw] = await Promise.all([
411
- bootstrapClient.getBalance({ address: wallet_1.account.address }),
412
- config_1.config.useX402
413
- ? bootstrapClient.readContract({
414
- address: config_1.config.chainName === "base" ? "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" : config_1.config.agentCoinAddress,
415
- abi: erc20BalanceAbi,
416
- functionName: "balanceOf",
417
- args: [wallet_1.account.address],
418
- })
419
- : Promise.resolve(0n),
420
- ]);
421
- ethBalance = Number((0, viem_1.formatEther)(ethBalanceRaw));
422
- usdcBalance = Number((0, viem_1.formatUnits)(usdcBalanceRaw, 6));
423
- }
424
- catch {
425
- balanceChecksAvailable = false;
426
- ui.warn("Could not query wallet balances via bootstrap RPC — funding flow may still be needed.");
427
- }
428
- const needsEth = !balanceChecksAvailable || ethBalance < constants_1.MIN_ETH;
429
- const needsUsdc = config_1.config.useX402 && (!balanceChecksAvailable || usdcBalance < constants_1.MIN_USDC);
430
- if (needsEth || needsUsdc) {
431
- console.log(` ${ui.yellow("Funding needed before minting.")}`);
432
- ui.table([
433
- ["Wallet", `${wallet_1.account.address.slice(0, 6)}...${wallet_1.account.address.slice(-4)}`],
434
- ["ETH", balanceChecksAvailable ? `${ethBalance.toFixed(6)} ETH${needsEth ? ` (need ≥${constants_1.MIN_ETH})` : ""}` : "unknown (RPC check failed)"],
435
- ["USDC", config_1.config.useX402 ? (balanceChecksAvailable ? `${usdcBalance.toFixed(2)} USDC${needsUsdc ? ` (need ≥${constants_1.MIN_USDC})` : ""}` : "unknown (RPC check failed)") : "not required"],
436
- ]);
437
- console.log("");
438
- if (!ui.isInteractiveSession()) {
439
- showHeadlessFundingHandoff(wallet_1.account.address, needsEth, needsUsdc);
440
- return;
441
- }
442
- const runFunding = await ui.confirm("Run funding flow now?");
443
- if (!runFunding) {
444
- ui.hint("Fund the wallet, then rerun `apow start`.");
445
- return;
446
- }
447
- await (0, fund_1.runFundFlow)({});
448
- const refreshedEth = Number((0, viem_1.formatEther)(await (0, wallet_1.getEthBalance)()));
449
- const refreshedUsdc = config_1.config.useX402 ? Number((0, viem_1.formatUnits)(await (0, uniswap_1.getUsdcBalance)(wallet_1.account.address), 6)) : usdcBalance;
450
- if (refreshedEth < constants_1.MIN_ETH || (config_1.config.useX402 && refreshedUsdc < constants_1.MIN_USDC)) {
451
- ui.warn("Funding is still incomplete.");
452
- ui.hint("Bridge or deposit may still be pending. Rerun `apow start` once balances update.");
453
- return;
454
- }
455
- }
456
- await (0, mint_1.runMintFlow)({ startMiningAfterMint: true });
590
+ (0, context_1.setSignerContext)("mint");
591
+ await (0, mint_1.runMintFlow)({
592
+ easyMode: options.easyMode === true,
593
+ startMiningAfterMint: true,
594
+ });
457
595
  }
458
596
  async function main() {
459
597
  const version = readVersion();
@@ -479,6 +617,9 @@ async function main() {
479
617
  .name("apow")
480
618
  .description("Mine AGENT tokens on Base L2 with Agentic Proof of Work")
481
619
  .version(version);
620
+ if (config_1.config.walletSource === "private-key") {
621
+ ui.warn("Legacy PRIVATE_KEY is loaded. Run `apow wallet migrate` to encrypt it into a keystore.");
622
+ }
482
623
  program
483
624
  .command("setup")
484
625
  .description("Agent-first setup wizard — choose Easy Mode (x402 for everything) or Advanced Mode")
@@ -487,18 +628,23 @@ async function main() {
487
628
  });
488
629
  program
489
630
  .command("start")
490
- .description("Agent-first happy path: setup -> fund -> mint -> mine")
491
- .action(async () => {
492
- await runStartFlow();
631
+ .description("Agent-first path: setup -> Base funding handoff -> mint -> mine")
632
+ .option("--easy", "Use the existing Easy Mode without the mode-selection prompt")
633
+ .action(async (opts) => {
634
+ await runStartFlow({ easyMode: opts.easy === true });
493
635
  });
494
636
  program
495
637
  .command("fund")
496
638
  .description("Fund your wallet — bridge from Solana/Ethereum or send on Base")
497
639
  .option("--chain <chain>", "Source chain: solana, ethereum, base")
498
640
  .option("--token <token>", "Source token: sol, usdc, eth")
499
- .option("--amount <eth>", "Target ETH amount (default: 0.005)")
641
+ .option("--amount <eth>", "Bridge ETH target (default: live funding requirement)")
500
642
  .option("--no-swap", "Skip auto-split after bridging")
501
643
  .action(async (opts) => {
644
+ (0, context_1.setSignerContext)("fund");
645
+ const unlocked = await unlockConfiguredKeystoreIfNeeded();
646
+ if (config_1.config.keystorePath && !unlocked && !wallet_1.account)
647
+ return;
502
648
  if (!config_1.config.privateKey || !wallet_1.account) {
503
649
  ui.warn("No wallet configured — launching setup first.");
504
650
  await setupWizard();
@@ -509,12 +655,17 @@ async function main() {
509
655
  return;
510
656
  }
511
657
  }
658
+ await checkWalletRecovery();
512
659
  await (0, fund_1.runFundFlow)(opts);
513
660
  });
514
661
  program
515
662
  .command("mint")
516
663
  .description("Mint a new miner NFT (Easy Mode: x402 LLM, no API key)")
517
664
  .action(async () => {
665
+ (0, context_1.setSignerContext)("mint");
666
+ const unlocked = await unlockConfiguredKeystoreIfNeeded();
667
+ if (config_1.config.keystorePath && !unlocked && !wallet_1.account)
668
+ return;
518
669
  if (!config_1.config.privateKey || !wallet_1.account) {
519
670
  ui.warn("No wallet configured — launching setup first.");
520
671
  await setupWizard();
@@ -525,6 +676,12 @@ async function main() {
525
676
  return;
526
677
  }
527
678
  }
679
+ await checkWalletRecovery();
680
+ const funding = await (0, base_funding_1.prepareBaseFunding)(true, true);
681
+ if (!funding.ready) {
682
+ showFundingHandoff(wallet_1.account.address, funding.depositEth, false);
683
+ return;
684
+ }
528
685
  await (0, preflight_1.runPreflight)("wallet");
529
686
  await (0, mint_1.runMintFlow)();
530
687
  });
@@ -533,6 +690,8 @@ async function main() {
533
690
  .description("Start the mining loop (Easy Mode: remote x402 GPU)")
534
691
  .argument("[tokenId]", "Miner token ID (auto-detects if omitted)")
535
692
  .action(async (tokenIdArg) => {
693
+ (0, context_1.setSignerContext)("mine");
694
+ await unlockConfiguredKeystoreIfNeeded();
536
695
  const hasWallet = !!config_1.config.privateKey && !!wallet_1.account;
537
696
  const hasRpc = config_1.config.useX402 || !!config_1.config.rpcUrl;
538
697
  if (!hasWallet || !hasRpc) {
@@ -610,90 +769,239 @@ async function main() {
610
769
  const { buildGrinders } = await Promise.resolve().then(() => __importStar(require("./build")));
611
770
  await buildGrinders(opts);
612
771
  });
772
+ const policyCmd = program
773
+ .command("policy")
774
+ .description("Show and configure local wallet signing policy");
775
+ policyCmd
776
+ .command("show")
777
+ .description("Print the current wallet policy")
778
+ .action(() => {
779
+ (0, context_1.setSignerContext)("policy");
780
+ console.log(JSON.stringify((0, policy_1.loadPolicy)(), null, 2));
781
+ });
782
+ policyCmd
783
+ .command("init")
784
+ .description("Write the default policy file")
785
+ .option("--force", "Overwrite existing policy.json")
786
+ .action((opts) => {
787
+ const path = (0, policy_1.writeDefaultPolicyFile)(opts.force === true);
788
+ ui.ok(`Policy file ready: ${path}`);
789
+ });
790
+ policyCmd
791
+ .command("set")
792
+ .description("Set policy values")
793
+ .command("mode <mode>")
794
+ .description("Set policy mode: enforce, warn, or off")
795
+ .action((mode) => {
796
+ if (mode !== "enforce" && mode !== "warn" && mode !== "off") {
797
+ ui.error("Mode must be enforce, warn, or off.");
798
+ return;
799
+ }
800
+ const policy = (0, policy_1.loadPolicy)();
801
+ policy.mode = mode;
802
+ const path = (0, policy_1.savePolicy)(policy);
803
+ ui.ok(`Policy mode set to ${mode} in ${path}`);
804
+ if (mode !== "enforce") {
805
+ ui.warn("Policy is not enforcing. Use only as a temporary recovery mode.");
806
+ }
807
+ });
613
808
  const walletCmd = program
614
809
  .command("wallet")
615
810
  .description("Wallet generation and management");
811
+ walletCmd.command("verify-recovery")
812
+ .description("Test a fresh-process unlock of the same wallet before funding")
813
+ .action(async () => {
814
+ if (!await unlockConfiguredKeystoreIfNeeded())
815
+ throw new Error("Unlock the existing wallet; do not replace it.");
816
+ await checkWalletRecovery();
817
+ });
616
818
  walletCmd
617
819
  .command("new")
618
- .description("Generate a new Base wallet (prints key and saves to file)")
820
+ .description("Generate a new encrypted Base wallet")
619
821
  .action(async () => {
822
+ const password = await getKeystorePassword(true);
823
+ if (!password) {
824
+ return;
825
+ }
620
826
  const { generatePrivateKey, privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
621
827
  const key = generatePrivateKey();
622
828
  const acct = privateKeyToAccount(key);
829
+ const artifacts = await saveWalletArtifacts(acct.address, key, {
830
+ requireKeystore: true,
831
+ });
832
+ (0, wallet_store_1.registerGeneratedWallet)(acct.address, artifacts.keystorePath);
623
833
  console.log("");
624
834
  console.log(` ${ui.bold("NEW WALLET GENERATED")}`);
625
835
  console.log("");
626
836
  console.log(` Address: ${acct.address}`);
627
- console.log(` Private Key: ${key}`);
837
+ if (artifacts.keystorePath) {
838
+ console.log(` Keystore: ${artifacts.keystorePath}`);
839
+ }
628
840
  console.log("");
629
- console.log(` ${ui.yellow("⚠ SAVE YOUR PRIVATE KEY — this is the only time")}`);
630
- console.log(` ${ui.yellow(" it will be displayed. Anyone with this key")}`);
631
- console.log(` ${ui.yellow(" controls your funds.")}`);
841
+ console.log(` ${ui.dim("Private key remains encrypted and is never printed.")}`);
842
+ console.log(` ${ui.dim("Back up the keystore and its password separately.")}`);
843
+ console.log(` ${ui.dim(`Activate it in this project with: apow wallet use ${acct.address}`)}`);
632
844
  console.log("");
633
- const artifacts = await saveWalletArtifacts(acct.address, key);
634
- if (artifacts.plaintextPath) {
635
- console.log(` ${ui.dim(`Import helper saved to: ${artifacts.plaintextPath}`)}`);
636
- console.log(` ${ui.yellow("This plaintext file is easy to import, but less secure than an encrypted keystore.")}`);
845
+ });
846
+ walletCmd
847
+ .command("list")
848
+ .description("List wallets generated locally by this APoW CLI")
849
+ .action(() => {
850
+ const wallets = (0, wallet_store_1.loadGeneratedWallets)();
851
+ if (wallets.length === 0) {
852
+ ui.error("No locally generated APoW wallets found.");
853
+ ui.hint("Create one with `apow wallet new` or the setup wizard.");
854
+ return;
637
855
  }
638
- if (artifacts.keystorePath) {
639
- console.log(` ${ui.dim(`Encrypted keystore saved to: ${artifacts.keystorePath}`)}`);
856
+ printGeneratedWallets(wallets);
857
+ });
858
+ walletCmd
859
+ .command("use")
860
+ .alias("select")
861
+ .description("Select a locally generated APoW wallet for this project")
862
+ .argument("[wallet]", "Wallet address or number from `apow wallet list`")
863
+ .action(async (walletArg) => {
864
+ const wallets = (0, wallet_store_1.loadGeneratedWallets)();
865
+ if (wallets.length === 0) {
866
+ ui.error("No locally generated APoW wallets found.");
867
+ ui.hint("Create one with `apow wallet new` or the setup wizard.");
868
+ return;
640
869
  }
641
- else {
642
- console.log(` ${ui.dim("Tip: set KEYSTORE_PASSWORD or rerun wallet export to create an encrypted JSON keystore backup.")}`);
870
+ let selection = walletArg?.trim() ?? "";
871
+ if (!selection) {
872
+ if (!ui.isInteractiveSession()) {
873
+ ui.error("Specify a wallet address or number from `apow wallet list`.");
874
+ return;
875
+ }
876
+ printGeneratedWallets(wallets);
877
+ const activeIndex = wallets.findIndex(isActiveGeneratedWallet);
878
+ selection = await ui.prompt("Wallet number or address", String(activeIndex >= 0 ? activeIndex + 1 : 1));
643
879
  }
644
- console.log("");
645
- console.log(` ${ui.dim("Import into Phantom, MetaMask, or any EVM wallet")}`);
646
- console.log(` ${ui.dim("to view your AGENT tokens and Mining Rig NFT.")}`);
647
- console.log("");
880
+ const selected = resolveGeneratedWalletSelection(wallets, selection);
881
+ if (!selected) {
882
+ ui.error("Wallet not found. Use an address or list number from `apow wallet list`.");
883
+ return;
884
+ }
885
+ if (isActiveGeneratedWallet(selected)) {
886
+ ui.ok(`Wallet already active: ${selected.address}`);
887
+ return;
888
+ }
889
+ const password = await unlockGeneratedWallet(selected);
890
+ if (!password) {
891
+ return;
892
+ }
893
+ (0, session_1.setSessionPassword)(password);
894
+ await (0, config_1.writeEnvFile)({ PRIVATE_KEY: "", KEYSTORE_PATH: selected.keystorePath });
895
+ (0, wallet_1.reinitClients)();
896
+ ui.ok(`Active wallet: ${selected.address}`);
897
+ ui.hint(`Project config updated: ${(0, node_path_1.join)(process.cwd(), ".env")}`);
648
898
  });
649
899
  walletCmd
650
900
  .command("show")
651
- .description("Show wallet address from current .env PRIVATE_KEY")
901
+ .description("Show configured wallet address")
652
902
  .action(async () => {
903
+ await unlockConfiguredKeystoreIfNeeded();
653
904
  if (!wallet_1.account) {
654
- ui.error("No wallet configured. Run `apow setup` and choose Easy Mode, or set PRIVATE_KEY in .env.");
905
+ ui.error("No wallet configured. Run `apow setup` and choose Easy Mode, or configure KEYSTORE_PATH.");
655
906
  return;
656
907
  }
657
908
  console.log("");
658
909
  console.log(` Address: ${wallet_1.account.address}`);
910
+ if (config_1.config.walletSource === "keystore" && config_1.config.keystorePath) {
911
+ console.log(` Source: encrypted keystore (${config_1.config.keystorePath})`);
912
+ }
913
+ else if (config_1.config.walletSource === "private-key") {
914
+ console.log(" Source: legacy PRIVATE_KEY");
915
+ }
659
916
  console.log("");
660
917
  });
661
918
  walletCmd
662
- .command("export")
663
- .description("Export wallet private key (with confirmation)")
919
+ .command("backup")
920
+ .description("Show the encrypted wallet backup location (never displays private keys)")
664
921
  .action(async () => {
665
- if (!wallet_1.account || !config_1.config.privateKey) {
666
- ui.error("No wallet configured. Run `apow setup` and choose Easy Mode, or set PRIVATE_KEY in .env.");
922
+ await unlockConfiguredKeystoreIfNeeded();
923
+ if (!wallet_1.account) {
924
+ ui.error("No wallet configured. Run `apow setup` and choose Easy Mode, or configure KEYSTORE_PATH.");
667
925
  return;
668
926
  }
669
- const proceed = await ui.confirm("This will display your private key. Continue?");
670
- if (!proceed) {
671
- console.log(" Cancelled.");
927
+ if (config_1.config.walletSource !== "keystore" || !config_1.config.keystorePath) {
928
+ ui.error("This wallet is using the legacy environment-key path.");
929
+ ui.hint("Run `apow wallet migrate` to create an encrypted keystore backup.");
672
930
  return;
673
931
  }
674
932
  console.log("");
675
- console.log(` Address: ${wallet_1.account.address}`);
676
- console.log(` Private Key: ${config_1.config.privateKey}`);
933
+ console.log(` Address: ${wallet_1.account.address}`);
934
+ console.log(` Keystore: ${config_1.config.keystorePath}`);
935
+ console.log(` ${ui.dim("Back up this encrypted file and its password separately.")}`);
936
+ console.log(` ${ui.dim("APoW never prints or writes a plaintext private-key export.")}`);
677
937
  console.log("");
678
- const savePlaintext = await ui.confirm("Save plaintext import helper?");
679
- const artifacts = await saveWalletArtifacts(wallet_1.account.address, config_1.config.privateKey, {
680
- createPlaintextImportFile: savePlaintext,
681
- promptForKeystoreBackup: true,
682
- });
683
- if (artifacts.plaintextPath) {
684
- console.log(` ${ui.dim(`Saved import helper: ${artifacts.plaintextPath}`)}`);
938
+ });
939
+ walletCmd
940
+ .command("migrate")
941
+ .description("Encrypt legacy PRIVATE_KEY into a keystore and clear .env PRIVATE_KEY")
942
+ .action(async () => {
943
+ if (config_1.config.walletSource !== "private-key" || !config_1.config.privateKey || !wallet_1.account) {
944
+ ui.error("No legacy PRIVATE_KEY wallet is loaded.");
945
+ return;
685
946
  }
686
- if (artifacts.keystorePath) {
687
- console.log(` ${ui.dim(`Saved encrypted keystore: ${artifacts.keystorePath}`)}`);
947
+ const password = await getKeystorePassword(true);
948
+ if (!password)
949
+ return;
950
+ const keystorePath = await saveKeystoreWithPassword(wallet_1.account.address, config_1.config.privateKey, password);
951
+ await (0, config_1.writeEnvFile)({ PRIVATE_KEY: "", KEYSTORE_PATH: keystorePath });
952
+ (0, config_1.reloadConfig)();
953
+ (0, wallet_1.reinitClients)();
954
+ ui.ok(`Encrypted keystore saved to ${keystorePath}`);
955
+ ui.hint("Unset PRIVATE_KEY in your shell or process manager if it is exported outside .env.");
956
+ });
957
+ const payoutCmd = walletCmd
958
+ .command("payout")
959
+ .description("Configure the cold payout address for mined AGENT sweeps");
960
+ payoutCmd
961
+ .command("set <address>")
962
+ .description("Set payout address")
963
+ .action(async (address) => {
964
+ await unlockConfiguredKeystoreIfNeeded();
965
+ if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
966
+ ui.error("Invalid payout address.");
967
+ return;
688
968
  }
969
+ const payout = (0, viem_1.getAddress)(address);
970
+ if (wallet_1.account && payout.toLowerCase() === wallet_1.account.address.toLowerCase()) {
971
+ ui.error("Payout address must differ from the mining wallet.");
972
+ return;
973
+ }
974
+ const policy = (0, policy_1.loadPolicy)();
975
+ policy.payout = payout;
976
+ const path = (0, policy_1.savePolicy)(policy);
977
+ ui.ok(`Payout set to ${payout.slice(0, 6)}...${payout.slice(-4)} in ${path}`);
978
+ });
979
+ payoutCmd
980
+ .command("show")
981
+ .description("Show configured payout address")
982
+ .action(() => {
983
+ const payout = (0, policy_1.getPayoutAddress)();
984
+ console.log("");
985
+ console.log(` Payout: ${payout ?? "(not configured)"}`);
689
986
  console.log("");
690
987
  });
988
+ walletCmd
989
+ .command("sweep")
990
+ .description("Sweep mined AGENT to the configured payout address")
991
+ .option("--all", "Also sweep excess ETH and USDC working balances")
992
+ .action(async (opts) => {
993
+ (0, context_1.setSignerContext)("sweep");
994
+ await unlockConfiguredKeystoreIfNeeded();
995
+ await (0, sweep_1.runSweep)({ all: opts.all === true });
996
+ });
691
997
  walletCmd
692
998
  .command("fund")
693
999
  .description("Send ETH from your wallet to another address")
694
1000
  .argument("<address>", "Destination address (0x-prefixed)")
695
1001
  .argument("[amount]", "ETH amount to send (default: mint price + 0.003 ETH gas buffer)")
696
1002
  .action(async (address, amountArg) => {
1003
+ (0, context_1.setSignerContext)("wallet-fund");
1004
+ await unlockConfiguredKeystoreIfNeeded();
697
1005
  if (!config_1.config.privateKey || !wallet_1.account) {
698
1006
  ui.warn("No wallet configured — launching setup first.");
699
1007
  await setupWizard();
@@ -777,28 +1085,30 @@ async function main() {
777
1085
  .command("start", { isDefault: true })
778
1086
  .description("Launch the dashboard web UI")
779
1087
  .action(async () => {
780
- const walletsPath = getWalletsPath();
781
- // Seed wallets.json if it doesn't exist
782
- if (!(0, node_fs_1.existsSync)(walletsPath)) {
783
- const walletsDir = (0, node_path_1.join)(process.env.HOME ?? "", ".apow");
784
- if (!(0, node_fs_1.existsSync)(walletsDir))
785
- (0, node_fs_1.mkdirSync)(walletsDir, { recursive: true });
786
- const initial = wallet_1.account ? [wallet_1.account.address] : [];
787
- (0, node_fs_1.writeFileSync)(walletsPath, JSON.stringify(initial, null, 2), "utf8");
788
- if (wallet_1.account) {
789
- ui.ok(`Seeded ${walletsPath} with ${wallet_1.account.address.slice(0, 6)}...${wallet_1.account.address.slice(-4)}`);
790
- }
791
- else {
792
- ui.ok(`Created ${walletsPath} (empty — add wallets with: apow dashboard add <address>)`);
1088
+ (0, context_1.setSignerContext)("dashboard");
1089
+ if (config_1.config.useX402) {
1090
+ await unlockConfiguredKeystoreIfNeeded();
1091
+ const policy = (0, policy_1.loadPolicy)();
1092
+ if (policy.mode !== "enforce") {
1093
+ ui.error("Paid dashboard reads require the wallet signing policy in enforce mode.");
1094
+ ui.hint("Run `apow policy set mode enforce`, then retry.");
1095
+ return;
793
1096
  }
794
1097
  }
795
- // Auto-detect wallets from CWD
796
- const { addresses, newCount } = detectWallets(process.cwd());
797
- if (newCount > 0) {
798
- ui.ok(`Detected ${addresses.length} wallets (${newCount} new)`);
1098
+ const generatedWallets = (0, wallet_store_1.loadGeneratedWalletAddresses)();
1099
+ const configuredAccount = wallet_1.account;
1100
+ const signerIsGenerated = !!configuredAccount && generatedWallets.some((address) => address.toLowerCase() === configuredAccount.address.toLowerCase());
1101
+ if (config_1.config.useX402 && !signerIsGenerated) {
1102
+ ui.error("Dashboard x402 requires a configured wallet generated locally by this APoW CLI.");
1103
+ ui.hint("Run `apow wallet new`, configure its KEYSTORE_PATH, then retry.");
1104
+ return;
1105
+ }
1106
+ if (generatedWallets.length === 0) {
1107
+ ui.warn("No locally generated APoW wallets are registered. The dashboard will be empty.");
1108
+ ui.hint("Run `apow wallet new` to create and register one.");
799
1109
  }
800
- else if (addresses.length > 0) {
801
- console.log(` ${ui.dim(`${addresses.length} wallets loaded`)}`);
1110
+ else {
1111
+ console.log(` ${ui.dim(`${generatedWallets.length} locally generated wallets loaded`)}`);
802
1112
  }
803
1113
  const { startDashboardServer } = await Promise.resolve().then(() => __importStar(require("./dashboard")));
804
1114
  console.log("");
@@ -807,17 +1117,16 @@ async function main() {
807
1117
  console.log("");
808
1118
  const server = startDashboardServer({
809
1119
  port: 3847,
810
- walletsPath,
811
1120
  rpcUrl: config_1.config.rpcUrl,
812
1121
  useX402: config_1.config.useX402,
813
- privateKey: config_1.config.privateKey,
1122
+ signer: signerIsGenerated ? configuredAccount ?? undefined : undefined,
814
1123
  miningAgentAddress: config_1.config.miningAgentAddress,
815
1124
  agentCoinAddress: config_1.config.agentCoinAddress,
816
1125
  });
817
1126
  // Open browser after short delay (server starts instantly)
818
1127
  setTimeout(() => {
819
1128
  const openCmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
820
- (0, node_child_process_1.spawn)(openCmd, ["http://localhost:3847"], { stdio: "ignore" });
1129
+ (0, node_child_process_1.spawn)(openCmd, ["http://localhost:3847"], { stdio: "ignore", env: (0, secure_env_1.childEnv)() });
821
1130
  }, 500);
822
1131
  // Wait for SIGINT
823
1132
  await new Promise((resolve) => {
@@ -827,72 +1136,17 @@ async function main() {
827
1136
  });
828
1137
  });
829
1138
  });
830
- dashboardCmd
831
- .command("add <address>")
832
- .description("Add a wallet address to monitor")
833
- .action((address) => {
834
- if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
835
- ui.error("Invalid address. Must be 0x + 40 hex characters.");
836
- return;
837
- }
838
- const walletsPath = getWalletsPath();
839
- const wallets = loadWallets(walletsPath);
840
- const lower = address.toLowerCase();
841
- if (wallets.some((w) => w.toLowerCase() === lower)) {
842
- ui.warn("Address already monitored.");
843
- return;
844
- }
845
- wallets.push(address);
846
- saveWallets(walletsPath, wallets);
847
- ui.ok(`Added ${address.slice(0, 6)}...${address.slice(-4)} (${wallets.length} wallets total)`);
848
- });
849
- dashboardCmd
850
- .command("remove <address>")
851
- .description("Remove a wallet address from monitoring")
852
- .action((address) => {
853
- const walletsPath = getWalletsPath();
854
- const wallets = loadWallets(walletsPath);
855
- const lower = address.toLowerCase();
856
- const filtered = wallets.filter((w) => w.toLowerCase() !== lower);
857
- if (filtered.length === wallets.length) {
858
- ui.warn("Address not found in wallet list.");
859
- return;
860
- }
861
- saveWallets(walletsPath, filtered);
862
- ui.ok(`Removed ${address.slice(0, 6)}...${address.slice(-4)} (${filtered.length} wallets remaining)`);
863
- });
864
- dashboardCmd
865
- .command("scan [dir]")
866
- .description("Auto-detect wallets from wallet-0x*.txt or wallet-0x*.json files in a directory")
867
- .action((dir) => {
868
- const scanDir = dir ?? process.cwd();
869
- const { addresses, newCount } = detectWallets(scanDir);
870
- console.log("");
871
- if (addresses.length === 0) {
872
- console.log(` No wallets found in ${scanDir}`);
873
- console.log(` ${ui.dim("Expected files named wallet-0x<address>.txt or wallet-0x<address>.json")}`);
874
- }
875
- else {
876
- console.log(` ${ui.bold("Detected Wallets")} (${newCount} new, ${addresses.length} total)`);
877
- console.log("");
878
- for (const addr of addresses) {
879
- console.log(` ${addr}`);
880
- }
881
- }
882
- console.log("");
883
- });
884
1139
  dashboardCmd
885
1140
  .command("wallets")
886
- .description("List monitored wallet addresses")
1141
+ .description("List locally generated APoW wallet addresses")
887
1142
  .action(() => {
888
- const walletsPath = getWalletsPath();
889
- const wallets = loadWallets(walletsPath);
1143
+ const wallets = (0, wallet_store_1.loadGeneratedWalletAddresses)();
890
1144
  if (wallets.length === 0) {
891
- console.log(" No wallets configured. Run: apow dashboard add <address>");
1145
+ console.log(" No locally generated APoW wallets. Run: apow wallet new");
892
1146
  return;
893
1147
  }
894
1148
  console.log("");
895
- console.log(` ${ui.bold("Monitored Wallets")} (${wallets.length})`);
1149
+ console.log(` ${ui.bold("Locally Generated Wallets")} (${wallets.length})`);
896
1150
  console.log("");
897
1151
  for (const w of wallets) {
898
1152
  console.log(` ${w}`);
@@ -901,70 +1155,7 @@ async function main() {
901
1155
  });
902
1156
  await program.parseAsync(process.argv);
903
1157
  }
904
- function getWalletsPath() {
905
- return (0, node_path_1.join)(process.env.HOME ?? "", ".apow", "wallets.json");
906
- }
907
- function loadWallets(path) {
908
- try {
909
- const raw = (0, node_fs_1.readFileSync)(path, "utf8");
910
- const data = JSON.parse(raw);
911
- return Array.isArray(data) ? data.filter((a) => typeof a === "string") : [];
912
- }
913
- catch {
914
- return [];
915
- }
916
- }
917
- function saveWallets(path, wallets) {
918
- const dir = (0, node_path_1.join)(process.env.HOME ?? "", ".apow");
919
- if (!(0, node_fs_1.existsSync)(dir))
920
- (0, node_fs_1.mkdirSync)(dir, { recursive: true });
921
- (0, node_fs_1.writeFileSync)(path, JSON.stringify(wallets, null, 2), "utf8");
922
- }
923
- function detectWallets(scanDir) {
924
- const walletsPath = getWalletsPath();
925
- const existing = loadWallets(walletsPath);
926
- const seen = new Set(existing.map((a) => a.toLowerCase()));
927
- const detected = [];
928
- // Scan scanDir for wallet-0x*.txt / .json files
929
- try {
930
- const entries = (0, node_fs_1.readdirSync)(scanDir, { withFileTypes: true });
931
- for (const entry of entries) {
932
- if (entry.isFile()) {
933
- const address = (0, wallet_store_1.detectWalletAddressFromFilename)(entry.name);
934
- if (address && !seen.has(address.toLowerCase())) {
935
- detected.push(address);
936
- seen.add(address.toLowerCase());
937
- }
938
- }
939
- // Scan rig*/wallet-0x* subdirectories
940
- if (entry.isDirectory() && entry.name.startsWith("rig")) {
941
- try {
942
- const rigFiles = (0, node_fs_1.readdirSync)((0, node_path_1.join)(scanDir, entry.name));
943
- for (const file of rigFiles) {
944
- const address = (0, wallet_store_1.detectWalletAddressFromFilename)(file);
945
- if (address && !seen.has(address.toLowerCase())) {
946
- detected.push(address);
947
- seen.add(address.toLowerCase());
948
- }
949
- }
950
- }
951
- catch {
952
- // rig dir not readable — skip
953
- }
954
- }
955
- }
956
- }
957
- catch {
958
- // scanDir not readable
959
- }
960
- const merged = [...existing, ...detected];
961
- if (detected.length > 0) {
962
- saveWallets(walletsPath, merged);
963
- }
964
- return { addresses: merged, newCount: detected.length };
965
- }
966
1158
  main().catch((error) => {
967
- const message = error instanceof Error ? error.message : String(error);
968
- ui.error(message);
1159
+ ui.error((0, errors_1.errorText)(error));
969
1160
  process.exitCode = 1;
970
1161
  });