apow-cli 0.9.1 → 0.9.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/fund.js CHANGED
@@ -1,13 +1,14 @@
1
1
  "use strict";
2
2
  // Fund command — unified funding for mining on Base.
3
- // Accepts deposits from Solana (via Squid Router bridge) or Base (direct send),
3
+ // Accepts deposits from Solana/Ethereum (via Squid Router bridge) or Base (direct send),
4
4
  // auto-splits into ETH (gas) + USDC (x402 RPC).
5
5
  //
6
6
  // Deposit types:
7
7
  // 1. Solana SOL → bridge → ETH on Base → swap portion to USDC
8
8
  // 2. Solana USDC → bridge → USDC on Base → swap portion to ETH
9
- // 3. Base ETH → (already there) → swap portion to USDC
10
- // 4. Base USDC → (already there) → swap portion to ETH
9
+ // 3. Ethereum ETH → bridge → ETH on Base → swap portion to USDC
10
+ // 4. Base ETH → (already there) → swap portion to USDC
11
+ // 5. Base USDC → (already there) → swap portion to ETH
11
12
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
13
  if (k2 === undefined) k2 = k;
13
14
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -288,6 +289,87 @@ async function runSolanaFund(baseAddress, sourceToken, targetEth) {
288
289
  await showFinalBalances();
289
290
  }
290
291
  // ---------------------------------------------------------------------------
292
+ // Ethereum fund (Squid Router deposit address)
293
+ // ---------------------------------------------------------------------------
294
+ async function runEthereumFund(baseAddress, targetEth) {
295
+ const priceSpinner = ui.spinner("Fetching prices...");
296
+ const prices = await fetchPrices();
297
+ priceSpinner.stop(`ETH price: $${prices.ethPriceUsd.toFixed(0)}`);
298
+ // ETH→ETH bridge is ~1:1, add 5% buffer for bridge fees
299
+ const amount = targetEth * 1.05;
300
+ const addrSpinner = ui.spinner("Generating deposit address...");
301
+ const squid = await Promise.resolve().then(() => __importStar(require("./bridge/squid")));
302
+ let deposit;
303
+ try {
304
+ deposit = await squid.getDepositAddress(baseAddress, amount, squid.SQUID_ROUTES.eth_to_base_eth);
305
+ }
306
+ catch (err) {
307
+ addrSpinner.fail("Failed to get deposit address");
308
+ const msg = err instanceof Error ? err.message : String(err);
309
+ if (msg.includes("DEPOSIT_ADDRESS_UNAVAILABLE")) {
310
+ console.log("");
311
+ ui.warn("Squid Router doesn't support deposit addresses for Ethereum.");
312
+ console.log(" Alternatives:");
313
+ console.log(` ${ui.cyan("1.")} Bridge via ${ui.bold("bridge.base.org")} → paste your mining wallet as recipient`);
314
+ console.log(` ${ui.cyan("2.")} Send ETH on Base directly: ${ui.cyan("apow fund --chain base")}`);
315
+ console.log(` ${ui.cyan("3.")} Bridge from Solana instead: ${ui.cyan("apow fund --chain solana")}`);
316
+ console.log("");
317
+ return;
318
+ }
319
+ throw err;
320
+ }
321
+ addrSpinner.stop("Deposit address ready");
322
+ console.log("");
323
+ console.log(` ${ui.bold("Send ETH on Ethereum mainnet to this address:")}`);
324
+ console.log("");
325
+ console.log(` ${ui.cyan(deposit.depositAddress)}`);
326
+ console.log("");
327
+ await showQrCode(deposit.depositAddress);
328
+ console.log("");
329
+ ui.table([
330
+ ["Amount", `~${amount.toFixed(6)} ETH`],
331
+ ["You'll receive", `~${deposit.expectedReceive} ETH on Base`],
332
+ ["Bridge", "Squid Router (Chainflip)"],
333
+ ["Time", "~1-3 minutes"],
334
+ ]);
335
+ console.log("");
336
+ if (deposit.expiresAt) {
337
+ ui.warn(`Deposit address expires: ${deposit.expiresAt}`);
338
+ console.log("");
339
+ }
340
+ // Poll for deposit on Ethereum mainnet
341
+ const ethereum = await Promise.resolve().then(() => __importStar(require("./bridge/ethereum")));
342
+ const depositSpinner = ui.spinner("Waiting for ETH deposit on Ethereum mainnet... (Ctrl+C to cancel)");
343
+ const initialBalance = await ethereum.getAddressBalance(deposit.depositAddress);
344
+ let depositDetected = false;
345
+ const depositDeadline = Date.now() + 600_000;
346
+ while (!depositDetected && Date.now() < depositDeadline) {
347
+ await new Promise((r) => setTimeout(r, 3000));
348
+ try {
349
+ const currentBalance = await ethereum.getAddressBalance(deposit.depositAddress);
350
+ if (currentBalance > initialBalance + 0.0001) {
351
+ depositDetected = true;
352
+ depositSpinner.stop(`Deposit received! ${(currentBalance - initialBalance).toFixed(6)} ETH`);
353
+ }
354
+ }
355
+ catch {
356
+ // Transient RPC error
357
+ }
358
+ }
359
+ if (!depositDetected) {
360
+ depositSpinner.fail("No ETH deposit detected after 10 minutes");
361
+ ui.hint("If you sent ETH, check: https://explorer.squidrouter.com");
362
+ return;
363
+ }
364
+ // Poll for bridge completion
365
+ const bridgeSpinner = ui.spinner("Bridging to Base... (~1-3 min)");
366
+ const result = await (0, squid_1.pollBridgeStatus)(deposit.requestId, 18, (status) => bridgeSpinner.update(`Bridge status: ${status}`));
367
+ const received = result.received || deposit.expectedReceive;
368
+ bridgeSpinner.stop(`Bridge complete! ${received} ETH arrived`);
369
+ await autoSplit("eth", prices, false);
370
+ await showFinalBalances();
371
+ }
372
+ // ---------------------------------------------------------------------------
291
373
  // Base manual send (already on the right chain)
292
374
  // ---------------------------------------------------------------------------
293
375
  async function runBaseFund(baseAddress, sourceToken, noSwap) {
@@ -356,12 +438,20 @@ async function runBaseFund(baseAddress, sourceToken, noSwap) {
356
438
  async function selectSourceChain() {
357
439
  console.log(" Where are your funds?");
358
440
  console.log(` ${ui.cyan("1.")} Solana (SOL or USDC)`);
359
- console.log(` ${ui.cyan("2.")} Base (send ETH or USDC directly)`);
441
+ console.log(` ${ui.cyan("2.")} Ethereum mainnet (ETH)`);
442
+ console.log(` ${ui.cyan("3.")} Base (send ETH or USDC directly)`);
360
443
  console.log("");
361
444
  const choice = await ui.prompt("Choice", "1");
362
- return choice === "2" ? "base" : "solana";
445
+ if (choice === "2")
446
+ return "ethereum";
447
+ if (choice === "3")
448
+ return "base";
449
+ return "solana";
363
450
  }
364
451
  async function selectSourceToken(chain) {
452
+ // Ethereum only supports native ETH — skip token prompt
453
+ if (chain === "ethereum")
454
+ return "native";
365
455
  const nativeLabel = chain === "solana" ? "SOL" : "ETH";
366
456
  console.log("");
367
457
  console.log(" What token?");
@@ -377,6 +467,8 @@ function parseSourceChain(value) {
377
467
  const v = value.toLowerCase();
378
468
  if (v === "solana" || v === "sol")
379
469
  return "solana";
470
+ if (v === "ethereum" || v === "eth" || v === "mainnet")
471
+ return "ethereum";
380
472
  if (v === "base")
381
473
  return "base";
382
474
  return undefined;
@@ -443,6 +535,10 @@ async function runFundFlow(options) {
443
535
  await runSolanaFund(baseAddress, token, targetEth);
444
536
  break;
445
537
  }
538
+ case "ethereum": {
539
+ await runEthereumFund(baseAddress, targetEth);
540
+ break;
541
+ }
446
542
  case "base": {
447
543
  await runBaseFund(baseAddress, token, noSwap);
448
544
  break;
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ /**
3
+ * HTTP x402 nonce grinder — pay-per-grind GPU mining via GrindProxy.
4
+ *
5
+ * Sends {challenge, target, address} to a remote GPU endpoint (default:
6
+ * grind.apow.io). Payment ($0.01 USDC) is handled automatically via the
7
+ * x402 protocol — the server returns 402, the client signs a USDC
8
+ * authorization and retries. No accounts, no API keys.
9
+ *
10
+ * Front-running is cryptographically impossible: nonces are bound to
11
+ * keccak256(challenge, msg.sender, nonce) — a nonce ground for address A
12
+ * is useless for address B.
13
+ */
14
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ var desc = Object.getOwnPropertyDescriptor(m, k);
17
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
18
+ desc = { enumerable: true, get: function() { return m[k]; } };
19
+ }
20
+ Object.defineProperty(o, k2, desc);
21
+ }) : (function(o, m, k, k2) {
22
+ if (k2 === undefined) k2 = k;
23
+ o[k2] = m[k];
24
+ }));
25
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
26
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
27
+ }) : function(o, v) {
28
+ o["default"] = v;
29
+ });
30
+ var __importStar = (this && this.__importStar) || (function () {
31
+ var ownKeys = function(o) {
32
+ ownKeys = Object.getOwnPropertyNames || function (o) {
33
+ var ar = [];
34
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
35
+ return ar;
36
+ };
37
+ return ownKeys(o);
38
+ };
39
+ return function (mod) {
40
+ if (mod && mod.__esModule) return mod;
41
+ var result = {};
42
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
43
+ __setModuleDefault(result, mod);
44
+ return result;
45
+ };
46
+ })();
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.isHttpGrinderConfigured = isHttpGrinderConfigured;
49
+ exports.getGrindUrl = getGrindUrl;
50
+ exports.grindNonceHttp = grindNonceHttp;
51
+ const config_1 = require("./config");
52
+ const DEFAULT_GRIND_URL = "https://grind.apow.io/grind";
53
+ // Lazy singleton — created on first grind, reused across calls
54
+ let _fetchWithPayment = null;
55
+ async function getPaymentFetch(privateKey) {
56
+ if (_fetchWithPayment)
57
+ return _fetchWithPayment;
58
+ const { privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
59
+ const { x402Client, wrapFetchWithPayment } = await Promise.resolve().then(() => __importStar(require("@x402/fetch")));
60
+ const { registerExactEvmScheme } = await Promise.resolve().then(() => __importStar(require("@x402/evm/exact/client")));
61
+ const signer = privateKeyToAccount(privateKey);
62
+ const client = new x402Client();
63
+ registerExactEvmScheme(client, { signer });
64
+ _fetchWithPayment = wrapFetchWithPayment(fetch, client);
65
+ return _fetchWithPayment;
66
+ }
67
+ function isHttpGrinderConfigured() {
68
+ return config_1.config.useX402Grind && !!config_1.config.privateKey;
69
+ }
70
+ function getGrindUrl() {
71
+ return config_1.config.grindUrl ?? DEFAULT_GRIND_URL;
72
+ }
73
+ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, privateKey, signal) {
74
+ const paidFetch = await getPaymentFetch(privateKey);
75
+ const start = process.hrtime();
76
+ const response = await paidFetch(grindUrl, {
77
+ method: "POST",
78
+ headers: { "Content-Type": "application/json" },
79
+ body: JSON.stringify({
80
+ challenge: challengeNumber,
81
+ target: target.toString(),
82
+ address: minerAddress,
83
+ }),
84
+ signal,
85
+ });
86
+ if (!response.ok) {
87
+ const body = await response.text().catch(() => "");
88
+ if (response.status === 402) {
89
+ throw new Error("x402 GPU grind payment failed — insufficient USDC on Base");
90
+ }
91
+ if (response.status === 504) {
92
+ throw new Error("Remote GPU grind timed out (90s)");
93
+ }
94
+ throw new Error(`GrindProxy HTTP ${response.status}: ${body.slice(0, 200)}`);
95
+ }
96
+ const data = (await response.json());
97
+ if (!data.nonce) {
98
+ throw new Error("GrindProxy returned no nonce");
99
+ }
100
+ const [s, ns] = process.hrtime(start);
101
+ const totalElapsed = s + ns / 1_000_000_000;
102
+ return {
103
+ nonce: BigInt(data.nonce),
104
+ attempts: 0n, // remote — unknown
105
+ elapsed: data.elapsed ?? totalElapsed,
106
+ hashrate: 0, // remote — unknown
107
+ };
108
+ }
@@ -39,8 +39,10 @@ const config_1 = require("./config");
39
39
  function detectGrinders() {
40
40
  return {
41
41
  gpu: detectLocalGpu(),
42
+ cuda: detectLocalCuda(),
42
43
  cpu: detectLocalCpu(),
43
44
  remoteGpu: !!(config_1.config.vastIp && config_1.config.vastPort),
45
+ httpGrind: config_1.config.useX402Grind && !!config_1.config.privateKey,
44
46
  };
45
47
  }
46
48
  function detectLocalGpu() {
@@ -61,6 +63,22 @@ function detectLocalGpu() {
61
63
  }
62
64
  return null;
63
65
  }
66
+ function detectLocalCuda() {
67
+ if (config_1.config.cudaGrinderPath) {
68
+ return (0, node_fs_1.existsSync)(config_1.config.cudaGrinderPath) ? config_1.config.cudaGrinderPath : null;
69
+ }
70
+ const candidates = [
71
+ (0, node_path_1.join)(process.cwd(), "gpu", "grinder-cuda"),
72
+ (0, node_path_1.join)(process.cwd(), "local", "gpu", "grinder-cuda"),
73
+ (0, node_path_1.join)(process.cwd(), "grinder-cuda"),
74
+ (0, node_path_1.join)(node_os_1.default.homedir(), ".apow", "grinder-cuda"),
75
+ ];
76
+ for (const p of candidates) {
77
+ if ((0, node_fs_1.existsSync)(p))
78
+ return p;
79
+ }
80
+ return null;
81
+ }
64
82
  function detectLocalCpu() {
65
83
  if (config_1.config.cpuGrinderPath) {
66
84
  return (0, node_fs_1.existsSync)(config_1.config.cpuGrinderPath) ? config_1.config.cpuGrinderPath : null;
@@ -78,12 +96,14 @@ function detectLocalCpu() {
78
96
  return null;
79
97
  }
80
98
  function hasNativeGrinders(info) {
81
- return !!(info.gpu || info.cpu || info.remoteGpu);
99
+ return !!(info.gpu || info.cuda || info.cpu || info.remoteGpu || info.httpGrind);
82
100
  }
83
101
  function grinderLabel(info) {
84
102
  const parts = [];
85
103
  if (info.remoteGpu)
86
104
  parts.push("CUDA (remote)");
105
+ if (info.cuda)
106
+ parts.push("CUDA GPU");
87
107
  if (info.gpu)
88
108
  parts.push(process.platform === "darwin" ? "Metal GPU" : "GPU");
89
109
  if (info.cpu)
@@ -164,7 +184,8 @@ async function grindNonceNative(challengeNumber, target, minerAddress, info, sig
164
184
  // Local Metal GPU
165
185
  if (info.gpu) {
166
186
  totalGrinders++;
167
- const proc = (0, node_child_process_1.spawn)(info.gpu, [challengeNumber, minerAddress, targetHex]);
187
+ // Set CWD to binary's directory so Metal grinder finds keccak.metal shader
188
+ const proc = (0, node_child_process_1.spawn)(info.gpu, [challengeNumber, minerAddress, targetHex], { cwd: (0, node_path_1.dirname)(info.gpu) });
168
189
  processes.push(proc);
169
190
  let stdout = "";
170
191
  proc.stdout.on("data", (d) => { stdout += d.toString(); });
@@ -189,6 +210,42 @@ async function grindNonceNative(challengeNumber, target, minerAddress, info, sig
189
210
  });
190
211
  proc.on("error", () => onFail());
191
212
  }
213
+ // Local CUDA GPU
214
+ if (info.cuda) {
215
+ totalGrinders++;
216
+ // CUDA arg order: <challenge> <target> <address>
217
+ const proc = (0, node_child_process_1.spawn)(info.cuda, [challengeNumber, targetHex, minerAddress]);
218
+ processes.push(proc);
219
+ let buf = "";
220
+ proc.stdout.on("data", (d) => {
221
+ if (settled)
222
+ return;
223
+ buf += d.toString();
224
+ let nl;
225
+ while ((nl = buf.indexOf("\n")) !== -1) {
226
+ const line = buf.slice(0, nl).trim();
227
+ buf = buf.slice(nl + 1);
228
+ if (line.startsWith("F ")) {
229
+ const parts = line.split(/\s+/);
230
+ if (parts.length >= 4) {
231
+ const e = parseFloat(parts[3]);
232
+ onResult({
233
+ nonce: BigInt(parts[2]),
234
+ attempts: 0n,
235
+ elapsed: e,
236
+ hashrate: 0,
237
+ });
238
+ return;
239
+ }
240
+ }
241
+ }
242
+ });
243
+ proc.on("close", () => {
244
+ if (!settled)
245
+ onFail();
246
+ });
247
+ proc.on("error", () => onFail());
248
+ }
192
249
  // Local CPU-C
193
250
  if (info.cpu) {
194
251
  totalGrinders++;
package/dist/index.js CHANGED
@@ -119,9 +119,21 @@ async function setupWizard() {
119
119
  console.log("");
120
120
  ui.banner(["AgentCoin Miner Setup"]);
121
121
  console.log("");
122
+ // Mode selection
123
+ console.log(` ${ui.bold("How do you want to configure?")}`);
124
+ console.log("");
125
+ console.log(` ${ui.cyan("1.")} Quick Start ${ui.dim("(recommended)")}`);
126
+ console.log(` ${ui.dim("Zero credentials. Pays for RPC + LLM with USDC from your wallet.")}`);
127
+ console.log(` ${ui.cyan("2.")} Custom`);
128
+ console.log(` ${ui.dim("Bring your own RPC endpoint and/or LLM API key.")}`);
129
+ console.log("");
130
+ const modeInput = await ui.prompt("Choice", "1");
131
+ const quickStart = modeInput !== "2";
132
+ console.log("");
133
+ const totalSteps = quickStart ? 2 : 3;
122
134
  const values = {};
123
135
  // Step 1: Wallet
124
- console.log(` ${ui.bold("Step 1/3: Wallet")}`);
136
+ console.log(` ${ui.bold(`Step 1/${totalSteps}: Wallet`)}`);
125
137
  const hasWallet = await ui.confirm("Do you have a Base wallet?");
126
138
  let privateKey;
127
139
  let addr;
@@ -168,72 +180,85 @@ async function setupWizard() {
168
180
  values.PRIVATE_KEY = privateKey;
169
181
  ui.ok(`Wallet: ${addr.slice(0, 6)}...${addr.slice(-4)}`);
170
182
  console.log("");
171
- // Step 2: RPC
172
- console.log(` ${ui.bold("Step 2/3: RPC")}`);
173
- console.log(` ${ui.dim("You need a Base RPC endpoint. Two options:")}`);
174
- console.log(` ${ui.dim(" 1. Bring your own (free from Alchemy, QuickNode, etc.)")}`);
175
- console.log(` ${ui.dim(" 2. Auto-pay via QuickNode x402 ($10 USDC for ~1M calls)")}`);
176
- const hasRpc = await ui.confirm("Do you have a Base RPC URL?");
177
- if (hasRpc) {
178
- const rpcUrl = await ui.prompt("RPC URL");
179
- if (rpcUrl) {
180
- values.RPC_URL = rpcUrl;
181
- ui.ok(`RPC: Custom (${rpcUrl.slice(0, 40)}${rpcUrl.length > 40 ? "..." : ""})`);
183
+ if (quickStart) {
184
+ // Quick Start: auto-configure x402 + clawrouter
185
+ console.log(` ${ui.bold(`Step 2/${totalSteps}: Configuration`)}`);
186
+ values.USE_X402 = "true";
187
+ values.LLM_PROVIDER = "clawrouter";
188
+ values.LLM_MODEL = "blockrun/eco";
189
+ ui.ok("RPC: QuickNode x402 (auto-pay with USDC, no API key)");
190
+ ui.ok("LLM: ClawRouter x402 (auto-pay with USDC, no API key)");
191
+ console.log(` ${ui.dim("Both services charge USDC from your mining wallet. ~$10 covers ~1M calls.")}`);
192
+ }
193
+ else {
194
+ // Custom: existing 3-step flow
195
+ // Step 2: RPC
196
+ console.log(` ${ui.bold(`Step 2/${totalSteps}: RPC`)}`);
197
+ console.log(` ${ui.dim("You need a Base RPC endpoint. Two options:")}`);
198
+ console.log(` ${ui.dim(" 1. Bring your own (free from Alchemy, QuickNode, etc.)")}`);
199
+ console.log(` ${ui.dim(" 2. Auto-pay via QuickNode x402 ($10 USDC for ~1M calls)")}`);
200
+ const hasRpc = await ui.confirm("Do you have a Base RPC URL?");
201
+ if (hasRpc) {
202
+ const rpcUrl = await ui.prompt("RPC URL");
203
+ if (rpcUrl) {
204
+ values.RPC_URL = rpcUrl;
205
+ ui.ok(`RPC: Custom (${rpcUrl.slice(0, 40)}${rpcUrl.length > 40 ? "..." : ""})`);
206
+ }
207
+ else {
208
+ ui.warn("No URL provided — using QuickNode x402");
209
+ values.USE_X402 = "true";
210
+ ui.ok("RPC: QuickNode x402 ($10 USDC for ~1M calls)");
211
+ }
182
212
  }
183
213
  else {
184
- ui.warn("No URL provided — using QuickNode x402");
185
214
  values.USE_X402 = "true";
215
+ console.log(` ${ui.dim("QuickNode x402 will charge $10 USDC from your mining wallet")}`);
216
+ console.log(` ${ui.dim("for ~1M RPC calls. No API key or account needed.")}`);
186
217
  ui.ok("RPC: QuickNode x402 ($10 USDC for ~1M calls)");
187
218
  }
188
- }
189
- else {
190
- values.USE_X402 = "true";
191
- console.log(` ${ui.dim("QuickNode x402 will charge $10 USDC from your mining wallet")}`);
192
- console.log(` ${ui.dim("for ~1M RPC calls. No API key or account needed.")}`);
193
- ui.ok("RPC: QuickNode x402 ($10 USDC for ~1M calls)");
194
- }
195
- console.log("");
196
- // Step 3: LLM (for minting)
197
- console.log(` ${ui.bold("Step 3/3: LLM Provider (for minting)")}`);
198
- console.log(` ${ui.dim("An LLM solves the SMHL challenge when minting your Mining Rig.")}`);
199
- console.log(` ${ui.dim("Mining uses optimized solving — no LLM needed after minting.")}`);
200
- console.log(` ${ui.dim(" clawrouter (recommended) — Zero credentials. Pays with USDC from your wallet.")}`);
201
- console.log(` ${ui.dim(" openai / anthropic / gemini / deepseek / qwen — Requires API key.")}`);
202
- console.log(` ${ui.dim(" ollama / claude-code / codex — Local, no API key.")}`);
203
- const providerInput = await ui.prompt("Provider", "clawrouter");
204
- const provider = (["clawrouter", "openai", "anthropic", "gemini", "ollama", "deepseek", "qwen", "claude-code", "codex"].includes(providerInput) ? providerInput : "clawrouter");
205
- values.LLM_PROVIDER = provider;
206
- if (provider === "clawrouter") {
207
- ui.ok("ClawRouter x402 — no API key needed, pays with USDC from your wallet");
208
- if (!values.USE_X402 && !values.RPC_URL) {
209
- values.USE_X402 = "true";
210
- ui.ok("Auto-enabled x402 RPC (same wallet, same USDC balance)");
219
+ console.log("");
220
+ // Step 3: LLM (for minting)
221
+ console.log(` ${ui.bold(`Step 3/${totalSteps}: LLM Provider (for minting)`)}`);
222
+ console.log(` ${ui.dim("An LLM solves the SMHL challenge when minting your Mining Rig.")}`);
223
+ console.log(` ${ui.dim("Mining uses optimized solving — no LLM needed after minting.")}`);
224
+ console.log(` ${ui.dim(" clawrouter (recommended) — Zero credentials. Pays with USDC from your wallet.")}`);
225
+ console.log(` ${ui.dim(" openai / anthropic / gemini / deepseek / qwen — Requires API key.")}`);
226
+ console.log(` ${ui.dim(" ollama / claude-code / codex — Local, no API key.")}`);
227
+ const providerInput = await ui.prompt("Provider", "clawrouter");
228
+ const provider = (["clawrouter", "openai", "anthropic", "gemini", "ollama", "deepseek", "qwen", "claude-code", "codex"].includes(providerInput) ? providerInput : "clawrouter");
229
+ values.LLM_PROVIDER = provider;
230
+ if (provider === "clawrouter") {
231
+ ui.ok("ClawRouter x402 — no API key needed, pays with USDC from your wallet");
232
+ if (!values.USE_X402 && !values.RPC_URL) {
233
+ values.USE_X402 = "true";
234
+ ui.ok("Auto-enabled x402 RPC (same wallet, same USDC balance)");
235
+ }
211
236
  }
212
- }
213
- else if (provider === "ollama") {
214
- const ollamaUrl = await ui.prompt("Ollama URL", "http://127.0.0.1:11434");
215
- values.OLLAMA_URL = ollamaUrl;
216
- ui.ok(`Ollama at ${ollamaUrl}`);
217
- }
218
- else if (provider === "claude-code" || provider === "codex") {
219
- ui.ok(`Using local ${provider} CLI — no API key needed`);
220
- }
221
- else {
222
- const apiKey = await ui.promptSecret("API key");
223
- if (apiKey) {
224
- values.LLM_API_KEY = apiKey;
225
- ui.ok(`${provider} key set`);
237
+ else if (provider === "ollama") {
238
+ const ollamaUrl = await ui.prompt("Ollama URL", "http://127.0.0.1:11434");
239
+ values.OLLAMA_URL = ollamaUrl;
240
+ ui.ok(`Ollama at ${ollamaUrl}`);
241
+ }
242
+ else if (provider === "claude-code" || provider === "codex") {
243
+ ui.ok(`Using local ${provider} CLI — no API key needed`);
226
244
  }
227
245
  else {
228
- ui.fail("No API key provided");
229
- ui.hint(`Set LLM_API_KEY in .env later`);
246
+ const apiKey = await ui.promptSecret("API key");
247
+ if (apiKey) {
248
+ values.LLM_API_KEY = apiKey;
249
+ ui.ok(`${provider} key set`);
250
+ }
251
+ else {
252
+ ui.fail("No API key provided");
253
+ ui.hint(`Set LLM_API_KEY in .env later`);
254
+ }
255
+ }
256
+ const defaultModel = (0, config_1.resolveDefaultModel)(provider);
257
+ const model = await ui.prompt("Model", defaultModel);
258
+ values.LLM_MODEL = model;
259
+ if ((0, config_1.isExpensiveModel)(model)) {
260
+ ui.warn(`${model} is expensive. Consider gpt-4o-mini for lower cost.`);
230
261
  }
231
- }
232
- const defaultModel = provider === "clawrouter" ? "blockrun/eco" : provider === "gemini" ? "gemini-2.5-flash" : provider === "anthropic" ? "claude-sonnet-4-5-20250929" : provider === "deepseek" ? "deepseek-chat" : provider === "qwen" ? "qwen-plus" : provider === "claude-code" || provider === "codex" ? "default" : "gpt-4o-mini";
233
- const model = await ui.prompt("Model", defaultModel);
234
- values.LLM_MODEL = model;
235
- if ((0, config_1.isExpensiveModel)(model)) {
236
- ui.warn(`${model} is expensive. Consider gpt-4o-mini for lower cost.`);
237
262
  }
238
263
  // Contract addresses
239
264
  values.MINING_AGENT_ADDRESS = config_1.config.miningAgentAddress ?? "";
@@ -294,8 +319,8 @@ async function main() {
294
319
  });
295
320
  program
296
321
  .command("fund")
297
- .description("Fund your wallet — bridge from Solana or send on Base")
298
- .option("--chain <chain>", "Source chain: solana, base")
322
+ .description("Fund your wallet — bridge from Solana/Ethereum or send on Base")
323
+ .option("--chain <chain>", "Source chain: solana, ethereum, base")
299
324
  .option("--token <token>", "Source token: sol, usdc, eth")
300
325
  .option("--amount <eth>", "Target ETH amount (default: 0.005)")
301
326
  .option("--no-swap", "Skip auto-split after bridging")
@@ -350,6 +375,14 @@ async function main() {
350
375
  }
351
376
  await (0, stats_1.displayStats)(tokenId);
352
377
  });
378
+ program
379
+ .command("build-grinders")
380
+ .description("Compile native grinder binaries for GPU/CPU mining (~10-100x faster)")
381
+ .option("--cuda-arch <arch>", "CUDA architecture override (e.g., sm_89)")
382
+ .action(async (opts) => {
383
+ const { buildGrinders } = await Promise.resolve().then(() => __importStar(require("./build")));
384
+ await buildGrinders(opts);
385
+ });
353
386
  const walletCmd = program
354
387
  .command("wallet")
355
388
  .description("Wallet generation and management");
package/dist/miner.js CHANGED
@@ -45,6 +45,7 @@ const detect_1 = require("./detect");
45
45
  const errors_1 = require("./errors");
46
46
  const explorer_1 = require("./explorer");
47
47
  const grinder_1 = require("./grinder");
48
+ const grinder_http_1 = require("./grinder-http");
48
49
  const grinder_native_1 = require("./grinder-native");
49
50
  const smhl_1 = require("./smhl");
50
51
  const ui = __importStar(require("./ui"));
@@ -175,9 +176,25 @@ async function startMining(tokenId) {
175
176
  // Detect native grinders once at startup
176
177
  const grinderInfo = (0, grinder_native_1.detectGrinders)();
177
178
  const useNative = config_1.config.grinderMode !== "js" && (0, grinder_native_1.hasNativeGrinders)(grinderInfo);
178
- const modeLabel = useNative ? (0, grinder_native_1.grinderLabel)(grinderInfo) : `JS (${config_1.config.minerThreads} threads)`;
179
+ const useHttpGrind = (0, grinder_http_1.isHttpGrinderConfigured)();
180
+ const grindUrl = (0, grinder_http_1.getGrindUrl)();
181
+ // Build grinder label
182
+ const labelParts = [];
183
+ if (useNative)
184
+ labelParts.push((0, grinder_native_1.grinderLabel)(grinderInfo));
185
+ if (useHttpGrind) {
186
+ const host = new URL(grindUrl).hostname;
187
+ labelParts.push(`x402 GPU (${host})`);
188
+ }
189
+ if (labelParts.length === 0)
190
+ labelParts.push(`JS (${config_1.config.minerThreads} threads)`);
191
+ const modeLabel = labelParts.join(" + ");
179
192
  await showStartupBanner(tokenId);
180
193
  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.01/grind).")}`);
197
+ }
181
198
  console.log("");
182
199
  while (true) {
183
200
  try {
@@ -277,36 +294,38 @@ async function startMining(tokenId) {
277
294
  }
278
295
  }, STALE_CHECK_INTERVAL_MS);
279
296
  try {
297
+ // Race all available grinders — first valid nonce wins
298
+ const grinders = [];
280
299
  if (useNative) {
281
- try {
282
- grind = await (0, grinder_native_1.grindNonceNative)(challengeNumber, target, account.address, grinderInfo, abortController.signal);
283
- }
284
- catch (err) {
300
+ grinders.push((0, grinder_native_1.grindNonceNative)(challengeNumber, target, account.address, grinderInfo, abortController.signal)
301
+ .catch((err) => {
285
302
  if (abortController.signal.aborted)
286
- throw err; // re-throw abort
287
- nonceSpinner.update("Native grinder failed — falling back to JS...");
288
- grind = await (0, grinder_1.grindNonceParallel)({
289
- challengeNumber,
290
- target,
291
- minerAddress: account.address,
292
- threads: config_1.config.minerThreads,
293
- signal: abortController.signal,
294
- });
295
- }
303
+ throw err;
304
+ // Native failed but don't abort the race — others may still win
305
+ return new Promise(() => { }); // hang forever (race will resolve via another grinder)
306
+ }));
296
307
  }
297
- else {
298
- grind = await (0, grinder_1.grindNonceParallel)({
299
- challengeNumber,
300
- target,
301
- minerAddress: account.address,
302
- threads: config_1.config.minerThreads,
303
- signal: abortController.signal,
304
- onProgress: (attempts, hashrate) => {
305
- const khs = (hashrate / 1000).toFixed(0);
306
- nonceSpinner.update(`Grinding nonce (JS)... ${khs}k H/s (${attempts.toLocaleString()} attempts)`);
307
- },
308
- });
308
+ if (useHttpGrind) {
309
+ grinders.push((0, grinder_http_1.grindNonceHttp)(challengeNumber, target, account.address, grindUrl, config_1.config.privateKey, abortController.signal)
310
+ .catch((err) => {
311
+ if (abortController.signal.aborted)
312
+ throw err;
313
+ return new Promise(() => { });
314
+ }));
309
315
  }
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
+ }));
328
+ grind = await Promise.race(grinders);
310
329
  clearInterval(staleTimer);
311
330
  const khs = grind.hashrate > 0 ? (grind.hashrate / 1000).toFixed(0) : "?";
312
331
  nonceSpinner.stop(`Nonce found (${grind.elapsed.toFixed(1)}s${grind.hashrate > 0 ? `, ${khs}k H/s` : ""})`);