@pod-network/trade-sdk 0.2.0 → 0.4.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 +94 -2
- package/dist/client.d.ts +19 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +25 -13
- package/dist/client.js.map +1 -1
- package/dist/codec/bridge.d.ts +82 -0
- package/dist/codec/bridge.d.ts.map +1 -0
- package/dist/codec/bridge.js +114 -0
- package/dist/codec/bridge.js.map +1 -0
- package/dist/codec/decode.d.ts +15 -2
- package/dist/codec/decode.d.ts.map +1 -1
- package/dist/codec/decode.js +46 -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 +25 -1
- package/dist/codec/units.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- 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/sync/sources.d.ts +5 -1
- package/dist/sync/sources.d.ts.map +1 -1
- package/dist/sync/sources.js +16 -0
- package/dist/sync/sources.js.map +1 -1
- package/dist/sync/withdrawals.d.ts +5 -0
- package/dist/sync/withdrawals.d.ts.map +1 -0
- package/dist/sync/withdrawals.js +172 -0
- package/dist/sync/withdrawals.js.map +1 -0
- package/dist/transport/claim.d.ts +160 -0
- package/dist/transport/claim.d.ts.map +1 -0
- package/dist/transport/claim.js +341 -0
- package/dist/transport/claim.js.map +1 -0
- package/dist/transport/jsonrpc.d.ts +16 -0
- package/dist/transport/jsonrpc.d.ts.map +1 -0
- package/dist/transport/jsonrpc.js +42 -0
- package/dist/transport/jsonrpc.js.map +1 -0
- package/dist/transport/rest.d.ts +15 -1
- package/dist/transport/rest.d.ts.map +1 -1
- package/dist/transport/rest.js +25 -1
- package/dist/transport/rest.js.map +1 -1
- package/dist/transport/ws.d.ts +22 -2
- package/dist/transport/ws.d.ts.map +1 -1
- package/dist/transport/ws.js +14 -2
- package/dist/transport/ws.js.map +1 -1
- package/dist/types/public.d.ts +212 -9
- package/dist/types/public.d.ts.map +1 -1
- package/dist/types/wire.d.ts +147 -41
- package/dist/types/wire.d.ts.map +1 -1
- package/dist/write/delegation.d.ts.map +1 -1
- package/dist/write/delegation.js +2 -12
- package/dist/write/delegation.js.map +1 -1
- package/dist/write/index.d.ts +26 -1
- package/dist/write/index.d.ts.map +1 -1
- package/dist/write/index.js +21 -14
- package/dist/write/index.js.map +1 -1
- package/package.json +1 -1
- package/src/client.ts +33 -18
- package/src/codec/bridge.ts +138 -0
- package/src/codec/decode.ts +54 -10
- package/src/codec/direction.ts +36 -0
- package/src/codec/orders-v2.ts +222 -0
- package/src/codec/units.ts +24 -1
- package/src/index.ts +16 -0
- package/src/sync/orders.ts +203 -83
- package/src/sync/sources.ts +16 -1
- package/src/sync/withdrawals.ts +177 -0
- package/src/transport/claim.ts +434 -0
- package/src/transport/jsonrpc.ts +54 -0
- package/src/transport/rest.ts +35 -7
- package/src/transport/ws.ts +30 -4
- package/src/types/public.ts +233 -7
- package/src/types/wire.ts +161 -29
- package/src/write/delegation.ts +2 -12
- package/src/write/index.ts +59 -13
package/src/codec/decode.ts
CHANGED
|
@@ -2,16 +2,18 @@
|
|
|
2
2
|
// representations are normalized into bigint + millisecond numbers.
|
|
3
3
|
|
|
4
4
|
import type {
|
|
5
|
-
Bar, BackstopTransfer, Balances, LeaderboardEntry, LeaderboardPage, Market, Order,
|
|
5
|
+
Bar, BackstopTransfer, Balances, BridgeConfig, LeaderboardEntry, LeaderboardPage, Market, Order,
|
|
6
6
|
Orderbook, PartialFill, PerpPosition, Position, PositionsSnapshot, SpotHolding,
|
|
7
7
|
SpotPosition, Status, Trigger, MarketType, OrderDirection, OrderKind, OrderStatus, TriggerType,
|
|
8
|
+
Withdrawal,
|
|
8
9
|
} from "../types/public.js";
|
|
9
10
|
import type {
|
|
10
|
-
WireBackstopTransfer, WireBalances, WireCandle, WireLeaderboard,
|
|
11
|
-
WireMarketStatic, WireOrder, WireOrderbook, WirePartialFill,
|
|
12
|
-
|
|
11
|
+
WireBackstopTransfer, WireBalances, WireBridgeConfig, WireCandle, WireLeaderboard,
|
|
12
|
+
WireMarketDynamics, WireMarketStatic, WireOrder, WireOrderbook, WirePartialFill,
|
|
13
|
+
WirePerpPosition, WirePosition, WirePositionsSnapshot, WireSpotHolding, WireSpotPosition,
|
|
14
|
+
WireStatus, WireTrigger, WireWithdrawal,
|
|
13
15
|
} from "../types/wire.js";
|
|
14
|
-
import { dec, decOpt, toNumber, usToMs, usToMsOpt } from "./units.js";
|
|
16
|
+
import { dec, decOpt, endMsFromUs, toNumber, usToMs, usToMsOpt } from "./units.js";
|
|
15
17
|
|
|
16
18
|
export function decodeStatus(w: WireStatus): Status {
|
|
17
19
|
return { solutionNow: usToMs(w.solution_now) };
|
|
@@ -80,9 +82,10 @@ export function decodeOrder(w: WireOrder): Order {
|
|
|
80
82
|
id: w.order_id,
|
|
81
83
|
txHash: w.tx_hash,
|
|
82
84
|
orderbookId: w.orderbook_id,
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
//
|
|
85
|
+
// The order endpoints spell a perp market "perpetual"; `/clob/markets` and
|
|
86
|
+
// `MarketType` say "perp". Normalized here so one list of orders cannot carry
|
|
87
|
+
// both spellings — a streamed order takes its type from the market.
|
|
88
|
+
marketType: w.market_type === "perpetual" ? "perp" : (w.market_type as MarketType | undefined),
|
|
86
89
|
side: w.side ?? (initialSize < 0n ? "sell" : "buy"),
|
|
87
90
|
orderType: w.order_type,
|
|
88
91
|
status: w.status as OrderStatus,
|
|
@@ -96,7 +99,7 @@ export function decodeOrder(w: WireOrder): Order {
|
|
|
96
99
|
fee: dec(w.fee),
|
|
97
100
|
effectivePrice: decOpt(w.effective_price),
|
|
98
101
|
deadlineMs: usToMs(w.deadline),
|
|
99
|
-
endMs:
|
|
102
|
+
endMs: endMsFromUs(w.end),
|
|
100
103
|
includedMs: usToMsOpt(w.included_batch),
|
|
101
104
|
fills: (w.fills ?? []).map(decodePartialFill),
|
|
102
105
|
reduceOnly: w.reduce_only,
|
|
@@ -261,7 +264,7 @@ export function decodeTrigger(w: WireTrigger): Trigger {
|
|
|
261
264
|
reduceOnly: w.reduce_only,
|
|
262
265
|
ioc: w.ioc,
|
|
263
266
|
deadlineMs: usToMs(w.deadline),
|
|
264
|
-
endMs:
|
|
267
|
+
endMs: endMsFromUs(w.end),
|
|
265
268
|
};
|
|
266
269
|
}
|
|
267
270
|
|
|
@@ -275,3 +278,44 @@ export function decodeBackstopTransfer(w: WireBackstopTransfer): BackstopTransfe
|
|
|
275
278
|
time: usToMs(w.timestamp_us),
|
|
276
279
|
};
|
|
277
280
|
}
|
|
281
|
+
|
|
282
|
+
export function decodeBridgeConfig(w: WireBridgeConfig): BridgeConfig {
|
|
283
|
+
return {
|
|
284
|
+
claimChainId: w.claim_chain_id,
|
|
285
|
+
sourceContract: w.source_contract,
|
|
286
|
+
version: w.version,
|
|
287
|
+
tokens: w.tokens.map((t) => ({
|
|
288
|
+
podToken: t.pod_token,
|
|
289
|
+
l1Token: t.l1_token,
|
|
290
|
+
decimals: t.decimals,
|
|
291
|
+
min: dec(t.min),
|
|
292
|
+
max: dec(t.max),
|
|
293
|
+
})),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* One withdrawal outcome.
|
|
299
|
+
*
|
|
300
|
+
* An unrecognised `error` spelling is carried through **verbatim**, never
|
|
301
|
+
* dropped. The node's reason enum is extensible and this app ships ahead of the
|
|
302
|
+
* fleet, so filtering to the spellings this build knows would turn a *failed*
|
|
303
|
+
* withdrawal into a claimable-looking one: the caller announces that the money
|
|
304
|
+
* is on its way and then waits for an L1 event that can never fire. Presence is
|
|
305
|
+
* what carries the meaning here — any reason at all means no claim — so only
|
|
306
|
+
* presence is decoded, and naming the reason is left to whatever renders it.
|
|
307
|
+
*/
|
|
308
|
+
export function decodeWithdrawal(w: WireWithdrawal): Withdrawal {
|
|
309
|
+
return {
|
|
310
|
+
id: w.withdrawal_id,
|
|
311
|
+
withdrawer: w.withdrawer,
|
|
312
|
+
to: w.to,
|
|
313
|
+
token: w.token,
|
|
314
|
+
amount: dec(w.amount),
|
|
315
|
+
// `||`, not `??`: an empty string is the wire saying "no reason", and it
|
|
316
|
+
// would otherwise be a present-but-falsy value that every `if (w.error)`
|
|
317
|
+
// reads as success while `error !== undefined` reads as failure.
|
|
318
|
+
error: w.error || undefined,
|
|
319
|
+
timeUs: w.timestamp_us,
|
|
320
|
+
};
|
|
321
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// What a perp fill did to the owner's position: opened, added to, reduced, closed
|
|
2
|
+
// or flipped it.
|
|
3
|
+
//
|
|
4
|
+
// A port of `classify_perp_order_direction` in `node/src/rpc/types.rs`, branch for
|
|
5
|
+
// branch and in the same order. It exists because the two sources of an order's
|
|
6
|
+
// direction have to agree: REST sends the server's label on `OrderResponse`, while
|
|
7
|
+
// `pod_orders_v2` sends the raw position and leaves the classification to the
|
|
8
|
+
// client. A divergence here would show one label on a streamed row and another after
|
|
9
|
+
// a refetch — so this file is a transcription, not an interpretation, and the test
|
|
10
|
+
// pins every branch.
|
|
11
|
+
|
|
12
|
+
import type { OrderDirection } from "../types/public.js";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Classify a position transition.
|
|
16
|
+
*
|
|
17
|
+
* `before` is not on the wire: it is `after - sign(size) * filledThisFill`, which is
|
|
18
|
+
* the same arithmetic the engine used to produce the pair (`buy_bookends` /
|
|
19
|
+
* `sell_bookends` in `trading/src/book.rs`), so deriving it loses nothing.
|
|
20
|
+
*/
|
|
21
|
+
export function classifyPerpDirection(before: bigint, after: bigint): OrderDirection {
|
|
22
|
+
if (before === 0n && after === 0n) return "reduce_long";
|
|
23
|
+
if (before === after) return before > 0n ? "reduce_long" : "reduce_short";
|
|
24
|
+
if (before === 0n && after > 0n) return "open_long";
|
|
25
|
+
if (before === 0n && after < 0n) return "open_short";
|
|
26
|
+
if (before > 0n && after === 0n) return "close_long";
|
|
27
|
+
if (before < 0n && after === 0n) return "close_short";
|
|
28
|
+
if (before > 0n && after < 0n) return "long_to_short";
|
|
29
|
+
if (before < 0n && after > 0n) return "short_to_long";
|
|
30
|
+
if (before > 0n && after > before) return "add_long";
|
|
31
|
+
if (before > 0n && after < before) return "reduce_long";
|
|
32
|
+
if (before < 0n && after < before) return "add_short";
|
|
33
|
+
if (before < 0n && after > before) return "reduce_short";
|
|
34
|
+
// Unreachable, and the Rust returns the same rather than erroring.
|
|
35
|
+
return "open_long";
|
|
36
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// `pod_orders_v2` frames -> the public `Order` map (ADR 0029).
|
|
2
|
+
//
|
|
3
|
+
// A frame is entity/event shaped: identity and terms cross the wire once, in
|
|
4
|
+
// `orders`, and everything after that is a reference. So decoding is two passes —
|
|
5
|
+
// materialize this batch's entities, then let the events say what happened to
|
|
6
|
+
// them and to orders already held. Status lives only in the events, which is what
|
|
7
|
+
// lets the server add transition kinds without changing the entity.
|
|
8
|
+
|
|
9
|
+
import type {
|
|
10
|
+
Address, AmendRejection, Order, OrderEvent, OrderEventFill, OrderEventKind, OrderStatus,
|
|
11
|
+
PartialFill, RejectCode, TerminalStatus,
|
|
12
|
+
} from "../types/public.js";
|
|
13
|
+
import type { WireOrderEntity, WireOrderEvent, WireOrdersFrame } from "../types/wire.js";
|
|
14
|
+
import { dec, endMsFromUs, usToMs } from "./units.js";
|
|
15
|
+
import { div } from "./fixed.js";
|
|
16
|
+
import { classifyPerpDirection } from "./direction.js";
|
|
17
|
+
|
|
18
|
+
export interface OrdersFrameContext {
|
|
19
|
+
/** The account the subscription is filtered to, used when the frame omits `accts`. */
|
|
20
|
+
account: Address;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Per-frame facts the events need. */
|
|
24
|
+
interface FrameFacts {
|
|
25
|
+
batchMs: number;
|
|
26
|
+
accts?: WireOrdersFrame["accts"];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Fold one frame into `byId`, in place, and report the transitions it applied.
|
|
31
|
+
*
|
|
32
|
+
* Events naming an order that is not in `byId` and not in this frame are skipped:
|
|
33
|
+
* they belong to an order resting outside the caller's window, and its terms have
|
|
34
|
+
* never been on the wire, so there is nothing to display — and nothing to report.
|
|
35
|
+
*
|
|
36
|
+
* The returned events carry the order as the *whole* frame left it, not as it stood
|
|
37
|
+
* mid-frame: they are collected while applying but the rows are mutated in place, so a
|
|
38
|
+
* consumer never sees a half-applied order.
|
|
39
|
+
*/
|
|
40
|
+
export function applyOrdersFrame(frame: WireOrdersFrame, byId: Map<string, Order>, ctx: OrdersFrameContext): OrderEvent[] {
|
|
41
|
+
// The book and the batch are frame constants: resolved once, not per entity.
|
|
42
|
+
const batchMs = usToMs(frame.batch);
|
|
43
|
+
const facts: FrameFacts = { batchMs, accts: frame.accts };
|
|
44
|
+
const created = frame.orders.map((e) => decodeEntity(e, frame, batchMs, ctx.account));
|
|
45
|
+
|
|
46
|
+
const applied: OrderEvent[] = [];
|
|
47
|
+
for (const event of frame.events) {
|
|
48
|
+
// `o` indexes this frame's entities and `id` names one resting from an earlier
|
|
49
|
+
// batch — but an event kind added later (ADR 0029 §6 reserves several) may name
|
|
50
|
+
// an entity from *this* frame by id, so try both before giving up. `created` is
|
|
51
|
+
// not in `byId` yet: entities are inserted after the events, so their own
|
|
52
|
+
// `new`/`reject` decides the status they land with.
|
|
53
|
+
const target = event.o !== undefined
|
|
54
|
+
? created[event.o]
|
|
55
|
+
: byId.get(event.id ?? "") ?? created.find((o) => o.id === event.id);
|
|
56
|
+
if (!target) continue;
|
|
57
|
+
// `undefined` means a kind this version does not know, which is ignored rather than
|
|
58
|
+
// handed on as an event a consumer cannot act on (ADR 0029 §6). The switch is the
|
|
59
|
+
// only list of what is recognised — a separate one could disagree with it.
|
|
60
|
+
const outcome = applyEvent(event, target, facts);
|
|
61
|
+
if (outcome) {
|
|
62
|
+
applied.push({
|
|
63
|
+
kind: event.k as OrderEventKind,
|
|
64
|
+
order: target,
|
|
65
|
+
batchMs,
|
|
66
|
+
fill: outcome.fill,
|
|
67
|
+
amendRejection: outcome.amendRejection,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// After the events, not before: an entity's own `new`/`reject` decides the
|
|
73
|
+
// status it lands with. Entities left untouched by every event this version
|
|
74
|
+
// understands are still inserted — the frame said the order exists, and a
|
|
75
|
+
// transition from a newer server is no reason to drop the row.
|
|
76
|
+
for (const order of created) byId.set(order.id, order);
|
|
77
|
+
return applied;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function decodeEntity(e: WireOrderEntity, frame: WireOrdersFrame, batchMs: number, account: Address): Order {
|
|
81
|
+
const initialSize = dec(e.sz);
|
|
82
|
+
return {
|
|
83
|
+
id: e.id,
|
|
84
|
+
txHash: e.tx,
|
|
85
|
+
// The frame names the book, so this is exact rather than inferred. Whether
|
|
86
|
+
// that book is spot or perp is static market metadata, joined at read time by
|
|
87
|
+
// whoever needs it — freezing it here would strand every order decoded before
|
|
88
|
+
// the markets list loaded.
|
|
89
|
+
orderbookId: frame.book,
|
|
90
|
+
side: initialSize < 0n ? "sell" : "buy",
|
|
91
|
+
orderType: e.type === "market" ? "market" : "limit",
|
|
92
|
+
// Not on the entity: an order that rests is `active`, and the events below
|
|
93
|
+
// move it from there.
|
|
94
|
+
status: "active",
|
|
95
|
+
kind: (e.kind ?? "user_signed") as Order["kind"],
|
|
96
|
+
nonce: e.n,
|
|
97
|
+
// A frame with no `accts` covers exactly one account, so every row is its. An
|
|
98
|
+
// index the table does not reach falls back the same way rather than becoming an
|
|
99
|
+
// `undefined` typed as an address.
|
|
100
|
+
bidder: (e.a !== undefined ? frame.accts?.[e.a] : undefined) ?? account,
|
|
101
|
+
price: dec(e.px),
|
|
102
|
+
initialSize,
|
|
103
|
+
filledBase: 0n,
|
|
104
|
+
filledQuote: 0n,
|
|
105
|
+
fee: 0n,
|
|
106
|
+
endMs: endMsFromUs(e.end),
|
|
107
|
+
// When the order became real. The signed deadline is not on this wire and is
|
|
108
|
+
// deliberately not invented from the batch: REST reports both separately, so
|
|
109
|
+
// inclusion time is the one thing every source agrees on and the only honest
|
|
110
|
+
// key to order by.
|
|
111
|
+
includedMs: batchMs,
|
|
112
|
+
fills: [],
|
|
113
|
+
reduceOnly: e.reduce_only ?? false,
|
|
114
|
+
ioc: e.ioc ?? false,
|
|
115
|
+
triggerType: e.trigger as Order["triggerType"],
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Take the order's life-to-date totals off the event that reports them.
|
|
121
|
+
*
|
|
122
|
+
* Every fill, cancel and expiry carries all three, zero included (ADR 0029 §4.1) —
|
|
123
|
+
* so they are read unconditionally, and an order that leaves the book reports what
|
|
124
|
+
* it filled rather than keeping whatever it last had. Authoritative rather than
|
|
125
|
+
* accumulated, so a client that missed a fill cannot drift.
|
|
126
|
+
*/
|
|
127
|
+
function applyTotals(event: WireOrderEvent, order: Order): void {
|
|
128
|
+
order.filledBase = dec(event.tb);
|
|
129
|
+
order.filledQuote = dec(event.tq);
|
|
130
|
+
order.fee = dec(event.tf);
|
|
131
|
+
// Cleared, not skipped, when nothing is filled: a row reporting zero filled beside
|
|
132
|
+
// a fill price from before is worse than one with no fill price.
|
|
133
|
+
order.effectivePrice = order.filledBase > 0n ? div(order.filledQuote, order.filledBase) : undefined;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Apply one event. `undefined` when the kind is not one this version knows; otherwise what
|
|
138
|
+
* the event contributed beyond the order's own state — the fill, or the refused amendment.
|
|
139
|
+
*/
|
|
140
|
+
function applyEvent(
|
|
141
|
+
event: WireOrderEvent,
|
|
142
|
+
order: Order,
|
|
143
|
+
facts: FrameFacts,
|
|
144
|
+
): { fill?: OrderEventFill; amendRejection?: AmendRejection } | undefined {
|
|
145
|
+
switch (event.k) {
|
|
146
|
+
case "new":
|
|
147
|
+
order.status = "active";
|
|
148
|
+
return {};
|
|
149
|
+
case "reject":
|
|
150
|
+
order.status = "invalid";
|
|
151
|
+
order.rejectReason = event.why;
|
|
152
|
+
return {};
|
|
153
|
+
case "cancel":
|
|
154
|
+
order.status = "canceled";
|
|
155
|
+
applyTotals(event, order);
|
|
156
|
+
return {};
|
|
157
|
+
case "expire":
|
|
158
|
+
order.status = "expired";
|
|
159
|
+
applyTotals(event, order);
|
|
160
|
+
return {};
|
|
161
|
+
case "modify": {
|
|
162
|
+
order.price = dec(event.px);
|
|
163
|
+
// `sz` is an unsigned magnitude, so the side comes from the order we hold.
|
|
164
|
+
const sign = order.initialSize < 0n ? -1n : 1n;
|
|
165
|
+
order.initialSize = sign * dec(event.sz);
|
|
166
|
+
return {};
|
|
167
|
+
}
|
|
168
|
+
case "fill": {
|
|
169
|
+
applyTotals(event, order);
|
|
170
|
+
// `b`/`q` are this fill alone, and its time is the batch it cleared in — the
|
|
171
|
+
// auction's own timestamp rather than when this client happened to read it.
|
|
172
|
+
const base = dec(event.b);
|
|
173
|
+
const quote = dec(event.q);
|
|
174
|
+
const fill: PartialFill = { base, quote, price: div(quote, base), time: facts.batchMs };
|
|
175
|
+
// A real fill always has size. A zero-size one is the engine flipping status: the
|
|
176
|
+
// cap-to-filled amendment fabricates it so `st: filled` reaches the indexer, which
|
|
177
|
+
// reads status from fills alone. Its totals and status count; adding a
|
|
178
|
+
// `0.0000 @ $0.00` row to the order's fill history would only invent a trade.
|
|
179
|
+
if (base !== 0n) order.fills = [...order.fills, fill];
|
|
180
|
+
// A perp fill reports the position it left. The position it started from is
|
|
181
|
+
// that minus what this fill moved it — a buy raises it, a sell lowers it — and
|
|
182
|
+
// the transition is what says whether the order opened, added to, reduced,
|
|
183
|
+
// closed or flipped. Without it a client can only guess from the order's own
|
|
184
|
+
// side and `reduceOnly`, which calls a plain sell that closed a long an
|
|
185
|
+
// "Open Short".
|
|
186
|
+
if (event.pa !== undefined) {
|
|
187
|
+
const after = dec(event.pa);
|
|
188
|
+
const before = after - (order.initialSize < 0n ? -base : base);
|
|
189
|
+
// A forced close is labelled by how it came about, not by the transition it
|
|
190
|
+
// made — `order_direction_for_response` overrides the classifier the same way,
|
|
191
|
+
// and without this a liquidation reads `close_long` here and `liquidation`
|
|
192
|
+
// after a REST refetch.
|
|
193
|
+
order.direction = order.kind === "liquidation" ? "liquidation" : classifyPerpDirection(before, after);
|
|
194
|
+
}
|
|
195
|
+
// Present only on the fill that closed the order.
|
|
196
|
+
if (event.st) order.status = event.st as OrderStatus;
|
|
197
|
+
// Copied rather than shared: the same object is in `order.fills`, and attaching a
|
|
198
|
+
// per-event field to it would leak the event into the order's fill history.
|
|
199
|
+
return {
|
|
200
|
+
fill: { ...fill, totalBase: dec(event.tb), closedAs: event.st as TerminalStatus | undefined },
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
case "modify_reject":
|
|
204
|
+
// Reported, not applied: this answers an amendment that did not happen, so the order
|
|
205
|
+
// is left exactly as it was — which is also why it belongs to the event and not to
|
|
206
|
+
// the order. Without it a refused price change looks like one still in flight.
|
|
207
|
+
// `by` is the requester, not the owner — on `not_order_owner` it is precisely who
|
|
208
|
+
// does not own the order — so it is resolved separately from `a`.
|
|
209
|
+
return {
|
|
210
|
+
amendRejection: {
|
|
211
|
+
requestedPrice: dec(event.req_px),
|
|
212
|
+
requestedSize: dec(event.req_sz),
|
|
213
|
+
code: (event.code ?? "unspecified") as RejectCode,
|
|
214
|
+
message: event.why,
|
|
215
|
+
requestedBy: event.by !== undefined ? facts.accts?.[event.by] : undefined,
|
|
216
|
+
batchMs: facts.batchMs,
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
// ADR 0029 §6: kinds are open, so an unrecognised one falls through to
|
|
220
|
+
// `undefined` — applied to nothing, reported to nobody.
|
|
221
|
+
}
|
|
222
|
+
}
|
package/src/codec/units.ts
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
// strings; wire timestamps are microseconds. Public surface uses `bigint`
|
|
3
3
|
// (1e18-scaled) and millisecond `number` timestamps.
|
|
4
4
|
|
|
5
|
+
// "wad" is the DappHub/MakerDAO name for a fixed-point number carrying 18
|
|
6
|
+
// digits of precision, which is the scale every pod amount is in. Spelled out
|
|
7
|
+
// because the term is only obvious if you have met it before, and code that
|
|
8
|
+
// mixes scales — bridge withdrawals settle in the claim-chain token's decimals,
|
|
9
|
+
// not pod's — reads very differently depending on whether you know that.
|
|
5
10
|
export const WAD = 1_000_000_000_000_000_000n; // 1e18
|
|
6
11
|
export const WAD_DECIMALS = 18;
|
|
7
12
|
|
|
@@ -34,6 +39,22 @@ export function usToMsOpt(us: number | string | null | undefined): number | unde
|
|
|
34
39
|
return us === null || us === undefined ? undefined : usToMs(us);
|
|
35
40
|
}
|
|
36
41
|
|
|
42
|
+
/**
|
|
43
|
+
* An order's TTL expiry: microseconds -> milliseconds, or undefined when it never
|
|
44
|
+
* expires.
|
|
45
|
+
*
|
|
46
|
+
* "Never" has two spellings on the wire. `pod_orders_v2` omits the field; REST
|
|
47
|
+
* sends the engine's `Timestamp::MAX` sentinel, a u128 that arrives as a 39-digit
|
|
48
|
+
* number no JS number can hold exactly. Anything past `Number.MAX_SAFE_INTEGER`
|
|
49
|
+
* micros — the year 2255 — is that sentinel rather than a TTL someone signed.
|
|
50
|
+
*/
|
|
51
|
+
export function endMsFromUs(us: number | string | null | undefined): number | undefined {
|
|
52
|
+
if (us === null || us === undefined) return undefined;
|
|
53
|
+
const n = typeof us === "string" ? Number(us) : us;
|
|
54
|
+
// `NaN` and `Infinity` both fail this comparison, so it is the whole guard.
|
|
55
|
+
return n <= Number.MAX_SAFE_INTEGER ? usToMs(n) : undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
37
58
|
/** Milliseconds -> microseconds (for request params that take micros). */
|
|
38
59
|
export function msToUs(ms: number): number {
|
|
39
60
|
return ms * 1000;
|
|
@@ -94,7 +115,9 @@ export function parseAmount(value: string, decimals: number = WAD_DECIMALS): big
|
|
|
94
115
|
const neg = value.trim().startsWith("-");
|
|
95
116
|
const clean = neg ? value.trim().slice(1) : value.trim();
|
|
96
117
|
const [whole = "0", frac = ""] = clean.split(".");
|
|
118
|
+
if (whole === "" && frac === "") throw new SyntaxError("Cannot convert empty amount to a BigInt");
|
|
97
119
|
const fracPadded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
98
|
-
const
|
|
120
|
+
const wholePart = whole === "" && frac !== "" ? "0" : whole;
|
|
121
|
+
const scaled = BigInt(wholePart) * 10n ** BigInt(decimals) + BigInt(fracPadded || "0");
|
|
99
122
|
return neg ? -scaled : scaled;
|
|
100
123
|
}
|
package/src/index.ts
CHANGED
|
@@ -47,3 +47,19 @@ export {
|
|
|
47
47
|
export {
|
|
48
48
|
RESOLUTION_SECONDS, RESOLUTION_PAGE_BUCKETS, RESOLUTIONS, isResolution,
|
|
49
49
|
} from "./codec/resolution.js";
|
|
50
|
+
|
|
51
|
+
// Withdrawal amount arithmetic (ADR 0033). Read-side, so a UI can size and
|
|
52
|
+
// validate a withdrawal without pulling the signing entry.
|
|
53
|
+
export {
|
|
54
|
+
withdrawStep, quantizeWithdrawAmount, toClaimAmount, toPodAmount,
|
|
55
|
+
maxWithdrawable, checkWithdrawAmount, type WithdrawRejection, bridgeTokenFor,
|
|
56
|
+
} from "./codec/bridge.js";
|
|
57
|
+
// Following a withdrawal onto the claim chain.
|
|
58
|
+
export {
|
|
59
|
+
fetchClaimStatus, waitForClaim, watchClaims, CLAIM_TOPIC,
|
|
60
|
+
type ClaimStatus, type ClaimOutcome, type WaitForClaimOptions,
|
|
61
|
+
type ClaimWatcher, type WatchClaimsOptions,
|
|
62
|
+
} from "./transport/claim.js";
|
|
63
|
+
// Only the options type: `WaitForClaimOptions` extends it, so declaration emit
|
|
64
|
+
// needs it public. The functions themselves stay internal.
|
|
65
|
+
export type { RpcOptions } from "./transport/jsonrpc.js";
|