@oracle-agent/oracle 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +98 -0
- package/LICENSE +202 -0
- package/README.md +384 -0
- package/SECURITY.md +89 -0
- package/SETUP.md +235 -0
- package/artifacts/inscription/oracle-was-here-preview.png +0 -0
- package/artifacts/inscription/oracle-was-here.svg +1 -0
- package/artifacts/specialist-packs/oracle-full-crypto.json +273 -0
- package/bin/desk-server.mjs +438 -0
- package/bin/oracle-data-mcp.mjs +603 -0
- package/bin/oracle-init.mjs +423 -0
- package/bin/oracle-public-server.mjs +36 -0
- package/bin/oracle-route.mjs +254 -0
- package/bin/oracle-scan.mjs +192 -0
- package/docs/adding-a-chain.md +229 -0
- package/docs/architecture.md +135 -0
- package/docs/profiles.md +132 -0
- package/examples/add-a-chain.mjs +65 -0
- package/examples/research-a-token.mjs +70 -0
- package/package.json +90 -0
- package/profiles/_template/SOUL.md +47 -0
- package/profiles/_template/profile.json +22 -0
- package/profiles/bitcoin-agent/SOUL.md +31 -0
- package/profiles/bitcoin-agent/profile.json +32 -0
- package/profiles/hyperliquid-agent/SOUL.md +34 -0
- package/profiles/hyperliquid-agent/profile.json +37 -0
- package/profiles/oracle/SOUL.md +65 -0
- package/profiles/oracle/profile.json +35 -0
- package/profiles/polymarket-agent/SOUL.md +35 -0
- package/profiles/polymarket-agent/profile.json +34 -0
- package/profiles/profile.schema.json +90 -0
- package/profiles/protocol-builder/SOUL.md +50 -0
- package/profiles/protocol-builder/profile.json +37 -0
- package/profiles/robinhood-agent/SOUL.md +45 -0
- package/profiles/robinhood-agent/profile.json +39 -0
- package/profiles/solana-agent/SOUL.md +37 -0
- package/profiles/solana-agent/profile.json +37 -0
- package/profiles/stable-agent/SOUL.md +43 -0
- package/profiles/stable-agent/profile.json +37 -0
- package/public/oracle-console/app.js +272 -0
- package/public/oracle-console/bitcoin-wallets.js +206 -0
- package/public/oracle-console/index.html +91 -0
- package/public/oracle-console/styles.css +239 -0
- package/public/oracle-splash/index.html +931 -0
- package/scripts/build-inscription.py +230 -0
- package/scripts/check-test-count.mjs +105 -0
- package/scripts/e2e-hl-markets.mjs +21 -0
- package/scripts/e2e-hl-perps.mjs +48 -0
- package/scripts/e2e-hypercore-staking.mjs +128 -0
- package/scripts/e2e-solana-bitcoin.mjs +183 -0
- package/scripts/public-api-scan.mjs +23 -0
- package/scripts/secret-scan.mjs +181 -0
- package/scripts/verify-v3-venues.mjs +192 -0
- package/skills/oracle-best-execution/SKILL.md +127 -0
- package/skills/oracle-bitcoin/SKILL.md +53 -0
- package/skills/oracle-chain-graphs-telegram-cards/SKILL.md +59 -0
- package/skills/oracle-circuit-breaker/SKILL.md +51 -0
- package/skills/oracle-contract-research/SKILL.md +55 -0
- package/skills/oracle-desk/SKILL.md +58 -0
- package/skills/oracle-dex-launch/SKILL.md +38 -0
- package/skills/oracle-grants/SKILL.md +69 -0
- package/skills/oracle-hypercore-staking/SKILL.md +57 -0
- package/skills/oracle-hyperliquid/SKILL.md +56 -0
- package/skills/oracle-meme-token-sniper/SKILL.md +73 -0
- package/skills/oracle-nft-gacha-launch/SKILL.md +48 -0
- package/skills/oracle-nft-mint-gas-war/SKILL.md +63 -0
- package/skills/oracle-polymarket/SKILL.md +60 -0
- package/skills/oracle-protocol-builder/SKILL.md +38 -0
- package/skills/oracle-protocol-security/SKILL.md +60 -0
- package/skills/oracle-public-product/SKILL.md +44 -0
- package/skills/oracle-receipts/SKILL.md +52 -0
- package/skills/oracle-rfq-tokenized-assets/SKILL.md +69 -0
- package/skills/oracle-smart-wallet-scanner/SKILL.md +49 -0
- package/skills/oracle-solana/SKILL.md +65 -0
- package/skills/oracle-solana-nft/SKILL.md +54 -0
- package/skills/oracle-token-research/SKILL.md +67 -0
- package/src/agent-auth.mjs +191 -0
- package/src/approval-guard.mjs +282 -0
- package/src/attestation-secret.mjs +88 -0
- package/src/audit-log.mjs +196 -0
- package/src/auto-slippage.mjs +378 -0
- package/src/capability-posture.mjs +125 -0
- package/src/chains.mjs +62 -0
- package/src/data/catalog.mjs +495 -0
- package/src/data/desk-data.mjs +623 -0
- package/src/data/http.mjs +200 -0
- package/src/data/provider-endpoint.mjs +94 -0
- package/src/data/providers/aerodrome.mjs +244 -0
- package/src/data/providers/balancer.mjs +208 -0
- package/src/data/providers/bitcoin-esplora.mjs +230 -0
- package/src/data/providers/bitcoin-meta.mjs +378 -0
- package/src/data/providers/blockscout.mjs +14 -0
- package/src/data/providers/bridges.mjs +241 -0
- package/src/data/providers/cowswap.mjs +501 -0
- package/src/data/providers/curve.mjs +200 -0
- package/src/data/providers/defillama.mjs +88 -0
- package/src/data/providers/dexscreener.mjs +43 -0
- package/src/data/providers/evm-rpc.mjs +203 -0
- package/src/data/providers/geckoterminal.mjs +34 -0
- package/src/data/providers/gmx.mjs +495 -0
- package/src/data/providers/hl-info.mjs +102 -0
- package/src/data/providers/hl-markets.mjs +210 -0
- package/src/data/providers/hl-perps.mjs +382 -0
- package/src/data/providers/hl-staking.mjs +352 -0
- package/src/data/providers/hl-ws.mjs +119 -0
- package/src/data/providers/hyperevm-dex.mjs +49 -0
- package/src/data/providers/jupiter.mjs +182 -0
- package/src/data/providers/lifi.mjs +150 -0
- package/src/data/providers/magiceden-sol.mjs +355 -0
- package/src/data/providers/morpho.mjs +173 -0
- package/src/data/providers/odos.mjs +155 -0
- package/src/data/providers/oneinch.mjs +173 -0
- package/src/data/providers/opensea-multichain.mjs +136 -0
- package/src/data/providers/opensea-nft.mjs +99 -0
- package/src/data/providers/paraswap.mjs +117 -0
- package/src/data/providers/pendle.mjs +187 -0
- package/src/data/providers/poly-public.mjs +96 -0
- package/src/data/providers/poly-ws.mjs +103 -0
- package/src/data/providers/rh-agent.mjs +59 -0
- package/src/data/providers/satflow.mjs +336 -0
- package/src/data/providers/solana-rpc.mjs +186 -0
- package/src/data/providers/uniswap-v3.mjs +303 -0
- package/src/data/providers/zerox.mjs +166 -0
- package/src/data/public-api-scan.mjs +61 -0
- package/src/data/quote-placeholder.mjs +31 -0
- package/src/exact-integer.mjs +72 -0
- package/src/exec-policy.mjs +444 -0
- package/src/flags.mjs +15 -0
- package/src/fresh-window.mjs +76 -0
- package/src/gmx-attestation.mjs +175 -0
- package/src/index.mjs +50 -0
- package/src/nft-gas-war-guard.mjs +139 -0
- package/src/onboarding/agent-keys.mjs +157 -0
- package/src/onboarding/index.mjs +18 -0
- package/src/onboarding/tiers.mjs +139 -0
- package/src/oracle-env.mjs +38 -0
- package/src/protocol-execution.mjs +84 -0
- package/src/public-api/buzz-integration.mjs +256 -0
- package/src/public-api/connect-agent.mjs +397 -0
- package/src/public-api/grants.mjs +142 -0
- package/src/public-api/http.mjs +374 -0
- package/src/public-control/aa-adapter.mjs +402 -0
- package/src/public-control/build-registry.mjs +227 -0
- package/src/public-control/bundler-client.mjs +372 -0
- package/src/public-control/grant-indexer.mjs +296 -0
- package/src/public-control/policy-render.mjs +69 -0
- package/src/public-control/policy-schema.mjs +318 -0
- package/src/public-control/runtime-config.mjs +265 -0
- package/src/public-control/session-key-model.mjs +374 -0
- package/src/public-control/session-orchestrator.mjs +412 -0
- package/src/route-attestation.mjs +132 -0
- package/src/router/best-execution.mjs +221 -0
- package/src/router/index.mjs +185 -0
- package/src/router/prepare-bridge.mjs +288 -0
- package/src/router/prepare-route.mjs +341 -0
- package/src/router/proposal.mjs +311 -0
- package/src/router/risk-classifier.mjs +119 -0
- package/src/router/route-sources.mjs +292 -0
- package/src/scanner/chains.config.mjs +381 -0
- package/src/scanner/contract.mjs +270 -0
- package/src/scanner/evm-scanner.mjs +394 -0
- package/src/scanner/index.mjs +9 -0
- package/src/scanner/v2-venue.mjs +335 -0
- package/src/scanner/v3-venue.mjs +290 -0
- package/src/scopes.mjs +44 -0
- package/src/sell-simulation.mjs +167 -0
- package/src/token-transfer-guard.mjs +188 -0
- package/src/vault-attestation.mjs +145 -0
- package/src/venues.mjs +206 -0
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
// Uniswap V3 QuoterV2 — exact-input quotes via eth_call (no API key).
|
|
2
|
+
// Chains: Ethereum, Base, Arbitrum. Read-only; never signs or swaps.
|
|
3
|
+
|
|
4
|
+
import { Interface, getAddress, isAddress } from "ethers";
|
|
5
|
+
import { rpcCall } from "./evm-rpc.mjs";
|
|
6
|
+
import { attachAutoSlippage, bindAutoSlippageGuardToCall } from "../../auto-slippage.mjs";
|
|
7
|
+
|
|
8
|
+
/** @type {Record<number, { quoter: string, weth: string, usdc: string, name: string }>} */
|
|
9
|
+
export const UNI_V3_CHAINS = {
|
|
10
|
+
1: {
|
|
11
|
+
name: "ethereum",
|
|
12
|
+
quoter: "0x61fFE014bA17989E743c5F6cB21bF9697530B21e",
|
|
13
|
+
router: "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",
|
|
14
|
+
weth: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
|
|
15
|
+
usdc: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
|
|
16
|
+
},
|
|
17
|
+
8453: {
|
|
18
|
+
name: "base",
|
|
19
|
+
quoter: "0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",
|
|
20
|
+
router: "0x2626664c2603336E57B271c5C0b26F421741e481",
|
|
21
|
+
weth: "0x4200000000000000000000000000000000000006",
|
|
22
|
+
usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
23
|
+
},
|
|
24
|
+
42161: {
|
|
25
|
+
name: "arbitrum",
|
|
26
|
+
quoter: "0x61fFE014bA17989E743c5F6cB21bF9697530B21e",
|
|
27
|
+
router: "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",
|
|
28
|
+
weth: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
|
|
29
|
+
usdc: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export const UNI_V3_FEE_TIERS = [100, 500, 3000, 10000];
|
|
34
|
+
|
|
35
|
+
const QUOTER_IFACE = new Interface([
|
|
36
|
+
"function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)",
|
|
37
|
+
"function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)",
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
const ROUTER_IFACE = new Interface([
|
|
41
|
+
"function exactInputSingle((address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)",
|
|
42
|
+
"function multicall(uint256 deadline,bytes[] data) payable returns (bytes[] results)",
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
const NATIVE = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
|
|
46
|
+
const ZERO = "0x0000000000000000000000000000000000000000";
|
|
47
|
+
|
|
48
|
+
function chainMeta(chainId) {
|
|
49
|
+
const id = Number(chainId);
|
|
50
|
+
const m = UNI_V3_CHAINS[id];
|
|
51
|
+
if (!m) {
|
|
52
|
+
throw new Error(
|
|
53
|
+
`uniswap-v3: unsupported chainId ${chainId} (supported: ${Object.keys(UNI_V3_CHAINS).join(", ")})`
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
return { chainId: id, ...m };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function normalizeToken(addr, chainId) {
|
|
60
|
+
const meta = UNI_V3_CHAINS[Number(chainId)];
|
|
61
|
+
if (!addr || addr === NATIVE || addr === ZERO || /^eth$/i.test(String(addr))) {
|
|
62
|
+
return getAddress(meta.weth);
|
|
63
|
+
}
|
|
64
|
+
const s = String(addr);
|
|
65
|
+
if (/^weth$/i.test(s)) return getAddress(meta.weth);
|
|
66
|
+
if (/^usdc$/i.test(s)) return getAddress(meta.usdc);
|
|
67
|
+
if (!isAddress(s)) throw new Error(`invalid token address: ${addr}`);
|
|
68
|
+
return getAddress(s);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function encodePath(tokens, fees) {
|
|
72
|
+
// path = token0 (20) + fee (3) + token1 (20) [+ fee + token2 ...]
|
|
73
|
+
if (tokens.length !== fees.length + 1) {
|
|
74
|
+
throw new Error("path: fees.length must be tokens.length - 1");
|
|
75
|
+
}
|
|
76
|
+
let hex = "0x";
|
|
77
|
+
for (let i = 0; i < fees.length; i++) {
|
|
78
|
+
hex += tokens[i].slice(2).toLowerCase();
|
|
79
|
+
hex += Number(fees[i]).toString(16).padStart(6, "0");
|
|
80
|
+
}
|
|
81
|
+
hex += tokens[tokens.length - 1].slice(2).toLowerCase();
|
|
82
|
+
return hex;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Quote exact-input single hop via QuoterV2.
|
|
87
|
+
* @param {object} q
|
|
88
|
+
* @param {number} q.chainId
|
|
89
|
+
* @param {string} [q.tokenIn] default WETH
|
|
90
|
+
* @param {string} [q.tokenOut] default USDC
|
|
91
|
+
* @param {string|number|bigint} q.amountIn raw wei/base units
|
|
92
|
+
* @param {number} [q.fee] 100|500|3000|10000 — if omitted, tries tiers best-out
|
|
93
|
+
*/
|
|
94
|
+
export async function uniV3QuoteExactIn(q = {}, opts = {}) {
|
|
95
|
+
const { chainId, quoter, router } = chainMeta(q.chainId ?? 8453);
|
|
96
|
+
const tokenIn = normalizeToken(q.tokenIn || "WETH", chainId);
|
|
97
|
+
const tokenOut = normalizeToken(q.tokenOut || UNI_V3_CHAINS[chainId].usdc, chainId);
|
|
98
|
+
const amountIn = BigInt(q.amountIn ?? 0);
|
|
99
|
+
if (amountIn <= 0n) throw new Error("amountIn required (raw base units)");
|
|
100
|
+
|
|
101
|
+
const fees =
|
|
102
|
+
q.fee != null
|
|
103
|
+
? [Number(q.fee)]
|
|
104
|
+
: q.tryFees === false
|
|
105
|
+
? [3000]
|
|
106
|
+
: [...UNI_V3_FEE_TIERS];
|
|
107
|
+
|
|
108
|
+
const results = [];
|
|
109
|
+
let best = null;
|
|
110
|
+
|
|
111
|
+
for (const fee of fees) {
|
|
112
|
+
const data = QUOTER_IFACE.encodeFunctionData("quoteExactInputSingle", [
|
|
113
|
+
{
|
|
114
|
+
tokenIn,
|
|
115
|
+
tokenOut,
|
|
116
|
+
amountIn,
|
|
117
|
+
fee,
|
|
118
|
+
sqrtPriceLimitX96: 0n,
|
|
119
|
+
},
|
|
120
|
+
]);
|
|
121
|
+
try {
|
|
122
|
+
const raw = await rpcCall(chainId, "eth_call", [{ to: quoter, data }, "latest"], opts);
|
|
123
|
+
if (!raw || raw === "0x") {
|
|
124
|
+
results.push({ fee, ok: false, error: "empty result" });
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const decoded = QUOTER_IFACE.decodeFunctionResult("quoteExactInputSingle", raw);
|
|
128
|
+
const row = {
|
|
129
|
+
fee,
|
|
130
|
+
ok: true,
|
|
131
|
+
amountOut: decoded[0].toString(),
|
|
132
|
+
sqrtPriceX96After: decoded[1].toString(),
|
|
133
|
+
initializedTicksCrossed: Number(decoded[2]),
|
|
134
|
+
gasEstimate: decoded[3].toString(),
|
|
135
|
+
};
|
|
136
|
+
results.push(row);
|
|
137
|
+
if (!best || BigInt(row.amountOut) > BigInt(best.amountOut)) best = row;
|
|
138
|
+
} catch (e) {
|
|
139
|
+
results.push({ fee, ok: false, error: String(e.message || e).slice(0, 160) });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (!best) {
|
|
144
|
+
const err = results.map((r) => `${r.fee}:${r.error || "fail"}`).join("; ");
|
|
145
|
+
throw new Error(`uniswap-v3 quote failed chain=${chainId}: ${err}`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return attachAutoSlippage({
|
|
149
|
+
venue: "uniswap-v3",
|
|
150
|
+
chainId,
|
|
151
|
+
chain: UNI_V3_CHAINS[chainId].name,
|
|
152
|
+
quoter,
|
|
153
|
+
tokenIn,
|
|
154
|
+
tokenOut,
|
|
155
|
+
amountIn: amountIn.toString(),
|
|
156
|
+
fee: best.fee,
|
|
157
|
+
amountOut: best.amountOut,
|
|
158
|
+
gasEstimate: best.gasEstimate,
|
|
159
|
+
sqrtPriceX96After: best.sqrtPriceX96After,
|
|
160
|
+
initializedTicksCrossed: best.initializedTicksCrossed,
|
|
161
|
+
triedFees: results,
|
|
162
|
+
best: true,
|
|
163
|
+
}, {
|
|
164
|
+
chainId,
|
|
165
|
+
venue: router,
|
|
166
|
+
amountOut: best.amountOut,
|
|
167
|
+
liquidityUsd: q.liquidityUsd,
|
|
168
|
+
priceChange5m: q.priceChange5m,
|
|
169
|
+
requestedCapBps: q.maxSlippageBps ?? q.slippageBps,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Multi-hop exact input. pathTokens + pathFees.
|
|
175
|
+
* e.g. tokens [WETH, USDC], fees [500]
|
|
176
|
+
*/
|
|
177
|
+
export async function uniV3QuoteExactInPath(q = {}, opts = {}) {
|
|
178
|
+
const { chainId, quoter, router } = chainMeta(q.chainId ?? 8453);
|
|
179
|
+
const tokens = (q.tokens || []).map((t) => normalizeToken(t, chainId));
|
|
180
|
+
const fees = (q.fees || []).map(Number);
|
|
181
|
+
if (tokens.length < 2) throw new Error("tokens[] need at least 2 addresses");
|
|
182
|
+
const amountIn = BigInt(q.amountIn ?? 0);
|
|
183
|
+
if (amountIn <= 0n) throw new Error("amountIn required");
|
|
184
|
+
|
|
185
|
+
const path = encodePath(tokens, fees);
|
|
186
|
+
const data = QUOTER_IFACE.encodeFunctionData("quoteExactInput", [path, amountIn]);
|
|
187
|
+
const raw = await rpcCall(chainId, "eth_call", [{ to: quoter, data }, "latest"], opts);
|
|
188
|
+
const decoded = QUOTER_IFACE.decodeFunctionResult("quoteExactInput", raw);
|
|
189
|
+
|
|
190
|
+
return attachAutoSlippage({
|
|
191
|
+
venue: "uniswap-v3",
|
|
192
|
+
chainId,
|
|
193
|
+
chain: UNI_V3_CHAINS[chainId].name,
|
|
194
|
+
quoter,
|
|
195
|
+
tokens,
|
|
196
|
+
fees,
|
|
197
|
+
path,
|
|
198
|
+
amountIn: amountIn.toString(),
|
|
199
|
+
amountOut: decoded[0].toString(),
|
|
200
|
+
gasEstimate: decoded[3].toString(),
|
|
201
|
+
}, {
|
|
202
|
+
chainId,
|
|
203
|
+
venue: router,
|
|
204
|
+
amountOut: decoded[0].toString(),
|
|
205
|
+
liquidityUsd: q.liquidityUsd,
|
|
206
|
+
priceChange5m: q.priceChange5m,
|
|
207
|
+
requestedCapBps: q.maxSlippageBps ?? q.slippageBps,
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Convenience: WETH → USDC for amountIn wei (default 0.001 ETH). */
|
|
212
|
+
export async function uniV3EthUsdc(q = {}, opts = {}) {
|
|
213
|
+
const chainId = Number(q.chainId ?? 8453);
|
|
214
|
+
const amountIn = q.amountIn ?? "1000000000000000"; // 0.001 ether
|
|
215
|
+
const quote = await uniV3QuoteExactIn(
|
|
216
|
+
{
|
|
217
|
+
chainId,
|
|
218
|
+
tokenIn: UNI_V3_CHAINS[chainId].weth,
|
|
219
|
+
tokenOut: UNI_V3_CHAINS[chainId].usdc,
|
|
220
|
+
amountIn,
|
|
221
|
+
fee: q.fee,
|
|
222
|
+
},
|
|
223
|
+
opts
|
|
224
|
+
);
|
|
225
|
+
const usdc = Number(quote.amountOut) / 1e6;
|
|
226
|
+
return { ...quote, amountOutUsdc: usdc, pair: "WETH/USDC" };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export async function uniV3PrepareExactIn(q = {}, opts = {}) {
|
|
230
|
+
const chainId = Number(q.chainId ?? 8453);
|
|
231
|
+
const meta = chainMeta(chainId);
|
|
232
|
+
const recipient = getAddress(q.recipient);
|
|
233
|
+
const inputRaw = String(q.tokenIn || "WETH");
|
|
234
|
+
const nativeInput = !q.tokenIn || inputRaw === NATIVE || inputRaw === ZERO || /^eth$/i.test(inputRaw);
|
|
235
|
+
const quote = await uniV3QuoteExactIn(q, opts);
|
|
236
|
+
const exact = ROUTER_IFACE.encodeFunctionData("exactInputSingle", [{
|
|
237
|
+
tokenIn: quote.tokenIn,
|
|
238
|
+
tokenOut: quote.tokenOut,
|
|
239
|
+
fee: quote.fee,
|
|
240
|
+
recipient,
|
|
241
|
+
amountIn: BigInt(quote.amountIn),
|
|
242
|
+
amountOutMinimum: BigInt(quote.amountOutMinimum),
|
|
243
|
+
sqrtPriceLimitX96: 0n,
|
|
244
|
+
}]);
|
|
245
|
+
const deadlineWindow = Math.min(600, Math.max(30, Number(q.deadlineSeconds ?? 300)));
|
|
246
|
+
const nowSeconds = Number(opts.nowSeconds ?? Math.floor(Date.now() / 1000));
|
|
247
|
+
const deadline = nowSeconds + deadlineWindow;
|
|
248
|
+
const data = ROUTER_IFACE.encodeFunctionData("multicall", [deadline, [exact]]);
|
|
249
|
+
return {
|
|
250
|
+
provider: "uniswap-v3",
|
|
251
|
+
calldataReady: true,
|
|
252
|
+
// NOT executable authority. The bytes are assembled but nothing is signed:
|
|
253
|
+
// the user's wallet is still the only thing that can authorize this. The
|
|
254
|
+
// previous `executionReady: true` read as "cleared to execute" and trained
|
|
255
|
+
// agents to treat a quote as permission.
|
|
256
|
+
requiresUserSignature: true,
|
|
257
|
+
signingReady: false,
|
|
258
|
+
broadcastReady: false,
|
|
259
|
+
chainId,
|
|
260
|
+
deadline,
|
|
261
|
+
quote,
|
|
262
|
+
autoSlippage: quote.autoSlippage,
|
|
263
|
+
requiresApproval: nativeInput ? null : {
|
|
264
|
+
token: quote.tokenIn,
|
|
265
|
+
spender: meta.router,
|
|
266
|
+
amount: quote.amountIn,
|
|
267
|
+
},
|
|
268
|
+
transaction: {
|
|
269
|
+
chainId,
|
|
270
|
+
from: recipient,
|
|
271
|
+
to: meta.router,
|
|
272
|
+
data,
|
|
273
|
+
value: nativeInput ? quote.amountIn : "0",
|
|
274
|
+
slippageGuard: bindAutoSlippageGuardToCall(quote.autoSlippage, { chainId, venue: meta.router, data }),
|
|
275
|
+
},
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export async function uniV3Health(opts = {}) {
|
|
280
|
+
const chainId = Number(opts.chainId ?? 8453);
|
|
281
|
+
try {
|
|
282
|
+
const q = await uniV3EthUsdc({ chainId, amountIn: "1000000000000000" }, opts);
|
|
283
|
+
return {
|
|
284
|
+
ok: true,
|
|
285
|
+
chainId,
|
|
286
|
+
fee: q.fee,
|
|
287
|
+
amountOutUsdc: q.amountOutUsdc,
|
|
288
|
+
midPxHint: q.amountOutUsdc / 0.001,
|
|
289
|
+
};
|
|
290
|
+
} catch (e) {
|
|
291
|
+
return { ok: false, chainId, error: String(e.message || e).slice(0, 200) };
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export async function uniV3Chains() {
|
|
296
|
+
return Object.entries(UNI_V3_CHAINS).map(([id, m]) => ({
|
|
297
|
+
chainId: Number(id),
|
|
298
|
+
name: m.name,
|
|
299
|
+
quoter: m.quoter,
|
|
300
|
+
weth: m.weth,
|
|
301
|
+
usdc: m.usdc,
|
|
302
|
+
}));
|
|
303
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// 0x Swap API v2 — price/quote. Requires ZEROX_API_KEY (or 0X_API_KEY).
|
|
2
|
+
|
|
3
|
+
import { httpJson } from "../http.mjs";
|
|
4
|
+
import { attachAutoSlippage, bindAutoSlippageGuardToCall, resolveAutoSlippage } from "../../auto-slippage.mjs";
|
|
5
|
+
import { resolveProviderEndpoint, credentialedHeaders } from "../provider-endpoint.mjs";
|
|
6
|
+
|
|
7
|
+
export const ZEROX_API = "https://api.0x.org";
|
|
8
|
+
|
|
9
|
+
function endpoint(opts = {}) {
|
|
10
|
+
return resolveProviderEndpoint({
|
|
11
|
+
provider: "zerox",
|
|
12
|
+
defaultUrl: ZEROX_API,
|
|
13
|
+
hosts: ["api.0x.org"],
|
|
14
|
+
url: opts.baseUrl || process.env.ZEROX_API_URL,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function base(opts = {}) {
|
|
19
|
+
return endpoint(opts).baseUrl;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function apiKey(opts = {}) {
|
|
23
|
+
return (
|
|
24
|
+
opts.apiKey ||
|
|
25
|
+
process.env.ZEROX_API_KEY ||
|
|
26
|
+
process.env.OX_API_KEY ||
|
|
27
|
+
process.env["0X_API_KEY"] ||
|
|
28
|
+
""
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function headers(opts = {}) {
|
|
33
|
+
return credentialedHeaders(
|
|
34
|
+
{ "0x-version": "v2", accept: "application/json" },
|
|
35
|
+
{ "0x-api-key": apiKey(opts) },
|
|
36
|
+
endpoint(opts).trusted
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function zeroxHealth(opts = {}) {
|
|
41
|
+
if (!apiKey(opts)) {
|
|
42
|
+
return { ok: false, configured: false, error: "ZEROX_API_KEY not set" };
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
const q = await zeroxPrice(
|
|
46
|
+
{
|
|
47
|
+
chainId: 8453,
|
|
48
|
+
sellToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
|
|
49
|
+
buyToken: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
50
|
+
sellAmount: "1000000000000000",
|
|
51
|
+
},
|
|
52
|
+
opts
|
|
53
|
+
);
|
|
54
|
+
return { ok: true, configured: true, buyAmount: q.buyAmount || q.grossBuyAmount };
|
|
55
|
+
} catch (e) {
|
|
56
|
+
return { ok: false, configured: true, error: String(e.message || e).slice(0, 160) };
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Indicative price (no firm quote). */
|
|
61
|
+
export async function zeroxPrice(q = {}, opts = {}) {
|
|
62
|
+
if (!apiKey(opts)) throw new Error("ZEROX_API_KEY required for 0x");
|
|
63
|
+
const {
|
|
64
|
+
chainId = 8453,
|
|
65
|
+
sellToken,
|
|
66
|
+
buyToken,
|
|
67
|
+
sellAmount,
|
|
68
|
+
taker,
|
|
69
|
+
} = q;
|
|
70
|
+
if (!sellToken || !buyToken || !sellAmount) {
|
|
71
|
+
throw new Error("zeroxPrice requires sellToken, buyToken, sellAmount");
|
|
72
|
+
}
|
|
73
|
+
const params = new URLSearchParams({
|
|
74
|
+
chainId: String(chainId),
|
|
75
|
+
sellToken,
|
|
76
|
+
buyToken,
|
|
77
|
+
sellAmount: String(sellAmount),
|
|
78
|
+
});
|
|
79
|
+
if (taker) params.set("taker", taker);
|
|
80
|
+
return httpJson(`${base(opts)}/swap/allowance-holder/price?${params}`, {
|
|
81
|
+
headers: headers(opts),
|
|
82
|
+
fetchImpl: opts.fetchImpl,
|
|
83
|
+
timeoutMs: opts.timeoutMs ?? 15_000,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Firm quote (may include transaction). */
|
|
88
|
+
export async function zeroxQuote(q = {}, opts = {}) {
|
|
89
|
+
if (!apiKey(opts)) throw new Error("ZEROX_API_KEY required for 0x");
|
|
90
|
+
const {
|
|
91
|
+
chainId = 8453,
|
|
92
|
+
sellToken,
|
|
93
|
+
buyToken,
|
|
94
|
+
sellAmount,
|
|
95
|
+
taker,
|
|
96
|
+
} = q;
|
|
97
|
+
if (!sellToken || !buyToken || !sellAmount) {
|
|
98
|
+
throw new Error("zeroxQuote requires sellToken, buyToken, sellAmount");
|
|
99
|
+
}
|
|
100
|
+
const selected = resolveAutoSlippage({
|
|
101
|
+
liquidityUsd: q.liquidityUsd,
|
|
102
|
+
priceChange5m: q.priceChange5m,
|
|
103
|
+
requestedCapBps: q.maxSlippageBps ?? q.slippageBps,
|
|
104
|
+
});
|
|
105
|
+
if (!selected.executable) {
|
|
106
|
+
throw new Error(`0x: route requires ${selected.requiredBps} bps above cap ${selected.capBps}`);
|
|
107
|
+
}
|
|
108
|
+
const params = new URLSearchParams({
|
|
109
|
+
chainId: String(chainId),
|
|
110
|
+
sellToken,
|
|
111
|
+
buyToken,
|
|
112
|
+
sellAmount: String(sellAmount),
|
|
113
|
+
slippageBps: String(selected.selectedBps),
|
|
114
|
+
});
|
|
115
|
+
if (taker) params.set("taker", taker);
|
|
116
|
+
const result = await httpJson(`${base(opts)}/swap/allowance-holder/quote?${params}`, {
|
|
117
|
+
headers: headers(opts),
|
|
118
|
+
fetchImpl: opts.fetchImpl,
|
|
119
|
+
timeoutMs: opts.timeoutMs ?? 15_000,
|
|
120
|
+
});
|
|
121
|
+
const amountOut = result?.buyAmount || result?.grossBuyAmount;
|
|
122
|
+
if (!amountOut) return { ...result, autoSlippagePolicy: selected };
|
|
123
|
+
return attachAutoSlippage(result, {
|
|
124
|
+
chainId,
|
|
125
|
+
venue: result?.transaction?.to || result?.to || "0x",
|
|
126
|
+
amountOut,
|
|
127
|
+
liquidityUsd: q.liquidityUsd,
|
|
128
|
+
priceChange5m: q.priceChange5m,
|
|
129
|
+
requestedCapBps: q.maxSlippageBps ?? q.slippageBps,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function zeroxPrepare(q = {}, opts = {}) {
|
|
134
|
+
if (!q.taker) throw new Error("0x: taker required for executable prepare");
|
|
135
|
+
const quote = await zeroxQuote(q, opts);
|
|
136
|
+
const tx = quote?.transaction;
|
|
137
|
+
if (!tx?.to || !tx?.data) throw new Error("0x: firm quote returned no transaction");
|
|
138
|
+
const chainId = Number(q.chainId ?? 8453);
|
|
139
|
+
const spender = quote?.issues?.allowance?.spender || quote?.allowanceTarget;
|
|
140
|
+
return {
|
|
141
|
+
provider: "zerox",
|
|
142
|
+
calldataReady: true,
|
|
143
|
+
// NOT executable authority. The bytes are assembled but nothing is signed:
|
|
144
|
+
// the user's wallet is still the only thing that can authorize this. The
|
|
145
|
+
// previous `executionReady: true` read as "cleared to execute" and trained
|
|
146
|
+
// agents to treat a quote as permission.
|
|
147
|
+
requiresUserSignature: true,
|
|
148
|
+
signingReady: false,
|
|
149
|
+
broadcastReady: false,
|
|
150
|
+
chainId,
|
|
151
|
+
quote,
|
|
152
|
+
autoSlippage: quote.autoSlippage,
|
|
153
|
+
requiresApproval: quote?.issues?.allowance?.actual != null && BigInt(quote.issues.allowance.actual) < BigInt(q.sellAmount)
|
|
154
|
+
? { token: q.sellToken, spender, amount: String(q.sellAmount) }
|
|
155
|
+
: null,
|
|
156
|
+
transaction: {
|
|
157
|
+
chainId,
|
|
158
|
+
from: q.taker,
|
|
159
|
+
to: tx.to,
|
|
160
|
+
data: tx.data,
|
|
161
|
+
value: tx.value ?? "0x0",
|
|
162
|
+
...(tx.gas != null ? { gasLimit: tx.gas } : {}),
|
|
163
|
+
slippageGuard: bindAutoSlippageGuardToCall(quote.autoSlippage, { chainId, venue: tx.to, data: tx.data }),
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { dataCatalog, dataHealth } from "./desk-data.mjs";
|
|
2
|
+
|
|
3
|
+
export const COVERED_CHAINS = Object.freeze({
|
|
4
|
+
1: "Ethereum",
|
|
5
|
+
10: "Optimism",
|
|
6
|
+
56: "BNB Chain",
|
|
7
|
+
137: "Polygon",
|
|
8
|
+
988: "Stable",
|
|
9
|
+
999: "HyperEVM",
|
|
10
|
+
2741: "Abstract",
|
|
11
|
+
4663: "Robinhood Chain",
|
|
12
|
+
8453: "Base",
|
|
13
|
+
42161: "Arbitrum",
|
|
14
|
+
43114: "Avalanche",
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
function providerStatus(record) {
|
|
18
|
+
if (!record) return "not-probed";
|
|
19
|
+
if (!record.ok) return "down";
|
|
20
|
+
if (record.detail?.configured === false) return "key-missing";
|
|
21
|
+
if (record.detail?.ok === false) return "degraded";
|
|
22
|
+
return "healthy";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function buildPublicApiCoverage(catalog, health) {
|
|
26
|
+
const globals = catalog.filter((p) => !p.chainIds.length).map((p) => p.id);
|
|
27
|
+
const providers = Object.fromEntries(catalog.map((p) => [p.id, {
|
|
28
|
+
venue: p.venue,
|
|
29
|
+
auth: p.auth,
|
|
30
|
+
chainIds: p.chainIds,
|
|
31
|
+
ops: p.ops,
|
|
32
|
+
description: p.description,
|
|
33
|
+
status: providerStatus(health?.providers?.[p.id]),
|
|
34
|
+
probe: health?.providers?.[p.id] || null,
|
|
35
|
+
}]));
|
|
36
|
+
const chains = {};
|
|
37
|
+
for (const [chainId, name] of Object.entries(COVERED_CHAINS)) {
|
|
38
|
+
const id = Number(chainId);
|
|
39
|
+
const explicit = catalog.filter((p) => p.chainIds.includes(id)).map((p) => p.id);
|
|
40
|
+
chains[chainId] = {
|
|
41
|
+
name,
|
|
42
|
+
providers: [...new Set([...globals, ...explicit])],
|
|
43
|
+
explicitProviders: explicit,
|
|
44
|
+
failClosed: explicit.length === 0,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
generatedAt: health?.when || new Date().toISOString(),
|
|
49
|
+
coveredChainCount: Object.keys(COVERED_CHAINS).length,
|
|
50
|
+
providerCount: catalog.length,
|
|
51
|
+
globals,
|
|
52
|
+
chains,
|
|
53
|
+
providers,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function scanPublicApis({ providers, timeoutMs = 12_000 } = {}) {
|
|
58
|
+
const catalog = dataCatalog();
|
|
59
|
+
const health = await dataHealth({ providers, timeoutMs });
|
|
60
|
+
return buildPublicApiCoverage(catalog, health);
|
|
61
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Placeholder addresses for quote-only provider calls.
|
|
2
|
+
//
|
|
3
|
+
// Several aggregator APIs (LI.FI, CoW, bridge quoters) require a `from`/`user`
|
|
4
|
+
// address to price a route, even when nothing will be signed. Hardcoding a real
|
|
5
|
+
// operator wallet as that default is a privacy and correctness bug: public users
|
|
6
|
+
// would silently quote against someone else's account, and balance-aware routers
|
|
7
|
+
// can return routes tailored to that stranger's holdings.
|
|
8
|
+
//
|
|
9
|
+
// So: callers SHOULD pass their own address. When they don't, we fall back to a
|
|
10
|
+
// well-known burn/zero-ish placeholder that holds nothing and signs nothing.
|
|
11
|
+
//
|
|
12
|
+
// vitalik.eth is deliberately NOT used here either -- a placeholder must be
|
|
13
|
+
// obviously inert, not a real person's account.
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* ERC-191 "dead" address. Universally recognizable as a placeholder, holds no
|
|
17
|
+
* meaningful balance, and cannot sign. Safe default for price-only queries.
|
|
18
|
+
*/
|
|
19
|
+
export const QUOTE_PLACEHOLDER_ADDRESS =
|
|
20
|
+
"0x000000000000000000000000000000000000dEaD";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Resolve the address to use for a quote-only request.
|
|
24
|
+
*
|
|
25
|
+
* @param {string} [preferred] caller-supplied address (their own wallet)
|
|
26
|
+
* @returns {string} the caller's address when usable, else the inert placeholder
|
|
27
|
+
*/
|
|
28
|
+
export function quoteAddress(preferred) {
|
|
29
|
+
const v = String(preferred || "").trim();
|
|
30
|
+
return /^0x[0-9a-fA-F]{40}$/.test(v) ? v : QUOTE_PLACEHOLDER_ADDRESS;
|
|
31
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Exact integer parsing for anything that bounds money.
|
|
2
|
+
//
|
|
3
|
+
// A JS number cannot represent every uint256, and above 2^53 it silently
|
|
4
|
+
// rounds — usually UPWARD, which widens a cap past what the user wrote.
|
|
5
|
+
// `9007199254740995` becomes `...996`. Every guard, allowance, and policy
|
|
6
|
+
// ceiling must therefore refuse unsafe numbers rather than quietly storing a
|
|
7
|
+
// different value than the caller asked for.
|
|
8
|
+
//
|
|
9
|
+
// This lives in one place because the same bug was found independently in
|
|
10
|
+
// token-transfer-guard, approval-guard, session grants, and exec-policy.
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Parse a value into an exact non-negative BigInt.
|
|
14
|
+
* Accepts: decimal string, BigInt, or a safe-integer number.
|
|
15
|
+
* Refuses: non-integers, unsafe numbers, and unparseable input.
|
|
16
|
+
*/
|
|
17
|
+
export function exactBigInt(value, label = "amount") {
|
|
18
|
+
if (typeof value === "bigint") return value;
|
|
19
|
+
|
|
20
|
+
if (typeof value === "number") {
|
|
21
|
+
if (!Number.isInteger(value)) {
|
|
22
|
+
throw new Error(`${label} must be an integer`);
|
|
23
|
+
}
|
|
24
|
+
if (!Number.isSafeInteger(value)) {
|
|
25
|
+
throw new Error(
|
|
26
|
+
`${label} exceeds safe integer precision — pass it as a decimal string or BigInt so the exact value is preserved`
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
return BigInt(value);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const text = String(value ?? "").trim();
|
|
33
|
+
if (text === "") throw new Error(`${label} is required`);
|
|
34
|
+
// Reject scientific notation and floats outright: BigInt("1e3") throws, but
|
|
35
|
+
// Number("1e3") would silently succeed if a caller coerced first.
|
|
36
|
+
if (!/^-?\d+$/.test(text) && !/^0x[0-9a-fA-F]+$/.test(text)) {
|
|
37
|
+
throw new Error(`${label} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(text)}`);
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
return BigInt(text);
|
|
41
|
+
} catch {
|
|
42
|
+
throw new Error(`${label} must be an integer, got ${JSON.stringify(text)}`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** As exactBigInt, but also requires the value to be strictly positive. */
|
|
47
|
+
export function exactPositiveBigInt(value, label = "amount") {
|
|
48
|
+
const n = exactBigInt(value, label);
|
|
49
|
+
if (n <= 0n) throw new Error(`${label} must be positive`);
|
|
50
|
+
return n;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Convert a decimal string to a scaled integer WITHOUT floats.
|
|
55
|
+
* `toScaledInteger("1.5", 6)` -> 1500000n, and `"01.5"` -> 1500000n.
|
|
56
|
+
* Leading zeros, missing fractions, and long fractions are all handled by
|
|
57
|
+
* string arithmetic, so magnitude never affects the scale.
|
|
58
|
+
*/
|
|
59
|
+
export function toScaledInteger(value, decimals, label = "amount") {
|
|
60
|
+
const text = String(value ?? "").trim();
|
|
61
|
+
if (!/^-?\d*(\.\d+)?$/.test(text) || text === "" || text === "." || text === "-") {
|
|
62
|
+
throw new Error(`${label} must be a decimal number, got ${JSON.stringify(text)}`);
|
|
63
|
+
}
|
|
64
|
+
const negative = text.startsWith("-");
|
|
65
|
+
const body = negative ? text.slice(1) : text;
|
|
66
|
+
const [intPart = "0", fracPart = ""] = body.split(".");
|
|
67
|
+
if (fracPart.length > decimals) {
|
|
68
|
+
throw new Error(`${label} has more than ${decimals} decimal places, which would lose precision`);
|
|
69
|
+
}
|
|
70
|
+
const scaled = BigInt((intPart || "0") + fracPart.padEnd(decimals, "0"));
|
|
71
|
+
return negative ? -scaled : scaled;
|
|
72
|
+
}
|