apow-cli 0.12.3 → 0.12.4

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/README.md CHANGED
@@ -49,7 +49,7 @@ The [managed cloud service](https://apow.io/docs/technical/managed-mining) is in
49
49
  development; the current CLI still needs a runner.
50
50
 
51
51
  ```bash
52
- npx --yes apow-cli@0.12.3 start --easy
52
+ npx --yes apow-cli@0.12.4 start --easy
53
53
  ```
54
54
 
55
55
  Relevant Easy Mode settings include:
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GATEWAY_TOPUP_COOLDOWN_MS = exports.GATEWAY_TOPUP_USDC = exports.GATEWAY_MIN_USDC = void 0;
4
+ exports.getGatewayBalanceUsdc = getGatewayBalanceUsdc;
5
+ exports.gatewayDepositCalls = gatewayDepositCalls;
6
+ exports.lastGatewayDepositAt = lastGatewayDepositAt;
7
+ exports.recordGatewayDeposit = recordGatewayDeposit;
8
+ /**
9
+ * Circle Gateway deposit for Easy Mode's x402 RPC. With a small USDC balance in Gateway, each
10
+ * QuickNode call costs $0.0001 and is settled in batches by Circle, instead of $0.001 and an
11
+ * on-chain USDC transfer per call. The deposit stays the user's: Gateway is a non-custodial
12
+ * contract and the balance can be withdrawn through Circle.
13
+ */
14
+ const node_fs_1 = require("node:fs");
15
+ const node_path_1 = require("node:path");
16
+ const viem_1 = require("viem");
17
+ const paths_1 = require("./policy/paths");
18
+ const decode_1 = require("./policy/decode");
19
+ const GATEWAY_API = "https://gateway-api.circle.com/v1";
20
+ const BASE_GATEWAY_DOMAIN = 6;
21
+ /** Below this the RPC falls back to paying per call; above it the RPC uses nanopayments. */
22
+ exports.GATEWAY_MIN_USDC = 0.005;
23
+ /** One top-up: about 1,000 RPC calls. */
24
+ exports.GATEWAY_TOPUP_USDC = 0.1;
25
+ const ERC20 = (0, viem_1.parseAbi)(["function approve(address spender, uint256 value) returns (bool)", "function allowance(address owner, address spender) view returns (uint256)"]);
26
+ const GATEWAY = (0, viem_1.parseAbi)(["function deposit(address token, uint256 value)"]);
27
+ async function getGatewayBalanceUsdc(depositor, fetchImpl = fetch) {
28
+ try {
29
+ const response = await fetchImpl(`${GATEWAY_API}/balances`, {
30
+ method: "POST",
31
+ headers: { "Content-Type": "application/json" },
32
+ body: JSON.stringify({ token: "USDC", sources: [{ depositor, domain: BASE_GATEWAY_DOMAIN }] }),
33
+ signal: AbortSignal.timeout(10_000),
34
+ });
35
+ if (!response.ok)
36
+ return null;
37
+ const data = await response.json();
38
+ const balance = Number(data.balances?.[0]?.balance ?? "0");
39
+ return Number.isFinite(balance) ? balance : null;
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ /** The two transactions of a deposit, for the guarded wallet to sign under the funding policy. */
46
+ function gatewayDepositCalls(amountUsdc) {
47
+ const value = BigInt(Math.round(amountUsdc * 1_000_000));
48
+ return [
49
+ { to: decode_1.USDC_ADDRESS, data: (0, viem_1.encodeFunctionData)({ abi: ERC20, functionName: "approve", args: [decode_1.CIRCLE_GATEWAY_WALLET, value] }) },
50
+ { to: decode_1.CIRCLE_GATEWAY_WALLET, data: (0, viem_1.encodeFunctionData)({ abi: GATEWAY, functionName: "deposit", args: [decode_1.USDC_ADDRESS, value] }) },
51
+ ];
52
+ }
53
+ /** Circle credits a deposit only after Base finality, so a fresh deposit reads as 0 for a while. */
54
+ exports.GATEWAY_TOPUP_COOLDOWN_MS = 2 * 60 * 60_000;
55
+ function depositLogPath() {
56
+ return (0, node_path_1.join)((0, paths_1.ensureApowDir)(), "gateway-deposits.json");
57
+ }
58
+ function lastGatewayDepositAt(address) {
59
+ const path = depositLogPath();
60
+ if (!(0, node_fs_1.existsSync)(path))
61
+ return 0;
62
+ try {
63
+ return Number(JSON.parse((0, node_fs_1.readFileSync)(path, "utf8"))[address.toLowerCase()] ?? 0);
64
+ }
65
+ catch {
66
+ return 0;
67
+ }
68
+ }
69
+ function recordGatewayDeposit(address, at = Date.now()) {
70
+ const path = depositLogPath();
71
+ let all = {};
72
+ try {
73
+ if ((0, node_fs_1.existsSync)(path))
74
+ all = JSON.parse((0, node_fs_1.readFileSync)(path, "utf8"));
75
+ }
76
+ catch {
77
+ all = {};
78
+ }
79
+ all[address.toLowerCase()] = at;
80
+ (0, node_fs_1.writeFileSync)(path, JSON.stringify(all, null, 2) + "\n", { mode: 0o600 });
81
+ try {
82
+ (0, node_fs_1.chmodSync)(path, 0o600);
83
+ }
84
+ catch { /* best effort */ }
85
+ }
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getStoredCredit = getStoredCredit;
4
+ exports.noteCreditUsed = noteCreditUsed;
5
+ exports.dropCredit = dropCredit;
6
+ exports.packSize = packSize;
7
+ exports.buyCredits = buyCredits;
8
+ /**
9
+ * Prepaid grind credits. One x402 payment buys a small pack from the grind service, and each
10
+ * grind then sends the credit token instead of paying, so it skips an on-chain settlement wait.
11
+ * The pack never costs more than the signing policy's per-request cap.
12
+ */
13
+ const node_crypto_1 = require("node:crypto");
14
+ const node_fs_1 = require("node:fs");
15
+ const node_path_1 = require("node:path");
16
+ const paths_1 = require("./policy/paths");
17
+ const policy_1 = require("./policy/policy");
18
+ const MAX_PACK = 10;
19
+ function creditsPath() {
20
+ return (0, node_path_1.join)((0, paths_1.ensureApowDir)(), "grind-credits.json");
21
+ }
22
+ function readAll() {
23
+ const path = creditsPath();
24
+ if (!(0, node_fs_1.existsSync)(path))
25
+ return {};
26
+ try {
27
+ return JSON.parse((0, node_fs_1.readFileSync)(path, "utf8"));
28
+ }
29
+ catch {
30
+ return {};
31
+ }
32
+ }
33
+ function writeAll(all) {
34
+ const path = creditsPath();
35
+ (0, node_fs_1.writeFileSync)(path, JSON.stringify(all, null, 2) + "\n", { mode: 0o600 });
36
+ try {
37
+ (0, node_fs_1.chmodSync)(path, 0o600);
38
+ }
39
+ catch {
40
+ // Best effort.
41
+ }
42
+ }
43
+ function key(address, service) {
44
+ return `${new URL(service).origin}|${address.toLowerCase()}`;
45
+ }
46
+ function getStoredCredit(address, grindUrl) {
47
+ const entry = readAll()[key(address, grindUrl)];
48
+ return entry && entry.left > 0 ? entry.token : null;
49
+ }
50
+ function noteCreditUsed(address, grindUrl) {
51
+ const all = readAll();
52
+ const entry = all[key(address, grindUrl)];
53
+ if (!entry)
54
+ return;
55
+ entry.left = Math.max(0, entry.left - 1);
56
+ writeAll(all);
57
+ }
58
+ function dropCredit(address, grindUrl) {
59
+ const all = readAll();
60
+ delete all[key(address, grindUrl)];
61
+ writeAll(all);
62
+ }
63
+ /** How many grinds fit under the per-request cap at this unit price (at least 1, at most 10). */
64
+ function packSize(unitPriceUsd, maxPerRequestUsdc) {
65
+ if (!Number.isFinite(unitPriceUsd) || unitPriceUsd <= 0)
66
+ return 1;
67
+ return Math.max(1, Math.min(MAX_PACK, Math.floor((maxPerRequestUsdc + 1e-9) / unitPriceUsd)));
68
+ }
69
+ /**
70
+ * Buys a pack with the given paying fetch. Returns the token, or null when the service has no
71
+ * credits or the purchase failed (the caller then pays per grind as before).
72
+ */
73
+ async function buyCredits(paidFetch, address, grindUrl, signal) {
74
+ const origin = new URL(grindUrl).origin;
75
+ const health = await fetch(`${origin}/health`, { signal: AbortSignal.timeout(15_000) })
76
+ .then((r) => (r.ok ? r.json() : null))
77
+ .catch(() => null);
78
+ const unit = Number(String(health?.price ?? "").replace(/^\$/, ""));
79
+ const grinds = packSize(unit, (0, policy_1.loadPolicy)().x402.maxPerRequestUsdc);
80
+ if (grinds < 2)
81
+ return null; // a pack of one saves nothing over paying per grind
82
+ // The token is ours: made and saved before paying, and only its hash is sent. If the reply
83
+ // is lost the pack is not, because the service switches it on once the payment is on chain.
84
+ const token = "gc_" + (0, node_crypto_1.randomBytes)(32).toString("hex");
85
+ const all = readAll();
86
+ all[key(address, grindUrl)] = { token, left: grinds, service: origin };
87
+ writeAll(all);
88
+ const forget = () => { dropCredit(address, grindUrl); return null; };
89
+ let response;
90
+ try {
91
+ response = await paidFetch(`${origin}/credits`, {
92
+ method: "POST",
93
+ headers: { "Content-Type": "application/json" },
94
+ body: JSON.stringify({ address, grinds, token_hash: (0, node_crypto_1.createHash)("sha256").update(token).digest("hex") }),
95
+ signal,
96
+ });
97
+ }
98
+ catch (err) {
99
+ // Refused before signing (policy cap): nothing was paid, pay per grind instead.
100
+ if (err instanceof Error && err.name === "PolicyDeniedError")
101
+ return forget();
102
+ // Otherwise the payment may be out: keep the token; the service confirms it from the chain.
103
+ return token;
104
+ }
105
+ if (!response.ok) {
106
+ const body = await response.text().catch(() => "");
107
+ let charged;
108
+ try {
109
+ charged = JSON.parse(body).charged;
110
+ }
111
+ catch { /* not JSON */ }
112
+ // x402 never settles a reply of 400 or more, so only a final 402 (payment rejected, or a
113
+ // settlement that failed after the transfer may have gone out) leaves the outcome open.
114
+ if (response.status !== 402 || (charged === false && !response.headers.get("payment-response")))
115
+ return forget();
116
+ return token;
117
+ }
118
+ return token;
119
+ }
@@ -45,10 +45,14 @@ var __importStar = (this && this.__importStar) || (function () {
45
45
  };
46
46
  })();
47
47
  Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.GrindStaleError = exports.GrindBusyError = void 0;
48
49
  exports.isHttpGrinderConfigured = isHttpGrinderConfigured;
49
50
  exports.getGrindUrl = getGrindUrl;
51
+ exports.unchargedStale = unchargedStale;
52
+ exports.uncharged503 = uncharged503;
50
53
  exports.grindNonceHttp = grindNonceHttp;
51
54
  const config_1 = require("./config");
55
+ const grind_credits_1 = require("./grind-credits");
52
56
  const DEFAULT_GRIND_URL = "https://grind.apow.io/grind";
53
57
  // The service allows 300 seconds including cold startup. Leave transport margin.
54
58
  const GRIND_HTTP_TIMEOUT_MS = 330_000;
@@ -90,6 +94,51 @@ function isHttpGrinderConfigured() {
90
94
  function getGrindUrl() {
91
95
  return config_1.config.grindUrl ?? DEFAULT_GRIND_URL;
92
96
  }
97
+ /** The service refused before asking for payment, so nothing was charged and retrying is safe. */
98
+ class GrindBusyError extends Error {
99
+ retryAfterMs;
100
+ constructor(retryAfterMs, detail) {
101
+ super(`Remote GPU busy, nothing charged; retrying in ${Math.round(retryAfterMs / 1000)}s${detail ? ` (${detail})` : ""}`);
102
+ this.name = "GrindBusyError";
103
+ this.retryAfterMs = retryAfterMs;
104
+ }
105
+ }
106
+ exports.GrindBusyError = GrindBusyError;
107
+ /** The chain moved on while the GPU worked; the service refused to charge for the nonce. */
108
+ class GrindStaleError extends Error {
109
+ constructor() {
110
+ super("Challenge changed during the remote grind; nothing charged");
111
+ this.name = "GrindStaleError";
112
+ }
113
+ }
114
+ exports.GrindStaleError = GrindStaleError;
115
+ /** True only for a 409 the service marks stale and uncharged, with no payment receipt. */
116
+ function unchargedStale(status, headers, body) {
117
+ if (status !== 409)
118
+ return false;
119
+ if (headers.get("payment-response") || headers.get("x-payment-response"))
120
+ return false;
121
+ try {
122
+ const parsed = JSON.parse(body);
123
+ return parsed.charged === false && parsed.stale === true;
124
+ }
125
+ catch {
126
+ return false;
127
+ }
128
+ }
129
+ /** True only for a 503 the service marks uncharged, with no payment receipt on the response. */
130
+ function uncharged503(status, headers, body) {
131
+ if (status !== 503)
132
+ return false;
133
+ if (headers.get("payment-response") || headers.get("x-payment-response"))
134
+ return false;
135
+ try {
136
+ return JSON.parse(body).charged === false;
137
+ }
138
+ catch {
139
+ return false;
140
+ }
141
+ }
93
142
  async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, signer, signal) {
94
143
  const start = process.hrtime();
95
144
  const timeoutSignal = AbortSignal.timeout(GRIND_HTTP_TIMEOUT_MS);
@@ -105,15 +154,26 @@ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, s
105
154
  signal: requestSignal,
106
155
  };
107
156
  let response = null;
157
+ let skipCredit = false;
108
158
  for (let attempt = 1; attempt <= 2; attempt += 1) {
109
159
  const paidFetch = await getPaymentFetch(signer);
160
+ // Prepaid credits first: no per-grind payment, so no settlement wait.
161
+ let credit = skipCredit ? null : (0, grind_credits_1.getStoredCredit)(minerAddress, grindUrl);
162
+ if (!credit && !skipCredit && attempt === 1)
163
+ credit = await (0, grind_credits_1.buyCredits)(paidFetch, minerAddress, grindUrl, requestSignal);
110
164
  try {
111
- response = await paidFetch(grindUrl, requestInit);
165
+ response = credit
166
+ ? await fetch(grindUrl, { ...requestInit, headers: { ...requestInit.headers, "X-Grind-Credit": credit } })
167
+ : await paidFetch(grindUrl, requestInit);
112
168
  }
113
169
  catch (err) {
114
170
  if (signal?.aborted) {
115
171
  throw err;
116
172
  }
173
+ if (credit) {
174
+ // No payment was made on this request; a lost reply costs at most one credit.
175
+ throw new Error(`Remote GPU grind request failed (prepaid credit, nothing charged): ${err instanceof Error ? err.message : String(err)}`);
176
+ }
117
177
  if (timeoutSignal.aborted) {
118
178
  resetPaymentFetch();
119
179
  throw new Error(`Remote GPU grind timed out (${GRIND_HTTP_TIMEOUT_MS / 1000}s); payment outcome is unknown`);
@@ -123,8 +183,23 @@ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, s
123
183
  throw new Error(`Remote GPU grind request failed; payment outcome is unknown: ${err instanceof Error ? err.message : String(err)}`);
124
184
  }
125
185
  if (response.ok) {
186
+ if (credit)
187
+ (0, grind_credits_1.noteCreditUsed)(minerAddress, grindUrl);
126
188
  break;
127
189
  }
190
+ if (credit && (response.status === 402 || response.status === 422)) {
191
+ const creditBody = await response.clone().json().catch(() => null);
192
+ if (response.status === 402 && (creditBody?.credits_left === 0 || creditBody?.unknown === true)) {
193
+ // Pack used up or unknown to the service: forget it and buy or pay afresh.
194
+ (0, grind_credits_1.dropCredit)(minerAddress, grindUrl);
195
+ continue;
196
+ }
197
+ if (response.status === 422) {
198
+ // This target costs more than the pack covers: pay for this one grind directly.
199
+ skipCredit = true;
200
+ continue;
201
+ }
202
+ }
128
203
  const body = await response.text().catch(() => "");
129
204
  const bodyDetail = extractErrorDetail(body);
130
205
  const paymentRequiredB64 = response.headers.get("payment-required");
@@ -157,6 +232,17 @@ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, s
157
232
  throw new Error(`x402 GPU payment failed: ${reason || bodyDetail.slice(0, 200) || "unknown"}`);
158
233
  }
159
234
  }
235
+ if (unchargedStale(response.status, response.headers, body)) {
236
+ throw new GrindStaleError();
237
+ }
238
+ if (uncharged503(response.status, response.headers, body)) {
239
+ const seconds = Number(response.headers.get("retry-after"));
240
+ throw new GrindBusyError(Number.isFinite(seconds) && seconds > 0 ? Math.min(seconds, 60) * 1000 : 10_000, bodyDetail.slice(0, 120));
241
+ }
242
+ if (credit && response.status >= 500) {
243
+ // The service refunds the credit when no nonce is delivered; nothing was paid on this request.
244
+ throw new Error(`GrindProxy HTTP ${response.status} (prepaid credit, nothing charged): ${bodyDetail.slice(0, 120)}`);
245
+ }
160
246
  if (response.status === 504) {
161
247
  throw new Error("Remote GPU service timed out; payment outcome is unknown");
162
248
  }
package/dist/grinder.js CHANGED
@@ -44,9 +44,19 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
44
44
  return (mod && mod.__esModule) ? mod : { "default": mod };
45
45
  };
46
46
  Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.LOCAL_GRIND_MAX_EXPECTED_HASHES = void 0;
48
+ exports.isLowDifficulty = isLowDifficulty;
47
49
  exports.grindNonceParallel = grindNonceParallel;
48
50
  const node_worker_threads_1 = require("node:worker_threads");
49
51
  const node_os_1 = __importDefault(require("node:os"));
52
+ /**
53
+ * At or below this many expected hashes, any laptop CPU finds a nonce in well under a second,
54
+ * so a paid remote GPU only adds a fee and a network round trip.
55
+ */
56
+ exports.LOCAL_GRIND_MAX_EXPECTED_HASHES = 1n << 16n;
57
+ function isLowDifficulty(target) {
58
+ return target > 0n && (2n ** 256n) / target <= exports.LOCAL_GRIND_MAX_EXPECTED_HASHES;
59
+ }
50
60
  function hexToBytes(hex) {
51
61
  const h = hex.startsWith("0x") ? hex.slice(2) : hex;
52
62
  const bytes = new Uint8Array(h.length / 2);
package/dist/index.js CHANGED
@@ -64,6 +64,9 @@ const brand_intro_1 = require("./brand-intro");
64
64
  const wallet_store_1 = require("./wallet-store");
65
65
  const wallet_1 = require("./wallet");
66
66
  const context_1 = require("./policy/context");
67
+ const gateway_1 = require("./gateway");
68
+ const decode_1 = require("./policy/decode");
69
+ const x402_1 = require("./x402");
67
70
  const policy_1 = require("./policy/policy");
68
71
  const miningAgentAbi = MiningAgent_json_1.default;
69
72
  const erc20BalanceAbi = [
@@ -106,6 +109,46 @@ function ensureGitignoreSafetyEntries() {
106
109
  (0, node_fs_1.writeFileSync)(gitignorePath, content, "utf8");
107
110
  ui.ok(`Updated .gitignore: added ${missing.join(", ")}`);
108
111
  }
112
+ /**
113
+ * Easy Mode's x402 RPC: keep a small Circle Gateway deposit so calls cost $0.0001 in batches
114
+ * instead of $0.001 and an on-chain transfer each. Skipped when USDC is short; the RPC then
115
+ * keeps paying per call.
116
+ */
117
+ async function topUpGatewayIfLow() {
118
+ const { publicClient: pc, walletClient: wc, account: acct } = (0, wallet_1.getFundingClients)();
119
+ if (!wc || !acct)
120
+ return;
121
+ // A recent deposit may not be credited yet; never stack top-ups while Circle catches up.
122
+ if (Date.now() - (0, gateway_1.lastGatewayDepositAt)(acct.address) < gateway_1.GATEWAY_TOPUP_COOLDOWN_MS)
123
+ return;
124
+ const balance = await (0, gateway_1.getGatewayBalanceUsdc)(acct.address);
125
+ if (balance === null || balance >= gateway_1.GATEWAY_MIN_USDC)
126
+ return;
127
+ const usdc = await pc.readContract({
128
+ address: decode_1.USDC_ADDRESS,
129
+ abi: [{ type: "function", name: "balanceOf", stateMutability: "view", inputs: [{ type: "address" }], outputs: [{ type: "uint256" }] }],
130
+ functionName: "balanceOf",
131
+ args: [acct.address],
132
+ });
133
+ // Keep enough USDC for grinding: only top up from a balance well above the deposit.
134
+ if (Number(usdc) / 1_000_000 < gateway_1.GATEWAY_TOPUP_USDC * 5)
135
+ return;
136
+ (0, context_1.setSignerContext)("fund");
137
+ try {
138
+ for (const call of (0, gateway_1.gatewayDepositCalls)(gateway_1.GATEWAY_TOPUP_USDC)) {
139
+ const hash = await wc.sendTransaction({ account: acct, chain: pc.chain, to: call.to, data: call.data });
140
+ const receipt = await pc.waitForTransactionReceipt({ hash });
141
+ if (receipt.status !== "success")
142
+ throw new Error(`Gateway deposit step reverted: ${hash}`);
143
+ }
144
+ (0, gateway_1.recordGatewayDeposit)(acct.address);
145
+ (0, x402_1.resetX402)();
146
+ ui.ok(`Deposited ${gateway_1.GATEWAY_TOPUP_USDC} USDC to Circle Gateway for x402 RPC at $0.0001 a call (credited after Base finality).`);
147
+ }
148
+ catch (err) {
149
+ ui.warn(`Gateway deposit skipped: ${err instanceof Error ? err.message : String(err)}. RPC keeps paying per call.`);
150
+ }
151
+ }
109
152
  async function getKeystorePassword(required, confirmPassword = true) {
110
153
  const configuredPassword = (0, config_1.resolveKeystorePassword)();
111
154
  if (configuredPassword) {
@@ -579,6 +622,8 @@ async function runStartFlow(options = {}) {
579
622
  showFundingHandoff(wallet_1.account.address, funding.depositEth, options.easyMode === true);
580
623
  return;
581
624
  }
625
+ if (options.easyMode)
626
+ await topUpGatewayIfLow();
582
627
  if (miners.length > 0) {
583
628
  const best = (0, detect_1.selectBestMiner)(miners);
584
629
  console.log(` ${ui.green("Wallet ready.")} Found ${miners.length} rig${miners.length === 1 ? "" : "s"} — starting miner #${best.tokenId}.`);
@@ -932,7 +977,9 @@ async function main() {
932
977
  console.log("");
933
978
  console.log(` Address: ${wallet_1.account.address}`);
934
979
  console.log(` Keystore: ${config_1.config.keystorePath}`);
935
- console.log(` ${ui.dim("Back up this encrypted file and its password separately.")}`);
980
+ const copyPath = (0, wallet_store_1.getKeystoreCopyPath)(wallet_1.account.address);
981
+ console.log(` Copy: ${(0, node_fs_1.existsSync)(copyPath) ? copyPath : `${ui.yellow("missing")} (${copyPath})`}`);
982
+ console.log(` ${ui.dim("Both copies are on this machine. For a lost or broken disk, also copy the file to an external drive or another device, and keep its password separately.")}`);
936
983
  console.log(` ${ui.dim("APoW never prints or writes a plaintext private-key export.")}`);
937
984
  console.log("");
938
985
  });
package/dist/miner.js CHANGED
@@ -57,9 +57,17 @@ const wallet_1 = require("./wallet");
57
57
  const agentCoinAbi = AgentCoin_json_1.default;
58
58
  const miningAgentAbi = MiningAgent_json_1.default;
59
59
  const MAX_CONSECUTIVE_FAILURES = 10;
60
+ // A busy remote GPU refuses before payment; wait it out for up to about 10 minutes.
61
+ const MAX_BUSY_RETRIES = 60;
62
+ // Stale replies in a row before giving up: losing that many races means something is wrong.
63
+ const MAX_STALE_STREAK = 50;
64
+ const STALE_RETRY_DELAY_MS = 1_000;
60
65
  const RETRY_DELAY_MS = 2_000;
61
66
  const RETRY_JITTER_MS = 500;
62
67
  const MAX_MINE_GAS_UNITS = 400000n;
68
+ // A mine uses about 100k gas, more on a difficulty adjustment; unused gas is refunded.
69
+ const FAST_MINE_GAS = 250000n;
70
+ const FEE_CACHE_MS = 30_000;
63
71
  const MIN_MINE_GAS_RESERVE_WEI = (0, viem_1.parseEther)("0.0002");
64
72
  const MINE_GAS_RESERVE_CACHE_MS = 30_000;
65
73
  const NEXT_BLOCK_POLL_MS = 1_500;
@@ -306,6 +314,10 @@ async function showStartupBanner(tokenId) {
306
314
  async function startMining(tokenId, options = {}) {
307
315
  const { account, walletClient } = (0, wallet_1.requireWallet)();
308
316
  let consecutiveFailures = 0;
317
+ let busyRetries = 0;
318
+ let fastNonce = null;
319
+ let feeCache = null;
320
+ let staleStreak = 0;
309
321
  let successfulMines = 0;
310
322
  let mineCount = 0;
311
323
  let runningTotal = (await wallet_1.publicClient.readContract({
@@ -467,7 +479,9 @@ async function startMining(tokenId, options = {}) {
467
479
  let staleRestarts = 0;
468
480
  while (!grind) {
469
481
  const abortController = new AbortController();
470
- const nonceSpinner = ui.spinner(`Grinding nonce (${modeLabel})...`);
482
+ // At low difficulty the user's own CPU finds a nonce at once: skip the paid remote GPU.
483
+ const grindHere = useHttpGrind && (0, grinder_1.isLowDifficulty)(target);
484
+ const nonceSpinner = ui.spinner(`Grinding nonce (${grindHere ? "CPU, low difficulty" : modeLabel})...`);
471
485
  // Background staleness checker
472
486
  let staleTimer = null;
473
487
  let staleCheckStopped = false;
@@ -509,7 +523,10 @@ async function startMining(tokenId, options = {}) {
509
523
  scheduleStaleCheck();
510
524
  }, staleCheckMs);
511
525
  };
512
- scheduleStaleCheck();
526
+ // With only the remote GPU, the grind service checks the challenge itself and never charges
527
+ // for a stale one. Aborting its request mid-flight would cut its cleanup and refund short.
528
+ if (!x402OnlyMode)
529
+ scheduleStaleCheck();
513
530
  try {
514
531
  // Race all available grinders — first valid nonce wins
515
532
  const grinders = [];
@@ -531,7 +548,7 @@ async function startMining(tokenId, options = {}) {
531
548
  throw err;
532
549
  }));
533
550
  }
534
- if (useHttpGrind) {
551
+ if (useHttpGrind && !grindHere) {
535
552
  grinders.push(Promise.race([
536
553
  (0, grinder_http_1.grindNonceHttp)(challengeNumber, target, account.address, grindUrl, account, abortController.signal),
537
554
  rejectOnAbort(abortController.signal),
@@ -556,7 +573,7 @@ async function startMining(tokenId, options = {}) {
556
573
  }));
557
574
  }
558
575
  // JS fallback is disabled by default when x402 grinding is active.
559
- if (useJsFallback) {
576
+ if (useJsFallback || grindHere) {
560
577
  grinders.push(Promise.race([
561
578
  (0, grinder_1.grindNonceParallel)({
562
579
  challengeNumber,
@@ -593,7 +610,9 @@ async function startMining(tokenId, options = {}) {
593
610
  nonceSpinner.stop(`Nonce found (${grind.elapsed.toFixed(1)}s${grind.hashrate > 0 ? `, ${khs}k H/s` : ""})`);
594
611
  // Final stale check: a challenge can change between the periodic
595
612
  // poll and transaction submission, which would make the SMHL stale.
596
- const latestChallenge = await readMiningChallenge();
613
+ // In remote-only mode the grind service has just confirmed the challenge, so skip
614
+ // the extra paid read; every second counts in a race.
615
+ const latestChallenge = x402OnlyMode ? [challengeNumber, target, null] : await readMiningChallenge();
597
616
  if (latestChallenge[0] !== challengeNumber) {
598
617
  staleRestarts++;
599
618
  [challengeNumber, target] = [latestChallenge[0], latestChallenge[1]];
@@ -632,13 +651,42 @@ async function startMining(tokenId, options = {}) {
632
651
  let txHash;
633
652
  let receipt;
634
653
  try {
635
- txHash = await walletClient.writeContract({
636
- address: config_1.config.agentCoinAddress,
637
- abi: agentCoinAbi,
638
- account,
639
- functionName: "mine",
640
- args: [grind.nonce, smhlSolution, tokenId],
641
- });
654
+ if (x402OnlyMode) {
655
+ // Easy Mode pays per RPC call, so send with a known gas limit, nonce and fees: one
656
+ // eth_sendRawTransaction instead of estimate + nonce + fee lookups before every mine.
657
+ if (fastNonce === null)
658
+ fastNonce = await wallet_1.publicClient.getTransactionCount({ address: account.address, blockTag: "pending" });
659
+ if (!feeCache || Date.now() - feeCache.at > FEE_CACHE_MS)
660
+ feeCache = { at: Date.now(), ...(await wallet_1.publicClient.estimateFeesPerGas()) };
661
+ try {
662
+ txHash = await walletClient.writeContract({
663
+ address: config_1.config.agentCoinAddress,
664
+ abi: agentCoinAbi,
665
+ account,
666
+ functionName: "mine",
667
+ args: [grind.nonce, smhlSolution, tokenId],
668
+ gas: FAST_MINE_GAS,
669
+ nonce: fastNonce,
670
+ maxFeePerGas: feeCache.maxFeePerGas,
671
+ maxPriorityFeePerGas: feeCache.maxPriorityFeePerGas,
672
+ });
673
+ fastNonce += 1;
674
+ }
675
+ catch (sendErr) {
676
+ fastNonce = null; // re-read the nonce next time
677
+ feeCache = null;
678
+ throw sendErr;
679
+ }
680
+ }
681
+ else {
682
+ txHash = await walletClient.writeContract({
683
+ address: config_1.config.agentCoinAddress,
684
+ abi: agentCoinAbi,
685
+ account,
686
+ functionName: "mine",
687
+ args: [grind.nonce, smhlSolution, tokenId],
688
+ });
689
+ }
642
690
  txSpinner.update("Waiting for confirmation...");
643
691
  receipt = await wallet_1.publicClient.waitForTransactionReceipt({ hash: txHash });
644
692
  if (receipt.status === "reverted") {
@@ -677,8 +725,24 @@ async function startMining(tokenId, options = {}) {
677
725
  successfulMines += 1;
678
726
  await (0, sweep_1.maybeAutoSweep)(successfulMines);
679
727
  consecutiveFailures = 0;
728
+ busyRetries = 0;
729
+ staleStreak = 0;
680
730
  }
681
731
  catch (error) {
732
+ if (error instanceof grinder_http_1.GrindStaleError && staleStreak < MAX_STALE_STREAK) {
733
+ // Another miner won this block. Start over on the new challenge after a short pause;
734
+ // a long streak means we and the service disagree on the challenge, so stop.
735
+ staleStreak += 1;
736
+ console.log(` ${ui.dim(`${error.message} [${staleStreak}/${MAX_STALE_STREAK}]`)}`);
737
+ await sleep(STALE_RETRY_DELAY_MS);
738
+ continue;
739
+ }
740
+ if (error instanceof grinder_http_1.GrindBusyError && busyRetries < MAX_BUSY_RETRIES) {
741
+ busyRetries += 1;
742
+ console.log(` ${ui.dim(`${error.message} [${busyRetries}/${MAX_BUSY_RETRIES}]`)}`);
743
+ await sleep(error.retryAfterMs);
744
+ continue;
745
+ }
682
746
  const classified = (0, errors_1.classifyError)(error);
683
747
  if (classified.category === "fatal" || classified.category === "setup") {
684
748
  ui.error(classified.userMessage);
package/dist/mint.js CHANGED
@@ -37,6 +37,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.runMintFlow = runMintFlow;
40
+ exports.withGasHeadroom = withGasHeadroom;
40
41
  const viem_1 = require("viem");
41
42
  const MiningAgent_json_1 = __importDefault(require("./abi/MiningAgent.json"));
42
43
  const config_1 = require("./config");
@@ -227,6 +228,15 @@ async function runMintFlow(options = {}) {
227
228
  // Mint
228
229
  const mintSpinner = ui.spinner("Minting...");
229
230
  try {
231
+ // An exact gas estimate left no headroom and a mint ran out of gas on Base (Dec 2 2026).
232
+ const mintGasEstimate = await wallet_1.publicClient.estimateContractGas({
233
+ address: config_1.config.miningAgentAddress,
234
+ abi: miningAgentAbi,
235
+ account,
236
+ functionName: "mint",
237
+ args: [solution],
238
+ value: mintPrice,
239
+ });
230
240
  const mintTx = await walletClient.writeContract({
231
241
  address: config_1.config.miningAgentAddress,
232
242
  abi: miningAgentAbi,
@@ -234,6 +244,7 @@ async function runMintFlow(options = {}) {
234
244
  functionName: "mint",
235
245
  args: [solution],
236
246
  value: mintPrice,
247
+ gas: withGasHeadroom(mintGasEstimate),
237
248
  });
238
249
  mintSpinner.update("Waiting for confirmation...");
239
250
  receipt = await wallet_1.publicClient.waitForTransactionReceipt({ hash: mintTx });
@@ -297,3 +308,7 @@ async function runMintFlow(options = {}) {
297
308
  }
298
309
  return tokenId;
299
310
  }
311
+ /** 30% above the estimate: unused gas is refunded, a too-tight limit loses the whole attempt. */
312
+ function withGasHeadroom(estimate) {
313
+ return (estimate * 13n) / 10n;
314
+ }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SELECTORS = exports.SWAP_ROUTER02 = exports.USDC_ADDRESS = void 0;
3
+ exports.SELECTORS = exports.CIRCLE_GATEWAY_WALLET = exports.SWAP_ROUTER02 = exports.USDC_ADDRESS = void 0;
4
4
  exports.selector = selector;
5
5
  exports.calldataSelector = calldataSelector;
6
6
  exports.readAddressArg = readAddressArg;
@@ -10,16 +10,21 @@ exports.parseErc20Approve = parseErc20Approve;
10
10
  exports.parseEip3009 = parseEip3009;
11
11
  exports.isPermitTypedData = isPermitTypedData;
12
12
  exports.padAddress = padAddress;
13
+ exports.swapRecipients = swapRecipients;
14
+ exports.parseGatewayDeposit = parseGatewayDeposit;
13
15
  const viem_1 = require("viem");
14
16
  const constants_1 = require("../bridge/constants");
15
17
  exports.USDC_ADDRESS = constants_1.TOKENS.base.usdc;
16
18
  exports.SWAP_ROUTER02 = "0x2626664c2603336E57B271c5C0b26F421741e481";
19
+ /** Circle Gateway wallet on Base: holds a small USDC deposit that pays x402 RPC nanopayments. */
20
+ exports.CIRCLE_GATEWAY_WALLET = "0x77777777Dcc4d5A8B6E418Fd04D8997ef11000eE";
17
21
  exports.SELECTORS = {
18
22
  mine: selector("mine(uint256,string,uint256)"),
19
23
  getChallenge: selector("getChallenge(address)"),
20
24
  mint: selector("mint(string)"),
21
25
  transfer: selector("transfer(address,uint256)"),
22
26
  approve: selector("approve(address,uint256)"),
27
+ gatewayDeposit: selector("deposit(address,uint256)"),
23
28
  exactInputSingle: selector("exactInputSingle((address,address,uint24,address,uint256,uint256,uint160))"),
24
29
  multicall: selector("multicall(uint256,bytes[])"),
25
30
  };
@@ -61,7 +66,11 @@ function addressFromUnknown(value) {
61
66
  function parseEip3009(parameters) {
62
67
  const typed = parameters;
63
68
  const verifying = addressFromUnknown(typed.domain?.verifyingContract);
64
- if (!verifying || verifying.toLowerCase() !== exports.USDC_ADDRESS.toLowerCase()) {
69
+ const domainName = typed.domain?.name;
70
+ // Plain USDC EIP-3009, or the same authorization batched through Circle Gateway.
71
+ const usdcDirect = verifying?.toLowerCase() === exports.USDC_ADDRESS.toLowerCase();
72
+ const gatewayBatched = verifying?.toLowerCase() === exports.CIRCLE_GATEWAY_WALLET.toLowerCase() && domainName === "GatewayWalletBatched";
73
+ if (!verifying || (!usdcDirect && !gatewayBatched)) {
65
74
  return null;
66
75
  }
67
76
  if (typed.primaryType !== "TransferWithAuthorization" && typed.primaryType !== "ReceiveWithAuthorization") {
@@ -82,3 +91,42 @@ function isPermitTypedData(parameters) {
82
91
  function padAddress(address) {
83
92
  return (0, viem_1.padHex)(address, { size: 32 });
84
93
  }
94
+ const SWAP_ROUTER_ABI = (0, viem_1.parseAbi)([
95
+ "function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256)",
96
+ "function multicall(uint256 deadline, bytes[] data) payable returns (bytes[])",
97
+ "function unwrapWETH9(uint256 amountMinimum, address recipient) payable",
98
+ "function refundETH() payable",
99
+ ]);
100
+ /** Every address a SwapRouter02 call pays out to, or null when the call is anything else. */
101
+ function swapRecipients(data, depth = 0) {
102
+ let decoded;
103
+ try {
104
+ decoded = (0, viem_1.decodeFunctionData)({ abi: SWAP_ROUTER_ABI, data });
105
+ }
106
+ catch {
107
+ return null;
108
+ }
109
+ if (decoded.functionName === "exactInputSingle")
110
+ return [(0, viem_1.getAddress)(decoded.args[0].recipient)];
111
+ if (decoded.functionName === "unwrapWETH9")
112
+ return [(0, viem_1.getAddress)(decoded.args[1])];
113
+ if (decoded.functionName === "refundETH")
114
+ return [];
115
+ if (decoded.functionName === "multicall" && depth === 0) {
116
+ const all = [];
117
+ for (const inner of decoded.args[1]) {
118
+ const r = swapRecipients(inner, 1);
119
+ if (!r)
120
+ return null;
121
+ all.push(...r);
122
+ }
123
+ return all;
124
+ }
125
+ return null;
126
+ }
127
+ /** A Circle Gateway USDC deposit: deposit(token, value) on the Gateway wallet. */
128
+ function parseGatewayDeposit(data) {
129
+ if (calldataSelector(data) !== exports.SELECTORS.gatewayDeposit)
130
+ return null;
131
+ return { token: readAddressArg(data, 0), amount: readUintArg(data, 1) };
132
+ }
@@ -160,6 +160,9 @@ function evaluateTx(req) {
160
160
  if (!to) {
161
161
  return deny(policy, "contract creation not allowed", "APoW CLI never needs to deploy contracts.");
162
162
  }
163
+ if (req.authorizationList && req.authorizationList.length > 0) {
164
+ return { verdict: "deny", rule: "eip7702-authorization-denied", hint: "APoW CLI never delegates the wallet's code.", kind: "other" };
165
+ }
163
166
  if (data === "0x") {
164
167
  if ((req.context === "sweep" || req.context === "wallet-fund") && value <= (0, viem_1.parseEther)(policy.maxEthTransferEth)) {
165
168
  return allow(policy, "eth-transfer-cap", "eth-send");
@@ -191,10 +194,26 @@ function evaluateTx(req) {
191
194
  if (approve && lower(to) === lower(decode_1.USDC_ADDRESS) && lower(approve.spender) === lower(decode_1.SWAP_ROUTER02) && req.context === "fund") {
192
195
  return allow(policy, "usdc-approve-swaprouter", "fund-swap");
193
196
  }
197
+ // A small Circle Gateway deposit pays Easy Mode's x402 RPC at $0.0001 a call. Bounded by the
198
+ // per-request cap, and only in the funding step.
199
+ const gatewayCap = BigInt(Math.round(policy.x402.maxPerRequestUsdc * 1_000_000));
200
+ if (approve && lower(to) === lower(decode_1.USDC_ADDRESS) && lower(approve.spender) === lower(decode_1.CIRCLE_GATEWAY_WALLET) && req.context === "fund") {
201
+ return approve.amount <= gatewayCap
202
+ ? allow(policy, "usdc-approve-gateway", "fund-swap")
203
+ : deny(policy, "gateway-approve-cap", `Gateway approvals are capped at ${policy.x402.maxPerRequestUsdc} USDC.`, "fund-swap");
204
+ }
205
+ const deposit = (0, decode_1.parseGatewayDeposit)(data);
206
+ if (deposit && lower(to) === lower(decode_1.CIRCLE_GATEWAY_WALLET) && lower(deposit.token) === lower(decode_1.USDC_ADDRESS) && value === 0n && req.context === "fund") {
207
+ return deposit.amount <= gatewayCap
208
+ ? allow(policy, "gateway-deposit", "fund-swap")
209
+ : deny(policy, "gateway-deposit-cap", `Gateway deposits are capped at ${policy.x402.maxPerRequestUsdc} USDC.`, "fund-swap");
210
+ }
194
211
  if (lower(to) === lower(decode_1.SWAP_ROUTER02) && req.context === "fund" && value <= (0, viem_1.parseEther)(policy.maxSwapEth)) {
195
- if (selector === decode_1.SELECTORS.exactInputSingle || selector === decode_1.SELECTORS.multicall) {
212
+ const recipients = (0, decode_1.swapRecipients)(data);
213
+ if (recipients && recipients.every((r) => lower(r) === lower(req.account) || lower(r) === lower(decode_1.SWAP_ROUTER02))) {
196
214
  return allow(policy, "swaprouter-fund", "fund-swap");
197
215
  }
216
+ return deny(policy, "swap-recipient-denied", "Funding swaps may only pay this wallet or the router (for unwrapping).", "fund-swap");
198
217
  }
199
218
  return deny(policy, `unknown-call-${selector}`, "Only APoW mining, minting, configured sweeps, and bounded funding swaps are allowed.");
200
219
  }
package/dist/preflight.js CHANGED
@@ -36,6 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.isClaudeSubscriptionStatus = isClaudeSubscriptionStatus;
39
40
  exports.runPreflight = runPreflight;
40
41
  const node_child_process_1 = require("node:child_process");
41
42
  const viem_1 = require("viem");
@@ -80,7 +81,19 @@ function hasLocalCli(command, env) {
80
81
  }
81
82
  function hasClaudeSubscriptionAuth() {
82
83
  const result = runLocalCliCheck("claude", ["auth", "status"], (0, secure_env_1.claudeSubscriptionEnv)());
83
- return result.passed && /claude\.ai|subscription/i.test(result.output);
84
+ return result.passed && isClaudeSubscriptionStatus(result.output);
85
+ }
86
+ /** Older Claude Code prints "claude.ai"/"subscription"; newer prints JSON with an OAuth login. */
87
+ function isClaudeSubscriptionStatus(output) {
88
+ if (/claude\.ai|subscription/i.test(output))
89
+ return true;
90
+ try {
91
+ const status = JSON.parse(output);
92
+ return status.loggedIn === true && (status.authMethod === "oauth_token" || status.authMethod === "claude.ai");
93
+ }
94
+ catch {
95
+ return false;
96
+ }
84
97
  }
85
98
  function hasCodexSubscriptionAuth() {
86
99
  const result = runLocalCliCheck("codex", ["login", "status"], (0, secure_env_1.codexSubscriptionEnv)());
@@ -396,7 +409,10 @@ async function runPreflight(level) {
396
409
  const healthUrl = grindUrl.replace(/\/grind$/, "/health");
397
410
  const grinderIsRequired = !config_1.config.allowLocalFallbackWithX402;
398
411
  try {
399
- const resp = await fetch(healthUrl, { signal: AbortSignal.timeout(5000) });
412
+ // The service can take a few seconds to answer after idling; try twice before failing.
413
+ let resp = await fetch(healthUrl, { signal: AbortSignal.timeout(15_000) }).catch(() => null);
414
+ if (!resp?.ok)
415
+ resp = await fetch(healthUrl, { signal: AbortSignal.timeout(15_000) });
400
416
  if (resp.ok) {
401
417
  const host = new URL(grindUrl).hostname;
402
418
  results.push({ label: `GrindProxy: ${host} (dynamic pricing)`, passed: true });
@@ -57,8 +57,15 @@ function subscriptionCliEnv(base) {
57
57
  }
58
58
  return next;
59
59
  }
60
+ /** Claude Code's own subscription login when it comes from the environment (`claude setup-token`). Never passed to other tools. */
61
+ const CLAUDE_LOGIN_ENV_KEYS = ["CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CONFIG_DIR"];
60
62
  function claudeSubscriptionEnv(base = process.env) {
61
- return subscriptionCliEnv(base);
63
+ const next = subscriptionCliEnv(base);
64
+ for (const key of CLAUDE_LOGIN_ENV_KEYS) {
65
+ if (base[key])
66
+ next[key] = base[key];
67
+ }
68
+ return next;
62
69
  }
63
70
  function codexSubscriptionEnv(base = process.env) {
64
71
  return subscriptionCliEnv(base);
@@ -9,6 +9,10 @@ const decode_1 = require("../policy/decode");
9
9
  function createGuardedAccount(base) {
10
10
  return {
11
11
  ...base,
12
+ // EIP-7702 delegation would hand the wallet's code to another contract. Never signed.
13
+ async signAuthorization() {
14
+ throw new Error("Policy denied: eip7702-authorization-denied. APoW CLI never delegates the wallet's code.");
15
+ },
12
16
  async signTransaction(transaction, options) {
13
17
  const context = (0, context_1.getSignerContext)();
14
18
  const verdict = (0, policy_1.evaluateTx)({
@@ -16,6 +20,7 @@ function createGuardedAccount(base) {
16
20
  to: transaction.to,
17
21
  value: transaction.value,
18
22
  data: transaction.data,
23
+ authorizationList: transaction.authorizationList,
19
24
  context,
20
25
  });
21
26
  (0, audit_log_1.appendAudit)({
@@ -5,6 +5,8 @@ exports.getKeystoreWalletPath = getKeystoreWalletPath;
5
5
  exports.getGeneratedWalletsPath = getGeneratedWalletsPath;
6
6
  exports.expandHomePath = expandHomePath;
7
7
  exports.resolveKeystorePath = resolveKeystorePath;
8
+ exports.getKeystoreCopyDir = getKeystoreCopyDir;
9
+ exports.getKeystoreCopyPath = getKeystoreCopyPath;
8
10
  exports.saveEncryptedKeystoreFile = saveEncryptedKeystoreFile;
9
11
  exports.registerGeneratedWallet = registerGeneratedWallet;
10
12
  exports.loadGeneratedWallets = loadGeneratedWallets;
@@ -52,6 +54,29 @@ function resolveKeystorePath(path) {
52
54
  const expanded = expandHomePath(path);
53
55
  return (0, node_path_1.isAbsolute)(expanded) ? expanded : (0, node_path_1.resolve)(process.cwd(), expanded);
54
56
  }
57
+ /**
58
+ * A second folder on the same machine for an identical encrypted copy, outside ~/.apow so
59
+ * deleting or corrupting one folder does not lose the wallet. It does not survive a lost disk.
60
+ */
61
+ function getKeystoreCopyDir(apowDir) {
62
+ const override = process.env.APOW_KEYSTORE_COPY_DIR?.trim();
63
+ let dir;
64
+ if (override)
65
+ dir = (0, node_path_1.resolve)(expandHomePath(override));
66
+ else if (apowDir)
67
+ dir = (0, node_path_1.join)(apowDir, "keystore-copies");
68
+ else if (process.platform === "darwin")
69
+ dir = (0, node_path_1.join)((0, node_os_1.homedir)(), "Library", "Application Support", "apow", "keystore-copies");
70
+ else if (process.platform === "win32")
71
+ dir = (0, node_path_1.join)(process.env.APPDATA || (0, node_path_1.join)((0, node_os_1.homedir)(), "AppData", "Roaming"), "apow", "keystore-copies");
72
+ else
73
+ dir = (0, node_path_1.join)(process.env.XDG_DATA_HOME || (0, node_path_1.join)((0, node_os_1.homedir)(), ".local", "share"), "apow", "keystore-copies");
74
+ ensureDir(dir);
75
+ return dir;
76
+ }
77
+ function getKeystoreCopyPath(address, apowDir) {
78
+ return (0, node_path_1.join)(getKeystoreCopyDir(apowDir), `wallet-${address}.json`);
79
+ }
55
80
  async function saveEncryptedKeystoreFile(address, privateKey, password, apowDir = getDefaultApowDir()) {
56
81
  const filepath = getKeystoreWalletPath(address, apowDir);
57
82
  const [key, opts] = await ox_1.Keystore.scryptAsync({ password });
@@ -60,12 +85,22 @@ async function saveEncryptedKeystoreFile(address, privateKey, password, apowDir
60
85
  ...keystore,
61
86
  address: address.slice(2).toLowerCase(),
62
87
  };
63
- (0, node_fs_1.writeFileSync)(filepath, JSON.stringify(payload, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
64
- try {
65
- (0, node_fs_1.chmodSync)(filepath, 0o600);
88
+ const text = JSON.stringify(payload, null, 2) + "\n";
89
+ const copyPath = getKeystoreCopyPath(address, apowDir === getDefaultApowDir() ? undefined : apowDir);
90
+ for (const path of [filepath, copyPath]) {
91
+ (0, node_fs_1.writeFileSync)(path, text, { encoding: "utf8", mode: 0o600 });
92
+ try {
93
+ (0, node_fs_1.chmodSync)(path, 0o600);
94
+ }
95
+ catch {
96
+ // Best-effort permissions hardening.
97
+ }
66
98
  }
67
- catch {
68
- // Best-effort permissions hardening.
99
+ // Both copies must open to the same wallet before anyone funds it.
100
+ for (const path of [filepath, copyPath]) {
101
+ if (loadEncryptedKeystoreFile(path, password).toLowerCase() !== privateKey.toLowerCase()) {
102
+ throw new Error(`Encrypted keystore at ${path} did not verify.`);
103
+ }
69
104
  }
70
105
  return filepath;
71
106
  }
package/dist/wallet.js CHANGED
@@ -11,9 +11,11 @@ const config_1 = require("./config");
11
11
  const local_keystore_1 = require("./signer/local-keystore");
12
12
  const x402_1 = require("./x402");
13
13
  exports.DATA_SUFFIX = erc8021_1.Attribution.toDataSuffix({ codes: ["bc_6wfeb1kd"] });
14
+ const FREE_BASE_RPC = "https://base.publicnode.com";
14
15
  function getTransport() {
15
16
  const signer = (0, local_keystore_1.getSigner)();
16
17
  if (config_1.config.useX402 && signer) {
18
+ // Easy Mode: every RPC call is paid through x402 (AKLO, Dec 2: RPC, AI and GPU all on x402).
17
19
  return (0, x402_1.createX402Transport)(signer.account);
18
20
  }
19
21
  return (0, viem_1.http)(config_1.config.rpcUrl);
@@ -49,7 +51,7 @@ function shouldUseBootstrapFundingClients() {
49
51
  return config_1.config.chainName === "base";
50
52
  }
51
53
  function getBootstrapTransport() {
52
- return config_1.config.chainName === "base" ? (0, viem_1.http)(config_1.config.rpcUrl || "https://base.publicnode.com") : transport;
54
+ return config_1.config.chainName === "base" ? (0, viem_1.http)(config_1.config.rpcUrl || FREE_BASE_RPC) : transport;
53
55
  }
54
56
  /** Reinitialize clients after config changes (e.g., x402 fallback). */
55
57
  function reinitClients() {
package/dist/x402.js CHANGED
@@ -33,35 +33,71 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.currentRpcPaymentModel = currentRpcPaymentModel;
36
37
  exports.createX402Transport = createX402Transport;
37
38
  exports.resetX402 = resetX402;
38
39
  const viem_1 = require("viem");
40
+ const gateway_1 = require("./gateway");
39
41
  const QUICKNODE_BASE = "https://x402.quicknode.com";
40
42
  const BASE_MAINNET = "eip155:8453";
41
43
  const X402_RPC_TIMEOUT_MS = 10_000;
42
- let _client = null;
43
- async function getClient(account) {
44
- if (_client && !_client.isTokenExpired())
45
- return _client;
44
+ const _clients = {};
45
+ let _gatewayOk = false;
46
+ let _gatewayCheckedAt = 0;
47
+ let _nanoPausedUntil = 0;
48
+ let _lastModel = null;
49
+ const MODEL_RECHECK_MS = 5 * 60_000;
50
+ /** QuickNode's nanopayment settlement rejects bursts; fall back to per-call payment for a while. */
51
+ const NANO_PAUSE_MS = 30_000;
52
+ async function clientFor(account, model) {
53
+ const existing = _clients[model];
54
+ if (existing && !existing.isTokenExpired())
55
+ return existing;
46
56
  const { createQuicknodeX402Client } = await Promise.resolve().then(() => __importStar(require("@quicknode/x402")));
47
- _client = await createQuicknodeX402Client({
57
+ const created = await createQuicknodeX402Client({
48
58
  baseUrl: QUICKNODE_BASE,
49
59
  network: BASE_MAINNET,
50
60
  evmSigner: account,
51
- paymentModel: "pay-per-request",
61
+ paymentModel: model,
52
62
  });
53
- return _client;
63
+ _clients[model] = created;
64
+ return created;
65
+ }
66
+ /** Nanopayments ($0.0001, batched by Circle) when the Gateway deposit covers them; else $0.001 per call. */
67
+ async function preferredModel(account) {
68
+ const now = Date.now();
69
+ if (now - _gatewayCheckedAt > MODEL_RECHECK_MS) {
70
+ const balance = await (0, gateway_1.getGatewayBalanceUsdc)(account.address);
71
+ _gatewayOk = balance !== null && balance >= gateway_1.GATEWAY_MIN_USDC;
72
+ _gatewayCheckedAt = now;
73
+ }
74
+ return _gatewayOk && now >= _nanoPausedUntil ? "nanopayment" : "pay-per-request";
75
+ }
76
+ function currentRpcPaymentModel() {
77
+ return _lastModel;
78
+ }
79
+ async function paidRpc(account, body) {
80
+ const model = await preferredModel(account);
81
+ _lastModel = model;
82
+ const send = async (m) => (await clientFor(account, m)).fetch(`${QUICKNODE_BASE}/base-mainnet`, {
83
+ method: "POST",
84
+ headers: { "Content-Type": "application/json" },
85
+ body,
86
+ signal: AbortSignal.timeout(X402_RPC_TIMEOUT_MS),
87
+ });
88
+ const response = await send(model);
89
+ if (response.status === 402 && model === "nanopayment") {
90
+ // A rejected nanopayment was not settled; retry once paying per call.
91
+ _nanoPausedUntil = Date.now() + NANO_PAUSE_MS;
92
+ _lastModel = "pay-per-request";
93
+ return send("pay-per-request");
94
+ }
95
+ return response;
54
96
  }
55
97
  function createX402Transport(account) {
56
98
  return (0, viem_1.custom)({
57
99
  async request({ method, params }) {
58
- const client = await getClient(account);
59
- const response = await client.fetch(`${QUICKNODE_BASE}/base-mainnet`, {
60
- method: "POST",
61
- headers: { "Content-Type": "application/json" },
62
- body: JSON.stringify({ jsonrpc: "2.0", method, params, id: 1 }),
63
- signal: AbortSignal.timeout(X402_RPC_TIMEOUT_MS),
64
- });
100
+ const response = await paidRpc(account, JSON.stringify({ jsonrpc: "2.0", method, params, id: 1 }));
65
101
  if (response.status === 402) {
66
102
  throw new Error("x402 payment failed — insufficient USDC balance on Base");
67
103
  }
@@ -78,5 +114,9 @@ function createX402Transport(account) {
78
114
  });
79
115
  }
80
116
  function resetX402() {
81
- _client = null;
117
+ delete _clients.nanopayment;
118
+ delete _clients["pay-per-request"];
119
+ _gatewayCheckedAt = 0;
120
+ _nanoPausedUntil = 0;
121
+ _lastModel = null;
82
122
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apow-cli",
3
- "version": "0.12.3",
3
+ "version": "0.12.4",
4
4
  "description": "Mine AGENT tokens on Base L2 with Agentic Proof of Work",
5
5
  "keywords": [
6
6
  "apow",
@@ -52,7 +52,7 @@
52
52
  "dependencies": {
53
53
  "@blockrun/clawrouter": "0.12.81",
54
54
  "@noble/hashes": "^1.8.0",
55
- "@quicknode/x402": "^0.1.2",
55
+ "@quicknode/x402": "^0.1.3",
56
56
  "@x402/evm": "^2.8.0",
57
57
  "@x402/fetch": "^2.8.0",
58
58
  "commander": "^14.0.0",
package/skill.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: apow-mining
3
- description: Set up APoW Easy Mode with one Base ETH deposit, a recoverable encrypted wallet, and remote GPU mining.
4
- allowed-tools: Bash(npx --yes apow-cli@0.12.3 start --easy) Bash(npx --yes apow-cli@0.12.3 wallet verify-recovery)
3
+ description: Mine AGENT on Base with the official APoW CLI from any AI agent that can run commands. One encrypted local wallet, x402 remote GPU grinding, one Base ETH deposit.
4
+ allowed-tools: Bash(npx --yes apow-cli@0.12.4 --version) Bash(npx --yes apow-cli@0.12.4 start --easy) Bash(npx --yes apow-cli@0.12.4 wallet verify-recovery)
5
5
  metadata:
6
6
  openclaw:
7
7
  requires:
@@ -11,106 +11,68 @@ metadata:
11
11
 
12
12
  # APoW Mining
13
13
 
14
- Use the official CLI to mine AGENT on Base with a dedicated low-balance wallet.
15
- SMHL means **Semantic-Mathematical Hybrid Lock**, adapted from
16
- [MoltCaptcha](https://github.com/MoltCaptcha/MoltCaptcha). APoW checks string
17
- format on-chain; it does not verify semantic meaning or prove AI authorship.
14
+ Mine AGENT on Base with the official CLI. The same steps work in any agent that
15
+ can run shell commands and keep files, such as Claude Code, Codex, OpenClaw or
16
+ Hermes, on the user's laptop or another computer they control.
18
17
 
19
- ## Runtime choice
18
+ ## What the agent needs
20
19
 
21
- Read the [personal assistant profiles](https://apow.io/docs/technical/assistants)
22
- for Grok Bot, Muse, Instinct, Wajo/Fo, OpenClaw, Hermes, Claude Code, Codex,
23
- Manus, Cowork, and Perplexity. Check Node 20+, outbound HTTPS, persistent files,
24
- secure CLI unlock, and the permitted process lifetime before funding.
20
+ - Node 20 or newer, outbound HTTPS, and files that survive a restart.
21
+ - Permission from its host to run a long process and sign transactions.
25
22
 
26
- Default to **Easy Mode**: wallet-paid RPC, mint LLM, and remote GPU grinding.
27
- A runner is still required to sign and submit transactions. Do not rent a VPS
28
- or switch to CPU mining by default. The current web app also needs its browser
29
- tab open; fully managed APoW jobs are [under development](https://apow.io/docs/technical/managed-mining).
30
- Do not claim that they are already available.
23
+ If it can't run commands or keep files, say so and stop. Don't work around a
24
+ platform rule to make mining run.
31
25
 
32
- ## Scope and approval
26
+ ## The wallet stays on this machine
33
27
 
34
- Explain once: one dedicated encrypted wallet, one rig mint within the local
35
- policy, ETH-to-USDC funding conversion, x402 services, and continuous Base
36
- mining transactions until stopped. Give the applicable caps and real costs.
37
- Obtain explicit approval if this scope has not already been approved. Honor
38
- an existing approval and budget; do not ask again at every routine step.
39
- Funding does not authorize access to another wallet or automatic top-ups.
40
- Do not enable sweeps unless the user already configured and approved them.
28
+ The CLI creates one encrypted wallet on the machine it runs on and keeps two
29
+ encrypted copies there, in separate folders (`apow wallet backup` shows both).
30
+ Nothing goes to a server, a cloud backup or this chat. The user may also copy the
31
+ encrypted file to an external drive or another device; that is their choice.
41
32
 
42
- ```bash
43
- npx --yes apow-cli@0.12.3 start --easy
44
- ```
33
+ - Never ask for, print or store a private key, password or recovery phrase in chat.
34
+ - The password comes from the machine's secret manager (`KEYSTORE_PASSWORD_CMD`)
35
+ or the user types it in a terminal.
36
+ - Mined AGENT can't be transferred until the protocol's LP deploys, so this wallet
37
+ holds its rewards for a long time. Losing the machine, or its disk, loses them
38
+ unless the user kept an outside copy. Tell the user this once.
39
+
40
+ ## Start
45
41
 
46
- Run only this pinned Easy Mode flow and the recovery check below in this skill.
47
- If the package is unavailable, report it; do not substitute `latest`.
42
+ Explain once, with the real numbers the CLI prints: one wallet, one rig mint,
43
+ part of the ETH swapped to USDC for grinding, then continuous mining until
44
+ stopped. Get the user's OK, then:
48
45
 
49
- ## Recover before funding
46
+ ```bash
47
+ npx --yes apow-cli@0.12.4 start --easy
48
+ ```
50
49
 
51
- The user enters a password directly in a trusted terminal, or uses a supported
52
- secret manager. Never ask for a password, private key, or recovery phrase in chat.
53
- For headless operation, a secret-manager `KEYSTORE_PASSWORD_CMD` reference must
54
- be saved in the private runner configuration. A password generated only in
55
- process memory is not recoverable after a restart. A browser credential vault
56
- must not be assumed to provide CLI secrets.
50
+ Easy Mode grinds on APoW's remote GPUs and pays per job with x402, so the agent's
51
+ own hardware doesn't matter. The first run creates the wallet and asks for **one
52
+ Base ETH deposit**, printing the address and amount. Before the user sends it,
53
+ check the wallet unlocks from scratch:
57
54
 
58
55
  ```bash
59
- npx --yes apow-cli@0.12.3 wallet verify-recovery
56
+ npx --yes apow-cli@0.12.4 wallet verify-recovery
60
57
  ```
61
58
 
62
- The CLI checks a fresh-process unlock of the **same address** before giving
63
- funding instructions. The user must also keep the encrypted keystore and
64
- password separately outside the runner. Process verification does not prove
65
- VM durability or an independent backup. If secure unlock is unavailable, stop
66
- before funding. Keep an existing locked wallet; do not replace it.
67
-
68
- ## One deposit
69
-
70
- Ask for **Base ETH only**, using the complete address and live amount printed
71
- by the CLI. The quote includes the current rig fee, conservative ETH reserve,
72
- swap gas, and a missing 2 USDC service budget. It is not a fixed USD quote.
73
- Do not ask the user to buy or send USDC separately. After deposit, rerun the
74
- same pinned start command: it converts the required ETH, checks landed balances,
75
- and mints or resumes an existing rig. It stops before a swap that would consume
76
- the ETH reserve.
77
-
78
- Solana SOL/USDC funding exists only with a configured Squid integration and a
79
- verified deposit-address quote. Never send SOL to the Base EOA. That optional
80
- bridge route requires the separate funding guide and the user's choice of asset;
81
- this default skill uses the Base ETH handoff.
82
-
83
- ## Run and report
84
-
85
- Start one runner per wallet. Record its process handle and inspect recent logs.
86
- Use the assistant profile's supported background mechanism. A background PID
87
- is not proof of survival after a session or VM ends.
88
-
89
- Report these states accurately: wallet recovery verified; awaiting ETH; funded;
90
- rig minted or found; runner active; first confirmed mine. Show a Base transaction
91
- hash for a confirmed mine. A health check or remote GPU request alone is not a
92
- mine. Never invent network activity, competing GPU counts, yield, or profitability.
93
-
94
- Local CPU mining is a separately chosen novelty experiment. Do not enable local
95
- fallback after remote errors without the user's instruction. A quiet-network
96
- success does not establish useful performance under competition.
97
-
98
- ## Policy and failure handling
99
-
100
- Keep the default signing policy in enforce mode. Default ceilings are 0.01 ETH
101
- per rig mint, 1 USDC per x402 request, and 20 USDC per UTC day. Swaps have their
102
- own 0.02 ETH ceiling. Lower user-approved limits take precedence. These ceilings
103
- do not constitute a hard USD cap on gas, swaps, hosting, or exchange-rate changes.
104
- Never raise caps or disable enforcement to make a task proceed.
105
-
106
- - Locked wallet or missing durable secret: repair supported local unlock; no replacement wallet.
107
- - Funding missing: return the single Base ETH quote; resume the same address after deposit.
108
- - Unsupported runner: report the exact missing capability; use an already approved host, without a new rental.
109
- - Policy denial: stop and report the requested action and cap.
110
- - GPU cold startup: allow the CLI's 330-second transport deadline; do not launch duplicate paid requests.
111
- - Unknown payment/transaction outcome: stop and reconcile before manually resuming.
112
- - Normal transient failures: let the CLI's bounded retries run; do not silently change mode.
113
- - User stop: stop the process and report any in-flight transaction or unresolved payment.
114
-
115
- Keep wallet secrets out of logs, project files, repositories, agent memory, and
116
- other agents' workspaces. Do not search for credentials or operate a main wallet.
59
+ After the deposit, run `start --easy` again: it swaps what it needs, mints a rig
60
+ (or finds the existing one) and starts mining.
61
+
62
+ ## While it runs
63
+
64
+ - One runner per wallet. Never start a second miner from a status check.
65
+ - Report only what happened: wallet verified, awaiting ETH, funded, rig minted,
66
+ runner active, first mine with its Base transaction hash. Never invent yields.
67
+ - Keep the signing policy in enforce mode. Defaults: 0.01 ETH per rig mint,
68
+ 1 USDC per grind, 20 USDC per day. Never raise a cap to get past an error.
69
+
70
+ ## When something fails
71
+
72
+ - Locked wallet: fix the unlock. Never make a replacement wallet.
73
+ - No funds: show the same deposit address and amount again.
74
+ - Policy refused a transaction: stop and report what was refused.
75
+ - Slow first grind: the GPU may be waking up; the CLI waits up to 330 s. Don't
76
+ send a second paid request.
77
+ - Unclear payment or transaction: stop and check before resuming.
78
+ - User says stop: stop the process and report anything still in flight.