Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 43 additions & 3 deletions src/api/perps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,10 +205,13 @@ export interface HlAssetInfo extends HlAssetMeta {
}

let _assetInfoCache: HlAssetInfo[] | null = null;
let _assetInfoCacheTime = 0;
const ASSET_CACHE_TTL_MS = 30_000; // 30 seconds — stale prices cause IOC failures

/** Fetch perpetuals universe metadata + live prices from Hyperliquid (cached per session). */
/** Fetch perpetuals universe metadata + live prices from Hyperliquid (cached for 30s). */
export async function getAssetMeta(): Promise<HlAssetInfo[]> {
if (_assetInfoCache) return _assetInfoCache;
const now = Date.now();
if (_assetInfoCache && (now - _assetInfoCacheTime) < ASSET_CACHE_TTL_MS) return _assetInfoCache;
try {
const res = await fetch('https://api.hyperliquid.xyz/info', {
method: 'POST',
Expand All @@ -224,9 +227,10 @@ export async function getAssetMeta(): Promise<HlAssetInfo[]> {
...m,
markPx: Number(ctxs?.[i]?.markPx ?? 0),
}));
_assetInfoCacheTime = now;
return _assetInfoCache;
} catch {
return [];
return _assetInfoCache ?? [];
}
}

Expand Down Expand Up @@ -322,3 +326,39 @@ export async function getUserLeverage(address: string): Promise<HlLeverageInfo[]
return [];
}
}

export interface HlPosition {
coin: string;
szi: number; // signed size: positive = long, negative = short
entryPx: number;
unrealizedPnl: number;
}

/** Fetch user's open positions from Hyperliquid clearinghouseState. */
export async function getUserPositions(address: string): Promise<HlPosition[]> {
try {
const res = await fetch('https://api.hyperliquid.xyz/info', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'clearinghouseState', user: address }),
});
const data = (await res.json()) as {
assetPositions?: {
position: {
coin: string;
szi: string;
entryPx?: string;
unrealizedPnl?: string;
};
}[];
};
return (data.assetPositions ?? []).map((ap) => ({
coin: ap.position.coin,
szi: parseFloat(ap.position.szi),
entryPx: parseFloat(ap.position.entryPx ?? '0'),
unrealizedPnl: parseFloat(ap.position.unrealizedPnl ?? '0'),
}));
Comment on lines +355 to +360

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

If ap.position is undefined or null, accessing ap.position.coin will throw a TypeError, causing the entire function to fail and return []. Enforce defensive programming by safely checking if ap.position exists before mapping.

    return (data.assetPositions ?? [])
      .map((ap) => {
        const pos = ap?.position;
        if (!pos) return null;
        return {
          coin: pos.coin,
          szi: parseFloat(pos.szi),
          entryPx: parseFloat(pos.entryPx ?? '0'),
          unrealizedPnl: parseFloat(pos.unrealizedPnl ?? '0'),
        };
      })
      .filter((p): p is HlPosition => p !== null);

} catch {
return [];
}
}
Loading