@paradex/sdk 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,7 +25,7 @@ import * as Paradex from '@paradex/sdk';
25
25
  import { ethers } from 'ethers';
26
26
 
27
27
  // 1. Fetch configuration for your environment
28
- const config = await Paradex.Config.fetch('testnet'); // or 'mainnet'
28
+ const config = await Paradex.Config.fetch('testnet'); // 'prod', 'testnet' or 'nightly'
29
29
 
30
30
  // 2. Connect to user's wallet
31
31
  const provider = new ethers.BrowserProvider(window.ethereum);
@@ -169,7 +169,7 @@ try {
169
169
  Fetch environment-specific configuration:
170
170
 
171
171
  ```typescript
172
- const config = await Paradex.Config.fetch('testnet'); // testnet, mainnet, or custom URL
172
+ const config = await Paradex.Config.fetch('testnet'); // 'prod', 'testnet' or 'nightly'
173
173
  ```
174
174
 
175
175
  ## Common Operations
@@ -326,13 +326,17 @@ Grants are checked before signing. These throw a `SessionGrantError` with a `cod
326
326
  - lifetimes past the server caps, less a 5-minute allowance for the client's clock running ahead (`clockSkewSeconds`; pass 0 when `issuedAt` comes from the server's clock);
327
327
  - a limit that is empty, or set while the server doesn't enforce it (`LIMIT_INVALID`);
328
328
  - builder grants asking for `trade:block` or `account:settings`;
329
- - builder grants without a numeric `maxLoss`. Builder grants need a loss cap, so they're refused until the server enforces `maxLoss`.
329
+ - builder grants whose `maxFeeRate` is 0 or has more than 8 decimal places, or whose builder `expiresAt` is not after `issuedAt`;
330
330
  - labels over 64 characters or outside printable ASCII;
331
331
  - passkey ceilings with scopes the server refuses: a first-party passkey's ceiling may carry `trade`, `trade:rfq` and `account:settings`, a builder passkey's only `trade`. Ceilings with subaccounts are refused until the server enables them; pass `passkeySubaccounts: true` once it does.
332
332
 
333
333
  `POST /v2/sessions` caps every grant at 30 days (7 with `trade:block` or `account:settings`). The `api` session type's 180-day cap is for IP-pinned API sessions, which that endpoint does not open; `SessionConnector.open()` always applies the 30-day cap.
334
334
 
335
- `assertMintWithinCeiling` keeps a mint's `expiresAt` the same 5 minutes inside the ceiling's `maxSessionTtl`; pass `clockSkewSeconds: 0` when `now` comes from the server's clock. For the same reason `validatePasskeyGrant` refuses a ceiling whose `maxSessionTtl` is 300 seconds or less, which would leave no time to mint; it takes the same `clockSkewSeconds` option.
335
+ A passkey opens a session by signing a `SessionMint`, whose WebAuthn challenge is `SessionTypedData.mintChallenge(mint)`. A mint names neither the account nor the passkey: the server finds the passkey by the assertion's credential id, so a page may pass an empty `allowCredentials` and let the user pick any passkey they hold. Its SNIP-12 hash is taken for account `0x0` (`MINT_HASH_ACCOUNT`). A mint may state `CEILING_LIMITS` (every amount `""` and `markets: []`) to take its passkey's ceiling, and `expiresAt: LONGEST_SESSION` (`0`) for the longest session the passkey allows. A stated `expiresAt` later than the passkey's own expiry is accepted, and the session ends when the passkey does; one past the ceiling's `maxSessionTtl` from now is refused.
336
+
337
+ `assertMintWithinCeiling` checks a mint against one `PasskeyGrant`, so it holds only when that grant's passkey signs. With an empty `allowCredentials` the user may pick another passkey, on another account or with another ceiling, and the server checks the mint against that one. A page that pre-checks against a grant, or shows the user limits taken from one, should pin `allowCredentials: [{ type: 'public-key', id: grant.passkey.credentialId }]` (the id decoded from base64url). A page that lets the user pick any passkey must compare the account in the server's response with the one it expected, and revoke the session it just opened if they differ.
338
+
339
+ `assertMintWithinCeiling` keeps a stated `expiresAt` the same 5 minutes inside the ceiling's `maxSessionTtl`; pass `clockSkewSeconds: 0` when `now` comes from the server's clock. For the same reason `validatePasskeyGrant` refuses a ceiling whose `maxSessionTtl` is 300 seconds or less, which would leave no time to mint; it takes the same `clockSkewSeconds` option.
336
340
 
337
341
  Pass `limitCaps` to refuse limits above your own ceilings before the wallet is asked. Caps apply only to enforced limits; a cap on a limit the server doesn't enforce refuses every grant.
338
342
 
@@ -387,6 +391,18 @@ await accounts.placeOrder('0x...', {
387
391
  size: '0.01',
388
392
  price: '60000',
389
393
  });
394
+ // An order attributed to a builder the account approved (for example in a
395
+ // grant's `builder`) pays it builderFeeRate of each fill's notional in USDC.
396
+ // It is signed as BuilderOrder rather than Order.
397
+ await accounts.placeOrder('0x...', {
398
+ market: 'BTC-USD-PERP',
399
+ side: 'BUY',
400
+ type: 'LIMIT',
401
+ size: '0.01',
402
+ price: '60000',
403
+ builder: '0x...',
404
+ builderFeeRate: '0.0005', // 5 bps
405
+ });
390
406
  const unsubscribe = await accounts.subscribe('0x...', 'orders.ALL', (data) =>
391
407
  console.log(data),
392
408
  );
@@ -394,6 +410,37 @@ const unsubscribe = await accounts.subscribe('0x...', 'orders.ALL', (data) =>
394
410
 
395
411
  > `/v2/sessions` is experimental; its request and response shapes may change.
396
412
 
413
+ ### Builder approvals without a session (experimental)
414
+
415
+ An owner who trades with its main key can approve a builder's fee without opening a session. `SessionConnector.approveBuilder()` reads `issuedAt` from the server's clock (`GET /v1/system/time`), since the server refuses an approval issued in its future. It then has the owner sign a `BuilderApproval` with EIP-712 (one wallet prompt) and sends it to `POST /v2/builders/approvals`, which needs no JWT. `builder.maxFeeRate` must be above 0 and have at most 8 decimal places; the server sets the highest rate it accepts. The approval expires `ttlSeconds` after `issuedAt`, at most 180 days (the default). Builder approvals carry no session limits, and Stark-key owners can't sign them. The owner revokes an approval with `DELETE /v2/builders/approvals/{builder_account}`. `issuedAt` is in whole seconds, and the server refuses an approval issued in the same second as the builder's last revoke or approval (including one a session grant made) with `BUILDER_APPROVAL_STALE`, so after either, wait for the next server second.
416
+
417
+ ```ts
418
+ const { approval } = await connector.approveBuilder({
419
+ account: '0x<account>',
420
+ builder: { account: '0x<builder account>', maxFeeRate: '0.0005' },
421
+ ttlSeconds: 30 * 24 * 3600,
422
+ });
423
+ ```
424
+
425
+ ### Builder Codes approvals and stats (experimental)
426
+
427
+ `BuilderCodesClient` reads an account's builder approvals and the public Builder Codes stats.
428
+
429
+ - `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.
431
+ - 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
+ - `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
+ - `fetchLeaderboard(window)` ranks builders by `fees_paid` over one window, `7d` by default. The server answers 400 for a window it does not serve.
434
+ - Stats lag the fills they count. `fetchStats` answers 404 for a builder with no recorded stats, and both stats calls answer 404 while the server has none to serve at all.
435
+
436
+ ```ts
437
+ const builders = new Paradex.BuilderCodesClient({ environment: 'testnet' });
438
+ const approvals = await builders.listApprovals(ownerJwt, {
439
+ includeInactive: true,
440
+ });
441
+ const leaderboard = await builders.fetchLeaderboard('30d');
442
+ ```
443
+
397
444
  ## Best Practices
398
445
 
399
446
  ### 1. Environment Variables
@@ -553,10 +600,13 @@ For a full React application example, see: [paradex-react-example](https://githu
553
600
  | Method | Description | Returns |
554
601
  | ------------------------------------- | ------------------------------------------------ | ----------------- |
555
602
  | `createGrant(params)` | Build a canonical, validated `SessionGrant` | `SessionGrant` |
603
+ | `createBuilderApproval(params)` | Build a canonical, validated `BuilderApproval` | `BuilderApproval` |
604
+ | `buildBuilderApprovalEip712(a, id)` | EIP-712 typed data for a `BuilderApproval` | `Eip712TypedData` |
556
605
  | `buildGrantEip712(grant, chainId)` | EIP-712 typed data for an EVM wallet | `Eip712TypedData` |
557
606
  | `buildGrantSnip12(grant)` | SNIP-12 rev 1 typed data for a Stark owner | `TypedData` |
558
607
  | `buildPasskeyGrantEip712/Snip12(...)` | Typed data for `PasskeyGrant` | typed data |
559
608
  | `buildMintEip712/Snip12(...)` | Typed data for `SessionMint` | typed data |
609
+ | `mintChallenge(mint)` | WebAuthn challenge for a `SessionMint` | `string` |
560
610
  | `hashEip712(typedData)` | EIP-712 digest | `Hex` |
561
611
  | `hashSnip12(typedData, account)` | SNIP-12 message hash | `Hex` |
562
612
  | `validateGrant(grant)` | Check format rules and lifetime caps | `void` (throws) |
@@ -0,0 +1,106 @@
1
+ import { type HttpTransport } from './session-transport.js';
2
+ import { type SessionEnvironment } from './session-typed-data.js';
3
+ /**
4
+ * Builder Codes reads: an owner's builder approvals (list and revoke) and
5
+ * the public builder stats and leaderboard.
6
+ *
7
+ * @experimental The request and response shapes may change.
8
+ */
9
+ export declare const BUILDER_APPROVALS_LIST_PATH = "/v2/builders/approvals";
10
+ /**
11
+ * A stats window. The server answers 400 for a window it does not serve, so
12
+ * any string is passed through.
13
+ */
14
+ export type BuilderStatsWindow = '24h' | '7d' | '30d' | 'all' | (string & Record<never, never>);
15
+ /** A builder as the API names it. */
16
+ export interface BuilderRef {
17
+ readonly account: string;
18
+ /** The builder's registered name; `null` when it has none. */
19
+ readonly name: string | null;
20
+ }
21
+ export type BuilderApprovalStatus = 'active' | 'revoked' | 'expired';
22
+ /** One of an account's builder approvals. */
23
+ export interface BuilderApprovalRecord {
24
+ readonly builder: BuilderRef;
25
+ readonly status: BuilderApprovalStatus;
26
+ /** Highest fee rate the builder may charge, as a decimal fraction. */
27
+ readonly max_fee_rate: string;
28
+ /** Milliseconds. */
29
+ readonly expires_at: number;
30
+ /** When the approval took effect, in milliseconds. */
31
+ readonly approved_at: number;
32
+ /** Milliseconds; 0 while not revoked. */
33
+ readonly revoked_at: number;
34
+ }
35
+ /** A builder's stats over one window. */
36
+ export interface BuilderStats {
37
+ readonly builder: BuilderRef;
38
+ readonly window: BuilderStatsWindow;
39
+ /** Builder fees traders paid, in USDC, before any protocol share. */
40
+ readonly fees_paid: string;
41
+ /** USD notional of the fill sides that paid this builder a fee. */
42
+ readonly volume: string;
43
+ /** Distinct accounts that paid the builder a fee. */
44
+ readonly users: number;
45
+ readonly fills: number;
46
+ /** When the stats were computed, in milliseconds. */
47
+ readonly as_of: number;
48
+ }
49
+ export interface BuilderLeaderboardRow extends BuilderStats {
50
+ /** 1 for the builder paid the most fees. */
51
+ readonly rank: number;
52
+ }
53
+ export interface BuilderCodesClientParams {
54
+ /** Picks the default API host. */
55
+ readonly environment: SessionEnvironment;
56
+ /** API host root, such as `https://api.testnet.paradex.trade`. */
57
+ readonly apiUrl?: string;
58
+ readonly transport?: HttpTransport;
59
+ }
60
+ export interface ListBuilderApprovalsOptions {
61
+ /** Also list revoked and expired approvals, for the approval history. */
62
+ readonly includeInactive?: boolean;
63
+ }
64
+ /**
65
+ * Reads Builder Codes approvals and stats.
66
+ *
67
+ * Listing and revoking approvals needs the account owner's main-key JWT,
68
+ * passed as `token`; a session or subkey token is refused with 403, and
69
+ * listing is also refused for an account Paradex has not enabled sessions
70
+ * for. The stats and leaderboard are public. `fetchStats` answers 404 for a
71
+ * builder with no recorded stats, and both answer 404 while the server has
72
+ * no stats to serve at all.
73
+ *
74
+ * @experimental
75
+ */
76
+ export declare class BuilderCodesClient {
77
+ private readonly apiUrl;
78
+ private readonly transport;
79
+ constructor(params: BuilderCodesClientParams);
80
+ /**
81
+ * `GET /v2/builders/approvals`: the account's live approvals, newest first;
82
+ * with `includeInactive` also its revoked and expired ones.
83
+ */
84
+ listApprovals(token: string, options?: ListBuilderApprovalsOptions): Promise<BuilderApprovalRecord[]>;
85
+ /**
86
+ * `DELETE /v2/builders/approvals/{builder_account}`: new orders naming the
87
+ * builder are refused at once, on the account and its sub-accounts, and
88
+ * the resting orders naming it there are cancelled. A
89
+ * builder with no live approval is a 404 `SessionApiError`.
90
+ */
91
+ revokeApproval(token: string, builderAccount: string): Promise<void>;
92
+ /**
93
+ * `GET /v1/builders/{builder_account}/stats`: one row per window. A window
94
+ * with no paid fill, or with too few paying users, is zeros. Stats lag the
95
+ * fills they count.
96
+ */
97
+ fetchStats(builderAccount: string): Promise<BuilderStats[]>;
98
+ /**
99
+ * `GET /v1/builders/leaderboard`: builders ranked by `fees_paid` over one
100
+ * window, then by volume. The server's default window is `7d`, and it
101
+ * answers 400 for a window it does not serve.
102
+ */
103
+ fetchLeaderboard(window?: BuilderStatsWindow): Promise<BuilderLeaderboardRow[]>;
104
+ private send;
105
+ private results;
106
+ }
@@ -0,0 +1,101 @@
1
+ import { defaultApiUrl, fetchTransport, SessionApiError, } from './session-transport.js';
2
+ import { builderAddress, } from './session-typed-data.js';
3
+ /**
4
+ * Builder Codes reads: an owner's builder approvals (list and revoke) and
5
+ * the public builder stats and leaderboard.
6
+ *
7
+ * @experimental The request and response shapes may change.
8
+ */
9
+ export const BUILDER_APPROVALS_LIST_PATH = '/v2/builders/approvals';
10
+ /**
11
+ * Reads Builder Codes approvals and stats.
12
+ *
13
+ * Listing and revoking approvals needs the account owner's main-key JWT,
14
+ * passed as `token`; a session or subkey token is refused with 403, and
15
+ * listing is also refused for an account Paradex has not enabled sessions
16
+ * for. The stats and leaderboard are public. `fetchStats` answers 404 for a
17
+ * builder with no recorded stats, and both answer 404 while the server has
18
+ * no stats to serve at all.
19
+ *
20
+ * @experimental
21
+ */
22
+ export class BuilderCodesClient {
23
+ constructor(params) {
24
+ this.apiUrl = (params.apiUrl ?? defaultApiUrl(params.environment)).replace(/\/+$/, '');
25
+ this.transport = params.transport ?? fetchTransport;
26
+ }
27
+ /**
28
+ * `GET /v2/builders/approvals`: the account's live approvals, newest first;
29
+ * with `includeInactive` also its revoked and expired ones.
30
+ */
31
+ async listApprovals(token, options = {}) {
32
+ const query = options.includeInactive === true ? '?include_inactive=true' : '';
33
+ return await this.results({
34
+ method: 'GET',
35
+ url: `${this.apiUrl}${BUILDER_APPROVALS_LIST_PATH}${query}`,
36
+ headers: bearer(token),
37
+ });
38
+ }
39
+ /**
40
+ * `DELETE /v2/builders/approvals/{builder_account}`: new orders naming the
41
+ * builder are refused at once, on the account and its sub-accounts, and
42
+ * the resting orders naming it there are cancelled. A
43
+ * builder with no live approval is a 404 `SessionApiError`.
44
+ */
45
+ async revokeApproval(token, builderAccount) {
46
+ await this.send({
47
+ method: 'DELETE',
48
+ url: `${this.apiUrl}${BUILDER_APPROVALS_LIST_PATH}/${builderAddress(builderAccount, 'builderAccount')}`,
49
+ headers: bearer(token),
50
+ });
51
+ }
52
+ /**
53
+ * `GET /v1/builders/{builder_account}/stats`: one row per window. A window
54
+ * with no paid fill, or with too few paying users, is zeros. Stats lag the
55
+ * fills they count.
56
+ */
57
+ async fetchStats(builderAccount) {
58
+ return await this.results({
59
+ method: 'GET',
60
+ url: `${this.apiUrl}/v1/builders/${builderAddress(builderAccount, 'builderAccount')}/stats`,
61
+ headers: {},
62
+ });
63
+ }
64
+ /**
65
+ * `GET /v1/builders/leaderboard`: builders ranked by `fees_paid` over one
66
+ * window, then by volume. The server's default window is `7d`, and it
67
+ * answers 400 for a window it does not serve.
68
+ */
69
+ async fetchLeaderboard(window) {
70
+ const query = window != null ? `?window=${encodeURIComponent(window)}` : '';
71
+ return await this.results({
72
+ method: 'GET',
73
+ url: `${this.apiUrl}/v1/builders/leaderboard${query}`,
74
+ headers: {},
75
+ });
76
+ }
77
+ async send(request) {
78
+ const response = await this.transport(request);
79
+ if (response.status < 200 || response.status >= 300) {
80
+ throw new SessionApiError(response.status, response.body);
81
+ }
82
+ return response.body;
83
+ }
84
+ async results(request) {
85
+ const body = await this.send(request);
86
+ const results = body?.results;
87
+ if (!Array.isArray(results)) {
88
+ throw new SessionApiError(200, {
89
+ error: 'INVALID_RESPONSE',
90
+ message: `${request.method} ${new URL(request.url).pathname} returned no results`,
91
+ });
92
+ }
93
+ return results;
94
+ }
95
+ }
96
+ function bearer(token) {
97
+ if (typeof token !== 'string' || token === '') {
98
+ throw new Error("token must be the account owner's JWT");
99
+ }
100
+ return { Authorization: `Bearer ${token}` };
101
+ }
package/dist/config.d.ts CHANGED
@@ -48,7 +48,8 @@ export interface ParadexConfig {
48
48
  */
49
49
  readonly paradexApiUrl?: string;
50
50
  }
51
- type ParadexEnvironment = 'testnet' | 'prod';
51
+ declare const PARADEX_ENVIRONMENTS: readonly ["prod", "testnet", "nightly"];
52
+ type ParadexEnvironment = (typeof PARADEX_ENVIRONMENTS)[number];
52
53
  /**
53
54
  * Fetches the Paradex config for the given environment.
54
55
  * This is required for account derivation.
package/dist/config.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ETHEREUM_MAINNET_CHAIN_ID, ETHEREUM_TESTNET_CHAIN_ID, STARKNET_MAINNET_CHAIN_ID, STARKNET_TESTNET_CHAIN_ID, } from './constants.js';
2
+ const PARADEX_ENVIRONMENTS = ['prod', 'testnet', 'nightly'];
2
3
  /**
3
4
  * Fetches the Paradex config for the given environment.
4
5
  * This is required for account derivation.
@@ -15,7 +16,7 @@ export async function fetchConfig(environment) {
15
16
  return buildConfig(config, apiUrl);
16
17
  }
17
18
  function assertParadexEnvironment(environment) {
18
- if (environment !== 'testnet' && environment !== 'prod') {
19
+ if (!PARADEX_ENVIRONMENTS.includes(environment)) {
19
20
  throw new Error(`Invalid Paradex environment: ${environment}`);
20
21
  }
21
22
  }
package/dist/index.d.ts CHANGED
@@ -24,6 +24,9 @@ export declare const Signer: {
24
24
  */
25
25
  export declare const SessionTypedData: {
26
26
  createGrant: typeof _SessionTypedData.createSessionGrant;
27
+ createBuilderApproval: typeof _SessionTypedData.createBuilderApproval;
28
+ validateBuilderApproval: typeof _SessionTypedData.validateBuilderApproval;
29
+ buildBuilderApprovalEip712: typeof _SessionTypedData.buildBuilderApprovalEip712;
27
30
  validateGrant: typeof _SessionTypedData.validateSessionGrant;
28
31
  validatePasskeyGrant: typeof _SessionTypedData.validatePasskeyGrant;
29
32
  validateMint: typeof _SessionTypedData.validateSessionMint;
@@ -56,8 +59,10 @@ export declare const Session: {
56
59
  memoryStorage: typeof _SessionKey.memorySessionStorage;
57
60
  indexedDbStorage: typeof _SessionKey.indexedDbSessionStorage;
58
61
  };
59
- export { ALL_LIMITS, DEFAULT_ENFORCED_LIMITS, DEFAULT_LIMIT_CAPS, MAX_GRANT_SUBACCOUNTS, SessionGrantError, UNCAPPED_LIMITS, } from './session-typed-data.js';
62
+ export { ALL_LIMITS, BUILDER_APPROVAL_TTL_MAX, CEILING_LIMITS, DEFAULT_ENFORCED_LIMITS, DEFAULT_LIMIT_CAPS, LONGEST_SESSION, MAX_GRANT_SUBACCOUNTS, MINT_HASH_ACCOUNT, SessionGrantError, UNCAPPED_LIMITS, } from './session-typed-data.js';
60
63
  export { SessionConnector } from './session-connector.js';
64
+ export { BuilderCodesClient } from './builder-codes.js';
65
+ export type { BuilderApprovalRecord, BuilderApprovalStatus, BuilderCodesClientParams, BuilderLeaderboardRow, BuilderRef, BuilderStats, BuilderStatsWindow, ListBuilderApprovalsOptions, } from './builder-codes.js';
61
66
  export { DeterminismGuardError, isContractCode } from './determinism-guard.js';
62
67
  export { SessionAccounts } from './session-accounts.js';
63
68
  export { SessionApiError } from './session-transport.js';
@@ -69,8 +74,8 @@ export type { EthereumSigner } from './ethereum-signer.js';
69
74
  export type { DeterminismGuardErrorCode, DeterminismGuardOptions, DeterminismGuardResult, EthCodeProvider, } from './determinism-guard.js';
70
75
  export type { Hex } from './types.js';
71
76
  export type { Eip712TypedData, Eip712Domain } from './eip712.js';
72
- export type { AssertMintOptions, Builder, Ceiling, CreateSessionGrantParams, LimitCaps, LimitName, LimitOptions, Limits, Passkey, PasskeyGrant, SessionEnvironment, SessionGrant, SessionGrantErrorCode, SessionMint, SessionScope, SessionType, ValidatePasskeyGrantOptions, } from './session-typed-data.js';
73
- export type { EvmSubaccount, OpenSessionParams, Session as RegisteredSession, SessionConnectorParams, SessionOnboardingParams, SessionUtm, } from './session-connector.js';
77
+ export type { AssertMintOptions, Builder, BuilderApproval, Ceiling, CreateBuilderApprovalParams, CreateSessionGrantParams, LimitCaps, LimitName, LimitOptions, Limits, Passkey, PasskeyGrant, SessionEnvironment, SessionGrant, SessionGrantErrorCode, SessionMint, SessionScope, SessionType, ValidatePasskeyGrantOptions, } from './session-typed-data.js';
78
+ export type { ApproveBuilderParams, EvmSubaccount, OpenSessionParams, RegisteredBuilderApproval, Session as RegisteredSession, SessionConnectorParams, SessionOnboardingParams, SessionUtm, } from './session-connector.js';
74
79
  export type { GrantState, GrantStatus, RevokeOptions, SessionAccountsParams, SessionRequest, SubscriptionHandler, } from './session-accounts.js';
75
80
  export type { OrderSide, OrderType, SessionOrder } from './session-auth.js';
76
81
  export type { SessionStorage, StoredSession } from './session-key.js';
package/dist/index.js CHANGED
@@ -25,6 +25,9 @@ export const Signer = {
25
25
  */
26
26
  export const SessionTypedData = {
27
27
  createGrant: _SessionTypedData.createSessionGrant,
28
+ createBuilderApproval: _SessionTypedData.createBuilderApproval,
29
+ validateBuilderApproval: _SessionTypedData.validateBuilderApproval,
30
+ buildBuilderApprovalEip712: _SessionTypedData.buildBuilderApprovalEip712,
28
31
  validateGrant: _SessionTypedData.validateSessionGrant,
29
32
  validatePasskeyGrant: _SessionTypedData.validatePasskeyGrant,
30
33
  validateMint: _SessionTypedData.validateSessionMint,
@@ -57,8 +60,9 @@ export const Session = {
57
60
  memoryStorage: _SessionKey.memorySessionStorage,
58
61
  indexedDbStorage: _SessionKey.indexedDbSessionStorage,
59
62
  };
60
- export { ALL_LIMITS, DEFAULT_ENFORCED_LIMITS, DEFAULT_LIMIT_CAPS, MAX_GRANT_SUBACCOUNTS, SessionGrantError, UNCAPPED_LIMITS, } from './session-typed-data.js';
63
+ export { ALL_LIMITS, BUILDER_APPROVAL_TTL_MAX, CEILING_LIMITS, DEFAULT_ENFORCED_LIMITS, DEFAULT_LIMIT_CAPS, LONGEST_SESSION, MAX_GRANT_SUBACCOUNTS, MINT_HASH_ACCOUNT, SessionGrantError, UNCAPPED_LIMITS, } from './session-typed-data.js';
61
64
  export { SessionConnector } from './session-connector.js';
65
+ export { BuilderCodesClient } from './builder-codes.js';
62
66
  export { DeterminismGuardError, isContractCode } from './determinism-guard.js';
63
67
  export { SessionAccounts } from './session-accounts.js';
64
68
  export { SessionApiError } from './session-transport.js';
@@ -1,3 +1,4 @@
1
+ import BigNumber from 'bignumber.js';
1
2
  import { buildAuthTypedData, buildOrderTypedData, jwtExpiry, SESSION_AUTH_MAX_TTL, sessionAuthPath, } from './session-auth.js';
2
3
  import { SESSIONS_PATH } from './session-connector.js';
3
4
  import { defaultApiUrl, defaultWebSocketFactory, defaultWsUrl, fetchTransport, SessionApiError, } from './session-transport.js';
@@ -169,6 +170,15 @@ export class SessionAccounts {
169
170
  signature_timestamp: timestamp,
170
171
  ...(order.clientId != null ? { client_id: order.clientId } : {}),
171
172
  ...(order.reduceOnly === true ? { flags: ['REDUCE_ONLY'] } : {}),
173
+ ...(order.builder != null
174
+ ? {
175
+ builder: order.builder,
176
+ // Canonical spelling ("0.000500000" -> "0.0005"): the server
177
+ // refuses more than 8 decimal places, and the signature covers
178
+ // the scaled value, so either spelling signs the same.
179
+ builder_fee_rate: new BigNumber(order.builderFeeRate ?? '').toFixed(),
180
+ }
181
+ : {}),
172
182
  },
173
183
  });
174
184
  }
@@ -23,9 +23,36 @@ 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
+ */
29
56
  export declare function buildOrderTypedData(paradexChain: string, order: SessionOrder, signatureTimestampMs: number): Starknet.TypedData;
30
57
  /** Reads `exp` (seconds) from a JWT without verifying it. */
31
58
  export declare function jwtExpiry(token: string): number | undefined;
@@ -1,5 +1,6 @@
1
1
  import BigNumber from 'bignumber.js';
2
2
  import * as Starknet from 'starknet';
3
+ import { builderAddress } from './session-typed-data.js';
3
4
  /**
4
5
  * Typed data a session key signs: the `/auth` request that mints a JWT and
5
6
  * the orders it places. Both are today's SNIP-12 (revision 0) "Paradex"
@@ -69,34 +70,73 @@ export function toChainQuantums(value, field) {
69
70
  }
70
71
  return scaled.toFixed(0);
71
72
  }
73
+ const ORDER_TYPES = [
74
+ { name: 'timestamp', type: 'felt' },
75
+ { name: 'market', type: 'felt' },
76
+ { name: 'side', type: 'felt' },
77
+ { name: 'orderType', type: 'felt' },
78
+ { name: 'size', type: 'felt' },
79
+ { name: 'price', type: 'felt' },
80
+ ];
81
+ /**
82
+ * The order's builder and its fee rate at 8 decimals (`"0.0005"` →
83
+ * `"50000"`), or `undefined` for an order naming none.
84
+ */
85
+ export function orderBuilder(order) {
86
+ const { builder, builderFeeRate } = order;
87
+ if (builder == null && builderFeeRate == null)
88
+ return undefined;
89
+ if (builder == null || builderFeeRate == null) {
90
+ throw new Error('builder and builderFeeRate must be set together');
91
+ }
92
+ builderAddress(builder);
93
+ const rate = toChainQuantums(builderFeeRate, 'builderFeeRate');
94
+ if (rate === '0')
95
+ throw new Error('builderFeeRate must be above 0');
96
+ return { builder, builderFeeRate: rate };
97
+ }
98
+ /**
99
+ * The SNIP-12 (revision 0) typed data `order` is signed under. An order
100
+ * naming a builder signs as `BuilderOrder`: the `Order` fields, in order,
101
+ * then `builder` and `builderFeeRate` at 8 decimals. Its distinct type hash
102
+ * keeps either signature from being replayed as the other. An order without
103
+ * a builder keeps the `Order` hash.
104
+ */
72
105
  export function buildOrderTypedData(paradexChain, order, signatureTimestampMs) {
73
106
  if (order.type === 'LIMIT' && order.price == null) {
74
107
  throw new Error('LIMIT orders need a price');
75
108
  }
109
+ const message = {
110
+ timestamp: String(signatureTimestampMs),
111
+ market: Starknet.shortString.encodeShortString(order.market),
112
+ side: order.side === 'BUY' ? '1' : '2',
113
+ orderType: Starknet.shortString.encodeShortString(order.type),
114
+ size: toChainQuantums(order.size, 'size'),
115
+ price: order.type === 'MARKET'
116
+ ? '0'
117
+ : toChainQuantums(order.price ?? '', 'price'),
118
+ };
119
+ const builder = orderBuilder(order);
120
+ if (builder == null) {
121
+ return {
122
+ domain: paradexDomain(paradexChain),
123
+ primaryType: 'Order',
124
+ types: { StarkNetDomain: REQUEST_DOMAIN_TYPES, Order: ORDER_TYPES },
125
+ message,
126
+ };
127
+ }
76
128
  return {
77
129
  domain: paradexDomain(paradexChain),
78
- primaryType: 'Order',
130
+ primaryType: 'BuilderOrder',
79
131
  types: {
80
132
  StarkNetDomain: REQUEST_DOMAIN_TYPES,
81
- Order: [
82
- { name: 'timestamp', type: 'felt' },
83
- { name: 'market', type: 'felt' },
84
- { name: 'side', type: 'felt' },
85
- { name: 'orderType', type: 'felt' },
86
- { name: 'size', type: 'felt' },
87
- { name: 'price', type: 'felt' },
133
+ BuilderOrder: [
134
+ ...ORDER_TYPES,
135
+ { name: 'builder', type: 'felt' },
136
+ { name: 'builderFeeRate', type: 'felt' },
88
137
  ],
89
138
  },
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
- },
139
+ message: { ...message, ...builder },
100
140
  };
101
141
  }
102
142
  /** 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