@paradex/sdk 0.11.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.
@@ -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
- /** Subscriptions sent on the current connection, settled or pending. */
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;
@@ -1,4 +1,5 @@
1
1
  import BigNumber from 'bignumber.js';
2
+ import { binaryFrame, channelDelivers, channelDeliversText, channelsOverlap, decodeSbe, isSbeFrame, subscriptionChannel, withSbeParams, } from './sbe.js';
2
3
  import { buildAuthTypedData, buildOrderTypedData, jwtExpiry, SESSION_AUTH_MAX_TTL, sessionAuthPath, } from './session-auth.js';
3
4
  import { SESSIONS_PATH } from './session-connector.js';
4
5
  import { defaultApiUrl, defaultWebSocketFactory, defaultWsUrl, fetchTransport, SessionApiError, } from './session-transport.js';
@@ -11,6 +12,37 @@ const RECONNECT_MAX_MS = 30000;
11
12
  const DEFAULT_RPC_TIMEOUT_MS = 10000;
12
13
  /** `/auth` is rate-limited per IP; `start()` mints this many at a time. */
13
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
+ }
14
46
  function hasOnBehalfOf(value) {
15
47
  if (Array.isArray(value))
16
48
  return value.some(hasOnBehalfOf);
@@ -89,7 +121,7 @@ export class SessionAccounts {
89
121
  this.accounts = grantAccounts(grant);
90
122
  this.transport = params.transport ?? fetchTransport;
91
123
  this.apiUrl = params.apiUrl ?? defaultApiUrl(grant.environment);
92
- this.wsUrl = params.wsUrl ?? defaultWsUrl(grant.environment);
124
+ this.wsUrl = withSbeParams(params.wsUrl ?? defaultWsUrl(grant.environment));
93
125
  this.webSocketFactory = params.webSocketFactory ?? defaultWebSocketFactory;
94
126
  this.refreshMargin = params.refreshMarginSeconds ?? 60;
95
127
  this.scheduleExpiry();
@@ -164,7 +196,9 @@ export class SessionAccounts {
164
196
  side: order.side,
165
197
  type: order.type,
166
198
  size: order.size,
167
- price: order.type === 'MARKET' ? '0' : order.price,
199
+ // A market order signs price 0, and the server refuses one that
200
+ // sends a price.
201
+ ...(order.type === 'MARKET' ? {} : { price: order.price }),
168
202
  instruction: order.instruction ?? 'GTC',
169
203
  signature: JSON.stringify(signature),
170
204
  signature_timestamp: timestamp,
@@ -234,6 +268,13 @@ export class SessionAccounts {
234
268
  * Subscribes to a channel on `account`'s socket, opening and authenticating
235
269
  * it if needed. Returns an unsubscribe function; the socket closes once its
236
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.
237
278
  */
238
279
  async subscribe(account, channel, handler) {
239
280
  const id = this.resolveAccount(account);
@@ -251,7 +292,16 @@ export class SessionAccounts {
251
292
  }
252
293
  /** @internal */
253
294
  createWebSocket() {
254
- return this.webSocketFactory(this.wsUrl);
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}`);
255
305
  }
256
306
  /** @internal */
257
307
  get isLive() {
@@ -296,26 +346,7 @@ export class SessionAccounts {
296
346
  * grant is gone; any other 404 (e.g. an unrouted path) is transient.
297
347
  */
298
348
  async checkGrantState() {
299
- let response;
300
- try {
301
- response = await this.transport({
302
- method: 'GET',
303
- url: `${this.apiUrl}${this.grantPath()}/status`,
304
- headers: {},
305
- });
306
- }
307
- catch {
308
- return undefined;
309
- }
310
- let state;
311
- if (response.status === 404) {
312
- const error = response.body?.error;
313
- if (error === 'NOT_FOUND')
314
- state = 'revoked';
315
- }
316
- else if (response.status >= 200 && response.status < 300) {
317
- state = response.body?.state;
318
- }
349
+ const state = await fetchGrantState(this.transport, this.apiUrl, this.params.session.grantId);
319
350
  if (state === 'revoked') {
320
351
  this.drop(new SessionGrantError('GRANT_REVOKED', 'session revoked'));
321
352
  }
@@ -324,9 +355,7 @@ export class SessionAccounts {
324
355
  }
325
356
  // Anything else is transient: callers fail this attempt, and sockets
326
357
  // retry with backoff.
327
- return state === 'active' || state === 'revoked' || state === 'expired'
328
- ? state
329
- : undefined;
358
+ return state;
330
359
  }
331
360
  grantPath() {
332
361
  return `${SESSIONS_PATH}/${encodeURIComponent(this.params.session.grantId)}`;
@@ -505,6 +534,10 @@ export class SessionAccounts {
505
534
  }, Math.max(0, Math.min(remainingMs, MAX_TIMER_DELAY_MS)));
506
535
  }
507
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
+ }
508
541
  /** One authenticated websocket for one account. */
509
542
  class AccountSocket {
510
543
  constructor(owner, account, rpcTimeoutMs = DEFAULT_RPC_TIMEOUT_MS) {
@@ -512,23 +545,43 @@ class AccountSocket {
512
545
  this.account = account;
513
546
  this.rpcTimeoutMs = rpcTimeoutMs;
514
547
  this.handlers = new Map();
515
- /** Subscriptions sent on the current connection, settled or pending. */
548
+ /**
549
+ * Server subscriptions (see `subscriptionChannel`) sent on the current
550
+ * connection, settled or pending.
551
+ */
516
552
  this.subscribed = new Map();
553
+ /** Unsubscribed server channels whose messages may still be on the way. */
554
+ this.closing = new Map();
517
555
  this.pending = new Map();
556
+ this.reported = new Set();
518
557
  this.nextId = 1;
519
558
  this.reconnectAttempts = 0;
520
559
  this.closed = false;
521
560
  }
522
561
  async subscribe(channel, handler) {
562
+ const wire = subscriptionChannel(channel);
523
563
  let set = this.handlers.get(channel);
524
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
+ }
525
571
  set = new Set();
526
572
  this.handlers.set(channel, set);
527
573
  }
528
574
  set.add(handler);
529
575
  try {
530
576
  await this.connect();
531
- await this.ensureSubscribed(channel);
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);
532
585
  }
533
586
  catch (error) {
534
587
  this.removeHandler(channel, handler, false);
@@ -574,16 +627,30 @@ class AccountSocket {
574
627
  if (current?.delete(handler) !== true || current.size > 0)
575
628
  return;
576
629
  this.handlers.delete(channel);
577
- const wasSubscribed = this.subscribed.delete(channel);
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);
578
635
  if (this.handlers.size === 0) {
579
636
  this.owner.socketIdle(this.account, this);
580
637
  }
581
638
  else if (unsubscribe &&
582
639
  wasSubscribed &&
583
640
  this.ws?.readyState === WS_OPEN) {
584
- this.call('unsubscribe', { channel }).catch(() => { });
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);
585
648
  }
586
649
  }
650
+ /** The server channels the open handlers need. */
651
+ wires() {
652
+ return new Set([...this.handlers.keys()].map(subscriptionChannel));
653
+ }
587
654
  async ensureSubscribed(channel) {
588
655
  let pending = this.subscribed.get(channel);
589
656
  if (pending == null) {
@@ -607,6 +674,8 @@ class AccountSocket {
607
674
  const ws = this.owner.createWebSocket();
608
675
  this.ws = ws;
609
676
  this.subscribed.clear();
677
+ this.closing.clear();
678
+ this.reported.clear();
610
679
  this.authedToken = undefined;
611
680
  try {
612
681
  await new Promise((resolve, reject) => {
@@ -657,8 +726,8 @@ class AccountSocket {
657
726
  this.reconnectTimer = undefined;
658
727
  // Every connection carries every channel, including ones a pending
659
728
  // reconnect would have restored.
660
- for (const channel of this.handlers.keys()) {
661
- this.ensureSubscribed(channel).catch(() => { });
729
+ for (const wire of this.wires()) {
730
+ this.ensureSubscribed(wire).catch(() => { });
662
731
  }
663
732
  }
664
733
  async call(method, params) {
@@ -680,11 +749,19 @@ class AccountSocket {
680
749
  });
681
750
  }
682
751
  onMessage(data) {
752
+ const bytes = binaryFrame(data);
753
+ if (bytes != null && isSbeFrame(bytes)) {
754
+ this.onBinaryMessage(bytes);
755
+ return;
756
+ }
683
757
  let message;
684
758
  try {
685
- message = JSON.parse(String(data));
759
+ message = JSON.parse(bytes != null ? new TextDecoder().decode(bytes) : String(data));
686
760
  }
687
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');
688
765
  return;
689
766
  }
690
767
  if (typeof message.id === 'number' && this.pending.has(message.id)) {
@@ -703,13 +780,44 @@ class AccountSocket {
703
780
  void this.owner.confirmActive().catch(() => { });
704
781
  return;
705
782
  }
706
- const channel = message.params?.channel;
707
- if (message.method === 'subscription' && typeof channel === 'string') {
708
- for (const handler of this.handlers.get(channel) ?? []) {
709
- handler(message.params?.data);
710
- }
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);
711
791
  }
712
792
  }
793
+ onBinaryMessage(bytes) {
794
+ let message;
795
+ try {
796
+ message = decodeSbe(bytes);
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));
820
+ }
713
821
  onClose(ws) {
714
822
  if (this.ws !== ws)
715
823
  return;
@@ -739,8 +847,8 @@ class AccountSocket {
739
847
  return;
740
848
  try {
741
849
  await this.connect();
742
- await Promise.all([...this.handlers.keys()].map(async (channel) => {
743
- await this.ensureSubscribed(channel);
850
+ await Promise.all([...this.wires()].map(async (wire) => {
851
+ await this.ensureSubscribed(wire);
744
852
  }));
745
853
  }
746
854
  catch {
@@ -52,6 +52,9 @@ export declare function orderBuilder(order: SessionOrder): {
52
52
  * then `builder` and `builderFeeRate` at 8 decimals. Its distinct type hash
53
53
  * keeps either signature from being replayed as the other. An order without
54
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`.
55
58
  */
56
59
  export declare function buildOrderTypedData(paradexChain: string, order: SessionOrder, signatureTimestampMs: number): Starknet.TypedData;
57
60
  /** Reads `exp` (seconds) from a JWT without verifying it. */
@@ -1,5 +1,6 @@
1
1
  import BigNumber from 'bignumber.js';
2
2
  import * as Starknet from 'starknet';
3
+ import { BuilderAppError } from './api-errors.js';
3
4
  import { builderAddress } from './session-typed-data.js';
4
5
  /**
5
6
  * Typed data a session key signs: the `/auth` request that mints a JWT and
@@ -101,8 +102,19 @@ export function orderBuilder(order) {
101
102
  * then `builder` and `builderFeeRate` at 8 decimals. Its distinct type hash
102
103
  * keeps either signature from being replayed as the other. An order without
103
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`.
104
108
  */
105
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) {
106
118
  if (order.type === 'LIMIT' && order.price == null) {
107
119
  throw new Error('LIMIT orders need a price');
108
120
  }
@@ -21,6 +21,8 @@ export declare const fetchTransport: HttpTransport;
21
21
  /** The subset of the WHATWG `WebSocket` used here. */
22
22
  export interface WebSocketLike {
23
23
  readonly readyState: number;
24
+ /** Set to `arraybuffer`: the server's data messages are binary. */
25
+ binaryType?: string;
24
26
  send: (data: string) => void;
25
27
  close: (code?: number, reason?: string) => void;
26
28
  onopen: ((event: unknown) => void) | null;
@@ -38,11 +40,16 @@ export declare function defaultWsUrl(environment: SessionEnvironment): string;
38
40
  * Error codes the session endpoints are known to return. Servers may add
39
41
  * codes, so `SessionApiError.code` can hold any string.
40
42
  */
41
- export type KnownSessionApiErrorCode = 'INVALID_SIGNATURE' | 'GRANT_EXPIRED' | 'INVALID_ENVIRONMENT' | 'INVALID_CHAIN' | 'SCOPE_NOT_ALLOWED' | 'LIMIT_INVALID' | 'NONCE_REUSED' | 'ACCOUNT_NOT_ELIGIBLE' | 'INVALID_GRANT' | 'SESSION_KEY_IN_USE' | 'SESSION_LIMIT_REACHED' | 'BUILDER_APPROVAL_LIMIT_REACHED' | 'BUILDER_APPROVAL_STALE' | 'SESSIONS_DISABLED' | 'INVALID_MARKETING_CODE' | 'INVALID_REQUEST_PARAMETER' | 'INSUFFICIENT_MIN_CHAIN_BALANCE' | 'ETHEREUM_ADDRESS_BLOCKED' | 'PARENT_ADDRESS_ALREADY_ONBOARDED' | 'ONBOARDING_RATE_LIMITED' | 'SESSION_REVOKED' | 'SESSION_EXPIRED' | 'NOT_ONBOARDED' | 'INVALID_TOKEN' | 'INVALID_SUBKEY' | 'STARKNET_SIGNATURE_VERIFICATION_FAILED' | 'INVALID_TOKEN_SCOPE' | 'REQUEST_NOT_ALLOWED' | 'IP_NOT_ALLOWED' | 'NOT_FOUND' | 'INVALID_RESPONSE';
43
+ export type KnownSessionApiErrorCode = 'INVALID_SIGNATURE' | 'GRANT_EXPIRED' | 'INVALID_ENVIRONMENT' | 'INVALID_CHAIN' | 'SCOPE_NOT_ALLOWED' | 'LIMIT_INVALID' | 'NONCE_REUSED' | 'ACCOUNT_NOT_ELIGIBLE' | 'INVALID_GRANT' | 'SESSION_KEY_IN_USE' | 'SESSION_LIMIT_REACHED' | 'BUILDER_APPROVAL_LIMIT_REACHED' | 'BUILDER_APPROVAL_STALE' | 'SESSIONS_DISABLED' | 'INVALID_MARKETING_CODE' | 'INVALID_REQUEST_PARAMETER' | 'INSUFFICIENT_MIN_CHAIN_BALANCE' | 'ETHEREUM_ADDRESS_BLOCKED' | 'PARENT_ADDRESS_ALREADY_ONBOARDED' | 'ONBOARDING_RATE_LIMITED' | 'SESSION_REVOKED' | 'SESSION_EXPIRED' | 'NOT_ONBOARDED' | 'INVALID_TOKEN' | 'INVALID_SUBKEY' | 'STARKNET_SIGNATURE_VERIFICATION_FAILED' | 'INVALID_TOKEN_SCOPE' | 'REQUEST_NOT_ALLOWED' | 'IP_NOT_ALLOWED' | 'NOT_FOUND' | 'EVM_SIGNATURE_VERIFICATION_FAILED' | 'INVALID_EVM_SIGNATURE' | 'ETHEREUM_SIGNER_MISMATCH' | 'INVALID_STARKNET_ADDRESS' | 'PUBLIC_KEY_INVALID' | 'UNAUTHORIZED_ERROR' | 'BUILDER_CODES_NOT_ENABLED' | 'BUILDER_NOT_APPROVED' | 'BUILDER_FEE_RATE_OVER_APPROVAL' | 'BUILDER_NOT_ONBOARDED' | 'RFQ_NOT_ENABLED' | 'TOKEN_LIMIT_REACHED' | 'SUBKEY_REVOKED' | 'VALIDATION_ERROR' | 'ORDER_ID_NOT_FOUND' | 'ORDER_IS_CLOSED' | 'CLIENT_ORDER_ID_NOT_FOUND' | 'DUPLICATED_CLIENT_ID' | 'INVALID_ORDER_SIZE' | 'MARKET_NOT_FOUND' | 'MARKET_NOT_OPEN' | 'NO_ACCESS_TO_MARKET' | 'SYSTEM_STATUS_POST_ONLY' | 'SYSTEM_STATUS_CANCEL_ONLY' | 'GEO_IP_BLOCK' | 'SERVICE_UNAVAILABLE' | 'INTERNAL_ERROR' | 'INVALID_RESPONSE';
42
44
  export type SessionApiErrorCode = KnownSessionApiErrorCode | (string & {});
43
45
  export declare class SessionApiError extends Error {
44
46
  readonly status: number;
45
47
  readonly code: SessionApiErrorCode | undefined;
46
48
  readonly body: unknown;
49
+ /**
50
+ * Per-field detail the server adds to some errors, such as
51
+ * `INVALID_REQUEST_PARAMETER`'s `{ builder_fee_rate: "…" }`.
52
+ */
53
+ readonly data: Readonly<Record<string, unknown>> | undefined;
47
54
  constructor(status: number, body: unknown);
48
55
  }
@@ -52,5 +52,9 @@ export class SessionApiError extends Error {
52
52
  this.status = status;
53
53
  this.code = code;
54
54
  this.body = body;
55
+ this.data =
56
+ record.data != null && typeof record.data === 'object'
57
+ ? record.data
58
+ : undefined;
55
59
  }
56
60
  }
package/dist/siwe.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import type { Hex } from './types.js';
2
+ /**
3
+ * Sign-In with Ethereum (ERC-4361) messages, as Paradex's EVM owner login
4
+ * (`POST /v2/auth`) and onboarding (`POST /v2/onboarding`) take them.
5
+ */
6
+ export declare const SIWE_AUTH_STATEMENT = "Paradex Auth";
7
+ export declare const SIWE_ONBOARDING_STATEMENT = "Paradex Onboarding";
8
+ /** The server refuses an auth message valid for longer than this. */
9
+ export declare const SIWE_AUTH_MAX_TTL = 300;
10
+ export interface SiweMessageParams {
11
+ /** The Paradex app host the server accepts, e.g. `app.paradex.trade`. */
12
+ readonly domain: string;
13
+ readonly address: string;
14
+ readonly statement: string;
15
+ readonly chainId: number;
16
+ readonly nonce: string;
17
+ /** Seconds since the epoch. */
18
+ readonly issuedAt: number;
19
+ /** Seconds since the epoch. */
20
+ readonly expirationTime?: number;
21
+ }
22
+ /** EIP-55 mixed-case checksum spelling of an address. */
23
+ export declare function checksumAddress(address: string): string;
24
+ /** A 32-hex-character nonce (the server needs at least 16 characters). */
25
+ export declare function siweNonce(): string;
26
+ /** Formats an ERC-4361 message. */
27
+ export declare function buildSiweMessage(params: SiweMessageParams): string;
28
+ /** Standard base64 of an ASCII message, as the SIWE headers carry it. */
29
+ export declare function base64Ascii(message: string): string;
30
+ /**
31
+ * The uncompressed public key (`0x04…`) that made `signature`, an EIP-191
32
+ * `personal_sign` over the UTF-8 text `message`. Throws unless it belongs to
33
+ * `address`.
34
+ */
35
+ export declare function recoverPersonalSignPublicKey(message: string, signature: string, address: string): Hex;
package/dist/siwe.js ADDED
@@ -0,0 +1,94 @@
1
+ import { secp256k1 } from '@noble/curves/secp256k1';
2
+ import { keccak_256 } from '@noble/hashes/sha3';
3
+ import { bytesToHex } from './wallet.js';
4
+ /**
5
+ * Sign-In with Ethereum (ERC-4361) messages, as Paradex's EVM owner login
6
+ * (`POST /v2/auth`) and onboarding (`POST /v2/onboarding`) take them.
7
+ */
8
+ export const SIWE_AUTH_STATEMENT = 'Paradex Auth';
9
+ export const SIWE_ONBOARDING_STATEMENT = 'Paradex Onboarding';
10
+ /** The server refuses an auth message valid for longer than this. */
11
+ export const SIWE_AUTH_MAX_TTL = 300;
12
+ /** EIP-55 mixed-case checksum spelling of an address. */
13
+ export function checksumAddress(address) {
14
+ if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
15
+ throw new Error('address must be a 0x-prefixed 20-byte address');
16
+ }
17
+ const lower = address.slice(2).toLowerCase();
18
+ const hash = bytesToHex(keccak_256(new TextEncoder().encode(lower))).slice(2);
19
+ let out = '0x';
20
+ for (let i = 0; i < lower.length; i++) {
21
+ const c = lower.charAt(i);
22
+ out += parseInt(hash.charAt(i), 16) >= 8 ? c.toUpperCase() : c;
23
+ }
24
+ return out;
25
+ }
26
+ /** A 32-hex-character nonce (the server needs at least 16 characters). */
27
+ export function siweNonce() {
28
+ const bytes = new Uint8Array(16);
29
+ globalThis.crypto.getRandomValues(bytes);
30
+ return bytesToHex(bytes).slice(2);
31
+ }
32
+ function isoSeconds(seconds) {
33
+ return new Date(seconds * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z');
34
+ }
35
+ /** Formats an ERC-4361 message. */
36
+ export function buildSiweMessage(params) {
37
+ if (!/^[A-Za-z0-9.-]+(:\d+)?$/.test(params.domain)) {
38
+ throw new Error('domain must be a host name');
39
+ }
40
+ if (!/^[A-Za-z0-9]{8,}$/.test(params.nonce)) {
41
+ throw new Error('nonce must be at least 8 alphanumeric characters');
42
+ }
43
+ const lines = [
44
+ `${params.domain} wants you to sign in with your Ethereum account:`,
45
+ checksumAddress(params.address),
46
+ '',
47
+ params.statement,
48
+ '',
49
+ `URI: https://${params.domain}`,
50
+ 'Version: 1',
51
+ `Chain ID: ${params.chainId}`,
52
+ `Nonce: ${params.nonce}`,
53
+ `Issued At: ${isoSeconds(params.issuedAt)}`,
54
+ ];
55
+ if (params.expirationTime != null) {
56
+ lines.push(`Expiration Time: ${isoSeconds(params.expirationTime)}`);
57
+ }
58
+ return lines.join('\n');
59
+ }
60
+ /** Standard base64 of an ASCII message, as the SIWE headers carry it. */
61
+ export function base64Ascii(message) {
62
+ if (!/^[\x20-\x7e\n]*$/.test(message)) {
63
+ throw new Error('SIWE message must be printable ASCII');
64
+ }
65
+ return btoa(message);
66
+ }
67
+ /**
68
+ * The uncompressed public key (`0x04…`) that made `signature`, an EIP-191
69
+ * `personal_sign` over the UTF-8 text `message`. Throws unless it belongs to
70
+ * `address`.
71
+ */
72
+ export function recoverPersonalSignPublicKey(message, signature, address) {
73
+ const sig = signature.replace(/^0x/, '');
74
+ if (!/^[0-9a-fA-F]{130}$/.test(sig)) {
75
+ throw new Error('Wallet signature must be a 65-byte EOA signature; contract wallets are not supported');
76
+ }
77
+ const v = parseInt(sig.slice(128, 130), 16);
78
+ const recovery = v >= 27 ? v - 27 : v;
79
+ if (recovery !== 0 && recovery !== 1) {
80
+ throw new Error(`Wallet signature has an invalid v: ${v}`);
81
+ }
82
+ const bytes = new TextEncoder().encode(message);
83
+ const prefix = new TextEncoder().encode(`\x19Ethereum Signed Message:\n${bytes.length}`);
84
+ const digest = keccak_256(new Uint8Array([...prefix, ...bytes]));
85
+ const publicKey = new secp256k1.Signature(BigInt(`0x${sig.slice(0, 64)}`), BigInt(`0x${sig.slice(64, 128)}`))
86
+ .addRecoveryBit(recovery)
87
+ .recoverPublicKey(digest)
88
+ .toRawBytes(false);
89
+ const recovered = bytesToHex(keccak_256(publicKey.slice(1)).slice(-20));
90
+ if (recovered.toLowerCase() !== address.toLowerCase()) {
91
+ throw new Error(`Wallet signature recovers to ${recovered}, not the wallet ${address}`);
92
+ }
93
+ return bytesToHex(publicKey);
94
+ }