apow-cli 0.11.11 → 0.11.13

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.
@@ -86,7 +86,8 @@ const swapRouterAbi = [
86
86
  ];
87
87
  /** Get USDC balance for an address on Base. */
88
88
  async function getUsdcBalance(address) {
89
- return (await wallet_1.publicClient.readContract({
89
+ const { publicClient } = (0, wallet_1.getFundingClients)();
90
+ return (await publicClient.readContract({
90
91
  address: USDC,
91
92
  abi: erc20Abi,
92
93
  functionName: "balanceOf",
@@ -98,8 +99,11 @@ async function getUsdcBalance(address) {
98
99
  * Sends ETH as msg.value; router auto-wraps to WETH.
99
100
  */
100
101
  async function swapEthToUsdc(ethAmount, minUsdcOut) {
101
- const { account, walletClient } = (0, wallet_1.requireWallet)();
102
- const txHash = await walletClient.writeContract({
102
+ const walletContext = (0, wallet_1.requireWallet)();
103
+ const { publicClient, walletClient, account } = (0, wallet_1.getFundingClients)();
104
+ const swapWalletClient = walletClient ?? walletContext.walletClient;
105
+ const swapAccount = account ?? walletContext.account;
106
+ const txHash = await swapWalletClient.writeContract({
103
107
  address: SWAP_ROUTER,
104
108
  abi: swapRouterAbi,
105
109
  functionName: "exactInputSingle",
@@ -108,7 +112,7 @@ async function swapEthToUsdc(ethAmount, minUsdcOut) {
108
112
  tokenIn: WETH,
109
113
  tokenOut: USDC,
110
114
  fee: FEE_TIER,
111
- recipient: account.address,
115
+ recipient: swapAccount.address,
112
116
  amountIn: ethAmount,
113
117
  amountOutMinimum: minUsdcOut,
114
118
  sqrtPriceLimitX96: 0n,
@@ -116,12 +120,12 @@ async function swapEthToUsdc(ethAmount, minUsdcOut) {
116
120
  ],
117
121
  value: ethAmount,
118
122
  });
119
- const receipt = await wallet_1.publicClient.waitForTransactionReceipt({ hash: txHash });
123
+ const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
120
124
  if (receipt.status === "reverted") {
121
125
  throw new Error("ETH→USDC swap reverted");
122
126
  }
123
127
  // Read USDC balance after swap to report actual amount
124
- const usdcBal = await getUsdcBalance(account.address);
128
+ const usdcBal = await getUsdcBalance(swapAccount.address);
125
129
  return { txHash, usdcReceived: (0, viem_1.formatUnits)(usdcBal, 6) };
126
130
  }
127
131
  /**
@@ -129,22 +133,25 @@ async function swapEthToUsdc(ethAmount, minUsdcOut) {
129
133
  * Approves USDC (if needed), then multicalls [exactInputSingle, unwrapWETH9].
130
134
  */
131
135
  async function swapUsdcToEth(usdcAmount, minEthOut) {
132
- const { account, walletClient } = (0, wallet_1.requireWallet)();
136
+ const walletContext = (0, wallet_1.requireWallet)();
137
+ const { publicClient, walletClient, account } = (0, wallet_1.getFundingClients)();
138
+ const swapWalletClient = walletClient ?? walletContext.walletClient;
139
+ const swapAccount = account ?? walletContext.account;
133
140
  // Check and set USDC allowance
134
- const allowance = (await wallet_1.publicClient.readContract({
141
+ const allowance = (await publicClient.readContract({
135
142
  address: USDC,
136
143
  abi: erc20Abi,
137
144
  functionName: "allowance",
138
- args: [account.address, SWAP_ROUTER],
145
+ args: [swapAccount.address, SWAP_ROUTER],
139
146
  }));
140
147
  if (allowance < usdcAmount) {
141
- const approveTx = await walletClient.writeContract({
148
+ const approveTx = await swapWalletClient.writeContract({
142
149
  address: USDC,
143
150
  abi: erc20Abi,
144
151
  functionName: "approve",
145
152
  args: [SWAP_ROUTER, usdcAmount],
146
153
  });
147
- await wallet_1.publicClient.waitForTransactionReceipt({ hash: approveTx });
154
+ await publicClient.waitForTransactionReceipt({ hash: approveTx });
148
155
  }
149
156
  // Encode exactInputSingle: USDC → WETH, recipient = SWAP_ROUTER (so it holds WETH)
150
157
  const swapData = (0, viem_1.encodeFunctionData)({
@@ -166,19 +173,19 @@ async function swapUsdcToEth(usdcAmount, minEthOut) {
166
173
  const unwrapData = (0, viem_1.encodeFunctionData)({
167
174
  abi: swapRouterAbi,
168
175
  functionName: "unwrapWETH9",
169
- args: [minEthOut, account.address],
176
+ args: [minEthOut, swapAccount.address],
170
177
  });
171
178
  const deadline = BigInt(Math.floor(Date.now() / 1000) + 300); // 5 min
172
- const txHash = await walletClient.writeContract({
179
+ const txHash = await swapWalletClient.writeContract({
173
180
  address: SWAP_ROUTER,
174
181
  abi: swapRouterAbi,
175
182
  functionName: "multicall",
176
183
  args: [deadline, [swapData, unwrapData]],
177
184
  });
178
- const receipt = await wallet_1.publicClient.waitForTransactionReceipt({ hash: txHash });
185
+ const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
179
186
  if (receipt.status === "reverted") {
180
187
  throw new Error("USDC→ETH swap reverted");
181
188
  }
182
- const ethBal = await wallet_1.publicClient.getBalance({ address: account.address });
189
+ const ethBal = await publicClient.getBalance({ address: swapAccount.address });
183
190
  return { txHash, ethReceived: (0, viem_1.formatEther)(ethBal) };
184
191
  }
package/dist/fund.js CHANGED
@@ -50,6 +50,17 @@ const squid_1 = require("./bridge/squid");
50
50
  const uniswap_1 = require("./bridge/uniswap");
51
51
  const wallet_1 = require("./wallet");
52
52
  const ui = __importStar(require("./ui"));
53
+ function showNonInteractiveFundingExamples() {
54
+ console.log("");
55
+ ui.warn("Headless funding needs an explicit route.");
56
+ ui.hint("Choose the source chain and token up front, then rerun one of:");
57
+ ui.hint("apow fund --chain base --token eth");
58
+ ui.hint("apow fund --chain base --token usdc");
59
+ ui.hint("apow fund --chain solana --token sol");
60
+ ui.hint("apow fund --chain solana --token usdc");
61
+ ui.hint("apow fund --chain ethereum");
62
+ console.log("");
63
+ }
53
64
  async function fetchPrices() {
54
65
  const res = await fetch("https://api.coingecko.com/api/v3/simple/price?ids=solana,ethereum&vs_currencies=usd");
55
66
  if (!res.ok)
@@ -491,10 +502,24 @@ async function runFundFlow(options) {
491
502
  ui.error("No wallet configured. Run `apow setup` first.");
492
503
  process.exit(1);
493
504
  }
505
+ const interactive = ui.isInteractiveSession();
494
506
  const baseAddress = wallet_1.account.address;
507
+ const noSwap = options.swap === false;
508
+ // Parse target ETH amount
509
+ const targetEth = options.amount ? parseFloat(options.amount) : 0.005;
510
+ if (isNaN(targetEth) || targetEth <= 0) {
511
+ ui.error("Invalid amount. Specify ETH target (e.g., --amount 0.005).");
512
+ return;
513
+ }
514
+ // Resolve source chain and token (from flags or interactive)
515
+ let chain = parseSourceChain(options.chain);
516
+ let token = parseSourceToken(options.token);
517
+ if (!interactive && (!chain || (chain !== "ethereum" && !token))) {
518
+ showNonInteractiveFundingExamples();
519
+ return;
520
+ }
495
521
  const ethBalance = Number((0, viem_1.formatEther)(await (0, wallet_1.getEthBalance)()));
496
522
  const usdcBalance = Number((0, viem_1.formatUnits)(await (0, uniswap_1.getUsdcBalance)(baseAddress), 6));
497
- const noSwap = options.swap === false;
498
523
  console.log("");
499
524
  ui.banner(["Fund Your Mining Wallet"]);
500
525
  console.log("");
@@ -509,7 +534,7 @@ async function runFundFlow(options) {
509
534
  console.log(` ${ui.green("Already funded! Ready to mint.")}`);
510
535
  console.log(` Next: ${ui.cyan("apow mint")}`);
511
536
  console.log("");
512
- if (!ui.isInteractiveSession()) {
537
+ if (!interactive) {
513
538
  return;
514
539
  }
515
540
  // Allow explicit re-run if user wants to add more
@@ -517,15 +542,6 @@ async function runFundFlow(options) {
517
542
  if (!addMore)
518
543
  return;
519
544
  }
520
- // Parse target ETH amount
521
- const targetEth = options.amount ? parseFloat(options.amount) : 0.005;
522
- if (isNaN(targetEth) || targetEth <= 0) {
523
- ui.error("Invalid amount. Specify ETH target (e.g., --amount 0.005).");
524
- return;
525
- }
526
- // Resolve source chain and token (from flags or interactive)
527
- let chain = parseSourceChain(options.chain);
528
- let token = parseSourceToken(options.token);
529
545
  if (!chain) {
530
546
  chain = await selectSourceChain();
531
547
  }
package/dist/index.js CHANGED
@@ -353,6 +353,21 @@ async function setupWizard() {
353
353
  console.log(` ${ui.dim("Guided happy path: setup -> fund -> mint -> mine")}`);
354
354
  console.log("");
355
355
  }
356
+ function showHeadlessFundingHandoff(address, needsEth, needsUsdc) {
357
+ ui.warn("Headless session detected — pausing before funding.");
358
+ ui.hint(`Send funds to ${address} on Base.`);
359
+ if (needsEth) {
360
+ ui.hint(`Need at least ${constants_1.MIN_ETH} ETH for gas and minting.`);
361
+ }
362
+ if (needsUsdc) {
363
+ ui.hint(`Need at least ${constants_1.MIN_USDC} USDC for QuickNode + ClawRouter x402.`);
364
+ }
365
+ ui.hint("Funding routes:");
366
+ ui.hint("Direct on Base: send ETH and/or USDC to this wallet");
367
+ ui.hint("Bridge from Solana: apow fund --chain solana --token sol");
368
+ ui.hint("Bridge from Ethereum: apow fund --chain ethereum");
369
+ ui.hint("After funds arrive, rerun `apow start`.");
370
+ }
356
371
  async function runStartFlow() {
357
372
  if (!config_1.config.privateKey || !wallet_1.account) {
358
373
  console.log("");
@@ -418,6 +433,10 @@ async function runStartFlow() {
418
433
  ["USDC", config_1.config.useX402 ? (balanceChecksAvailable ? `${usdcBalance.toFixed(2)} USDC${needsUsdc ? ` (need ≥${constants_1.MIN_USDC})` : ""}` : "unknown (RPC check failed)") : "not required"],
419
434
  ]);
420
435
  console.log("");
436
+ if (!ui.isInteractiveSession()) {
437
+ showHeadlessFundingHandoff(wallet_1.account.address, needsEth, needsUsdc);
438
+ return;
439
+ }
421
440
  const runFunding = await ui.confirm("Run funding flow now?");
422
441
  if (!runFunding) {
423
442
  ui.hint("Fund the wallet, then rerun `apow start`.");
@@ -522,17 +541,25 @@ async function main() {
522
541
  const miningAccount = wallet_1.account;
523
542
  let tokenId;
524
543
  if (tokenIdArg) {
525
- await (0, preflight_1.runPreflight)("mining");
526
544
  tokenId = parseTokenId(tokenIdArg);
545
+ await (0, preflight_1.runPreflight)("mining");
527
546
  }
528
547
  else {
529
- const miners = await (0, detect_1.detectMiners)(miningAccount.address);
548
+ await (0, preflight_1.runPreflight)("mining");
549
+ let miners;
550
+ try {
551
+ miners = await (0, detect_1.detectMiners)(miningAccount.address);
552
+ }
553
+ catch {
554
+ ui.error("Could not detect mining rigs — RPC may be unreachable.");
555
+ ui.hint("Check your RPC_URL or USDC balance for x402, then retry.");
556
+ return;
557
+ }
530
558
  if (miners.length === 0) {
531
559
  ui.warn("No mining rigs found — launching guided start flow.");
532
560
  await runStartFlow();
533
561
  return;
534
562
  }
535
- await (0, preflight_1.runPreflight)("mining");
536
563
  tokenId = (0, detect_1.selectBestMiner)(miners).tokenId;
537
564
  if (miners.length === 1) {
538
565
  console.log(` Using miner #${tokenId} (${miners[0].rarityLabel}, ${(0, detect_1.formatHashpower)(miners[0].hashpower)})`);
package/dist/miner.js CHANGED
@@ -241,26 +241,6 @@ function autoBuildGrinders() {
241
241
  }
242
242
  return built > 0;
243
243
  }
244
- async function grindNonce(challengeNumber, target, minerAddress, onProgress) {
245
- let nonce = 0n;
246
- let attempts = 0n;
247
- const start = process.hrtime();
248
- while (true) {
249
- const digest = BigInt((0, viem_1.keccak256)((0, viem_1.encodePacked)(["bytes32", "address", "uint256"], [challengeNumber, minerAddress, nonce])));
250
- attempts += 1n;
251
- if (digest < target) {
252
- const elapsed = elapsedSeconds(start);
253
- const hashrate = elapsed > 0 ? Number(attempts) / elapsed : Number(attempts);
254
- return { nonce, attempts, hashrate, elapsed };
255
- }
256
- if (onProgress && attempts % 50000n === 0n) {
257
- const elapsed = elapsedSeconds(start);
258
- const hashrate = elapsed > 0 ? Number(attempts) / elapsed : Number(attempts);
259
- onProgress(attempts, hashrate);
260
- }
261
- nonce += 1n;
262
- }
263
- }
264
244
  function toBigInt(value) {
265
245
  return typeof value === "bigint" ? value : BigInt(value);
266
246
  }
@@ -492,7 +472,9 @@ async function startMining(tokenId) {
492
472
  return;
493
473
  staleTimer = setTimeout(async () => {
494
474
  if (staleCheckStopped || abortController.signal.aborted || staleCheckInFlight) {
495
- scheduleStaleCheck();
475
+ // Don't reschedule here — the in-flight check's finally block
476
+ // will reschedule when it completes. Rescheduling here causes
477
+ // exponential timer duplication over long sessions.
496
478
  return;
497
479
  }
498
480
  staleCheckInFlight = true;
@@ -592,6 +574,9 @@ async function startMining(tokenId) {
592
574
  }
593
575
  throw err;
594
576
  }
577
+ // Signal all losing grinders to stop — prevents zombie JS workers,
578
+ // HTTP fetches, and native processes from lingering between mines.
579
+ abortController.abort();
595
580
  const khs = grind.hashrate > 0 ? (grind.hashrate / 1000).toFixed(0) : "?";
596
581
  nonceSpinner.stop(`Nonce found (${grind.elapsed.toFixed(1)}s${grind.hashrate > 0 ? `, ${khs}k H/s` : ""})`);
597
582
  // Final stale check: a challenge can change between the periodic
package/dist/mint.js CHANGED
@@ -156,16 +156,23 @@ async function runMintFlow(options = {}) {
156
156
  for (let attempt = 1; attempt <= 2; attempt += 1) {
157
157
  // Request challenge
158
158
  const challengeSpinner = ui.spinner(`Requesting challenge${attempt > 1 ? ` (retry ${attempt}/2)` : ""}...`);
159
- const challengeTx = await walletClient.writeContract({
160
- address: config_1.config.miningAgentAddress,
161
- abi: miningAgentAbi,
162
- account,
163
- functionName: "getChallenge",
164
- args: [account.address],
165
- });
166
- const challengeReceipt = await wallet_1.publicClient.waitForTransactionReceipt({ hash: challengeTx });
167
- if (challengeReceipt.status === "reverted") {
168
- throw new Error("Challenge request reverted on-chain");
159
+ let challengeReceipt;
160
+ try {
161
+ const challengeTx = await walletClient.writeContract({
162
+ address: config_1.config.miningAgentAddress,
163
+ abi: miningAgentAbi,
164
+ account,
165
+ functionName: "getChallenge",
166
+ args: [account.address],
167
+ });
168
+ challengeReceipt = await wallet_1.publicClient.waitForTransactionReceipt({ hash: challengeTx });
169
+ if (challengeReceipt.status === "reverted") {
170
+ throw new Error("Challenge request reverted on-chain");
171
+ }
172
+ }
173
+ catch (error) {
174
+ challengeSpinner.fail(`Requesting challenge... failed`);
175
+ throw error;
169
176
  }
170
177
  challengeSpinner.stop(`Requesting challenge${attempt > 1 ? ` (retry ${attempt}/2)` : ""}... done`);
171
178
  // Try reading the seed at the exact receipt block to avoid burning the 20s
@@ -206,9 +213,16 @@ async function runMintFlow(options = {}) {
206
213
  // Solve SMHL
207
214
  const challenge = deriveChallengeFromSeed(challengeSeed);
208
215
  const smhlSpinner = ui.spinner("Solving SMHL...");
209
- const solution = await (0, smhl_1.solveSmhlChallenge)(challenge, (smhlAttempt) => {
210
- smhlSpinner.update(`Solving SMHL... attempt ${smhlAttempt}/5`);
211
- });
216
+ let solution;
217
+ try {
218
+ solution = await (0, smhl_1.solveSmhlChallenge)(challenge, (smhlAttempt) => {
219
+ smhlSpinner.update(`Solving SMHL... attempt ${smhlAttempt}/5`);
220
+ });
221
+ }
222
+ catch (error) {
223
+ smhlSpinner.fail("Solving SMHL... failed");
224
+ throw error;
225
+ }
212
226
  smhlSpinner.stop("Solving SMHL... done");
213
227
  // Mint
214
228
  const mintSpinner = ui.spinner("Minting...");
package/dist/preflight.js CHANGED
@@ -132,6 +132,7 @@ async function runPreflight(level) {
132
132
  // Check 2: RPC reachable + chain ID
133
133
  // Skip when: no RPC configured at all, or x402 active but unfunded
134
134
  const hasRpc = config_1.config.useX402 || !!config_1.config.rpcUrl;
135
+ let rpcReachable = false;
135
136
  if (hasRpc && (!config_1.config.useX402 || x402Funded)) {
136
137
  try {
137
138
  const chainId = await wallet_1.publicClient.getChainId();
@@ -144,6 +145,7 @@ async function runPreflight(level) {
144
145
  });
145
146
  }
146
147
  else {
148
+ rpcReachable = true;
147
149
  results.push({ label: `RPC connected — ${config_1.config.chain.name}`, passed: true });
148
150
  }
149
151
  }
@@ -172,8 +174,8 @@ async function runPreflight(level) {
172
174
  fix: "Run `apow setup` and choose Easy Mode, or set PRIVATE_KEY in .env (0x-prefixed 32-byte hex)",
173
175
  });
174
176
  }
175
- // Check 4: Wallet has ETH
176
- if (wallet_1.account) {
177
+ // Check 4: Wallet has ETH (skip if RPC already failed — avoids duplicate errors)
178
+ if (wallet_1.account && rpcReachable) {
177
179
  try {
178
180
  const balance = await wallet_1.publicClient.getBalance({ address: wallet_1.account.address });
179
181
  const ethBalance = Number((0, viem_1.formatEther)(balance));
@@ -279,33 +281,37 @@ async function runPreflight(level) {
279
281
  }
280
282
  }
281
283
  }
282
- // Check 6: Contracts exist on-chain (bytecode check)
283
- try {
284
- const [miningAgentCode, agentCoinCode] = await Promise.all([
285
- wallet_1.publicClient.getCode({ address: config_1.config.miningAgentAddress }),
286
- wallet_1.publicClient.getCode({ address: config_1.config.agentCoinAddress }),
287
- ]);
288
- if (!miningAgentCode || miningAgentCode === "0x") {
289
- results.push({
290
- label: "MiningAgent contract not found on-chain",
291
- passed: false,
292
- fix: "Verify MINING_AGENT_ADDRESS is correct for this network",
293
- });
294
- }
295
- else if (!agentCoinCode || agentCoinCode === "0x") {
296
- results.push({
297
- label: "AgentCoin contract not found on-chain",
298
- passed: false,
299
- fix: "Verify AGENT_COIN_ADDRESS is correct for this network",
300
- });
284
+ // Check 6: Contracts exist on-chain (bytecode check) — skip if RPC is unreachable
285
+ if (!rpcReachable) {
286
+ // Don't pile on errors when RPC is already known to be down
287
+ }
288
+ else
289
+ try {
290
+ const [miningAgentCode, agentCoinCode] = await Promise.all([
291
+ wallet_1.publicClient.getCode({ address: config_1.config.miningAgentAddress }),
292
+ wallet_1.publicClient.getCode({ address: config_1.config.agentCoinAddress }),
293
+ ]);
294
+ if (!miningAgentCode || miningAgentCode === "0x") {
295
+ results.push({
296
+ label: "MiningAgent contract not found on-chain",
297
+ passed: false,
298
+ fix: "Verify MINING_AGENT_ADDRESS is correct for this network",
299
+ });
300
+ }
301
+ else if (!agentCoinCode || agentCoinCode === "0x") {
302
+ results.push({
303
+ label: "AgentCoin contract not found on-chain",
304
+ passed: false,
305
+ fix: "Verify AGENT_COIN_ADDRESS is correct for this network",
306
+ });
307
+ }
308
+ else {
309
+ results.push({ label: "Contracts verified on-chain", passed: true });
310
+ }
301
311
  }
302
- else {
303
- results.push({ label: "Contracts verified on-chain", passed: true });
312
+ catch {
313
+ // Skip if contract addresses not configured (already caught above)
304
314
  }
305
- }
306
- catch {
307
- // Skip if contract addresses not configured (already caught above)
308
- }
309
315
  // Check: GrindProxy reachability (mining only, non-blocking)
310
316
  if (level === "mining" && (0, grinder_http_1.isHttpGrinderConfigured)()) {
311
317
  const grindUrl = (0, grinder_http_1.getGrindUrl)();
package/dist/smhl.js CHANGED
@@ -475,7 +475,9 @@ async function solveSmhlChallenge(challenge, onAttempt) {
475
475
  if (isPermanentProviderError(msg)) {
476
476
  throw new Error(`SMHL solve failed with ${describeProvider(provider)}: ${msg}`);
477
477
  }
478
- feedback = msg;
478
+ // Don't pass network/provider error messages as LLM feedback —
479
+ // it confuses the prompt. Clear feedback so next attempt starts fresh.
480
+ feedback = undefined;
479
481
  lastIssues = `attempt ${attempt} (${describeProvider(provider)}): ${msg}`;
480
482
  break;
481
483
  }
package/dist/wallet.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.walletClient = exports.account = exports.publicClient = void 0;
4
4
  exports.reinitClients = reinitClients;
5
+ exports.getFundingClients = getFundingClients;
5
6
  exports.requireWallet = requireWallet;
6
7
  exports.getEthBalance = getEthBalance;
7
8
  const viem_1 = require("viem");
@@ -10,6 +11,7 @@ const erc8021_1 = require("ox/erc8021");
10
11
  const config_1 = require("./config");
11
12
  const x402_1 = require("./x402");
12
13
  const DATA_SUFFIX = erc8021_1.Attribution.toDataSuffix({ codes: ["bc_6wfeb1kd"] });
14
+ const BASE_BOOTSTRAP_RPC_URL = "https://mainnet.base.org";
13
15
  function getTransport() {
14
16
  if (config_1.config.useX402 && config_1.config.privateKey) {
15
17
  return (0, x402_1.createX402Transport)(config_1.config.privateKey);
@@ -32,6 +34,24 @@ exports.walletClient = exports.account
32
34
  dataSuffix: DATA_SUFFIX,
33
35
  })
34
36
  : null;
37
+ let bootstrapPublicClient = (0, viem_1.createPublicClient)({
38
+ chain: config_1.config.chain,
39
+ transport: (0, viem_1.http)(BASE_BOOTSTRAP_RPC_URL),
40
+ });
41
+ let bootstrapAccount = config_1.config.privateKey
42
+ ? (0, accounts_1.privateKeyToAccount)(config_1.config.privateKey)
43
+ : null;
44
+ let bootstrapWalletClient = bootstrapAccount
45
+ ? (0, viem_1.createWalletClient)({
46
+ account: bootstrapAccount,
47
+ chain: config_1.config.chain,
48
+ transport: (0, viem_1.http)(BASE_BOOTSTRAP_RPC_URL),
49
+ dataSuffix: DATA_SUFFIX,
50
+ })
51
+ : null;
52
+ function shouldUseBootstrapFundingClients() {
53
+ return config_1.config.useX402 && config_1.config.chainName === "base";
54
+ }
35
55
  /** Reinitialize clients after config changes (e.g., x402 fallback). */
36
56
  function reinitClients() {
37
57
  transport = getTransport();
@@ -47,6 +67,31 @@ function reinitClients() {
47
67
  dataSuffix: DATA_SUFFIX,
48
68
  })
49
69
  : null;
70
+ bootstrapPublicClient = (0, viem_1.createPublicClient)({
71
+ chain: config_1.config.chain,
72
+ transport: (0, viem_1.http)(BASE_BOOTSTRAP_RPC_URL),
73
+ });
74
+ bootstrapAccount = config_1.config.privateKey
75
+ ? (0, accounts_1.privateKeyToAccount)(config_1.config.privateKey)
76
+ : null;
77
+ bootstrapWalletClient = bootstrapAccount
78
+ ? (0, viem_1.createWalletClient)({
79
+ account: bootstrapAccount,
80
+ chain: config_1.config.chain,
81
+ transport: (0, viem_1.http)(BASE_BOOTSTRAP_RPC_URL),
82
+ dataSuffix: DATA_SUFFIX,
83
+ })
84
+ : null;
85
+ }
86
+ function getFundingClients() {
87
+ if (shouldUseBootstrapFundingClients()) {
88
+ return {
89
+ publicClient: bootstrapPublicClient,
90
+ account: bootstrapAccount,
91
+ walletClient: bootstrapWalletClient,
92
+ };
93
+ }
94
+ return { publicClient: exports.publicClient, account: exports.account, walletClient: exports.walletClient };
50
95
  }
51
96
  function requireWallet() {
52
97
  if (!exports.account || !exports.walletClient) {
@@ -55,7 +100,8 @@ function requireWallet() {
55
100
  return { account: exports.account, walletClient: exports.walletClient };
56
101
  }
57
102
  async function getEthBalance() {
58
- if (!exports.account)
103
+ const { publicClient: balanceClient, account: balanceAccount } = getFundingClients();
104
+ if (!balanceAccount)
59
105
  return 0n;
60
- return exports.publicClient.getBalance({ address: exports.account.address });
106
+ return balanceClient.getBalance({ address: balanceAccount.address });
61
107
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apow-cli",
3
- "version": "0.11.11",
3
+ "version": "0.11.13",
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,17 +1,14 @@
1
1
  ---
2
2
  name: apow-mine
3
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
- allowed-tools: Bash(npx:*), Bash(node:*), Bash(curl:*)
4
+ allowed-tools: Bash(npx:*), Bash(node:*), Bash(npm:*), Bash(curl:*), Bash(cat:*), Bash(echo:*), Bash(ls:*), Bash(mkdir:*)
5
5
  argument-hint: [setup|mint|mine|stats]
6
6
  metadata:
7
7
  openclaw:
8
8
  requires:
9
- env:
10
- - PRIVATE_KEY
11
9
  anyBins:
12
10
  - npx
13
11
  - node
14
- primaryEnv: PRIVATE_KEY
15
12
  ---
16
13
 
17
14
  # APoW Mining Skill
@@ -22,7 +19,9 @@ metadata:
22
19
  and mine autonomously. The only step that requires your user is funding the wallet with ETH + USDC
23
20
  on Base. Everything else you handle yourself.
24
21
 
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.
22
+ > **Mode guide**
23
+ > - **Easy Mode** (recommended / beginner path): run `npx apow-cli start` or `npx apow-cli setup`, choose `Easy Mode`, let the CLI generate a wallet and private key if needed, then hand the user the funding address. No API keys or pre-existing `PRIVATE_KEY` are required up front.
24
+ > - **Advanced Mode:** bring your own wallet, RPC, LLM, and grinder settings via `.env` or the interactive setup flow.
26
25
 
27
26
  ---
28
27
 
@@ -40,17 +39,35 @@ cd apow-cli && npm install
40
39
  npx tsx src/index.ts start
41
40
  ```
42
41
 
43
- ### Autonomous Agent Flow — Zero Credentials (non-interactive)
42
+ ### Recommended Agent Flow — Easy Mode
44
43
 
45
- If you're an AI agent, you can skip the wizard and write the `.env` directly.
46
- **No API keys needed.** The same wallet pays for x402 RPC, x402 LLM, and x402 GPU grinding.
44
+ For OpenClaw and other interactive agents, start here. Do not ask the user for a `PRIVATE_KEY`
45
+ before running Easy Mode.
46
+
47
+ ```bash
48
+ npx apow-cli start
49
+ ```
50
+
51
+ 1. Choose `Easy Mode`
52
+ 2. If no wallet exists yet, let the CLI generate it and show the new Base address
53
+ 3. Hand the funding address to the user and explain they need ETH for gas + minting and USDC for the x402 stack
54
+ 4. If they want the built-in bridge, use `npx apow-cli fund`; otherwise let them fund the wallet manually
55
+ 5. After funding arrives, rerun `npx apow-cli start` to continue through minting and mining
56
+
57
+ Easy Mode writes the x402-backed config for the user. The manual requirement is funding the newly
58
+ generated wallet, not bringing a private key or API keys ahead of time.
59
+
60
+ ### Headless Fallback — Reproduce Easy Mode Defaults Manually
61
+
62
+ Only use this if the environment cannot drive the interactive CLI prompts. This reproduces the
63
+ same zero-credential x402 stack that Easy Mode would write for you.
47
64
 
48
65
  ```bash
49
66
  # 1. Generate a wallet
50
67
  npx apow-cli wallet new
51
68
  # Captures address + private key from output (and can save a plaintext import helper plus encrypted keystore)
52
69
 
53
- # 2. Write .env directly — Easy Mode equivalent
70
+ # 2. Write .env directly — headless fallback for Easy Mode
54
71
  # Contract addresses are built-in defaults — no need to specify them
55
72
  cat > .env << 'EOF'
56
73
  PRIVATE_KEY=0x<from step 1>
@@ -65,7 +82,12 @@ EOF
65
82
  npx apow-cli start
66
83
  ```
67
84
 
68
- ### Legacy Flow (with API keys)
85
+ In headless shells like OpenClaw, treat funding as a user handoff. Do not run `apow fund`
86
+ without explicit `--chain` and `--token` flags. If `npx apow-cli start` reports that funding
87
+ is needed, show the wallet address, explain the funding options, wait for the user to fund the
88
+ wallet or pick a route, then rerun `npx apow-cli start`.
89
+
90
+ ### Advanced Mode / Manual Flow
69
91
 
70
92
  If you prefer to use your own LLM API key instead of ClawRouter:
71
93
 
@@ -112,29 +134,31 @@ The miner client validates locally before submitting.
112
134
  | Requirement | Details |
113
135
  |---|---|
114
136
  | **Node.js** | v20 or higher |
115
- | **Base wallet** | A private key with ETH on Base (for gas + mint fee) |
116
- | **USDC on Base** | 2.00 USDC minimum starting balance for x402 RPC/ClawRouter; more gives headroom |
117
- | **LLM access** | ClawRouter (zero credentials, recommended) OR API key (OpenAI, Gemini, etc.) OR local Ollama (**required for minting only**) |
137
+ | **Base wallet** | Easy Mode: none up front, the CLI can create one for you. Advanced Mode: existing private key with ETH on Base for gas + mint fee. |
138
+ | **USDC on Base** | 2.00 USDC minimum starting balance in the mining wallet for x402 RPC / ClawRouter / remote grind; more gives headroom |
139
+ | **LLM access** | Easy Mode: none up front, uses ClawRouter via x402. Advanced Mode: API key (OpenAI, Gemini, etc.) or local Ollama for minting. |
118
140
  | **git** | Only if installing from source (not needed for npm) |
119
141
 
120
142
  ---
121
143
 
122
144
  ## 3. Step 1: Create a Mining Wallet
123
145
 
124
- The miner CLI can generate a wallet for you during setup:
146
+ In Easy Mode, the normal path is to let `apow start` or `apow setup` create the mining wallet for
147
+ you. You do not need to arrive with a `PRIVATE_KEY`.
125
148
 
126
149
  ```bash
127
- npx apow-cli setup
150
+ npx apow-cli start
151
+ # Choose "Easy Mode"
128
152
  # Select "No" when asked if you have a wallet → generates one automatically
129
153
  ```
130
154
 
131
- Or generate one directly (useful for agents, no prompts):
155
+ You can also generate one directly (useful for agents, headless shells, or Advanced Mode):
132
156
 
133
157
  ```bash
134
158
  npx apow-cli wallet new
135
159
  ```
136
160
 
137
- This outputs a private key (0x + 64 hex chars) and Base address, saves a plaintext `wallet-<address>.txt` import helper to the current directory, and can also create an encrypted `wallet-<address>.json` keystore under `~/.apow/keystores/` when a password is available. The private key goes in your `.env` as `PRIVATE_KEY`.
161
+ This outputs a private key (0x + 64 hex chars) and Base address, saves a plaintext `wallet-<address>.txt` import helper to the current directory, and can also create an encrypted `wallet-<address>.json` keystore under `~/.apow/keystores/` when a password is available. If you are using a manual or headless flow, put that key in your `.env` as `PRIVATE_KEY`.
138
162
 
139
163
  **Exporting an existing wallet:** If you've already set up a wallet and need to retrieve the key:
140
164
 
@@ -209,7 +233,8 @@ npx apow-cli stats
209
233
 
210
234
  **Via npm (no install needed):**
211
235
  ```bash
212
- npx apow-cli setup
236
+ npx apow-cli start
237
+ # or: npx apow-cli setup
213
238
  ```
214
239
  All `apow` commands work via `npx` with no global install required.
215
240
 
@@ -222,7 +247,10 @@ cd apow-cli && npm install
222
247
 
223
248
  ---
224
249
 
225
- ## 6. Step 3: Configure Environment
250
+ ## 6. Step 3: Configure Environment (Advanced Mode / Manual Setup)
251
+
252
+ Skip this section for Easy Mode. The CLI writes the equivalent config for you during `apow start`
253
+ or `apow setup`. Use a manual `.env` only when you want full control or need a headless fallback.
226
254
 
227
255
  Run `npx apow-cli setup` for interactive configuration, or create a `.env` file manually in your working directory:
228
256
 
@@ -230,9 +258,10 @@ Run `npx apow-cli setup` for interactive configuration, or create a `.env` file
230
258
  # === Required ===
231
259
 
232
260
  # Your wallet private key (0x-prefixed, 64 hex chars)
261
+ # Required for manual / headless minting and mining commands
233
262
  PRIVATE_KEY=0xYOUR_PRIVATE_KEY_HERE
234
263
 
235
- # Deployed contract addresses (set after mainnet deployment)
264
+ # Built-in Base mainnet defaults. Only override if you want a different deployment.
236
265
  MINING_AGENT_ADDRESS=0xB7caD3ca5F2BD8aEC2Eb67d6E8D448099B3bC03D
237
266
  AGENT_COIN_ADDRESS=0x12577CF0D8a07363224D6909c54C056A183e13b3
238
267
 
@@ -250,7 +279,7 @@ LLM_MODEL=blockrun/eco
250
279
 
251
280
  # === Network ===
252
281
 
253
- # Base RPC endpoint (required). Get a free URL from alchemy.com (no credit card).
282
+ # Base RPC endpoint (optional if USE_X402=true). Get a free URL from alchemy.com (no credit card).
254
283
  # Or set USE_X402=true instead for auto-pay via QuickNode (2.00 USDC minimum starting balance; add more for headroom).
255
284
  RPC_URL=https://base-mainnet.g.alchemy.com/v2/YOUR_KEY
256
285
 
@@ -262,16 +291,16 @@ CHAIN=base
262
291
 
263
292
  | Variable | Required | Default | Description |
264
293
  |---|---|---|---|
265
- | `PRIVATE_KEY` | Yes | - | Wallet private key (0x + 64 hex chars) |
294
+ | `PRIVATE_KEY` | Manual / headless only | - | Wallet private key (0x + 64 hex chars). Easy Mode generates this for you if no wallet exists yet. |
266
295
  | `KEYSTORE_PASSWORD` | No | unset | If set, `wallet new`/`wallet export` also create an encrypted JSON keystore backup under `~/.apow/keystores/` |
267
- | `MINING_AGENT_ADDRESS` | Yes | - | Deployed MiningAgent contract address |
268
- | `AGENT_COIN_ADDRESS` | Yes | - | Deployed AgentCoin contract address |
269
- | `LLM_PROVIDER` | For minting | `clawrouter` if `USE_X402=true`, else `openai` | LLM provider for minting: `clawrouter` (recommended, zero credentials), `openai`, `gemini`, `deepseek`, `qwen`, `anthropic`, `ollama`, `claude-code`, `codex`. Not needed for mining. |
270
- | `LLM_API_KEY` | For minting* | - | API key for minting. Not needed for `clawrouter`, `ollama`, `claude-code`, `codex`, or mining. Falls back to `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, `DEEPSEEK_API_KEY`, `DASHSCOPE_API_KEY`. |
271
- | `LLM_MODEL` | For minting | per-provider (e.g. `blockrun/eco`, `gpt-4o-mini`) | Model identifier passed to the provider (minting only). Auto-detected from provider if omitted. |
296
+ | `MINING_AGENT_ADDRESS` | No | built-in Base mainnet address | MiningAgent contract address. Override only for another deployment or network. |
297
+ | `AGENT_COIN_ADDRESS` | No | built-in Base mainnet address | AgentCoin contract address. Override only for another deployment or network. |
298
+ | `LLM_PROVIDER` | No | `clawrouter` if `USE_X402=true`, else `openai` | LLM provider for minting: `clawrouter` (recommended, zero credentials), `openai`, `gemini`, `deepseek`, `qwen`, `anthropic`, `ollama`, `claude-code`, `codex`. Not needed for mining. |
299
+ | `LLM_API_KEY` | Only for cloud providers that require one | - | API key for minting. Not needed for `clawrouter`, `ollama`, `claude-code`, `codex`, or mining. Falls back to `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, `DEEPSEEK_API_KEY`, `DASHSCOPE_API_KEY`. |
300
+ | `LLM_MODEL` | No | per-provider default (e.g. `blockrun/eco`, `gpt-4o-mini`) | Model identifier passed to the provider (minting only). Auto-detected from provider if omitted. |
272
301
  | `CLAWROUTER_PORT` | No | `8402` | Port for ClawRouter local proxy (only if default is in use) |
273
302
  | `MINER_THREADS` | No | All CPU cores | Threads for JS nonce grinding (fallback if no native GPU/CPU grinder detected) |
274
- | `RPC_URL` | Yes* | — | Base JSON-RPC endpoint. Get a free URL from Alchemy or QuickNode. *Not needed if `USE_X402=true`. |
303
+ | `RPC_URL` | No* | — | Base JSON-RPC endpoint. Get a free URL from Alchemy or QuickNode. *Not needed if `USE_X402=true`. |
275
304
  | `USE_X402` | No | `false` | Set to `true` to auto-pay via QuickNode x402 (2.00 USDC minimum starting balance; add more for headroom). Replaces `RPC_URL`. |
276
305
  | `CHAIN` | No | `base` | Network selector; auto-detects `baseSepolia` if RPC URL contains "sepolia" |
277
306
  | `SOLANA_RPC_URL` | No | `https://api.mainnet-beta.solana.com` | Solana RPC endpoint (only for `apow fund --chain solana`) |
@@ -621,10 +650,10 @@ Use the corresponding testnet contract addresses.
621
650
 
622
651
  | Error | Cause | Fix |
623
652
  |---|---|---|
624
- | `PRIVATE_KEY is required for minting and mining commands.` | Missing or unset `PRIVATE_KEY` in `.env` | Add `PRIVATE_KEY=0x...` to your `.env` file |
653
+ | `PRIVATE_KEY is required for minting and mining commands.` | No wallet is configured for the current manual command | Run `npx apow-cli start` and choose Easy Mode to generate one, or add `PRIVATE_KEY=0x...` to your `.env` file |
625
654
  | `PRIVATE_KEY must be a 32-byte hex string prefixed with 0x.` | Malformed private key | Ensure key is exactly `0x` + 64 hex characters |
626
- | `MINING_AGENT_ADDRESS is required.` | Contract address not set | Set `MINING_AGENT_ADDRESS` in `.env` |
627
- | `AGENT_COIN_ADDRESS is required.` | Contract address not set | Set `AGENT_COIN_ADDRESS` in `.env` |
655
+ | `MINING_AGENT_ADDRESS is required.` | Contract address missing or overridden with an invalid value | Remove the bad override to use the built-in default, or set the correct `MINING_AGENT_ADDRESS` in `.env` |
656
+ | `AGENT_COIN_ADDRESS is required.` | Contract address missing or overridden with an invalid value | Remove the bad override to use the built-in default, or set the correct `AGENT_COIN_ADDRESS` in `.env` |
628
657
  | `LLM_API_KEY is required for openai.` | Missing API key for cloud provider | Set `LLM_API_KEY` (or provider-specific key like `OPENAI_API_KEY`) in `.env`, or switch to `ollama` |
629
658
  | `Insufficient fee` | Not enough ETH sent with mint | Check `getMintPrice()` and ensure wallet has enough ETH |
630
659
  | `Sold out` | All 10,000 Miner NFTs minted | No more rigs available; buy one on secondary market |