apow-cli 0.11.19 → 0.12.3
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 +25 -5
- package/README.md +141 -84
- package/dist/base-funding.js +98 -0
- package/dist/brand-intro.js +160 -0
- package/dist/bridge/solana.js +27 -45
- package/dist/bridge/squid.js +29 -8
- package/dist/bridge/uniswap.js +48 -1
- package/dist/config.js +90 -5
- package/dist/dashboard-html.js +36 -43
- package/dist/dashboard.js +22 -151
- package/dist/errors.js +26 -3
- package/dist/fund.js +91 -506
- package/dist/funding-plan.js +29 -0
- package/dist/grinder-http.js +13 -14
- package/dist/grinder-native.js +6 -5
- package/dist/index.js +575 -384
- package/dist/llm-setup.js +42 -0
- package/dist/lp-gate.js +28 -0
- package/dist/miner.js +26 -12
- 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 +133 -55
- 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-recovery.js +52 -0
- package/dist/wallet-store.js +127 -31
- package/dist/wallet.js +24 -28
- package/dist/x402.js +4 -4
- package/package.json +10 -6
- package/skill.md +81 -837
package/dist/stats.js
CHANGED
|
@@ -43,12 +43,14 @@ const MiningAgent_json_1 = __importDefault(require("./abi/MiningAgent.json"));
|
|
|
43
43
|
const config_1 = require("./config");
|
|
44
44
|
const detect_1 = require("./detect");
|
|
45
45
|
const explorer_1 = require("./explorer");
|
|
46
|
+
const policy_1 = require("./policy/policy");
|
|
46
47
|
const ui = __importStar(require("./ui"));
|
|
47
48
|
const wallet_1 = require("./wallet");
|
|
48
49
|
const miningAgentAbi = MiningAgent_json_1.default;
|
|
49
50
|
const agentCoinAbi = AgentCoin_json_1.default;
|
|
50
51
|
async function displayStats(tokenId) {
|
|
51
|
-
const
|
|
52
|
+
const payout = (0, policy_1.getPayoutAddress)();
|
|
53
|
+
const [totalMines, totalMinted, miningTarget, mineableSupply, eraInterval, walletBalance, payoutBalance] = await Promise.all([
|
|
52
54
|
wallet_1.publicClient.readContract({
|
|
53
55
|
address: config_1.config.agentCoinAddress,
|
|
54
56
|
abi: agentCoinAbi,
|
|
@@ -82,6 +84,14 @@ async function displayStats(tokenId) {
|
|
|
82
84
|
args: [wallet_1.account.address],
|
|
83
85
|
})
|
|
84
86
|
: Promise.resolve(0n),
|
|
87
|
+
payout
|
|
88
|
+
? wallet_1.publicClient.readContract({
|
|
89
|
+
address: config_1.config.agentCoinAddress,
|
|
90
|
+
abi: agentCoinAbi,
|
|
91
|
+
functionName: "balanceOf",
|
|
92
|
+
args: [payout],
|
|
93
|
+
})
|
|
94
|
+
: Promise.resolve(0n),
|
|
85
95
|
]);
|
|
86
96
|
const era = totalMines / eraInterval;
|
|
87
97
|
const minesUntilNextEra = eraInterval - (totalMines % eraInterval);
|
|
@@ -112,6 +122,8 @@ async function displayStats(tokenId) {
|
|
|
112
122
|
ui.table([
|
|
113
123
|
["Address", `${wallet_1.account.address.slice(0, 6)}...${wallet_1.account.address.slice(-4)}`],
|
|
114
124
|
["AGENT balance", `${Number((0, viem_1.formatEther)(walletBalance)).toLocaleString()} AGENT`],
|
|
125
|
+
["Payout", payout ? `${payout.slice(0, 6)}...${payout.slice(-4)}` : "(not configured)"],
|
|
126
|
+
["Payout AGENT", payout ? `${Number((0, viem_1.formatEther)(payoutBalance)).toLocaleString()} AGENT` : "-"],
|
|
115
127
|
]);
|
|
116
128
|
}
|
|
117
129
|
if (tokenId === undefined) {
|
package/dist/sweep.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.runSweep = runSweep;
|
|
40
|
+
exports.maybeAutoSweep = maybeAutoSweep;
|
|
41
|
+
const viem_1 = require("viem");
|
|
42
|
+
const AgentCoin_json_1 = __importDefault(require("./abi/AgentCoin.json"));
|
|
43
|
+
const constants_1 = require("./bridge/constants");
|
|
44
|
+
const config_1 = require("./config");
|
|
45
|
+
const explorer_1 = require("./explorer");
|
|
46
|
+
const errors_1 = require("./errors");
|
|
47
|
+
const lp_gate_1 = require("./lp-gate");
|
|
48
|
+
const context_1 = require("./policy/context");
|
|
49
|
+
const policy_1 = require("./policy/policy");
|
|
50
|
+
const ui = __importStar(require("./ui"));
|
|
51
|
+
const wallet_1 = require("./wallet");
|
|
52
|
+
const agentCoinAbi = AgentCoin_json_1.default;
|
|
53
|
+
const ERC20_ABI = [
|
|
54
|
+
{ type: "function", name: "balanceOf", inputs: [{ name: "account", type: "address" }], outputs: [{ name: "", type: "uint256" }], stateMutability: "view" },
|
|
55
|
+
{ type: "function", name: "transfer", inputs: [{ name: "to", type: "address" }, { name: "amount", type: "uint256" }], outputs: [{ name: "", type: "bool" }], stateMutability: "nonpayable" },
|
|
56
|
+
];
|
|
57
|
+
// lpDeployed is absent from the frozen AgentCoin.json ABI; declare it inline.
|
|
58
|
+
const LP_GATE_ABI = [
|
|
59
|
+
{ type: "function", name: "lpDeployed", inputs: [], outputs: [{ name: "", type: "bool" }], stateMutability: "view" },
|
|
60
|
+
];
|
|
61
|
+
const ETH_GAS_RESERVE = (0, viem_1.parseEther)("0.0002");
|
|
62
|
+
const USDC_WORKING_BALANCE = (0, viem_1.parseUnits)("5", 6);
|
|
63
|
+
const SWEEP_RECEIPT_TIMEOUT_MS = 30_000;
|
|
64
|
+
let nextAutoSweepMine = 0;
|
|
65
|
+
let autoSweepFailures = 0;
|
|
66
|
+
let lockNoticeShown = false;
|
|
67
|
+
const agentTransfersUnlocked = (0, lp_gate_1.createLpUnlockGate)(async () => {
|
|
68
|
+
return (await wallet_1.publicClient.readContract({
|
|
69
|
+
address: config_1.config.agentCoinAddress,
|
|
70
|
+
abi: LP_GATE_ABI,
|
|
71
|
+
functionName: "lpDeployed",
|
|
72
|
+
}));
|
|
73
|
+
});
|
|
74
|
+
async function waitForReceipt(hash) {
|
|
75
|
+
await Promise.race([
|
|
76
|
+
wallet_1.publicClient.waitForTransactionReceipt({ hash }),
|
|
77
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error("Sweep receipt wait timed out")), SWEEP_RECEIPT_TIMEOUT_MS)),
|
|
78
|
+
]);
|
|
79
|
+
}
|
|
80
|
+
async function runSweep(opts = {}) {
|
|
81
|
+
const policy = (0, policy_1.loadPolicy)();
|
|
82
|
+
const payout = (0, policy_1.getPayoutAddress)(policy);
|
|
83
|
+
const { account, walletClient } = (0, wallet_1.requireWallet)();
|
|
84
|
+
if (!payout) {
|
|
85
|
+
if (!opts.quiet)
|
|
86
|
+
ui.warn("No payout address configured. Run `apow wallet payout set <address>`.");
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
if (payout.toLowerCase() === account.address.toLowerCase()) {
|
|
90
|
+
throw new Error("Payout address must be different from the mining wallet.");
|
|
91
|
+
}
|
|
92
|
+
(0, context_1.setSignerContext)("sweep");
|
|
93
|
+
const minAgent = opts.minAgent ?? (0, viem_1.parseEther)(policy.sweep.thresholdAgent);
|
|
94
|
+
const agentBalance = (await wallet_1.publicClient.readContract({
|
|
95
|
+
address: config_1.config.agentCoinAddress,
|
|
96
|
+
abi: agentCoinAbi,
|
|
97
|
+
functionName: "balanceOf",
|
|
98
|
+
args: [account.address],
|
|
99
|
+
}));
|
|
100
|
+
let swept = false;
|
|
101
|
+
let agentLocked = false;
|
|
102
|
+
if (agentBalance >= minAgent) {
|
|
103
|
+
if (await agentTransfersUnlocked()) {
|
|
104
|
+
const hash = await walletClient.writeContract({
|
|
105
|
+
address: config_1.config.agentCoinAddress,
|
|
106
|
+
abi: ERC20_ABI,
|
|
107
|
+
account,
|
|
108
|
+
functionName: "transfer",
|
|
109
|
+
args: [payout, agentBalance],
|
|
110
|
+
});
|
|
111
|
+
await waitForReceipt(hash);
|
|
112
|
+
swept = true;
|
|
113
|
+
if (!opts.quiet) {
|
|
114
|
+
console.log(` ${ui.green("Swept")} ${(0, viem_1.formatEther)(agentBalance)} AGENT to ${payout.slice(0, 6)}...${payout.slice(-4)}`);
|
|
115
|
+
console.log(` Tx: ${ui.dim((0, explorer_1.txUrl)(hash))}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
agentLocked = true;
|
|
120
|
+
if (!opts.quiet) {
|
|
121
|
+
console.log(` ${ui.yellow("AGENT transfers are locked until the LP pool goes live.")}`);
|
|
122
|
+
console.log(` ${ui.dim(`${(0, viem_1.formatEther)(agentBalance)} AGENT stays in the mining wallet; sweeps activate automatically at pool-live.`)}`);
|
|
123
|
+
}
|
|
124
|
+
else if (!lockNoticeShown) {
|
|
125
|
+
lockNoticeShown = true;
|
|
126
|
+
ui.hint(`Auto-sweep armed: mined AGENT sweeps to payout once the LP pool goes live (transfers are locked until then).`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (opts.all) {
|
|
131
|
+
const eth = await wallet_1.publicClient.getBalance({ address: account.address });
|
|
132
|
+
if (eth > ETH_GAS_RESERVE * 4n) {
|
|
133
|
+
const value = eth - ETH_GAS_RESERVE * 4n;
|
|
134
|
+
const hash = await walletClient.sendTransaction({ account, to: payout, value });
|
|
135
|
+
await waitForReceipt(hash);
|
|
136
|
+
swept = true;
|
|
137
|
+
if (!opts.quiet)
|
|
138
|
+
console.log(` ${ui.green("Swept")} ${(0, viem_1.formatEther)(value)} ETH`);
|
|
139
|
+
}
|
|
140
|
+
const usdcBalance = (await wallet_1.publicClient.readContract({
|
|
141
|
+
address: constants_1.TOKENS.base.usdc,
|
|
142
|
+
abi: ERC20_ABI,
|
|
143
|
+
functionName: "balanceOf",
|
|
144
|
+
args: [account.address],
|
|
145
|
+
}));
|
|
146
|
+
if (usdcBalance > USDC_WORKING_BALANCE) {
|
|
147
|
+
const value = usdcBalance - USDC_WORKING_BALANCE;
|
|
148
|
+
const hash = await walletClient.writeContract({
|
|
149
|
+
address: constants_1.TOKENS.base.usdc,
|
|
150
|
+
abi: ERC20_ABI,
|
|
151
|
+
account,
|
|
152
|
+
functionName: "transfer",
|
|
153
|
+
args: [payout, value],
|
|
154
|
+
});
|
|
155
|
+
await waitForReceipt(hash);
|
|
156
|
+
swept = true;
|
|
157
|
+
if (!opts.quiet)
|
|
158
|
+
console.log(` ${ui.green("Swept")} ${(0, viem_1.formatUnits)(value, 6)} USDC`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (!swept && !agentLocked && !opts.quiet) {
|
|
162
|
+
console.log(` ${ui.dim(`Nothing to sweep. Unswept AGENT: ${(0, viem_1.formatEther)(agentBalance)}`)}`);
|
|
163
|
+
}
|
|
164
|
+
return swept;
|
|
165
|
+
}
|
|
166
|
+
async function maybeAutoSweep(mineCount) {
|
|
167
|
+
const policy = (0, policy_1.loadPolicy)();
|
|
168
|
+
if (!policy.payout || !policy.sweep.auto || mineCount < nextAutoSweepMine)
|
|
169
|
+
return;
|
|
170
|
+
try {
|
|
171
|
+
const swept = await runSweep({ quiet: true });
|
|
172
|
+
if (swept)
|
|
173
|
+
ui.ok("Auto-swept mined AGENT to payout address.");
|
|
174
|
+
autoSweepFailures = 0;
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
autoSweepFailures += 1;
|
|
178
|
+
nextAutoSweepMine = mineCount + 50;
|
|
179
|
+
ui.warn(`Auto-sweep skipped: ${(0, errors_1.errorText)(error)}`);
|
|
180
|
+
}
|
|
181
|
+
}
|
package/dist/ui.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.cyan = exports.yellow = exports.green = exports.red = exports.bold = exports.dim = void 0;
|
|
3
|
+
exports.baseBlue = exports.cyan = exports.yellow = exports.green = exports.red = exports.bold = exports.dim = void 0;
|
|
4
4
|
exports.isInteractiveSession = isInteractiveSession;
|
|
5
5
|
exports.banner = banner;
|
|
6
6
|
exports.table = table;
|
|
@@ -9,6 +9,7 @@ exports.stopAll = stopAll;
|
|
|
9
9
|
exports.confirm = confirm;
|
|
10
10
|
exports.prompt = prompt;
|
|
11
11
|
exports.promptSecret = promptSecret;
|
|
12
|
+
exports.readMaskedInput = readMaskedInput;
|
|
12
13
|
exports.ok = ok;
|
|
13
14
|
exports.fail = fail;
|
|
14
15
|
exports.hint = hint;
|
|
@@ -17,6 +18,7 @@ exports.warn = warn;
|
|
|
17
18
|
exports.info = info;
|
|
18
19
|
const promises_1 = require("node:readline/promises");
|
|
19
20
|
const node_process_1 = require("node:process");
|
|
21
|
+
const node_string_decoder_1 = require("node:string_decoder");
|
|
20
22
|
const isTTY = !!node_process_1.stdout.isTTY && !!node_process_1.stderr.isTTY;
|
|
21
23
|
const isInteractive = !!node_process_1.stdin.isTTY && isTTY;
|
|
22
24
|
const noColor = !!process.env.NO_COLOR || !isTTY;
|
|
@@ -28,23 +30,29 @@ function wrap(code, reset) {
|
|
|
28
30
|
return (s) => s;
|
|
29
31
|
return (s) => `\x1b[${code}m${s}\x1b[${reset}m`;
|
|
30
32
|
}
|
|
33
|
+
function wrapRgb(red, green, blue) {
|
|
34
|
+
if (noColor)
|
|
35
|
+
return (s) => s;
|
|
36
|
+
return (s) => `\x1b[38;2;${red};${green};${blue}m${s}\x1b[39m`;
|
|
37
|
+
}
|
|
31
38
|
exports.dim = wrap(2, 22);
|
|
32
39
|
exports.bold = wrap(1, 22);
|
|
33
|
-
exports.red =
|
|
34
|
-
exports.green =
|
|
35
|
-
exports.yellow =
|
|
36
|
-
exports.cyan =
|
|
40
|
+
exports.red = wrapRgb(252, 64, 31);
|
|
41
|
+
exports.green = wrapRgb(102, 200, 0);
|
|
42
|
+
exports.yellow = wrapRgb(255, 209, 47);
|
|
43
|
+
exports.cyan = wrapRgb(77, 159, 255);
|
|
44
|
+
exports.baseBlue = wrapRgb(0, 82, 255);
|
|
37
45
|
function banner(lines) {
|
|
38
46
|
if (!lines.length)
|
|
39
47
|
return;
|
|
40
48
|
const maxLen = Math.max(...lines.map((l) => l.length));
|
|
41
49
|
const pad = (s) => s + " ".repeat(maxLen - s.length);
|
|
42
|
-
const border = "
|
|
43
|
-
console.log(` ${(0, exports.
|
|
50
|
+
const border = `+${"-".repeat(maxLen + 2)}+`;
|
|
51
|
+
console.log(` ${(0, exports.baseBlue)(border)}`);
|
|
44
52
|
for (const line of lines) {
|
|
45
|
-
console.log(`
|
|
53
|
+
console.log(` ${(0, exports.baseBlue)("|")} ${(0, exports.bold)(pad(line))} ${(0, exports.baseBlue)("|")}`);
|
|
46
54
|
}
|
|
47
|
-
console.log(` ${(0, exports.
|
|
55
|
+
console.log(` ${(0, exports.baseBlue)(border)}`);
|
|
48
56
|
}
|
|
49
57
|
function table(rows) {
|
|
50
58
|
const maxKey = Math.max(...rows.map(([k]) => k.length));
|
|
@@ -118,12 +126,12 @@ function stopAll() {
|
|
|
118
126
|
}
|
|
119
127
|
async function confirm(question) {
|
|
120
128
|
if (!isInteractive)
|
|
121
|
-
return
|
|
129
|
+
return false;
|
|
122
130
|
const rl = (0, promises_1.createInterface)({ input: node_process_1.stdin, output: node_process_1.stderr });
|
|
123
|
-
const answer = await rl.question(` ${question} ${(0, exports.dim)("(
|
|
131
|
+
const answer = await rl.question(` ${question} ${(0, exports.dim)("(y/N)")} `);
|
|
124
132
|
rl.close();
|
|
125
133
|
const trimmed = answer.trim().toLowerCase();
|
|
126
|
-
return trimmed === "
|
|
134
|
+
return trimmed === "y" || trimmed === "yes";
|
|
127
135
|
}
|
|
128
136
|
async function prompt(question, defaultValue) {
|
|
129
137
|
if (!isInteractive) {
|
|
@@ -139,10 +147,126 @@ async function promptSecret(question) {
|
|
|
139
147
|
if (!isInteractive) {
|
|
140
148
|
return "";
|
|
141
149
|
}
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
150
|
+
return readMaskedInput(` ${question}: `);
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Read one secret value while rendering one asterisk per typed character.
|
|
154
|
+
* Exported for regression testing; interactive callers should use promptSecret().
|
|
155
|
+
*/
|
|
156
|
+
function readMaskedInput(promptText, input = node_process_1.stdin, output = node_process_1.stderr) {
|
|
157
|
+
output.write(promptText);
|
|
158
|
+
return new Promise((resolve, reject) => {
|
|
159
|
+
const decoder = new node_string_decoder_1.StringDecoder("utf8");
|
|
160
|
+
const characters = [];
|
|
161
|
+
const wasRaw = input.isRaw === true;
|
|
162
|
+
const wasFlowing = input.readableFlowing === true;
|
|
163
|
+
let escapeState = "none";
|
|
164
|
+
let settled = false;
|
|
165
|
+
const cleanup = () => {
|
|
166
|
+
input.removeListener("data", onData);
|
|
167
|
+
input.removeListener("end", onEnd);
|
|
168
|
+
input.removeListener("error", onError);
|
|
169
|
+
if (input.setRawMode) {
|
|
170
|
+
try {
|
|
171
|
+
input.setRawMode(wasRaw);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
// The stream may have closed while the prompt was active.
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (!wasFlowing) {
|
|
178
|
+
input.pause();
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
const finish = () => {
|
|
182
|
+
if (settled)
|
|
183
|
+
return;
|
|
184
|
+
settled = true;
|
|
185
|
+
cleanup();
|
|
186
|
+
output.write("\n");
|
|
187
|
+
resolve(characters.join("").trim());
|
|
188
|
+
};
|
|
189
|
+
const interrupt = () => {
|
|
190
|
+
if (settled)
|
|
191
|
+
return;
|
|
192
|
+
settled = true;
|
|
193
|
+
cleanup();
|
|
194
|
+
output.write("\n");
|
|
195
|
+
const error = Object.assign(new Error("Secret input interrupted."), { code: "SIGINT" });
|
|
196
|
+
reject(error);
|
|
197
|
+
process.kill(process.pid, "SIGINT");
|
|
198
|
+
};
|
|
199
|
+
const eraseCharacter = () => {
|
|
200
|
+
if (characters.length === 0)
|
|
201
|
+
return;
|
|
202
|
+
characters.pop();
|
|
203
|
+
output.write("\b \b");
|
|
204
|
+
};
|
|
205
|
+
const onData = (chunk) => {
|
|
206
|
+
const text = typeof chunk === "string" ? chunk : decoder.write(chunk);
|
|
207
|
+
for (const character of text) {
|
|
208
|
+
if (escapeState === "start") {
|
|
209
|
+
escapeState = character === "[" ? "csi" : character === "O" ? "ss3" : "none";
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (escapeState === "csi") {
|
|
213
|
+
const code = character.codePointAt(0) ?? 0;
|
|
214
|
+
if (code >= 0x40 && code <= 0x7e)
|
|
215
|
+
escapeState = "none";
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
if (escapeState === "ss3") {
|
|
219
|
+
escapeState = "none";
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
if (character === "\u001b") {
|
|
223
|
+
escapeState = "start";
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (character === "\r" || character === "\n") {
|
|
227
|
+
finish();
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
if (character === "\u0003") {
|
|
231
|
+
interrupt();
|
|
232
|
+
break;
|
|
233
|
+
}
|
|
234
|
+
if (character === "\u007f" || character === "\b") {
|
|
235
|
+
eraseCharacter();
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
if (character === "\u0015") {
|
|
239
|
+
while (characters.length > 0)
|
|
240
|
+
eraseCharacter();
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
const code = character.codePointAt(0) ?? 0;
|
|
244
|
+
if (code < 0x20 || code === 0x7f)
|
|
245
|
+
continue;
|
|
246
|
+
characters.push(character);
|
|
247
|
+
output.write("*");
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
const onEnd = () => finish();
|
|
251
|
+
const onError = (error) => {
|
|
252
|
+
if (settled)
|
|
253
|
+
return;
|
|
254
|
+
settled = true;
|
|
255
|
+
cleanup();
|
|
256
|
+
output.write("\n");
|
|
257
|
+
reject(error);
|
|
258
|
+
};
|
|
259
|
+
input.on("data", onData);
|
|
260
|
+
input.once("end", onEnd);
|
|
261
|
+
input.once("error", onError);
|
|
262
|
+
try {
|
|
263
|
+
input.setRawMode?.(true);
|
|
264
|
+
input.resume();
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
onError(error instanceof Error ? error : new Error(String(error)));
|
|
268
|
+
}
|
|
269
|
+
});
|
|
146
270
|
}
|
|
147
271
|
function ok(label) {
|
|
148
272
|
console.log(` ${(0, exports.green)("[OK]")} ${label}`);
|
|
@@ -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
|
@@ -1,48 +1,59 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.getKeystoreDir = getKeystoreDir;
|
|
4
|
-
exports.getPlaintextWalletPath = getPlaintextWalletPath;
|
|
5
4
|
exports.getKeystoreWalletPath = getKeystoreWalletPath;
|
|
6
|
-
exports.
|
|
5
|
+
exports.getGeneratedWalletsPath = getGeneratedWalletsPath;
|
|
6
|
+
exports.expandHomePath = expandHomePath;
|
|
7
|
+
exports.resolveKeystorePath = resolveKeystorePath;
|
|
7
8
|
exports.saveEncryptedKeystoreFile = saveEncryptedKeystoreFile;
|
|
8
|
-
exports.
|
|
9
|
+
exports.registerGeneratedWallet = registerGeneratedWallet;
|
|
10
|
+
exports.loadGeneratedWallets = loadGeneratedWallets;
|
|
11
|
+
exports.loadGeneratedWalletAddresses = loadGeneratedWalletAddresses;
|
|
12
|
+
exports.loadEncryptedKeystoreFile = loadEncryptedKeystoreFile;
|
|
9
13
|
const node_fs_1 = require("node:fs");
|
|
10
14
|
const node_os_1 = require("node:os");
|
|
11
15
|
const node_path_1 = require("node:path");
|
|
12
16
|
const ox_1 = require("ox");
|
|
17
|
+
const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
18
|
+
const GENERATED_WALLETS_VERSION = 1;
|
|
13
19
|
function ensureDir(path) {
|
|
14
20
|
if (!(0, node_fs_1.existsSync)(path)) {
|
|
15
|
-
(0, node_fs_1.mkdirSync)(path, { recursive: true });
|
|
21
|
+
(0, node_fs_1.mkdirSync)(path, { recursive: true, mode: 0o700 });
|
|
16
22
|
}
|
|
23
|
+
try {
|
|
24
|
+
(0, node_fs_1.chmodSync)(path, 0o700);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// Best-effort permissions hardening; some filesystems do not support chmod.
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function getDefaultApowDir() {
|
|
31
|
+
return (0, node_path_1.join)((0, node_os_1.homedir)(), ".apow");
|
|
17
32
|
}
|
|
18
|
-
function getKeystoreDir() {
|
|
19
|
-
const dir = (0, node_path_1.join)(
|
|
33
|
+
function getKeystoreDir(apowDir = getDefaultApowDir()) {
|
|
34
|
+
const dir = (0, node_path_1.join)(apowDir, "keystores");
|
|
20
35
|
ensureDir(dir);
|
|
21
36
|
return dir;
|
|
22
37
|
}
|
|
23
|
-
function
|
|
24
|
-
return (0, node_path_1.join)(
|
|
25
|
-
}
|
|
26
|
-
function
|
|
27
|
-
return (0, node_path_1.join)(
|
|
28
|
-
}
|
|
29
|
-
function
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
`Generated: ${new Date().toISOString()}`,
|
|
36
|
-
"",
|
|
37
|
-
"Import this key into MetaMask, Rabby, Phantom, or any EVM wallet.",
|
|
38
|
-
"Keep this file safe — anyone with the private key controls your funds.",
|
|
39
|
-
"",
|
|
40
|
-
].join("\n");
|
|
41
|
-
(0, node_fs_1.writeFileSync)(filepath, content, { encoding: "utf8", mode: 0o600 });
|
|
42
|
-
return filepath;
|
|
38
|
+
function getKeystoreWalletPath(address, apowDir = getDefaultApowDir()) {
|
|
39
|
+
return (0, node_path_1.join)(getKeystoreDir(apowDir), `wallet-${address}.json`);
|
|
40
|
+
}
|
|
41
|
+
function getGeneratedWalletsPath(apowDir = getDefaultApowDir()) {
|
|
42
|
+
return (0, node_path_1.join)(apowDir, "generated-wallets.json");
|
|
43
|
+
}
|
|
44
|
+
function expandHomePath(path) {
|
|
45
|
+
if (path === "~")
|
|
46
|
+
return (0, node_os_1.homedir)();
|
|
47
|
+
if (path.startsWith("~/"))
|
|
48
|
+
return (0, node_path_1.join)((0, node_os_1.homedir)(), path.slice(2));
|
|
49
|
+
return path;
|
|
43
50
|
}
|
|
44
|
-
|
|
45
|
-
const
|
|
51
|
+
function resolveKeystorePath(path) {
|
|
52
|
+
const expanded = expandHomePath(path);
|
|
53
|
+
return (0, node_path_1.isAbsolute)(expanded) ? expanded : (0, node_path_1.resolve)(process.cwd(), expanded);
|
|
54
|
+
}
|
|
55
|
+
async function saveEncryptedKeystoreFile(address, privateKey, password, apowDir = getDefaultApowDir()) {
|
|
56
|
+
const filepath = getKeystoreWalletPath(address, apowDir);
|
|
46
57
|
const [key, opts] = await ox_1.Keystore.scryptAsync({ password });
|
|
47
58
|
const keystore = ox_1.Keystore.encrypt(privateKey, key, opts);
|
|
48
59
|
const payload = {
|
|
@@ -50,9 +61,94 @@ async function saveEncryptedKeystoreFile(address, privateKey, password) {
|
|
|
50
61
|
address: address.slice(2).toLowerCase(),
|
|
51
62
|
};
|
|
52
63
|
(0, node_fs_1.writeFileSync)(filepath, JSON.stringify(payload, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
|
|
64
|
+
try {
|
|
65
|
+
(0, node_fs_1.chmodSync)(filepath, 0o600);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
// Best-effort permissions hardening.
|
|
69
|
+
}
|
|
53
70
|
return filepath;
|
|
54
71
|
}
|
|
55
|
-
function
|
|
56
|
-
|
|
57
|
-
|
|
72
|
+
function registerGeneratedWallet(address, keystorePath, apowDir = getDefaultApowDir()) {
|
|
73
|
+
if (!ADDRESS_RE.test(address)) {
|
|
74
|
+
throw new Error("Cannot register an invalid generated wallet address.");
|
|
75
|
+
}
|
|
76
|
+
const expectedKeystorePath = (0, node_path_1.resolve)(getKeystoreWalletPath(address, apowDir));
|
|
77
|
+
if ((0, node_path_1.resolve)(keystorePath) !== expectedKeystorePath || !(0, node_fs_1.existsSync)(expectedKeystorePath)) {
|
|
78
|
+
throw new Error("Generated wallet registration requires its local APoW encrypted keystore.");
|
|
79
|
+
}
|
|
80
|
+
const registryPath = getGeneratedWalletsPath(apowDir);
|
|
81
|
+
ensureDir(apowDir);
|
|
82
|
+
const existing = loadGeneratedWalletRegistry(apowDir);
|
|
83
|
+
const withoutDuplicate = existing.wallets.filter((wallet) => wallet.address.toLowerCase() !== address.toLowerCase());
|
|
84
|
+
const registry = {
|
|
85
|
+
version: GENERATED_WALLETS_VERSION,
|
|
86
|
+
wallets: [
|
|
87
|
+
...withoutDuplicate,
|
|
88
|
+
{
|
|
89
|
+
address,
|
|
90
|
+
keystorePath: expectedKeystorePath,
|
|
91
|
+
createdAt: new Date().toISOString(),
|
|
92
|
+
},
|
|
93
|
+
],
|
|
94
|
+
};
|
|
95
|
+
(0, node_fs_1.writeFileSync)(registryPath, JSON.stringify(registry, null, 2) + "\n", {
|
|
96
|
+
encoding: "utf8",
|
|
97
|
+
mode: 0o600,
|
|
98
|
+
});
|
|
99
|
+
try {
|
|
100
|
+
(0, node_fs_1.chmodSync)(registryPath, 0o600);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
// Best-effort permissions hardening.
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function loadGeneratedWallets(apowDir = getDefaultApowDir()) {
|
|
107
|
+
return loadGeneratedWalletRegistry(apowDir).wallets.flatMap((wallet) => {
|
|
108
|
+
if (!ADDRESS_RE.test(wallet.address))
|
|
109
|
+
return [];
|
|
110
|
+
const expectedKeystorePath = (0, node_path_1.resolve)(getKeystoreWalletPath(wallet.address, apowDir));
|
|
111
|
+
if ((0, node_path_1.resolve)(wallet.keystorePath) !== expectedKeystorePath || !(0, node_fs_1.existsSync)(expectedKeystorePath)) {
|
|
112
|
+
return [];
|
|
113
|
+
}
|
|
114
|
+
return [{
|
|
115
|
+
address: wallet.address,
|
|
116
|
+
keystorePath: expectedKeystorePath,
|
|
117
|
+
createdAt: wallet.createdAt,
|
|
118
|
+
}];
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
function loadGeneratedWalletAddresses(apowDir = getDefaultApowDir()) {
|
|
122
|
+
return loadGeneratedWallets(apowDir).map((wallet) => wallet.address);
|
|
123
|
+
}
|
|
124
|
+
function loadEncryptedKeystoreFile(path, password) {
|
|
125
|
+
const filepath = resolveKeystorePath(path);
|
|
126
|
+
const raw = (0, node_fs_1.readFileSync)(filepath, "utf8");
|
|
127
|
+
const keystore = JSON.parse(raw);
|
|
128
|
+
const key = ox_1.Keystore.toKey(keystore, { password });
|
|
129
|
+
const privateKey = ox_1.Keystore.decrypt(keystore, key);
|
|
130
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(privateKey)) {
|
|
131
|
+
throw new Error("Keystore decrypted, but did not contain a valid EVM private key.");
|
|
132
|
+
}
|
|
133
|
+
return privateKey;
|
|
134
|
+
}
|
|
135
|
+
function loadGeneratedWalletRegistry(apowDir = getDefaultApowDir()) {
|
|
136
|
+
try {
|
|
137
|
+
const raw = (0, node_fs_1.readFileSync)(getGeneratedWalletsPath(apowDir), "utf8");
|
|
138
|
+
const parsed = JSON.parse(raw);
|
|
139
|
+
if (parsed.version !== GENERATED_WALLETS_VERSION || !Array.isArray(parsed.wallets)) {
|
|
140
|
+
return { version: GENERATED_WALLETS_VERSION, wallets: [] };
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
version: GENERATED_WALLETS_VERSION,
|
|
144
|
+
wallets: parsed.wallets.filter((wallet) => (typeof wallet === "object"
|
|
145
|
+
&& wallet !== null
|
|
146
|
+
&& typeof wallet.address === "string"
|
|
147
|
+
&& typeof wallet.keystorePath === "string"
|
|
148
|
+
&& typeof wallet.createdAt === "string")),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return { version: GENERATED_WALLETS_VERSION, wallets: [] };
|
|
153
|
+
}
|
|
58
154
|
}
|