apow-cli 0.11.4 → 0.11.6

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
@@ -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,33 +85,61 @@ function readVersion() {
99
85
  return "0.1.0";
100
86
  }
101
87
  }
102
- async function resolveTokenId(tokenIdArg) {
103
- if (tokenIdArg) {
104
- return parseTokenId(tokenIdArg);
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;
105
95
  }
106
- if (!wallet_1.account) {
107
- ui.error("No token ID provided and no wallet configured.");
108
- ui.hint("Usage: apow mine <tokenId>, or run `apow setup` and choose Easy Mode");
109
- process.exit(1);
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;
110
120
  }
111
- const miners = await (0, detect_1.detectMiners)(wallet_1.account.address);
112
- if (miners.length === 0) {
113
- ui.error("No mining rigs found for this wallet.");
114
- ui.hint("Run `apow mint` to mint a miner NFT first.");
115
- process.exit(1);
121
+ if (!password) {
122
+ return null;
116
123
  }
117
- const best = (0, detect_1.selectBestMiner)(miners);
118
- if (miners.length === 1) {
119
- console.log(` Using miner #${best.tokenId} (${best.rarityLabel}, ${(0, detect_1.formatHashpower)(best.hashpower)})`);
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);
120
130
  }
121
- else {
122
- console.log(` Found ${miners.length} miners — using #${best.tokenId} (${best.rarityLabel}, ${(0, detect_1.formatHashpower)(best.hashpower)})`);
123
- for (const m of miners) {
124
- const marker = m.tokenId === best.tokenId ? ui.green(" *") : " ";
125
- console.log(` ${marker} #${m.tokenId} — ${m.rarityLabel} (${(0, detect_1.formatHashpower)(m.hashpower)})`);
126
- }
131
+ const keystorePath = await maybeCreateEncryptedKeystoreBackup(address, privateKey);
132
+ if (keystorePath) {
133
+ result.keystorePath = keystorePath;
127
134
  }
128
- return best.tokenId;
135
+ return result;
136
+ }
137
+ function shouldSkipUpdateCheck(argv) {
138
+ return argv.includes("--help")
139
+ || argv.includes("-h")
140
+ || argv.includes("--version")
141
+ || argv.includes("-V")
142
+ || argv[0] === "help";
129
143
  }
130
144
  async function setupWizard() {
131
145
  console.log("");
@@ -190,9 +204,17 @@ async function setupWizard() {
190
204
  console.log("");
191
205
  console.log(` ${ui.dim("Fund this address with ≥0.005 ETH on Base to start.")}`);
192
206
  console.log("");
193
- const keyPath = saveKeyFile(addr, privateKey);
194
- console.log(` ${ui.dim(`Key saved to: ${keyPath}`)}`);
195
- 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
+ }
196
218
  console.log("");
197
219
  }
198
220
  values.PRIVATE_KEY = privateKey;
@@ -210,7 +232,7 @@ async function setupWizard() {
210
232
  ui.ok("LLM: ClawRouter x402 (wallet-paid, no API key)");
211
233
  ui.ok("Grinder: x402 GPU (remote, wallet-paid, no local CPU fallback)");
212
234
  console.log(` ${ui.dim("Easy mode is agent-first: no RPC key, no LLM key, no GPU rental setup.")}`);
213
- console.log(` ${ui.dim("Fund the wallet with ETH + USDC on Base, then run: apow mint && apow mine")}`);
235
+ console.log(` ${ui.dim("Fund the wallet with ETH + USDC on Base, then run: apow start")}`);
214
236
  }
215
237
  else {
216
238
  // Advanced: user picks which services remain autonomous
@@ -325,22 +347,10 @@ async function setupWizard() {
325
347
  (0, config_1.reloadConfig)();
326
348
  (0, wallet_1.reinitClients)();
327
349
  ui.ok("Config saved to .env");
328
- // Check .gitignore
329
- const gitignorePath = (0, node_path_1.join)(process.cwd(), ".gitignore");
330
- if ((0, node_fs_1.existsSync)(gitignorePath)) {
331
- const gitignore = (0, node_fs_1.readFileSync)(gitignorePath, "utf8");
332
- if (!gitignore.includes(".env")) {
333
- ui.warn(".gitignore does not include .env — your secrets may be committed!");
334
- ui.hint("Add .env and wallet-*.txt to .gitignore");
335
- }
336
- if (!gitignore.includes("wallet-")) {
337
- ui.hint("Consider adding wallet-*.txt to .gitignore");
338
- }
339
- }
350
+ ensureGitignoreSafetyEntries();
340
351
  console.log("");
341
- console.log(` Next: ${ui.cyan("apow fund")}`);
342
- console.log(` ${ui.cyan("apow mint")}`);
343
- console.log(` ${ui.cyan("apow mine")}`);
352
+ console.log(` Next: ${ui.cyan("apow start")}`);
353
+ console.log(` ${ui.dim("Guided happy path: setup -> fund -> mint -> mine")}`);
344
354
  console.log("");
345
355
  }
346
356
  async function runStartFlow() {
@@ -422,17 +432,14 @@ async function runStartFlow() {
422
432
  return;
423
433
  }
424
434
  }
425
- const tokenId = await (0, mint_1.runMintFlow)({ startMiningAfterMint: false });
426
- if (!tokenId) {
427
- return;
428
- }
429
- console.log("");
430
- await (0, preflight_1.runPreflight)("mining");
431
- await (0, miner_1.startMining)(tokenId);
435
+ await (0, mint_1.runMintFlow)({ startMiningAfterMint: true });
432
436
  }
433
437
  async function main() {
434
438
  const version = readVersion();
435
- void (0, update_1.warnIfUpdateAvailable)(version);
439
+ const argv = process.argv.slice(2);
440
+ if (!shouldSkipUpdateCheck(argv)) {
441
+ void (0, update_1.warnIfUpdateAvailable)(version);
442
+ }
436
443
  const program = new commander_1.Command();
437
444
  // SIGINT handler
438
445
  process.on("SIGINT", async () => {
@@ -486,21 +493,59 @@ async function main() {
486
493
  program
487
494
  .command("mint")
488
495
  .description("Mint a new miner NFT (Easy Mode: x402 LLM, no API key)")
489
- .hook("preAction", async () => {
490
- await (0, preflight_1.runPreflight)("wallet");
491
- })
492
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");
493
508
  await (0, mint_1.runMintFlow)();
494
509
  });
495
510
  program
496
511
  .command("mine")
497
512
  .description("Start the mining loop (Easy Mode: remote x402 GPU)")
498
513
  .argument("[tokenId]", "Miner token ID (auto-detects if omitted)")
499
- .hook("preAction", async () => {
500
- await (0, preflight_1.runPreflight)("mining");
501
- })
502
514
  .action(async (tokenIdArg) => {
503
- 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
+ }
504
549
  await (0, miner_1.startMining)(tokenId);
505
550
  });
506
551
  program
@@ -556,9 +601,17 @@ async function main() {
556
601
  console.log(` ${ui.yellow(" it will be displayed. Anyone with this key")}`);
557
602
  console.log(` ${ui.yellow(" controls your funds.")}`);
558
603
  console.log("");
559
- const keyPath = saveKeyFile(acct.address, key);
560
- console.log(` ${ui.dim(`Key saved to: ${keyPath}`)}`);
561
- 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
+ }
562
615
  console.log("");
563
616
  console.log(` ${ui.dim("Import into Phantom, MetaMask, or any EVM wallet")}`);
564
617
  console.log(` ${ui.dim("to view your AGENT tokens and Mining Rig NFT.")}`);
@@ -593,27 +646,34 @@ async function main() {
593
646
  console.log(` Address: ${wallet_1.account.address}`);
594
647
  console.log(` Private Key: ${config_1.config.privateKey}`);
595
648
  console.log("");
596
- const filename = `wallet-${wallet_1.account.address}.txt`;
597
- const filepath = (0, node_path_1.join)(process.cwd(), filename);
598
- if (!(0, node_fs_1.existsSync)(filepath)) {
599
- const save = await ui.confirm("Save to file?");
600
- if (save) {
601
- const keyPath = saveKeyFile(wallet_1.account.address, config_1.config.privateKey);
602
- console.log(` ${ui.dim(`Saved to: ${keyPath}`)}`);
603
- console.log(` ${ui.yellow("Back up this file securely, then delete it.")}`);
604
- console.log("");
605
- }
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}`)}`);
606
655
  }
656
+ if (artifacts.keystorePath) {
657
+ console.log(` ${ui.dim(`Saved encrypted keystore: ${artifacts.keystorePath}`)}`);
658
+ }
659
+ console.log("");
607
660
  });
608
661
  walletCmd
609
662
  .command("fund")
610
663
  .description("Send ETH from your wallet to another address")
611
664
  .argument("<address>", "Destination address (0x-prefixed)")
612
665
  .argument("[amount]", "ETH amount to send (default: mint price + 0.003 ETH gas buffer)")
613
- .hook("preAction", async () => {
614
- await (0, preflight_1.runPreflight)("wallet");
615
- })
616
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
+ }
617
677
  if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
618
678
  ui.error("Invalid address format. Must be 0x + 40 hex characters.");
619
679
  return;
@@ -650,9 +710,11 @@ async function main() {
650
710
  ["Balance", `${Number((0, viem_1.formatEther)(senderBalance)).toFixed(6)} ETH`],
651
711
  ]);
652
712
  console.log("");
653
- if (senderBalance < amount) {
713
+ const requiredBalance = amount + TRANSFER_GAS_RESERVE_ETH;
714
+ if (senderBalance < requiredBalance) {
654
715
  ui.error("Insufficient ETH balance.");
655
- 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.`);
656
718
  return;
657
719
  }
658
720
  const proceed = await ui.confirm("Send ETH?");
@@ -771,14 +833,14 @@ async function main() {
771
833
  });
772
834
  dashboardCmd
773
835
  .command("scan [dir]")
774
- .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")
775
837
  .action((dir) => {
776
838
  const scanDir = dir ?? process.cwd();
777
839
  const { addresses, newCount } = detectWallets(scanDir);
778
840
  console.log("");
779
841
  if (addresses.length === 0) {
780
842
  console.log(` No wallets found in ${scanDir}`);
781
- 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")}`);
782
844
  }
783
845
  else {
784
846
  console.log(` ${ui.bold("Detected Wallets")} (${newCount} new, ${addresses.length} total)`);
@@ -833,26 +895,26 @@ function detectWallets(scanDir) {
833
895
  const existing = loadWallets(walletsPath);
834
896
  const seen = new Set(existing.map((a) => a.toLowerCase()));
835
897
  const detected = [];
836
- // Scan scanDir for wallet-0x*.txt files
898
+ // Scan scanDir for wallet-0x*.txt / .json files
837
899
  try {
838
900
  const entries = (0, node_fs_1.readdirSync)(scanDir, { withFileTypes: true });
839
901
  for (const entry of entries) {
840
902
  if (entry.isFile()) {
841
- const match = entry.name.match(/^wallet-(0x[0-9a-fA-F]{40})\.txt$/);
842
- if (match && !seen.has(match[1].toLowerCase())) {
843
- detected.push(match[1]);
844
- 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());
845
907
  }
846
908
  }
847
- // Scan rig*/wallet-0x*.txt subdirectories
909
+ // Scan rig*/wallet-0x* subdirectories
848
910
  if (entry.isDirectory() && entry.name.startsWith("rig")) {
849
911
  try {
850
912
  const rigFiles = (0, node_fs_1.readdirSync)((0, node_path_1.join)(scanDir, entry.name));
851
913
  for (const file of rigFiles) {
852
- const m = file.match(/^wallet-(0x[0-9a-fA-F]{40})\.txt$/);
853
- if (m && !seen.has(m[1].toLowerCase())) {
854
- detected.push(m[1]);
855
- 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());
856
918
  }
857
919
  }
858
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
  }
@@ -650,8 +664,13 @@ async function startMining(tokenId) {
650
664
  await new Promise((r) => setTimeout(r, 2000));
651
665
  }
652
666
  const delta = earnings - runningTotal;
653
- runningTotal = earnings;
654
- console.log(` ${ui.green("+")} ${(0, viem_1.formatEther)(delta)} AGENT | Total: ${(0, viem_1.formatEther)(earnings)} AGENT | Tx: ${ui.dim((0, explorer_1.txUrl)(txHash))}`);
667
+ if (delta > 0n) {
668
+ runningTotal = earnings;
669
+ console.log(` ${ui.green("+")} ${(0, viem_1.formatEther)(delta)} AGENT | Total: ${(0, viem_1.formatEther)(earnings)} AGENT | Tx: ${ui.dim((0, explorer_1.txUrl)(txHash))}`);
670
+ }
671
+ else {
672
+ console.log(` ${ui.green("+")} ~${(0, viem_1.formatEther)(estimatedReward)} AGENT ${ui.dim("(earnings sync pending)")} | Total: ${(0, viem_1.formatEther)(runningTotal)} AGENT | Tx: ${ui.dim((0, explorer_1.txUrl)(txHash))}`);
673
+ }
655
674
  console.log("");
656
675
  // Wait for block advancement before next iteration
657
676
  await waitForNextBlock(receipt.blockNumber);
package/dist/mint.js CHANGED
@@ -48,6 +48,7 @@ const ui = __importStar(require("./ui"));
48
48
  const wallet_1 = require("./wallet");
49
49
  const miningAgentAbi = MiningAgent_json_1.default;
50
50
  const ZERO_SEED = `0x${"0".repeat(64)}`;
51
+ const MINT_GAS_RESERVE_ETH = (0, viem_1.parseEther)("0.003");
51
52
  function deriveChallengeFromSeed(seed) {
52
53
  const bytes = (0, viem_1.hexToBytes)(seed);
53
54
  const firstNChars = 5 + (bytes[0] % 6);
@@ -128,12 +129,16 @@ async function runMintFlow(options = {}) {
128
129
  console.log("");
129
130
  ui.table([
130
131
  ["Mint price", `${(0, viem_1.formatEther)(mintPrice)} ETH`],
132
+ ["Gas reserve", `${(0, viem_1.formatEther)(MINT_GAS_RESERVE_ETH)} ETH (getChallenge + mint)`],
133
+ ["Required", `${(0, viem_1.formatEther)(mintPrice + MINT_GAS_RESERVE_ETH)} ETH total`],
131
134
  ["Balance", `${Number((0, viem_1.formatEther)(ethBalance)).toFixed(6)} ETH`],
132
135
  ]);
133
136
  console.log("");
134
- if (ethBalance < mintPrice) {
135
- ui.error("Insufficient ETH for mint.");
136
- ui.hint(`Send at least ${(0, viem_1.formatEther)(mintPrice)} ETH to ${account.address} on Base`);
137
+ const requiredBalance = mintPrice + MINT_GAS_RESERVE_ETH;
138
+ if (ethBalance < requiredBalance) {
139
+ ui.error("Insufficient ETH for mint and challenge gas.");
140
+ ui.hint(`Mint uses 2 transactions: getChallenge and mint.`);
141
+ ui.hint(`Send at least ${(0, viem_1.formatEther)(requiredBalance)} ETH to ${account.address} on Base.`);
137
142
  return null;
138
143
  }
139
144
  // Confirm before spending ETH
package/dist/preflight.js CHANGED
@@ -40,13 +40,16 @@ exports.runPreflight = runPreflight;
40
40
  const viem_1 = require("viem");
41
41
  const chains_1 = require("viem/chains");
42
42
  const AgentCoin_json_1 = __importDefault(require("./abi/AgentCoin.json"));
43
+ const MiningAgent_json_1 = __importDefault(require("./abi/MiningAgent.json"));
43
44
  const config_1 = require("./config");
44
45
  const grinder_http_1 = require("./grinder-http");
45
46
  const wallet_1 = require("./wallet");
46
47
  const ui = __importStar(require("./ui"));
47
48
  const agentCoinAbi = AgentCoin_json_1.default;
49
+ const miningAgentAbi = MiningAgent_json_1.default;
48
50
  const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
49
51
  const USDC_DECIMALS = 6;
52
+ const MINT_GAS_RESERVE_ETH = (0, viem_1.parseEther)("0.003");
50
53
  const erc20BalanceAbi = [
51
54
  {
52
55
  type: "function",
@@ -98,7 +101,7 @@ async function runPreflight(level) {
98
101
  results.push({
99
102
  label: "No USDC balance — QuickNode x402 requires USDC on Base",
100
103
  passed: false,
101
- fix: `Send USDC to ${wallet_1.account.address} on Base (~$10 covers ${config_1.config.llmProvider === "clawrouter" ? "RPC, LLM, and remote GPU grinding" : "~1M RPC calls"}). Run \`apow fund\` to bridge from Solana or Ethereum.`,
104
+ fix: `Send at least 2.00 USDC to ${wallet_1.account.address} on Base for x402 starting balance; add more if you want extra headroom. Run \`apow fund\` to bridge from Solana or Ethereum.`,
102
105
  });
103
106
  }
104
107
  else {
@@ -164,7 +167,28 @@ async function runPreflight(level) {
164
167
  try {
165
168
  const balance = await wallet_1.publicClient.getBalance({ address: wallet_1.account.address });
166
169
  const ethBalance = Number((0, viem_1.formatEther)(balance));
167
- if (ethBalance < 0.001) {
170
+ if (level === "wallet") {
171
+ const mintPrice = (await wallet_1.publicClient.readContract({
172
+ address: config_1.config.miningAgentAddress,
173
+ abi: miningAgentAbi,
174
+ functionName: "getMintPrice",
175
+ }));
176
+ const requiredBalance = mintPrice + MINT_GAS_RESERVE_ETH;
177
+ if (balance < requiredBalance) {
178
+ results.push({
179
+ label: `Mint-ready ETH balance (${ethBalance.toFixed(6)} ETH)`,
180
+ passed: false,
181
+ fix: `Mint needs ${(0, viem_1.formatEther)(mintPrice)} ETH for the rig plus ~${(0, viem_1.formatEther)(MINT_GAS_RESERVE_ETH)} ETH for the getChallenge and mint transactions. Send at least ${(0, viem_1.formatEther)(requiredBalance)} ETH to ${wallet_1.account.address} on Base.`,
182
+ });
183
+ }
184
+ else {
185
+ results.push({
186
+ label: `Mint-ready ETH balance (${ethBalance.toFixed(6)} ETH)`,
187
+ passed: true,
188
+ });
189
+ }
190
+ }
191
+ else if (ethBalance < 0.001) {
168
192
  results.push({
169
193
  label: `Low ETH balance (${ethBalance.toFixed(6)} ETH)`,
170
194
  passed: false,