@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,208 @@
1
+ // Balancer public GraphQL API + v3 Router exact-input prepare. No key.
2
+ import { Interface, getAddress, isAddress } from "ethers";
3
+ import { httpJson } from "../http.mjs";
4
+ import { rpcCall as defaultRpcCall } from "./evm-rpc.mjs";
5
+ import { attachAutoSlippage, bindAutoSlippageGuardToCall } from "../../auto-slippage.mjs";
6
+
7
+ export const BALANCER_API = "https://api-v3.balancer.fi/";
8
+ const endpoint = (o = {}) => o.baseUrl || process.env.BALANCER_API_URL || BALANCER_API;
9
+
10
+ async function gql(query, variables, opts = {}) {
11
+ return httpJson(endpoint(opts), {
12
+ method: "POST",
13
+ body: { query, variables },
14
+ fetchImpl: opts.fetchImpl,
15
+ timeoutMs: opts.timeoutMs ?? 20_000,
16
+ });
17
+ }
18
+
19
+ const POOLS_QUERY = `query Pools($first: Int, $where: GqlPoolFilter) { poolGetPools(first: $first, where: $where) { id address chain type protocolVersion dynamicData { totalLiquidity volume24h fees24h } } }`;
20
+
21
+ // Official Balancer v3 Router deployments; bytecode checked via eth_getCode on
22
+ // 2026-07-23. Polygon is intentionally excluded from this v3 prepare slice.
23
+ export const BALANCER_V3_CHAINS = Object.freeze({
24
+ 1: {
25
+ name: "ethereum",
26
+ router: "0xAE563E3f8219521950555F5962419C8919758Ea2",
27
+ weth: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
28
+ usdc: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
29
+ },
30
+ 10: {
31
+ name: "optimism",
32
+ router: "0xe2fa4e1d17725e72dcdAfe943Ecf45dF4B9E285b",
33
+ weth: "0x4200000000000000000000000000000000000006",
34
+ usdc: "0x0b2c639c533813f4aa9d7837caf62653d097ff85",
35
+ },
36
+ 8453: {
37
+ name: "base",
38
+ router: "0x3f170631ed9821Ca51A59D996aB095162438DC10",
39
+ weth: "0x4200000000000000000000000000000000000006",
40
+ usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
41
+ },
42
+ 42161: {
43
+ name: "arbitrum",
44
+ router: "0xEAedc32a51c510d35ebC11088fD5fF2b47aACF2E",
45
+ weth: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
46
+ usdc: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
47
+ },
48
+ 43114: {
49
+ name: "avalanche",
50
+ router: "0xF39CA6ede9BF7820a952b52f3c94af526bAB9015",
51
+ weth: "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",
52
+ usdc: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",
53
+ },
54
+ });
55
+
56
+ const NATIVE = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
57
+ const ZERO = "0x0000000000000000000000000000000000000000";
58
+ const BALANCER_V3_IFACE = new Interface([
59
+ "function querySwapSingleTokenExactIn(address pool,address tokenIn,address tokenOut,uint256 exactAmountIn,address sender,bytes userData) returns (uint256 amountOut)",
60
+ "function swapSingleTokenExactIn(address pool,address tokenIn,address tokenOut,uint256 exactAmountIn,uint256 minAmountOut,uint256 deadline,bool wethIsEth,bytes userData) payable returns (uint256 amountOut)",
61
+ ]);
62
+
63
+ function chainMeta(chainId) {
64
+ const id = Number(chainId ?? 8453);
65
+ const meta = BALANCER_V3_CHAINS[id];
66
+ if (!meta) {
67
+ throw new Error(`balancer-v3: unsupported chainId ${chainId} (supported: ${Object.keys(BALANCER_V3_CHAINS).join(", ")})`);
68
+ }
69
+ return { chainId: id, ...meta };
70
+ }
71
+
72
+ function isNativeToken(value) {
73
+ const v = String(value || "").toLowerCase();
74
+ return !v || v === "eth" || v === "native" || v === ZERO || v === NATIVE.toLowerCase();
75
+ }
76
+
77
+ function normalizeAddress(value, label) {
78
+ if (!isAddress(value)) throw new Error(`${label} must be a valid EVM address`);
79
+ return getAddress(value);
80
+ }
81
+
82
+ function normalizeToken(value, meta, label) {
83
+ const s = String(value || "");
84
+ if (isNativeToken(s) || /^weth$/i.test(s)) return getAddress(meta.weth);
85
+ if (/^usdc$/i.test(s)) return getAddress(meta.usdc);
86
+ return normalizeAddress(s, label);
87
+ }
88
+
89
+ function positiveAmount(value, label) {
90
+ let amount;
91
+ try {
92
+ amount = BigInt(String(value));
93
+ } catch {
94
+ throw new Error(`${label} must be an integer string`);
95
+ }
96
+ if (amount <= 0n) throw new Error(`${label} must be positive`);
97
+ return amount;
98
+ }
99
+
100
+ function userData(value) {
101
+ if (value == null || value === "") return "0x";
102
+ const data = String(value);
103
+ if (!/^0x[0-9a-fA-F]*$/.test(data)) throw new Error("balancer userData must be hex");
104
+ return data;
105
+ }
106
+
107
+ export async function balancerPools(args = {}, opts = {}) {
108
+ const first = Math.min(100, Math.max(1, Number(args.first || 20)));
109
+ const chains = (args.chains || [args.chain || "ETHEREUM"]).map((x) => String(x).toUpperCase());
110
+ return gql(POOLS_QUERY, { first, chains, where: { chainIn: chains } }, opts);
111
+ }
112
+
113
+ export async function balancerHealth(opts = {}) {
114
+ const data = await gql("query { __typename }", {}, opts);
115
+ return { ok: data?.data?.__typename === "Query" };
116
+ }
117
+
118
+ export async function balancerQuote(q = {}, opts = {}) {
119
+ const meta = chainMeta(q.chainId);
120
+ const pool = normalizeAddress(q.pool, "balancer pool");
121
+ const tokenInRaw = q.tokenIn || "WETH";
122
+ const tokenIn = normalizeToken(tokenInRaw, meta, "balancer tokenIn");
123
+ const tokenOut = normalizeToken(q.tokenOut || "USDC", meta, "balancer tokenOut");
124
+ const amountIn = positiveAmount(q.amountIn, "balancer amountIn");
125
+ const sender = normalizeAddress(q.sender || q.from || q.fromAddress || q.recipient, "balancer sender");
126
+ const data = BALANCER_V3_IFACE.encodeFunctionData("querySwapSingleTokenExactIn", [
127
+ pool,
128
+ tokenIn,
129
+ tokenOut,
130
+ amountIn,
131
+ sender,
132
+ userData(q.userData),
133
+ ]);
134
+ const call = opts.rpcCall || defaultRpcCall;
135
+ const raw = await call(meta.chainId, "eth_call", [{ to: meta.router, data }, q.blockTag || "latest"], opts);
136
+ const decoded = BALANCER_V3_IFACE.decodeFunctionResult("querySwapSingleTokenExactIn", raw);
137
+ const amountOut = BigInt(decoded[0]);
138
+ if (amountOut <= 0n) throw new Error("balancer quote returned zero output");
139
+ return attachAutoSlippage({
140
+ venue: "balancer",
141
+ protocolVersion: 3,
142
+ chainId: meta.chainId,
143
+ chain: meta.name,
144
+ router: meta.router,
145
+ pool,
146
+ tokenIn,
147
+ tokenOut,
148
+ amountIn: amountIn.toString(),
149
+ amountOut: amountOut.toString(),
150
+ }, {
151
+ chainId: meta.chainId,
152
+ venue: meta.router,
153
+ amountOut: amountOut.toString(),
154
+ liquidityUsd: q.liquidityUsd,
155
+ priceChange5m: q.priceChange5m,
156
+ requestedCapBps: q.maxSlippageBps ?? q.slippageBps,
157
+ });
158
+ }
159
+
160
+ export async function balancerPrepare(q = {}, opts = {}) {
161
+ const meta = chainMeta(q.chainId);
162
+ const sender = normalizeAddress(q.sender || q.from || q.fromAddress || q.recipient, "balancer sender");
163
+ const inputRaw = q.tokenIn || "WETH";
164
+ const nativeInput = isNativeToken(inputRaw);
165
+ const quote = await balancerQuote({ ...q, sender }, opts);
166
+ const deadlineWindow = Math.min(600, Math.max(30, Number(q.deadlineSeconds ?? 300)));
167
+ const nowSeconds = Number(opts.nowSeconds ?? Math.floor(Date.now() / 1000));
168
+ const deadline = BigInt(nowSeconds + deadlineWindow);
169
+ const wethIsEth = q.wethIsEth != null ? Boolean(q.wethIsEth) : nativeInput;
170
+ const data = BALANCER_V3_IFACE.encodeFunctionData("swapSingleTokenExactIn", [
171
+ quote.pool,
172
+ quote.tokenIn,
173
+ quote.tokenOut,
174
+ BigInt(quote.amountIn),
175
+ BigInt(quote.amountOutMinimum),
176
+ deadline,
177
+ wethIsEth,
178
+ userData(q.userData),
179
+ ]);
180
+ return {
181
+ provider: "balancer",
182
+ calldataReady: true,
183
+ // NOT executable authority. The bytes are assembled but nothing is signed:
184
+ // the user's wallet is still the only thing that can authorize this. The
185
+ // previous `executionReady: true` read as "cleared to execute" and trained
186
+ // agents to treat a quote as permission.
187
+ requiresUserSignature: true,
188
+ signingReady: false,
189
+ broadcastReady: false,
190
+ chainId: meta.chainId,
191
+ deadline: deadline.toString(),
192
+ quote,
193
+ autoSlippage: quote.autoSlippage,
194
+ requiresApproval: nativeInput ? null : {
195
+ token: quote.tokenIn,
196
+ spender: meta.router,
197
+ amount: quote.amountIn,
198
+ },
199
+ transaction: {
200
+ chainId: meta.chainId,
201
+ from: sender,
202
+ to: meta.router,
203
+ data,
204
+ value: nativeInput ? quote.amountIn : "0",
205
+ slippageGuard: bindAutoSlippageGuardToCall(quote.autoSlippage, { chainId: meta.chainId, venue: meta.router, data }),
206
+ },
207
+ };
208
+ }
@@ -0,0 +1,230 @@
1
+ // Bitcoin L1 read/broadcast via Esplora HTTP (mempool.space / Blockstream).
2
+ // No Bitcoin Core RPC required. No keys, no signing.
3
+
4
+ import { httpJson } from "../http.mjs";
5
+
6
+ export const BTC_NETWORK_MAINNET = "mainnet";
7
+ export const BTC_ESPLORA_MAINNET = "https://mempool.space/api";
8
+ export const BTC_ESPLORA_TESTNET = "https://mempool.space/testnet/api";
9
+
10
+ function network(opts = {}) {
11
+ const n = String(opts.network || process.env.BTC_NETWORK || BTC_NETWORK_MAINNET).trim().toLowerCase();
12
+ return n === "testnet" ? "testnet" : "mainnet";
13
+ }
14
+
15
+ function baseUrl(opts = {}) {
16
+ if (opts.baseUrl) return String(opts.baseUrl).replace(/\/$/, "");
17
+ if (process.env.BTC_ESPLORA_URL) return String(process.env.BTC_ESPLORA_URL).replace(/\/$/, "");
18
+ return network(opts) === "testnet" ? BTC_ESPLORA_TESTNET : BTC_ESPLORA_MAINNET;
19
+ }
20
+
21
+ export function btcAddress(value, label = "address") {
22
+ const text = String(value || "").trim();
23
+ // bech32 / bech32m / legacy / p2sh — loose shape check, not full BIP validation
24
+ if (!/^(bc1|tb1|bcrt1)[a-z0-9]{20,90}$/i.test(text) && !/^[13mn2][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(text)) {
25
+ throw new Error(`bitcoin-esplora: ${label} must look like a Bitcoin address`);
26
+ }
27
+ return text;
28
+ }
29
+
30
+ export function btcTxHex(value, label = "txHex") {
31
+ const text = String(value || "").trim().toLowerCase().replace(/^0x/, "");
32
+ if (!/^[0-9a-f]+$/.test(text) || text.length < 20 || text.length % 2 !== 0) {
33
+ throw new Error(`bitcoin-esplora: ${label} must be even-length hex`);
34
+ }
35
+ return text;
36
+ }
37
+
38
+ async function getText(path, opts = {}) {
39
+ const url = `${baseUrl(opts)}${path.startsWith("/") ? path : `/${path}`}`;
40
+ const fetchImpl = opts.fetchImpl || fetch;
41
+ const res = await fetchImpl(url, {
42
+ method: "GET",
43
+ headers: { accept: "application/json,text/plain;q=0.9,*/*;q=0.8" },
44
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 12_000),
45
+ });
46
+ const text = await res.text();
47
+ if (!res.ok) throw new Error(`bitcoin-esplora GET ${path}: HTTP ${res.status} ${text.slice(0, 160)}`);
48
+ return text;
49
+ }
50
+
51
+ async function getJson(path, opts = {}) {
52
+ const text = await getText(path, opts);
53
+ try {
54
+ return JSON.parse(text);
55
+ } catch {
56
+ return text;
57
+ }
58
+ }
59
+
60
+ async function postText(path, body, opts = {}) {
61
+ const url = `${baseUrl(opts)}${path.startsWith("/") ? path : `/${path}`}`;
62
+ const fetchImpl = opts.fetchImpl || fetch;
63
+ const res = await fetchImpl(url, {
64
+ method: "POST",
65
+ headers: { "content-type": "text/plain", accept: "application/json,text/plain;q=0.9,*/*;q=0.8" },
66
+ body: String(body || ""),
67
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 15_000),
68
+ });
69
+ const text = await res.text();
70
+ if (!res.ok) throw new Error(`bitcoin-esplora POST ${path}: HTTP ${res.status} ${text.slice(0, 200)}`);
71
+ return text.trim();
72
+ }
73
+
74
+ export async function btcHealth(opts = {}) {
75
+ try {
76
+ const tip = await getText("/blocks/tip/height", opts);
77
+ const height = Number(tip);
78
+ return {
79
+ ok: Number.isFinite(height) && height > 0,
80
+ provider: "bitcoin-esplora",
81
+ network: network(opts),
82
+ baseUrl: baseUrl(opts),
83
+ tipHeight: height,
84
+ exec: false,
85
+ signing: "user-wallet",
86
+ };
87
+ } catch (error) {
88
+ return {
89
+ ok: false,
90
+ provider: "bitcoin-esplora",
91
+ network: network(opts),
92
+ baseUrl: baseUrl(opts),
93
+ error: String(error?.message || error),
94
+ exec: false,
95
+ };
96
+ }
97
+ }
98
+
99
+ export async function btcTipHeight(opts = {}) {
100
+ const tip = await getText("/blocks/tip/height", opts);
101
+ return {
102
+ provider: "bitcoin-esplora",
103
+ network: network(opts),
104
+ tipHeight: Number(tip),
105
+ };
106
+ }
107
+
108
+ export async function btcFees(opts = {}) {
109
+ // mempool.space recommended fees; Blockstream may 404 — fall back empty
110
+ try {
111
+ const fees = await getJson("/v1/fees/recommended", opts);
112
+ return {
113
+ provider: "bitcoin-esplora",
114
+ network: network(opts),
115
+ fastestFee: fees.fastestFee ?? null,
116
+ halfHourFee: fees.halfHourFee ?? null,
117
+ hourFee: fees.hourFee ?? null,
118
+ economyFee: fees.economyFee ?? null,
119
+ minimumFee: fees.minimumFee ?? null,
120
+ raw: fees,
121
+ };
122
+ } catch {
123
+ return {
124
+ provider: "bitcoin-esplora",
125
+ network: network(opts),
126
+ fastestFee: null,
127
+ halfHourFee: null,
128
+ hourFee: null,
129
+ note: "fee endpoint unavailable on this Esplora host",
130
+ };
131
+ }
132
+ }
133
+
134
+ export async function btcAddressInfo(args = {}, opts = {}) {
135
+ const address = btcAddress(args.address || args.addr, "address");
136
+ const info = await getJson(`/address/${address}`, opts);
137
+ const chain = info.chain_stats || {};
138
+ const mempool = info.mempool_stats || {};
139
+ const funded = Number(chain.funded_txo_sum || 0) + Number(mempool.funded_txo_sum || 0);
140
+ const spent = Number(chain.spent_txo_sum || 0) + Number(mempool.spent_txo_sum || 0);
141
+ return {
142
+ provider: "bitcoin-esplora",
143
+ network: network(opts),
144
+ address,
145
+ balanceSats: String(funded - spent),
146
+ chainStats: chain,
147
+ mempoolStats: mempool,
148
+ raw: info,
149
+ };
150
+ }
151
+
152
+ export async function btcUtxos(args = {}, opts = {}) {
153
+ const address = btcAddress(args.address || args.addr, "address");
154
+ const utxos = await getJson(`/address/${address}/utxo`, opts);
155
+ const list = Array.isArray(utxos) ? utxos : [];
156
+ return {
157
+ provider: "bitcoin-esplora",
158
+ network: network(opts),
159
+ address,
160
+ count: list.length,
161
+ totalSats: String(list.reduce((n, u) => n + Number(u.value || 0), 0)),
162
+ utxos: list.map((u) => ({
163
+ txid: u.txid,
164
+ vout: u.vout,
165
+ value: Number(u.value || 0),
166
+ status: u.status || null,
167
+ })),
168
+ };
169
+ }
170
+
171
+ export async function btcTx(args = {}, opts = {}) {
172
+ const txid = String(args.txid || args.txId || "").trim().toLowerCase();
173
+ if (!/^[0-9a-f]{64}$/.test(txid)) throw new Error("bitcoin-esplora: txid must be 64-char hex");
174
+ const tx = await getJson(`/tx/${txid}`, opts);
175
+ return {
176
+ provider: "bitcoin-esplora",
177
+ network: network(opts),
178
+ txid,
179
+ confirmed: Boolean(tx.status?.confirmed),
180
+ fee: tx.fee ?? null,
181
+ size: tx.size ?? null,
182
+ weight: tx.weight ?? null,
183
+ vinCount: Array.isArray(tx.vin) ? tx.vin.length : null,
184
+ voutCount: Array.isArray(tx.vout) ? tx.vout.length : null,
185
+ raw: tx,
186
+ };
187
+ }
188
+
189
+ export async function btcDecodeTxHex(args = {}, opts = {}) {
190
+ const txHex = btcTxHex(args.txHex || args.hex || args.transaction, "txHex");
191
+ // Esplora has no universal decode; return structural summary from hex length + optional /tx/hex reverse via broadcast dry path.
192
+ return {
193
+ provider: "bitcoin-esplora",
194
+ network: network(opts),
195
+ encoding: "hex",
196
+ txHex,
197
+ byteLength: txHex.length / 2,
198
+ note: "full decode is wallet/client-side or via bitcoinjs; Esplora returns broadcast acceptance only",
199
+ };
200
+ }
201
+
202
+ /**
203
+ * Broadcast a fully signed raw transaction hex.
204
+ *
205
+ * Posture: broadcasting is ARMED whenever the caller has signed bytes to send —
206
+ * possessing a signed transaction IS the authorization. What is still required
207
+ * is that the SEND be asked for: `execute:true` marks a user-initiated
208
+ * broadcast, so nothing goes out as a side effect of a read path. Oracle never
209
+ * signs here; the caller supplies the bytes.
210
+ */
211
+ export async function btcBroadcast(args = {}, opts = {}) {
212
+ if (args.execute !== true) {
213
+ throw new Error("bitcoin-esplora: broadcast requires execute:true — refusing an implicit send");
214
+ }
215
+ const txHex = btcTxHex(args.txHex || args.hex || args.signedTransaction, "txHex");
216
+ const txid = await postText("/tx", txHex, opts);
217
+ if (!/^[0-9a-f]{64}$/i.test(txid)) {
218
+ throw new Error(`bitcoin-esplora: unexpected broadcast response ${String(txid).slice(0, 80)}`);
219
+ }
220
+ return {
221
+ provider: "bitcoin-esplora",
222
+ network: network(opts),
223
+ sent: true,
224
+ txid: txid.toLowerCase(),
225
+ signedTransactionHex: txHex,
226
+ };
227
+ }
228
+
229
+ // Keep httpJson import usable for Core RPC optional path later without circular deps.
230
+ void httpJson;