@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,374 @@
1
+ // Oracle Control — provider-neutral account-abstraction session-key model.
2
+ //
3
+ // This is a design spike (Slice B / Phase 2 of the Oracle public release plan,
4
+ // see artifacts/oracle-public-plan.md and docs/public-self-custody-aa.md).
5
+ // It defines the SHAPE of a public self-custody session-key grant and the
6
+ // deterministic policy checks that decide whether a proposed action is
7
+ // authorized by that grant — independent of which account-abstraction stack
8
+ // (Safe, Kernel/ZeroDev, Biconomy/Nexus, permissionless/viem) eventually
9
+ // enforces it on-chain.
10
+ //
11
+ // Hard boundaries for this file:
12
+ // - No wallet/AA SDK imports. No RPC calls. No live chain integration.
13
+ // - No import from the private executor stack (get-signer.mjs, keystore.mjs,
14
+ // exec-policy.mjs, local-signer/*, oracle-env.mjs, adapters/*). This model
15
+ // must stand alone so it can never be wired to a private operator wallet.
16
+ // - Deterministic, pure functions only — same input always produces the
17
+ // same session id and the same authorization verdict.
18
+ // - `owner` (the user's main wallet / smart-account) never signs a
19
+ // transaction here. This module only decides whether an already-proposed
20
+ // action fits inside an already-granted, bounded session.
21
+ //
22
+ // Terminology:
23
+ // grant — the bounded permission the owner signed (chain, actions,
24
+ // targets, value/gas caps, expiry). Provider-neutral; a real
25
+ // integration maps this onto a Safe allowance module, a ZeroDev
26
+ // session-key validator, a Biconomy Nexus session module, or a
27
+ // permissionless/viem session account.
28
+ // agent — the session key address the grant authorizes to act. Never the
29
+ // owner's main key.
30
+ // request — a single proposed action (action id, target, value, gas) that
31
+ // is checked against a grant before anything is prepared/signed.
32
+
33
+ import { createHash } from "node:crypto";
34
+ import { exactBigInt } from "../exact-integer.mjs";
35
+ import { isWindowOpen } from "../fresh-window.mjs";
36
+
37
+ /** Account-abstraction stacks this model is written to be portable across.
38
+ * Purely descriptive — no SDK behavior is implied or imported here. */
39
+ export const PROVIDERS = Object.freeze({
40
+ SAFE: "safe",
41
+ KERNEL_ZERODEV: "kernel-zerodev",
42
+ BICONOMY_NEXUS: "biconomy-nexus",
43
+ PERMISSIONLESS_VIEM: "permissionless-viem",
44
+ });
45
+
46
+ export const PROVIDER_IDS = Object.freeze(Object.values(PROVIDERS));
47
+
48
+ /** Session lifecycle states returned by sessionStatus(). */
49
+ export const SESSION_STATUS = Object.freeze({
50
+ ACTIVE: "active",
51
+ EXPIRED: "expired",
52
+ REVOKED: "revoked",
53
+ });
54
+
55
+ /** Action-id prefixes that never move funds or touch a target contract and
56
+ * therefore never require a non-empty target allowlist. Matches the "empty
57
+ * target allowlist only allowed for read/simulate scopes" rule in the Oracle
58
+ * public policy schema (artifacts/oracle-public-plan.md Phase 1). */
59
+ const READ_ONLY_ACTION_PREFIXES = ["read:", "simulate:"];
60
+
61
+ const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
62
+ const HEX32_RE = /^0x[0-9a-fA-F]{64}$/;
63
+
64
+ function isReadOnlyAction(action) {
65
+ const a = String(action || "");
66
+ return READ_ONLY_ACTION_PREFIXES.some((p) => a.startsWith(p));
67
+ }
68
+
69
+ function fail(message) {
70
+ throw new Error(`session: ${message}`);
71
+ }
72
+
73
+ function normalAddress(value, label) {
74
+ const text = String(value ?? "").trim().toLowerCase();
75
+ if (!ADDRESS_RE.test(text)) fail(`${label} must be a 0x-prefixed 20-byte address`);
76
+ return text;
77
+ }
78
+
79
+ function normalActionId(value) {
80
+ const text = String(value ?? "").trim().toLowerCase();
81
+ if (!text) fail("action ids must be non-empty strings");
82
+ if (text.length > 128) fail("action id too long");
83
+ return text;
84
+ }
85
+
86
+ function normalPositiveInt(value, label) {
87
+ const n = Number(value);
88
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) fail(`${label} must be a positive integer`);
89
+ return n;
90
+ }
91
+
92
+ function normalBigString(value, label, { allowZero = true } = {}) {
93
+ if (value == null || value === "") return "0";
94
+ // Wei caps bound delegated spend. An unsafe JS number rounds UP here and
95
+ // stores a looser cap than the owner wrote, so refuse rather than coerce.
96
+ let n;
97
+ try {
98
+ n = exactBigInt(value, label);
99
+ } catch (e) {
100
+ fail(e.message);
101
+ }
102
+ if (n < 0n) fail(`${label} must not be negative`);
103
+ if (!allowZero && n === 0n) fail(`${label} must be greater than zero`);
104
+ return n.toString();
105
+ }
106
+
107
+ /** Deterministic JSON: object keys sorted recursively, matching the
108
+ * canonicalJson convention already used by audit-log.mjs / vault-attestation.mjs
109
+ * so the same fields hash identically everywhere. Self-contained here on
110
+ * purpose (no cross-file import) to keep this design-spike file standalone. */
111
+ export function canonicalJson(value) {
112
+ if (value === null || value === undefined) return "null";
113
+ if (typeof value !== "object") return JSON.stringify(value);
114
+ if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
115
+ const keys = Object.keys(value).sort();
116
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalJson(value[k])).join(",") + "}";
117
+ }
118
+
119
+ /**
120
+ * Deterministic session id: sha256 over the canonical JSON of the grant's
121
+ * identity fields, prefixed 0x. Two grants with identical owner/agent/chain/
122
+ * actions/targets/caps/expiry/nonce always produce the same id; changing any
123
+ * field (including the ordering-insensitive actions/targets arrays, which are
124
+ * sorted before hashing) changes the id.
125
+ */
126
+ export function computeSessionId(fields) {
127
+ const h = createHash("sha256");
128
+ h.update(canonicalJson(fields), "utf8");
129
+ return `0x${h.digest("hex")}`;
130
+ }
131
+
132
+ /**
133
+ * Build and validate a provider-neutral session grant. Throws on any
134
+ * malformed/unsafe input (fail-closed). Returns a deep-frozen record.
135
+ *
136
+ * @param {object} input
137
+ * @param {string} input.provider one of PROVIDERS (informational; which
138
+ * AA stack is expected to enforce this)
139
+ * @param {string} input.owner user's main wallet / smart-account address
140
+ * @param {string} input.agent session key address (must differ from owner)
141
+ * @param {number} input.chainId positive integer chain id
142
+ * @param {string[]} input.actions non-empty list of action ids (e.g.
143
+ * "erc20:transfer", "swap:exec", "read:balance")
144
+ * @param {string[]} [input.targets] allowed destination addresses. May be
145
+ * empty ONLY if every action is read/simulate.
146
+ * @param {string|number|bigint} [input.maxValueWei] native-value cap (default "0")
147
+ * @param {string|number|bigint} [input.maxGasWei] optional gas-fee cap (gasLimit*feePerGas)
148
+ * @param {number} input.expiresAtMs epoch ms the grant stops being valid
149
+ * @param {string|number} [input.nonce] uniqueness salt (default 0)
150
+ * @param {number} [input.issuedAtMs] epoch ms issuance time (default Date.now())
151
+ */
152
+ export function createSessionGrant({
153
+ provider,
154
+ owner,
155
+ agent,
156
+ chainId,
157
+ actions,
158
+ targets = [],
159
+ maxValueWei = "0",
160
+ maxGasWei,
161
+ expiresAtMs,
162
+ nonce = 0,
163
+ issuedAtMs = Date.now(),
164
+ } = {}) {
165
+ const normalizedProvider = String(provider ?? "").trim().toLowerCase();
166
+ if (!PROVIDER_IDS.includes(normalizedProvider)) {
167
+ fail(`provider must be one of ${PROVIDER_IDS.join(", ")}`);
168
+ }
169
+
170
+ const normalizedOwner = normalAddress(owner, "owner");
171
+ const normalizedAgent = normalAddress(agent, "agent");
172
+ if (normalizedOwner === normalizedAgent) fail("agent key must differ from owner wallet");
173
+
174
+ const normalizedChainId = normalPositiveInt(chainId, "chainId");
175
+
176
+ if (!Array.isArray(actions) || actions.length === 0) fail("actions must be a non-empty array");
177
+ const normalizedActions = [...new Set(actions.map(normalActionId))].sort();
178
+
179
+ if (!Array.isArray(targets)) fail("targets must be an array");
180
+ const normalizedTargets = [...new Set(targets.map((t) => normalAddress(t, "target")))].sort();
181
+
182
+ const allActionsReadOnly = normalizedActions.every(isReadOnlyAction);
183
+ if (normalizedTargets.length === 0 && !allActionsReadOnly) {
184
+ fail("empty target allowlist is only allowed when every action is read/simulate");
185
+ }
186
+
187
+ const normalizedMaxValueWei = normalBigString(maxValueWei, "maxValueWei");
188
+ const normalizedMaxGasWei = maxGasWei == null ? null : normalBigString(maxGasWei, "maxGasWei");
189
+
190
+ const normalizedIssuedAtMs = Number(issuedAtMs);
191
+ if (!Number.isFinite(normalizedIssuedAtMs)) fail("issuedAtMs must be a finite number");
192
+ const normalizedExpiresAtMs = Number(expiresAtMs);
193
+ if (!Number.isFinite(normalizedExpiresAtMs)) fail("expiresAtMs must be a finite number");
194
+ if (normalizedExpiresAtMs <= normalizedIssuedAtMs) fail("expiresAtMs must be after issuedAtMs");
195
+
196
+ const normalizedNonce = String(nonce ?? 0);
197
+
198
+ const identity = {
199
+ mode: "oracle-session-grant",
200
+ version: 1,
201
+ provider: normalizedProvider,
202
+ owner: normalizedOwner,
203
+ agent: normalizedAgent,
204
+ chainId: normalizedChainId,
205
+ actions: normalizedActions,
206
+ targets: normalizedTargets,
207
+ maxValueWei: normalizedMaxValueWei,
208
+ maxGasWei: normalizedMaxGasWei,
209
+ issuedAtMs: normalizedIssuedAtMs,
210
+ expiresAtMs: normalizedExpiresAtMs,
211
+ nonce: normalizedNonce,
212
+ };
213
+
214
+ const id = computeSessionId(identity);
215
+ const grant = { id, ...identity };
216
+ return Object.freeze(grant);
217
+ }
218
+
219
+ /** In-memory revocation registry. Deterministic, no chain dependency — a real
220
+ * integration backs this with an on-chain revoke (Safe module disable,
221
+ * ZeroDev/Biconomy session revoke) or an off-chain indexer; the interface
222
+ * here is what Oracle Control's policy check consumes either way. */
223
+ export function createRevocationRegistry() {
224
+ const revoked = new Map(); // sessionId -> { revokedAtMs, reason }
225
+ return {
226
+ revoke(sessionId, { nowMs = Date.now(), reason = null } = {}) {
227
+ if (!sessionId) fail("revoke requires a sessionId");
228
+ if (!revoked.has(sessionId)) revoked.set(sessionId, { revokedAtMs: Number(nowMs), reason });
229
+ return revoked.get(sessionId);
230
+ },
231
+ isRevoked(sessionId) {
232
+ return revoked.has(sessionId);
233
+ },
234
+ revokedAt(sessionId) {
235
+ return revoked.get(sessionId)?.revokedAtMs ?? null;
236
+ },
237
+ get size() {
238
+ return revoked.size;
239
+ },
240
+ };
241
+ }
242
+
243
+ function isRevokedGrant(grant, revocation) {
244
+ if (!revocation) return false;
245
+ if (typeof revocation.isRevoked === "function") return revocation.isRevoked(grant.id);
246
+ if (revocation instanceof Set) return revocation.has(grant.id);
247
+ if (Array.isArray(revocation)) return revocation.includes(grant.id);
248
+ return false;
249
+ }
250
+
251
+ /**
252
+ * Compute a grant's current lifecycle status. Revocation takes precedence
253
+ * over expiry (a revoked-then-expired grant still reports "revoked", which
254
+ * matters for audit trails downstream).
255
+ */
256
+ export function sessionStatus(grant, { nowMs = Date.now(), revocation } = {}) {
257
+ if (!grant || grant.mode !== "oracle-session-grant") fail("invalid session grant");
258
+ if (isRevokedGrant(grant, revocation)) return SESSION_STATUS.REVOKED;
259
+ // Fail CLOSED on an unusable clock. `Number(nowMs) >= expiresAtMs` is false
260
+ // for NaN / null / "later" / -Infinity, so a long-dead grant reported ACTIVE
261
+ // and authorized spending at its full cap. `null` is the sharp edge: it slips
262
+ // past the `= Date.now()` default because it is a supplied value, and
263
+ // Number(null) === 0.
264
+ if (!isWindowOpen({ expiresAtMs: grant.expiresAtMs }, nowMs, { inclusive: true })) return SESSION_STATUS.EXPIRED;
265
+ return SESSION_STATUS.ACTIVE;
266
+ }
267
+
268
+ export function isSessionActive(grant, opts = {}) {
269
+ return sessionStatus(grant, opts) === SESSION_STATUS.ACTIVE;
270
+ }
271
+
272
+ /**
273
+ * Authorize a single proposed action against a session grant. Throws a
274
+ * "session: ..." Error on any violation (fail-closed); returns true only when
275
+ * every check passes. This is a pure policy check — it does not sign,
276
+ * prepare, or broadcast anything.
277
+ *
278
+ * @param {object} grant output of createSessionGrant()
279
+ * @param {object} request
280
+ * @param {string} request.action action id being attempted
281
+ * @param {number} request.chainId chain the action targets
282
+ * @param {string} [request.target] destination address (required unless read/simulate)
283
+ * @param {string|number|bigint} [request.valueWei] native value moved (default 0)
284
+ * @param {string|number|bigint} [request.gasWei] gasLimit*feePerGas estimate
285
+ * @param {object} [opts]
286
+ * @param {number} [opts.nowMs]
287
+ * @param {object|Set|string[]} [opts.revocation] registry / set / array of revoked ids
288
+ */
289
+ export function assertSessionAuthorized(grant, request = {}, opts = {}) {
290
+ if (!grant || grant.mode !== "oracle-session-grant") fail("invalid session grant");
291
+
292
+ const status = sessionStatus(grant, opts);
293
+ if (status === SESSION_STATUS.REVOKED) fail(`session ${grant.id} is revoked`);
294
+ if (status === SESSION_STATUS.EXPIRED) fail(`session ${grant.id} expired at ${grant.expiresAtMs}`);
295
+
296
+ const requestedChainId = normalPositiveInt(request.chainId, "request.chainId");
297
+ if (requestedChainId !== grant.chainId) {
298
+ fail(`chain mismatch: session is scoped to ${grant.chainId}, request is ${requestedChainId}`);
299
+ }
300
+
301
+ const action = normalActionId(request.action);
302
+ if (!grant.actions.includes(action)) {
303
+ fail(`action "${action}" not permitted by session ${grant.id}`);
304
+ }
305
+
306
+ const readOnly = isReadOnlyAction(action);
307
+ if (!readOnly) {
308
+ if (request.target == null || request.target === "") fail("target required for a non-read action");
309
+ const target = normalAddress(request.target, "request.target");
310
+ if (grant.targets.length === 0) fail(`session ${grant.id} has no granted targets (fail-closed)`);
311
+ if (!grant.targets.includes(target)) {
312
+ fail(`target ${target} not permitted by session ${grant.id}`);
313
+ }
314
+ }
315
+
316
+ const valueWei = BigInt(normalBigString(request.valueWei ?? "0", "request.valueWei"));
317
+ const maxValueWei = BigInt(grant.maxValueWei);
318
+ if (valueWei > maxValueWei) {
319
+ fail(`value ${valueWei} exceeds session cap ${maxValueWei}`);
320
+ }
321
+
322
+ // A gas ceiling on the grant is a promise the grant makes. Honouring it only
323
+ // when the REQUEST volunteers a gasWei made it optional in practice: a
324
+ // requester could omit the field and satisfy a grant whose explicit ceiling
325
+ // would otherwise reject the transaction. If the grant bounds gas, the
326
+ // request must state it.
327
+ if (grant.maxGasWei != null) {
328
+ if (request.gasWei == null) {
329
+ fail("session grant bounds gas but the request omitted gasWei — refusing to authorize unbounded gas");
330
+ }
331
+ const gasWei = BigInt(normalBigString(request.gasWei, "request.gasWei"));
332
+ const maxGasWei = BigInt(grant.maxGasWei);
333
+ if (gasWei > maxGasWei) {
334
+ fail(`gas fee ${gasWei} exceeds session cap ${maxGasWei}`);
335
+ }
336
+ }
337
+
338
+ return true;
339
+ }
340
+
341
+ /** Convenience non-throwing wrapper: returns { ok, reason }. */
342
+ export function checkSessionAuthorized(grant, request = {}, opts = {}) {
343
+ try {
344
+ assertSessionAuthorized(grant, request, opts);
345
+ return { ok: true };
346
+ } catch (e) {
347
+ return { ok: false, reason: String(e?.message || e) };
348
+ }
349
+ }
350
+
351
+ /** Redacted view safe to log/index — drops nothing secret today (this model
352
+ * never carries key material) but exists so callers have one stable place to
353
+ * serialize a grant for an audit trail without hand-picking fields. */
354
+ export function toAuditRecord(grant) {
355
+ if (!grant || grant.mode !== "oracle-session-grant") fail("invalid session grant");
356
+ return {
357
+ id: grant.id,
358
+ provider: grant.provider,
359
+ owner: grant.owner,
360
+ agent: grant.agent,
361
+ chainId: grant.chainId,
362
+ actions: grant.actions,
363
+ targets: grant.targets,
364
+ maxValueWei: grant.maxValueWei,
365
+ maxGasWei: grant.maxGasWei,
366
+ issuedAtMs: grant.issuedAtMs,
367
+ expiresAtMs: grant.expiresAtMs,
368
+ nonce: grant.nonce,
369
+ };
370
+ }
371
+
372
+ // Exported for tests / callers that want the raw address/hash validators
373
+ // without re-implementing them.
374
+ export const _internal = { ADDRESS_RE, HEX32_RE, isReadOnlyAction };