@pod-network/trade-sdk 0.18.0 → 0.19.1
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 +5 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +6 -5
- package/dist/client.js.map +1 -1
- package/dist/codec/activity.d.ts +4 -9
- package/dist/codec/activity.d.ts.map +1 -1
- package/dist/codec/activity.js +6 -23
- package/dist/codec/activity.js.map +1 -1
- package/dist/codec/resolution.js +2 -2
- package/dist/datafeed.js +1 -1
- package/dist/stores/resource.d.ts +9 -3
- package/dist/stores/resource.d.ts.map +1 -1
- package/dist/stores/resource.js +6 -1
- package/dist/stores/resource.js.map +1 -1
- package/dist/sync/activity.d.ts +11 -2
- package/dist/sync/activity.d.ts.map +1 -1
- package/dist/sync/activity.js +74 -18
- package/dist/sync/activity.js.map +1 -1
- package/dist/sync/candles.d.ts.map +1 -1
- package/dist/sync/candles.js +6 -0
- package/dist/sync/candles.js.map +1 -1
- package/dist/sync/order-ledger.d.ts +42 -0
- package/dist/sync/order-ledger.d.ts.map +1 -0
- package/dist/sync/order-ledger.js +163 -0
- package/dist/sync/order-ledger.js.map +1 -0
- package/dist/sync/order-preview.d.ts.map +1 -1
- package/dist/sync/order-preview.js +5 -1
- package/dist/sync/order-preview.js.map +1 -1
- package/dist/sync/orders.d.ts +5 -1
- package/dist/sync/orders.d.ts.map +1 -1
- package/dist/sync/orders.js +41 -16
- package/dist/sync/orders.js.map +1 -1
- package/dist/sync/positions-live.d.ts.map +1 -1
- package/dist/sync/positions-live.js +33 -7
- package/dist/sync/positions-live.js.map +1 -1
- package/dist/sync/sources.d.ts +3 -1
- package/dist/sync/sources.d.ts.map +1 -1
- package/dist/sync/sources.js +21 -9
- package/dist/sync/sources.js.map +1 -1
- package/dist/sync/withdrawals.d.ts +1 -1
- package/dist/sync/withdrawals.d.ts.map +1 -1
- package/dist/sync/withdrawals.js +15 -6
- package/dist/sync/withdrawals.js.map +1 -1
- package/dist/transport/rest.d.ts +5 -0
- package/dist/transport/rest.d.ts.map +1 -1
- package/dist/transport/rest.js +3 -0
- package/dist/transport/rest.js.map +1 -1
- package/dist/types/public.d.ts +6 -2
- package/dist/types/public.d.ts.map +1 -1
- package/dist/write/index.d.ts +2 -2
- package/dist/write/index.js +1 -1
- package/package.json +1 -1
- package/src/client.ts +11 -5
- package/src/codec/activity.ts +5 -22
- package/src/codec/resolution.ts +2 -2
- package/src/datafeed.ts +1 -1
- package/src/stores/resource.ts +13 -4
- package/src/sync/activity.ts +78 -20
- package/src/sync/candles.ts +5 -0
- package/src/sync/order-ledger.ts +157 -0
- package/src/sync/order-preview.ts +5 -1
- package/src/sync/orders.ts +39 -14
- package/src/sync/positions-live.ts +32 -7
- package/src/sync/sources.ts +22 -8
- package/src/sync/withdrawals.ts +15 -6
- package/src/transport/rest.ts +8 -0
- package/src/types/public.ts +6 -2
- package/src/write/index.ts +2 -2
package/src/sync/orders.ts
CHANGED
|
@@ -2,21 +2,25 @@
|
|
|
2
2
|
// live by the pod_orders_v2 stream (bidder-filtered, resumed from a (batch, book)
|
|
3
3
|
// cursor by `ResumableStream`), and paged backwards by cursor for deep history.
|
|
4
4
|
|
|
5
|
-
import type { Address, Order, OrderEvent, OrdersQuery } from "../types/public.js";
|
|
5
|
+
import type { ActivityType, Address, Order, OrderEvent, OrdersQuery } from "../types/public.js";
|
|
6
6
|
import type { WireOrdersFrame } from "../types/wire.js";
|
|
7
7
|
import { applyOrdersFrame } from "../codec/orders-v2.js";
|
|
8
8
|
import { BaseResource, type ResourceHandle, type Snapshot, type SnapshotSlot } from "../stores/resource.js";
|
|
9
9
|
import type { SubParams } from "../transport/ws.js";
|
|
10
10
|
import type { SeriesResource } from "./candles.js";
|
|
11
|
+
import { OrderLedger, readActivityAfter } from "./order-ledger.js";
|
|
11
12
|
import { readAtLeast, type SyncContext } from "./sources.js";
|
|
12
|
-
import {
|
|
13
|
+
import { ResumableStream } from "./stream.js";
|
|
13
14
|
|
|
14
15
|
export { compareCursor } from "./stream.js";
|
|
15
16
|
|
|
17
|
+
const ORDER_ACTIVITY: ActivityType[] = ["order", "fill", "modify", "termination"];
|
|
18
|
+
|
|
16
19
|
export class OrderHistory implements SeriesResource<Order> {
|
|
17
20
|
private readonly base: BaseResource<Order[]>;
|
|
18
21
|
private handle: ResourceHandle<Order[]> | undefined;
|
|
19
|
-
private readonly
|
|
22
|
+
private readonly ledger: OrderLedger<WireOrdersFrame, OrderEvent[]>;
|
|
23
|
+
private reconciling = false;
|
|
20
24
|
private nextCursor: string | null = null;
|
|
21
25
|
private painted = false;
|
|
22
26
|
private seedGen = 0;
|
|
@@ -31,6 +35,7 @@ export class OrderHistory implements SeriesResource<Order> {
|
|
|
31
35
|
private readonly query: OrdersQuery = {},
|
|
32
36
|
slot?: SnapshotSlot,
|
|
33
37
|
) {
|
|
38
|
+
this.ledger = new OrderLedger((frame, orders) => applyOrdersFrame(frame, orders, { account }));
|
|
34
39
|
this.stream = new ResumableStream({
|
|
35
40
|
ws: ctx.ws,
|
|
36
41
|
channel: "pod_orders_v2",
|
|
@@ -41,7 +46,9 @@ export class OrderHistory implements SeriesResource<Order> {
|
|
|
41
46
|
this.base = new BaseResource<Order[]>((h) => {
|
|
42
47
|
this.handle = h;
|
|
43
48
|
this.stream.start();
|
|
49
|
+
const timer = ctx.historyResyncMs > 0 ? setInterval(() => void this.reconcile(), ctx.historyResyncMs) : undefined;
|
|
44
50
|
return () => {
|
|
51
|
+
clearInterval(timer);
|
|
45
52
|
this.stream.stop();
|
|
46
53
|
this.handle = undefined;
|
|
47
54
|
};
|
|
@@ -89,8 +96,8 @@ export class OrderHistory implements SeriesResource<Order> {
|
|
|
89
96
|
const page = await readAtLeast((min) => this.ctx.rest.orders(this.account, {
|
|
90
97
|
cursor,
|
|
91
98
|
limit: this.query.limit ?? 100,
|
|
92
|
-
}, min), this.
|
|
93
|
-
|
|
99
|
+
}, min), this.minimum());
|
|
100
|
+
if (!this.ledger.rows(page.orders, page.solutionNowUs)) return;
|
|
94
101
|
this.nextCursor = page.nextCursor;
|
|
95
102
|
this._hasMore = page.nextCursor !== null;
|
|
96
103
|
} finally {
|
|
@@ -106,18 +113,16 @@ export class OrderHistory implements SeriesResource<Order> {
|
|
|
106
113
|
try {
|
|
107
114
|
const page = await readAtLeast(
|
|
108
115
|
(min) => this.ctx.rest.orders(this.account, { limit: this.query.limit ?? 100 }, min),
|
|
109
|
-
this.
|
|
116
|
+
this.minimum(),
|
|
110
117
|
);
|
|
111
118
|
// A seed overtaken by a fresher one is dropped whole: it would absorb rows the
|
|
112
119
|
// newer page has already corrected, and raise the cursor to an older watermark.
|
|
113
120
|
if (!this.stream.running || gen !== this.seedGen) return false;
|
|
114
121
|
const settled: SubParams = { since: page.solutionNow * 1000, sinceBook: undefined };
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
this.byId.set(o.id, o);
|
|
120
|
-
}
|
|
122
|
+
if (!this.ledger.rows(page.orders, page.solutionNowUs)) throw new Error("orders read below the held frames");
|
|
123
|
+
// A reconnect: the stream may have missed frames for orders this page does not hold.
|
|
124
|
+
if (this.painted) void this.reconcile();
|
|
125
|
+
else this.ledger.stampUs ||= page.solutionNowUs;
|
|
121
126
|
// Paging is the consumer's position in history, not the seed's: a reconnect
|
|
122
127
|
// re-paints the first page, and taking its cursor again would hand back pages
|
|
123
128
|
// `loadOlder` has already walked past.
|
|
@@ -152,7 +157,7 @@ export class OrderHistory implements SeriesResource<Order> {
|
|
|
152
157
|
const at: SubParams = { since: frame.batch, sinceBook: frame.book };
|
|
153
158
|
if (this.stream.delivered(at)) return;
|
|
154
159
|
|
|
155
|
-
const events =
|
|
160
|
+
const events = this.ledger.live(frame.batch, frame);
|
|
156
161
|
this.stream.advance(at);
|
|
157
162
|
this.rebuild();
|
|
158
163
|
// Strictly after `rebuild()`: a listener that reads the resource in response to an
|
|
@@ -164,9 +169,29 @@ export class OrderHistory implements SeriesResource<Order> {
|
|
|
164
169
|
}
|
|
165
170
|
}
|
|
166
171
|
|
|
172
|
+
/** The lowest round a read may answer at: past the stream, and past the reconcile so no order misses a transition. */
|
|
173
|
+
private minimum(): number | undefined {
|
|
174
|
+
return Math.max(this.stream.cursor.since ?? 0, this.ledger.minimum()) || undefined;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private async reconcile(): Promise<void> {
|
|
178
|
+
if (this.reconciling || !this.painted || !this.stream.running) return;
|
|
179
|
+
this.reconciling = true;
|
|
180
|
+
try {
|
|
181
|
+
const pages = await readActivityAfter(
|
|
182
|
+
this.ctx.rest, this.account, this.ledger.stampUs, this.ledger.minimum(), ORDER_ACTIVITY,
|
|
183
|
+
);
|
|
184
|
+
if (this.stream.running && this.ledger.reconcile(pages)) this.rebuild();
|
|
185
|
+
} catch {
|
|
186
|
+
// The next interval or reconnect asks again.
|
|
187
|
+
} finally {
|
|
188
|
+
this.reconciling = false;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
167
192
|
private rebuild(): void {
|
|
168
193
|
if (!this.handle) return;
|
|
169
|
-
let arr = [...this.
|
|
194
|
+
let arr = [...this.ledger.view.values()];
|
|
170
195
|
if (this.query.status) arr = arr.filter((o) => o.status === this.query.status);
|
|
171
196
|
if (this.query.orderbookId) arr = arr.filter((o) => o.orderbookId === this.query.orderbookId);
|
|
172
197
|
// Newest first by when the order became real. Inclusion time is the key both
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// basis, resting-order escrow).
|
|
9
9
|
//
|
|
10
10
|
// EXACT replication of pod — see the cross-reference notes in pod at:
|
|
11
|
-
// trading/src/perps/mod.rs `cross_budgets` (
|
|
11
|
+
// trading/src/perps/mod.rs `cross_budgets` (equity)
|
|
12
12
|
// trading/src/perps/mod.rs `pending_funding` (funding)
|
|
13
13
|
// Integer semantics match trading/src/decimal.rs:
|
|
14
14
|
// mul(a,b) = (a*b)/1e18 truncated toward zero (Decimal `*`)
|
|
@@ -37,6 +37,13 @@ export function enrichPositions(snap: PositionsSnapshot, markets: Market[]): Pos
|
|
|
37
37
|
let im = 0n; // Σ initial-margin requirement at live notional
|
|
38
38
|
let mm = 0n; // Σ maintenance-margin requirement at live notional
|
|
39
39
|
let dSpot = 0n; // change in spot mark value vs snapshot (slope = balance)
|
|
40
|
+
// Withdrawable is the node's figure moved by the equity and reserve change since
|
|
41
|
+
// it was read. Market data older than the snapshot (another node behind a load
|
|
42
|
+
// balancer) moves nothing.
|
|
43
|
+
let dEquity = 0n;
|
|
44
|
+
let imMoved = 0n;
|
|
45
|
+
let notionalMoved = 0n;
|
|
46
|
+
let notionalSnap = 0n;
|
|
40
47
|
|
|
41
48
|
const positions: Position[] = snap.positions.map((p) => {
|
|
42
49
|
const market = p.orderbookId ? byId.get(p.orderbookId) : undefined;
|
|
@@ -48,9 +55,10 @@ export function enrichPositions(snap: PositionsSnapshot, markets: Market[]): Pos
|
|
|
48
55
|
const liveMark = market?.markPrice && market.markPrice > 0n ? market.markPrice : p.markPrice;
|
|
49
56
|
const mark = liveMark > 0n ? liveMark : p.entryPrice;
|
|
50
57
|
// The entry-price fallback rounds against the holder.
|
|
51
|
-
const
|
|
52
|
-
? mul(
|
|
53
|
-
: mulFloor(
|
|
58
|
+
const pnlAt = (m: bigint) => p.costBasis !== undefined
|
|
59
|
+
? mul(m, p.size) - p.costBasis
|
|
60
|
+
: mulFloor(m - p.entryPrice, p.size); // pure price drift (signed)
|
|
61
|
+
const upnl = pnlAt(mark);
|
|
54
62
|
const sizeQuote = mul(absB(p.size), mark); // = notional
|
|
55
63
|
const imr = market?.initialMargin ?? imRate(market?.maxLeverage ?? 0);
|
|
56
64
|
im += mul(sizeQuote, imr);
|
|
@@ -66,6 +74,15 @@ export function enrichPositions(snap: PositionsSnapshot, markets: Market[]): Pos
|
|
|
66
74
|
}
|
|
67
75
|
fundingLiveTotal += funding;
|
|
68
76
|
fundingSnapTotal += p.fundingAccrued;
|
|
77
|
+
const marketFresh = snap.timestampUs === undefined
|
|
78
|
+
|| (market?.dynamicsUs !== undefined && market.dynamicsUs >= snap.timestampUs);
|
|
79
|
+
const snapMark = p.markPrice > 0n ? p.markPrice : p.entryPrice;
|
|
80
|
+
const movedMark = marketFresh ? mark : snapMark;
|
|
81
|
+
if (marketFresh) dEquity += upnl - pnlAt(snapMark) - (funding - p.fundingAccrued);
|
|
82
|
+
const movedNotional = mul(absB(p.size), movedMark);
|
|
83
|
+
imMoved += mul(movedNotional, imr);
|
|
84
|
+
notionalMoved += movedNotional;
|
|
85
|
+
notionalSnap += mul(absB(p.size), snapMark);
|
|
69
86
|
|
|
70
87
|
return { ...p, markPrice: mark, unrealizedPnl: upnl, notional: sizeQuote, fundingAccrued: funding };
|
|
71
88
|
}
|
|
@@ -80,10 +97,16 @@ export function enrichPositions(snap: PositionsSnapshot, markets: Market[]): Pos
|
|
|
80
97
|
const nativeCash = snap.cash + fundingSnapTotal;
|
|
81
98
|
const cashWithFunding = nativeCash - fundingLiveTotal;
|
|
82
99
|
|
|
83
|
-
// EXACT (perp-only, integer-faithful): equity = cash_with_funding + Σ price PnL
|
|
84
|
-
// withdrawable = max(0, equity - Σ IM), forced to 0 below maintenance margin.
|
|
100
|
+
// EXACT (perp-only, integer-faithful): equity = cash_with_funding + Σ price PnL.
|
|
85
101
|
const perpsEquity = cashWithFunding + priceUpnl;
|
|
86
|
-
|
|
102
|
+
// The node reserves max(IM, ratio × notional) plus frozen profit; the ratio is not
|
|
103
|
+
// served, so the snapshot's reserve is scaled with notional, floored at live IM.
|
|
104
|
+
// A zero base hides the reserve, so it moves with equity alone.
|
|
105
|
+
const reserveSnap = snap.perpsEquity - snap.withdrawableCash;
|
|
106
|
+
const dReserve = snap.withdrawableCash > 0n && notionalSnap > 0n
|
|
107
|
+
? maxB(imMoved, (reserveSnap * notionalMoved) / notionalSnap) - reserveSnap
|
|
108
|
+
: 0n;
|
|
109
|
+
const withdrawableCash = maxB(0n, snap.withdrawableCash + dEquity - dReserve);
|
|
87
110
|
|
|
88
111
|
// account_value moves with perp equity (incl. funding) AND spot mark; total
|
|
89
112
|
// uPnL is pure price drift only (funding is reported separately). Re-baseline
|
|
@@ -95,8 +118,10 @@ export function enrichPositions(snap: PositionsSnapshot, markets: Market[]): Pos
|
|
|
95
118
|
totalRealizedPnl: snap.totalRealizedPnl,
|
|
96
119
|
perpsEquity,
|
|
97
120
|
withdrawableCash,
|
|
121
|
+
initialMargin: im,
|
|
98
122
|
maintenanceMargin: mm,
|
|
99
123
|
totalUnrealizedPnl: snap.totalUnrealizedPnl + dPriceUpnl + dSpot,
|
|
100
124
|
accountValue: snap.accountValue + (perpsEquity - snap.perpsEquity) + dSpot,
|
|
125
|
+
timestampUs: snap.timestampUs,
|
|
101
126
|
};
|
|
102
127
|
}
|
package/src/sync/sources.ts
CHANGED
|
@@ -34,6 +34,8 @@ export interface SyncContext {
|
|
|
34
34
|
positionResyncMs: number;
|
|
35
35
|
/** Periodic REST re-poll (ms) of market 24h stats; 0 disables. */
|
|
36
36
|
marketResyncMs: number;
|
|
37
|
+
/** Periodic REST reconcile (ms) of orders, activity, withdrawals, candles and triggers; 0 disables. */
|
|
38
|
+
historyResyncMs: number;
|
|
37
39
|
/** Optional persistence for the static markets list (see marketsSource). */
|
|
38
40
|
marketsCache?: MarketsCache;
|
|
39
41
|
}
|
|
@@ -226,7 +228,7 @@ export function marketsSource(
|
|
|
226
228
|
const seedStats = () => readAtLeast((min) => rest.marketStats(undefined, min), heldUs).then((page) => {
|
|
227
229
|
if (!alive) return;
|
|
228
230
|
heldUs = Math.max(heldUs, page.solutionNow * 1000);
|
|
229
|
-
page.markets.forEach((m) => { if (fresh(page.solutionNow, m.id)) mergePatch(m); });
|
|
231
|
+
page.markets.forEach((m) => { if (fresh(page.solutionNow, m.id)) mergePatch({ ...m, dynamicsUs: page.solutionNow * 1000 }); });
|
|
230
232
|
publish();
|
|
231
233
|
}).catch(() => { /* live dynamics also arrive on the stream */ });
|
|
232
234
|
|
|
@@ -241,7 +243,10 @@ export function marketsSource(
|
|
|
241
243
|
const id = (w.orderbook_id ?? w.orderbook) as string;
|
|
242
244
|
if (typeof w.timestamp === "number") heldUs = Math.max(heldUs, w.timestamp);
|
|
243
245
|
if (!fresh(typeof w.timestamp === "number" ? usToMs(w.timestamp) : undefined, id)) continue;
|
|
244
|
-
mergePatch(
|
|
246
|
+
mergePatch({
|
|
247
|
+
...decodeMarketDynamics({ ...w, orderbook_id: id } as WireMarketDynamics),
|
|
248
|
+
dynamicsUs: typeof w.timestamp === "number" ? w.timestamp : undefined,
|
|
249
|
+
});
|
|
245
250
|
}
|
|
246
251
|
publish();
|
|
247
252
|
});
|
|
@@ -284,12 +289,13 @@ export function positionsSource(
|
|
|
284
289
|
// - a periodic REST poll that re-aligns to the backend's exact accounting
|
|
285
290
|
// (corrects mark-extrapolation drift even when the account isn't touched).
|
|
286
291
|
const fresh = watermarks();
|
|
292
|
+
fresh(h.lastKnown()?.value.timestampUs);
|
|
287
293
|
const accept = (s: PositionsSnapshot) => { if (alive && fresh(s.timestampUs)) h.set(s); };
|
|
288
294
|
const reseed = () =>
|
|
289
|
-
readAtLeast((min) => rest.positions(account, min), h.
|
|
295
|
+
readAtLeast((min) => rest.positions(account, min), h.lastKnown()?.value.timestampUs).then(accept).catch(() => {});
|
|
290
296
|
reseed();
|
|
291
297
|
const timer = positionResyncMs > 0 ? setInterval(reseed, positionResyncMs) : undefined;
|
|
292
|
-
const sub = subscribeRetrying(ws, "pod_positions", () => ({ account, since: h.
|
|
298
|
+
const sub = subscribeRetrying(ws, "pod_positions", () => ({ account, since: h.lastKnown()?.value.timestampUs ?? 0 }), (result) => {
|
|
293
299
|
accept(decodePositions((result as WirePositionsPush).data));
|
|
294
300
|
});
|
|
295
301
|
return () => { alive = false; if (timer) clearInterval(timer); sub.unsubscribe(); };
|
|
@@ -331,17 +337,25 @@ export function balancesSource(
|
|
|
331
337
|
}
|
|
332
338
|
|
|
333
339
|
export function triggersSource(
|
|
334
|
-
{ ws }: SyncContext,
|
|
340
|
+
{ rest, ws, historyResyncMs }: SyncContext,
|
|
335
341
|
account: Address,
|
|
336
342
|
): ResourceSource<Trigger[]> {
|
|
337
343
|
const fresh = watermarks();
|
|
338
344
|
let heldUs = 0;
|
|
339
345
|
return (h) => {
|
|
346
|
+
let alive = true;
|
|
347
|
+
const accept = (triggers: Trigger[], timestampUs: number | undefined) => {
|
|
348
|
+
heldUs = Math.max(heldUs, timestampUs ?? 0);
|
|
349
|
+
if (alive && fresh(timestampUs)) h.set(triggers);
|
|
350
|
+
};
|
|
351
|
+
// 200 is the page `pod_triggers` pushes.
|
|
352
|
+
const reconcile = () => readAtLeast((min) => rest.triggers(account, { limit: 200 }, min), heldUs)
|
|
353
|
+
.then((page) => accept(page.triggers, page.timestampUs)).catch(() => {});
|
|
354
|
+
const timer = historyResyncMs > 0 ? setInterval(reconcile, historyResyncMs) : undefined;
|
|
340
355
|
const sub = subscribeRetrying(ws, "pod_triggers", () => ({ account, since: heldUs }), (result) => {
|
|
341
356
|
const w = result as WireTriggersPush;
|
|
342
|
-
|
|
343
|
-
if (fresh(w.timestamp)) h.set(w.triggers.map(decodeTrigger));
|
|
357
|
+
accept(w.triggers.map(decodeTrigger), w.timestamp);
|
|
344
358
|
});
|
|
345
|
-
return () => sub.unsubscribe();
|
|
359
|
+
return () => { alive = false; clearInterval(timer); sub.unsubscribe(); };
|
|
346
360
|
};
|
|
347
361
|
}
|
package/src/sync/withdrawals.ts
CHANGED
|
@@ -24,7 +24,7 @@ const PAGE_LIMIT = 500;
|
|
|
24
24
|
const MAX_PAGES = 50;
|
|
25
25
|
|
|
26
26
|
export function withdrawalsSource(
|
|
27
|
-
{ rest, ws }: SyncContext,
|
|
27
|
+
{ rest, ws, historyResyncMs }: SyncContext,
|
|
28
28
|
account: Address,
|
|
29
29
|
): ResourceSource<Withdrawal[]> {
|
|
30
30
|
return (h) => {
|
|
@@ -66,16 +66,23 @@ export function withdrawalsSource(
|
|
|
66
66
|
* the cursor, so concurrent loops would re-request each other's pages.
|
|
67
67
|
*/
|
|
68
68
|
let inflight: Promise<boolean> | undefined;
|
|
69
|
-
const
|
|
69
|
+
const walk = (fromUs: number, fromId: Withdrawal["txHash"] | undefined): Promise<boolean> =>
|
|
70
|
+
(inflight ??= run(fromUs, fromId).finally(() => { inflight = undefined; }));
|
|
71
|
+
const backfill = () => walk(sinceUs, sinceId);
|
|
72
|
+
// From the end of the log REST last served rather than the shared cursor, which
|
|
73
|
+
// pushes move: an outcome the stream lost below a later push is read again.
|
|
74
|
+
const reconcile = () => { void walk(servedUs, undefined); };
|
|
70
75
|
|
|
71
|
-
const run = async () => {
|
|
76
|
+
const run = async (fromUs: number, fromId: Withdrawal["txHash"] | undefined) => {
|
|
72
77
|
try {
|
|
73
78
|
// Page against a cursor local to this run. The shared one is also moved
|
|
74
79
|
// by live pushes, and a push landing mid-backfill would jump the next
|
|
75
80
|
// page past the rest of an older tick — rows the forward-only cursor
|
|
76
81
|
// could then never come back for.
|
|
77
|
-
|
|
78
|
-
|
|
82
|
+
// A walk from above `servedUs` skipped whatever lies between, so it cannot vouch for the log.
|
|
83
|
+
const vouches = fromUs <= servedUs;
|
|
84
|
+
let pageSince = fromUs;
|
|
85
|
+
let pageSinceId = fromId;
|
|
79
86
|
for (let page = 0; page < MAX_PAGES; page++) {
|
|
80
87
|
const query = { since: pageSince, sinceId: pageSinceId, limit: PAGE_LIMIT };
|
|
81
88
|
const res = await readAtLeast(
|
|
@@ -86,7 +93,7 @@ export function withdrawalsSource(
|
|
|
86
93
|
const rows = res.withdrawals;
|
|
87
94
|
absorb(rows);
|
|
88
95
|
// Pages may come from different nodes: only the one that served the end of the log vouches for it.
|
|
89
|
-
if (rows.length < PAGE_LIMIT) { servedUs = Math.max(servedUs, res.timestampUs); break; }
|
|
96
|
+
if (rows.length < PAGE_LIMIT) { if (vouches) servedUs = Math.max(servedUs, res.timestampUs); break; }
|
|
90
97
|
// Rows come back ascending, so the last one is this page's high-water
|
|
91
98
|
// mark — regardless of what the stream did to the shared cursor.
|
|
92
99
|
const last = rows[rows.length - 1]!;
|
|
@@ -169,6 +176,7 @@ export function withdrawalsSource(
|
|
|
169
176
|
// Seed immediately — REST needs no socket, so history paints without waiting
|
|
170
177
|
// on the handshake — and fill the gap again on every reconnect.
|
|
171
178
|
const offOpen = ws.on("open", () => { if (alive) void backfill(); });
|
|
179
|
+
const timer = historyResyncMs > 0 ? setInterval(reconcile, historyResyncMs) : undefined;
|
|
172
180
|
// Subscribing after the first backfill lets `since` cover the gap between a
|
|
173
181
|
// lagging REST node and the head of the node the socket landed on.
|
|
174
182
|
void backfill().then((ok) => {
|
|
@@ -180,6 +188,7 @@ export function withdrawalsSource(
|
|
|
180
188
|
return () => {
|
|
181
189
|
alive = false;
|
|
182
190
|
offOpen();
|
|
191
|
+
clearInterval(timer);
|
|
183
192
|
if (retryTimer) clearTimeout(retryTimer);
|
|
184
193
|
sub?.unsubscribe();
|
|
185
194
|
};
|
package/src/transport/rest.ts
CHANGED
|
@@ -31,6 +31,8 @@ export interface OrdersPage {
|
|
|
31
31
|
nextCursor: string | null;
|
|
32
32
|
totalCount: number;
|
|
33
33
|
solutionNow: number;
|
|
34
|
+
/** The read's indexer round, exact; `solutionNow` is truncated to ms. */
|
|
35
|
+
solutionNowUs: number;
|
|
34
36
|
}
|
|
35
37
|
export interface ActivityPage {
|
|
36
38
|
/** Newest first, each batch's entries in the node's order. */
|
|
@@ -38,6 +40,8 @@ export interface ActivityPage {
|
|
|
38
40
|
/** Pass back as `toUs` for the next, older page; null when the window is exhausted. */
|
|
39
41
|
nextUs: number | null;
|
|
40
42
|
solutionNow: number; // ms
|
|
43
|
+
/** The read's indexer round, exact; `solutionNow` is truncated to ms. */
|
|
44
|
+
solutionNowUs: number;
|
|
41
45
|
}
|
|
42
46
|
export interface BackstopPage {
|
|
43
47
|
transfers: BackstopTransfer[];
|
|
@@ -48,6 +52,7 @@ export interface TriggersPage {
|
|
|
48
52
|
triggers: Trigger[];
|
|
49
53
|
totalCount: number;
|
|
50
54
|
nextCursor: string | null;
|
|
55
|
+
timestampUs?: number;
|
|
51
56
|
}
|
|
52
57
|
export interface WithdrawalsPage {
|
|
53
58
|
withdrawals: Withdrawal[];
|
|
@@ -210,6 +215,7 @@ export class PodRestClient {
|
|
|
210
215
|
nextCursor: w.next_cursor,
|
|
211
216
|
totalCount: w.total_count,
|
|
212
217
|
solutionNow: Math.trunc(w.solution_now / 1000),
|
|
218
|
+
solutionNowUs: w.solution_now,
|
|
213
219
|
};
|
|
214
220
|
}
|
|
215
221
|
|
|
@@ -229,6 +235,7 @@ export class PodRestClient {
|
|
|
229
235
|
batches,
|
|
230
236
|
nextUs: w.next === null ? null : Number(w.next),
|
|
231
237
|
solutionNow: usToMs(w.solution_now),
|
|
238
|
+
solutionNowUs: w.solution_now,
|
|
232
239
|
};
|
|
233
240
|
}
|
|
234
241
|
|
|
@@ -319,6 +326,7 @@ export class PodRestClient {
|
|
|
319
326
|
triggers: w.triggers.map(decodeTrigger),
|
|
320
327
|
totalCount: w.total_count,
|
|
321
328
|
nextCursor: w.next_cursor,
|
|
329
|
+
timestampUs: w.timestamp,
|
|
322
330
|
};
|
|
323
331
|
}
|
|
324
332
|
}
|
package/src/types/public.ts
CHANGED
|
@@ -7,7 +7,7 @@ export type Address = Hex;
|
|
|
7
7
|
export type Hash = Hex;
|
|
8
8
|
|
|
9
9
|
export type Resolution =
|
|
10
|
-
| "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "1d" | "
|
|
10
|
+
| "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "1d" | "1w" | "1M";
|
|
11
11
|
|
|
12
12
|
/** Inclusive-from, exclusive-to time window in milliseconds. `to` defaults to now. */
|
|
13
13
|
export interface TimeRange {
|
|
@@ -212,6 +212,8 @@ export interface Market {
|
|
|
212
212
|
fundingSettlingIndex?: bigint;
|
|
213
213
|
fundingLastUpdatedMs?: number;
|
|
214
214
|
openInterest?: bigint;
|
|
215
|
+
/** Solution time (µs) of the node state the dynamics above were read from. */
|
|
216
|
+
dynamicsUs?: number;
|
|
215
217
|
}
|
|
216
218
|
|
|
217
219
|
export interface Bar {
|
|
@@ -347,6 +349,8 @@ export interface PositionsSnapshot {
|
|
|
347
349
|
accountValue: bigint;
|
|
348
350
|
cash: bigint;
|
|
349
351
|
withdrawableCash: bigint;
|
|
352
|
+
/** Live snapshots only: Σ initial margin at live notional. */
|
|
353
|
+
initialMargin?: bigint;
|
|
350
354
|
maintenanceMargin?: bigint;
|
|
351
355
|
/** Deadline (µs) of the last tick the answering node executed. */
|
|
352
356
|
timestampUs?: number;
|
|
@@ -425,7 +429,7 @@ export interface TxExplorer {
|
|
|
425
429
|
chainId?: string;
|
|
426
430
|
maxFeePerGas?: string;
|
|
427
431
|
effectiveGasPrice?: string;
|
|
428
|
-
/** Null when the tx is in no block (solutions,
|
|
432
|
+
/** Null when the tx is in no block (solutions, an intent whose
|
|
429
433
|
* auction tick has not run yet); a height once it is sequenced. */
|
|
430
434
|
blockNumber?: string | null;
|
|
431
435
|
/** Always null: pod does not order the transactions within a block. */
|
package/src/write/index.ts
CHANGED
|
@@ -160,7 +160,7 @@ const ERROR_SELECTOR = "0x08c379a0";
|
|
|
160
160
|
/**
|
|
161
161
|
* A rejected pod transaction. `data`'s shape follows `code`: −32000 validation (string),
|
|
162
162
|
* 3 execution revert (`Error(string)`, decoded into `reason`), −32003 rejection quorum
|
|
163
|
-
* (array)
|
|
163
|
+
* (array).
|
|
164
164
|
*/
|
|
165
165
|
export class PodTxRevertError extends Error {
|
|
166
166
|
constructor(public reason: string, public data?: unknown, public code?: number) {
|
|
@@ -563,7 +563,7 @@ export interface TxReceipt {
|
|
|
563
563
|
status: "success" | "reverted";
|
|
564
564
|
transactionHash: Hash;
|
|
565
565
|
/** The height the tx was sequenced at, or `null` when it is in no block —
|
|
566
|
-
* `submitSolutions
|
|
566
|
+
* `submitSolutions` and an intent whose auction tick has not
|
|
567
567
|
* run yet. A null height is not a pending state: the receipt is still final. */
|
|
568
568
|
blockNumber: bigint | null;
|
|
569
569
|
gasUsed: bigint;
|