@pod-network/trade-sdk 0.1.0-rc.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/README.md +113 -0
- package/dist/client.d.ts +93 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +168 -0
- package/dist/client.js.map +1 -0
- package/dist/codec/decode.d.ts +22 -0
- package/dist/codec/decode.d.ts.map +1 -0
- package/dist/codec/decode.js +251 -0
- package/dist/codec/decode.js.map +1 -0
- package/dist/codec/fixed.d.ts +11 -0
- package/dist/codec/fixed.d.ts.map +1 -0
- package/dist/codec/fixed.js +37 -0
- package/dist/codec/fixed.js.map +1 -0
- package/dist/codec/resolution.d.ts +14 -0
- package/dist/codec/resolution.d.ts.map +1 -0
- package/dist/codec/resolution.js +35 -0
- package/dist/codec/resolution.js.map +1 -0
- package/dist/codec/units.d.ts +35 -0
- package/dist/codec/units.d.ts.map +1 -0
- package/dist/codec/units.js +86 -0
- package/dist/codec/units.js.map +1 -0
- package/dist/datafeed.d.ts +4 -0
- package/dist/datafeed.d.ts.map +1 -0
- package/dist/datafeed.js +73 -0
- package/dist/datafeed.js.map +1 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +19 -0
- package/dist/index.js.map +1 -0
- package/dist/stores/resource.d.ts +50 -0
- package/dist/stores/resource.d.ts.map +1 -0
- package/dist/stores/resource.js +154 -0
- package/dist/stores/resource.js.map +1 -0
- package/dist/sync/account-metrics.d.ts +26 -0
- package/dist/sync/account-metrics.d.ts.map +1 -0
- package/dist/sync/account-metrics.js +41 -0
- package/dist/sync/account-metrics.js.map +1 -0
- package/dist/sync/candles.d.ts +68 -0
- package/dist/sync/candles.d.ts.map +1 -0
- package/dist/sync/candles.js +318 -0
- package/dist/sync/candles.js.map +1 -0
- package/dist/sync/order-preview.d.ts +74 -0
- package/dist/sync/order-preview.d.ts.map +1 -0
- package/dist/sync/order-preview.js +86 -0
- package/dist/sync/order-preview.js.map +1 -0
- package/dist/sync/orders.d.ts +49 -0
- package/dist/sync/orders.d.ts.map +1 -0
- package/dist/sync/orders.js +210 -0
- package/dist/sync/orders.js.map +1 -0
- package/dist/sync/positions-live.d.ts +3 -0
- package/dist/sync/positions-live.d.ts.map +1 -0
- package/dist/sync/positions-live.js +86 -0
- package/dist/sync/positions-live.js.map +1 -0
- package/dist/sync/sources.d.ts +40 -0
- package/dist/sync/sources.d.ts.map +1 -0
- package/dist/sync/sources.js +197 -0
- package/dist/sync/sources.js.map +1 -0
- package/dist/transport/rest.d.ts +83 -0
- package/dist/transport/rest.d.ts.map +1 -0
- package/dist/transport/rest.js +146 -0
- package/dist/transport/rest.js.map +1 -0
- package/dist/transport/ws.d.ts +60 -0
- package/dist/transport/ws.d.ts.map +1 -0
- package/dist/transport/ws.js +235 -0
- package/dist/transport/ws.js.map +1 -0
- package/dist/types/public.d.ts +292 -0
- package/dist/types/public.d.ts.map +1 -0
- package/dist/types/public.js +4 -0
- package/dist/types/public.js.map +1 -0
- package/dist/types/wire.d.ts +283 -0
- package/dist/types/wire.d.ts.map +1 -0
- package/dist/types/wire.js +6 -0
- package/dist/types/wire.js.map +1 -0
- package/dist/write/delegation.d.ts +54 -0
- package/dist/write/delegation.d.ts.map +1 -0
- package/dist/write/delegation.js +81 -0
- package/dist/write/delegation.js.map +1 -0
- package/dist/write/index.d.ts +261 -0
- package/dist/write/index.d.ts.map +1 -0
- package/dist/write/index.js +428 -0
- package/dist/write/index.js.map +1 -0
- package/package.json +43 -0
- package/src/client.ts +229 -0
- package/src/codec/decode.ts +277 -0
- package/src/codec/fixed.ts +41 -0
- package/src/codec/resolution.ts +39 -0
- package/src/codec/units.ts +100 -0
- package/src/datafeed.ts +94 -0
- package/src/index.ts +49 -0
- package/src/stores/resource.ts +172 -0
- package/src/sync/account-metrics.ts +71 -0
- package/src/sync/candles.ts +326 -0
- package/src/sync/order-preview.ts +152 -0
- package/src/sync/orders.ts +205 -0
- package/src/sync/positions-live.ts +102 -0
- package/src/sync/sources.ts +239 -0
- package/src/transport/rest.ts +213 -0
- package/src/transport/ws.ts +255 -0
- package/src/types/public.ts +335 -0
- package/src/types/wire.ts +301 -0
- package/src/write/delegation.ts +113 -0
- package/src/write/index.ts +642 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// Live position recompute, replicating the backend's exact account math so the
|
|
2
|
+
// mark- AND funding-driven fields stay correct between pod_positions snapshots.
|
|
3
|
+
//
|
|
4
|
+
// A snapshot is only pushed when the account is touched, but mark moves every
|
|
5
|
+
// tick and funding accrues every tick. We recompute from the live marks and the
|
|
6
|
+
// live funding accumulator (funding_index, streamed via pod_markets), holding
|
|
7
|
+
// the snapshot's frozen inputs (native cash, size, entry, entry_funding, cost
|
|
8
|
+
// basis, resting-order escrow).
|
|
9
|
+
//
|
|
10
|
+
// EXACT replication of pod — see the cross-reference notes in pod at:
|
|
11
|
+
// trading/src/perps/mod.rs `cross_budgets` (withdrawable / equity)
|
|
12
|
+
// trading/src/perps/mod.rs `funding_accrued` (funding)
|
|
13
|
+
// trading/src/perps/config.rs `into_market` (margin-rate derivation)
|
|
14
|
+
// Integer semantics match trading/src/decimal.rs:
|
|
15
|
+
// mul(a,b) = (a*b)/1e18 truncated toward zero (Decimal `*`)
|
|
16
|
+
// mulFloor(a,b) = (a*b)/1e18 rounded toward -infinity (`mul_floor`)
|
|
17
|
+
// mulDivCeil(a,b,d) = (a*b)/d, positive results rounded up (`mul_div_ceil`)
|
|
18
|
+
// im = 1e18 / max_leverage ; mm = im / 2
|
|
19
|
+
// funding_accrued = mulDivCeil(funding_index - entry_funding, size, window_us*1e18)
|
|
20
|
+
// cash_with_funding = native_cash - Σ funding_accrued
|
|
21
|
+
|
|
22
|
+
import type { Market, MarketId, Position, PositionsSnapshot } from "../types/public.js";
|
|
23
|
+
import { WAD } from "../codec/units.js";
|
|
24
|
+
import { imRate, mul, mulDivCeil, mulFloor } from "../codec/fixed.js";
|
|
25
|
+
|
|
26
|
+
const absB = (x: bigint) => (x < 0n ? -x : x);
|
|
27
|
+
const maxB = (a: bigint, b: bigint) => (a > b ? a : b);
|
|
28
|
+
|
|
29
|
+
export function enrichPositions(snap: PositionsSnapshot, markets: Market[]): PositionsSnapshot {
|
|
30
|
+
const byId = new Map<MarketId, Market>(markets.map((m) => [m.id, m]));
|
|
31
|
+
|
|
32
|
+
let priceUpnl = 0n; // Σ perp price PnL at live mark (excludes funding)
|
|
33
|
+
let priceUpnlSnap = 0n; // Σ perp price PnL recorded in the snapshot
|
|
34
|
+
let fundingLiveTotal = 0n; // Σ funding accrued at the live funding_index
|
|
35
|
+
let fundingSnapTotal = 0n; // Σ funding accrued in the snapshot
|
|
36
|
+
let im = 0n; // Σ initial-margin requirement at live notional
|
|
37
|
+
let mm = 0n; // Σ maintenance-margin requirement at live notional
|
|
38
|
+
let dSpot = 0n; // change in spot mark value vs snapshot (slope = balance)
|
|
39
|
+
|
|
40
|
+
const positions: Position[] = snap.positions.map((p) => {
|
|
41
|
+
const market = p.orderbookId ? byId.get(p.orderbookId) : undefined;
|
|
42
|
+
|
|
43
|
+
if (p.kind === "perp") {
|
|
44
|
+
// Server-banded mark from pod_markets. Before a market's first trade the
|
|
45
|
+
// mark is unseeded (0) — fall back to the entry price so uPnL is 0 rather
|
|
46
|
+
// than a spurious −entry·size that would wrongly zero withdrawable cash.
|
|
47
|
+
const liveMark = market?.markPrice && market.markPrice > 0n ? market.markPrice : p.markPrice;
|
|
48
|
+
const mark = liveMark > 0n ? liveMark : p.entryPrice;
|
|
49
|
+
const upnl = mulFloor(mark - p.entryPrice, p.size); // pure price drift (signed)
|
|
50
|
+
const sizeQuote = mul(absB(p.size), mark); // = notional
|
|
51
|
+
const imr = imRate(market?.maxLeverage ?? 0);
|
|
52
|
+
im += mul(sizeQuote, imr);
|
|
53
|
+
mm += mul(sizeQuote, imr / 2n);
|
|
54
|
+
priceUpnl += upnl;
|
|
55
|
+
priceUpnlSnap += p.unrealizedPnl;
|
|
56
|
+
|
|
57
|
+
// Live funding: mul_div_ceil(funding_index - entry_funding, size, window_us*1e18).
|
|
58
|
+
// funding_index (= market.funding) streams via pod_markets; if unavailable,
|
|
59
|
+
// hold the snapshot value (re-aligned by the periodic REST resync).
|
|
60
|
+
let funding = p.fundingAccrued;
|
|
61
|
+
if (market?.fundingIndex !== undefined && market.fundingWindowUs) {
|
|
62
|
+
funding = mulDivCeil(
|
|
63
|
+
market.fundingIndex - p.entryFunding,
|
|
64
|
+
p.size,
|
|
65
|
+
BigInt(market.fundingWindowUs) * WAD,
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
fundingLiveTotal += funding;
|
|
69
|
+
fundingSnapTotal += p.fundingAccrued;
|
|
70
|
+
|
|
71
|
+
return { ...p, markPrice: mark, unrealizedPnl: upnl, notional: sizeQuote, fundingAccrued: funding };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const mark = market?.lastClearingPrice ?? market?.markPrice ?? p.markPrice;
|
|
75
|
+
dSpot += mul(p.balance, mark) - mul(p.balance, p.markPrice);
|
|
76
|
+
return { ...p, markPrice: mark, unrealizedPnl: p.unrealizedPnl + (mul(p.balance, mark) - mul(p.balance, p.markPrice)) };
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// native_cash is frozen between snapshots; back it out of the snapshot's
|
|
80
|
+
// funding-adjusted cash, then re-apply funding at the live index.
|
|
81
|
+
const nativeCash = snap.cash + fundingSnapTotal;
|
|
82
|
+
const cashWithFunding = nativeCash - fundingLiveTotal;
|
|
83
|
+
|
|
84
|
+
// EXACT (perp-only, integer-faithful): equity = cash_with_funding + Σ price PnL;
|
|
85
|
+
// withdrawable = max(0, equity - Σ IM), forced to 0 below maintenance margin.
|
|
86
|
+
const perpsEquity = cashWithFunding + priceUpnl;
|
|
87
|
+
const withdrawableCash = perpsEquity < mm ? 0n : maxB(0n, perpsEquity - im);
|
|
88
|
+
|
|
89
|
+
// account_value moves with perp equity (incl. funding) AND spot mark; total
|
|
90
|
+
// uPnL is pure price drift only (funding is reported separately). Re-baseline
|
|
91
|
+
// off the snapshot with exact slopes, leaving the frozen resting escrow alone.
|
|
92
|
+
const dPriceUpnl = priceUpnl - priceUpnlSnap;
|
|
93
|
+
return {
|
|
94
|
+
positions,
|
|
95
|
+
cash: cashWithFunding,
|
|
96
|
+
totalRealizedPnl: snap.totalRealizedPnl,
|
|
97
|
+
perpsEquity,
|
|
98
|
+
withdrawableCash,
|
|
99
|
+
totalUnrealizedPnl: snap.totalUnrealizedPnl + dPriceUpnl + dSpot,
|
|
100
|
+
accountValue: snap.accountValue + (perpsEquity - snap.perpsEquity) + dSpot,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// Per-entity ResourceSource factories: seed once over REST where it helps, then
|
|
2
|
+
// maintain in memory from the matching `pod_*` channel.
|
|
3
|
+
//
|
|
4
|
+
// Reconnect model:
|
|
5
|
+
// - Current-state channels (markets/positions/triggers) subscribe with
|
|
6
|
+
// `since: 0`, so every (re)subscribe yields a fresh immediate snapshot — no
|
|
7
|
+
// staleness possible, nothing to re-seed.
|
|
8
|
+
// - REST-seeded channels (markets static, orderbook, balances) seed
|
|
9
|
+
// immediately — the fetch doesn't need the socket, so first data isn't
|
|
10
|
+
// held behind the WS handshake — and re-seed on every (re)connect via
|
|
11
|
+
// `seedNowAndOnReconnect`, so state is refreshed after any downtime.
|
|
12
|
+
// - The WS client auto-resubscribes live subs on reconnect; tick-log channels
|
|
13
|
+
// that use `since` (candles/orders) advance/refresh it and fall back to a
|
|
14
|
+
// REST re-seed via `onError` when `since` is too old (down too long).
|
|
15
|
+
|
|
16
|
+
import type {
|
|
17
|
+
Address, Balances, Market, MarketId, Orderbook, PositionsSnapshot, Status, Trigger,
|
|
18
|
+
} from "../types/public.js";
|
|
19
|
+
import type {
|
|
20
|
+
WireMarketDynamics, WireOrderbook, WirePositionsPush, WireTriggersPush,
|
|
21
|
+
} from "../types/wire.js";
|
|
22
|
+
import {
|
|
23
|
+
decodeMarketDynamics, decodeOrderbook, decodePositions, decodeTrigger,
|
|
24
|
+
} from "../codec/decode.js";
|
|
25
|
+
import type { PodRestClient } from "../transport/rest.js";
|
|
26
|
+
import type { PodWsClient } from "../transport/ws.js";
|
|
27
|
+
import type { ResourceSource } from "../stores/resource.js";
|
|
28
|
+
|
|
29
|
+
export interface SyncContext {
|
|
30
|
+
rest: PodRestClient;
|
|
31
|
+
ws: PodWsClient;
|
|
32
|
+
/** Periodic REST re-alignment interval (ms) for positions; 0 disables. */
|
|
33
|
+
positionResyncMs: number;
|
|
34
|
+
/** Periodic REST re-poll (ms) of market 24h stats; 0 disables. */
|
|
35
|
+
marketResyncMs: number;
|
|
36
|
+
/** Optional persistence for the static markets list (see marketsSource). */
|
|
37
|
+
marketsCache?: MarketsCache;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Host-supplied persistence (e.g. localStorage-backed) for the static markets
|
|
42
|
+
* list, so market-keyed UI can mount immediately on a repeat visit instead of
|
|
43
|
+
* waiting a REST round trip. Only the static `/clob/markets` config is stored —
|
|
44
|
+
* never prices/stats, which always arrive live. Implementations may throw
|
|
45
|
+
* (storage denied, quota); callers ignore failures.
|
|
46
|
+
*/
|
|
47
|
+
export interface MarketsCache {
|
|
48
|
+
get(): string | null;
|
|
49
|
+
set(value: string): void;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Static-list serialization for MarketsCache. Version is embedded in the
|
|
53
|
+
// payload: a mismatch after an SDK format change just falls back to a cold
|
|
54
|
+
// start. bigints round-trip as "<digits>n" strings.
|
|
55
|
+
const MARKETS_CACHE_VERSION = 1;
|
|
56
|
+
const serializeMarkets = (markets: Market[]): string =>
|
|
57
|
+
JSON.stringify({ v: MARKETS_CACHE_VERSION, markets }, (_k, v: unknown) => (typeof v === "bigint" ? `${v}n` : v));
|
|
58
|
+
const parseCachedMarkets = (raw: string | null): Market[] | undefined => {
|
|
59
|
+
if (!raw) return undefined;
|
|
60
|
+
const data = JSON.parse(raw, (_k, v: unknown) =>
|
|
61
|
+
typeof v === "string" && /^-?\d+n$/.test(v) ? BigInt(v.slice(0, -1)) : v) as { v: number; markets: Market[] };
|
|
62
|
+
return data?.v === MARKETS_CACHE_VERSION ? data.markets : undefined;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Seed now — a REST fetch needs no socket, so don't hold first data behind the
|
|
67
|
+
* WS handshake — and re-seed on every (re)connect so state refreshes after any
|
|
68
|
+
* downtime. On a cold start the connect completes shortly after the immediate
|
|
69
|
+
* seed and triggers one extra seed; that duplicate is what guarantees a seed
|
|
70
|
+
* at/after the moment the WS subscription goes live, exactly as before.
|
|
71
|
+
*/
|
|
72
|
+
export function seedNowAndOnReconnect(ws: PodWsClient, fn: () => void): () => void {
|
|
73
|
+
const off = ws.on("open", fn);
|
|
74
|
+
fn();
|
|
75
|
+
return off;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function statusSource({ rest, ws }: SyncContext): ResourceSource<Status> {
|
|
79
|
+
return (h) => {
|
|
80
|
+
let alive = true;
|
|
81
|
+
const seed = () => { rest.status().then((s) => { if (alive) h.set(s); }).catch((e) => h.fail(e)); };
|
|
82
|
+
const off = seedNowAndOnReconnect(ws, seed);
|
|
83
|
+
return () => { alive = false; off(); };
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function marketsSource(
|
|
88
|
+
{ rest, ws, marketResyncMs, marketsCache }: SyncContext,
|
|
89
|
+
): ResourceSource<Market[]> {
|
|
90
|
+
return (h) => {
|
|
91
|
+
let alive = true;
|
|
92
|
+
const byId = new Map<string, Market>();
|
|
93
|
+
// Stable display order = the static /clob/markets order, so the list never
|
|
94
|
+
// reshuffles as dynamics arrive (markets not yet in the static list sort last).
|
|
95
|
+
const orderIndex = new Map<string, number>();
|
|
96
|
+
const publish = () => h.set(
|
|
97
|
+
[...byId.values()]
|
|
98
|
+
// pod_markets dynamics can arrive (and create an entry) before the static
|
|
99
|
+
// /clob/markets seed — those lack base/quote/name. Don't expose a market
|
|
100
|
+
// until its static config has merged in; the dynamics stay buffered.
|
|
101
|
+
.filter((m) => m.base !== undefined)
|
|
102
|
+
.sort((a, b) =>
|
|
103
|
+
(orderIndex.get(a.id) ?? Number.MAX_SAFE_INTEGER) - (orderIndex.get(b.id) ?? Number.MAX_SAFE_INTEGER)
|
|
104
|
+
|| a.id.localeCompare(b.id)),
|
|
105
|
+
);
|
|
106
|
+
const mergePatch = (patch: Partial<Market> & { id: string }) => {
|
|
107
|
+
const existing = byId.get(patch.id);
|
|
108
|
+
byId.set(patch.id, existing ? { ...existing, ...patch } : (patch as Market));
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// Last session's static list (never dynamics — those stay live-only):
|
|
112
|
+
// seeded synchronously so market-keyed UI mounts without a round trip.
|
|
113
|
+
// The REST seed below overwrites it field-for-field when it lands.
|
|
114
|
+
const fromCache = new Set<MarketId>();
|
|
115
|
+
try {
|
|
116
|
+
const cached = marketsCache && parseCachedMarkets(marketsCache.get());
|
|
117
|
+
cached?.forEach((m, i) => { orderIndex.set(m.id, i); byId.set(m.id, m); fromCache.add(m.id); });
|
|
118
|
+
if (byId.size) publish();
|
|
119
|
+
} catch { /* absent/corrupt cache — plain cold start */ }
|
|
120
|
+
|
|
121
|
+
const seedStatic = () => rest.markets().then((markets) => {
|
|
122
|
+
if (!alive) return;
|
|
123
|
+
// Fresh static truth: drop cache-seeded markets that no longer exist,
|
|
124
|
+
// so a delisting can't outlive the first seed. (Dynamics-only entries
|
|
125
|
+
// buffered from the WS stream are untouched, as before.)
|
|
126
|
+
const fresh = new Set(markets.map((m) => m.id));
|
|
127
|
+
for (const id of fromCache) if (!fresh.has(id)) { byId.delete(id); orderIndex.delete(id); }
|
|
128
|
+
fromCache.clear();
|
|
129
|
+
markets.forEach((m, i) => { orderIndex.set(m.id, i); byId.set(m.id, { ...byId.get(m.id), ...m }); });
|
|
130
|
+
publish();
|
|
131
|
+
try { marketsCache?.set(serializeMarkets(markets)); } catch { /* storage denied/full */ }
|
|
132
|
+
}).catch((e) => { if (!byId.size) h.fail(e); });
|
|
133
|
+
|
|
134
|
+
// 24h vol/high/low slide with time and only the REST stats reflect that
|
|
135
|
+
// (the WS only pushes on a clear) — so poll them periodically.
|
|
136
|
+
const seedStats = () => rest.marketStats().then((page) => {
|
|
137
|
+
if (!alive) return;
|
|
138
|
+
page.markets.forEach(mergePatch);
|
|
139
|
+
publish();
|
|
140
|
+
}).catch(() => { /* live dynamics also arrive on the stream */ });
|
|
141
|
+
|
|
142
|
+
const offOpen = seedNowAndOnReconnect(ws, () => { void seedStatic(); void seedStats(); });
|
|
143
|
+
const timer = marketResyncMs > 0 ? setInterval(seedStats, marketResyncMs) : undefined;
|
|
144
|
+
|
|
145
|
+
// Live clearing/mark/funding between polls.
|
|
146
|
+
const sub = ws.subscribe("pod_markets", { since: 0 }, (result) => {
|
|
147
|
+
const items = Array.isArray(result) ? result : [result];
|
|
148
|
+
for (const it of items) {
|
|
149
|
+
const w = it as Record<string, unknown>;
|
|
150
|
+
mergePatch(decodeMarketDynamics({ ...w, orderbook_id: w.orderbook_id ?? w.orderbook } as WireMarketDynamics));
|
|
151
|
+
}
|
|
152
|
+
publish();
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
return () => { alive = false; offOpen(); if (timer) clearInterval(timer); sub.unsubscribe(); };
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function orderbookSource(
|
|
160
|
+
{ rest, ws }: SyncContext,
|
|
161
|
+
id: MarketId,
|
|
162
|
+
depth?: number,
|
|
163
|
+
): ResourceSource<Orderbook> {
|
|
164
|
+
return (h) => {
|
|
165
|
+
let alive = true;
|
|
166
|
+
const seed = () => {
|
|
167
|
+
rest.orderbook(id).then((ob) => {
|
|
168
|
+
const cur = h.current();
|
|
169
|
+
if (alive && (!cur || cur.timeMs <= ob.timeMs)) h.set(ob);
|
|
170
|
+
}).catch((e) => { if (!h.current()) h.fail(e); });
|
|
171
|
+
};
|
|
172
|
+
const offOpen = seedNowAndOnReconnect(ws, seed);
|
|
173
|
+
const sub = ws.subscribe("pod_orderbook", { clobIds: [id], depth }, (result) => {
|
|
174
|
+
const ob = decodeOrderbook(result as WireOrderbook);
|
|
175
|
+
const cur = h.current();
|
|
176
|
+
if (!cur || ob.timeMs >= cur.timeMs) h.set(ob);
|
|
177
|
+
});
|
|
178
|
+
return () => { alive = false; offOpen(); sub.unsubscribe(); };
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function positionsSource(
|
|
183
|
+
{ rest, ws, positionResyncMs }: SyncContext,
|
|
184
|
+
account: Address,
|
|
185
|
+
): ResourceSource<PositionsSnapshot> {
|
|
186
|
+
return (h) => {
|
|
187
|
+
let alive = true;
|
|
188
|
+
// Baseline refreshes from three triggers, all just replacing the snapshot:
|
|
189
|
+
// - WS since:0 immediate + on every account-touching tick,
|
|
190
|
+
// - a periodic REST poll that re-aligns to the backend's exact accounting
|
|
191
|
+
// (corrects mark-extrapolation drift even when the account isn't touched).
|
|
192
|
+
const reseed = () => rest.positions(account).then((s) => { if (alive) h.set(s); }).catch(() => {});
|
|
193
|
+
reseed();
|
|
194
|
+
const timer = positionResyncMs > 0 ? setInterval(reseed, positionResyncMs) : undefined;
|
|
195
|
+
const sub = ws.subscribe("pod_positions", { account, since: 0 }, (result) => {
|
|
196
|
+
if (alive) h.set(decodePositions((result as WirePositionsPush).data));
|
|
197
|
+
});
|
|
198
|
+
return () => { alive = false; if (timer) clearInterval(timer); sub.unsubscribe(); };
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function balancesSource(
|
|
203
|
+
{ rest, ws, positionResyncMs }: SyncContext,
|
|
204
|
+
account: Address,
|
|
205
|
+
): ResourceSource<Balances> {
|
|
206
|
+
return (h) => {
|
|
207
|
+
let alive = true;
|
|
208
|
+
// No dedicated balances stream — seed over REST, re-poll periodically, and
|
|
209
|
+
// re-fetch (debounced) whenever the account is touched on pod_positions, so
|
|
210
|
+
// a spot fill / deposit reflects promptly without spamming a fetch per tick.
|
|
211
|
+
const seed = () => rest.balances(account).then((b) => { if (alive) h.set(b); }).catch((e) => { if (!h.current()) h.fail(e as Error); });
|
|
212
|
+
const offOpen = seedNowAndOnReconnect(ws, seed);
|
|
213
|
+
const timer = positionResyncMs > 0 ? setInterval(seed, positionResyncMs) : undefined;
|
|
214
|
+
let debounce: ReturnType<typeof setTimeout> | undefined;
|
|
215
|
+
const sub = ws.subscribe("pod_positions", { account, since: 0 }, () => {
|
|
216
|
+
if (!alive || debounce) return;
|
|
217
|
+
debounce = setTimeout(() => { debounce = undefined; seed(); }, 500);
|
|
218
|
+
});
|
|
219
|
+
return () => {
|
|
220
|
+
alive = false;
|
|
221
|
+
offOpen();
|
|
222
|
+
if (timer) clearInterval(timer);
|
|
223
|
+
if (debounce) clearTimeout(debounce);
|
|
224
|
+
sub.unsubscribe();
|
|
225
|
+
};
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export function triggersSource(
|
|
230
|
+
{ ws }: SyncContext,
|
|
231
|
+
account: Address,
|
|
232
|
+
): ResourceSource<Trigger[]> {
|
|
233
|
+
return (h) => {
|
|
234
|
+
const sub = ws.subscribe("pod_triggers", { account, since: 0 }, (result) => {
|
|
235
|
+
h.set((result as WireTriggersPush).triggers.map(decodeTrigger));
|
|
236
|
+
});
|
|
237
|
+
return () => sub.unsubscribe();
|
|
238
|
+
};
|
|
239
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// Layer 1: typed one-shot REST reads of `/clob/*`. Plain fetch so the browser /
|
|
2
|
+
// CDN honor the server's Cache-Control; identical concurrent GETs are deduped.
|
|
3
|
+
// ms in, decoded (bigint / ms) out.
|
|
4
|
+
|
|
5
|
+
import type {
|
|
6
|
+
Address, BackstopTransfer, Balances, Bar, CandleQuery, LeaderboardPage, LeaderboardQuery,
|
|
7
|
+
Market, MarketId, Order, Orderbook, PositionsSnapshot, Resolution, Status, Trigger, TxExplorer,
|
|
8
|
+
} from "../types/public.js";
|
|
9
|
+
import type {
|
|
10
|
+
WireBackstopPage, WireBalances, WireCandlesEnvelope, WireLeaderboard, WireMarketStatic,
|
|
11
|
+
WireMarketStatsPage, WireOrderbook, WireOrdersPage, WirePositionsSnapshot, WireStatus,
|
|
12
|
+
WireTriggersPage,
|
|
13
|
+
} from "../types/wire.js";
|
|
14
|
+
import {
|
|
15
|
+
decodeBackstopTransfer, decodeBalances, decodeCandle, decodeLeaderboard, decodeMarketDynamics,
|
|
16
|
+
decodeMarketStatic, decodeOrder, decodeOrderbook, decodePositions, decodeStatus, decodeTrigger,
|
|
17
|
+
} from "../codec/decode.js";
|
|
18
|
+
import { msToSecs, usToMs } from "../codec/units.js";
|
|
19
|
+
|
|
20
|
+
export type MarketDynamicsPatch = Partial<Market> & { id: string };
|
|
21
|
+
|
|
22
|
+
export interface MarketStatsPage {
|
|
23
|
+
solutionNow: number;
|
|
24
|
+
markets: MarketDynamicsPatch[];
|
|
25
|
+
}
|
|
26
|
+
export interface OrdersPage {
|
|
27
|
+
orders: Order[];
|
|
28
|
+
nextCursor: string | null;
|
|
29
|
+
totalCount: number;
|
|
30
|
+
solutionNow: number;
|
|
31
|
+
}
|
|
32
|
+
export interface BackstopPage {
|
|
33
|
+
transfers: BackstopTransfer[];
|
|
34
|
+
totalCount: number;
|
|
35
|
+
solutionNow: number;
|
|
36
|
+
}
|
|
37
|
+
export interface TriggersPage {
|
|
38
|
+
triggers: Trigger[];
|
|
39
|
+
totalCount: number;
|
|
40
|
+
nextCursor: string | null;
|
|
41
|
+
}
|
|
42
|
+
export interface CandlesPage {
|
|
43
|
+
bars: Bar[]; // oldest-first
|
|
44
|
+
resolution: Resolution;
|
|
45
|
+
range: { from: number; to: number } | null; // ms, oldest->newest bucket returned
|
|
46
|
+
solutionNow: number; // ms (indexer watermark; thread into pod_candles `since`)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface OrdersQueryRest {
|
|
50
|
+
until?: number; // ms
|
|
51
|
+
limit?: number;
|
|
52
|
+
cursor?: string;
|
|
53
|
+
}
|
|
54
|
+
export interface TriggersQueryRest {
|
|
55
|
+
orderbook?: MarketId;
|
|
56
|
+
limit?: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class PodHttpError extends Error {
|
|
60
|
+
constructor(public status: number, public url: string, message: string) {
|
|
61
|
+
super(message);
|
|
62
|
+
this.name = "PodHttpError";
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
type FetchFn = typeof fetch;
|
|
67
|
+
|
|
68
|
+
export interface RestClientOptions {
|
|
69
|
+
restUrl: string;
|
|
70
|
+
fetch?: FetchFn;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export class PodRestClient {
|
|
74
|
+
private readonly base: string;
|
|
75
|
+
private readonly fetchFn: FetchFn;
|
|
76
|
+
private readonly inflight = new Map<string, Promise<unknown>>();
|
|
77
|
+
|
|
78
|
+
constructor(opts: RestClientOptions) {
|
|
79
|
+
this.base = opts.restUrl.replace(/\/$/, "");
|
|
80
|
+
this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
private async get<T>(path: string, query?: Record<string, string | number | undefined>): Promise<T> {
|
|
84
|
+
const url = this.buildUrl(path, query);
|
|
85
|
+
const existing = this.inflight.get(url) as Promise<T> | undefined;
|
|
86
|
+
if (existing) return existing;
|
|
87
|
+
const p = this.doGet<T>(url).finally(() => this.inflight.delete(url));
|
|
88
|
+
this.inflight.set(url, p);
|
|
89
|
+
return p;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
private buildUrl(path: string, query?: Record<string, string | number | undefined>): string {
|
|
93
|
+
// Resolve against the page origin so a relative/empty base (same-origin
|
|
94
|
+
// deployment or a dev proxy) works as well as an absolute base.
|
|
95
|
+
const origin = (globalThis as { location?: { origin: string } }).location?.origin;
|
|
96
|
+
const u = origin ? new URL(this.base + path, origin) : new URL(this.base + path);
|
|
97
|
+
if (query) {
|
|
98
|
+
for (const [k, v] of Object.entries(query)) {
|
|
99
|
+
if (v !== undefined) u.searchParams.set(k, String(v));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return u.toString();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private async doGet<T>(url: string): Promise<T> {
|
|
106
|
+
const res = await this.fetchFn(url, { headers: { accept: "application/json" } });
|
|
107
|
+
if (!res.ok) {
|
|
108
|
+
let body = "";
|
|
109
|
+
try { body = await res.text(); } catch { /* ignore */ }
|
|
110
|
+
throw new PodHttpError(res.status, url, `GET ${url} -> ${res.status} ${body}`.trim());
|
|
111
|
+
}
|
|
112
|
+
return (await res.json()) as T;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async status(): Promise<Status> {
|
|
116
|
+
return decodeStatus(await this.get<WireStatus>("/clob/status"));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async markets(): Promise<Market[]> {
|
|
120
|
+
const w = await this.get<WireMarketStatic[]>("/clob/markets");
|
|
121
|
+
return w.map(decodeMarketStatic);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async marketStats(opts?: { to?: number }): Promise<MarketStatsPage> {
|
|
125
|
+
const w = await this.get<WireMarketStatsPage>("/clob/markets/stats", {
|
|
126
|
+
to: opts?.to !== undefined ? msToSecs(opts.to) : undefined,
|
|
127
|
+
});
|
|
128
|
+
return {
|
|
129
|
+
solutionNow: Math.trunc(w.solution_now / 1000),
|
|
130
|
+
markets: w.markets.map(decodeMarketDynamics),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async candles(id: MarketId, q: CandleQuery): Promise<CandlesPage> {
|
|
135
|
+
const w = await this.get<WireCandlesEnvelope>(`/clob/candles/${id}`, {
|
|
136
|
+
resolution: q.resolution,
|
|
137
|
+
from: q.from !== undefined ? msToSecs(q.from) : undefined,
|
|
138
|
+
to: q.to !== undefined ? msToSecs(q.to) : undefined,
|
|
139
|
+
limit: q.limit,
|
|
140
|
+
});
|
|
141
|
+
return {
|
|
142
|
+
// Wire is newest-first; return oldest-first for chart consumption.
|
|
143
|
+
bars: w.candles.map(decodeCandle).reverse(),
|
|
144
|
+
resolution: w.resolution as Resolution,
|
|
145
|
+
range: w.range ? { from: usToMs(w.range.from_us), to: usToMs(w.range.to_us) } : null,
|
|
146
|
+
solutionNow: usToMs(w.solution_now_us),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async orders(account: Address, q?: OrdersQueryRest): Promise<OrdersPage> {
|
|
151
|
+
const w = await this.get<WireOrdersPage>(`/clob/orders/${account}`, {
|
|
152
|
+
until: q?.until !== undefined ? msToSecs(q.until) : undefined,
|
|
153
|
+
limit: q?.limit,
|
|
154
|
+
cursor: q?.cursor,
|
|
155
|
+
});
|
|
156
|
+
return {
|
|
157
|
+
orders: w.orders.map(decodeOrder),
|
|
158
|
+
nextCursor: w.next_cursor,
|
|
159
|
+
totalCount: w.total_count,
|
|
160
|
+
solutionNow: Math.trunc(w.solution_now / 1000),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async backstopTransfers(account: Address): Promise<BackstopPage> {
|
|
165
|
+
const w = await this.get<WireBackstopPage>(`/clob/backstop-transfers/${account}`);
|
|
166
|
+
return {
|
|
167
|
+
transfers: w.backstop_transfers.map(decodeBackstopTransfer),
|
|
168
|
+
totalCount: w.total_count,
|
|
169
|
+
solutionNow: Math.trunc(w.solution_now / 1000),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async orderbook(id: MarketId): Promise<Orderbook> {
|
|
174
|
+
return decodeOrderbook(await this.get<WireOrderbook>(`/clob/orderbook/${id}`));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Perp positions + account aggregates (spot holdings are at `/clob/balances`). */
|
|
178
|
+
async positions(account: Address): Promise<PositionsSnapshot> {
|
|
179
|
+
return decodePositions(await this.get<WirePositionsSnapshot>(`/clob/positions/${account}`));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Spot holdings + native cash. */
|
|
183
|
+
async balances(account: Address): Promise<Balances> {
|
|
184
|
+
return decodeBalances(await this.get<WireBalances>(`/clob/balances/${account}`));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Flat explorer view of a transaction (fields, receipt, logs, attestations,
|
|
188
|
+
* decoded calldata). Returned as-is (hex fields raw). */
|
|
189
|
+
async transaction(hash: string): Promise<TxExplorer> {
|
|
190
|
+
return this.get<TxExplorer>(`/tx/${hash}`);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Accounts ranked by net PnL (realized + unrealized), descending. Paginate
|
|
194
|
+
* with `{ limit, offset }`; ranks are 1-based over the full ordering. */
|
|
195
|
+
async leaderboard(q?: LeaderboardQuery): Promise<LeaderboardPage> {
|
|
196
|
+
const w = await this.get<WireLeaderboard>("/clob/leaderboard", {
|
|
197
|
+
limit: q?.limit, offset: q?.offset, address: q?.account,
|
|
198
|
+
});
|
|
199
|
+
return decodeLeaderboard(w, q?.offset ?? 0);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async triggers(account: Address, q?: TriggersQueryRest): Promise<TriggersPage> {
|
|
203
|
+
const w = await this.get<WireTriggersPage>(`/clob/triggers/${account}`, {
|
|
204
|
+
orderbook: q?.orderbook,
|
|
205
|
+
limit: q?.limit,
|
|
206
|
+
});
|
|
207
|
+
return {
|
|
208
|
+
triggers: w.triggers.map(decodeTrigger),
|
|
209
|
+
totalCount: w.total_count,
|
|
210
|
+
nextCursor: w.next_cursor,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
}
|