@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.
Files changed (102) hide show
  1. package/README.md +113 -0
  2. package/dist/client.d.ts +93 -0
  3. package/dist/client.d.ts.map +1 -0
  4. package/dist/client.js +168 -0
  5. package/dist/client.js.map +1 -0
  6. package/dist/codec/decode.d.ts +22 -0
  7. package/dist/codec/decode.d.ts.map +1 -0
  8. package/dist/codec/decode.js +251 -0
  9. package/dist/codec/decode.js.map +1 -0
  10. package/dist/codec/fixed.d.ts +11 -0
  11. package/dist/codec/fixed.d.ts.map +1 -0
  12. package/dist/codec/fixed.js +37 -0
  13. package/dist/codec/fixed.js.map +1 -0
  14. package/dist/codec/resolution.d.ts +14 -0
  15. package/dist/codec/resolution.d.ts.map +1 -0
  16. package/dist/codec/resolution.js +35 -0
  17. package/dist/codec/resolution.js.map +1 -0
  18. package/dist/codec/units.d.ts +35 -0
  19. package/dist/codec/units.d.ts.map +1 -0
  20. package/dist/codec/units.js +86 -0
  21. package/dist/codec/units.js.map +1 -0
  22. package/dist/datafeed.d.ts +4 -0
  23. package/dist/datafeed.d.ts.map +1 -0
  24. package/dist/datafeed.js +73 -0
  25. package/dist/datafeed.js.map +1 -0
  26. package/dist/index.d.ts +20 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +19 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/stores/resource.d.ts +50 -0
  31. package/dist/stores/resource.d.ts.map +1 -0
  32. package/dist/stores/resource.js +154 -0
  33. package/dist/stores/resource.js.map +1 -0
  34. package/dist/sync/account-metrics.d.ts +26 -0
  35. package/dist/sync/account-metrics.d.ts.map +1 -0
  36. package/dist/sync/account-metrics.js +41 -0
  37. package/dist/sync/account-metrics.js.map +1 -0
  38. package/dist/sync/candles.d.ts +68 -0
  39. package/dist/sync/candles.d.ts.map +1 -0
  40. package/dist/sync/candles.js +318 -0
  41. package/dist/sync/candles.js.map +1 -0
  42. package/dist/sync/order-preview.d.ts +74 -0
  43. package/dist/sync/order-preview.d.ts.map +1 -0
  44. package/dist/sync/order-preview.js +86 -0
  45. package/dist/sync/order-preview.js.map +1 -0
  46. package/dist/sync/orders.d.ts +49 -0
  47. package/dist/sync/orders.d.ts.map +1 -0
  48. package/dist/sync/orders.js +210 -0
  49. package/dist/sync/orders.js.map +1 -0
  50. package/dist/sync/positions-live.d.ts +3 -0
  51. package/dist/sync/positions-live.d.ts.map +1 -0
  52. package/dist/sync/positions-live.js +86 -0
  53. package/dist/sync/positions-live.js.map +1 -0
  54. package/dist/sync/sources.d.ts +40 -0
  55. package/dist/sync/sources.d.ts.map +1 -0
  56. package/dist/sync/sources.js +197 -0
  57. package/dist/sync/sources.js.map +1 -0
  58. package/dist/transport/rest.d.ts +83 -0
  59. package/dist/transport/rest.d.ts.map +1 -0
  60. package/dist/transport/rest.js +146 -0
  61. package/dist/transport/rest.js.map +1 -0
  62. package/dist/transport/ws.d.ts +60 -0
  63. package/dist/transport/ws.d.ts.map +1 -0
  64. package/dist/transport/ws.js +235 -0
  65. package/dist/transport/ws.js.map +1 -0
  66. package/dist/types/public.d.ts +292 -0
  67. package/dist/types/public.d.ts.map +1 -0
  68. package/dist/types/public.js +4 -0
  69. package/dist/types/public.js.map +1 -0
  70. package/dist/types/wire.d.ts +283 -0
  71. package/dist/types/wire.d.ts.map +1 -0
  72. package/dist/types/wire.js +6 -0
  73. package/dist/types/wire.js.map +1 -0
  74. package/dist/write/delegation.d.ts +54 -0
  75. package/dist/write/delegation.d.ts.map +1 -0
  76. package/dist/write/delegation.js +81 -0
  77. package/dist/write/delegation.js.map +1 -0
  78. package/dist/write/index.d.ts +261 -0
  79. package/dist/write/index.d.ts.map +1 -0
  80. package/dist/write/index.js +428 -0
  81. package/dist/write/index.js.map +1 -0
  82. package/package.json +43 -0
  83. package/src/client.ts +229 -0
  84. package/src/codec/decode.ts +277 -0
  85. package/src/codec/fixed.ts +41 -0
  86. package/src/codec/resolution.ts +39 -0
  87. package/src/codec/units.ts +100 -0
  88. package/src/datafeed.ts +94 -0
  89. package/src/index.ts +49 -0
  90. package/src/stores/resource.ts +172 -0
  91. package/src/sync/account-metrics.ts +71 -0
  92. package/src/sync/candles.ts +326 -0
  93. package/src/sync/order-preview.ts +152 -0
  94. package/src/sync/orders.ts +205 -0
  95. package/src/sync/positions-live.ts +102 -0
  96. package/src/sync/sources.ts +239 -0
  97. package/src/transport/rest.ts +213 -0
  98. package/src/transport/ws.ts +255 -0
  99. package/src/types/public.ts +335 -0
  100. package/src/types/wire.ts +301 -0
  101. package/src/write/delegation.ts +113 -0
  102. package/src/write/index.ts +642 -0
@@ -0,0 +1,255 @@
1
+ // Layer 1: one multiplexed WebSocket over the JSON-RPC `eth_subscribe` /
2
+ // `eth_subscription` / `eth_unsubscribe` protocol with `pod_*` sub-types.
3
+ // Ref-counted logical subscriptions, exponential backoff, idle-timeout
4
+ // reconnect, and automatic re-subscribe (with each sub's current `since`).
5
+
6
+ import type { Address, MarketId } from "../types/public.js";
7
+
8
+ export type Channel =
9
+ | "pod_orderbook" | "pod_orders" | "pod_candles"
10
+ | "pod_markets" | "pod_positions" | "pod_triggers";
11
+
12
+ export interface SubParams {
13
+ clobIds?: MarketId[];
14
+ account?: Address;
15
+ depth?: number;
16
+ since?: number; // micros (solution time)
17
+ }
18
+
19
+ export interface Subscription {
20
+ unsubscribe(): void;
21
+ /** Update stored params (e.g. advance `since`) used on the next (re)subscribe. */
22
+ update(params: SubParams): void;
23
+ /** Force a fresh eth_subscribe with the current params (used after `onError`). */
24
+ resubscribe(): void;
25
+ }
26
+
27
+ export type ConnectionState = "connecting" | "open" | "closed";
28
+ export type WsEvent = "open" | "close" | "reconnect" | "error";
29
+
30
+ export type WebSocketCtor = {
31
+ new (url: string): WebSocket;
32
+ };
33
+
34
+ export interface WsClientOptions {
35
+ wsUrl: string;
36
+ WebSocket?: WebSocketCtor;
37
+ maxDelayMs?: number;
38
+ idleTimeoutMs?: number;
39
+ }
40
+
41
+ interface LogicalSub {
42
+ channel: Channel;
43
+ params: SubParams;
44
+ onMessage: (result: unknown) => void;
45
+ onError?: (err: unknown) => void; // eth_subscribe rejected (e.g. `since` too old)
46
+ subId?: string; // server-assigned, when active
47
+ }
48
+
49
+ let nextReqId = 1;
50
+
51
+ export class PodWsClient {
52
+ private readonly url: string;
53
+ private readonly WS: WebSocketCtor;
54
+ private readonly maxDelayMs: number;
55
+ private readonly idleTimeoutMs: number;
56
+
57
+ private ws?: WebSocket;
58
+ private _state: ConnectionState = "closed";
59
+ private attempts = 0;
60
+ private reconnectTimer?: ReturnType<typeof setTimeout>;
61
+ private idleTimer?: ReturnType<typeof setTimeout>;
62
+ private wantOpen = false;
63
+
64
+ private readonly subs = new Set<LogicalSub>();
65
+ private readonly bySubId = new Map<string, LogicalSub>();
66
+ private readonly pending = new Map<number, (result: unknown, error?: unknown) => void>();
67
+ private readonly listeners = new Map<WsEvent, Set<(e?: unknown) => void>>();
68
+
69
+ constructor(opts: WsClientOptions) {
70
+ this.url = opts.wsUrl;
71
+ const WS = opts.WebSocket ?? (globalThis as { WebSocket?: WebSocketCtor }).WebSocket;
72
+ if (!WS) throw new Error("No WebSocket implementation available; pass `WebSocket` in options.");
73
+ this.WS = WS;
74
+ this.maxDelayMs = opts.maxDelayMs ?? 30_000;
75
+ this.idleTimeoutMs = opts.idleTimeoutMs ?? 45_000;
76
+ }
77
+
78
+ get state(): ConnectionState {
79
+ return this._state;
80
+ }
81
+
82
+ on(event: WsEvent, handler: (e?: unknown) => void): () => void {
83
+ let set = this.listeners.get(event);
84
+ if (!set) this.listeners.set(event, (set = new Set()));
85
+ set.add(handler);
86
+ return () => set!.delete(handler);
87
+ }
88
+
89
+ private emit(event: WsEvent, e?: unknown): void {
90
+ this.listeners.get(event)?.forEach((h) => {
91
+ try { h(e); } catch { /* ignore listener errors */ }
92
+ });
93
+ }
94
+
95
+ connect(): void {
96
+ this.wantOpen = true;
97
+ if (this._state === "closed") this.open();
98
+ }
99
+
100
+ close(): void {
101
+ this.wantOpen = false;
102
+ this.clearTimers();
103
+ this.subs.clear();
104
+ this.bySubId.clear();
105
+ this.pending.clear();
106
+ if (this.ws) {
107
+ try { this.ws.close(); } catch { /* ignore */ }
108
+ this.ws = undefined;
109
+ }
110
+ this._state = "closed";
111
+ }
112
+
113
+ subscribe(
114
+ channel: Channel,
115
+ params: SubParams,
116
+ onMessage: (result: unknown) => void,
117
+ onError?: (err: unknown) => void,
118
+ ): Subscription {
119
+ const sub: LogicalSub = { channel, params: { ...params }, onMessage, onError };
120
+ this.subs.add(sub);
121
+ this.connect();
122
+ if (this._state === "open") this.sendSubscribe(sub);
123
+ return {
124
+ unsubscribe: () => this.removeSub(sub),
125
+ update: (p) => { sub.params = { ...sub.params, ...p }; },
126
+ resubscribe: () => {
127
+ if (this._state !== "open") return;
128
+ if (sub.subId) { this.bySubId.delete(sub.subId); sub.subId = undefined; }
129
+ this.sendSubscribe(sub);
130
+ },
131
+ };
132
+ }
133
+
134
+ // --- connection lifecycle ---
135
+
136
+ private open(): void {
137
+ this.clearReconnect();
138
+ this._state = "connecting";
139
+ const ws = new this.WS(this.url);
140
+ this.ws = ws;
141
+ ws.onopen = () => {
142
+ this._state = "open";
143
+ this.attempts = 0;
144
+ this.emit("open");
145
+ this.armIdle();
146
+ for (const sub of this.subs) { sub.subId = undefined; this.sendSubscribe(sub); }
147
+ };
148
+ ws.onmessage = (ev: MessageEvent) => this.onMessage(ev.data);
149
+ ws.onerror = (ev: Event) => this.emit("error", ev);
150
+ ws.onclose = () => {
151
+ this.ws = undefined;
152
+ this.bySubId.clear();
153
+ for (const s of this.subs) s.subId = undefined;
154
+ if (this.wantOpen) this.scheduleReconnect();
155
+ else this._state = "closed";
156
+ };
157
+ }
158
+
159
+ private scheduleReconnect(): void {
160
+ this._state = "connecting";
161
+ const base = Math.min(this.maxDelayMs, 1000 * 2 ** this.attempts);
162
+ const delay = base / 2 + Math.random() * (base / 2); // jittered
163
+ this.attempts++;
164
+ this.clearTimers();
165
+ this.reconnectTimer = setTimeout(() => {
166
+ this.emit("reconnect");
167
+ this.open();
168
+ }, delay);
169
+ }
170
+
171
+ private armIdle(): void {
172
+ if (this.idleTimer) clearTimeout(this.idleTimer);
173
+ this.idleTimer = setTimeout(() => {
174
+ // No traffic for too long; force a reconnect.
175
+ if (this.ws) { try { this.ws.close(); } catch { /* ignore */ } }
176
+ }, this.idleTimeoutMs);
177
+ }
178
+
179
+ private clearReconnect(): void {
180
+ if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = undefined; }
181
+ }
182
+ private clearTimers(): void {
183
+ this.clearReconnect();
184
+ if (this.idleTimer) { clearTimeout(this.idleTimer); this.idleTimer = undefined; }
185
+ }
186
+
187
+ // --- protocol ---
188
+
189
+ private send(method: string, params: unknown[], onReply?: (result: unknown, error?: unknown) => void): void {
190
+ if (!this.ws || this._state !== "open") return;
191
+ const id = nextReqId++;
192
+ if (onReply) this.pending.set(id, onReply);
193
+ this.ws.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }));
194
+ }
195
+
196
+ private wireParams(p: SubParams): Record<string, unknown> {
197
+ const out: Record<string, unknown> = {};
198
+ if (p.clobIds && p.clobIds.length) out.clob_ids = p.clobIds;
199
+ if (p.account) out.account = p.account; // server aliases to `bidder`
200
+ if (p.depth !== undefined) out.depth = p.depth;
201
+ if (p.since !== undefined) out.since = p.since;
202
+ return out;
203
+ }
204
+
205
+ private sendSubscribe(sub: LogicalSub): void {
206
+ this.send("eth_subscribe", [sub.channel, this.wireParams(sub.params)], (result, error) => {
207
+ if (error || typeof result !== "string") {
208
+ const err = error ?? new Error("eth_subscribe failed");
209
+ if (sub.onError) sub.onError(err); // owner can re-seed + resubscribe (e.g. `since` too old)
210
+ else this.emit("error", err);
211
+ return;
212
+ }
213
+ // Unsubscribed while the ack was in flight (removeSub had no subId to
214
+ // cancel yet): registering it now would resurrect a dead subscription
215
+ // that keeps pushing into its owner's stale state — tell the server to
216
+ // drop it instead.
217
+ if (!this.subs.has(sub)) {
218
+ this.send("eth_unsubscribe", [result]);
219
+ return;
220
+ }
221
+ sub.subId = result;
222
+ this.bySubId.set(result, sub);
223
+ });
224
+ }
225
+
226
+ private removeSub(sub: LogicalSub): void {
227
+ this.subs.delete(sub);
228
+ if (sub.subId) {
229
+ this.bySubId.delete(sub.subId);
230
+ this.send("eth_unsubscribe", [sub.subId]);
231
+ sub.subId = undefined;
232
+ }
233
+ }
234
+
235
+ private onMessage(data: unknown): void {
236
+ this.armIdle();
237
+ const handle = (text: string) => {
238
+ let msg: any;
239
+ try { msg = JSON.parse(text); } catch { return; }
240
+ if (msg && msg.method === "eth_subscription" && msg.params) {
241
+ const sub = this.bySubId.get(msg.params.subscription);
242
+ if (sub) sub.onMessage(msg.params.result);
243
+ return;
244
+ }
245
+ if (msg && msg.id !== undefined && this.pending.has(msg.id)) {
246
+ const cb = this.pending.get(msg.id)!;
247
+ this.pending.delete(msg.id);
248
+ cb(msg.result, msg.error);
249
+ }
250
+ };
251
+ if (typeof data === "string") handle(data);
252
+ else if (data instanceof Blob) data.text().then(handle).catch(() => {});
253
+ else if (data instanceof ArrayBuffer) handle(new TextDecoder().decode(data));
254
+ }
255
+ }
@@ -0,0 +1,335 @@
1
+ // Decoded, consumer-facing types. All monetary values are `bigint` (1e18-scaled
2
+ // unless a token's own decimals are noted); all timestamps are milliseconds.
3
+
4
+ export type Hex = `0x${string}`;
5
+ export type MarketId = Hex;
6
+ export type Address = Hex;
7
+ export type Hash = Hex;
8
+
9
+ export type Resolution =
10
+ | "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "1d" | "1W" | "1M";
11
+
12
+ /** Inclusive-from, exclusive-to time window in milliseconds. `to` defaults to now. */
13
+ export interface TimeRange {
14
+ from: number;
15
+ to?: number;
16
+ }
17
+
18
+ export type MarketType = "spot" | "perp";
19
+ export type OrderSide = "buy" | "sell";
20
+ export type OrderType = "limit" | "market";
21
+ export type OrderStatus =
22
+ | "pending" | "active" | "filled" | "expired"
23
+ | "canceled" | "margin_canceled" | "invalid";
24
+ export type OrderKind =
25
+ | "user_signed" | "liquidation" | "triggered" | "adl" | "adl_counterparty"
26
+ /** A backstop transfer merged into the order feed as a synthetic terminal row. */
27
+ | "backstop_transfer";
28
+ export type TriggerType = "take_profit" | "stop_loss";
29
+ export type OrderDirection =
30
+ | "buy" | "sell"
31
+ | "open_long" | "add_long" | "reduce_long" | "close_long"
32
+ | "open_short" | "add_short" | "reduce_short" | "close_short"
33
+ | "long_to_short" | "short_to_long" | "liquidation";
34
+
35
+ export interface TokenInfo {
36
+ address: Address;
37
+ symbol: string;
38
+ name: string;
39
+ }
40
+
41
+ export interface Market {
42
+ id: MarketId;
43
+ name: string; // "BASE/QUOTE"
44
+ type: MarketType;
45
+ base: TokenInfo;
46
+ quote: TokenInfo;
47
+ tickPrecision: bigint;
48
+ lotSize: bigint;
49
+ maxLeverage: number;
50
+ fundingWindowUs: number; // funding-accrual divisor (micros)
51
+ makerFee: bigint;
52
+ takerFee: bigint;
53
+ auctionIntervalMs: number;
54
+ // --- live dynamics (undefined until first stats seed / tick) ---
55
+ lastClearingPrice?: bigint;
56
+ volume24h?: bigint;
57
+ high24h?: bigint;
58
+ low24h?: bigint;
59
+ priceChange24hBps?: number;
60
+ // --- perpetual-only dynamics ---
61
+ oraclePrice?: bigint;
62
+ markPrice?: bigint;
63
+ fundingRate?: bigint;
64
+ fundingIndex?: bigint;
65
+ fundingLastUpdatedMs?: number;
66
+ openInterest?: bigint;
67
+ }
68
+
69
+ export interface Bar {
70
+ time: number; // bucket start, ms
71
+ open: bigint;
72
+ high: bigint;
73
+ low: bigint;
74
+ close: bigint;
75
+ volume: bigint; // base volume
76
+ quoteVolume: bigint; // quote (USD) notional
77
+ }
78
+
79
+ export interface OrderbookLevel {
80
+ price: bigint;
81
+ volume: bigint; // size resting at this level
82
+ total: bigint; // cumulative size from the best price through this level
83
+ /** `total` as a 0..1 fraction of this side's full depth (deepest level → 1).
84
+ * Use directly as a depth-bar width. */
85
+ depth: number;
86
+ }
87
+
88
+ export interface Orderbook {
89
+ id: MarketId;
90
+ timeMs: number;
91
+ clearingPrice?: bigint;
92
+ bids: OrderbookLevel[]; // descending price (best first)
93
+ asks: OrderbookLevel[]; // ascending price (best first)
94
+ /** (bestBid + bestAsk) / 2; undefined if a side is empty. */
95
+ mid?: bigint;
96
+ /** bestAsk − bestBid (absolute). */
97
+ spread?: bigint;
98
+ /** spread as a percentage of mid. */
99
+ spreadPct?: number;
100
+ bidCount: number;
101
+ askCount: number;
102
+ groupingPrecision: bigint;
103
+ // perpetual-only
104
+ oraclePrice?: bigint;
105
+ fundingRate?: bigint;
106
+ fundingIndex?: bigint;
107
+ fundingLastUpdatedMs?: number;
108
+ }
109
+
110
+ export interface PartialFill {
111
+ base: bigint;
112
+ quote: bigint;
113
+ price: bigint;
114
+ time: number;
115
+ }
116
+
117
+ export interface Order {
118
+ id: Hash;
119
+ txHash: Hash;
120
+ orderbookId?: MarketId; // REST orders; WS stream orders carry `pair` instead
121
+ marketType?: MarketType;
122
+ /** Token-address pair (base/quote); present on WS stream orders. */
123
+ pair?: { base: Address; quote: Address };
124
+ side: OrderSide;
125
+ orderType: OrderType;
126
+ status: OrderStatus;
127
+ kind: OrderKind;
128
+ nonce: number;
129
+ bidder: Address;
130
+ price: bigint;
131
+ initialSize: bigint; // signed: + buy/long, - sell/short
132
+ filledBase: bigint;
133
+ filledQuote: bigint;
134
+ fee: bigint;
135
+ effectivePrice?: bigint;
136
+ deadlineMs: number;
137
+ endMs: number;
138
+ /** Batch-inclusion time (ms) — when the order entered the book. REST history only. */
139
+ includedMs?: number;
140
+ fills: PartialFill[];
141
+ // perpetual-only
142
+ reduceOnly?: boolean;
143
+ ioc?: boolean;
144
+ direction?: OrderDirection;
145
+ triggerType?: TriggerType;
146
+ }
147
+
148
+ export type Position = SpotPosition | PerpPosition;
149
+
150
+ export interface SpotPosition {
151
+ kind: "spot";
152
+ orderbookId?: MarketId;
153
+ token: Address;
154
+ balance: bigint;
155
+ freeBalance: bigint;
156
+ lockedBalance: bigint;
157
+ costBasis: bigint;
158
+ markPrice: bigint;
159
+ unrealizedPnl: bigint;
160
+ realizedPnl: bigint;
161
+ }
162
+
163
+ export interface PerpPosition {
164
+ kind: "perp";
165
+ orderbookId: MarketId;
166
+ side: "long" | "short";
167
+ size: bigint; // signed
168
+ notional: bigint;
169
+ entryPrice: bigint;
170
+ markPrice: bigint;
171
+ margin: bigint;
172
+ leverage: number;
173
+ fundingAccrued: bigint;
174
+ /** Funding accumulator at entry; with the live fundingIndex + fundingWindowUs, recompute fundingAccrued. */
175
+ entryFunding: bigint;
176
+ liquidationPrice: bigint;
177
+ unrealizedPnl: bigint;
178
+ realizedPnl: bigint;
179
+ }
180
+
181
+ export interface PositionsSnapshot {
182
+ positions: Position[];
183
+ totalUnrealizedPnl: bigint;
184
+ totalRealizedPnl: bigint;
185
+ perpsEquity: bigint;
186
+ accountValue: bigint;
187
+ cash: bigint;
188
+ withdrawableCash: bigint;
189
+ }
190
+
191
+ export interface Trigger {
192
+ orderbookId: MarketId;
193
+ orderId: Hash;
194
+ txHash: Hash;
195
+ bidder: Address;
196
+ nonce: number;
197
+ size: bigint; // signed
198
+ limitPrice: bigint;
199
+ triggerPrice: bigint;
200
+ triggerType: TriggerType;
201
+ reduceOnly: boolean;
202
+ ioc: boolean;
203
+ deadlineMs: number;
204
+ endMs: number;
205
+ }
206
+
207
+ export interface BackstopTransfer {
208
+ orderbookId?: MarketId;
209
+ size: bigint; // signed
210
+ cash: bigint;
211
+ markPrice: bigint;
212
+ equity: bigint;
213
+ time: number;
214
+ }
215
+
216
+ export interface Status {
217
+ /** Newest indexed solution time (the settled watermark), in ms. */
218
+ solutionNow: number;
219
+ }
220
+
221
+ // --- explorer (`/tx/{hash}`) ---
222
+
223
+ export interface TxAttestation {
224
+ validator_address: string;
225
+ sequence_number: number;
226
+ batch_index?: number;
227
+ timestamp: number; // microseconds
228
+ signature: string;
229
+ }
230
+
231
+ /** Pre-decoded calldata: `{contract, function, args}` plus curation
232
+ * (order_id, submitBatch sub-intents, ERC20 symbol …). */
233
+ export interface TxDecoded {
234
+ contract: string;
235
+ function: string;
236
+ args: Record<string, unknown>;
237
+ order_id?: string;
238
+ [k: string]: unknown;
239
+ }
240
+
241
+ /** Flat explorer view of a transaction. Hex fields are raw RPC encodings —
242
+ * format them at the edge. Extra fields are tolerated (index signature). */
243
+ export interface TxExplorer {
244
+ hash: string;
245
+ type: string;
246
+ nonce: string;
247
+ from: string;
248
+ to: string | null;
249
+ value: string;
250
+ gas: string;
251
+ gasUsed: string;
252
+ status: string; // "0x1" success, "0x0" reverted
253
+ input: string;
254
+ logs: unknown[];
255
+ decoded?: TxDecoded | null;
256
+ attestations: TxAttestation[];
257
+ committee_epoch?: number;
258
+ chainId?: string;
259
+ maxFeePerGas?: string;
260
+ effectiveGasPrice?: string;
261
+ blockNumber?: string;
262
+ transactionIndex?: string;
263
+ contractAddress?: string | null;
264
+ [k: string]: unknown;
265
+ }
266
+
267
+ /** A spot token holding (`/clob/balances`). Like SpotPosition but identified by
268
+ * market + symbols rather than token address. */
269
+ export interface SpotHolding {
270
+ orderbookId: MarketId;
271
+ baseSymbol: string;
272
+ quoteSymbol: string;
273
+ balance: bigint; // free + locked
274
+ freeBalance: bigint;
275
+ lockedBalance: bigint;
276
+ costBasis: bigint;
277
+ markPrice: bigint;
278
+ unrealizedPnl: bigint;
279
+ realizedPnl: bigint;
280
+ }
281
+
282
+ /** Spot holdings + native cash for an account (`/clob/balances`). Perp positions
283
+ * and their aggregates live in {@link PositionsSnapshot}. */
284
+ export interface Balances {
285
+ holdings: SpotHolding[];
286
+ cash: bigint;
287
+ withdrawableCash: bigint;
288
+ netDeposits: bigint;
289
+ }
290
+
291
+ /** One ranked account from the leaderboard (`/clob/leaderboard`). */
292
+ export interface LeaderboardEntry {
293
+ rank: number; // 1-based position in the full ordering
294
+ account: Address;
295
+ accountValue: bigint;
296
+ unrealizedPnl: bigint;
297
+ realizedPnl: bigint;
298
+ /** Net PnL = unrealized + realized — the key the board is ranked by. */
299
+ pnl: bigint;
300
+ /** pnl / (accountValue − unrealized) × 100; 0 when the basis is dust. */
301
+ pnlPercent: number;
302
+ }
303
+
304
+ export interface LeaderboardPage {
305
+ entries: LeaderboardEntry[];
306
+ /** Full count of ranked accounts (before paging) — for page math. */
307
+ total: number;
308
+ }
309
+
310
+ export interface LeaderboardQuery {
311
+ limit?: number;
312
+ offset?: number;
313
+ /** When set, the response also locates this account's own rank. */
314
+ account?: Address;
315
+ }
316
+
317
+ // --- query / paging types ---
318
+
319
+ export interface CandleQuery {
320
+ resolution: Resolution;
321
+ from?: number; // ms
322
+ to?: number; // ms
323
+ limit?: number;
324
+ }
325
+
326
+ export interface OrdersQuery {
327
+ status?: OrderStatus;
328
+ orderbookId?: MarketId;
329
+ limit?: number;
330
+ }
331
+
332
+ export interface TriggersQuery {
333
+ orderbookId?: MarketId;
334
+ limit?: number;
335
+ }