apow-cli 0.11.18 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +23 -5
- package/README.md +117 -67
- package/dist/brand-intro.js +160 -0
- package/dist/bridge/solana.js +27 -45
- package/dist/config.js +90 -5
- package/dist/dashboard-html.js +36 -43
- package/dist/dashboard.js +22 -151
- package/dist/errors.js +22 -3
- package/dist/grinder-http.js +3 -5
- package/dist/grinder-native.js +6 -5
- package/dist/index.js +540 -343
- package/dist/llm-setup.js +42 -0
- package/dist/lp-gate.js +28 -0
- package/dist/miner.js +24 -10
- package/dist/mint.js +6 -7
- package/dist/policy/audit-log.js +57 -0
- package/dist/policy/context.js +11 -0
- package/dist/policy/decode.js +84 -0
- package/dist/policy/paths.js +41 -0
- package/dist/policy/policy.js +224 -0
- package/dist/policy/spend-ledger.js +43 -0
- package/dist/preflight.js +138 -50
- package/dist/secure-env.js +65 -0
- package/dist/signer/guarded-account.js +78 -0
- package/dist/signer/local-keystore.js +40 -0
- package/dist/signer/session.js +11 -0
- package/dist/signer/types.js +2 -0
- package/dist/smhl.js +83 -10
- package/dist/stats.js +13 -1
- package/dist/sweep.js +181 -0
- package/dist/ui.js +140 -16
- package/dist/wallet-store.js +127 -31
- package/dist/wallet.js +18 -22
- package/dist/x402.js +4 -4
- package/package.json +8 -5
- package/skill.md +57 -833
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.resolveLlmSetupMode = resolveLlmSetupMode;
|
|
4
|
+
exports.resolveApiProvider = resolveApiProvider;
|
|
5
|
+
exports.resolveLocalProvider = resolveLocalProvider;
|
|
6
|
+
function resolveLlmSetupMode(input) {
|
|
7
|
+
const value = input.trim().toLowerCase();
|
|
8
|
+
if (value === "2" || value === "api" || value === "api-key")
|
|
9
|
+
return "api-key";
|
|
10
|
+
if (value === "3" || value === "local" || value === "subscription")
|
|
11
|
+
return "local";
|
|
12
|
+
return "x402";
|
|
13
|
+
}
|
|
14
|
+
function resolveApiProvider(input) {
|
|
15
|
+
const value = input.trim().toLowerCase();
|
|
16
|
+
const choices = {
|
|
17
|
+
"1": "openai",
|
|
18
|
+
openai: "openai",
|
|
19
|
+
"2": "anthropic",
|
|
20
|
+
anthropic: "anthropic",
|
|
21
|
+
"3": "gemini",
|
|
22
|
+
gemini: "gemini",
|
|
23
|
+
"4": "deepseek",
|
|
24
|
+
deepseek: "deepseek",
|
|
25
|
+
"5": "qwen",
|
|
26
|
+
qwen: "qwen",
|
|
27
|
+
};
|
|
28
|
+
return choices[value] ?? "openai";
|
|
29
|
+
}
|
|
30
|
+
function resolveLocalProvider(input) {
|
|
31
|
+
const value = input.trim().toLowerCase();
|
|
32
|
+
const choices = {
|
|
33
|
+
"1": "ollama",
|
|
34
|
+
ollama: "ollama",
|
|
35
|
+
"2": "claude-code",
|
|
36
|
+
claude: "claude-code",
|
|
37
|
+
"claude-code": "claude-code",
|
|
38
|
+
"3": "codex",
|
|
39
|
+
codex: "codex",
|
|
40
|
+
};
|
|
41
|
+
return choices[value] ?? "ollama";
|
|
42
|
+
}
|
package/dist/lp-gate.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LP_RECHECK_INTERVAL_MS = void 0;
|
|
4
|
+
exports.createLpUnlockGate = createLpUnlockGate;
|
|
5
|
+
// AgentCoin freezes all AGENT transfers until the LP pool deploys
|
|
6
|
+
// (AgentCoin._update reverts while lpDeployed is false). The gate is sticky
|
|
7
|
+
// once unlocked and re-checks at most every interval while locked, so sweeps
|
|
8
|
+
// activate on their own when the pool goes live mid-process.
|
|
9
|
+
exports.LP_RECHECK_INTERVAL_MS = 10 * 60_000;
|
|
10
|
+
function createLpUnlockGate(reader, intervalMs = exports.LP_RECHECK_INTERVAL_MS, now = Date.now) {
|
|
11
|
+
let unlocked = false;
|
|
12
|
+
let nextCheckAt = 0;
|
|
13
|
+
return async () => {
|
|
14
|
+
if (unlocked)
|
|
15
|
+
return true;
|
|
16
|
+
const at = now();
|
|
17
|
+
if (at < nextCheckAt)
|
|
18
|
+
return false;
|
|
19
|
+
nextCheckAt = at + intervalMs;
|
|
20
|
+
try {
|
|
21
|
+
unlocked = await reader();
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
// RPC failure: stay locked; the next interval re-checks.
|
|
25
|
+
}
|
|
26
|
+
return unlocked;
|
|
27
|
+
};
|
|
28
|
+
}
|
package/dist/miner.js
CHANGED
|
@@ -51,6 +51,7 @@ const grinder_1 = require("./grinder");
|
|
|
51
51
|
const grinder_http_1 = require("./grinder-http");
|
|
52
52
|
const grinder_native_1 = require("./grinder-native");
|
|
53
53
|
const smhl_1 = require("./smhl");
|
|
54
|
+
const sweep_1 = require("./sweep");
|
|
54
55
|
const ui = __importStar(require("./ui"));
|
|
55
56
|
const wallet_1 = require("./wallet");
|
|
56
57
|
const agentCoinAbi = AgentCoin_json_1.default;
|
|
@@ -302,9 +303,10 @@ async function showStartupBanner(tokenId) {
|
|
|
302
303
|
hashpower: toBigInt(hashpowerRaw),
|
|
303
304
|
};
|
|
304
305
|
}
|
|
305
|
-
async function startMining(tokenId) {
|
|
306
|
+
async function startMining(tokenId, options = {}) {
|
|
306
307
|
const { account, walletClient } = (0, wallet_1.requireWallet)();
|
|
307
308
|
let consecutiveFailures = 0;
|
|
309
|
+
let successfulMines = 0;
|
|
308
310
|
let mineCount = 0;
|
|
309
311
|
let runningTotal = (await wallet_1.publicClient.readContract({
|
|
310
312
|
address: config_1.config.agentCoinAddress,
|
|
@@ -376,10 +378,15 @@ async function startMining(tokenId) {
|
|
|
376
378
|
console.log(` 2. Add USDC to wallet for x402 GPU mining (~20 GH/s, ~$0.006/mine)`);
|
|
377
379
|
console.log(` 3. Set up VAST.ai CUDA for ~20 GH/s (see docs)`);
|
|
378
380
|
console.log("");
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
381
|
+
if (!options.easyMode) {
|
|
382
|
+
const proceed = await ui.confirm("Mining is strongly discouraged at this speed. Continue anyway?");
|
|
383
|
+
if (!proceed) {
|
|
384
|
+
console.log(` ${ui.dim("Exiting. Build faster grinders and try again.")}`);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
else {
|
|
389
|
+
ui.hint("Easy Mode is continuing; add a faster grinder to improve results.");
|
|
383
390
|
}
|
|
384
391
|
}
|
|
385
392
|
else if (estimatedSeconds > staleCheckSeconds) {
|
|
@@ -392,10 +399,15 @@ async function startMining(tokenId) {
|
|
|
392
399
|
console.log(` 2. Add USDC to wallet for x402 GPU mining (~20 GH/s, ~$0.006/mine)`);
|
|
393
400
|
console.log(` 3. Set up VAST.ai CUDA for ~20 GH/s (see docs)`);
|
|
394
401
|
console.log("");
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
402
|
+
if (!options.easyMode) {
|
|
403
|
+
const proceed = await ui.confirm("Continue anyway?");
|
|
404
|
+
if (!proceed) {
|
|
405
|
+
console.log(` ${ui.dim("Exiting. Build faster grinders and try again.")}`);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
else {
|
|
410
|
+
ui.hint("Easy Mode is continuing; add a faster grinder to improve results.");
|
|
399
411
|
}
|
|
400
412
|
}
|
|
401
413
|
console.log("");
|
|
@@ -521,7 +533,7 @@ async function startMining(tokenId) {
|
|
|
521
533
|
}
|
|
522
534
|
if (useHttpGrind) {
|
|
523
535
|
grinders.push(Promise.race([
|
|
524
|
-
(0, grinder_http_1.grindNonceHttp)(challengeNumber, target, account.address, grindUrl,
|
|
536
|
+
(0, grinder_http_1.grindNonceHttp)(challengeNumber, target, account.address, grindUrl, account, abortController.signal),
|
|
525
537
|
rejectOnAbort(abortController.signal),
|
|
526
538
|
])
|
|
527
539
|
.catch((err) => {
|
|
@@ -662,6 +674,8 @@ async function startMining(tokenId) {
|
|
|
662
674
|
console.log("");
|
|
663
675
|
// Wait for block advancement before next iteration
|
|
664
676
|
await waitForNextBlock(receipt.blockNumber);
|
|
677
|
+
successfulMines += 1;
|
|
678
|
+
await (0, sweep_1.maybeAutoSweep)(successfulMines);
|
|
665
679
|
consecutiveFailures = 0;
|
|
666
680
|
}
|
|
667
681
|
catch (error) {
|
package/dist/mint.js
CHANGED
|
@@ -44,6 +44,7 @@ const explorer_1 = require("./explorer");
|
|
|
44
44
|
const smhl_1 = require("./smhl");
|
|
45
45
|
const detect_1 = require("./detect");
|
|
46
46
|
const miner_1 = require("./miner");
|
|
47
|
+
const context_1 = require("./policy/context");
|
|
47
48
|
const ui = __importStar(require("./ui"));
|
|
48
49
|
const wallet_1 = require("./wallet");
|
|
49
50
|
const miningAgentAbi = MiningAgent_json_1.default;
|
|
@@ -145,8 +146,7 @@ async function runMintFlow(options = {}) {
|
|
|
145
146
|
ui.hint(`Send at least ${(0, viem_1.formatEther)(requiredBalance)} ETH to ${account.address} on Base.`);
|
|
146
147
|
return null;
|
|
147
148
|
}
|
|
148
|
-
|
|
149
|
-
const proceed = await ui.confirm("Proceed with mint?");
|
|
149
|
+
const proceed = options.easyMode === true || await ui.confirm("Proceed with mint?");
|
|
150
150
|
if (!proceed) {
|
|
151
151
|
console.log(" Mint cancelled.");
|
|
152
152
|
return null;
|
|
@@ -288,13 +288,12 @@ async function runMintFlow(options = {}) {
|
|
|
288
288
|
console.log("");
|
|
289
289
|
// Offer to start mining
|
|
290
290
|
if (options.startMiningAfterMint === true) {
|
|
291
|
-
|
|
291
|
+
(0, context_1.setSignerContext)("mine");
|
|
292
|
+
await (0, miner_1.startMining)(tokenId, { easyMode: options.easyMode === true });
|
|
292
293
|
}
|
|
293
294
|
else if (options.startMiningAfterMint !== false) {
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
await (0, miner_1.startMining)(tokenId);
|
|
297
|
-
}
|
|
295
|
+
(0, context_1.setSignerContext)("mine");
|
|
296
|
+
await (0, miner_1.startMining)(tokenId);
|
|
298
297
|
}
|
|
299
298
|
return tokenId;
|
|
300
299
|
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.appendAudit = appendAudit;
|
|
4
|
+
exports.verifyAuditChain = verifyAuditChain;
|
|
5
|
+
const node_fs_1 = require("node:fs");
|
|
6
|
+
const node_crypto_1 = require("node:crypto");
|
|
7
|
+
const paths_1 = require("./paths");
|
|
8
|
+
function hashLine(line) {
|
|
9
|
+
return `0x${(0, node_crypto_1.createHash)("sha256").update(line).digest("hex")}`;
|
|
10
|
+
}
|
|
11
|
+
function readLast(path) {
|
|
12
|
+
if (!(0, node_fs_1.existsSync)(path)) {
|
|
13
|
+
return { seq: 0, hash: "0x0" };
|
|
14
|
+
}
|
|
15
|
+
const lines = (0, node_fs_1.readFileSync)(path, "utf8").split(/\r?\n/).filter(Boolean);
|
|
16
|
+
if (lines.length === 0) {
|
|
17
|
+
return { seq: 0, hash: "0x0" };
|
|
18
|
+
}
|
|
19
|
+
const last = JSON.parse(lines[lines.length - 1]);
|
|
20
|
+
return { seq: last.seq, hash: hashLine(lines[lines.length - 1]) };
|
|
21
|
+
}
|
|
22
|
+
function appendAudit(entry) {
|
|
23
|
+
const path = (0, paths_1.auditPath)(entry.address);
|
|
24
|
+
if (!(0, node_fs_1.existsSync)(path)) {
|
|
25
|
+
(0, node_fs_1.writeFileSync)(path, "", { mode: 0o600 });
|
|
26
|
+
}
|
|
27
|
+
const last = readLast(path);
|
|
28
|
+
const stored = {
|
|
29
|
+
...entry,
|
|
30
|
+
ts: new Date().toISOString(),
|
|
31
|
+
seq: last.seq + 1,
|
|
32
|
+
prev: last.hash,
|
|
33
|
+
};
|
|
34
|
+
(0, node_fs_1.appendFileSync)(path, `${JSON.stringify(stored)}\n`, { mode: 0o600 });
|
|
35
|
+
try {
|
|
36
|
+
(0, node_fs_1.chmodSync)(path, 0o600);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// Best effort.
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function verifyAuditChain(path) {
|
|
43
|
+
if (!(0, node_fs_1.existsSync)(path))
|
|
44
|
+
return true;
|
|
45
|
+
const lines = (0, node_fs_1.readFileSync)(path, "utf8").split(/\r?\n/).filter(Boolean);
|
|
46
|
+
let prev = "0x0";
|
|
47
|
+
let seq = 0;
|
|
48
|
+
for (const line of lines) {
|
|
49
|
+
const entry = JSON.parse(line);
|
|
50
|
+
seq += 1;
|
|
51
|
+
if (entry.seq !== seq || entry.prev !== prev) {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
prev = hashLine(line);
|
|
55
|
+
}
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.setSignerContext = setSignerContext;
|
|
4
|
+
exports.getSignerContext = getSignerContext;
|
|
5
|
+
let currentContext = "default";
|
|
6
|
+
function setSignerContext(context) {
|
|
7
|
+
currentContext = context;
|
|
8
|
+
}
|
|
9
|
+
function getSignerContext() {
|
|
10
|
+
return currentContext;
|
|
11
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SELECTORS = exports.SWAP_ROUTER02 = exports.USDC_ADDRESS = void 0;
|
|
4
|
+
exports.selector = selector;
|
|
5
|
+
exports.calldataSelector = calldataSelector;
|
|
6
|
+
exports.readAddressArg = readAddressArg;
|
|
7
|
+
exports.readUintArg = readUintArg;
|
|
8
|
+
exports.parseErc20Transfer = parseErc20Transfer;
|
|
9
|
+
exports.parseErc20Approve = parseErc20Approve;
|
|
10
|
+
exports.parseEip3009 = parseEip3009;
|
|
11
|
+
exports.isPermitTypedData = isPermitTypedData;
|
|
12
|
+
exports.padAddress = padAddress;
|
|
13
|
+
const viem_1 = require("viem");
|
|
14
|
+
const constants_1 = require("../bridge/constants");
|
|
15
|
+
exports.USDC_ADDRESS = constants_1.TOKENS.base.usdc;
|
|
16
|
+
exports.SWAP_ROUTER02 = "0x2626664c2603336E57B271c5C0b26F421741e481";
|
|
17
|
+
exports.SELECTORS = {
|
|
18
|
+
mine: selector("mine(uint256,string,uint256)"),
|
|
19
|
+
getChallenge: selector("getChallenge(address)"),
|
|
20
|
+
mint: selector("mint(string)"),
|
|
21
|
+
transfer: selector("transfer(address,uint256)"),
|
|
22
|
+
approve: selector("approve(address,uint256)"),
|
|
23
|
+
exactInputSingle: selector("exactInputSingle((address,address,uint24,address,uint256,uint256,uint160))"),
|
|
24
|
+
multicall: selector("multicall(uint256,bytes[])"),
|
|
25
|
+
};
|
|
26
|
+
function selector(signature) {
|
|
27
|
+
return (0, viem_1.sliceHex)((0, viem_1.keccak256)((0, viem_1.stringToHex)(signature)), 0, 4);
|
|
28
|
+
}
|
|
29
|
+
function calldataSelector(data) {
|
|
30
|
+
return data && data.length >= 10 ? (0, viem_1.sliceHex)(data, 0, 4) : "0x";
|
|
31
|
+
}
|
|
32
|
+
function word(data, index) {
|
|
33
|
+
const start = 4 + index * 32;
|
|
34
|
+
return (0, viem_1.sliceHex)(data, start, start + 32);
|
|
35
|
+
}
|
|
36
|
+
function readAddressArg(data, index) {
|
|
37
|
+
return (0, viem_1.getAddress)(`0x${word(data, index).slice(-40)}`);
|
|
38
|
+
}
|
|
39
|
+
function readUintArg(data, index) {
|
|
40
|
+
return (0, viem_1.hexToBigInt)(word(data, index));
|
|
41
|
+
}
|
|
42
|
+
function parseErc20Transfer(data) {
|
|
43
|
+
if (calldataSelector(data) !== exports.SELECTORS.transfer)
|
|
44
|
+
return null;
|
|
45
|
+
return { recipient: readAddressArg(data, 0), amount: readUintArg(data, 1) };
|
|
46
|
+
}
|
|
47
|
+
function parseErc20Approve(data) {
|
|
48
|
+
if (calldataSelector(data) !== exports.SELECTORS.approve)
|
|
49
|
+
return null;
|
|
50
|
+
return { spender: readAddressArg(data, 0), amount: readUintArg(data, 1) };
|
|
51
|
+
}
|
|
52
|
+
function getTypedMessage(parameters) {
|
|
53
|
+
const obj = parameters;
|
|
54
|
+
return obj.message && typeof obj.message === "object" ? obj.message : {};
|
|
55
|
+
}
|
|
56
|
+
function addressFromUnknown(value) {
|
|
57
|
+
if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value))
|
|
58
|
+
return null;
|
|
59
|
+
return (0, viem_1.getAddress)(value);
|
|
60
|
+
}
|
|
61
|
+
function parseEip3009(parameters) {
|
|
62
|
+
const typed = parameters;
|
|
63
|
+
const verifying = addressFromUnknown(typed.domain?.verifyingContract);
|
|
64
|
+
if (!verifying || verifying.toLowerCase() !== exports.USDC_ADDRESS.toLowerCase()) {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
if (typed.primaryType !== "TransferWithAuthorization" && typed.primaryType !== "ReceiveWithAuthorization") {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
const message = getTypedMessage(parameters);
|
|
71
|
+
const payee = addressFromUnknown(message.to);
|
|
72
|
+
const rawValue = typeof message.value === "bigint" ? message.value : BigInt(String(message.value ?? "0"));
|
|
73
|
+
if (!payee)
|
|
74
|
+
return null;
|
|
75
|
+
const validBefore = message.validBefore !== undefined ? BigInt(String(message.validBefore)) : undefined;
|
|
76
|
+
return { payee, usdc: Number(rawValue) / 1_000_000, validBefore };
|
|
77
|
+
}
|
|
78
|
+
function isPermitTypedData(parameters) {
|
|
79
|
+
const primaryType = parameters.primaryType;
|
|
80
|
+
return typeof primaryType === "string" && /permit/i.test(primaryType);
|
|
81
|
+
}
|
|
82
|
+
function padAddress(address) {
|
|
83
|
+
return (0, viem_1.padHex)(address, { size: 32 });
|
|
84
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ensureApowDir = ensureApowDir;
|
|
4
|
+
exports.expandHome = expandHome;
|
|
5
|
+
exports.policyPath = policyPath;
|
|
6
|
+
exports.auditPath = auditPath;
|
|
7
|
+
exports.spendPath = spendPath;
|
|
8
|
+
const node_fs_1 = require("node:fs");
|
|
9
|
+
const node_os_1 = require("node:os");
|
|
10
|
+
const node_path_1 = require("node:path");
|
|
11
|
+
function ensureApowDir() {
|
|
12
|
+
const override = process.env.APOW_DATA_DIR?.trim();
|
|
13
|
+
const dir = override ? (0, node_path_1.resolve)(expandHome(override)) : (0, node_path_1.join)((0, node_os_1.homedir)(), ".apow");
|
|
14
|
+
if (!(0, node_fs_1.existsSync)(dir)) {
|
|
15
|
+
(0, node_fs_1.mkdirSync)(dir, { recursive: true, mode: 0o700 });
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
(0, node_fs_1.chmodSync)(dir, 0o700);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// Best effort on filesystems that do not support chmod.
|
|
22
|
+
}
|
|
23
|
+
return dir;
|
|
24
|
+
}
|
|
25
|
+
function expandHome(path) {
|
|
26
|
+
if (path === "~")
|
|
27
|
+
return (0, node_os_1.homedir)();
|
|
28
|
+
if (path.startsWith("~/"))
|
|
29
|
+
return (0, node_path_1.join)((0, node_os_1.homedir)(), path.slice(2));
|
|
30
|
+
return path;
|
|
31
|
+
}
|
|
32
|
+
function policyPath() {
|
|
33
|
+
const override = process.env.APOW_POLICY_PATH?.trim();
|
|
34
|
+
return override ? (0, node_path_1.resolve)(expandHome(override)) : (0, node_path_1.join)(ensureApowDir(), "policy.json");
|
|
35
|
+
}
|
|
36
|
+
function auditPath(address) {
|
|
37
|
+
return (0, node_path_1.join)(ensureApowDir(), `audit-${address.toLowerCase()}.jsonl`);
|
|
38
|
+
}
|
|
39
|
+
function spendPath(address) {
|
|
40
|
+
return (0, node_path_1.join)(ensureApowDir(), `spend-${address.toLowerCase()}.jsonl`);
|
|
41
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PolicyDeniedError = exports.EASY_MODE_POLICY_CAPS = void 0;
|
|
4
|
+
exports.loadPolicy = loadPolicy;
|
|
5
|
+
exports.validateEasyModePolicyCaps = validateEasyModePolicyCaps;
|
|
6
|
+
exports.writeDefaultPolicyFile = writeDefaultPolicyFile;
|
|
7
|
+
exports.savePolicy = savePolicy;
|
|
8
|
+
exports.assertAllowed = assertAllowed;
|
|
9
|
+
exports.evaluateTx = evaluateTx;
|
|
10
|
+
exports.evaluateTypedData = evaluateTypedData;
|
|
11
|
+
exports.getPayoutAddress = getPayoutAddress;
|
|
12
|
+
const node_fs_1 = require("node:fs");
|
|
13
|
+
const viem_1 = require("viem");
|
|
14
|
+
const config_1 = require("../config");
|
|
15
|
+
const decode_1 = require("./decode");
|
|
16
|
+
const paths_1 = require("./paths");
|
|
17
|
+
const spend_ledger_1 = require("./spend-ledger");
|
|
18
|
+
exports.EASY_MODE_POLICY_CAPS = {
|
|
19
|
+
maxMintEth: "0.01",
|
|
20
|
+
maxPerRequestUsdc: 1,
|
|
21
|
+
dailyUsdc: 20,
|
|
22
|
+
};
|
|
23
|
+
class PolicyDeniedError extends Error {
|
|
24
|
+
rule;
|
|
25
|
+
hint;
|
|
26
|
+
constructor(rule, hint) {
|
|
27
|
+
super(`Policy denied: ${rule}. ${hint}`);
|
|
28
|
+
this.name = "PolicyDeniedError";
|
|
29
|
+
this.rule = rule;
|
|
30
|
+
this.hint = hint;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
exports.PolicyDeniedError = PolicyDeniedError;
|
|
34
|
+
function parseMode(value) {
|
|
35
|
+
return value === "enforce" || value === "warn" || value === "off" ? value : undefined;
|
|
36
|
+
}
|
|
37
|
+
function defaultPolicy() {
|
|
38
|
+
return {
|
|
39
|
+
mode: "enforce",
|
|
40
|
+
maxMintEth: "0.01",
|
|
41
|
+
maxSwapEth: "0.02",
|
|
42
|
+
maxEthTransferEth: "0.05",
|
|
43
|
+
x402: {
|
|
44
|
+
maxPerRequestUsdc: Number(process.env.APOW_X402_MAX_PER_REQUEST_USDC ?? "1"),
|
|
45
|
+
dailyUsdc: Number(process.env.APOW_X402_DAILY_USDC ?? "20"),
|
|
46
|
+
payees: [],
|
|
47
|
+
},
|
|
48
|
+
sweep: {
|
|
49
|
+
auto: true,
|
|
50
|
+
thresholdAgent: process.env.APOW_SWEEP_THRESHOLD_AGENT ?? "25",
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function sanitizePolicy(raw) {
|
|
55
|
+
const base = defaultPolicy();
|
|
56
|
+
const payout = process.env.APOW_PAYOUT_ADDRESS?.trim() || raw.payout;
|
|
57
|
+
return {
|
|
58
|
+
...base,
|
|
59
|
+
...raw,
|
|
60
|
+
mode: parseMode(process.env.APOW_POLICY) ?? parseMode(raw.mode) ?? base.mode,
|
|
61
|
+
payout: payout && /^0x[0-9a-fA-F]{40}$/.test(payout) ? (0, viem_1.getAddress)(payout) : undefined,
|
|
62
|
+
x402: {
|
|
63
|
+
...base.x402,
|
|
64
|
+
...(raw.x402 ?? {}),
|
|
65
|
+
maxPerRequestUsdc: Number(process.env.APOW_X402_MAX_PER_REQUEST_USDC ?? raw.x402?.maxPerRequestUsdc ?? base.x402.maxPerRequestUsdc),
|
|
66
|
+
dailyUsdc: Number(process.env.APOW_X402_DAILY_USDC ?? raw.x402?.dailyUsdc ?? base.x402.dailyUsdc),
|
|
67
|
+
payees: (raw.x402?.payees ?? []).filter((p) => /^0x[0-9a-fA-F]{40}$/.test(p)),
|
|
68
|
+
},
|
|
69
|
+
sweep: {
|
|
70
|
+
...base.sweep,
|
|
71
|
+
...(raw.sweep ?? {}),
|
|
72
|
+
thresholdAgent: process.env.APOW_SWEEP_THRESHOLD_AGENT ?? raw.sweep?.thresholdAgent ?? base.sweep.thresholdAgent,
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function loadPolicy() {
|
|
77
|
+
const path = (0, paths_1.policyPath)();
|
|
78
|
+
if (!(0, node_fs_1.existsSync)(path))
|
|
79
|
+
return sanitizePolicy({});
|
|
80
|
+
const raw = JSON.parse((0, node_fs_1.readFileSync)(path, "utf8"));
|
|
81
|
+
return sanitizePolicy(raw);
|
|
82
|
+
}
|
|
83
|
+
function validateEasyModePolicyCaps(policy) {
|
|
84
|
+
if (policy.mode !== "enforce") {
|
|
85
|
+
return "Easy Mode requires the wallet signing policy in enforce mode.";
|
|
86
|
+
}
|
|
87
|
+
let maxMint;
|
|
88
|
+
try {
|
|
89
|
+
maxMint = (0, viem_1.parseEther)(policy.maxMintEth);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return "The policy mint cap is invalid.";
|
|
93
|
+
}
|
|
94
|
+
if (maxMint < 0n || maxMint > (0, viem_1.parseEther)(exports.EASY_MODE_POLICY_CAPS.maxMintEth)) {
|
|
95
|
+
return `The policy mint cap must not exceed ${exports.EASY_MODE_POLICY_CAPS.maxMintEth} ETH.`;
|
|
96
|
+
}
|
|
97
|
+
const perRequest = policy.x402.maxPerRequestUsdc;
|
|
98
|
+
const daily = policy.x402.dailyUsdc;
|
|
99
|
+
if (!Number.isFinite(perRequest) || perRequest < 0 || perRequest > exports.EASY_MODE_POLICY_CAPS.maxPerRequestUsdc) {
|
|
100
|
+
return `The x402 per-request cap must be between 0 and ${exports.EASY_MODE_POLICY_CAPS.maxPerRequestUsdc} USDC.`;
|
|
101
|
+
}
|
|
102
|
+
if (!Number.isFinite(daily) || daily < 0 || daily > exports.EASY_MODE_POLICY_CAPS.dailyUsdc) {
|
|
103
|
+
return `The x402 daily cap must be between 0 and ${exports.EASY_MODE_POLICY_CAPS.dailyUsdc} USDC.`;
|
|
104
|
+
}
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
function writeDefaultPolicyFile(overwrite = false) {
|
|
108
|
+
const path = (0, paths_1.policyPath)();
|
|
109
|
+
if ((0, node_fs_1.existsSync)(path) && !overwrite)
|
|
110
|
+
return path;
|
|
111
|
+
(0, node_fs_1.writeFileSync)(path, JSON.stringify(defaultPolicy(), null, 2) + "\n", { mode: 0o600 });
|
|
112
|
+
try {
|
|
113
|
+
(0, node_fs_1.chmodSync)(path, 0o600);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
// Best effort.
|
|
117
|
+
}
|
|
118
|
+
return path;
|
|
119
|
+
}
|
|
120
|
+
function savePolicy(policy) {
|
|
121
|
+
const path = (0, paths_1.policyPath)();
|
|
122
|
+
(0, node_fs_1.writeFileSync)(path, JSON.stringify(policy, null, 2) + "\n", { mode: 0o600 });
|
|
123
|
+
try {
|
|
124
|
+
(0, node_fs_1.chmodSync)(path, 0o600);
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
// Best effort.
|
|
128
|
+
}
|
|
129
|
+
return path;
|
|
130
|
+
}
|
|
131
|
+
function lower(value) {
|
|
132
|
+
return (value ?? "").toLowerCase();
|
|
133
|
+
}
|
|
134
|
+
function finalize(policy, verdict) {
|
|
135
|
+
if (policy.mode === "off" && verdict.verdict === "deny") {
|
|
136
|
+
return { ...verdict, verdict: "warn", rule: `${verdict.rule}: policy off` };
|
|
137
|
+
}
|
|
138
|
+
if (policy.mode === "warn" && verdict.verdict === "deny") {
|
|
139
|
+
return { ...verdict, verdict: "warn" };
|
|
140
|
+
}
|
|
141
|
+
return verdict;
|
|
142
|
+
}
|
|
143
|
+
function deny(policy, rule, hint, kind = "other") {
|
|
144
|
+
return finalize(policy, { verdict: "deny", rule, hint, kind });
|
|
145
|
+
}
|
|
146
|
+
function allow(policy, rule, kind, extra = {}) {
|
|
147
|
+
return finalize(policy, { verdict: "allow", rule, kind, ...extra });
|
|
148
|
+
}
|
|
149
|
+
function assertAllowed(verdict) {
|
|
150
|
+
if (verdict.verdict === "deny") {
|
|
151
|
+
throw new PolicyDeniedError(verdict.rule, verdict.hint ?? "Change policy.json or the command inputs.");
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function evaluateTx(req) {
|
|
155
|
+
const policy = loadPolicy();
|
|
156
|
+
const to = req.to ? (0, viem_1.getAddress)(req.to) : undefined;
|
|
157
|
+
const value = req.value ?? 0n;
|
|
158
|
+
const data = req.data ?? "0x";
|
|
159
|
+
const selector = (0, decode_1.calldataSelector)(data);
|
|
160
|
+
if (!to) {
|
|
161
|
+
return deny(policy, "contract creation not allowed", "APoW CLI never needs to deploy contracts.");
|
|
162
|
+
}
|
|
163
|
+
if (data === "0x") {
|
|
164
|
+
if ((req.context === "sweep" || req.context === "wallet-fund") && value <= (0, viem_1.parseEther)(policy.maxEthTransferEth)) {
|
|
165
|
+
return allow(policy, "eth-transfer-cap", "eth-send");
|
|
166
|
+
}
|
|
167
|
+
if (req.context === "sweep" && policy.payout && lower(to) === lower(policy.payout)) {
|
|
168
|
+
return allow(policy, "eth-sweep-to-payout", "sweep");
|
|
169
|
+
}
|
|
170
|
+
return deny(policy, "eth-transfer-denied", `Plain ETH transfers are capped at ${policy.maxEthTransferEth} ETH.`);
|
|
171
|
+
}
|
|
172
|
+
if (lower(to) === lower(config_1.config.agentCoinAddress) && selector === decode_1.SELECTORS.mine && value === 0n) {
|
|
173
|
+
return allow(policy, "agentcoin-mine", "mine");
|
|
174
|
+
}
|
|
175
|
+
if (lower(to) === lower(config_1.config.miningAgentAddress) && selector === decode_1.SELECTORS.getChallenge && value === 0n) {
|
|
176
|
+
return allow(policy, "miningagent-getchallenge", "challenge");
|
|
177
|
+
}
|
|
178
|
+
if (lower(to) === lower(config_1.config.miningAgentAddress) && selector === decode_1.SELECTORS.mint && value <= (0, viem_1.parseEther)(policy.maxMintEth)) {
|
|
179
|
+
return allow(policy, "miningagent-mint", "mint");
|
|
180
|
+
}
|
|
181
|
+
const transfer = (0, decode_1.parseErc20Transfer)(data);
|
|
182
|
+
if (transfer && policy.payout && lower(transfer.recipient) === lower(policy.payout)) {
|
|
183
|
+
if (lower(to) === lower(config_1.config.agentCoinAddress)) {
|
|
184
|
+
return allow(policy, "agent-sweep-to-payout", "sweep");
|
|
185
|
+
}
|
|
186
|
+
if (lower(to) === lower(decode_1.USDC_ADDRESS) && req.context === "sweep") {
|
|
187
|
+
return allow(policy, "usdc-sweep-to-payout", "sweep");
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
const approve = (0, decode_1.parseErc20Approve)(data);
|
|
191
|
+
if (approve && lower(to) === lower(decode_1.USDC_ADDRESS) && lower(approve.spender) === lower(decode_1.SWAP_ROUTER02) && req.context === "fund") {
|
|
192
|
+
return allow(policy, "usdc-approve-swaprouter", "fund-swap");
|
|
193
|
+
}
|
|
194
|
+
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) {
|
|
196
|
+
return allow(policy, "swaprouter-fund", "fund-swap");
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return deny(policy, `unknown-call-${selector}`, "Only APoW mining, minting, configured sweeps, and bounded funding swaps are allowed.");
|
|
200
|
+
}
|
|
201
|
+
function evaluateTypedData(req) {
|
|
202
|
+
const policy = loadPolicy();
|
|
203
|
+
if ((0, decode_1.isPermitTypedData)(req.parameters)) {
|
|
204
|
+
return deny(policy, "permit-typed-data-denied", "Permit and Permit2 signatures are disabled.");
|
|
205
|
+
}
|
|
206
|
+
const payment = (0, decode_1.parseEip3009)(req.parameters);
|
|
207
|
+
if (!payment) {
|
|
208
|
+
return deny(policy, "typed-data-denied", "Only USDC EIP-3009 x402 payment signatures are allowed.");
|
|
209
|
+
}
|
|
210
|
+
if (payment.usdc > policy.x402.maxPerRequestUsdc) {
|
|
211
|
+
return deny(policy, "x402-per-request-cap", `Payment ${payment.usdc} USDC exceeds ${policy.x402.maxPerRequestUsdc} USDC.`);
|
|
212
|
+
}
|
|
213
|
+
const spent = (0, spend_ledger_1.spentTodayUsdc)(req.account);
|
|
214
|
+
if (spent + payment.usdc > policy.x402.dailyUsdc) {
|
|
215
|
+
return deny(policy, "x402-daily-cap", `Daily x402 budget would exceed ${policy.x402.dailyUsdc} USDC.`);
|
|
216
|
+
}
|
|
217
|
+
if (policy.x402.payees.length > 0 && !policy.x402.payees.some((p) => lower(p) === lower(payment.payee))) {
|
|
218
|
+
return deny(policy, "x402-payee-denied", "This x402 payee is not pinned in policy.json.");
|
|
219
|
+
}
|
|
220
|
+
return allow(policy, "x402-eip3009", "x402", { payee: payment.payee, usdc: payment.usdc });
|
|
221
|
+
}
|
|
222
|
+
function getPayoutAddress(policy = loadPolicy()) {
|
|
223
|
+
return policy.payout;
|
|
224
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.recordSpend = recordSpend;
|
|
4
|
+
exports.spentTodayUsdc = spentTodayUsdc;
|
|
5
|
+
const node_fs_1 = require("node:fs");
|
|
6
|
+
const paths_1 = require("./paths");
|
|
7
|
+
function utcDay(ts = new Date()) {
|
|
8
|
+
return ts.toISOString().slice(0, 10);
|
|
9
|
+
}
|
|
10
|
+
function recordSpend(entry) {
|
|
11
|
+
const path = (0, paths_1.spendPath)(entry.address);
|
|
12
|
+
if (!(0, node_fs_1.existsSync)(path)) {
|
|
13
|
+
(0, node_fs_1.writeFileSync)(path, "", { mode: 0o600 });
|
|
14
|
+
}
|
|
15
|
+
const stored = { ...entry, ts: new Date().toISOString(), day: utcDay() };
|
|
16
|
+
(0, node_fs_1.appendFileSync)(path, `${JSON.stringify(stored)}\n`, { mode: 0o600 });
|
|
17
|
+
try {
|
|
18
|
+
(0, node_fs_1.chmodSync)(path, 0o600);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// Best effort.
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function spentTodayUsdc(address) {
|
|
25
|
+
const path = (0, paths_1.spendPath)(address);
|
|
26
|
+
if (!(0, node_fs_1.existsSync)(path))
|
|
27
|
+
return 0;
|
|
28
|
+
const day = utcDay();
|
|
29
|
+
let total = 0;
|
|
30
|
+
for (const line of (0, node_fs_1.readFileSync)(path, "utf8").split(/\r?\n/)) {
|
|
31
|
+
if (!line.trim())
|
|
32
|
+
continue;
|
|
33
|
+
try {
|
|
34
|
+
const entry = JSON.parse(line);
|
|
35
|
+
if (entry.day === day)
|
|
36
|
+
total += Number(entry.usdc) || 0;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// Ignore malformed historical rows.
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return total;
|
|
43
|
+
}
|