@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,352 @@
1
+ // Hyperliquid HyperCore staking lane: HYPE stake / unstake / delegate.
2
+ //
3
+ // Reads are public info endpoints. Writes are PREPARE-ONLY: this module returns
4
+ // EIP-712 typed data plus the exact action payload for the user's own wallet to
5
+ // sign. It never signs, never posts to /exchange, never holds a key.
6
+ //
7
+ // Flow the user actually performs:
8
+ // spot -> staking balance : cDeposit
9
+ // staking balance -> validator : tokenDelegate (isUndelegate=false)
10
+ // validator -> staking balance : tokenDelegate (isUndelegate=true) [1 day validator lockup]
11
+ // staking balance -> spot : cWithdraw [7 day unstaking queue]
12
+
13
+ import { httpJson } from "../http.mjs";
14
+ import { hlInfo } from "./hl-info.mjs";
15
+ export const HYPE_STAKING_DECIMALS = 8;
16
+ export const HYPE_WEI_PER_TOKEN = 10n ** BigInt(HYPE_STAKING_DECIMALS);
17
+ export const HL_SIGNATURE_CHAIN_ID = "0xa4b1"; // Arbitrum One, per Hyperliquid user-signed action spec
18
+ export const HL_UNSTAKING_QUEUE_DAYS = 7;
19
+ export const HL_VALIDATOR_LOCKUP_DAYS = 1;
20
+ // The signed action encodes wei as uint64.
21
+ export const MAX_UINT64 = 2n ** 64n - 1n;
22
+
23
+ function exchangeUrl(opts = {}) {
24
+ if (opts.exchangeUrl) return opts.exchangeUrl;
25
+ if (process.env.HL_EXCHANGE_URL) return process.env.HL_EXCHANGE_URL;
26
+ const testnet = opts.testnet || process.env.HL_TESTNET === "1";
27
+ return testnet ? "https://api.hyperliquid-testnet.xyz/exchange" : "https://api.hyperliquid.xyz/exchange";
28
+ }
29
+
30
+ function hyperliquidChain(opts = {}) {
31
+ return opts.testnet || process.env.HL_TESTNET === "1" ? "Testnet" : "Mainnet";
32
+ }
33
+
34
+ function evmAddress(value, label) {
35
+ const addr = String(value || "").trim();
36
+ if (!/^0x[0-9a-fA-F]{40}$/.test(addr)) throw new Error(`hl-staking: ${label} must be a 0x EVM address`);
37
+ return addr.toLowerCase();
38
+ }
39
+
40
+ /** HYPE amount (decimal string or number) -> integer wei string at 8 decimals. */
41
+ export function hypeToWei(amount, label = "amount") {
42
+ const text = String(amount ?? "").trim();
43
+ if (!/^\d+(\.\d+)?$/.test(text)) throw new Error(`hl-staking: ${label} must be a positive decimal HYPE amount`);
44
+ const [whole, frac = ""] = text.split(".");
45
+ if (frac.length > HYPE_STAKING_DECIMALS) {
46
+ throw new Error(`hl-staking: ${label} has more than ${HYPE_STAKING_DECIMALS} decimals`);
47
+ }
48
+ const wei = BigInt(whole) * HYPE_WEI_PER_TOKEN + BigInt((frac + "0".repeat(HYPE_STAKING_DECIMALS)).slice(0, HYPE_STAKING_DECIMALS) || "0");
49
+ if (wei <= 0n) throw new Error(`hl-staking: ${label} must be greater than zero`);
50
+ if (wei > MAX_UINT64) throw new Error(`hl-staking: ${label} exceeds the uint64 range the signed action encodes`);
51
+ return wei.toString();
52
+ }
53
+
54
+ /**
55
+ * The EIP-712 field is uint64. JavaScript's Number loses integer precision
56
+ * above 2^53, so passing Number(wei) can hand the wallet a DIFFERENT amount
57
+ * than the one Oracle prepared and displayed. Keep wei exact: emit a JS number
58
+ * only while it is provably lossless, otherwise emit the decimal string, which
59
+ * every EIP-712 encoder accepts for uintN.
60
+ */
61
+ function exactWei(weiString) {
62
+ const n = BigInt(weiString);
63
+ return n <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(n) : weiString;
64
+ }
65
+
66
+ export function weiToHype(wei) {
67
+ const n = BigInt(String(wei || "0"));
68
+ const whole = n / HYPE_WEI_PER_TOKEN;
69
+ const frac = (n % HYPE_WEI_PER_TOKEN).toString().padStart(HYPE_STAKING_DECIMALS, "0").replace(/0+$/, "");
70
+ return frac ? `${whole}.${frac}` : String(whole);
71
+ }
72
+
73
+ // ---------------------------------------------------------------- reads
74
+
75
+ export async function hlStakingHealth(opts = {}) {
76
+ try {
77
+ const validators = await hlValidatorSummaries(opts);
78
+ return {
79
+ ok: validators.count > 0,
80
+ provider: "hl-staking",
81
+ chain: hyperliquidChain(opts),
82
+ validators: validators.count,
83
+ exec: false,
84
+ };
85
+ } catch (error) {
86
+ return { ok: false, provider: "hl-staking", error: String(error?.message || error).slice(0, 160), exec: false };
87
+ }
88
+ }
89
+
90
+ export async function hlValidatorSummaries(opts = {}) {
91
+ const raw = await hlInfo({ type: "validatorSummaries" }, opts);
92
+ const list = Array.isArray(raw) ? raw : [];
93
+ const validators = list.map((v) => ({
94
+ validator: v.validator ?? null,
95
+ name: v.name ?? null,
96
+ isActive: v.isActive ?? null,
97
+ isJailed: v.isJailed ?? null,
98
+ commission: v.commission ?? null,
99
+ stake: v.stake ?? null,
100
+ nRecentBlocks: v.nRecentBlocks ?? null,
101
+ }));
102
+ return { provider: "hl-staking", count: validators.length, validators, exec: false, raw };
103
+ }
104
+
105
+ export async function hlDelegatorSummary(args = {}, opts = {}) {
106
+ const user = evmAddress(args.user || args.address, "user");
107
+ const raw = await hlInfo({ type: "delegatorSummary", user }, opts);
108
+ return {
109
+ provider: "hl-staking",
110
+ user,
111
+ delegatedWei: raw?.delegated ?? null,
112
+ undelegatedWei: raw?.undelegated ?? null,
113
+ totalPendingWithdrawalWei: raw?.totalPendingWithdrawal ?? null,
114
+ nPendingWithdrawals: raw?.nPendingWithdrawals ?? null,
115
+ delegatedHype: raw?.delegated != null ? String(raw.delegated) : null,
116
+ undelegatedHype: raw?.undelegated != null ? String(raw.undelegated) : null,
117
+ exec: false,
118
+ raw,
119
+ };
120
+ }
121
+
122
+ export async function hlDelegations(args = {}, opts = {}) {
123
+ const user = evmAddress(args.user || args.address, "user");
124
+ const raw = await hlInfo({ type: "delegations", user }, opts);
125
+ const list = Array.isArray(raw) ? raw : [];
126
+ return {
127
+ provider: "hl-staking",
128
+ user,
129
+ count: list.length,
130
+ delegations: list.map((d) => ({
131
+ validator: d.validator ?? null,
132
+ amount: d.amount ?? null,
133
+ lockedUntilTimestamp: d.lockedUntilTimestamp ?? null,
134
+ })),
135
+ exec: false,
136
+ raw,
137
+ };
138
+ }
139
+
140
+ export async function hlDelegatorRewards(args = {}, opts = {}) {
141
+ const user = evmAddress(args.user || args.address, "user");
142
+ const raw = await hlInfo({ type: "delegatorRewards", user }, opts);
143
+ return { provider: "hl-staking", user, rewards: Array.isArray(raw) ? raw : [], exec: false };
144
+ }
145
+
146
+ export async function hlDelegatorHistory(args = {}, opts = {}) {
147
+ const user = evmAddress(args.user || args.address, "user");
148
+ const raw = await hlInfo({ type: "delegatorHistory", user }, opts);
149
+ return { provider: "hl-staking", user, history: Array.isArray(raw) ? raw : [], exec: false };
150
+ }
151
+
152
+ // ------------------------------------------------------------- prepares
153
+
154
+ function nonceNow(args = {}) {
155
+ const n = args.nonce == null ? Date.now() : Number(args.nonce);
156
+ if (!Number.isInteger(n) || n <= 0) throw new Error("hl-staking: nonce must be a positive integer ms timestamp");
157
+ return n;
158
+ }
159
+
160
+ function signatureChainId(opts = {}) {
161
+ return String(opts.signatureChainId || process.env.HL_SIGNATURE_CHAIN_ID || HL_SIGNATURE_CHAIN_ID);
162
+ }
163
+
164
+ function eip712Domain(opts = {}) {
165
+ return {
166
+ name: "HyperliquidSignTransaction",
167
+ version: "1",
168
+ chainId: Number(BigInt(signatureChainId(opts))),
169
+ verifyingContract: "0x0000000000000000000000000000000000000000",
170
+ };
171
+ }
172
+
173
+ function preparedAction({ kind, action, types, primaryType, message, opts, notes, caps }) {
174
+ return {
175
+ provider: "hl-staking",
176
+ venue: "hypercore",
177
+ chain: hyperliquidChain(opts),
178
+ kind,
179
+ prepareReady: true,
180
+ executionReady: false,
181
+ signingReady: false,
182
+ broadcastReady: false,
183
+ requiresUserSignature: true,
184
+ signWith: "user wallet (EIP-712 typed data)",
185
+ submitTo: exchangeUrl(opts),
186
+ submitShape: { action, nonce: action.nonce, signature: "<user 65-byte signature>" },
187
+ action,
188
+ typedData: {
189
+ domain: eip712Domain(opts),
190
+ types,
191
+ primaryType,
192
+ message,
193
+ },
194
+ caps: caps || null,
195
+ notes,
196
+ exec: false,
197
+ };
198
+ }
199
+
200
+ /** spot HYPE -> staking balance. Instant. */
201
+ export function hlPrepareStakeDeposit(args = {}, opts = {}) {
202
+ const wei = hypeToWei(args.amountHype ?? args.amount, "amountHype");
203
+ const maxHype = args.maxHype == null ? null : hypeToWei(args.maxHype, "maxHype");
204
+ if (maxHype && BigInt(wei) > BigInt(maxHype)) {
205
+ throw new Error(`hl-staking: amount ${weiToHype(wei)} HYPE exceeds maxHype cap ${weiToHype(maxHype)} HYPE`);
206
+ }
207
+ const nonce = nonceNow(args);
208
+ const chain = hyperliquidChain(opts);
209
+ const action = {
210
+ type: "cDeposit",
211
+ hyperliquidChain: chain,
212
+ signatureChainId: signatureChainId(opts),
213
+ wei: exactWei(wei),
214
+ nonce,
215
+ };
216
+ return preparedAction({
217
+ kind: "hype-stake-deposit",
218
+ action,
219
+ primaryType: "HyperliquidTransaction:CDeposit",
220
+ types: {
221
+ "HyperliquidTransaction:CDeposit": [
222
+ { name: "hyperliquidChain", type: "string" },
223
+ { name: "wei", type: "uint64" },
224
+ { name: "nonce", type: "uint64" },
225
+ ],
226
+ },
227
+ message: { hyperliquidChain: chain, wei: exactWei(wei), nonce },
228
+ opts,
229
+ caps: { amountHype: weiToHype(wei), maxHype: maxHype ? weiToHype(maxHype) : null },
230
+ notes: [
231
+ "Moves HYPE from your Hyperliquid spot balance into your staking balance.",
232
+ "Staking balance still earns nothing until it is delegated to a validator.",
233
+ "Oracle prepared this. Your wallet signs it. Nothing was submitted.",
234
+ ],
235
+ });
236
+ }
237
+
238
+ /** staking balance -> spot HYPE. Enters the 7 day unstaking queue. */
239
+ export function hlPrepareStakeWithdraw(args = {}, opts = {}) {
240
+ const wei = hypeToWei(args.amountHype ?? args.amount, "amountHype");
241
+ const nonce = nonceNow(args);
242
+ const chain = hyperliquidChain(opts);
243
+ const action = {
244
+ type: "cWithdraw",
245
+ hyperliquidChain: chain,
246
+ signatureChainId: signatureChainId(opts),
247
+ wei: exactWei(wei),
248
+ nonce,
249
+ };
250
+ return preparedAction({
251
+ kind: "hype-stake-withdraw",
252
+ action,
253
+ primaryType: "HyperliquidTransaction:CWithdraw",
254
+ types: {
255
+ "HyperliquidTransaction:CWithdraw": [
256
+ { name: "hyperliquidChain", type: "string" },
257
+ { name: "wei", type: "uint64" },
258
+ { name: "nonce", type: "uint64" },
259
+ ],
260
+ },
261
+ message: { hyperliquidChain: chain, wei: exactWei(wei), nonce },
262
+ opts,
263
+ caps: { amountHype: weiToHype(wei) },
264
+ notes: [
265
+ `Starts the ${HL_UNSTAKING_QUEUE_DAYS} day unstaking queue back to spot. The HYPE is not liquid during the queue.`,
266
+ "Undelegate from the validator first: only undelegated staking balance can be withdrawn.",
267
+ "Oracle prepared this. Your wallet signs it. Nothing was submitted.",
268
+ ],
269
+ });
270
+ }
271
+
272
+ /** staking balance <-> validator. isUndelegate=false stakes, true unstakes. */
273
+ export function hlPrepareDelegate(args = {}, opts = {}) {
274
+ const validator = evmAddress(args.validator, "validator");
275
+ const wei = hypeToWei(args.amountHype ?? args.amount, "amountHype");
276
+ const isUndelegate = Boolean(args.isUndelegate ?? args.undelegate ?? false);
277
+ const maxHype = args.maxHype == null ? null : hypeToWei(args.maxHype, "maxHype");
278
+ if (!isUndelegate && maxHype && BigInt(wei) > BigInt(maxHype)) {
279
+ throw new Error(`hl-staking: delegate amount ${weiToHype(wei)} HYPE exceeds maxHype cap ${weiToHype(maxHype)} HYPE`);
280
+ }
281
+ const nonce = nonceNow(args);
282
+ const chain = hyperliquidChain(opts);
283
+ const action = {
284
+ type: "tokenDelegate",
285
+ hyperliquidChain: chain,
286
+ signatureChainId: signatureChainId(opts),
287
+ validator,
288
+ wei: exactWei(wei),
289
+ isUndelegate,
290
+ nonce,
291
+ };
292
+ return preparedAction({
293
+ kind: isUndelegate ? "hype-undelegate" : "hype-delegate",
294
+ action,
295
+ primaryType: "HyperliquidTransaction:TokenDelegate",
296
+ types: {
297
+ "HyperliquidTransaction:TokenDelegate": [
298
+ { name: "hyperliquidChain", type: "string" },
299
+ { name: "validator", type: "address" },
300
+ { name: "wei", type: "uint64" },
301
+ { name: "isUndelegate", type: "bool" },
302
+ { name: "nonce", type: "uint64" },
303
+ ],
304
+ },
305
+ message: { hyperliquidChain: chain, validator, wei: exactWei(wei), isUndelegate, nonce },
306
+ opts,
307
+ caps: { amountHype: weiToHype(wei), maxHype: maxHype ? weiToHype(maxHype) : null, validator },
308
+ notes: isUndelegate
309
+ ? [
310
+ "Returns stake from the validator to your staking balance.",
311
+ `Delegations carry a ${HL_VALIDATOR_LOCKUP_DAYS} day validator lockup before they can be undelegated.`,
312
+ "Oracle prepared this. Your wallet signs it. Nothing was submitted.",
313
+ ]
314
+ : [
315
+ "Delegates staking balance to the chosen validator so it starts earning.",
316
+ `Once delegated, the stake is locked with that validator for ${HL_VALIDATOR_LOCKUP_DAYS} day.`,
317
+ "Check the validator's commission and jail status before delegating.",
318
+ "Oracle prepared this. Your wallet signs it. Nothing was submitted.",
319
+ ],
320
+ });
321
+ }
322
+
323
+ /**
324
+ * Read-only preflight: does the user actually hold enough in the right bucket
325
+ * for the requested stake/unstake move? Never mutates anything.
326
+ */
327
+ export async function hlStakingPreflight(args = {}, opts = {}) {
328
+ const user = evmAddress(args.user || args.address, "user");
329
+ const summary = await hlDelegatorSummary({ user }, opts);
330
+ const delegations = await hlDelegations({ user }, opts);
331
+ return {
332
+ provider: "hl-staking",
333
+ user,
334
+ stakingBalanceUndelegated: summary.undelegatedWei,
335
+ stakingBalanceDelegated: summary.delegatedWei,
336
+ pendingWithdrawals: summary.nPendingWithdrawals,
337
+ delegations: delegations.delegations,
338
+ unstakingQueueDays: HL_UNSTAKING_QUEUE_DAYS,
339
+ validatorLockupDays: HL_VALIDATOR_LOCKUP_DAYS,
340
+ exec: false,
341
+ };
342
+ }
343
+
344
+ /** Never used by Oracle itself. Exposed so a self-hoster can see the exact submit shape. */
345
+ export function hlStakingSubmitShape(opts = {}) {
346
+ return {
347
+ method: "POST",
348
+ url: exchangeUrl(opts),
349
+ body: { action: "<prepared action>", nonce: "<action.nonce>", signature: "<user signature r/s/v>" },
350
+ note: "Oracle does not submit this. The signing wallet or its owner posts it. There is deliberately no submit function in this module.",
351
+ };
352
+ }
@@ -0,0 +1,119 @@
1
+ // Short-lived Hyperliquid WebSocket snapshots (subscribe → first payload → close).
2
+ // No long-running daemon; safe for desk HTTP handlers.
3
+
4
+ const HL_WS = process.env.HL_WS_URL || "wss://api.hyperliquid.xyz/ws";
5
+
6
+ /**
7
+ * @param {object} subscription e.g. { type: 'allMids' } | { type: 'l2Book', coin: 'BTC' }
8
+ * @param {object} [opts]
9
+ * @param {number} [opts.timeoutMs]
10
+ * @param {number} [opts.maxMessages] stop after N data messages (default 1)
11
+ */
12
+ export async function hlWsSnapshot(subscription, opts = {}) {
13
+ if (!subscription?.type) throw new Error("hlWsSnapshot requires subscription.type");
14
+ const timeoutMs = opts.timeoutMs ?? 8_000;
15
+ const maxMessages = opts.maxMessages ?? 1;
16
+ const WebSocketImpl = opts.WebSocket || globalThis.WebSocket;
17
+ if (!WebSocketImpl) throw new Error("WebSocket not available in this runtime");
18
+
19
+ const url = opts.url || HL_WS;
20
+ const started = Date.now();
21
+
22
+ return new Promise((resolve, reject) => {
23
+ let settled = false;
24
+ const messages = [];
25
+ let dataCount = 0;
26
+ const ws = new WebSocketImpl(url);
27
+ const timer = setTimeout(() => {
28
+ cleanup();
29
+ if (!settled) {
30
+ settled = true;
31
+ if (messages.length) {
32
+ resolve({ ok: true, partial: true, ms: Date.now() - started, messages });
33
+ } else {
34
+ reject(new Error(`hl ws timeout after ${timeoutMs}ms`));
35
+ }
36
+ }
37
+ }, timeoutMs);
38
+
39
+ function cleanup() {
40
+ clearTimeout(timer);
41
+ try {
42
+ ws.close();
43
+ } catch {
44
+ /* ignore */
45
+ }
46
+ }
47
+
48
+ ws.addEventListener("open", () => {
49
+ ws.send(JSON.stringify({ method: "subscribe", subscription }));
50
+ });
51
+
52
+ ws.addEventListener("message", (ev) => {
53
+ let data;
54
+ try {
55
+ data = JSON.parse(typeof ev.data === "string" ? ev.data : String(ev.data));
56
+ } catch {
57
+ data = { raw: String(ev.data).slice(0, 200) };
58
+ }
59
+ messages.push(data);
60
+ // skip pure subscriptionResponse for counting "data"
61
+ if (data.channel && data.channel !== "subscriptionResponse") {
62
+ dataCount += 1;
63
+ } else if (data.data && data.channel === "subscriptionResponse") {
64
+ // ignore ack
65
+ } else if (!data.channel) {
66
+ dataCount += 1;
67
+ }
68
+ if (dataCount >= maxMessages) {
69
+ cleanup();
70
+ if (!settled) {
71
+ settled = true;
72
+ resolve({
73
+ ok: true,
74
+ ms: Date.now() - started,
75
+ subscription,
76
+ messages,
77
+ last: messages[messages.length - 1],
78
+ });
79
+ }
80
+ }
81
+ });
82
+
83
+ ws.addEventListener("error", () => {
84
+ cleanup();
85
+ if (!settled) {
86
+ settled = true;
87
+ reject(new Error("hl ws error"));
88
+ }
89
+ });
90
+ });
91
+ }
92
+
93
+ export async function hlWsHealth(opts = {}) {
94
+ try {
95
+ const snap = await hlWsSnapshot({ type: "allMids" }, { ...opts, maxMessages: 1 });
96
+ const last = snap.last || {};
97
+ const mids = last.data?.mids || last.data || {};
98
+ const n = typeof mids === "object" ? Object.keys(mids).length : 0;
99
+ return { ok: true, ms: snap.ms, midCount: n, channel: last.channel || null };
100
+ } catch (e) {
101
+ return { ok: false, error: String(e.message || e).slice(0, 160) };
102
+ }
103
+ }
104
+
105
+ export async function hlWsAllMids(opts = {}) {
106
+ const snap = await hlWsSnapshot({ type: "allMids" }, opts);
107
+ const last = snap.last || {};
108
+ return {
109
+ ms: snap.ms,
110
+ mids: last.data?.mids || last.data || {},
111
+ channel: last.channel,
112
+ };
113
+ }
114
+
115
+ export async function hlWsL2Book(coin, opts = {}) {
116
+ if (!coin) throw new Error("coin required");
117
+ const snap = await hlWsSnapshot({ type: "l2Book", coin: String(coin) }, opts);
118
+ return { ms: snap.ms, book: snap.last?.data || snap.last, channel: snap.last?.channel };
119
+ }
@@ -0,0 +1,49 @@
1
+ // HyperEVM (chain 999) discovery via DexScreener + optional RPC health.
2
+ // No dedicated public Uniswap QuoterV2 on HyperEVM assumed.
3
+
4
+ import { dexscreenerSearch, dexscreenerToken } from "./dexscreener.mjs";
5
+ import { rpcHealth } from "./evm-rpc.mjs";
6
+
7
+ export const HYPEREVM_CHAIN_ID = 999;
8
+
9
+ export async function hyperevmHealth(opts = {}) {
10
+ const out = { chainId: HYPEREVM_CHAIN_ID, rpc: null, dex: null };
11
+ try {
12
+ out.rpc = await rpcHealth(HYPEREVM_CHAIN_ID, opts);
13
+ } catch (e) {
14
+ out.rpc = { ok: false, error: String(e.message || e).slice(0, 120) };
15
+ }
16
+ try {
17
+ const s = await dexscreenerSearch("HYPE", opts);
18
+ const pairs = (s.pairs || []).filter((p) =>
19
+ /hyper|hl|hyperevm/i.test(String(p.chainId || p.chain || ""))
20
+ );
21
+ out.dex = {
22
+ ok: true,
23
+ hypePairs: pairs.length || (s.pairs || []).length,
24
+ sample: (pairs[0] || s.pairs?.[0])?.pairAddress || null,
25
+ };
26
+ } catch (e) {
27
+ out.dex = { ok: false, error: String(e.message || e).slice(0, 120) };
28
+ }
29
+ return {
30
+ ok: Boolean(out.rpc?.ok || out.dex?.ok),
31
+ ...out,
32
+ };
33
+ }
34
+
35
+ export async function hyperevmSearch(q = "HYPE", opts = {}) {
36
+ const s = await dexscreenerSearch(q, opts);
37
+ const pairs = s.pairs || [];
38
+ const hl = pairs.filter((p) => /hyper|hl|hyperevm/i.test(String(p.chainId || "")));
39
+ return {
40
+ query: q,
41
+ hyperPairs: hl,
42
+ allPairs: pairs.slice(0, 20),
43
+ count: hl.length || pairs.length,
44
+ };
45
+ }
46
+
47
+ export async function hyperevmToken(address, opts = {}) {
48
+ return dexscreenerToken(address, opts);
49
+ }