@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.
Files changed (169) hide show
  1. package/CONTRIBUTING.md +98 -0
  2. package/LICENSE +202 -0
  3. package/README.md +384 -0
  4. package/SECURITY.md +89 -0
  5. package/SETUP.md +235 -0
  6. package/artifacts/inscription/oracle-was-here-preview.png +0 -0
  7. package/artifacts/inscription/oracle-was-here.svg +1 -0
  8. package/artifacts/specialist-packs/oracle-full-crypto.json +273 -0
  9. package/bin/desk-server.mjs +438 -0
  10. package/bin/oracle-data-mcp.mjs +603 -0
  11. package/bin/oracle-init.mjs +423 -0
  12. package/bin/oracle-public-server.mjs +36 -0
  13. package/bin/oracle-route.mjs +254 -0
  14. package/bin/oracle-scan.mjs +192 -0
  15. package/docs/adding-a-chain.md +229 -0
  16. package/docs/architecture.md +135 -0
  17. package/docs/profiles.md +132 -0
  18. package/examples/add-a-chain.mjs +65 -0
  19. package/examples/research-a-token.mjs +70 -0
  20. package/package.json +90 -0
  21. package/profiles/_template/SOUL.md +47 -0
  22. package/profiles/_template/profile.json +22 -0
  23. package/profiles/bitcoin-agent/SOUL.md +31 -0
  24. package/profiles/bitcoin-agent/profile.json +32 -0
  25. package/profiles/hyperliquid-agent/SOUL.md +34 -0
  26. package/profiles/hyperliquid-agent/profile.json +37 -0
  27. package/profiles/oracle/SOUL.md +65 -0
  28. package/profiles/oracle/profile.json +35 -0
  29. package/profiles/polymarket-agent/SOUL.md +35 -0
  30. package/profiles/polymarket-agent/profile.json +34 -0
  31. package/profiles/profile.schema.json +90 -0
  32. package/profiles/protocol-builder/SOUL.md +50 -0
  33. package/profiles/protocol-builder/profile.json +37 -0
  34. package/profiles/robinhood-agent/SOUL.md +45 -0
  35. package/profiles/robinhood-agent/profile.json +39 -0
  36. package/profiles/solana-agent/SOUL.md +37 -0
  37. package/profiles/solana-agent/profile.json +37 -0
  38. package/profiles/stable-agent/SOUL.md +43 -0
  39. package/profiles/stable-agent/profile.json +37 -0
  40. package/public/oracle-console/app.js +272 -0
  41. package/public/oracle-console/bitcoin-wallets.js +206 -0
  42. package/public/oracle-console/index.html +91 -0
  43. package/public/oracle-console/styles.css +239 -0
  44. package/public/oracle-splash/index.html +931 -0
  45. package/scripts/build-inscription.py +230 -0
  46. package/scripts/check-test-count.mjs +105 -0
  47. package/scripts/e2e-hl-markets.mjs +21 -0
  48. package/scripts/e2e-hl-perps.mjs +48 -0
  49. package/scripts/e2e-hypercore-staking.mjs +128 -0
  50. package/scripts/e2e-solana-bitcoin.mjs +183 -0
  51. package/scripts/public-api-scan.mjs +23 -0
  52. package/scripts/secret-scan.mjs +181 -0
  53. package/scripts/verify-v3-venues.mjs +192 -0
  54. package/skills/oracle-best-execution/SKILL.md +127 -0
  55. package/skills/oracle-bitcoin/SKILL.md +53 -0
  56. package/skills/oracle-chain-graphs-telegram-cards/SKILL.md +59 -0
  57. package/skills/oracle-circuit-breaker/SKILL.md +51 -0
  58. package/skills/oracle-contract-research/SKILL.md +55 -0
  59. package/skills/oracle-desk/SKILL.md +58 -0
  60. package/skills/oracle-dex-launch/SKILL.md +38 -0
  61. package/skills/oracle-grants/SKILL.md +69 -0
  62. package/skills/oracle-hypercore-staking/SKILL.md +57 -0
  63. package/skills/oracle-hyperliquid/SKILL.md +56 -0
  64. package/skills/oracle-meme-token-sniper/SKILL.md +73 -0
  65. package/skills/oracle-nft-gacha-launch/SKILL.md +48 -0
  66. package/skills/oracle-nft-mint-gas-war/SKILL.md +63 -0
  67. package/skills/oracle-polymarket/SKILL.md +60 -0
  68. package/skills/oracle-protocol-builder/SKILL.md +38 -0
  69. package/skills/oracle-protocol-security/SKILL.md +60 -0
  70. package/skills/oracle-public-product/SKILL.md +44 -0
  71. package/skills/oracle-receipts/SKILL.md +52 -0
  72. package/skills/oracle-rfq-tokenized-assets/SKILL.md +69 -0
  73. package/skills/oracle-smart-wallet-scanner/SKILL.md +49 -0
  74. package/skills/oracle-solana/SKILL.md +65 -0
  75. package/skills/oracle-solana-nft/SKILL.md +54 -0
  76. package/skills/oracle-token-research/SKILL.md +67 -0
  77. package/src/agent-auth.mjs +191 -0
  78. package/src/approval-guard.mjs +282 -0
  79. package/src/attestation-secret.mjs +88 -0
  80. package/src/audit-log.mjs +196 -0
  81. package/src/auto-slippage.mjs +378 -0
  82. package/src/capability-posture.mjs +125 -0
  83. package/src/chains.mjs +62 -0
  84. package/src/data/catalog.mjs +495 -0
  85. package/src/data/desk-data.mjs +623 -0
  86. package/src/data/http.mjs +200 -0
  87. package/src/data/provider-endpoint.mjs +94 -0
  88. package/src/data/providers/aerodrome.mjs +244 -0
  89. package/src/data/providers/balancer.mjs +208 -0
  90. package/src/data/providers/bitcoin-esplora.mjs +230 -0
  91. package/src/data/providers/bitcoin-meta.mjs +378 -0
  92. package/src/data/providers/blockscout.mjs +14 -0
  93. package/src/data/providers/bridges.mjs +241 -0
  94. package/src/data/providers/cowswap.mjs +501 -0
  95. package/src/data/providers/curve.mjs +200 -0
  96. package/src/data/providers/defillama.mjs +88 -0
  97. package/src/data/providers/dexscreener.mjs +43 -0
  98. package/src/data/providers/evm-rpc.mjs +203 -0
  99. package/src/data/providers/geckoterminal.mjs +34 -0
  100. package/src/data/providers/gmx.mjs +495 -0
  101. package/src/data/providers/hl-info.mjs +102 -0
  102. package/src/data/providers/hl-markets.mjs +210 -0
  103. package/src/data/providers/hl-perps.mjs +382 -0
  104. package/src/data/providers/hl-staking.mjs +352 -0
  105. package/src/data/providers/hl-ws.mjs +119 -0
  106. package/src/data/providers/hyperevm-dex.mjs +49 -0
  107. package/src/data/providers/jupiter.mjs +182 -0
  108. package/src/data/providers/lifi.mjs +150 -0
  109. package/src/data/providers/magiceden-sol.mjs +355 -0
  110. package/src/data/providers/morpho.mjs +173 -0
  111. package/src/data/providers/odos.mjs +155 -0
  112. package/src/data/providers/oneinch.mjs +173 -0
  113. package/src/data/providers/opensea-multichain.mjs +136 -0
  114. package/src/data/providers/opensea-nft.mjs +99 -0
  115. package/src/data/providers/paraswap.mjs +117 -0
  116. package/src/data/providers/pendle.mjs +187 -0
  117. package/src/data/providers/poly-public.mjs +96 -0
  118. package/src/data/providers/poly-ws.mjs +103 -0
  119. package/src/data/providers/rh-agent.mjs +59 -0
  120. package/src/data/providers/satflow.mjs +336 -0
  121. package/src/data/providers/solana-rpc.mjs +186 -0
  122. package/src/data/providers/uniswap-v3.mjs +303 -0
  123. package/src/data/providers/zerox.mjs +166 -0
  124. package/src/data/public-api-scan.mjs +61 -0
  125. package/src/data/quote-placeholder.mjs +31 -0
  126. package/src/exact-integer.mjs +72 -0
  127. package/src/exec-policy.mjs +444 -0
  128. package/src/flags.mjs +15 -0
  129. package/src/fresh-window.mjs +76 -0
  130. package/src/gmx-attestation.mjs +175 -0
  131. package/src/index.mjs +50 -0
  132. package/src/nft-gas-war-guard.mjs +139 -0
  133. package/src/onboarding/agent-keys.mjs +157 -0
  134. package/src/onboarding/index.mjs +18 -0
  135. package/src/onboarding/tiers.mjs +139 -0
  136. package/src/oracle-env.mjs +38 -0
  137. package/src/protocol-execution.mjs +84 -0
  138. package/src/public-api/buzz-integration.mjs +256 -0
  139. package/src/public-api/connect-agent.mjs +397 -0
  140. package/src/public-api/grants.mjs +142 -0
  141. package/src/public-api/http.mjs +374 -0
  142. package/src/public-control/aa-adapter.mjs +402 -0
  143. package/src/public-control/build-registry.mjs +227 -0
  144. package/src/public-control/bundler-client.mjs +372 -0
  145. package/src/public-control/grant-indexer.mjs +296 -0
  146. package/src/public-control/policy-render.mjs +69 -0
  147. package/src/public-control/policy-schema.mjs +318 -0
  148. package/src/public-control/runtime-config.mjs +265 -0
  149. package/src/public-control/session-key-model.mjs +374 -0
  150. package/src/public-control/session-orchestrator.mjs +412 -0
  151. package/src/route-attestation.mjs +132 -0
  152. package/src/router/best-execution.mjs +221 -0
  153. package/src/router/index.mjs +185 -0
  154. package/src/router/prepare-bridge.mjs +288 -0
  155. package/src/router/prepare-route.mjs +341 -0
  156. package/src/router/proposal.mjs +311 -0
  157. package/src/router/risk-classifier.mjs +119 -0
  158. package/src/router/route-sources.mjs +292 -0
  159. package/src/scanner/chains.config.mjs +381 -0
  160. package/src/scanner/contract.mjs +270 -0
  161. package/src/scanner/evm-scanner.mjs +394 -0
  162. package/src/scanner/index.mjs +9 -0
  163. package/src/scanner/v2-venue.mjs +335 -0
  164. package/src/scanner/v3-venue.mjs +290 -0
  165. package/src/scopes.mjs +44 -0
  166. package/src/sell-simulation.mjs +167 -0
  167. package/src/token-transfer-guard.mjs +188 -0
  168. package/src/vault-attestation.mjs +145 -0
  169. package/src/venues.mjs +206 -0
@@ -0,0 +1,200 @@
1
+ // Tiny HTTP helpers for the read-only data plane. No signing. No secrets logged.
2
+ //
3
+ // Optimizations that matter for a self-hoster hitting public rate limits:
4
+ // - bounded retry with Retry-After support on 429 / 502 / 503 / 504
5
+ // - single-flight dedupe so N concurrent identical GETs cost ONE upstream call
6
+ // - both are opt-out via opts.retries = 0 / opts.dedupe = false
7
+ //
8
+ // SECURITY: the dedupe key binds the FULL credential (hashed), not merely whether
9
+ // one was present. Keying on presence alone lets two callers with different API
10
+ // keys collapse into one upstream request, so the second caller receives data
11
+ // fetched with the first caller's credential. Found in pre-public red team.
12
+
13
+ import { createHash } from "node:crypto";
14
+
15
+ const RETRYABLE_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);
16
+ // Methods safe to replay when the transport failed and we cannot know whether
17
+ // the server already applied the request.
18
+ const IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
19
+ const DEFAULT_RETRIES = 2;
20
+ const MAX_BACKOFF_MS = 4_000;
21
+
22
+ // Headers that identify the CALLER. Two requests may only share a deduped
23
+ // in-flight response when every one of these matches exactly.
24
+ // Any header that distinguishes one caller's credentials from another's. If a
25
+ // credential header is MISSING from this list, two different users' requests
26
+ // hash identically and the in-flight dedupe collapses them into one — user B
27
+ // receives a response fetched with user A's key. Enumerating providers here is
28
+ // fragile, so the matcher below also treats anything key/token/secret-shaped as
29
+ // identity-bearing.
30
+ const IDENTITY_HEADERS = [
31
+ "authorization",
32
+ "x-api-key",
33
+ "x-tensor-api-key",
34
+ "0x-api-key",
35
+ "api-key",
36
+ "cookie",
37
+ "proxy-authorization",
38
+ ];
39
+
40
+ const inflight = new Map();
41
+
42
+ /**
43
+ * Derive a dedupe key that is safe to hold in memory: credential material is
44
+ * hashed, never stored raw, so the cache cannot become a secret-disclosure
45
+ * surface (heap dump, debugger, accidental log of the map).
46
+ */
47
+ function dedupeKey(method, url, headers) {
48
+ const lower = {};
49
+ for (const [k, v] of Object.entries(headers || {})) lower[k.toLowerCase()] = v;
50
+
51
+ // Structural, not just the known list: ANY header whose name looks like it
52
+ // carries a credential participates in the fingerprint. A fixed enumeration
53
+ // silently fails the moment a provider uses a new header name — that is how
54
+ // `0x-api-key` was omitted, which collapsed two users' 0x requests into one
55
+ // and served user B a response fetched with user A's key.
56
+ const credentialShaped = Object.keys(lower).filter((h) =>
57
+ /(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(h)
58
+ );
59
+ const names = [...new Set([...IDENTITY_HEADERS, ...credentialShaped])].sort();
60
+ const identity = names.map((h) => `${h}=${lower[h] ?? ""}`).join("\n");
61
+ const fingerprint = createHash("sha256").update(identity).digest("hex").slice(0, 32);
62
+ return `${method} ${url} ${fingerprint}`;
63
+ }
64
+
65
+ function backoffMs(attempt, retryAfterHeader) {
66
+ const retryAfter = Number(retryAfterHeader);
67
+ if (Number.isFinite(retryAfter) && retryAfter > 0) {
68
+ return Math.min(retryAfter * 1000, MAX_BACKOFF_MS);
69
+ }
70
+ const base = Math.min(250 * 2 ** attempt, MAX_BACKOFF_MS);
71
+ return base + Math.floor(Math.random() * 100);
72
+ }
73
+
74
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
75
+
76
+ async function once(url, { fetchImpl, method, headers, body, timeoutMs }) {
77
+ const ac = new AbortController();
78
+ const t = setTimeout(() => ac.abort(), timeoutMs);
79
+ try {
80
+ const res = await fetchImpl(url, { method, headers, body, signal: ac.signal });
81
+ const text = await res.text();
82
+ let json = null;
83
+ if (text) {
84
+ try {
85
+ json = JSON.parse(text);
86
+ } catch {
87
+ json = null;
88
+ }
89
+ }
90
+ if (!res.ok) {
91
+ const err = new Error(`HTTP ${res.status} ${method} ${url}`);
92
+ err.status = res.status;
93
+ err.retryAfter = res.headers?.get?.("retry-after") ?? null;
94
+ err.body = json ?? text.slice(0, 300);
95
+ throw err;
96
+ }
97
+ return json ?? text;
98
+ } finally {
99
+ clearTimeout(t);
100
+ }
101
+ }
102
+
103
+ /**
104
+ * @param {string} url
105
+ * @param {{ method?: string, headers?: Record<string,string>, body?: any, timeoutMs?: number, fetchImpl?: typeof fetch, retries?: number, dedupe?: boolean }} [opts]
106
+ */
107
+ export async function httpJson(url, opts = {}) {
108
+ const fetchImpl = opts.fetchImpl || globalThis.fetch;
109
+ if (typeof fetchImpl !== "function") {
110
+ throw new Error("fetch unavailable — pass opts.fetchImpl");
111
+ }
112
+ const timeoutMs = opts.timeoutMs ?? 12_000;
113
+ const method = (opts.method || "GET").toUpperCase();
114
+ const headers = { Accept: "application/json", ...(opts.headers || {}) };
115
+ let body = opts.body;
116
+ if (body != null && typeof body !== "string") {
117
+ headers["Content-Type"] = headers["Content-Type"] || "application/json";
118
+ body = JSON.stringify(body);
119
+ }
120
+ const retries = Number.isInteger(opts.retries) ? Math.max(opts.retries, 0) : DEFAULT_RETRIES;
121
+
122
+ const attempt = async () => {
123
+ let lastError;
124
+ for (let i = 0; i <= retries; i++) {
125
+ try {
126
+ return await once(url, { fetchImpl, method, headers, body, timeoutMs });
127
+ } catch (error) {
128
+ lastError = error;
129
+ const status = error?.status;
130
+ const abortLike = error?.name === "AbortError";
131
+ // A response with a status means the SERVER answered and refused to
132
+ // process the request, so replaying it is safe. A transport-level
133
+ // failure (no status) is ambiguous: the server may have already applied
134
+ // the request and only the response was lost. Never replay a
135
+ // non-idempotent method on an ambiguous failure.
136
+ // A retryable STATUS is not on its own a licence to replay: a 500 or
137
+ // 503 can be returned after the server already applied the request, so
138
+ // replaying a POST can place a second order or submit a second
139
+ // transaction. 429/408/425 mean "not processed", so those stay
140
+ // retryable for every method; genuine server errors only replay for
141
+ // idempotent methods.
142
+ const ALWAYS_SAFE_STATUS = new Set([408, 425, 429]);
143
+ const retryable =
144
+ status != null
145
+ ? ALWAYS_SAFE_STATUS.has(status) ||
146
+ (RETRYABLE_STATUS.has(status) && IDEMPOTENT_METHODS.has(method))
147
+ : !abortLike && IDEMPOTENT_METHODS.has(method);
148
+ if (i === retries || !retryable) throw error;
149
+ await sleep(backoffMs(i, error?.retryAfter));
150
+ }
151
+ }
152
+ throw lastError;
153
+ };
154
+
155
+ // Single-flight only for idempotent GETs with no body.
156
+ const dedupe = opts.dedupe !== false && method === "GET" && body == null;
157
+ if (!dedupe) return attempt();
158
+
159
+ const key = dedupeKey(method, url, headers);
160
+ const existing = inflight.get(key);
161
+ if (existing) return existing;
162
+ const p = attempt().finally(() => inflight.delete(key));
163
+ inflight.set(key, p);
164
+ return p;
165
+ }
166
+
167
+ export async function timed(fn) {
168
+ const t0 = Date.now();
169
+ try {
170
+ const data = await fn();
171
+ return { ok: true, ms: Date.now() - t0, data };
172
+ } catch (e) {
173
+ return {
174
+ ok: false,
175
+ ms: Date.now() - t0,
176
+ error: String(e.message || e),
177
+ status: e.status ?? null,
178
+ };
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Run async tasks with a hard concurrency ceiling. Public health sweeps fan out
184
+ * across ~30 providers; unbounded Promise.all trips public rate limits.
185
+ */
186
+ export async function mapLimit(items, limit, fn) {
187
+ const list = Array.from(items);
188
+ const cap = Math.max(1, Math.min(Number(limit) || 1, list.length || 1));
189
+ const out = new Array(list.length);
190
+ let cursor = 0;
191
+ await Promise.all(
192
+ Array.from({ length: cap }, async () => {
193
+ while (cursor < list.length) {
194
+ const index = cursor++;
195
+ out[index] = await fn(list[index], index);
196
+ }
197
+ })
198
+ );
199
+ return out;
200
+ }
@@ -0,0 +1,94 @@
1
+ // Provider endpoint pinning.
2
+ //
3
+ // Every keyed provider had the same shape: `baseUrl` came from caller-supplied
4
+ // opts, and headers() attached the operator's API key unconditionally. One
5
+ // hostile opts object — from a prompt-injected model, a malicious skill, or a
6
+ // config someone pasted — ships the credential to an arbitrary host. That is
7
+ // credential exfiltration and SSRF wearing a configuration costume.
8
+ //
9
+ // The rule here: a credential is attached ONLY when the resolved host is one
10
+ // the provider is pinned to. Overriding the URL is still allowed (local mocks,
11
+ // self-hosted proxies, testing) but doing so DROPS the key rather than
12
+ // forwarding it somewhere new.
13
+
14
+ const OVERRIDE_ENV = "ORACLE_ALLOW_CUSTOM_PROVIDER_URL";
15
+
16
+ /**
17
+ * @param {object} spec
18
+ * @param {string} spec.provider provider id, for error messages
19
+ * @param {string} spec.defaultUrl the pinned default endpoint
20
+ * @param {string[]} spec.hosts hostnames allowed to receive the credential
21
+ * @param {string} [spec.url] caller/env supplied override
22
+ * @param {boolean} [spec.strict] throw instead of dropping the key
23
+ */
24
+ export function resolveProviderEndpoint({ provider, defaultUrl, hosts = [], url, strict = false }) {
25
+ // An empty/blank override means "not configured", not "call the empty
26
+ // string". Treat it as absent so callers can pass `opts.baseUrl` straight
27
+ // through without pre-checking it.
28
+ const override = String(url ?? "").trim();
29
+ const raw = (override || String(defaultUrl)).replace(/\/$/, "");
30
+ if (raw === String(defaultUrl).replace(/\/$/, "")) {
31
+ return { baseUrl: raw, trusted: true, host: hostOf(defaultUrl) };
32
+ }
33
+
34
+ let parsed;
35
+ try {
36
+ parsed = new URL(raw);
37
+ } catch {
38
+ throw new Error(`${provider}: baseUrl must be an absolute http(s) URL`);
39
+ }
40
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
41
+ throw new Error(`${provider}: baseUrl must be an absolute http(s) URL`);
42
+ }
43
+ const host = parsed.host;
44
+ if (!host) {
45
+ throw new Error(`${provider}: baseUrl must be an absolute http(s) URL`);
46
+ }
47
+
48
+ const allowed = new Set([hostOf(defaultUrl), ...hosts]);
49
+ if (allowed.has(host)) {
50
+ // A protocol downgrade to plaintext would put the pinned credential on the
51
+ // wire in cleartext, so an allowlisted HOST over http:// is still not a
52
+ // trusted destination for a secret. Loopback is exempt: there is no wire.
53
+ const loopback = /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(host);
54
+ if (parsed.protocol === "http:" && !loopback) {
55
+ return { baseUrl: raw, trusted: false, host, reason: "plaintext http downgrade" };
56
+ }
57
+ return { baseUrl: raw, trusted: true, host };
58
+ }
59
+
60
+ if (String(process.env[OVERRIDE_ENV] || "") === "1") {
61
+ // Explicit operator opt-in. Still untrusted: the caller asked for a
62
+ // different host, so the key does not travel there.
63
+ return { baseUrl: raw, trusted: false, host };
64
+ }
65
+
66
+ if (strict) {
67
+ throw new Error(
68
+ `${provider}: refusing to call non-allowlisted host ${host} (set ${OVERRIDE_ENV}=1 to permit it)`
69
+ );
70
+ }
71
+ return { baseUrl: raw, trusted: false, host };
72
+ }
73
+
74
+ function hostOf(url) {
75
+ const u = new URL(String(url));
76
+ if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error("unsupported protocol");
77
+ return u.host;
78
+ }
79
+
80
+ /**
81
+ * Attach credential headers only to a trusted endpoint.
82
+ *
83
+ * @param {object} baseHeaders headers safe for any host (accept, user-agent)
84
+ * @param {object} credentials header name -> secret value
85
+ * @param {boolean} trusted from resolveProviderEndpoint
86
+ */
87
+ export function credentialedHeaders(baseHeaders, credentials, trusted) {
88
+ const h = { ...baseHeaders };
89
+ if (!trusted) return h;
90
+ for (const [name, value] of Object.entries(credentials || {})) {
91
+ if (value) h[name] = value;
92
+ }
93
+ return h;
94
+ }
@@ -0,0 +1,244 @@
1
+ // Aerodrome Slipstream (Base) — QuoterV2 + SwapRouter exact-input.
2
+ // Official deployments: aerodrome-finance/slipstream README (Base).
3
+ // Quoter/router use tickSpacing (not Uniswap fee tiers). No API key.
4
+ // Read/quote/prepare only — never signs or broadcasts.
5
+
6
+ import { Interface, getAddress, isAddress } from "ethers";
7
+ import { rpcCall } from "./evm-rpc.mjs";
8
+ import { attachAutoSlippage, bindAutoSlippageGuardToCall } from "../../auto-slippage.mjs";
9
+
10
+ /** @type {Record<number, { name: string, quoter: string, router: string, factory: string, weth: string, usdc: string }>} */
11
+ export const AERODROME_CHAINS = {
12
+ 8453: {
13
+ name: "base",
14
+ // Verified 2026-07-24: slipstream README initial deployment + eth_getCode + live quote.
15
+ quoter: "0x254cF9E1E6e233aa1AC962CB9B05b2cfeAaE15b0",
16
+ router: "0xBE6D8f0d05cC4be24d5167a3eF062215bE6D18a5",
17
+ factory: "0x5e7BB104d84c7CB9B682AaC2F3d509f5F406809A",
18
+ weth: "0x4200000000000000000000000000000000000006",
19
+ usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
20
+ },
21
+ };
22
+
23
+ // Common Slipstream tick spacings on Base.
24
+ export const AERODROME_TICK_SPACINGS = [1, 50, 100, 200, 2000];
25
+
26
+ const QUOTER_IFACE = new Interface([
27
+ "function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, int24 tickSpacing, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)",
28
+ ]);
29
+
30
+ const ROUTER_IFACE = new Interface([
31
+ "function exactInputSingle((address tokenIn, address tokenOut, int24 tickSpacing, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)",
32
+ ]);
33
+
34
+ const NATIVE = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
35
+ const ZERO = "0x0000000000000000000000000000000000000000";
36
+
37
+ function chainMeta(chainId) {
38
+ const id = Number(chainId);
39
+ const m = AERODROME_CHAINS[id];
40
+ if (!m) {
41
+ throw new Error(
42
+ `aerodrome: unsupported chainId ${chainId} (supported: ${Object.keys(AERODROME_CHAINS).join(", ")})`
43
+ );
44
+ }
45
+ return { chainId: id, ...m };
46
+ }
47
+
48
+ function normalizeToken(addr, chainId) {
49
+ const meta = AERODROME_CHAINS[Number(chainId)];
50
+ if (!addr || addr === NATIVE || addr === ZERO || /^eth$/i.test(String(addr))) {
51
+ return getAddress(meta.weth);
52
+ }
53
+ const s = String(addr);
54
+ if (/^weth$/i.test(s)) return getAddress(meta.weth);
55
+ if (/^usdc$/i.test(s)) return getAddress(meta.usdc);
56
+ if (!isAddress(s)) throw new Error(`invalid token address: ${addr}`);
57
+ return getAddress(s);
58
+ }
59
+
60
+ /**
61
+ * Quote exact-input single hop via Aerodrome Slipstream QuoterV2.
62
+ * @param {object} q
63
+ * @param {number} [q.chainId=8453]
64
+ * @param {string} [q.tokenIn] default WETH
65
+ * @param {string} [q.tokenOut] default USDC
66
+ * @param {string|number|bigint} q.amountIn raw base units
67
+ * @param {number} [q.tickSpacing] if omitted, tries common spacings for best-out
68
+ */
69
+ export async function aerodromeQuoteExactIn(q = {}, opts = {}) {
70
+ const { chainId, quoter, router } = chainMeta(q.chainId ?? 8453);
71
+ const tokenIn = normalizeToken(q.tokenIn || "WETH", chainId);
72
+ const tokenOut = normalizeToken(q.tokenOut || AERODROME_CHAINS[chainId].usdc, chainId);
73
+ const amountIn = BigInt(q.amountIn ?? 0);
74
+ if (amountIn <= 0n) throw new Error("amountIn required (raw base units)");
75
+
76
+ const spacings =
77
+ q.tickSpacing != null
78
+ ? [Number(q.tickSpacing)]
79
+ : q.tryTickSpacings === false
80
+ ? [100]
81
+ : [...AERODROME_TICK_SPACINGS];
82
+
83
+ const results = [];
84
+ let best = null;
85
+
86
+ for (const tickSpacing of spacings) {
87
+ const data = QUOTER_IFACE.encodeFunctionData("quoteExactInputSingle", [
88
+ {
89
+ tokenIn,
90
+ tokenOut,
91
+ amountIn,
92
+ tickSpacing,
93
+ sqrtPriceLimitX96: 0n,
94
+ },
95
+ ]);
96
+ try {
97
+ const raw = await rpcCall(chainId, "eth_call", [{ to: quoter, data }, "latest"], opts);
98
+ if (!raw || raw === "0x") {
99
+ results.push({ tickSpacing, ok: false, error: "empty result" });
100
+ continue;
101
+ }
102
+ const decoded = QUOTER_IFACE.decodeFunctionResult("quoteExactInputSingle", raw);
103
+ const row = {
104
+ tickSpacing,
105
+ ok: true,
106
+ amountOut: decoded[0].toString(),
107
+ sqrtPriceX96After: decoded[1].toString(),
108
+ initializedTicksCrossed: Number(decoded[2]),
109
+ gasEstimate: decoded[3].toString(),
110
+ };
111
+ results.push(row);
112
+ if (!best || BigInt(row.amountOut) > BigInt(best.amountOut)) best = row;
113
+ } catch (e) {
114
+ results.push({ tickSpacing, ok: false, error: String(e.message || e).slice(0, 160) });
115
+ }
116
+ }
117
+
118
+ if (!best) {
119
+ const err = results.map((r) => `${r.tickSpacing}:${r.error || "fail"}`).join("; ");
120
+ throw new Error(`aerodrome quote failed chain=${chainId}: ${err}`);
121
+ }
122
+
123
+ return attachAutoSlippage(
124
+ {
125
+ venue: "aerodrome",
126
+ chainId,
127
+ chain: AERODROME_CHAINS[chainId].name,
128
+ quoter,
129
+ router,
130
+ tokenIn,
131
+ tokenOut,
132
+ amountIn: amountIn.toString(),
133
+ tickSpacing: best.tickSpacing,
134
+ amountOut: best.amountOut,
135
+ gasEstimate: best.gasEstimate,
136
+ sqrtPriceX96After: best.sqrtPriceX96After,
137
+ initializedTicksCrossed: best.initializedTicksCrossed,
138
+ triedTickSpacings: results,
139
+ best: true,
140
+ },
141
+ {
142
+ chainId,
143
+ venue: router,
144
+ amountOut: best.amountOut,
145
+ liquidityUsd: q.liquidityUsd,
146
+ priceChange5m: q.priceChange5m,
147
+ requestedCapBps: q.maxSlippageBps ?? q.slippageBps,
148
+ }
149
+ );
150
+ }
151
+
152
+ export async function aerodromePrepareExactIn(q = {}, opts = {}) {
153
+ const chainId = Number(q.chainId ?? 8453);
154
+ const meta = chainMeta(chainId);
155
+ const recipient = getAddress(q.recipient || q.from || q.userAddress);
156
+ const inputRaw = String(q.tokenIn || "WETH");
157
+ const nativeInput =
158
+ !q.tokenIn || inputRaw === NATIVE || inputRaw === ZERO || /^eth$/i.test(inputRaw);
159
+ const quote = await aerodromeQuoteExactIn(q, opts);
160
+ const deadlineWindow = Math.min(600, Math.max(30, Number(q.deadlineSeconds ?? 300)));
161
+ const nowSeconds = Number(opts.nowSeconds ?? Math.floor(Date.now() / 1000));
162
+ const deadline = nowSeconds + deadlineWindow;
163
+ const data = ROUTER_IFACE.encodeFunctionData("exactInputSingle", [
164
+ {
165
+ tokenIn: quote.tokenIn,
166
+ tokenOut: quote.tokenOut,
167
+ tickSpacing: quote.tickSpacing,
168
+ recipient,
169
+ deadline,
170
+ amountIn: BigInt(quote.amountIn),
171
+ amountOutMinimum: BigInt(quote.amountOutMinimum),
172
+ sqrtPriceLimitX96: 0n,
173
+ },
174
+ ]);
175
+ return {
176
+ provider: "aerodrome",
177
+ calldataReady: true,
178
+ // NOT executable authority. The bytes are assembled but nothing is signed:
179
+ // the user's wallet is still the only thing that can authorize this. The
180
+ // previous `executionReady: true` read as "cleared to execute" and trained
181
+ // agents to treat a quote as permission.
182
+ requiresUserSignature: true,
183
+ signingReady: false,
184
+ broadcastReady: false,
185
+ chainId,
186
+ deadline,
187
+ quote,
188
+ autoSlippage: quote.autoSlippage,
189
+ requiresApproval: nativeInput
190
+ ? null
191
+ : {
192
+ token: quote.tokenIn,
193
+ spender: meta.router,
194
+ amount: quote.amountIn,
195
+ },
196
+ transaction: {
197
+ chainId,
198
+ from: recipient,
199
+ to: meta.router,
200
+ data,
201
+ value: nativeInput ? quote.amountIn : "0",
202
+ slippageGuard: bindAutoSlippageGuardToCall(quote.autoSlippage, { chainId, venue: meta.router, data }),
203
+ },
204
+ };
205
+ }
206
+
207
+ export async function aerodromeHealth(opts = {}) {
208
+ const chainId = Number(opts.chainId ?? 8453);
209
+ try {
210
+ const q = await aerodromeQuoteExactIn(
211
+ {
212
+ chainId,
213
+ tokenIn: "WETH",
214
+ tokenOut: "USDC",
215
+ amountIn: "1000000000000000",
216
+ },
217
+ opts
218
+ );
219
+ const usdc = Number(q.amountOut) / 1e6;
220
+ return {
221
+ ok: true,
222
+ chainId,
223
+ tickSpacing: q.tickSpacing,
224
+ amountOutUsdc: usdc,
225
+ midPxHint: usdc / 0.001,
226
+ router: AERODROME_CHAINS[chainId]?.router,
227
+ quoter: AERODROME_CHAINS[chainId]?.quoter,
228
+ };
229
+ } catch (e) {
230
+ return { ok: false, chainId, error: String(e.message || e).slice(0, 200) };
231
+ }
232
+ }
233
+
234
+ export async function aerodromeChains() {
235
+ return Object.entries(AERODROME_CHAINS).map(([id, m]) => ({
236
+ chainId: Number(id),
237
+ name: m.name,
238
+ quoter: m.quoter,
239
+ router: m.router,
240
+ factory: m.factory,
241
+ weth: m.weth,
242
+ usdc: m.usdc,
243
+ }));
244
+ }