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.
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.renderBrandLogo = renderBrandLogo;
4
+ exports.renderStartWelcome = renderStartWelcome;
5
+ exports.showBrandIntro = showBrandIntro;
6
+ const node_process_1 = require("node:process");
7
+ const BASE_BLUE = [0, 82, 255];
8
+ const WHITE = [255, 255, 255];
9
+ /**
10
+ * Generated from the canonical 512x512 logo.png with:
11
+ * jp2a --colors --color-depth=24 --background=light --size=40x20 --chars='##'
12
+ *
13
+ * The circular edge was normalized after conversion to remove asymmetric
14
+ * transparency sampling at the bottom of the source PNG.
15
+ *
16
+ * # = Base-blue circle
17
+ * @ = white APoW mark
18
+ */
19
+ const FULL_LOGO = [
20
+ "############",
21
+ "######################",
22
+ "##########################",
23
+ "##############################",
24
+ "################@@################",
25
+ "################@@@@################",
26
+ "################@@@@@@################",
27
+ "###############@@@##@@@###############",
28
+ "###############@@@####@@@###############",
29
+ "###########@@@@@@@@@@@@@@@@@@###########",
30
+ "#############@@@########@@@#############",
31
+ "#########@@@@@@@@@@@@@@@@@@@@@@#########",
32
+ "##########@@@############@@@##########",
33
+ "#########@@@##############@@@#########",
34
+ "####################################",
35
+ "##################################",
36
+ "##############################",
37
+ "##########################",
38
+ "######################",
39
+ "############",
40
+ ];
41
+ const COMPACT_LOGO = [
42
+ "############",
43
+ "##################",
44
+ "########################",
45
+ "##########################",
46
+ "#############@@#############",
47
+ "#############@@@@#############",
48
+ "#############@@##@@#############",
49
+ "#########@@@@@@@@@@@@@@#########",
50
+ "##########@@@######@@@##########",
51
+ "#######@@@@@@@@@@@@@@@@@@#######",
52
+ "#######@@############@@#######",
53
+ "############################",
54
+ "##########################",
55
+ "########################",
56
+ "##################",
57
+ "############",
58
+ ];
59
+ const MICRO_LOGO = [
60
+ "##########",
61
+ "################",
62
+ "####################",
63
+ "##########@@##########",
64
+ "##########@##@##########",
65
+ "#######@@@@@@@@@@#######",
66
+ "########@@####@@########",
67
+ "######@@@@@@@@@@@@######",
68
+ "######################",
69
+ "####################",
70
+ "################",
71
+ "##########",
72
+ ];
73
+ function startWelcomeLines(columns) {
74
+ const startFlow = columns >= 47
75
+ ? [
76
+ "1 Choose Easy or Advanced Mode",
77
+ "2 Fund the displayed Base wallet when prompted",
78
+ "3 Rerun apow start to mint your rig and mine",
79
+ ]
80
+ : [
81
+ "1 Choose Easy or Advanced",
82
+ "2 Fund the Base wallet",
83
+ "3 Rerun apow start to mine",
84
+ ];
85
+ const docsLink = columns >= 27
86
+ ? "Docs: https://apow.io/docs/"
87
+ : "Docs: apow.io/docs";
88
+ const skillLink = columns >= 54
89
+ ? "Skill: https://clawhub.ai/agentoshi/skills/apow-mining"
90
+ : columns >= 46
91
+ ? "Skill: clawhub.ai/agentoshi/skills/apow-mining"
92
+ : "Skill: ClawHub agentoshi/apow-mining";
93
+ return [
94
+ "WELCOME TO THE APoW CLI",
95
+ "Agentic Proof of Work on Base",
96
+ "",
97
+ "START FLOW",
98
+ ...startFlow,
99
+ "",
100
+ docsLink,
101
+ skillLink,
102
+ ];
103
+ }
104
+ function ansi(text, rgb, enabled) {
105
+ if (!enabled || !text)
106
+ return text;
107
+ return `\x1b[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m${text}\x1b[39m`;
108
+ }
109
+ function renderMaskLine(line, color) {
110
+ if (!color)
111
+ return line;
112
+ return (line.match(/#+|@+| +/g) ?? [])
113
+ .map((run) => {
114
+ if (run[0] === "#")
115
+ return ansi(run, BASE_BLUE, true);
116
+ if (run[0] === "@")
117
+ return ansi(run, WHITE, true);
118
+ return run;
119
+ })
120
+ .join("");
121
+ }
122
+ function maskWidth(mask) {
123
+ return Math.max(...mask.map((line) => line.length));
124
+ }
125
+ function renderBrandLogo(options = {}) {
126
+ const columns = options.columns ?? 48;
127
+ const mask = columns >= 40 ? FULL_LOGO : columns >= 32 ? COMPACT_LOGO : MICRO_LOGO;
128
+ const width = maskWidth(mask);
129
+ const canvasWidth = Math.max(width, columns);
130
+ return mask.map((line) => {
131
+ const leftPadding = " ".repeat(Math.max(0, Math.floor((canvasWidth - line.length) / 2)));
132
+ return leftPadding + renderMaskLine(line, options.color === true);
133
+ });
134
+ }
135
+ function renderStartWelcome(options = {}) {
136
+ const columns = options.columns ?? 48;
137
+ const lines = startWelcomeLines(columns);
138
+ const width = Math.max(...lines.map((line) => line.length));
139
+ const leftPadding = " ".repeat(Math.max(0, Math.floor((columns - width) / 2)));
140
+ return lines.map((line, index) => {
141
+ if (!line)
142
+ return "";
143
+ if (index <= 1) {
144
+ const centered = " ".repeat(Math.max(0, Math.floor((columns - line.length) / 2))) + line;
145
+ return index === 0 ? ansi(centered, BASE_BLUE, options.color === true) : centered;
146
+ }
147
+ return leftPadding + line;
148
+ });
149
+ }
150
+ async function showBrandIntro(sequence, options = {}) {
151
+ const output = options.output ?? node_process_1.stdout;
152
+ const color = options.color
153
+ ?? (output.isTTY === true && !process.env.NO_COLOR && process.env.TERM !== "dumb");
154
+ const lines = renderBrandLogo({ color, columns: output.columns });
155
+ const sections = [lines.join("\n")];
156
+ if (sequence === "start") {
157
+ sections.push(renderStartWelcome({ color, columns: output.columns }).join("\n"));
158
+ }
159
+ output.write(`\n${sections.join("\n\n")}\n\n`);
160
+ }
@@ -1,39 +1,5 @@
1
1
  "use strict";
2
2
  // Solana balance utilities for deposit detection.
3
- // Uses dynamic import() for @solana/web3.js to avoid bloating startup.
4
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
- if (k2 === undefined) k2 = k;
6
- var desc = Object.getOwnPropertyDescriptor(m, k);
7
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
- desc = { enumerable: true, get: function() { return m[k]; } };
9
- }
10
- Object.defineProperty(o, k2, desc);
11
- }) : (function(o, m, k, k2) {
12
- if (k2 === undefined) k2 = k;
13
- o[k2] = m[k];
14
- }));
15
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
- Object.defineProperty(o, "default", { enumerable: true, value: v });
17
- }) : function(o, v) {
18
- o["default"] = v;
19
- });
20
- var __importStar = (this && this.__importStar) || (function () {
21
- var ownKeys = function(o) {
22
- ownKeys = Object.getOwnPropertyNames || function (o) {
23
- var ar = [];
24
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
25
- return ar;
26
- };
27
- return ownKeys(o);
28
- };
29
- return function (mod) {
30
- if (mod && mod.__esModule) return mod;
31
- var result = {};
32
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
33
- __setModuleDefault(result, mod);
34
- return result;
35
- };
36
- })();
37
3
  Object.defineProperty(exports, "__esModule", { value: true });
38
4
  exports.getSolanaRpcUrl = getSolanaRpcUrl;
39
5
  exports.getAddressBalance = getAddressBalance;
@@ -42,22 +8,38 @@ const DEFAULT_SOLANA_RPC = "https://api.mainnet-beta.solana.com";
42
8
  function getSolanaRpcUrl() {
43
9
  return process.env.SOLANA_RPC_URL || DEFAULT_SOLANA_RPC;
44
10
  }
11
+ async function solanaRpc(method, params) {
12
+ const response = await fetch(getSolanaRpcUrl(), {
13
+ method: "POST",
14
+ headers: { "Content-Type": "application/json" },
15
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
16
+ });
17
+ if (!response.ok) {
18
+ throw new Error(`Solana RPC ${method} failed (${response.status})`);
19
+ }
20
+ const body = (await response.json());
21
+ if (body.error || body.result === undefined) {
22
+ const message = body.error?.message || "missing result";
23
+ throw new Error(`Solana RPC ${method} failed: ${message}`);
24
+ }
25
+ return body.result;
26
+ }
45
27
  /** Get SOL balance for any address (used to detect deposits). */
46
28
  async function getAddressBalance(address) {
47
- const { Connection, PublicKey } = await Promise.resolve().then(() => __importStar(require("@solana/web3.js")));
48
- const connection = new Connection(getSolanaRpcUrl(), "confirmed");
49
- const lamports = await connection.getBalance(new PublicKey(address));
50
- return lamports / 1e9;
29
+ const result = await solanaRpc("getBalance", [
30
+ address,
31
+ { commitment: "confirmed" },
32
+ ]);
33
+ return result.value / 1e9;
51
34
  }
52
35
  /** Get SPL token balance (e.g., USDC) for a Solana public key. Returns UI amount (not raw). */
53
36
  async function getSplTokenBalance(publicKeyBase58, mintAddress) {
54
- const { Connection, PublicKey } = await Promise.resolve().then(() => __importStar(require("@solana/web3.js")));
55
- const connection = new Connection(getSolanaRpcUrl(), "confirmed");
56
- const owner = new PublicKey(publicKeyBase58);
57
- const mint = new PublicKey(mintAddress);
58
- const accounts = await connection.getParsedTokenAccountsByOwner(owner, { mint });
37
+ const accounts = await solanaRpc("getTokenAccountsByOwner", [
38
+ publicKeyBase58,
39
+ { mint: mintAddress },
40
+ { encoding: "jsonParsed", commitment: "confirmed" },
41
+ ]);
59
42
  if (accounts.value.length === 0)
60
43
  return 0;
61
- const parsed = accounts.value[0].account.data.parsed;
62
- return parsed?.info?.tokenAmount?.uiAmount ?? 0;
44
+ return accounts.value[0].account.data.parsed?.info?.tokenAmount?.uiAmount ?? 0;
63
45
  }
@@ -7,6 +7,7 @@ exports.SQUID_ROUTES = void 0;
7
7
  exports.getDepositAddress = getDepositAddress;
8
8
  exports.pollBridgeStatus = pollBridgeStatus;
9
9
  const constants_1 = require("./constants");
10
+ const viem_1 = require("viem");
10
11
  const SQUID_API = "https://v2.api.squidrouter.com/v2";
11
12
  exports.SQUID_ROUTES = {
12
13
  sol_to_eth: {
@@ -17,13 +18,13 @@ exports.SQUID_ROUTES = {
17
18
  srcDecimals: 9,
18
19
  dstDecimals: 18,
19
20
  },
20
- sol_usdc_to_base_usdc: {
21
+ sol_usdc_to_base_eth: {
21
22
  fromChain: constants_1.CHAIN_IDS.solana,
22
23
  fromToken: constants_1.TOKENS.solana.usdc,
23
24
  toChain: constants_1.CHAIN_IDS.base,
24
- toToken: constants_1.TOKENS.base.usdc,
25
+ toToken: constants_1.TOKENS.base.nativeSquid,
25
26
  srcDecimals: 6,
26
- dstDecimals: 6,
27
+ dstDecimals: 18,
27
28
  },
28
29
  eth_to_base_eth: {
29
30
  fromChain: constants_1.CHAIN_IDS.ethereum,
@@ -46,9 +47,11 @@ function getIntegratorId() {
46
47
  * Get a Squid deposit address for bridging to Base.
47
48
  * User sends tokens to this address from any wallet; Squid handles the rest.
48
49
  */
49
- async function getDepositAddress(baseAddress, amount, route = exports.SQUID_ROUTES.sol_to_eth) {
50
+ async function getDepositAddress(baseAddress, amount, route = exports.SQUID_ROUTES.sol_to_eth, minimumEth = 0n) {
50
51
  const integratorId = getIntegratorId();
51
- const rawAmount = Math.floor(amount * 10 ** route.srcDecimals).toString();
52
+ if (!/^0x[0-9a-fA-F]{40}$/.test(baseAddress) || !Number.isFinite(amount) || amount <= 0)
53
+ throw new Error("Invalid bridge recipient or amount");
54
+ const rawAmount = (0, viem_1.parseUnits)(amount.toFixed(route.srcDecimals), route.srcDecimals).toString();
52
55
  // Step 1: Get route quote
53
56
  const routeResponse = await fetch(`${SQUID_API}/route`, {
54
57
  method: "POST",
@@ -56,6 +59,7 @@ async function getDepositAddress(baseAddress, amount, route = exports.SQUID_ROUT
56
59
  "Content-Type": "application/json",
57
60
  "x-integrator-id": integratorId,
58
61
  },
62
+ signal: AbortSignal.timeout(15_000),
59
63
  body: JSON.stringify({
60
64
  fromChain: route.fromChain,
61
65
  toChain: route.toChain,
@@ -64,6 +68,7 @@ async function getDepositAddress(baseAddress, amount, route = exports.SQUID_ROUT
64
68
  fromAmount: rawAmount,
65
69
  toAddress: baseAddress,
66
70
  quoteOnly: false,
71
+ slippage: 2,
67
72
  enableBoost: true,
68
73
  prefer: ["CHAINFLIP_DEPOSIT_ADDRESS"],
69
74
  }),
@@ -83,15 +88,20 @@ async function getDepositAddress(baseAddress, amount, route = exports.SQUID_ROUT
83
88
  if (tx && !routeData.route?.params?.prefer?.includes("CHAINFLIP_DEPOSIT_ADDRESS")) {
84
89
  throw new Error("DEPOSIT_ADDRESS_UNAVAILABLE: Squid returned a contract-call route instead of a deposit address for this chain.\n" +
85
90
  "This means the bridge requires an on-chain transaction from the source chain.\n" +
86
- "Use an alternative: bridge.base.org, send ETH on Base directly, or bridge from Solana.");
91
+ "Send ETH on Base directly instead. No deposit address was issued.");
87
92
  }
88
- // Step 2: Request deposit address from route
93
+ const minReceive = routeData.route?.estimate?.toAmountMin;
94
+ if (typeof minReceive !== "string" || !/^\d+$/.test(minReceive) || BigInt(minReceive) < minimumEth) {
95
+ throw new Error("The bridge quote does not guarantee enough Base ETH after fees and slippage. Increase the ETH target with --amount; no deposit address was issued.");
96
+ }
97
+ // Step 2: Request deposit address from a validated route
89
98
  const depositResponse = await fetch(`${SQUID_API}/deposit-address`, {
90
99
  method: "POST",
91
100
  headers: {
92
101
  "Content-Type": "application/json",
93
102
  "x-integrator-id": integratorId,
94
103
  },
104
+ signal: AbortSignal.timeout(15_000),
95
105
  body: JSON.stringify({
96
106
  routeData: routeData.route,
97
107
  }),
@@ -101,6 +111,15 @@ async function getDepositAddress(baseAddress, amount, route = exports.SQUID_ROUT
101
111
  throw new Error(`Squid deposit-address API error (${depositResponse.status}): ${body}`);
102
112
  }
103
113
  const depositData = (await depositResponse.json());
114
+ const validAddress = typeof depositData.depositAddress === "string" && (route.fromChain === "solana"
115
+ ? /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(depositData.depositAddress)
116
+ : /^0x[0-9a-fA-F]{40}$/.test(depositData.depositAddress));
117
+ if (!validAddress
118
+ || !(depositData.requestId || routeData.requestId))
119
+ throw new Error("Bridge returned an invalid deposit address or request ID");
120
+ if (depositData.expiresAt && (!Number.isFinite(Date.parse(depositData.expiresAt)) || Date.parse(depositData.expiresAt) <= Date.now())) {
121
+ throw new Error("Bridge returned an expired or invalid deposit-address expiry");
122
+ }
104
123
  const toAmount = routeData.route?.estimate?.toAmount;
105
124
  const estimatedReceive = toAmount
106
125
  ? (Number(toAmount) / 10 ** route.dstDecimals).toFixed(route.dstDecimals === 6 ? 2 : 6)
@@ -109,6 +128,7 @@ async function getDepositAddress(baseAddress, amount, route = exports.SQUID_ROUT
109
128
  depositAddress: depositData.depositAddress,
110
129
  requestId: depositData.requestId || routeData.requestId,
111
130
  expectedReceive: estimatedReceive,
131
+ minimumReceive: (0, viem_1.formatEther)(BigInt(minReceive)),
112
132
  expiresAt: depositData.expiresAt,
113
133
  };
114
134
  }
@@ -127,10 +147,11 @@ async function pollBridgeStatus(requestId, dstDecimals = 18, onUpdate, timeoutMs
127
147
  });
128
148
  const response = await fetch(`${SQUID_API}/status?${params}`, {
129
149
  headers: { "x-integrator-id": integratorId },
150
+ signal: AbortSignal.timeout(15_000),
130
151
  });
131
152
  if (response.ok) {
132
153
  const data = (await response.json());
133
- const status = data.squidTransactionStatus || data.status || "unknown";
154
+ const status = String(data.squidTransactionStatus || data.status || "unknown").toLowerCase();
134
155
  if (onUpdate)
135
156
  onUpdate(status);
136
157
  if (status === "success" ||
@@ -2,16 +2,41 @@
2
2
  // Uniswap V3 SwapRouter02 on Base — ETH↔USDC swaps.
3
3
  // No new npm deps — uses viem's built-in ABI encoding.
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.quoteUsdcForEth = exports.quoteEthForUsdc = void 0;
6
+ exports.quoteEthSwapFees = quoteEthSwapFees;
5
7
  exports.getUsdcBalance = getUsdcBalance;
6
8
  exports.swapEthToUsdc = swapEthToUsdc;
7
9
  exports.swapUsdcToEth = swapUsdcToEth;
8
10
  const viem_1 = require("viem");
11
+ const op_stack_1 = require("viem/op-stack");
9
12
  const constants_1 = require("./constants");
10
13
  const wallet_1 = require("../wallet");
11
14
  const SWAP_ROUTER = "0x2626664c2603336E57B271c5C0b26F421741e481";
12
15
  const WETH = constants_1.TOKENS.base.weth;
13
16
  const USDC = constants_1.TOKENS.base.usdc;
14
17
  const FEE_TIER = 500; // 0.05% pool (highest TVL)
18
+ /** Read-only QuoterV2 simulation. Include a 2% input buffer, rounded up. */
19
+ async function quoteForExactOutput(tokenIn, tokenOut, amount) {
20
+ const { publicClient } = (0, wallet_1.getFundingClients)();
21
+ const { result } = await publicClient.simulateContract({
22
+ address: "0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",
23
+ abi: [{ name: "quoteExactOutputSingle", type: "function", stateMutability: "nonpayable", inputs: [{
24
+ name: "params", type: "tuple", components: [
25
+ { name: "tokenIn", type: "address" }, { name: "tokenOut", type: "address" },
26
+ { name: "amount", type: "uint256" }, { name: "fee", type: "uint24" },
27
+ { name: "sqrtPriceLimitX96", type: "uint160" },
28
+ ],
29
+ }], outputs: [{ name: "amountIn", type: "uint256" }, { name: "sqrtPriceX96After", type: "uint160" },
30
+ { name: "initializedTicksCrossed", type: "uint32" }, { name: "gasEstimate", type: "uint256" }] }],
31
+ functionName: "quoteExactOutputSingle",
32
+ args: [{ tokenIn, tokenOut, amount, fee: FEE_TIER, sqrtPriceLimitX96: 0n }],
33
+ });
34
+ return (result[0] * BigInt(10000 + constants_1.SLIPPAGE_BPS) + 9999n) / 10000n;
35
+ }
36
+ const quoteEthForUsdc = (usdcOut) => quoteForExactOutput(WETH, USDC, usdcOut);
37
+ exports.quoteEthForUsdc = quoteEthForUsdc;
38
+ const quoteUsdcForEth = (ethOut) => quoteForExactOutput(USDC, WETH, ethOut);
39
+ exports.quoteUsdcForEth = quoteUsdcForEth;
15
40
  const erc20Abi = [
16
41
  {
17
42
  type: "function",
@@ -84,6 +109,27 @@ const swapRouterAbi = [
84
109
  outputs: [],
85
110
  },
86
111
  ];
112
+ /** Quote all Base fee components without requiring a funded sender. */
113
+ async function quoteEthSwapFees(ethAmount, minUsdcOut) {
114
+ const { publicClient, account } = (0, wallet_1.getFundingClients)();
115
+ if (!account)
116
+ throw new Error("Unlock the same wallet before quoting swap fees");
117
+ const gas = 600000n; // Explicit transaction ceiling, also used at signing.
118
+ const data = (0, viem_1.concat)([(0, viem_1.encodeFunctionData)({ abi: swapRouterAbi, functionName: "exactInputSingle", args: [{
119
+ tokenIn: WETH, tokenOut: USDC, fee: FEE_TIER, recipient: account.address,
120
+ amountIn: ethAmount, amountOutMinimum: minUsdcOut, sqrtPriceLimitX96: 0n,
121
+ }] }), wallet_1.DATA_SUFFIX]);
122
+ const [fees, l1Fee, scalar, constant] = await Promise.all([
123
+ publicClient.estimateFeesPerGas(),
124
+ (0, op_stack_1.estimateL1Fee)(publicClient, { account: account.address, to: SWAP_ROUTER, data, value: ethAmount }),
125
+ publicClient.readContract({ address: "0x4200000000000000000000000000000000000015",
126
+ abi: [{ name: "operatorFeeScalar", type: "function", stateMutability: "view", inputs: [], outputs: [{ type: "uint32" }] }], functionName: "operatorFeeScalar" }),
127
+ publicClient.readContract({ address: "0x4200000000000000000000000000000000000015",
128
+ abi: [{ name: "operatorFeeConstant", type: "function", stateMutability: "view", inputs: [], outputs: [{ type: "uint64" }] }], functionName: "operatorFeeConstant" }),
129
+ ]);
130
+ const operatorFee = gas * BigInt(scalar) / 1000000n + BigInt(constant);
131
+ return { gas, ...fees, feeReserve: gas * fees.maxFeePerGas + 2n * (l1Fee + operatorFee) };
132
+ }
87
133
  /** Get USDC balance for an address on Base. */
88
134
  async function getUsdcBalance(address) {
89
135
  const { publicClient } = (0, wallet_1.getFundingClients)();
@@ -98,7 +144,7 @@ async function getUsdcBalance(address) {
98
144
  * Swap ETH → USDC via Uniswap V3 on Base.
99
145
  * Sends ETH as msg.value; router auto-wraps to WETH.
100
146
  */
101
- async function swapEthToUsdc(ethAmount, minUsdcOut) {
147
+ async function swapEthToUsdc(ethAmount, minUsdcOut, fees) {
102
148
  const walletContext = (0, wallet_1.requireWallet)();
103
149
  const { publicClient, walletClient, account } = (0, wallet_1.getFundingClients)();
104
150
  const swapWalletClient = walletClient ?? walletContext.walletClient;
@@ -119,6 +165,7 @@ async function swapEthToUsdc(ethAmount, minUsdcOut) {
119
165
  },
120
166
  ],
121
167
  value: ethAmount,
168
+ ...(fees ? { gas: fees.gas, maxFeePerGas: fees.maxFeePerGas, maxPriorityFeePerGas: fees.maxPriorityFeePerGas } : {}),
122
169
  });
123
170
  const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
124
171
  if (receipt.status === "reverted") {
package/dist/config.js CHANGED
@@ -5,17 +5,21 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.config = void 0;
7
7
  exports.resolveDefaultModel = resolveDefaultModel;
8
+ exports.resolveKeystorePassword = resolveKeystorePassword;
8
9
  exports.reloadConfig = reloadConfig;
9
10
  exports.requirePrivateKey = requirePrivateKey;
10
11
  exports.requireLlmApiKey = requireLlmApiKey;
11
12
  exports.isExpensiveModel = isExpensiveModel;
12
13
  exports.writeEnvFile = writeEnvFile;
13
14
  const dotenv_1 = require("dotenv");
15
+ const node_child_process_1 = require("node:child_process");
14
16
  const node_fs_1 = require("node:fs");
15
17
  const promises_1 = require("node:fs/promises");
16
18
  const node_os_1 = __importDefault(require("node:os"));
17
19
  const node_path_1 = require("node:path");
18
20
  const chains_1 = require("viem/chains");
21
+ const session_1 = require("./signer/session");
22
+ const wallet_store_1 = require("./wallet-store");
19
23
  (0, dotenv_1.config)({ quiet: true });
20
24
  const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
21
25
  const DEFAULT_OLLAMA_URL = "http://127.0.0.1:11434";
@@ -41,8 +45,9 @@ function resolveDefaultModel(provider) {
41
45
  case "anthropic": return "claude-sonnet-4-5-20250929";
42
46
  case "deepseek": return "deepseek-chat";
43
47
  case "qwen": return "qwen-plus";
44
- case "claude-code":
45
- case "codex": return "default";
48
+ case "ollama": return "llama3.1";
49
+ case "claude-code": return "haiku";
50
+ case "codex": return "gpt-5.6-luna";
46
51
  default: return "gpt-4o-mini";
47
52
  }
48
53
  }
@@ -58,7 +63,7 @@ function resolveChainName() {
58
63
  return DEFAULT_CHAIN_NAME;
59
64
  }
60
65
  function parsePrivateKey(value) {
61
- if (!value) {
66
+ if (!value?.trim()) {
62
67
  return undefined;
63
68
  }
64
69
  if (!/^0x[0-9a-fA-F]{64}$/.test(value)) {
@@ -66,6 +71,73 @@ function parsePrivateKey(value) {
66
71
  }
67
72
  return value;
68
73
  }
74
+ function resolveKeystorePassword() {
75
+ const sessionPassword = (0, session_1.getSessionPassword)();
76
+ if (sessionPassword)
77
+ return sessionPassword;
78
+ const envPassword = process.env.KEYSTORE_PASSWORD?.trim()
79
+ || process.env.APOW_KEYSTORE_PASSWORD?.trim();
80
+ if (envPassword)
81
+ return envPassword;
82
+ const command = process.env.KEYSTORE_PASSWORD_CMD?.trim()
83
+ || process.env.APOW_KEYSTORE_PASSWORD_CMD?.trim();
84
+ if (command) {
85
+ const result = (0, node_child_process_1.spawnSync)(command, {
86
+ shell: true,
87
+ encoding: "utf8",
88
+ timeout: 10_000,
89
+ stdio: ["ignore", "pipe", "ignore"],
90
+ });
91
+ if (result.status === 0 && result.stdout.trim()) {
92
+ return result.stdout.trim();
93
+ }
94
+ }
95
+ return process.env.KEYSTORE_PASSWORD?.trim()
96
+ || process.env.APOW_KEYSTORE_PASSWORD?.trim()
97
+ || "";
98
+ }
99
+ function getConfiguredKeystorePath() {
100
+ const value = process.env.KEYSTORE_PATH
101
+ || process.env.WALLET_KEYSTORE_PATH
102
+ || process.env.APOW_KEYSTORE_PATH;
103
+ if (!value?.trim()) {
104
+ return undefined;
105
+ }
106
+ return (0, wallet_store_1.resolveKeystorePath)(value.trim());
107
+ }
108
+ function resolveWalletConfig() {
109
+ const legacyPrivateKey = parsePrivateKey(process.env.PRIVATE_KEY);
110
+ const keystorePath = getConfiguredKeystorePath();
111
+ if (legacyPrivateKey) {
112
+ return {
113
+ privateKey: legacyPrivateKey,
114
+ keystorePath,
115
+ walletSource: "private-key",
116
+ };
117
+ }
118
+ if (!keystorePath) {
119
+ return { walletSource: "none" };
120
+ }
121
+ const password = resolveKeystorePassword();
122
+ if (!password) {
123
+ return {
124
+ keystorePath,
125
+ walletSource: "keystore",
126
+ walletLoadError: "Encrypted keystore is configured but locked. Set KEYSTORE_PASSWORD in your shell or run an interactive command to unlock it.",
127
+ };
128
+ }
129
+ try {
130
+ return {
131
+ privateKey: (0, wallet_store_1.loadEncryptedKeystoreFile)(keystorePath, password),
132
+ keystorePath,
133
+ walletSource: "keystore",
134
+ };
135
+ }
136
+ catch (error) {
137
+ const message = error instanceof Error ? error.message : String(error);
138
+ throw new Error(`Could not unlock KEYSTORE_PATH (${keystorePath}): ${message}`);
139
+ }
140
+ }
69
141
  function parseAddress(envKey, fallback) {
70
142
  const value = process.env[envKey];
71
143
  if (value && /^0x[0-9a-fA-F]{40}$/.test(value)) {
@@ -105,12 +177,16 @@ function buildConfig() {
105
177
  const chainName = resolveChainName();
106
178
  const useX402 = process.env.USE_X402 === "true";
107
179
  const resolvedProvider = normalizeProvider(process.env.LLM_PROVIDER, useX402);
180
+ const walletConfig = resolveWalletConfig();
108
181
  const useX402Grind = process.env.USE_X402_GRIND !== undefined
109
182
  ? process.env.USE_X402_GRIND === "true"
110
183
  : useX402;
111
184
  const allowLocalFallbackWithX402 = process.env.ALLOW_LOCAL_FALLBACK_WITH_X402 === "true";
112
185
  return {
113
- privateKey: parsePrivateKey(process.env.PRIVATE_KEY),
186
+ privateKey: walletConfig.privateKey,
187
+ keystorePath: walletConfig.keystorePath,
188
+ walletSource: walletConfig.walletSource,
189
+ walletLoadError: walletConfig.walletLoadError,
114
190
  rpcUrl: process.env.RPC_URL ?? "",
115
191
  useX402,
116
192
  llmProvider: resolvedProvider,
@@ -143,7 +219,7 @@ function reloadConfig() {
143
219
  }
144
220
  function requirePrivateKey() {
145
221
  if (!exports.config.privateKey) {
146
- throw new Error("PRIVATE_KEY is required for minting and mining commands.");
222
+ throw new Error("An unlocked wallet signer is required. Configure KEYSTORE_PATH and unlock it with KEYSTORE_PASSWORD.");
147
223
  }
148
224
  return exports.config.privateKey;
149
225
  }
@@ -165,6 +241,14 @@ function isExpensiveModel(model) {
165
241
  return EXPENSIVE_MODELS.some((e) => m.startsWith(e));
166
242
  }
167
243
  async function writeEnvFile(values) {
244
+ for (const [key, value] of Object.entries(values)) {
245
+ if (/KEYSTORE_PASSWORD/i.test(key)) {
246
+ throw new Error(`${key} must not be written to .env. Use KEYSTORE_PASSWORD_CMD or a shell secret manager.`);
247
+ }
248
+ if (key === "PRIVATE_KEY" && value.trim()) {
249
+ throw new Error("PRIVATE_KEY must not be written to .env. Use an encrypted keystore.");
250
+ }
251
+ }
168
252
  const envPath = (0, node_path_1.join)(process.cwd(), ".env");
169
253
  const preserved = [];
170
254
  if ((0, node_fs_1.existsSync)(envPath)) {
@@ -173,6 +257,7 @@ async function writeEnvFile(values) {
173
257
  for (const line of existingContent.split(/\r?\n/)) {
174
258
  const trimmed = line.trim();
175
259
  if (!trimmed || trimmed.startsWith("#")) {
260
+ preserved.push(line);
176
261
  continue;
177
262
  }
178
263
  const eq = line.indexOf("=");