@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
package/src/client.ts
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Address, BackstopTransfer, Balances, LeaderboardPage, LeaderboardQuery, Market, MarketId,
|
|
3
|
+
PositionsSnapshot, Resolution, Status, TimeRange, Trigger, TriggersQuery, TxExplorer, OrdersQuery,
|
|
4
|
+
} from "./types/public.js";
|
|
5
|
+
import { PodRestClient } from "./transport/rest.js";
|
|
6
|
+
import { PodWsClient, type WebSocketCtor } from "./transport/ws.js";
|
|
7
|
+
import { BaseResource, combineResources, derivedResource, type Resource } from "./stores/resource.js";
|
|
8
|
+
import {
|
|
9
|
+
balancesSource, marketsSource, orderbookSource, positionsSource, statusSource, triggersSource,
|
|
10
|
+
type MarketsCache, type SyncContext,
|
|
11
|
+
} from "./sync/sources.js";
|
|
12
|
+
import { CandleSeries } from "./sync/candles.js";
|
|
13
|
+
import { OrderHistory } from "./sync/orders.js";
|
|
14
|
+
import { enrichPositions } from "./sync/positions-live.js";
|
|
15
|
+
|
|
16
|
+
export interface PodTradeClientOptions {
|
|
17
|
+
restUrl: string;
|
|
18
|
+
wsUrl: string;
|
|
19
|
+
/** Node JSON-RPC HTTP endpoint — needed only for tx features (e.g. mint). */
|
|
20
|
+
rpcUrl?: string;
|
|
21
|
+
fetch?: typeof fetch;
|
|
22
|
+
WebSocket?: WebSocketCtor;
|
|
23
|
+
reconnect?: { maxDelayMs?: number; idleTimeoutMs?: number };
|
|
24
|
+
/** Periodic REST re-alignment for positions (ms). Default 60_000; 0 disables. */
|
|
25
|
+
positionResyncMs?: number;
|
|
26
|
+
/** Periodic REST re-poll of market 24h stats (ms). Default 30_000; 0 disables. */
|
|
27
|
+
marketResyncMs?: number;
|
|
28
|
+
/**
|
|
29
|
+
* Optional persistence for the static markets list (localStorage-backed in a
|
|
30
|
+
* browser), so market-keyed UI mounts instantly on repeat visits. Key it per
|
|
31
|
+
* backend environment — the list differs between them.
|
|
32
|
+
*/
|
|
33
|
+
marketsCache?: MarketsCache;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface Destroyable { destroy(): void }
|
|
37
|
+
|
|
38
|
+
export class PodTradeClient {
|
|
39
|
+
readonly rest: PodRestClient;
|
|
40
|
+
readonly ws: PodWsClient;
|
|
41
|
+
private readonly ctx: SyncContext;
|
|
42
|
+
private readonly cache = new Map<string, Destroyable & object>();
|
|
43
|
+
private readonly rpcUrl?: string;
|
|
44
|
+
private readonly fetchFn?: typeof fetch;
|
|
45
|
+
|
|
46
|
+
constructor(opts: PodTradeClientOptions) {
|
|
47
|
+
this.rpcUrl = opts.rpcUrl;
|
|
48
|
+
this.fetchFn = opts.fetch;
|
|
49
|
+
this.rest = new PodRestClient({ restUrl: opts.restUrl, fetch: opts.fetch });
|
|
50
|
+
this.ws = new PodWsClient({
|
|
51
|
+
wsUrl: opts.wsUrl,
|
|
52
|
+
WebSocket: opts.WebSocket,
|
|
53
|
+
maxDelayMs: opts.reconnect?.maxDelayMs,
|
|
54
|
+
idleTimeoutMs: opts.reconnect?.idleTimeoutMs,
|
|
55
|
+
});
|
|
56
|
+
this.ctx = {
|
|
57
|
+
rest: this.rest,
|
|
58
|
+
ws: this.ws,
|
|
59
|
+
positionResyncMs: opts.positionResyncMs ?? 60_000,
|
|
60
|
+
marketResyncMs: opts.marketResyncMs ?? 30_000,
|
|
61
|
+
marketsCache: opts.marketsCache,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
connect(): void { this.ws.connect(); }
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Re-seed an account's cached resources (positions, balances, triggers —
|
|
69
|
+
* and anything derived from them). For out-of-band mutations the streams
|
|
70
|
+
* don't announce (e.g. a mint, or a trigger update — `pod_triggers` only
|
|
71
|
+
* pushes on ticks with order activity); stream-covered state needs no
|
|
72
|
+
* manual refresh. Address-case-insensitive: resources may have been created
|
|
73
|
+
* under a checksummed address while callers pass the wire's lowercase form.
|
|
74
|
+
*/
|
|
75
|
+
refresh(account: Address): void {
|
|
76
|
+
const want = new Set(["positions", "balances", "triggers"].map((k) => `${k}:${account.toLowerCase()}`));
|
|
77
|
+
for (const [key, r] of this.cache) {
|
|
78
|
+
if (want.has(key.toLowerCase()) && r instanceof BaseResource) r.refresh();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Faucet mint (test environments where the node sets `minting_allowed`):
|
|
84
|
+
* credit `to` — by default straight into the CLOB — wait for the receipt,
|
|
85
|
+
* then refresh the account's cached resources, since a mint emits no account
|
|
86
|
+
* tick and would otherwise only appear on the next periodic resync. Mint txs
|
|
87
|
+
* are gas-exempt and signer-irrelevant (signed by a one-shot throwaway key
|
|
88
|
+
* inside the SDK), so no wallet or delegation is needed. Requires `rpcUrl`
|
|
89
|
+
* in the client options; the /write entry is loaded on demand.
|
|
90
|
+
*/
|
|
91
|
+
async mint(
|
|
92
|
+
to: Address,
|
|
93
|
+
tokens: Array<{ token?: Address; amount: bigint }>,
|
|
94
|
+
opts?: { depositToClob?: boolean; onSubmitted?: (hash: string) => void },
|
|
95
|
+
): Promise<{ transactionHash: string }> {
|
|
96
|
+
if (!this.rpcUrl) throw new Error("PodTradeClient.mint requires `rpcUrl` in the client options");
|
|
97
|
+
const { mint } = await import("./write/index.js");
|
|
98
|
+
const receipt = await mint({
|
|
99
|
+
rpcUrl: this.rpcUrl,
|
|
100
|
+
to,
|
|
101
|
+
tokens,
|
|
102
|
+
depositToClob: opts?.depositToClob,
|
|
103
|
+
onSubmitted: opts?.onSubmitted,
|
|
104
|
+
fetch: this.fetchFn,
|
|
105
|
+
});
|
|
106
|
+
this.refresh(to);
|
|
107
|
+
return receipt;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
close(): void {
|
|
111
|
+
for (const r of this.cache.values()) r.destroy();
|
|
112
|
+
this.cache.clear();
|
|
113
|
+
this.ws.close();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private memo<T extends Destroyable & object>(key: string, make: () => T): T {
|
|
117
|
+
const hit = this.cache.get(key);
|
|
118
|
+
if (hit) return hit as T;
|
|
119
|
+
const made = make();
|
|
120
|
+
this.cache.set(key, made);
|
|
121
|
+
return made;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
get status(): Resource<Status> {
|
|
125
|
+
return this.memo("status", () => new BaseResource(statusSource(this.ctx)));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
get markets(): Resource<Market[]> {
|
|
129
|
+
return this.memo("markets", () => new BaseResource(marketsSource(this.ctx)));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
market(id: MarketId): Resource<Market> {
|
|
133
|
+
return this.memo(`market:${id}`, () =>
|
|
134
|
+
derivedResource(this.markets, (list) => list?.find((m) => m.id === id)) as BaseResource<Market>,
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
orderbook(id: MarketId, opts?: { depth?: number }): Resource<import("./types/public.js").Orderbook> {
|
|
139
|
+
const depth = opts?.depth;
|
|
140
|
+
return this.memo(`orderbook:${id}:${depth ?? ""}`, () =>
|
|
141
|
+
new BaseResource(orderbookSource(this.ctx, id, depth)),
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
positions(account: Address): Resource<PositionsSnapshot> {
|
|
146
|
+
return this.memo(`positions:${account}`, () =>
|
|
147
|
+
new BaseResource(positionsSource(this.ctx, account)),
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Positions with mark-driven fields (uPnL, notional, equity, account value,
|
|
153
|
+
* withdrawable) kept live off the market stream between snapshots, and
|
|
154
|
+
* re-aligned to the backend on every snapshot / periodic REST resync.
|
|
155
|
+
*/
|
|
156
|
+
livePositions(account: Address): Resource<PositionsSnapshot> {
|
|
157
|
+
return this.memo(`livePositions:${account}`, () => {
|
|
158
|
+
const positions = this.positions(account);
|
|
159
|
+
const markets = this.markets;
|
|
160
|
+
return combineResources([positions, markets], () => {
|
|
161
|
+
const snap = positions.get();
|
|
162
|
+
if (!snap) return undefined;
|
|
163
|
+
return enrichPositions(snap, markets.get() ?? []);
|
|
164
|
+
}) as BaseResource<PositionsSnapshot>;
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
triggers(account: Address, _query?: TriggersQuery): Resource<Trigger[]> {
|
|
169
|
+
return this.memo(`triggers:${account}`, () =>
|
|
170
|
+
new BaseResource(triggersSource(this.ctx, account)),
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Live spot holdings + native cash. */
|
|
175
|
+
balances(account: Address): Resource<Balances> {
|
|
176
|
+
return this.memo(`balances:${account}`, () =>
|
|
177
|
+
new BaseResource(balancesSource(this.ctx, account)),
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Leaderboard (ranked accounts by net PnL). One-shot REST; paginate via
|
|
182
|
+
* `{ limit, offset }`. Not a stream — call again to refresh. */
|
|
183
|
+
leaderboard(query?: LeaderboardQuery): Promise<LeaderboardPage> {
|
|
184
|
+
return this.rest.leaderboard(query);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Explorer view of a transaction by hash. One-shot. */
|
|
188
|
+
transaction(hash: string): Promise<TxExplorer> {
|
|
189
|
+
return this.rest.transaction(hash);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
backstopTransfers(account: Address): Resource<BackstopTransfer[]> {
|
|
193
|
+
return this.memo(`backstop:${account}`, () =>
|
|
194
|
+
new BaseResource<BackstopTransfer[]>((h) => {
|
|
195
|
+
let alive = true;
|
|
196
|
+
this.rest.backstopTransfers(account)
|
|
197
|
+
.then((p) => { if (alive) h.set(p.transfers); })
|
|
198
|
+
.catch((e) => h.fail(e));
|
|
199
|
+
return () => { alive = false; };
|
|
200
|
+
}),
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
candles(id: MarketId, resolution: Resolution, range?: TimeRange): CandleSeries {
|
|
205
|
+
const series = this.memo(`candles:${id}:${resolution}`, () =>
|
|
206
|
+
new CandleSeries(this.ctx, id, resolution, range),
|
|
207
|
+
);
|
|
208
|
+
if (range) series.setWindow(range);
|
|
209
|
+
return series;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
orders(account: Address, query?: OrdersQuery): OrderHistory {
|
|
213
|
+
const key = `orders:${account}:${query ? JSON.stringify(query) : ""}`;
|
|
214
|
+
// WS stream orders identify their market by token pair; resolve it against
|
|
215
|
+
// the markets list (unambiguous: base tokens are unique per market — if a
|
|
216
|
+
// pair ever matched several markets we leave orderbookId unset rather than
|
|
217
|
+
// guess). Reads the markets snapshot, so it adds no extra subscription.
|
|
218
|
+
const resolveOrderbookId = (pair: { base: Address; quote: Address }) => {
|
|
219
|
+
const base = pair.base.toLowerCase();
|
|
220
|
+
const quote = pair.quote.toLowerCase();
|
|
221
|
+
const matches = this.markets.get()?.filter((m) =>
|
|
222
|
+
m.base?.address.toLowerCase() === base && m.quote?.address.toLowerCase() === quote,
|
|
223
|
+
);
|
|
224
|
+
const only = matches && matches.length === 1 ? matches[0] : undefined;
|
|
225
|
+
return only?.id;
|
|
226
|
+
};
|
|
227
|
+
return this.memo(key, () => new OrderHistory(this.ctx, account, query, resolveOrderbookId));
|
|
228
|
+
}
|
|
229
|
+
}
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
// Wire -> public decoders. The single place hex/decimal-string/microsecond
|
|
2
|
+
// representations are normalized into bigint + millisecond numbers.
|
|
3
|
+
|
|
4
|
+
import type {
|
|
5
|
+
Bar, BackstopTransfer, Balances, LeaderboardEntry, LeaderboardPage, Market, Order,
|
|
6
|
+
Orderbook, PartialFill, PerpPosition, Position, PositionsSnapshot, SpotHolding,
|
|
7
|
+
SpotPosition, Status, Trigger, MarketType, OrderDirection, OrderKind, OrderStatus, TriggerType,
|
|
8
|
+
} from "../types/public.js";
|
|
9
|
+
import type {
|
|
10
|
+
WireBackstopTransfer, WireBalances, WireCandle, WireLeaderboard, WireMarketDynamics,
|
|
11
|
+
WireMarketStatic, WireOrder, WireOrderbook, WirePartialFill, WirePerpPosition, WirePosition,
|
|
12
|
+
WirePositionsSnapshot, WireSpotHolding, WireSpotPosition, WireStatus, WireTrigger,
|
|
13
|
+
} from "../types/wire.js";
|
|
14
|
+
import { dec, decOpt, toNumber, usToMs, usToMsOpt } from "./units.js";
|
|
15
|
+
|
|
16
|
+
export function decodeStatus(w: WireStatus): Status {
|
|
17
|
+
return { solutionNow: usToMs(w.solution_now) };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Static market identity. Dynamics are merged in later by the market store. */
|
|
21
|
+
export function decodeMarketStatic(w: WireMarketStatic): Market {
|
|
22
|
+
return {
|
|
23
|
+
id: w.id,
|
|
24
|
+
name: w.name,
|
|
25
|
+
type: w.market_type,
|
|
26
|
+
base: { address: w.base_token_address, symbol: w.base_token_symbol, name: w.base_token_name },
|
|
27
|
+
quote: { address: w.quote_token_address, symbol: w.quote_token_symbol, name: w.quote_token_name },
|
|
28
|
+
tickPrecision: dec(w.tick_precision),
|
|
29
|
+
lotSize: dec(w.lot_size),
|
|
30
|
+
maxLeverage: w.max_leverage,
|
|
31
|
+
fundingWindowUs: w.funding_window_us,
|
|
32
|
+
makerFee: dec(w.maker_fee),
|
|
33
|
+
takerFee: dec(w.taker_fee),
|
|
34
|
+
auctionIntervalMs: usToMs(w.auction_interval_us),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Dynamics fields (clearing/24h/perp) as a partial Market patch. */
|
|
39
|
+
export function decodeMarketDynamics(w: WireMarketDynamics): Partial<Market> & { id: string } {
|
|
40
|
+
return {
|
|
41
|
+
id: w.orderbook_id,
|
|
42
|
+
lastClearingPrice: dec(w.last_clearing_price),
|
|
43
|
+
volume24h: dec(w.volume_24h),
|
|
44
|
+
high24h: dec(w.high_24h),
|
|
45
|
+
low24h: dec(w.low_24h),
|
|
46
|
+
priceChange24hBps: w.price_change_24h,
|
|
47
|
+
oraclePrice: decOpt(w.oracle_price),
|
|
48
|
+
markPrice: decOpt(w.mark_price),
|
|
49
|
+
fundingRate: decOpt(w.funding_rate),
|
|
50
|
+
fundingIndex: decOpt(w.funding_index),
|
|
51
|
+
fundingLastUpdatedMs: usToMsOpt(w.funding_last_updated_us),
|
|
52
|
+
openInterest: decOpt(w.open_interest),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function decodeCandle(w: WireCandle): Bar {
|
|
57
|
+
return {
|
|
58
|
+
time: usToMs(w.timestamp),
|
|
59
|
+
open: dec(w.open),
|
|
60
|
+
high: dec(w.high),
|
|
61
|
+
low: dec(w.low),
|
|
62
|
+
close: dec(w.close),
|
|
63
|
+
volume: dec(w.volume),
|
|
64
|
+
quoteVolume: dec(w.quote_volume),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function decodePartialFill(w: WirePartialFill): PartialFill {
|
|
69
|
+
return {
|
|
70
|
+
base: dec(w.base_amount),
|
|
71
|
+
quote: dec(w.quote_amount),
|
|
72
|
+
price: dec(w.price),
|
|
73
|
+
time: usToMs(w.timestamp),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function decodeOrder(w: WireOrder): Order {
|
|
78
|
+
const initialSize = dec(w.initial_size);
|
|
79
|
+
return {
|
|
80
|
+
id: w.order_id,
|
|
81
|
+
txHash: w.tx_hash,
|
|
82
|
+
orderbookId: w.orderbook_id,
|
|
83
|
+
marketType: w.market_type as MarketType | undefined,
|
|
84
|
+
pair: w.pair ? { base: w.pair.base, quote: w.pair.quote } : undefined,
|
|
85
|
+
// WS raw orders have no `side` field — derive it from the signed size.
|
|
86
|
+
side: w.side ?? (initialSize < 0n ? "sell" : "buy"),
|
|
87
|
+
orderType: w.order_type,
|
|
88
|
+
status: w.status as OrderStatus,
|
|
89
|
+
kind: w.kind as OrderKind,
|
|
90
|
+
nonce: w.nonce,
|
|
91
|
+
bidder: w.bidder,
|
|
92
|
+
price: dec(w.price),
|
|
93
|
+
initialSize,
|
|
94
|
+
filledBase: dec(w.filled_base_amount),
|
|
95
|
+
filledQuote: dec(w.filled_quote_amount),
|
|
96
|
+
fee: dec(w.fee),
|
|
97
|
+
effectivePrice: decOpt(w.effective_price),
|
|
98
|
+
deadlineMs: usToMs(w.deadline),
|
|
99
|
+
endMs: usToMs(w.end),
|
|
100
|
+
includedMs: usToMsOpt(w.included_batch),
|
|
101
|
+
fills: (w.fills ?? []).map(decodePartialFill),
|
|
102
|
+
reduceOnly: w.reduce_only,
|
|
103
|
+
ioc: w.ioc,
|
|
104
|
+
direction: w.direction as OrderDirection | undefined,
|
|
105
|
+
triggerType: (w.trigger_type ?? undefined) as TriggerType | undefined,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function decodeOrderbook(w: WireOrderbook): Orderbook {
|
|
110
|
+
const id = (w.orderbook_id ?? w.clob_id)!;
|
|
111
|
+
// Levels best-first; `total` is the cumulative size from the best price to here.
|
|
112
|
+
const levels = (entries: [string, { volume: string }][], ascending: boolean) => {
|
|
113
|
+
const sorted = entries
|
|
114
|
+
.map(([price, t]) => ({ price: dec(price), volume: dec(t.volume) }))
|
|
115
|
+
.sort((a, b) => (ascending ? (a.price < b.price ? -1 : a.price > b.price ? 1 : 0)
|
|
116
|
+
: (b.price < a.price ? -1 : b.price > a.price ? 1 : 0)));
|
|
117
|
+
let cum = 0n;
|
|
118
|
+
const withTotal = sorted.map((l) => { cum += l.volume; return { price: l.price, volume: l.volume, total: cum }; });
|
|
119
|
+
// `depth` = cumulative size as a 0..1 fraction of this side's total (the
|
|
120
|
+
// deepest level → 1). Ready to use as a depth-bar width; no app-side scaling.
|
|
121
|
+
const sideMax = cum;
|
|
122
|
+
return withTotal.map((l) => ({ ...l, depth: sideMax > 0n ? Number(l.total) / Number(sideMax) : 0 }));
|
|
123
|
+
};
|
|
124
|
+
const bids = levels(Object.entries(w.buys), false);
|
|
125
|
+
const asks = levels(Object.entries(w.sells), true);
|
|
126
|
+
const bestBid = bids[0]?.price;
|
|
127
|
+
const bestAsk = asks[0]?.price;
|
|
128
|
+
const hasBoth = bestBid !== undefined && bestAsk !== undefined;
|
|
129
|
+
const mid = hasBoth ? (bestBid + bestAsk) / 2n : undefined;
|
|
130
|
+
const spread = hasBoth ? bestAsk - bestBid : undefined;
|
|
131
|
+
const spreadPct = mid && mid > 0n && spread !== undefined ? (Number(spread) / Number(mid)) * 100 : undefined;
|
|
132
|
+
return {
|
|
133
|
+
id,
|
|
134
|
+
timeMs: usToMs(w.timestamp),
|
|
135
|
+
clearingPrice: decOpt(w.clearing_price),
|
|
136
|
+
bids,
|
|
137
|
+
asks,
|
|
138
|
+
mid,
|
|
139
|
+
spread,
|
|
140
|
+
spreadPct,
|
|
141
|
+
bidCount: w.buys_count,
|
|
142
|
+
askCount: w.sells_count,
|
|
143
|
+
groupingPrecision: dec(w.grouping_precision),
|
|
144
|
+
oraclePrice: decOpt(w.oracle_price),
|
|
145
|
+
fundingRate: decOpt(w.funding_rate),
|
|
146
|
+
fundingIndex: decOpt(w.funding_index),
|
|
147
|
+
fundingLastUpdatedMs: usToMsOpt(w.funding_last_updated),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function decodeSpotPosition(w: WireSpotPosition): SpotPosition {
|
|
152
|
+
return {
|
|
153
|
+
kind: "spot",
|
|
154
|
+
orderbookId: w.orderbook_id,
|
|
155
|
+
token: w.token,
|
|
156
|
+
balance: dec(w.balance),
|
|
157
|
+
freeBalance: dec(w.free_balance),
|
|
158
|
+
lockedBalance: dec(w.locked_balance),
|
|
159
|
+
costBasis: dec(w.cost_basis),
|
|
160
|
+
markPrice: dec(w.mark_price),
|
|
161
|
+
unrealizedPnl: dec(w.unrealized_pnl),
|
|
162
|
+
realizedPnl: dec(w.realized_pnl),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function decodePerpPosition(w: WirePerpPosition): PerpPosition {
|
|
167
|
+
return {
|
|
168
|
+
kind: "perp",
|
|
169
|
+
orderbookId: w.orderbook_id,
|
|
170
|
+
side: w.side,
|
|
171
|
+
size: dec(w.size),
|
|
172
|
+
notional: dec(w.notional),
|
|
173
|
+
entryPrice: dec(w.entry_price),
|
|
174
|
+
markPrice: dec(w.mark_price),
|
|
175
|
+
margin: dec(w.margin),
|
|
176
|
+
leverage: toNumber(dec(w.leverage)), // wire is 1e18-scaled, not a plain int
|
|
177
|
+
fundingAccrued: dec(w.funding_accrued),
|
|
178
|
+
entryFunding: dec(w.entry_funding),
|
|
179
|
+
liquidationPrice: dec(w.liquidation_price),
|
|
180
|
+
unrealizedPnl: dec(w.unrealized_pnl),
|
|
181
|
+
realizedPnl: dec(w.realized_pnl),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function decodePosition(w: WirePosition): Position {
|
|
186
|
+
return w.kind === "perp" ? decodePerpPosition(w) : decodeSpotPosition(w);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function decodePositions(w: WirePositionsSnapshot): PositionsSnapshot {
|
|
190
|
+
return {
|
|
191
|
+
positions: w.positions.map(decodePosition),
|
|
192
|
+
totalUnrealizedPnl: dec(w.total_unrealized_pnl),
|
|
193
|
+
totalRealizedPnl: dec(w.total_realized_pnl),
|
|
194
|
+
perpsEquity: dec(w.perps_equity),
|
|
195
|
+
accountValue: dec(w.account_value),
|
|
196
|
+
cash: dec(w.cash),
|
|
197
|
+
withdrawableCash: dec(w.withdrawable_cash),
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function decodeSpotHolding(w: WireSpotHolding): SpotHolding {
|
|
202
|
+
return {
|
|
203
|
+
orderbookId: w.orderbook_id,
|
|
204
|
+
baseSymbol: w.base_symbol,
|
|
205
|
+
quoteSymbol: w.quote_symbol,
|
|
206
|
+
balance: dec(w.balance),
|
|
207
|
+
freeBalance: dec(w.free_balance),
|
|
208
|
+
lockedBalance: dec(w.locked_balance),
|
|
209
|
+
costBasis: dec(w.cost_basis),
|
|
210
|
+
markPrice: dec(w.mark_price),
|
|
211
|
+
unrealizedPnl: dec(w.unrealized_pnl),
|
|
212
|
+
realizedPnl: dec(w.realized_pnl),
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function decodeBalances(w: WireBalances): Balances {
|
|
217
|
+
return {
|
|
218
|
+
holdings: w.balances.map(decodeSpotHolding),
|
|
219
|
+
cash: dec(w.cash),
|
|
220
|
+
withdrawableCash: dec(w.withdrawable_cash),
|
|
221
|
+
netDeposits: dec(w.net_deposits),
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Decode a ranked-accounts page (REST `/clob/leaderboard`). `offset` makes the
|
|
226
|
+
* ranks 1-based over the full ordering. PnL = unrealized + realized (the rank
|
|
227
|
+
* key); `%` is suppressed to 0 when the basis (accountValue − unrealized) is dust. */
|
|
228
|
+
export function decodeLeaderboard(w: WireLeaderboard, offset = 0): LeaderboardPage {
|
|
229
|
+
const entries: LeaderboardEntry[] = (w.ranked ?? []).map((r, i) => {
|
|
230
|
+
const unrealizedPnl = dec(r.positions.total_unrealized_pnl);
|
|
231
|
+
const realizedPnl = dec(r.positions.total_realized_pnl);
|
|
232
|
+
const accountValue = dec(r.positions.account_value);
|
|
233
|
+
const pnl = unrealizedPnl + realizedPnl;
|
|
234
|
+
const basis = accountValue - unrealizedPnl;
|
|
235
|
+
const absAv = accountValue < 0n ? -accountValue : accountValue;
|
|
236
|
+
const safe = basis > 0n && absAv > 0n && basis * 1000n >= absAv * 5n; // basis ≥ 0.5% of |av|
|
|
237
|
+
return {
|
|
238
|
+
rank: offset + i + 1,
|
|
239
|
+
account: r.account,
|
|
240
|
+
accountValue,
|
|
241
|
+
unrealizedPnl,
|
|
242
|
+
realizedPnl,
|
|
243
|
+
pnl,
|
|
244
|
+
pnlPercent: safe ? (Number(pnl) / Number(basis)) * 100 : 0,
|
|
245
|
+
};
|
|
246
|
+
});
|
|
247
|
+
return { entries, total: w.total ?? 0 };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function decodeTrigger(w: WireTrigger): Trigger {
|
|
251
|
+
return {
|
|
252
|
+
orderbookId: w.orderbook_id,
|
|
253
|
+
orderId: w.order_id,
|
|
254
|
+
txHash: w.tx_hash,
|
|
255
|
+
bidder: w.bidder,
|
|
256
|
+
nonce: w.nonce,
|
|
257
|
+
size: dec(w.size),
|
|
258
|
+
limitPrice: dec(w.limit_price),
|
|
259
|
+
triggerPrice: dec(w.trigger_price),
|
|
260
|
+
triggerType: w.trigger_type as TriggerType,
|
|
261
|
+
reduceOnly: w.reduce_only,
|
|
262
|
+
ioc: w.ioc,
|
|
263
|
+
deadlineMs: usToMs(w.deadline),
|
|
264
|
+
endMs: usToMs(w.end),
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function decodeBackstopTransfer(w: WireBackstopTransfer): BackstopTransfer {
|
|
269
|
+
return {
|
|
270
|
+
orderbookId: w.orderbook_id,
|
|
271
|
+
size: dec(w.size),
|
|
272
|
+
cash: dec(w.cash),
|
|
273
|
+
markPrice: dec(w.mark_price),
|
|
274
|
+
equity: dec(w.equity),
|
|
275
|
+
time: usToMs(w.timestamp_us),
|
|
276
|
+
};
|
|
277
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Fixed-point (1e18) integer ops matching pod's trading/src/decimal.rs, shared
|
|
2
|
+
// by the account-math replications so they all round identically.
|
|
3
|
+
|
|
4
|
+
import { WAD } from "./units.js";
|
|
5
|
+
|
|
6
|
+
const absB = (x: bigint) => (x < 0n ? -x : x);
|
|
7
|
+
|
|
8
|
+
/** Decimal `*`: (a*b)/1e18 truncated toward zero. */
|
|
9
|
+
export function mul(a: bigint, b: bigint): bigint {
|
|
10
|
+
const n = a * b;
|
|
11
|
+
return n >= 0n ? n / WAD : -((-n) / WAD);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Decimal `/`: (a*1e18)/b truncated toward zero. */
|
|
15
|
+
export function div(a: bigint, b: bigint): bigint {
|
|
16
|
+
if (b === 0n) return 0n;
|
|
17
|
+
const n = a * WAD;
|
|
18
|
+
return n >= 0n ? n / b : -((-n) / b);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Decimal `mul_floor`: (a*b)/1e18 rounded toward -infinity. */
|
|
22
|
+
export function mulFloor(a: bigint, b: bigint): bigint {
|
|
23
|
+
const n = a * b;
|
|
24
|
+
return n >= 0n ? n / WAD : -((-n + WAD - 1n) / WAD);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Decimal `mul_div_ceil`: (a*b)/d; positive magnitudes round up, negative truncate. */
|
|
28
|
+
export function mulDivCeil(a: bigint, b: bigint, d: bigint): bigint {
|
|
29
|
+
if (d <= 0n) return 0n;
|
|
30
|
+
const prod = absB(a) * absB(b);
|
|
31
|
+
const q = prod / d;
|
|
32
|
+
const r = prod % d;
|
|
33
|
+
const negative = a < 0n !== b < 0n; // d is positive
|
|
34
|
+
const mag = !negative && r !== 0n ? q + 1n : q;
|
|
35
|
+
return negative ? -mag : mag;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** initial_margin = UDecimal::ONE / max_leverage = floor(1e18 / L). */
|
|
39
|
+
export function imRate(maxLeverage: number): bigint {
|
|
40
|
+
return maxLeverage > 0 ? WAD / BigInt(maxLeverage) : 0n;
|
|
41
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Resolution } from "../types/public.js";
|
|
2
|
+
|
|
3
|
+
/** Bucket width per resolution, in seconds. 1M is calendar-variable; see pages. */
|
|
4
|
+
export const RESOLUTION_SECONDS: Record<Resolution, number> = {
|
|
5
|
+
"1m": 60,
|
|
6
|
+
"5m": 300,
|
|
7
|
+
"15m": 900,
|
|
8
|
+
"30m": 1_800,
|
|
9
|
+
"1h": 3_600,
|
|
10
|
+
"4h": 14_400,
|
|
11
|
+
"1d": 86_400,
|
|
12
|
+
"1W": 604_800,
|
|
13
|
+
"1M": 2_592_000, // nominal 30d; only used as a hint, pages use calendar months
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Canonical page size K (number of buckets per cached page), chosen as the
|
|
18
|
+
* largest value <= 500 (the server's hard cap) for the resolution. Pages are
|
|
19
|
+
* epoch-anchored (pageIndex = floor(bucketIndex / K)) so every client computes
|
|
20
|
+
* identical, settled-aligned page boundaries -> high cache-hit rate + the
|
|
21
|
+
* server flags fully-past pages `immutable`.
|
|
22
|
+
*/
|
|
23
|
+
export const RESOLUTION_PAGE_BUCKETS: Record<Resolution, number> = {
|
|
24
|
+
"1m": 360, // 6h
|
|
25
|
+
"5m": 288, // 1 day
|
|
26
|
+
"15m": 96, // 1 day
|
|
27
|
+
"30m": 336, // 1 week
|
|
28
|
+
"1h": 168, // 1 week
|
|
29
|
+
"4h": 180, // ~30 days
|
|
30
|
+
"1d": 365, // ~1 year
|
|
31
|
+
"1W": 260, // ~5 years
|
|
32
|
+
"1M": 120, // ~decade (calendar-month buckets)
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export const RESOLUTIONS = Object.keys(RESOLUTION_SECONDS) as Resolution[];
|
|
36
|
+
|
|
37
|
+
export function isResolution(x: string): x is Resolution {
|
|
38
|
+
return x in RESOLUTION_SECONDS;
|
|
39
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Unit conversions at the SDK boundary. Wire numerics are 1e18-scaled decimal
|
|
2
|
+
// strings; wire timestamps are microseconds. Public surface uses `bigint`
|
|
3
|
+
// (1e18-scaled) and millisecond `number` timestamps.
|
|
4
|
+
|
|
5
|
+
export const WAD = 1_000_000_000_000_000_000n; // 1e18
|
|
6
|
+
export const WAD_DECIMALS = 18;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Parse a wire numeric (possibly null) into a 1e18-scaled bigint. Handles both
|
|
10
|
+
* decimal (`"50000…"`, markets/stats) and hex (`"0x0"`, candles/orderbook)
|
|
11
|
+
* encodings, signed values (`"-5"` / `"-0x5"`), and tolerates a fraction.
|
|
12
|
+
*/
|
|
13
|
+
export function dec(value: string | null | undefined): bigint {
|
|
14
|
+
if (value === null || value === undefined || value === "") return 0n;
|
|
15
|
+
const neg = value[0] === "-";
|
|
16
|
+
const body = neg ? value.slice(1) : value;
|
|
17
|
+
const dot = body.indexOf(".");
|
|
18
|
+
const n = BigInt(dot === -1 ? body : body.slice(0, dot));
|
|
19
|
+
return neg ? -n : n;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Parse an optional wire decimal; returns undefined when absent/null. */
|
|
23
|
+
export function decOpt(value: string | null | undefined): bigint | undefined {
|
|
24
|
+
return value === null || value === undefined ? undefined : dec(value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Microseconds (number) -> milliseconds (number). */
|
|
28
|
+
export function usToMs(us: number | string): number {
|
|
29
|
+
const n = typeof us === "string" ? Number(us) : us;
|
|
30
|
+
return Math.trunc(n / 1000);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function usToMsOpt(us: number | string | null | undefined): number | undefined {
|
|
34
|
+
return us === null || us === undefined ? undefined : usToMs(us);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Milliseconds -> microseconds (for request params that take micros). */
|
|
38
|
+
export function msToUs(ms: number): number {
|
|
39
|
+
return ms * 1000;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Milliseconds -> unix seconds (REST candle/orders/stats query params). */
|
|
43
|
+
export function msToSecs(ms: number): number {
|
|
44
|
+
return Math.trunc(ms / 1000);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function secsToMs(secs: number): number {
|
|
48
|
+
return secs * 1000;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// --- display helpers (lossy, for UI) ---
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Format a 1e18-scaled bigint as a decimal string with up to `precision` dp.
|
|
55
|
+
* By default trailing zeros are trimmed; pass `{ trim: false }` for fixed
|
|
56
|
+
* decimals (stable column widths in tables).
|
|
57
|
+
*/
|
|
58
|
+
export function formatAmount(
|
|
59
|
+
value: bigint,
|
|
60
|
+
decimals: number = WAD_DECIMALS,
|
|
61
|
+
precision?: number,
|
|
62
|
+
opts?: { trim?: boolean },
|
|
63
|
+
): string {
|
|
64
|
+
const trim = opts?.trim ?? true;
|
|
65
|
+
const scale = 10n ** BigInt(decimals);
|
|
66
|
+
const neg = value < 0n;
|
|
67
|
+
const abs = neg ? -value : value;
|
|
68
|
+
const whole = abs / scale;
|
|
69
|
+
let frac = (abs % scale).toString().padStart(decimals, "0");
|
|
70
|
+
if (precision !== undefined) frac = frac.slice(0, precision);
|
|
71
|
+
if (trim) frac = frac.replace(/0+$/, "");
|
|
72
|
+
const sign = neg ? "-" : "";
|
|
73
|
+
return frac.length ? `${sign}${whole}.${frac}` : `${sign}${whole}`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Decimals implied by a market's 1e18-scaled tick (e.g. tick 1e16 → 2 dp). */
|
|
77
|
+
export function decimalsForTick(tick: bigint): number {
|
|
78
|
+
if (tick <= 0n) return 2;
|
|
79
|
+
return Math.max(0, Math.min(8, WAD_DECIMALS + 1 - tick.toString().length));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Format a price with fixed decimals derived from the market's tick precision. */
|
|
83
|
+
export function formatPrice(value: bigint, tickPrecision: bigint): string {
|
|
84
|
+
return formatAmount(value, WAD_DECIMALS, decimalsForTick(tickPrecision), { trim: false });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Convert a 1e18-scaled bigint to a JS number (lossy; charts/PnL display). */
|
|
88
|
+
export function toNumber(value: bigint, decimals: number = WAD_DECIMALS): number {
|
|
89
|
+
return Number(value) / 10 ** decimals;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Parse a human decimal string into a 1e18-scaled bigint. */
|
|
93
|
+
export function parseAmount(value: string, decimals: number = WAD_DECIMALS): bigint {
|
|
94
|
+
const neg = value.trim().startsWith("-");
|
|
95
|
+
const clean = neg ? value.trim().slice(1) : value.trim();
|
|
96
|
+
const [whole = "0", frac = ""] = clean.split(".");
|
|
97
|
+
const fracPadded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
98
|
+
const scaled = BigInt(whole) * 10n ** BigInt(decimals) + BigInt(fracPadded || "0");
|
|
99
|
+
return neg ? -scaled : scaled;
|
|
100
|
+
}
|