apow-cli 0.11.0 → 0.11.2

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/config.js CHANGED
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.config = void 0;
7
7
  exports.resolveDefaultModel = resolveDefaultModel;
8
+ exports.reloadConfig = reloadConfig;
8
9
  exports.requirePrivateKey = requirePrivateKey;
9
10
  exports.requireLlmApiKey = requireLlmApiKey;
10
11
  exports.isExpensiveModel = isExpensiveModel;
@@ -86,37 +87,52 @@ function resolveLlmApiKey(provider) {
86
87
  default: return undefined;
87
88
  }
88
89
  }
89
- const chainName = resolveChainName();
90
- const useX402 = process.env.USE_X402 === "true";
91
- const resolvedProvider = normalizeProvider(process.env.LLM_PROVIDER, useX402);
92
- exports.config = {
93
- privateKey: parsePrivateKey(process.env.PRIVATE_KEY),
94
- rpcUrl: process.env.RPC_URL ?? "",
95
- useX402,
96
- llmProvider: resolvedProvider,
97
- llmApiKey: resolveLlmApiKey(resolvedProvider),
98
- llmModel: process.env.LLM_MODEL ?? resolveDefaultModel(resolvedProvider),
99
- ollamaUrl: process.env.OLLAMA_URL ?? DEFAULT_OLLAMA_URL,
100
- chain: chainName === "baseSepolia" ? chains_1.baseSepolia : chains_1.base,
101
- chainName,
102
- miningAgentAddress: parseAddress("MINING_AGENT_ADDRESS", DEFAULT_MINING_AGENT_ADDRESS),
103
- agentCoinAddress: parseAddress("AGENT_COIN_ADDRESS", DEFAULT_AGENT_COIN_ADDRESS),
104
- minerThreads: parseInt(process.env.MINER_THREADS ?? String(node_os_1.default.cpus().length), 10),
105
- grinderMode: (process.env.GRINDER_MODE === "js" ? "js" : "auto"),
106
- gpuGrinderPath: process.env.GPU_GRINDER_PATH,
107
- cpuGrinderPath: process.env.CPU_GRINDER_PATH,
108
- cudaGrinderPath: process.env.CUDA_GRINDER_PATH,
109
- vastIp: process.env.VAST_IP,
110
- vastPort: process.env.VAST_PORT,
111
- cpuGrinderThreads: parseInt(process.env.CPU_THREADS ?? String(node_os_1.default.cpus().length), 10),
112
- remoteGrinderPath: process.env.REMOTE_GRINDER ?? "/root/grinder-cuda",
113
- grindUrl: process.env.GRIND_URL,
114
- useX402Grind: process.env.USE_X402_GRIND !== undefined
90
+ function resolveStaleCheckIntervalMs() {
91
+ if (process.env.STALE_CHECK_INTERVAL) {
92
+ return parseInt(process.env.STALE_CHECK_INTERVAL, 10) * 1000;
93
+ }
94
+ return 10_000;
95
+ }
96
+ function buildConfig() {
97
+ const chainName = resolveChainName();
98
+ const useX402 = process.env.USE_X402 === "true";
99
+ const resolvedProvider = normalizeProvider(process.env.LLM_PROVIDER, useX402);
100
+ const useX402Grind = process.env.USE_X402_GRIND !== undefined
115
101
  ? process.env.USE_X402_GRIND === "true"
116
- : useX402, // defaults to USE_X402 value when not explicitly set
117
- allowLocalFallbackWithX402: process.env.ALLOW_LOCAL_FALLBACK_WITH_X402 === "true",
118
- staleCheckIntervalMs: parseInt(process.env.STALE_CHECK_INTERVAL ?? "60", 10) * 1000,
119
- };
102
+ : useX402;
103
+ const allowLocalFallbackWithX402 = process.env.ALLOW_LOCAL_FALLBACK_WITH_X402 === "true";
104
+ return {
105
+ privateKey: parsePrivateKey(process.env.PRIVATE_KEY),
106
+ rpcUrl: process.env.RPC_URL ?? "",
107
+ useX402,
108
+ llmProvider: resolvedProvider,
109
+ llmApiKey: resolveLlmApiKey(resolvedProvider),
110
+ llmModel: process.env.LLM_MODEL ?? resolveDefaultModel(resolvedProvider),
111
+ ollamaUrl: process.env.OLLAMA_URL ?? DEFAULT_OLLAMA_URL,
112
+ chain: chainName === "baseSepolia" ? chains_1.baseSepolia : chains_1.base,
113
+ chainName,
114
+ miningAgentAddress: parseAddress("MINING_AGENT_ADDRESS", DEFAULT_MINING_AGENT_ADDRESS),
115
+ agentCoinAddress: parseAddress("AGENT_COIN_ADDRESS", DEFAULT_AGENT_COIN_ADDRESS),
116
+ minerThreads: parseInt(process.env.MINER_THREADS ?? String(node_os_1.default.cpus().length), 10),
117
+ grinderMode: (process.env.GRINDER_MODE === "js" ? "js" : "auto"),
118
+ gpuGrinderPath: process.env.GPU_GRINDER_PATH,
119
+ cpuGrinderPath: process.env.CPU_GRINDER_PATH,
120
+ cudaGrinderPath: process.env.CUDA_GRINDER_PATH,
121
+ vastIp: process.env.VAST_IP,
122
+ vastPort: process.env.VAST_PORT,
123
+ cpuGrinderThreads: parseInt(process.env.CPU_THREADS ?? String(node_os_1.default.cpus().length), 10),
124
+ remoteGrinderPath: process.env.REMOTE_GRINDER ?? "/root/grinder-cuda",
125
+ grindUrl: process.env.GRIND_URL,
126
+ useX402Grind,
127
+ allowLocalFallbackWithX402,
128
+ staleCheckIntervalMs: resolveStaleCheckIntervalMs(),
129
+ };
130
+ }
131
+ exports.config = buildConfig();
132
+ function reloadConfig() {
133
+ exports.config = buildConfig();
134
+ return exports.config;
135
+ }
120
136
  function requirePrivateKey() {
121
137
  if (!exports.config.privateKey) {
122
138
  throw new Error("PRIVATE_KEY is required for minting and mining commands.");
@@ -145,4 +161,8 @@ async function writeEnvFile(values) {
145
161
  .map(([key, value]) => `${key}=${value}`)
146
162
  .join("\n");
147
163
  await (0, promises_1.writeFile)((0, node_path_1.join)(process.cwd(), ".env"), lines + "\n", "utf8");
164
+ for (const [key, value] of Object.entries(values)) {
165
+ process.env[key] = value;
166
+ }
167
+ reloadConfig();
148
168
  }
package/dist/detect.js CHANGED
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.rarityLabels = void 0;
7
+ exports.detectMinersWithClient = detectMinersWithClient;
7
8
  exports.detectMiners = detectMiners;
8
9
  exports.selectBestMiner = selectBestMiner;
9
10
  exports.formatHashpower = formatHashpower;
@@ -12,8 +13,8 @@ const config_1 = require("./config");
12
13
  const wallet_1 = require("./wallet");
13
14
  const miningAgentAbi = MiningAgent_json_1.default;
14
15
  exports.rarityLabels = ["Common", "Uncommon", "Rare", "Epic", "Mythic"];
15
- async function detectMiners(owner) {
16
- const balance = (await wallet_1.publicClient.readContract({
16
+ async function detectMinersWithClient(client, owner) {
17
+ const balance = (await client.readContract({
17
18
  address: config_1.config.miningAgentAddress,
18
19
  abi: miningAgentAbi,
19
20
  functionName: "balanceOf",
@@ -24,20 +25,20 @@ async function detectMiners(owner) {
24
25
  }
25
26
  const miners = [];
26
27
  for (let i = 0n; i < balance; i++) {
27
- const tokenId = (await wallet_1.publicClient.readContract({
28
+ const tokenId = (await client.readContract({
28
29
  address: config_1.config.miningAgentAddress,
29
30
  abi: miningAgentAbi,
30
31
  functionName: "tokenOfOwnerByIndex",
31
32
  args: [owner, i],
32
33
  }));
33
34
  const [rarityRaw, hashpowerRaw] = await Promise.all([
34
- wallet_1.publicClient.readContract({
35
+ client.readContract({
35
36
  address: config_1.config.miningAgentAddress,
36
37
  abi: miningAgentAbi,
37
38
  functionName: "rarity",
38
39
  args: [tokenId],
39
40
  }),
40
- wallet_1.publicClient.readContract({
41
+ client.readContract({
41
42
  address: config_1.config.miningAgentAddress,
42
43
  abi: miningAgentAbi,
43
44
  functionName: "hashpower",
@@ -54,6 +55,9 @@ async function detectMiners(owner) {
54
55
  }
55
56
  return miners;
56
57
  }
58
+ async function detectMiners(owner) {
59
+ return detectMinersWithClient(wallet_1.publicClient, owner);
60
+ }
57
61
  function selectBestMiner(miners) {
58
62
  return miners.reduce((best, m) => (m.hashpower > best.hashpower ? m : best));
59
63
  }
package/dist/errors.js CHANGED
@@ -70,7 +70,31 @@ const patterns = [
70
70
  }),
71
71
  },
72
72
  {
73
- test: (m) => /\b402\b/.test(m) || m.toLowerCase().includes("x402") || (m.toLowerCase().includes("insufficient") && m.toLowerCase().includes("usdc")),
73
+ test: (m) => m.includes("x402 GPU payment failed: insufficient USDC balance"),
74
+ classify: () => ({
75
+ category: "setup",
76
+ userMessage: "Insufficient USDC for x402 GPU grinding",
77
+ recovery: "Send USDC to your wallet on Base, or set USE_X402_GRIND=false to disable remote grinding",
78
+ }),
79
+ },
80
+ {
81
+ test: (m) => m.includes("x402 GPU payment failed: EVM simulation failed"),
82
+ classify: () => ({
83
+ category: "setup",
84
+ userMessage: "x402 GPU payment simulation failed",
85
+ recovery: "Check wallet state and USDC balance, then retry",
86
+ }),
87
+ },
88
+ {
89
+ test: (m) => m.includes("x402 GPU payment failed") || m.includes("No matching payment requirements"),
90
+ classify: () => ({
91
+ category: "transient",
92
+ userMessage: "x402 GPU payment failed",
93
+ recovery: "Retrying with a fresh payment session...",
94
+ }),
95
+ },
96
+ {
97
+ test: (m) => /\b402\b/.test(m) || m.includes("QuickNode x402") || (m.toLowerCase().includes("insufficient") && m.toLowerCase().includes("usdc")),
74
98
  classify: () => ({
75
99
  category: "transient",
76
100
  userMessage: "QuickNode x402 credit purchase failed — check USDC balance on Base",
@@ -125,14 +149,6 @@ const patterns = [
125
149
  recovery: "High difficulty — local grinders may still find a nonce.",
126
150
  }),
127
151
  },
128
- {
129
- test: (m) => m.includes("x402 GPU grind payment failed") || m.includes("No matching payment requirements"),
130
- classify: () => ({
131
- category: "setup",
132
- userMessage: "Insufficient USDC for x402 GPU grinding",
133
- recovery: "Send USDC to your wallet on Base, or set USE_X402_GRIND=false to disable remote grinding",
134
- }),
135
- },
136
152
  {
137
153
  test: (m) => m.includes("INSUFFICIENT_OUTPUT_AMOUNT") || m.includes("Too little received"),
138
154
  classify: () => ({
@@ -55,6 +55,23 @@ let _fetchWithPayment = null;
55
55
  function resetPaymentFetch() {
56
56
  _fetchWithPayment = null;
57
57
  }
58
+ function extractErrorDetail(body) {
59
+ if (!body)
60
+ return "";
61
+ try {
62
+ const parsed = JSON.parse(body);
63
+ if (typeof parsed.error === "string" && parsed.error.trim())
64
+ return parsed.error.trim();
65
+ if (typeof parsed.message === "string" && parsed.message.trim())
66
+ return parsed.message.trim();
67
+ if (body.trim() === "{}")
68
+ return "";
69
+ }
70
+ catch {
71
+ // plain text body
72
+ }
73
+ return body.trim();
74
+ }
58
75
  async function getPaymentFetch(privateKey) {
59
76
  if (_fetchWithPayment)
60
77
  return _fetchWithPayment;
@@ -93,6 +110,7 @@ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, p
93
110
  break;
94
111
  }
95
112
  const body = await response.text().catch(() => "");
113
+ const bodyDetail = extractErrorDetail(body);
96
114
  const paymentRequiredB64 = response.headers.get("payment-required");
97
115
  let reason = "";
98
116
  if (paymentRequiredB64) {
@@ -102,7 +120,7 @@ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, p
102
120
  }
103
121
  catch { /* ignore decode errors */ }
104
122
  }
105
- const combinedError = `${reason} ${body}`.trim();
123
+ const combinedError = `${reason} ${bodyDetail}`.trim();
106
124
  if (attempt === 1 && combinedError.includes("No matching payment requirements")) {
107
125
  resetPaymentFetch();
108
126
  continue;
@@ -115,13 +133,13 @@ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, p
115
133
  throw new Error(`x402 GPU payment failed: EVM simulation failed (USDC approval issue?) [${reason}]`);
116
134
  }
117
135
  else {
118
- throw new Error(`x402 GPU payment failed: ${reason || body.slice(0, 200) || "unknown"}`);
136
+ throw new Error(`x402 GPU payment failed: ${reason || bodyDetail.slice(0, 200) || "unknown"}`);
119
137
  }
120
138
  }
121
139
  if (response.status === 504) {
122
140
  throw new Error("Remote GPU grind timed out (120s)");
123
141
  }
124
- throw new Error(`GrindProxy HTTP ${response.status}: ${body.slice(0, 200)}`);
142
+ throw new Error(`GrindProxy HTTP ${response.status}: ${(bodyDetail || body).slice(0, 200)}`);
125
143
  }
126
144
  if (!response || !response.ok) {
127
145
  throw new Error("x402 GPU payment failed: no successful response");
package/dist/index.js CHANGED
@@ -44,6 +44,8 @@ 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");
47
49
  const detect_1 = require("./detect");
48
50
  const explorer_1 = require("./explorer");
49
51
  const fund_1 = require("./fund");
@@ -51,9 +53,19 @@ const mint_1 = require("./mint");
51
53
  const miner_1 = require("./miner");
52
54
  const preflight_1 = require("./preflight");
53
55
  const stats_1 = require("./stats");
56
+ const update_1 = require("./update");
54
57
  const ui = __importStar(require("./ui"));
55
58
  const wallet_1 = require("./wallet");
56
59
  const miningAgentAbi = MiningAgent_json_1.default;
60
+ const erc20BalanceAbi = [
61
+ {
62
+ type: "function",
63
+ name: "balanceOf",
64
+ inputs: [{ name: "account", type: "address" }],
65
+ outputs: [{ name: "", type: "uint256" }],
66
+ stateMutability: "view",
67
+ },
68
+ ];
57
69
  function saveKeyFile(address, privateKey) {
58
70
  const filename = `wallet-${address}.txt`;
59
71
  const filepath = (0, node_path_1.join)(process.cwd(), filename);
@@ -310,6 +322,8 @@ async function setupWizard() {
310
322
  }
311
323
  }
312
324
  await (0, config_1.writeEnvFile)(values);
325
+ (0, config_1.reloadConfig)();
326
+ (0, wallet_1.reinitClients)();
313
327
  ui.ok("Config saved to .env");
314
328
  // Check .gitignore
315
329
  const gitignorePath = (0, node_path_1.join)(process.cwd(), ".gitignore");
@@ -329,8 +343,96 @@ async function setupWizard() {
329
343
  console.log(` ${ui.cyan("apow mine")}`);
330
344
  console.log("");
331
345
  }
346
+ async function runStartFlow() {
347
+ if (!config_1.config.privateKey || !wallet_1.account) {
348
+ console.log("");
349
+ ui.warn("No wallet configured — launching setup.");
350
+ await setupWizard();
351
+ (0, config_1.reloadConfig)();
352
+ (0, wallet_1.reinitClients)();
353
+ }
354
+ if (!wallet_1.account) {
355
+ ui.error("Wallet configuration did not complete.");
356
+ return;
357
+ }
358
+ const bootstrapClient = config_1.config.useX402 && config_1.config.chainName === "base"
359
+ ? (0, viem_1.createPublicClient)({ chain: config_1.config.chain, transport: (0, viem_1.http)("https://1rpc.io/base") })
360
+ : wallet_1.publicClient;
361
+ console.log("");
362
+ ui.banner(["APoW Start"]);
363
+ console.log("");
364
+ let miners = [];
365
+ try {
366
+ miners = await (0, detect_1.detectMinersWithClient)(bootstrapClient, wallet_1.account.address);
367
+ }
368
+ catch {
369
+ ui.warn("Could not query wallet rigs via bootstrap RPC — continuing with funding guidance.");
370
+ }
371
+ if (miners.length > 0) {
372
+ const best = (0, detect_1.selectBestMiner)(miners);
373
+ console.log(` ${ui.green("Wallet ready.")} Found ${miners.length} rig${miners.length === 1 ? "" : "s"} — starting miner #${best.tokenId}.`);
374
+ console.log("");
375
+ await (0, preflight_1.runPreflight)("mining");
376
+ await (0, miner_1.startMining)(best.tokenId);
377
+ return;
378
+ }
379
+ let ethBalance = 0;
380
+ let usdcBalance = 0;
381
+ let balanceChecksAvailable = true;
382
+ try {
383
+ const [ethBalanceRaw, usdcBalanceRaw] = await Promise.all([
384
+ bootstrapClient.getBalance({ address: wallet_1.account.address }),
385
+ config_1.config.useX402
386
+ ? bootstrapClient.readContract({
387
+ address: config_1.config.chainName === "base" ? "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" : config_1.config.agentCoinAddress,
388
+ abi: erc20BalanceAbi,
389
+ functionName: "balanceOf",
390
+ args: [wallet_1.account.address],
391
+ })
392
+ : Promise.resolve(0n),
393
+ ]);
394
+ ethBalance = Number((0, viem_1.formatEther)(ethBalanceRaw));
395
+ usdcBalance = Number((0, viem_1.formatUnits)(usdcBalanceRaw, 6));
396
+ }
397
+ catch {
398
+ balanceChecksAvailable = false;
399
+ ui.warn("Could not query wallet balances via bootstrap RPC — funding flow may still be needed.");
400
+ }
401
+ const needsEth = !balanceChecksAvailable || ethBalance < constants_1.MIN_ETH;
402
+ const needsUsdc = config_1.config.useX402 && (!balanceChecksAvailable || usdcBalance < constants_1.MIN_USDC);
403
+ if (needsEth || needsUsdc) {
404
+ console.log(` ${ui.yellow("Funding needed before minting.")}`);
405
+ ui.table([
406
+ ["Wallet", `${wallet_1.account.address.slice(0, 6)}...${wallet_1.account.address.slice(-4)}`],
407
+ ["ETH", balanceChecksAvailable ? `${ethBalance.toFixed(6)} ETH${needsEth ? ` (need ≥${constants_1.MIN_ETH})` : ""}` : "unknown (RPC check failed)"],
408
+ ["USDC", config_1.config.useX402 ? (balanceChecksAvailable ? `${usdcBalance.toFixed(2)} USDC${needsUsdc ? ` (need ≥${constants_1.MIN_USDC})` : ""}` : "unknown (RPC check failed)") : "not required"],
409
+ ]);
410
+ console.log("");
411
+ const runFunding = await ui.confirm("Run funding flow now?");
412
+ if (!runFunding) {
413
+ ui.hint("Fund the wallet, then rerun `apow start`.");
414
+ return;
415
+ }
416
+ await (0, fund_1.runFundFlow)({});
417
+ const refreshedEth = Number((0, viem_1.formatEther)(await (0, wallet_1.getEthBalance)()));
418
+ const refreshedUsdc = config_1.config.useX402 ? Number((0, viem_1.formatUnits)(await (0, uniswap_1.getUsdcBalance)(wallet_1.account.address), 6)) : usdcBalance;
419
+ if (refreshedEth < constants_1.MIN_ETH || (config_1.config.useX402 && refreshedUsdc < constants_1.MIN_USDC)) {
420
+ ui.warn("Funding is still incomplete.");
421
+ ui.hint("Bridge or deposit may still be pending. Rerun `apow start` once balances update.");
422
+ return;
423
+ }
424
+ }
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);
432
+ }
332
433
  async function main() {
333
434
  const version = readVersion();
435
+ void (0, update_1.warnIfUpdateAvailable)(version);
334
436
  const program = new commander_1.Command();
335
437
  // SIGINT handler
336
438
  process.on("SIGINT", async () => {
@@ -355,6 +457,12 @@ async function main() {
355
457
  .action(async () => {
356
458
  await setupWizard();
357
459
  });
460
+ program
461
+ .command("start")
462
+ .description("Agent-first happy path: setup -> fund -> mint -> mine")
463
+ .action(async () => {
464
+ await runStartFlow();
465
+ });
358
466
  program
359
467
  .command("fund")
360
468
  .description("Fund your wallet — bridge from Solana/Ethereum or send on Base")
package/dist/miner.js CHANGED
@@ -39,6 +39,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.startMining = startMining;
40
40
  const viem_1 = require("viem");
41
41
  const node_fs_1 = require("node:fs");
42
+ const node_path_1 = require("node:path");
42
43
  const AgentCoin_json_1 = __importDefault(require("./abi/AgentCoin.json"));
43
44
  const MiningAgent_json_1 = __importDefault(require("./abi/MiningAgent.json"));
44
45
  const build_1 = require("./build");
@@ -67,6 +68,20 @@ function elapsedSeconds(start) {
67
68
  function sleep(ms) {
68
69
  return new Promise((resolve) => setTimeout(resolve, ms));
69
70
  }
71
+ function rejectOnAbort(signal) {
72
+ if (signal.aborted) {
73
+ const err = new Error("Aborted");
74
+ err.name = "AbortError";
75
+ return Promise.reject(err);
76
+ }
77
+ return new Promise((_, reject) => {
78
+ signal.addEventListener("abort", () => {
79
+ const err = new Error("Aborted");
80
+ err.name = "AbortError";
81
+ reject(err);
82
+ }, { once: true });
83
+ });
84
+ }
70
85
  function backoffMs(failures) {
71
86
  const base = Math.min(BASE_BACKOFF_MS * 2 ** (failures - 1), MAX_BACKOFF_MS);
72
87
  const jitter = Math.random() * base * 0.3;
@@ -148,6 +163,15 @@ function formatTime(seconds) {
148
163
  return `${(seconds / 60).toFixed(1)} min`;
149
164
  return `${(seconds / 3600).toFixed(1)} hr`;
150
165
  }
166
+ function readCliVersion() {
167
+ try {
168
+ const pkg = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(__dirname, "..", "package.json"), "utf8"));
169
+ return pkg.version ?? "0.1.0";
170
+ }
171
+ catch {
172
+ return "0.1.0";
173
+ }
174
+ }
151
175
  function autoBuildGrinders() {
152
176
  const sourceDir = (0, build_1.findSourceDir)();
153
177
  if (!sourceDir)
@@ -239,7 +263,8 @@ async function showStartupBanner(tokenId) {
239
263
  const era = totalMines / eraInterval;
240
264
  const supplyPct = Number(totalMinted * 10000n / mineableSupply) / 100;
241
265
  console.log("");
242
- ui.banner([`AgentCoin Miner v${config_1.config.chainName === "baseSepolia" ? "0.1.0-testnet" : "0.1.0"}`]);
266
+ const version = readCliVersion();
267
+ ui.banner([`AgentCoin Miner v${config_1.config.chainName === "baseSepolia" ? `${version}-testnet` : version}`]);
243
268
  ui.table([
244
269
  ["Wallet", `${account.address.slice(0, 6)}...${account.address.slice(-4)} (${Number((0, viem_1.formatEther)(ethBalance)).toFixed(4)} ETH)`],
245
270
  ["Miner", `#${tokenId} (${detect_1.rarityLabels[rarity] ?? `Tier ${rarity}`}, ${(0, detect_1.formatHashpower)(hashpower)})`],
@@ -445,7 +470,10 @@ async function startMining(tokenId) {
445
470
  // Race all available grinders — first valid nonce wins
446
471
  const grinders = [];
447
472
  if (useNative) {
448
- grinders.push((0, grinder_native_1.grindNonceNative)(challengeNumber, target, account.address, grinderInfo, abortController.signal)
473
+ grinders.push(Promise.race([
474
+ (0, grinder_native_1.grindNonceNative)(challengeNumber, target, account.address, grinderInfo, abortController.signal),
475
+ rejectOnAbort(abortController.signal),
476
+ ])
449
477
  .catch((err) => {
450
478
  if (abortController.signal.aborted)
451
479
  throw err;
@@ -456,11 +484,14 @@ async function startMining(tokenId) {
456
484
  else {
457
485
  console.log(` ${ui.dim(`Native grinder error: ${msg}`)}`);
458
486
  }
459
- return new Promise(() => { }); // hang forever (race will resolve via another grinder)
487
+ throw err;
460
488
  }));
461
489
  }
462
490
  if (useHttpGrind) {
463
- grinders.push((0, grinder_http_1.grindNonceHttp)(challengeNumber, target, account.address, grindUrl, config_1.config.privateKey, abortController.signal)
491
+ grinders.push(Promise.race([
492
+ (0, grinder_http_1.grindNonceHttp)(challengeNumber, target, account.address, grindUrl, config_1.config.privateKey, abortController.signal),
493
+ rejectOnAbort(abortController.signal),
494
+ ])
464
495
  .catch((err) => {
465
496
  if (abortController.signal.aborted)
466
497
  throw err;
@@ -477,24 +508,40 @@ async function startMining(tokenId) {
477
508
  else {
478
509
  console.log(` ${ui.dim(`x402 GPU grinder error: ${msg}`)}`);
479
510
  }
480
- return new Promise(() => { });
511
+ throw err;
481
512
  }));
482
513
  }
483
514
  // JS fallback is disabled by default when x402 grinding is active.
484
515
  if (useJsFallback) {
485
- grinders.push((0, grinder_1.grindNonceParallel)({
486
- challengeNumber,
487
- target,
488
- minerAddress: account.address,
489
- threads: config_1.config.minerThreads,
490
- signal: abortController.signal,
491
- onProgress: !useHttpGrind ? (attempts, hashrate) => {
492
- const khs = (hashrate / 1000).toFixed(0);
493
- nonceSpinner.update(`Grinding nonce (JS)... ${khs}k H/s (${attempts.toLocaleString()} attempts)`);
494
- } : undefined,
495
- }));
516
+ grinders.push(Promise.race([
517
+ (0, grinder_1.grindNonceParallel)({
518
+ challengeNumber,
519
+ target,
520
+ minerAddress: account.address,
521
+ threads: config_1.config.minerThreads,
522
+ signal: abortController.signal,
523
+ onProgress: !useHttpGrind ? (attempts, hashrate) => {
524
+ const khs = (hashrate / 1000).toFixed(0);
525
+ nonceSpinner.update(`Grinding nonce (JS)... ${khs}k H/s (${attempts.toLocaleString()} attempts)`);
526
+ } : undefined,
527
+ }),
528
+ rejectOnAbort(abortController.signal),
529
+ ]));
530
+ }
531
+ try {
532
+ grind = await Promise.any(grinders);
533
+ }
534
+ catch (err) {
535
+ if (err instanceof AggregateError && err.errors.length > 0) {
536
+ const firstNonAbort = err.errors.find((inner) => {
537
+ if (!(inner instanceof Error))
538
+ return true;
539
+ return inner.name !== "AbortError";
540
+ });
541
+ throw firstNonAbort ?? err.errors[0];
542
+ }
543
+ throw err;
496
544
  }
497
- grind = await Promise.race(grinders);
498
545
  const khs = grind.hashrate > 0 ? (grind.hashrate / 1000).toFixed(0) : "?";
499
546
  nonceSpinner.stop(`Nonce found (${grind.elapsed.toFixed(1)}s${grind.hashrate > 0 ? `, ${khs}k H/s` : ""})`);
500
547
  // Final stale check: a challenge can change between the periodic
@@ -587,7 +634,7 @@ async function startMining(tokenId) {
587
634
  }
588
635
  catch (error) {
589
636
  const classified = (0, errors_1.classifyError)(error);
590
- if (classified.category === "fatal") {
637
+ if (classified.category === "fatal" || classified.category === "setup") {
591
638
  ui.error(classified.userMessage);
592
639
  if (classified.recovery)
593
640
  ui.hint(classified.recovery);
package/dist/mint.js CHANGED
@@ -72,7 +72,7 @@ function deriveChallengeFromSeed(seed) {
72
72
  totalLength,
73
73
  ]);
74
74
  }
75
- async function runMintFlow() {
75
+ async function runMintFlow(options = {}) {
76
76
  const { account, walletClient } = (0, wallet_1.requireWallet)();
77
77
  console.log("");
78
78
  // 1-rig-per-wallet enforcement
@@ -111,7 +111,7 @@ async function runMintFlow() {
111
111
  ui.hint("One rig per wallet. Only one mine can succeed per block,");
112
112
  ui.hint("so extra rigs in the same wallet waste ETH.");
113
113
  ui.hint("To scale: apow wallet new → fund → apow mint");
114
- return;
114
+ return tokenId;
115
115
  }
116
116
  // Fetch mint price and balance FIRST
117
117
  const priceSpinner = ui.spinner("Fetching mint price...");
@@ -134,13 +134,13 @@ async function runMintFlow() {
134
134
  if (ethBalance < mintPrice) {
135
135
  ui.error("Insufficient ETH for mint.");
136
136
  ui.hint(`Send at least ${(0, viem_1.formatEther)(mintPrice)} ETH to ${account.address} on Base`);
137
- return;
137
+ return null;
138
138
  }
139
139
  // Confirm before spending ETH
140
140
  const proceed = await ui.confirm("Proceed with mint?");
141
141
  if (!proceed) {
142
142
  console.log(" Mint cancelled.");
143
- return;
143
+ return null;
144
144
  }
145
145
  console.log("");
146
146
  // Request challenge
@@ -227,8 +227,14 @@ async function runMintFlow() {
227
227
  console.log(` NFT: ${ui.dim((0, explorer_1.tokenUrl)(config_1.config.miningAgentAddress, tokenId))}`);
228
228
  console.log("");
229
229
  // Offer to start mining
230
- const startMine = await ui.confirm("Start mining?");
231
- if (startMine) {
230
+ if (options.startMiningAfterMint === true) {
232
231
  await (0, miner_1.startMining)(tokenId);
233
232
  }
233
+ else if (options.startMiningAfterMint !== false) {
234
+ const startMine = await ui.confirm("Start mining?");
235
+ if (startMine) {
236
+ await (0, miner_1.startMining)(tokenId);
237
+ }
238
+ }
239
+ return tokenId;
234
240
  }
package/dist/update.js ADDED
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.warnIfUpdateAvailable = warnIfUpdateAvailable;
40
+ const node_fs_1 = require("node:fs");
41
+ const node_os_1 = __importDefault(require("node:os"));
42
+ const node_path_1 = require("node:path");
43
+ const ui = __importStar(require("./ui"));
44
+ const CACHE_DIR = (0, node_path_1.join)(node_os_1.default.homedir(), ".apow");
45
+ const CACHE_PATH = (0, node_path_1.join)(CACHE_DIR, "latest-version.json");
46
+ const CACHE_TTL_MS = 12 * 60 * 60 * 1000;
47
+ const PACKAGE_NAME = "apow-cli";
48
+ function parseVersion(value) {
49
+ return value
50
+ .replace(/^v/, "")
51
+ .split(".")
52
+ .map((part) => parseInt(part, 10) || 0);
53
+ }
54
+ function isNewerVersion(latest, current) {
55
+ const a = parseVersion(latest);
56
+ const b = parseVersion(current);
57
+ const len = Math.max(a.length, b.length);
58
+ for (let i = 0; i < len; i += 1) {
59
+ const left = a[i] ?? 0;
60
+ const right = b[i] ?? 0;
61
+ if (left > right)
62
+ return true;
63
+ if (left < right)
64
+ return false;
65
+ }
66
+ return false;
67
+ }
68
+ function readCache() {
69
+ if (!(0, node_fs_1.existsSync)(CACHE_PATH))
70
+ return null;
71
+ try {
72
+ return JSON.parse((0, node_fs_1.readFileSync)(CACHE_PATH, "utf8"));
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
78
+ function writeCache(cache) {
79
+ try {
80
+ if (!(0, node_fs_1.existsSync)(CACHE_DIR)) {
81
+ (0, node_fs_1.mkdirSync)(CACHE_DIR, { recursive: true });
82
+ }
83
+ (0, node_fs_1.writeFileSync)(CACHE_PATH, JSON.stringify(cache), "utf8");
84
+ }
85
+ catch {
86
+ // cache is best-effort only
87
+ }
88
+ }
89
+ async function fetchLatestVersion() {
90
+ try {
91
+ const resp = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, {
92
+ signal: AbortSignal.timeout(2500),
93
+ });
94
+ if (!resp.ok)
95
+ return null;
96
+ const data = (await resp.json());
97
+ return data.version ?? null;
98
+ }
99
+ catch {
100
+ return null;
101
+ }
102
+ }
103
+ async function warnIfUpdateAvailable(currentVersion) {
104
+ const cached = readCache();
105
+ let latest = cached?.latest ?? null;
106
+ if (!cached || Date.now() - cached.checkedAt > CACHE_TTL_MS) {
107
+ const fresh = await fetchLatestVersion();
108
+ if (fresh) {
109
+ latest = fresh;
110
+ writeCache({ latest: fresh, checkedAt: Date.now() });
111
+ }
112
+ }
113
+ if (!latest || !isNewerVersion(latest, currentVersion)) {
114
+ return;
115
+ }
116
+ ui.warn(`Update available: apow-cli ${currentVersion} → ${latest}`);
117
+ ui.hint("Run: npm install -g apow-cli@latest");
118
+ ui.hint(`Or: npx apow-cli@${latest} <command>`);
119
+ }
package/dist/wallet.js CHANGED
@@ -16,7 +16,7 @@ function getTransport() {
16
16
  }
17
17
  return (0, viem_1.http)(config_1.config.rpcUrl);
18
18
  }
19
- const transport = getTransport();
19
+ let transport = getTransport();
20
20
  exports.publicClient = (0, viem_1.createPublicClient)({
21
21
  chain: config_1.config.chain,
22
22
  transport,
@@ -34,16 +34,19 @@ exports.walletClient = exports.account
34
34
  : null;
35
35
  /** Reinitialize clients after config changes (e.g., x402 fallback). */
36
36
  function reinitClients() {
37
- const t = getTransport();
38
- exports.publicClient = (0, viem_1.createPublicClient)({ chain: config_1.config.chain, transport: t });
39
- if (exports.account) {
40
- exports.walletClient = (0, viem_1.createWalletClient)({
37
+ transport = getTransport();
38
+ exports.account = config_1.config.privateKey
39
+ ? (0, accounts_1.privateKeyToAccount)(config_1.config.privateKey)
40
+ : null;
41
+ exports.publicClient = (0, viem_1.createPublicClient)({ chain: config_1.config.chain, transport });
42
+ exports.walletClient = exports.account
43
+ ? (0, viem_1.createWalletClient)({
41
44
  account: exports.account,
42
45
  chain: config_1.config.chain,
43
- transport: t,
46
+ transport,
44
47
  dataSuffix: DATA_SUFFIX,
45
- });
46
- }
48
+ })
49
+ : null;
47
50
  }
48
51
  function requireWallet() {
49
52
  if (!exports.account || !exports.walletClient) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apow-cli",
3
- "version": "0.11.0",
3
+ "version": "0.11.2",
4
4
  "description": "Mine AGENT tokens on Base L2 with Agentic Proof of Work",
5
5
  "keywords": [
6
6
  "apow",