@pod-network/trade-sdk 0.10.0 → 0.12.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 +6 -4
- package/dist/client.d.ts +30 -11
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +37 -17
- package/dist/client.js.map +1 -1
- package/dist/codec/activity.d.ts +11 -0
- package/dist/codec/activity.d.ts.map +1 -0
- package/dist/codec/activity.js +33 -0
- package/dist/codec/activity.js.map +1 -0
- package/dist/codec/decode.d.ts +14 -6
- package/dist/codec/decode.d.ts.map +1 -1
- package/dist/codec/decode.js +58 -24
- package/dist/codec/decode.js.map +1 -1
- package/dist/codec/json.d.ts +3 -0
- package/dist/codec/json.d.ts.map +1 -0
- package/dist/codec/json.js +14 -0
- package/dist/codec/json.js.map +1 -0
- package/dist/codec/orders-v2.d.ts +9 -3
- package/dist/codec/orders-v2.d.ts.map +1 -1
- package/dist/codec/orders-v2.js +12 -9
- package/dist/codec/orders-v2.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/stores/resource.d.ts +48 -2
- package/dist/stores/resource.d.ts.map +1 -1
- package/dist/stores/resource.js +75 -6
- package/dist/stores/resource.js.map +1 -1
- package/dist/sync/activity.d.ts +58 -0
- package/dist/sync/activity.d.ts.map +1 -0
- package/dist/sync/activity.js +259 -0
- package/dist/sync/activity.js.map +1 -0
- package/dist/sync/orders.d.ts +8 -65
- package/dist/sync/orders.d.ts.map +1 -1
- package/dist/sync/orders.js +44 -192
- package/dist/sync/orders.js.map +1 -1
- package/dist/sync/pnl-history.d.ts +33 -14
- package/dist/sync/pnl-history.d.ts.map +1 -1
- package/dist/sync/pnl-history.js +255 -65
- package/dist/sync/pnl-history.js.map +1 -1
- package/dist/sync/sources.d.ts.map +1 -1
- package/dist/sync/sources.js +12 -5
- package/dist/sync/sources.js.map +1 -1
- package/dist/sync/stream.d.ts +101 -0
- package/dist/sync/stream.d.ts.map +1 -0
- package/dist/sync/stream.js +243 -0
- package/dist/sync/stream.js.map +1 -0
- package/dist/transport/jsonrpc.d.ts +0 -5
- package/dist/transport/jsonrpc.d.ts.map +1 -1
- package/dist/transport/jsonrpc.js +0 -20
- package/dist/transport/jsonrpc.js.map +1 -1
- package/dist/transport/rest.d.ts +36 -4
- package/dist/transport/rest.d.ts.map +1 -1
- package/dist/transport/rest.js +43 -10
- package/dist/transport/rest.js.map +1 -1
- package/dist/transport/ws.d.ts +5 -1
- package/dist/transport/ws.d.ts.map +1 -1
- package/dist/transport/ws.js.map +1 -1
- package/dist/types/public.d.ts +62 -23
- package/dist/types/public.d.ts.map +1 -1
- package/dist/types/wire.d.ts +98 -16
- package/dist/types/wire.d.ts.map +1 -1
- package/dist/write/index.d.ts +3 -3
- package/dist/write/index.d.ts.map +1 -1
- package/dist/write/index.js +0 -3
- package/dist/write/index.js.map +1 -1
- package/package.json +1 -1
- package/src/client.ts +49 -19
- package/src/codec/activity.ts +46 -0
- package/src/codec/decode.ts +65 -30
- package/src/codec/json.ts +18 -0
- package/src/codec/orders-v2.ts +24 -11
- package/src/index.ts +4 -2
- package/src/stores/resource.ts +111 -5
- package/src/sync/activity.ts +266 -0
- package/src/sync/orders.ts +46 -189
- package/src/sync/pnl-history.ts +244 -75
- package/src/sync/sources.ts +12 -6
- package/src/sync/stream.ts +270 -0
- package/src/transport/jsonrpc.ts +0 -23
- package/src/transport/rest.ts +62 -14
- package/src/transport/ws.ts +5 -1
- package/src/types/public.ts +62 -26
- package/src/types/wire.ts +105 -18
- package/src/write/index.ts +3 -6
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// The subscribe / resume / re-seed loop shared by the account feeds.
|
|
2
|
+
//
|
|
3
|
+
// Reconnect: on every (re)connect the owner re-seeds its first page (the
|
|
4
|
+
// authoritative snapshot) and refreshes the cursor from its watermark; the WS
|
|
5
|
+
// auto-resubscribes, and if the cursor is too old (down too long) `onSubError`
|
|
6
|
+
// re-seeds and resubscribes. A server-initiated close is not the same as a
|
|
7
|
+
// rejection: it reports where delivery stopped, so resuming from one is a bare
|
|
8
|
+
// `resubscribe()` with no re-seed.
|
|
9
|
+
|
|
10
|
+
import type { MarketId } from "../types/public.js";
|
|
11
|
+
import { PodHttpError } from "../transport/rest.js";
|
|
12
|
+
import type { Channel, PodWsClient, SubParams, Subscription } from "../transport/ws.js";
|
|
13
|
+
import { PodSubscriptionClosedError } from "../transport/ws.js";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Consecutive server closes we resume from before falling back to the re-seed
|
|
17
|
+
* path. A lagged close is recoverable by resubscribing, so the fast path is the
|
|
18
|
+
* right default — but a stream that keeps closing is one we are not keeping up
|
|
19
|
+
* with, and re-seeding beats replaying a growing backlog on every attempt.
|
|
20
|
+
*/
|
|
21
|
+
const FAST_RESUMES_BEFORE_RESEED = 3;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Re-seed attempts that keep the cursor before we conclude the cursor is what the
|
|
25
|
+
* server is rejecting, drop it, and settle for streaming live.
|
|
26
|
+
*/
|
|
27
|
+
const RETRIES_BEFORE_DROPPING_CURSOR = 2;
|
|
28
|
+
|
|
29
|
+
/** The largest book id, which is what an absent `sinceBook` means. */
|
|
30
|
+
const WHOLE_BATCH = `0x${"ff".repeat(32)}` as MarketId;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Order two positions in the stream, the way the server does.
|
|
34
|
+
*
|
|
35
|
+
* A batch is delivered as one frame per book, so a position is the pair
|
|
36
|
+
* `(batch, book)` — and an absent book means the whole batch, which sorts *above*
|
|
37
|
+
* every book in it. This mirrors `already_delivered` in
|
|
38
|
+
* `node/src/rpc/orders_v2.rs`: `(frame_batch, frame_book) <= (since,
|
|
39
|
+
* since_book.unwrap_or(0xff…))`. Getting the absent case wrong turns "all of batch
|
|
40
|
+
* N" into "up to book B of batch N", which asks the server to re-send the rest.
|
|
41
|
+
*
|
|
42
|
+
* `pod_activity` sends one frame per tick and names no book, so the pair collapses
|
|
43
|
+
* to the batch there — the same comparison, with both books absent.
|
|
44
|
+
*
|
|
45
|
+
* Book ids are fixed-width lowercase hex, so comparing them as strings is
|
|
46
|
+
* comparing their bytes.
|
|
47
|
+
*/
|
|
48
|
+
export function compareCursor(a: SubParams, b: SubParams): number {
|
|
49
|
+
const aBatch = a.since ?? 0;
|
|
50
|
+
const bBatch = b.since ?? 0;
|
|
51
|
+
if (aBatch !== bBatch) return aBatch < bBatch ? -1 : 1;
|
|
52
|
+
const aBook = a.sinceBook ?? WHOLE_BATCH;
|
|
53
|
+
const bBook = b.sinceBook ?? WHOLE_BATCH;
|
|
54
|
+
return aBook === bBook ? 0 : aBook < bBook ? -1 : 1;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A seed the server refused on its own terms. Retrying reproduces it, so the
|
|
59
|
+
* backoff would be an infinite loop against an answer that will not change.
|
|
60
|
+
*/
|
|
61
|
+
const permanent = (err: unknown): boolean =>
|
|
62
|
+
err instanceof PodHttpError && err.status >= 400 && err.status < 500;
|
|
63
|
+
|
|
64
|
+
export interface ResumableStreamOptions {
|
|
65
|
+
ws: PodWsClient;
|
|
66
|
+
channel: Channel;
|
|
67
|
+
/** Everything that identifies the subscription except the cursor. */
|
|
68
|
+
params: SubParams;
|
|
69
|
+
/**
|
|
70
|
+
* Re-seed over REST, and raise the cursor to the page's watermark. `true` when
|
|
71
|
+
* the page was applied, `false` when it was abandoned (the stream stopped, or a
|
|
72
|
+
* fresher seed overtook it); a rejection is a failed fetch, which is what decides
|
|
73
|
+
* between backing off and giving up.
|
|
74
|
+
*/
|
|
75
|
+
reseed(): Promise<boolean>;
|
|
76
|
+
onFrame(result: unknown): void;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export class ResumableStream {
|
|
80
|
+
/**
|
|
81
|
+
* Where the stream is: the last frame accepted. Replaced whole rather than
|
|
82
|
+
* patched half at a time — on `pod_orders_v2` `sinceBook` names a book *within*
|
|
83
|
+
* `since`, so the two are one fact and a mismatched pair asks the server to skip
|
|
84
|
+
* books we never saw.
|
|
85
|
+
*/
|
|
86
|
+
cursor: SubParams = {};
|
|
87
|
+
private sub: Subscription | undefined;
|
|
88
|
+
private alive = false;
|
|
89
|
+
private subRetries = 0;
|
|
90
|
+
private fastResumes = 0;
|
|
91
|
+
private retryTimer?: ReturnType<typeof setTimeout>;
|
|
92
|
+
private offOpen?: () => void;
|
|
93
|
+
|
|
94
|
+
constructor(private readonly opts: ResumableStreamOptions) {}
|
|
95
|
+
|
|
96
|
+
/** Whether the owner's resource is still running; guards its async seeds. */
|
|
97
|
+
get running(): boolean { return this.alive; }
|
|
98
|
+
|
|
99
|
+
start(): void {
|
|
100
|
+
this.alive = true;
|
|
101
|
+
this.offOpen = this.opts.ws.on("open", () => { if (this.alive) this.seed(); });
|
|
102
|
+
this.seed(); // initial paint (REST is independent of the socket being open)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
stop(): void {
|
|
106
|
+
this.alive = false;
|
|
107
|
+
this.offOpen?.();
|
|
108
|
+
this.offOpen = undefined;
|
|
109
|
+
this.clearRetry();
|
|
110
|
+
this.sub?.unsubscribe();
|
|
111
|
+
this.sub = undefined;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The server's `already_delivered`: is this frame at or behind where we are? */
|
|
115
|
+
delivered(at: SubParams): boolean {
|
|
116
|
+
return compareCursor(at, this.cursor) <= 0;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Move to `at` and tell the transport, so a reconnect resumes from there. */
|
|
120
|
+
advance(at: SubParams): void {
|
|
121
|
+
this.cursor = at;
|
|
122
|
+
this.sub?.update(at);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Move to `at` only when it is ahead. Never rewinds — a re-delivered frame is dropped. */
|
|
126
|
+
raise(at: SubParams): void {
|
|
127
|
+
if (compareCursor(at, this.cursor) > 0) this.cursor = at;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
seed(): void {
|
|
131
|
+
// A seed that lands supersedes whatever the last failure armed; leaving the
|
|
132
|
+
// timer would re-seed and resubscribe a stream that is already healthy.
|
|
133
|
+
const armed = this.retryTimer !== undefined;
|
|
134
|
+
this.clearRetry();
|
|
135
|
+
void this.opts.reseed().then(
|
|
136
|
+
(ok) => { if (ok) this.resume(); },
|
|
137
|
+
(err) => {
|
|
138
|
+
// Nothing is subscribed yet, so no close or rejection can arrive to schedule
|
|
139
|
+
// another attempt — a failed first paint has to re-arm itself or the resource
|
|
140
|
+
// stays empty for good. With a subscription up, the live stream is unaffected
|
|
141
|
+
// and its own error path owns the recovery; the exception is a retry this call
|
|
142
|
+
// just disarmed, which nothing else would re-arm.
|
|
143
|
+
if (this.alive && (!this.sub || armed) && !permanent(err)) this.scheduleReseed();
|
|
144
|
+
},
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
private resume(): void {
|
|
149
|
+
if (!this.alive) return;
|
|
150
|
+
if (!this.sub) this.subscribe();
|
|
151
|
+
else this.pushCursor(); // refresh for the next reconnect
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
private subscribe(): void {
|
|
155
|
+
this.sub = this.opts.ws.subscribe(
|
|
156
|
+
this.opts.channel,
|
|
157
|
+
{ ...this.opts.params, ...this.cursor },
|
|
158
|
+
(r) => this.onFrame(r),
|
|
159
|
+
(e) => this.onSubError(e),
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Push the cursor to the transport, both halves.
|
|
165
|
+
*
|
|
166
|
+
* `update` merges, so sending `{ since }` alone would leave whatever `sinceBook`
|
|
167
|
+
* was there before — a book from an older batch beside a newer `since`, which asks
|
|
168
|
+
* the server to skip less than it should and re-send the difference.
|
|
169
|
+
*/
|
|
170
|
+
private pushCursor(): void {
|
|
171
|
+
this.sub?.update({ since: this.cursor.since, sinceBook: this.cursor.sinceBook });
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
private clearRetry(): void {
|
|
175
|
+
if (this.retryTimer) { clearTimeout(this.retryTimer); this.retryTimer = undefined; }
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
private onFrame(result: unknown): void {
|
|
179
|
+
// Live data flowing → the subscription is healthy on both paths, and a retry
|
|
180
|
+
// armed by whatever went wrong before has nothing left to recover.
|
|
181
|
+
this.subRetries = 0;
|
|
182
|
+
this.fastResumes = 0;
|
|
183
|
+
this.clearRetry();
|
|
184
|
+
this.opts.onFrame(result);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* The subscription is not running: `eth_subscribe` was rejected, or the server
|
|
189
|
+
* closed it.
|
|
190
|
+
*
|
|
191
|
+
* A resumable close needs neither a re-seed nor a delay: the server reports where
|
|
192
|
+
* it stopped, so resubscribing from that delivers exactly the frames we never got.
|
|
193
|
+
* That fast path is only taken while the socket is actually open — `resubscribe()`
|
|
194
|
+
* is a no-op otherwise, which would spend the budget without an attempt and leave
|
|
195
|
+
* nothing scheduled, and `-32021` (node shutting down) arrives exactly as the
|
|
196
|
+
* socket goes away.
|
|
197
|
+
*
|
|
198
|
+
* Everything else (a rejection, a server bug, a close with the socket already
|
|
199
|
+
* gone, or closes that keep coming) takes the slow path: backed off and capped, so
|
|
200
|
+
* a server that keeps refusing cannot spin this into a tight re-seed loop, and
|
|
201
|
+
* eventually the cursor is dropped (the likely culprit) to just stream live. Both
|
|
202
|
+
* counters reset once live data flows (`onFrame`).
|
|
203
|
+
*/
|
|
204
|
+
private onSubError(err: unknown): void {
|
|
205
|
+
if (!this.alive) return;
|
|
206
|
+
const canFastResume = err instanceof PodSubscriptionClosedError && err.resumable
|
|
207
|
+
&& this.fastResumes < FAST_RESUMES_BEFORE_RESEED && this.opts.ws.state === "open";
|
|
208
|
+
if (canFastResume) {
|
|
209
|
+
this.fastResumes++;
|
|
210
|
+
// Adopt the server's watermark only when it is ahead of ours: it knows which
|
|
211
|
+
// frames it handed over, but a re-seed may already have carried us past it,
|
|
212
|
+
// and rewinding would re-deliver frames we have applied.
|
|
213
|
+
const reported: SubParams = { since: err.resumeSince, sinceBook: err.resumeSinceBook };
|
|
214
|
+
if (err.resumeSince !== undefined) this.raise(reported);
|
|
215
|
+
// The transport rewrote `sub.params` from the close before this ran, so without
|
|
216
|
+
// pushing our own decision back the wire resumes from the server's point
|
|
217
|
+
// regardless and the guard above protects nothing.
|
|
218
|
+
this.pushCursor();
|
|
219
|
+
this.sub?.resubscribe();
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
// The slow path, and the one that answers "what if we fell behind the server's
|
|
223
|
+
// replay buffer": `eth_subscribe` rejects a `since` older than what the buffer
|
|
224
|
+
// retains, and the prescribed recovery is to backfill over REST and resubscribe.
|
|
225
|
+
// That is what this is. The re-seed also *raises the cursor* to the page's
|
|
226
|
+
// watermark, so the position that was too old is gone by the first retry and the
|
|
227
|
+
// resubscribe is accepted with no gap — the server replays from the page forward.
|
|
228
|
+
// Dropping the cursor below is the backstop for when even that fresh watermark is
|
|
229
|
+
// refused (the indexer further behind than the buffer retains): live-only
|
|
230
|
+
// resubscribe, trading the unreplayable window for a working stream.
|
|
231
|
+
this.scheduleReseed();
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Back off, re-seed over REST, then resubscribe — and keep trying.
|
|
236
|
+
*
|
|
237
|
+
* The re-seed can fail too (the same node is usually behind both the stream and the
|
|
238
|
+
* indexer), and a failure has to re-arm here: not resubscribing means no further
|
|
239
|
+
* close or rejection arrives, so nothing else would ever schedule another attempt and
|
|
240
|
+
* the stream would stay down with no error surfaced. Capped, so a node that keeps
|
|
241
|
+
* refusing cannot spin this.
|
|
242
|
+
*/
|
|
243
|
+
private scheduleReseed(): void {
|
|
244
|
+
this.subRetries++;
|
|
245
|
+
const delay = Math.min(30_000, 500 * 2 ** (this.subRetries - 1));
|
|
246
|
+
this.clearRetry();
|
|
247
|
+
this.retryTimer = setTimeout(() => {
|
|
248
|
+
this.retryTimer = undefined;
|
|
249
|
+
void this.opts.reseed().then((ok) => {
|
|
250
|
+
if (!this.alive || !ok) return;
|
|
251
|
+
if (!this.sub) {
|
|
252
|
+
// Retrying the first paint: there is no subscription to resume, and no
|
|
253
|
+
// cursor the server has refused — open one from the page we just landed,
|
|
254
|
+
// and let the live stream start on a full budget rather than inheriting
|
|
255
|
+
// the attempts the indexer's outage cost.
|
|
256
|
+
this.subRetries = 0;
|
|
257
|
+
this.fastResumes = 0;
|
|
258
|
+
this.subscribe();
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const tooOld = this.subRetries > RETRIES_BEFORE_DROPPING_CURSOR;
|
|
262
|
+
if (tooOld) this.sub.update({ since: undefined, sinceBook: undefined });
|
|
263
|
+
else this.pushCursor();
|
|
264
|
+
this.sub.resubscribe();
|
|
265
|
+
}, (err) => {
|
|
266
|
+
if (this.alive && !permanent(err)) this.scheduleReseed();
|
|
267
|
+
});
|
|
268
|
+
}, delay);
|
|
269
|
+
}
|
|
270
|
+
}
|
package/src/transport/jsonrpc.ts
CHANGED
|
@@ -52,26 +52,3 @@ export async function tryRpc<T>(
|
|
|
52
52
|
return undefined;
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
|
-
|
|
56
|
-
/** One HTTP round trip carrying many calls; results come back in call order. */
|
|
57
|
-
export async function rpcBatch<T>(
|
|
58
|
-
rpcUrl: string,
|
|
59
|
-
calls: { method: string; params: unknown[] }[],
|
|
60
|
-
opts?: RpcOptions,
|
|
61
|
-
): Promise<T[]> {
|
|
62
|
-
const doFetch = opts?.fetch ?? fetch;
|
|
63
|
-
const res = await doFetch(rpcUrl, {
|
|
64
|
-
method: "POST",
|
|
65
|
-
headers: { "content-type": "application/json" },
|
|
66
|
-
body: JSON.stringify(calls.map((c, id) => ({ jsonrpc: "2.0", id, ...c }))),
|
|
67
|
-
signal: opts?.signal,
|
|
68
|
-
});
|
|
69
|
-
const json = (await res.json()) as { id: number; result?: T; error?: { code?: number; message?: string } }[];
|
|
70
|
-
if (!Array.isArray(json)) throw new PodRpcError(undefined, "batch response is not an array");
|
|
71
|
-
const out = new Array<T>(calls.length);
|
|
72
|
-
for (const r of json) {
|
|
73
|
-
if (r.error) throw new PodRpcError(r.error.code, r.error.message ?? `${calls[r.id]?.method} failed`);
|
|
74
|
-
out[r.id] = r.result as T;
|
|
75
|
-
}
|
|
76
|
-
return out;
|
|
77
|
-
}
|
package/src/transport/rest.ts
CHANGED
|
@@ -2,22 +2,23 @@
|
|
|
2
2
|
// CDN honor the server's Cache-Control; identical concurrent GETs are deduped.
|
|
3
3
|
// ms in, decoded (bigint / ms) out.
|
|
4
4
|
|
|
5
|
+
import type { WireFillRow, WireSolutionRow } from "../types/wire.js";
|
|
5
6
|
import type {
|
|
6
|
-
Address, BackstopTransfer, Balances, Bar, BridgeConfig, CandleQuery,
|
|
7
|
-
|
|
7
|
+
ActivityEntry, ActivityType, Address, BackstopTransfer, Balances, Bar, BridgeConfig, CandleQuery,
|
|
8
|
+
Market, MarketId, Order, Orderbook, PositionsSnapshot, Resolution, Status,
|
|
8
9
|
Trigger, TxExplorer, Withdrawal, WithdrawalsQuery,
|
|
9
10
|
} from "../types/public.js";
|
|
10
11
|
import type {
|
|
11
|
-
WireBackstopPage, WireBalances, WireBridgeConfig, WireCandlesEnvelope,
|
|
12
|
+
WireActivityPage, WireBackstopPage, WireBalances, WireBridgeConfig, WireCandlesEnvelope,
|
|
12
13
|
WireMarketStatic, WireMarketStatsPage, WireOrderbook, WireOrdersPage, WirePositionsSnapshot,
|
|
13
14
|
WireStatus, WireTriggersPage, WireWithdrawal,
|
|
14
15
|
} from "../types/wire.js";
|
|
15
16
|
import {
|
|
16
|
-
decodeBackstopTransfer, decodeBalances, decodeBridgeConfig, decodeCandle,
|
|
17
|
+
decodeActivityEntry, decodeBackstopTransfer, decodeBalances, decodeBridgeConfig, decodeCandle,
|
|
17
18
|
decodeMarketDynamics, decodeMarketStatic, decodeOrder, decodeOrderbook, decodePositions,
|
|
18
19
|
decodeStatus, decodeTrigger, decodeWithdrawal,
|
|
19
20
|
} from "../codec/decode.js";
|
|
20
|
-
import { msToSecs, usToMs } from "../codec/units.js";
|
|
21
|
+
import { msToSecs, msToUs, usToMs } from "../codec/units.js";
|
|
21
22
|
|
|
22
23
|
export type MarketDynamicsPatch = Partial<Market> & { id: string };
|
|
23
24
|
|
|
@@ -31,6 +32,11 @@ export interface OrdersPage {
|
|
|
31
32
|
totalCount: number;
|
|
32
33
|
solutionNow: number;
|
|
33
34
|
}
|
|
35
|
+
export interface ActivityPage {
|
|
36
|
+
activity: ActivityEntry[];
|
|
37
|
+
nextCursor: string | null;
|
|
38
|
+
solutionNow: number; // ms
|
|
39
|
+
}
|
|
34
40
|
export interface BackstopPage {
|
|
35
41
|
transfers: BackstopTransfer[];
|
|
36
42
|
totalCount: number;
|
|
@@ -53,6 +59,13 @@ export interface OrdersQueryRest {
|
|
|
53
59
|
limit?: number;
|
|
54
60
|
cursor?: string;
|
|
55
61
|
}
|
|
62
|
+
export interface ActivityQueryRest {
|
|
63
|
+
limit?: number;
|
|
64
|
+
cursor?: string;
|
|
65
|
+
types?: ActivityType[];
|
|
66
|
+
from?: number; // ms
|
|
67
|
+
to?: number; // ms
|
|
68
|
+
}
|
|
56
69
|
export interface TriggersQueryRest {
|
|
57
70
|
orderbook?: MarketId;
|
|
58
71
|
limit?: number;
|
|
@@ -177,6 +190,50 @@ export class PodRestClient {
|
|
|
177
190
|
};
|
|
178
191
|
}
|
|
179
192
|
|
|
193
|
+
/**
|
|
194
|
+
* One account's activity, newest first: orders at their placement tick, and the
|
|
195
|
+
* money that moved (ADR 0057 §5). The seed behind `pod_activity`; page it
|
|
196
|
+
* with `cursor`.
|
|
197
|
+
*/
|
|
198
|
+
async activity(account: Address, q?: ActivityQueryRest): Promise<ActivityPage> {
|
|
199
|
+
const w = await this.get<WireActivityPage>(`/clob/activity/${account}`, {
|
|
200
|
+
limit: q?.limit,
|
|
201
|
+
cursor: q?.cursor,
|
|
202
|
+
activity_types: q?.types?.length ? q.types.join(",") : undefined,
|
|
203
|
+
from: q?.from !== undefined ? msToUs(q.from) : undefined,
|
|
204
|
+
to: q?.to !== undefined ? msToUs(q.to) : undefined,
|
|
205
|
+
});
|
|
206
|
+
return {
|
|
207
|
+
activity: w.activity.map(decodeActivityEntry).filter((e): e is ActivityEntry => e !== undefined),
|
|
208
|
+
nextCursor: w.next_cursor,
|
|
209
|
+
solutionNow: usToMs(w.solution_now),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** An account's fills with `fromUs ≤ timestamp < toUs`, newest first, at
|
|
214
|
+
* most 500; page by moving `toUs` down to the oldest timestamp seen. */
|
|
215
|
+
async fills(account: Address, q: { fromUs: number; toUs?: number; orderbook?: MarketId; limit?: number }): Promise<WireFillRow[]> {
|
|
216
|
+
const w = await this.get<{ fills: WireFillRow[] }>(`/clob/fills/${account}`, {
|
|
217
|
+
from_us: q.fromUs,
|
|
218
|
+
to_us: q.toUs,
|
|
219
|
+
orderbook: q.orderbook,
|
|
220
|
+
limit: q.limit,
|
|
221
|
+
});
|
|
222
|
+
return w.fills;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Solutions rows, newest first, with `sinceUs ≤ timestamp < untilUs`;
|
|
226
|
+
* `limit` counts ticks, so one tick returns every market's row. */
|
|
227
|
+
async solutions(q: { orderbook?: MarketId; sinceUs?: number; untilUs?: number; limit?: number }): Promise<WireSolutionRow[]> {
|
|
228
|
+
const w = await this.get<{ solutions: WireSolutionRow[] }>(`/clob/solutions`, {
|
|
229
|
+
orderbook: q.orderbook,
|
|
230
|
+
since_us: q.sinceUs,
|
|
231
|
+
until_us: q.untilUs,
|
|
232
|
+
limit: q.limit,
|
|
233
|
+
});
|
|
234
|
+
return w.solutions;
|
|
235
|
+
}
|
|
236
|
+
|
|
180
237
|
async backstopTransfers(account: Address): Promise<BackstopPage> {
|
|
181
238
|
const w = await this.get<WireBackstopPage>(`/clob/backstop-transfers/${account}`);
|
|
182
239
|
return {
|
|
@@ -206,15 +263,6 @@ export class PodRestClient {
|
|
|
206
263
|
return this.get<TxExplorer>(`/tx/${hash}`);
|
|
207
264
|
}
|
|
208
265
|
|
|
209
|
-
/** Accounts ranked by net PnL (realized + unrealized), descending. Paginate
|
|
210
|
-
* with `{ limit, offset }`; ranks are 1-based over the full ordering. */
|
|
211
|
-
async leaderboard(q?: LeaderboardQuery): Promise<LeaderboardPage> {
|
|
212
|
-
const w = await this.get<WireLeaderboard>("/clob/leaderboard", {
|
|
213
|
-
limit: q?.limit, offset: q?.offset, address: q?.account,
|
|
214
|
-
});
|
|
215
|
-
return decodeLeaderboard(w, q?.offset ?? 0);
|
|
216
|
-
}
|
|
217
|
-
|
|
218
266
|
/** Static bridge config: the claim chain, the bridge contract, and every
|
|
219
267
|
* bridged token's L1 address, decimals and withdraw window (ADR 0033 §5).
|
|
220
268
|
* Served unconditionally — it is not behind the CLOB indexer's gate. */
|
package/src/transport/ws.ts
CHANGED
|
@@ -10,7 +10,11 @@ export type Channel =
|
|
|
10
10
|
| "pod_markets" | "pod_positions" | "pod_triggers"
|
|
11
11
|
/** Terminal withdrawal outcomes; one array per tick, `account`-filtered on the
|
|
12
12
|
* debited account. ADR 0033 §6. */
|
|
13
|
-
| "pod_withdrawals"
|
|
13
|
+
| "pod_withdrawals"
|
|
14
|
+
/** One account's whole activity: `pod_orders_v2` for every book the tick
|
|
15
|
+
* cleared, plus the money it moved. One frame per tick, so `since` alone
|
|
16
|
+
* resumes it. ADR 0057 §6. */
|
|
17
|
+
| "pod_activity";
|
|
14
18
|
|
|
15
19
|
export interface SubParams {
|
|
16
20
|
clobIds?: MarketId[];
|
package/src/types/public.ts
CHANGED
|
@@ -359,6 +359,8 @@ export interface BackstopTransfer {
|
|
|
359
359
|
cash: bigint;
|
|
360
360
|
markPrice: bigint;
|
|
361
361
|
equity: bigint;
|
|
362
|
+
/** Crystallized by the forced close; `0n` on the terminal cash sweep. */
|
|
363
|
+
realizedPnl: bigint;
|
|
362
364
|
time: number;
|
|
363
365
|
}
|
|
364
366
|
|
|
@@ -440,32 +442,6 @@ export interface Balances {
|
|
|
440
442
|
netDeposits: bigint;
|
|
441
443
|
}
|
|
442
444
|
|
|
443
|
-
/** One ranked account from the leaderboard (`/clob/leaderboard`). */
|
|
444
|
-
export interface LeaderboardEntry {
|
|
445
|
-
rank: number; // 1-based position in the full ordering
|
|
446
|
-
account: Address;
|
|
447
|
-
accountValue: bigint;
|
|
448
|
-
unrealizedPnl: bigint;
|
|
449
|
-
realizedPnl: bigint;
|
|
450
|
-
/** Net PnL = unrealized + realized — the key the board is ranked by. */
|
|
451
|
-
pnl: bigint;
|
|
452
|
-
/** pnl / (accountValue − unrealized) × 100; 0 when the basis is dust. */
|
|
453
|
-
pnlPercent: number;
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
export interface LeaderboardPage {
|
|
457
|
-
entries: LeaderboardEntry[];
|
|
458
|
-
/** Full count of ranked accounts (before paging) — for page math. */
|
|
459
|
-
total: number;
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
export interface LeaderboardQuery {
|
|
463
|
-
limit?: number;
|
|
464
|
-
offset?: number;
|
|
465
|
-
/** When set, the response also locates this account's own rank. */
|
|
466
|
-
account?: Address;
|
|
467
|
-
}
|
|
468
|
-
|
|
469
445
|
// --- query / paging types ---
|
|
470
446
|
|
|
471
447
|
export interface CandleQuery {
|
|
@@ -475,6 +451,66 @@ export interface CandleQuery {
|
|
|
475
451
|
limit?: number;
|
|
476
452
|
}
|
|
477
453
|
|
|
454
|
+
export type ActivityType = "order" | "backstop" | "bridge_transfer" | "transfer";
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* One row of an account's activity (ADR 0057): an order at its placement tick,
|
|
458
|
+
* or money that moved.
|
|
459
|
+
*
|
|
460
|
+
* `timeMs` is what the row is ordered by. Fills, cancels and amendments are not
|
|
461
|
+
* rows — they are events on the stream, and the order an `order` row carries
|
|
462
|
+
* already reflects them.
|
|
463
|
+
*
|
|
464
|
+
* Money amounts are signed from the account's side — negative left, positive
|
|
465
|
+
* arrived — and say nothing about the other end.
|
|
466
|
+
*/
|
|
467
|
+
export type ActivityEntry =
|
|
468
|
+
| { activityType: "order"; timeMs: number; order: Order }
|
|
469
|
+
| (BackstopTransfer & { activityType: "backstop"; timeMs: number })
|
|
470
|
+
| {
|
|
471
|
+
activityType: "bridge_transfer";
|
|
472
|
+
timeMs: number;
|
|
473
|
+
txHash: Hash;
|
|
474
|
+
/** Position within the transaction: one tx can bridge several amounts, so
|
|
475
|
+
* the hash alone does not identify the row. */
|
|
476
|
+
idx: number;
|
|
477
|
+
token: Address;
|
|
478
|
+
amount: bigint;
|
|
479
|
+
/** Absent when the movement settled. */
|
|
480
|
+
error?: string;
|
|
481
|
+
}
|
|
482
|
+
| {
|
|
483
|
+
activityType: "transfer";
|
|
484
|
+
timeMs: number;
|
|
485
|
+
transferId: Hash;
|
|
486
|
+
token: Address;
|
|
487
|
+
amount: bigint;
|
|
488
|
+
error?: string;
|
|
489
|
+
};
|
|
490
|
+
|
|
491
|
+
/** The activity rows that are not orders. */
|
|
492
|
+
export type MoneyActivity = Exclude<ActivityEntry, { activityType: "order" }>;
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* What the stream reported in one tick: the order transitions, and the money
|
|
496
|
+
* that moved, which is reported as the entry it produced.
|
|
497
|
+
*
|
|
498
|
+
* Discriminate with `"activityType" in event` — an order event is tagged by
|
|
499
|
+
* `kind` and a money one by `activityType`.
|
|
500
|
+
*/
|
|
501
|
+
export type ActivityEvent = OrderEvent | MoneyActivity;
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* `from` and `to` are milliseconds; `limit` is a row count, not a span of time.
|
|
505
|
+
* `types` names the kinds to keep — absent or empty keeps every kind.
|
|
506
|
+
*/
|
|
507
|
+
export interface ActivityQuery {
|
|
508
|
+
types?: ActivityType[];
|
|
509
|
+
from?: number;
|
|
510
|
+
to?: number;
|
|
511
|
+
limit?: number;
|
|
512
|
+
}
|
|
513
|
+
|
|
478
514
|
export interface OrdersQuery {
|
|
479
515
|
status?: OrderStatus;
|
|
480
516
|
orderbookId?: MarketId;
|
package/src/types/wire.ts
CHANGED
|
@@ -221,22 +221,6 @@ export interface WireBalances {
|
|
|
221
221
|
net_deposits: WireDecimal;
|
|
222
222
|
}
|
|
223
223
|
|
|
224
|
-
/** `/clob/leaderboard` (and RPC ob_getRankedPositions) share this shape. Only
|
|
225
|
-
* the aggregate PnL fields of each account's positions block are read. */
|
|
226
|
-
export interface WireRankedAccount {
|
|
227
|
-
account: Hex;
|
|
228
|
-
positions: {
|
|
229
|
-
total_unrealized_pnl: WireDecimal;
|
|
230
|
-
total_realized_pnl: WireDecimal;
|
|
231
|
-
account_value: WireDecimal;
|
|
232
|
-
};
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
export interface WireLeaderboard {
|
|
236
|
-
ranked: WireRankedAccount[];
|
|
237
|
-
total: number;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
224
|
export interface WireTrigger {
|
|
241
225
|
orderbook_id: Hex;
|
|
242
226
|
order_id: Hex;
|
|
@@ -265,6 +249,8 @@ export interface WireBackstopTransfer {
|
|
|
265
249
|
cash: WireDecimal;
|
|
266
250
|
mark_price: WireDecimal;
|
|
267
251
|
equity: WireDecimal;
|
|
252
|
+
/** Crystallized by the forced close; `"0"` on the terminal cash sweep. */
|
|
253
|
+
realized_pnl?: WireDecimal;
|
|
268
254
|
timestamp_us: number;
|
|
269
255
|
}
|
|
270
256
|
|
|
@@ -283,8 +269,9 @@ export interface WireBackstopPage {
|
|
|
283
269
|
// means something specific — noted per field.
|
|
284
270
|
|
|
285
271
|
export interface WireOrdersFrame {
|
|
286
|
-
/** The orderbook these actions happened on; constant for the frame.
|
|
287
|
-
|
|
272
|
+
/** The orderbook these actions happened on; constant for the frame. Absent on
|
|
273
|
+
* `pod_activity`, which is one frame per tick and names the book per entity. */
|
|
274
|
+
book?: Hex;
|
|
288
275
|
/** Deadline (micros) of the batch the actions **landed in**. Half of the resume cursor; `book` is the other half. */
|
|
289
276
|
batch: number;
|
|
290
277
|
/**
|
|
@@ -302,6 +289,9 @@ export interface WireOrderEntity {
|
|
|
302
289
|
id: Hex;
|
|
303
290
|
/** Creating transaction, or its parent `submitBatch` envelope. */
|
|
304
291
|
tx: Hex;
|
|
292
|
+
/** The order's book. Sent here by `pod_activity`, which covers a whole
|
|
293
|
+
* account; `pod_orders_v2` names it once on the frame instead. */
|
|
294
|
+
book?: Hex;
|
|
305
295
|
/** Index into the frame's `accts`; present iff `accts` is. */
|
|
306
296
|
a?: number;
|
|
307
297
|
n: number;
|
|
@@ -448,3 +438,100 @@ export interface WireWithdrawalDetail {
|
|
|
448
438
|
status: "claimable" | "pending" | "refused";
|
|
449
439
|
proof?: { claim_hash?: Hex | null };
|
|
450
440
|
}
|
|
441
|
+
|
|
442
|
+
// --- account activity (ADR 0057) ---
|
|
443
|
+
//
|
|
444
|
+
// `GET /clob/activity/{account}` serves the seed and `pod_activity` streams it.
|
|
445
|
+
// The seed is a union tagged by `activity_type`: the order variant flattens the
|
|
446
|
+
// orders route's `WireOrder`, and every money variant carries exactly the fields
|
|
447
|
+
// its stream event does, so the two decode through one decoder. The channel is
|
|
448
|
+
// `pod_orders_v2`'s frame for a whole account — one frame per tick, with the
|
|
449
|
+
// money the tick moved as extra event kinds.
|
|
450
|
+
|
|
451
|
+
export interface WireActivityPage {
|
|
452
|
+
activity: WireActivityEntry[];
|
|
453
|
+
next_cursor: string | null;
|
|
454
|
+
solution_now: number; // micros
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** What each money kind carries. Shared because the seed row and the stream
|
|
458
|
+
* event differ only in how they are tagged. */
|
|
459
|
+
export interface WireBackstopMoney {
|
|
460
|
+
/** Absent on the terminal cash sweep, which belongs to no market. */
|
|
461
|
+
book?: Hex;
|
|
462
|
+
size: WireDecimal; // signed
|
|
463
|
+
cash: WireDecimal; // signed
|
|
464
|
+
mark: WireDecimal;
|
|
465
|
+
equity: WireDecimal; // signed
|
|
466
|
+
pnl: WireDecimal; // signed
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
export interface WireBridgeMoney {
|
|
470
|
+
tx: Hex;
|
|
471
|
+
/** Position within the transaction: one tx can bridge several amounts, so the
|
|
472
|
+
* hash alone does not identify the row. */
|
|
473
|
+
idx: number;
|
|
474
|
+
token: Hex;
|
|
475
|
+
amount: WireDecimal; // signed
|
|
476
|
+
error?: string;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
export interface WireTransferMoney {
|
|
480
|
+
id: Hex;
|
|
481
|
+
token: Hex;
|
|
482
|
+
amount: WireDecimal; // signed
|
|
483
|
+
error?: string;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* One activity row. `ts` is what the node sorted the page by — for an order that
|
|
488
|
+
* is its **signed deadline**, not the batch it landed in.
|
|
489
|
+
*
|
|
490
|
+
* Money amounts are signed from the account's side: negative left, positive
|
|
491
|
+
* arrived, for the bridge and for a transfer alike.
|
|
492
|
+
*/
|
|
493
|
+
export type WireActivityEntry =
|
|
494
|
+
| ({ activity_type: "order"; ts: number } & WireOrder)
|
|
495
|
+
| ({ activity_type: "backstop"; ts: number } & WireBackstopMoney)
|
|
496
|
+
| ({ activity_type: "bridge_transfer"; ts: number } & WireBridgeMoney)
|
|
497
|
+
| ({ activity_type: "transfer"; ts: number } & WireTransferMoney);
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* One tick of an account's activity. No `book` — a tick covers every book the
|
|
501
|
+
* account traded on, so each entity names its own — and no `accts`, since the
|
|
502
|
+
* channel takes exactly one account.
|
|
503
|
+
*/
|
|
504
|
+
export interface WireActivityFrame {
|
|
505
|
+
/** Deadline (micros) of the batch. One frame per tick, so this alone is the
|
|
506
|
+
* resume cursor: a frame is already delivered exactly when `batch <= since`. */
|
|
507
|
+
batch: number;
|
|
508
|
+
orders: WireOrderEntity[];
|
|
509
|
+
events: (WireOrderEvent | WireMoneyEvent)[];
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** Money the tick moved, discriminated by `k` — disjoint from the order kinds,
|
|
513
|
+
* which is what lets the two share one untagged union on the wire. */
|
|
514
|
+
export type WireMoneyEvent =
|
|
515
|
+
| ({ k: "backstop" } & WireBackstopMoney)
|
|
516
|
+
| ({ k: "bridge_transfer" } & WireBridgeMoney)
|
|
517
|
+
| ({ k: "transfer" } & WireTransferMoney);
|
|
518
|
+
|
|
519
|
+
/** One `/clob/fills/{account}` row: a fill of one order in one batch. */
|
|
520
|
+
export interface WireFillRow {
|
|
521
|
+
orderbook_id: Hex;
|
|
522
|
+
order_id: Hex;
|
|
523
|
+
initial_size: WireDecimal; // signed: the order's side
|
|
524
|
+
base_amount: WireDecimal;
|
|
525
|
+
quote_amount: WireDecimal;
|
|
526
|
+
timestamp: number; // micros, the batch deadline
|
|
527
|
+
price: WireDecimal;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** One `/clob/solutions` row: a market's tick. */
|
|
531
|
+
export interface WireSolutionRow {
|
|
532
|
+
orderbook_id: Hex;
|
|
533
|
+
timestamp: number; // micros
|
|
534
|
+
clearing_price?: WireDecimal;
|
|
535
|
+
mark_price: WireDecimal;
|
|
536
|
+
funding_index?: WireDecimal;
|
|
537
|
+
}
|