apow-cli 0.9.4 → 0.10.0

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/build.js CHANGED
@@ -47,13 +47,19 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
47
47
  return (mod && mod.__esModule) ? mod : { "default": mod };
48
48
  };
49
49
  Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.INSTALL_DIR = void 0;
51
+ exports.findSourceDir = findSourceDir;
52
+ exports.which = which;
53
+ exports.buildCpuC = buildCpuC;
54
+ exports.buildCuda = buildCuda;
55
+ exports.buildMetal = buildMetal;
50
56
  exports.buildGrinders = buildGrinders;
51
57
  const node_child_process_1 = require("node:child_process");
52
58
  const node_fs_1 = require("node:fs");
53
59
  const node_path_1 = require("node:path");
54
60
  const node_os_1 = __importDefault(require("node:os"));
55
61
  const ui = __importStar(require("./ui"));
56
- const INSTALL_DIR = (0, node_path_1.join)(node_os_1.default.homedir(), ".apow");
62
+ exports.INSTALL_DIR = (0, node_path_1.join)(node_os_1.default.homedir(), ".apow");
57
63
  function findSourceDir() {
58
64
  // Check relative to this file's compiled location (dist/)
59
65
  const fromDist = (0, node_path_1.join)((0, node_path_1.dirname)(__dirname), "local", "gpu");
@@ -91,7 +97,7 @@ function detectCudaArch() {
91
97
  }
92
98
  function buildCpuC(sourceDir) {
93
99
  const src = (0, node_path_1.join)(sourceDir, "grinder-cpu.c");
94
- const out = (0, node_path_1.join)(INSTALL_DIR, "grinder-cpu");
100
+ const out = (0, node_path_1.join)(exports.INSTALL_DIR, "grinder-cpu");
95
101
  const name = "CPU-C";
96
102
  if (!(0, node_fs_1.existsSync)(src)) {
97
103
  return { name, success: false, error: "source file not found" };
@@ -116,7 +122,7 @@ function buildCpuC(sourceDir) {
116
122
  }
117
123
  function buildCuda(sourceDir, archOverride) {
118
124
  const src = (0, node_path_1.join)(sourceDir, "grinder-cuda.cu");
119
- const out = (0, node_path_1.join)(INSTALL_DIR, "grinder-cuda");
125
+ const out = (0, node_path_1.join)(exports.INSTALL_DIR, "grinder-cuda");
120
126
  const name = "CUDA";
121
127
  if (!(0, node_fs_1.existsSync)(src)) {
122
128
  return { name, success: false, error: "source file not found" };
@@ -137,7 +143,7 @@ function buildCuda(sourceDir, archOverride) {
137
143
  }
138
144
  function buildMetal(sourceDir) {
139
145
  const src = (0, node_path_1.join)(sourceDir, "grinder.m");
140
- const out = (0, node_path_1.join)(INSTALL_DIR, "grinder-gpu");
146
+ const out = (0, node_path_1.join)(exports.INSTALL_DIR, "grinder-gpu");
141
147
  const name = "Metal GPU";
142
148
  if (process.platform !== "darwin") {
143
149
  return { name, success: false, error: "macOS only" };
@@ -154,7 +160,7 @@ function buildMetal(sourceDir) {
154
160
  // Copy Metal shader alongside binary — grinder loads it at runtime from CWD
155
161
  const shader = (0, node_path_1.join)(sourceDir, "keccak.metal");
156
162
  if ((0, node_fs_1.existsSync)(shader)) {
157
- (0, node_fs_1.copyFileSync)(shader, (0, node_path_1.join)(INSTALL_DIR, "keccak.metal"));
163
+ (0, node_fs_1.copyFileSync)(shader, (0, node_path_1.join)(exports.INSTALL_DIR, "keccak.metal"));
158
164
  }
159
165
  return { name, success: true, path: out };
160
166
  }
@@ -176,10 +182,10 @@ async function buildGrinders(opts) {
176
182
  }
177
183
  console.log(` Source: ${ui.dim(sourceDir)}`);
178
184
  // Create install directory
179
- if (!(0, node_fs_1.existsSync)(INSTALL_DIR)) {
180
- (0, node_fs_1.mkdirSync)(INSTALL_DIR, { recursive: true });
185
+ if (!(0, node_fs_1.existsSync)(exports.INSTALL_DIR)) {
186
+ (0, node_fs_1.mkdirSync)(exports.INSTALL_DIR, { recursive: true });
181
187
  }
182
- console.log(` Install: ${ui.dim(INSTALL_DIR)}`);
188
+ console.log(` Install: ${ui.dim(exports.INSTALL_DIR)}`);
183
189
  console.log("");
184
190
  // Build each grinder
185
191
  const results = [];
package/dist/config.js CHANGED
@@ -114,6 +114,7 @@ exports.config = {
114
114
  useX402Grind: process.env.USE_X402_GRIND !== undefined
115
115
  ? process.env.USE_X402_GRIND === "true"
116
116
  : useX402, // defaults to USE_X402 value when not explicitly set
117
+ staleCheckIntervalMs: parseInt(process.env.STALE_CHECK_INTERVAL ?? "60", 10) * 1000,
117
118
  };
118
119
  function requirePrivateKey() {
119
120
  if (!exports.config.privateKey) {
@@ -86,7 +86,7 @@ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, p
86
86
  if (!response.ok) {
87
87
  const body = await response.text().catch(() => "");
88
88
  if (response.status === 402) {
89
- throw new Error("x402 GPU grind payment failed — insufficient USDC on Base");
89
+ throw new Error(`x402 GPU payment failed (402): ${body.slice(0, 300) || "no response body"}`);
90
90
  }
91
91
  if (response.status === 504) {
92
92
  throw new Error("Remote GPU grind timed out (90s)");
package/dist/grinder.js CHANGED
@@ -3,7 +3,43 @@
3
3
  * Multi-threaded nonce grinding via worker_threads.
4
4
  * Spawns N workers that search different nonce ranges in parallel.
5
5
  * First worker to find a valid nonce wins; all others are terminated.
6
+ *
7
+ * Uses raw buffer operations + @noble/hashes for ~5-15x speedup over
8
+ * the previous viem encodePacked/keccak256 approach.
6
9
  */
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ var desc = Object.getOwnPropertyDescriptor(m, k);
13
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
+ desc = { enumerable: true, get: function() { return m[k]; } };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }) : (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ o[k2] = m[k];
20
+ }));
21
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
22
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
23
+ }) : function(o, v) {
24
+ o["default"] = v;
25
+ });
26
+ var __importStar = (this && this.__importStar) || (function () {
27
+ var ownKeys = function(o) {
28
+ ownKeys = Object.getOwnPropertyNames || function (o) {
29
+ var ar = [];
30
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
+ return ar;
32
+ };
33
+ return ownKeys(o);
34
+ };
35
+ return function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
42
+ })();
7
43
  var __importDefault = (this && this.__importDefault) || function (mod) {
8
44
  return (mod && mod.__esModule) ? mod : { "default": mod };
9
45
  };
@@ -11,33 +47,74 @@ Object.defineProperty(exports, "__esModule", { value: true });
11
47
  exports.grindNonceParallel = grindNonceParallel;
12
48
  const node_worker_threads_1 = require("node:worker_threads");
13
49
  const node_os_1 = __importDefault(require("node:os"));
14
- const viem_1 = require("viem");
50
+ function hexToBytes(hex) {
51
+ const h = hex.startsWith("0x") ? hex.slice(2) : hex;
52
+ const bytes = new Uint8Array(h.length / 2);
53
+ for (let i = 0; i < bytes.length; i++) {
54
+ bytes[i] = parseInt(h.substring(i * 2, i * 2 + 2), 16);
55
+ }
56
+ return bytes;
57
+ }
15
58
  // ── Worker thread logic ──────────────────────────────────────────────
16
59
  if (!node_worker_threads_1.isMainThread && node_worker_threads_1.parentPort) {
17
- const params = node_worker_threads_1.workerData;
18
- const target = BigInt(params.targetHex);
19
- let nonce = BigInt(params.startNonce);
20
- let attempts = 0n;
21
- const reportInterval = 50000n;
22
- while (true) {
23
- const digest = BigInt((0, viem_1.keccak256)((0, viem_1.encodePacked)(["bytes32", "address", "uint256"], [params.challengeNumber, params.minerAddress, nonce])));
24
- attempts += 1n;
25
- if (digest < target) {
26
- node_worker_threads_1.parentPort.postMessage({
27
- type: "found",
28
- nonce: nonce.toString(),
29
- attempts: attempts.toString(),
30
- });
31
- break;
32
- }
33
- if (attempts % reportInterval === 0n) {
34
- node_worker_threads_1.parentPort.postMessage({
35
- type: "progress",
36
- attempts: attempts.toString(),
37
- });
60
+ // Dynamic import inside worker to avoid loading at module level in main thread
61
+ Promise.resolve().then(() => __importStar(require("@noble/hashes/sha3"))).then(({ keccak_256 }) => {
62
+ const params = node_worker_threads_1.workerData;
63
+ // Pre-allocate the 84-byte input buffer: challenge[32] + address[20] + nonce[32]
64
+ // Layout matches Solidity encodePacked(bytes32, address, uint256)
65
+ const buf = new Uint8Array(84);
66
+ const view = new DataView(buf.buffer);
67
+ // Fill challenge (bytes 0-31) and address (bytes 32-51) once
68
+ const challengeBytes = hexToBytes(params.challengeNumber);
69
+ const addressBytes = hexToBytes(params.minerAddress);
70
+ buf.set(challengeBytes, 0);
71
+ buf.set(addressBytes, 32);
72
+ // Zero the nonce high bytes (bytes 52-75) — we only use low 8 bytes
73
+ buf.fill(0, 52, 76);
74
+ // Convert target to raw bytes for byte-by-byte comparison
75
+ const targetBytes = hexToBytes(params.targetHex.length === 66 ? params.targetHex : "0x" + BigInt(params.targetHex).toString(16).padStart(64, "0"));
76
+ let nonce = Number(params.startNonce);
77
+ let attempts = 0;
78
+ const reportInterval = 100_000;
79
+ while (true) {
80
+ // Write nonce as big-endian uint64 at bytes 76-83
81
+ // (high 24 bytes of the uint256 nonce slot are zeros — fine for the
82
+ // search space we need; Number.MAX_SAFE_INTEGER = 2^53 which is plenty)
83
+ view.setUint32(76, (nonce / 0x100000000) >>> 0, false);
84
+ view.setUint32(80, nonce >>> 0, false);
85
+ // Hash with raw Keccak-256 (returns Uint8Array, no allocations)
86
+ const hash = keccak_256(buf);
87
+ attempts++;
88
+ // Byte-by-byte comparison: hash < target means valid nonce
89
+ let found = false;
90
+ for (let i = 0; i < 32; i++) {
91
+ if (hash[i] < targetBytes[i]) {
92
+ found = true;
93
+ break;
94
+ }
95
+ if (hash[i] > targetBytes[i]) {
96
+ break;
97
+ }
98
+ }
99
+ if (found) {
100
+ // Convert nonce back to BigInt string for the main thread
101
+ const nonceBigInt = BigInt(nonce);
102
+ node_worker_threads_1.parentPort.postMessage({
103
+ type: "found",
104
+ nonce: nonceBigInt.toString(),
105
+ attempts: String(attempts),
106
+ });
107
+ break;
108
+ }
109
+ if (attempts % reportInterval === 0) {
110
+ node_worker_threads_1.parentPort.postMessage({
111
+ type: "progress",
112
+ attempts: String(attempts),
113
+ });
114
+ }
115
+ nonce++;
38
116
  }
39
- nonce += 1n;
40
- }
117
+ });
41
118
  }
42
119
  // ── Main thread: spawn workers, collect results ──────────────────────
43
120
  async function grindNonceParallel(params) {
@@ -77,7 +154,7 @@ async function grindNonceParallel(params) {
77
154
  const worker = new node_worker_threads_1.Worker(__filename, {
78
155
  workerData: {
79
156
  challengeNumber: params.challengeNumber,
80
- targetHex: params.target.toString(),
157
+ targetHex: "0x" + params.target.toString(16).padStart(64, "0"),
81
158
  minerAddress: params.minerAddress,
82
159
  startNonce: startNonce.toString(),
83
160
  },
package/dist/miner.js CHANGED
@@ -38,8 +38,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.startMining = startMining;
40
40
  const viem_1 = require("viem");
41
+ const node_fs_1 = require("node:fs");
41
42
  const AgentCoin_json_1 = __importDefault(require("./abi/AgentCoin.json"));
42
43
  const MiningAgent_json_1 = __importDefault(require("./abi/MiningAgent.json"));
44
+ const build_1 = require("./build");
43
45
  const config_1 = require("./config");
44
46
  const detect_1 = require("./detect");
45
47
  const errors_1 = require("./errors");
@@ -96,6 +98,85 @@ async function waitForNextBlock(lastMineBlock) {
96
98
  }
97
99
  throw new Error("Timed out waiting for next block (60s)");
98
100
  }
101
+ function estimateHashrate(grinderInfo, useNative, useHttpGrind) {
102
+ if (useHttpGrind)
103
+ return 20_000_000_000; // 20 GH/s
104
+ if (!useNative)
105
+ return 25_000_000; // 25 MH/s (optimized JS)
106
+ let rate = 0;
107
+ if (grinderInfo.gpu)
108
+ rate += 500_000_000; // 500 MH/s Metal
109
+ if (grinderInfo.cpu)
110
+ rate += 300_000_000; // 300 MH/s CPU-C
111
+ if (grinderInfo.cuda)
112
+ rate += 20_000_000_000; // 20 GH/s local CUDA
113
+ if (grinderInfo.remoteGpu)
114
+ rate += 20_000_000_000; // 20 GH/s remote CUDA
115
+ return rate || 25_000_000;
116
+ }
117
+ function formatRate(rate) {
118
+ if (rate >= 1_000_000_000)
119
+ return `${(rate / 1_000_000_000).toFixed(1)} GH/s`;
120
+ if (rate >= 1_000_000)
121
+ return `${(rate / 1_000_000).toFixed(0)} MH/s`;
122
+ return `${(rate / 1_000).toFixed(0)} kH/s`;
123
+ }
124
+ function formatExpectedHashes(n) {
125
+ if (n >= 1000000000n)
126
+ return `${Number(n / 1000000000n)}G`;
127
+ if (n >= 1000000n)
128
+ return `${Number(n / 1000000n)}M`;
129
+ if (n >= 1000n)
130
+ return `${Number(n / 1000n)}K`;
131
+ return String(n);
132
+ }
133
+ function difficultyBits(target) {
134
+ if (target === 0n)
135
+ return 256;
136
+ let bits = 0;
137
+ let t = (2n ** 256n - 1n) / target;
138
+ while (t > 1n) {
139
+ bits++;
140
+ t >>= 1n;
141
+ }
142
+ return bits;
143
+ }
144
+ function formatTime(seconds) {
145
+ if (seconds < 60)
146
+ return `${seconds.toFixed(0)}s`;
147
+ if (seconds < 3600)
148
+ return `${(seconds / 60).toFixed(1)} min`;
149
+ return `${(seconds / 3600).toFixed(1)} hr`;
150
+ }
151
+ function autoBuildGrinders() {
152
+ const sourceDir = (0, build_1.findSourceDir)();
153
+ if (!sourceDir)
154
+ return false;
155
+ console.log(` ${ui.dim("Native grinders not found — auto-building (first mine only)...")}`);
156
+ if (!(0, node_fs_1.existsSync)(build_1.INSTALL_DIR)) {
157
+ (0, node_fs_1.mkdirSync)(build_1.INSTALL_DIR, { recursive: true });
158
+ }
159
+ let built = 0;
160
+ const cpuResult = (0, build_1.buildCpuC)(sourceDir);
161
+ if (cpuResult.success) {
162
+ console.log(` ${ui.green("CPU-C")} grinder built → ${ui.dim(cpuResult.path)}`);
163
+ built++;
164
+ }
165
+ if (process.platform === "darwin") {
166
+ const metalResult = (0, build_1.buildMetal)(sourceDir);
167
+ if (metalResult.success) {
168
+ console.log(` ${ui.green("Metal GPU")} grinder built → ${ui.dim(metalResult.path)}`);
169
+ built++;
170
+ }
171
+ }
172
+ if (built > 0) {
173
+ console.log(` ${ui.green("Native grinders built!")} Re-detecting...`);
174
+ }
175
+ else {
176
+ console.log(` ${ui.dim("Auto-build failed (no C compiler). Install Xcode CLI tools or gcc, then run: apow build-grinders")}`);
177
+ }
178
+ return built > 0;
179
+ }
99
180
  async function grindNonce(challengeNumber, target, minerAddress, onProgress) {
100
181
  let nonce = 0n;
101
182
  let attempts = 0n;
@@ -173,11 +254,19 @@ async function startMining(tokenId) {
173
254
  let consecutiveFailures = 0;
174
255
  let mineCount = 0;
175
256
  let runningTotal = 0n;
176
- // Detect native grinders once at startup
177
- const grinderInfo = (0, grinder_native_1.detectGrinders)();
178
- const useNative = config_1.config.grinderMode !== "js" && (0, grinder_native_1.hasNativeGrinders)(grinderInfo);
257
+ // Detect native grinders — auto-build if none found
258
+ let grinderInfo = (0, grinder_native_1.detectGrinders)();
259
+ let useNative = config_1.config.grinderMode !== "js" && !!(grinderInfo.gpu || grinderInfo.cuda || grinderInfo.cpu || grinderInfo.remoteGpu);
179
260
  const useHttpGrind = (0, grinder_http_1.isHttpGrinderConfigured)();
180
261
  const grindUrl = (0, grinder_http_1.getGrindUrl)();
262
+ // Auto-build native grinders on first mine if none detected
263
+ if (!useNative && !useHttpGrind && config_1.config.grinderMode !== "js") {
264
+ const built = autoBuildGrinders();
265
+ if (built) {
266
+ grinderInfo = (0, grinder_native_1.detectGrinders)();
267
+ useNative = !!(grinderInfo.gpu || grinderInfo.cuda || grinderInfo.cpu || grinderInfo.remoteGpu);
268
+ }
269
+ }
181
270
  // Build grinder label
182
271
  const labelParts = [];
183
272
  if (useNative)
@@ -188,12 +277,55 @@ async function startMining(tokenId) {
188
277
  }
189
278
  if (labelParts.length === 0)
190
279
  labelParts.push(`JS (${config_1.config.minerThreads} threads)`);
191
- const modeLabel = labelParts.join(" + ");
280
+ let modeLabel = labelParts.join(" + ");
192
281
  await showStartupBanner(tokenId);
193
282
  console.log(` Grinder: ${ui.bold(modeLabel)}`);
194
- // Hint for JS-only miners without x402 grind
195
- if (!useNative && !useHttpGrind) {
196
- console.log(` ${ui.dim("Tip: Add USE_X402_GRIND=true for 10-100x faster mining (~$0.006/grind).")}`);
283
+ // Difficulty-aware preflight gate
284
+ const preflight = (await wallet_1.publicClient.readContract({
285
+ address: config_1.config.agentCoinAddress,
286
+ abi: agentCoinAbi,
287
+ functionName: "getMiningChallenge",
288
+ }));
289
+ const preflightTarget = preflight[1];
290
+ const expectedHashes = preflightTarget > 0n ? (2n ** 256n) / preflightTarget : 0n;
291
+ const estHashrate = estimateHashrate(grinderInfo, useNative, useHttpGrind);
292
+ const estimatedSeconds = expectedHashes > 0n ? Number(expectedHashes) / estHashrate : 0;
293
+ const bits = difficultyBits(preflightTarget);
294
+ const staleCheckSeconds = config_1.config.staleCheckIntervalMs / 1000;
295
+ console.log(` Difficulty: 2^${bits} (~${formatExpectedHashes(expectedHashes)} hashes expected)`);
296
+ console.log(` Est. speed: ${formatRate(estHashrate)} (${modeLabel})`);
297
+ console.log(` Est. time: ~${formatTime(estimatedSeconds)} per mine`);
298
+ if (estimatedSeconds > 300) {
299
+ console.log("");
300
+ ui.warn(`Your grinder (~${formatRate(estHashrate)}) is far too slow for current difficulty.`);
301
+ console.log(` Expected time per mine: ~${formatTime(estimatedSeconds)} (challenges go stale every ${staleCheckSeconds}s).`);
302
+ console.log("");
303
+ console.log(` Fix options:`);
304
+ console.log(` 1. Run ${ui.cyan("apow build-grinders")} for 100x faster local mining (~500 MH/s)`);
305
+ console.log(` 2. Add USDC to wallet for x402 GPU mining (~20 GH/s, ~$0.006/mine)`);
306
+ console.log(` 3. Set up VAST.ai CUDA for ~20 GH/s (see docs)`);
307
+ console.log("");
308
+ const proceed = await ui.confirm("Mining is strongly discouraged at this speed. Continue anyway?");
309
+ if (!proceed) {
310
+ console.log(` ${ui.dim("Exiting. Build faster grinders and try again.")}`);
311
+ return;
312
+ }
313
+ }
314
+ else if (estimatedSeconds > staleCheckSeconds) {
315
+ console.log("");
316
+ ui.warn(`Your grinder (~${formatRate(estHashrate)}) is too slow for current difficulty.`);
317
+ console.log(` Expected time per mine: ~${formatTime(estimatedSeconds)} (challenges go stale every ${staleCheckSeconds}s).`);
318
+ console.log("");
319
+ console.log(` Fix options:`);
320
+ console.log(` 1. Run ${ui.cyan("apow build-grinders")} for 100x faster local mining (~500 MH/s)`);
321
+ console.log(` 2. Add USDC to wallet for x402 GPU mining (~20 GH/s, ~$0.006/mine)`);
322
+ console.log(` 3. Set up VAST.ai CUDA for ~20 GH/s (see docs)`);
323
+ console.log("");
324
+ const proceed = await ui.confirm("Continue anyway?");
325
+ if (!proceed) {
326
+ console.log(` ${ui.dim("Exiting. Build faster grinders and try again.")}`);
327
+ return;
328
+ }
197
329
  }
198
330
  console.log("");
199
331
  while (true) {
@@ -269,14 +401,16 @@ async function startMining(tokenId) {
269
401
  const smhlElapsed = elapsedSeconds(smhlStart);
270
402
  console.log(` ${ui.dim(`SMHL solved (${(smhlElapsed * 1000).toFixed(1)}ms)`)}`);
271
403
  // Grind nonce — native GPU/CPU if available, JS fallback
272
- // Abort and re-fetch challenge every STALE_CHECK_INTERVAL_MS to avoid
273
- // grinding a dead nonce after another miner wins the block.
274
- const STALE_CHECK_INTERVAL_MS = 20_000;
404
+ // Abort and re-fetch challenge periodically to avoid grinding a dead
405
+ // nonce after another miner wins the block. Configurable via
406
+ // STALE_CHECK_INTERVAL env var (seconds, default 60).
407
+ const staleCheckMs = config_1.config.staleCheckIntervalMs;
275
408
  let grind = null;
409
+ let staleRestarts = 0;
276
410
  while (!grind) {
277
411
  const abortController = new AbortController();
278
412
  const nonceSpinner = ui.spinner(`Grinding nonce (${modeLabel})...`);
279
- // Background staleness checker — polls challenge every 20s
413
+ // Background staleness checker
280
414
  const staleTimer = setInterval(async () => {
281
415
  try {
282
416
  const fresh = (await wallet_1.publicClient.readContract({
@@ -285,14 +419,15 @@ async function startMining(tokenId) {
285
419
  functionName: "getMiningChallenge",
286
420
  }));
287
421
  if (fresh[0] !== challengeNumber) {
288
- nonceSpinner.stop("Challenge changed — restarting grind");
422
+ staleRestarts++;
423
+ nonceSpinner.stop(`Challenge changed — restarting grind (stale #${staleRestarts})`);
289
424
  abortController.abort();
290
425
  }
291
426
  }
292
427
  catch {
293
428
  // RPC hiccup — don't abort, just skip this check
294
429
  }
295
- }, STALE_CHECK_INTERVAL_MS);
430
+ }, staleCheckMs);
296
431
  try {
297
432
  // Race all available grinders — first valid nonce wins
298
433
  const grinders = [];
@@ -301,7 +436,13 @@ async function startMining(tokenId) {
301
436
  .catch((err) => {
302
437
  if (abortController.signal.aborted)
303
438
  throw err;
304
- // Native failed but don't abort the race — others may still win
439
+ const msg = err instanceof Error ? err.message : String(err);
440
+ if (msg.includes("No native grinders")) {
441
+ console.log(` ${ui.dim("No native grinders found.")} ${ui.yellow("Tip:")} Run ${ui.cyan("apow build-grinders")} for 100x speedup`);
442
+ }
443
+ else {
444
+ console.log(` ${ui.dim(`Native grinder error: ${msg}`)}`);
445
+ }
305
446
  return new Promise(() => { }); // hang forever (race will resolve via another grinder)
306
447
  }));
307
448
  }
@@ -310,21 +451,34 @@ async function startMining(tokenId) {
310
451
  .catch((err) => {
311
452
  if (abortController.signal.aborted)
312
453
  throw err;
454
+ const msg = err instanceof Error ? err.message : String(err);
455
+ if (msg.includes("402")) {
456
+ console.log(` ${ui.yellow("x402 GPU payment failed.")} Check USDC balance or run: ${ui.cyan("apow wallet fund")}`);
457
+ }
458
+ else if (msg.includes("insufficient USDC")) {
459
+ console.log(` ${ui.yellow("x402 GPU needs USDC.")} Run: ${ui.cyan("apow wallet fund")}`);
460
+ }
461
+ else {
462
+ console.log(` ${ui.dim(`x402 GPU grinder error: ${msg}`)}`);
463
+ }
313
464
  return new Promise(() => { });
314
465
  }));
315
466
  }
316
- // JS fallback always runs (it's the baseline)
317
- grinders.push((0, grinder_1.grindNonceParallel)({
318
- challengeNumber,
319
- target,
320
- minerAddress: account.address,
321
- threads: config_1.config.minerThreads,
322
- signal: abortController.signal,
323
- onProgress: !useNative && !useHttpGrind ? (attempts, hashrate) => {
324
- const khs = (hashrate / 1000).toFixed(0);
325
- nonceSpinner.update(`Grinding nonce (JS)... ${khs}k H/s (${attempts.toLocaleString()} attempts)`);
326
- } : undefined,
327
- }));
467
+ // JS grinder only runs when no native or HTTP grinders are active
468
+ // (avoids wasting CPU cores that CPU-C needs)
469
+ if (!useNative && !useHttpGrind) {
470
+ grinders.push((0, grinder_1.grindNonceParallel)({
471
+ challengeNumber,
472
+ target,
473
+ minerAddress: account.address,
474
+ threads: config_1.config.minerThreads,
475
+ signal: abortController.signal,
476
+ onProgress: (attempts, hashrate) => {
477
+ const khs = (hashrate / 1000).toFixed(0);
478
+ nonceSpinner.update(`Grinding nonce (JS)... ${khs}k H/s (${attempts.toLocaleString()} attempts)`);
479
+ },
480
+ }));
481
+ }
328
482
  grind = await Promise.race(grinders);
329
483
  clearInterval(staleTimer);
330
484
  const khs = grind.hashrate > 0 ? (grind.hashrate / 1000).toFixed(0) : "?";
@@ -343,6 +497,10 @@ async function startMining(tokenId) {
343
497
  const freshSmhl = (0, smhl_1.normalizeSmhlChallenge)(freshChallenge[2]);
344
498
  smhlSolution = (0, smhl_1.solveSmhlAlgorithmic)(freshSmhl);
345
499
  console.log(` ${ui.dim("SMHL re-solved, grinding fresh challenge...")}`);
500
+ if (staleRestarts >= 3 && staleRestarts % 3 === 0) {
501
+ ui.warn(`Challenge has gone stale ${staleRestarts} times — grinder may be too slow for current difficulty.`);
502
+ ui.warn(`Tip: increase STALE_CHECK_INTERVAL (current: ${staleCheckMs / 1000}s) or use a faster grinder.`);
503
+ }
346
504
  grind = null; // loop again
347
505
  continue;
348
506
  }
@@ -32,6 +32,9 @@
32
32
  #define MAX_ADDRS 8
33
33
  #define MAX_LINE 4096
34
34
 
35
+ // Signal state — declared early so run_grind can check it
36
+ static volatile sig_atomic_t got_signal = 0;
37
+
35
38
  // ── Keccak round constants ──
36
39
 
37
40
  __constant__ uint64_t RC[24] = {
@@ -271,7 +274,7 @@ static void compute_target_be(uint64_t target_be[4], const uint8_t target[32]) {
271
274
  static void configure_dispatch(GrindParams* params, const int weights[], int num_addrs,
272
275
  uint64_t* out_batch_size, int* out_grid_size) {
273
276
  const int BLOCK_SIZE = 256;
274
- const uint64_t RAW_BATCH = 1ULL << 26; // 64M
277
+ const uint64_t RAW_BATCH = 1ULL << 24; // 16M — faster first-nonce latency (check 16x more often)
275
278
 
276
279
  int total_weight = 0;
277
280
  for (int a = 0; a < num_addrs; a++) total_weight += weights[a];
@@ -332,19 +335,51 @@ static bool run_grind(GrindParams* params, GrindResult* result,
332
335
  }
333
336
  }
334
337
 
335
- // In daemon mode, check for ABORT between batches
336
- if (check_abort && stdin_has_data()) {
337
- char abort_buf[MAX_LINE];
338
- if (fgets(abort_buf, sizeof(abort_buf), stdin)) {
339
- // Trim
340
- char* p = abort_buf;
341
- while (*p == ' ' || *p == '\t') p++;
342
- if (strncmp(p, "ABORT", 5) == 0) {
338
+ // Check CUDA errors
339
+ cudaError_t err = cudaGetLastError();
340
+ if (err != cudaSuccess) {
341
+ fprintf(stderr, "CUDA error: %s\n", cudaGetErrorString(err));
342
+ cudaDeviceReset();
343
+ auto t1 = std::chrono::steady_clock::now();
344
+ double elapsed = std::chrono::duration<double>(t1 - t0).count();
345
+ printf("D %llu %.3f\n", (unsigned long long)totalAttempts, elapsed);
346
+ fflush(stdout);
347
+ return false;
348
+ }
349
+
350
+ // In daemon mode, check for ABORT / EOF / signal between batches
351
+ if (check_abort) {
352
+ // Check for fatal signal (SIGHUP from SSH death, SIGTERM, etc.)
353
+ if (got_signal) {
354
+ cudaDeviceSynchronize();
355
+ auto t1 = std::chrono::steady_clock::now();
356
+ double elapsed = std::chrono::duration<double>(t1 - t0).count();
357
+ printf("D %llu %.3f\n", (unsigned long long)totalAttempts, elapsed);
358
+ fflush(stdout);
359
+ return false; // Signal received — exit grind
360
+ }
361
+ if (stdin_has_data()) {
362
+ char abort_buf[MAX_LINE];
363
+ if (fgets(abort_buf, sizeof(abort_buf), stdin)) {
364
+ // Trim
365
+ char* p = abort_buf;
366
+ while (*p == ' ' || *p == '\t') p++;
367
+ if (strncmp(p, "ABORT", 5) == 0) {
368
+ cudaDeviceSynchronize();
369
+ auto t1 = std::chrono::steady_clock::now();
370
+ double elapsed = std::chrono::duration<double>(t1 - t0).count();
371
+ printf("D %llu %.3f\n", (unsigned long long)totalAttempts, elapsed);
372
+ fflush(stdout);
373
+ return false; // Aborted
374
+ }
375
+ } else {
376
+ // fgets returned NULL = EOF (SSH connection died)
377
+ cudaDeviceSynchronize();
343
378
  auto t1 = std::chrono::steady_clock::now();
344
379
  double elapsed = std::chrono::duration<double>(t1 - t0).count();
345
380
  printf("D %llu %.3f\n", (unsigned long long)totalAttempts, elapsed);
346
381
  fflush(stdout);
347
- return false; // Aborted
382
+ return false; // EOF — exit immediately
348
383
  }
349
384
  }
350
385
  }
@@ -357,8 +392,7 @@ static bool run_grind(GrindParams* params, GrindResult* result,
357
392
  return true;
358
393
  }
359
394
 
360
- // Signal handler for debugging
361
- static volatile sig_atomic_t got_signal = 0;
395
+ // Signal handler — sets flag so grind loop exits quickly
362
396
  static void signal_handler(int sig) {
363
397
  // Write signal info to stderr (async-signal-safe)
364
398
  const char* name = "UNKNOWN";
@@ -396,13 +430,16 @@ static int run_daemon() {
396
430
  grind_kernel<<<1, 1>>>(params, result);
397
431
  cudaDeviceSynchronize();
398
432
 
399
- // Install signal handlers for debugging
433
+ // Ignore SIGPIPE (critical for daemon writing to SSH channel)
434
+ signal(SIGPIPE, SIG_IGN);
435
+ // Install signal handlers for debugging other signals
400
436
  signal(SIGTERM, signal_handler);
401
437
  signal(SIGINT, signal_handler);
402
- signal(SIGPIPE, signal_handler);
403
438
  signal(SIGHUP, signal_handler);
404
439
  signal(SIGUSR1, signal_handler);
405
440
  signal(SIGUSR2, signal_handler);
441
+ signal(SIGSEGV, signal_handler);
442
+ signal(SIGABRT, signal_handler);
406
443
 
407
444
  fprintf(stderr, "CUDA daemon ready (pid=%d)\n", getpid());
408
445
  printf("READY\n");
@@ -410,7 +447,7 @@ static int run_daemon() {
410
447
 
411
448
  // Main loop: read challenges from stdin
412
449
  char line[MAX_LINE];
413
- while (fgets(line, sizeof(line), stdin)) {
450
+ while (!got_signal && fgets(line, sizeof(line), stdin)) {
414
451
  // Trim leading whitespace
415
452
  char* p = line;
416
453
  while (*p == ' ' || *p == '\t') p++;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apow-cli",
3
- "version": "0.9.4",
3
+ "version": "0.10.0",
4
4
  "description": "Mine AGENT tokens on Base L2 with Agentic Proof of Work",
5
5
  "keywords": [
6
6
  "apow",
@@ -45,10 +45,11 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@blockrun/clawrouter": "^0.12.81",
48
- "@x402/evm": "^2.8.0",
49
- "@x402/fetch": "^2.8.0",
48
+ "@noble/hashes": "^1.8.0",
50
49
  "@quicknode/x402": "^0.1.2",
51
50
  "@solana/web3.js": "^1.98.0",
51
+ "@x402/evm": "^2.8.0",
52
+ "@x402/fetch": "^2.8.0",
52
53
  "commander": "^14.0.0",
53
54
  "dotenv": "^17.2.3",
54
55
  "openai": "^6.6.0",