@paradex/sdk 0.10.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
@@ -326,7 +326,7 @@ 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
 
@@ -391,6 +391,18 @@ await accounts.placeOrder('0x...', {
391
391
  size: '0.01',
392
392
  price: '60000',
393
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
+ });
394
406
  const unsubscribe = await accounts.subscribe('0x...', 'orders.ALL', (data) =>
395
407
  console.log(data),
396
408
  );
@@ -398,6 +410,37 @@ const unsubscribe = await accounts.subscribe('0x...', 'orders.ALL', (data) =>
398
410
 
399
411
  > `/v2/sessions` is experimental; its request and response shapes may change.
400
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
+
401
444
  ## Best Practices
402
445
 
403
446
  ### 1. Environment Variables
@@ -557,6 +600,8 @@ For a full React application example, see: [paradex-react-example](https://githu
557
600
  | Method | Description | Returns |
558
601
  | ------------------------------------- | ------------------------------------------------ | ----------------- |
559
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` |
560
605
  | `buildGrantEip712(grant, chainId)` | EIP-712 typed data for an EVM wallet | `Eip712TypedData` |
561
606
  | `buildGrantSnip12(grant)` | SNIP-12 rev 1 typed data for a Stark owner | `TypedData` |
562
607
  | `buildPasskeyGrantEip712/Snip12(...)` | Typed data for `PasskeyGrant` | typed data |
@@ -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/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, CEILING_LIMITS, DEFAULT_ENFORCED_LIMITS, DEFAULT_LIMIT_CAPS, LONGEST_SESSION, MAX_GRANT_SUBACCOUNTS, MINT_HASH_ACCOUNT, 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, CEILING_LIMITS, DEFAULT_ENFORCED_LIMITS, DEFAULT_LIMIT_CAPS, LONGEST_SESSION, MAX_GRANT_SUBACCOUNTS, MINT_HASH_ACCOUNT, 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
@@ -2,9 +2,11 @@ import { hashTypedData } from './eip712.js';
2
2
  import { assertRecordVersion, memorySessionStorage, SessionKey, } from './session-key.js';
3
3
  import { assertEoaSignature, } from './session-owner-signer.js';
4
4
  import { defaultApiUrl, fetchTransport, SessionApiError, } from './session-transport.js';
5
- import { assertGrantActive, buildSessionGrantEip712, canonicalFelt, createSessionGrant, grantAccounts, nowSeconds, SessionGrantError, } from './session-typed-data.js';
5
+ import { assertGrantActive, buildBuilderApprovalEip712, buildSessionGrantEip712, canonicalFelt, createBuilderApproval, createSessionGrant, grantAccounts, nowSeconds, SessionGrantError, } from './session-typed-data.js';
6
6
  export const SESSIONS_PATH = '/v2/sessions';
7
7
  export const EVM_SUBACCOUNTS_PATH = '/v2/onboarding/subaccounts';
8
+ export const BUILDER_APPROVALS_PATH = '/v2/builders/approvals';
9
+ export const SYSTEM_TIME_PATH = '/v1/system/time';
8
10
  /** Whether `open()` finished registering this record. */
9
11
  function isRegistered(record) {
10
12
  return (record.grant != null &&
@@ -201,6 +203,75 @@ export class SessionConnector {
201
203
  throw error;
202
204
  }
203
205
  }
206
+ /**
207
+ * Has the owner approve a builder's fee without opening a session (one
208
+ * wallet prompt) and registers the approval with
209
+ * `POST /v2/builders/approvals`, which needs no JWT. The approval covers
210
+ * the account and any `subaccounts` it lists until `builder.expiresAt`.
211
+ * The owner revokes it with `DELETE /v2/builders/approvals/{builder_account}`.
212
+ *
213
+ * `issuedAt` is the server's time in whole seconds, and the server refuses
214
+ * an approval issued in the same second as the builder's last revoke or
215
+ * approval (including one a session grant made) with
216
+ * `BUILDER_APPROVAL_STALE`. So after either, wait for the next server
217
+ * second, or the owner signs an approval that is refused.
218
+ *
219
+ * @experimental
220
+ */
221
+ async approveBuilder(params) {
222
+ const approval = createBuilderApproval({
223
+ ...params,
224
+ paradexChain: this.paradexChain,
225
+ environment: this.environment,
226
+ issuedAt: await this.serverTime(),
227
+ });
228
+ await this.assertSubaccountsOwned(approval);
229
+ const signatureChainId = await this.owner.getChainId();
230
+ const typedData = buildBuilderApprovalEip712(approval, signatureChainId);
231
+ const ownerSignature = assertEoaSignature(await this.owner.signTypedData({
232
+ typedData,
233
+ digest: hashTypedData(typedData),
234
+ }));
235
+ const response = await this.transport({
236
+ method: 'POST',
237
+ url: `${this.apiUrl}${BUILDER_APPROVALS_PATH}`,
238
+ headers: { 'Content-Type': 'application/json' },
239
+ body: JSON.stringify({
240
+ approval,
241
+ signature: ownerSignature,
242
+ signature_type: 'eip712',
243
+ signature_chain_id: signatureChainId,
244
+ }),
245
+ });
246
+ if (response.status < 200 || response.status >= 300) {
247
+ throw new SessionApiError(response.status, response.body);
248
+ }
249
+ return {
250
+ approval,
251
+ ownerSignature,
252
+ signatureChainId,
253
+ response: response.body,
254
+ };
255
+ }
256
+ /** The server's clock in whole seconds, from `GET /v1/system/time`. */
257
+ async serverTime() {
258
+ const response = await this.transport({
259
+ method: 'GET',
260
+ url: `${this.apiUrl}${SYSTEM_TIME_PATH}`,
261
+ headers: {},
262
+ });
263
+ if (response.status < 200 || response.status >= 300) {
264
+ throw new SessionApiError(response.status, response.body);
265
+ }
266
+ const ms = Number(response.body?.server_time);
267
+ if (!Number.isSafeInteger(ms) || ms <= 0) {
268
+ throw new SessionApiError(response.status, {
269
+ error: 'INVALID_RESPONSE',
270
+ message: `GET ${SYSTEM_TIME_PATH} returned no server_time`,
271
+ });
272
+ }
273
+ return Math.floor(ms / 1000);
274
+ }
204
275
  /**
205
276
  * Restores registered sessions from storage for this environment. Expired
206
277
  * sessions and sessions that never registered are deleted; records that
@@ -33,7 +33,9 @@ export declare const SESSION_TTL: {
33
33
  export declare const MAX_PASSKEY_CONCURRENT_SESSIONS = 5;
34
34
  /** A grant, mint or passkey ceiling lists at most this many subaccounts. */
35
35
  export declare const MAX_GRANT_SUBACCOUNTS = 32;
36
- export type SessionGrantErrorCode = 'INVALID_FIELD' | 'UNKNOWN_SCOPE' | 'RESERVED_SCOPE' | 'TTL_EXCEEDED' | 'BUILDER_LIMITS_REQUIRED' | 'BUILDER_REQUIRES_EIP712' | 'GRANT_EXPIRED' | 'GRANT_REVOKED' | 'ENVIRONMENT_MISMATCH' | 'ACCOUNT_NOT_IN_GRANT' | 'ACCOUNT_NOT_ELIGIBLE' | 'EXCEEDS_CEILING' | 'SCOPE_NOT_ALLOWED' | 'LIMIT_INVALID';
36
+ export type SessionGrantErrorCode = 'INVALID_FIELD' | 'UNKNOWN_SCOPE' | 'RESERVED_SCOPE' | 'TTL_EXCEEDED'
37
+ /** @deprecated No longer thrown: builder grants follow the normal limit rules. */
38
+ | 'BUILDER_LIMITS_REQUIRED' | 'BUILDER_REQUIRES_EIP712' | 'GRANT_EXPIRED' | 'GRANT_REVOKED' | 'ENVIRONMENT_MISMATCH' | 'ACCOUNT_NOT_IN_GRANT' | 'ACCOUNT_NOT_ELIGIBLE' | 'EXCEEDS_CEILING' | 'SCOPE_NOT_ALLOWED' | 'LIMIT_INVALID';
37
39
  export declare class SessionGrantError extends Error {
38
40
  readonly code: SessionGrantErrorCode;
39
41
  constructor(code: SessionGrantErrorCode, message: string);
@@ -141,6 +143,24 @@ export interface PasskeyGrant {
141
143
  readonly issuedAt: number;
142
144
  readonly expiresAt: number;
143
145
  }
146
+ /**
147
+ * An EVM owner's approval of a builder's fee, outside any session grant.
148
+ * Signed with EIP-712 only and registered with
149
+ * `POST /v2/builders/approvals`.
150
+ *
151
+ * @experimental
152
+ */
153
+ export interface BuilderApproval {
154
+ readonly paradexChain: string;
155
+ readonly environment: SessionEnvironment;
156
+ readonly account: string;
157
+ /** `expiresAt` is required here: there is no session to follow. */
158
+ readonly builder: Builder;
159
+ readonly subaccounts: readonly string[];
160
+ readonly nonce: string;
161
+ /** Seconds, by the server's clock: the server refuses one in its future. */
162
+ readonly issuedAt: number;
163
+ }
144
164
  /**
145
165
  * What a passkey signs to open one session; its SNIP-12 hash is the WebAuthn
146
166
  * challenge ({@link sessionMintChallenge}).
@@ -184,11 +204,19 @@ export declare const CEILING_LIMITS: Limits;
184
204
  /** Whether `limits` are {@link CEILING_LIMITS}: no limit stated at all. */
185
205
  export declare function isCeilingLimits(limits: Limits): boolean;
186
206
  export declare const SESSION_GRANT_EIP712_TYPES: Eip712Types;
207
+ export declare const BUILDER_APPROVAL_EIP712_TYPES: Eip712Types;
187
208
  export declare const PASSKEY_GRANT_EIP712_TYPES: Eip712Types;
188
209
  export declare const SESSION_MINT_EIP712_TYPES: Eip712Types;
189
210
  export declare const SESSION_GRANT_SNIP12_TYPES: Starknet.TypedData['types'];
190
211
  export declare const PASSKEY_GRANT_SNIP12_TYPES: Starknet.TypedData['types'];
191
212
  export declare const SESSION_MINT_SNIP12_TYPES: Starknet.TypedData['types'];
213
+ /**
214
+ * A builder account in canonical `0x` form, refusing anything but a
215
+ * non-zero felt address. Orders and the Builder Codes calls share it.
216
+ *
217
+ * @internal
218
+ */
219
+ export declare function builderAddress(value: string, name?: string): string;
192
220
  /** Whether a ceiling market entry covers a mint's market entry. */
193
221
  export declare function marketCovers(pattern: string, market: string): boolean;
194
222
  /**
@@ -205,10 +233,11 @@ export declare function validateScopes(scopes: readonly string[], field?: string
205
233
  * non-empty list, or `["*"]` alone. A limit the server does not enforce
206
234
  * must be `"none"` (`markets`: `["*"]`).
207
235
  *
208
- * @param builderGrant builder grants must cap `maxLoss` with a number, so
209
- * they are refused while the server does not enforce `maxLoss`.
236
+ * Builder grants and builder passkeys follow the same rules as any other grant.
237
+ *
238
+ * @param _builderGrant ignored; kept so existing callers still compile.
210
239
  */
211
- export declare function validateLimits(limits: Limits, builderGrant: boolean, field?: string, options?: LimitOptions): void;
240
+ export declare function validateLimits(limits: Limits, _builderGrant: boolean, field?: string, options?: LimitOptions): void;
212
241
  export type SessionType = 'browser' | 'api';
213
242
  /**
214
243
  * Longest lifetime a grant with these scopes can request. The server measures
@@ -240,6 +269,18 @@ export interface ValidateSessionGrantOptions extends LimitOptions {
240
269
  * before the owner is asked to sign.
241
270
  */
242
271
  export declare function validateSessionGrant(grant: SessionGrant, options?: ValidateSessionGrantOptions): void;
272
+ /** Longest a builder approval may live after its `issuedAt`. */
273
+ export declare const BUILDER_APPROVAL_TTL_MAX: number;
274
+ /**
275
+ * Checks a builder approval against the server's rules: a builder other than
276
+ * the account, a `maxFeeRate` above 0 with at most 8 decimal places, and a
277
+ * required `expiresAt` at most
278
+ * {@link BUILDER_APPROVAL_TTL_MAX} after `issuedAt`. Throws a
279
+ * {@link SessionGrantError}.
280
+ *
281
+ * @experimental
282
+ */
283
+ export declare function validateBuilderApproval(approval: BuilderApproval): void;
243
284
  export interface ValidatePasskeyGrantOptions extends LimitOptions {
244
285
  /**
245
286
  * Whether the server accepts subaccounts in a passkey ceiling. Defaults to
@@ -282,9 +323,8 @@ export interface AssertMintOptions extends LimitOptions {
282
323
  * unless it allows `["*"]`. Unenforced limits are `"none"` on the mint and
283
324
  * skipped, so passkeys registered with numeric limits keep working. A mint
284
325
  * stating {@link CEILING_LIMITS} takes the ceiling's and fits by definition.
285
- * A builder passkey's mints are checked like any other: the server checks
286
- * `maxLoss` when the passkey registers, not on its mints. Subaccounts must
287
- * not list the passkey's account.
326
+ * A builder passkey's mints are checked like any other. Subaccounts must not
327
+ * list the passkey's account.
288
328
  *
289
329
  * The check holds only when `grant`'s passkey signs. With an empty
290
330
  * `allowCredentials` the user may pick another passkey, on another account
@@ -347,6 +387,32 @@ export declare function nowSeconds(): number;
347
387
  * @experimental
348
388
  */
349
389
  export declare function createSessionGrant(params: CreateSessionGrantParams): SessionGrant;
390
+ export interface CreateBuilderApprovalParams {
391
+ readonly paradexChain: string;
392
+ readonly environment: SessionEnvironment;
393
+ readonly account: string;
394
+ /**
395
+ * The builder and its fee cap. `expiresAt` (seconds) defaults to
396
+ * `issuedAt + ttlSeconds`, as on a grant's builder.
397
+ */
398
+ readonly builder: {
399
+ readonly account: string;
400
+ readonly maxFeeRate: string;
401
+ readonly expiresAt?: number;
402
+ };
403
+ /** Seconds, from the server's clock (`GET /v1/system/time`). */
404
+ readonly issuedAt: number;
405
+ /** Defaults to {@link BUILDER_APPROVAL_TTL_MAX}. */
406
+ readonly ttlSeconds?: number;
407
+ readonly subaccounts?: readonly string[];
408
+ readonly nonce?: string;
409
+ }
410
+ /**
411
+ * Builds a canonical, validated {@link BuilderApproval}.
412
+ *
413
+ * @experimental
414
+ */
415
+ export declare function createBuilderApproval(params: CreateBuilderApprovalParams): BuilderApproval;
350
416
  /** Every account a grant reaches: the anchor first, then its sub-accounts. */
351
417
  export declare function grantAccounts(grant: Pick<SessionGrant, 'account' | 'subaccounts'>): readonly string[];
352
418
  /**
@@ -376,6 +442,14 @@ export declare function buildPasskeyGrantSnip12(grant: PasskeyGrant, options?: V
376
442
  export declare function buildSessionMintEip712(mint: SessionMint, signatureChainId: number | string | bigint, options?: LimitOptions): Eip712TypedData;
377
443
  /** @experimental */
378
444
  export declare function buildSessionMintSnip12(mint: SessionMint, options?: LimitOptions): Starknet.TypedData;
445
+ /**
446
+ * EIP-712 `BuilderApproval`, signed by the account's EVM owner on the
447
+ * wallet's current chain. There is no SNIP-12 form: the server accepts
448
+ * builder approvals from EVM owners only.
449
+ *
450
+ * @experimental
451
+ */
452
+ export declare function buildBuilderApprovalEip712(approval: BuilderApproval, signatureChainId: number | string | bigint): Eip712TypedData;
379
453
  /** EIP-712 digest (`0x1901 ‖ domain ‖ struct`) as 0x-prefixed 32-byte hex. */
380
454
  export declare function hashEip712(typedData: Eip712TypedData): Hex;
381
455
  /**
@@ -132,6 +132,11 @@ const EIP712_LIMITS = [
132
132
  { name: 'maxLeverage', type: 'string' },
133
133
  { name: 'markets', type: 'string[]' },
134
134
  ];
135
+ const EIP712_BUILDER = [
136
+ { name: 'account', type: 'string' },
137
+ { name: 'maxFeeRate', type: 'string' },
138
+ { name: 'expiresAt', type: 'uint64' },
139
+ ];
135
140
  export const SESSION_GRANT_EIP712_TYPES = {
136
141
  SessionGrant: [
137
142
  { name: 'paradexChain', type: 'string' },
@@ -148,11 +153,19 @@ export const SESSION_GRANT_EIP712_TYPES = {
148
153
  { name: 'expiresAt', type: 'uint64' },
149
154
  ],
150
155
  Limits: EIP712_LIMITS,
151
- Builder: [
156
+ Builder: EIP712_BUILDER,
157
+ };
158
+ export const BUILDER_APPROVAL_EIP712_TYPES = {
159
+ BuilderApproval: [
160
+ { name: 'paradexChain', type: 'string' },
161
+ { name: 'environment', type: 'string' },
152
162
  { name: 'account', type: 'string' },
153
- { name: 'maxFeeRate', type: 'string' },
154
- { name: 'expiresAt', type: 'uint64' },
163
+ { name: 'builder', type: 'Builder' },
164
+ { name: 'subaccounts', type: 'string[]' },
165
+ { name: 'nonce', type: 'string' },
166
+ { name: 'issuedAt', type: 'uint64' },
155
167
  ],
168
+ Builder: EIP712_BUILDER,
156
169
  };
157
170
  export const PASSKEY_GRANT_EIP712_TYPES = {
158
171
  PasskeyGrant: [
@@ -282,6 +295,21 @@ export const SESSION_MINT_SNIP12_TYPES = {
282
295
  // ---------------------------------------------------------------------------
283
296
  /** Starknet field prime. */
284
297
  const FELT_PRIME = 2n ** 251n + 17n * 2n ** 192n + 1n;
298
+ /**
299
+ * A builder account in canonical `0x` form, refusing anything but a
300
+ * non-zero felt address. Orders and the Builder Codes calls share it.
301
+ *
302
+ * @internal
303
+ */
304
+ export function builderAddress(value, name = 'builder') {
305
+ if (typeof value !== 'string' ||
306
+ !/^0x[0-9a-fA-F]{1,64}$/.test(value) ||
307
+ BigInt(value) === 0n ||
308
+ BigInt(value) >= FELT_PRIME) {
309
+ throw new Error(`${name} must be a non-zero 0x-prefixed hex address`);
310
+ }
311
+ return `0x${BigInt(value).toString(16)}`;
312
+ }
285
313
  /** Upper bound (exclusive) of a Starknet contract address. */
286
314
  const ADDRESS_BOUND = 2n ** 251n - 256n;
287
315
  const NONCE_BOUND = 2n ** 128n;
@@ -449,18 +477,16 @@ function isNoCap(value) {
449
477
  * non-empty list, or `["*"]` alone. A limit the server does not enforce
450
478
  * must be `"none"` (`markets`: `["*"]`).
451
479
  *
452
- * @param builderGrant builder grants must cap `maxLoss` with a number, so
453
- * they are refused while the server does not enforce `maxLoss`.
480
+ * Builder grants and builder passkeys follow the same rules as any other grant.
481
+ *
482
+ * @param _builderGrant ignored; kept so existing callers still compile.
454
483
  */
455
- export function validateLimits(limits, builderGrant, field = 'limits', options = {}) {
484
+ export function validateLimits(limits, _builderGrant, field = 'limits', options = {}) {
456
485
  const caps = options.limitCaps ?? DEFAULT_LIMIT_CAPS;
457
486
  const enforced = options.enforcedLimits ?? DEFAULT_ENFORCED_LIMITS;
458
487
  if (limits == null || typeof limits !== 'object') {
459
488
  throw invalid(field, 'is required');
460
489
  }
461
- if (builderGrant && !enforced.includes('maxLoss')) {
462
- throw new SessionGrantError('BUILDER_LIMITS_REQUIRED', `${field}.maxLoss: builder grants need a loss cap, which the server does not enforce yet`);
463
- }
464
490
  for (const key of LIMIT_AMOUNTS) {
465
491
  const value = limits[key];
466
492
  if (value === '' || value == null) {
@@ -468,12 +494,7 @@ export function validateLimits(limits, builderGrant, field = 'limits', options =
468
494
  }
469
495
  if (typeof value !== 'string')
470
496
  throw invalid(`${field}.${key}`, 'must be a string');
471
- if (isNoCap(value)) {
472
- if (key === 'maxLoss' && builderGrant) {
473
- throw new SessionGrantError('BUILDER_LIMITS_REQUIRED', `${field}.maxLoss: builder grants must cap losses with a number`);
474
- }
475
- }
476
- else {
497
+ if (!isNoCap(value)) {
477
498
  requireDecimal(`${field}.${key}`, value, false);
478
499
  if (new BigNumber(value).isZero()) {
479
500
  throw invalid(`${field}.${key}`, 'must be positive');
@@ -587,11 +608,65 @@ export function validateSessionGrant(grant, options = {}) {
587
608
  if (hasBuilder && builder.account === grant.account) {
588
609
  throw invalid('builder.account', 'must not be the granting account');
589
610
  }
611
+ if (hasBuilder)
612
+ requireBuilderFeeRate(builder.maxFeeRate);
590
613
  if (builder.expiresAt > grant.expiresAt) {
591
614
  throw invalid('builder.expiresAt', 'must not outlive the session');
592
615
  }
616
+ if (builder.expiresAt !== 0 && builder.expiresAt <= grant.issuedAt) {
617
+ throw invalid('builder.expiresAt', 'must be after issuedAt');
618
+ }
593
619
  validateLimits(grant.limits, hasBuilder, 'limits', options);
594
620
  }
621
+ /** Longest a builder approval may live after its `issuedAt`. */
622
+ export const BUILDER_APPROVAL_TTL_MAX = 180 * DAY;
623
+ /** Most decimal places a builder's `maxFeeRate` may have. The server sets the highest rate it accepts. */
624
+ const BUILDER_FEE_RATE_PLACES = 8;
625
+ /**
626
+ * A builder's fee ceiling, as the server checks it on grants and approvals:
627
+ * above 0 and at most 8 decimal places. The server refuses a rate above its
628
+ * configured cap.
629
+ */
630
+ function requireBuilderFeeRate(maxFeeRate) {
631
+ requireDecimal('builder.maxFeeRate', maxFeeRate, false);
632
+ const rate = new BigNumber(maxFeeRate);
633
+ if (rate.isZero()) {
634
+ throw invalid('builder.maxFeeRate', 'must be above 0');
635
+ }
636
+ if ((rate.decimalPlaces() ?? 0) > BUILDER_FEE_RATE_PLACES) {
637
+ throw invalid('builder.maxFeeRate', `must have at most ${BUILDER_FEE_RATE_PLACES} decimal places`);
638
+ }
639
+ }
640
+ /**
641
+ * Checks a builder approval against the server's rules: a builder other than
642
+ * the account, a `maxFeeRate` above 0 with at most 8 decimal places, and a
643
+ * required `expiresAt` at most
644
+ * {@link BUILDER_APPROVAL_TTL_MAX} after `issuedAt`. Throws a
645
+ * {@link SessionGrantError}.
646
+ *
647
+ * @experimental
648
+ */
649
+ export function validateBuilderApproval(approval) {
650
+ validateAccountBinding(approval);
651
+ requireUniqueAddresses('subaccounts', approval.subaccounts, approval.account);
652
+ requireTimestamp('issuedAt', approval.issuedAt);
653
+ const builder = approval.builder;
654
+ if (builder == null || typeof builder !== 'object') {
655
+ throw invalid('builder', 'is required');
656
+ }
657
+ requireAddress('builder.account', builder.account);
658
+ if (builder.account === approval.account) {
659
+ throw invalid('builder.account', 'must not be the approving account');
660
+ }
661
+ requireBuilderFeeRate(builder.maxFeeRate);
662
+ requireTimestamp('builder.expiresAt', builder.expiresAt);
663
+ if (builder.expiresAt <= approval.issuedAt) {
664
+ throw invalid('builder.expiresAt', 'must be after issuedAt');
665
+ }
666
+ if (builder.expiresAt - approval.issuedAt > BUILDER_APPROVAL_TTL_MAX) {
667
+ throw new SessionGrantError('TTL_EXCEEDED', `builder.expiresAt: an approval lives at most ${BUILDER_APPROVAL_TTL_MAX}s after issuedAt`);
668
+ }
669
+ }
595
670
  export function validatePasskeyGrant(grant, options = {}) {
596
671
  validateAccountBinding(grant);
597
672
  requireAddress('builderAccount', grant.builderAccount, false);
@@ -688,9 +763,8 @@ function exceeds(message) {
688
763
  * unless it allows `["*"]`. Unenforced limits are `"none"` on the mint and
689
764
  * skipped, so passkeys registered with numeric limits keep working. A mint
690
765
  * stating {@link CEILING_LIMITS} takes the ceiling's and fits by definition.
691
- * A builder passkey's mints are checked like any other: the server checks
692
- * `maxLoss` when the passkey registers, not on its mints. Subaccounts must
693
- * not list the passkey's account.
766
+ * A builder passkey's mints are checked like any other. Subaccounts must not
767
+ * list the passkey's account.
694
768
  *
695
769
  * The check holds only when `grant`'s passkey signs. With an empty
696
770
  * `allowCredentials` the user may pick another passkey, on another account
@@ -846,6 +920,31 @@ export function createSessionGrant(params) {
846
920
  });
847
921
  return grant;
848
922
  }
923
+ /**
924
+ * Builds a canonical, validated {@link BuilderApproval}.
925
+ *
926
+ * @experimental
927
+ */
928
+ export function createBuilderApproval(params) {
929
+ const approval = {
930
+ paradexChain: params.paradexChain,
931
+ environment: params.environment,
932
+ account: canonicalFelt(params.account),
933
+ builder: {
934
+ account: canonicalFelt(params.builder.account),
935
+ maxFeeRate: params.builder.maxFeeRate,
936
+ expiresAt: params.builder.expiresAt ??
937
+ params.issuedAt + (params.ttlSeconds ?? BUILDER_APPROVAL_TTL_MAX),
938
+ },
939
+ subaccounts: (params.subaccounts ?? []).map((a) => canonicalFelt(a)),
940
+ nonce: params.nonce != null
941
+ ? canonicalFelt(params.nonce)
942
+ : generateSessionNonce(),
943
+ issuedAt: params.issuedAt,
944
+ };
945
+ validateBuilderApproval(approval);
946
+ return approval;
947
+ }
849
948
  /** Every account a grant reaches: the anchor first, then its sub-accounts. */
850
949
  export function grantAccounts(grant) {
851
950
  return [grant.account, ...grant.subaccounts];
@@ -971,6 +1070,17 @@ export function buildSessionMintSnip12(mint, options = {}) {
971
1070
  validateSessionMint(mint, options);
972
1071
  return snip12('SessionMint', SESSION_MINT_SNIP12_TYPES, mint, mint.paradexChain);
973
1072
  }
1073
+ /**
1074
+ * EIP-712 `BuilderApproval`, signed by the account's EVM owner on the
1075
+ * wallet's current chain. There is no SNIP-12 form: the server accepts
1076
+ * builder approvals from EVM owners only.
1077
+ *
1078
+ * @experimental
1079
+ */
1080
+ export function buildBuilderApprovalEip712(approval, signatureChainId) {
1081
+ validateBuilderApproval(approval);
1082
+ return eip712('BuilderApproval', BUILDER_APPROVAL_EIP712_TYPES, approval, signatureChainId);
1083
+ }
974
1084
  /** EIP-712 digest (`0x1901 ‖ domain ‖ struct`) as 0x-prefixed 32-byte hex. */
975
1085
  export function hashEip712(typedData) {
976
1086
  return hashEip712TypedData(typedData);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@paradex/sdk",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "JavaScript SDK for Paradex",
5
5
  "main": "dist/index.js",
6
6
  "files": [