@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,341 @@
1
+ // Prepare the winning route.
2
+ //
3
+ // The gap this closes: the router says "paraswap wins" and the user then has to
4
+ // rebuild that transaction through a completely different path, by hand, hoping they
5
+ // pick the same venue and parameters. That handoff is where the value of a
6
+ // comparison leaks away.
7
+ //
8
+ // Three things make this more than a thin wrapper:
9
+ //
10
+ // 1. QUOTES DECAY. The comparison ran at a past block. Preparing against that
11
+ // number would carry a stale minOut into a signature -- the exact failure the
12
+ // guard exists to prevent. So we RE-QUOTE, and if the fresh number is materially
13
+ // worse we say so rather than quietly preparing a worse trade than the one the
14
+ // user agreed to.
15
+ //
16
+ // 2. NOT EVERY WINNER IS A TRANSACTION. CoW returns EIP-712 typed data for an
17
+ // off-chain order; LI.FI/ParaSwap/0x return an unsigned EVM transaction. These
18
+ // are different artifacts requiring different wallet actions, and collapsing
19
+ // them into one "prepared" shape would hand someone typed data where they
20
+ // expected a tx. The artifact kind is explicit and always stated.
21
+ //
22
+ // 3. THE DESTINATION IS THE ATTACK SURFACE. A prepared transaction is a `to` plus
23
+ // opaque calldata. If that address is wrong, nothing downstream saves you. It is
24
+ // echoed prominently and checked against the quoting venue.
25
+ //
26
+ // Custody is unchanged: this returns artifacts to sign. It cannot sign or broadcast.
27
+
28
+ import { bestSwapRoute } from "./index.mjs";
29
+
30
+ export const ARTIFACT = Object.freeze({
31
+ /** Unsigned EVM transaction: wallet signs and broadcasts it. */
32
+ TRANSACTION: "unsigned-transaction",
33
+ /** EIP-712 payload: wallet signs data; a solver settles on-chain. No broadcast. */
34
+ TYPED_DATA_ORDER: "typed-data-order",
35
+ });
36
+
37
+ /**
38
+ * How much the re-quote may fall below the comparison before we refuse.
39
+ *
40
+ * Not zero: prices move between blocks and a hard-zero tolerance would make prepare
41
+ * fail constantly for no safety benefit. But bounded, because "the route you picked
42
+ * is now 4% worse" is a decision the user should get to make again.
43
+ */
44
+ const DEFAULT_DRIFT_TOLERANCE_BPS = 100;
45
+
46
+ const PREPARERS = {
47
+ lifi: async ({ chainId, tokenIn, tokenOut, amountIn, taker }, opts) => {
48
+ const { lifiPrepare } = await import("../data/providers/lifi.mjs");
49
+ const p = await lifiPrepare(
50
+ { fromChain: chainId, toChain: chainId, fromToken: tokenIn, toToken: tokenOut, fromAmount: amountIn, fromAddress: taker },
51
+ opts,
52
+ );
53
+ return {
54
+ artifactKind: ARTIFACT.TRANSACTION,
55
+ transaction: p.transaction,
56
+ requiresApproval: p.requiresApproval ?? null,
57
+ amountOut: p.quote?.estimate?.toAmount ?? null,
58
+ minOut: p.quote?.estimate?.toAmountMin ?? null,
59
+ };
60
+ },
61
+
62
+ paraswap: async ({ chainId, tokenIn, tokenOut, amountIn, taker, decimalsIn, decimalsOut }, opts) => {
63
+ const { paraswapPrepare } = await import("../data/providers/paraswap.mjs");
64
+ const p = await paraswapPrepare(
65
+ { chainId, srcToken: tokenIn, destToken: tokenOut, amount: amountIn, srcDecimals: decimalsIn, destDecimals: decimalsOut, userAddress: taker, side: "SELL" },
66
+ opts,
67
+ );
68
+ return {
69
+ artifactKind: ARTIFACT.TRANSACTION,
70
+ transaction: p.transaction,
71
+ requiresApproval: p.requiresApproval ?? null,
72
+ amountOut: p.quote?.priceRoute?.destAmount ?? null,
73
+ minOut: p.quote?.amountOutMinimum ?? null,
74
+ };
75
+ },
76
+
77
+ "0x": async ({ chainId, tokenIn, tokenOut, amountIn, taker }, opts) => {
78
+ const { zeroxPrepare } = await import("../data/providers/zerox.mjs");
79
+ const p = await zeroxPrepare(
80
+ { chainId, sellToken: tokenIn, buyToken: tokenOut, sellAmount: amountIn, taker },
81
+ opts,
82
+ );
83
+ return {
84
+ artifactKind: ARTIFACT.TRANSACTION,
85
+ transaction: p.transaction,
86
+ requiresApproval: p.requiresApproval ?? null,
87
+ amountOut: p.quote?.buyAmount ?? null,
88
+ minOut: p.quote?.minBuyAmount ?? null,
89
+ };
90
+ },
91
+
92
+ cow: async ({ chainId, tokenIn, tokenOut, amountIn, taker }, opts) => {
93
+ const { cowPrepareOrder } = await import("../data/providers/cowswap.mjs");
94
+ const p = await cowPrepareOrder(
95
+ { chainId, sellToken: tokenIn, buyToken: tokenOut, sellAmountBeforeFee: String(amountIn), from: taker },
96
+ opts,
97
+ );
98
+ return {
99
+ // Deliberately NOT a transaction. The wallet signs typed data and a solver
100
+ // settles it; there is nothing to broadcast, and treating this as a tx would
101
+ // produce a confusing failure at signing time.
102
+ artifactKind: ARTIFACT.TYPED_DATA_ORDER,
103
+ typedData: p.typedData,
104
+ // The relayer is what needs the ERC-20 allowance for CoW, NOT the settlement
105
+ // contract. Approving the wrong one produces an order that can never fill.
106
+ requiresApproval: {
107
+ token: tokenIn,
108
+ spender: p.vaultRelayer,
109
+ amount: String(amountIn),
110
+ note: "CoW pulls funds via the vault relayer, not the settlement contract",
111
+ },
112
+ settlement: p.settlement,
113
+ amountOut: p.quote?.quote?.buyAmount ?? null,
114
+ minOut: null,
115
+ submission: "sign the typed data, then submit the order to the CoW API",
116
+ };
117
+ },
118
+ };
119
+
120
+ export function supportedPreparers() {
121
+ return Object.keys(PREPARERS);
122
+ }
123
+
124
+ /**
125
+ * Addresses that are fine for QUOTING but must never reach a prepare call.
126
+ *
127
+ * The quote placeholder exists so aggregators that demand a `from` will price a route
128
+ * for an anonymous caller. Passing it to prepare is a category error: you would be
129
+ * building a transaction for the burn address.
130
+ *
131
+ * Some venues catch this and some do not, which is the dangerous part. ParaSwap
132
+ * rejects it with "userAddress must be a valid address" (verified live), while other
133
+ * venues will happily build a transaction addressed to nobody. Relying on the venue
134
+ * to notice is relying on the least careful one.
135
+ */
136
+ const NON_TAKER_ADDRESSES = new Set(
137
+ [
138
+ "0x0000000000000000000000000000000000000000",
139
+ "0x000000000000000000000000000000000000dead",
140
+ "0x0000000000000000000000000000000000000001",
141
+ "0x00000000000000000000000000000000000a1ce5",
142
+ ].map((a) => a.toLowerCase()),
143
+ );
144
+
145
+ const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
146
+
147
+ /**
148
+ * Compare routes, then prepare the winner.
149
+ *
150
+ * @param {object} p same shape as bestSwapRoute, plus:
151
+ * @param {string} [p.source] force a specific source instead of the winner
152
+ * @param {number} [p.driftToleranceBps]
153
+ */
154
+ export async function prepareBestRoute(p, opts = {}) {
155
+ const { taker } = p;
156
+ if (!taker) {
157
+ throw new Error(
158
+ "prepareBestRoute requires taker: a prepared transaction is built FOR an " +
159
+ "address, and the quote-only placeholder must never end up in one",
160
+ );
161
+ }
162
+ if (!ADDRESS_RE.test(taker)) {
163
+ throw new Error(`taker must be a valid 20-byte address, got "${taker}"`);
164
+ }
165
+ if (NON_TAKER_ADDRESSES.has(taker.toLowerCase())) {
166
+ throw new Error(
167
+ `taker "${taker}" is a placeholder/burn address. It is valid for quoting but ` +
168
+ "not for preparing -- that would build a transaction for an address nobody " +
169
+ "controls. Pass the real wallet that will sign.",
170
+ );
171
+ }
172
+
173
+ const comparison = await bestSwapRoute(p, opts);
174
+ if (!comparison.best) {
175
+ return { ok: false, reason: "no source returned a usable route", comparison };
176
+ }
177
+
178
+ // Honour an explicit override, but never silently: picking a non-winner is a
179
+ // legitimate choice (a user may distrust a venue) and it should be visible.
180
+ const chosenSource = p.source || comparison.best.source;
181
+ const chosen = comparison.routes.find((r) => r.source === chosenSource);
182
+ if (!chosen) {
183
+ return {
184
+ ok: false,
185
+ reason: `source "${chosenSource}" did not return a usable route`,
186
+ comparison,
187
+ };
188
+ }
189
+
190
+ const prepare = PREPARERS[chosenSource];
191
+ if (!prepare) {
192
+ // Honest failure beats a fabricated transaction. Name the fallback.
193
+ const alt = comparison.routes.find((r) => PREPARERS[r.source] && r.source !== chosenSource);
194
+ return {
195
+ ok: false,
196
+ reason:
197
+ `${chosenSource} won the comparison but has no prepare path in this build. ` +
198
+ (alt
199
+ ? `Next preparable route is ${alt.source}; pass source:"${alt.source}" to use it.`
200
+ : "No route in this comparison can be prepared."),
201
+ comparison,
202
+ winner: chosenSource,
203
+ };
204
+ }
205
+
206
+ let prepared;
207
+ try {
208
+ prepared = await prepare(p, opts);
209
+ } catch (err) {
210
+ // Read the API's actual complaint, not just the HTTP status line.
211
+ //
212
+ // httpJson throws `HTTP 400 POST <url>` and attaches the parsed response to
213
+ // err.body. Matching only err.message would classify every venue rejection as a
214
+ // generic "provider-error", which is how a fixable user-side problem ("you have
215
+ // not approved yet") gets reported as an opaque failure.
216
+ const detail =
217
+ typeof err?.body === "string"
218
+ ? err.body
219
+ : err?.body
220
+ ? JSON.stringify(err.body)
221
+ : "";
222
+ const msg = [String(err?.message || err), detail].filter(Boolean).join(" :: ");
223
+
224
+ // Translate the two failures that will confuse people most.
225
+ //
226
+ // Several venues validate on-chain state before building calldata:
227
+ // * "Not enough WETH balance" -- the taker does not hold the input token
228
+ // * "Not enough WETH allowance" -- the approval does not exist YET
229
+ //
230
+ // The allowance case is the important one, and it is a genuine ordering
231
+ // constraint rather than a bug: ParaSwap will not build swap calldata until the
232
+ // TokenTransferProxy is already approved. So the honest flow is approve first,
233
+ // then prepare -- which is exactly why requiresApproval is a separate step in
234
+ // this API instead of being bundled into one "just sign this" blob.
235
+ //
236
+ // Reporting the raw HTTP 400 would read as "the router is broken" when the user
237
+ // simply has not approved yet.
238
+ const allowanceIssue = /allowance/i.test(msg);
239
+ const balanceIssue = !allowanceIssue && /not enough|insufficient|balance/i.test(msg);
240
+
241
+ let reason;
242
+ let failureKind;
243
+ if (allowanceIssue) {
244
+ failureKind = "approval-required-first";
245
+ reason =
246
+ `${chosenSource} will not build swap calldata until the token approval ` +
247
+ `exists on-chain. Approve the spender first, then prepare again. ` +
248
+ `Underlying: ${msg}`;
249
+ } else if (balanceIssue) {
250
+ failureKind = "taker-not-funded";
251
+ reason =
252
+ `${chosenSource} refused to build the transaction: ${msg}. This venue ` +
253
+ `verifies the taker holds the input token. Quoting works for any address; ` +
254
+ `preparing needs the real funded wallet.`;
255
+ } else {
256
+ failureKind = "provider-error";
257
+ reason = `${chosenSource} prepare failed: ${msg}`;
258
+ }
259
+
260
+ // Name a preparable alternative so a blocked winner is not a dead end.
261
+ const alt = comparison.routes.find(
262
+ (r) => PREPARERS[r.source] && r.source !== chosenSource,
263
+ );
264
+
265
+ return {
266
+ ok: false,
267
+ reason,
268
+ failureKind,
269
+ ...(alt ? { alternative: alt.source } : {}),
270
+ comparison,
271
+ };
272
+ }
273
+
274
+ // Drift check. The comparison is already stale; this is the number that will
275
+ // actually be signed against.
276
+ const tolerance = p.driftToleranceBps ?? DEFAULT_DRIFT_TOLERANCE_BPS;
277
+ let driftBps = null;
278
+ let driftWarning = null;
279
+ if (prepared.amountOut != null && chosen.grossOut != null) {
280
+ try {
281
+ const then = BigInt(chosen.grossOut);
282
+ const now = BigInt(prepared.amountOut);
283
+ if (then > 0n) {
284
+ driftBps = Number(((now - then) * 10_000n) / then);
285
+ if (driftBps < -tolerance) {
286
+ driftWarning =
287
+ `route moved ${(driftBps / 100).toFixed(2)}% against you between the ` +
288
+ `comparison and this prepare (tolerance ${(tolerance / 100).toFixed(2)}%). ` +
289
+ "The ranking may no longer hold -- re-run the comparison before signing.";
290
+ }
291
+ }
292
+ } catch {
293
+ /* leave null rather than invent a drift figure */
294
+ }
295
+ }
296
+
297
+ const runnersUp = comparison.routes
298
+ .filter((r) => r.source !== chosenSource)
299
+ .map((r) => ({ source: r.source, netOut: r.netOut, gasUsd: r.gasUsd }));
300
+
301
+ return {
302
+ ok: true,
303
+ chosen: {
304
+ source: chosenSource,
305
+ wasWinner: chosenSource === comparison.best.source,
306
+ netOut: chosen.netOut,
307
+ grossOut: chosen.grossOut,
308
+ gasUsd: chosen.gasUsd,
309
+ },
310
+ ...prepared,
311
+ unsigned: true,
312
+ signedBy: "user-wallet",
313
+ // The single most security-relevant field: where value goes.
314
+ destination:
315
+ prepared.artifactKind === ARTIFACT.TRANSACTION
316
+ ? prepared.transaction?.to ?? null
317
+ : prepared.settlement ?? null,
318
+ driftBps,
319
+ warnings: [
320
+ ...(driftWarning ? [driftWarning] : []),
321
+ ...(comparison.warnings || []),
322
+ ...(prepared.artifactKind === ARTIFACT.TYPED_DATA_ORDER
323
+ ? [
324
+ "This is an ORDER to sign, not a transaction to broadcast. Signing it " +
325
+ "authorizes a solver to settle on your behalf.",
326
+ ]
327
+ : []),
328
+ ],
329
+ runnersUp,
330
+ comparison: {
331
+ rankedOn: comparison.rankedOn,
332
+ sourcesAnswered: comparison.sourcesAnswered,
333
+ sourcesTried: comparison.sourcesTried,
334
+ improvementBps: comparison.improvementBps,
335
+ },
336
+ note:
337
+ "UNSIGNED. Verify the destination address and minOut against a fresh quote " +
338
+ "immediately before signing -- a quote-time minimum is not a minimum at " +
339
+ "broadcast time.",
340
+ };
341
+ }
@@ -0,0 +1,311 @@
1
+ // Oracle Router proposal model.
2
+ //
3
+ // Pure, dependency-free. A "proposal" is an advisory object: a labeled
4
+ // suggestion for what Oracle Control *could* do, carrying no authority of its
5
+ // own. This module MUST NEVER be able to produce an object that authorizes,
6
+ // signs, or broadcasts anything, and MUST NEVER accept or echo back secrets
7
+ // (bearer tokens, private/session keys, passphrases, keystore paths, etc.).
8
+ //
9
+ // Enforcement is defense-in-depth, in this order:
10
+ // 1. Reject: any dangerous field anywhere in the input throws immediately.
11
+ // 2. Strip: the emitted proposal is built from an explicit field allowlist
12
+ // only (nothing "extra" from the input can leak through even if step 1
13
+ // had a gap).
14
+ // 3. Pin: every proposal carries fixed, non-overridable advisory markers
15
+ // (mode: "proposal", authorized: false, signed: false, broadcast: false)
16
+ // that the caller cannot set to anything else.
17
+ // 4. Freeze: the returned proposal (and its nested plain objects/arrays)
18
+ // is deep-frozen so downstream code cannot mutate it into something
19
+ // that looks authorized.
20
+
21
+ import { classifyRisk } from "./risk-classifier.mjs";
22
+
23
+ // Case-insensitive key patterns that must never appear anywhere in a
24
+ // proposal request or its emitted output. Deliberately broad: it is safer to
25
+ // over-reject an oddly named benign field than to under-reject a secret.
26
+ export const DANGEROUS_FIELD_PATTERNS = Object.freeze([
27
+ /priv(ate)?[-_ ]?key/i,
28
+ /seed[-_ ]?phrase/i,
29
+ /mnemonic/i,
30
+ /api[-_ ]?key/i,
31
+ /api[-_ ]?secret/i,
32
+ /bearer/i,
33
+ /session[-_ ]?key/i,
34
+ /session[-_ ]?secret/i,
35
+ /session[-_ ]?token/i,
36
+ /keystore/i,
37
+ /passphrase/i,
38
+ /^password$/i,
39
+ /secret/i,
40
+ /signature/i,
41
+ /signed[-_ ]?tx/i,
42
+ /raw[-_ ]?tx/i,
43
+ /broadcast/i,
44
+ /authoriz/i,
45
+ /^grant$/i,
46
+ /grant[-_ ]?token/i,
47
+ /credential/i,
48
+ /house[-_ ]?wallet/i,
49
+ /executor[-_ ]?token/i,
50
+ /access[-_ ]?token/i,
51
+ /^token$/i,
52
+ /^sig$/i,
53
+ /wallet[-_ ]?key/i,
54
+ ]);
55
+
56
+ // Exact key names the router itself emits as PINNED, hardcoded-false/fixed
57
+ // advisory markers (see createProposal below). These key names happen to
58
+ // match the dangerous-field patterns above (e.g. "authorized" contains
59
+ // "authoriz", "canAccessSecrets" contains "secret") precisely BECAUSE they
60
+ // exist to make the proposal's non-authority explicit and readable. They are
61
+ // only ever assigned literal constants by this module, never taken from
62
+ // caller input, so allowing them past the OUTPUT-side scan is safe. This
63
+ // allowlist is NEVER applied when scanning untrusted caller input.
64
+ const PINNED_SAFE_OUTPUT_KEYS = new Set([
65
+ "mode",
66
+ "advisoryOnly",
67
+ "authorized",
68
+ "signed",
69
+ "broadcast",
70
+ "requiresHumanConfirmation",
71
+ "grantsPermissions",
72
+ "capabilities",
73
+ "canClassifyRisk",
74
+ "canExplain",
75
+ "canSimulate",
76
+ "canSign",
77
+ "canBroadcast",
78
+ "canAuthorize",
79
+ "canMintCapability",
80
+ "canAccessSecrets",
81
+ ]);
82
+
83
+ function isDangerousKey(key, { allowPinnedSafe = false } = {}) {
84
+ const k = String(key);
85
+ if (allowPinnedSafe && PINNED_SAFE_OUTPUT_KEYS.has(k)) return false;
86
+ return DANGEROUS_FIELD_PATTERNS.some((re) => re.test(k));
87
+ }
88
+
89
+ /**
90
+ * Recursively scan a value for keys matching DANGEROUS_FIELD_PATTERNS.
91
+ * Returns a list of dotted paths where a dangerous key was found. Pure,
92
+ * read-only -- never mutates the input.
93
+ *
94
+ * @param {*} value
95
+ * @param {string} [pathPrefix]
96
+ * @param {object} [opts]
97
+ * @param {boolean} [opts.allowPinnedSafe] when true, exempts this module's own
98
+ * fixed advisory-marker key names (see PINNED_SAFE_OUTPUT_KEYS). Only ever
99
+ * pass this when scanning output THIS module constructed itself -- never
100
+ * when scanning caller-supplied input.
101
+ */
102
+ export function findDangerousFields(value, pathPrefix = "", opts = {}) {
103
+ const hits = [];
104
+ if (Array.isArray(value)) {
105
+ value.forEach((item, i) => {
106
+ hits.push(...findDangerousFields(item, `${pathPrefix}[${i}]`, opts));
107
+ });
108
+ return hits;
109
+ }
110
+ if (value && typeof value === "object") {
111
+ for (const [key, val] of Object.entries(value)) {
112
+ const path = pathPrefix ? `${pathPrefix}.${key}` : key;
113
+ if (isDangerousKey(key, opts)) hits.push(path);
114
+ hits.push(...findDangerousFields(val, path, opts));
115
+ }
116
+ return hits;
117
+ }
118
+ return hits;
119
+ }
120
+
121
+ /** Throws if `value` contains any dangerous field anywhere, at any depth.
122
+ * Pass { allowPinnedSafe: true } ONLY for output this module itself built. */
123
+ export function assertNoDangerousFields(value, label = "proposal input", opts = {}) {
124
+ const hits = findDangerousFields(value, "", opts);
125
+ if (hits.length) {
126
+ throw new Error(
127
+ `${label} contains disallowed secret/signing/broadcast field(s): ${hits.join(", ")}`
128
+ );
129
+ }
130
+ }
131
+
132
+ /** Deep-clones plain objects/arrays with any dangerous keys removed. Defense
133
+ * in depth only -- createProposal() rejects rather than relying on this to
134
+ * silently clean up the input. */
135
+ export function stripDangerousFields(value) {
136
+ if (Array.isArray(value)) return value.map(stripDangerousFields);
137
+ if (value && typeof value === "object") {
138
+ const out = {};
139
+ for (const [key, val] of Object.entries(value)) {
140
+ if (isDangerousKey(key)) continue;
141
+ out[key] = stripDangerousFields(val);
142
+ }
143
+ return out;
144
+ }
145
+ return value;
146
+ }
147
+
148
+ function deepFreeze(value) {
149
+ if (Array.isArray(value)) {
150
+ value.forEach(deepFreeze);
151
+ return Object.freeze(value);
152
+ }
153
+ if (value && typeof value === "object") {
154
+ for (const v of Object.values(value)) deepFreeze(v);
155
+ return Object.freeze(value);
156
+ }
157
+ return value;
158
+ }
159
+
160
+ // Fields the router is allowed to read off a proposal request. Anything not
161
+ // in this list is dropped when the proposal is built, regardless of what the
162
+ // caller sent -- this is what makes step 2 (Strip) effective even if a
163
+ // dangerous field used a name the regex list hasn't seen yet.
164
+ const ALLOWED_INPUT_FIELDS = Object.freeze([
165
+ "kind",
166
+ "target",
167
+ "notionalUsd",
168
+ "chainId",
169
+ "venue",
170
+ "destinationKnown",
171
+ "unlimitedApproval",
172
+ "crossChain",
173
+ "note",
174
+ ]);
175
+
176
+ function pickAllowed(input) {
177
+ const out = {};
178
+ for (const key of ALLOWED_INPUT_FIELDS) {
179
+ if (input && Object.prototype.hasOwnProperty.call(input, key) && input[key] !== undefined) {
180
+ out[key] = input[key];
181
+ }
182
+ }
183
+ return out;
184
+ }
185
+
186
+ let proposalCounter = 0;
187
+ function nextProposalId(nowMs) {
188
+ proposalCounter += 1;
189
+ return `proposal-${nowMs}-${proposalCounter}`;
190
+ }
191
+
192
+ /**
193
+ * Build an advisory-only proposal object. Never authorizes, signs, or
194
+ * broadcasts anything; the returned object cannot be mistaken for one that
195
+ * does because its authority markers are pinned to false/"proposal" and it is
196
+ * deep-frozen.
197
+ *
198
+ * @param {object} input
199
+ * @param {string} input.kind see risk-classifier.mjs for recognized kinds
200
+ * @param {string} [input.target] human-readable description of the target (e.g. "HL BTC-PERP")
201
+ * @param {number} [input.notionalUsd]
202
+ * @param {number} [input.chainId]
203
+ * @param {string} [input.venue]
204
+ * @param {boolean} [input.destinationKnown]
205
+ * @param {boolean} [input.unlimitedApproval]
206
+ * @param {boolean} [input.crossChain]
207
+ * @param {string} [input.note] free-text rationale; itself scanned for dangerous fields if an object is passed by mistake
208
+ * @param {number} [nowMs] injectable clock for deterministic tests
209
+ * @returns {object} frozen proposal
210
+ */
211
+ export function createProposal(input = {}, nowMs = Date.now()) {
212
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
213
+ throw new Error("proposal input must be a plain object");
214
+ }
215
+
216
+ // Step 1: reject. Scan the FULL raw input (not just the allowlisted
217
+ // subset) so a caller cannot smuggle a secret in under an allowed key name
218
+ // collision, nor bury one in an unlisted field and have it silently
219
+ // dropped without anyone noticing the attempt.
220
+ assertNoDangerousFields(input, "proposal input");
221
+
222
+ const kind = String(input.kind || "").trim().toLowerCase();
223
+ if (!kind) throw new Error("proposal input: kind is required");
224
+
225
+ // Step 2: strip / allowlist. Only known-safe fields are read from input.
226
+ const safeInput = pickAllowed(input);
227
+ safeInput.kind = kind;
228
+
229
+ const risk = classifyRisk({
230
+ kind,
231
+ notionalUsd: safeInput.notionalUsd,
232
+ destinationKnown: safeInput.destinationKnown,
233
+ unlimitedApproval: safeInput.unlimitedApproval,
234
+ crossChain: safeInput.crossChain,
235
+ });
236
+
237
+ const proposal = {
238
+ id: nextProposalId(Number(nowMs) || Date.now()),
239
+ createdAt: new Date(Number(nowMs) || Date.now()).toISOString(),
240
+
241
+ kind: safeInput.kind,
242
+ target: safeInput.target != null ? String(safeInput.target) : null,
243
+ notionalUsd: safeInput.notionalUsd != null ? Number(safeInput.notionalUsd) : null,
244
+ chainId: safeInput.chainId != null ? Number(safeInput.chainId) : null,
245
+ venue: safeInput.venue != null ? String(safeInput.venue) : null,
246
+ note: safeInput.note != null ? String(safeInput.note) : null,
247
+
248
+ risk: {
249
+ tier: risk.tier,
250
+ score: risk.score,
251
+ reasons: risk.reasons,
252
+ },
253
+
254
+ // Step 3: pinned advisory markers. These are NOT derived from input and
255
+ // cannot be overridden by any input field -- they are literal constants.
256
+ mode: "proposal",
257
+ advisoryOnly: true,
258
+ authorized: false,
259
+ signed: false,
260
+ broadcast: false,
261
+ requiresHumanConfirmation: true,
262
+ grantsPermissions: false,
263
+ capabilities: Object.freeze({
264
+ canClassifyRisk: true,
265
+ canExplain: true,
266
+ canSimulate: kind === "simulate",
267
+ canSign: false,
268
+ canBroadcast: false,
269
+ canAuthorize: false,
270
+ canMintCapability: false,
271
+ canAccessSecrets: false,
272
+ }),
273
+ };
274
+
275
+ // Belt-and-suspenders: re-verify the object we are about to hand out
276
+ // contains no dangerous keys before freezing, in case a future edit to
277
+ // ALLOWED_INPUT_FIELDS accidentally lets one through. allowPinnedSafe is
278
+ // required here because this module's own fixed advisory markers (e.g.
279
+ // "authorized", "broadcast", "canAccessSecrets") intentionally reuse
280
+ // wording from the dangerous-pattern list to stay self-documenting; they
281
+ // are hardcoded constants above, never derived from input.
282
+ assertNoDangerousFields(proposal, "proposal output", { allowPinnedSafe: true });
283
+
284
+ return deepFreeze(proposal);
285
+ }
286
+
287
+ /**
288
+ * Defense-in-depth guard for anything downstream that receives a proposal
289
+ * object from the router and wants to double check, before acting on it in
290
+ * any way, that it really is advisory-only. Throws if the object does not
291
+ * look like a well-formed, unauthorized proposal.
292
+ */
293
+ export function assertAdvisoryProposal(proposal) {
294
+ if (!proposal || typeof proposal !== "object") {
295
+ throw new Error("proposal required");
296
+ }
297
+ if (proposal.mode !== "proposal") throw new Error("proposal: mode must be \"proposal\"");
298
+ if (proposal.authorized !== false) throw new Error("proposal: authorized must be false");
299
+ if (proposal.signed !== false) throw new Error("proposal: signed must be false");
300
+ if (proposal.broadcast !== false) throw new Error("proposal: broadcast must be false");
301
+ if (proposal.advisoryOnly !== true) throw new Error("proposal: advisoryOnly must be true");
302
+ if (proposal.grantsPermissions !== false) {
303
+ throw new Error("proposal: grantsPermissions must be false");
304
+ }
305
+ const caps = proposal.capabilities || {};
306
+ if (caps.canSign || caps.canBroadcast || caps.canAuthorize || caps.canMintCapability || caps.canAccessSecrets) {
307
+ throw new Error("proposal: capabilities must not grant sign/broadcast/authorize/mint/secret access");
308
+ }
309
+ assertNoDangerousFields(proposal, "proposal", { allowPinnedSafe: true });
310
+ return true;
311
+ }