apow-cli 0.12.0 → 0.12.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +3 -1
- package/README.md +39 -30
- package/dist/base-funding.js +98 -0
- package/dist/bridge/squid.js +29 -8
- package/dist/bridge/uniswap.js +48 -1
- package/dist/errors.js +5 -1
- package/dist/fund.js +91 -506
- package/dist/funding-plan.js +29 -0
- package/dist/gateway.js +85 -0
- package/dist/grind-credits.js +119 -0
- package/dist/grinder-http.js +97 -10
- package/dist/grinder.js +10 -0
- package/dist/index.js +101 -60
- package/dist/miner.js +78 -14
- package/dist/mint.js +15 -0
- package/dist/policy/decode.js +50 -2
- package/dist/policy/policy.js +20 -1
- package/dist/preflight.js +25 -19
- package/dist/secure-env.js +8 -1
- package/dist/signer/guarded-account.js +5 -0
- package/dist/wallet-recovery.js +52 -0
- package/dist/wallet-store.js +40 -5
- package/dist/wallet.js +10 -8
- package/dist/x402.js +55 -15
- package/package.json +6 -5
- package/skill.md +51 -65
package/dist/fund.js
CHANGED
|
@@ -1,14 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
// Fund command — unified funding for mining on Base.
|
|
3
|
-
// Accepts deposits from Solana/Ethereum (via Squid Router bridge) or Base (direct send),
|
|
4
|
-
// auto-splits into ETH (gas) + USDC (x402 RPC).
|
|
5
|
-
//
|
|
6
|
-
// Deposit types:
|
|
7
|
-
// 1. Solana SOL → bridge → ETH on Base → swap portion to USDC
|
|
8
|
-
// 2. Solana USDC → bridge → USDC on Base → swap portion to ETH
|
|
9
|
-
// 3. Ethereum ETH → bridge → ETH on Base → swap portion to USDC
|
|
10
|
-
// 4. Base ETH → (already there) → swap portion to USDC
|
|
11
|
-
// 5. Base USDC → (already there) → swap portion to ETH
|
|
12
2
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
13
3
|
if (k2 === undefined) k2 = k;
|
|
14
4
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
@@ -45,522 +35,117 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
45
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
46
36
|
exports.runFundFlow = runFundFlow;
|
|
47
37
|
const viem_1 = require("viem");
|
|
48
|
-
const
|
|
38
|
+
const wallet_1 = require("./wallet");
|
|
39
|
+
const detect_1 = require("./detect");
|
|
40
|
+
const base_funding_1 = require("./base-funding");
|
|
49
41
|
const squid_1 = require("./bridge/squid");
|
|
50
42
|
const uniswap_1 = require("./bridge/uniswap");
|
|
51
|
-
const wallet_1 = require("./wallet");
|
|
52
43
|
const ui = __importStar(require("./ui"));
|
|
53
|
-
function
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
ui.hint("apow fund --chain base --token eth");
|
|
58
|
-
ui.hint("apow fund --chain base --token usdc");
|
|
59
|
-
ui.hint("apow fund --chain solana --token sol");
|
|
60
|
-
ui.hint("apow fund --chain solana --token usdc");
|
|
61
|
-
ui.hint("apow fund --chain ethereum");
|
|
62
|
-
console.log("");
|
|
63
|
-
}
|
|
64
|
-
async function fetchPrices() {
|
|
65
|
-
const res = await fetch("https://api.coingecko.com/api/v3/simple/price?ids=solana,ethereum&vs_currencies=usd");
|
|
66
|
-
if (!res.ok)
|
|
67
|
-
throw new Error("Failed to fetch prices from CoinGecko");
|
|
68
|
-
const data = (await res.json());
|
|
69
|
-
const ethUsd = data.ethereum.usd;
|
|
70
|
-
const solUsd = data.solana.usd;
|
|
71
|
-
return { solPerEth: ethUsd / solUsd, ethPriceUsd: ethUsd, solPriceUsd: solUsd };
|
|
44
|
+
async function needsMint() {
|
|
45
|
+
if (!wallet_1.account)
|
|
46
|
+
throw new Error("Unlock your existing mining wallet before funding");
|
|
47
|
+
return (await (0, detect_1.detectMinersWithClient)((0, wallet_1.getFundingClients)().publicClient, wallet_1.account.address)).length === 0;
|
|
72
48
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
49
|
+
function handoff(address, amount) {
|
|
50
|
+
ui.hint(`Send at least ${(0, viem_1.formatEther)(amount)} ETH on Base to ${address}.`);
|
|
51
|
+
ui.hint("The quote includes the live rig price, ETH reserve, swap gas, and USDC service budget. You only send ETH.");
|
|
52
|
+
ui.hint("After deposit, rerun apow start --easy to convert and resume with the same wallet.");
|
|
76
53
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
try {
|
|
82
|
-
const mod = await Promise.resolve().then(() => __importStar(require("qrcode-terminal")));
|
|
83
|
-
const qrcode = mod.default || mod;
|
|
84
|
-
await new Promise((resolve) => {
|
|
85
|
-
qrcode.generate(text, { small: true }, (qr) => {
|
|
86
|
-
for (const line of qr.split("\n")) {
|
|
87
|
-
if (line)
|
|
88
|
-
console.log(` ${line}`);
|
|
89
|
-
}
|
|
90
|
-
resolve();
|
|
91
|
-
});
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
catch {
|
|
95
|
-
// QR is nice-to-have, not critical
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
// ---------------------------------------------------------------------------
|
|
99
|
-
// Auto-split: ensure both ETH and USDC minimums are met
|
|
100
|
-
// ---------------------------------------------------------------------------
|
|
101
|
-
async function autoSplit(depositedAsset, prices, noSwap) {
|
|
102
|
-
if (noSwap)
|
|
103
|
-
return;
|
|
104
|
-
if (!wallet_1.account)
|
|
105
|
-
return;
|
|
106
|
-
const ethBal = Number((0, viem_1.formatEther)(await (0, wallet_1.getEthBalance)()));
|
|
107
|
-
const usdcBal = Number((0, viem_1.formatUnits)(await (0, uniswap_1.getUsdcBalance)(wallet_1.account.address), 6));
|
|
108
|
-
// Already good
|
|
109
|
-
if (ethBal >= constants_1.MIN_ETH && usdcBal >= constants_1.MIN_USDC) {
|
|
54
|
+
async function runBaseFund(mint, allowSwap) {
|
|
55
|
+
let plan = await (0, base_funding_1.prepareBaseFunding)(mint, allowSwap);
|
|
56
|
+
if (plan.ready) {
|
|
57
|
+
ui.ok(`Funding verified: ${(0, viem_1.formatEther)(plan.balances.eth)} ETH and ${(0, viem_1.formatUnits)(plan.balances.usdc, 6)} USDC.`);
|
|
110
58
|
return;
|
|
111
59
|
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
const minTotalUsd = constants_1.MIN_ETH * prices.ethPriceUsd + constants_1.MIN_USDC;
|
|
115
|
-
if (totalUsd < minTotalUsd * 0.5) {
|
|
116
|
-
ui.warn("Balance too low for auto-split. Fund more to cover both ETH (gas) and USDC (x402 RPC).");
|
|
60
|
+
if (plan.depositEth === 0n) {
|
|
61
|
+
ui.hint("ETH is sufficient. Rerun without --no-swap to convert the service budget to USDC.");
|
|
117
62
|
return;
|
|
118
63
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
const ethToSwap = (usdcNeeded / prices.ethPriceUsd) * 1.02; // 2% buffer
|
|
122
|
-
if (ethBal - ethToSwap < constants_1.MIN_ETH * 0.5) {
|
|
123
|
-
ui.warn("Not enough ETH to swap for USDC and keep enough for gas. Skipping auto-split.");
|
|
124
|
-
return;
|
|
125
|
-
}
|
|
126
|
-
console.log("");
|
|
127
|
-
ui.table([
|
|
128
|
-
["Auto-split", `Swap ~${ethToSwap.toFixed(6)} ETH → ~${usdcNeeded.toFixed(2)} USDC`],
|
|
129
|
-
["Purpose", "USDC for x402 RPC calls"],
|
|
130
|
-
["Remaining ETH", `~${(ethBal - ethToSwap).toFixed(6)} ETH (gas)`],
|
|
131
|
-
]);
|
|
132
|
-
console.log("");
|
|
133
|
-
const proceed = await ui.confirm("Confirm swap?");
|
|
134
|
-
if (!proceed) {
|
|
135
|
-
console.log(" Skipped auto-split.");
|
|
136
|
-
return;
|
|
137
|
-
}
|
|
138
|
-
const swapSpinner = ui.spinner("Swapping ETH → USDC on Uniswap V3...");
|
|
139
|
-
const ethWei = (0, viem_1.parseEther)(ethToSwap.toFixed(18));
|
|
140
|
-
const minUsdc = (0, viem_1.parseUnits)((usdcNeeded * (1 - constants_1.SLIPPAGE_BPS / 10000)).toFixed(6), 6);
|
|
141
|
-
try {
|
|
142
|
-
const result = await (0, uniswap_1.swapEthToUsdc)(ethWei, minUsdc);
|
|
143
|
-
swapSpinner.stop(`Swap complete: ${result.usdcReceived} USDC`);
|
|
144
|
-
}
|
|
145
|
-
catch (err) {
|
|
146
|
-
swapSpinner.fail("Swap failed");
|
|
147
|
-
throw err;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
if (depositedAsset === "usdc" && ethBal < constants_1.MIN_ETH) {
|
|
151
|
-
const ethNeeded = constants_1.MIN_ETH - ethBal;
|
|
152
|
-
const usdcToSwap = ethNeeded * prices.ethPriceUsd * 1.02; // 2% buffer
|
|
153
|
-
if (usdcBal - usdcToSwap < constants_1.MIN_USDC * 0.5) {
|
|
154
|
-
ui.warn("Not enough USDC to swap for ETH and keep enough for RPC. Skipping auto-split.");
|
|
155
|
-
return;
|
|
156
|
-
}
|
|
157
|
-
console.log("");
|
|
158
|
-
ui.table([
|
|
159
|
-
["Auto-split", `Swap ~${usdcToSwap.toFixed(2)} USDC → ~${ethNeeded.toFixed(6)} ETH`],
|
|
160
|
-
["Purpose", "ETH for gas"],
|
|
161
|
-
["Remaining USDC", `~${(usdcBal - usdcToSwap).toFixed(2)} USDC (x402 RPC)`],
|
|
162
|
-
]);
|
|
163
|
-
console.log("");
|
|
164
|
-
const proceed = await ui.confirm("Confirm swap?");
|
|
165
|
-
if (!proceed) {
|
|
166
|
-
console.log(" Skipped auto-split.");
|
|
167
|
-
return;
|
|
168
|
-
}
|
|
169
|
-
const swapSpinner = ui.spinner("Swapping USDC → ETH on Uniswap V3...");
|
|
170
|
-
const usdcRaw = (0, viem_1.parseUnits)(usdcToSwap.toFixed(6), 6);
|
|
171
|
-
const minEth = (0, viem_1.parseEther)((ethNeeded * (1 - constants_1.SLIPPAGE_BPS / 10000)).toFixed(18));
|
|
172
|
-
try {
|
|
173
|
-
const result = await (0, uniswap_1.swapUsdcToEth)(usdcRaw, minEth);
|
|
174
|
-
swapSpinner.stop(`Swap complete: ${result.ethReceived} ETH`);
|
|
175
|
-
}
|
|
176
|
-
catch (err) {
|
|
177
|
-
swapSpinner.fail("Swap failed");
|
|
178
|
-
throw err;
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
// ---------------------------------------------------------------------------
|
|
183
|
-
// Show final balances
|
|
184
|
-
// ---------------------------------------------------------------------------
|
|
185
|
-
async function showFinalBalances() {
|
|
186
|
-
if (!wallet_1.account)
|
|
64
|
+
handoff(wallet_1.account.address, plan.depositEth);
|
|
65
|
+
if (!ui.isInteractiveSession() || !await ui.confirm("Watch this address for up to 10 minutes and finish the conversion?"))
|
|
187
66
|
return;
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
["USDC", `${usdcBal.toFixed(2)} USDC (x402 RPC)`],
|
|
195
|
-
]);
|
|
196
|
-
console.log(` Next: ${ui.cyan("apow mint")}`);
|
|
197
|
-
console.log("");
|
|
198
|
-
}
|
|
199
|
-
// ---------------------------------------------------------------------------
|
|
200
|
-
// Solana fund (Squid Router deposit address)
|
|
201
|
-
// ---------------------------------------------------------------------------
|
|
202
|
-
async function runSolanaFund(baseAddress, sourceToken, targetEth) {
|
|
203
|
-
const priceSpinner = ui.spinner("Fetching prices...");
|
|
204
|
-
const prices = await fetchPrices();
|
|
205
|
-
priceSpinner.stop(`ETH price: $${prices.ethPriceUsd.toFixed(0)}`);
|
|
206
|
-
const route = sourceToken === "usdc"
|
|
207
|
-
? squid_1.SQUID_ROUTES.sol_usdc_to_base_usdc
|
|
208
|
-
: squid_1.SQUID_ROUTES.sol_to_eth;
|
|
209
|
-
const amount = sourceToken === "usdc"
|
|
210
|
-
? targetEth * prices.ethPriceUsd * 1.1
|
|
211
|
-
: amountNeededForEth(targetEth, prices.solPriceUsd, prices.ethPriceUsd);
|
|
212
|
-
const tokenLabel = sourceToken === "usdc" ? "USDC" : "SOL";
|
|
213
|
-
const addrSpinner = ui.spinner("Generating deposit address...");
|
|
214
|
-
const squid = await Promise.resolve().then(() => __importStar(require("./bridge/squid")));
|
|
215
|
-
const solana = await Promise.resolve().then(() => __importStar(require("./bridge/solana")));
|
|
216
|
-
let deposit;
|
|
217
|
-
try {
|
|
218
|
-
deposit = await squid.getDepositAddress(baseAddress, amount, route);
|
|
219
|
-
}
|
|
220
|
-
catch (err) {
|
|
221
|
-
addrSpinner.fail("Failed to get deposit address");
|
|
222
|
-
throw err;
|
|
223
|
-
}
|
|
224
|
-
addrSpinner.stop("Deposit address ready");
|
|
225
|
-
console.log("");
|
|
226
|
-
console.log(` ${ui.bold(`Send ${tokenLabel} to this address:`)}`);
|
|
227
|
-
console.log("");
|
|
228
|
-
console.log(` ${ui.cyan(deposit.depositAddress)}`);
|
|
229
|
-
console.log("");
|
|
230
|
-
await showQrCode(deposit.depositAddress);
|
|
231
|
-
console.log("");
|
|
232
|
-
ui.table([
|
|
233
|
-
["Amount", `~${amount.toFixed(sourceToken === "usdc" ? 2 : 4)} ${tokenLabel}`],
|
|
234
|
-
["You'll receive", `~${deposit.expectedReceive} ${sourceToken === "usdc" ? "USDC" : "ETH"} on Base`],
|
|
235
|
-
["Bridge", "Squid Router (Chainflip)"],
|
|
236
|
-
["Time", "~1-3 minutes"],
|
|
237
|
-
]);
|
|
238
|
-
console.log("");
|
|
239
|
-
if (deposit.expiresAt) {
|
|
240
|
-
ui.warn(`Deposit address expires: ${deposit.expiresAt}`);
|
|
241
|
-
console.log("");
|
|
242
|
-
}
|
|
243
|
-
// Poll for deposit
|
|
244
|
-
const depositSpinner = ui.spinner(`Waiting for ${tokenLabel} deposit... (Ctrl+C to cancel)`);
|
|
245
|
-
if (sourceToken === "native") {
|
|
246
|
-
// SOL deposit: poll Solana balance
|
|
247
|
-
const initialBalance = await solana.getAddressBalance(deposit.depositAddress);
|
|
248
|
-
let depositDetected = false;
|
|
249
|
-
const depositDeadline = Date.now() + 600_000;
|
|
250
|
-
while (!depositDetected && Date.now() < depositDeadline) {
|
|
251
|
-
await new Promise((r) => setTimeout(r, 3000));
|
|
252
|
-
try {
|
|
253
|
-
const currentBalance = await solana.getAddressBalance(deposit.depositAddress);
|
|
254
|
-
if (currentBalance > initialBalance + 0.001) {
|
|
255
|
-
depositDetected = true;
|
|
256
|
-
depositSpinner.stop(`Deposit received! ${(currentBalance - initialBalance).toFixed(4)} SOL`);
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
catch {
|
|
260
|
-
// Transient RPC error
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
if (!depositDetected) {
|
|
264
|
-
depositSpinner.fail(`No ${tokenLabel} deposit detected after 10 minutes`);
|
|
265
|
-
ui.hint("If you sent tokens, check: https://explorer.squidrouter.com");
|
|
67
|
+
const deadline = Date.now() + 600_000;
|
|
68
|
+
while (Date.now() < deadline) {
|
|
69
|
+
await new Promise(resolve => setTimeout(resolve, 5_000));
|
|
70
|
+
plan = await (0, base_funding_1.prepareBaseFunding)(mint, allowSwap);
|
|
71
|
+
if (plan.ready) {
|
|
72
|
+
ui.ok("Deposit and funding conversion verified. Run apow start --easy.");
|
|
266
73
|
return;
|
|
267
74
|
}
|
|
268
75
|
}
|
|
269
|
-
|
|
270
|
-
// USDC deposit: poll SPL token balance at the deposit address
|
|
271
|
-
let depositDetected = false;
|
|
272
|
-
const depositDeadline = Date.now() + 600_000;
|
|
273
|
-
while (!depositDetected && Date.now() < depositDeadline) {
|
|
274
|
-
await new Promise((r) => setTimeout(r, 3000));
|
|
275
|
-
try {
|
|
276
|
-
const bal = await solana.getSplTokenBalance(deposit.depositAddress, constants_1.TOKENS.solana.usdc);
|
|
277
|
-
if (bal > 0.01) {
|
|
278
|
-
depositDetected = true;
|
|
279
|
-
depositSpinner.stop(`Deposit received! ${bal.toFixed(2)} USDC`);
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
catch {
|
|
283
|
-
// Transient RPC error
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
if (!depositDetected) {
|
|
287
|
-
depositSpinner.fail("No USDC deposit detected after 10 minutes");
|
|
288
|
-
ui.hint("If you sent USDC, check: https://explorer.squidrouter.com");
|
|
289
|
-
return;
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
// Poll for bridge completion
|
|
293
|
-
const bridgeSpinner = ui.spinner("Bridging to Base... (~1-3 min)");
|
|
294
|
-
const result = await (0, squid_1.pollBridgeStatus)(deposit.requestId, route.dstDecimals, (status) => bridgeSpinner.update(`Bridge status: ${status}`));
|
|
295
|
-
const received = result.received || deposit.expectedReceive;
|
|
296
|
-
const receivedAsset = sourceToken === "usdc" ? "USDC" : "ETH";
|
|
297
|
-
bridgeSpinner.stop(`Bridge complete! ${received} ${receivedAsset} arrived`);
|
|
298
|
-
const outputAsset = (0, constants_1.bridgeOutputAsset)(sourceToken);
|
|
299
|
-
await autoSplit(outputAsset, prices, false);
|
|
300
|
-
await showFinalBalances();
|
|
76
|
+
ui.warn("Funding is still incomplete. Keep the same wallet and rerun after deposit.");
|
|
301
77
|
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
const priceSpinner = ui.spinner("Fetching prices...");
|
|
307
|
-
const prices = await fetchPrices();
|
|
308
|
-
priceSpinner.stop(`ETH price: $${prices.ethPriceUsd.toFixed(0)}`);
|
|
309
|
-
// ETH→ETH bridge is ~1:1, add 5% buffer for bridge fees
|
|
310
|
-
const amount = targetEth * 1.05;
|
|
311
|
-
const addrSpinner = ui.spinner("Generating deposit address...");
|
|
312
|
-
const squid = await Promise.resolve().then(() => __importStar(require("./bridge/squid")));
|
|
313
|
-
let deposit;
|
|
314
|
-
try {
|
|
315
|
-
deposit = await squid.getDepositAddress(baseAddress, amount, squid.SQUID_ROUTES.eth_to_base_eth);
|
|
316
|
-
}
|
|
317
|
-
catch (err) {
|
|
318
|
-
addrSpinner.fail("Failed to get deposit address");
|
|
319
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
320
|
-
if (msg.includes("DEPOSIT_ADDRESS_UNAVAILABLE")) {
|
|
321
|
-
console.log("");
|
|
322
|
-
ui.warn("Squid Router doesn't support deposit addresses for Ethereum.");
|
|
323
|
-
console.log(" Alternatives:");
|
|
324
|
-
console.log(` ${ui.cyan("1.")} Bridge via ${ui.bold("bridge.base.org")} → paste your mining wallet as recipient`);
|
|
325
|
-
console.log(` ${ui.cyan("2.")} Send ETH on Base directly: ${ui.cyan("apow fund --chain base")}`);
|
|
326
|
-
console.log(` ${ui.cyan("3.")} Bridge from Solana instead: ${ui.cyan("apow fund --chain solana")}`);
|
|
327
|
-
console.log("");
|
|
328
|
-
return;
|
|
329
|
-
}
|
|
330
|
-
throw err;
|
|
331
|
-
}
|
|
332
|
-
addrSpinner.stop("Deposit address ready");
|
|
333
|
-
console.log("");
|
|
334
|
-
console.log(` ${ui.bold("Send ETH on Ethereum mainnet to this address:")}`);
|
|
335
|
-
console.log("");
|
|
336
|
-
console.log(` ${ui.cyan(deposit.depositAddress)}`);
|
|
337
|
-
console.log("");
|
|
338
|
-
await showQrCode(deposit.depositAddress);
|
|
339
|
-
console.log("");
|
|
340
|
-
ui.table([
|
|
341
|
-
["Amount", `~${amount.toFixed(6)} ETH`],
|
|
342
|
-
["You'll receive", `~${deposit.expectedReceive} ETH on Base`],
|
|
343
|
-
["Bridge", "Squid Router (Chainflip)"],
|
|
344
|
-
["Time", "~1-3 minutes"],
|
|
345
|
-
]);
|
|
346
|
-
console.log("");
|
|
347
|
-
if (deposit.expiresAt) {
|
|
348
|
-
ui.warn(`Deposit address expires: ${deposit.expiresAt}`);
|
|
349
|
-
console.log("");
|
|
350
|
-
}
|
|
351
|
-
// Poll for deposit on Ethereum mainnet
|
|
352
|
-
const ethereum = await Promise.resolve().then(() => __importStar(require("./bridge/ethereum")));
|
|
353
|
-
const depositSpinner = ui.spinner("Waiting for ETH deposit on Ethereum mainnet... (Ctrl+C to cancel)");
|
|
354
|
-
const initialBalance = await ethereum.getAddressBalance(deposit.depositAddress);
|
|
355
|
-
let depositDetected = false;
|
|
356
|
-
const depositDeadline = Date.now() + 600_000;
|
|
357
|
-
while (!depositDetected && Date.now() < depositDeadline) {
|
|
358
|
-
await new Promise((r) => setTimeout(r, 3000));
|
|
359
|
-
try {
|
|
360
|
-
const currentBalance = await ethereum.getAddressBalance(deposit.depositAddress);
|
|
361
|
-
if (currentBalance > initialBalance + 0.0001) {
|
|
362
|
-
depositDetected = true;
|
|
363
|
-
depositSpinner.stop(`Deposit received! ${(currentBalance - initialBalance).toFixed(6)} ETH`);
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
catch {
|
|
367
|
-
// Transient RPC error
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
if (!depositDetected) {
|
|
371
|
-
depositSpinner.fail("No ETH deposit detected after 10 minutes");
|
|
372
|
-
ui.hint("If you sent ETH, check: https://explorer.squidrouter.com");
|
|
78
|
+
/** Preserve the explicit legacy USDC route without asking for a second deposit asset. */
|
|
79
|
+
async function convertExistingUsdc(mint) {
|
|
80
|
+
const plan = await (0, base_funding_1.prepareBaseFunding)(mint, false);
|
|
81
|
+
if (plan.balances.eth >= plan.requirements.ethReserve)
|
|
373
82
|
return;
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
const bridgeSpinner = ui.spinner("Bridging to Base... (~1-3 min)");
|
|
377
|
-
const result = await (0, squid_1.pollBridgeStatus)(deposit.requestId, 18, (status) => bridgeSpinner.update(`Bridge status: ${status}`));
|
|
378
|
-
const received = result.received || deposit.expectedReceive;
|
|
379
|
-
bridgeSpinner.stop(`Bridge complete! ${received} ETH arrived`);
|
|
380
|
-
await autoSplit("eth", prices, false);
|
|
381
|
-
await showFinalBalances();
|
|
382
|
-
}
|
|
383
|
-
// ---------------------------------------------------------------------------
|
|
384
|
-
// Base manual send (already on the right chain)
|
|
385
|
-
// ---------------------------------------------------------------------------
|
|
386
|
-
async function runBaseFund(baseAddress, sourceToken, noSwap) {
|
|
387
|
-
const tokenLabel = sourceToken === "usdc" ? "USDC" : "ETH";
|
|
388
|
-
console.log("");
|
|
389
|
-
console.log(` ${ui.bold(`Send ${tokenLabel} on Base to this address:`)}`);
|
|
390
|
-
console.log("");
|
|
391
|
-
console.log(` ${ui.cyan(baseAddress)}`);
|
|
392
|
-
console.log("");
|
|
393
|
-
await showQrCode(baseAddress);
|
|
394
|
-
console.log("");
|
|
395
|
-
console.log(` ${ui.dim("Send from any wallet — Coinbase, MetaMask, Phantom, etc.")}`);
|
|
396
|
-
if (sourceToken === "usdc") {
|
|
397
|
-
console.log(` ${ui.dim("Need at least 2 USDC for x402 RPC + some for ETH swap.")}`);
|
|
398
|
-
}
|
|
399
|
-
else {
|
|
400
|
-
console.log(` ${ui.dim("Need ~0.005 ETH to cover gas + USDC swap.")}`);
|
|
401
|
-
}
|
|
402
|
-
console.log("");
|
|
403
|
-
const waitForDeposit = await ui.confirm("Wait for deposit and auto-split?");
|
|
404
|
-
if (!waitForDeposit) {
|
|
405
|
-
console.log(` ${ui.dim("After sending, run:")} ${ui.cyan("apow fund --chain base")} to auto-split.`);
|
|
406
|
-
console.log("");
|
|
83
|
+
const gas = 2n * (await (0, uniswap_1.quoteEthSwapFees)(plan.swapEth || 1n, plan.requirements.usdcTarget || 1n)).feeReserve;
|
|
84
|
+
if (plan.balances.eth < gas)
|
|
407
85
|
return;
|
|
408
|
-
|
|
409
|
-
const
|
|
410
|
-
|
|
411
|
-
const depositSpinner = ui.spinner(`Waiting for ${tokenLabel} deposit... (Ctrl+C to cancel)`);
|
|
412
|
-
const initialEth = await (0, wallet_1.getEthBalance)();
|
|
413
|
-
const initialUsdc = wallet_1.account ? await (0, uniswap_1.getUsdcBalance)(wallet_1.account.address) : 0n;
|
|
414
|
-
const depositDeadline = Date.now() + 600_000;
|
|
415
|
-
let depositDetected = false;
|
|
416
|
-
while (!depositDetected && Date.now() < depositDeadline) {
|
|
417
|
-
await new Promise((r) => setTimeout(r, 3000));
|
|
418
|
-
try {
|
|
419
|
-
if (sourceToken === "usdc" && wallet_1.account) {
|
|
420
|
-
const currentUsdc = await (0, uniswap_1.getUsdcBalance)(wallet_1.account.address);
|
|
421
|
-
if (currentUsdc > initialUsdc + 100000n) { // > 0.1 USDC
|
|
422
|
-
depositDetected = true;
|
|
423
|
-
depositSpinner.stop(`Deposit received! ${(0, viem_1.formatUnits)(currentUsdc - initialUsdc, 6)} USDC`);
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
else {
|
|
427
|
-
const currentEth = await (0, wallet_1.getEthBalance)();
|
|
428
|
-
if (currentEth > initialEth + (0, viem_1.parseEther)("0.0001")) {
|
|
429
|
-
depositDetected = true;
|
|
430
|
-
depositSpinner.stop(`Deposit received! ${(0, viem_1.formatEther)(currentEth - initialEth)} ETH`);
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
catch {
|
|
435
|
-
// Transient RPC error
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
if (!depositDetected) {
|
|
439
|
-
depositSpinner.fail(`No ${tokenLabel} deposit detected after 10 minutes`);
|
|
86
|
+
const minimumEth = plan.requirements.ethReserve - plan.balances.eth + gas;
|
|
87
|
+
const input = await (0, uniswap_1.quoteUsdcForEth)(minimumEth);
|
|
88
|
+
if (plan.balances.usdc < input + plan.requirements.usdcTarget)
|
|
440
89
|
return;
|
|
441
|
-
|
|
442
|
-
const outputAsset = (0, constants_1.bridgeOutputAsset)(sourceToken);
|
|
443
|
-
await autoSplit(outputAsset, prices, noSwap);
|
|
444
|
-
await showFinalBalances();
|
|
445
|
-
}
|
|
446
|
-
// ---------------------------------------------------------------------------
|
|
447
|
-
// Interactive menus
|
|
448
|
-
// ---------------------------------------------------------------------------
|
|
449
|
-
async function selectSourceChain() {
|
|
450
|
-
console.log(" Where are your funds?");
|
|
451
|
-
console.log(` ${ui.cyan("1.")} Solana (SOL or USDC)`);
|
|
452
|
-
console.log(` ${ui.cyan("2.")} Ethereum mainnet (ETH)`);
|
|
453
|
-
console.log(` ${ui.cyan("3.")} Base (send ETH or USDC directly)`);
|
|
454
|
-
console.log("");
|
|
455
|
-
const choice = await ui.prompt("Choice", "1");
|
|
456
|
-
if (choice === "2")
|
|
457
|
-
return "ethereum";
|
|
458
|
-
if (choice === "3")
|
|
459
|
-
return "base";
|
|
460
|
-
return "solana";
|
|
461
|
-
}
|
|
462
|
-
async function selectSourceToken(chain) {
|
|
463
|
-
// Ethereum only supports native ETH — skip token prompt
|
|
464
|
-
if (chain === "ethereum")
|
|
465
|
-
return "native";
|
|
466
|
-
const nativeLabel = chain === "solana" ? "SOL" : "ETH";
|
|
467
|
-
console.log("");
|
|
468
|
-
console.log(" What token?");
|
|
469
|
-
console.log(` ${ui.cyan("1.")} ${nativeLabel}`);
|
|
470
|
-
console.log(` ${ui.cyan("2.")} USDC`);
|
|
471
|
-
console.log("");
|
|
472
|
-
const choice = await ui.prompt("Choice", "1");
|
|
473
|
-
return choice === "2" ? "usdc" : "native";
|
|
90
|
+
await (0, uniswap_1.swapUsdcToEth)(input, minimumEth);
|
|
474
91
|
}
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
const
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
}
|
|
487
|
-
function parseSourceToken(value) {
|
|
488
|
-
if (!value)
|
|
489
|
-
return undefined;
|
|
490
|
-
const v = value.toLowerCase();
|
|
491
|
-
if (v === "sol" || v === "eth" || v === "native")
|
|
492
|
-
return "native";
|
|
493
|
-
if (v === "usdc")
|
|
494
|
-
return "usdc";
|
|
495
|
-
return undefined;
|
|
496
|
-
}
|
|
497
|
-
// ---------------------------------------------------------------------------
|
|
498
|
-
// Main entry point
|
|
499
|
-
// ---------------------------------------------------------------------------
|
|
500
|
-
async function runFundFlow(options) {
|
|
501
|
-
if (!wallet_1.account) {
|
|
502
|
-
ui.error("No wallet configured. Run `apow setup` first.");
|
|
503
|
-
process.exit(1);
|
|
504
|
-
}
|
|
505
|
-
const interactive = ui.isInteractiveSession();
|
|
506
|
-
const baseAddress = wallet_1.account.address;
|
|
507
|
-
const noSwap = options.swap === false;
|
|
508
|
-
// Parse target ETH amount
|
|
509
|
-
const targetEth = options.amount ? parseFloat(options.amount) : 0.005;
|
|
510
|
-
if (isNaN(targetEth) || targetEth <= 0) {
|
|
511
|
-
ui.error("Invalid amount. Specify ETH target (e.g., --amount 0.005).");
|
|
92
|
+
/** Quote a bridge before offering a deposit address; verify Base funds before mining. */
|
|
93
|
+
async function runBridgeFund(options, mint) {
|
|
94
|
+
const chain = options.chain.toLowerCase();
|
|
95
|
+
const token = (options.token ?? (chain === "solana" ? "sol" : "eth")).toLowerCase();
|
|
96
|
+
const route = chain === "solana"
|
|
97
|
+
? token === "usdc" ? squid_1.SQUID_ROUTES.sol_usdc_to_base_eth : squid_1.SQUID_ROUTES.sol_to_eth
|
|
98
|
+
: squid_1.SQUID_ROUTES.eth_to_base_eth;
|
|
99
|
+
const plan = await (0, base_funding_1.prepareBaseFunding)(mint, false);
|
|
100
|
+
const target = options.amount ? (0, viem_1.parseEther)(options.amount) : plan.depositEth;
|
|
101
|
+
if (target <= 0n) {
|
|
102
|
+
await runBaseFund(mint, options.swap !== false);
|
|
512
103
|
return;
|
|
513
104
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
105
|
+
const needed = target > plan.depositEth ? target : plan.depositEth;
|
|
106
|
+
// Prices only seed the source amount. The provider minimum must cover Base costs.
|
|
107
|
+
const prices = await fetch("https://api.coingecko.com/api/v3/simple/price?ids=solana,ethereum&vs_currencies=usd", {
|
|
108
|
+
signal: AbortSignal.timeout(10_000),
|
|
109
|
+
});
|
|
110
|
+
if (!prices.ok)
|
|
111
|
+
throw new Error("Could not price the bridge. No deposit address was issued.");
|
|
112
|
+
const data = await prices.json();
|
|
113
|
+
const ethUsd = data.ethereum?.usd;
|
|
114
|
+
const sourceUsd = token === "usdc" ? 1 : chain === "solana" ? data.solana?.usd : ethUsd;
|
|
115
|
+
if (!ethUsd || !sourceUsd || !Number.isFinite(ethUsd) || !Number.isFinite(sourceUsd) || ethUsd <= 0 || sourceUsd <= 0) {
|
|
116
|
+
throw new Error("Invalid bridge price. No deposit address was issued.");
|
|
117
|
+
}
|
|
118
|
+
const amount = Number((0, viem_1.formatEther)(needed)) * ethUsd / sourceUsd * 1.15;
|
|
119
|
+
const deposit = await (0, squid_1.getDepositAddress)(wallet_1.account.address, amount, route, needed);
|
|
120
|
+
ui.hint(`Send ${amount.toFixed(route.srcDecimals)} ${chain === "solana" ? token.toUpperCase() : "ETH"} on ${chain} to ${deposit.depositAddress}.`);
|
|
121
|
+
ui.hint(`Minimum receive: ${deposit.minimumReceive} ETH on Base. Keep request ${deposit.requestId} to recover this route.`);
|
|
122
|
+
if (deposit.expiresAt)
|
|
123
|
+
ui.hint(`Deposit address expires: ${deposit.expiresAt}. Do not reuse it after expiry.`);
|
|
124
|
+
if (!ui.isInteractiveSession() || !await ui.confirm("Watch this bridge for up to 10 minutes?")) {
|
|
125
|
+
ui.hint("After Base funds arrive, rerun apow start --easy; no second deposit asset is needed.");
|
|
519
126
|
return;
|
|
520
127
|
}
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
}
|
|
545
|
-
if (!chain) {
|
|
546
|
-
chain = await selectSourceChain();
|
|
547
|
-
}
|
|
548
|
-
if (!token) {
|
|
549
|
-
token = await selectSourceToken(chain);
|
|
550
|
-
}
|
|
551
|
-
// Route to the appropriate flow
|
|
552
|
-
switch (chain) {
|
|
553
|
-
case "solana": {
|
|
554
|
-
await runSolanaFund(baseAddress, token, targetEth);
|
|
555
|
-
break;
|
|
556
|
-
}
|
|
557
|
-
case "ethereum": {
|
|
558
|
-
await runEthereumFund(baseAddress, targetEth);
|
|
559
|
-
break;
|
|
560
|
-
}
|
|
561
|
-
case "base": {
|
|
562
|
-
await runBaseFund(baseAddress, token, noSwap);
|
|
563
|
-
break;
|
|
564
|
-
}
|
|
565
|
-
}
|
|
128
|
+
await (0, squid_1.pollBridgeStatus)(deposit.requestId);
|
|
129
|
+
await runBaseFund(mint, options.swap !== false);
|
|
130
|
+
}
|
|
131
|
+
async function runFundFlow(options) {
|
|
132
|
+
if (!wallet_1.account)
|
|
133
|
+
throw new Error("Unlock your existing mining wallet before funding");
|
|
134
|
+
if (options.amount && (!/^\d+(\.\d{1,18})?$/.test(options.amount) || (0, viem_1.parseEther)(options.amount) <= 0n)) {
|
|
135
|
+
throw new Error("--amount must be a positive ETH target with at most 18 decimal places");
|
|
136
|
+
}
|
|
137
|
+
const chain = (options.chain ?? "base").toLowerCase();
|
|
138
|
+
if (!["base", "solana", "ethereum"].includes(chain))
|
|
139
|
+
throw new Error("Source chain must be base, solana, or ethereum");
|
|
140
|
+
const token = options.token?.toLowerCase();
|
|
141
|
+
if (token && !(chain === "solana" ? ["sol", "usdc", "native"] : chain === "base" ? ["eth", "usdc", "native"] : ["eth", "native"]).includes(token)) {
|
|
142
|
+
throw new Error("Use Base ETH, Solana SOL/USDC, or Ethereum ETH for single-asset funding");
|
|
143
|
+
}
|
|
144
|
+
const mint = await needsMint();
|
|
145
|
+
if (chain === "base" && token === "usdc" && options.swap !== false)
|
|
146
|
+
await convertExistingUsdc(mint);
|
|
147
|
+
if (chain === "base")
|
|
148
|
+
await runBaseFund(mint, options.swap !== false);
|
|
149
|
+
else
|
|
150
|
+
await runBridgeFund({ ...options, chain, token: token === "native" ? chain === "solana" ? "sol" : "eth" : token }, mint);
|
|
566
151
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.prepareFunding = prepareFunding;
|
|
4
|
+
/** Quote before spending, preserve the ETH reserve, and verify the landed balance. */
|
|
5
|
+
async function prepareFunding(requirements, deps, allowSwap) {
|
|
6
|
+
const balances = await deps.balances();
|
|
7
|
+
const missingUsdc = requirements.usdcTarget > balances.usdc ? requirements.usdcTarget - balances.usdc : 0n;
|
|
8
|
+
const swapEth = missingUsdc > 0n ? await deps.quoteEth(missingUsdc) : 0n;
|
|
9
|
+
if (missingUsdc > 0n && swapEth <= 0n)
|
|
10
|
+
throw new Error("Invalid ETH funding quote");
|
|
11
|
+
const swapGasReserve = missingUsdc > 0n
|
|
12
|
+
? deps.quoteSwapGas ? await deps.quoteSwapGas(swapEth, missingUsdc) : requirements.swapGasReserve ?? 0n : 0n;
|
|
13
|
+
if (swapGasReserve < 0n)
|
|
14
|
+
throw new Error("Invalid swap fee quote");
|
|
15
|
+
const requiredEth = requirements.ethReserve + swapEth + swapGasReserve;
|
|
16
|
+
if (balances.eth < requiredEth) {
|
|
17
|
+
return { ready: false, depositEth: requiredEth - balances.eth, swapEth, balances };
|
|
18
|
+
}
|
|
19
|
+
if (missingUsdc === 0n)
|
|
20
|
+
return { ready: true, depositEth: 0n, swapEth: 0n, balances };
|
|
21
|
+
if (!allowSwap)
|
|
22
|
+
return { ready: false, depositEth: 0n, swapEth, balances };
|
|
23
|
+
await deps.swapEth(swapEth, missingUsdc);
|
|
24
|
+
const landed = await deps.balances();
|
|
25
|
+
if (landed.eth < requirements.ethReserve || landed.usdc < requirements.usdcTarget) {
|
|
26
|
+
throw new Error("Funding conversion did not meet the ETH reserve and USDC target; stopping before mining");
|
|
27
|
+
}
|
|
28
|
+
return { ready: true, depositEth: 0n, swapEth, balances: landed };
|
|
29
|
+
}
|