apow-cli 0.10.1 → 0.11.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/.env.example CHANGED
@@ -1,7 +1,9 @@
1
- # === Quick Start (zero credentials) ===
2
- # Just these 2 lines to get started. RPC + LLM auto-pay with USDC from your wallet.
1
+ # === Easy Mode (zero credentials) ===
2
+ # RPC + LLM + remote GPU grind all auto-pay with USDC from your wallet.
3
3
  PRIVATE_KEY=
4
4
  USE_X402=true
5
+ USE_X402_GRIND=true
6
+ ALLOW_LOCAL_FALLBACK_WITH_X402=false
5
7
 
6
8
  # === Custom Configuration (override any defaults below) ===
7
9
 
@@ -31,9 +33,10 @@ USE_X402=true
31
33
  # ETHEREUM_RPC_URL=https://cloudflare-eth.com
32
34
  # SQUID_INTEGRATOR_ID=
33
35
 
34
- # x402 GPU Grinding (remote RTX 4090, $0.01/grind, zero setup)
35
- # Enabled automatically when USE_X402=true. Override with USE_X402_GRIND=false to disable.
36
+ # x402 GPU Grinding (remote RTX 4090, zero setup)
37
+ # Enabled automatically in Easy Mode. Advanced Mode can disable or run a hybrid fallback.
36
38
  # USE_X402_GRIND=true
39
+ # ALLOW_LOCAL_FALLBACK_WITH_X402=true
37
40
  # GRIND_URL=https://grind.apow.io/grind
38
41
 
39
42
  # GPU Mining (optional — auto-detected, massive speed boost)
package/README.md CHANGED
@@ -4,6 +4,10 @@ Mining client for the [APoW (Agentic Proof of Work)](https://github.com/Agentosh
4
4
 
5
5
  **Your agent does all the work. You just fund a wallet.**
6
6
 
7
+ `apow setup` is agent-first:
8
+ - `Easy Mode`: no config, x402 for RPC + LLM + GPU grinding
9
+ - `Advanced Mode`: choose which credentials you supply and which services stay autonomous
10
+
7
11
  ## Install
8
12
 
9
13
  ```bash
@@ -27,34 +31,34 @@ npx apow-cli
27
31
 
28
32
  ## For AI Agents
29
33
 
30
- Any AI agent can go from zero to actively mining in 5 steps with no human interaction except funding the wallet.
34
+ Any AI agent can go from zero to actively mining with no human interaction except funding the wallet.
31
35
 
32
36
  ```bash
33
- # 1. Generate a wallet
34
- npx apow-cli wallet new
35
- # → Captures address + private key from stdout
36
-
37
- # 2. Write .env (no interactive prompts)
38
- # LLM config is only needed for minting; mining uses optimized SMHL solving
39
- # RPC: set RPC_URL for a free RPC, or USE_X402=true for auto-pay ($10 USDC)
40
- cat > .env << 'EOF'
41
- PRIVATE_KEY=0x<from step 1>
42
- USE_X402=true
43
- EOF
44
- # USE_X402=true auto-activates clawrouter LLM + QuickNode RPC (both pay with USDC)
45
- # Contract addresses are built-in defaults — no need to specify them
37
+ # 1. Run setup and choose Easy Mode
38
+ npx apow-cli setup
46
39
 
47
- # 3. Fund the wallet (bridge from any chain, auto-splits into ETH + USDC)
40
+ # 2. Fund the wallet (bridge from any chain, auto-splits into ETH + USDC)
48
41
  npx apow-cli fund --chain solana --token sol # bridge SOL → ETH+USDC on Base
49
42
  # Or send ETH/USDC on Base directly
50
43
 
51
- # 4. Mint a mining rig NFT (proves AI via LLM, one-time)
44
+ # 3. Mint a mining rig NFT (proves AI via LLM, one-time)
52
45
  npx apow-cli mint
53
46
 
54
- # 5. Start mining (runs forever, no LLM needed, multi-threaded)
47
+ # 4. Start mining (Easy Mode uses remote x402 GPU by default)
55
48
  npx apow-cli mine
56
49
  ```
57
50
 
51
+ Easy Mode writes an `.env` equivalent to:
52
+
53
+ ```bash
54
+ PRIVATE_KEY=0x...
55
+ USE_X402=true
56
+ USE_X402_GRIND=true
57
+ LLM_PROVIDER=clawrouter
58
+ LLM_MODEL=blockrun/eco
59
+ ALLOW_LOCAL_FALLBACK_WITH_X402=false
60
+ ```
61
+
58
62
  **Scale up** with multiple wallets from a single funded wallet:
59
63
 
60
64
  ```bash
@@ -91,7 +95,7 @@ npx apow-cli mine
91
95
 
92
96
  | Command | Description |
93
97
  |---------|-------------|
94
- | `apow setup` | Interactive setup wizard: configure wallet, RPC, and LLM |
98
+ | `apow setup` | Agent-first setup wizard: Easy Mode (x402 everywhere) or Advanced Mode |
95
99
  | `apow fund` | Fund your wallet: bridge from Solana/Ethereum or send on Base, auto-split ETH+USDC |
96
100
  | `apow wallet new` | Generate a new mining wallet |
97
101
  | `apow wallet show` | Show configured wallet address |
@@ -111,6 +115,8 @@ Create a `.env` file or use `apow setup`:
111
115
  ```bash
112
116
  PRIVATE_KEY=0x... # Your wallet private key
113
117
  USE_X402=true # Auto-pay RPC + LLM via x402 ($10 USDC for ~1M calls, zero API keys)
118
+ USE_X402_GRIND=true # Auto-pay remote GPU grinding via x402
119
+ ALLOW_LOCAL_FALLBACK_WITH_X402=false # Easy Mode default: do not burn local CPU while x402 GPU is active
114
120
  # RPC_URL=https://... # Or: bring your own RPC (free from Alchemy, QuickNode, etc.)
115
121
  # LLM_PROVIDER=clawrouter # clawrouter (auto with x402) | openai | gemini | deepseek | qwen | anthropic | ollama (for minting)
116
122
  # LLM_MODEL=blockrun/eco # Auto-detected per provider; override only if needed
@@ -169,15 +175,17 @@ apow fund --chain base --no-swap
169
175
  No GPU? No problem. Remote RTX 4090 nonce grinding via the [x402 payment protocol](https://www.x402.org/) — ~$0.006/grind (dynamic pricing tracks actual GPU cost), zero setup:
170
176
 
171
177
  ```bash
172
- # In your .env (enabled automatically when USE_X402=true)
178
+ # In your .env (enabled automatically in Easy Mode)
173
179
  USE_X402_GRIND=true
180
+ # ALLOW_LOCAL_FALLBACK_WITH_X402=true # Advanced Mode hybrid option
174
181
  ```
175
182
 
176
- The HTTP grinder races alongside any local grinders you have. First valid nonce wins. Front-running is cryptographically impossible — nonces are bound to `keccak256(challenge, msg.sender, nonce)`.
183
+ In Easy Mode, the HTTP grinder is the only nonce source, so agents do not silently burn local CPU while remote x402 GPU mining is active. Advanced Mode can opt into a hybrid local fallback. Front-running is cryptographically impossible — nonces are bound to `keccak256(challenge, msg.sender, nonce)`.
177
184
 
178
185
  | Config | Description |
179
186
  |--------|-------------|
180
187
  | `USE_X402_GRIND` | Enable remote GPU grinding (default: same as `USE_X402`) |
188
+ | `ALLOW_LOCAL_FALLBACK_WITH_X402` | Let local JS fallback run alongside x402 GPU (`false` in Easy Mode) |
181
189
  | `GRIND_URL` | Custom GrindProxy endpoint (default: `https://grind.apow.io/grind`) |
182
190
 
183
191
  Self-host your own GrindProxy: see [apow-grind](https://github.com/Agentoshi/apow-grind).
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
+ allowLocalFallbackWithX402: process.env.ALLOW_LOCAL_FALLBACK_WITH_X402 === "true",
117
118
  staleCheckIntervalMs: parseInt(process.env.STALE_CHECK_INTERVAL ?? "60", 10) * 1000,
118
119
  };
119
120
  function requirePrivateKey() {
package/dist/errors.js CHANGED
@@ -121,12 +121,12 @@ const patterns = [
121
121
  test: (m) => m.includes("Remote GPU grind timed out") || (m.includes("GrindProxy") && /\b504\b/.test(m)),
122
122
  classify: () => ({
123
123
  category: "transient",
124
- userMessage: "Remote GPU grind timed out (90s)",
124
+ userMessage: "Remote GPU grind timed out (120s)",
125
125
  recovery: "High difficulty — local grinders may still find a nonce.",
126
126
  }),
127
127
  },
128
128
  {
129
- test: (m) => m.includes("x402 GPU grind payment failed"),
129
+ test: (m) => m.includes("x402 GPU grind payment failed") || m.includes("No matching payment requirements"),
130
130
  classify: () => ({
131
131
  category: "setup",
132
132
  userMessage: "Insufficient USDC for x402 GPU grinding",
@@ -52,6 +52,9 @@ const config_1 = require("./config");
52
52
  const DEFAULT_GRIND_URL = "https://grind.apow.io/grind";
53
53
  // Lazy singleton — created on first grind, reused across calls
54
54
  let _fetchWithPayment = null;
55
+ function resetPaymentFetch() {
56
+ _fetchWithPayment = null;
57
+ }
55
58
  async function getPaymentFetch(privateKey) {
56
59
  if (_fetchWithPayment)
57
60
  return _fetchWithPayment;
@@ -71,9 +74,8 @@ function getGrindUrl() {
71
74
  return config_1.config.grindUrl ?? DEFAULT_GRIND_URL;
72
75
  }
73
76
  async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, privateKey, signal) {
74
- const paidFetch = await getPaymentFetch(privateKey);
75
77
  const start = process.hrtime();
76
- const response = await paidFetch(grindUrl, {
78
+ const requestInit = {
77
79
  method: "POST",
78
80
  headers: { "Content-Type": "application/json" },
79
81
  body: JSON.stringify({
@@ -82,17 +84,48 @@ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, p
82
84
  address: minerAddress,
83
85
  }),
84
86
  signal,
85
- });
86
- if (!response.ok) {
87
+ };
88
+ let response = null;
89
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
90
+ const paidFetch = await getPaymentFetch(privateKey);
91
+ response = await paidFetch(grindUrl, requestInit);
92
+ if (response.ok) {
93
+ break;
94
+ }
87
95
  const body = await response.text().catch(() => "");
96
+ const paymentRequiredB64 = response.headers.get("payment-required");
97
+ let reason = "";
98
+ if (paymentRequiredB64) {
99
+ try {
100
+ const decoded = JSON.parse(Buffer.from(paymentRequiredB64, "base64").toString());
101
+ reason = decoded.error || "";
102
+ }
103
+ catch { /* ignore decode errors */ }
104
+ }
105
+ const combinedError = `${reason} ${body}`.trim();
106
+ if (attempt === 1 && combinedError.includes("No matching payment requirements")) {
107
+ resetPaymentFetch();
108
+ continue;
109
+ }
88
110
  if (response.status === 402) {
89
- throw new Error(`x402 GPU payment failed (402): ${body.slice(0, 300) || "no response body"}`);
111
+ if (reason.includes("insufficient_balance")) {
112
+ throw new Error("x402 GPU payment failed: insufficient USDC balance");
113
+ }
114
+ else if (reason.includes("simulation_failed")) {
115
+ throw new Error(`x402 GPU payment failed: EVM simulation failed (USDC approval issue?) [${reason}]`);
116
+ }
117
+ else {
118
+ throw new Error(`x402 GPU payment failed: ${reason || body.slice(0, 200) || "unknown"}`);
119
+ }
90
120
  }
91
121
  if (response.status === 504) {
92
- throw new Error("Remote GPU grind timed out (90s)");
122
+ throw new Error("Remote GPU grind timed out (120s)");
93
123
  }
94
124
  throw new Error(`GrindProxy HTTP ${response.status}: ${body.slice(0, 200)}`);
95
125
  }
126
+ if (!response || !response.ok) {
127
+ throw new Error("x402 GPU payment failed: no successful response");
128
+ }
96
129
  const data = (await response.json());
97
130
  if (!data.nonce) {
98
131
  throw new Error("GrindProxy returned no nonce");
package/dist/index.js CHANGED
@@ -93,7 +93,7 @@ async function resolveTokenId(tokenIdArg) {
93
93
  }
94
94
  if (!wallet_1.account) {
95
95
  ui.error("No token ID provided and no wallet configured.");
96
- ui.hint("Usage: apow mine <tokenId> or configure PRIVATE_KEY in .env");
96
+ ui.hint("Usage: apow mine <tokenId>, or run `apow setup` and choose Easy Mode");
97
97
  process.exit(1);
98
98
  }
99
99
  const miners = await (0, detect_1.detectMiners)(wallet_1.account.address);
@@ -117,27 +117,33 @@ async function resolveTokenId(tokenIdArg) {
117
117
  }
118
118
  async function setupWizard() {
119
119
  console.log("");
120
- ui.banner(["AgentCoin Miner Setup"]);
120
+ ui.banner(["APoW Agent Setup"]);
121
121
  console.log("");
122
122
  // Mode selection
123
- console.log(` ${ui.bold("How do you want to configure?")}`);
123
+ console.log(` ${ui.bold("Choose an operating mode")}`);
124
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.")}`);
125
+ console.log(` ${ui.cyan("1.")} Easy Mode ${ui.dim("(recommended)")}`);
126
+ console.log(` ${ui.dim("No config. Wallet + x402 RPC + x402 LLM + x402 GPU grind.")}`);
127
+ console.log(` ${ui.cyan("2.")} Advanced Mode`);
128
+ console.log(` ${ui.dim("Choose which parts your agent manages and which credentials you supply.")}`);
129
129
  console.log("");
130
130
  const modeInput = await ui.prompt("Choice", "1");
131
- const quickStart = modeInput !== "2";
131
+ const easyMode = modeInput !== "2";
132
132
  console.log("");
133
- const totalSteps = quickStart ? 2 : 3;
133
+ const totalSteps = easyMode ? 2 : 4;
134
134
  const values = {};
135
135
  // Step 1: Wallet
136
136
  console.log(` ${ui.bold(`Step 1/${totalSteps}: Wallet`)}`);
137
- const hasWallet = await ui.confirm("Do you have a Base wallet?");
137
+ console.log(` ${ui.dim("Your agent can manage a wallet for you, or you can supply your own.")}`);
138
+ console.log("");
139
+ console.log(` ${ui.cyan("1.")} Agent-managed wallet ${ui.dim("(generate one now)")}`);
140
+ console.log(` ${ui.cyan("2.")} Existing wallet ${ui.dim("(paste private key)")}`);
141
+ console.log("");
142
+ const walletMode = await ui.prompt("Wallet choice", "1");
143
+ const useExistingWallet = walletMode === "2";
138
144
  let privateKey;
139
145
  let addr;
140
- if (hasWallet) {
146
+ if (useExistingWallet) {
141
147
  const inputKey = await ui.promptSecret("Private key (0x-prefixed)");
142
148
  if (!inputKey) {
143
149
  ui.error("Private key is required.");
@@ -180,25 +186,31 @@ async function setupWizard() {
180
186
  values.PRIVATE_KEY = privateKey;
181
187
  ui.ok(`Wallet: ${addr.slice(0, 6)}...${addr.slice(-4)}`);
182
188
  console.log("");
183
- if (quickStart) {
184
- // Quick Start: auto-configure x402 + clawrouter
189
+ if (easyMode) {
190
+ // Easy Mode: fully autonomous x402 stack
185
191
  console.log(` ${ui.bold(`Step 2/${totalSteps}: Configuration`)}`);
186
192
  values.USE_X402 = "true";
193
+ values.USE_X402_GRIND = "true";
187
194
  values.LLM_PROVIDER = "clawrouter";
188
195
  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.")}`);
196
+ values.ALLOW_LOCAL_FALLBACK_WITH_X402 = "false";
197
+ ui.ok("RPC: QuickNode x402 (wallet-paid, no API key)");
198
+ ui.ok("LLM: ClawRouter x402 (wallet-paid, no API key)");
199
+ ui.ok("Grinder: x402 GPU (remote, wallet-paid, no local CPU fallback)");
200
+ console.log(` ${ui.dim("Easy mode is agent-first: no RPC key, no LLM key, no GPU rental setup.")}`);
201
+ console.log(` ${ui.dim("Fund the wallet with ETH + USDC on Base, then run: apow mint && apow mine")}`);
192
202
  }
193
203
  else {
194
- // Custom: existing 3-step flow
204
+ // Advanced: user picks which services remain autonomous
195
205
  // Step 2: RPC
196
206
  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) {
207
+ console.log(` ${ui.dim("Choose whether your agent pays for RPC via x402 or you provide your own endpoint.")}`);
208
+ console.log("");
209
+ console.log(` ${ui.cyan("1.")} Agent-managed x402 RPC ${ui.dim("(recommended)")}`);
210
+ console.log(` ${ui.cyan("2.")} Custom RPC URL`);
211
+ console.log("");
212
+ const rpcMode = await ui.prompt("RPC choice", "1");
213
+ if (rpcMode === "2") {
202
214
  const rpcUrl = await ui.prompt("RPC URL");
203
215
  if (rpcUrl) {
204
216
  values.RPC_URL = rpcUrl;
@@ -207,23 +219,21 @@ async function setupWizard() {
207
219
  else {
208
220
  ui.warn("No URL provided — using QuickNode x402");
209
221
  values.USE_X402 = "true";
210
- ui.ok("RPC: QuickNode x402 ($10 USDC for ~1M calls)");
222
+ ui.ok("RPC: QuickNode x402");
211
223
  }
212
224
  }
213
225
  else {
214
226
  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.")}`);
217
- ui.ok("RPC: QuickNode x402 ($10 USDC for ~1M calls)");
227
+ ui.ok("RPC: QuickNode x402 (wallet-paid)");
218
228
  }
219
229
  console.log("");
220
230
  // Step 3: LLM (for minting)
221
- console.log(` ${ui.bold(`Step 3/${totalSteps}: LLM Provider (for minting)`)}`);
231
+ console.log(` ${ui.bold(`Step 3/${totalSteps}: LLM (minting only)`)}`);
222
232
  console.log(` ${ui.dim("An LLM solves the SMHL challenge when minting your Mining Rig.")}`);
223
233
  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.")}`);
234
+ console.log(` ${ui.dim(" clawrouter (recommended) — wallet-paid via x402")}`);
235
+ console.log(` ${ui.dim(" openai / anthropic / gemini / deepseek / qwen — API key")}`);
236
+ console.log(` ${ui.dim(" ollama / claude-code / codex — local")}`);
227
237
  const providerInput = await ui.prompt("Provider", "clawrouter");
228
238
  const provider = (["clawrouter", "openai", "anthropic", "gemini", "ollama", "deepseek", "qwen", "claude-code", "codex"].includes(providerInput) ? providerInput : "clawrouter");
229
239
  values.LLM_PROVIDER = provider;
@@ -259,6 +269,32 @@ async function setupWizard() {
259
269
  if ((0, config_1.isExpensiveModel)(model)) {
260
270
  ui.warn(`${model} is expensive. Consider gpt-4o-mini for lower cost.`);
261
271
  }
272
+ console.log("");
273
+ // Step 4: Nonce grinding strategy
274
+ console.log(` ${ui.bold(`Step 4/${totalSteps}: GPU Grinding`)}`);
275
+ console.log(` ${ui.dim("Choose how the miner should find nonces at current network difficulty.")}`);
276
+ console.log("");
277
+ console.log(` ${ui.cyan("1.")} Agent-managed x402 GPU ${ui.dim("(recommended, no setup)")}`);
278
+ console.log(` ${ui.cyan("2.")} Local / custom grinders only`);
279
+ console.log(` ${ui.cyan("3.")} Hybrid ${ui.dim("(x402 GPU + local JS fallback)")}`);
280
+ console.log("");
281
+ const grindMode = await ui.prompt("Grinding choice", "1");
282
+ if (grindMode === "2") {
283
+ values.USE_X402_GRIND = "false";
284
+ values.ALLOW_LOCAL_FALLBACK_WITH_X402 = "false";
285
+ ui.ok("Grinding: local/custom only");
286
+ ui.hint("Configure GPU_GRINDER_PATH, CUDA_GRINDER_PATH, or VAST_* yourself if needed.");
287
+ }
288
+ else if (grindMode === "3") {
289
+ values.USE_X402_GRIND = "true";
290
+ values.ALLOW_LOCAL_FALLBACK_WITH_X402 = "true";
291
+ ui.ok("Grinding: x402 GPU with local JS fallback");
292
+ }
293
+ else {
294
+ values.USE_X402_GRIND = "true";
295
+ values.ALLOW_LOCAL_FALLBACK_WITH_X402 = "false";
296
+ ui.ok("Grinding: x402 GPU only");
297
+ }
262
298
  }
263
299
  // Contract addresses
264
300
  values.MINING_AGENT_ADDRESS = config_1.config.miningAgentAddress ?? "";
@@ -288,7 +324,9 @@ async function setupWizard() {
288
324
  }
289
325
  }
290
326
  console.log("");
291
- console.log(` Next: ${ui.cyan("apow mint")}`);
327
+ console.log(` Next: ${ui.cyan("apow fund")}`);
328
+ console.log(` ${ui.cyan("apow mint")}`);
329
+ console.log(` ${ui.cyan("apow mine")}`);
292
330
  console.log("");
293
331
  }
294
332
  async function main() {
@@ -313,7 +351,7 @@ async function main() {
313
351
  .version(version);
314
352
  program
315
353
  .command("setup")
316
- .description("Interactive setup wizard — configure wallet, RPC, and LLM")
354
+ .description("Agent-first setup wizard — choose Easy Mode (x402 for everything) or Advanced Mode")
317
355
  .action(async () => {
318
356
  await setupWizard();
319
357
  });
@@ -332,7 +370,7 @@ async function main() {
332
370
  });
333
371
  program
334
372
  .command("mint")
335
- .description("Mint a new miner NFT")
373
+ .description("Mint a new miner NFT (Easy Mode: x402 LLM, no API key)")
336
374
  .hook("preAction", async () => {
337
375
  await (0, preflight_1.runPreflight)("wallet");
338
376
  })
@@ -341,7 +379,7 @@ async function main() {
341
379
  });
342
380
  program
343
381
  .command("mine")
344
- .description("Start the mining loop")
382
+ .description("Start the mining loop (Easy Mode: remote x402 GPU)")
345
383
  .argument("[tokenId]", "Miner token ID (auto-detects if omitted)")
346
384
  .hook("preAction", async () => {
347
385
  await (0, preflight_1.runPreflight)("mining");
@@ -416,7 +454,7 @@ async function main() {
416
454
  .description("Show wallet address from current .env PRIVATE_KEY")
417
455
  .action(async () => {
418
456
  if (!wallet_1.account) {
419
- ui.error("No wallet configured. Set PRIVATE_KEY in .env or run: apow wallet new");
457
+ ui.error("No wallet configured. Run `apow setup` and choose Easy Mode, or set PRIVATE_KEY in .env.");
420
458
  return;
421
459
  }
422
460
  console.log("");
@@ -428,7 +466,7 @@ async function main() {
428
466
  .description("Export wallet private key (with confirmation)")
429
467
  .action(async () => {
430
468
  if (!wallet_1.account || !config_1.config.privateKey) {
431
- ui.error("No wallet configured. Set PRIVATE_KEY in .env or run: apow wallet new");
469
+ ui.error("No wallet configured. Run `apow setup` and choose Easy Mode, or set PRIVATE_KEY in .env.");
432
470
  return;
433
471
  }
434
472
  const proceed = await ui.confirm("This will display your private key. Continue?");
package/dist/miner.js CHANGED
@@ -253,20 +253,29 @@ async function startMining(tokenId) {
253
253
  const { account, walletClient } = (0, wallet_1.requireWallet)();
254
254
  let consecutiveFailures = 0;
255
255
  let mineCount = 0;
256
- let runningTotal = 0n;
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);
256
+ let runningTotal = (await wallet_1.publicClient.readContract({
257
+ address: config_1.config.agentCoinAddress,
258
+ abi: agentCoinAbi,
259
+ functionName: "tokenEarnings",
260
+ args: [tokenId],
261
+ }));
260
262
  const useHttpGrind = (0, grinder_http_1.isHttpGrinderConfigured)();
263
+ const x402OnlyMode = useHttpGrind && !config_1.config.allowLocalFallbackWithX402;
264
+ // Detect native grinders only when they can actually participate.
265
+ let grinderInfo = x402OnlyMode
266
+ ? { gpu: null, cuda: null, cpu: null, remoteGpu: false, httpGrind: true }
267
+ : (0, grinder_native_1.detectGrinders)();
268
+ let useNative = !x402OnlyMode && config_1.config.grinderMode !== "js" && !!(grinderInfo.gpu || grinderInfo.cuda || grinderInfo.cpu || grinderInfo.remoteGpu);
261
269
  const grindUrl = (0, grinder_http_1.getGrindUrl)();
262
270
  // Auto-build native grinders on first mine if none detected
263
- if (!useNative && !useHttpGrind && config_1.config.grinderMode !== "js") {
271
+ if (!x402OnlyMode && !useNative && !useHttpGrind && config_1.config.grinderMode !== "js") {
264
272
  const built = autoBuildGrinders();
265
273
  if (built) {
266
274
  grinderInfo = (0, grinder_native_1.detectGrinders)();
267
275
  useNative = !!(grinderInfo.gpu || grinderInfo.cuda || grinderInfo.cpu || grinderInfo.remoteGpu);
268
276
  }
269
277
  }
278
+ const useJsFallback = !useNative && (!useHttpGrind || config_1.config.allowLocalFallbackWithX402);
270
279
  // Build grinder label
271
280
  const labelParts = [];
272
281
  if (useNative)
@@ -275,6 +284,8 @@ async function startMining(tokenId) {
275
284
  const host = new URL(grindUrl).hostname;
276
285
  labelParts.push(`x402 GPU (${host})`);
277
286
  }
287
+ if (useJsFallback)
288
+ labelParts.push(`JS (${config_1.config.minerThreads} threads)`);
278
289
  if (labelParts.length === 0)
279
290
  labelParts.push(`JS (${config_1.config.minerThreads} threads)`);
280
291
  let modeLabel = labelParts.join(" + ");
@@ -400,7 +411,9 @@ async function startMining(tokenId) {
400
411
  }
401
412
  const smhlElapsed = elapsedSeconds(smhlStart);
402
413
  console.log(` ${ui.dim(`SMHL solved (${(smhlElapsed * 1000).toFixed(1)}ms)`)}`);
403
- // Grind nonce — native GPU/CPU if available, JS fallback
414
+ // Grind nonce — x402 GPU is preferred for agent-first easy mode.
415
+ // JS fallback only runs when explicitly allowed, to avoid burning
416
+ // local CPU while a remote GPU grind is already in flight.
404
417
  // Abort and re-fetch challenge periodically to avoid grinding a dead
405
418
  // nonce after another miner wins the block. Configurable via
406
419
  // STALE_CHECK_INTERVAL env var (seconds, default 60).
@@ -452,11 +465,14 @@ async function startMining(tokenId) {
452
465
  if (abortController.signal.aborted)
453
466
  throw err;
454
467
  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")}`);
468
+ if (msg.includes("insufficient USDC")) {
469
+ console.log(` ${ui.yellow("x402 GPU: insufficient USDC.")} Run: ${ui.cyan("apow wallet fund")}`);
470
+ }
471
+ else if (msg.includes("simulation_failed")) {
472
+ console.log(` ${ui.yellow("x402 GPU: EVM simulation failed.")} ${ui.dim("USDC approval or balance issue")}`);
457
473
  }
458
- else if (msg.includes("insufficient USDC")) {
459
- console.log(` ${ui.yellow("x402 GPU needs USDC.")} Run: ${ui.cyan("apow wallet fund")}`);
474
+ else if (msg.includes("402")) {
475
+ console.log(` ${ui.yellow("x402 GPU payment failed.")} ${ui.dim(msg.slice(0, 120))}`);
460
476
  }
461
477
  else {
462
478
  console.log(` ${ui.dim(`x402 GPU grinder error: ${msg}`)}`);
@@ -464,9 +480,8 @@ async function startMining(tokenId) {
464
480
  return new Promise(() => { });
465
481
  }));
466
482
  }
467
- // JS grinder runs unless local native grinders are active.
468
- // Local CPU-C needs those cores, but x402 is remote — no conflict.
469
- if (!useNative) {
483
+ // JS fallback is disabled by default when x402 grinding is active.
484
+ if (useJsFallback) {
470
485
  grinders.push((0, grinder_1.grindNonceParallel)({
471
486
  challengeNumber,
472
487
  target,
@@ -480,9 +495,24 @@ async function startMining(tokenId) {
480
495
  }));
481
496
  }
482
497
  grind = await Promise.race(grinders);
483
- clearInterval(staleTimer);
484
498
  const khs = grind.hashrate > 0 ? (grind.hashrate / 1000).toFixed(0) : "?";
485
499
  nonceSpinner.stop(`Nonce found (${grind.elapsed.toFixed(1)}s${grind.hashrate > 0 ? `, ${khs}k H/s` : ""})`);
500
+ // Final stale check: a challenge can change between the periodic
501
+ // poll and transaction submission, which would make the SMHL stale.
502
+ const latestChallenge = (await wallet_1.publicClient.readContract({
503
+ address: config_1.config.agentCoinAddress,
504
+ abi: agentCoinAbi,
505
+ functionName: "getMiningChallenge",
506
+ }));
507
+ if (latestChallenge[0] !== challengeNumber) {
508
+ staleRestarts++;
509
+ [challengeNumber, target] = [latestChallenge[0], latestChallenge[1]];
510
+ const freshSmhl = (0, smhl_1.normalizeSmhlChallenge)(latestChallenge[2]);
511
+ smhlSolution = (0, smhl_1.solveSmhlAlgorithmic)(freshSmhl);
512
+ console.log(` ${ui.dim("Challenge changed before submit — re-grinding fresh nonce...")}`);
513
+ grind = null;
514
+ continue;
515
+ }
486
516
  }
487
517
  catch (err) {
488
518
  clearInterval(staleTimer);
@@ -504,24 +534,36 @@ async function startMining(tokenId) {
504
534
  grind = null; // loop again
505
535
  continue;
506
536
  }
537
+ nonceSpinner.fail("Grinding nonce failed");
507
538
  throw err; // non-abort error — propagate
508
539
  }
540
+ finally {
541
+ clearInterval(staleTimer);
542
+ }
509
543
  }
510
544
  // Submit transaction with spinner
511
545
  const txSpinner = ui.spinner("Submitting transaction...");
512
- const txHash = await walletClient.writeContract({
513
- address: config_1.config.agentCoinAddress,
514
- abi: agentCoinAbi,
515
- account,
516
- functionName: "mine",
517
- args: [grind.nonce, smhlSolution, tokenId],
518
- });
519
- txSpinner.update("Waiting for confirmation...");
520
- const receipt = await wallet_1.publicClient.waitForTransactionReceipt({ hash: txHash });
521
- if (receipt.status === "reverted") {
522
- throw new Error("Mine transaction reverted on-chain");
546
+ let txHash;
547
+ let receipt;
548
+ try {
549
+ txHash = await walletClient.writeContract({
550
+ address: config_1.config.agentCoinAddress,
551
+ abi: agentCoinAbi,
552
+ account,
553
+ functionName: "mine",
554
+ args: [grind.nonce, smhlSolution, tokenId],
555
+ });
556
+ txSpinner.update("Waiting for confirmation...");
557
+ receipt = await wallet_1.publicClient.waitForTransactionReceipt({ hash: txHash });
558
+ if (receipt.status === "reverted") {
559
+ throw new Error("Mine transaction reverted on-chain");
560
+ }
561
+ txSpinner.stop("Submitting transaction... confirmed");
562
+ }
563
+ catch (err) {
564
+ txSpinner.fail("Submitting transaction failed");
565
+ throw err;
523
566
  }
524
- txSpinner.stop("Submitting transaction... confirmed");
525
567
  // Fetch post-mine earnings with retry (public RPC may lag)
526
568
  let earnings = runningTotal;
527
569
  for (let retry = 0; retry < 5; retry++) {
@@ -540,12 +582,7 @@ async function startMining(tokenId) {
540
582
  console.log(` ${ui.green("+")} ${(0, viem_1.formatEther)(delta)} AGENT | Total: ${(0, viem_1.formatEther)(earnings)} AGENT | Tx: ${ui.dim((0, explorer_1.txUrl)(txHash))}`);
541
583
  console.log("");
542
584
  // Wait for block advancement before next iteration
543
- const lastMineBlock = (await wallet_1.publicClient.readContract({
544
- address: config_1.config.agentCoinAddress,
545
- abi: agentCoinAbi,
546
- functionName: "lastMineBlockNumber",
547
- }));
548
- await waitForNextBlock(lastMineBlock);
585
+ await waitForNextBlock(receipt.blockNumber);
549
586
  consecutiveFailures = 0;
550
587
  }
551
588
  catch (error) {
package/dist/preflight.js CHANGED
@@ -75,7 +75,7 @@ async function runPreflight(level) {
75
75
  results.push({
76
76
  label: "No RPC configured",
77
77
  passed: false,
78
- fix: "Set USE_X402=true in .env (auto-pay with USDC), or set RPC_URL to a Base endpoint, or run `apow setup`",
78
+ fix: "Set USE_X402=true in .env, or run `apow setup` and choose Easy Mode, or set RPC_URL to a Base endpoint",
79
79
  });
80
80
  }
81
81
  // Check x402: USDC balance BEFORE RPC check (can't use x402 without USDC)
@@ -98,7 +98,7 @@ async function runPreflight(level) {
98
98
  results.push({
99
99
  label: "No USDC balance — QuickNode x402 requires USDC on Base",
100
100
  passed: false,
101
- fix: `Send USDC to ${wallet_1.account.address} on Base (~$10 covers ${config_1.config.llmProvider === "clawrouter" ? "both RPC and LLM calls" : "~1M RPC calls"}). Run \`apow fund\` to bridge from Solana.`,
101
+ fix: `Send USDC to ${wallet_1.account.address} on Base (~$10 covers ${config_1.config.llmProvider === "clawrouter" ? "RPC, LLM, and remote GPU grinding" : "~1M RPC calls"}). Run \`apow fund\` to bridge from Solana or Ethereum.`,
102
102
  });
103
103
  }
104
104
  else {
@@ -156,7 +156,7 @@ async function runPreflight(level) {
156
156
  results.push({
157
157
  label: "Private key not configured",
158
158
  passed: false,
159
- fix: "Set PRIVATE_KEY in .env (0x-prefixed 32-byte hex)",
159
+ fix: "Run `apow setup` and choose Easy Mode, or set PRIVATE_KEY in .env (0x-prefixed 32-byte hex)",
160
160
  });
161
161
  }
162
162
  // Check 4: Wallet has ETH
@@ -249,6 +249,7 @@ async function runPreflight(level) {
249
249
  if (level === "mining" && (0, grinder_http_1.isHttpGrinderConfigured)()) {
250
250
  const grindUrl = (0, grinder_http_1.getGrindUrl)();
251
251
  const healthUrl = grindUrl.replace(/\/grind$/, "/health");
252
+ const grinderIsRequired = !config_1.config.allowLocalFallbackWithX402;
252
253
  try {
253
254
  const resp = await fetch(healthUrl, { signal: AbortSignal.timeout(5000) });
254
255
  if (resp.ok) {
@@ -257,15 +258,25 @@ async function runPreflight(level) {
257
258
  }
258
259
  else {
259
260
  results.push({
260
- label: "GrindProxy unreachable (will use local grinders only)",
261
- passed: true, // warn but don't fail — local grinders still work
261
+ label: grinderIsRequired
262
+ ? "GrindProxy unreachable (required in Easy Mode)"
263
+ : "GrindProxy unreachable (will use local grinders only)",
264
+ passed: !grinderIsRequired,
265
+ fix: grinderIsRequired
266
+ ? "Check internet connection, grind.apow.io status, or switch to Advanced Mode with local/custom grinders"
267
+ : undefined,
262
268
  });
263
269
  }
264
270
  }
265
271
  catch {
266
272
  results.push({
267
- label: "GrindProxy unreachable (will use local grinders only)",
268
- passed: true,
273
+ label: grinderIsRequired
274
+ ? "GrindProxy unreachable (required in Easy Mode)"
275
+ : "GrindProxy unreachable (will use local grinders only)",
276
+ passed: !grinderIsRequired,
277
+ fix: grinderIsRequired
278
+ ? "Check internet connection, grind.apow.io status, or switch to Advanced Mode with local/custom grinders"
279
+ : undefined,
269
280
  });
270
281
  }
271
282
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apow-cli",
3
- "version": "0.10.1",
3
+ "version": "0.11.0",
4
4
  "description": "Mine AGENT tokens on Base L2 with Agentic Proof of Work",
5
5
  "keywords": [
6
6
  "apow",
package/skill.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: apow-mine
3
- description: Set up and start mining AGENT tokens on Base L2 using apow-cli. Handles wallet creation, RPC setup, LLM config, minting a rig, and starting the mining loop. Zero credentials needed — only ETH + USDC on Base.
3
+ description: Set up and start mining AGENT tokens on Base L2 using apow-cli. Easy Mode uses x402 for RPC, LLM, and GPU grinding with no config beyond wallet funding.
4
4
  allowed-tools: Bash(npx:*), Bash(node:*), Bash(curl:*)
5
5
  argument-hint: [setup|mint|mine|stats]
6
6
  metadata:
@@ -18,11 +18,11 @@ metadata:
18
18
 
19
19
  > A self-contained guide for any AI agent to go from zero knowledge to actively mining AGENT tokens on Base.
20
20
 
21
- **For AI agents:** You are the operator. You can do everything autonomously: generate wallets,
22
- configure the miner, mint, and mine. The only step that requires your user is funding the wallet
23
- with ETH on Base. Everything else you handle yourself.
21
+ **For AI agents:** You are the operator. You can generate wallets, configure the miner, mint,
22
+ and mine autonomously. The only step that requires your user is funding the wallet with ETH + USDC
23
+ on Base. Everything else you handle yourself.
24
24
 
25
- > **RPC:** You need a Base RPC endpoint. Either set `RPC_URL` in `.env` (free from Alchemy, QuickNode, etc.) or set `USE_X402=true` to auto-pay via [QuickNode x402](https://x402.quicknode.com/) ($10 USDC for ~1M calls, no API key needed). Run `apow setup` to configure interactively.
25
+ > **Easy Mode:** `apow setup` now starts with `Easy Mode` vs `Advanced Mode`. Easy Mode is the default and uses x402 for RPC, LLM, and GPU grinding with no API keys.
26
26
 
27
27
  ---
28
28
 
@@ -30,7 +30,7 @@ with ETH on Base. Everything else you handle yourself.
30
30
 
31
31
  **Via npm (recommended):**
32
32
  ```bash
33
- npx apow-cli setup # interactive wizard: wallet, RPC, LLM config
33
+ npx apow-cli setup # choose Easy Mode for zero-config x402 setup
34
34
  npx apow-cli fund # fund wallet: bridge from Solana or show deposit address
35
35
  npx apow-cli mint # mint a mining rig NFT
36
36
  npx apow-cli mine # start mining (auto-detects your best rig)
@@ -47,20 +47,23 @@ npx tsx src/index.ts mine
47
47
 
48
48
  ### Autonomous Agent Flow — Zero Credentials (non-interactive)
49
49
 
50
- If you're an AI agent, skip the interactive wizard and write the `.env` directly.
51
- **No API keys needed.** ClawRouter pays for LLM inference with USDC from your mining wallet via x402. Same private key, same USDC balance, zero credentials.
50
+ If you're an AI agent, you can skip the wizard and write the `.env` directly.
51
+ **No API keys needed.** The same wallet pays for x402 RPC, x402 LLM, and x402 GPU grinding.
52
52
 
53
53
  ```bash
54
54
  # 1. Generate a wallet
55
55
  npx apow-cli wallet new
56
56
  # Captures address + private key from output (also saved to wallet-<address>.txt)
57
57
 
58
- # 2. Write .env directly — just 2 lines, ZERO API keys needed
59
- # USE_X402=true auto-activates clawrouter LLM + QuickNode RPC (both pay with USDC)
58
+ # 2. Write .env directly — Easy Mode equivalent
60
59
  # Contract addresses are built-in defaults — no need to specify them
61
60
  cat > .env << 'EOF'
62
61
  PRIVATE_KEY=0x<from step 1>
63
62
  USE_X402=true
63
+ USE_X402_GRIND=true
64
+ LLM_PROVIDER=clawrouter
65
+ LLM_MODEL=blockrun/eco
66
+ ALLOW_LOCAL_FALLBACK_WITH_X402=false
64
67
  EOF
65
68
 
66
69
  # 3. Fund the wallet with ETH (gas) + USDC (x402 RPC + LLM payments)
@@ -564,12 +567,13 @@ Supported grinders (all race in parallel -- first nonce wins, falls back to JS a
564
567
  No GPU? Add `USE_X402_GRIND=true` to your `.env` for remote RTX 4090 nonce grinding at ~$0.006/grind (dynamic pricing) via the [x402 payment protocol](https://www.x402.org/). Zero setup, zero API keys — payment is automatic from your mining wallet's USDC balance.
565
568
 
566
569
  ```bash
567
- # In your .env (enabled automatically when USE_X402=true)
570
+ # In your .env (enabled automatically in Easy Mode)
568
571
  USE_X402_GRIND=true
572
+ # ALLOW_LOCAL_FALLBACK_WITH_X402=true # Advanced Mode hybrid option
569
573
  # GRIND_URL=https://grind.apow.io/grind # default, override for self-hosted
570
574
  ```
571
575
 
572
- The HTTP grinder races alongside all local grinders (Metal, CUDA, CPU-C, JS). First valid nonce wins; losers are cancelled. For GPU-less miners, this is a 10-100x speed improvement over JS fallback.
576
+ In Easy Mode, the HTTP grinder is the only nonce source, so agents do not silently burn local CPU while remote x402 GPU mining is active. Advanced Mode can opt into a hybrid local fallback. For GPU-less miners, this is still a 10-100x speed improvement over JS fallback.
573
577
 
574
578
  **Front-running is cryptographically impossible:** nonces are bound to `keccak256(challenge, msg.sender, nonce)` — a nonce ground for address A is useless for address B.
575
579