@pod-network/trade-sdk 0.1.0-rc.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 +113 -0
- package/dist/client.d.ts +93 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +168 -0
- package/dist/client.js.map +1 -0
- package/dist/codec/decode.d.ts +22 -0
- package/dist/codec/decode.d.ts.map +1 -0
- package/dist/codec/decode.js +251 -0
- package/dist/codec/decode.js.map +1 -0
- package/dist/codec/fixed.d.ts +11 -0
- package/dist/codec/fixed.d.ts.map +1 -0
- package/dist/codec/fixed.js +37 -0
- package/dist/codec/fixed.js.map +1 -0
- package/dist/codec/resolution.d.ts +14 -0
- package/dist/codec/resolution.d.ts.map +1 -0
- package/dist/codec/resolution.js +35 -0
- package/dist/codec/resolution.js.map +1 -0
- package/dist/codec/units.d.ts +35 -0
- package/dist/codec/units.d.ts.map +1 -0
- package/dist/codec/units.js +86 -0
- package/dist/codec/units.js.map +1 -0
- package/dist/datafeed.d.ts +4 -0
- package/dist/datafeed.d.ts.map +1 -0
- package/dist/datafeed.js +73 -0
- package/dist/datafeed.js.map +1 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +19 -0
- package/dist/index.js.map +1 -0
- package/dist/stores/resource.d.ts +50 -0
- package/dist/stores/resource.d.ts.map +1 -0
- package/dist/stores/resource.js +154 -0
- package/dist/stores/resource.js.map +1 -0
- package/dist/sync/account-metrics.d.ts +26 -0
- package/dist/sync/account-metrics.d.ts.map +1 -0
- package/dist/sync/account-metrics.js +41 -0
- package/dist/sync/account-metrics.js.map +1 -0
- package/dist/sync/candles.d.ts +68 -0
- package/dist/sync/candles.d.ts.map +1 -0
- package/dist/sync/candles.js +318 -0
- package/dist/sync/candles.js.map +1 -0
- package/dist/sync/order-preview.d.ts +74 -0
- package/dist/sync/order-preview.d.ts.map +1 -0
- package/dist/sync/order-preview.js +86 -0
- package/dist/sync/order-preview.js.map +1 -0
- package/dist/sync/orders.d.ts +49 -0
- package/dist/sync/orders.d.ts.map +1 -0
- package/dist/sync/orders.js +210 -0
- package/dist/sync/orders.js.map +1 -0
- package/dist/sync/positions-live.d.ts +3 -0
- package/dist/sync/positions-live.d.ts.map +1 -0
- package/dist/sync/positions-live.js +86 -0
- package/dist/sync/positions-live.js.map +1 -0
- package/dist/sync/sources.d.ts +40 -0
- package/dist/sync/sources.d.ts.map +1 -0
- package/dist/sync/sources.js +197 -0
- package/dist/sync/sources.js.map +1 -0
- package/dist/transport/rest.d.ts +83 -0
- package/dist/transport/rest.d.ts.map +1 -0
- package/dist/transport/rest.js +146 -0
- package/dist/transport/rest.js.map +1 -0
- package/dist/transport/ws.d.ts +60 -0
- package/dist/transport/ws.d.ts.map +1 -0
- package/dist/transport/ws.js +235 -0
- package/dist/transport/ws.js.map +1 -0
- package/dist/types/public.d.ts +292 -0
- package/dist/types/public.d.ts.map +1 -0
- package/dist/types/public.js +4 -0
- package/dist/types/public.js.map +1 -0
- package/dist/types/wire.d.ts +283 -0
- package/dist/types/wire.d.ts.map +1 -0
- package/dist/types/wire.js +6 -0
- package/dist/types/wire.js.map +1 -0
- package/dist/write/delegation.d.ts +54 -0
- package/dist/write/delegation.d.ts.map +1 -0
- package/dist/write/delegation.js +81 -0
- package/dist/write/delegation.js.map +1 -0
- package/dist/write/index.d.ts +261 -0
- package/dist/write/index.d.ts.map +1 -0
- package/dist/write/index.js +428 -0
- package/dist/write/index.js.map +1 -0
- package/package.json +43 -0
- package/src/client.ts +229 -0
- package/src/codec/decode.ts +277 -0
- package/src/codec/fixed.ts +41 -0
- package/src/codec/resolution.ts +39 -0
- package/src/codec/units.ts +100 -0
- package/src/datafeed.ts +94 -0
- package/src/index.ts +49 -0
- package/src/stores/resource.ts +172 -0
- package/src/sync/account-metrics.ts +71 -0
- package/src/sync/candles.ts +326 -0
- package/src/sync/order-preview.ts +152 -0
- package/src/sync/orders.ts +205 -0
- package/src/sync/positions-live.ts +102 -0
- package/src/sync/sources.ts +239 -0
- package/src/transport/rest.ts +213 -0
- package/src/transport/ws.ts +255 -0
- package/src/types/public.ts +335 -0
- package/src/types/wire.ts +301 -0
- package/src/write/delegation.ts +113 -0
- package/src/write/index.ts +642 -0
package/README.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# @pod-network/trade-sdk
|
|
2
|
+
|
|
3
|
+
Read/stream market-data SDK for the pod trading indexer. It seeds initial values
|
|
4
|
+
from the cacheable REST API, then keeps everything live over **one multiplexed
|
|
5
|
+
WebSocket**, holds it in memory, and exposes it through a tiny, framework-agnostic
|
|
6
|
+
`Resource` abstraction. No polling.
|
|
7
|
+
|
|
8
|
+
> **Scope:** read/stream only. Order submission (nonce management, recovery) is a
|
|
9
|
+
> separate library — see `doc/ts-sdk-design.md`.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install @pod-network/trade-sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Quick start
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { PodTradeClient } from "@pod-network/trade-sdk";
|
|
21
|
+
|
|
22
|
+
const client = new PodTradeClient({
|
|
23
|
+
restUrl: "https://<indexer-rest-host>", // /clob/* REST API (consumer config)
|
|
24
|
+
wsUrl: "wss://<indexer-ws-host>", // eth_subscribe WebSocket
|
|
25
|
+
});
|
|
26
|
+
client.connect();
|
|
27
|
+
|
|
28
|
+
const markets = client.markets;
|
|
29
|
+
const off = markets.subscribe(() => console.log(markets.get()));
|
|
30
|
+
await markets.ready();
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Framework bindings
|
|
34
|
+
|
|
35
|
+
The SDK ships no framework bindings — every resource is a `{ get(), subscribe(cb) }`
|
|
36
|
+
store, so it drops straight into React's `useSyncExternalStore`, Vue's
|
|
37
|
+
`shallowRef`, Svelte stores, etc.
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
// React, in one line — no provider, no library hook needed:
|
|
41
|
+
const ob = useSyncExternalStore(
|
|
42
|
+
(cb) => client.orderbook(id, { depth: 20 }).subscribe(cb),
|
|
43
|
+
() => client.orderbook(id, { depth: 20 }).get(),
|
|
44
|
+
);
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## API surface
|
|
48
|
+
|
|
49
|
+
- **Layer 1 (low-level, exposed):** `client.rest.*` typed one-shot reads and
|
|
50
|
+
`client.ws.subscribe(channel, params, onMessage)` raw subscriptions.
|
|
51
|
+
- **Layer 2 (resources):** `client.status`, `.markets`, `.market(id)`,
|
|
52
|
+
`.orderbook(id,{depth})`, `.positions(account)`, `.triggers(account)`,
|
|
53
|
+
`.backstopTransfers(account)`, `.candles(id, resolution, range)` (a
|
|
54
|
+
`SeriesResource` with `setWindow`/`loadOlder`), `.orders(account, query)`.
|
|
55
|
+
- **Charting:** `createPodDatafeed(client)` returns an `IDatafeedChartApi`-shaped
|
|
56
|
+
object for the TradingView Charting Library (framework-agnostic, no React).
|
|
57
|
+
|
|
58
|
+
All monetary values are `bigint` (1e18-scaled; use `formatAmount`/`toNumber`/
|
|
59
|
+
`parseAmount`); all timestamps are millisecond `number`s.
|
|
60
|
+
|
|
61
|
+
## How caching / low traffic works
|
|
62
|
+
|
|
63
|
+
- Each resource **seeds once** over REST, then lives off WS pushes — no polling.
|
|
64
|
+
- One WebSocket, ref-counted: N subscribers to the same market = one server
|
|
65
|
+
subscription.
|
|
66
|
+
- Candle history is fetched as **epoch-anchored canonical pages** (per
|
|
67
|
+
resolution), so settled pages are byte-identical across clients/time and the
|
|
68
|
+
server flags them `immutable` — the browser/CDN serve them, the SDK never
|
|
69
|
+
re-requests them. The forming bar is built in memory from the `pod_candles`
|
|
70
|
+
tick stream, so the hot edge costs zero extra requests.
|
|
71
|
+
|
|
72
|
+
## Build
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
npm install && npm run build # build the package to dist/
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Working on the SDK and a consumer together
|
|
79
|
+
|
|
80
|
+
The consumer's committed dependency is always the published version. To iterate
|
|
81
|
+
locally, link this package into it instead of editing that dependency:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
cd ts-sdk && npm run build && npm link
|
|
85
|
+
cd ../../frontend && npm link @pod-network/trade-sdk
|
|
86
|
+
# undo
|
|
87
|
+
npm unlink @pod-network/trade-sdk && npm ci
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`dist/` is what consumers import, so rebuild after each change. Nothing is
|
|
91
|
+
committed on either side, so a local path can never leak into a release.
|
|
92
|
+
|
|
93
|
+
## Releasing
|
|
94
|
+
|
|
95
|
+
Publishing is driven by a **`ts-sdk-v*`** tag, which is deliberately distinct
|
|
96
|
+
from the repo-wide `v*` tag that `release.yml` uses to zip every SDK into a
|
|
97
|
+
GitHub Release — so a TypeScript release doesn't drag `rust-sdk` along:
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
# 1. bump the version in package.json, commit it
|
|
101
|
+
# 2. tag it — the tag must match package.json or the job fails
|
|
102
|
+
git tag ts-sdk-v0.1.0 && git push origin ts-sdk-v0.1.0
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`publish-ts-sdk.yml` then typechecks, builds and publishes to npm with
|
|
106
|
+
provenance. Two things worth knowing:
|
|
107
|
+
|
|
108
|
+
- A version containing a hyphen (`0.2.0-rc.0`) publishes under the **`rc`**
|
|
109
|
+
dist-tag, leaving `latest` alone — so prereleases never become the default
|
|
110
|
+
install. Use one to rehearse a release; npm versions can never be reused.
|
|
111
|
+
- `dist/` is gitignored and built during the release, and `prepublishOnly`
|
|
112
|
+
rebuilds it on any manual `npm publish` too, so a stale or empty `dist/`
|
|
113
|
+
can't ship.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { Address, BackstopTransfer, Balances, LeaderboardPage, LeaderboardQuery, Market, MarketId, PositionsSnapshot, Resolution, Status, TimeRange, Trigger, TriggersQuery, TxExplorer, OrdersQuery } from "./types/public.js";
|
|
2
|
+
import { PodRestClient } from "./transport/rest.js";
|
|
3
|
+
import { PodWsClient, type WebSocketCtor } from "./transport/ws.js";
|
|
4
|
+
import { type Resource } from "./stores/resource.js";
|
|
5
|
+
import { type MarketsCache } from "./sync/sources.js";
|
|
6
|
+
import { CandleSeries } from "./sync/candles.js";
|
|
7
|
+
import { OrderHistory } from "./sync/orders.js";
|
|
8
|
+
export interface PodTradeClientOptions {
|
|
9
|
+
restUrl: string;
|
|
10
|
+
wsUrl: string;
|
|
11
|
+
/** Node JSON-RPC HTTP endpoint — needed only for tx features (e.g. mint). */
|
|
12
|
+
rpcUrl?: string;
|
|
13
|
+
fetch?: typeof fetch;
|
|
14
|
+
WebSocket?: WebSocketCtor;
|
|
15
|
+
reconnect?: {
|
|
16
|
+
maxDelayMs?: number;
|
|
17
|
+
idleTimeoutMs?: number;
|
|
18
|
+
};
|
|
19
|
+
/** Periodic REST re-alignment for positions (ms). Default 60_000; 0 disables. */
|
|
20
|
+
positionResyncMs?: number;
|
|
21
|
+
/** Periodic REST re-poll of market 24h stats (ms). Default 30_000; 0 disables. */
|
|
22
|
+
marketResyncMs?: number;
|
|
23
|
+
/**
|
|
24
|
+
* Optional persistence for the static markets list (localStorage-backed in a
|
|
25
|
+
* browser), so market-keyed UI mounts instantly on repeat visits. Key it per
|
|
26
|
+
* backend environment — the list differs between them.
|
|
27
|
+
*/
|
|
28
|
+
marketsCache?: MarketsCache;
|
|
29
|
+
}
|
|
30
|
+
export declare class PodTradeClient {
|
|
31
|
+
readonly rest: PodRestClient;
|
|
32
|
+
readonly ws: PodWsClient;
|
|
33
|
+
private readonly ctx;
|
|
34
|
+
private readonly cache;
|
|
35
|
+
private readonly rpcUrl?;
|
|
36
|
+
private readonly fetchFn?;
|
|
37
|
+
constructor(opts: PodTradeClientOptions);
|
|
38
|
+
connect(): void;
|
|
39
|
+
/**
|
|
40
|
+
* Re-seed an account's cached resources (positions, balances, triggers —
|
|
41
|
+
* and anything derived from them). For out-of-band mutations the streams
|
|
42
|
+
* don't announce (e.g. a mint, or a trigger update — `pod_triggers` only
|
|
43
|
+
* pushes on ticks with order activity); stream-covered state needs no
|
|
44
|
+
* manual refresh. Address-case-insensitive: resources may have been created
|
|
45
|
+
* under a checksummed address while callers pass the wire's lowercase form.
|
|
46
|
+
*/
|
|
47
|
+
refresh(account: Address): void;
|
|
48
|
+
/**
|
|
49
|
+
* Faucet mint (test environments where the node sets `minting_allowed`):
|
|
50
|
+
* credit `to` — by default straight into the CLOB — wait for the receipt,
|
|
51
|
+
* then refresh the account's cached resources, since a mint emits no account
|
|
52
|
+
* tick and would otherwise only appear on the next periodic resync. Mint txs
|
|
53
|
+
* are gas-exempt and signer-irrelevant (signed by a one-shot throwaway key
|
|
54
|
+
* inside the SDK), so no wallet or delegation is needed. Requires `rpcUrl`
|
|
55
|
+
* in the client options; the /write entry is loaded on demand.
|
|
56
|
+
*/
|
|
57
|
+
mint(to: Address, tokens: Array<{
|
|
58
|
+
token?: Address;
|
|
59
|
+
amount: bigint;
|
|
60
|
+
}>, opts?: {
|
|
61
|
+
depositToClob?: boolean;
|
|
62
|
+
onSubmitted?: (hash: string) => void;
|
|
63
|
+
}): Promise<{
|
|
64
|
+
transactionHash: string;
|
|
65
|
+
}>;
|
|
66
|
+
close(): void;
|
|
67
|
+
private memo;
|
|
68
|
+
get status(): Resource<Status>;
|
|
69
|
+
get markets(): Resource<Market[]>;
|
|
70
|
+
market(id: MarketId): Resource<Market>;
|
|
71
|
+
orderbook(id: MarketId, opts?: {
|
|
72
|
+
depth?: number;
|
|
73
|
+
}): Resource<import("./types/public.js").Orderbook>;
|
|
74
|
+
positions(account: Address): Resource<PositionsSnapshot>;
|
|
75
|
+
/**
|
|
76
|
+
* Positions with mark-driven fields (uPnL, notional, equity, account value,
|
|
77
|
+
* withdrawable) kept live off the market stream between snapshots, and
|
|
78
|
+
* re-aligned to the backend on every snapshot / periodic REST resync.
|
|
79
|
+
*/
|
|
80
|
+
livePositions(account: Address): Resource<PositionsSnapshot>;
|
|
81
|
+
triggers(account: Address, _query?: TriggersQuery): Resource<Trigger[]>;
|
|
82
|
+
/** Live spot holdings + native cash. */
|
|
83
|
+
balances(account: Address): Resource<Balances>;
|
|
84
|
+
/** Leaderboard (ranked accounts by net PnL). One-shot REST; paginate via
|
|
85
|
+
* `{ limit, offset }`. Not a stream — call again to refresh. */
|
|
86
|
+
leaderboard(query?: LeaderboardQuery): Promise<LeaderboardPage>;
|
|
87
|
+
/** Explorer view of a transaction by hash. One-shot. */
|
|
88
|
+
transaction(hash: string): Promise<TxExplorer>;
|
|
89
|
+
backstopTransfers(account: Address): Resource<BackstopTransfer[]>;
|
|
90
|
+
candles(id: MarketId, resolution: Resolution, range?: TimeRange): CandleSeries;
|
|
91
|
+
orders(account: Address, query?: OrdersQuery): OrderHistory;
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,EAAE,QAAQ,EACxF,iBAAiB,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,WAAW,EAClG,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,KAAK,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAmD,KAAK,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AACtG,OAAO,EAEL,KAAK,YAAY,EAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,mBA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CAAC,EAAE,WAAW,GAAG,YAAY;CAiB5D"}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { PodRestClient } from "./transport/rest.js";
|
|
2
|
+
import { PodWsClient } from "./transport/ws.js";
|
|
3
|
+
import { BaseResource, combineResources, derivedResource } from "./stores/resource.js";
|
|
4
|
+
import { balancesSource, marketsSource, orderbookSource, positionsSource, statusSource, triggersSource, } from "./sync/sources.js";
|
|
5
|
+
import { CandleSeries } from "./sync/candles.js";
|
|
6
|
+
import { OrderHistory } from "./sync/orders.js";
|
|
7
|
+
import { enrichPositions } from "./sync/positions-live.js";
|
|
8
|
+
export class PodTradeClient {
|
|
9
|
+
rest;
|
|
10
|
+
ws;
|
|
11
|
+
ctx;
|
|
12
|
+
cache = new Map();
|
|
13
|
+
rpcUrl;
|
|
14
|
+
fetchFn;
|
|
15
|
+
constructor(opts) {
|
|
16
|
+
this.rpcUrl = opts.rpcUrl;
|
|
17
|
+
this.fetchFn = opts.fetch;
|
|
18
|
+
this.rest = new PodRestClient({ restUrl: opts.restUrl, fetch: opts.fetch });
|
|
19
|
+
this.ws = new PodWsClient({
|
|
20
|
+
wsUrl: opts.wsUrl,
|
|
21
|
+
WebSocket: opts.WebSocket,
|
|
22
|
+
maxDelayMs: opts.reconnect?.maxDelayMs,
|
|
23
|
+
idleTimeoutMs: opts.reconnect?.idleTimeoutMs,
|
|
24
|
+
});
|
|
25
|
+
this.ctx = {
|
|
26
|
+
rest: this.rest,
|
|
27
|
+
ws: this.ws,
|
|
28
|
+
positionResyncMs: opts.positionResyncMs ?? 60_000,
|
|
29
|
+
marketResyncMs: opts.marketResyncMs ?? 30_000,
|
|
30
|
+
marketsCache: opts.marketsCache,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
connect() { this.ws.connect(); }
|
|
34
|
+
/**
|
|
35
|
+
* Re-seed an account's cached resources (positions, balances, triggers —
|
|
36
|
+
* and anything derived from them). For out-of-band mutations the streams
|
|
37
|
+
* don't announce (e.g. a mint, or a trigger update — `pod_triggers` only
|
|
38
|
+
* pushes on ticks with order activity); stream-covered state needs no
|
|
39
|
+
* manual refresh. Address-case-insensitive: resources may have been created
|
|
40
|
+
* under a checksummed address while callers pass the wire's lowercase form.
|
|
41
|
+
*/
|
|
42
|
+
refresh(account) {
|
|
43
|
+
const want = new Set(["positions", "balances", "triggers"].map((k) => `${k}:${account.toLowerCase()}`));
|
|
44
|
+
for (const [key, r] of this.cache) {
|
|
45
|
+
if (want.has(key.toLowerCase()) && r instanceof BaseResource)
|
|
46
|
+
r.refresh();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Faucet mint (test environments where the node sets `minting_allowed`):
|
|
51
|
+
* credit `to` — by default straight into the CLOB — wait for the receipt,
|
|
52
|
+
* then refresh the account's cached resources, since a mint emits no account
|
|
53
|
+
* tick and would otherwise only appear on the next periodic resync. Mint txs
|
|
54
|
+
* are gas-exempt and signer-irrelevant (signed by a one-shot throwaway key
|
|
55
|
+
* inside the SDK), so no wallet or delegation is needed. Requires `rpcUrl`
|
|
56
|
+
* in the client options; the /write entry is loaded on demand.
|
|
57
|
+
*/
|
|
58
|
+
async mint(to, tokens, opts) {
|
|
59
|
+
if (!this.rpcUrl)
|
|
60
|
+
throw new Error("PodTradeClient.mint requires `rpcUrl` in the client options");
|
|
61
|
+
const { mint } = await import("./write/index.js");
|
|
62
|
+
const receipt = await mint({
|
|
63
|
+
rpcUrl: this.rpcUrl,
|
|
64
|
+
to,
|
|
65
|
+
tokens,
|
|
66
|
+
depositToClob: opts?.depositToClob,
|
|
67
|
+
onSubmitted: opts?.onSubmitted,
|
|
68
|
+
fetch: this.fetchFn,
|
|
69
|
+
});
|
|
70
|
+
this.refresh(to);
|
|
71
|
+
return receipt;
|
|
72
|
+
}
|
|
73
|
+
close() {
|
|
74
|
+
for (const r of this.cache.values())
|
|
75
|
+
r.destroy();
|
|
76
|
+
this.cache.clear();
|
|
77
|
+
this.ws.close();
|
|
78
|
+
}
|
|
79
|
+
memo(key, make) {
|
|
80
|
+
const hit = this.cache.get(key);
|
|
81
|
+
if (hit)
|
|
82
|
+
return hit;
|
|
83
|
+
const made = make();
|
|
84
|
+
this.cache.set(key, made);
|
|
85
|
+
return made;
|
|
86
|
+
}
|
|
87
|
+
get status() {
|
|
88
|
+
return this.memo("status", () => new BaseResource(statusSource(this.ctx)));
|
|
89
|
+
}
|
|
90
|
+
get markets() {
|
|
91
|
+
return this.memo("markets", () => new BaseResource(marketsSource(this.ctx)));
|
|
92
|
+
}
|
|
93
|
+
market(id) {
|
|
94
|
+
return this.memo(`market:${id}`, () => derivedResource(this.markets, (list) => list?.find((m) => m.id === id)));
|
|
95
|
+
}
|
|
96
|
+
orderbook(id, opts) {
|
|
97
|
+
const depth = opts?.depth;
|
|
98
|
+
return this.memo(`orderbook:${id}:${depth ?? ""}`, () => new BaseResource(orderbookSource(this.ctx, id, depth)));
|
|
99
|
+
}
|
|
100
|
+
positions(account) {
|
|
101
|
+
return this.memo(`positions:${account}`, () => new BaseResource(positionsSource(this.ctx, account)));
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Positions with mark-driven fields (uPnL, notional, equity, account value,
|
|
105
|
+
* withdrawable) kept live off the market stream between snapshots, and
|
|
106
|
+
* re-aligned to the backend on every snapshot / periodic REST resync.
|
|
107
|
+
*/
|
|
108
|
+
livePositions(account) {
|
|
109
|
+
return this.memo(`livePositions:${account}`, () => {
|
|
110
|
+
const positions = this.positions(account);
|
|
111
|
+
const markets = this.markets;
|
|
112
|
+
return combineResources([positions, markets], () => {
|
|
113
|
+
const snap = positions.get();
|
|
114
|
+
if (!snap)
|
|
115
|
+
return undefined;
|
|
116
|
+
return enrichPositions(snap, markets.get() ?? []);
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
triggers(account, _query) {
|
|
121
|
+
return this.memo(`triggers:${account}`, () => new BaseResource(triggersSource(this.ctx, account)));
|
|
122
|
+
}
|
|
123
|
+
/** Live spot holdings + native cash. */
|
|
124
|
+
balances(account) {
|
|
125
|
+
return this.memo(`balances:${account}`, () => new BaseResource(balancesSource(this.ctx, account)));
|
|
126
|
+
}
|
|
127
|
+
/** Leaderboard (ranked accounts by net PnL). One-shot REST; paginate via
|
|
128
|
+
* `{ limit, offset }`. Not a stream — call again to refresh. */
|
|
129
|
+
leaderboard(query) {
|
|
130
|
+
return this.rest.leaderboard(query);
|
|
131
|
+
}
|
|
132
|
+
/** Explorer view of a transaction by hash. One-shot. */
|
|
133
|
+
transaction(hash) {
|
|
134
|
+
return this.rest.transaction(hash);
|
|
135
|
+
}
|
|
136
|
+
backstopTransfers(account) {
|
|
137
|
+
return this.memo(`backstop:${account}`, () => new BaseResource((h) => {
|
|
138
|
+
let alive = true;
|
|
139
|
+
this.rest.backstopTransfers(account)
|
|
140
|
+
.then((p) => { if (alive)
|
|
141
|
+
h.set(p.transfers); })
|
|
142
|
+
.catch((e) => h.fail(e));
|
|
143
|
+
return () => { alive = false; };
|
|
144
|
+
}));
|
|
145
|
+
}
|
|
146
|
+
candles(id, resolution, range) {
|
|
147
|
+
const series = this.memo(`candles:${id}:${resolution}`, () => new CandleSeries(this.ctx, id, resolution, range));
|
|
148
|
+
if (range)
|
|
149
|
+
series.setWindow(range);
|
|
150
|
+
return series;
|
|
151
|
+
}
|
|
152
|
+
orders(account, query) {
|
|
153
|
+
const key = `orders:${account}:${query ? JSON.stringify(query) : ""}`;
|
|
154
|
+
// WS stream orders identify their market by token pair; resolve it against
|
|
155
|
+
// the markets list (unambiguous: base tokens are unique per market — if a
|
|
156
|
+
// pair ever matched several markets we leave orderbookId unset rather than
|
|
157
|
+
// guess). Reads the markets snapshot, so it adds no extra subscription.
|
|
158
|
+
const resolveOrderbookId = (pair) => {
|
|
159
|
+
const base = pair.base.toLowerCase();
|
|
160
|
+
const quote = pair.quote.toLowerCase();
|
|
161
|
+
const matches = this.markets.get()?.filter((m) => m.base?.address.toLowerCase() === base && m.quote?.address.toLowerCase() === quote);
|
|
162
|
+
const only = matches && matches.length === 1 ? matches[0] : undefined;
|
|
163
|
+
return only?.id;
|
|
164
|
+
};
|
|
165
|
+
return this.memo(key, () => new OrderHistory(this.ctx, account, query, resolveOrderbookId));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAsB,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,eAAe,EAAiB,MAAM,sBAAsB,CAAC;AACtG,OAAO,EACL,cAAc,EAAE,aAAa,EAAE,eAAe,EAAE,eAAe,EAAE,YAAY,EAAE,cAAc,GAE9F,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAwB3D,MAAM,OAAO,cAAc;IAChB,IAAI,CAAgB;IACpB,EAAE,CAAc;IACR,GAAG,CAAc;IACjB,KAAK,GAAG,IAAI,GAAG,EAAgC,CAAC;IAChD,MAAM,CAAU;IAChB,OAAO,CAAgB;IAExC,YAAY,IAA2B;QACrC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,aAAa,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAC5E,IAAI,CAAC,EAAE,GAAG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C,CAAC,CAAC,SAAS,CAAC;YACtE,OAAO,IAAI,EAAE,EAAE,CAAC;QAClB,CAAC,CAAC;QACF,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,YAAY,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,kBAAkB,CAAC,CAAC,CAAC;IAC9F,CAAC;CACF"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Bar, BackstopTransfer, Balances, LeaderboardPage, Market, Order, Orderbook, PositionsSnapshot, SpotHolding, Status, Trigger } from "../types/public.js";
|
|
2
|
+
import type { WireBackstopTransfer, WireBalances, WireCandle, WireLeaderboard, WireMarketDynamics, WireMarketStatic, WireOrder, WireOrderbook, WirePositionsSnapshot, WireSpotHolding, WireStatus, WireTrigger } from "../types/wire.js";
|
|
3
|
+
export declare function decodeStatus(w: WireStatus): Status;
|
|
4
|
+
/** Static market identity. Dynamics are merged in later by the market store. */
|
|
5
|
+
export declare function decodeMarketStatic(w: WireMarketStatic): Market;
|
|
6
|
+
/** Dynamics fields (clearing/24h/perp) as a partial Market patch. */
|
|
7
|
+
export declare function decodeMarketDynamics(w: WireMarketDynamics): Partial<Market> & {
|
|
8
|
+
id: string;
|
|
9
|
+
};
|
|
10
|
+
export declare function decodeCandle(w: WireCandle): Bar;
|
|
11
|
+
export declare function decodeOrder(w: WireOrder): Order;
|
|
12
|
+
export declare function decodeOrderbook(w: WireOrderbook): Orderbook;
|
|
13
|
+
export declare function decodePositions(w: WirePositionsSnapshot): PositionsSnapshot;
|
|
14
|
+
export declare function decodeSpotHolding(w: WireSpotHolding): SpotHolding;
|
|
15
|
+
export declare function decodeBalances(w: WireBalances): Balances;
|
|
16
|
+
/** Decode a ranked-accounts page (REST `/clob/leaderboard`). `offset` makes the
|
|
17
|
+
* ranks 1-based over the full ordering. PnL = unrealized + realized (the rank
|
|
18
|
+
* key); `%` is suppressed to 0 when the basis (accountValue − unrealized) is dust. */
|
|
19
|
+
export declare function decodeLeaderboard(w: WireLeaderboard, offset?: number): LeaderboardPage;
|
|
20
|
+
export declare function decodeTrigger(w: WireTrigger): Trigger;
|
|
21
|
+
export declare function decodeBackstopTransfer(w: WireBackstopTransfer): BackstopTransfer;
|
|
22
|
+
//# sourceMappingURL=decode.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decode.d.ts","sourceRoot":"","sources":["../../src/codec/decode.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,GAAG,EAAE,gBAAgB,EAAE,QAAQ,EAAoB,eAAe,EAAE,MAAM,EAAE,KAAK,EACjF,SAAS,EAAuC,iBAAiB,EAAE,WAAW,EAChE,MAAM,EAAE,OAAO,EAC9B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EACV,oBAAoB,EAAE,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,kBAAkB,EACnF,gBAAgB,EAAE,SAAS,EAAE,aAAa,EAC1C,qBAAqB,EAAE,eAAe,EAAoB,UAAU,EAAE,WAAW,EAClF,MAAM,kBAAkB,CAAC;AAG1B,wBAAgB,YAAY,CAAC,CAAC,EAAE,UAAU,GAAG,MAAM,CAElD;AAED,gFAAgF;AAChF,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,gBAAgB,GAAG,MAAM,CAe9D;AAED,qEAAqE;AACrE,wBAAgB,oBAAoB,CAAC,CAAC,EAAE,kBAAkB,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,CAe5F;AAED,wBAAgB,YAAY,CAAC,CAAC,EAAE,UAAU,GAAG,GAAG,CAU/C;AAWD,wBAAgB,WAAW,CAAC,CAAC,EAAE,SAAS,GAAG,KAAK,CA8B/C;AAED,wBAAgB,eAAe,CAAC,CAAC,EAAE,aAAa,GAAG,SAAS,CAwC3D;AAwCD,wBAAgB,eAAe,CAAC,CAAC,EAAE,qBAAqB,GAAG,iBAAiB,CAU3E;AAED,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,eAAe,GAAG,WAAW,CAajE;AAED,wBAAgB,cAAc,CAAC,CAAC,EAAE,YAAY,GAAG,QAAQ,CAOxD;AAED;;sFAEsF;AACtF,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,eAAe,EAAE,MAAM,SAAI,GAAG,eAAe,CAoBjF;AAED,wBAAgB,aAAa,CAAC,CAAC,EAAE,WAAW,GAAG,OAAO,CAgBrD;AAED,wBAAgB,sBAAsB,CAAC,CAAC,EAAE,oBAAoB,GAAG,gBAAgB,CAShF"}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// Wire -> public decoders. The single place hex/decimal-string/microsecond
|
|
2
|
+
// representations are normalized into bigint + millisecond numbers.
|
|
3
|
+
import { dec, decOpt, toNumber, usToMs, usToMsOpt } from "./units.js";
|
|
4
|
+
export function decodeStatus(w) {
|
|
5
|
+
return { solutionNow: usToMs(w.solution_now) };
|
|
6
|
+
}
|
|
7
|
+
/** Static market identity. Dynamics are merged in later by the market store. */
|
|
8
|
+
export function decodeMarketStatic(w) {
|
|
9
|
+
return {
|
|
10
|
+
id: w.id,
|
|
11
|
+
name: w.name,
|
|
12
|
+
type: w.market_type,
|
|
13
|
+
base: { address: w.base_token_address, symbol: w.base_token_symbol, name: w.base_token_name },
|
|
14
|
+
quote: { address: w.quote_token_address, symbol: w.quote_token_symbol, name: w.quote_token_name },
|
|
15
|
+
tickPrecision: dec(w.tick_precision),
|
|
16
|
+
lotSize: dec(w.lot_size),
|
|
17
|
+
maxLeverage: w.max_leverage,
|
|
18
|
+
fundingWindowUs: w.funding_window_us,
|
|
19
|
+
makerFee: dec(w.maker_fee),
|
|
20
|
+
takerFee: dec(w.taker_fee),
|
|
21
|
+
auctionIntervalMs: usToMs(w.auction_interval_us),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** Dynamics fields (clearing/24h/perp) as a partial Market patch. */
|
|
25
|
+
export function decodeMarketDynamics(w) {
|
|
26
|
+
return {
|
|
27
|
+
id: w.orderbook_id,
|
|
28
|
+
lastClearingPrice: dec(w.last_clearing_price),
|
|
29
|
+
volume24h: dec(w.volume_24h),
|
|
30
|
+
high24h: dec(w.high_24h),
|
|
31
|
+
low24h: dec(w.low_24h),
|
|
32
|
+
priceChange24hBps: w.price_change_24h,
|
|
33
|
+
oraclePrice: decOpt(w.oracle_price),
|
|
34
|
+
markPrice: decOpt(w.mark_price),
|
|
35
|
+
fundingRate: decOpt(w.funding_rate),
|
|
36
|
+
fundingIndex: decOpt(w.funding_index),
|
|
37
|
+
fundingLastUpdatedMs: usToMsOpt(w.funding_last_updated_us),
|
|
38
|
+
openInterest: decOpt(w.open_interest),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export function decodeCandle(w) {
|
|
42
|
+
return {
|
|
43
|
+
time: usToMs(w.timestamp),
|
|
44
|
+
open: dec(w.open),
|
|
45
|
+
high: dec(w.high),
|
|
46
|
+
low: dec(w.low),
|
|
47
|
+
close: dec(w.close),
|
|
48
|
+
volume: dec(w.volume),
|
|
49
|
+
quoteVolume: dec(w.quote_volume),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function decodePartialFill(w) {
|
|
53
|
+
return {
|
|
54
|
+
base: dec(w.base_amount),
|
|
55
|
+
quote: dec(w.quote_amount),
|
|
56
|
+
price: dec(w.price),
|
|
57
|
+
time: usToMs(w.timestamp),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export function decodeOrder(w) {
|
|
61
|
+
const initialSize = dec(w.initial_size);
|
|
62
|
+
return {
|
|
63
|
+
id: w.order_id,
|
|
64
|
+
txHash: w.tx_hash,
|
|
65
|
+
orderbookId: w.orderbook_id,
|
|
66
|
+
marketType: w.market_type,
|
|
67
|
+
pair: w.pair ? { base: w.pair.base, quote: w.pair.quote } : undefined,
|
|
68
|
+
// WS raw orders have no `side` field — derive it from the signed size.
|
|
69
|
+
side: w.side ?? (initialSize < 0n ? "sell" : "buy"),
|
|
70
|
+
orderType: w.order_type,
|
|
71
|
+
status: w.status,
|
|
72
|
+
kind: w.kind,
|
|
73
|
+
nonce: w.nonce,
|
|
74
|
+
bidder: w.bidder,
|
|
75
|
+
price: dec(w.price),
|
|
76
|
+
initialSize,
|
|
77
|
+
filledBase: dec(w.filled_base_amount),
|
|
78
|
+
filledQuote: dec(w.filled_quote_amount),
|
|
79
|
+
fee: dec(w.fee),
|
|
80
|
+
effectivePrice: decOpt(w.effective_price),
|
|
81
|
+
deadlineMs: usToMs(w.deadline),
|
|
82
|
+
endMs: usToMs(w.end),
|
|
83
|
+
includedMs: usToMsOpt(w.included_batch),
|
|
84
|
+
fills: (w.fills ?? []).map(decodePartialFill),
|
|
85
|
+
reduceOnly: w.reduce_only,
|
|
86
|
+
ioc: w.ioc,
|
|
87
|
+
direction: w.direction,
|
|
88
|
+
triggerType: (w.trigger_type ?? undefined),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
export function decodeOrderbook(w) {
|
|
92
|
+
const id = (w.orderbook_id ?? w.clob_id);
|
|
93
|
+
// Levels best-first; `total` is the cumulative size from the best price to here.
|
|
94
|
+
const levels = (entries, ascending) => {
|
|
95
|
+
const sorted = entries
|
|
96
|
+
.map(([price, t]) => ({ price: dec(price), volume: dec(t.volume) }))
|
|
97
|
+
.sort((a, b) => (ascending ? (a.price < b.price ? -1 : a.price > b.price ? 1 : 0)
|
|
98
|
+
: (b.price < a.price ? -1 : b.price > a.price ? 1 : 0)));
|
|
99
|
+
let cum = 0n;
|
|
100
|
+
const withTotal = sorted.map((l) => { cum += l.volume; return { price: l.price, volume: l.volume, total: cum }; });
|
|
101
|
+
// `depth` = cumulative size as a 0..1 fraction of this side's total (the
|
|
102
|
+
// deepest level → 1). Ready to use as a depth-bar width; no app-side scaling.
|
|
103
|
+
const sideMax = cum;
|
|
104
|
+
return withTotal.map((l) => ({ ...l, depth: sideMax > 0n ? Number(l.total) / Number(sideMax) : 0 }));
|
|
105
|
+
};
|
|
106
|
+
const bids = levels(Object.entries(w.buys), false);
|
|
107
|
+
const asks = levels(Object.entries(w.sells), true);
|
|
108
|
+
const bestBid = bids[0]?.price;
|
|
109
|
+
const bestAsk = asks[0]?.price;
|
|
110
|
+
const hasBoth = bestBid !== undefined && bestAsk !== undefined;
|
|
111
|
+
const mid = hasBoth ? (bestBid + bestAsk) / 2n : undefined;
|
|
112
|
+
const spread = hasBoth ? bestAsk - bestBid : undefined;
|
|
113
|
+
const spreadPct = mid && mid > 0n && spread !== undefined ? (Number(spread) / Number(mid)) * 100 : undefined;
|
|
114
|
+
return {
|
|
115
|
+
id,
|
|
116
|
+
timeMs: usToMs(w.timestamp),
|
|
117
|
+
clearingPrice: decOpt(w.clearing_price),
|
|
118
|
+
bids,
|
|
119
|
+
asks,
|
|
120
|
+
mid,
|
|
121
|
+
spread,
|
|
122
|
+
spreadPct,
|
|
123
|
+
bidCount: w.buys_count,
|
|
124
|
+
askCount: w.sells_count,
|
|
125
|
+
groupingPrecision: dec(w.grouping_precision),
|
|
126
|
+
oraclePrice: decOpt(w.oracle_price),
|
|
127
|
+
fundingRate: decOpt(w.funding_rate),
|
|
128
|
+
fundingIndex: decOpt(w.funding_index),
|
|
129
|
+
fundingLastUpdatedMs: usToMsOpt(w.funding_last_updated),
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function decodeSpotPosition(w) {
|
|
133
|
+
return {
|
|
134
|
+
kind: "spot",
|
|
135
|
+
orderbookId: w.orderbook_id,
|
|
136
|
+
token: w.token,
|
|
137
|
+
balance: dec(w.balance),
|
|
138
|
+
freeBalance: dec(w.free_balance),
|
|
139
|
+
lockedBalance: dec(w.locked_balance),
|
|
140
|
+
costBasis: dec(w.cost_basis),
|
|
141
|
+
markPrice: dec(w.mark_price),
|
|
142
|
+
unrealizedPnl: dec(w.unrealized_pnl),
|
|
143
|
+
realizedPnl: dec(w.realized_pnl),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
function decodePerpPosition(w) {
|
|
147
|
+
return {
|
|
148
|
+
kind: "perp",
|
|
149
|
+
orderbookId: w.orderbook_id,
|
|
150
|
+
side: w.side,
|
|
151
|
+
size: dec(w.size),
|
|
152
|
+
notional: dec(w.notional),
|
|
153
|
+
entryPrice: dec(w.entry_price),
|
|
154
|
+
markPrice: dec(w.mark_price),
|
|
155
|
+
margin: dec(w.margin),
|
|
156
|
+
leverage: toNumber(dec(w.leverage)), // wire is 1e18-scaled, not a plain int
|
|
157
|
+
fundingAccrued: dec(w.funding_accrued),
|
|
158
|
+
entryFunding: dec(w.entry_funding),
|
|
159
|
+
liquidationPrice: dec(w.liquidation_price),
|
|
160
|
+
unrealizedPnl: dec(w.unrealized_pnl),
|
|
161
|
+
realizedPnl: dec(w.realized_pnl),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
function decodePosition(w) {
|
|
165
|
+
return w.kind === "perp" ? decodePerpPosition(w) : decodeSpotPosition(w);
|
|
166
|
+
}
|
|
167
|
+
export function decodePositions(w) {
|
|
168
|
+
return {
|
|
169
|
+
positions: w.positions.map(decodePosition),
|
|
170
|
+
totalUnrealizedPnl: dec(w.total_unrealized_pnl),
|
|
171
|
+
totalRealizedPnl: dec(w.total_realized_pnl),
|
|
172
|
+
perpsEquity: dec(w.perps_equity),
|
|
173
|
+
accountValue: dec(w.account_value),
|
|
174
|
+
cash: dec(w.cash),
|
|
175
|
+
withdrawableCash: dec(w.withdrawable_cash),
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
export function decodeSpotHolding(w) {
|
|
179
|
+
return {
|
|
180
|
+
orderbookId: w.orderbook_id,
|
|
181
|
+
baseSymbol: w.base_symbol,
|
|
182
|
+
quoteSymbol: w.quote_symbol,
|
|
183
|
+
balance: dec(w.balance),
|
|
184
|
+
freeBalance: dec(w.free_balance),
|
|
185
|
+
lockedBalance: dec(w.locked_balance),
|
|
186
|
+
costBasis: dec(w.cost_basis),
|
|
187
|
+
markPrice: dec(w.mark_price),
|
|
188
|
+
unrealizedPnl: dec(w.unrealized_pnl),
|
|
189
|
+
realizedPnl: dec(w.realized_pnl),
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
export function decodeBalances(w) {
|
|
193
|
+
return {
|
|
194
|
+
holdings: w.balances.map(decodeSpotHolding),
|
|
195
|
+
cash: dec(w.cash),
|
|
196
|
+
withdrawableCash: dec(w.withdrawable_cash),
|
|
197
|
+
netDeposits: dec(w.net_deposits),
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/** Decode a ranked-accounts page (REST `/clob/leaderboard`). `offset` makes the
|
|
201
|
+
* ranks 1-based over the full ordering. PnL = unrealized + realized (the rank
|
|
202
|
+
* key); `%` is suppressed to 0 when the basis (accountValue − unrealized) is dust. */
|
|
203
|
+
export function decodeLeaderboard(w, offset = 0) {
|
|
204
|
+
const entries = (w.ranked ?? []).map((r, i) => {
|
|
205
|
+
const unrealizedPnl = dec(r.positions.total_unrealized_pnl);
|
|
206
|
+
const realizedPnl = dec(r.positions.total_realized_pnl);
|
|
207
|
+
const accountValue = dec(r.positions.account_value);
|
|
208
|
+
const pnl = unrealizedPnl + realizedPnl;
|
|
209
|
+
const basis = accountValue - unrealizedPnl;
|
|
210
|
+
const absAv = accountValue < 0n ? -accountValue : accountValue;
|
|
211
|
+
const safe = basis > 0n && absAv > 0n && basis * 1000n >= absAv * 5n; // basis ≥ 0.5% of |av|
|
|
212
|
+
return {
|
|
213
|
+
rank: offset + i + 1,
|
|
214
|
+
account: r.account,
|
|
215
|
+
accountValue,
|
|
216
|
+
unrealizedPnl,
|
|
217
|
+
realizedPnl,
|
|
218
|
+
pnl,
|
|
219
|
+
pnlPercent: safe ? (Number(pnl) / Number(basis)) * 100 : 0,
|
|
220
|
+
};
|
|
221
|
+
});
|
|
222
|
+
return { entries, total: w.total ?? 0 };
|
|
223
|
+
}
|
|
224
|
+
export function decodeTrigger(w) {
|
|
225
|
+
return {
|
|
226
|
+
orderbookId: w.orderbook_id,
|
|
227
|
+
orderId: w.order_id,
|
|
228
|
+
txHash: w.tx_hash,
|
|
229
|
+
bidder: w.bidder,
|
|
230
|
+
nonce: w.nonce,
|
|
231
|
+
size: dec(w.size),
|
|
232
|
+
limitPrice: dec(w.limit_price),
|
|
233
|
+
triggerPrice: dec(w.trigger_price),
|
|
234
|
+
triggerType: w.trigger_type,
|
|
235
|
+
reduceOnly: w.reduce_only,
|
|
236
|
+
ioc: w.ioc,
|
|
237
|
+
deadlineMs: usToMs(w.deadline),
|
|
238
|
+
endMs: usToMs(w.end),
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
export function decodeBackstopTransfer(w) {
|
|
242
|
+
return {
|
|
243
|
+
orderbookId: w.orderbook_id,
|
|
244
|
+
size: dec(w.size),
|
|
245
|
+
cash: dec(w.cash),
|
|
246
|
+
markPrice: dec(w.mark_price),
|
|
247
|
+
equity: dec(w.equity),
|
|
248
|
+
time: usToMs(w.timestamp_us),
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
//# sourceMappingURL=decode.js.map
|