@paradex/sdk 0.10.0 → 0.12.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/README.md +177 -2
- package/dist/api-errors.d.ts +76 -0
- package/dist/api-errors.js +249 -0
- package/dist/builder-app.d.ts +329 -0
- package/dist/builder-app.js +527 -0
- package/dist/builder-codes.d.ts +109 -0
- package/dist/builder-codes.js +103 -0
- package/dist/evm-owner-client.d.ts +101 -0
- package/dist/evm-owner-client.js +191 -0
- package/dist/evm-owner-signer.d.ts +81 -0
- package/dist/evm-owner-signer.js +165 -0
- package/dist/index.d.ts +56 -4
- package/dist/index.js +45 -2
- package/dist/owner-auth.d.ts +68 -0
- package/dist/owner-auth.js +184 -0
- package/dist/paraclear.d.ts +6 -1
- package/dist/paraclear.js +15 -8
- package/dist/rfq.d.ts +54 -0
- package/dist/rfq.js +64 -0
- package/dist/sbe.d.ts +47 -0
- package/dist/sbe.js +744 -0
- package/dist/session-accounts.d.ts +33 -1
- package/dist/session-accounts.js +158 -40
- package/dist/session-auth.d.ts +30 -0
- package/dist/session-auth.js +70 -18
- package/dist/session-connector.d.ts +35 -1
- package/dist/session-connector.js +72 -1
- package/dist/session-transport.d.ts +8 -1
- package/dist/session-transport.js +4 -0
- package/dist/session-typed-data.d.ts +81 -7
- package/dist/session-typed-data.js +128 -18
- package/dist/siwe.d.ts +35 -0
- package/dist/siwe.js +94 -0
- package/dist/trading.d.ts +98 -0
- package/dist/trading.js +39 -0
- package/dist/wallet.d.ts +78 -0
- package/dist/wallet.js +157 -0
- package/package.json +4 -2
|
@@ -36,6 +36,11 @@ export interface SessionAccountsParams {
|
|
|
36
36
|
* `restore()` keeps returning the ended session until it expires.
|
|
37
37
|
*/
|
|
38
38
|
readonly onDropped?: (reason: SessionGrantError) => void;
|
|
39
|
+
/**
|
|
40
|
+
* Called when a websocket message can't be read, once for each kind on a
|
|
41
|
+
* connection. Defaults to `console.error`.
|
|
42
|
+
*/
|
|
43
|
+
readonly onMessageError?: (error: Error) => void;
|
|
39
44
|
}
|
|
40
45
|
export interface SessionRequest {
|
|
41
46
|
readonly method: HttpRequest['method'];
|
|
@@ -51,6 +56,13 @@ export interface RevokeOptions {
|
|
|
51
56
|
readonly cancelOrders?: boolean;
|
|
52
57
|
}
|
|
53
58
|
export type SubscriptionHandler = (data: unknown) => void;
|
|
59
|
+
/**
|
|
60
|
+
* A grant's state from `GET /v2/sessions/{grant_id}/status`, which needs no
|
|
61
|
+
* token, so it still answers once the session's tokens are refused. A 404
|
|
62
|
+
* with `NOT_FOUND` means the grant is gone (`revoked`); `undefined` means
|
|
63
|
+
* the state could not be read (an unrouted 404, a 5xx, no network).
|
|
64
|
+
*/
|
|
65
|
+
export declare function fetchGrantState(transport: HttpTransport, apiUrl: string, grantId: string): Promise<GrantState | undefined>;
|
|
54
66
|
/**
|
|
55
67
|
* Trades every account a grant lists with one session key: a JWT per account
|
|
56
68
|
* (`POST /v1/auth/{session_public_key}` with `PARADEX-STARKNET-ACCOUNT`,
|
|
@@ -125,12 +137,21 @@ export declare class SessionAccounts {
|
|
|
125
137
|
* Subscribes to a channel on `account`'s socket, opening and authenticating
|
|
126
138
|
* it if needed. Returns an unsubscribe function; the socket closes once its
|
|
127
139
|
* last subscription is gone.
|
|
140
|
+
*
|
|
141
|
+
* Handlers get the objects the JSON feed sends. Some fields are not in the
|
|
142
|
+
* binary messages the server sends, such as a fill's builder fee: read
|
|
143
|
+
* those from the REST API. `orders.*` and `fills.*` channels share one
|
|
144
|
+
* `.ALL` subscription, so `orders.ALL` and `orders.BTC-USD-PERP` can be
|
|
145
|
+
* open together. Two market channels of one kind that share a market,
|
|
146
|
+
* such as `trades.ALL` and `trades.BTC-USD-PERP`, can't.
|
|
128
147
|
*/
|
|
129
148
|
subscribe(account: string, channel: string, handler: SubscriptionHandler): Promise<() => void>;
|
|
130
149
|
/** Closes sockets and timers. The session itself stays valid. */
|
|
131
150
|
close(): void;
|
|
132
151
|
/** @internal */
|
|
133
152
|
createWebSocket(): WebSocketLike;
|
|
153
|
+
/** @internal A websocket message that could not be read. */
|
|
154
|
+
messageError(error: Error): void;
|
|
134
155
|
/** @internal */
|
|
135
156
|
get isLive(): boolean;
|
|
136
157
|
/** @internal Drops every account. Idempotent. */
|
|
@@ -177,9 +198,15 @@ declare class AccountSocket {
|
|
|
177
198
|
private ws;
|
|
178
199
|
private ready;
|
|
179
200
|
private readonly handlers;
|
|
180
|
-
/**
|
|
201
|
+
/**
|
|
202
|
+
* Server subscriptions (see `subscriptionChannel`) sent on the current
|
|
203
|
+
* connection, settled or pending.
|
|
204
|
+
*/
|
|
181
205
|
private readonly subscribed;
|
|
206
|
+
/** Unsubscribed server channels whose messages may still be on the way. */
|
|
207
|
+
private readonly closing;
|
|
182
208
|
private readonly pending;
|
|
209
|
+
private readonly reported;
|
|
183
210
|
private nextId;
|
|
184
211
|
private reconnectAttempts;
|
|
185
212
|
private reconnectTimer;
|
|
@@ -193,11 +220,16 @@ declare class AccountSocket {
|
|
|
193
220
|
restart(): void;
|
|
194
221
|
close(): void;
|
|
195
222
|
private removeHandler;
|
|
223
|
+
/** The server channels the open handlers need. */
|
|
224
|
+
private wires;
|
|
196
225
|
private ensureSubscribed;
|
|
197
226
|
private connect;
|
|
198
227
|
private open;
|
|
199
228
|
private call;
|
|
200
229
|
private onMessage;
|
|
230
|
+
private onBinaryMessage;
|
|
231
|
+
/** Reports each kind of unreadable message once, not once a message. */
|
|
232
|
+
private reportUnreadable;
|
|
201
233
|
private onClose;
|
|
202
234
|
private scheduleReconnect;
|
|
203
235
|
private resubscribe;
|
package/dist/session-accounts.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import BigNumber from 'bignumber.js';
|
|
2
|
+
import { binaryFrame, channelDelivers, channelDeliversText, channelsOverlap, decodeSbe, isSbeFrame, subscriptionChannel, withSbeParams, } from './sbe.js';
|
|
1
3
|
import { buildAuthTypedData, buildOrderTypedData, jwtExpiry, SESSION_AUTH_MAX_TTL, sessionAuthPath, } from './session-auth.js';
|
|
2
4
|
import { SESSIONS_PATH } from './session-connector.js';
|
|
3
5
|
import { defaultApiUrl, defaultWebSocketFactory, defaultWsUrl, fetchTransport, SessionApiError, } from './session-transport.js';
|
|
@@ -10,6 +12,37 @@ const RECONNECT_MAX_MS = 30000;
|
|
|
10
12
|
const DEFAULT_RPC_TIMEOUT_MS = 10000;
|
|
11
13
|
/** `/auth` is rate-limited per IP; `start()` mints this many at a time. */
|
|
12
14
|
const START_CONCURRENCY = 10;
|
|
15
|
+
/**
|
|
16
|
+
* A grant's state from `GET /v2/sessions/{grant_id}/status`, which needs no
|
|
17
|
+
* token, so it still answers once the session's tokens are refused. A 404
|
|
18
|
+
* with `NOT_FOUND` means the grant is gone (`revoked`); `undefined` means
|
|
19
|
+
* the state could not be read (an unrouted 404, a 5xx, no network).
|
|
20
|
+
*/
|
|
21
|
+
export async function fetchGrantState(transport, apiUrl, grantId) {
|
|
22
|
+
let response;
|
|
23
|
+
try {
|
|
24
|
+
response = await transport({
|
|
25
|
+
method: 'GET',
|
|
26
|
+
url: `${apiUrl}${SESSIONS_PATH}/${encodeURIComponent(grantId)}/status`,
|
|
27
|
+
headers: {},
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
let state;
|
|
34
|
+
if (response.status === 404) {
|
|
35
|
+
const error = response.body?.error;
|
|
36
|
+
if (error === 'NOT_FOUND')
|
|
37
|
+
state = 'revoked';
|
|
38
|
+
}
|
|
39
|
+
else if (response.status >= 200 && response.status < 300) {
|
|
40
|
+
state = response.body?.state;
|
|
41
|
+
}
|
|
42
|
+
return state === 'active' || state === 'revoked' || state === 'expired'
|
|
43
|
+
? state
|
|
44
|
+
: undefined;
|
|
45
|
+
}
|
|
13
46
|
function hasOnBehalfOf(value) {
|
|
14
47
|
if (Array.isArray(value))
|
|
15
48
|
return value.some(hasOnBehalfOf);
|
|
@@ -88,7 +121,7 @@ export class SessionAccounts {
|
|
|
88
121
|
this.accounts = grantAccounts(grant);
|
|
89
122
|
this.transport = params.transport ?? fetchTransport;
|
|
90
123
|
this.apiUrl = params.apiUrl ?? defaultApiUrl(grant.environment);
|
|
91
|
-
this.wsUrl = params.wsUrl ?? defaultWsUrl(grant.environment);
|
|
124
|
+
this.wsUrl = withSbeParams(params.wsUrl ?? defaultWsUrl(grant.environment));
|
|
92
125
|
this.webSocketFactory = params.webSocketFactory ?? defaultWebSocketFactory;
|
|
93
126
|
this.refreshMargin = params.refreshMarginSeconds ?? 60;
|
|
94
127
|
this.scheduleExpiry();
|
|
@@ -163,12 +196,23 @@ export class SessionAccounts {
|
|
|
163
196
|
side: order.side,
|
|
164
197
|
type: order.type,
|
|
165
198
|
size: order.size,
|
|
166
|
-
|
|
199
|
+
// A market order signs price 0, and the server refuses one that
|
|
200
|
+
// sends a price.
|
|
201
|
+
...(order.type === 'MARKET' ? {} : { price: order.price }),
|
|
167
202
|
instruction: order.instruction ?? 'GTC',
|
|
168
203
|
signature: JSON.stringify(signature),
|
|
169
204
|
signature_timestamp: timestamp,
|
|
170
205
|
...(order.clientId != null ? { client_id: order.clientId } : {}),
|
|
171
206
|
...(order.reduceOnly === true ? { flags: ['REDUCE_ONLY'] } : {}),
|
|
207
|
+
...(order.builder != null
|
|
208
|
+
? {
|
|
209
|
+
builder: order.builder,
|
|
210
|
+
// Canonical spelling ("0.000500000" -> "0.0005"): the server
|
|
211
|
+
// refuses more than 8 decimal places, and the signature covers
|
|
212
|
+
// the scaled value, so either spelling signs the same.
|
|
213
|
+
builder_fee_rate: new BigNumber(order.builderFeeRate ?? '').toFixed(),
|
|
214
|
+
}
|
|
215
|
+
: {}),
|
|
172
216
|
},
|
|
173
217
|
});
|
|
174
218
|
}
|
|
@@ -224,6 +268,13 @@ export class SessionAccounts {
|
|
|
224
268
|
* Subscribes to a channel on `account`'s socket, opening and authenticating
|
|
225
269
|
* it if needed. Returns an unsubscribe function; the socket closes once its
|
|
226
270
|
* last subscription is gone.
|
|
271
|
+
*
|
|
272
|
+
* Handlers get the objects the JSON feed sends. Some fields are not in the
|
|
273
|
+
* binary messages the server sends, such as a fill's builder fee: read
|
|
274
|
+
* those from the REST API. `orders.*` and `fills.*` channels share one
|
|
275
|
+
* `.ALL` subscription, so `orders.ALL` and `orders.BTC-USD-PERP` can be
|
|
276
|
+
* open together. Two market channels of one kind that share a market,
|
|
277
|
+
* such as `trades.ALL` and `trades.BTC-USD-PERP`, can't.
|
|
227
278
|
*/
|
|
228
279
|
async subscribe(account, channel, handler) {
|
|
229
280
|
const id = this.resolveAccount(account);
|
|
@@ -241,7 +292,16 @@ export class SessionAccounts {
|
|
|
241
292
|
}
|
|
242
293
|
/** @internal */
|
|
243
294
|
createWebSocket() {
|
|
244
|
-
|
|
295
|
+
const ws = this.webSocketFactory(this.wsUrl);
|
|
296
|
+
ws.binaryType = 'arraybuffer';
|
|
297
|
+
return ws;
|
|
298
|
+
}
|
|
299
|
+
/** @internal A websocket message that could not be read. */
|
|
300
|
+
messageError(error) {
|
|
301
|
+
if (this.params.onMessageError != null)
|
|
302
|
+
this.params.onMessageError(error);
|
|
303
|
+
else
|
|
304
|
+
console.error(`Paradex websocket: ${error.message}`);
|
|
245
305
|
}
|
|
246
306
|
/** @internal */
|
|
247
307
|
get isLive() {
|
|
@@ -286,26 +346,7 @@ export class SessionAccounts {
|
|
|
286
346
|
* grant is gone; any other 404 (e.g. an unrouted path) is transient.
|
|
287
347
|
*/
|
|
288
348
|
async checkGrantState() {
|
|
289
|
-
|
|
290
|
-
try {
|
|
291
|
-
response = await this.transport({
|
|
292
|
-
method: 'GET',
|
|
293
|
-
url: `${this.apiUrl}${this.grantPath()}/status`,
|
|
294
|
-
headers: {},
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
catch {
|
|
298
|
-
return undefined;
|
|
299
|
-
}
|
|
300
|
-
let state;
|
|
301
|
-
if (response.status === 404) {
|
|
302
|
-
const error = response.body?.error;
|
|
303
|
-
if (error === 'NOT_FOUND')
|
|
304
|
-
state = 'revoked';
|
|
305
|
-
}
|
|
306
|
-
else if (response.status >= 200 && response.status < 300) {
|
|
307
|
-
state = response.body?.state;
|
|
308
|
-
}
|
|
349
|
+
const state = await fetchGrantState(this.transport, this.apiUrl, this.params.session.grantId);
|
|
309
350
|
if (state === 'revoked') {
|
|
310
351
|
this.drop(new SessionGrantError('GRANT_REVOKED', 'session revoked'));
|
|
311
352
|
}
|
|
@@ -314,9 +355,7 @@ export class SessionAccounts {
|
|
|
314
355
|
}
|
|
315
356
|
// Anything else is transient: callers fail this attempt, and sockets
|
|
316
357
|
// retry with backoff.
|
|
317
|
-
return state
|
|
318
|
-
? state
|
|
319
|
-
: undefined;
|
|
358
|
+
return state;
|
|
320
359
|
}
|
|
321
360
|
grantPath() {
|
|
322
361
|
return `${SESSIONS_PATH}/${encodeURIComponent(this.params.session.grantId)}`;
|
|
@@ -495,6 +534,10 @@ export class SessionAccounts {
|
|
|
495
534
|
}, Math.max(0, Math.min(remainingMs, MAX_TIMER_DELAY_MS)));
|
|
496
535
|
}
|
|
497
536
|
}
|
|
537
|
+
/** Whether one server channel's messages could pass for the other's. */
|
|
538
|
+
function conflicts(a, b) {
|
|
539
|
+
return a === b || channelsOverlap(a, b);
|
|
540
|
+
}
|
|
498
541
|
/** One authenticated websocket for one account. */
|
|
499
542
|
class AccountSocket {
|
|
500
543
|
constructor(owner, account, rpcTimeoutMs = DEFAULT_RPC_TIMEOUT_MS) {
|
|
@@ -502,23 +545,43 @@ class AccountSocket {
|
|
|
502
545
|
this.account = account;
|
|
503
546
|
this.rpcTimeoutMs = rpcTimeoutMs;
|
|
504
547
|
this.handlers = new Map();
|
|
505
|
-
/**
|
|
548
|
+
/**
|
|
549
|
+
* Server subscriptions (see `subscriptionChannel`) sent on the current
|
|
550
|
+
* connection, settled or pending.
|
|
551
|
+
*/
|
|
506
552
|
this.subscribed = new Map();
|
|
553
|
+
/** Unsubscribed server channels whose messages may still be on the way. */
|
|
554
|
+
this.closing = new Map();
|
|
507
555
|
this.pending = new Map();
|
|
556
|
+
this.reported = new Set();
|
|
508
557
|
this.nextId = 1;
|
|
509
558
|
this.reconnectAttempts = 0;
|
|
510
559
|
this.closed = false;
|
|
511
560
|
}
|
|
512
561
|
async subscribe(channel, handler) {
|
|
562
|
+
const wire = subscriptionChannel(channel);
|
|
513
563
|
let set = this.handlers.get(channel);
|
|
514
564
|
if (set == null) {
|
|
565
|
+
// Binary messages don't name their channel, and the server sends one
|
|
566
|
+
// per subscription.
|
|
567
|
+
const other = [...this.handlers.keys()].find((c) => channelsOverlap(subscriptionChannel(c), wire));
|
|
568
|
+
if (other != null) {
|
|
569
|
+
throw new Error(`Cannot subscribe to ${channel} together with ${other}: their messages can't be told apart. Unsubscribe from ${other} first.`);
|
|
570
|
+
}
|
|
515
571
|
set = new Set();
|
|
516
572
|
this.handlers.set(channel, set);
|
|
517
573
|
}
|
|
518
574
|
set.add(handler);
|
|
519
575
|
try {
|
|
520
576
|
await this.connect();
|
|
521
|
-
await this.
|
|
577
|
+
await Promise.all([...this.closing]
|
|
578
|
+
.filter(([other]) => conflicts(other, wire))
|
|
579
|
+
.map(async ([, done]) => {
|
|
580
|
+
await done;
|
|
581
|
+
}));
|
|
582
|
+
// The socket may have dropped while waiting.
|
|
583
|
+
await this.connect();
|
|
584
|
+
await this.ensureSubscribed(wire);
|
|
522
585
|
}
|
|
523
586
|
catch (error) {
|
|
524
587
|
this.removeHandler(channel, handler, false);
|
|
@@ -564,16 +627,30 @@ class AccountSocket {
|
|
|
564
627
|
if (current?.delete(handler) !== true || current.size > 0)
|
|
565
628
|
return;
|
|
566
629
|
this.handlers.delete(channel);
|
|
567
|
-
const
|
|
630
|
+
const wire = subscriptionChannel(channel);
|
|
631
|
+
// Another channel may still need the server subscription.
|
|
632
|
+
if (this.wires().has(wire))
|
|
633
|
+
return;
|
|
634
|
+
const wasSubscribed = this.subscribed.delete(wire);
|
|
568
635
|
if (this.handlers.size === 0) {
|
|
569
636
|
this.owner.socketIdle(this.account, this);
|
|
570
637
|
}
|
|
571
638
|
else if (unsubscribe &&
|
|
572
639
|
wasSubscribed &&
|
|
573
640
|
this.ws?.readyState === WS_OPEN) {
|
|
574
|
-
this.call('unsubscribe', { channel
|
|
641
|
+
const done = this.call('unsubscribe', { channel: wire })
|
|
642
|
+
.then(() => { }, () => { })
|
|
643
|
+
.then(() => {
|
|
644
|
+
if (this.closing.get(wire) === done)
|
|
645
|
+
this.closing.delete(wire);
|
|
646
|
+
});
|
|
647
|
+
this.closing.set(wire, done);
|
|
575
648
|
}
|
|
576
649
|
}
|
|
650
|
+
/** The server channels the open handlers need. */
|
|
651
|
+
wires() {
|
|
652
|
+
return new Set([...this.handlers.keys()].map(subscriptionChannel));
|
|
653
|
+
}
|
|
577
654
|
async ensureSubscribed(channel) {
|
|
578
655
|
let pending = this.subscribed.get(channel);
|
|
579
656
|
if (pending == null) {
|
|
@@ -597,6 +674,8 @@ class AccountSocket {
|
|
|
597
674
|
const ws = this.owner.createWebSocket();
|
|
598
675
|
this.ws = ws;
|
|
599
676
|
this.subscribed.clear();
|
|
677
|
+
this.closing.clear();
|
|
678
|
+
this.reported.clear();
|
|
600
679
|
this.authedToken = undefined;
|
|
601
680
|
try {
|
|
602
681
|
await new Promise((resolve, reject) => {
|
|
@@ -647,8 +726,8 @@ class AccountSocket {
|
|
|
647
726
|
this.reconnectTimer = undefined;
|
|
648
727
|
// Every connection carries every channel, including ones a pending
|
|
649
728
|
// reconnect would have restored.
|
|
650
|
-
for (const
|
|
651
|
-
this.ensureSubscribed(
|
|
729
|
+
for (const wire of this.wires()) {
|
|
730
|
+
this.ensureSubscribed(wire).catch(() => { });
|
|
652
731
|
}
|
|
653
732
|
}
|
|
654
733
|
async call(method, params) {
|
|
@@ -670,11 +749,19 @@ class AccountSocket {
|
|
|
670
749
|
});
|
|
671
750
|
}
|
|
672
751
|
onMessage(data) {
|
|
752
|
+
const bytes = binaryFrame(data);
|
|
753
|
+
if (bytes != null && isSbeFrame(bytes)) {
|
|
754
|
+
this.onBinaryMessage(bytes);
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
673
757
|
let message;
|
|
674
758
|
try {
|
|
675
|
-
message = JSON.parse(String(data));
|
|
759
|
+
message = JSON.parse(bytes != null ? new TextDecoder().decode(bytes) : String(data));
|
|
676
760
|
}
|
|
677
761
|
catch {
|
|
762
|
+
this.reportUnreadable(typeof data === 'string' || bytes != null
|
|
763
|
+
? 'message is not JSON'
|
|
764
|
+
: 'message is neither text nor an ArrayBuffer; the webSocketFactory must honour binaryType');
|
|
678
765
|
return;
|
|
679
766
|
}
|
|
680
767
|
if (typeof message.id === 'number' && this.pending.has(message.id)) {
|
|
@@ -693,12 +780,43 @@ class AccountSocket {
|
|
|
693
780
|
void this.owner.confirmActive().catch(() => { });
|
|
694
781
|
return;
|
|
695
782
|
}
|
|
696
|
-
const
|
|
697
|
-
if (message.method === 'subscription' && typeof
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
783
|
+
const sent = message.params?.channel;
|
|
784
|
+
if (message.method === 'subscription' && typeof sent === 'string') {
|
|
785
|
+
const data = message.params?.data;
|
|
786
|
+
const handlers = [...this.handlers]
|
|
787
|
+
.filter(([channel]) => channelDeliversText(channel, sent, data))
|
|
788
|
+
.flatMap(([, set]) => [...set]);
|
|
789
|
+
for (const handler of handlers)
|
|
790
|
+
handler(data);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
onBinaryMessage(bytes) {
|
|
794
|
+
let message;
|
|
795
|
+
try {
|
|
796
|
+
message = decodeSbe(bytes);
|
|
701
797
|
}
|
|
798
|
+
catch (error) {
|
|
799
|
+
this.reportUnreadable(error instanceof Error ? error.message : String(error));
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
if (message == null)
|
|
803
|
+
return;
|
|
804
|
+
const { data } = message;
|
|
805
|
+
// Copied, as a handler may subscribe or unsubscribe.
|
|
806
|
+
const handlers = [...this.handlers]
|
|
807
|
+
.filter(([channel]) => channelDelivers(channel, message) &&
|
|
808
|
+
// Not a late message of the channel this one waits on.
|
|
809
|
+
![...this.closing.keys()].some((other) => conflicts(other, subscriptionChannel(channel))))
|
|
810
|
+
.flatMap(([, set]) => [...set]);
|
|
811
|
+
for (const handler of handlers)
|
|
812
|
+
handler(data);
|
|
813
|
+
}
|
|
814
|
+
/** Reports each kind of unreadable message once, not once a message. */
|
|
815
|
+
reportUnreadable(reason) {
|
|
816
|
+
if (this.reported.has(reason))
|
|
817
|
+
return;
|
|
818
|
+
this.reported.add(reason);
|
|
819
|
+
this.owner.messageError(new Error(reason));
|
|
702
820
|
}
|
|
703
821
|
onClose(ws) {
|
|
704
822
|
if (this.ws !== ws)
|
|
@@ -729,8 +847,8 @@ class AccountSocket {
|
|
|
729
847
|
return;
|
|
730
848
|
try {
|
|
731
849
|
await this.connect();
|
|
732
|
-
await Promise.all([...this.
|
|
733
|
-
await this.ensureSubscribed(
|
|
850
|
+
await Promise.all([...this.wires()].map(async (wire) => {
|
|
851
|
+
await this.ensureSubscribed(wire);
|
|
734
852
|
}));
|
|
735
853
|
}
|
|
736
854
|
catch {
|
package/dist/session-auth.d.ts
CHANGED
|
@@ -23,9 +23,39 @@ export interface SessionOrder {
|
|
|
23
23
|
readonly instruction?: 'GTC' | 'IOC' | 'POST_ONLY' | 'RPI';
|
|
24
24
|
readonly clientId?: string;
|
|
25
25
|
readonly reduceOnly?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Builder the order is attributed to: its Paradex account address. The
|
|
28
|
+
* builder charges `builderFeeRate` in USDC on every fill. Set it with
|
|
29
|
+
* `builderFeeRate`, or neither. The account must hold a live approval of
|
|
30
|
+
* this builder at a rate at least as high, such as a grant's `builder`.
|
|
31
|
+
*/
|
|
32
|
+
readonly builder?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Builder fee as a fraction of each fill's notional, a decimal string with
|
|
35
|
+
* at most 8 decimal places: `"0.0005"` is 5 bps.
|
|
36
|
+
*/
|
|
37
|
+
readonly builderFeeRate?: string;
|
|
26
38
|
}
|
|
27
39
|
/** Decimal string → 8-decimal quantum integer string, as the chain signs it. */
|
|
28
40
|
export declare function toChainQuantums(value: string, field: string): string;
|
|
41
|
+
/**
|
|
42
|
+
* The order's builder and its fee rate at 8 decimals (`"0.0005"` →
|
|
43
|
+
* `"50000"`), or `undefined` for an order naming none.
|
|
44
|
+
*/
|
|
45
|
+
export declare function orderBuilder(order: SessionOrder): {
|
|
46
|
+
builder: string;
|
|
47
|
+
builderFeeRate: string;
|
|
48
|
+
} | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* The SNIP-12 (revision 0) typed data `order` is signed under. An order
|
|
51
|
+
* naming a builder signs as `BuilderOrder`: the `Order` fields, in order,
|
|
52
|
+
* then `builder` and `builderFeeRate` at 8 decimals. Its distinct type hash
|
|
53
|
+
* keeps either signature from being replayed as the other. An order without
|
|
54
|
+
* a builder keeps the `Order` hash.
|
|
55
|
+
*
|
|
56
|
+
* An order that can't be signed, such as one with a size that is not a
|
|
57
|
+
* decimal, throws a `BuilderAppError` with code `INVALID_ORDER`.
|
|
58
|
+
*/
|
|
29
59
|
export declare function buildOrderTypedData(paradexChain: string, order: SessionOrder, signatureTimestampMs: number): Starknet.TypedData;
|
|
30
60
|
/** Reads `exp` (seconds) from a JWT without verifying it. */
|
|
31
61
|
export declare function jwtExpiry(token: string): number | undefined;
|
package/dist/session-auth.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import BigNumber from 'bignumber.js';
|
|
2
2
|
import * as Starknet from 'starknet';
|
|
3
|
+
import { BuilderAppError } from './api-errors.js';
|
|
4
|
+
import { builderAddress } from './session-typed-data.js';
|
|
3
5
|
/**
|
|
4
6
|
* Typed data a session key signs: the `/auth` request that mints a JWT and
|
|
5
7
|
* the orders it places. Both are today's SNIP-12 (revision 0) "Paradex"
|
|
@@ -69,34 +71,84 @@ export function toChainQuantums(value, field) {
|
|
|
69
71
|
}
|
|
70
72
|
return scaled.toFixed(0);
|
|
71
73
|
}
|
|
74
|
+
const ORDER_TYPES = [
|
|
75
|
+
{ name: 'timestamp', type: 'felt' },
|
|
76
|
+
{ name: 'market', type: 'felt' },
|
|
77
|
+
{ name: 'side', type: 'felt' },
|
|
78
|
+
{ name: 'orderType', type: 'felt' },
|
|
79
|
+
{ name: 'size', type: 'felt' },
|
|
80
|
+
{ name: 'price', type: 'felt' },
|
|
81
|
+
];
|
|
82
|
+
/**
|
|
83
|
+
* The order's builder and its fee rate at 8 decimals (`"0.0005"` →
|
|
84
|
+
* `"50000"`), or `undefined` for an order naming none.
|
|
85
|
+
*/
|
|
86
|
+
export function orderBuilder(order) {
|
|
87
|
+
const { builder, builderFeeRate } = order;
|
|
88
|
+
if (builder == null && builderFeeRate == null)
|
|
89
|
+
return undefined;
|
|
90
|
+
if (builder == null || builderFeeRate == null) {
|
|
91
|
+
throw new Error('builder and builderFeeRate must be set together');
|
|
92
|
+
}
|
|
93
|
+
builderAddress(builder);
|
|
94
|
+
const rate = toChainQuantums(builderFeeRate, 'builderFeeRate');
|
|
95
|
+
if (rate === '0')
|
|
96
|
+
throw new Error('builderFeeRate must be above 0');
|
|
97
|
+
return { builder, builderFeeRate: rate };
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* The SNIP-12 (revision 0) typed data `order` is signed under. An order
|
|
101
|
+
* naming a builder signs as `BuilderOrder`: the `Order` fields, in order,
|
|
102
|
+
* then `builder` and `builderFeeRate` at 8 decimals. Its distinct type hash
|
|
103
|
+
* keeps either signature from being replayed as the other. An order without
|
|
104
|
+
* a builder keeps the `Order` hash.
|
|
105
|
+
*
|
|
106
|
+
* An order that can't be signed, such as one with a size that is not a
|
|
107
|
+
* decimal, throws a `BuilderAppError` with code `INVALID_ORDER`.
|
|
108
|
+
*/
|
|
72
109
|
export function buildOrderTypedData(paradexChain, order, signatureTimestampMs) {
|
|
110
|
+
try {
|
|
111
|
+
return orderTypedData(paradexChain, order, signatureTimestampMs);
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
throw new BuilderAppError('INVALID_ORDER', error instanceof Error ? error.message : String(error), { cause: error });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function orderTypedData(paradexChain, order, signatureTimestampMs) {
|
|
73
118
|
if (order.type === 'LIMIT' && order.price == null) {
|
|
74
119
|
throw new Error('LIMIT orders need a price');
|
|
75
120
|
}
|
|
121
|
+
const message = {
|
|
122
|
+
timestamp: String(signatureTimestampMs),
|
|
123
|
+
market: Starknet.shortString.encodeShortString(order.market),
|
|
124
|
+
side: order.side === 'BUY' ? '1' : '2',
|
|
125
|
+
orderType: Starknet.shortString.encodeShortString(order.type),
|
|
126
|
+
size: toChainQuantums(order.size, 'size'),
|
|
127
|
+
price: order.type === 'MARKET'
|
|
128
|
+
? '0'
|
|
129
|
+
: toChainQuantums(order.price ?? '', 'price'),
|
|
130
|
+
};
|
|
131
|
+
const builder = orderBuilder(order);
|
|
132
|
+
if (builder == null) {
|
|
133
|
+
return {
|
|
134
|
+
domain: paradexDomain(paradexChain),
|
|
135
|
+
primaryType: 'Order',
|
|
136
|
+
types: { StarkNetDomain: REQUEST_DOMAIN_TYPES, Order: ORDER_TYPES },
|
|
137
|
+
message,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
76
140
|
return {
|
|
77
141
|
domain: paradexDomain(paradexChain),
|
|
78
|
-
primaryType: '
|
|
142
|
+
primaryType: 'BuilderOrder',
|
|
79
143
|
types: {
|
|
80
144
|
StarkNetDomain: REQUEST_DOMAIN_TYPES,
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
{ name: '
|
|
84
|
-
{ name: '
|
|
85
|
-
{ name: 'orderType', type: 'felt' },
|
|
86
|
-
{ name: 'size', type: 'felt' },
|
|
87
|
-
{ name: 'price', type: 'felt' },
|
|
145
|
+
BuilderOrder: [
|
|
146
|
+
...ORDER_TYPES,
|
|
147
|
+
{ name: 'builder', type: 'felt' },
|
|
148
|
+
{ name: 'builderFeeRate', type: 'felt' },
|
|
88
149
|
],
|
|
89
150
|
},
|
|
90
|
-
message: {
|
|
91
|
-
timestamp: String(signatureTimestampMs),
|
|
92
|
-
market: Starknet.shortString.encodeShortString(order.market),
|
|
93
|
-
side: order.side === 'BUY' ? '1' : '2',
|
|
94
|
-
orderType: Starknet.shortString.encodeShortString(order.type),
|
|
95
|
-
size: toChainQuantums(order.size, 'size'),
|
|
96
|
-
price: order.type === 'MARKET'
|
|
97
|
-
? '0'
|
|
98
|
-
: toChainQuantums(order.price ?? '', 'price'),
|
|
99
|
-
},
|
|
151
|
+
message: { ...message, ...builder },
|
|
100
152
|
};
|
|
101
153
|
}
|
|
102
154
|
/** Reads `exp` (seconds) from a JWT without verifying it. */
|
|
@@ -1,10 +1,26 @@
|
|
|
1
1
|
import { SessionKey, type SessionStorage } from './session-key.js';
|
|
2
2
|
import { type SessionOwnerSigner } from './session-owner-signer.js';
|
|
3
3
|
import { type HttpTransport } from './session-transport.js';
|
|
4
|
-
import { type CreateSessionGrantParams, type LimitCaps, type LimitName, type SessionEnvironment, type SessionGrant } from './session-typed-data.js';
|
|
4
|
+
import { type BuilderApproval, type CreateBuilderApprovalParams, type CreateSessionGrantParams, type LimitCaps, type LimitName, type SessionEnvironment, type SessionGrant } from './session-typed-data.js';
|
|
5
5
|
import type { Hex } from './types.js';
|
|
6
6
|
export declare const SESSIONS_PATH = "/v2/sessions";
|
|
7
7
|
export declare const EVM_SUBACCOUNTS_PATH = "/v2/onboarding/subaccounts";
|
|
8
|
+
export declare const BUILDER_APPROVALS_PATH = "/v2/builders/approvals";
|
|
9
|
+
export declare const SYSTEM_TIME_PATH = "/v1/system/time";
|
|
10
|
+
/**
|
|
11
|
+
* What {@link SessionConnector.approveBuilder} takes. `issuedAt` always comes
|
|
12
|
+
* from the server's clock (`GET /v1/system/time`), since the server refuses
|
|
13
|
+
* an approval issued in its future.
|
|
14
|
+
*/
|
|
15
|
+
export type ApproveBuilderParams = Omit<CreateBuilderApprovalParams, 'paradexChain' | 'environment' | 'issuedAt'>;
|
|
16
|
+
/** A registered builder approval and the owner's signature over it. */
|
|
17
|
+
export interface RegisteredBuilderApproval {
|
|
18
|
+
readonly approval: BuilderApproval;
|
|
19
|
+
readonly ownerSignature: Hex;
|
|
20
|
+
readonly signatureChainId: number;
|
|
21
|
+
/** The server's response to `POST /v2/builders/approvals`. */
|
|
22
|
+
readonly response: unknown;
|
|
23
|
+
}
|
|
8
24
|
/** A registered session: the grant and the key that may act under it. */
|
|
9
25
|
export interface Session {
|
|
10
26
|
/** The server's id for the grant (its hash). */
|
|
@@ -106,6 +122,24 @@ export declare class SessionConnector {
|
|
|
106
122
|
* the one `POST /v2/sessions` applies.
|
|
107
123
|
*/
|
|
108
124
|
open(params: OpenSessionParams): Promise<Session>;
|
|
125
|
+
/**
|
|
126
|
+
* Has the owner approve a builder's fee without opening a session (one
|
|
127
|
+
* wallet prompt) and registers the approval with
|
|
128
|
+
* `POST /v2/builders/approvals`, which needs no JWT. The approval covers
|
|
129
|
+
* the account and any `subaccounts` it lists until `builder.expiresAt`.
|
|
130
|
+
* The owner revokes it with `DELETE /v2/builders/approvals/{builder_account}`.
|
|
131
|
+
*
|
|
132
|
+
* `issuedAt` is the server's time in whole seconds, and the server refuses
|
|
133
|
+
* an approval issued in the same second as the builder's last revoke or
|
|
134
|
+
* approval (including one a session grant made) with
|
|
135
|
+
* `BUILDER_APPROVAL_STALE`. So after either, wait for the next server
|
|
136
|
+
* second, or the owner signs an approval that is refused.
|
|
137
|
+
*
|
|
138
|
+
* @experimental
|
|
139
|
+
*/
|
|
140
|
+
approveBuilder(params: ApproveBuilderParams): Promise<RegisteredBuilderApproval>;
|
|
141
|
+
/** The server's clock in whole seconds, from `GET /v1/system/time`. */
|
|
142
|
+
private serverTime;
|
|
109
143
|
/**
|
|
110
144
|
* Restores registered sessions from storage for this environment. Expired
|
|
111
145
|
* sessions and sessions that never registered are deleted; records that
|