@pod-network/trade-sdk 0.1.1-rc.0 → 0.3.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/dist/client.d.ts.map +1 -1
- package/dist/client.js +1 -12
- package/dist/client.js.map +1 -1
- package/dist/codec/decode.d.ts.map +1 -1
- package/dist/codec/decode.js +7 -6
- package/dist/codec/decode.js.map +1 -1
- package/dist/codec/direction.d.ts +10 -0
- package/dist/codec/direction.d.ts.map +1 -0
- package/dist/codec/direction.js +46 -0
- package/dist/codec/direction.js.map +1 -0
- package/dist/codec/orders-v2.d.ts +19 -0
- package/dist/codec/orders-v2.d.ts.map +1 -0
- package/dist/codec/orders-v2.js +200 -0
- package/dist/codec/orders-v2.js.map +1 -0
- package/dist/codec/units.d.ts +10 -0
- package/dist/codec/units.d.ts.map +1 -1
- package/dist/codec/units.js +16 -0
- package/dist/codec/units.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/sync/orders.d.ts +71 -16
- package/dist/sync/orders.d.ts.map +1 -1
- package/dist/sync/orders.js +202 -83
- package/dist/sync/orders.js.map +1 -1
- package/dist/transport/ws.d.ts +63 -1
- package/dist/transport/ws.d.ts.map +1 -1
- package/dist/transport/ws.js +82 -2
- package/dist/transport/ws.js.map +1 -1
- package/dist/types/public.d.ts +125 -9
- package/dist/types/public.d.ts.map +1 -1
- package/dist/types/wire.d.ts +104 -40
- package/dist/types/wire.d.ts.map +1 -1
- package/dist/write/index.d.ts +31 -1
- package/dist/write/index.d.ts.map +1 -1
- package/dist/write/index.js +34 -1
- package/dist/write/index.js.map +1 -1
- package/package.json +6 -3
- package/src/client.ts +1 -14
- package/src/codec/decode.ts +7 -6
- package/src/codec/direction.ts +36 -0
- package/src/codec/orders-v2.ts +222 -0
- package/src/codec/units.ts +16 -0
- package/src/index.ts +1 -1
- package/src/sync/orders.ts +203 -83
- package/src/transport/ws.ts +111 -3
- package/src/types/public.ts +139 -7
- package/src/types/wire.ts +114 -28
- package/src/write/index.ts +65 -1
package/src/sync/orders.ts
CHANGED
|
@@ -1,39 +1,97 @@
|
|
|
1
1
|
// OrderHistory: a SeriesResource<Order> seeded from the warm first page, kept
|
|
2
|
-
// live by the
|
|
3
|
-
//
|
|
2
|
+
// live by the pod_orders_v2 stream (bidder-filtered, resumed from a (batch, book)
|
|
3
|
+
// cursor), and paged backwards by cursor for deep history.
|
|
4
4
|
//
|
|
5
5
|
// Reconnect: on every (re)connect we re-seed the first page (authoritative open
|
|
6
|
-
// orders) and refresh
|
|
7
|
-
// if
|
|
6
|
+
// orders) and refresh the cursor from its watermark; the WS auto-resubscribes,
|
|
7
|
+
// and if the cursor is too old (down too long) `onError` re-seeds and
|
|
8
|
+
// resubscribes. A server-initiated close is not the same as a rejection: it
|
|
9
|
+
// reports where delivery stopped, so resuming from one is a bare `resubscribe()`
|
|
10
|
+
// with no re-seed.
|
|
8
11
|
|
|
9
|
-
import type { Address, MarketId, Order,
|
|
10
|
-
import type {
|
|
11
|
-
import {
|
|
12
|
-
import { decodeOrder } from "../codec/decode.js";
|
|
12
|
+
import type { Address, MarketId, Order, OrderEvent, OrdersQuery } from "../types/public.js";
|
|
13
|
+
import type { WireOrdersFrame } from "../types/wire.js";
|
|
14
|
+
import { applyOrdersFrame } from "../codec/orders-v2.js";
|
|
13
15
|
import { BaseResource, type ResourceHandle } from "../stores/resource.js";
|
|
14
|
-
import type
|
|
16
|
+
import { PodSubscriptionClosedError, type SubParams, type Subscription } from "../transport/ws.js";
|
|
15
17
|
import type { SeriesResource } from "./candles.js";
|
|
16
18
|
import type { SyncContext } from "./sources.js";
|
|
17
19
|
|
|
20
|
+
/**
|
|
21
|
+
* Consecutive server closes we resume from before falling back to the re-seed
|
|
22
|
+
* path. A lagged close is recoverable by resubscribing, so the fast path is the
|
|
23
|
+
* right default — but a stream that keeps closing is one we are not keeping up
|
|
24
|
+
* with, and re-seeding beats replaying a growing backlog on every attempt.
|
|
25
|
+
*/
|
|
26
|
+
const FAST_RESUMES_BEFORE_RESEED = 3;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Re-seed attempts that keep the cursor before we conclude the cursor is what the
|
|
30
|
+
* server is rejecting, drop it, and settle for streaming live.
|
|
31
|
+
*/
|
|
32
|
+
const RETRIES_BEFORE_DROPPING_CURSOR = 2;
|
|
33
|
+
|
|
34
|
+
/** The largest book id, which is what an absent `sinceBook` means. */
|
|
35
|
+
const WHOLE_BATCH = `0x${"ff".repeat(32)}` as MarketId;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Order two positions in the stream, the way the server does.
|
|
39
|
+
*
|
|
40
|
+
* A batch is delivered as one frame per book, so a position is the pair
|
|
41
|
+
* `(batch, book)` — and an absent book means the whole batch, which sorts *above*
|
|
42
|
+
* every book in it. This mirrors `already_delivered` in
|
|
43
|
+
* `node/src/rpc/orders_v2.rs`: `(frame_batch, frame_book) <= (since,
|
|
44
|
+
* since_book.unwrap_or(0xff…))`. Getting the absent case wrong turns "all of batch
|
|
45
|
+
* N" into "up to book B of batch N", which asks the server to re-send the rest.
|
|
46
|
+
*
|
|
47
|
+
* Book ids are fixed-width lowercase hex, so comparing them as strings is
|
|
48
|
+
* comparing their bytes.
|
|
49
|
+
*/
|
|
50
|
+
export function compareCursor(a: SubParams, b: SubParams): number {
|
|
51
|
+
const aBatch = a.since ?? 0;
|
|
52
|
+
const bBatch = b.since ?? 0;
|
|
53
|
+
if (aBatch !== bBatch) return aBatch < bBatch ? -1 : 1;
|
|
54
|
+
const aBook = a.sinceBook ?? WHOLE_BATCH;
|
|
55
|
+
const bBook = b.sinceBook ?? WHOLE_BATCH;
|
|
56
|
+
return aBook === bBook ? 0 : aBook < bBook ? -1 : 1;
|
|
57
|
+
}
|
|
58
|
+
|
|
18
59
|
export class OrderHistory implements SeriesResource<Order> {
|
|
19
60
|
private readonly base: BaseResource<Order[]>;
|
|
20
61
|
private handle: ResourceHandle<Order[]> | undefined;
|
|
21
62
|
private readonly byId = new Map<string, Order>();
|
|
22
63
|
private nextCursor: string | null = null;
|
|
23
64
|
private sub: Subscription | undefined;
|
|
24
|
-
private watermarkUs = 0;
|
|
25
65
|
private alive = false;
|
|
26
66
|
private _hasMore = true;
|
|
27
67
|
private _loading = false;
|
|
28
68
|
private subRetries = 0;
|
|
69
|
+
private fastResumes = 0;
|
|
29
70
|
private retryTimer?: ReturnType<typeof setTimeout>;
|
|
71
|
+
private readonly eventListeners = new Set<(events: OrderEvent[]) => void>();
|
|
72
|
+
/**
|
|
73
|
+
* Where the stream is: the last frame accepted, as the `(batch, book)` pair the
|
|
74
|
+
* channel resumes from. Replaced whole rather than patched half at a time —
|
|
75
|
+
* `sinceBook` names a book *within* `since`, so the two are one fact and a
|
|
76
|
+
* mismatched pair asks the server to skip books we never saw.
|
|
77
|
+
*/
|
|
78
|
+
private cursor: SubParams = { since: 0, sinceBook: undefined };
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Push the cursor to the transport, both halves.
|
|
82
|
+
*
|
|
83
|
+
* `update` merges, so sending `{ since }` alone would leave whatever `sinceBook` was
|
|
84
|
+
* there before — a book from an older batch beside a newer `since`, which asks the
|
|
85
|
+
* server to skip less than it should and re-send the difference.
|
|
86
|
+
*/
|
|
87
|
+
private pushCursor(): void {
|
|
88
|
+
this.sub?.update({ since: this.cursor.since, sinceBook: this.cursor.sinceBook });
|
|
89
|
+
}
|
|
30
90
|
|
|
31
91
|
constructor(
|
|
32
92
|
private readonly ctx: SyncContext,
|
|
33
93
|
private readonly account: Address,
|
|
34
94
|
private readonly query: OrdersQuery = {},
|
|
35
|
-
/** Maps a WS order's token pair to its orderbook id (see rebuild). */
|
|
36
|
-
private readonly resolveOrderbookId?: (pair: { base: Address; quote: Address }) => MarketId | undefined,
|
|
37
95
|
) {
|
|
38
96
|
this.base = new BaseResource<Order[]>((h) => {
|
|
39
97
|
this.handle = h;
|
|
@@ -59,6 +117,26 @@ export class OrderHistory implements SeriesResource<Order> {
|
|
|
59
117
|
loading(): boolean { return this._loading; }
|
|
60
118
|
destroy(): void { this.base.destroy(); }
|
|
61
119
|
|
|
120
|
+
/**
|
|
121
|
+
* Observe the transitions the stream reports, as they arrive — a frame at a time, in
|
|
122
|
+
* the order the engine caused them.
|
|
123
|
+
*
|
|
124
|
+
* The snapshot (`get`/`subscribe`) is what to render; this is what *happened*, which
|
|
125
|
+
* a snapshot cannot express: two fills in one batch are one state change, and a
|
|
126
|
+
* refused amendment is none at all. Nothing is emitted for the REST seed, so a
|
|
127
|
+
* consumer never has to filter out a backlog of history as if it were live.
|
|
128
|
+
*/
|
|
129
|
+
onEvent(listener: (events: OrderEvent[]) => void): () => void {
|
|
130
|
+
this.eventListeners.add(listener);
|
|
131
|
+
// Listening starts the stream, like subscribing does. The resource is ref-counted
|
|
132
|
+
// from `subscribe`/`ready` alone, so without holding one an event-only consumer
|
|
133
|
+
// would wait forever — and would fall silent the moment the last snapshot
|
|
134
|
+
// subscriber left, since teardown drops the websocket subscription and leaves the
|
|
135
|
+
// listeners registered.
|
|
136
|
+
const release = this.base.subscribe(() => {});
|
|
137
|
+
return () => { this.eventListeners.delete(listener); release(); };
|
|
138
|
+
}
|
|
139
|
+
|
|
62
140
|
setWindow(): void { /* order history pages by cursor, not by time window */ }
|
|
63
141
|
|
|
64
142
|
async loadOlder(): Promise<void> {
|
|
@@ -82,13 +160,27 @@ export class OrderHistory implements SeriesResource<Order> {
|
|
|
82
160
|
// --- internals ---
|
|
83
161
|
|
|
84
162
|
private async fetchFirstPage(): Promise<boolean> {
|
|
163
|
+
const before = this.cursor;
|
|
85
164
|
try {
|
|
86
165
|
const page = await this.ctx.rest.orders(this.account, { limit: this.query.limit ?? 100 });
|
|
87
166
|
if (!this.alive) return false;
|
|
88
|
-
|
|
167
|
+
// The transport resubscribes synchronously right after the `open` event that
|
|
168
|
+
// starts this fetch, so replayed frames can land while it is still in flight —
|
|
169
|
+
// and the indexer trails the stream by design. Overwriting a row the stream has
|
|
170
|
+
// already advanced would revert it, permanently: the cursor below refuses to
|
|
171
|
+
// rewind and `onFrame` drops a re-delivery, so nothing would repair it.
|
|
172
|
+
const streamMovedOn = compareCursor(this.cursor, before) > 0;
|
|
173
|
+
for (const o of page.orders) {
|
|
174
|
+
if (streamMovedOn && this.byId.has(o.id)) continue;
|
|
175
|
+
this.byId.set(o.id, o);
|
|
176
|
+
}
|
|
89
177
|
this.nextCursor = page.nextCursor;
|
|
90
178
|
this._hasMore = page.nextCursor !== null;
|
|
91
|
-
|
|
179
|
+
// Only ever forward, and a page settles whole batches, so its watermark
|
|
180
|
+
// carries no book — which makes it *ahead* of a stream position in the same
|
|
181
|
+
// batch, not equal to it.
|
|
182
|
+
const settled: SubParams = { since: page.solutionNow * 1000, sinceBook: undefined };
|
|
183
|
+
if (compareCursor(settled, this.cursor) > 0) this.cursor = settled;
|
|
92
184
|
this.rebuild();
|
|
93
185
|
return true;
|
|
94
186
|
} catch (e) {
|
|
@@ -102,104 +194,132 @@ export class OrderHistory implements SeriesResource<Order> {
|
|
|
102
194
|
if (!ok || !this.alive) return;
|
|
103
195
|
if (!this.sub) {
|
|
104
196
|
this.sub = this.ctx.ws.subscribe(
|
|
105
|
-
"
|
|
106
|
-
{ account: this.account,
|
|
107
|
-
(r) => this.
|
|
108
|
-
() => this.onSubError(),
|
|
197
|
+
"pod_orders_v2",
|
|
198
|
+
{ account: this.account, ...this.cursor },
|
|
199
|
+
(r) => this.onFrame(r),
|
|
200
|
+
(e) => this.onSubError(e),
|
|
109
201
|
);
|
|
110
202
|
} else {
|
|
111
|
-
this.
|
|
203
|
+
this.pushCursor(); // refresh for the next reconnect
|
|
112
204
|
}
|
|
113
205
|
});
|
|
114
206
|
}
|
|
115
207
|
|
|
116
208
|
/**
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
*
|
|
209
|
+
* The subscription is not running: `eth_subscribe` was rejected, or the server
|
|
210
|
+
* closed it.
|
|
211
|
+
*
|
|
212
|
+
* A resumable close needs neither a re-seed nor a delay: the server reports where
|
|
213
|
+
* it stopped, so resubscribing from that delivers exactly the frames we never got.
|
|
214
|
+
* That fast path is only taken while the socket is actually open — `resubscribe()`
|
|
215
|
+
* is a no-op otherwise, which would spend the budget without an attempt and leave
|
|
216
|
+
* nothing scheduled, and `-32021` (node shutting down) arrives exactly as the
|
|
217
|
+
* socket goes away.
|
|
218
|
+
*
|
|
219
|
+
* Everything else (a rejection, a server bug, a close with the socket already
|
|
220
|
+
* gone, or closes that keep coming) takes the slow path: backed off and capped, so
|
|
221
|
+
* a server that keeps refusing cannot spin this into a tight re-seed loop, and
|
|
222
|
+
* eventually the cursor is dropped (the likely culprit) to just stream live. Both
|
|
223
|
+
* counters reset once live data flows (`onFrame`).
|
|
121
224
|
*/
|
|
122
|
-
private onSubError(): void {
|
|
225
|
+
private onSubError(err: unknown): void {
|
|
123
226
|
if (!this.alive) return;
|
|
227
|
+
const canFastResume = err instanceof PodSubscriptionClosedError && err.resumable
|
|
228
|
+
&& this.fastResumes < FAST_RESUMES_BEFORE_RESEED && this.ctx.ws.state === "open";
|
|
229
|
+
if (canFastResume) {
|
|
230
|
+
this.fastResumes++;
|
|
231
|
+
// Adopt the server's watermark only when it is ahead of ours: it knows which
|
|
232
|
+
// frames it handed over, but a re-seed may already have carried us past it,
|
|
233
|
+
// and rewinding would re-deliver frames we have applied.
|
|
234
|
+
const reported: SubParams = { since: err.resumeSince, sinceBook: err.resumeSinceBook };
|
|
235
|
+
if (err.resumeSince !== undefined && compareCursor(reported, this.cursor) > 0) this.cursor = reported;
|
|
236
|
+
// The transport rewrote `sub.params` from the close before this ran, so without
|
|
237
|
+
// pushing our own decision back the wire resumes from the server's point
|
|
238
|
+
// regardless and the guard above protects nothing.
|
|
239
|
+
this.pushCursor();
|
|
240
|
+
this.sub?.resubscribe();
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
// The slow path, and the one that answers "what if we fell behind the server's
|
|
244
|
+
// replay buffer": `eth_subscribe` rejects a `since` older than what the buffer
|
|
245
|
+
// retains, and the prescribed recovery is to backfill over REST and resubscribe.
|
|
246
|
+
// That is what this is. `fetchFirstPage` also *replaces the cursor* with the
|
|
247
|
+
// page's watermark, so the position that was too old is gone by the first retry
|
|
248
|
+
// and the resubscribe is accepted with no gap — the server replays from the page
|
|
249
|
+
// forward. Dropping the cursor below is the backstop for when even that fresh
|
|
250
|
+
// watermark is refused (the indexer further behind than the buffer retains):
|
|
251
|
+
// live-only resubscribe, trading the unreplayable window for a working stream.
|
|
252
|
+
this.scheduleReseed();
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Back off, re-seed over REST, then resubscribe — and keep trying.
|
|
257
|
+
*
|
|
258
|
+
* The re-seed can fail too (the same node is usually behind both the stream and the
|
|
259
|
+
* indexer), and a failure has to re-arm here: not resubscribing means no further
|
|
260
|
+
* close or rejection arrives, so nothing else would ever schedule another attempt and
|
|
261
|
+
* the stream would stay down with no error surfaced. Capped, so a node that keeps
|
|
262
|
+
* refusing cannot spin this.
|
|
263
|
+
*/
|
|
264
|
+
private scheduleReseed(): void {
|
|
124
265
|
this.subRetries++;
|
|
125
266
|
const delay = Math.min(30_000, 500 * 2 ** (this.subRetries - 1));
|
|
126
267
|
if (this.retryTimer) clearTimeout(this.retryTimer);
|
|
127
268
|
this.retryTimer = setTimeout(() => {
|
|
128
269
|
void this.fetchFirstPage().then((ok) => {
|
|
129
|
-
if (!
|
|
130
|
-
|
|
270
|
+
if (!this.alive) return;
|
|
271
|
+
if (!ok) { this.scheduleReseed(); return; }
|
|
272
|
+
const tooOld = this.subRetries > RETRIES_BEFORE_DROPPING_CURSOR;
|
|
273
|
+
if (tooOld) this.sub?.update({ since: undefined, sinceBook: undefined });
|
|
274
|
+
else this.pushCursor();
|
|
131
275
|
this.sub?.resubscribe();
|
|
132
276
|
});
|
|
133
277
|
}, delay);
|
|
134
278
|
}
|
|
135
279
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
this.
|
|
141
|
-
|
|
280
|
+
/** One frame: everything that happened to one book in one auction batch. */
|
|
281
|
+
private onFrame(result: unknown): void {
|
|
282
|
+
// Live data flowing → the subscription is healthy on both paths.
|
|
283
|
+
this.subRetries = 0;
|
|
284
|
+
this.fastResumes = 0;
|
|
285
|
+
const frame = result as WireOrdersFrame;
|
|
286
|
+
if (!frame || !Array.isArray(frame.orders) || !Array.isArray(frame.events)) return;
|
|
142
287
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
const base = dec(u.base_amount);
|
|
162
|
-
const quote = dec(u.quote_amount);
|
|
163
|
-
e.fills = [...e.fills, { base, quote, price: base > 0n ? (quote * WAD) / base : 0n, time: Date.now() }];
|
|
164
|
-
}
|
|
165
|
-
break;
|
|
166
|
-
}
|
|
167
|
-
case "modified": {
|
|
168
|
-
const e = this.byId.get(u.order_id);
|
|
169
|
-
if (e) {
|
|
170
|
-
e.price = dec(u.new_price);
|
|
171
|
-
const sign = e.initialSize < 0n ? -1n : 1n;
|
|
172
|
-
e.initialSize = sign * dec(u.new_size); // new_size is an unsigned magnitude
|
|
173
|
-
}
|
|
174
|
-
break;
|
|
175
|
-
}
|
|
176
|
-
case "expired": {
|
|
177
|
-
const e = this.byId.get(u.order_id);
|
|
178
|
-
if (e) e.status = "expired";
|
|
179
|
-
break;
|
|
180
|
-
}
|
|
181
|
-
case "canceled": {
|
|
182
|
-
const e = this.byId.get(u.order_id);
|
|
183
|
-
if (e) e.status = "canceled";
|
|
184
|
-
break;
|
|
288
|
+
// Drop what we already hold. Applying a frame is not idempotent — a fill event
|
|
289
|
+
// appends to `order.fills`, and re-creating an entity resets its totals — and
|
|
290
|
+
// re-delivery is designed in: a resumed subscription replays from a cursor, and
|
|
291
|
+
// the replay boundary is a whole batch. Same predicate as the server's
|
|
292
|
+
// `already_delivered`, so client and server agree on what "already sent" means.
|
|
293
|
+
const at: SubParams = { since: frame.batch, sinceBook: frame.book };
|
|
294
|
+
if (compareCursor(at, this.cursor) <= 0) return;
|
|
295
|
+
|
|
296
|
+
const events = applyOrdersFrame(frame, this.byId, { account: this.account });
|
|
297
|
+
// A socket-level reconnect resubscribes from whatever is stored here.
|
|
298
|
+
this.cursor = at;
|
|
299
|
+
this.sub?.update(at);
|
|
300
|
+
this.rebuild();
|
|
301
|
+
// Strictly after `rebuild()`: a listener that reads the resource in response to an
|
|
302
|
+
// event must see the state that event produced, not the state before it.
|
|
303
|
+
if (events.length) {
|
|
304
|
+
for (const listener of this.eventListeners) {
|
|
305
|
+
try { listener(events); } catch { /* a listener's failure is not the stream's */ }
|
|
185
306
|
}
|
|
186
307
|
}
|
|
187
308
|
}
|
|
188
309
|
|
|
189
310
|
private rebuild(): void {
|
|
190
311
|
if (!this.handle) return;
|
|
191
|
-
// WS stream orders carry a token `pair` instead of orderbook_id — resolve
|
|
192
|
-
// it here so consumers can always filter by market. Retried every rebuild,
|
|
193
|
-
// so orders that streamed in before the markets list loaded still resolve.
|
|
194
|
-
if (this.resolveOrderbookId) {
|
|
195
|
-
for (const o of this.byId.values()) {
|
|
196
|
-
if (o.orderbookId === undefined && o.pair) o.orderbookId = this.resolveOrderbookId(o.pair);
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
312
|
let arr = [...this.byId.values()];
|
|
200
313
|
if (this.query.status) arr = arr.filter((o) => o.status === this.query.status);
|
|
201
314
|
if (this.query.orderbookId) arr = arr.filter((o) => o.orderbookId === this.query.orderbookId);
|
|
202
|
-
|
|
315
|
+
// Newest first by when the order became real. Inclusion time is the key both
|
|
316
|
+
// sources report — REST sends it alongside the signed deadline, and a frame's
|
|
317
|
+
// batch *is* it — so a REST row and a streamed row sort against each other. An
|
|
318
|
+
// order with none has not been in a batch yet, so it is newer than every order
|
|
319
|
+
// that has; the signed deadline is deliberately not a fallback, since it is a
|
|
320
|
+
// future time and would sort on a different clock.
|
|
321
|
+
const at = (o: Order) => o.includedMs ?? Number.MAX_SAFE_INTEGER;
|
|
322
|
+
arr.sort((a, b) => at(b) - at(a) || b.nonce - a.nonce);
|
|
203
323
|
this.handle.set(arr);
|
|
204
324
|
}
|
|
205
325
|
}
|
package/src/transport/ws.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import type { Address, MarketId } from "../types/public.js";
|
|
7
7
|
|
|
8
8
|
export type Channel =
|
|
9
|
-
| "pod_orderbook" | "
|
|
9
|
+
| "pod_orderbook" | "pod_orders_v2" | "pod_candles"
|
|
10
10
|
| "pod_markets" | "pod_positions" | "pod_triggers";
|
|
11
11
|
|
|
12
12
|
export interface SubParams {
|
|
@@ -14,6 +14,17 @@ export interface SubParams {
|
|
|
14
14
|
account?: Address;
|
|
15
15
|
depth?: number;
|
|
16
16
|
since?: number; // micros (solution time)
|
|
17
|
+
/**
|
|
18
|
+
* `pod_orders_v2` only: the `book` of the last frame accepted at `since`,
|
|
19
|
+
* completing the resume cursor.
|
|
20
|
+
*
|
|
21
|
+
* One batch settles many orderbooks and is delivered as one frame each, so a
|
|
22
|
+
* client can hold part of a batch, and `since` alone cannot express that
|
|
23
|
+
* position. With this set, replay skips every book at or below it within
|
|
24
|
+
* `since`, then delivers later batches whole. Omitted means the whole of
|
|
25
|
+
* `since` arrived — what `since` means on every other channel.
|
|
26
|
+
*/
|
|
27
|
+
sinceBook?: MarketId;
|
|
17
28
|
}
|
|
18
29
|
|
|
19
30
|
export interface Subscription {
|
|
@@ -38,11 +49,84 @@ export interface WsClientOptions {
|
|
|
38
49
|
idleTimeoutMs?: number;
|
|
39
50
|
}
|
|
40
51
|
|
|
52
|
+
/** What the server sends in a close notification's `params.error`. */
|
|
53
|
+
interface WireCloseError {
|
|
54
|
+
code?: unknown;
|
|
55
|
+
message?: unknown;
|
|
56
|
+
data?: {
|
|
57
|
+
resumable?: unknown;
|
|
58
|
+
resume_since?: unknown;
|
|
59
|
+
resume_since_book?: unknown;
|
|
60
|
+
missed?: unknown;
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const asNumber = (v: unknown) => (typeof v === "number" ? v : undefined);
|
|
65
|
+
const asString = (v: unknown) => (typeof v === "string" ? v : undefined);
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The server ended a subscription on its own initiative.
|
|
69
|
+
*
|
|
70
|
+
* Delivered to `subscribe`'s `onError`. The subscription is gone server-side, and
|
|
71
|
+
* the connection stays open — so nothing else will nudge you, and no further
|
|
72
|
+
* updates arrive on it. On a resumable close the client has already advanced the
|
|
73
|
+
* subscription's `since` to `resumeSince`, so restarting it is one call:
|
|
74
|
+
*
|
|
75
|
+
* ```ts
|
|
76
|
+
* const sub = ws.subscribe("pod_orders_v2", { account }, onFrame, (err) => {
|
|
77
|
+
* if (err instanceof PodSubscriptionClosedError && err.resumable) sub.resubscribe();
|
|
78
|
+
* });
|
|
79
|
+
* ```
|
|
80
|
+
*
|
|
81
|
+
* `resumable` is false for a server bug (`-32023`) and for any close this version
|
|
82
|
+
* cannot parse: resubscribing immediately would most likely reproduce it, so back
|
|
83
|
+
* off or report it instead.
|
|
84
|
+
*/
|
|
85
|
+
export class PodSubscriptionClosedError extends Error {
|
|
86
|
+
/** -32020 lagged, -32021 node shutting down, -32022 send timeout, -32023 server bug. */
|
|
87
|
+
readonly code: number;
|
|
88
|
+
/** Whether resubscribing recovers the stream. */
|
|
89
|
+
readonly resumable: boolean;
|
|
90
|
+
/**
|
|
91
|
+
* Solution time (micros) the stream is square on. Absent when the subscription
|
|
92
|
+
* had not yet taken a whole tick.
|
|
93
|
+
*/
|
|
94
|
+
readonly resumeSince?: number;
|
|
95
|
+
/**
|
|
96
|
+
* `pod_orders_v2` only: the last book of `resumeSince` that was delivered, when
|
|
97
|
+
* that batch was only partly delivered. Absent means the batch landed whole.
|
|
98
|
+
*/
|
|
99
|
+
readonly resumeSinceBook?: MarketId;
|
|
100
|
+
/** `-32020` only: how many ticks the broadcast dropped. */
|
|
101
|
+
readonly missed?: number;
|
|
102
|
+
/** The raw `params.error`, for fields this version does not map. */
|
|
103
|
+
readonly raw: unknown;
|
|
104
|
+
|
|
105
|
+
constructor(raw: WireCloseError) {
|
|
106
|
+
super(asString(raw.message) ?? "subscription closed by the server");
|
|
107
|
+
const data = raw.data ?? {};
|
|
108
|
+
this.name = "PodSubscriptionClosedError";
|
|
109
|
+
this.code = asNumber(raw.code) ?? 0;
|
|
110
|
+
// Anything other than an explicit `true` counts as not resumable: retrying a
|
|
111
|
+
// close we failed to understand can hot-loop, which is the worse failure.
|
|
112
|
+
this.resumable = data.resumable === true;
|
|
113
|
+
this.resumeSince = asNumber(data.resume_since);
|
|
114
|
+
this.resumeSinceBook = asString(data.resume_since_book) as MarketId | undefined;
|
|
115
|
+
this.missed = asNumber(data.missed);
|
|
116
|
+
this.raw = raw;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
41
120
|
interface LogicalSub {
|
|
42
121
|
channel: Channel;
|
|
43
122
|
params: SubParams;
|
|
44
123
|
onMessage: (result: unknown) => void;
|
|
45
|
-
|
|
124
|
+
/**
|
|
125
|
+
* `eth_subscribe` was rejected (e.g. `since` too old), or the server closed a
|
|
126
|
+
* live subscription — the latter is a {@link PodSubscriptionClosedError}.
|
|
127
|
+
* Either way the subscription is not running; `resubscribe()` starts a new one.
|
|
128
|
+
*/
|
|
129
|
+
onError?: (err: unknown) => void;
|
|
46
130
|
subId?: string; // server-assigned, when active
|
|
47
131
|
}
|
|
48
132
|
|
|
@@ -199,6 +283,7 @@ export class PodWsClient {
|
|
|
199
283
|
if (p.account) out.account = p.account; // server aliases to `bidder`
|
|
200
284
|
if (p.depth !== undefined) out.depth = p.depth;
|
|
201
285
|
if (p.since !== undefined) out.since = p.since;
|
|
286
|
+
if (p.sinceBook !== undefined) out.since_book = p.sinceBook;
|
|
202
287
|
return out;
|
|
203
288
|
}
|
|
204
289
|
|
|
@@ -239,7 +324,30 @@ export class PodWsClient {
|
|
|
239
324
|
try { msg = JSON.parse(text); } catch { return; }
|
|
240
325
|
if (msg && msg.method === "eth_subscription" && msg.params) {
|
|
241
326
|
const sub = this.bySubId.get(msg.params.subscription);
|
|
242
|
-
if (sub)
|
|
327
|
+
if (!sub) return;
|
|
328
|
+
// A close carries `error` where an update carries `result`; dispatching
|
|
329
|
+
// one as an update would hand the owner `undefined`.
|
|
330
|
+
if (msg.params.error) {
|
|
331
|
+
this.bySubId.delete(msg.params.subscription);
|
|
332
|
+
sub.subId = undefined; // server already dropped it; don't unsubscribe
|
|
333
|
+
const closed = new PodSubscriptionClosedError(msg.params.error as WireCloseError);
|
|
334
|
+
// Advance the cursor before anyone can act on the close. The sub stays
|
|
335
|
+
// in `subs`, so a later socket reconnect re-subscribes it from
|
|
336
|
+
// `onopen` — with the pre-close `since` unless it is moved here, which
|
|
337
|
+
// is the gap the close frame exists to prevent. Doing it here also
|
|
338
|
+
// means `resubscribe()` alone resumes correctly.
|
|
339
|
+
if (closed.resumable && closed.resumeSince !== undefined) {
|
|
340
|
+
// Both halves, together. A close with no `resume_since_book` says the
|
|
341
|
+
// batch landed whole, so the stored book must be cleared rather than
|
|
342
|
+
// carried over: it belongs to an older batch, and leaving it would
|
|
343
|
+
// ask the server to skip books inside the new one.
|
|
344
|
+
sub.params = { ...sub.params, since: closed.resumeSince, sinceBook: closed.resumeSinceBook };
|
|
345
|
+
}
|
|
346
|
+
if (sub.onError) sub.onError(closed);
|
|
347
|
+
else this.emit("error", closed);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
sub.onMessage(msg.params.result);
|
|
243
351
|
return;
|
|
244
352
|
}
|
|
245
353
|
if (msg && msg.id !== undefined && this.pending.has(msg.id)) {
|