@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,175 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import { Interface, isAddress } from "ethers";
3
+ import { routeCalldataHash } from "./route-attestation.mjs";
4
+ import { resolveAttestationSecret } from "./attestation-secret.mjs";
5
+ import { assertFreshWindow } from "./fresh-window.mjs";
6
+
7
+ const DEFAULT_GMX_ATTESTATION_TTL_MS = 20_000;
8
+ const ERC20 = new Interface(["function approve(address spender,uint256 amount) returns (bool)"]);
9
+
10
+ export const GMX_EXCHANGE_ROUTERS = Object.freeze({
11
+ 42161: "0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",
12
+ 43114: "0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2",
13
+ });
14
+
15
+ function canonicalJson(value) {
16
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
17
+ if (value && typeof value === "object") {
18
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(",")}}`;
19
+ }
20
+ return JSON.stringify(value);
21
+ }
22
+
23
+ function normalAddress(value, label) {
24
+ const text = String(value || "").trim();
25
+ if (!isAddress(text)) throw new Error(`${label} must be an address`);
26
+ return text.toLowerCase();
27
+ }
28
+
29
+ function amountString(value, label = "gmx amount") {
30
+ try {
31
+ const n = BigInt(String(value));
32
+ if (n <= 0n) throw new Error("nonpositive");
33
+ return n.toString();
34
+ } catch {
35
+ throw new Error(`${label} must be a positive integer string`);
36
+ }
37
+ }
38
+
39
+ function boolValue(value) {
40
+ return Boolean(value);
41
+ }
42
+
43
+ function hmac(secret, payload) {
44
+ return `0x${createHmac("sha256", String(secret)).update(payload).digest("hex")}`;
45
+ }
46
+
47
+ function sameSignature(a, b) {
48
+ const left = Buffer.from(String(a || "").replace(/^0x/, ""), "hex");
49
+ const right = Buffer.from(String(b || "").replace(/^0x/, ""), "hex");
50
+ return left.length === right.length && left.length > 0 && timingSafeEqual(left, right);
51
+ }
52
+
53
+ function attestationSecret(secret) {
54
+ return resolveAttestationSecret(
55
+ secret,
56
+ "ORACLE_ROUTE_ATTESTATION_SECRET",
57
+ "MAD_ROUTE_ATTESTATION_SECRET",
58
+ );
59
+ }
60
+
61
+ function unsigned(attestation) {
62
+ const { signature: _signature, ...payload } = attestation;
63
+ return payload;
64
+ }
65
+
66
+ function decodeApproveCalldata(data) {
67
+ const hex = String(data || "").toLowerCase();
68
+ if (!hex.startsWith("0x095ea7b3")) throw new Error("approval calldata required");
69
+ const [spender, amount] = ERC20.decodeFunctionData("approve", hex);
70
+ return { spender: normalAddress(spender, "approval spender"), amount: amountString(amount, "approval amount") };
71
+ }
72
+
73
+ export function isGmxExchangeRouter(chainId, address) {
74
+ const router = GMX_EXCHANGE_ROUTERS[Number(chainId)];
75
+ return !!router && normalAddress(address, "gmx exchange router") === router;
76
+ }
77
+
78
+ export function createGmxOrderAttestation({
79
+ provider = "gmx",
80
+ chainId,
81
+ account,
82
+ receiver,
83
+ exchangeRouter,
84
+ router,
85
+ orderVault,
86
+ orderType,
87
+ market,
88
+ initialCollateralToken,
89
+ initialCollateralDeltaAmount,
90
+ sizeDeltaUsd,
91
+ executionFee,
92
+ acceptablePrice,
93
+ isLong,
94
+ data,
95
+ calldataHash,
96
+ value,
97
+ maxSlippageBps,
98
+ nowMs = Date.now(),
99
+ ttlMs = DEFAULT_GMX_ATTESTATION_TTL_MS,
100
+ secret,
101
+ } = {}) {
102
+ const attestation = {
103
+ mode: "gmx-order-attestation",
104
+ version: 1,
105
+ provider: String(provider || "").trim() || "gmx",
106
+ chainId: Number(chainId),
107
+ account: normalAddress(account, "gmx account"),
108
+ receiver: normalAddress(receiver || account, "gmx receiver"),
109
+ exchangeRouter: normalAddress(exchangeRouter, "gmx exchangeRouter"),
110
+ router: normalAddress(router, "gmx router"),
111
+ orderVault: normalAddress(orderVault, "gmx orderVault"),
112
+ orderType: String(orderType || "").trim(),
113
+ market: normalAddress(market, "gmx market"),
114
+ initialCollateralToken: normalAddress(initialCollateralToken, "gmx initialCollateralToken"),
115
+ initialCollateralDeltaAmount: amountString(initialCollateralDeltaAmount, "gmx initialCollateralDeltaAmount"),
116
+ sizeDeltaUsd: amountString(sizeDeltaUsd, "gmx sizeDeltaUsd"),
117
+ executionFee: amountString(executionFee, "gmx executionFee"),
118
+ acceptablePrice: amountString(acceptablePrice, "gmx acceptablePrice"),
119
+ isLong: boolValue(isLong),
120
+ calldataHash: data ? routeCalldataHash(data) : calldataHash,
121
+ value: value == null ? amountString(executionFee, "gmx value") : amountString(value, "gmx value"),
122
+ issuedAtMs: Number(nowMs),
123
+ expiresAtMs: Number(nowMs) + Number(ttlMs),
124
+ };
125
+ if (!Number.isFinite(attestation.chainId)) throw new Error("gmx attestation chainId required");
126
+ if (!attestation.orderType) throw new Error("gmx orderType required");
127
+ if (!isGmxExchangeRouter(attestation.chainId, attestation.exchangeRouter)) throw new Error("gmx exchangeRouter mismatch for chain");
128
+ if (maxSlippageBps != null) attestation.maxSlippageBps = Number(maxSlippageBps);
129
+ const payload = canonicalJson(attestation);
130
+ return { ...attestation, signature: hmac(attestationSecret(secret), payload) };
131
+ }
132
+
133
+ function assertSignature(attestation, secret) {
134
+ const expected = hmac(attestationSecret(secret), canonicalJson(unsigned(attestation)));
135
+ if (!sameSignature(attestation.signature, expected)) throw new Error("gmx attestation signature mismatch");
136
+ }
137
+
138
+ export function assertGmxOrderAttestation(attestation, tx = {}, { chainId, nowMs = Date.now(), secret } = {}) {
139
+ if (!attestation || attestation.mode !== "gmx-order-attestation") throw new Error("gmx order attestation required");
140
+ if (Number(attestation.expiresAtMs) <= Number(nowMs)) throw new Error("gmx attestation expired");
141
+ assertSignature(attestation, secret);
142
+ const txChainId = Number(chainId ?? tx.chainId);
143
+ if (Number(attestation.chainId) !== txChainId) throw new Error("gmx attestation chain mismatch");
144
+ const to = normalAddress(tx.to, "gmx tx.to");
145
+ if (normalAddress(attestation.exchangeRouter, "gmx exchangeRouter") !== to) throw new Error("gmx attestation destination mismatch");
146
+ if (!isGmxExchangeRouter(txChainId, to)) throw new Error("gmx exchangeRouter mismatch for chain");
147
+ if (tx.from && normalAddress(attestation.account, "gmx account") !== normalAddress(tx.from, "gmx tx.from")) {
148
+ throw new Error("gmx attestation account mismatch");
149
+ }
150
+ // Time is a security parameter: an unusable clock must fail CLOSED,
151
+ // otherwise NaN/null/-Infinity silently makes this attestation eternal.
152
+ assertFreshWindow(attestation || {}, nowMs, "gmx order attestation");
153
+ const value = tx.value == null ? "0" : String(BigInt(String(tx.value).startsWith("0x") ? String(tx.value) : String(tx.value)));
154
+ if (String(attestation.value) !== value || String(attestation.executionFee) !== value) throw new Error("gmx attestation value mismatch");
155
+ if (attestation.calldataHash !== routeCalldataHash(tx.data || "0x")) throw new Error("gmx attestation calldata mismatch");
156
+ return true;
157
+ }
158
+
159
+ export function assertGmxApprovalAttestation(attestation, tx = {}, guard = {}, { chainId, nowMs = Date.now(), secret } = {}) {
160
+ if (!attestation || attestation.mode !== "gmx-order-attestation") throw new Error("gmx order attestation required");
161
+ if (Number(attestation.expiresAtMs) <= Number(nowMs)) throw new Error("gmx attestation expired");
162
+ assertSignature(attestation, secret);
163
+ const txChainId = Number(tx.chainId ?? chainId);
164
+ if (Number(attestation.chainId) !== txChainId) throw new Error("gmx attestation chain mismatch");
165
+ const decoded = decodeApproveCalldata(tx.data);
166
+ if (normalAddress(attestation.initialCollateralToken, "gmx collateral") !== normalAddress(tx.to, "approval token")) {
167
+ throw new Error("gmx attestation collateral mismatch");
168
+ }
169
+ if (normalAddress(attestation.router, "gmx router") !== decoded.spender) throw new Error("gmx attestation spender mismatch");
170
+ if (String(attestation.initialCollateralDeltaAmount) !== decoded.amount || String(guard.amount) !== decoded.amount) {
171
+ throw new Error("gmx attestation amount mismatch");
172
+ }
173
+ if (guard.provider && String(guard.provider) !== String(attestation.provider)) throw new Error("gmx attestation provider mismatch");
174
+ return true;
175
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,50 @@
1
+ // Oracle public package root.
2
+ //
3
+ // Curated exports only: data/read plane, scanner/chain registration, routing,
4
+ // policy schema, and scope constants.
5
+ //
6
+ // Key-material and execution modules are deliberately absent from every
7
+ // public package entrypoint, so importing the package cannot hand a caller a
8
+ // signer.
9
+
10
+ export { data, dataCall, dataHealth, dataCatalog } from "./data/desk-data.mjs";
11
+ export { registerProvider, getProvider, listProviders } from "./data/catalog.mjs";
12
+
13
+ export { CHAINS, chainById, registerChain, rpcUrlFor, isSupportedChain } from "./chains.mjs";
14
+
15
+ export {
16
+ SCANNER_CAPABILITIES,
17
+ EVIDENCE,
18
+ RISK,
19
+ validateScanner,
20
+ createScanner,
21
+ registerScanner,
22
+ getScanner,
23
+ listScanners,
24
+ scannerCoverage,
25
+ CHAIN_CONFIGS,
26
+ registerBuiltinScanners,
27
+ registerCustomChain,
28
+ } from "./scanner/index.mjs";
29
+
30
+ export { bestSwapRoute, bestBridgeRoute, QUALITY } from "./router/index.mjs";
31
+ export { validateNftMintGasWar, assertNftMintGasWar, NftGasWarLimitError } from "./nft-gas-war-guard.mjs";
32
+ export { simulateSell, assertSellable, SELL_SIM } from "./sell-simulation.mjs";
33
+ export { capabilityStatus, assertCapability, autonomousTradingEnabled, posture } from "./capability-posture.mjs";
34
+
35
+ export {
36
+ GRANT_VERSION,
37
+ normalizeGrant,
38
+ validateGrant,
39
+ canonicalizeGrant,
40
+ grantId,
41
+ GrantValidationError,
42
+ } from "./public-control/policy-schema.mjs";
43
+
44
+ export {
45
+ ALLOWED_SCOPES,
46
+ EXECUTE_SCOPE,
47
+ BUILD_SCOPE,
48
+ DEFAULT_SCOPES,
49
+ normalizeScopes,
50
+ } from "./scopes.mjs";
@@ -0,0 +1,139 @@
1
+ // Oracle public NFT mint gas-war guard.
2
+ //
3
+ // Pure, dependency-free policy checks for NFT mint bots across any configured
4
+ // chain. This module does not sign, broadcast, read RPC, or know private keys.
5
+ // It only decides whether a proposed mint transaction's gas envelope fits the
6
+ // user's explicit cap. Missing caps fail closed.
7
+
8
+ const DECIMAL_RE = /^(0|[1-9][0-9]*)$/;
9
+
10
+ export class NftGasWarLimitError extends Error {
11
+ constructor(verdict) {
12
+ super(`nft gas-war limit: ${verdict.reason}`);
13
+ this.name = "NftGasWarLimitError";
14
+ this.verdict = verdict;
15
+ }
16
+ }
17
+
18
+ function toBig(value, label, { required = true, allowZero = false } = {}) {
19
+ if (value == null || value === "") {
20
+ if (required) throw new Error(`${label} required`);
21
+ return null;
22
+ }
23
+ let n;
24
+ if (typeof value === "bigint") n = value;
25
+ else if (typeof value === "number") {
26
+ if (!Number.isSafeInteger(value)) throw new Error(`${label} must be a safe integer`);
27
+ n = BigInt(value);
28
+ } else if (typeof value === "string") {
29
+ const s = value.trim();
30
+ if (s.startsWith("0x") || s.startsWith("0X")) n = BigInt(s);
31
+ else {
32
+ if (!DECIMAL_RE.test(s)) throw new Error(`${label} must be an integer wei string`);
33
+ n = BigInt(s);
34
+ }
35
+ } else throw new Error(`${label} must be bigint, number, or integer string`);
36
+ if (n < 0n || (!allowZero && n === 0n)) throw new Error(`${label} must be ${allowZero ? "non-negative" : "positive"}`);
37
+ return n;
38
+ }
39
+
40
+ function toChainId(value) {
41
+ const n = Number(value);
42
+ if (!Number.isSafeInteger(n) || n <= 0) throw new Error("chainId must be a positive integer");
43
+ return n;
44
+ }
45
+
46
+ function readGasPrice(tx = {}) {
47
+ if (tx.maxFeePerGas != null) return toBig(tx.maxFeePerGas, "maxFeePerGas");
48
+ if (tx.gasPrice != null) return toBig(tx.gasPrice, "gasPrice");
49
+ return null;
50
+ }
51
+
52
+ /**
53
+ * Validate an NFT mint gas envelope against a user/grant gas-war policy.
54
+ *
55
+ * Input accepts either top-level gas fields or a tx object:
56
+ * validateNftMintGasWar({ chainId, tx, policy })
57
+ * tx: { gasLimit, maxFeePerGas, maxPriorityFeePerGas } or legacy { gasPrice }
58
+ * policy: {
59
+ * maxTotalGasWei, // required unless grant.maxGasWei provided
60
+ * maxFeePerGasWei, // optional per-unit cap
61
+ * maxPriorityFeePerGasWei, // optional EIP-1559 tip cap
62
+ * grant // optional normalized public grant with maxGasWei
63
+ * }
64
+ */
65
+ export function validateNftMintGasWar(input = {}) {
66
+ try {
67
+ const chainId = toChainId(input.chainId ?? input.tx?.chainId);
68
+ const tx = input.tx || input;
69
+ const policy = input.policy || input;
70
+ const grantMaxGas = policy.grant?.maxGasWei ?? input.grant?.maxGasWei;
71
+ const maxTotalGasWei = toBig(policy.maxTotalGasWei ?? policy.maxGasWei ?? grantMaxGas, "maxTotalGasWei");
72
+ const gasLimit = toBig(tx.gasLimit ?? tx.gas, "gasLimit");
73
+ const unitFee = readGasPrice(tx);
74
+ if (unitFee == null) throw new Error("maxFeePerGas or gasPrice required");
75
+ const maxFeePerGasWei = toBig(policy.maxFeePerGasWei, "maxFeePerGasWei", { required: false });
76
+ const maxPriorityFeePerGasWei = toBig(policy.maxPriorityFeePerGasWei, "maxPriorityFeePerGasWei", { required: false });
77
+ const priorityFee = tx.maxPriorityFeePerGas == null ? null : toBig(tx.maxPriorityFeePerGas, "maxPriorityFeePerGas");
78
+ const totalGasWei = gasLimit * unitFee;
79
+
80
+ if (totalGasWei > maxTotalGasWei) {
81
+ return {
82
+ ok: false,
83
+ status: "BLOCK",
84
+ reason: `total gas ${totalGasWei} exceeds cap ${maxTotalGasWei}`,
85
+ chainId,
86
+ totalGasWei: totalGasWei.toString(),
87
+ maxTotalGasWei: maxTotalGasWei.toString(),
88
+ };
89
+ }
90
+ if (maxFeePerGasWei != null && unitFee > maxFeePerGasWei) {
91
+ return {
92
+ ok: false,
93
+ status: "BLOCK",
94
+ reason: `unit fee ${unitFee} exceeds cap ${maxFeePerGasWei}`,
95
+ chainId,
96
+ unitFeeWei: unitFee.toString(),
97
+ maxFeePerGasWei: maxFeePerGasWei.toString(),
98
+ totalGasWei: totalGasWei.toString(),
99
+ maxTotalGasWei: maxTotalGasWei.toString(),
100
+ };
101
+ }
102
+ if (priorityFee != null && maxPriorityFeePerGasWei != null && priorityFee > maxPriorityFeePerGasWei) {
103
+ return {
104
+ ok: false,
105
+ status: "BLOCK",
106
+ reason: `priority fee ${priorityFee} exceeds cap ${maxPriorityFeePerGasWei}`,
107
+ chainId,
108
+ priorityFeeWei: priorityFee.toString(),
109
+ maxPriorityFeePerGasWei: maxPriorityFeePerGasWei.toString(),
110
+ totalGasWei: totalGasWei.toString(),
111
+ maxTotalGasWei: maxTotalGasWei.toString(),
112
+ };
113
+ }
114
+ return {
115
+ ok: true,
116
+ status: "PASS",
117
+ reason: "gas envelope within NFT mint gas-war caps",
118
+ chainId,
119
+ totalGasWei: totalGasWei.toString(),
120
+ maxTotalGasWei: maxTotalGasWei.toString(),
121
+ unitFeeWei: unitFee.toString(),
122
+ maxFeePerGasWei: maxFeePerGasWei?.toString() ?? null,
123
+ priorityFeeWei: priorityFee?.toString() ?? null,
124
+ maxPriorityFeePerGasWei: maxPriorityFeePerGasWei?.toString() ?? null,
125
+ };
126
+ } catch (error) {
127
+ return {
128
+ ok: false,
129
+ status: "BLOCK",
130
+ reason: String(error?.message || error),
131
+ };
132
+ }
133
+ }
134
+
135
+ export function assertNftMintGasWar(input = {}) {
136
+ const verdict = validateNftMintGasWar(input);
137
+ if (!verdict.ok) throw new NftGasWarLimitError(verdict);
138
+ return verdict;
139
+ }
@@ -0,0 +1,157 @@
1
+ // File-backed scoped API keys for multi-user onboarding.
2
+ // NON-CUSTODIAL: we store only a HASH of the API key + owner wallet address.
3
+ // We never store the user's private key. agent:execute requires controller allowlist.
4
+
5
+ import { createHash, randomBytes } from "node:crypto";
6
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
7
+ import { dirname, join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { normalizeScopes, EXECUTE_SCOPE, DEFAULT_SCOPES } from "../scopes.mjs";
10
+
11
+ function hashKey(raw) {
12
+ return createHash("sha256").update(String(raw), "utf8").digest("hex");
13
+ }
14
+
15
+ function emptyState() {
16
+ return { version: 1, keys: [] };
17
+ }
18
+
19
+ export function defaultStorePath() {
20
+ if (process.env.ORACLE_AGENT_KEYS_PATH) return process.env.ORACLE_AGENT_KEYS_PATH;
21
+ if (process.env.MAD_AGENT_KEYS_PATH) return process.env.MAD_AGENT_KEYS_PATH;
22
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
23
+ return join(root, "data", "agent-keys.json");
24
+ }
25
+
26
+ function readState(path) {
27
+ if (!existsSync(path)) return emptyState();
28
+ try {
29
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
30
+ if (!parsed || !Array.isArray(parsed.keys)) return emptyState();
31
+ return parsed;
32
+ } catch {
33
+ return emptyState();
34
+ }
35
+ }
36
+
37
+ function writeState(path, state) {
38
+ mkdirSync(dirname(path), { recursive: true });
39
+ writeFileSync(path, JSON.stringify(state, null, 2), { mode: 0o600 });
40
+ }
41
+
42
+ function publicRecord(rec) {
43
+ return {
44
+ id: rec.id,
45
+ owner: rec.owner,
46
+ name: rec.name,
47
+ scopes: rec.scopes,
48
+ tier: rec.tier || null,
49
+ createdAt: rec.createdAt,
50
+ revokedAt: rec.revokedAt || null,
51
+ lastUsedAt: rec.lastUsedAt || null,
52
+ };
53
+ }
54
+
55
+ /**
56
+ * @param {object} opts
57
+ * @param {string} opts.owner user wallet address (checksum optional)
58
+ * @param {string} [opts.name]
59
+ * @param {string[]} [opts.scopes]
60
+ * @param {string} [opts.tier]
61
+ * @param {string[]} [opts.controllerAllowlist] required if scopes include agent:execute
62
+ * @param {string} [opts.storePath]
63
+ * @returns {{ key: string, record: object }} raw key shown ONCE
64
+ */
65
+ export function createAgentKey({
66
+ owner,
67
+ name = "Agent key",
68
+ scopes,
69
+ tier = null,
70
+ controllerAllowlist = [],
71
+ storePath = defaultStorePath(),
72
+ } = {}) {
73
+ const normalizedOwner = String(owner || "").toLowerCase();
74
+ if (!/^0x[0-9a-f]{40}$/.test(normalizedOwner)) {
75
+ throw new Error("owner must be a 0x-prefixed 20-byte address");
76
+ }
77
+ const normalizedScopes = normalizeScopes(scopes);
78
+ if (normalizedScopes.includes(EXECUTE_SCOPE)) {
79
+ const rawList = controllerAllowlist.length
80
+ ? controllerAllowlist
81
+ : String(process.env.MAD_EXECUTOR_CONTROLLERS || "")
82
+ .split(",")
83
+ .map((s) => s.trim())
84
+ .filter(Boolean);
85
+ const allow = new Set(rawList.map((a) => String(a).toLowerCase()));
86
+ if (!allow.has(normalizedOwner)) {
87
+ throw new Error("Wallet is not an executor controller");
88
+ }
89
+ }
90
+
91
+ const raw = `mad_${randomBytes(24).toString("base64url")}`;
92
+ const rec = {
93
+ id: randomBytes(8).toString("hex"),
94
+ owner: normalizedOwner,
95
+ name: String(name).slice(0, 80),
96
+ scopes: normalizedScopes,
97
+ tier,
98
+ keyHash: hashKey(raw),
99
+ createdAt: new Date().toISOString(),
100
+ revokedAt: null,
101
+ lastUsedAt: null,
102
+ };
103
+
104
+ const state = readState(storePath);
105
+ state.keys.push(rec);
106
+ writeState(storePath, state);
107
+
108
+ return { key: raw, record: publicRecord(rec) };
109
+ }
110
+
111
+ export function listAgentKeys(owner, { storePath = defaultStorePath(), includeRevoked = false } = {}) {
112
+ const o = String(owner || "").toLowerCase();
113
+ const state = readState(storePath);
114
+ return state.keys
115
+ .filter((k) => k.owner === o)
116
+ .filter((k) => includeRevoked || !k.revokedAt)
117
+ .map(publicRecord);
118
+ }
119
+
120
+ export function revokeAgentKey({ owner, id, storePath = defaultStorePath() } = {}) {
121
+ const o = String(owner || "").toLowerCase();
122
+ const state = readState(storePath);
123
+ const rec = state.keys.find((k) => k.owner === o && k.id === id);
124
+ if (!rec) throw new Error("key not found");
125
+ if (rec.revokedAt) return publicRecord(rec);
126
+ rec.revokedAt = new Date().toISOString();
127
+ writeState(storePath, state);
128
+ return publicRecord(rec);
129
+ }
130
+
131
+ /**
132
+ * Authenticate a raw API key. Returns public record + owner-bound identity
133
+ * suitable for getSigner({ identity: { type: 'scoped-key', ... } }).
134
+ */
135
+ export function authenticateAgentKey(rawKey, { storePath = defaultStorePath() } = {}) {
136
+ if (!rawKey) throw new Error("key required");
137
+ const h = hashKey(rawKey);
138
+ const state = readState(storePath);
139
+ const rec = state.keys.find((k) => k.keyHash === h && !k.revokedAt);
140
+ if (!rec) throw new Error("invalid or revoked key");
141
+ rec.lastUsedAt = new Date().toISOString();
142
+ writeState(storePath, state);
143
+ return {
144
+ ...publicRecord(rec),
145
+ identity: {
146
+ type: "scoped-key",
147
+ owner: rec.owner,
148
+ scopes: rec.scopes,
149
+ },
150
+ };
151
+ }
152
+
153
+ export function __resetAgentKeysForTest(storePath) {
154
+ writeState(storePath || defaultStorePath(), emptyState());
155
+ }
156
+
157
+ export { DEFAULT_SCOPES, EXECUTE_SCOPE };
@@ -0,0 +1,18 @@
1
+ export {
2
+ createAgentKey,
3
+ listAgentKeys,
4
+ revokeAgentKey,
5
+ authenticateAgentKey,
6
+ defaultStorePath,
7
+ __resetAgentKeysForTest,
8
+ } from "./agent-keys.mjs";
9
+
10
+ export {
11
+ TIERS,
12
+ listTiers,
13
+ getTier,
14
+ onboardUser,
15
+ onboardAuthenticate,
16
+ onboardListKeys,
17
+ onboardRevoke,
18
+ } from "./tiers.mjs";
@@ -0,0 +1,139 @@
1
+ // Product onboarding tiers — multi-user, non-custodial.
2
+ // Tier chooses default scopes. Higher tiers never put user private keys on our box.
3
+
4
+ import { DEFAULT_SCOPES, EXECUTE_SCOPE } from "../scopes.mjs";
5
+ import { createAgentKey, listAgentKeys, revokeAgentKey, authenticateAgentKey } from "./agent-keys.mjs";
6
+
7
+ /**
8
+ * Tier catalog (product story):
9
+ * - observer: read-only market/position data
10
+ * - preparer: can prepare trades/mints (unsigned / advisory)
11
+ * - shadow: paper/shadow agent loops
12
+ * - executor: live agent:execute — ONLY if owner is on controller allowlist
13
+ * - local_signer: no API key needed for signing; user signs off-infra (docs only)
14
+ */
15
+ export const TIERS = {
16
+ observer: {
17
+ id: "observer",
18
+ label: "Observer",
19
+ description: "Read markets, NFTs, positions. No prepare/execute.",
20
+ scopes: ["read:markets", "read:nfts", "read:positions"],
21
+ custody: "none",
22
+ canExecute: false,
23
+ },
24
+ preparer: {
25
+ id: "preparer",
26
+ label: "Preparer",
27
+ description: "Prepare trades/mints; user or operator co-signs. No live execute scope.",
28
+ scopes: [...DEFAULT_SCOPES].filter((s) => s !== "agent:shadow"),
29
+ custody: "none",
30
+ canExecute: false,
31
+ },
32
+ shadow: {
33
+ id: "shadow",
34
+ label: "Shadow agent",
35
+ description: "Full prepare + agent:shadow paper loops. Still no live execute.",
36
+ scopes: [...DEFAULT_SCOPES],
37
+ custody: "none",
38
+ canExecute: false,
39
+ },
40
+ executor: {
41
+ id: "executor",
42
+ label: "Executor (controller)",
43
+ description:
44
+ "Live agent:execute on the owner's own wallet only. Owner must be an executor controller. Key is NOT a wallet key.",
45
+ scopes: [...DEFAULT_SCOPES, EXECUTE_SCOPE],
46
+ custody: "none — scoped API key only; user wallet key never stored",
47
+ canExecute: true,
48
+ },
49
+ local_signer: {
50
+ id: "local_signer",
51
+ label: "Local signer",
52
+ description:
53
+ "User keeps keys on their device. Desk issues prepare-only key; signing happens off our infra.",
54
+ scopes: ["read:markets", "read:positions", "prepare:trade", "prepare:mint"],
55
+ custody: "none — signing off-box",
56
+ canExecute: false,
57
+ mintKey: true,
58
+ },
59
+ };
60
+
61
+ export function listTiers() {
62
+ return Object.values(TIERS).map((t) => ({
63
+ id: t.id,
64
+ label: t.label,
65
+ description: t.description,
66
+ scopes: t.scopes,
67
+ custody: t.custody,
68
+ canExecute: t.canExecute,
69
+ }));
70
+ }
71
+
72
+ export function getTier(id) {
73
+ const t = TIERS[id];
74
+ if (!t) throw new Error(`Unknown tier: ${id}`);
75
+ return t;
76
+ }
77
+
78
+ /**
79
+ * Onboard a user wallet onto a tier. Returns one-time raw API key (except pure docs).
80
+ * NEVER accepts or stores a private key.
81
+ */
82
+ export function onboardUser({
83
+ owner,
84
+ tier = "observer",
85
+ name,
86
+ controllerAllowlist = [],
87
+ storePath,
88
+ scopes, // optional override
89
+ } = {}) {
90
+ if (owner && typeof owner === "object" && owner.privateKey) {
91
+ throw new Error("Refusing privateKey — non-custodial onboarding accepts owner address only");
92
+ }
93
+ const t = getTier(tier);
94
+ const finalScopes = scopes || t.scopes;
95
+ const result = createAgentKey({
96
+ owner,
97
+ name: name || `${t.label} key`,
98
+ scopes: finalScopes,
99
+ tier: t.id,
100
+ controllerAllowlist,
101
+ storePath,
102
+ });
103
+ return {
104
+ tier: t.id,
105
+ custody: t.custody,
106
+ canExecute: t.canExecute && finalScopes.includes(EXECUTE_SCOPE),
107
+ key: result.key, // show once
108
+ record: result.record,
109
+ nextSteps:
110
+ t.id === "local_signer"
111
+ ? [
112
+ "Store the API key for prepare/read calls only",
113
+ "Keep your wallet key on your device / hardware signer",
114
+ "Submit prepared payloads to your local signer — never upload the key here",
115
+ ]
116
+ : t.canExecute
117
+ ? [
118
+ "Store the API key securely",
119
+ "Live execute still requires MAD_EXECUTE_ENABLED=1 on the operator side",
120
+ "This key can only act on YOUR owner wallet (custody firewall)",
121
+ ]
122
+ : [
123
+ "Store the API key securely",
124
+ "Use with getSigner({ identity: auth.identity, venue }) after authenticateAgentKey",
125
+ ],
126
+ };
127
+ }
128
+
129
+ export function onboardAuthenticate(rawKey, opts) {
130
+ return authenticateAgentKey(rawKey, opts);
131
+ }
132
+
133
+ export function onboardListKeys(owner, opts) {
134
+ return listAgentKeys(owner, opts);
135
+ }
136
+
137
+ export function onboardRevoke(opts) {
138
+ return revokeAgentKey(opts);
139
+ }