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/.env.example
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
# === Easy Mode (no API keys) ===
|
|
2
2
|
# RPC + LLM + remote GPU grind all auto-pay with USDC from your wallet.
|
|
3
3
|
KEYSTORE_PATH=
|
|
4
|
-
# KEYSTORE_PASSWORD= #
|
|
4
|
+
# KEYSTORE_PASSWORD= # A temporary unlock only; never persist the password here.
|
|
5
|
+
# Before funding in a headless/cloud runner, persist a secret-manager command.
|
|
6
|
+
# Store its secret separately and verify: apow wallet verify-recovery
|
|
5
7
|
# KEYSTORE_PASSWORD_CMD=security find-generic-password -s apow-keystore -w
|
|
6
8
|
USE_X402=true
|
|
7
9
|
USE_X402_GRIND=true
|
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Agent-first mining client for [APoW (Agentic Proof of Work)](https://apow.io) on
|
|
4
4
|
Base. Onboard a Mining Rig, then run the protocol's SMHL and Keccak verification
|
|
5
5
|
flow continuously to earn $AGENT tokens. The contracts are
|
|
6
|
-
[open source](https://github.com/Agentoshi/apow
|
|
6
|
+
[open source](https://github.com/Agentoshi/apow/tree/main/packages/core).
|
|
7
7
|
|
|
8
8
|
**Your agent does all the work. You just fund a wallet.**
|
|
9
9
|
|
|
@@ -32,19 +32,24 @@ npx apow-cli
|
|
|
32
32
|
> **v0.8.0+: Bring your own RPC or use auto-pay.** You need a Base RPC endpoint. Two options:
|
|
33
33
|
>
|
|
34
34
|
> 1. **Bring your own** (free): Get a free RPC URL from [Alchemy](https://www.alchemy.com/), [QuickNode](https://www.quicknode.com/), or any Base RPC provider. Set `RPC_URL` in your `.env`.
|
|
35
|
-
> 2. **QuickNode x402** (paid, zero setup): Set `USE_X402=true` in your `.env`. Your mining wallet pays for RPC usage via the [x402 payment protocol](https://www.x402.org/).
|
|
35
|
+
> 2. **QuickNode x402** (paid, zero setup): Set `USE_X402=true` in your `.env`. Your mining wallet pays for RPC usage via the [x402 payment protocol](https://www.x402.org/). Deposit Base ETH through the funding flow; the CLI converts the initial 2.00 USDC service budget. No API key or account needed.
|
|
36
36
|
>
|
|
37
37
|
> Run `apow setup` to configure interactively.
|
|
38
38
|
|
|
39
39
|
## For AI Agents
|
|
40
40
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
41
|
+
Deposit **Base ETH only**. The CLI quotes the live rig price, retains ETH for gas,
|
|
42
|
+
and converts the service budget to USDC. It tests wallet recovery before giving
|
|
43
|
+
funding instructions. Rerun the same command after deposit to mint or resume
|
|
44
|
+
an existing rig; the wallet address stays the same.
|
|
45
|
+
|
|
46
|
+
See the [assistant profiles](https://apow.io/docs/technical/assistants) for Grok Bot,
|
|
47
|
+
Muse, Instinct, Wajo, OpenClaw, Hermes, Claude Code, Codex, and other runtimes.
|
|
48
|
+
The [managed cloud service](https://apow.io/docs/technical/managed-mining) is in
|
|
49
|
+
development; the current CLI still needs a runner.
|
|
45
50
|
|
|
46
51
|
```bash
|
|
47
|
-
npx --yes apow-cli@0.12.
|
|
52
|
+
npx --yes apow-cli@0.12.4 start --easy
|
|
48
53
|
```
|
|
49
54
|
|
|
50
55
|
Relevant Easy Mode settings include:
|
|
@@ -58,7 +63,9 @@ ALLOW_LOCAL_FALLBACK_WITH_X402=false
|
|
|
58
63
|
```
|
|
59
64
|
|
|
60
65
|
The keystore password is prompted interactively. For headless launch services,
|
|
61
|
-
|
|
66
|
+
save a `KEYSTORE_PASSWORD_CMD` reference in the private `.env` and use a supported
|
|
67
|
+
secret manager. Run `apow wallet verify-recovery` before funding. A password kept
|
|
68
|
+
only in process memory cannot recover after a restart. Never send secrets in chat.
|
|
62
69
|
Never put it in chat or commit it to a project file. See [skill.md](skill.md) for
|
|
63
70
|
the narrow autonomous mining workflow.
|
|
64
71
|
|
|
@@ -78,8 +85,9 @@ If you want to control each step manually, the older step-by-step flow is still
|
|
|
78
85
|
|---------|-------------|
|
|
79
86
|
| `apow start [--easy]` | Existing Easy/Advanced flow: setup -> Base funding check/handoff -> mint -> mine |
|
|
80
87
|
| `apow setup` | Agent-first setup wizard: Easy Mode (x402 everywhere) or Advanced Mode |
|
|
81
|
-
| `apow fund` |
|
|
88
|
+
| `apow fund` | ETH-only funding quote, conversion, and configured bridge routes |
|
|
82
89
|
| `apow wallet new` | Generate a new encrypted mining wallet |
|
|
90
|
+
| `apow wallet verify-recovery` | Test fresh-process unlock before funding |
|
|
83
91
|
| `apow wallet list` | List every wallet generated locally by this APoW CLI and mark the active wallet |
|
|
84
92
|
| `apow wallet use [address-or-number]` | Select a generated wallet for the current project (`select` is an alias) |
|
|
85
93
|
| `apow wallet show` | Show configured wallet address |
|
|
@@ -109,7 +117,7 @@ ALLOW_LOCAL_FALLBACK_WITH_X402=false # Easy Mode default: do not burn local CPU
|
|
|
109
117
|
# LLM_PROVIDER=clawrouter # x402: clawrouter | API key: openai/anthropic/gemini/deepseek/qwen | local/subscription CLI: ollama/claude-code/codex
|
|
110
118
|
# LLM_MODEL=... # Optional override; x402 selects automatically
|
|
111
119
|
# LLM_API_KEY=sk-... # Required only for API-key providers
|
|
112
|
-
# KEYSTORE_PASSWORD
|
|
120
|
+
# KEYSTORE_PASSWORD= # Temporary unlock only; never store the password here
|
|
113
121
|
# KEYSTORE_PASSWORD_CMD=... # Preferred headless unlock command, stdout is used as password
|
|
114
122
|
# APOW_POLICY=enforce # enforce | warn | off
|
|
115
123
|
# APOW_PAYOUT_ADDRESS=0x... # optional cold payout wallet for AGENT sweeps
|
|
@@ -194,29 +202,30 @@ yet recorded as a completed APoW mainnet mint.
|
|
|
194
202
|
|
|
195
203
|
## Funding (v0.7.0+)
|
|
196
204
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
The
|
|
205
|
+
Send **one asset: Base ETH**. `apow start --easy` quotes the current rig price,
|
|
206
|
+
a conservative 0.003 ETH reserve, swap gas, and the missing 2 USDC service budget.
|
|
207
|
+
The reserve is not the actual gas cost per mine. The Uniswap quote includes a
|
|
208
|
+
2% input buffer and requires enough USDC output; the CLI checks balances again
|
|
209
|
+
after the swap. The fee budget uses current L2 fee caps, a fixed transaction gas
|
|
210
|
+
ceiling, and buffered Base L1/operator fees. Those L2 caps are used when signing.
|
|
211
|
+
It stops if conversion would consume the required ETH reserve.
|
|
200
212
|
|
|
201
213
|
```bash
|
|
202
|
-
#
|
|
203
|
-
apow fund
|
|
204
|
-
apow fund --chain solana --token
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
apow fund --
|
|
208
|
-
|
|
209
|
-
# Already on Base
|
|
210
|
-
apow fund --chain base --token eth # show address, wait for deposit, auto-split
|
|
211
|
-
apow fund --chain base --token usdc # show address, wait for deposit, auto-split
|
|
212
|
-
|
|
213
|
-
# Skip auto-split (keep single asset)
|
|
214
|
-
apow fund --chain base --no-swap
|
|
214
|
+
apow start --easy # quote, deposit ETH, then rerun to convert/mint/mine
|
|
215
|
+
apow fund # default Base ETH; resumes existing deposits
|
|
216
|
+
apow fund --chain solana --token sol # configured Squid route: SOL to Base ETH
|
|
217
|
+
apow fund --chain solana --token usdc # configured Squid route: USDC to Base ETH
|
|
218
|
+
apow fund --chain ethereum --token eth
|
|
219
|
+
apow fund --no-swap # quote only; no conversion
|
|
215
220
|
```
|
|
216
221
|
|
|
217
|
-
|
|
222
|
+
Solana routes require an operator-configured `SQUID_INTEGRATOR_ID`. They are
|
|
223
|
+
unavailable until configured. Bridge quotes must cover the Base requirement
|
|
224
|
+
after fees and slippage before a deposit address is offered. Do not send SOL
|
|
225
|
+
to the Base wallet address. Keep the bridge request ID and respect its expiry.
|
|
218
226
|
|
|
219
|
-
|
|
227
|
+
Existing USDC stays usable for services. Base ETH is the funding deposit asset;
|
|
228
|
+
the CLI does not ask the user to supply both ETH and USDC.
|
|
220
229
|
|
|
221
230
|
## x402 GPU Grinding
|
|
222
231
|
|
|
@@ -236,7 +245,7 @@ In Easy Mode, the HTTP grinder is the only nonce source, so agents do not silent
|
|
|
236
245
|
| `ALLOW_LOCAL_FALLBACK_WITH_X402` | Let local JS fallback run alongside x402 GPU (`false` in Easy Mode) |
|
|
237
246
|
| `GRIND_URL` | Custom GrindProxy endpoint (default: `https://grind.apow.io/grind`) |
|
|
238
247
|
|
|
239
|
-
Self-host your own GrindProxy: see [
|
|
248
|
+
Self-host your own GrindProxy: see [packages/grind](https://github.com/Agentoshi/apow/tree/main/packages/grind).
|
|
240
249
|
|
|
241
250
|
## GPU Mining (v0.9.2+)
|
|
242
251
|
|
|
@@ -300,7 +309,7 @@ Refreshes use chunked multicalls and a 25-second cache. Clicking **Refresh** aft
|
|
|
300
309
|
|
|
301
310
|
## Protocol
|
|
302
311
|
|
|
303
|
-
The APoW protocol contracts and documentation live in [
|
|
312
|
+
The APoW protocol contracts and documentation live in [packages/core](https://github.com/Agentoshi/apow/tree/main/packages/core) of the [APoW monorepo](https://github.com/Agentoshi/apow).
|
|
304
313
|
|
|
305
314
|
## License
|
|
306
315
|
|
|
@@ -0,0 +1,98 @@
|
|
|
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
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.MINT_GAS_RESERVE_ETH = void 0;
|
|
37
|
+
exports.requiresUsdc = requiresUsdc;
|
|
38
|
+
exports.prepareBaseFunding = prepareBaseFunding;
|
|
39
|
+
const viem_1 = require("viem");
|
|
40
|
+
const config_1 = require("./config");
|
|
41
|
+
const constants_1 = require("./bridge/constants");
|
|
42
|
+
const uniswap_1 = require("./bridge/uniswap");
|
|
43
|
+
const funding_plan_1 = require("./funding-plan");
|
|
44
|
+
const wallet_1 = require("./wallet");
|
|
45
|
+
const context_1 = require("./policy/context");
|
|
46
|
+
const ui = __importStar(require("./ui"));
|
|
47
|
+
exports.MINT_GAS_RESERVE_ETH = (0, viem_1.parseEther)(String(constants_1.MIN_ETH));
|
|
48
|
+
const SWAP_GAS_RESERVE_ETH = (0, viem_1.parseEther)("0.00005");
|
|
49
|
+
function requiresUsdc(needsMint = true) {
|
|
50
|
+
return config_1.config.useX402 || config_1.config.useX402Grind || (needsMint && config_1.config.llmProvider === "clawrouter");
|
|
51
|
+
}
|
|
52
|
+
/** All reads use the funding RPC, so a wallet with only ETH can bootstrap x402. */
|
|
53
|
+
async function prepareBaseFunding(needsMint, allowSwap) {
|
|
54
|
+
if (!wallet_1.account)
|
|
55
|
+
throw new Error("Unlock the configured wallet before funding");
|
|
56
|
+
const fundingAccount = wallet_1.account;
|
|
57
|
+
const { publicClient } = (0, wallet_1.getFundingClients)();
|
|
58
|
+
if (await publicClient.getChainId() !== config_1.config.chain.id)
|
|
59
|
+
throw new Error("Funding RPC chain does not match the configured network");
|
|
60
|
+
const mintPrice = needsMint ? await publicClient.readContract({
|
|
61
|
+
address: config_1.config.miningAgentAddress,
|
|
62
|
+
abi: [{ name: "getMintPrice", type: "function", stateMutability: "view", inputs: [], outputs: [{ type: "uint256" }] }],
|
|
63
|
+
functionName: "getMintPrice",
|
|
64
|
+
}) : 0n;
|
|
65
|
+
const requirements = {
|
|
66
|
+
ethReserve: mintPrice + exports.MINT_GAS_RESERVE_ETH,
|
|
67
|
+
usdcTarget: requiresUsdc(needsMint) ? (0, viem_1.parseUnits)(String(constants_1.MIN_USDC), 6) : 0n,
|
|
68
|
+
swapGasReserve: SWAP_GAS_RESERVE_ETH,
|
|
69
|
+
};
|
|
70
|
+
const context = (0, context_1.getSignerContext)();
|
|
71
|
+
let swapFees;
|
|
72
|
+
try {
|
|
73
|
+
(0, context_1.setSignerContext)("fund");
|
|
74
|
+
const plan = await (0, funding_plan_1.prepareFunding)(requirements, {
|
|
75
|
+
balances: async () => {
|
|
76
|
+
const [eth, usdc] = await Promise.all([
|
|
77
|
+
publicClient.getBalance({ address: fundingAccount.address }),
|
|
78
|
+
requiresUsdc(needsMint) ? (0, uniswap_1.getUsdcBalance)(fundingAccount.address) : Promise.resolve(0n),
|
|
79
|
+
]);
|
|
80
|
+
return { eth, usdc };
|
|
81
|
+
},
|
|
82
|
+
quoteEth: uniswap_1.quoteEthForUsdc,
|
|
83
|
+
quoteSwapGas: async (eth, usdc) => {
|
|
84
|
+
swapFees = await (0, uniswap_1.quoteEthSwapFees)(eth, usdc);
|
|
85
|
+
return swapFees.feeReserve;
|
|
86
|
+
},
|
|
87
|
+
swapEth: async (eth, usdc) => {
|
|
88
|
+
ui.info("Funding", `Converting ${(0, viem_1.formatEther)(eth)} ETH to USDC; retaining the mint and gas reserve.`);
|
|
89
|
+
const result = await (0, uniswap_1.swapEthToUsdc)(eth, usdc, swapFees);
|
|
90
|
+
ui.ok(`Funding swap confirmed: ${result.txHash}`);
|
|
91
|
+
},
|
|
92
|
+
}, allowSwap);
|
|
93
|
+
return { ...plan, mintPrice, requirements };
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
(0, context_1.setSignerContext)(context);
|
|
97
|
+
}
|
|
98
|
+
}
|
package/dist/bridge/squid.js
CHANGED
|
@@ -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
|
-
|
|
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.
|
|
25
|
+
toToken: constants_1.TOKENS.base.nativeSquid,
|
|
25
26
|
srcDecimals: 6,
|
|
26
|
-
dstDecimals:
|
|
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
|
-
|
|
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
|
-
"
|
|
91
|
+
"Send ETH on Base directly instead. No deposit address was issued.");
|
|
87
92
|
}
|
|
88
|
-
|
|
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" ||
|
package/dist/bridge/uniswap.js
CHANGED
|
@@ -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/errors.js
CHANGED
|
@@ -4,12 +4,16 @@ exports.redactUrls = redactUrls;
|
|
|
4
4
|
exports.errorText = errorText;
|
|
5
5
|
exports.classifyError = classifyError;
|
|
6
6
|
const patterns = [
|
|
7
|
+
{
|
|
8
|
+
test: (m) => m.includes("payment outcome is unknown"),
|
|
9
|
+
classify: (msg) => ({ category: "fatal", userMessage: msg, recovery: "Check the service job/payment result before manually resuming. Do not repeat an unknown paid request." }),
|
|
10
|
+
},
|
|
7
11
|
{
|
|
8
12
|
test: (m) => m.includes("Policy denied:"),
|
|
9
13
|
classify: (msg) => ({
|
|
10
14
|
category: "setup",
|
|
11
15
|
userMessage: msg,
|
|
12
|
-
recovery: "Review `apow policy show
|
|
16
|
+
recovery: "Review `apow policy show` and the requested operation. Keep policy enforcement enabled.",
|
|
13
17
|
}),
|
|
14
18
|
},
|
|
15
19
|
{
|