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/gateway.js
ADDED
|
@@ -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
|
+
}
|
package/dist/grinder-http.js
CHANGED
|
@@ -45,12 +45,17 @@ 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.
|
|
58
|
+
const GRIND_HTTP_TIMEOUT_MS = 330_000;
|
|
54
59
|
// Lazy singleton — created on first grind, reused across calls
|
|
55
60
|
let _fetchWithPayment = null;
|
|
56
61
|
function resetPaymentFetch() {
|
|
@@ -89,6 +94,51 @@ function isHttpGrinderConfigured() {
|
|
|
89
94
|
function getGrindUrl() {
|
|
90
95
|
return config_1.config.grindUrl ?? DEFAULT_GRIND_URL;
|
|
91
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
|
+
}
|
|
92
142
|
async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, signer, signal) {
|
|
93
143
|
const start = process.hrtime();
|
|
94
144
|
const timeoutSignal = AbortSignal.timeout(GRIND_HTTP_TIMEOUT_MS);
|
|
@@ -104,28 +154,52 @@ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, s
|
|
|
104
154
|
signal: requestSignal,
|
|
105
155
|
};
|
|
106
156
|
let response = null;
|
|
157
|
+
let skipCredit = false;
|
|
107
158
|
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
108
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);
|
|
109
164
|
try {
|
|
110
|
-
response =
|
|
165
|
+
response = credit
|
|
166
|
+
? await fetch(grindUrl, { ...requestInit, headers: { ...requestInit.headers, "X-Grind-Credit": credit } })
|
|
167
|
+
: await paidFetch(grindUrl, requestInit);
|
|
111
168
|
}
|
|
112
169
|
catch (err) {
|
|
113
170
|
if (signal?.aborted) {
|
|
114
171
|
throw err;
|
|
115
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
|
+
}
|
|
116
177
|
if (timeoutSignal.aborted) {
|
|
117
178
|
resetPaymentFetch();
|
|
118
|
-
throw new Error(`Remote GPU grind timed out (${GRIND_HTTP_TIMEOUT_MS / 1000}s)`);
|
|
179
|
+
throw new Error(`Remote GPU grind timed out (${GRIND_HTTP_TIMEOUT_MS / 1000}s); payment outcome is unknown`);
|
|
119
180
|
}
|
|
120
181
|
resetPaymentFetch();
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
}
|
|
124
|
-
throw new Error(`Remote GPU grind request failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
182
|
+
// A lost response can follow a settled payment. Do not replay an unknown paid request.
|
|
183
|
+
throw new Error(`Remote GPU grind request failed; payment outcome is unknown: ${err instanceof Error ? err.message : String(err)}`);
|
|
125
184
|
}
|
|
126
185
|
if (response.ok) {
|
|
186
|
+
if (credit)
|
|
187
|
+
(0, grind_credits_1.noteCreditUsed)(minerAddress, grindUrl);
|
|
127
188
|
break;
|
|
128
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
|
+
}
|
|
129
203
|
const body = await response.text().catch(() => "");
|
|
130
204
|
const bodyDetail = extractErrorDetail(body);
|
|
131
205
|
const paymentRequiredB64 = response.headers.get("payment-required");
|
|
@@ -139,7 +213,7 @@ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, s
|
|
|
139
213
|
}
|
|
140
214
|
const combinedError = `${reason} ${bodyDetail}`.trim();
|
|
141
215
|
const stalePaymentSession = /No matching payment requirements|facilitator|payment session|authorization/i.test(combinedError);
|
|
142
|
-
if (attempt === 1 &&
|
|
216
|
+
if (attempt === 1 && response.status === 402 && stalePaymentSession) {
|
|
143
217
|
resetPaymentFetch();
|
|
144
218
|
continue;
|
|
145
219
|
}
|
|
@@ -149,7 +223,7 @@ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, s
|
|
|
149
223
|
throw new Error("x402 GPU payment failed: insufficient USDC balance");
|
|
150
224
|
}
|
|
151
225
|
else if (reason.includes("simulation_failed")) {
|
|
152
|
-
throw new Error(`x402 GPU payment failed: EVM simulation failed
|
|
226
|
+
throw new Error(`x402 GPU payment failed: EVM simulation failed; check balance, policy, and service settlement RPC [${reason}]`);
|
|
153
227
|
}
|
|
154
228
|
else if (attempt === 1) {
|
|
155
229
|
continue;
|
|
@@ -158,9 +232,22 @@ async function grindNonceHttp(challengeNumber, target, minerAddress, grindUrl, s
|
|
|
158
232
|
throw new Error(`x402 GPU payment failed: ${reason || bodyDetail.slice(0, 200) || "unknown"}`);
|
|
159
233
|
}
|
|
160
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
|
+
}
|
|
161
246
|
if (response.status === 504) {
|
|
162
|
-
throw new Error(
|
|
247
|
+
throw new Error("Remote GPU service timed out; payment outcome is unknown");
|
|
163
248
|
}
|
|
249
|
+
if (response.status >= 500)
|
|
250
|
+
throw new Error(`GrindProxy HTTP ${response.status}; payment outcome is unknown`);
|
|
164
251
|
throw new Error(`GrindProxy HTTP ${response.status}: ${(bodyDetail || body).slice(0, 200)}`);
|
|
165
252
|
}
|
|
166
253
|
if (!response || !response.ok) {
|
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
|
@@ -44,11 +44,12 @@ const commander_1 = require("commander");
|
|
|
44
44
|
const viem_1 = require("viem");
|
|
45
45
|
const MiningAgent_json_1 = __importDefault(require("./abi/MiningAgent.json"));
|
|
46
46
|
const config_1 = require("./config");
|
|
47
|
-
const constants_1 = require("./bridge/constants");
|
|
48
47
|
const detect_1 = require("./detect");
|
|
49
48
|
const errors_1 = require("./errors");
|
|
50
49
|
const explorer_1 = require("./explorer");
|
|
51
50
|
const fund_1 = require("./fund");
|
|
51
|
+
const base_funding_1 = require("./base-funding");
|
|
52
|
+
const wallet_recovery_1 = require("./wallet-recovery");
|
|
52
53
|
const llm_setup_1 = require("./llm-setup");
|
|
53
54
|
const mint_1 = require("./mint");
|
|
54
55
|
const miner_1 = require("./miner");
|
|
@@ -63,6 +64,9 @@ const brand_intro_1 = require("./brand-intro");
|
|
|
63
64
|
const wallet_store_1 = require("./wallet-store");
|
|
64
65
|
const wallet_1 = require("./wallet");
|
|
65
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");
|
|
66
70
|
const policy_1 = require("./policy/policy");
|
|
67
71
|
const miningAgentAbi = MiningAgent_json_1.default;
|
|
68
72
|
const erc20BalanceAbi = [
|
|
@@ -105,6 +109,46 @@ function ensureGitignoreSafetyEntries() {
|
|
|
105
109
|
(0, node_fs_1.writeFileSync)(gitignorePath, content, "utf8");
|
|
106
110
|
ui.ok(`Updated .gitignore: added ${missing.join(", ")}`);
|
|
107
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
|
+
}
|
|
108
152
|
async function getKeystorePassword(required, confirmPassword = true) {
|
|
109
153
|
const configuredPassword = (0, config_1.resolveKeystorePassword)();
|
|
110
154
|
if (configuredPassword) {
|
|
@@ -343,7 +387,7 @@ async function setupWizard(options = {}) {
|
|
|
343
387
|
console.log("");
|
|
344
388
|
console.log(` ${ui.dim("Back up the encrypted keystore and its password separately.")}`);
|
|
345
389
|
console.log("");
|
|
346
|
-
console.log(` ${ui.dim("
|
|
390
|
+
console.log(` ${ui.dim("Verify wallet recovery before funding. apow start calculates the ETH deposit.")}`);
|
|
347
391
|
console.log("");
|
|
348
392
|
}
|
|
349
393
|
values.PRIVATE_KEY = "";
|
|
@@ -363,7 +407,7 @@ async function setupWizard(options = {}) {
|
|
|
363
407
|
ui.ok("LLM: Auto (Zero Config via ClawRouter x402; wallet-paid in USDC)");
|
|
364
408
|
ui.ok("Grinder: Auto (Zero Config via RunPod x402; wallet-paid in USDC)");
|
|
365
409
|
console.log(` ${ui.dim("Easy mode is agent-first: no RPC key, no LLM key, no GPU rental setup.")}`);
|
|
366
|
-
console.log(` ${ui.dim(`
|
|
410
|
+
console.log(` ${ui.dim(`Deposit Base ETH only. The CLI converts the service budget to USDC. Run: apow start${options.easyMode ? " --easy" : ""}`)}`);
|
|
367
411
|
}
|
|
368
412
|
else {
|
|
369
413
|
// Advanced: user picks which services remain autonomous
|
|
@@ -516,17 +560,26 @@ async function setupWizard(options = {}) {
|
|
|
516
560
|
console.log("");
|
|
517
561
|
}
|
|
518
562
|
}
|
|
519
|
-
function showFundingHandoff(address,
|
|
563
|
+
function showFundingHandoff(address, depositEth, easyMode) {
|
|
520
564
|
ui.warn("Pausing for Base funding.");
|
|
521
|
-
ui.hint(`Send
|
|
522
|
-
if
|
|
523
|
-
|
|
524
|
-
}
|
|
525
|
-
if (needsUsdc) {
|
|
526
|
-
ui.hint(`Need at least ${constants_1.MIN_USDC} USDC for x402 RPC + LLM services.`);
|
|
527
|
-
}
|
|
565
|
+
ui.hint(`Send at least ${(0, viem_1.formatEther)(depositEth)} ETH on Base to ${address}.`);
|
|
566
|
+
ui.hint("This quote includes the current mint price, an ETH reserve, and the USDC conversion if needed. Costs can change before deposit.");
|
|
567
|
+
ui.hint("The CLI converts ETH to USDC within the signing policy. You do not need to send USDC.");
|
|
528
568
|
ui.hint(`After funds arrive, rerun \`apow start${easyMode ? " --easy" : ""}\`.`);
|
|
529
569
|
}
|
|
570
|
+
async function checkWalletRecovery() {
|
|
571
|
+
if (!wallet_1.account || !config_1.config.keystorePath)
|
|
572
|
+
throw new Error("Use an encrypted APoW wallet before funding.");
|
|
573
|
+
// A person can supply a separately retained password directly in a local terminal.
|
|
574
|
+
// Headless agents must use a saved secret-manager command, never process memory alone.
|
|
575
|
+
const password = ui.isInteractiveSession()
|
|
576
|
+
? await ui.promptSecret("Re-enter your separately saved keystore password to test recovery") : undefined;
|
|
577
|
+
if (ui.isInteractiveSession() && !password)
|
|
578
|
+
throw new Error("Wallet recovery test cancelled.");
|
|
579
|
+
(0, wallet_recovery_1.verifyWalletRecovery)(config_1.config.keystorePath, wallet_1.account.address, password);
|
|
580
|
+
ui.ok(`Fresh-process unlock verified for ${wallet_1.account.address}.`);
|
|
581
|
+
ui.hint("Keep an independent encrypted-keystore backup and its password separately. This check does not verify host uptime or your backup.");
|
|
582
|
+
}
|
|
530
583
|
async function runStartFlow(options = {}) {
|
|
531
584
|
await (0, brand_intro_1.showBrandIntro)("start");
|
|
532
585
|
const unlockedConfiguredWallet = await unlockConfiguredKeystoreIfNeeded();
|
|
@@ -551,17 +604,26 @@ async function runStartFlow(options = {}) {
|
|
|
551
604
|
ui.hint("Restore the default enforce-mode Easy Mode caps, then retry.");
|
|
552
605
|
return;
|
|
553
606
|
}
|
|
607
|
+
await (0, config_1.writeEnvFile)({ USE_X402: "true", USE_X402_GRIND: "true", LLM_PROVIDER: "clawrouter", ALLOW_LOCAL_FALLBACK_WITH_X402: "false" });
|
|
608
|
+
(0, config_1.reloadConfig)();
|
|
609
|
+
(0, wallet_1.reinitClients)();
|
|
554
610
|
}
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
: wallet_1.publicClient;
|
|
611
|
+
await checkWalletRecovery();
|
|
612
|
+
const bootstrapClient = (0, wallet_1.getFundingClients)().publicClient;
|
|
558
613
|
let miners = [];
|
|
559
614
|
try {
|
|
560
615
|
miners = await (0, detect_1.detectMinersWithClient)(bootstrapClient, wallet_1.account.address);
|
|
561
616
|
}
|
|
562
617
|
catch {
|
|
563
|
-
|
|
618
|
+
throw new Error("Could not query owned rigs. Retry when the funding RPC responds; do not create a replacement wallet or rig.");
|
|
619
|
+
}
|
|
620
|
+
const funding = await (0, base_funding_1.prepareBaseFunding)(miners.length === 0, true);
|
|
621
|
+
if (!funding.ready) {
|
|
622
|
+
showFundingHandoff(wallet_1.account.address, funding.depositEth, options.easyMode === true);
|
|
623
|
+
return;
|
|
564
624
|
}
|
|
625
|
+
if (options.easyMode)
|
|
626
|
+
await topUpGatewayIfLow();
|
|
565
627
|
if (miners.length > 0) {
|
|
566
628
|
const best = (0, detect_1.selectBestMiner)(miners);
|
|
567
629
|
console.log(` ${ui.green("Wallet ready.")} Found ${miners.length} rig${miners.length === 1 ? "" : "s"} — starting miner #${best.tokenId}.`);
|
|
@@ -570,47 +632,6 @@ async function runStartFlow(options = {}) {
|
|
|
570
632
|
await (0, miner_1.startMining)(best.tokenId, { easyMode: options.easyMode === true });
|
|
571
633
|
return;
|
|
572
634
|
}
|
|
573
|
-
let ethBalance = 0;
|
|
574
|
-
let usdcBalance = 0;
|
|
575
|
-
let balanceChecksAvailable = true;
|
|
576
|
-
try {
|
|
577
|
-
const [ethBalanceRaw, usdcBalanceRaw] = await Promise.all([
|
|
578
|
-
bootstrapClient.getBalance({ address: wallet_1.account.address }),
|
|
579
|
-
config_1.config.useX402
|
|
580
|
-
? bootstrapClient.readContract({
|
|
581
|
-
address: config_1.config.chainName === "base" ? "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" : config_1.config.agentCoinAddress,
|
|
582
|
-
abi: erc20BalanceAbi,
|
|
583
|
-
functionName: "balanceOf",
|
|
584
|
-
args: [wallet_1.account.address],
|
|
585
|
-
})
|
|
586
|
-
: Promise.resolve(0n),
|
|
587
|
-
]);
|
|
588
|
-
ethBalance = Number((0, viem_1.formatEther)(ethBalanceRaw));
|
|
589
|
-
usdcBalance = Number((0, viem_1.formatUnits)(usdcBalanceRaw, 6));
|
|
590
|
-
}
|
|
591
|
-
catch {
|
|
592
|
-
balanceChecksAvailable = false;
|
|
593
|
-
ui.warn("Could not query wallet balances via bootstrap RPC — funding flow may still be needed.");
|
|
594
|
-
}
|
|
595
|
-
const needsEth = !balanceChecksAvailable || ethBalance < constants_1.MIN_ETH;
|
|
596
|
-
const needsUsdc = config_1.config.useX402 && (!balanceChecksAvailable || usdcBalance < constants_1.MIN_USDC);
|
|
597
|
-
if (needsEth || needsUsdc) {
|
|
598
|
-
console.log(` ${ui.yellow("Funding needed before minting.")}`);
|
|
599
|
-
const fundingRows = [
|
|
600
|
-
["Wallet", `${wallet_1.account.address.slice(0, 6)}...${wallet_1.account.address.slice(-4)}`],
|
|
601
|
-
["ETH", balanceChecksAvailable ? `${ethBalance.toFixed(6)} ETH${needsEth ? ` (need ≥${constants_1.MIN_ETH})` : ""}` : "unknown (RPC check failed)"],
|
|
602
|
-
];
|
|
603
|
-
if (config_1.config.useX402) {
|
|
604
|
-
fundingRows.push([
|
|
605
|
-
"USDC",
|
|
606
|
-
balanceChecksAvailable ? `${usdcBalance.toFixed(2)} USDC${needsUsdc ? ` (need ≥${constants_1.MIN_USDC})` : ""}` : "unknown (RPC check failed)",
|
|
607
|
-
]);
|
|
608
|
-
}
|
|
609
|
-
ui.table(fundingRows);
|
|
610
|
-
console.log("");
|
|
611
|
-
showFundingHandoff(wallet_1.account.address, needsEth, needsUsdc, options.easyMode === true);
|
|
612
|
-
return;
|
|
613
|
-
}
|
|
614
635
|
(0, context_1.setSignerContext)("mint");
|
|
615
636
|
await (0, mint_1.runMintFlow)({
|
|
616
637
|
easyMode: options.easyMode === true,
|
|
@@ -662,11 +683,13 @@ async function main() {
|
|
|
662
683
|
.description("Fund your wallet — bridge from Solana/Ethereum or send on Base")
|
|
663
684
|
.option("--chain <chain>", "Source chain: solana, ethereum, base")
|
|
664
685
|
.option("--token <token>", "Source token: sol, usdc, eth")
|
|
665
|
-
.option("--amount <eth>", "
|
|
686
|
+
.option("--amount <eth>", "Bridge ETH target (default: live funding requirement)")
|
|
666
687
|
.option("--no-swap", "Skip auto-split after bridging")
|
|
667
688
|
.action(async (opts) => {
|
|
668
689
|
(0, context_1.setSignerContext)("fund");
|
|
669
|
-
await unlockConfiguredKeystoreIfNeeded();
|
|
690
|
+
const unlocked = await unlockConfiguredKeystoreIfNeeded();
|
|
691
|
+
if (config_1.config.keystorePath && !unlocked && !wallet_1.account)
|
|
692
|
+
return;
|
|
670
693
|
if (!config_1.config.privateKey || !wallet_1.account) {
|
|
671
694
|
ui.warn("No wallet configured — launching setup first.");
|
|
672
695
|
await setupWizard();
|
|
@@ -677,6 +700,7 @@ async function main() {
|
|
|
677
700
|
return;
|
|
678
701
|
}
|
|
679
702
|
}
|
|
703
|
+
await checkWalletRecovery();
|
|
680
704
|
await (0, fund_1.runFundFlow)(opts);
|
|
681
705
|
});
|
|
682
706
|
program
|
|
@@ -684,7 +708,9 @@ async function main() {
|
|
|
684
708
|
.description("Mint a new miner NFT (Easy Mode: x402 LLM, no API key)")
|
|
685
709
|
.action(async () => {
|
|
686
710
|
(0, context_1.setSignerContext)("mint");
|
|
687
|
-
await unlockConfiguredKeystoreIfNeeded();
|
|
711
|
+
const unlocked = await unlockConfiguredKeystoreIfNeeded();
|
|
712
|
+
if (config_1.config.keystorePath && !unlocked && !wallet_1.account)
|
|
713
|
+
return;
|
|
688
714
|
if (!config_1.config.privateKey || !wallet_1.account) {
|
|
689
715
|
ui.warn("No wallet configured — launching setup first.");
|
|
690
716
|
await setupWizard();
|
|
@@ -695,6 +721,12 @@ async function main() {
|
|
|
695
721
|
return;
|
|
696
722
|
}
|
|
697
723
|
}
|
|
724
|
+
await checkWalletRecovery();
|
|
725
|
+
const funding = await (0, base_funding_1.prepareBaseFunding)(true, true);
|
|
726
|
+
if (!funding.ready) {
|
|
727
|
+
showFundingHandoff(wallet_1.account.address, funding.depositEth, false);
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
698
730
|
await (0, preflight_1.runPreflight)("wallet");
|
|
699
731
|
await (0, mint_1.runMintFlow)();
|
|
700
732
|
});
|
|
@@ -821,6 +853,13 @@ async function main() {
|
|
|
821
853
|
const walletCmd = program
|
|
822
854
|
.command("wallet")
|
|
823
855
|
.description("Wallet generation and management");
|
|
856
|
+
walletCmd.command("verify-recovery")
|
|
857
|
+
.description("Test a fresh-process unlock of the same wallet before funding")
|
|
858
|
+
.action(async () => {
|
|
859
|
+
if (!await unlockConfiguredKeystoreIfNeeded())
|
|
860
|
+
throw new Error("Unlock the existing wallet; do not replace it.");
|
|
861
|
+
await checkWalletRecovery();
|
|
862
|
+
});
|
|
824
863
|
walletCmd
|
|
825
864
|
.command("new")
|
|
826
865
|
.description("Generate a new encrypted Base wallet")
|
|
@@ -938,7 +977,9 @@ async function main() {
|
|
|
938
977
|
console.log("");
|
|
939
978
|
console.log(` Address: ${wallet_1.account.address}`);
|
|
940
979
|
console.log(` Keystore: ${config_1.config.keystorePath}`);
|
|
941
|
-
|
|
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.")}`);
|
|
942
983
|
console.log(` ${ui.dim("APoW never prints or writes a plaintext private-key export.")}`);
|
|
943
984
|
console.log("");
|
|
944
985
|
});
|