@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.
package/dist/index.d.ts CHANGED
@@ -1,13 +1,22 @@
1
1
  import * as _Account from './account.js';
2
+ import * as _ApiErrors from './api-errors.js';
2
3
  import * as _Client from './client.js';
3
4
  import * as _Config from './config.js';
4
5
  import * as _Signer from './ethereum-signer.js';
6
+ import * as _EvmOwnerClient from './evm-owner-client.js';
7
+ import * as _EvmOwnerSigner from './evm-owner-signer.js';
5
8
  import * as _SessionKey from './session-key.js';
6
9
  import * as _SessionOwnerSigner from './session-owner-signer.js';
7
10
  import * as _SessionTypedData from './session-typed-data.js';
11
+ import * as _Wallet from './wallet.js';
8
12
  export declare const Client: {
9
13
  fromEthSigner: (params: _Client.CreateClientFromEthSignerParams) => Promise<_Client.ParadexClient>;
10
14
  fromStarknetAccount: (params: _Client.CreateClientFromStarknetAccountParams) => Promise<_Client.ParadexClient>;
15
+ /**
16
+ * Client for an EVM-owned (EIP-191) account: every transaction is signed
17
+ * by the owner wallet. No Stark key is derived.
18
+ */
19
+ fromEvmOwner: (params: _EvmOwnerClient.CreateClientFromEvmOwnerParams) => Promise<_EvmOwnerClient.EvmOwnerClient>;
11
20
  };
12
21
  export declare const Config: {
13
22
  fetch: typeof _Config.fetchConfig;
@@ -18,12 +27,39 @@ export declare const Onboarding: {
18
27
  export declare const Signer: {
19
28
  fromEthers: typeof _Signer.ethersSignerAdapter;
20
29
  };
30
+ /** Owner signers for EVM-owned (EIP-191) accounts, for `Client.fromEvmOwner`. */
31
+ export declare const EvmOwnerSigner: {
32
+ fromEthers: typeof _EvmOwnerSigner.evmOwnerSignerFromEthers;
33
+ fromViem: typeof _EvmOwnerSigner.evmOwnerSignerFromViem;
34
+ fromEip1193: typeof _EvmOwnerSigner.evmOwnerSignerFromEip1193;
35
+ };
36
+ /**
37
+ * The user's EVM wallet for `BuilderApp`: an injected wallet, a Privy
38
+ * embedded wallet, or an ethers signer.
39
+ * @experimental
40
+ */
41
+ export declare const Wallet: {
42
+ fromEip1193: typeof _Wallet.walletFromEip1193;
43
+ fromPrivy: typeof _Wallet.walletFromPrivy;
44
+ fromEthers: typeof _Wallet.walletFromEthers;
45
+ };
46
+ /** Help for Paradex API errors. @experimental */
47
+ export declare const Errors: {
48
+ isCode: typeof _ApiErrors.isApiErrorCode;
49
+ describe: typeof _ApiErrors.describeApiError;
50
+ };
51
+ export declare const Bridge: {
52
+ starkgateWithdrawCall: typeof _EvmOwnerClient.starkgateWithdrawCall;
53
+ };
21
54
  /**
22
55
  * Session grant typed data and hashing.
23
56
  * @experimental The server side of sessions is not released yet.
24
57
  */
25
58
  export declare const SessionTypedData: {
26
59
  createGrant: typeof _SessionTypedData.createSessionGrant;
60
+ createBuilderApproval: typeof _SessionTypedData.createBuilderApproval;
61
+ validateBuilderApproval: typeof _SessionTypedData.validateBuilderApproval;
62
+ buildBuilderApprovalEip712: typeof _SessionTypedData.buildBuilderApprovalEip712;
27
63
  validateGrant: typeof _SessionTypedData.validateSessionGrant;
28
64
  validatePasskeyGrant: typeof _SessionTypedData.validatePasskeyGrant;
29
65
  validateMint: typeof _SessionTypedData.validateSessionMint;
@@ -56,21 +92,37 @@ export declare const Session: {
56
92
  memoryStorage: typeof _SessionKey.memorySessionStorage;
57
93
  indexedDbStorage: typeof _SessionKey.indexedDbSessionStorage;
58
94
  };
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';
95
+ 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
96
  export { SessionConnector } from './session-connector.js';
97
+ export { BuilderApp, BuilderSession, estimateBuilderFee, SIWE_DOMAINS, } from './builder-app.js';
98
+ export type { ApproveBuilderOptions, BuilderAppAccount, BuilderAppBuilder, BuilderAppEnvironment, BuilderAppParams, BuilderOrder, BuilderSessionScope, BuilderWithdrawParams, EstimateBuilderFeeParams, EnableRfqOptions, OpenBuilderSessionOptions, } from './builder-app.js';
99
+ export type { OnboardOptions } from './owner-auth.js';
100
+ export { WalletRejectedError } from './wallet.js';
101
+ export type { ParadexWallet, WalletFromEip1193Params, WalletFromEthersParams, WalletFromPrivyParams, } from './wallet.js';
102
+ export { BuilderAppError } from './api-errors.js';
103
+ export type { ApiErrorDescription, ApiErrorWithCode, DerivedApiErrorCode, BuilderAppErrorCode, BuilderCancelReason, } from './api-errors.js';
104
+ export type { AccountInfo, Fill, FillsQuery, OnboardingStatus, Order, OrderStatus, OrdersHistoryQuery, Page, } from './trading.js';
105
+ export { BuilderCodesClient } from './builder-codes.js';
106
+ export type { BuilderApprovalRecord, BuilderApprovalStatus, BuilderCodesClientParams, BuilderLeaderboardRow, BuilderRef, BuilderStats, BuilderStatsWindow, ListBuilderApprovalsOptions, } from './builder-codes.js';
107
+ export { RfqClient } from './rfq.js';
108
+ export type { RfqClientParams, RfqEnableResult } from './rfq.js';
61
109
  export { DeterminismGuardError, isContractCode } from './determinism-guard.js';
62
110
  export { SessionAccounts } from './session-accounts.js';
63
- export { SessionApiError } from './session-transport.js';
111
+ export { SessionApiError,
112
+ /** The error every Paradex REST call throws; the same class as `SessionApiError`. */
113
+ SessionApiError as ParadexApiError, } from './session-transport.js';
64
114
  export { SessionKey } from './session-key.js';
65
115
  export type { AddressDerivationOptions, OnboardingInfo, OnboardingDerivationInfo, } from './account.js';
66
116
  export type { ParadexClient, CreateClientFromEthSignerParams, CreateClientFromStarknetAccountParams, TokenBalance, SocializedLossFactor, ReceivableAmount, MaxWithdraw, WithdrawResult, } from './client.js';
67
117
  export type { ParadexConfig } from './config.js';
118
+ export type { CreateClientFromEvmOwnerParams, EvmOwnerClient, StarkgateWithdrawCallParams, } from './evm-owner-client.js';
119
+ export type { EvmOwnerSigner as EvmOwnerSignerInterface, EvmOwnerSignerFromEip1193Params, EvmOwnerSignerFromViemParams, ViemMessageSigner, } from './evm-owner-signer.js';
68
120
  export type { EthereumSigner } from './ethereum-signer.js';
69
121
  export type { DeterminismGuardErrorCode, DeterminismGuardOptions, DeterminismGuardResult, EthCodeProvider, } from './determinism-guard.js';
70
122
  export type { Hex } from './types.js';
71
123
  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';
124
+ 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';
125
+ export type { ApproveBuilderParams, EvmSubaccount, OpenSessionParams, RegisteredBuilderApproval, Session as RegisteredSession, SessionConnectorParams, SessionOnboardingParams, SessionUtm, } from './session-connector.js';
74
126
  export type { GrantState, GrantStatus, RevokeOptions, SessionAccountsParams, SessionRequest, SubscriptionHandler, } from './session-accounts.js';
75
127
  export type { OrderSide, OrderType, SessionOrder } from './session-auth.js';
76
128
  export type { SessionStorage, StoredSession } from './session-key.js';
package/dist/index.js CHANGED
@@ -1,14 +1,23 @@
1
1
  import * as _Account from './account.js';
2
+ import * as _ApiErrors from './api-errors.js';
2
3
  import * as _Client from './client.js';
3
4
  import * as _Config from './config.js';
4
5
  import * as _Signer from './ethereum-signer.js';
6
+ import * as _EvmOwnerClient from './evm-owner-client.js';
7
+ import * as _EvmOwnerSigner from './evm-owner-signer.js';
5
8
  import * as _SessionKey from './session-key.js';
6
9
  import * as _SessionOwnerSigner from './session-owner-signer.js';
7
10
  import * as _SessionTypedData from './session-typed-data.js';
11
+ import * as _Wallet from './wallet.js';
8
12
  // Recommended: High-level client interface
9
13
  export const Client = {
10
14
  fromEthSigner: async (params) => await _Client.ParadexClient.createFromEthSigner(params),
11
15
  fromStarknetAccount: async (params) => await _Client.ParadexClient.createFromStarknetAccount(params),
16
+ /**
17
+ * Client for an EVM-owned (EIP-191) account: every transaction is signed
18
+ * by the owner wallet. No Stark key is derived.
19
+ */
20
+ fromEvmOwner: async (params) => await _EvmOwnerClient.EvmOwnerClient.create(params),
12
21
  };
13
22
  export const Config = {
14
23
  fetch: _Config.fetchConfig,
@@ -19,12 +28,39 @@ export const Onboarding = {
19
28
  export const Signer = {
20
29
  fromEthers: _Signer.ethersSignerAdapter,
21
30
  };
31
+ /** Owner signers for EVM-owned (EIP-191) accounts, for `Client.fromEvmOwner`. */
32
+ export const EvmOwnerSigner = {
33
+ fromEthers: _EvmOwnerSigner.evmOwnerSignerFromEthers,
34
+ fromViem: _EvmOwnerSigner.evmOwnerSignerFromViem,
35
+ fromEip1193: _EvmOwnerSigner.evmOwnerSignerFromEip1193,
36
+ };
37
+ /**
38
+ * The user's EVM wallet for `BuilderApp`: an injected wallet, a Privy
39
+ * embedded wallet, or an ethers signer.
40
+ * @experimental
41
+ */
42
+ export const Wallet = {
43
+ fromEip1193: _Wallet.walletFromEip1193,
44
+ fromPrivy: _Wallet.walletFromPrivy,
45
+ fromEthers: _Wallet.walletFromEthers,
46
+ };
47
+ /** Help for Paradex API errors. @experimental */
48
+ export const Errors = {
49
+ isCode: _ApiErrors.isApiErrorCode,
50
+ describe: _ApiErrors.describeApiError,
51
+ };
52
+ export const Bridge = {
53
+ starkgateWithdrawCall: _EvmOwnerClient.starkgateWithdrawCall,
54
+ };
22
55
  /**
23
56
  * Session grant typed data and hashing.
24
57
  * @experimental The server side of sessions is not released yet.
25
58
  */
26
59
  export const SessionTypedData = {
27
60
  createGrant: _SessionTypedData.createSessionGrant,
61
+ createBuilderApproval: _SessionTypedData.createBuilderApproval,
62
+ validateBuilderApproval: _SessionTypedData.validateBuilderApproval,
63
+ buildBuilderApprovalEip712: _SessionTypedData.buildBuilderApprovalEip712,
28
64
  validateGrant: _SessionTypedData.validateSessionGrant,
29
65
  validatePasskeyGrant: _SessionTypedData.validatePasskeyGrant,
30
66
  validateMint: _SessionTypedData.validateSessionMint,
@@ -57,9 +93,16 @@ export const Session = {
57
93
  memoryStorage: _SessionKey.memorySessionStorage,
58
94
  indexedDbStorage: _SessionKey.indexedDbSessionStorage,
59
95
  };
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';
96
+ 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
97
  export { SessionConnector } from './session-connector.js';
98
+ export { BuilderApp, BuilderSession, estimateBuilderFee, SIWE_DOMAINS, } from './builder-app.js';
99
+ export { WalletRejectedError } from './wallet.js';
100
+ export { BuilderAppError } from './api-errors.js';
101
+ export { BuilderCodesClient } from './builder-codes.js';
102
+ export { RfqClient } from './rfq.js';
62
103
  export { DeterminismGuardError, isContractCode } from './determinism-guard.js';
63
104
  export { SessionAccounts } from './session-accounts.js';
64
- export { SessionApiError } from './session-transport.js';
105
+ export { SessionApiError,
106
+ /** The error every Paradex REST call throws; the same class as `SessionApiError`. */
107
+ SessionApiError as ParadexApiError, } from './session-transport.js';
65
108
  export { SessionKey } from './session-key.js';
@@ -0,0 +1,68 @@
1
+ import { type SessionUtm } from './session-connector.js';
2
+ import { type HttpTransport } from './session-transport.js';
3
+ import type { ParadexWallet } from './wallet.js';
4
+ export declare const EVM_AUTH_PATH = "/v2/auth";
5
+ export declare const EVM_ONBOARDING_PATH = "/v2/onboarding";
6
+ export interface OwnerAuthParams {
7
+ readonly wallet: ParadexWallet;
8
+ /** API host root, e.g. `https://api.testnet.paradex.trade`. */
9
+ readonly apiUrl: string;
10
+ /** The Paradex app host the server accepts in SIWE messages. */
11
+ readonly siweDomain: string;
12
+ /** The Ethereum chain id the server expects (`ParadexConfig.ethereumChainId`). */
13
+ readonly ethereumChainId: number;
14
+ readonly transport?: HttpTransport;
15
+ /** Seconds since the epoch. */
16
+ readonly now?: () => number;
17
+ }
18
+ export interface OnboardOptions {
19
+ readonly referralCode?: string;
20
+ /** `campaign:code`. */
21
+ readonly marketingCode?: string;
22
+ readonly utm?: SessionUtm;
23
+ }
24
+ /**
25
+ * The account owner's own sign-in, with the EVM wallet: SIWE login for a
26
+ * main-key JWT (`POST /v2/auth`), and onboarding without a session
27
+ * (`POST /v2/onboarding`).
28
+ *
29
+ * The SIWE message names the Paradex app's host, the only domain the server
30
+ * accepts. Embedded wallets (Privy) sign it without comment; injected
31
+ * wallets such as MetaMask warn that the domain differs from the page's.
32
+ *
33
+ * Not exported from the package: `BuilderApp` is the public way in.
34
+ *
35
+ * @internal
36
+ */
37
+ export declare class OwnerAuth {
38
+ private readonly params;
39
+ private readonly transport;
40
+ private readonly now;
41
+ private readonly tokens;
42
+ private readonly inflight;
43
+ /** Bumped by `logout()`, so a login in flight then is not cached. */
44
+ private generation;
45
+ constructor(params: OwnerAuthParams);
46
+ /**
47
+ * The owner's main-key JWT for `account` (5 minutes), minted with one
48
+ * `personal_sign` prompt and reused until 30 s before it expires. It is
49
+ * what listing and revoking builder approvals need.
50
+ */
51
+ login(account: string): Promise<string>;
52
+ /** Drops the cached owner tokens. */
53
+ logout(): void;
54
+ private mint;
55
+ /** The server's clock in whole seconds, from `GET /v1/system/time`. */
56
+ private serverTime;
57
+ /**
58
+ * Opens the wallet's account without a session (one `personal_sign`
59
+ * prompt). A new main account is created at once and deployed later
60
+ * ("deferred deploy"); it trades once it is deployed. Calling it for an
61
+ * account that exists is a no-op on the server.
62
+ *
63
+ * A Privy wallet sends its access token, so a verified Privy user skips
64
+ * the minimum-balance check. Otherwise the server may refuse with
65
+ * `INSUFFICIENT_MIN_CHAIN_BALANCE` or `ONBOARDING_RATE_LIMITED`.
66
+ */
67
+ onboard(account: string, options?: OnboardOptions): Promise<void>;
68
+ }
@@ -0,0 +1,184 @@
1
+ import { jwtExpiry } from './session-auth.js';
2
+ import { SYSTEM_TIME_PATH } from './session-connector.js';
3
+ import { fetchTransport, SessionApiError, } from './session-transport.js';
4
+ import { nowSeconds } from './session-typed-data.js';
5
+ import { base64Ascii, buildSiweMessage, recoverPersonalSignPublicKey, SIWE_AUTH_MAX_TTL, SIWE_AUTH_STATEMENT, SIWE_ONBOARDING_STATEMENT, siweNonce, } from './siwe.js';
6
+ export const EVM_AUTH_PATH = '/v2/auth';
7
+ export const EVM_ONBOARDING_PATH = '/v2/onboarding';
8
+ /** Refresh the owner token this many seconds before it expires. */
9
+ const OWNER_TOKEN_MARGIN = 30;
10
+ /**
11
+ * The account owner's own sign-in, with the EVM wallet: SIWE login for a
12
+ * main-key JWT (`POST /v2/auth`), and onboarding without a session
13
+ * (`POST /v2/onboarding`).
14
+ *
15
+ * The SIWE message names the Paradex app's host, the only domain the server
16
+ * accepts. Embedded wallets (Privy) sign it without comment; injected
17
+ * wallets such as MetaMask warn that the domain differs from the page's.
18
+ *
19
+ * Not exported from the package: `BuilderApp` is the public way in.
20
+ *
21
+ * @internal
22
+ */
23
+ export class OwnerAuth {
24
+ constructor(params) {
25
+ this.tokens = new Map();
26
+ this.inflight = new Map();
27
+ /** Bumped by `logout()`, so a login in flight then is not cached. */
28
+ this.generation = 0;
29
+ this.params = params;
30
+ this.transport = params.transport ?? fetchTransport;
31
+ this.now = params.now ?? nowSeconds;
32
+ }
33
+ /**
34
+ * The owner's main-key JWT for `account` (5 minutes), minted with one
35
+ * `personal_sign` prompt and reused until 30 s before it expires. It is
36
+ * what listing and revoking builder approvals need.
37
+ */
38
+ async login(account) {
39
+ const cached = this.tokens.get(account);
40
+ if (cached != null && cached.expiresAt - OWNER_TOKEN_MARGIN > this.now()) {
41
+ return cached.token;
42
+ }
43
+ let pending = this.inflight.get(account);
44
+ if (pending == null) {
45
+ const mint = this.mint(account).finally(() => {
46
+ // logout() may have cleared it and a newer login taken its place.
47
+ if (this.inflight.get(account) === mint)
48
+ this.inflight.delete(account);
49
+ });
50
+ pending = mint;
51
+ this.inflight.set(account, mint);
52
+ }
53
+ return await pending;
54
+ }
55
+ /** Drops the cached owner tokens. */
56
+ logout() {
57
+ this.generation++;
58
+ this.tokens.clear();
59
+ this.inflight.clear();
60
+ }
61
+ async mint(account) {
62
+ const { wallet } = this.params;
63
+ const address = await wallet.getAddress();
64
+ const generation = this.generation;
65
+ // The server's clock: it refuses a message issued in its future, or
66
+ // expired by its clock, so a device clock off by 30 s would fail.
67
+ const issuedAt = await this.serverTime();
68
+ const skew = issuedAt - this.now();
69
+ const message = buildSiweMessage({
70
+ domain: this.params.siweDomain,
71
+ address,
72
+ statement: SIWE_AUTH_STATEMENT,
73
+ chainId: this.params.ethereumChainId,
74
+ nonce: siweNonce(),
75
+ issuedAt,
76
+ expirationTime: issuedAt + SIWE_AUTH_MAX_TTL,
77
+ });
78
+ const signature = await wallet.signMessage(message);
79
+ // Fails fast on a wallet that signed something else.
80
+ recoverPersonalSignPublicKey(message, signature, address);
81
+ const response = await this.transport({
82
+ method: 'POST',
83
+ url: `${this.params.apiUrl}${EVM_AUTH_PATH}?token_usage=interactive`,
84
+ headers: {
85
+ 'PARADEX-STARKNET-ACCOUNT': account,
86
+ 'PARADEX-EVM-SIGNATURE': signature,
87
+ 'PARADEX-SIWE-MESSAGE': base64Ascii(message),
88
+ },
89
+ });
90
+ if (response.status < 200 || response.status >= 300) {
91
+ throw new SessionApiError(response.status, response.body);
92
+ }
93
+ const token = response.body?.jwt_token;
94
+ if (typeof token !== 'string' || token === '') {
95
+ throw new SessionApiError(response.status, {
96
+ error: 'INVALID_RESPONSE',
97
+ message: `POST ${EVM_AUTH_PATH} returned no jwt_token`,
98
+ });
99
+ }
100
+ if (generation === this.generation) {
101
+ // Kept in device-clock seconds, which `login` compares against.
102
+ this.tokens.set(account, {
103
+ token,
104
+ expiresAt: (jwtExpiry(token) ?? issuedAt + SIWE_AUTH_MAX_TTL) - skew,
105
+ });
106
+ }
107
+ return token;
108
+ }
109
+ /** The server's clock in whole seconds, from `GET /v1/system/time`. */
110
+ async serverTime() {
111
+ const response = await this.transport({
112
+ method: 'GET',
113
+ url: `${this.params.apiUrl}${SYSTEM_TIME_PATH}`,
114
+ headers: {},
115
+ });
116
+ if (response.status < 200 || response.status >= 300) {
117
+ throw new SessionApiError(response.status, response.body);
118
+ }
119
+ const ms = Number(response.body?.server_time);
120
+ if (!Number.isSafeInteger(ms) || ms <= 0) {
121
+ throw new SessionApiError(response.status, {
122
+ error: 'INVALID_RESPONSE',
123
+ message: `GET ${SYSTEM_TIME_PATH} returned no server_time`,
124
+ });
125
+ }
126
+ return Math.floor(ms / 1000);
127
+ }
128
+ /**
129
+ * Opens the wallet's account without a session (one `personal_sign`
130
+ * prompt). A new main account is created at once and deployed later
131
+ * ("deferred deploy"); it trades once it is deployed. Calling it for an
132
+ * account that exists is a no-op on the server.
133
+ *
134
+ * A Privy wallet sends its access token, so a verified Privy user skips
135
+ * the minimum-balance check. Otherwise the server may refuse with
136
+ * `INSUFFICIENT_MIN_CHAIN_BALANCE` or `ONBOARDING_RATE_LIMITED`.
137
+ */
138
+ async onboard(account, options = {}) {
139
+ const { wallet } = this.params;
140
+ const address = await wallet.getAddress();
141
+ const message = buildSiweMessage({
142
+ domain: this.params.siweDomain,
143
+ address,
144
+ statement: SIWE_ONBOARDING_STATEMENT,
145
+ chainId: this.params.ethereumChainId,
146
+ nonce: siweNonce(),
147
+ issuedAt: await this.serverTime(),
148
+ });
149
+ const signature = await wallet.signMessage(message);
150
+ const publicKey = recoverPersonalSignPublicKey(message, signature, address);
151
+ const privyToken = await wallet.getPrivyAccessToken?.();
152
+ const body = { public_key: publicKey };
153
+ if (options.referralCode != null && options.referralCode !== '') {
154
+ body.referral_code = options.referralCode;
155
+ }
156
+ if (options.marketingCode != null && options.marketingCode !== '') {
157
+ body.marketing_code = options.marketingCode;
158
+ }
159
+ if (options.utm != null) {
160
+ body.utm = {
161
+ source: options.utm.source,
162
+ campaign: options.utm.campaign,
163
+ ...(options.utm.type != null ? { type: options.utm.type } : {}),
164
+ };
165
+ }
166
+ const response = await this.transport({
167
+ method: 'POST',
168
+ url: `${this.params.apiUrl}${EVM_ONBOARDING_PATH}`,
169
+ headers: {
170
+ 'Content-Type': 'application/json',
171
+ 'PARADEX-STARKNET-ACCOUNT': account,
172
+ 'PARADEX-EVM-SIGNATURE': signature,
173
+ 'PARADEX-SIWE-MESSAGE': base64Ascii(message),
174
+ ...(privyToken != null
175
+ ? { 'PARADEX-PRIVY-ACCESS-TOKEN': privyToken }
176
+ : {}),
177
+ },
178
+ body: JSON.stringify(body),
179
+ });
180
+ if (response.status < 200 || response.status >= 300) {
181
+ throw new SessionApiError(response.status, response.body);
182
+ }
183
+ }
184
+ }
@@ -120,7 +120,7 @@ interface GetReceivableAmountResult {
120
120
  * will be equal to the requested amount.
121
121
  */
122
122
  export declare function getReceivableAmount(params: GetReceivableAmountParams): Promise<GetReceivableAmountResult>;
123
- interface WithdrawParams {
123
+ export interface WithdrawParams {
124
124
  readonly config: ParadexConfig;
125
125
  /**
126
126
  * Account to withdraw from.
@@ -167,4 +167,9 @@ interface TransactionResult {
167
167
  * failed withdrawal.
168
168
  */
169
169
  export declare function withdraw(params: WithdrawParams): Promise<TransactionResult>;
170
+ /**
171
+ * The calls a withdrawal signs: `paraclear.withdraw` of `amount`, then the
172
+ * bridge call(s), in one atomic batch.
173
+ */
174
+ export declare function buildWithdrawCalls(params: Pick<WithdrawParams, 'config' | 'token' | 'amount' | 'bridgeCall'>): Starknet.Call[];
170
175
  export {};
package/dist/paraclear.js CHANGED
@@ -121,12 +121,26 @@ export async function getReceivableAmount(params) {
121
121
  * failed withdrawal.
122
122
  */
123
123
  export async function withdraw(params) {
124
+ const txnInvocation = buildWithdrawCalls(params);
125
+ // Estimate fees to get proper resource bounds
126
+ const fees = await params.account.estimateInvokeFee(txnInvocation);
127
+ // Use the resource bounds from fee estimation
128
+ const result = await params.account.execute(txnInvocation, {
129
+ resourceBounds: fees.resourceBounds,
130
+ });
131
+ return { hash: result.transaction_hash };
132
+ }
133
+ /**
134
+ * The calls a withdrawal signs: `paraclear.withdraw` of `amount`, then the
135
+ * bridge call(s), in one atomic batch.
136
+ */
137
+ export function buildWithdrawCalls(params) {
124
138
  const token = params.config.bridgedTokens[params.token];
125
139
  if (token == null) {
126
140
  throw new Error(`Token ${params.token} is not supported`);
127
141
  }
128
142
  const chainAmountBn = toChainSize(params.amount, params.config.paraclearDecimals);
129
- const txnInvocation = [
143
+ return [
130
144
  {
131
145
  contractAddress: params.config.paraclearAddress,
132
146
  entrypoint: 'withdraw',
@@ -136,13 +150,6 @@ export async function withdraw(params) {
136
150
  ? params.bridgeCall
137
151
  : [params.bridgeCall]),
138
152
  ];
139
- // Estimate fees to get proper resource bounds
140
- const fees = await params.account.estimateInvokeFee(txnInvocation);
141
- // Use the resource bounds from fee estimation
142
- const result = await params.account.execute(txnInvocation, {
143
- resourceBounds: fees.resourceBounds,
144
- });
145
- return { hash: result.transaction_hash };
146
153
  }
147
154
  function fromChainSize(size, decimals) {
148
155
  return new BigNumber(size).div(10 ** decimals);
package/dist/rfq.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { type HttpTransport } from './session-transport.js';
2
+ import type { SessionEnvironment } from './session-typed-data.js';
3
+ /**
4
+ * Turning on RFQ trading for an account.
5
+ *
6
+ * @experimental The request and response shapes may change.
7
+ */
8
+ export declare const RFQ_ENABLE_PATH = "/v1/account/paradigm/enable";
9
+ /** The account's RFQ state after `POST /v1/account/paradigm/enable`. */
10
+ export interface RfqEnableResult {
11
+ /** The Paradex account RFQ is enabled for. */
12
+ readonly account: string;
13
+ /**
14
+ * Public key of the delegation subkey that signs the account's RFQ
15
+ * trades; absent when the server does not report one.
16
+ */
17
+ readonly subkey_public_key?: string;
18
+ readonly status: 'ENABLED';
19
+ }
20
+ export interface RfqClientParams {
21
+ /** Picks the default API host. */
22
+ readonly environment: SessionEnvironment;
23
+ /** API host root, such as `https://api.testnet.paradex.trade`. */
24
+ readonly apiUrl?: string;
25
+ readonly transport?: HttpTransport;
26
+ }
27
+ /**
28
+ * Enables RFQ trading on an account.
29
+ *
30
+ * @experimental
31
+ */
32
+ export declare class RfqClient {
33
+ private readonly apiUrl;
34
+ private readonly transport;
35
+ constructor(params: RfqClientParams);
36
+ /**
37
+ * `POST /v1/account/paradigm/enable`: provisions the token's account on
38
+ * Paradigm, the RFQ venue, and registers a Paradigm delegation subkey on
39
+ * it, which counts against the account's subkey limit. Idempotent: once
40
+ * enabled, a second call returns the same state.
41
+ *
42
+ * Only the account owner's main-key JWT, as `token`, can enable it. A
43
+ * subkey or session token only reads the state back once it is enabled,
44
+ * and gets 403 `UNAUTHORIZED_ERROR` before that; a session the server
45
+ * does not let use RFQ gets 403 `INVALID_TOKEN_SCOPE`. Other refusals:
46
+ * 400 `TOKEN_LIMIT_REACHED` when the account has no room for the subkey,
47
+ * 400 `REQUEST_NOT_ALLOWED` when Paradigm refuses the account, 409
48
+ * `SUBKEY_REVOKED` when the new delegation subkey is already revoked, and
49
+ * `NOT_ONBOARDED` while the account is still deploying. The call can take
50
+ * up to 30 s; a slow one ends as a retryable 503 `SERVICE_UNAVAILABLE`,
51
+ * and calling again resumes it.
52
+ */
53
+ enable(token: string): Promise<RfqEnableResult>;
54
+ }
package/dist/rfq.js ADDED
@@ -0,0 +1,64 @@
1
+ import { bearer } from './builder-codes.js';
2
+ import { defaultApiUrl, fetchTransport, SessionApiError, } from './session-transport.js';
3
+ /**
4
+ * Turning on RFQ trading for an account.
5
+ *
6
+ * @experimental The request and response shapes may change.
7
+ */
8
+ export const RFQ_ENABLE_PATH = '/v1/account/paradigm/enable';
9
+ /**
10
+ * Enables RFQ trading on an account.
11
+ *
12
+ * @experimental
13
+ */
14
+ export class RfqClient {
15
+ constructor(params) {
16
+ this.apiUrl = (params.apiUrl ?? defaultApiUrl(params.environment)).replace(/\/+$/, '');
17
+ this.transport = params.transport ?? fetchTransport;
18
+ }
19
+ /**
20
+ * `POST /v1/account/paradigm/enable`: provisions the token's account on
21
+ * Paradigm, the RFQ venue, and registers a Paradigm delegation subkey on
22
+ * it, which counts against the account's subkey limit. Idempotent: once
23
+ * enabled, a second call returns the same state.
24
+ *
25
+ * Only the account owner's main-key JWT, as `token`, can enable it. A
26
+ * subkey or session token only reads the state back once it is enabled,
27
+ * and gets 403 `UNAUTHORIZED_ERROR` before that; a session the server
28
+ * does not let use RFQ gets 403 `INVALID_TOKEN_SCOPE`. Other refusals:
29
+ * 400 `TOKEN_LIMIT_REACHED` when the account has no room for the subkey,
30
+ * 400 `REQUEST_NOT_ALLOWED` when Paradigm refuses the account, 409
31
+ * `SUBKEY_REVOKED` when the new delegation subkey is already revoked, and
32
+ * `NOT_ONBOARDED` while the account is still deploying. The call can take
33
+ * up to 30 s; a slow one ends as a retryable 503 `SERVICE_UNAVAILABLE`,
34
+ * and calling again resumes it.
35
+ */
36
+ async enable(token) {
37
+ const response = await this.transport({
38
+ method: 'POST',
39
+ url: `${this.apiUrl}${RFQ_ENABLE_PATH}`,
40
+ headers: bearer(token),
41
+ });
42
+ if (response.status < 200 || response.status >= 300) {
43
+ throw new SessionApiError(response.status, response.body);
44
+ }
45
+ const body = response.body;
46
+ if (body == null ||
47
+ typeof body !== 'object' ||
48
+ typeof body.account !== 'string' ||
49
+ body.status !== 'ENABLED') {
50
+ throw new SessionApiError(response.status, {
51
+ error: 'INVALID_RESPONSE',
52
+ message: `POST ${RFQ_ENABLE_PATH} returned no enabled account`,
53
+ });
54
+ }
55
+ return {
56
+ account: body.account,
57
+ status: 'ENABLED',
58
+ ...(typeof body.subkey_public_key === 'string' &&
59
+ body.subkey_public_key !== ''
60
+ ? { subkey_public_key: body.subkey_public_key }
61
+ : {}),
62
+ };
63
+ }
64
+ }
package/dist/sbe.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Reads the binary (SBE) messages the websocket sends and turns each into
3
+ * the object the JSON feed sends for it: the API's snake_case names,
4
+ * decimals as strings, times in milliseconds.
5
+ *
6
+ * A message's header gives the length of its fixed part, and the reader
7
+ * goes by that, so fields a newer server adds at the end are skipped and
8
+ * fields an older one lacks read as missing.
9
+ */
10
+ /** A message that could not be read. */
11
+ export declare class SbeDecodeError extends Error {
12
+ constructor(message: string);
13
+ }
14
+ export interface SbeMessage {
15
+ /** The channel's first part, such as `orders` in `orders.ALL`. */
16
+ readonly base: string;
17
+ /** The market it is about; `undefined` for account messages. */
18
+ readonly market: string | undefined;
19
+ readonly data: Readonly<Record<string, unknown>>;
20
+ }
21
+ /** `url` asking the server for messages this decoder reads. */
22
+ export declare function withSbeParams(url: string): string;
23
+ /** The bytes of a websocket message, or `undefined` for a text message. */
24
+ export declare function binaryFrame(data: unknown): Uint8Array | undefined;
25
+ /** Whether `bytes` is a binary message rather than text sent as bytes. */
26
+ export declare function isSbeFrame(bytes: Uint8Array): boolean;
27
+ /**
28
+ * Reads one message; `undefined` for a control message.
29
+ *
30
+ * @throws SbeDecodeError if it is malformed or of a type not known here.
31
+ */
32
+ export declare function decodeSbe(bytes: Uint8Array): SbeMessage | undefined;
33
+ /** The channel the server is asked for to serve `channel`. */
34
+ export declare function subscriptionChannel(channel: string): string;
35
+ /**
36
+ * Whether a text message the server sent on `sent` is one that `channel`
37
+ * delivers: the same channel, or the shared `.ALL` channel serving it with
38
+ * a matching market.
39
+ */
40
+ export declare function channelDeliversText(channel: string, sent: string, data: unknown): boolean;
41
+ /** Whether `message` is one that `channel` delivers. */
42
+ export declare function channelDelivers(channel: string, message: SbeMessage): boolean;
43
+ /**
44
+ * Whether the messages of two channels can't be told apart on one
45
+ * connection: binary ones that share a market.
46
+ */
47
+ export declare function channelsOverlap(a: string, b: string): boolean;