@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.
- package/CONTRIBUTING.md +98 -0
- package/LICENSE +202 -0
- package/README.md +384 -0
- package/SECURITY.md +89 -0
- package/SETUP.md +235 -0
- package/artifacts/inscription/oracle-was-here-preview.png +0 -0
- package/artifacts/inscription/oracle-was-here.svg +1 -0
- package/artifacts/specialist-packs/oracle-full-crypto.json +273 -0
- package/bin/desk-server.mjs +438 -0
- package/bin/oracle-data-mcp.mjs +603 -0
- package/bin/oracle-init.mjs +423 -0
- package/bin/oracle-public-server.mjs +36 -0
- package/bin/oracle-route.mjs +254 -0
- package/bin/oracle-scan.mjs +192 -0
- package/docs/adding-a-chain.md +229 -0
- package/docs/architecture.md +135 -0
- package/docs/profiles.md +132 -0
- package/examples/add-a-chain.mjs +65 -0
- package/examples/research-a-token.mjs +70 -0
- package/package.json +90 -0
- package/profiles/_template/SOUL.md +47 -0
- package/profiles/_template/profile.json +22 -0
- package/profiles/bitcoin-agent/SOUL.md +31 -0
- package/profiles/bitcoin-agent/profile.json +32 -0
- package/profiles/hyperliquid-agent/SOUL.md +34 -0
- package/profiles/hyperliquid-agent/profile.json +37 -0
- package/profiles/oracle/SOUL.md +65 -0
- package/profiles/oracle/profile.json +35 -0
- package/profiles/polymarket-agent/SOUL.md +35 -0
- package/profiles/polymarket-agent/profile.json +34 -0
- package/profiles/profile.schema.json +90 -0
- package/profiles/protocol-builder/SOUL.md +50 -0
- package/profiles/protocol-builder/profile.json +37 -0
- package/profiles/robinhood-agent/SOUL.md +45 -0
- package/profiles/robinhood-agent/profile.json +39 -0
- package/profiles/solana-agent/SOUL.md +37 -0
- package/profiles/solana-agent/profile.json +37 -0
- package/profiles/stable-agent/SOUL.md +43 -0
- package/profiles/stable-agent/profile.json +37 -0
- package/public/oracle-console/app.js +272 -0
- package/public/oracle-console/bitcoin-wallets.js +206 -0
- package/public/oracle-console/index.html +91 -0
- package/public/oracle-console/styles.css +239 -0
- package/public/oracle-splash/index.html +931 -0
- package/scripts/build-inscription.py +230 -0
- package/scripts/check-test-count.mjs +105 -0
- package/scripts/e2e-hl-markets.mjs +21 -0
- package/scripts/e2e-hl-perps.mjs +48 -0
- package/scripts/e2e-hypercore-staking.mjs +128 -0
- package/scripts/e2e-solana-bitcoin.mjs +183 -0
- package/scripts/public-api-scan.mjs +23 -0
- package/scripts/secret-scan.mjs +181 -0
- package/scripts/verify-v3-venues.mjs +192 -0
- package/skills/oracle-best-execution/SKILL.md +127 -0
- package/skills/oracle-bitcoin/SKILL.md +53 -0
- package/skills/oracle-chain-graphs-telegram-cards/SKILL.md +59 -0
- package/skills/oracle-circuit-breaker/SKILL.md +51 -0
- package/skills/oracle-contract-research/SKILL.md +55 -0
- package/skills/oracle-desk/SKILL.md +58 -0
- package/skills/oracle-dex-launch/SKILL.md +38 -0
- package/skills/oracle-grants/SKILL.md +69 -0
- package/skills/oracle-hypercore-staking/SKILL.md +57 -0
- package/skills/oracle-hyperliquid/SKILL.md +56 -0
- package/skills/oracle-meme-token-sniper/SKILL.md +73 -0
- package/skills/oracle-nft-gacha-launch/SKILL.md +48 -0
- package/skills/oracle-nft-mint-gas-war/SKILL.md +63 -0
- package/skills/oracle-polymarket/SKILL.md +60 -0
- package/skills/oracle-protocol-builder/SKILL.md +38 -0
- package/skills/oracle-protocol-security/SKILL.md +60 -0
- package/skills/oracle-public-product/SKILL.md +44 -0
- package/skills/oracle-receipts/SKILL.md +52 -0
- package/skills/oracle-rfq-tokenized-assets/SKILL.md +69 -0
- package/skills/oracle-smart-wallet-scanner/SKILL.md +49 -0
- package/skills/oracle-solana/SKILL.md +65 -0
- package/skills/oracle-solana-nft/SKILL.md +54 -0
- package/skills/oracle-token-research/SKILL.md +67 -0
- package/src/agent-auth.mjs +191 -0
- package/src/approval-guard.mjs +282 -0
- package/src/attestation-secret.mjs +88 -0
- package/src/audit-log.mjs +196 -0
- package/src/auto-slippage.mjs +378 -0
- package/src/capability-posture.mjs +125 -0
- package/src/chains.mjs +62 -0
- package/src/data/catalog.mjs +495 -0
- package/src/data/desk-data.mjs +623 -0
- package/src/data/http.mjs +200 -0
- package/src/data/provider-endpoint.mjs +94 -0
- package/src/data/providers/aerodrome.mjs +244 -0
- package/src/data/providers/balancer.mjs +208 -0
- package/src/data/providers/bitcoin-esplora.mjs +230 -0
- package/src/data/providers/bitcoin-meta.mjs +378 -0
- package/src/data/providers/blockscout.mjs +14 -0
- package/src/data/providers/bridges.mjs +241 -0
- package/src/data/providers/cowswap.mjs +501 -0
- package/src/data/providers/curve.mjs +200 -0
- package/src/data/providers/defillama.mjs +88 -0
- package/src/data/providers/dexscreener.mjs +43 -0
- package/src/data/providers/evm-rpc.mjs +203 -0
- package/src/data/providers/geckoterminal.mjs +34 -0
- package/src/data/providers/gmx.mjs +495 -0
- package/src/data/providers/hl-info.mjs +102 -0
- package/src/data/providers/hl-markets.mjs +210 -0
- package/src/data/providers/hl-perps.mjs +382 -0
- package/src/data/providers/hl-staking.mjs +352 -0
- package/src/data/providers/hl-ws.mjs +119 -0
- package/src/data/providers/hyperevm-dex.mjs +49 -0
- package/src/data/providers/jupiter.mjs +182 -0
- package/src/data/providers/lifi.mjs +150 -0
- package/src/data/providers/magiceden-sol.mjs +355 -0
- package/src/data/providers/morpho.mjs +173 -0
- package/src/data/providers/odos.mjs +155 -0
- package/src/data/providers/oneinch.mjs +173 -0
- package/src/data/providers/opensea-multichain.mjs +136 -0
- package/src/data/providers/opensea-nft.mjs +99 -0
- package/src/data/providers/paraswap.mjs +117 -0
- package/src/data/providers/pendle.mjs +187 -0
- package/src/data/providers/poly-public.mjs +96 -0
- package/src/data/providers/poly-ws.mjs +103 -0
- package/src/data/providers/rh-agent.mjs +59 -0
- package/src/data/providers/satflow.mjs +336 -0
- package/src/data/providers/solana-rpc.mjs +186 -0
- package/src/data/providers/uniswap-v3.mjs +303 -0
- package/src/data/providers/zerox.mjs +166 -0
- package/src/data/public-api-scan.mjs +61 -0
- package/src/data/quote-placeholder.mjs +31 -0
- package/src/exact-integer.mjs +72 -0
- package/src/exec-policy.mjs +444 -0
- package/src/flags.mjs +15 -0
- package/src/fresh-window.mjs +76 -0
- package/src/gmx-attestation.mjs +175 -0
- package/src/index.mjs +50 -0
- package/src/nft-gas-war-guard.mjs +139 -0
- package/src/onboarding/agent-keys.mjs +157 -0
- package/src/onboarding/index.mjs +18 -0
- package/src/onboarding/tiers.mjs +139 -0
- package/src/oracle-env.mjs +38 -0
- package/src/protocol-execution.mjs +84 -0
- package/src/public-api/buzz-integration.mjs +256 -0
- package/src/public-api/connect-agent.mjs +397 -0
- package/src/public-api/grants.mjs +142 -0
- package/src/public-api/http.mjs +374 -0
- package/src/public-control/aa-adapter.mjs +402 -0
- package/src/public-control/build-registry.mjs +227 -0
- package/src/public-control/bundler-client.mjs +372 -0
- package/src/public-control/grant-indexer.mjs +296 -0
- package/src/public-control/policy-render.mjs +69 -0
- package/src/public-control/policy-schema.mjs +318 -0
- package/src/public-control/runtime-config.mjs +265 -0
- package/src/public-control/session-key-model.mjs +374 -0
- package/src/public-control/session-orchestrator.mjs +412 -0
- package/src/route-attestation.mjs +132 -0
- package/src/router/best-execution.mjs +221 -0
- package/src/router/index.mjs +185 -0
- package/src/router/prepare-bridge.mjs +288 -0
- package/src/router/prepare-route.mjs +341 -0
- package/src/router/proposal.mjs +311 -0
- package/src/router/risk-classifier.mjs +119 -0
- package/src/router/route-sources.mjs +292 -0
- package/src/scanner/chains.config.mjs +381 -0
- package/src/scanner/contract.mjs +270 -0
- package/src/scanner/evm-scanner.mjs +394 -0
- package/src/scanner/index.mjs +9 -0
- package/src/scanner/v2-venue.mjs +335 -0
- package/src/scanner/v3-venue.mjs +290 -0
- package/src/scopes.mjs +44 -0
- package/src/sell-simulation.mjs +167 -0
- package/src/token-transfer-guard.mjs +188 -0
- package/src/vault-attestation.mjs +145 -0
- package/src/venues.mjs +206 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
// Hyperliquid market datapoints for the Hyperliquid agent.
|
|
2
|
+
//
|
|
3
|
+
// The raw /info endpoints return parallel arrays and stringly-typed numbers
|
|
4
|
+
// that every consumer ends up re-deriving: universe[i] pairs with assetCtxs[i],
|
|
5
|
+
// funding is an 8-hour decimal that people want annualized, open interest is
|
|
6
|
+
// denominated in the coin rather than USD. Doing that join once, here, keeps
|
|
7
|
+
// every chart and card consistent instead of each one inventing its own math.
|
|
8
|
+
//
|
|
9
|
+
// Reads only. No keys, no signing.
|
|
10
|
+
|
|
11
|
+
import { hlMetaAndAssetCtxs, hlAllMids, hlCandleSnapshot, hlL2Book, hlSpotMeta } from "./hl-info.mjs";
|
|
12
|
+
|
|
13
|
+
/** Liveness: the media lane is healthy when the underlying info plane answers. */
|
|
14
|
+
export async function hlMarketsHealth(opts = {}) {
|
|
15
|
+
const t0 = Date.now();
|
|
16
|
+
try {
|
|
17
|
+
const mids = await hlAllMids(opts);
|
|
18
|
+
return {
|
|
19
|
+
provider: "hl-markets",
|
|
20
|
+
ok: true,
|
|
21
|
+
venue: "hyperliquid",
|
|
22
|
+
symbols: Object.keys(mids || {}).length,
|
|
23
|
+
latencyMs: Date.now() - t0,
|
|
24
|
+
};
|
|
25
|
+
} catch (e) {
|
|
26
|
+
return { provider: "hl-markets", ok: false, error: String(e?.message || e), latencyMs: Date.now() - t0 };
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const HOURS_PER_YEAR = 24 * 365;
|
|
31
|
+
const FUNDING_INTERVAL_HOURS = 8;
|
|
32
|
+
|
|
33
|
+
function num(value) {
|
|
34
|
+
if (value == null) return null;
|
|
35
|
+
const n = Number(value);
|
|
36
|
+
return Number.isFinite(n) ? n : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function pct(a, b) {
|
|
40
|
+
if (a == null || b == null || b === 0) return null;
|
|
41
|
+
return ((a - b) / b) * 100;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Join the perp universe with its asset contexts into one flat row per market.
|
|
46
|
+
*
|
|
47
|
+
* This is THE datapoint set for an Hyperliquid agent board: price, 24h change, volume,
|
|
48
|
+
* open interest in both coin and USD, funding (interval + annualized), and the
|
|
49
|
+
* leverage/decimals metadata needed to render or size an order.
|
|
50
|
+
*/
|
|
51
|
+
export async function hlMarketDatapoints(args = {}, opts = {}) {
|
|
52
|
+
const [meta, mids] = await Promise.all([
|
|
53
|
+
hlMetaAndAssetCtxs(opts),
|
|
54
|
+
hlAllMids(opts).catch(() => ({})),
|
|
55
|
+
]);
|
|
56
|
+
|
|
57
|
+
// metaAndAssetCtxs returns [ { universe: [...] }, [ ctx, ... ] ]
|
|
58
|
+
const universe = meta?.[0]?.universe ?? meta?.universe ?? [];
|
|
59
|
+
const ctxs = Array.isArray(meta?.[1]) ? meta[1] : [];
|
|
60
|
+
|
|
61
|
+
const rows = universe.map((asset, i) => {
|
|
62
|
+
const ctx = ctxs[i] || {};
|
|
63
|
+
const mark = num(ctx.markPx);
|
|
64
|
+
const prev = num(ctx.prevDayPx);
|
|
65
|
+
const oiCoin = num(ctx.openInterest);
|
|
66
|
+
const funding = num(ctx.funding);
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
coin: asset.name,
|
|
70
|
+
index: i,
|
|
71
|
+
markPx: mark,
|
|
72
|
+
oraclePx: num(ctx.oraclePx),
|
|
73
|
+
midPx: num(ctx.midPx) ?? num(mids?.[asset.name]),
|
|
74
|
+
prevDayPx: prev,
|
|
75
|
+
change24hPct: pct(mark, prev),
|
|
76
|
+
dayNtlVolumeUsd: num(ctx.dayNtlVlm),
|
|
77
|
+
premium: num(ctx.premium),
|
|
78
|
+
// funding is the per-8h rate as a decimal; both forms are useful and
|
|
79
|
+
// people get the conversion wrong constantly.
|
|
80
|
+
fundingRate: funding,
|
|
81
|
+
fundingRateAprPct: funding == null ? null : funding * (HOURS_PER_YEAR / FUNDING_INTERVAL_HOURS) * 100,
|
|
82
|
+
openInterestCoin: oiCoin,
|
|
83
|
+
openInterestUsd: oiCoin == null || mark == null ? null : oiCoin * mark,
|
|
84
|
+
maxLeverage: asset.maxLeverage ?? null,
|
|
85
|
+
szDecimals: asset.szDecimals ?? null,
|
|
86
|
+
isDelisted: Boolean(asset.isDelisted),
|
|
87
|
+
};
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const live = rows.filter((r) => !r.isDelisted);
|
|
91
|
+
return {
|
|
92
|
+
provider: "hl-info",
|
|
93
|
+
venue: "hyperliquid",
|
|
94
|
+
kind: "market-datapoints",
|
|
95
|
+
asOfMs: Date.now(),
|
|
96
|
+
count: live.length,
|
|
97
|
+
markets: live,
|
|
98
|
+
totals: {
|
|
99
|
+
openInterestUsd: live.reduce((a, r) => a + (r.openInterestUsd || 0), 0),
|
|
100
|
+
dayNtlVolumeUsd: live.reduce((a, r) => a + (r.dayNtlVolumeUsd || 0), 0),
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Top movers / volume / OI / funding leaders — the standard board cuts. */
|
|
106
|
+
export async function hlLeaderboards(args = {}, opts = {}) {
|
|
107
|
+
const limit = Math.max(1, Math.min(Number(args.limit) || 10, 50));
|
|
108
|
+
const { markets, asOfMs, totals } = await hlMarketDatapoints(args, opts);
|
|
109
|
+
|
|
110
|
+
const by = (key, dir = -1) =>
|
|
111
|
+
markets
|
|
112
|
+
.filter((m) => m[key] != null)
|
|
113
|
+
.sort((a, b) => (a[key] - b[key]) * dir)
|
|
114
|
+
.slice(0, limit);
|
|
115
|
+
|
|
116
|
+
return {
|
|
117
|
+
provider: "hl-info",
|
|
118
|
+
venue: "hyperliquid",
|
|
119
|
+
kind: "leaderboards",
|
|
120
|
+
asOfMs,
|
|
121
|
+
totals,
|
|
122
|
+
gainers: by("change24hPct"),
|
|
123
|
+
losers: by("change24hPct", 1),
|
|
124
|
+
byVolume: by("dayNtlVolumeUsd"),
|
|
125
|
+
byOpenInterest: by("openInterestUsd"),
|
|
126
|
+
fundingHighest: by("fundingRateAprPct"),
|
|
127
|
+
fundingLowest: by("fundingRateAprPct", 1),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* One coin, everything a segment or card needs: current state, the recent
|
|
133
|
+
* candle series, and top-of-book depth.
|
|
134
|
+
*/
|
|
135
|
+
export async function hlCoinDatapoints(args = {}, opts = {}) {
|
|
136
|
+
const coin = String(args.coin || args.symbol || "").trim().toUpperCase();
|
|
137
|
+
if (!coin) throw new Error("hl-markets: coin required");
|
|
138
|
+
const interval = String(args.interval || "1h");
|
|
139
|
+
const lookbackMs = Number(args.lookbackMs) || 24 * 60 * 60 * 1000;
|
|
140
|
+
const endTime = Date.now();
|
|
141
|
+
const startTime = endTime - lookbackMs;
|
|
142
|
+
|
|
143
|
+
const [board, candles, book] = await Promise.all([
|
|
144
|
+
hlMarketDatapoints({}, opts),
|
|
145
|
+
hlCandleSnapshot({ coin, interval, startTime, endTime }, opts).catch(() => []),
|
|
146
|
+
// hlL2Book takes a bare coin string, not an args object.
|
|
147
|
+
hlL2Book(coin, opts).catch(() => null),
|
|
148
|
+
]);
|
|
149
|
+
|
|
150
|
+
const market = board.markets.find((m) => m.coin === coin) || null;
|
|
151
|
+
if (!market) throw new Error(`hl-markets: ${coin} is not a listed perp`);
|
|
152
|
+
|
|
153
|
+
const series = (Array.isArray(candles) ? candles : []).map((c) => ({
|
|
154
|
+
t: Number(c.t),
|
|
155
|
+
open: num(c.o),
|
|
156
|
+
high: num(c.h),
|
|
157
|
+
low: num(c.l),
|
|
158
|
+
close: num(c.c),
|
|
159
|
+
volume: num(c.v),
|
|
160
|
+
}));
|
|
161
|
+
|
|
162
|
+
const levels = book?.levels ?? [];
|
|
163
|
+
const bestBid = num(levels?.[0]?.[0]?.px);
|
|
164
|
+
const bestAsk = num(levels?.[1]?.[0]?.px);
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
provider: "hl-info",
|
|
168
|
+
venue: "hyperliquid",
|
|
169
|
+
kind: "coin-datapoints",
|
|
170
|
+
asOfMs: Date.now(),
|
|
171
|
+
coin,
|
|
172
|
+
market,
|
|
173
|
+
book: {
|
|
174
|
+
bestBid,
|
|
175
|
+
bestAsk,
|
|
176
|
+
spread: bestBid == null || bestAsk == null ? null : bestAsk - bestBid,
|
|
177
|
+
spreadBps: bestBid == null || bestAsk == null || bestAsk === 0 ? null : ((bestAsk - bestBid) / bestAsk) * 10_000,
|
|
178
|
+
},
|
|
179
|
+
candles: { interval, count: series.length, series },
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Spot pairs, joined the same way. */
|
|
184
|
+
export async function hlSpotDatapoints(args = {}, opts = {}) {
|
|
185
|
+
const spot = await hlSpotMeta(opts);
|
|
186
|
+
const tokens = spot?.tokens ?? [];
|
|
187
|
+
const pairs = spot?.universe ?? [];
|
|
188
|
+
return {
|
|
189
|
+
provider: "hl-info",
|
|
190
|
+
venue: "hyperliquid",
|
|
191
|
+
kind: "spot-datapoints",
|
|
192
|
+
asOfMs: Date.now(),
|
|
193
|
+
tokenCount: tokens.length,
|
|
194
|
+
pairCount: pairs.length,
|
|
195
|
+
tokens: tokens.map((t) => ({
|
|
196
|
+
name: t.name,
|
|
197
|
+
index: t.index,
|
|
198
|
+
szDecimals: t.szDecimals ?? null,
|
|
199
|
+
weiDecimals: t.weiDecimals ?? null,
|
|
200
|
+
tokenId: t.tokenId ?? null,
|
|
201
|
+
isCanonical: Boolean(t.isCanonical),
|
|
202
|
+
})),
|
|
203
|
+
pairs: pairs.map((p) => ({
|
|
204
|
+
name: p.name,
|
|
205
|
+
index: p.index,
|
|
206
|
+
tokens: p.tokens,
|
|
207
|
+
isCanonical: Boolean(p.isCanonical),
|
|
208
|
+
})),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
// Hyperliquid perpetuals: orders, leverage, and position management.
|
|
2
|
+
//
|
|
3
|
+
// PREPARE-ONLY. Every function here returns EIP-712 typed data plus the exact
|
|
4
|
+
// action payload the user's wallet will sign. Nothing in this file signs,
|
|
5
|
+
// submits, or broadcasts — there is deliberately no submit function, and a
|
|
6
|
+
// test asserts that no write-shaped export ever appears.
|
|
7
|
+
//
|
|
8
|
+
// Why the arithmetic is fussy: Hyperliquid rejects orders whose price or size
|
|
9
|
+
// carry more precision than the asset allows, and a rejected order at the wrong
|
|
10
|
+
// moment is indistinguishable from a missed fill. Prices allow at most 5
|
|
11
|
+
// significant figures and (6 - szDecimals) decimal places for perps; sizes are
|
|
12
|
+
// rounded to szDecimals. Integers are always allowed regardless of sig figs.
|
|
13
|
+
// We do that rounding here, once, in decimal — never through a float.
|
|
14
|
+
|
|
15
|
+
import { hlMetaAndAssetCtxs } from "./hl-info.mjs";
|
|
16
|
+
import { toScaledInteger } from "../../exact-integer.mjs";
|
|
17
|
+
|
|
18
|
+
export const HL_PERP_MAX_SIG_FIGS = 5;
|
|
19
|
+
export const HL_PERP_PRICE_DECIMALS = 6; // 6 - szDecimals for perps
|
|
20
|
+
export const HL_SIGNATURE_CHAIN_ID = "0x66eee";
|
|
21
|
+
|
|
22
|
+
export const ORDER_TYPES = Object.freeze({
|
|
23
|
+
LIMIT: "limit",
|
|
24
|
+
MARKET: "market",
|
|
25
|
+
STOP_MARKET: "stopMarket",
|
|
26
|
+
STOP_LIMIT: "stopLimit",
|
|
27
|
+
TAKE_PROFIT_MARKET: "takeProfitMarket",
|
|
28
|
+
TAKE_PROFIT_LIMIT: "takeProfitLimit",
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
export const TIF = Object.freeze({
|
|
32
|
+
GTC: "Gtc", // rest on the book
|
|
33
|
+
IOC: "Ioc", // fill what you can, cancel the rest
|
|
34
|
+
ALO: "Alo", // add liquidity only; rejected if it would cross
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
export const MARGIN_MODE = Object.freeze({
|
|
38
|
+
CROSS: "cross",
|
|
39
|
+
ISOLATED: "isolated",
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/** Exact decimal rounding — no floats, so 0.1+0.2 problems cannot appear. */
|
|
43
|
+
function roundDecimal(value, maxDecimals, { roundDown = null } = {}) {
|
|
44
|
+
// `value` may arrive as a JS number from price math; normalise without
|
|
45
|
+
// exponent notation, which BigInt cannot parse.
|
|
46
|
+
const text = typeof value === "number" ? value.toFixed(Math.min(20, maxDecimals + 8)) : String(value).trim();
|
|
47
|
+
if (!/^-?\d+(\.\d+)?$/.test(text)) throw new Error(`hl-perps: "${value}" is not a decimal number`);
|
|
48
|
+
const neg = text.startsWith("-");
|
|
49
|
+
const [intPart, fracPart = ""] = text.replace(/^-/, "").split(".");
|
|
50
|
+
if (fracPart.length <= maxDecimals) {
|
|
51
|
+
const trimmed = fracPart.replace(/0+$/, "");
|
|
52
|
+
return (neg ? "-" : "") + (trimmed ? `${intPart}.${trimmed}` : intPart);
|
|
53
|
+
}
|
|
54
|
+
// Round on the exact decimal string. `roundDown` forces truncation (toward
|
|
55
|
+
// zero) or ceiling, which callers use to guarantee a bound is never crossed
|
|
56
|
+
// by the rounding itself; otherwise round half-up.
|
|
57
|
+
const keep = fracPart.slice(0, maxDecimals);
|
|
58
|
+
const nextDigit = Number(fracPart[maxDecimals]);
|
|
59
|
+
let scaled = BigInt(intPart + keep);
|
|
60
|
+
const remainder = fracPart.slice(maxDecimals).replace(/0+$/, "") !== "";
|
|
61
|
+
if (roundDown === true) {
|
|
62
|
+
// truncate: scaled already floors the magnitude
|
|
63
|
+
} else if (roundDown === false) {
|
|
64
|
+
if (remainder) scaled += 1n;
|
|
65
|
+
} else if (nextDigit >= 5) {
|
|
66
|
+
scaled += 1n;
|
|
67
|
+
}
|
|
68
|
+
const s = scaled.toString().padStart(maxDecimals + 1, "0");
|
|
69
|
+
const cut = maxDecimals === 0 ? s : `${s.slice(0, -maxDecimals)}.${s.slice(-maxDecimals)}`;
|
|
70
|
+
const cleaned = cut.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "");
|
|
71
|
+
return (neg ? "-" : "") + cleaned;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Significant-figure clamp. Integers are exempt, per Hyperliquid's rule. */
|
|
75
|
+
function clampSigFigs(value, sigFigs, opts = {}) {
|
|
76
|
+
const text = String(value);
|
|
77
|
+
if (!text.includes(".")) return text; // integer prices are always allowed
|
|
78
|
+
const n = Number(text);
|
|
79
|
+
if (!Number.isFinite(n) || n === 0) return text;
|
|
80
|
+
const magnitude = Math.floor(Math.log10(Math.abs(n)));
|
|
81
|
+
const decimals = Math.max(0, sigFigs - 1 - magnitude);
|
|
82
|
+
return roundDecimal(text, decimals, opts);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Format a price for a given asset. Applies BOTH constraints: at most 5
|
|
87
|
+
* significant figures AND at most (6 - szDecimals) decimal places.
|
|
88
|
+
*/
|
|
89
|
+
export function formatPerpPrice(price, szDecimals, opts = {}) {
|
|
90
|
+
const maxDecimals = HL_PERP_PRICE_DECIMALS - Number(szDecimals ?? 0);
|
|
91
|
+
if (maxDecimals < 0) throw new Error("hl-perps: szDecimals out of range");
|
|
92
|
+
return roundDecimal(clampSigFigs(price, HL_PERP_MAX_SIG_FIGS, opts), maxDecimals, opts);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Format an order size to the asset's size precision. */
|
|
96
|
+
export function formatPerpSize(size, szDecimals) {
|
|
97
|
+
const out = roundDecimal(size, Number(szDecimals ?? 0));
|
|
98
|
+
if (BigInt(out.split(".")[0]) < 0n) throw new Error("hl-perps: size must be positive");
|
|
99
|
+
if (Number(out) <= 0) throw new Error("hl-perps: size rounds to zero at this asset's precision");
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Resolve a coin to its asset index and precision. Required before ordering. */
|
|
104
|
+
export async function hlPerpAssetInfo(args = {}, opts = {}) {
|
|
105
|
+
const coin = String(args.coin || args.symbol || "").trim().toUpperCase();
|
|
106
|
+
if (!coin) throw new Error("hl-perps: coin required");
|
|
107
|
+
const meta = await hlMetaAndAssetCtxs(opts);
|
|
108
|
+
const universe = meta?.[0]?.universe ?? meta?.universe ?? [];
|
|
109
|
+
const ctxs = Array.isArray(meta?.[1]) ? meta[1] : [];
|
|
110
|
+
const index = universe.findIndex((a) => a.name === coin);
|
|
111
|
+
if (index < 0) throw new Error(`hl-perps: ${coin} is not a listed perp`);
|
|
112
|
+
const asset = universe[index];
|
|
113
|
+
if (asset.isDelisted) throw new Error(`hl-perps: ${coin} is delisted`);
|
|
114
|
+
const ctx = ctxs[index] || {};
|
|
115
|
+
return {
|
|
116
|
+
coin,
|
|
117
|
+
assetId: index,
|
|
118
|
+
szDecimals: asset.szDecimals ?? 0,
|
|
119
|
+
maxLeverage: asset.maxLeverage ?? null,
|
|
120
|
+
markPx: ctx.markPx ?? null,
|
|
121
|
+
oraclePx: ctx.oraclePx ?? null,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function orderTypeWire(kind, { tif = TIF.GTC, triggerPx, isMarket, szDecimals } = {}) {
|
|
126
|
+
switch (kind) {
|
|
127
|
+
case ORDER_TYPES.LIMIT:
|
|
128
|
+
return { limit: { tif } };
|
|
129
|
+
case ORDER_TYPES.MARKET:
|
|
130
|
+
// A "market" order on Hyperliquid is an IOC limit at an aggressive price.
|
|
131
|
+
return { limit: { tif: TIF.IOC } };
|
|
132
|
+
case ORDER_TYPES.STOP_MARKET:
|
|
133
|
+
case ORDER_TYPES.TAKE_PROFIT_MARKET:
|
|
134
|
+
return {
|
|
135
|
+
trigger: {
|
|
136
|
+
isMarket: true,
|
|
137
|
+
triggerPx: formatPerpPrice(triggerPx, szDecimals),
|
|
138
|
+
tpsl: kind === ORDER_TYPES.STOP_MARKET ? "sl" : "tp",
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
case ORDER_TYPES.STOP_LIMIT:
|
|
142
|
+
case ORDER_TYPES.TAKE_PROFIT_LIMIT:
|
|
143
|
+
return {
|
|
144
|
+
trigger: {
|
|
145
|
+
isMarket: false,
|
|
146
|
+
triggerPx: formatPerpPrice(triggerPx, szDecimals),
|
|
147
|
+
tpsl: kind === ORDER_TYPES.STOP_LIMIT ? "sl" : "tp",
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
default:
|
|
151
|
+
throw new Error(`hl-perps: unknown order type ${kind}`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function envelope(action, nonce) {
|
|
156
|
+
return {
|
|
157
|
+
action,
|
|
158
|
+
nonce,
|
|
159
|
+
signatureChainId: HL_SIGNATURE_CHAIN_ID,
|
|
160
|
+
// The wallet signs this; Oracle never does.
|
|
161
|
+
requiresUserSignature: true,
|
|
162
|
+
signingReady: false,
|
|
163
|
+
broadcastReady: false,
|
|
164
|
+
executionReady: false,
|
|
165
|
+
submitTo: "https://api.hyperliquid.xyz/exchange",
|
|
166
|
+
note: "Sign this action with the user's wallet and POST it. Oracle does not submit.",
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Prepare a perp order.
|
|
172
|
+
*
|
|
173
|
+
* Guardrails, all enforced BEFORE anything is built:
|
|
174
|
+
* - size and price rounded to the asset's exact precision
|
|
175
|
+
* - a limit order must state a price; a market order must state a slippage cap
|
|
176
|
+
* - `maxSlippageBps` is capped at 100 bps, matching every other Oracle venue
|
|
177
|
+
* - reduce-only is explicit, never inferred
|
|
178
|
+
*/
|
|
179
|
+
export async function hlPreparePerpOrder(args = {}, opts = {}) {
|
|
180
|
+
const info = await hlPerpAssetInfo(args, opts);
|
|
181
|
+
const kind = String(args.type || ORDER_TYPES.LIMIT);
|
|
182
|
+
const isBuy = args.side ? String(args.side).toLowerCase() === "buy" : Boolean(args.isBuy);
|
|
183
|
+
const reduceOnly = Boolean(args.reduceOnly);
|
|
184
|
+
const size = formatPerpSize(args.size ?? args.sz, info.szDecimals);
|
|
185
|
+
|
|
186
|
+
let price;
|
|
187
|
+
if (kind === ORDER_TYPES.MARKET) {
|
|
188
|
+
const mark = Number(info.markPx);
|
|
189
|
+
if (!Number.isFinite(mark)) throw new Error("hl-perps: no mark price available for a market order");
|
|
190
|
+
const bps = Number(args.maxSlippageBps ?? 50);
|
|
191
|
+
if (!Number.isInteger(bps) || bps < 0) throw new Error("hl-perps: maxSlippageBps must be a non-negative integer");
|
|
192
|
+
if (bps > 100) throw new Error(`hl-perps: maxSlippageBps ${bps} exceeds the hard 100 bps cap`);
|
|
193
|
+
// Aggressive IOC price: cross the book by at most the allowed slippage.
|
|
194
|
+
// Rounding to the venue's tick can push the limit BACK past the cap
|
|
195
|
+
// (0.0012345 * 1.01 rounds to 0.001247 = 101.26 bps), so round toward the
|
|
196
|
+
// mark — down for a buy, up for a sell — and verify the realised bps.
|
|
197
|
+
const rawLimit = isBuy ? mark * (1 + bps / 10_000) : mark * (1 - bps / 10_000);
|
|
198
|
+
price = formatPerpPrice(rawLimit, info.szDecimals, { roundDown: isBuy });
|
|
199
|
+
const realisedBps = Math.abs(Number(price) / mark - 1) * 10_000;
|
|
200
|
+
if (realisedBps > bps + 1e-9) {
|
|
201
|
+
throw new Error(
|
|
202
|
+
`hl-perps: tick rounding makes the limit ${realisedBps.toFixed(2)} bps from mark, above the ${bps} bps cap`
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
} else {
|
|
206
|
+
if (args.price == null && args.limitPx == null) {
|
|
207
|
+
throw new Error("hl-perps: a limit order requires an explicit price");
|
|
208
|
+
}
|
|
209
|
+
price = formatPerpPrice(args.price ?? args.limitPx, info.szDecimals);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const orderType = orderTypeWire(kind, {
|
|
213
|
+
tif: args.tif ?? (kind === ORDER_TYPES.MARKET ? TIF.IOC : TIF.GTC),
|
|
214
|
+
triggerPx: args.triggerPx,
|
|
215
|
+
szDecimals: info.szDecimals,
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
const order = {
|
|
219
|
+
a: info.assetId,
|
|
220
|
+
b: isBuy,
|
|
221
|
+
p: price,
|
|
222
|
+
s: size,
|
|
223
|
+
r: reduceOnly,
|
|
224
|
+
t: orderType,
|
|
225
|
+
};
|
|
226
|
+
if (args.clientOrderId) order.c = String(args.clientOrderId);
|
|
227
|
+
|
|
228
|
+
const action = {
|
|
229
|
+
type: "order",
|
|
230
|
+
orders: [order],
|
|
231
|
+
grouping: args.grouping || "na",
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
const nonce = Number(args.nonce ?? Date.now());
|
|
235
|
+
const notional = Number(price) * Number(size);
|
|
236
|
+
|
|
237
|
+
return {
|
|
238
|
+
provider: "hl-perps",
|
|
239
|
+
venue: "hyperliquid",
|
|
240
|
+
kind: "perp-order",
|
|
241
|
+
coin: info.coin,
|
|
242
|
+
assetId: info.assetId,
|
|
243
|
+
side: isBuy ? "buy" : "sell",
|
|
244
|
+
orderType: kind,
|
|
245
|
+
price,
|
|
246
|
+
size,
|
|
247
|
+
reduceOnly,
|
|
248
|
+
notionalUsd: Number.isFinite(notional) ? notional : null,
|
|
249
|
+
maxLeverage: info.maxLeverage,
|
|
250
|
+
markPx: info.markPx,
|
|
251
|
+
...envelope(action, nonce),
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Prepare a cancel by order id. */
|
|
256
|
+
export async function hlPrepareCancelOrder(args = {}, opts = {}) {
|
|
257
|
+
const info = await hlPerpAssetInfo(args, opts);
|
|
258
|
+
const oid = args.orderId ?? args.oid;
|
|
259
|
+
if (oid == null) throw new Error("hl-perps: orderId required");
|
|
260
|
+
const action = { type: "cancel", cancels: [{ a: info.assetId, o: Number(oid) }] };
|
|
261
|
+
return {
|
|
262
|
+
provider: "hl-perps",
|
|
263
|
+
venue: "hyperliquid",
|
|
264
|
+
kind: "perp-cancel",
|
|
265
|
+
coin: info.coin,
|
|
266
|
+
orderId: Number(oid),
|
|
267
|
+
...envelope(action, Number(args.nonce ?? Date.now())),
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Prepare a leverage change.
|
|
273
|
+
* Cross vs isolated is an explicit choice: isolated caps loss to the margin
|
|
274
|
+
* posted on that position, cross shares the whole account balance.
|
|
275
|
+
*/
|
|
276
|
+
export async function hlPrepareUpdateLeverage(args = {}, opts = {}) {
|
|
277
|
+
const info = await hlPerpAssetInfo(args, opts);
|
|
278
|
+
const leverage = Number(args.leverage);
|
|
279
|
+
if (!Number.isInteger(leverage) || leverage < 1) {
|
|
280
|
+
throw new Error("hl-perps: leverage must be a positive integer");
|
|
281
|
+
}
|
|
282
|
+
if (info.maxLeverage != null && leverage > info.maxLeverage) {
|
|
283
|
+
throw new Error(`hl-perps: ${info.coin} allows at most ${info.maxLeverage}x, requested ${leverage}x`);
|
|
284
|
+
}
|
|
285
|
+
const mode = String(args.marginMode || MARGIN_MODE.CROSS).toLowerCase();
|
|
286
|
+
if (mode !== MARGIN_MODE.CROSS && mode !== MARGIN_MODE.ISOLATED) {
|
|
287
|
+
throw new Error(`hl-perps: marginMode must be "cross" or "isolated"`);
|
|
288
|
+
}
|
|
289
|
+
const action = {
|
|
290
|
+
type: "updateLeverage",
|
|
291
|
+
asset: info.assetId,
|
|
292
|
+
isCross: mode === MARGIN_MODE.CROSS,
|
|
293
|
+
leverage,
|
|
294
|
+
};
|
|
295
|
+
return {
|
|
296
|
+
provider: "hl-perps",
|
|
297
|
+
venue: "hyperliquid",
|
|
298
|
+
kind: "perp-leverage",
|
|
299
|
+
coin: info.coin,
|
|
300
|
+
leverage,
|
|
301
|
+
marginMode: mode,
|
|
302
|
+
maxLeverage: info.maxLeverage,
|
|
303
|
+
liquidationWarning:
|
|
304
|
+
leverage >= 20
|
|
305
|
+
? `${leverage}x liquidates on roughly a ${(100 / leverage).toFixed(2)}% adverse move before fees`
|
|
306
|
+
: null,
|
|
307
|
+
...envelope(action, Number(args.nonce ?? Date.now())),
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Prepare an isolated-margin adjustment for an existing position. */
|
|
312
|
+
export async function hlPrepareUpdateIsolatedMargin(args = {}, opts = {}) {
|
|
313
|
+
const info = await hlPerpAssetInfo(args, opts);
|
|
314
|
+
const usd = args.usd ?? args.amountUsd;
|
|
315
|
+
if (usd == null) throw new Error("hl-perps: usd amount required");
|
|
316
|
+
const text = String(usd).trim();
|
|
317
|
+
if (!/^-?\d+(\.\d+)?$/.test(text)) throw new Error("hl-perps: usd must be a decimal number");
|
|
318
|
+
// Hyperliquid takes this in micro-USD as an integer. The old padEnd() sized
|
|
319
|
+
// the result from the NUMERIC magnitude, so "01.5" scaled 10x too small and
|
|
320
|
+
// silently under-posted margin. Scale by exact string arithmetic instead.
|
|
321
|
+
const micro = toScaledInteger(text, 6, "hl-perps: usd");
|
|
322
|
+
const action = {
|
|
323
|
+
type: "updateIsolatedMargin",
|
|
324
|
+
asset: info.assetId,
|
|
325
|
+
isBuy: true,
|
|
326
|
+
ntli: micro <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(micro) : micro.toString(),
|
|
327
|
+
};
|
|
328
|
+
return {
|
|
329
|
+
provider: "hl-perps",
|
|
330
|
+
venue: "hyperliquid",
|
|
331
|
+
kind: "perp-isolated-margin",
|
|
332
|
+
coin: info.coin,
|
|
333
|
+
usd: text,
|
|
334
|
+
...envelope(action, Number(args.nonce ?? Date.now())),
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Prepare a bracket: entry plus take-profit and/or stop-loss as reduce-only
|
|
340
|
+
* triggers. Grouped so the venue treats them as one position's protection.
|
|
341
|
+
*/
|
|
342
|
+
export async function hlPrepareBracketOrder(args = {}, opts = {}) {
|
|
343
|
+
const entry = await hlPreparePerpOrder(args, opts);
|
|
344
|
+
const info = await hlPerpAssetInfo(args, opts);
|
|
345
|
+
const isBuy = entry.side === "buy";
|
|
346
|
+
const orders = [entry.action.orders[0]];
|
|
347
|
+
|
|
348
|
+
if (args.takeProfitPx != null) {
|
|
349
|
+
orders.push({
|
|
350
|
+
a: info.assetId,
|
|
351
|
+
b: !isBuy,
|
|
352
|
+
p: formatPerpPrice(args.takeProfitPx, info.szDecimals),
|
|
353
|
+
s: entry.size,
|
|
354
|
+
r: true,
|
|
355
|
+
t: orderTypeWire(ORDER_TYPES.TAKE_PROFIT_MARKET, { triggerPx: args.takeProfitPx, szDecimals: info.szDecimals }),
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
if (args.stopLossPx != null) {
|
|
359
|
+
orders.push({
|
|
360
|
+
a: info.assetId,
|
|
361
|
+
b: !isBuy,
|
|
362
|
+
p: formatPerpPrice(args.stopLossPx, info.szDecimals),
|
|
363
|
+
s: entry.size,
|
|
364
|
+
r: true,
|
|
365
|
+
t: orderTypeWire(ORDER_TYPES.STOP_MARKET, { triggerPx: args.stopLossPx, szDecimals: info.szDecimals }),
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
if (orders.length === 1) throw new Error("hl-perps: a bracket needs takeProfitPx and/or stopLossPx");
|
|
369
|
+
|
|
370
|
+
const action = { type: "order", orders, grouping: "normalTpsl" };
|
|
371
|
+
return {
|
|
372
|
+
provider: "hl-perps",
|
|
373
|
+
venue: "hyperliquid",
|
|
374
|
+
kind: "perp-bracket",
|
|
375
|
+
coin: info.coin,
|
|
376
|
+
legs: orders.length,
|
|
377
|
+
entry: { side: entry.side, price: entry.price, size: entry.size },
|
|
378
|
+
takeProfitPx: args.takeProfitPx == null ? null : formatPerpPrice(args.takeProfitPx, info.szDecimals),
|
|
379
|
+
stopLossPx: args.stopLossPx == null ? null : formatPerpPrice(args.stopLossPx, info.szDecimals),
|
|
380
|
+
...envelope(action, Number(args.nonce ?? Date.now())),
|
|
381
|
+
};
|
|
382
|
+
}
|