apow-cli 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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: () => ({
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,34 @@ function elapsedSeconds(start) {
67
68
  function sleep(ms) {
68
69
  return new Promise((resolve) => setTimeout(resolve, ms));
69
70
  }
71
+ function withTimeout(promise, ms, label) {
72
+ return new Promise((resolve, reject) => {
73
+ const timer = setTimeout(() => {
74
+ reject(new Error(`${label} timed out after ${ms / 1000}s`));
75
+ }, ms);
76
+ promise.then((value) => {
77
+ clearTimeout(timer);
78
+ resolve(value);
79
+ }, (error) => {
80
+ clearTimeout(timer);
81
+ reject(error);
82
+ });
83
+ });
84
+ }
85
+ function rejectOnAbort(signal) {
86
+ if (signal.aborted) {
87
+ const err = new Error("Aborted");
88
+ err.name = "AbortError";
89
+ return Promise.reject(err);
90
+ }
91
+ return new Promise((_, reject) => {
92
+ signal.addEventListener("abort", () => {
93
+ const err = new Error("Aborted");
94
+ err.name = "AbortError";
95
+ reject(err);
96
+ }, { once: true });
97
+ });
98
+ }
70
99
  function backoffMs(failures) {
71
100
  const base = Math.min(BASE_BACKOFF_MS * 2 ** (failures - 1), MAX_BACKOFF_MS);
72
101
  const jitter = Math.random() * base * 0.3;
@@ -148,6 +177,22 @@ function formatTime(seconds) {
148
177
  return `${(seconds / 60).toFixed(1)} min`;
149
178
  return `${(seconds / 3600).toFixed(1)} hr`;
150
179
  }
180
+ async function readMiningChallenge(timeoutMs = 8_000) {
181
+ return withTimeout(wallet_1.publicClient.readContract({
182
+ address: config_1.config.agentCoinAddress,
183
+ abi: agentCoinAbi,
184
+ functionName: "getMiningChallenge",
185
+ }), timeoutMs, "Mining challenge refresh");
186
+ }
187
+ function readCliVersion() {
188
+ try {
189
+ const pkg = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(__dirname, "..", "package.json"), "utf8"));
190
+ return pkg.version ?? "0.1.0";
191
+ }
192
+ catch {
193
+ return "0.1.0";
194
+ }
195
+ }
151
196
  function autoBuildGrinders() {
152
197
  const sourceDir = (0, build_1.findSourceDir)();
153
198
  if (!sourceDir)
@@ -239,7 +284,8 @@ async function showStartupBanner(tokenId) {
239
284
  const era = totalMines / eraInterval;
240
285
  const supplyPct = Number(totalMinted * 10000n / mineableSupply) / 100;
241
286
  console.log("");
242
- ui.banner([`AgentCoin Miner v${config_1.config.chainName === "baseSepolia" ? "0.1.0-testnet" : "0.1.0"}`]);
287
+ const version = readCliVersion();
288
+ ui.banner([`AgentCoin Miner v${config_1.config.chainName === "baseSepolia" ? `${version}-testnet` : version}`]);
243
289
  ui.table([
244
290
  ["Wallet", `${account.address.slice(0, 6)}...${account.address.slice(-4)} (${Number((0, viem_1.formatEther)(ethBalance)).toFixed(4)} ETH)`],
245
291
  ["Miner", `#${tokenId} (${detect_1.rarityLabels[rarity] ?? `Tier ${rarity}`}, ${(0, detect_1.formatHashpower)(hashpower)})`],
@@ -292,11 +338,7 @@ async function startMining(tokenId) {
292
338
  await showStartupBanner(tokenId);
293
339
  console.log(` Grinder: ${ui.bold(modeLabel)}`);
294
340
  // Difficulty-aware preflight gate
295
- const preflight = (await wallet_1.publicClient.readContract({
296
- address: config_1.config.agentCoinAddress,
297
- abi: agentCoinAbi,
298
- functionName: "getMiningChallenge",
299
- }));
341
+ const preflight = await readMiningChallenge();
300
342
  const preflightTarget = preflight[1];
301
343
  const expectedHashes = preflightTarget > 0n ? (2n ** 256n) / preflightTarget : 0n;
302
344
  const estHashrate = estimateHashrate(grinderInfo, useNative, useHttpGrind);
@@ -395,11 +437,7 @@ async function startMining(tokenId) {
395
437
  }
396
438
  mineCount++;
397
439
  console.log(` ${ui.bold(`[Mine #${mineCount}]`)}`);
398
- const miningChallenge = (await wallet_1.publicClient.readContract({
399
- address: config_1.config.agentCoinAddress,
400
- abi: agentCoinAbi,
401
- functionName: "getMiningChallenge",
402
- }));
440
+ const miningChallenge = await readMiningChallenge();
403
441
  let [challengeNumber, target] = [miningChallenge[0], miningChallenge[1]];
404
442
  const smhl = (0, smhl_1.normalizeSmhlChallenge)(miningChallenge[2]);
405
443
  // Solve SMHL algorithmically (sub-millisecond)
@@ -424,28 +462,53 @@ async function startMining(tokenId) {
424
462
  const abortController = new AbortController();
425
463
  const nonceSpinner = ui.spinner(`Grinding nonce (${modeLabel})...`);
426
464
  // Background staleness checker
427
- const staleTimer = setInterval(async () => {
428
- try {
429
- const fresh = (await wallet_1.publicClient.readContract({
430
- address: config_1.config.agentCoinAddress,
431
- abi: agentCoinAbi,
432
- functionName: "getMiningChallenge",
433
- }));
434
- if (fresh[0] !== challengeNumber) {
435
- staleRestarts++;
436
- nonceSpinner.stop(`Challenge changed — restarting grind (stale #${staleRestarts})`);
437
- abortController.abort();
438
- }
439
- }
440
- catch {
441
- // RPC hiccup — don't abort, just skip this check
465
+ let staleTimer = null;
466
+ let staleCheckStopped = false;
467
+ let staleCheckInFlight = false;
468
+ const stopStaleChecks = () => {
469
+ staleCheckStopped = true;
470
+ if (staleTimer) {
471
+ clearTimeout(staleTimer);
472
+ staleTimer = null;
442
473
  }
443
- }, staleCheckMs);
474
+ };
475
+ const scheduleStaleCheck = () => {
476
+ if (staleCheckStopped || abortController.signal.aborted)
477
+ return;
478
+ staleTimer = setTimeout(async () => {
479
+ if (staleCheckStopped || abortController.signal.aborted || staleCheckInFlight) {
480
+ scheduleStaleCheck();
481
+ return;
482
+ }
483
+ staleCheckInFlight = true;
484
+ try {
485
+ const fresh = await readMiningChallenge(Math.min(staleCheckMs, 5_000));
486
+ if (fresh[0] !== challengeNumber && !abortController.signal.aborted) {
487
+ staleRestarts++;
488
+ nonceSpinner.stop(`Challenge changed — restarting grind (stale #${staleRestarts})`);
489
+ abortController.abort();
490
+ stopStaleChecks();
491
+ return;
492
+ }
493
+ }
494
+ catch {
495
+ // RPC hiccup — don't abort, just skip this check
496
+ }
497
+ finally {
498
+ staleCheckInFlight = false;
499
+ }
500
+ scheduleStaleCheck();
501
+ }, staleCheckMs);
502
+ };
503
+ scheduleStaleCheck();
444
504
  try {
445
505
  // Race all available grinders — first valid nonce wins
446
506
  const grinders = [];
447
507
  if (useNative) {
448
- grinders.push((0, grinder_native_1.grindNonceNative)(challengeNumber, target, account.address, grinderInfo, abortController.signal)
508
+ grinders.push(Promise.race([
509
+ (0, grinder_native_1.grindNonceNative)(challengeNumber, target, account.address, grinderInfo, abortController.signal),
510
+ rejectOnAbort(abortController.signal),
511
+ ])
449
512
  .catch((err) => {
450
513
  if (abortController.signal.aborted)
451
514
  throw err;
@@ -460,7 +523,10 @@ async function startMining(tokenId) {
460
523
  }));
461
524
  }
462
525
  if (useHttpGrind) {
463
- grinders.push((0, grinder_http_1.grindNonceHttp)(challengeNumber, target, account.address, grindUrl, config_1.config.privateKey, abortController.signal)
526
+ grinders.push(Promise.race([
527
+ (0, grinder_http_1.grindNonceHttp)(challengeNumber, target, account.address, grindUrl, config_1.config.privateKey, abortController.signal),
528
+ rejectOnAbort(abortController.signal),
529
+ ])
464
530
  .catch((err) => {
465
531
  if (abortController.signal.aborted)
466
532
  throw err;
@@ -482,17 +548,20 @@ async function startMining(tokenId) {
482
548
  }
483
549
  // JS fallback is disabled by default when x402 grinding is active.
484
550
  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
- }));
551
+ grinders.push(Promise.race([
552
+ (0, grinder_1.grindNonceParallel)({
553
+ challengeNumber,
554
+ target,
555
+ minerAddress: account.address,
556
+ threads: config_1.config.minerThreads,
557
+ signal: abortController.signal,
558
+ onProgress: !useHttpGrind ? (attempts, hashrate) => {
559
+ const khs = (hashrate / 1000).toFixed(0);
560
+ nonceSpinner.update(`Grinding nonce (JS)... ${khs}k H/s (${attempts.toLocaleString()} attempts)`);
561
+ } : undefined,
562
+ }),
563
+ rejectOnAbort(abortController.signal),
564
+ ]));
496
565
  }
497
566
  try {
498
567
  grind = await Promise.any(grinders);
@@ -512,11 +581,7 @@ async function startMining(tokenId) {
512
581
  nonceSpinner.stop(`Nonce found (${grind.elapsed.toFixed(1)}s${grind.hashrate > 0 ? `, ${khs}k H/s` : ""})`);
513
582
  // Final stale check: a challenge can change between the periodic
514
583
  // poll and transaction submission, which would make the SMHL stale.
515
- const latestChallenge = (await wallet_1.publicClient.readContract({
516
- address: config_1.config.agentCoinAddress,
517
- abi: agentCoinAbi,
518
- functionName: "getMiningChallenge",
519
- }));
584
+ const latestChallenge = await readMiningChallenge();
520
585
  if (latestChallenge[0] !== challengeNumber) {
521
586
  staleRestarts++;
522
587
  [challengeNumber, target] = [latestChallenge[0], latestChallenge[1]];
@@ -528,14 +593,10 @@ async function startMining(tokenId) {
528
593
  }
529
594
  }
530
595
  catch (err) {
531
- clearInterval(staleTimer);
596
+ stopStaleChecks();
532
597
  if (abortController.signal.aborted) {
533
598
  // Challenge went stale — re-fetch and retry
534
- const freshChallenge = (await wallet_1.publicClient.readContract({
535
- address: config_1.config.agentCoinAddress,
536
- abi: agentCoinAbi,
537
- functionName: "getMiningChallenge",
538
- }));
599
+ const freshChallenge = await readMiningChallenge();
539
600
  [challengeNumber, target] = [freshChallenge[0], freshChallenge[1]];
540
601
  const freshSmhl = (0, smhl_1.normalizeSmhlChallenge)(freshChallenge[2]);
541
602
  smhlSolution = (0, smhl_1.solveSmhlAlgorithmic)(freshSmhl);
@@ -551,7 +612,7 @@ async function startMining(tokenId) {
551
612
  throw err; // non-abort error — propagate
552
613
  }
553
614
  finally {
554
- clearInterval(staleTimer);
615
+ stopStaleChecks();
555
616
  }
556
617
  }
557
618
  // Submit transaction with spinner
@@ -600,7 +661,7 @@ async function startMining(tokenId) {
600
661
  }
601
662
  catch (error) {
602
663
  const classified = (0, errors_1.classifyError)(error);
603
- if (classified.category === "fatal") {
664
+ if (classified.category === "fatal" || classified.category === "setup") {
604
665
  ui.error(classified.userMessage);
605
666
  if (classified.recovery)
606
667
  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.1",
3
+ "version": "0.11.3",
4
4
  "description": "Mine AGENT tokens on Base L2 with Agentic Proof of Work",
5
5
  "keywords": [
6
6
  "apow",