@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.
package/README.md CHANGED
@@ -237,6 +237,50 @@ const result = await client.withdraw('USDC', '100', bridgeCall);
237
237
  await client.waitForTransaction(result.hash);
238
238
  ```
239
239
 
240
+ ### Withdraw from an EVM-owned account
241
+
242
+ An EVM-owned (EIP-191) account is one whose on-chain owner is an EVM wallet, for example a Privy embedded wallet or MetaMask. Paradex creates these for wallets that log in with one signature. They have no Stark key: do not use `Client.fromEthSigner` for them, which derives a key for a different account (with the determinism guard on, it refuses with `evm_owned_account`).
243
+
244
+ `Client.fromEvmOwner` signs each transaction with the owner wallet (`personal_sign` over the Starknet transaction hash), one wallet prompt per withdrawal. The account address is looked up from the wallet; pass `accountAddress` to act on an EVM sub-account the same wallet owns.
245
+
246
+ ```typescript
247
+ import * as Paradex from '@paradex/sdk';
248
+
249
+ const config = await Paradex.Config.fetch('testnet');
250
+
251
+ // Any of: ethers Signer, viem WalletClient/LocalAccount, or an EIP-1193
252
+ // provider (window.ethereum, a Privy embedded wallet's provider).
253
+ const signer = Paradex.EvmOwnerSigner.fromEip1193({
254
+ provider: await privyWallet.getEthereumProvider(),
255
+ address: privyWallet.address,
256
+ });
257
+ // const signer = Paradex.EvmOwnerSigner.fromEthers(ethersSigner);
258
+ // const signer = Paradex.EvmOwnerSigner.fromViem({ client: walletClient, account });
259
+
260
+ const client = await Paradex.Client.fromEvmOwner({ config, signer });
261
+
262
+ // Build the bridge call for the amount that arrives after socialized loss.
263
+ const amount = '100';
264
+ const receivable = await client.getReceivableAmount('USDC', amount);
265
+ const bridgeCall = Paradex.Bridge.starkgateWithdrawCall({
266
+ config,
267
+ token: 'USDC',
268
+ l1Recipient: await signer.getAddress(),
269
+ amountChain: receivable.receivableAmountChain,
270
+ });
271
+
272
+ // paraclear.withdraw + bridge call in one atomic transaction.
273
+ const { hash } = await client.withdraw('USDC', amount, bridgeCall);
274
+ await client.waitForTransaction(hash);
275
+ ```
276
+
277
+ Notes:
278
+
279
+ - `paraclear.withdraw` moves the funds into the account contract's own Starknet token balance, and the bridge call moves them out in the same transaction. Don't use `paraclear.transfer` as a bridge call: it credits another account's Paraclear balance, not the bridge.
280
+ - A custom signer (an MPC or embedded-wallet API) must `personal_sign` the 32 hash bytes, not their hex text. The SDK checks that each signature recovers to the owner before it sends, so a wrong encoding fails with a clear error.
281
+ - The fee is estimated without account validation, so the wallet signs only once, and a fixed L2 gas allowance covers the account's EIP-191 check.
282
+ - `getTokenBalance` and `getMaxWithdraw` are not available on this client: the full node returns account data only to authenticated callers. Read balances from the REST API (`GET /v1/balance`) with the account's JWT.
283
+
240
284
  ## TypeScript Support
241
285
 
242
286
  The SDK is written in TypeScript and provides full type definitions out of the box.
@@ -350,7 +394,7 @@ A grant from a wallet with no Paradex account yet opens the account along with i
350
394
 
351
395
  An EVM-owned account's sub-accounts can be listed before signing in with `connector.listSubaccounts(ethAddress)`. When the owner signer knows its address (`ownerSignerFromEip1193` does; pass `address` to `ownerSignerFromExternal`), `open()` checks a grant's `subaccounts` against that list before the wallet is asked to sign.
352
396
 
353
- `SessionAccounts` then mints a JWT per account the grant lists (the main account and any `subaccounts`) through `POST /v1/auth/{session_public_key}` with `PARADEX-STARKNET-ACCOUNT`, each for at most 15 minutes and never past the grant's expiry. It keeps one websocket per account and routes requests by account. Sessions never use `on_behalf_of`. When the server refuses a session token or the session key, `SessionAccounts` checks `GET /v2/sessions/{grant_id}/status`. If the grant is revoked or expired, every account is dropped and `onDropped` is called; any other refusal is treated as transient. RFQ endpoints need `trade:rfq` in the grant, or they answer 403 `INVALID_TOKEN_SCOPE`. Create, execute and drafts are open to a session whose grant also caps nothing and names no builder, where the server has enabled RFQ for the account's sessions; otherwise they answer 403 `REQUEST_NOT_ALLOWED`. An account not yet deployed gets 400 `NOT_ONBOARDED`. None of these ends the session. A session may also deposit into its own account (`POST /v1/deposit-addresses`, and `POST /v1/bridges/layerswap/swaps` with `use_deposit_address` and no `source_address`), but never move funds out. `accounts.revoke()` revokes the grant itself and, by default, cancels the session's resting orders, TWAPs and untriggered stops on every account: once revoked, the key can no longer cancel them. This differs from the Paradex app's own sign-out, which keeps orders because they are the owner's own trading. With `accounts.revoke({ cancelOrders: false })` a grant without a builder signs out and its orders keep working; a builder grant still has its TWAPs and untriggered stops cancelled and keeps only its resting orders.
397
+ `SessionAccounts` then mints a JWT per account the grant lists (the main account and any `subaccounts`) through `POST /v1/auth/{session_public_key}` with `PARADEX-STARKNET-ACCOUNT`, each for at most 15 minutes and never past the grant's expiry. It keeps one websocket per account and routes requests by account. Sessions never use `on_behalf_of`. When the server refuses a session token or the session key, `SessionAccounts` checks `GET /v2/sessions/{grant_id}/status`. If the grant is revoked or expired, every account is dropped and `onDropped` is called; any other refusal is treated as transient. RFQ endpoints need `trade:rfq` in the grant, or they answer 403 `INVALID_TOKEN_SCOPE`. Create, execute and drafts are open to a session whose grant also caps nothing, where the server has enabled RFQ for the account's sessions; a grant that names a builder also needs the server to have enabled RFQ for that builder. Otherwise they answer 403 `REQUEST_NOT_ALLOWED`. An account not yet deployed gets 400 `NOT_ONBOARDED`. None of these ends the session. A session may also deposit into its own account (`POST /v1/deposit-addresses`, and `POST /v1/bridges/layerswap/swaps` with `use_deposit_address` and no `source_address`), but never move funds out. `accounts.revoke()` revokes the grant itself and, by default, cancels the session's resting orders, TWAPs and untriggered stops on every account: once revoked, the key can no longer cancel them. This differs from the Paradex app's own sign-out, which keeps orders because they are the owner's own trading. With `accounts.revoke({ cancelOrders: false })` a grant without a builder signs out and its orders keep working; a builder grant still has its TWAPs and untriggered stops cancelled and keeps only its resting orders.
354
398
 
355
399
  ```typescript
356
400
  const connector = new Paradex.SessionConnector({
@@ -408,6 +452,15 @@ const unsubscribe = await accounts.subscribe('0x...', 'orders.ALL', (data) =>
408
452
  );
409
453
  ```
410
454
 
455
+ Handlers get objects in the JSON feed's shape (`orders.*`, `fills.*`, `positions`, `account` and the market channels). The server sends most of these as binary (SBE) messages, which the SDK asks for and decodes:
456
+
457
+ - Some fields are not in the binary messages: a fill's `builder`, `builder_fee`, `builder_fee_rate`, `remaining_size` and `leverage`; an order's `builder`, `builder_fee_rate` and `timestamp`; a position's `id`, `created_at`, `closed_at`, `average_exit_price` and `realized_positional_funding_pnl`; an account's `withdrawal_lock`, `withdrawal_lock_rejection` and `resync_pause_until`; a market summary's `rolling_details` and deprecated top-level `delta`; and a trade's `block_id`. Read them from the REST API, for example `listFills`.
458
+ - Some values differ from the JSON feed: one the messages have no code for reads `UNKNOWN`, `flags` is `[]` rather than `null` when there are none, `funding_data` rates are cut to 8 decimal places, a market summary's `total_volume` stops at 92233720368.54775807, and a funding rate comparison's `last_updated_at` is in milliseconds.
459
+ - `orders.*` and `fills.*` are served from one `.ALL` subscription per account, filtered by market, so `orders.ALL` and `orders.BTC-USD-PERP` can be open together. Two market channels of one kind that share a market, such as `trades.ALL` and `trades.BTC-USD-PERP`, can't be open on one account at once; the second `subscribe` throws.
460
+ - The SDK asks for schema version 3. For a server that offers less, pass a `wsUrl` with its own `sbeSchemaId` and `sbeSchemaVersion`.
461
+ - A custom `webSocketFactory` must return a socket that honours `binaryType = 'arraybuffer'`.
462
+ - A message that can't be read goes to `onMessageError`, or `console.error`.
463
+
411
464
  > `/v2/sessions` is experimental; its request and response shapes may change.
412
465
 
413
466
  ### Builder approvals without a session (experimental)
@@ -427,7 +480,7 @@ const { approval } = await connector.approveBuilder({
427
480
  `BuilderCodesClient` reads an account's builder approvals and the public Builder Codes stats.
428
481
 
429
482
  - `listApprovals(token)` lists the account's live approvals, newest first. Pass `{ includeInactive: true }` to add revoked and expired ones, for the history. Each approval has a `status` (`active`, `revoked` or `expired`), a `max_fee_rate`, and `expires_at`, `approved_at` and `revoked_at` in milliseconds.
430
- - `revokeApproval(token, builderAccount)` revokes an approval. New orders naming that builder are refused at once, and its resting orders on the account and its sub-accounts are cancelled.
483
+ - `revokeApproval(token, builderAccount)` revokes an approval. New orders naming that builder are refused at once, and its resting orders on the account and its sub-accounts are cancelled. Every session of the account naming that builder is revoked too, on every device.
431
484
  - Both calls need the account owner's main-key JWT as `token`. A session or subkey token is refused. Listing is also refused for an account Paradex has not enabled sessions for.
432
485
  - `fetchStats(builderAccount)` returns one row per window (`24h`, `7d`, `30d`, `all`). `fees_paid` is what traders paid the builder in USDC, before any protocol share.
433
486
  - `fetchLeaderboard(window)` ranks builders by `fees_paid` over one window, `7d` by default. The server answers 400 for a window it does not serve.
@@ -441,6 +494,81 @@ const approvals = await builders.listApprovals(ownerJwt, {
441
494
  const leaderboard = await builders.fetchLeaderboard('30d');
442
495
  ```
443
496
 
497
+ ## Build a builder app (experimental)
498
+
499
+ `BuilderApp` is the whole Builder Codes flow for a builder's web app, behind one object: connect the user's wallet, open their account and a session that approves your builder, trade with your fee, read fills, manage approvals, withdraw, and read builder stats. Builders use sessions, never subkeys. Apps that used Privy-made subkeys: see [docs/migrating-from-privy-subkeys.md](docs/migrating-from-privy-subkeys.md).
500
+
501
+ ```ts
502
+ import * as Paradex from '@paradex/sdk';
503
+
504
+ // An injected wallet…
505
+ const wallet = Paradex.Wallet.fromEip1193({ provider: window.ethereum });
506
+ // …or a Privy embedded wallet (its access token lets a verified user skip
507
+ // the minimum-balance check when their account is opened):
508
+ // const wallet = Paradex.Wallet.fromPrivy({
509
+ // provider: await embedded.getEthereumProvider(),
510
+ // address: embedded.address,
511
+ // getAccessToken,
512
+ // });
513
+
514
+ const app = await Paradex.BuilderApp.connect({
515
+ environment: 'testnet', // 'prod' | 'testnet' | 'nightly'
516
+ wallet,
517
+ builder: {
518
+ account: '0x<builder account>',
519
+ feeRate: '0.0005',
520
+ maxFeeRate: '0.001',
521
+ },
522
+ });
523
+
524
+ // One EIP-712 prompt. For a wallet with no account, the grant opens it too.
525
+ const session = (await app.restoreSession()) ?? (await app.openSession());
526
+
527
+ const order = await session.placeOrder({
528
+ market: 'BTC-USD-PERP',
529
+ side: 'BUY',
530
+ type: 'LIMIT',
531
+ size: '0.01',
532
+ price: '60000',
533
+ }); // carries builder and builder_fee_rate
534
+ await session.cancelOrder(order.id);
535
+ const { results: fills } = await session.listFills({ pageSize: 50 }); // builder, builder_fee
536
+
537
+ await app.approveBuilder(); // standalone approval, for main-key orders
538
+ await app.listApprovals(); // needs the owner's SIWE login, see below
539
+ await app.revokeApproval();
540
+ await app.enableRfq(); // same owner login; turns on RFQ for the account
541
+ await app.withdraw({ amount: '25' }); // EIP-191 by the owner, StarkGate to L1
542
+ await app.builderStats();
543
+ await app.leaderboard('7d');
544
+ ```
545
+
546
+ | Step | Call | Wallet prompts |
547
+ | ---------------------------- | --------------------------------------------- | ------------------------------- |
548
+ | Connect | `BuilderApp.connect` | none (connect only) |
549
+ | Open account without trading | `app.onboard({ referralCode })` | 1 `personal_sign` (SIWE) |
550
+ | Open session (and account) | `app.openSession()` | 1 EIP-712 |
551
+ | Orders, fills, account info | `session.*` | none |
552
+ | Standalone approval | `app.approveBuilder()` | 1 EIP-712 |
553
+ | List or revoke approvals | `app.listApprovals()`, `app.revokeApproval()` | 1 `personal_sign` per 5 minutes |
554
+ | Enable RFQ | `app.enableRfq()` | 1 `personal_sign` per 5 minutes |
555
+ | Withdraw | `app.withdraw()` | 1 `personal_sign` |
556
+
557
+ Things to know:
558
+
559
+ - **Scopes.** `openSession()` grants `trade` only. To trade RFQs through the session, ask for `trade:rfq` too: `app.openSession({ scopes: ['trade', 'trade:rfq'] })`, and restore with `app.restoreSession({ scopes: ['trade:rfq'] })` so a session opened without it is not picked. RFQ reads need only the scope. RFQ writes (create, execute, drafts) through a builder session also need the server to have enabled RFQ for your builder and for the account's sessions; until then they answer 403. The scopes must include `trade` (`BuilderSessionScope` allows `trade` and `trade:rfq`).
560
+ - **Deferred deploy.** A new account exists at once and deploys shortly after. Until then `session.accountInfo()` reads `onboarding_status: 'ONBOARDING'` and `is_deployed: false`, and orders may be refused with `NOT_ONBOARDED`.
561
+ - **Enabling RFQ.** RFQ calls on an account are refused with `RFQ_NOT_ENABLED` until the account owner enables RFQ once, with `app.enableRfq()` (or in the Paradex app). That turns RFQ on for the account only: a session's RFQ calls also need `trade:rfq` in its grant and Paradex allowing RFQ for that builder's sessions, and otherwise get 403 `INVALID_TOKEN_SCOPE` or `REQUEST_NOT_ALLOWED`. It provisions the account on Paradigm, the RFQ venue, and registers a Paradigm delegation subkey on the account, which signs its RFQ trades and counts against the account's subkey limit: at the limit it fails with 400 `TOKEN_LIMIT_REACHED` until the user revokes a subkey. It needs the owner login below, since a session cannot enable RFQ. It is idempotent: on an enabled account it returns the same `{ account, subkey_public_key, status: 'ENABLED' }`, so you can call it whenever you see `RFQ_NOT_ENABLED`. RFQ is enabled per account: for a session trading an EVM sub-account, pass it as `app.enableRfq({ account })`, which takes its own owner login. It can take up to 30 s; a slow call ends as a retryable 503 `SERVICE_UNAVAILABLE`, and calling again resumes it. Other refusals: 400 `REQUEST_NOT_ALLOWED` with Paradigm's reason when Paradigm refuses the account (calling again does not change it), 409 `SUBKEY_REVOKED` when the new delegation subkey is already revoked (the user contacts support), and `NOT_ONBOARDED` while the account is still deploying. `RfqClient.enable(token)` makes the same call with a token you already hold.
562
+ - **Owner login.** Listing and revoking approvals, and enabling RFQ, need the owner's own JWT, from a Sign-In with Ethereum message that must name the Paradex app's host (`SIWE_DOMAINS`). Privy's embedded wallet signs it with no domain warning (behind its usual confirmation, unless the app turned that off). Injected wallets such as MetaMask warn that the message is for another site than yours, and that warning is what protects users from phishing pages asking for the same message. So with an injected wallet `listApprovals`, `revokeApproval` and `enableRfq` throw `OWNER_LOGIN_NEEDS_PARADEX_APP`: check `app.canManageApprovals` (it covers `enableRfq` too) and link to `app.approvalsSettingsUrl` (Paradex settings, Builder approvals) instead, or have the user enable RFQ in the Paradex app. `allowCrossSiteOwnerLogin: true` turns the check off; think hard before you set it. The login gives the page a 5-minute token with the owner's full rights, which can also mint a year-long read-only token, enable RFQ and change subkey IP allowlists. The SDK uses it only for these three calls and has no public method that returns it, but it is not hidden from your page: a custom `transport`, or any script on the page, can read it from the requests. Never log or store it. The SDK may move the approval calls to the session's own token later; their signatures will not change.
563
+ - **Classic accounts.** A wallet whose Paradex account is Stark-owned (opened before one-signature login) can't use a builder app: `BuilderApp.connect` throws `STARK_OWNED_ACCOUNT`. Tell the user to keep trading in the Paradex app.
564
+ - **Ending a session keeps the approval.** `session.revoke()` stops the session, but the builder approval its grant carried stays active until it expires, by default when the last of the sessions that carried it would have expired, unless `app.approveBuilder()` gave it its own expiry (180 days by default). Call `app.revokeApproval()` to end the approval (with an injected wallet, link to `app.approvalsSettingsUrl`). It also revokes every session of the account naming your builder, on every device including this page's own (its `BuilderSession` keeps working until its next request is refused; the SDK then drops it and calls `onDropped`), and cancels resting orders naming it on the account and its subaccounts, including any a session kept with `cancelOrders: false`; those also end when the approval expires.
565
+ - **One builder per session.** A session's orders may name only its grant's builder. A grant naming a builder carries no referral code; call `app.onboard({ referralCode })` first if you need one.
566
+ - **Errors.** A request the server refuses throws a `ParadexApiError` with `status`, `code` and `data`; the SDK throws a `BuilderAppError` with a `code` for `INVALID_ORDER` (an order it can't sign, from `BuilderApp` or `SessionAccounts` alike), `BUILDER_FEE_RATE_OVER_APPROVAL`, `STARK_OWNED_ACCOUNT` and `OWNER_LOGIN_NEEDS_PARADEX_APP`, the grant checks the SDK makes before sending throw a `SessionGrantError` with a `code` (such as `ACCOUNT_NOT_IN_GRANT`, `GRANT_EXPIRED` or `TTL_EXCEEDED`), other checks throw a plain `Error`, and a declined wallet prompt throws `WalletRejectedError`. `Paradex.Errors.describe(error)` gives `{ code, status, retryable, hint }`; `Paradex.Errors.isCode(error, 'BUILDER_CODES_NOT_ENABLED')` tests the code `describe` reports, whichever side raised it, and narrows `error` to the classes that carry it. Codes to expect: `BUILDER_CODES_NOT_ENABLED`, `BUILDER_NOT_APPROVED`, `BUILDER_FEE_RATE_OVER_APPROVAL`, `RFQ_NOT_ENABLED`, `TOKEN_LIMIT_REACHED`, `SUBKEY_REVOKED`, `REQUEST_NOT_ALLOWED` and `NOT_ONBOARDED` (from `enableRfq`), `INVALID_REQUEST_PARAMETER` (the hint gives the reason; `error.data` has it by field), `INVALID_GRANT` (such as a `maxFeeRate` above Paradex's limit), `INVALID_ORDER`, the grant codes above, `ONBOARDING_RATE_LIMITED`, `INSUFFICIENT_MIN_CHAIN_BALANCE`, `STARK_OWNED_ACCOUNT`, `OWNER_LOGIN_NEEDS_PARADEX_APP`, and `WALLET_REJECTED` when the user declines a prompt.
567
+ - Only EOA wallets are supported.
568
+ - **Account switches.** The wallet keeps the address it connected with. When the user switches accounts (`accountsChanged`), call `BuilderApp.connect` again; signing with a switched injected wallet fails with an error rather than signing for the other account.
569
+
570
+ Runnable: `PRIVATE_KEY=0x… BUILDER_ACCOUNT=0x… yarn example:builder` runs the flow on testnet. Browser snippets: `examples/builder-app/browser.ts`.
571
+
444
572
  ## Best Practices
445
573
 
446
574
  ### 1. Environment Variables
@@ -576,6 +704,8 @@ For a full React application example, see: [paradex-react-example](https://githu
576
704
  | `getAddress()` | Get account address | `string` |
577
705
  | `getProvider()` | Get underlying provider | `DefaultProvider` |
578
706
 
707
+ `Client.fromEvmOwner({ config, signer, accountAddress? })` returns an `EvmOwnerClient` with `withdraw`, `getReceivableAmount`, `getSocializedLossFactor`, `waitForTransaction`, `getAddress` and `getOwnerAddress`. Owner signers: `EvmOwnerSigner.fromEthers`, `EvmOwnerSigner.fromViem`, `EvmOwnerSigner.fromEip1193`. Bridge calls: `Bridge.starkgateWithdrawCall`.
708
+
579
709
  ### Configuration
580
710
 
581
711
  | Method | Description | Returns |
@@ -0,0 +1,76 @@
1
+ import { SessionApiError, type KnownSessionApiErrorCode } from './session-transport.js';
2
+ import { SessionGrantError, type SessionGrantErrorCode } from './session-typed-data.js';
3
+ import { WalletRejectedError } from './wallet.js';
4
+ /**
5
+ * Builder-facing help for a Paradex API error: whether it is worth retrying
6
+ * and a one-line hint to show or log.
7
+ *
8
+ * @experimental
9
+ */
10
+ export interface ApiErrorDescription {
11
+ /** The API error code, or an SDK code for errors raised locally. */
12
+ readonly code: string;
13
+ /** HTTP status; `undefined` for errors raised before any request. */
14
+ readonly status: number | undefined;
15
+ /** Whether the same call may succeed if retried later, unchanged. */
16
+ readonly retryable: boolean;
17
+ readonly hint: string;
18
+ }
19
+ /** Codes of the errors the SDK raises itself, before any request. */
20
+ export type BuilderAppErrorCode = 'STARK_OWNED_ACCOUNT' | 'OWNER_LOGIN_NEEDS_PARADEX_APP' | 'BUILDER_FEE_RATE_OVER_APPROVAL' | 'INVALID_ORDER';
21
+ /**
22
+ * An error the SDK raises itself, with a stable code for
23
+ * {@link describeApiError}.
24
+ *
25
+ * @experimental
26
+ */
27
+ export declare class BuilderAppError extends Error {
28
+ readonly code: BuilderAppErrorCode;
29
+ /** `options.cause` is the error this one wraps, as `Error`'s own `cause`. */
30
+ constructor(code: BuilderAppErrorCode, message: string, options?: {
31
+ readonly cause?: unknown;
32
+ });
33
+ }
34
+ /** Codes only the SDK raises, never the server. */
35
+ type SdkOnlyErrorCode = Exclude<'WALLET_REJECTED' | SessionGrantErrorCode | BuilderAppErrorCode, KnownSessionApiErrorCode>;
36
+ /** Codes {@link describeApiError} gives an error that carries none. */
37
+ type DerivedErrorCode = 'NETWORK_ERROR' | 'UNKNOWN' | `HTTP_${number}`;
38
+ declare const derivedCode: unique symbol;
39
+ /**
40
+ * A type no value has: `isApiErrorCode` narrows to it when the code says
41
+ * nothing about the class, so a false answer drops no type either.
42
+ */
43
+ export interface DerivedApiErrorCode<C extends string> {
44
+ readonly [derivedCode]: C;
45
+ }
46
+ /**
47
+ * What `isApiErrorCode(error, C)` narrows `error` to: the classes that can
48
+ * carry `C`, with `code` fixed to `C` so an error of the same class with
49
+ * another code is left in the other branch. `NETWORK_ERROR` narrows only to
50
+ * `TypeError`, and `UNKNOWN` or a `string` code not at all, without
51
+ * dropping a type when the answer is false.
52
+ */
53
+ export type ApiErrorWithCode<C extends string> = string extends C ? DerivedApiErrorCode<C> : C extends DerivedErrorCode ? C extends `HTTP_${number}` ? SessionApiError & {
54
+ readonly code: undefined;
55
+ } : C extends 'NETWORK_ERROR' ? TypeError & DerivedApiErrorCode<C> : DerivedApiErrorCode<C> : (C extends 'WALLET_REJECTED' ? WalletRejectedError : never) | (C extends SessionGrantErrorCode ? SessionGrantError & {
56
+ readonly code: C;
57
+ } : never) | (C extends BuilderAppErrorCode ? BuilderAppError & {
58
+ readonly code: C;
59
+ } : never) | (C extends SdkOnlyErrorCode ? never : SessionApiError & {
60
+ readonly code: C;
61
+ });
62
+ /**
63
+ * Whether {@link describeApiError} reports `code` for `error`, whether the
64
+ * server or the SDK raised it. It narrows to the classes that can carry the
65
+ * code, so a server-only code such as `INVALID_REQUEST_PARAMETER` gives a
66
+ * `SessionApiError` with its `data`.
67
+ */
68
+ export declare function isApiErrorCode<C extends KnownSessionApiErrorCode | BuilderAppErrorCode | SessionGrantErrorCode | DerivedErrorCode | 'WALLET_REJECTED' | (string & Record<never, never>)>(error: unknown, code: C): error is ApiErrorWithCode<C>;
69
+ /** A code, whether it retries and a hint for any error the SDK throws. */
70
+ export declare function describeApiError(error: unknown): ApiErrorDescription;
71
+ /**
72
+ * Why Paradex cancelled an order naming a builder, as the order's
73
+ * `cancel_reason` reads.
74
+ */
75
+ export type BuilderCancelReason = 'BUILDER_FEES_DISABLED' | 'BUILDER_FEE_INVALID' | 'BUILDER_APPROVAL_EXPIRED' | 'BUILDER_APPROVAL_REVOKED' | 'BUILDER_FEE_RATE_OVER_APPROVAL';
76
+ export {};
@@ -0,0 +1,249 @@
1
+ import { SessionApiError, } from './session-transport.js';
2
+ import { SessionGrantError, } from './session-typed-data.js';
3
+ import { WalletRejectedError } from './wallet.js';
4
+ const HELP = {
5
+ BUILDER_CODES_NOT_ENABLED: {
6
+ retryable: false,
7
+ hint: 'Builder Codes is not enabled for this account yet.',
8
+ },
9
+ BUILDER_NOT_APPROVED: {
10
+ retryable: false,
11
+ hint: "The account has no live approval of this builder, or the session's grant names another builder. Approve the builder first.",
12
+ },
13
+ BUILDER_FEE_RATE_OVER_APPROVAL: {
14
+ retryable: false,
15
+ hint: "The order's builder fee rate is above the rate the user approved.",
16
+ detail: true,
17
+ },
18
+ BUILDER_NOT_ONBOARDED: {
19
+ retryable: false,
20
+ hint: 'The builder account is not an onboarded Paradex account.',
21
+ },
22
+ BUILDER_APPROVAL_LIMIT_REACHED: {
23
+ retryable: false,
24
+ hint: 'The account has too many live builder approvals; revoke one first.',
25
+ },
26
+ BUILDER_APPROVAL_STALE: {
27
+ retryable: true,
28
+ hint: 'The approval was replaced or revoked in the same second it was signed; sign it again.',
29
+ },
30
+ RFQ_NOT_ENABLED: {
31
+ retryable: false,
32
+ hint: 'RFQ is not enabled for this account. The owner enables it with BuilderApp.enableRfq() or in the Paradex app.',
33
+ },
34
+ TOKEN_LIMIT_REACHED: {
35
+ retryable: false,
36
+ hint: 'The account has too many subkeys or tokens; revoke one and try again.',
37
+ },
38
+ SUBKEY_REVOKED: {
39
+ retryable: false,
40
+ hint: "The account's RFQ delegation subkey was revoked; contact Paradex support to restore RFQ access.",
41
+ },
42
+ INVALID_GRANT: {
43
+ retryable: false,
44
+ hint: 'The grant or approval is malformed, or asks for more than Paradex allows, such as a builder maxFeeRate above its limit.',
45
+ detail: true,
46
+ },
47
+ INVALID_REQUEST_PARAMETER: {
48
+ retryable: false,
49
+ hint: "A request field is invalid; the error's data names the field.",
50
+ detail: true,
51
+ },
52
+ VALIDATION_ERROR: {
53
+ retryable: false,
54
+ hint: 'The request failed validation.',
55
+ },
56
+ ONBOARDING_RATE_LIMITED: {
57
+ retryable: true,
58
+ hint: 'Too many new accounts were opened from this network; try again later.',
59
+ },
60
+ INSUFFICIENT_MIN_CHAIN_BALANCE: {
61
+ retryable: false,
62
+ hint: 'The wallet needs a minimum ETH or USDC balance on a supported chain to open an account, or a verified Privy login.',
63
+ },
64
+ PARENT_ADDRESS_ALREADY_ONBOARDED: {
65
+ retryable: false,
66
+ hint: 'This wallet already has a Paradex account.',
67
+ },
68
+ ETHEREUM_ADDRESS_BLOCKED: {
69
+ retryable: false,
70
+ hint: 'This wallet cannot use Paradex.',
71
+ },
72
+ ACCOUNT_NOT_ELIGIBLE: {
73
+ retryable: false,
74
+ hint: 'This account cannot take this action (for example a vault or sub-account where a main account is needed).',
75
+ },
76
+ SESSIONS_DISABLED: {
77
+ retryable: false,
78
+ hint: 'Sessions (or Builder Codes on a grant) are not enabled for this account yet.',
79
+ },
80
+ SESSION_LIMIT_REACHED: {
81
+ retryable: false,
82
+ hint: 'The account has too many live sessions; revoke one first.',
83
+ },
84
+ SESSION_REVOKED: { retryable: false, hint: 'The session was revoked.' },
85
+ SESSION_EXPIRED: { retryable: false, hint: 'The session expired.' },
86
+ GRANT_EXPIRED: {
87
+ retryable: true,
88
+ hint: "The signed message was outside the server's time window; check the device clock and sign again.",
89
+ },
90
+ INVALID_SIGNATURE: {
91
+ retryable: false,
92
+ hint: 'The wallet signature was refused. Contract wallets are not supported.',
93
+ },
94
+ EVM_SIGNATURE_VERIFICATION_FAILED: {
95
+ retryable: false,
96
+ hint: "The sign-in message was refused: wrong domain or chain, outside the server's time window, or already used.",
97
+ },
98
+ UNAUTHORIZED_ERROR: {
99
+ retryable: false,
100
+ hint: "Only the account owner's own login may do this.",
101
+ },
102
+ INVALID_TOKEN_SCOPE: {
103
+ retryable: false,
104
+ hint: 'A session cannot do this; the account owner must sign in.',
105
+ },
106
+ NOT_ONBOARDED: {
107
+ retryable: true,
108
+ hint: 'The account is not active yet (it may still be deploying).',
109
+ },
110
+ GEO_IP_BLOCK: {
111
+ retryable: false,
112
+ hint: 'Paradex is not available in this region.',
113
+ },
114
+ SERVICE_UNAVAILABLE: {
115
+ retryable: true,
116
+ hint: 'Paradex is temporarily unavailable.',
117
+ },
118
+ INTERNAL_ERROR: { retryable: true, hint: 'Paradex had an internal error.' },
119
+ SYSTEM_STATUS_CANCEL_ONLY: {
120
+ retryable: true,
121
+ hint: 'The exchange is in cancel-only mode.',
122
+ },
123
+ SYSTEM_STATUS_POST_ONLY: {
124
+ retryable: true,
125
+ hint: 'The exchange is in post-only mode.',
126
+ },
127
+ };
128
+ /** `INVALID_ORDER` has none: its message is the reason. */
129
+ const BUILDER_APP_HELP = {
130
+ // The server raises it too; the SDK checks first.
131
+ BUILDER_FEE_RATE_OVER_APPROVAL: HELP.BUILDER_FEE_RATE_OVER_APPROVAL?.hint,
132
+ STARK_OWNED_ACCOUNT: "This wallet's Paradex account can't trade through builder apps yet; the user can keep using it in the Paradex app.",
133
+ OWNER_LOGIN_NEEDS_PARADEX_APP: 'Listing and revoking builder approvals, and enabling RFQ, with an injected wallet need the Paradex app: link the user to Paradex settings, Builder approvals, or have them enable RFQ there.',
134
+ };
135
+ /**
136
+ * An error the SDK raises itself, with a stable code for
137
+ * {@link describeApiError}.
138
+ *
139
+ * @experimental
140
+ */
141
+ export class BuilderAppError extends Error {
142
+ /** `options.cause` is the error this one wraps, as `Error`'s own `cause`. */
143
+ constructor(code, message, options = {}) {
144
+ super(message);
145
+ this.name = 'BuilderAppError';
146
+ this.code = code;
147
+ if ('cause' in options) {
148
+ Object.defineProperty(this, 'cause', {
149
+ value: options.cause,
150
+ writable: true,
151
+ configurable: true,
152
+ });
153
+ }
154
+ }
155
+ }
156
+ /**
157
+ * Whether {@link describeApiError} reports `code` for `error`, whether the
158
+ * server or the SDK raised it. It narrows to the classes that can carry the
159
+ * code, so a server-only code such as `INVALID_REQUEST_PARAMETER` gives a
160
+ * `SessionApiError` with its `data`.
161
+ */
162
+ export function isApiErrorCode(error, code) {
163
+ return describeApiError(error).code === code;
164
+ }
165
+ /** `hint`, then the fields the server named or else its message. */
166
+ function withReason(hint, error) {
167
+ const fields = Object.entries(error.data ?? {}).map(([field, why]) => `${field}: ${typeof why === 'string' ? why : JSON.stringify(why)}`);
168
+ const message = error.body?.message;
169
+ // A request the server could not parse names the field in `message`;
170
+ // its data is only `{ param, expected, got }`.
171
+ const bindError = typeof message === 'string' &&
172
+ ['param', 'expected', 'got'].every((key) => key in (error.data ?? {}));
173
+ const reason = fields.length > 0 && !bindError
174
+ ? fields.join('; ')
175
+ : typeof message === 'string'
176
+ ? message
177
+ : '';
178
+ return reason === '' ? hint : `${hint} Reason: ${reason}`;
179
+ }
180
+ /** The code's hint and the error's own message, which has the values. */
181
+ function builderAppHint(error) {
182
+ const hint = BUILDER_APP_HELP[error.code];
183
+ if (hint == null)
184
+ return error.message;
185
+ return error.code === 'BUILDER_FEE_RATE_OVER_APPROVAL'
186
+ ? `${hint} Reason: ${error.message}`
187
+ : hint;
188
+ }
189
+ /** A code, whether it retries and a hint for any error the SDK throws. */
190
+ export function describeApiError(error) {
191
+ if (error instanceof WalletRejectedError) {
192
+ return {
193
+ code: 'WALLET_REJECTED',
194
+ status: undefined,
195
+ retryable: true,
196
+ hint: 'The user rejected the wallet prompt.',
197
+ };
198
+ }
199
+ if (error instanceof BuilderAppError) {
200
+ return {
201
+ code: error.code,
202
+ status: undefined,
203
+ retryable: false,
204
+ hint: builderAppHint(error),
205
+ };
206
+ }
207
+ if (error instanceof SessionGrantError) {
208
+ return {
209
+ code: error.code,
210
+ status: undefined,
211
+ retryable: false,
212
+ hint: error.message,
213
+ };
214
+ }
215
+ if (error instanceof SessionApiError) {
216
+ const help = error.code != null
217
+ ? HELP[error.code]
218
+ : undefined;
219
+ const status = error.status;
220
+ return {
221
+ code: error.code ?? `HTTP_${status}`,
222
+ status,
223
+ retryable: help?.retryable ?? (status === 429 || status >= 500),
224
+ hint: help == null
225
+ ? error.message
226
+ : help.detail === true
227
+ ? withReason(help.hint, error)
228
+ : help.hint,
229
+ };
230
+ }
231
+ // `fetch` rejects with a TypeError when the request never got an answer:
232
+ // "fetch failed" (Node), "Failed to fetch" (Chrome), "NetworkError when
233
+ // attempting to fetch resource." (Firefox), "Load failed" (Safari).
234
+ if (error instanceof TypeError &&
235
+ /^(fetch failed|Failed to fetch|Load failed|NetworkError when attempting to fetch resource\.?)$/.test(error.message)) {
236
+ return {
237
+ code: 'NETWORK_ERROR',
238
+ status: undefined,
239
+ retryable: true,
240
+ hint: `Paradex could not be reached: ${error.message}`,
241
+ };
242
+ }
243
+ return {
244
+ code: 'UNKNOWN',
245
+ status: undefined,
246
+ retryable: false,
247
+ hint: error instanceof Error ? error.message : String(error),
248
+ };
249
+ }