@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,412 @@
1
+ // Oracle Control — end-to-end session orchestrator (Slice J).
2
+ //
3
+ // Pure GLUE. This module composes the already-tested public lanes into one
4
+ // plan -> activate -> revoke -> describe lifecycle and adds NO new custody,
5
+ // NO new crypto, NO new policy. Every capability below is an import:
6
+ //
7
+ // plan — policy-schema.validateGrant + connect-agent.assembleUnsignedGrant
8
+ // activate — session-key-model.createSessionGrant + aa-adapter
9
+ // (encodeSessionKeyInstall / buildUserOperation)
10
+ // revoke — aa-adapter.revokeSessionKey + session-key-model's
11
+ // createRevocationRegistry entry shape
12
+ // describe — grant-indexer.reconstructGrantIndex
13
+ //
14
+ // Hard boundaries (same posture as every other public-control module):
15
+ // - NEVER signs. There is no signer here. activateSession() verifies the
16
+ // owner's grant signature before assembly but never stores or returns it.
17
+ // Every userOp leaving this module has signature: "0x".
18
+ // - NEVER imports the private executor stack (get-signer.mjs, keystore.mjs,
19
+ // exec-policy.mjs, local-signer/*, adapters/*, mint-capability.mjs).
20
+ // - Fail-closed no-secret invariant: every object returned from this module
21
+ // is scanned with connect-agent's assertNoSecretMaterial (see
22
+ // scanPublicReturn below for the two documented, narrow redactions).
23
+ //
24
+ // CRITICAL UNIT RULE (control lane vs AA lane):
25
+ // - policy-schema / grant-indexer / connect-agent speak UNIX SECONDS
26
+ // (`expiresAt`, `now`).
27
+ // - session-key-model / aa-adapter speak MILLISECONDS (`expiresAtMs`,
28
+ // `issuedAtMs`, `nowMs`).
29
+ // Every crossing in this file converts EXPLICITLY:
30
+ // seconds -> ms: seconds * 1000
31
+ // ms -> seconds: Math.floor(ms / 1000)
32
+ // and is marked with a "UNIT BOUNDARY" comment.
33
+
34
+ import {
35
+ assembleUnsignedGrant,
36
+ assertNoSecretMaterial,
37
+ SIGNING_SCHEME,
38
+ } from "../public-api/connect-agent.mjs";
39
+ import { validateGrant, grantId as computeControlGrantId, GrantValidationError } from "./policy-schema.mjs";
40
+ import { reconstructGrantIndex } from "./grant-indexer.mjs";
41
+ import {
42
+ createSessionGrant,
43
+ createRevocationRegistry,
44
+ PROVIDERS,
45
+ } from "./session-key-model.mjs";
46
+ import {
47
+ encodeSessionKeyInstall,
48
+ revokeSessionKey,
49
+ buildUserOperation,
50
+ } from "./aa-adapter.mjs";
51
+ import { getBytes, verifyMessage } from "ethers";
52
+
53
+ export const ORCHESTRATOR_KINDS = Object.freeze({
54
+ PLAN: "oracle-session-plan",
55
+ ACTIVATION: "oracle-session-activation",
56
+ REVOCATION: "oracle-session-revocation",
57
+ DESCRIPTION: "oracle-session-description",
58
+ });
59
+
60
+ export { SIGNING_SCHEME };
61
+
62
+ function fail(message) {
63
+ throw new Error(`session-orchestrator: ${message}`);
64
+ }
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // No-secret scan for orchestrator returns
68
+ // ---------------------------------------------------------------------------
69
+ //
70
+ // connect-agent's assertNoSecretMaterial is intentionally stricter than this
71
+ // lane's data: it forbids ANY `signature` key and ANY 0x+64-hex string value
72
+ // (the shape of a raw EVM private key). Two values in the AA lane are public
73
+ // by design yet share those shapes:
74
+ //
75
+ // 1. userOp.signature — ALWAYS the empty placeholder "0x" here (unsigned).
76
+ // We PROVE it is exactly "0x" and then strip the key from the scan
77
+ // clone. A signature key holding anything else fails closed.
78
+ // 2. session ids — sha256-derived 0x+64-hex PUBLIC identifiers produced by
79
+ // session-key-model.computeSessionId. They are redacted in the scan
80
+ // clone ONLY when sitting at the known id keys below. A 0x+64-hex
81
+ // value at ANY other key (i.e. anything that could be a smuggled raw
82
+ // private key) still fails closed.
83
+ //
84
+ // The ORIGINAL object is returned untouched; only the scan clone is redacted.
85
+
86
+ const SESSION_ID_KEYS = Object.freeze(["id", "sessionId"]);
87
+ const SESSION_ID_RE = /^0x[0-9a-fA-F]{64}$/;
88
+
89
+ function redactForScan(value, keyName) {
90
+ if (value == null || typeof value !== "object") {
91
+ if (
92
+ typeof value === "string" &&
93
+ SESSION_ID_KEYS.includes(keyName) &&
94
+ SESSION_ID_RE.test(value)
95
+ ) {
96
+ // Public sha256 session id (see header note 2): scan the bare hex so
97
+ // the raw-32-byte-hex-key value rule doesn't misfire, while keeping
98
+ // the content itself scannable.
99
+ return `session-id:${value.slice(2)}`;
100
+ }
101
+ return value;
102
+ }
103
+ if (Array.isArray(value)) return value.map((v) => redactForScan(v, null));
104
+ const out = {};
105
+ for (const [k, v] of Object.entries(value)) {
106
+ if (k === "signature") {
107
+ // See header note 1: unsigned invariant is PROVEN, then the key is
108
+ // dropped from the scan clone only.
109
+ if (v !== "0x") {
110
+ fail(
111
+ `refusing to return a userOp whose signature is not the empty "0x" placeholder (this module never signs)`
112
+ );
113
+ }
114
+ continue;
115
+ }
116
+ out[k] = redactForScan(v, k);
117
+ }
118
+ return out;
119
+ }
120
+
121
+ /** Fail-closed scan of an orchestrator return value. Throws SecretLeakError /
122
+ * Error on anything secret-shaped; returns the ORIGINAL value unchanged. */
123
+ export function scanPublicReturn(value) {
124
+ assertNoSecretMaterial(redactForScan(value, null));
125
+ return value;
126
+ }
127
+
128
+ function deepFreeze(value) {
129
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
130
+ Object.freeze(value);
131
+ for (const v of Object.values(value)) deepFreeze(v);
132
+ }
133
+ return value;
134
+ }
135
+
136
+ // ---------------------------------------------------------------------------
137
+ // 1. planConnection
138
+ // ---------------------------------------------------------------------------
139
+
140
+ /**
141
+ * Validate a raw control-lane grant and assemble the UNSIGNED payload the
142
+ * owner reviews and signs in their own wallet.
143
+ *
144
+ * Out-of-policy input is refused HERE, before anything downstream sees it:
145
+ * validateGrant() fails closed (unknown fields, wildcard actions, empty
146
+ * targets for state-changing scopes, expired grants when opts.now is given)
147
+ * and this function throws its GrantValidationError verbatim.
148
+ *
149
+ * @param {object} input raw grant fields (policy-schema REQUIRED_FIELDS;
150
+ * `expiresAt` is UNIX SECONDS)
151
+ * @param {object} [opts]
152
+ * @param {number} [opts.now] unix SECONDS — enables the liveness check
153
+ * @returns frozen { kind, grantId, grant, unsignedGrant, signingBytes, render }
154
+ */
155
+ export function planConnection(input, opts = {}) {
156
+ // Control lane: validateGrant speaks UNIX SECONDS (expiresAt, opts.now).
157
+ const verdict = validateGrant(input, { now: opts.now });
158
+ if (!verdict.ok) {
159
+ // Refused at the door — out-of-policy grants never reach assembly.
160
+ throw new GrantValidationError(verdict.errors);
161
+ }
162
+
163
+ const unsignedGrant = assembleUnsignedGrant(verdict.grant, { now: opts.now });
164
+
165
+ const result = deepFreeze({
166
+ kind: ORCHESTRATOR_KINDS.PLAN,
167
+ unsigned: true,
168
+ grantId: unsignedGrant.payload.grantId,
169
+ grant: verdict.grant,
170
+ unsignedGrant,
171
+ signingBytes: unsignedGrant.signing,
172
+ render: unsignedGrant.render,
173
+ });
174
+ return scanPublicReturn(result);
175
+ }
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // 2. activateSession
179
+ // ---------------------------------------------------------------------------
180
+
181
+ function normalizeOwnerSignature(ownerSignature) {
182
+ if (typeof ownerSignature !== "string" || ownerSignature.trim() === "") {
183
+ fail("ownerSignature is required (the owner must have signed the grant in their own wallet)");
184
+ }
185
+ const sig = ownerSignature.trim();
186
+ if (!/^0x[0-9a-fA-F]+$/.test(sig) || sig === "0x") {
187
+ fail("ownerSignature must be non-empty 0x-prefixed hex");
188
+ }
189
+ return sig;
190
+ }
191
+
192
+ async function verifyOwnerApproval({ grant, ownerSignature, verifyOwnerSignature }) {
193
+ const signature = normalizeOwnerSignature(ownerSignature);
194
+ const unsignedGrant = assembleUnsignedGrant(grant);
195
+ if (typeof verifyOwnerSignature === "function") {
196
+ const approved = await verifyOwnerSignature({
197
+ grant,
198
+ ownerSignature: signature,
199
+ signingBytes: unsignedGrant.signing,
200
+ });
201
+ if (approved !== true) fail("ownerSignature verification failed");
202
+ return;
203
+ }
204
+ try {
205
+ const recovered = verifyMessage(getBytes(unsignedGrant.signing.bytesHex), signature);
206
+ if (recovered.toLowerCase() !== grant.accountAddress.toLowerCase()) {
207
+ fail("ownerSignature signer does not match grant accountAddress");
208
+ }
209
+ } catch (error) {
210
+ if (String(error?.message || "").startsWith("session-orchestrator:")) throw error;
211
+ fail("ownerSignature could not be verified; smart accounts must provide verifyOwnerSignature");
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Bridge an owner-approved control-lane grant (UNIX SECONDS) into the AA
217
+ * lane (MILLISECONDS): create the session-key-model grant, encode install
218
+ * calldata, and assemble the UNSIGNED ERC-4337 userOp that carries it.
219
+ *
220
+ * NEVER signs. The returned userOp always has signature "0x", and the
221
+ * ownerSignature the caller proved possession of is not part of the return.
222
+ *
223
+ * @param {object} params
224
+ * @param {object} params.grant control-lane grant (policy-schema shape,
225
+ * `expiresAt` in UNIX SECONDS). Re-validated.
226
+ * @param {string} params.ownerSignature owner's grant signature, verified
227
+ * against accountAddress for EOAs.
228
+ * @param {object} params.sessionKeyModel AA-lane parameters:
229
+ * provider one of session-key-model PROVIDERS (default permissionless-viem)
230
+ * moduleAddress REQUIRED deployed session-key module address
231
+ * issuedAtMs REQUIRED epoch MILLISECONDS issuance instant (explicit for
232
+ * determinism; also used as the active-check nowMs)
233
+ * abi optional module ABI override
234
+ * userOp REQUIRED buildUserOperation params minus sender/callData:
235
+ * { nonce | client, callGasLimit, verificationGasLimit,
236
+ * preVerificationGas, maxFeePerGas, maxPriorityFeePerGas, ... }
237
+ * @returns frozen { kind, unsigned, grantId, sessionId, sessionGrant,
238
+ * install, userOp, units }
239
+ */
240
+ async function activateSessionWithVerifier(
241
+ { grant, ownerSignature, sessionKeyModel } = {},
242
+ verifyOwnerSignature,
243
+ ) {
244
+ if (sessionKeyModel == null || typeof sessionKeyModel !== "object") {
245
+ fail("sessionKeyModel is required ({ provider?, moduleAddress, issuedAtMs, userOp })");
246
+ }
247
+ const {
248
+ provider = PROVIDERS.PERMISSIONLESS_VIEM,
249
+ moduleAddress,
250
+ issuedAtMs,
251
+ abi,
252
+ userOp: userOpParams,
253
+ } = sessionKeyModel;
254
+
255
+ if (!Number.isFinite(Number(issuedAtMs))) {
256
+ fail("sessionKeyModel.issuedAtMs (epoch MILLISECONDS) is required for a deterministic session grant");
257
+ }
258
+ if (userOpParams == null || typeof userOpParams !== "object") {
259
+ fail("sessionKeyModel.userOp (gas/fee/nonce params for buildUserOperation) is required");
260
+ }
261
+
262
+ // Control lane: re-validate the grant (expiresAt in UNIX SECONDS).
263
+ // UNIT BOUNDARY (SECONDS -> for the liveness check we pass the AA-lane
264
+ // instant down-converted): now = Math.floor(issuedAtMs / 1000).
265
+ const verdict = validateGrant(grant, { now: Math.floor(Number(issuedAtMs) / 1000) });
266
+ if (!verdict.ok) throw new GrantValidationError(verdict.errors);
267
+ const controlGrant = verdict.grant;
268
+ await verifyOwnerApproval({ grant: controlGrant, ownerSignature, verifyOwnerSignature });
269
+
270
+ // UNIT BOUNDARY (SECONDS -> MILLISECONDS): the control lane's expiresAt is
271
+ // UNIX SECONDS; session-key-model requires expiresAtMs in MILLISECONDS.
272
+ const expiresAtMs = controlGrant.expiresAt * 1000;
273
+
274
+ const sessionGrant = createSessionGrant({
275
+ provider,
276
+ owner: controlGrant.accountAddress, // owner smart account
277
+ agent: controlGrant.agentAddress, // session key address
278
+ chainId: controlGrant.chainId,
279
+ actions: controlGrant.actions,
280
+ targets: controlGrant.targets,
281
+ maxValueWei: controlGrant.maxValueWei,
282
+ maxGasWei: controlGrant.maxGasWei,
283
+ expiresAtMs, // MILLISECONDS (converted above)
284
+ nonce: controlGrant.nonce,
285
+ issuedAtMs: Number(issuedAtMs), // MILLISECONDS
286
+ });
287
+
288
+ // AA lane: encodeSessionKeyInstall / sessionStatus speak MILLISECONDS.
289
+ const install = encodeSessionKeyInstall(sessionGrant, {
290
+ moduleAddress,
291
+ abi,
292
+ nowMs: Number(issuedAtMs),
293
+ });
294
+
295
+ // UNSIGNED ERC-4337 envelope. buildUserOperation always emits
296
+ // signature: "0x" — scanPublicReturn additionally proves it below.
297
+ const userOp = await buildUserOperation({
298
+ ...userOpParams,
299
+ sender: controlGrant.accountAddress,
300
+ callData: install.data,
301
+ });
302
+
303
+ const result = deepFreeze({
304
+ kind: ORCHESTRATOR_KINDS.ACTIVATION,
305
+ unsigned: true,
306
+ grantId: computeControlGrantId(controlGrant), // control-lane public id (bare sha256 hex)
307
+ sessionId: sessionGrant.id,
308
+ sessionGrant,
309
+ install,
310
+ userOp,
311
+ units: {
312
+ // Both representations surfaced so callers/tests can audit the
313
+ // SECONDS<->MILLISECONDS conversion explicitly.
314
+ expiresAtSeconds: controlGrant.expiresAt,
315
+ expiresAtMs: sessionGrant.expiresAtMs,
316
+ },
317
+ });
318
+ return scanPublicReturn(result);
319
+ }
320
+
321
+ export async function activateSession(params = {}) {
322
+ return activateSessionWithVerifier(params, undefined);
323
+ }
324
+
325
+ export function createSessionOrchestrator({ verifyOwnerSignature } = {}) {
326
+ if (typeof verifyOwnerSignature !== "function") {
327
+ fail("createSessionOrchestrator requires a trusted verifyOwnerSignature function");
328
+ }
329
+ const trustedVerifier = verifyOwnerSignature;
330
+ return Object.freeze({
331
+ activateSession(params = {}) {
332
+ return activateSessionWithVerifier(params, trustedVerifier);
333
+ },
334
+ });
335
+ }
336
+
337
+ // ---------------------------------------------------------------------------
338
+ // 3. revokeSession
339
+ // ---------------------------------------------------------------------------
340
+
341
+ /**
342
+ * Revoke a session: deterministic revoke calldata for the on-chain module
343
+ * plus the off-chain revocation-registry entry Oracle Control's policy
344
+ * checks consume.
345
+ *
346
+ * @param {object|string} grantOrSessionId session-key-model grant or raw id
347
+ * @param {object} opts
348
+ * @param {string} opts.moduleAddress REQUIRED session-key module address
349
+ * @param {object} [opts.registry] createRevocationRegistry() instance to
350
+ * record into (a fresh one is created —
351
+ * and returned — when omitted)
352
+ * @param {number} [opts.nowMs] epoch MILLISECONDS revocation instant
353
+ * @param {string} [opts.reason]
354
+ * @returns frozen { kind, sessionId, revoke, revocation:{revokedAtMs,reason}, registry }
355
+ */
356
+ export function revokeSession(grantOrSessionId, opts = {}) {
357
+ const revoke = revokeSessionKey(grantOrSessionId, {
358
+ moduleAddress: opts.moduleAddress,
359
+ abi: opts.abi,
360
+ });
361
+
362
+ const sessionId =
363
+ typeof grantOrSessionId === "string" ? grantOrSessionId : grantOrSessionId.id;
364
+
365
+ // AA lane registry speaks MILLISECONDS (revokedAtMs).
366
+ const registry = opts.registry ?? createRevocationRegistry();
367
+ const entry = registry.revoke(sessionId, {
368
+ nowMs: opts.nowMs ?? Date.now(), // MILLISECONDS
369
+ reason: opts.reason ?? null,
370
+ });
371
+
372
+ const result = {
373
+ kind: ORCHESTRATOR_KINDS.REVOCATION,
374
+ sessionId,
375
+ revoke,
376
+ revocation: Object.freeze({ revokedAtMs: entry.revokedAtMs, reason: entry.reason }),
377
+ // The live registry is handed back for the caller's subsequent
378
+ // sessionStatus / checkSessionAuthorized calls; not frozen on purpose.
379
+ registry,
380
+ };
381
+ Object.freeze(result);
382
+ deepFreeze(result.revoke);
383
+ return scanPublicReturn(result);
384
+ }
385
+
386
+ // ---------------------------------------------------------------------------
387
+ // 4. describeActive
388
+ // ---------------------------------------------------------------------------
389
+
390
+ /**
391
+ * Reconstruct the control-lane grant index from an event log and return the
392
+ * currently-active grants.
393
+ *
394
+ * @param {object[]} events grant-indexer event log
395
+ * @param {number} now UNIX SECONDS reference instant (control lane)
396
+ * @returns frozen { kind, now, active, count, index }
397
+ */
398
+ export function describeActive(events, now) {
399
+ // Control lane: reconstructGrantIndex speaks UNIX SECONDS (`now`,
400
+ // record.expiresAt). No conversion happens here — callers holding a
401
+ // MILLISECONDS clock must pass Math.floor(ms / 1000) themselves.
402
+ const index = reconstructGrantIndex(events, { now });
403
+
404
+ const result = deepFreeze({
405
+ kind: ORCHESTRATOR_KINDS.DESCRIPTION,
406
+ now,
407
+ active: index.active,
408
+ count: index.active.length,
409
+ index,
410
+ });
411
+ return scanPublicReturn(result);
412
+ }
@@ -0,0 +1,132 @@
1
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
2
+ import { isAddress } from "ethers";
3
+ import { assertAutoSlippageGuard } from "./auto-slippage.mjs";
4
+ import { resolveAttestationSecret } from "./attestation-secret.mjs";
5
+ import { assertFreshWindow } from "./fresh-window.mjs";
6
+
7
+ const DEFAULT_ROUTE_ATTESTATION_TTL_MS = 20_000;
8
+
9
+ function canonicalJson(value) {
10
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
11
+ if (value && typeof value === "object") {
12
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(",")}}`;
13
+ }
14
+ return JSON.stringify(value);
15
+ }
16
+
17
+ function normalAddress(value, label) {
18
+ const text = String(value || "").trim();
19
+ if (!isAddress(text)) throw new Error(`${label} must be an address`);
20
+ return text.toLowerCase();
21
+ }
22
+
23
+ function normalData(value) {
24
+ const data = String(value || "0x").toLowerCase();
25
+ if (!/^0x(?:[0-9a-f]{2})*$/.test(data)) throw new Error("route attestation calldata must be hex bytes");
26
+ return data;
27
+ }
28
+
29
+ function hashText(value) {
30
+ return `0x${createHash("sha256").update(String(value)).digest("hex")}`;
31
+ }
32
+
33
+ function hmac(secret, payload) {
34
+ return `0x${createHmac("sha256", String(secret)).update(payload).digest("hex")}`;
35
+ }
36
+
37
+ function sameSignature(a, b) {
38
+ const left = Buffer.from(String(a || "").replace(/^0x/, ""), "hex");
39
+ const right = Buffer.from(String(b || "").replace(/^0x/, ""), "hex");
40
+ return left.length === right.length && left.length > 0 && timingSafeEqual(left, right);
41
+ }
42
+
43
+ function routeSecret(secret) {
44
+ return resolveAttestationSecret(
45
+ secret,
46
+ "ORACLE_ROUTE_ATTESTATION_SECRET",
47
+ "MAD_ROUTE_ATTESTATION_SECRET",
48
+ );
49
+ }
50
+
51
+ function unsigned(attestation) {
52
+ const { signature: _signature, ...payload } = attestation;
53
+ return payload;
54
+ }
55
+
56
+ export function routeCalldataHash(data) {
57
+ return hashText(normalData(data));
58
+ }
59
+
60
+ export function routeSlippageHash(slippageGuard) {
61
+ if (!slippageGuard) throw new Error("route attestation requires slippage guard");
62
+ return hashText(canonicalJson(slippageGuard));
63
+ }
64
+
65
+ export function createRouteAttestation({
66
+ provider,
67
+ chainId,
68
+ sender,
69
+ to,
70
+ destination,
71
+ data,
72
+ value = "0",
73
+ slippageGuard,
74
+ nowMs = Date.now(),
75
+ ttlMs = DEFAULT_ROUTE_ATTESTATION_TTL_MS,
76
+ secret,
77
+ } = {}) {
78
+ const target = normalAddress(destination || to, "route destination");
79
+ const attestation = {
80
+ mode: "route-attestation",
81
+ version: 1,
82
+ provider: String(provider || "").trim(),
83
+ chainId: Number(chainId),
84
+ sender: sender ? normalAddress(sender, "route sender") : null,
85
+ destination: target,
86
+ calldataHash: routeCalldataHash(data),
87
+ value: String(value ?? "0"),
88
+ slippageHash: routeSlippageHash(slippageGuard),
89
+ issuedAtMs: Number(nowMs),
90
+ expiresAtMs: Number(nowMs) + Number(ttlMs),
91
+ };
92
+ if (!attestation.provider) throw new Error("route attestation provider required");
93
+ if (!Number.isFinite(attestation.chainId)) throw new Error("route attestation chainId required");
94
+ const payload = canonicalJson(attestation);
95
+ return { ...attestation, signature: hmac(routeSecret(secret), payload) };
96
+ }
97
+
98
+ export function assertRouteAttestation(attestation, tx = {}, { chainId, nowMs = Date.now(), secret } = {}) {
99
+ // Time is a security parameter: an unusable clock must fail CLOSED,
100
+ // otherwise NaN/null/-Infinity silently makes this attestation eternal.
101
+ assertFreshWindow(attestation || {}, nowMs, "route attestation");
102
+ if (!attestation || attestation.mode !== "route-attestation") throw new Error("route attestation required");
103
+ if (Number(attestation.expiresAtMs) <= Number(nowMs)) throw new Error("route attestation expired");
104
+ if (Number(attestation.chainId) !== Number(chainId ?? tx.chainId)) throw new Error("route attestation chain mismatch");
105
+ const to = normalAddress(tx.to, "route tx.to");
106
+ if (normalAddress(attestation.destination, "route destination") !== to) throw new Error("route attestation destination mismatch");
107
+ if (tx.from && attestation.sender && normalAddress(attestation.sender, "route sender") !== normalAddress(tx.from, "route tx.from")) {
108
+ throw new Error("route attestation sender mismatch");
109
+ }
110
+ if (String(attestation.value) !== String(tx.value ?? "0")) throw new Error("route attestation value mismatch");
111
+ if (attestation.calldataHash !== routeCalldataHash(tx.data || "0x")) throw new Error("route attestation calldata mismatch");
112
+ if (attestation.slippageHash !== routeSlippageHash(tx.slippageGuard ?? tx.madSlippage)) {
113
+ throw new Error("route attestation slippage mismatch");
114
+ }
115
+ const expected = hmac(routeSecret(secret), canonicalJson(unsigned(attestation)));
116
+ if (!sameSignature(attestation.signature, expected)) throw new Error("route attestation signature mismatch");
117
+ // Third call site. exec-policy and protocol-execution both demand an
118
+ // authenticated, calldata-bound guard; this path asked for neither, so a
119
+ // dynamic route destination got a weaker slippage check than a static one.
120
+ // The attestation's own calldataHash/slippageHash made it non-exploitable,
121
+ // but a guard boundary that differs by which door you came through is the
122
+ // shape every one of these findings has had. Same bar on all three.
123
+ assertAutoSlippageGuard(tx.slippageGuard ?? tx.madSlippage, {
124
+ chainId: Number(chainId ?? tx.chainId),
125
+ venue: to,
126
+ nowMs,
127
+ secret,
128
+ tx: { ...tx, chainId: Number(chainId ?? tx.chainId), to, data: tx.data },
129
+ requireSigned: true,
130
+ });
131
+ return true;
132
+ }