@pod-network/trade-sdk 0.13.0 → 0.15.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 +7 -3
- package/dist/client.d.ts +5 -5
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +3 -16
- package/dist/client.js.map +1 -1
- package/dist/codec/activity.d.ts +15 -10
- package/dist/codec/activity.d.ts.map +1 -1
- package/dist/codec/activity.js +166 -31
- package/dist/codec/activity.js.map +1 -1
- package/dist/codec/decode.d.ts +2 -14
- package/dist/codec/decode.d.ts.map +1 -1
- package/dist/codec/decode.js +2 -66
- package/dist/codec/decode.js.map +1 -1
- package/dist/codec/orders-v2.d.ts +16 -9
- package/dist/codec/orders-v2.d.ts.map +1 -1
- package/dist/codec/orders-v2.js +6 -16
- package/dist/codec/orders-v2.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/sync/activity.d.ts +19 -28
- package/dist/sync/activity.d.ts.map +1 -1
- package/dist/sync/activity.js +141 -167
- package/dist/sync/activity.js.map +1 -1
- package/dist/sync/orders.js +4 -4
- package/dist/sync/orders.js.map +1 -1
- package/dist/sync/pnl-history.d.ts.map +1 -1
- package/dist/sync/pnl-history.js +14 -9
- package/dist/sync/pnl-history.js.map +1 -1
- package/dist/transport/rest.d.ts +11 -12
- package/dist/transport/rest.d.ts.map +1 -1
- package/dist/transport/rest.js +11 -13
- package/dist/transport/rest.js.map +1 -1
- package/dist/transport/ws.d.ts +1 -3
- package/dist/transport/ws.d.ts.map +1 -1
- package/dist/transport/ws.js.map +1 -1
- package/dist/types/public.d.ts +84 -22
- package/dist/types/public.d.ts.map +1 -1
- package/dist/types/wire.d.ts +69 -63
- package/dist/types/wire.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/client.ts +8 -11
- package/src/codec/activity.ts +167 -41
- package/src/codec/decode.ts +7 -74
- package/src/codec/orders-v2.ts +11 -26
- package/src/index.ts +2 -1
- package/src/sync/activity.ts +141 -167
- package/src/sync/orders.ts +4 -4
- package/src/sync/pnl-history.ts +13 -7
- package/src/transport/rest.ts +21 -21
- package/src/transport/ws.ts +1 -3
- package/src/types/public.ts +89 -20
- package/src/types/wire.ts +57 -65
package/src/sync/activity.ts
CHANGED
|
@@ -1,95 +1,47 @@
|
|
|
1
|
-
//
|
|
2
|
-
// widened to the money the account moved. Seeded from the first REST page, kept
|
|
3
|
-
// live by `pod_activity`, paged backwards by cursor.
|
|
4
|
-
//
|
|
5
|
-
// The cursor is the batch alone. `pod_activity` sends one frame per tick,
|
|
6
|
-
// covering every book, so a frame is already delivered exactly when its batch is
|
|
7
|
-
// at or below `since` — there is no `sinceBook` to resume inside a tick with.
|
|
1
|
+
// `pod_activity` sends one batch per tick, so the batch alone is the resume cursor (ADR 0057).
|
|
8
2
|
|
|
9
3
|
import type {
|
|
10
|
-
ActivityEntry, ActivityEvent, ActivityQuery,
|
|
4
|
+
ActivityEntry, ActivityEvent, ActivityQuery, ActivityType, Address, Order, OrderEventKind,
|
|
11
5
|
} from "../types/public.js";
|
|
12
|
-
import type {
|
|
13
|
-
import {
|
|
14
|
-
import { msToUs
|
|
6
|
+
import type { WireActivityEntry } from "../types/wire.js";
|
|
7
|
+
import { foldActivityBatch } from "../codec/activity.js";
|
|
8
|
+
import { msToUs } from "../codec/units.js";
|
|
15
9
|
import { BaseResource, type ResourceHandle } from "../stores/resource.js";
|
|
10
|
+
import type { ActivityPage } from "../transport/rest.js";
|
|
16
11
|
import type { SubParams } from "../transport/ws.js";
|
|
17
12
|
import type { SeriesResource } from "./candles.js";
|
|
18
13
|
import type { SyncContext } from "./sources.js";
|
|
19
|
-
import {
|
|
14
|
+
import { ResumableStream } from "./stream.js";
|
|
20
15
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
* `keep()` and the client's memo key cannot read the same query three ways.
|
|
24
|
-
*/
|
|
25
|
-
export function normalizeActivityQuery(query: ActivityQuery = {}): ActivityQuery {
|
|
26
|
-
return query.types?.length ? query : { ...query, types: undefined };
|
|
16
|
+
export interface ActivityView extends SeriesResource<ActivityEntry> {
|
|
17
|
+
onEvent(listener: (events: ActivityEvent[]) => void): () => void;
|
|
27
18
|
}
|
|
28
19
|
|
|
29
|
-
/**
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* A money row's identity, read off the row itself — so the same row keys the same
|
|
34
|
-
* whichever page it arrives on and however many of its kind share its tick. A
|
|
35
|
-
* backstop leg has no id of its own, but a sweep touches each market once.
|
|
36
|
-
*/
|
|
37
|
-
function moneyKey(entry: MoneyActivity): string {
|
|
38
|
-
switch (entry.activityType) {
|
|
39
|
-
case "transfer": return `transfer:${entry.transferId}`;
|
|
40
|
-
case "bridge_transfer": return `bridge:${entry.txHash}:${entry.idx}`;
|
|
41
|
-
case "backstop": return `backstop:${entry.timeMs}:${entry.orderbookId ?? "cash"}`;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
const cmp = (a: string, b: string): number => a < b ? -1 : a > b ? 1 : 0;
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Separate two rows the tick and the ordinal cannot. Insertion order would do it
|
|
49
|
-
* for one source alone, but a tick that arrives as a frame and a tick that arrives
|
|
50
|
-
* as a page are built in different orders, and a reload must not reshuffle the list.
|
|
51
|
-
*/
|
|
52
|
-
function tiebreak(a: ActivityEntry, b: ActivityEntry): number {
|
|
53
|
-
if (a.activityType === "order" && b.activityType === "order") {
|
|
54
|
-
return b.order.nonce - a.order.nonce || cmp(a.order.id, b.order.id);
|
|
55
|
-
}
|
|
56
|
-
// Equal ordinals, so neither is an order.
|
|
57
|
-
return cmp(moneyKey(a as MoneyActivity), moneyKey(b as MoneyActivity));
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export class ActivityHistory implements SeriesResource<ActivityEntry> {
|
|
20
|
+
/** One account's whole feed: the one subscription, batch map and paging state its views share. */
|
|
21
|
+
export class ActivityHistory implements ActivityView {
|
|
61
22
|
private readonly base: BaseResource<ActivityEntry[]>;
|
|
62
23
|
private handle: ResourceHandle<ActivityEntry[]> | undefined;
|
|
24
|
+
/** Every batch's rows, from either source; what dedupes one against the other. */
|
|
25
|
+
private readonly batches = new Map<number, ActivityEntry[]>();
|
|
63
26
|
private readonly orders = new Map<string, Order>();
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
* it: the node times an order by its signed deadline, which no frame carries, so
|
|
67
|
-
* neither a later frame nor a re-seed must be able to retime a row already placed.
|
|
68
|
-
*/
|
|
69
|
-
private readonly orderTimeMs = new Map<string, number>();
|
|
70
|
-
/** The money rows, by {@link moneyKey}. */
|
|
71
|
-
private readonly money = new Map<string, ActivityEntry>();
|
|
72
|
-
private nextCursor: string | null = null;
|
|
73
|
-
private painted = false;
|
|
27
|
+
private rows: ActivityEntry[] = [];
|
|
28
|
+
private nextUs: number | null = null;
|
|
74
29
|
private seedGen = 0;
|
|
75
30
|
private _hasMore = true;
|
|
76
31
|
private _loading = false;
|
|
77
32
|
private readonly eventListeners = new Set<(events: ActivityEvent[]) => void>();
|
|
78
33
|
private readonly stream: ResumableStream;
|
|
79
|
-
|
|
80
|
-
private readonly query: ActivityQuery;
|
|
34
|
+
private readonly views = new Map<string, FilteredActivity>();
|
|
81
35
|
|
|
82
36
|
constructor(
|
|
83
37
|
private readonly ctx: SyncContext,
|
|
84
38
|
private readonly account: Address,
|
|
85
|
-
query: ActivityQuery = {},
|
|
86
39
|
) {
|
|
87
|
-
this.query = normalizeActivityQuery(query);
|
|
88
40
|
this.stream = new ResumableStream({
|
|
89
41
|
ws: ctx.ws,
|
|
90
42
|
channel: "pod_activity",
|
|
91
43
|
params: { account },
|
|
92
|
-
reseed: () => this.
|
|
44
|
+
reseed: () => this.seed(),
|
|
93
45
|
onFrame: (r) => this.onFrame(r),
|
|
94
46
|
});
|
|
95
47
|
this.base = new BaseResource<ActivityEntry[]>((h) => {
|
|
@@ -110,67 +62,73 @@ export class ActivityHistory implements SeriesResource<ActivityEntry> {
|
|
|
110
62
|
loading(): boolean { return this._loading; }
|
|
111
63
|
destroy(): void { this.base.destroy(); }
|
|
112
64
|
|
|
65
|
+
/** The rows of `types` whose `timeMs` is within inclusive `from`/`to`. */
|
|
66
|
+
view(query: ActivityQuery): ActivityView {
|
|
67
|
+
// An empty `types` is no filter; sorted, since key order is an argument's accident.
|
|
68
|
+
const q = query.types?.length ? query : { ...query, types: undefined };
|
|
69
|
+
const key = JSON.stringify(q, Object.keys(q).sort());
|
|
70
|
+
let view = this.views.get(key);
|
|
71
|
+
if (!view) this.views.set(key, view = new FilteredActivity(this, q));
|
|
72
|
+
return view;
|
|
73
|
+
}
|
|
74
|
+
|
|
113
75
|
/**
|
|
114
76
|
* Observe what the stream reported, a tick at a time: the order transitions and
|
|
115
|
-
* the money that moved. Nothing is emitted for
|
|
77
|
+
* the money that moved. Nothing is emitted for REST pages.
|
|
116
78
|
*/
|
|
117
79
|
onEvent(listener: (events: ActivityEvent[]) => void): () => void {
|
|
118
80
|
this.eventListeners.add(listener);
|
|
119
|
-
// Listening starts the stream, like subscribing does
|
|
120
|
-
// ref-counted from `subscribe`/`ready` alone.
|
|
81
|
+
// Listening starts the stream, like subscribing does.
|
|
121
82
|
const release = this.base.subscribe(() => {});
|
|
122
83
|
return () => { this.eventListeners.delete(listener); release(); };
|
|
123
84
|
}
|
|
124
85
|
|
|
125
|
-
setWindow(): void { /* activity pages by
|
|
86
|
+
setWindow(): void { /* activity pages by batch, not by time window */ }
|
|
126
87
|
|
|
127
88
|
async loadOlder(): Promise<void> {
|
|
128
|
-
if (!this.handle ||
|
|
89
|
+
if (!this.handle || this.nextUs === null || this._loading) return;
|
|
129
90
|
this._loading = true;
|
|
130
91
|
this.rebuild();
|
|
131
92
|
try {
|
|
132
|
-
const page = await this.ctx.rest.activity(this.account, {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
this.
|
|
137
|
-
this.nextCursor = page.nextCursor;
|
|
138
|
-
this._hasMore = page.nextCursor !== null;
|
|
93
|
+
const page = await this.ctx.rest.activity(this.account, { toUs: this.nextUs });
|
|
94
|
+
this.store([page]);
|
|
95
|
+
this.nextUs = page.nextUs;
|
|
96
|
+
this._hasMore = page.nextUs !== null;
|
|
97
|
+
this.restack();
|
|
139
98
|
} finally {
|
|
140
99
|
this._loading = false;
|
|
141
100
|
this.rebuild();
|
|
142
101
|
}
|
|
143
102
|
}
|
|
144
103
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
private restQuery() {
|
|
148
|
-
return { ...this.query, limit: this.query.limit ?? 100 };
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
private async fetchFirstPage(): Promise<boolean> {
|
|
104
|
+
private async seed(): Promise<boolean> {
|
|
152
105
|
const gen = ++this.seedGen;
|
|
153
|
-
const
|
|
106
|
+
const since = this.stream.cursor.since;
|
|
107
|
+
const stale = () => !this.stream.running || gen !== this.seedGen;
|
|
154
108
|
try {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
// Paging is the consumer's position in history, not the seed's: a reconnect
|
|
165
|
-
// re-paints the first page, and taking its cursor again would hand back pages
|
|
166
|
-
// `loadOlder` has already walked past.
|
|
167
|
-
if (!this.painted) {
|
|
168
|
-
this.painted = true;
|
|
169
|
-
this.nextCursor = page.nextCursor;
|
|
170
|
-
this._hasMore = page.nextCursor !== null;
|
|
109
|
+
if (since === undefined) {
|
|
110
|
+
const page = await this.ctx.rest.activity(this.account);
|
|
111
|
+
if (stale()) return false;
|
|
112
|
+
this.store([page]);
|
|
113
|
+
this.nextUs = page.nextUs;
|
|
114
|
+
this._hasMore = page.nextUs !== null;
|
|
115
|
+
this.restack();
|
|
116
|
+
this.stream.raise({ since: msToUs(page.solutionNow) });
|
|
117
|
+
return true;
|
|
171
118
|
}
|
|
172
|
-
|
|
173
|
-
|
|
119
|
+
// A reconnect: fill the gap above the cursor, and keep the consumer's paging position.
|
|
120
|
+
const fromUs = since + 1;
|
|
121
|
+
let toUs: number | undefined;
|
|
122
|
+
const pages: ActivityPage[] = [];
|
|
123
|
+
do {
|
|
124
|
+
const page = await this.ctx.rest.activity(this.account, { fromUs, toUs });
|
|
125
|
+
if (stale()) return false;
|
|
126
|
+
pages.push(page);
|
|
127
|
+
toUs = page.nextUs ?? undefined;
|
|
128
|
+
} while (toUs !== undefined);
|
|
129
|
+
this.store(pages);
|
|
130
|
+
this.restack();
|
|
131
|
+
for (const page of pages) this.stream.raise({ since: msToUs(page.solutionNow) });
|
|
174
132
|
return true;
|
|
175
133
|
} catch (e) {
|
|
176
134
|
// Only before the first paint: an account whose history is genuinely empty has
|
|
@@ -180,46 +138,33 @@ export class ActivityHistory implements SeriesResource<ActivityEntry> {
|
|
|
180
138
|
}
|
|
181
139
|
}
|
|
182
140
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
// carries the node's row time for an order the stream already placed by its
|
|
190
|
-
// batch, and taking it would move the row on every reconnect.
|
|
191
|
-
if (!this.orderTimeMs.has(entry.order.id)) this.orderTimeMs.set(entry.order.id, entry.timeMs);
|
|
192
|
-
continue;
|
|
193
|
-
}
|
|
194
|
-
const key = moneyKey(entry);
|
|
195
|
-
if (!this.money.has(key)) this.money.set(key, entry);
|
|
141
|
+
/** Oldest batch first, so transitions to held orders land in order; a batch already held is skipped. */
|
|
142
|
+
private store(pages: ActivityPage[]): void {
|
|
143
|
+
const fresh = pages.flatMap((p) => p.batches).filter(([batchUs]) => !this.batches.has(batchUs));
|
|
144
|
+
const pageOrders = new Set(fresh.flatMap(([, entries]) => entries.flatMap((e) => (e.k === "order" ? [e.order_id] : []))));
|
|
145
|
+
for (const [batchUs, entries] of fresh.sort((a, b) => a[0] - b[0])) {
|
|
146
|
+
this.batches.set(batchUs, foldActivityBatch(batchUs, entries, this.orders, { pageOrders }).rows);
|
|
196
147
|
}
|
|
197
148
|
}
|
|
198
149
|
|
|
199
|
-
/** One frame: everything that happened to the account in one auction batch. */
|
|
200
150
|
private onFrame(result: unknown): void {
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
const
|
|
151
|
+
if (!result || typeof result !== "object") return;
|
|
152
|
+
const keys = Object.keys(result);
|
|
153
|
+
if (keys.length !== 1) return;
|
|
154
|
+
const key = keys[0]!;
|
|
155
|
+
const entries = (result as Record<string, unknown>)[key];
|
|
156
|
+
const batchUs = Number(key);
|
|
157
|
+
if (!Array.isArray(entries) || !Number.isSafeInteger(batchUs)) return;
|
|
158
|
+
// Folding is not idempotent (events would be reported twice) and a resume replays from the cursor.
|
|
159
|
+
const at: SubParams = { since: batchUs };
|
|
206
160
|
if (this.stream.delivered(at)) return;
|
|
207
|
-
const kept = this.keep(frame);
|
|
208
|
-
if (!kept) return;
|
|
209
|
-
|
|
210
|
-
const entries: ActivityEntry[] = [];
|
|
211
|
-
const events = applyActivityFrame(kept, { orders: this.orders, entries }, {
|
|
212
|
-
account: this.account,
|
|
213
|
-
});
|
|
214
|
-
// An order the stream is the first to report is timed by its batch; one the
|
|
215
|
-
// seed already placed keeps the time the node gave it.
|
|
216
|
-
const batchMs = usToMs(kept.batch);
|
|
217
|
-
for (const o of kept.orders) if (!this.orderTimeMs.has(o.id)) this.orderTimeMs.set(o.id, batchMs);
|
|
218
|
-
this.absorb(entries, false);
|
|
219
161
|
this.stream.advance(at);
|
|
162
|
+
if (!entries.length || this.batches.has(batchUs)) return;
|
|
163
|
+
const { rows, events } = foldActivityBatch(batchUs, entries as WireActivityEntry[], this.orders, "stream");
|
|
164
|
+
this.batches.set(batchUs, rows);
|
|
165
|
+
this.rows = [...rows, ...this.rows];
|
|
166
|
+
// Listeners run after rebuild() so one that reads the resource sees what the event produced.
|
|
220
167
|
this.rebuild();
|
|
221
|
-
// Strictly after `rebuild()`: a listener that reads the resource in response to an
|
|
222
|
-
// event must see the state that event produced.
|
|
223
168
|
if (events.length) {
|
|
224
169
|
for (const listener of this.eventListeners) {
|
|
225
170
|
try { listener(events); } catch { /* a listener's failure is not the stream's */ }
|
|
@@ -227,40 +172,69 @@ export class ActivityHistory implements SeriesResource<ActivityEntry> {
|
|
|
227
172
|
}
|
|
228
173
|
}
|
|
229
174
|
|
|
230
|
-
/**
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
private keep(frame: WireActivityFrame): WireActivityFrame | undefined {
|
|
235
|
-
const { types, from, to } = this.query;
|
|
236
|
-
if (from !== undefined && frame.batch < msToUs(from)) return undefined;
|
|
237
|
-
if (to !== undefined && frame.batch >= msToUs(to)) return undefined;
|
|
238
|
-
if (!types) return frame;
|
|
239
|
-
const want = new Set<string>(types);
|
|
240
|
-
return {
|
|
241
|
-
...frame,
|
|
242
|
-
// The order events index `orders`, so the two are kept or dropped together.
|
|
243
|
-
orders: want.has("order") ? frame.orders : [],
|
|
244
|
-
events: frame.events.filter((e) => want.has(isMoney(e.k) ? e.k : "order")),
|
|
245
|
-
};
|
|
175
|
+
/** Rows newest batch first, wire order within a batch. */
|
|
176
|
+
private restack(): void {
|
|
177
|
+
this.rows = [...this.batches.keys()].sort((a, b) => b - a).flatMap((b) => this.batches.get(b)!);
|
|
178
|
+
this.rebuild();
|
|
246
179
|
}
|
|
247
180
|
|
|
248
181
|
private rebuild(): void {
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
182
|
+
this.handle?.set(this.rows.slice());
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const EVENT_TYPE: Record<OrderEventKind, ActivityType> = {
|
|
187
|
+
new: "order", reject: "order", modify_reject: "modify_reject", cancel_reject: "cancel_reject",
|
|
188
|
+
fill: "fill", modify: "modify", cancel: "termination", expire: "termination",
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
class FilteredActivity implements ActivityView {
|
|
192
|
+
private readonly want: Set<ActivityType> | undefined;
|
|
193
|
+
private held: ActivityEntry[] | undefined;
|
|
194
|
+
private shown: ActivityEntry[] | undefined;
|
|
195
|
+
|
|
196
|
+
constructor(private readonly parent: ActivityHistory, private readonly query: ActivityQuery) {
|
|
197
|
+
this.want = query.types && new Set(query.types);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
get(): ActivityEntry[] | undefined {
|
|
201
|
+
const rows = this.parent.get();
|
|
202
|
+
if (rows !== this.held) {
|
|
203
|
+
this.held = rows;
|
|
204
|
+
this.shown = rows?.filter((r) => this.keeps(r));
|
|
258
205
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
206
|
+
return this.shown;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
subscribe(listener: () => void): () => void { return this.parent.subscribe(listener); }
|
|
210
|
+
async ready(): Promise<ActivityEntry[]> { return (await this.parent.ready()).filter((r) => this.keeps(r)); }
|
|
211
|
+
get error(): Error | undefined { return this.parent.error; }
|
|
212
|
+
loading(): boolean { return this.parent.loading(); }
|
|
213
|
+
setWindow(): void { /* a view's window is its query */ }
|
|
214
|
+
|
|
215
|
+
hasMore(): boolean {
|
|
216
|
+
const oldest = this.parent.get()?.at(-1)?.timeMs;
|
|
217
|
+
const floor = this.query.from;
|
|
218
|
+
return this.parent.hasMore() && (floor === undefined || oldest === undefined || oldest > floor);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async loadOlder(): Promise<void> {
|
|
222
|
+
if (this.hasMore()) await this.parent.loadOlder();
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
onEvent(listener: (events: ActivityEvent[]) => void): () => void {
|
|
226
|
+
const want = this.want;
|
|
227
|
+
if (!want) return this.parent.onEvent(listener);
|
|
228
|
+
return this.parent.onEvent((events) => {
|
|
229
|
+
const kept = events.filter((e) => want.has("activityType" in e ? e.activityType : EVENT_TYPE[e.kind]));
|
|
230
|
+
if (kept.length) listener(kept);
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
private keeps(r: ActivityEntry): boolean {
|
|
235
|
+
const { from, to } = this.query;
|
|
236
|
+
if (from !== undefined && r.timeMs < from) return false;
|
|
237
|
+
if (to !== undefined && r.timeMs > to) return false;
|
|
238
|
+
return !this.want || this.want.has(r.activityType);
|
|
265
239
|
}
|
|
266
240
|
}
|
package/src/sync/orders.ts
CHANGED
|
@@ -145,10 +145,10 @@ export class OrderHistory implements SeriesResource<Order> {
|
|
|
145
145
|
const frame = result as WireOrdersFrame;
|
|
146
146
|
if (!frame || !Array.isArray(frame.orders) || !Array.isArray(frame.events)) return;
|
|
147
147
|
|
|
148
|
-
// Drop what we already hold. Applying a frame is not idempotent —
|
|
149
|
-
//
|
|
150
|
-
//
|
|
151
|
-
//
|
|
148
|
+
// Drop what we already hold. Applying a frame is not idempotent — re-creating an
|
|
149
|
+
// entity resets its totals, and events would be reported twice — and re-delivery is
|
|
150
|
+
// designed in: a resumed subscription replays from a cursor, and the replay boundary
|
|
151
|
+
// is a whole batch.
|
|
152
152
|
const at: SubParams = { since: frame.batch, sinceBook: frame.book };
|
|
153
153
|
if (this.stream.delivered(at)) return;
|
|
154
154
|
|
package/src/sync/pnl-history.ts
CHANGED
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
|
|
14
14
|
import type { Address, MarketId, MoneyActivity } from "../types/public.js";
|
|
15
15
|
import { div, mul } from "../codec/fixed.js";
|
|
16
|
-
import { dec } from "../codec/units.js";
|
|
16
|
+
import { dec, usToMs } from "../codec/units.js";
|
|
17
|
+
import { decodeActivityEntry } from "../codec/activity.js";
|
|
17
18
|
import type { WireFillRow, WireSolutionRow } from "../types/wire.js";
|
|
18
19
|
import { rpc, type RpcOptions } from "../transport/jsonrpc.js";
|
|
19
20
|
import { PodHttpError, type PodRestClient } from "../transport/rest.js";
|
|
@@ -380,15 +381,20 @@ const FLOW_TYPES = ["backstop", "bridge_transfer", "transfer"] as const;
|
|
|
380
381
|
|
|
381
382
|
/** Money movements in [fromUs, toUs) from the activity feed, or `undefined`
|
|
382
383
|
* when the node does not serve it. */
|
|
383
|
-
async function drainFlows(rest: PodRestClient, account: Address, fromUs: number,
|
|
384
|
+
async function drainFlows(rest: PodRestClient, account: Address, fromUs: number, toUsExclusive: number): Promise<MoneyActivity[] | undefined> {
|
|
384
385
|
const out: MoneyActivity[] = [];
|
|
385
|
-
let
|
|
386
|
+
let toUs: number | null = toUsExclusive - 1;
|
|
386
387
|
try {
|
|
387
388
|
do {
|
|
388
|
-
const page = await rest.activity(account, { types: [...FLOW_TYPES],
|
|
389
|
-
for (const
|
|
390
|
-
|
|
391
|
-
|
|
389
|
+
const page = await rest.activity(account, { types: [...FLOW_TYPES], fromUs, toUs, limit: 500 });
|
|
390
|
+
for (const [batchUs, entries] of page.batches) {
|
|
391
|
+
for (const e of entries) {
|
|
392
|
+
if (e.k !== "backstop" && e.k !== "bridge_transfer" && e.k !== "transfer") continue;
|
|
393
|
+
out.push(decodeActivityEntry(e, usToMs(batchUs)) as MoneyActivity);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
toUs = page.nextUs;
|
|
397
|
+
} while (toUs !== null);
|
|
392
398
|
} catch (e) {
|
|
393
399
|
// Only a missing route means the node has no feed. Anything else (a 503,
|
|
394
400
|
// a timeout) must fail the run, or the range would be cached without
|
package/src/transport/rest.ts
CHANGED
|
@@ -4,21 +4,21 @@
|
|
|
4
4
|
|
|
5
5
|
import type { WireFillRow, WireSolutionRow } from "../types/wire.js";
|
|
6
6
|
import type {
|
|
7
|
-
|
|
7
|
+
ActivityType, Address, BackstopTransfer, Balances, Bar, BridgeConfig, CandleQuery,
|
|
8
8
|
Market, MarketId, Order, Orderbook, PositionsSnapshot, Resolution, Status,
|
|
9
9
|
Trigger, TxExplorer, Withdrawal, WithdrawalsQuery,
|
|
10
10
|
} from "../types/public.js";
|
|
11
11
|
import type {
|
|
12
|
-
WireActivityPage, WireBackstopPage, WireBalances, WireBridgeConfig, WireCandlesEnvelope,
|
|
12
|
+
WireActivityEntry, WireActivityPage, WireBackstopPage, WireBalances, WireBridgeConfig, WireCandlesEnvelope,
|
|
13
13
|
WireMarketStatic, WireMarketStatsPage, WireOrderbook, WireOrdersPage, WirePositionsSnapshot,
|
|
14
14
|
WireStatus, WireTriggersPage, WireWithdrawal,
|
|
15
15
|
} from "../types/wire.js";
|
|
16
16
|
import {
|
|
17
|
-
|
|
17
|
+
decodeBackstopTransfer, decodeBalances, decodeBridgeConfig, decodeCandle,
|
|
18
18
|
decodeMarketDynamics, decodeMarketStatic, decodeOrder, decodeOrderbook, decodePositions,
|
|
19
19
|
decodeStatus, decodeTrigger, decodeWithdrawal,
|
|
20
20
|
} from "../codec/decode.js";
|
|
21
|
-
import { msToSecs,
|
|
21
|
+
import { msToSecs, usToMs } from "../codec/units.js";
|
|
22
22
|
|
|
23
23
|
export type MarketDynamicsPatch = Partial<Market> & { id: string };
|
|
24
24
|
|
|
@@ -33,8 +33,10 @@ export interface OrdersPage {
|
|
|
33
33
|
solutionNow: number;
|
|
34
34
|
}
|
|
35
35
|
export interface ActivityPage {
|
|
36
|
-
|
|
37
|
-
|
|
36
|
+
/** Newest first, each batch's entries in the node's order. */
|
|
37
|
+
batches: Array<[batchUs: number, entries: WireActivityEntry[]]>;
|
|
38
|
+
/** Pass back as `toUs` for the next, older page; null when the window is exhausted. */
|
|
39
|
+
nextUs: number | null;
|
|
38
40
|
solutionNow: number; // ms
|
|
39
41
|
}
|
|
40
42
|
export interface BackstopPage {
|
|
@@ -60,11 +62,11 @@ export interface OrdersQueryRest {
|
|
|
60
62
|
cursor?: string;
|
|
61
63
|
}
|
|
62
64
|
export interface ActivityQueryRest {
|
|
63
|
-
limit?: number;
|
|
64
|
-
cursor?: string;
|
|
65
65
|
types?: ActivityType[];
|
|
66
|
-
|
|
67
|
-
|
|
66
|
+
fromUs?: number; // inclusive
|
|
67
|
+
toUs?: number; // inclusive
|
|
68
|
+
/** Entries per page, 1..=2000; the newest batch is served whole even past it. */
|
|
69
|
+
limit?: number;
|
|
68
70
|
}
|
|
69
71
|
export interface TriggersQueryRest {
|
|
70
72
|
orderbook?: MarketId;
|
|
@@ -190,22 +192,20 @@ export class PodRestClient {
|
|
|
190
192
|
};
|
|
191
193
|
}
|
|
192
194
|
|
|
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
|
-
*/
|
|
195
|
+
/** One page of an account's activity by batch, newest batches first (ADR 0057 §5); page with `nextUs`. */
|
|
198
196
|
async activity(account: Address, q?: ActivityQueryRest): Promise<ActivityPage> {
|
|
199
197
|
const w = await this.get<WireActivityPage>(`/clob/activity/${account}`, {
|
|
200
|
-
limit: q?.limit,
|
|
201
|
-
cursor: q?.cursor,
|
|
202
198
|
activity_types: q?.types?.length ? q.types.join(",") : undefined,
|
|
203
|
-
from: q?.
|
|
204
|
-
to: q?.
|
|
199
|
+
from: q?.fromUs !== undefined ? String(q.fromUs) : undefined,
|
|
200
|
+
to: q?.toUs !== undefined ? String(q.toUs) : undefined,
|
|
201
|
+
limit: q?.limit,
|
|
205
202
|
});
|
|
203
|
+
const batches = Object.entries(w.activity)
|
|
204
|
+
.map(([batch, entries]): [number, WireActivityEntry[]] => [Number(batch), entries])
|
|
205
|
+
.sort((a, b) => b[0] - a[0]);
|
|
206
206
|
return {
|
|
207
|
-
|
|
208
|
-
|
|
207
|
+
batches,
|
|
208
|
+
nextUs: w.next === null ? null : Number(w.next),
|
|
209
209
|
solutionNow: usToMs(w.solution_now),
|
|
210
210
|
};
|
|
211
211
|
}
|
package/src/transport/ws.ts
CHANGED
|
@@ -11,9 +11,7 @@ export type Channel =
|
|
|
11
11
|
/** Terminal withdrawal outcomes; one array per tick, `account`-filtered on the
|
|
12
12
|
* debited account. ADR 0033 §6. */
|
|
13
13
|
| "pod_withdrawals"
|
|
14
|
-
/** One
|
|
15
|
-
* cleared, plus the money it moved. One frame per tick, so `since` alone
|
|
16
|
-
* resumes it. ADR 0057 §6. */
|
|
14
|
+
/** One `{ "<batch>": [entries] }` message per tick, so `since` alone resumes it. ADR 0057 §6. */
|
|
17
15
|
| "pod_activity";
|
|
18
16
|
|
|
19
17
|
export interface SubParams {
|