apow-cli 0.11.5 → 0.11.7

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/README.md CHANGED
@@ -28,7 +28,7 @@ npx apow-cli
28
28
  > **v0.8.0+: Bring your own RPC or use auto-pay.** You need a Base RPC endpoint. Two options:
29
29
  >
30
30
  > 1. **Bring your own** (free): Get a free RPC URL from [Alchemy](https://www.alchemy.com/), [QuickNode](https://www.quicknode.com/), or any Base RPC provider. Set `RPC_URL` in your `.env`.
31
- > 2. **QuickNode x402** (paid, zero setup): Set `USE_X402=true` in your `.env`. Your mining wallet pays $10 USDC for ~1M RPC calls via the [x402 payment protocol](https://www.x402.org/). No API key, no account needed.
31
+ > 2. **QuickNode x402** (paid, zero setup): Set `USE_X402=true` in your `.env`. Your mining wallet pays for RPC usage via the [x402 payment protocol](https://www.x402.org/). Start with at least 2.00 USDC on Base and add more for headroom. No API key or account needed.
32
32
  >
33
33
  > Run `apow setup` to configure interactively.
34
34
 
@@ -71,28 +71,28 @@ Each wallet gets one rig, each rig mines independently. More wallets = more chan
71
71
  If you prefer to do it yourself:
72
72
 
73
73
  ```bash
74
- npx apow-cli start # guided happy path: setup -> fund -> mint -> mine
74
+ npx apow-cli start # guided happy path: setup -> funding checks -> mint -> mine
75
75
  ```
76
76
 
77
- If you want to control each step manually, the older `setup -> fund -> mint -> mine` flow is still supported below.
77
+ If you want to control each step manually, the older step-by-step flow is still supported below.
78
78
 
79
79
  ## Commands
80
80
 
81
81
  | Command | Description |
82
82
  |---------|-------------|
83
- | `apow start` | Guided happy path: setup -> fund -> mint -> mine |
83
+ | `apow start` | Guided happy path: setup -> funding checks -> mint -> mine |
84
84
  | `apow setup` | Agent-first setup wizard: Easy Mode (x402 everywhere) or Advanced Mode |
85
85
  | `apow fund` | Fund your wallet: bridge from Solana/Ethereum or send on Base, auto-split ETH+USDC |
86
- | `apow wallet new` | Generate a new mining wallet |
86
+ | `apow wallet new` | Generate a new mining wallet, plus optional encrypted JSON keystore backup |
87
87
  | `apow wallet show` | Show configured wallet address |
88
- | `apow wallet export` | Export your wallet's private key |
88
+ | `apow wallet export` | Export your wallet's private key and optional backups |
89
89
  | `apow wallet fund <addr> [eth]` | Send ETH to another address (default: mint price + gas) |
90
90
  | `apow mint` | Mint a MiningAgent NFT (one per wallet) |
91
91
  | `apow mine [tokenId]` | Mine $AGENT with your NFT (auto-detects best rig) |
92
92
  | `apow stats [tokenId]` | View mining stats, earnings, difficulty |
93
93
  | `apow dashboard start` | Launch multi-wallet mining dashboard |
94
94
  | `apow dashboard add <addr>` | Add a wallet to the dashboard |
95
- | `apow dashboard scan [dir]` | Auto-detect wallet files in a directory |
95
+ | `apow dashboard scan [dir]` | Auto-detect `wallet-0x*.txt` and `wallet-0x*.json` files in a directory |
96
96
 
97
97
  ## Configuration
98
98
 
@@ -107,6 +107,7 @@ ALLOW_LOCAL_FALLBACK_WITH_X402=false # Easy Mode default: do not burn local CPU
107
107
  # LLM_PROVIDER=clawrouter # clawrouter (auto with x402) | openai | gemini | deepseek | qwen | anthropic | ollama (for minting)
108
108
  # LLM_MODEL=blockrun/eco # Auto-detected per provider; override only if needed
109
109
  # LLM_API_KEY=sk-... # Not needed with clawrouter/ollama; required for openai/gemini/etc.
110
+ # KEYSTORE_PASSWORD=... # Optional: create encrypted wallet JSON backups during wallet new/export
110
111
  # Bridging (only for `apow fund`)
111
112
  # SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
112
113
  # ETHEREUM_RPC_URL=https://cloudflare-eth.com
@@ -219,7 +220,7 @@ Monitor your entire mining fleet from a single web UI. Zero external dependencie
219
220
 
220
221
  ```bash
221
222
  # Quick start: scan wallet files and launch
222
- apow dashboard scan . # detect wallet-0x*.txt files in current directory
223
+ apow dashboard scan . # detect wallet-0x*.txt / .json files in current directory
223
224
  apow dashboard start # open dashboard at http://localhost:3847
224
225
  ```
225
226
 
@@ -230,7 +231,7 @@ apow dashboard start # open dashboard at http://localhost:3847
230
231
  | `apow dashboard start` | Launch dashboard web UI (default port 3847) |
231
232
  | `apow dashboard add <addr>` | Add a wallet address to monitor |
232
233
  | `apow dashboard remove <addr>` | Remove a wallet from monitoring |
233
- | `apow dashboard scan [dir]` | Auto-detect wallets from `wallet-0x*.txt` files |
234
+ | `apow dashboard scan [dir]` | Auto-detect wallets from `wallet-0x*.txt` and `wallet-0x*.json` files |
234
235
  | `apow dashboard wallets` | List all monitored wallets |
235
236
 
236
237
  ### Fleet Configuration
@@ -245,7 +246,7 @@ Wallets are stored in `~/.apow/wallets.json` (plain JSON array of addresses). Fo
245
246
  ]
246
247
  ```
247
248
 
248
- Fleet types: `array` (JSON array of addresses), `solkek` (master/miners JSON), `rigdirs` (scan `rig*/wallet-0x*.txt`), `walletfiles` (scan `wallet-0x*.txt`).
249
+ Fleet types: `array` (JSON array of addresses), `solkek` (master/miners JSON), `rigdirs` (scan `rig*/wallet-0x*.txt` / `.json`), `walletfiles` (scan `wallet-0x*.txt` / `.json`).
249
250
 
250
251
  ## Protocol
251
252
 
package/dist/config.js CHANGED
@@ -11,6 +11,7 @@ exports.requireLlmApiKey = requireLlmApiKey;
11
11
  exports.isExpensiveModel = isExpensiveModel;
12
12
  exports.writeEnvFile = writeEnvFile;
13
13
  const dotenv_1 = require("dotenv");
14
+ const node_fs_1 = require("node:fs");
14
15
  const promises_1 = require("node:fs/promises");
15
16
  const node_os_1 = __importDefault(require("node:os"));
16
17
  const node_path_1 = require("node:path");
@@ -157,10 +158,32 @@ function isExpensiveModel(model) {
157
158
  return EXPENSIVE_MODELS.some((e) => m.startsWith(e));
158
159
  }
159
160
  async function writeEnvFile(values) {
160
- const lines = Object.entries(values)
161
- .map(([key, value]) => `${key}=${value}`)
162
- .join("\n");
163
- await (0, promises_1.writeFile)((0, node_path_1.join)(process.cwd(), ".env"), lines + "\n", "utf8");
161
+ const envPath = (0, node_path_1.join)(process.cwd(), ".env");
162
+ const preserved = [];
163
+ if ((0, node_fs_1.existsSync)(envPath)) {
164
+ const existingContent = await (0, promises_1.readFile)(envPath, "utf8").catch(() => "");
165
+ const seenKeys = new Set(Object.keys(values));
166
+ for (const line of existingContent.split(/\r?\n/)) {
167
+ const trimmed = line.trim();
168
+ if (!trimmed || trimmed.startsWith("#")) {
169
+ continue;
170
+ }
171
+ const eq = line.indexOf("=");
172
+ if (eq === -1) {
173
+ preserved.push(line);
174
+ continue;
175
+ }
176
+ const key = line.slice(0, eq).trim();
177
+ if (!seenKeys.has(key)) {
178
+ preserved.push(line);
179
+ }
180
+ }
181
+ }
182
+ const lines = [
183
+ ...preserved,
184
+ ...Object.entries(values).map(([key, value]) => `${key}=${value}`),
185
+ ].join("\n");
186
+ await (0, promises_1.writeFile)(envPath, lines + "\n", "utf8");
164
187
  for (const [key, value] of Object.entries(values)) {
165
188
  process.env[key] = value;
166
189
  }
package/dist/dashboard.js CHANGED
@@ -44,6 +44,7 @@ const viem_1 = require("viem");
44
44
  const chains_1 = require("viem/chains");
45
45
  const dashboard_html_1 = require("./dashboard-html");
46
46
  const x402_1 = require("./x402");
47
+ const wallet_store_1 = require("./wallet-store");
47
48
  const AgentCoin_json_1 = __importDefault(require("./abi/AgentCoin.json"));
48
49
  const MiningAgent_json_1 = __importDefault(require("./abi/MiningAgent.json"));
49
50
  const AgentCoinAbi = AgentCoin_json_1.default;
@@ -87,9 +88,9 @@ function extractRigdirs(dir) {
87
88
  continue;
88
89
  const rigFiles = (0, node_fs_1.readdirSync)((0, node_path_1.join)(dir, entry.name));
89
90
  for (const file of rigFiles) {
90
- const match = file.match(/^wallet-(0x[0-9a-fA-F]{40})\.txt$/);
91
- if (match && isAddress(match[1])) {
92
- addrs.push(match[1]);
91
+ const address = (0, wallet_store_1.detectWalletAddressFromFilename)(file);
92
+ if (address && isAddress(address)) {
93
+ addrs.push(address);
93
94
  }
94
95
  }
95
96
  }
@@ -99,9 +100,9 @@ function extractWalletfiles(dir) {
99
100
  const addrs = [];
100
101
  const files = (0, node_fs_1.readdirSync)(dir);
101
102
  for (const file of files) {
102
- const match = file.match(/^wallet-(0x[0-9a-fA-F]{40})\.txt$/);
103
- if (match && isAddress(match[1])) {
104
- addrs.push(match[1]);
103
+ const address = (0, wallet_store_1.detectWalletAddressFromFilename)(file);
104
+ if (address && isAddress(address)) {
105
+ addrs.push(address);
105
106
  }
106
107
  }
107
108
  return addrs;
package/dist/detect.js CHANGED
@@ -23,14 +23,14 @@ async function detectMinersWithClient(client, owner) {
23
23
  if (balance === 0n) {
24
24
  return [];
25
25
  }
26
- const miners = [];
27
- for (let i = 0n; i < balance; i++) {
28
- const tokenId = (await client.readContract({
29
- address: config_1.config.miningAgentAddress,
30
- abi: miningAgentAbi,
31
- functionName: "tokenOfOwnerByIndex",
32
- args: [owner, i],
33
- }));
26
+ const indexes = Array.from({ length: Number(balance) }, (_, i) => BigInt(i));
27
+ const tokenIds = await Promise.all(indexes.map((index) => client.readContract({
28
+ address: config_1.config.miningAgentAddress,
29
+ abi: miningAgentAbi,
30
+ functionName: "tokenOfOwnerByIndex",
31
+ args: [owner, index],
32
+ })));
33
+ const miners = await Promise.all(tokenIds.map(async (tokenId) => {
34
34
  const [rarityRaw, hashpowerRaw] = await Promise.all([
35
35
  client.readContract({
36
36
  address: config_1.config.miningAgentAddress,
@@ -46,13 +46,13 @@ async function detectMinersWithClient(client, owner) {
46
46
  }),
47
47
  ]);
48
48
  const rarity = Number(rarityRaw);
49
- miners.push({
49
+ return {
50
50
  tokenId,
51
51
  rarity,
52
52
  rarityLabel: exports.rarityLabels[rarity] ?? `Tier ${rarity}`,
53
53
  hashpower: Number(hashpowerRaw),
54
- });
55
- }
54
+ };
55
+ }));
56
56
  return miners;
57
57
  }
58
58
  async function detectMiners(owner) {
package/dist/errors.js CHANGED
@@ -110,11 +110,11 @@ const patterns = [
110
110
  }),
111
111
  },
112
112
  {
113
- test: (m) => m.toLowerCase().includes("insufficient funds"),
113
+ test: (m) => m.includes("Not enough ETH for gas") || m.toLowerCase().includes("insufficient funds"),
114
114
  classify: () => ({
115
115
  category: "setup",
116
116
  userMessage: "Not enough ETH for gas",
117
- recovery: "Send ETH to your wallet on Base",
117
+ recovery: "Send ETH to your wallet on Base, or run `apow fund` to top up gas before mining again",
118
118
  }),
119
119
  },
120
120
  {
package/dist/fund.js CHANGED
@@ -509,6 +509,9 @@ async function runFundFlow(options) {
509
509
  console.log(` ${ui.green("Already funded! Ready to mint.")}`);
510
510
  console.log(` Next: ${ui.cyan("apow mint")}`);
511
511
  console.log("");
512
+ if (!ui.isInteractiveSession()) {
513
+ return;
514
+ }
512
515
  // Allow explicit re-run if user wants to add more
513
516
  const addMore = await ui.confirm("Add more funds?");
514
517
  if (!addMore)
package/dist/index.js CHANGED
@@ -55,6 +55,7 @@ const preflight_1 = require("./preflight");
55
55
  const stats_1 = require("./stats");
56
56
  const update_1 = require("./update");
57
57
  const ui = __importStar(require("./ui"));
58
+ const wallet_store_1 = require("./wallet-store");
58
59
  const wallet_1 = require("./wallet");
59
60
  const miningAgentAbi = MiningAgent_json_1.default;
60
61
  const erc20BalanceAbi = [
@@ -66,22 +67,7 @@ const erc20BalanceAbi = [
66
67
  stateMutability: "view",
67
68
  },
68
69
  ];
69
- function saveKeyFile(address, privateKey) {
70
- const filename = `wallet-${address}.txt`;
71
- const filepath = (0, node_path_1.join)(process.cwd(), filename);
72
- const content = [
73
- `Address: ${address}`,
74
- `Private Key: ${privateKey}`,
75
- ``,
76
- `Generated: ${new Date().toISOString()}`,
77
- ``,
78
- `Import this key into MetaMask, Phantom, or any EVM wallet.`,
79
- `Keep this file safe — anyone with the private key controls your funds.`,
80
- "",
81
- ].join("\n");
82
- (0, node_fs_1.writeFileSync)(filepath, content, { encoding: "utf8", mode: 0o600 });
83
- return filepath;
84
- }
70
+ const TRANSFER_GAS_RESERVE_ETH = (0, viem_1.parseEther)("0.00005");
85
71
  function parseTokenId(value) {
86
72
  try {
87
73
  return BigInt(value);
@@ -99,6 +85,55 @@ function readVersion() {
99
85
  return "0.1.0";
100
86
  }
101
87
  }
88
+ function ensureGitignoreSafetyEntries() {
89
+ const gitignorePath = (0, node_path_1.join)(process.cwd(), ".gitignore");
90
+ const wanted = [".env", "wallet-*.txt"];
91
+ const existing = (0, node_fs_1.existsSync)(gitignorePath) ? (0, node_fs_1.readFileSync)(gitignorePath, "utf8") : "";
92
+ const missing = wanted.filter((entry) => !existing.split(/\r?\n/).includes(entry));
93
+ if (missing.length === 0) {
94
+ return;
95
+ }
96
+ const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
97
+ const content = `${existing}${prefix}${missing.join("\n")}\n`;
98
+ (0, node_fs_1.writeFileSync)(gitignorePath, content, "utf8");
99
+ ui.ok(`Updated .gitignore: added ${missing.join(", ")}`);
100
+ }
101
+ async function maybeCreateEncryptedKeystoreBackup(address, privateKey) {
102
+ const envPassword = process.env.KEYSTORE_PASSWORD?.trim();
103
+ let password = envPassword ?? "";
104
+ if (!password && ui.isInteractiveSession()) {
105
+ const createBackup = await ui.confirm("Create encrypted JSON keystore backup? (recommended)");
106
+ if (!createBackup) {
107
+ return null;
108
+ }
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;
114
+ }
115
+ if (entered !== confirm) {
116
+ ui.warn("Keystore passwords did not match — skipping encrypted backup.");
117
+ return null;
118
+ }
119
+ password = entered;
120
+ }
121
+ if (!password) {
122
+ return null;
123
+ }
124
+ return (0, wallet_store_1.saveEncryptedKeystoreFile)(address, privateKey, password);
125
+ }
126
+ async function saveWalletArtifacts(address, privateKey, opts = {}) {
127
+ const result = {};
128
+ if (opts.createPlaintextImportFile !== false) {
129
+ result.plaintextPath = (0, wallet_store_1.savePlaintextImportFile)(address, privateKey);
130
+ }
131
+ const keystorePath = await maybeCreateEncryptedKeystoreBackup(address, privateKey);
132
+ if (keystorePath) {
133
+ result.keystorePath = keystorePath;
134
+ }
135
+ return result;
136
+ }
102
137
  function shouldSkipUpdateCheck(argv) {
103
138
  return argv.includes("--help")
104
139
  || argv.includes("-h")
@@ -106,34 +141,6 @@ function shouldSkipUpdateCheck(argv) {
106
141
  || argv.includes("-V")
107
142
  || argv[0] === "help";
108
143
  }
109
- async function resolveTokenId(tokenIdArg) {
110
- if (tokenIdArg) {
111
- return parseTokenId(tokenIdArg);
112
- }
113
- if (!wallet_1.account) {
114
- ui.error("No token ID provided and no wallet configured.");
115
- ui.hint("Usage: apow mine <tokenId>, or run `apow start` for the guided happy path");
116
- process.exit(1);
117
- }
118
- const miners = await (0, detect_1.detectMiners)(wallet_1.account.address);
119
- if (miners.length === 0) {
120
- ui.error("No mining rigs found for this wallet.");
121
- ui.hint("Run `apow mint` to mint a miner NFT first.");
122
- process.exit(1);
123
- }
124
- const best = (0, detect_1.selectBestMiner)(miners);
125
- if (miners.length === 1) {
126
- console.log(` Using miner #${best.tokenId} (${best.rarityLabel}, ${(0, detect_1.formatHashpower)(best.hashpower)})`);
127
- }
128
- else {
129
- console.log(` Found ${miners.length} miners — using #${best.tokenId} (${best.rarityLabel}, ${(0, detect_1.formatHashpower)(best.hashpower)})`);
130
- for (const m of miners) {
131
- const marker = m.tokenId === best.tokenId ? ui.green(" *") : " ";
132
- console.log(` ${marker} #${m.tokenId} — ${m.rarityLabel} (${(0, detect_1.formatHashpower)(m.hashpower)})`);
133
- }
134
- }
135
- return best.tokenId;
136
- }
137
144
  async function setupWizard() {
138
145
  console.log("");
139
146
  ui.banner(["APoW Agent Setup"]);
@@ -197,9 +204,17 @@ async function setupWizard() {
197
204
  console.log("");
198
205
  console.log(` ${ui.dim("Fund this address with ≥0.005 ETH on Base to start.")}`);
199
206
  console.log("");
200
- const keyPath = saveKeyFile(addr, privateKey);
201
- console.log(` ${ui.dim(`Key saved to: ${keyPath}`)}`);
202
- console.log(` ${ui.yellow("Back up this file securely, then delete it.")}`);
207
+ const artifacts = await saveWalletArtifacts(addr, privateKey);
208
+ if (artifacts.plaintextPath) {
209
+ console.log(` ${ui.dim(`Import helper saved to: ${artifacts.plaintextPath}`)}`);
210
+ console.log(` ${ui.yellow("This plaintext file is easy to import, but less secure than an encrypted keystore.")}`);
211
+ }
212
+ if (artifacts.keystorePath) {
213
+ console.log(` ${ui.dim(`Encrypted keystore saved to: ${artifacts.keystorePath}`)}`);
214
+ }
215
+ else {
216
+ console.log(` ${ui.dim("Tip: set KEYSTORE_PASSWORD or rerun wallet export to create an encrypted JSON keystore backup.")}`);
217
+ }
203
218
  console.log("");
204
219
  }
205
220
  values.PRIVATE_KEY = privateKey;
@@ -332,18 +347,7 @@ async function setupWizard() {
332
347
  (0, config_1.reloadConfig)();
333
348
  (0, wallet_1.reinitClients)();
334
349
  ui.ok("Config saved to .env");
335
- // Check .gitignore
336
- const gitignorePath = (0, node_path_1.join)(process.cwd(), ".gitignore");
337
- if ((0, node_fs_1.existsSync)(gitignorePath)) {
338
- const gitignore = (0, node_fs_1.readFileSync)(gitignorePath, "utf8");
339
- if (!gitignore.includes(".env")) {
340
- ui.warn(".gitignore does not include .env — your secrets may be committed!");
341
- ui.hint("Add .env and wallet-*.txt to .gitignore");
342
- }
343
- if (!gitignore.includes("wallet-")) {
344
- ui.hint("Consider adding wallet-*.txt to .gitignore");
345
- }
346
- }
350
+ ensureGitignoreSafetyEntries();
347
351
  console.log("");
348
352
  console.log(` Next: ${ui.cyan("apow start")}`);
349
353
  console.log(` ${ui.dim("Guided happy path: setup -> fund -> mint -> mine")}`);
@@ -428,13 +432,7 @@ async function runStartFlow() {
428
432
  return;
429
433
  }
430
434
  }
431
- const tokenId = await (0, mint_1.runMintFlow)({ startMiningAfterMint: false });
432
- if (!tokenId) {
433
- return;
434
- }
435
- console.log("");
436
- await (0, preflight_1.runPreflight)("mining");
437
- await (0, miner_1.startMining)(tokenId);
435
+ await (0, mint_1.runMintFlow)({ startMiningAfterMint: true });
438
436
  }
439
437
  async function main() {
440
438
  const version = readVersion();
@@ -495,21 +493,59 @@ async function main() {
495
493
  program
496
494
  .command("mint")
497
495
  .description("Mint a new miner NFT (Easy Mode: x402 LLM, no API key)")
498
- .hook("preAction", async () => {
499
- await (0, preflight_1.runPreflight)("wallet");
500
- })
501
496
  .action(async () => {
497
+ if (!config_1.config.privateKey || !wallet_1.account) {
498
+ ui.warn("No wallet configured — launching setup first.");
499
+ await setupWizard();
500
+ (0, config_1.reloadConfig)();
501
+ (0, wallet_1.reinitClients)();
502
+ if (!wallet_1.account) {
503
+ ui.error("Wallet configuration did not complete.");
504
+ return;
505
+ }
506
+ }
507
+ await (0, preflight_1.runPreflight)("wallet");
502
508
  await (0, mint_1.runMintFlow)();
503
509
  });
504
510
  program
505
511
  .command("mine")
506
512
  .description("Start the mining loop (Easy Mode: remote x402 GPU)")
507
513
  .argument("[tokenId]", "Miner token ID (auto-detects if omitted)")
508
- .hook("preAction", async () => {
509
- await (0, preflight_1.runPreflight)("mining");
510
- })
511
514
  .action(async (tokenIdArg) => {
512
- const tokenId = await resolveTokenId(tokenIdArg);
515
+ const hasWallet = !!config_1.config.privateKey && !!wallet_1.account;
516
+ const hasRpc = config_1.config.useX402 || !!config_1.config.rpcUrl;
517
+ if (!hasWallet || !hasRpc) {
518
+ ui.warn("Mining prerequisites are missing — launching guided start flow.");
519
+ await runStartFlow();
520
+ return;
521
+ }
522
+ const miningAccount = wallet_1.account;
523
+ let tokenId;
524
+ if (tokenIdArg) {
525
+ await (0, preflight_1.runPreflight)("mining");
526
+ tokenId = parseTokenId(tokenIdArg);
527
+ }
528
+ else {
529
+ const miners = await (0, detect_1.detectMiners)(miningAccount.address);
530
+ if (miners.length === 0) {
531
+ ui.warn("No mining rigs found — launching guided start flow.");
532
+ await runStartFlow();
533
+ return;
534
+ }
535
+ await (0, preflight_1.runPreflight)("mining");
536
+ tokenId = (0, detect_1.selectBestMiner)(miners).tokenId;
537
+ if (miners.length === 1) {
538
+ console.log(` Using miner #${tokenId} (${miners[0].rarityLabel}, ${(0, detect_1.formatHashpower)(miners[0].hashpower)})`);
539
+ }
540
+ else {
541
+ const best = miners.find((m) => m.tokenId === tokenId);
542
+ console.log(` Found ${miners.length} miners — using #${best.tokenId} (${best.rarityLabel}, ${(0, detect_1.formatHashpower)(best.hashpower)})`);
543
+ for (const m of miners) {
544
+ const marker = m.tokenId === tokenId ? ui.green(" *") : " ";
545
+ console.log(` ${marker} #${m.tokenId} — ${m.rarityLabel} (${(0, detect_1.formatHashpower)(m.hashpower)})`);
546
+ }
547
+ }
548
+ }
513
549
  await (0, miner_1.startMining)(tokenId);
514
550
  });
515
551
  program
@@ -565,9 +601,17 @@ async function main() {
565
601
  console.log(` ${ui.yellow(" it will be displayed. Anyone with this key")}`);
566
602
  console.log(` ${ui.yellow(" controls your funds.")}`);
567
603
  console.log("");
568
- const keyPath = saveKeyFile(acct.address, key);
569
- console.log(` ${ui.dim(`Key saved to: ${keyPath}`)}`);
570
- console.log(` ${ui.yellow("Back up this file securely, then delete it.")}`);
604
+ const artifacts = await saveWalletArtifacts(acct.address, key);
605
+ if (artifacts.plaintextPath) {
606
+ console.log(` ${ui.dim(`Import helper saved to: ${artifacts.plaintextPath}`)}`);
607
+ console.log(` ${ui.yellow("This plaintext file is easy to import, but less secure than an encrypted keystore.")}`);
608
+ }
609
+ if (artifacts.keystorePath) {
610
+ console.log(` ${ui.dim(`Encrypted keystore saved to: ${artifacts.keystorePath}`)}`);
611
+ }
612
+ else {
613
+ console.log(` ${ui.dim("Tip: set KEYSTORE_PASSWORD or rerun wallet export to create an encrypted JSON keystore backup.")}`);
614
+ }
571
615
  console.log("");
572
616
  console.log(` ${ui.dim("Import into Phantom, MetaMask, or any EVM wallet")}`);
573
617
  console.log(` ${ui.dim("to view your AGENT tokens and Mining Rig NFT.")}`);
@@ -602,27 +646,34 @@ async function main() {
602
646
  console.log(` Address: ${wallet_1.account.address}`);
603
647
  console.log(` Private Key: ${config_1.config.privateKey}`);
604
648
  console.log("");
605
- const filename = `wallet-${wallet_1.account.address}.txt`;
606
- const filepath = (0, node_path_1.join)(process.cwd(), filename);
607
- if (!(0, node_fs_1.existsSync)(filepath)) {
608
- const save = await ui.confirm("Save to file?");
609
- if (save) {
610
- const keyPath = saveKeyFile(wallet_1.account.address, config_1.config.privateKey);
611
- console.log(` ${ui.dim(`Saved to: ${keyPath}`)}`);
612
- console.log(` ${ui.yellow("Back up this file securely, then delete it.")}`);
613
- console.log("");
614
- }
649
+ const savePlaintext = await ui.confirm("Save plaintext import helper?");
650
+ const artifacts = await saveWalletArtifacts(wallet_1.account.address, config_1.config.privateKey, {
651
+ createPlaintextImportFile: savePlaintext,
652
+ });
653
+ if (artifacts.plaintextPath) {
654
+ console.log(` ${ui.dim(`Saved import helper: ${artifacts.plaintextPath}`)}`);
615
655
  }
656
+ if (artifacts.keystorePath) {
657
+ console.log(` ${ui.dim(`Saved encrypted keystore: ${artifacts.keystorePath}`)}`);
658
+ }
659
+ console.log("");
616
660
  });
617
661
  walletCmd
618
662
  .command("fund")
619
663
  .description("Send ETH from your wallet to another address")
620
664
  .argument("<address>", "Destination address (0x-prefixed)")
621
665
  .argument("[amount]", "ETH amount to send (default: mint price + 0.003 ETH gas buffer)")
622
- .hook("preAction", async () => {
623
- await (0, preflight_1.runPreflight)("wallet");
624
- })
625
666
  .action(async (address, amountArg) => {
667
+ if (!config_1.config.privateKey || !wallet_1.account) {
668
+ ui.warn("No wallet configured — launching setup first.");
669
+ await setupWizard();
670
+ (0, config_1.reloadConfig)();
671
+ (0, wallet_1.reinitClients)();
672
+ if (!wallet_1.account) {
673
+ ui.error("Wallet configuration did not complete.");
674
+ return;
675
+ }
676
+ }
626
677
  if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
627
678
  ui.error("Invalid address format. Must be 0x + 40 hex characters.");
628
679
  return;
@@ -659,9 +710,11 @@ async function main() {
659
710
  ["Balance", `${Number((0, viem_1.formatEther)(senderBalance)).toFixed(6)} ETH`],
660
711
  ]);
661
712
  console.log("");
662
- if (senderBalance < amount) {
713
+ const requiredBalance = amount + TRANSFER_GAS_RESERVE_ETH;
714
+ if (senderBalance < requiredBalance) {
663
715
  ui.error("Insufficient ETH balance.");
664
- ui.hint(`Need ${(0, viem_1.formatEther)(amount)} ETH, have ${Number((0, viem_1.formatEther)(senderBalance)).toFixed(6)} ETH`);
716
+ ui.hint(`Need ${(0, viem_1.formatEther)(amount)} ETH for the transfer plus ~${(0, viem_1.formatEther)(TRANSFER_GAS_RESERVE_ETH)} ETH for send gas.`);
717
+ ui.hint(`Have ${Number((0, viem_1.formatEther)(senderBalance)).toFixed(6)} ETH in the sender wallet.`);
665
718
  return;
666
719
  }
667
720
  const proceed = await ui.confirm("Send ETH?");
@@ -780,14 +833,14 @@ async function main() {
780
833
  });
781
834
  dashboardCmd
782
835
  .command("scan [dir]")
783
- .description("Auto-detect wallets from wallet-0x*.txt files in a directory")
836
+ .description("Auto-detect wallets from wallet-0x*.txt or wallet-0x*.json files in a directory")
784
837
  .action((dir) => {
785
838
  const scanDir = dir ?? process.cwd();
786
839
  const { addresses, newCount } = detectWallets(scanDir);
787
840
  console.log("");
788
841
  if (addresses.length === 0) {
789
842
  console.log(` No wallets found in ${scanDir}`);
790
- console.log(` ${ui.dim("Expected files named wallet-0x<address>.txt")}`);
843
+ console.log(` ${ui.dim("Expected files named wallet-0x<address>.txt or wallet-0x<address>.json")}`);
791
844
  }
792
845
  else {
793
846
  console.log(` ${ui.bold("Detected Wallets")} (${newCount} new, ${addresses.length} total)`);
@@ -842,26 +895,26 @@ function detectWallets(scanDir) {
842
895
  const existing = loadWallets(walletsPath);
843
896
  const seen = new Set(existing.map((a) => a.toLowerCase()));
844
897
  const detected = [];
845
- // Scan scanDir for wallet-0x*.txt files
898
+ // Scan scanDir for wallet-0x*.txt / .json files
846
899
  try {
847
900
  const entries = (0, node_fs_1.readdirSync)(scanDir, { withFileTypes: true });
848
901
  for (const entry of entries) {
849
902
  if (entry.isFile()) {
850
- const match = entry.name.match(/^wallet-(0x[0-9a-fA-F]{40})\.txt$/);
851
- if (match && !seen.has(match[1].toLowerCase())) {
852
- detected.push(match[1]);
853
- seen.add(match[1].toLowerCase());
903
+ const address = (0, wallet_store_1.detectWalletAddressFromFilename)(entry.name);
904
+ if (address && !seen.has(address.toLowerCase())) {
905
+ detected.push(address);
906
+ seen.add(address.toLowerCase());
854
907
  }
855
908
  }
856
- // Scan rig*/wallet-0x*.txt subdirectories
909
+ // Scan rig*/wallet-0x* subdirectories
857
910
  if (entry.isDirectory() && entry.name.startsWith("rig")) {
858
911
  try {
859
912
  const rigFiles = (0, node_fs_1.readdirSync)((0, node_path_1.join)(scanDir, entry.name));
860
913
  for (const file of rigFiles) {
861
- const m = file.match(/^wallet-(0x[0-9a-fA-F]{40})\.txt$/);
862
- if (m && !seen.has(m[1].toLowerCase())) {
863
- detected.push(m[1]);
864
- seen.add(m[1].toLowerCase());
914
+ const address = (0, wallet_store_1.detectWalletAddressFromFilename)(file);
915
+ if (address && !seen.has(address.toLowerCase())) {
916
+ detected.push(address);
917
+ seen.add(address.toLowerCase());
865
918
  }
866
919
  }
867
920
  }
package/dist/miner.js CHANGED
@@ -58,6 +58,10 @@ const miningAgentAbi = MiningAgent_json_1.default;
58
58
  const MAX_CONSECUTIVE_FAILURES = 10;
59
59
  const RETRY_DELAY_MS = 2_000;
60
60
  const RETRY_JITTER_MS = 500;
61
+ const MAX_MINE_GAS_UNITS = 400000n;
62
+ const MIN_MINE_GAS_RESERVE_WEI = (0, viem_1.parseEther)("0.0002");
63
+ const MINE_GAS_RESERVE_CACHE_MS = 30_000;
64
+ const NEXT_BLOCK_POLL_MS = 1_500;
61
65
  const BASE_REWARD = 3n * 10n ** 18n;
62
66
  const REWARD_DECAY_NUM = 90n;
63
67
  const REWARD_DECAY_DEN = 100n;
@@ -99,6 +103,23 @@ function rejectOnAbort(signal) {
99
103
  function retryDelayMs() {
100
104
  return RETRY_DELAY_MS + Math.random() * RETRY_JITTER_MS;
101
105
  }
106
+ let cachedMineGasReserve = null;
107
+ async function estimateMineGasReserve() {
108
+ if (cachedMineGasReserve && cachedMineGasReserve.expiresAt > Date.now()) {
109
+ return cachedMineGasReserve.value;
110
+ }
111
+ try {
112
+ const fees = await wallet_1.publicClient.estimateFeesPerGas();
113
+ const feePerGas = fees.maxFeePerGas ?? fees.gasPrice ?? 0n;
114
+ const estimated = (feePerGas * MAX_MINE_GAS_UNITS * 3n) / 2n;
115
+ const value = estimated > MIN_MINE_GAS_RESERVE_WEI ? estimated : MIN_MINE_GAS_RESERVE_WEI;
116
+ cachedMineGasReserve = { value, expiresAt: Date.now() + MINE_GAS_RESERVE_CACHE_MS };
117
+ return value;
118
+ }
119
+ catch {
120
+ return MIN_MINE_GAS_RESERVE_WEI;
121
+ }
122
+ }
102
123
  function estimateReward(totalMines, eraInterval, hashpower) {
103
124
  const era = totalMines / eraInterval;
104
125
  let reward = BASE_REWARD;
@@ -121,7 +142,7 @@ async function waitForNextBlock(lastMineBlock) {
121
142
  if (currentBlock > lastMineBlock) {
122
143
  return;
123
144
  }
124
- await sleep(500);
145
+ await sleep(NEXT_BLOCK_POLL_MS);
125
146
  }
126
147
  throw new Error("Timed out waiting for next block (60s)");
127
148
  }
@@ -292,6 +313,11 @@ async function showStartupBanner(tokenId) {
292
313
  ["Supply", `${supplyPct.toFixed(2)}% mined (${Number((0, viem_1.formatEther)(totalMinted)).toLocaleString()} / ${Number((0, viem_1.formatEther)(mineableSupply)).toLocaleString()} AGENT)`],
293
314
  ]);
294
315
  console.log("");
316
+ return {
317
+ mineableSupply,
318
+ eraInterval,
319
+ hashpower: hashpowerRaw,
320
+ };
295
321
  }
296
322
  async function startMining(tokenId) {
297
323
  const { account, walletClient } = (0, wallet_1.requireWallet)();
@@ -333,7 +359,18 @@ async function startMining(tokenId) {
333
359
  if (labelParts.length === 0)
334
360
  labelParts.push(`JS (${config_1.config.minerThreads} threads)`);
335
361
  let modeLabel = labelParts.join(" + ");
336
- await showStartupBanner(tokenId);
362
+ const owner = (await wallet_1.publicClient.readContract({
363
+ address: config_1.config.miningAgentAddress,
364
+ abi: miningAgentAbi,
365
+ functionName: "ownerOf",
366
+ args: [tokenId],
367
+ }));
368
+ if (owner.toLowerCase() !== account.address.toLowerCase()) {
369
+ ui.error(`Miner #${tokenId} is owned by ${owner}, not your wallet.`);
370
+ ui.hint("Check token ID or verify ownership on Basescan");
371
+ return;
372
+ }
373
+ const startup = await showStartupBanner(tokenId);
337
374
  console.log(` Grinder: ${ui.bold(modeLabel)}`);
338
375
  // Difficulty-aware preflight gate
339
376
  const preflight = await readMiningChallenge();
@@ -381,20 +418,8 @@ async function startMining(tokenId) {
381
418
  console.log("");
382
419
  while (true) {
383
420
  try {
384
- // Pre-flight ownership check
385
- const owner = (await wallet_1.publicClient.readContract({
386
- address: config_1.config.miningAgentAddress,
387
- abi: miningAgentAbi,
388
- functionName: "ownerOf",
389
- args: [tokenId],
390
- }));
391
- if (owner.toLowerCase() !== account.address.toLowerCase()) {
392
- ui.error(`Miner #${tokenId} is owned by ${owner}, not your wallet.`);
393
- ui.hint("Check token ID or verify ownership on Basescan");
394
- return;
395
- }
396
- // Supply exhaustion pre-check
397
- const [totalMines, totalMinted, mineableSupply, eraInterval, hashpower] = await Promise.all([
421
+ // Supply exhaustion + gas readiness pre-check
422
+ const [totalMines, totalMinted, ethBalance, mineGasReserve] = await Promise.all([
398
423
  wallet_1.publicClient.readContract({
399
424
  address: config_1.config.agentCoinAddress,
400
425
  abi: agentCoinAbi,
@@ -405,31 +430,20 @@ async function startMining(tokenId) {
405
430
  abi: agentCoinAbi,
406
431
  functionName: "totalMinted",
407
432
  }),
408
- wallet_1.publicClient.readContract({
409
- address: config_1.config.agentCoinAddress,
410
- abi: agentCoinAbi,
411
- functionName: "MINEABLE_SUPPLY",
412
- }),
413
- wallet_1.publicClient.readContract({
414
- address: config_1.config.agentCoinAddress,
415
- abi: agentCoinAbi,
416
- functionName: "ERA_INTERVAL",
417
- }),
418
- wallet_1.publicClient.readContract({
419
- address: config_1.config.miningAgentAddress,
420
- abi: miningAgentAbi,
421
- functionName: "hashpower",
422
- args: [tokenId],
423
- }),
433
+ (0, wallet_1.getEthBalance)(),
434
+ estimateMineGasReserve(),
424
435
  ]);
425
- const estimatedReward = estimateReward(totalMines, eraInterval, BigInt(hashpower));
426
- if (totalMinted + estimatedReward > mineableSupply) {
427
- ui.error(`Supply nearly exhausted. Remaining: ${(0, viem_1.formatEther)(mineableSupply - totalMinted)} AGENT.`);
436
+ if (ethBalance < mineGasReserve) {
437
+ throw new Error(`Not enough ETH for gas (have ${(0, viem_1.formatEther)(ethBalance)} ETH, need ~${(0, viem_1.formatEther)(mineGasReserve)} ETH)`);
438
+ }
439
+ const estimatedReward = estimateReward(totalMines, startup.eraInterval, startup.hashpower);
440
+ if (totalMinted + estimatedReward > startup.mineableSupply) {
441
+ ui.error(`Supply nearly exhausted. Remaining: ${(0, viem_1.formatEther)(startup.mineableSupply - totalMinted)} AGENT.`);
428
442
  return;
429
443
  }
430
444
  // Era transition alert
431
- const currentEra = totalMines / eraInterval;
432
- const minesUntilNextEra = eraInterval - (totalMines % eraInterval);
445
+ const currentEra = totalMines / startup.eraInterval;
446
+ const minesUntilNextEra = startup.eraInterval - (totalMines % startup.eraInterval);
433
447
  if (minesUntilNextEra <= 10n) {
434
448
  ui.warn(`Era transition in ${minesUntilNextEra} mines! Reward will decrease.`);
435
449
  }
package/dist/ui.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.cyan = exports.yellow = exports.green = exports.red = exports.bold = exports.dim = void 0;
4
+ exports.isInteractiveSession = isInteractiveSession;
4
5
  exports.banner = banner;
5
6
  exports.table = table;
6
7
  exports.spinner = spinner;
@@ -19,6 +20,9 @@ const node_process_1 = require("node:process");
19
20
  const isTTY = !!node_process_1.stdout.isTTY && !!node_process_1.stderr.isTTY;
20
21
  const isInteractive = !!node_process_1.stdin.isTTY && isTTY;
21
22
  const noColor = !!process.env.NO_COLOR || !isTTY;
23
+ function isInteractiveSession() {
24
+ return isInteractive;
25
+ }
22
26
  function wrap(code, reset) {
23
27
  if (noColor)
24
28
  return (s) => s;
@@ -52,10 +56,21 @@ const activeSpinners = new Set();
52
56
  function spinner(label) {
53
57
  if (!isTTY) {
54
58
  console.error(` ${label}`);
59
+ let finished = false;
55
60
  const noop = {
56
- update(l) { console.error(` ${l}`); },
57
- stop(l) { console.error(` ${l}`); },
58
- fail(l) { console.error(` ${l}`); },
61
+ update() { },
62
+ stop(l) {
63
+ if (finished)
64
+ return;
65
+ finished = true;
66
+ console.error(` ${l}`);
67
+ },
68
+ fail(l) {
69
+ if (finished)
70
+ return;
71
+ finished = true;
72
+ console.error(` ${l}`);
73
+ },
59
74
  };
60
75
  return noop;
61
76
  }
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getKeystoreDir = getKeystoreDir;
4
+ exports.getPlaintextWalletPath = getPlaintextWalletPath;
5
+ exports.getKeystoreWalletPath = getKeystoreWalletPath;
6
+ exports.savePlaintextImportFile = savePlaintextImportFile;
7
+ exports.saveEncryptedKeystoreFile = saveEncryptedKeystoreFile;
8
+ exports.detectWalletAddressFromFilename = detectWalletAddressFromFilename;
9
+ const node_fs_1 = require("node:fs");
10
+ const node_os_1 = require("node:os");
11
+ const node_path_1 = require("node:path");
12
+ const ox_1 = require("ox");
13
+ function ensureDir(path) {
14
+ if (!(0, node_fs_1.existsSync)(path)) {
15
+ (0, node_fs_1.mkdirSync)(path, { recursive: true });
16
+ }
17
+ }
18
+ function getKeystoreDir() {
19
+ const dir = (0, node_path_1.join)((0, node_os_1.homedir)(), ".apow", "keystores");
20
+ ensureDir(dir);
21
+ return dir;
22
+ }
23
+ function getPlaintextWalletPath(address, cwd = process.cwd()) {
24
+ return (0, node_path_1.join)(cwd, `wallet-${address}.txt`);
25
+ }
26
+ function getKeystoreWalletPath(address) {
27
+ return (0, node_path_1.join)(getKeystoreDir(), `wallet-${address}.json`);
28
+ }
29
+ function savePlaintextImportFile(address, privateKey, cwd = process.cwd()) {
30
+ const filepath = getPlaintextWalletPath(address, cwd);
31
+ const content = [
32
+ `Address: ${address}`,
33
+ `Private Key: ${privateKey}`,
34
+ "",
35
+ `Generated: ${new Date().toISOString()}`,
36
+ "",
37
+ "Import this key into MetaMask, Rabby, Phantom, or any EVM wallet.",
38
+ "Keep this file safe — anyone with the private key controls your funds.",
39
+ "",
40
+ ].join("\n");
41
+ (0, node_fs_1.writeFileSync)(filepath, content, { encoding: "utf8", mode: 0o600 });
42
+ return filepath;
43
+ }
44
+ async function saveEncryptedKeystoreFile(address, privateKey, password) {
45
+ const filepath = getKeystoreWalletPath(address);
46
+ const [key, opts] = await ox_1.Keystore.scryptAsync({ password });
47
+ const keystore = ox_1.Keystore.encrypt(privateKey, key, opts);
48
+ const payload = {
49
+ ...keystore,
50
+ address: address.slice(2).toLowerCase(),
51
+ };
52
+ (0, node_fs_1.writeFileSync)(filepath, JSON.stringify(payload, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
53
+ return filepath;
54
+ }
55
+ function detectWalletAddressFromFilename(filename) {
56
+ const match = filename.match(/^wallet-(0x[0-9a-fA-F]{40})(?:\.keystore)?\.(txt|json)$/);
57
+ return match?.[1] ?? null;
58
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apow-cli",
3
- "version": "0.11.5",
3
+ "version": "0.11.7",
4
4
  "description": "Mine AGENT tokens on Base L2 with Agentic Proof of Work",
5
5
  "keywords": [
6
6
  "apow",
package/skill.md CHANGED
@@ -30,7 +30,7 @@ on Base. Everything else you handle yourself.
30
30
 
31
31
  **Via npm (recommended):**
32
32
  ```bash
33
- npx apow-cli start # zero-config happy path: setup -> fund -> mint -> mine
33
+ npx apow-cli start # zero-config happy path: setup -> funding checks -> mint -> mine
34
34
  ```
35
35
 
36
36
  **Via source:**
@@ -48,7 +48,7 @@ If you're an AI agent, you can skip the wizard and write the `.env` directly.
48
48
  ```bash
49
49
  # 1. Generate a wallet
50
50
  npx apow-cli wallet new
51
- # Captures address + private key from output (also saved to wallet-<address>.txt)
51
+ # Captures address + private key from output (and can save a plaintext import helper plus encrypted keystore)
52
52
 
53
53
  # 2. Write .env directly — Easy Mode equivalent
54
54
  # Contract addresses are built-in defaults — no need to specify them
@@ -134,7 +134,7 @@ Or generate one directly (useful for agents, no prompts):
134
134
  npx apow-cli wallet new
135
135
  ```
136
136
 
137
- This outputs a private key (0x + 64 hex chars) and Base address, and saves a `wallet-<address>.txt` file to the current directory. The private key goes in your `.env` as `PRIVATE_KEY`.
137
+ This outputs a private key (0x + 64 hex chars) and Base address, saves a plaintext `wallet-<address>.txt` import helper to the current directory, and can also create an encrypted `wallet-<address>.json` keystore under `~/.apow/keystores/` when a password is available. The private key goes in your `.env` as `PRIVATE_KEY`.
138
138
 
139
139
  **Exporting an existing wallet:** If you've already set up a wallet and need to retrieve the key:
140
140
 
@@ -142,7 +142,7 @@ This outputs a private key (0x + 64 hex chars) and Base address, and saves a `wa
142
142
  npx apow-cli wallet export
143
143
  ```
144
144
 
145
- This prompts for confirmation, then displays your address and private key. It also offers to save a `wallet-<address>.txt` file if one doesn't already exist.
145
+ This prompts for confirmation, then displays your address and private key. It can save a plaintext `wallet-<address>.txt` import helper and/or an encrypted JSON keystore backup.
146
146
 
147
147
  **Exporting to a wallet app:** The user can import this private key into Phantom, MetaMask, Rainbow, or any EVM-compatible wallet to view their AGENT tokens and Mining Rig NFT alongside their other assets.
148
148
 
@@ -263,6 +263,7 @@ CHAIN=base
263
263
  | Variable | Required | Default | Description |
264
264
  |---|---|---|---|
265
265
  | `PRIVATE_KEY` | Yes | - | Wallet private key (0x + 64 hex chars) |
266
+ | `KEYSTORE_PASSWORD` | No | unset | If set, `wallet new`/`wallet export` also create an encrypted JSON keystore backup under `~/.apow/keystores/` |
266
267
  | `MINING_AGENT_ADDRESS` | Yes | - | Deployed MiningAgent contract address |
267
268
  | `AGENT_COIN_ADDRESS` | Yes | - | Deployed AgentCoin contract address |
268
269
  | `LLM_PROVIDER` | For minting | `clawrouter` if `USE_X402=true`, else `openai` | LLM provider for minting: `clawrouter` (recommended, zero credentials), `openai`, `gemini`, `deepseek`, `qwen`, `anthropic`, `ollama`, `claude-code`, `codex`. Not needed for mining. |
@@ -650,7 +651,7 @@ This section addresses the security model of apow-cli head-on. Every claim below
650
651
 
651
652
  ### Private Key Generation (Local Only)
652
653
 
653
- Keys are generated via `viem/accounts` `generatePrivateKey()`, which uses Node.js `crypto.randomBytes(32)`, a cryptographically secure random number generator. Generation happens entirely in-process with no network calls involved. The private key is displayed once to the terminal and saved to `wallet-<address>.txt` with file permissions `0o600` (owner-read-write only).
654
+ Keys are generated via `viem/accounts` `generatePrivateKey()`, which uses Node.js `crypto.randomBytes(32)`, a cryptographically secure random number generator. Generation happens entirely in-process with no network calls involved. The private key is displayed once to the terminal, and the CLI can create both a plaintext `wallet-<address>.txt` import helper and a password-protected JSON keystore (`Web3 Secret Storage v3`) with file permissions `0o600`.
654
655
 
655
656
  ### Private Key Is NEVER Transmitted
656
657
 
@@ -698,7 +699,7 @@ The SMHL solver sends only generic word-generation prompts to the LLM (e.g., "Wr
698
699
 
699
700
  1. **Use a fresh wallet.** Generate one with `npx apow-cli wallet new`. Do not import your main wallet or any wallet holding significant funds.
700
701
  2. **Fund with only what you need.** ~0.005 ETH covers minting + several mining cycles.
701
- 3. **Wallet backups are created automatically** at `wallet-<address>.txt` with restricted file permissions (`0o600`).
702
+ 3. **Prefer encrypted keystore backups** in `~/.apow/keystores/wallet-<address>.json`. The plaintext `wallet-<address>.txt` helper is convenient for importing into wallet UIs, but it is less secure.
702
703
  4. **Verify the source before running** if you prefer:
703
704
  ```bash
704
705
  git clone https://github.com/Agentoshi/apow-cli
@@ -769,7 +770,7 @@ The `apow dashboard` command group provides a real-time web UI for monitoring yo
769
770
  | `apow dashboard start` | Launch the dashboard web UI at `http://localhost:3847`. Auto-opens browser. Press Ctrl+C to stop. |
770
771
  | `apow dashboard add <address>` | Add a wallet address to monitor. Validates 0x + 40 hex chars. |
771
772
  | `apow dashboard remove <address>` | Remove a wallet address from monitoring. |
772
- | `apow dashboard scan [dir]` | Auto-detect wallets from `wallet-0x*.txt` files in the given directory (default: CWD). Also scans `rig*/` subdirectories. |
773
+ | `apow dashboard scan [dir]` | Auto-detect wallets from `wallet-0x*.txt` and `wallet-0x*.json` files in the given directory (default: CWD). Also scans `rig*/` subdirectories. |
773
774
  | `apow dashboard wallets` | List all currently monitored wallet addresses. |
774
775
 
775
776
  ### How It Works
@@ -779,7 +780,7 @@ The `apow dashboard` command group provides a real-time web UI for monitoring yo
779
780
  - **Data fetching:** Chunked RPC multicalls (max 30 per batch) with a 25-second TTL cache. Queries ETH balance, AGENT balance, rig ownership, rarity, hashpower, mine count, and earnings for every wallet.
780
781
  - **NFT art:** Renders on-chain SVG art for each Mining Rig with rarity-based color coding.
781
782
  - **Auto-seed:** On first run, seeds `wallets.json` with the address from your `.env` if configured.
782
- - **Auto-detect:** `dashboard start` automatically scans CWD for `wallet-0x*.txt` files before launching.
783
+ - **Auto-detect:** `dashboard start` automatically scans CWD for `wallet-0x*.txt` and `wallet-0x*.json` files before launching.
783
784
 
784
785
  ### Fleet Configuration (`~/.apow/fleets.json`)
785
786
 
@@ -800,8 +801,8 @@ For managing wallets across multiple machines or directories, create `~/.apow/fl
800
801
  |------|--------------|-------------|
801
802
  | `array` | JSON array of addresses | Simple list: `["0xABC...", "0xDEF..."]` |
802
803
  | `solkek` | JSON with `master.address` + `miners[].address` | Solkek fleet manager format |
803
- | `rigdirs` | Directory containing `rig*/wallet-0x*.txt` | Scan rig subdirectories for wallet files |
804
- | `walletfiles` | Directory containing `wallet-0x*.txt` | Scan flat directory for wallet files |
804
+ | `rigdirs` | Directory containing `rig*/wallet-0x*.txt` or `.json` | Scan rig subdirectories for wallet files |
805
+ | `walletfiles` | Directory containing `wallet-0x*.txt` or `.json` | Scan flat directory for wallet files |
805
806
 
806
807
  If `fleets.json` does not exist, the dashboard falls back to `wallets.json` as a single "Main" fleet.
807
808