apow-cli 0.12.0 → 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/.env.example +3 -1
- package/README.md +39 -30
- package/dist/base-funding.js +98 -0
- package/dist/bridge/squid.js +29 -8
- package/dist/bridge/uniswap.js +48 -1
- package/dist/errors.js +5 -1
- package/dist/fund.js +91 -506
- package/dist/funding-plan.js +29 -0
- package/dist/gateway.js +85 -0
- package/dist/grind-credits.js +119 -0
- package/dist/grinder-http.js +97 -10
- package/dist/grinder.js +10 -0
- package/dist/index.js +101 -60
- package/dist/miner.js +78 -14
- package/dist/mint.js +15 -0
- package/dist/policy/decode.js +50 -2
- package/dist/policy/policy.js +20 -1
- package/dist/preflight.js +25 -19
- package/dist/secure-env.js +8 -1
- package/dist/signer/guarded-account.js +5 -0
- package/dist/wallet-recovery.js +52 -0
- package/dist/wallet-store.js +40 -5
- package/dist/wallet.js +10 -8
- package/dist/x402.js +55 -15
- package/package.json +6 -5
- package/skill.md +51 -65
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
|
-
|
|
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
|
-
|
|
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),
|
|
@@ -541,10 +558,10 @@ async function startMining(tokenId, options = {}) {
|
|
|
541
558
|
throw err;
|
|
542
559
|
const msg = err instanceof Error ? err.message : String(err);
|
|
543
560
|
if (msg.includes("insufficient USDC")) {
|
|
544
|
-
console.log(` ${ui.yellow("x402 GPU: insufficient USDC.")} Run: ${ui.cyan("apow
|
|
561
|
+
console.log(` ${ui.yellow("x402 GPU: insufficient USDC.")} Run: ${ui.cyan("apow start --easy")} for an ETH-only quote.`);
|
|
545
562
|
}
|
|
546
563
|
else if (msg.includes("simulation_failed")) {
|
|
547
|
-
console.log(` ${ui.yellow("x402 GPU: EVM simulation failed.")} ${ui.dim("
|
|
564
|
+
console.log(` ${ui.yellow("x402 GPU: EVM simulation failed.")} ${ui.dim("Check balance, signing policy, and the service RPC")}`);
|
|
548
565
|
}
|
|
549
566
|
else if (msg.includes("402")) {
|
|
550
567
|
console.log(` ${ui.yellow("x402 GPU payment failed.")} ${ui.dim(msg.slice(0, 120))}`);
|
|
@@ -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
|
-
|
|
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
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
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
|
+
}
|
package/dist/policy/decode.js
CHANGED
|
@@ -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
|
-
|
|
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
|
+
}
|
package/dist/policy/policy.js
CHANGED
|
@@ -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
|
-
|
|
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,10 +36,10 @@ 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");
|
|
42
|
-
const chains_1 = require("viem/chains");
|
|
43
43
|
const AgentCoin_json_1 = __importDefault(require("./abi/AgentCoin.json"));
|
|
44
44
|
const MiningAgent_json_1 = __importDefault(require("./abi/MiningAgent.json"));
|
|
45
45
|
const config_1 = require("./config");
|
|
@@ -49,12 +49,12 @@ const policy_1 = require("./policy/policy");
|
|
|
49
49
|
const spend_ledger_1 = require("./policy/spend-ledger");
|
|
50
50
|
const secure_env_1 = require("./secure-env");
|
|
51
51
|
const wallet_1 = require("./wallet");
|
|
52
|
+
const base_funding_1 = require("./base-funding");
|
|
52
53
|
const ui = __importStar(require("./ui"));
|
|
53
54
|
const agentCoinAbi = AgentCoin_json_1.default;
|
|
54
55
|
const miningAgentAbi = MiningAgent_json_1.default;
|
|
55
56
|
const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
|
|
56
57
|
const USDC_DECIMALS = 6;
|
|
57
|
-
const MINT_GAS_RESERVE_ETH = (0, viem_1.parseEther)("0.003");
|
|
58
58
|
const erc20BalanceAbi = [
|
|
59
59
|
{
|
|
60
60
|
type: "function",
|
|
@@ -81,7 +81,19 @@ function hasLocalCli(command, env) {
|
|
|
81
81
|
}
|
|
82
82
|
function hasClaudeSubscriptionAuth() {
|
|
83
83
|
const result = runLocalCliCheck("claude", ["auth", "status"], (0, secure_env_1.claudeSubscriptionEnv)());
|
|
84
|
-
return result.passed &&
|
|
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
|
+
}
|
|
85
97
|
}
|
|
86
98
|
function hasCodexSubscriptionAuth() {
|
|
87
99
|
const result = runLocalCliCheck("codex", ["login", "status"], (0, secure_env_1.codexSubscriptionEnv)());
|
|
@@ -145,18 +157,11 @@ async function runPreflight(level) {
|
|
|
145
157
|
// Check x402: USDC balance BEFORE RPC check (can't use x402 without USDC)
|
|
146
158
|
let x402Funded = false;
|
|
147
159
|
if (config_1.config.useX402 && wallet_1.account) {
|
|
148
|
-
|
|
149
|
-
x402Funded = true; // optimistic — the x402 RPC check below will verify reachability.
|
|
150
|
-
ui.warn("Skipping x402 USDC precheck because RPC_URL is not set; refusing to use public Base RPC endpoints");
|
|
151
|
-
}
|
|
152
|
-
else {
|
|
160
|
+
{
|
|
153
161
|
try {
|
|
154
162
|
// Use a separate lightweight client to avoid chicken-and-egg
|
|
155
163
|
// (can't use x402 to check if we can pay for x402)
|
|
156
|
-
const checkClient = (0,
|
|
157
|
-
chain: chains_1.base,
|
|
158
|
-
transport: (0, viem_1.http)(config_1.config.rpcUrl),
|
|
159
|
-
});
|
|
164
|
+
const checkClient = (0, wallet_1.getFundingClients)().publicClient;
|
|
160
165
|
const usdcBalance = (await checkClient.readContract({
|
|
161
166
|
address: USDC_ADDRESS,
|
|
162
167
|
abi: erc20BalanceAbi,
|
|
@@ -167,7 +172,7 @@ async function runPreflight(level) {
|
|
|
167
172
|
results.push({
|
|
168
173
|
label: "No USDC balance — QuickNode x402 requires USDC on Base",
|
|
169
174
|
passed: false,
|
|
170
|
-
fix: `
|
|
175
|
+
fix: "Run `apow start --easy` to quote an ETH-only deposit and convert the service budget to USDC.",
|
|
171
176
|
});
|
|
172
177
|
}
|
|
173
178
|
else {
|
|
@@ -180,9 +185,7 @@ async function runPreflight(level) {
|
|
|
180
185
|
}
|
|
181
186
|
}
|
|
182
187
|
catch {
|
|
183
|
-
|
|
184
|
-
x402Funded = true; // optimistic — let the RPC check determine reachability
|
|
185
|
-
ui.warn("Could not check USDC balance — QuickNode x402 may fail if wallet has no USDC");
|
|
188
|
+
results.push({ label: "Could not verify x402 funding", passed: false, fix: "Retry when the funding RPC responds" });
|
|
186
189
|
}
|
|
187
190
|
}
|
|
188
191
|
}
|
|
@@ -257,12 +260,12 @@ async function runPreflight(level) {
|
|
|
257
260
|
abi: miningAgentAbi,
|
|
258
261
|
functionName: "getMintPrice",
|
|
259
262
|
}));
|
|
260
|
-
const requiredBalance = mintPrice + MINT_GAS_RESERVE_ETH;
|
|
263
|
+
const requiredBalance = mintPrice + base_funding_1.MINT_GAS_RESERVE_ETH;
|
|
261
264
|
if (balance < requiredBalance) {
|
|
262
265
|
results.push({
|
|
263
266
|
label: `Mint-ready ETH balance (${ethBalance.toFixed(6)} ETH)`,
|
|
264
267
|
passed: false,
|
|
265
|
-
fix: `Mint
|
|
268
|
+
fix: `Mint price is ${(0, viem_1.formatEther)(mintPrice)} ETH; the CLI also retains a conservative ${(0, viem_1.formatEther)(base_funding_1.MINT_GAS_RESERVE_ETH)} ETH reserve. The reserve is not a transaction fee. Run apow start --easy for the complete ETH-only quote.`,
|
|
266
269
|
});
|
|
267
270
|
}
|
|
268
271
|
else {
|
|
@@ -406,7 +409,10 @@ async function runPreflight(level) {
|
|
|
406
409
|
const healthUrl = grindUrl.replace(/\/grind$/, "/health");
|
|
407
410
|
const grinderIsRequired = !config_1.config.allowLocalFallbackWithX402;
|
|
408
411
|
try {
|
|
409
|
-
|
|
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) });
|
|
410
416
|
if (resp.ok) {
|
|
411
417
|
const host = new URL(grindUrl).hostname;
|
|
412
418
|
results.push({ label: `GrindProxy: ${host} (dynamic pricing)`, passed: true });
|
package/dist/secure-env.js
CHANGED
|
@@ -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
|
-
|
|
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)({
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.verifyWalletRecovery = verifyWalletRecovery;
|
|
4
|
+
const node_child_process_1 = require("node:child_process");
|
|
5
|
+
const node_fs_1 = require("node:fs");
|
|
6
|
+
const node_path_1 = require("node:path");
|
|
7
|
+
const dotenv_1 = require("dotenv");
|
|
8
|
+
/** Verify an independent unlock without returning a key or password to the caller. */
|
|
9
|
+
function verifyWalletRecovery(keystorePath, expectedAddress, password) {
|
|
10
|
+
const environment = { ...process.env };
|
|
11
|
+
delete environment.PRIVATE_KEY;
|
|
12
|
+
delete environment.KEYSTORE_PASSWORD;
|
|
13
|
+
delete environment.APOW_KEYSTORE_PASSWORD;
|
|
14
|
+
delete environment.KEYSTORE_PASSWORD_CMD;
|
|
15
|
+
delete environment.APOW_KEYSTORE_PASSWORD_CMD;
|
|
16
|
+
if (!password) {
|
|
17
|
+
let saved = {};
|
|
18
|
+
try {
|
|
19
|
+
saved = (0, dotenv_1.parse)((0, node_fs_1.readFileSync)((0, node_path_1.join)(process.cwd(), ".env")));
|
|
20
|
+
}
|
|
21
|
+
catch { /* report below */ }
|
|
22
|
+
const command = saved.KEYSTORE_PASSWORD_CMD || saved.APOW_KEYSTORE_PASSWORD_CMD;
|
|
23
|
+
if (!command?.trim()) {
|
|
24
|
+
throw new Error("Before funding, save a secret-manager unlock command as KEYSTORE_PASSWORD_CMD in .env. A process-only password will not survive a restart. Do not put the password in chat or .env.");
|
|
25
|
+
}
|
|
26
|
+
environment.KEYSTORE_PASSWORD_CMD = command;
|
|
27
|
+
}
|
|
28
|
+
const script = `
|
|
29
|
+
try {
|
|
30
|
+
const fs = require('node:fs');
|
|
31
|
+
const { spawnSync } = require('node:child_process');
|
|
32
|
+
let password = fs.readFileSync(0, 'utf8');
|
|
33
|
+
if (!password) {
|
|
34
|
+
const result = spawnSync(process.env.KEYSTORE_PASSWORD_CMD, { shell: true, encoding: 'utf8', timeout: 10000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
35
|
+
if (result.status !== 0) process.exit(1);
|
|
36
|
+
password = result.stdout.trim();
|
|
37
|
+
}
|
|
38
|
+
if (!password) process.exit(1);
|
|
39
|
+
const { loadEncryptedKeystoreFile } = require(process.argv[1]);
|
|
40
|
+
const { privateKeyToAccount } = require(process.argv[3]);
|
|
41
|
+
const address = privateKeyToAccount(loadEncryptedKeystoreFile(process.argv[2], password)).address;
|
|
42
|
+
process.stdout.write(address);
|
|
43
|
+
} catch { process.exit(1); }
|
|
44
|
+
`;
|
|
45
|
+
const result = (0, node_child_process_1.spawnSync)(process.execPath, ["-e", script, (0, node_path_1.join)(__dirname, "wallet-store.js"), keystorePath, require.resolve("viem/accounts")], {
|
|
46
|
+
env: environment, input: password ?? "", encoding: "utf8", timeout: 30_000,
|
|
47
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
48
|
+
});
|
|
49
|
+
if (result.status !== 0 || result.stdout.trim().toLowerCase() !== expectedAddress.toLowerCase()) {
|
|
50
|
+
throw new Error("Fresh-process wallet recovery failed. Keep the same wallet and repair its secret-manager unlock before funding.");
|
|
51
|
+
}
|
|
52
|
+
}
|
package/dist/wallet-store.js
CHANGED
|
@@ -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
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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
|
-
|
|
68
|
-
|
|
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
|
}
|