@paradex/sdk 0.10.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,527 @@
1
+ import BigNumber from 'bignumber.js';
2
+ import { BuilderAppError } from './api-errors.js';
3
+ import { BuilderCodesClient, } from './builder-codes.js';
4
+ import { fetchConfig } from './config.js';
5
+ import { EvmOwnerClient, starkgateWithdrawCall } from './evm-owner-client.js';
6
+ import { OwnerAuth } from './owner-auth.js';
7
+ import { RfqClient } from './rfq.js';
8
+ import { fetchGrantState, SessionAccounts, } from './session-accounts.js';
9
+ import { toChainQuantums } from './session-auth.js';
10
+ import { SessionConnector } from './session-connector.js';
11
+ import { indexedDbSessionStorage, memorySessionStorage, } from './session-key.js';
12
+ import { defaultApiUrl, fetchTransport, SessionApiError, } from './session-transport.js';
13
+ import { builderAddress, canonicalFelt, nowSeconds, SessionGrantError, } from './session-typed-data.js';
14
+ import { fillsQueryParams, queryString, toPage, } from './trading.js';
15
+ import { walletEvmOwnerSigner, walletOwnerSigner, } from './wallet.js';
16
+ /** The Paradex app host each environment's SIWE messages must name. */
17
+ export const SIWE_DOMAINS = {
18
+ prod: 'app.paradex.trade',
19
+ testnet: 'app.testnet.paradex.trade',
20
+ nightly: 'app.nightly.paradex.trade',
21
+ };
22
+ const APPROVALS_LOGIN = 'approvals';
23
+ const RFQ_LOGIN = 'rfq';
24
+ /**
25
+ * The builder fee a fill of `size` at `price` pays, in USDC, as a decimal
26
+ * string: `size × price × feeRate`. It is what the fill's `builder_fee` will
27
+ * read for a perpetual filled at that price. For display before an order is
28
+ * placed; the fill itself is the record.
29
+ */
30
+ export function estimateBuilderFee({ size, price, feeRate, }) {
31
+ const values = [size, price, feeRate].map((v) => new BigNumber(v));
32
+ if (values.some((v) => !v.isFinite() || v.isNegative())) {
33
+ throw new Error('size, price and feeRate must be non-negative decimals');
34
+ }
35
+ const [s, p, r] = values;
36
+ return s.times(p).times(r).decimalPlaces(8, BigNumber.ROUND_UP).toFixed();
37
+ }
38
+ function sessionEnvironment(env) {
39
+ return env === 'prod' ? 'mainnet' : env;
40
+ }
41
+ function defaultStorage() {
42
+ return typeof globalThis.indexedDB !== 'undefined'
43
+ ? indexedDbSessionStorage()
44
+ : memorySessionStorage();
45
+ }
46
+ function sameFelt(a, b) {
47
+ return canonicalFelt(a) === canonicalFelt(b);
48
+ }
49
+ /**
50
+ * Everything a builder's web app does with Paradex, behind one object:
51
+ * open the user's account and a trading session that approves the builder,
52
+ * trade with the builder fee, read fills, manage approvals, withdraw, and
53
+ * read builder stats. Builders never use subkeys.
54
+ *
55
+ * @experimental
56
+ */
57
+ export class BuilderApp {
58
+ constructor(params, config, ownerAddress, account) {
59
+ this.params = params;
60
+ this.environment = params.environment;
61
+ this.wallet = params.wallet;
62
+ this.builder = {
63
+ account: builderAddress(params.builder.account, 'builder.account'),
64
+ feeRate: params.builder.feeRate,
65
+ maxFeeRate: params.builder.maxFeeRate ?? params.builder.feeRate,
66
+ };
67
+ this.config = config;
68
+ this.ownerAddress = ownerAddress;
69
+ this.accountState = account;
70
+ this.apiUrl = (params.apiUrl ?? defaultApiUrl(sessionEnvironment(params.environment))).replace(/\/+$/, '');
71
+ this.transport = params.transport ?? fetchTransport;
72
+ this.connector = new SessionConnector({
73
+ environment: sessionEnvironment(params.environment),
74
+ paradexChain: config.paradexChainId,
75
+ owner: walletOwnerSigner(params.wallet),
76
+ storage: params.storage ?? defaultStorage(),
77
+ transport: this.transport,
78
+ apiUrl: this.apiUrl,
79
+ ...(params.now != null ? { now: params.now } : {}),
80
+ });
81
+ this.ownerAuth = new OwnerAuth({
82
+ wallet: params.wallet,
83
+ apiUrl: this.apiUrl,
84
+ siweDomain: params.siweDomain ?? SIWE_DOMAINS[params.environment],
85
+ ethereumChainId: Number(config.ethereumChainId),
86
+ transport: this.transport,
87
+ ...(params.now != null ? { now: params.now } : {}),
88
+ });
89
+ this.codes = new BuilderCodesClient({
90
+ environment: sessionEnvironment(params.environment),
91
+ apiUrl: this.apiUrl,
92
+ transport: this.transport,
93
+ });
94
+ this.rfq = new RfqClient({
95
+ environment: sessionEnvironment(params.environment),
96
+ apiUrl: this.apiUrl,
97
+ transport: this.transport,
98
+ });
99
+ }
100
+ /**
101
+ * Reads the config and the wallet's account. Prompts the wallet only to
102
+ * connect (`eth_requestAccounts`) when it has no address yet.
103
+ */
104
+ static async connect(params) {
105
+ const { feeRate } = params.builder;
106
+ const maxFeeRate = params.builder.maxFeeRate ?? feeRate;
107
+ builderAddress(params.builder.account, 'builder.account');
108
+ if (toChainQuantums(feeRate, 'builder.feeRate') === '0') {
109
+ throw new Error('builder.feeRate must be above 0');
110
+ }
111
+ toChainQuantums(maxFeeRate, 'builder.maxFeeRate');
112
+ if (new BigNumber(maxFeeRate).isLessThan(feeRate)) {
113
+ throw new Error('builder.maxFeeRate must be at least builder.feeRate');
114
+ }
115
+ const config = params.config ?? (await fetchConfig(params.environment));
116
+ const ownerAddress = await params.wallet.getAddress();
117
+ const apiUrl = (params.apiUrl ?? defaultApiUrl(sessionEnvironment(params.environment))).replace(/\/+$/, '');
118
+ const account = await lookupAccount(params.transport ?? fetchTransport, apiUrl, ownerAddress);
119
+ return new BuilderApp(params, config, ownerAddress, account);
120
+ }
121
+ /** The wallet's account as last read. */
122
+ get account() {
123
+ return this.accountState;
124
+ }
125
+ /** Re-reads whether the wallet's account exists. */
126
+ async refreshAccount() {
127
+ this.accountState = await lookupAccount(this.transport, this.apiUrl, this.ownerAddress);
128
+ return this.accountState;
129
+ }
130
+ /**
131
+ * Opens the account without a session (one `personal_sign` prompt). Only
132
+ * for an app that needs the account, or a referral code, before trading:
133
+ * {@link openSession} opens a new account itself, and a grant naming a
134
+ * builder carries no referral.
135
+ */
136
+ async onboard(options = {}) {
137
+ await this.ownerAuth.onboard(this.accountState.address, options);
138
+ return await this.refreshAccount();
139
+ }
140
+ /**
141
+ * Opens a trading session that approves the app's builder (one EIP-712
142
+ * prompt). For a wallet with no account, the same grant opens it: the
143
+ * account exists at once and deploys shortly after, and a Privy wallet's
144
+ * access token lets a verified user skip the minimum-balance check.
145
+ */
146
+ async openSession(options = {}) {
147
+ if (options.scopes != null && !options.scopes.includes('trade')) {
148
+ throw new SessionGrantError('INVALID_FIELD', 'scopes: a builder session must include "trade"');
149
+ }
150
+ const privyAccessToken = this.accountState.exists
151
+ ? undefined
152
+ : await this.wallet.getPrivyAccessToken?.();
153
+ const session = await this.connector.open({
154
+ account: this.accountState.address,
155
+ builder: {
156
+ account: this.builder.account,
157
+ maxFeeRate: this.builder.maxFeeRate,
158
+ expiresAt: 0,
159
+ },
160
+ ...(options.scopes != null ? { scopes: options.scopes } : {}),
161
+ ...(options.subaccounts != null
162
+ ? { subaccounts: options.subaccounts }
163
+ : {}),
164
+ ...(options.ttlSeconds != null ? { ttlSeconds: options.ttlSeconds } : {}),
165
+ ...(options.label != null ? { label: options.label } : {}),
166
+ ...(privyAccessToken != null ? { onboarding: { privyAccessToken } } : {}),
167
+ });
168
+ this.accountState = { ...this.accountState, exists: true };
169
+ return this.sessionFor(session, options.onDropped);
170
+ }
171
+ /**
172
+ * The newest stored session of this wallet's account that can still place
173
+ * the app's orders, or `undefined`: its grant approves the app's builder
174
+ * at a ceiling of at least `feeRate`, and the server reports it active.
175
+ * Its grant lists `trade` and, with `scopes`, every one of those too.
176
+ * Sessions the server reports revoked or expired are deleted from
177
+ * storage. When the status cannot be read (offline), the session is kept
178
+ * and returned; its first call re-checks it.
179
+ */
180
+ async restoreSession(options = {}) {
181
+ const now = this.now();
182
+ // A session without `trade` cannot place the app's orders.
183
+ const scopes = [
184
+ 'trade',
185
+ ...(options.scopes ?? []),
186
+ ];
187
+ const sessions = (await this.connector.restore()).filter((s) => sameFelt(s.grant.account, this.accountState.address) &&
188
+ scopes.every((scope) => s.grant.scopes.includes(scope)) &&
189
+ sameFelt(s.grant.builder.account, this.builder.account) &&
190
+ new BigNumber(s.grant.builder.maxFeeRate).gte(this.builder.feeRate) &&
191
+ (s.grant.builder.expiresAt === 0 || s.grant.builder.expiresAt > now));
192
+ sessions.sort((a, b) => b.grant.issuedAt - a.grant.issuedAt);
193
+ for (const session of sessions) {
194
+ const state = await fetchGrantState(this.transport, this.apiUrl, session.grantId);
195
+ if (state === 'revoked' || state === 'expired') {
196
+ await this.connector.forget(session);
197
+ continue;
198
+ }
199
+ return this.sessionFor(session, options.onDropped);
200
+ }
201
+ return undefined;
202
+ }
203
+ now() {
204
+ return (this.params.now ?? nowSeconds)();
205
+ }
206
+ /** Deletes a session's key from storage (after it ends). */
207
+ async forgetSession(session) {
208
+ await this.connector.forget(session.session);
209
+ }
210
+ sessionFor(session, onDropped) {
211
+ const accounts = new SessionAccounts({
212
+ session,
213
+ environment: sessionEnvironment(this.environment),
214
+ paradexChain: this.config.paradexChainId,
215
+ transport: this.transport,
216
+ apiUrl: this.apiUrl,
217
+ ...(this.params.wsUrl != null ? { wsUrl: this.params.wsUrl } : {}),
218
+ ...(this.params.webSocketFactory != null
219
+ ? { webSocketFactory: this.params.webSocketFactory }
220
+ : {}),
221
+ ...(this.params.onMessageError != null
222
+ ? { onMessageError: this.params.onMessageError }
223
+ : {}),
224
+ ...(this.params.now != null ? { now: this.params.now } : {}),
225
+ // A session that ended is never usable again: delete its key so
226
+ // restoreSession() does not offer it.
227
+ onDropped: (reason) => {
228
+ void this.connector.forget(session).catch(() => undefined);
229
+ onDropped?.(reason);
230
+ },
231
+ });
232
+ return new BuilderSession(session, accounts, this.builder);
233
+ }
234
+ /**
235
+ * Approves the app's builder without a session (one EIP-712 prompt), for
236
+ * orders the user signs with their own key. A session already approves
237
+ * the builder through its grant.
238
+ */
239
+ async approveBuilder(options = {}) {
240
+ const { response } = await this.connector.approveBuilder({
241
+ account: this.accountState.address,
242
+ builder: {
243
+ account: this.builder.account,
244
+ maxFeeRate: options.maxFeeRate ?? this.builder.maxFeeRate,
245
+ },
246
+ ...(options.ttlSeconds != null ? { ttlSeconds: options.ttlSeconds } : {}),
247
+ ...(options.subaccounts != null
248
+ ? { subaccounts: options.subaccounts }
249
+ : {}),
250
+ });
251
+ const approval = response?.approval;
252
+ if (approval == null || typeof approval !== 'object') {
253
+ throw new SessionApiError(200, {
254
+ error: 'INVALID_RESPONSE',
255
+ message: 'POST /v2/builders/approvals returned no approval',
256
+ });
257
+ }
258
+ return approval;
259
+ }
260
+ /**
261
+ * The account's builder approvals, standalone and in-grant. Needs the
262
+ * owner's login: one `personal_sign` of a Sign-In with Ethereum message
263
+ * naming the Paradex app, reused for 5 minutes.
264
+ */
265
+ async listApprovals(options = {}) {
266
+ return await this.codes.listApprovals(await this.ownerLogin(APPROVALS_LOGIN), options);
267
+ }
268
+ /**
269
+ * Revokes the account's approval of a builder (the app's by default).
270
+ * New orders naming it are refused at once and resting ones are
271
+ * cancelled. It also revokes every session of the account that names the
272
+ * builder, on every device, including this page's own: its
273
+ * {@link BuilderSession} keeps its key until its next request is refused,
274
+ * then the SDK drops it and calls `onDropped`. Needs the owner's
275
+ * login, as {@link listApprovals}.
276
+ */
277
+ async revokeApproval(builderAccount) {
278
+ await this.codes.revokeApproval(await this.ownerLogin(APPROVALS_LOGIN), builderAccount ?? this.builder.account);
279
+ }
280
+ /**
281
+ * The Paradex app's Builder approvals settings page for this
282
+ * environment, where the user lists and revokes approvals with no
283
+ * cross-site warning.
284
+ */
285
+ get approvalsSettingsUrl() {
286
+ return `https://${SIWE_DOMAINS[this.params.environment]}/settings/builder-approvals`;
287
+ }
288
+ /**
289
+ * Turns on RFQ trading for the user's account: until then its RFQ calls
290
+ * are refused with `RFQ_NOT_ENABLED`. A session's RFQ calls also need
291
+ * `trade:rfq` in its grant and Paradex allowing RFQ for the builder's
292
+ * sessions; this call does neither. It
293
+ * provisions the account on Paradigm, the RFQ venue, and registers a
294
+ * Paradigm delegation subkey on the account, which counts against its
295
+ * subkey limit. Needs the owner's login, as {@link listApprovals}; a
296
+ * session cannot enable RFQ. RFQ is enabled per account: pass
297
+ * `account` to enable one of the user's EVM sub-accounts, which takes
298
+ * its own owner login. Safe to call again: an enabled account gets the
299
+ * same state back. It can take up to 30 s; a slow call ends as a
300
+ * retryable 503 `SERVICE_UNAVAILABLE`, and calling again resumes it.
301
+ */
302
+ async enableRfq(options = {}) {
303
+ const account = options.account != null
304
+ ? canonicalFelt(options.account)
305
+ : this.accountState.address;
306
+ return await this.rfq.enable(await this.ownerLogin(RFQ_LOGIN, account));
307
+ }
308
+ /**
309
+ * Whether {@link listApprovals}, {@link revokeApproval} and
310
+ * {@link enableRfq} work here without sending the user to the Paradex
311
+ * app: false for an injected wallet unless `allowCrossSiteOwnerLogin` is
312
+ * set.
313
+ */
314
+ get canManageApprovals() {
315
+ return (this.params.wallet.kind !== 'injected' ||
316
+ this.params.allowCrossSiteOwnerLogin === true);
317
+ }
318
+ async ownerLogin(purpose, account = this.accountState.address) {
319
+ if (!this.canManageApprovals) {
320
+ throw new BuilderAppError('OWNER_LOGIN_NEEDS_PARADEX_APP', purpose === APPROVALS_LOGIN
321
+ ? `Listing and revoking approvals with an injected wallet signs in to the Paradex app, which the wallet flags as another site. Link the user to ${this.approvalsSettingsUrl}, or set allowCrossSiteOwnerLogin.`
322
+ : `Enabling RFQ with an injected wallet signs in to the Paradex app, which the wallet flags as another site. Have the user enable RFQ in the Paradex app (${SIWE_DOMAINS[this.params.environment]}), or set allowCrossSiteOwnerLogin.`);
323
+ }
324
+ return await this.ownerAuth.login(account);
325
+ }
326
+ /**
327
+ * Withdraws to Ethereum, signed by the owner wallet with EIP-191 (one
328
+ * `personal_sign` prompt). By default the funds go through StarkGate to
329
+ * the owner's own address and are claimable on L1 once the block is
330
+ * proven there.
331
+ */
332
+ async withdraw(params) {
333
+ const token = params.token ?? 'USDC';
334
+ const client = await this.evmOwnerClient();
335
+ let bridgeCall = params.bridgeCall;
336
+ if (bridgeCall == null) {
337
+ const { receivableAmountChain } = await client.getReceivableAmount(token, params.amount);
338
+ bridgeCall = starkgateWithdrawCall({
339
+ config: this.config,
340
+ token,
341
+ l1Recipient: this.ownerAddress,
342
+ amountChain: receivableAmountChain,
343
+ });
344
+ }
345
+ return await client.withdraw(token, params.amount, bridgeCall);
346
+ }
347
+ async waitForTransaction(hash, options) {
348
+ return await (await this.evmOwnerClient()).waitForTransaction(hash, options);
349
+ }
350
+ async evmOwnerClient() {
351
+ this.withdrawClient ?? (this.withdrawClient = EvmOwnerClient.create({
352
+ config: this.config,
353
+ signer: walletEvmOwnerSigner(this.wallet),
354
+ accountAddress: this.accountState.address,
355
+ }).catch((error) => {
356
+ this.withdrawClient = undefined;
357
+ throw error;
358
+ }));
359
+ return await this.withdrawClient;
360
+ }
361
+ /** The app's builder fee for an order of `size` at `price`, in USDC. */
362
+ estimateFee(size, price, feeRate) {
363
+ return estimateBuilderFee({
364
+ size,
365
+ price,
366
+ feeRate: feeRate ?? this.builder.feeRate,
367
+ });
368
+ }
369
+ /** A builder's stats, one row per window (the app's builder by default). */
370
+ async builderStats(builderAccount) {
371
+ return await this.codes.fetchStats(builderAccount ?? this.builder.account);
372
+ }
373
+ async leaderboard(window) {
374
+ return await this.codes.fetchLeaderboard(window);
375
+ }
376
+ }
377
+ /**
378
+ * A trading session that approves the app's builder. Calls act on the
379
+ * grant's main account unless `account` names one of its sub-accounts.
380
+ *
381
+ * @experimental
382
+ */
383
+ export class BuilderSession {
384
+ /** @internal */
385
+ constructor(session, accounts, builder) {
386
+ this.session = session;
387
+ this.accounts = accounts;
388
+ this.builder = builder;
389
+ }
390
+ /** The main account the session trades. */
391
+ get account() {
392
+ return this.session.grant.account;
393
+ }
394
+ get expiresAt() {
395
+ return this.session.grant.expiresAt;
396
+ }
397
+ /** Signs and places an order carrying the app's builder fee. */
398
+ async placeOrder(order, account) {
399
+ const builderFeeRate = order.builderFeeRate ?? this.builder.feeRate;
400
+ // The grant's ceiling, not the app's current one: a restored session
401
+ // may have been opened with a lower maxFeeRate.
402
+ if (new BigNumber(builderFeeRate).isGreaterThan(this.session.grant.builder.maxFeeRate)) {
403
+ throw new BuilderAppError('BUILDER_FEE_RATE_OVER_APPROVAL', `builderFeeRate ${builderFeeRate} is above the session's approved ${this.session.grant.builder.maxFeeRate}`);
404
+ }
405
+ return (await this.accounts.placeOrder(account ?? this.account, {
406
+ ...order,
407
+ builder: this.builder.account,
408
+ builderFeeRate,
409
+ }));
410
+ }
411
+ async cancelOrder(orderId, account) {
412
+ await this.accounts.cancelOrder(account ?? this.account, orderId);
413
+ }
414
+ async cancelOrderByClientId(clientId, account) {
415
+ await this.accounts.request(account ?? this.account, {
416
+ method: 'DELETE',
417
+ path: `/v1/orders/by_client_id/${encodeURIComponent(clientId)}`,
418
+ });
419
+ }
420
+ /** Cancels every open order, or those in one market. */
421
+ async cancelAllOrders(options = {}, account) {
422
+ await this.accounts.request(account ?? this.account, {
423
+ method: 'DELETE',
424
+ path: `/v1/orders${queryString({ market: options.market })}`,
425
+ });
426
+ }
427
+ async listOpenOrders(options = {}, account) {
428
+ const body = await this.accounts.request(account ?? this.account, {
429
+ method: 'GET',
430
+ path: `/v1/orders${queryString({ market: options.market })}`,
431
+ });
432
+ return toPage(body, 'GET /v1/orders').results;
433
+ }
434
+ async listOrdersHistory(query = {}, account) {
435
+ const body = await this.accounts.request(account ?? this.account, {
436
+ method: 'GET',
437
+ path: `/v1/orders-history${queryString({
438
+ ...fillsQueryParams(query),
439
+ side: query.side,
440
+ status: query.status,
441
+ type: query.type,
442
+ client_id: query.clientId,
443
+ })}`,
444
+ });
445
+ return toPage(body, 'GET /v1/orders-history');
446
+ }
447
+ /** Fills, newest first, with the builder fee each paid. */
448
+ async listFills(query = {}, account) {
449
+ const body = await this.accounts.request(account ?? this.account, {
450
+ method: 'GET',
451
+ path: `/v1/fills${queryString(fillsQueryParams(query))}`,
452
+ });
453
+ return toPage(body, 'GET /v1/fills');
454
+ }
455
+ /**
456
+ * The account's onboarding state. A new account reads `ONBOARDING` and
457
+ * `is_deployed: false` until it deploys.
458
+ */
459
+ async accountInfo(account) {
460
+ return (await this.accounts.request(account ?? this.account, {
461
+ method: 'GET',
462
+ path: '/v1/account/info',
463
+ }));
464
+ }
465
+ async status() {
466
+ return await this.accounts.status();
467
+ }
468
+ /**
469
+ * Subscribes to a websocket channel, such as `orders.ALL`, `fills.ALL`,
470
+ * `positions`, `account` or `bbo.BTC-USD-PERP`; returns the unsubscribe
471
+ * function. Fills come without the builder fee: read it with
472
+ * {@link listFills}. See {@link SessionAccounts.subscribe}.
473
+ */
474
+ async subscribe(channel, handler, account) {
475
+ return await this.accounts.subscribe(account ?? this.account, channel, handler);
476
+ }
477
+ /**
478
+ * Ends the session on the server and deletes its key from storage. Its
479
+ * resting orders, TWAPs and untriggered stops are cancelled. With
480
+ * `cancelOrders: false` only resting orders are kept: a grant that names
481
+ * a builder still has its TWAPs and untriggered stops cancelled, and its
482
+ * kept orders last until the approval ends, by revoke or expiry.
483
+ *
484
+ * The builder approval the grant carried stays active until it expires
485
+ * (by default, when the last of the sessions that carried it would have
486
+ * expired, unless {@link BuilderApp.approveBuilder} gave it its own
487
+ * expiry). To end it too, call
488
+ * {@link BuilderApp.revokeApproval}, which also revokes the account's
489
+ * sessions naming the builder and cancels resting orders naming it. With
490
+ * an injected wallet, link to {@link BuilderApp.approvalsSettingsUrl}
491
+ * instead.
492
+ */
493
+ async revoke(options = {}) {
494
+ await this.accounts.revoke(options);
495
+ }
496
+ /** Closes sockets and timers; the session stays valid. */
497
+ close() {
498
+ this.accounts.close();
499
+ }
500
+ }
501
+ async function lookupAccount(transport, apiUrl, ethAddress) {
502
+ if (!/^0x[0-9a-fA-F]{40}$/.test(ethAddress)) {
503
+ throw new Error('Wallet address must be a 0x-prefixed 20-byte address');
504
+ }
505
+ const response = await transport({
506
+ method: 'GET',
507
+ url: `${apiUrl}/v1/onboarding${queryString({
508
+ eth_address: ethAddress,
509
+ account_signer_type: 'eip191',
510
+ })}`,
511
+ headers: {},
512
+ });
513
+ if (response.status < 200 || response.status >= 300) {
514
+ throw new SessionApiError(response.status, response.body);
515
+ }
516
+ const body = (response.body ?? {});
517
+ if (typeof body.address !== 'string' || typeof body.exists !== 'boolean') {
518
+ throw new SessionApiError(response.status, {
519
+ error: 'INVALID_RESPONSE',
520
+ message: 'GET /v1/onboarding returned no address',
521
+ });
522
+ }
523
+ if (body.account_signer_type !== 'eip191') {
524
+ throw new BuilderAppError('STARK_OWNED_ACCOUNT', "The wallet's Paradex account is Stark-owned; builder apps need an EVM-owned account");
525
+ }
526
+ return { address: canonicalFelt(body.address), exists: body.exists };
527
+ }
@@ -0,0 +1,109 @@
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. Every session of the
89
+ * account that names the builder is revoked too, on every device. A
90
+ * builder with no live approval is a 404 `SessionApiError`.
91
+ */
92
+ revokeApproval(token: string, builderAccount: string): Promise<void>;
93
+ /**
94
+ * `GET /v1/builders/{builder_account}/stats`: one row per window. A window
95
+ * with no paid fill, or with too few paying users, is zeros. Stats lag the
96
+ * fills they count.
97
+ */
98
+ fetchStats(builderAccount: string): Promise<BuilderStats[]>;
99
+ /**
100
+ * `GET /v1/builders/leaderboard`: builders ranked by `fees_paid` over one
101
+ * window, then by volume. The server's default window is `7d`, and it
102
+ * answers 400 for a window it does not serve.
103
+ */
104
+ fetchLeaderboard(window?: BuilderStatsWindow): Promise<BuilderLeaderboardRow[]>;
105
+ private send;
106
+ private results;
107
+ }
108
+ /** The `Authorization` header for an account owner's JWT. */
109
+ export declare function bearer(token: string): Record<string, string>;