@paradex/sdk 0.8.1 → 0.10.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/dist/account.js CHANGED
@@ -1,6 +1,7 @@
1
- import { keyDerivation } from '@starkware-industries/starkware-crypto-utils';
2
1
  import * as Starknet from 'starknet';
2
+ import { DeterminismGuardError, hasContractCode, publicKeyForms, } from './determinism-guard.js';
3
3
  import * as ethereumSigner from './ethereum-signer.js';
4
+ import * as keyDerivation from './key-derivation.js';
4
5
  import * as starknetSigner from './starknet-signer.js';
5
6
  /**
6
7
  * Derives Paradex account credentials from an Ethereum wallet.
@@ -8,7 +9,15 @@ import * as starknetSigner from './starknet-signer.js';
8
9
  * @internal
9
10
  * @returns The account address and private key.
10
11
  */
11
- export async function deriveFromEthSigner({ config, signer, }) {
12
+ export async function deriveFromEthSigner({ config, signer, serverDeriveAddress, apiUrl, determinismGuard, }) {
13
+ if (determinismGuard != null && determinismGuard !== false) {
14
+ return await deriveFromEthSignerGuarded({
15
+ config,
16
+ signer,
17
+ apiUrl,
18
+ options: determinismGuard === true ? {} : determinismGuard,
19
+ });
20
+ }
12
21
  const starkKeyTypedData = ethereumSigner.buildEthereumStarkKeyTypedData(config.ethereumChainId);
13
22
  const seed = await signer.signTypedData(starkKeyTypedData);
14
23
  const additionalSeed = await signer.signTypedData(starkKeyTypedData);
@@ -16,23 +25,163 @@ export async function deriveFromEthSigner({ config, signer, }) {
16
25
  throw new Error('Wallet does not support deterministic signing. Please use different wallet.');
17
26
  const privateKey = keyDerivation.getPrivateKeyFromEthSignature(seed);
18
27
  const publicKey = keyDerivation.privateToStarkKey(privateKey);
19
- const address = generateAccountAddress({
28
+ const address = await resolveAccountAddress({
29
+ config,
20
30
  publicKey: `0x${publicKey}`,
21
- accountClassHash: config.paraclearAccountHash,
22
- accountProxyClassHash: config.paraclearAccountProxyHash,
31
+ serverDeriveAddress,
32
+ apiUrl,
23
33
  });
24
34
  return {
25
35
  address,
26
36
  privateKey: `0x${privateKey}`,
27
37
  };
28
38
  }
39
+ const NON_DETERMINISTIC_MESSAGE = 'Wallet does not support deterministic signing. Please use different wallet.';
40
+ /**
41
+ * Derives the key from one signature and accepts it when an account already
42
+ * holds it. When none does, refuses a wallet that already owns an account
43
+ * (its key would differ from the stored one), and otherwise asks for a
44
+ * second signature to test determinism before a new account is created.
45
+ *
46
+ * Every lookup failure throws, so a guarded derivation never returns
47
+ * credentials for an account it could not check.
48
+ */
49
+ async function deriveFromEthSignerGuarded({ config, signer, apiUrl, options, }) {
50
+ const resolvedApiUrl = apiUrl ?? config.paradexApiUrl;
51
+ if (resolvedApiUrl == null || resolvedApiUrl === '') {
52
+ throw new DeterminismGuardError('invalid_options', 'determinismGuard requires an API URL: pass apiUrl or use a config from Config.fetch()');
53
+ }
54
+ const walletAddressAsGiven = await resolveWalletAddress(signer, options);
55
+ const walletAddress = walletAddressAsGiven.toLowerCase();
56
+ if (options.contractCodeCheck !== false) {
57
+ const signerGetCode = signer.getCode;
58
+ const providers = options.codeProviders ??
59
+ (signerGetCode != null
60
+ ? [
61
+ {
62
+ getCode: async (a) => await signerGetCode.call(signer, a),
63
+ },
64
+ ]
65
+ : []);
66
+ if (providers.length === 0) {
67
+ throw new DeterminismGuardError('invalid_options', 'determinismGuard needs a provider to check the wallet for contract code: ' +
68
+ 'pass codeProviders, use a signer with a provider, or set contractCodeCheck: false');
69
+ }
70
+ if (await hasContractCode(walletAddress, providers, options.contractCodeTimeoutMs)) {
71
+ throw new DeterminismGuardError('contract_wallet', 'This wallet is a smart contract wallet, which cannot derive a Paradex key. ' +
72
+ 'Use a regular wallet (EOA).');
73
+ }
74
+ }
75
+ const starkKeyTypedData = ethereumSigner.buildEthereumStarkKeyTypedData(config.ethereumChainId);
76
+ const seed = await signer.signTypedData(starkKeyTypedData);
77
+ const privateKey = keyDerivation.getPrivateKeyFromEthSignature(seed);
78
+ const publicKey = `0x${keyDerivation.privateToStarkKey(privateKey)}`;
79
+ let byKey;
80
+ for (const candidate of publicKeyForms(publicKey)) {
81
+ const result = await guardedLookup({
82
+ apiUrl: resolvedApiUrl,
83
+ publicKey: candidate,
84
+ });
85
+ if (!result.ok)
86
+ throw lookupFailed(result);
87
+ if (result.info.exists) {
88
+ return await accept({
89
+ kind: 'existing',
90
+ signatures: 1,
91
+ walletAddress,
92
+ address: result.info.address,
93
+ publicKey,
94
+ privateKey,
95
+ options,
96
+ });
97
+ }
98
+ byKey ?? (byKey = result.info);
99
+ }
100
+ if (byKey == null) {
101
+ throw new DeterminismGuardError('lookup_failed', 'No public key to look up');
102
+ }
103
+ const byWallet = await guardedLookup({
104
+ apiUrl: resolvedApiUrl,
105
+ ethAddress: walletAddressAsGiven,
106
+ });
107
+ if (byWallet.ok &&
108
+ byWallet.info.exists &&
109
+ byWallet.info.accountSignerType === 'eip191') {
110
+ throw new DeterminismGuardError('evm_owned_account', 'This wallet owns an EVM-owned Paradex account, which is used through ' +
111
+ 'a session (SessionConnector), not a derived key. Do not onboard a new account.');
112
+ }
113
+ // 400: the wallet is already linked to an account of another signer type,
114
+ // which for a wallet deriving a Stark key is its Stark account.
115
+ if ((byWallet.ok && byWallet.info.exists) ||
116
+ (!byWallet.ok && byWallet.status === 400)) {
117
+ throw new DeterminismGuardError('key_mismatch', 'This wallet already has a Paradex account, but the key it derived does not match ' +
118
+ "the account's key. The wallet may not sign deterministically. Do not onboard a new account.");
119
+ }
120
+ if (!byWallet.ok)
121
+ throw lookupFailed(byWallet);
122
+ const additionalSeed = await signer.signTypedData(starkKeyTypedData);
123
+ if (seed !== additionalSeed) {
124
+ throw new DeterminismGuardError('non_deterministic', NON_DETERMINISTIC_MESSAGE);
125
+ }
126
+ return await accept({
127
+ kind: 'new',
128
+ signatures: 2,
129
+ walletAddress,
130
+ address: byKey.address,
131
+ publicKey,
132
+ privateKey,
133
+ options,
134
+ });
135
+ }
136
+ async function resolveWalletAddress(signer, options) {
137
+ const signerAddress = signer.getAddress != null ? await signer.getAddress() : undefined;
138
+ if (options.walletAddress != null &&
139
+ signerAddress != null &&
140
+ options.walletAddress.toLowerCase() !== signerAddress.toLowerCase()) {
141
+ throw new DeterminismGuardError('invalid_options', 'walletAddress does not match the address the signer reports');
142
+ }
143
+ const address = options.walletAddress ?? signerAddress;
144
+ if (address == null) {
145
+ throw new DeterminismGuardError('invalid_options', 'determinismGuard needs the wallet address: pass walletAddress or use a signer with getAddress');
146
+ }
147
+ if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
148
+ throw new DeterminismGuardError('invalid_options', 'walletAddress must be a 0x-prefixed 20-byte address');
149
+ }
150
+ return address;
151
+ }
152
+ function lookupFailed(result) {
153
+ return new DeterminismGuardError('lookup_failed', `Paradex onboarding lookup failed: ${result.statusText} ${result.status}` +
154
+ (result.detail != null ? ` (${result.detail})` : ''));
155
+ }
156
+ /**
157
+ * `requestOnboarding` with network and response-parsing errors turned into
158
+ * `lookup_failed`, so every failed lookup surfaces as a guard error.
159
+ */
160
+ async function guardedLookup(params) {
161
+ try {
162
+ return await requestOnboarding(params);
163
+ }
164
+ catch (error) {
165
+ throw new DeterminismGuardError('lookup_failed', `Paradex onboarding lookup failed: ${error instanceof Error ? error.message : String(error)}`);
166
+ }
167
+ }
168
+ async function accept({ privateKey, options, ...result }) {
169
+ await options.onResult?.(result);
170
+ return { address: result.address, privateKey: `0x${privateKey}` };
171
+ }
29
172
  /**
30
173
  * Generates a Paradex account from an Ethereum wallet.
31
174
  * @deprecated Use deriveFromEthSigner() and pass credentials to DefaultProvider constructor
32
175
  * @returns The generated Paradex account.
33
176
  */
34
- export async function fromEthSigner({ provider, config, signer, }) {
35
- const credentials = await deriveFromEthSigner({ config, signer });
177
+ export async function fromEthSigner({ provider, config, signer, serverDeriveAddress, apiUrl, determinismGuard, }) {
178
+ const credentials = await deriveFromEthSigner({
179
+ config,
180
+ signer,
181
+ serverDeriveAddress,
182
+ apiUrl,
183
+ determinismGuard,
184
+ });
36
185
  return new Starknet.Account({
37
186
  provider,
38
187
  address: credentials.address,
@@ -45,7 +194,7 @@ export async function fromEthSigner({ provider, config, signer, }) {
45
194
  * @internal
46
195
  * @returns The account address and private key.
47
196
  */
48
- export async function deriveFromStarknetAccount({ config, account, starknetProvider, rpcUrl, }) {
197
+ export async function deriveFromStarknetAccount({ config, account, starknetProvider, rpcUrl, serverDeriveAddress, apiUrl, }) {
49
198
  const starkKeyTypedData = starknetSigner.buildStarknetStarkKeyTypedData(config.starknetChainId);
50
199
  const provider = starknetProvider ??
51
200
  (rpcUrl != null
@@ -58,10 +207,11 @@ export async function deriveFromStarknetAccount({ config, account, starknetProvi
58
207
  throw new Error('Wallet does not support deterministic signing. Please use different wallet.');
59
208
  const seed = accountSupport.getSeedFromSignature(signature);
60
209
  const [privateKey, publicKey] = await starknetSigner.getStarkKeypairFromStarknetSignature(seed);
61
- const address = generateAccountAddress({
210
+ const address = await resolveAccountAddress({
211
+ config,
62
212
  publicKey: `0x${publicKey}`,
63
- accountClassHash: config.paraclearAccountHash,
64
- accountProxyClassHash: config.paraclearAccountProxyHash,
213
+ serverDeriveAddress,
214
+ apiUrl,
65
215
  });
66
216
  return {
67
217
  address,
@@ -73,12 +223,14 @@ export async function deriveFromStarknetAccount({ config, account, starknetProvi
73
223
  * @deprecated Use deriveFromStarknetAccount() and pass credentials to DefaultProvider constructor
74
224
  * @returns The generated Paradex account.
75
225
  */
76
- export async function fromStarknetAccount({ provider, config, account, starknetProvider, rpcUrl, }) {
226
+ export async function fromStarknetAccount({ provider, config, account, starknetProvider, rpcUrl, serverDeriveAddress, apiUrl, }) {
77
227
  const credentials = await deriveFromStarknetAccount({
78
228
  config,
79
229
  account,
80
230
  starknetProvider,
81
231
  rpcUrl,
232
+ serverDeriveAddress,
233
+ apiUrl,
82
234
  });
83
235
  return new Starknet.Account({
84
236
  provider,
@@ -86,6 +238,140 @@ export async function fromStarknetAccount({ provider, config, account, starknetP
86
238
  signer: credentials.privateKey,
87
239
  });
88
240
  }
241
+ /**
242
+ * Fetches the account address and onboarding status for a Starknet public key,
243
+ * or for the wallet of an EVM-owned account, from the Paradex API. Public
244
+ * endpoint, no authentication required.
245
+ */
246
+ export async function fetchOnboarding(params) {
247
+ const result = await requestOnboarding(params);
248
+ if (!result.ok) {
249
+ throw new Error(`Failed to fetch Paradex onboarding info: ${result.statusText} ${result.status}` +
250
+ (result.detail != null ? ` (${result.detail})` : ''));
251
+ }
252
+ return result.info;
253
+ }
254
+ /**
255
+ * `GET /onboarding`, returning the HTTP status of a failed lookup instead of
256
+ * throwing, so a caller can act on a specific status.
257
+ */
258
+ async function requestOnboarding(params) {
259
+ const { apiUrl } = params;
260
+ let query;
261
+ if (params.ethAddress != null) {
262
+ if (!/^0x[0-9a-fA-F]{40}$/.test(params.ethAddress)) {
263
+ throw new Error('ethAddress must be a 0x-prefixed 20-byte address');
264
+ }
265
+ query = new URLSearchParams({
266
+ account_signer_type: 'eip191',
267
+ eth_address: params.ethAddress,
268
+ });
269
+ }
270
+ else {
271
+ query = new URLSearchParams({
272
+ account_signer_type: 'starknet',
273
+ public_key: params.publicKey,
274
+ });
275
+ }
276
+ const resp = await fetch(`${apiUrl.replace(/\/+$/, '')}/onboarding?${query.toString()}`);
277
+ if (!resp.ok) {
278
+ const detail = await readErrorMessage(resp);
279
+ return {
280
+ ok: false,
281
+ status: resp.status,
282
+ statusText: resp.statusText,
283
+ ...(detail != null ? { detail } : {}),
284
+ };
285
+ }
286
+ const raw = (await resp.json());
287
+ if (typeof raw.address !== 'string' || !raw.address.startsWith('0x')) {
288
+ throw new Error('Paradex onboarding response is missing the address');
289
+ }
290
+ return {
291
+ ok: true,
292
+ info: {
293
+ address: raw.address,
294
+ exists: raw.exists === true,
295
+ accountSignerType: raw.account_signer_type ?? 'starknet',
296
+ ...(raw.derivation_info != null
297
+ ? {
298
+ derivationInfo: {
299
+ classHash: raw.derivation_info.class_hash,
300
+ ...(raw.derivation_info.proxy_class_hash != null
301
+ ? { proxyClassHash: raw.derivation_info.proxy_class_hash }
302
+ : {}),
303
+ },
304
+ }
305
+ : {}),
306
+ },
307
+ };
308
+ }
309
+ /**
310
+ * Returns the `message` field of a Paradex API error body, if there is one.
311
+ */
312
+ async function readErrorMessage(resp) {
313
+ try {
314
+ const body = (await resp.json());
315
+ return typeof body.message === 'string' && body.message !== ''
316
+ ? body.message
317
+ : undefined;
318
+ }
319
+ catch {
320
+ return undefined;
321
+ }
322
+ }
323
+ /**
324
+ * Resolves the account address from the Paradex API, or locally when
325
+ * `serverDeriveAddress` is false. A failed request throws: it never falls
326
+ * back to the local address, which can belong to a different account.
327
+ */
328
+ async function resolveAccountAddress({ config, publicKey, serverDeriveAddress = true, apiUrl, }) {
329
+ if (!serverDeriveAddress) {
330
+ return generateAccountAddress({
331
+ publicKey,
332
+ accountClassHash: config.paraclearAccountHash,
333
+ accountProxyClassHash: config.paraclearAccountProxyHash,
334
+ });
335
+ }
336
+ const resolvedApiUrl = apiUrl ?? config.paradexApiUrl;
337
+ if (resolvedApiUrl == null || resolvedApiUrl === '') {
338
+ throw new Error('The account address comes from the Paradex API, which needs an API URL: ' +
339
+ 'pass apiUrl or use a config from Config.fetch(). ' +
340
+ OPT_OUT_HINT);
341
+ }
342
+ // The API matches keys as written, so an account stored under the
343
+ // zero-padded key reads as missing when looked up unpadded. Use the first
344
+ // form that has an account; for a new key, the unpadded form's address.
345
+ let info;
346
+ for (const candidate of publicKeyForms(publicKey)) {
347
+ let result;
348
+ try {
349
+ result = await fetchOnboarding({
350
+ apiUrl: resolvedApiUrl,
351
+ publicKey: candidate,
352
+ });
353
+ }
354
+ catch (error) {
355
+ const reason = error instanceof Error ? error.message : String(error);
356
+ throw Object.assign(new Error(`Could not fetch the account address from GET /onboarding: ${reason}. ` +
357
+ `Retry. ${OPT_OUT_HINT}`), { cause: error });
358
+ }
359
+ if (result.exists) {
360
+ info = result;
361
+ break;
362
+ }
363
+ info ?? (info = result);
364
+ }
365
+ if (info == null) {
366
+ throw new Error('No public key to look up');
367
+ }
368
+ if (!/^0x[0-9a-fA-F]{1,64}$/.test(info.address)) {
369
+ throw new Error(`GET /onboarding returned an invalid account address: ${info.address}`);
370
+ }
371
+ return info.address;
372
+ }
373
+ const OPT_OUT_HINT = 'Pass serverDeriveAddress: false only if local derivation is right for ' +
374
+ 'this account (only accounts created with the legacy proxy class).';
89
375
  /**
90
376
  * Generates an account address based on the account contract and public key.
91
377
  */
package/dist/client.d.ts CHANGED
@@ -1,12 +1,20 @@
1
1
  import type * as Starknet from 'starknet';
2
+ import { type AddressDerivationOptions } from './account.js';
2
3
  import type { ParadexConfig } from './config.js';
4
+ import type { DeterminismGuardOptions } from './determinism-guard.js';
3
5
  import type { EthereumSigner } from './ethereum-signer.js';
4
6
  import { DefaultProvider } from './paraclear-provider.js';
5
- export interface CreateClientFromEthSignerParams {
7
+ export interface CreateClientFromEthSignerParams extends AddressDerivationOptions {
6
8
  readonly config: ParadexConfig;
7
9
  readonly signer: EthereumSigner;
10
+ /**
11
+ * Check the derived key against the wallet's existing account, and refuse
12
+ * contract wallets. See `DeterminismGuardOptions`.
13
+ * @experimental
14
+ */
15
+ readonly determinismGuard?: boolean | DeterminismGuardOptions;
8
16
  }
9
- export interface CreateClientFromStarknetAccountParams {
17
+ export interface CreateClientFromStarknetAccountParams extends AddressDerivationOptions {
10
18
  readonly config: ParadexConfig;
11
19
  readonly account: Starknet.AccountInterface;
12
20
  readonly starknetProvider?: Starknet.ProviderInterface;
@@ -41,11 +49,11 @@ export declare class ParadexClient {
41
49
  /**
42
50
  * Create a Paradex client from an Ethereum signer
43
51
  */
44
- static createFromEthSigner({ config, signer, }: CreateClientFromEthSignerParams): Promise<ParadexClient>;
52
+ static createFromEthSigner({ config, signer, serverDeriveAddress, apiUrl, determinismGuard, }: CreateClientFromEthSignerParams): Promise<ParadexClient>;
45
53
  /**
46
54
  * Create a Paradex client from a Starknet account
47
55
  */
48
- static createFromStarknetAccount({ config, account, starknetProvider, rpcUrl, }: CreateClientFromStarknetAccountParams): Promise<ParadexClient>;
56
+ static createFromStarknetAccount({ config, account, starknetProvider, rpcUrl, serverDeriveAddress, apiUrl, }: CreateClientFromStarknetAccountParams): Promise<ParadexClient>;
49
57
  /**
50
58
  * Get maximum withdrawable amount (includes balance and accounts for socialized loss)
51
59
  */
package/dist/client.js CHANGED
@@ -13,9 +13,15 @@ export class ParadexClient {
13
13
  /**
14
14
  * Create a Paradex client from an Ethereum signer
15
15
  */
16
- static async createFromEthSigner({ config, signer, }) {
16
+ static async createFromEthSigner({ config, signer, serverDeriveAddress, apiUrl, determinismGuard, }) {
17
17
  // Derive credentials internally (privateKey never exposed)
18
- const credentials = await deriveFromEthSigner({ config, signer });
18
+ const credentials = await deriveFromEthSigner({
19
+ config,
20
+ signer,
21
+ serverDeriveAddress,
22
+ apiUrl,
23
+ determinismGuard,
24
+ });
19
25
  // Create authenticated provider
20
26
  const provider = new DefaultProvider(config, credentials);
21
27
  // Get the account from provider
@@ -28,13 +34,15 @@ export class ParadexClient {
28
34
  /**
29
35
  * Create a Paradex client from a Starknet account
30
36
  */
31
- static async createFromStarknetAccount({ config, account, starknetProvider, rpcUrl, }) {
37
+ static async createFromStarknetAccount({ config, account, starknetProvider, rpcUrl, serverDeriveAddress, apiUrl, }) {
32
38
  // Derive credentials internally (privateKey never exposed)
33
39
  const credentials = await deriveFromStarknetAccount({
34
40
  config,
35
41
  account,
36
42
  starknetProvider,
37
43
  rpcUrl,
44
+ serverDeriveAddress,
45
+ apiUrl,
38
46
  });
39
47
  // Create authenticated provider
40
48
  const provider = new DefaultProvider(config, credentials);
package/dist/config.d.ts CHANGED
@@ -42,12 +42,18 @@ export interface ParadexConfig {
42
42
  readonly paraclearAddress: Hex;
43
43
  readonly paraclearDecimals: number;
44
44
  readonly bridgedTokens: Record<string, BridgedTokenConfig>;
45
+ /**
46
+ * Base URL of the Paradex REST API (e.g. `https://api.testnet.paradex.trade/v1`).
47
+ * Set by `fetchConfig`; used when deriving the account address via the API.
48
+ */
49
+ readonly paradexApiUrl?: string;
45
50
  }
46
- type ParadexEnvironment = 'testnet' | 'prod';
51
+ declare const PARADEX_ENVIRONMENTS: readonly ["prod", "testnet", "nightly"];
52
+ type ParadexEnvironment = (typeof PARADEX_ENVIRONMENTS)[number];
47
53
  /**
48
54
  * Fetches the Paradex config for the given environment.
49
55
  * This is required for account derivation.
50
56
  */
51
57
  export declare function fetchConfig(environment: ParadexEnvironment): Promise<ParadexConfig>;
52
- export declare function buildConfig(rawConfig: RawParadexConfig): ParadexConfig;
58
+ export declare function buildConfig(rawConfig: RawParadexConfig, paradexApiUrl?: string): ParadexConfig;
53
59
  export {};
package/dist/config.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ETHEREUM_MAINNET_CHAIN_ID, ETHEREUM_TESTNET_CHAIN_ID, STARKNET_MAINNET_CHAIN_ID, STARKNET_TESTNET_CHAIN_ID, } from './constants.js';
2
+ const PARADEX_ENVIRONMENTS = ['prod', 'testnet', 'nightly'];
2
3
  /**
3
4
  * Fetches the Paradex config for the given environment.
4
5
  * This is required for account derivation.
@@ -12,17 +13,17 @@ export async function fetchConfig(environment) {
12
13
  }
13
14
  const jsonResp = await resp.json();
14
15
  const config = jsonResp;
15
- return buildConfig(config);
16
+ return buildConfig(config, apiUrl);
16
17
  }
17
18
  function assertParadexEnvironment(environment) {
18
- if (environment !== 'testnet' && environment !== 'prod') {
19
+ if (!PARADEX_ENVIRONMENTS.includes(environment)) {
19
20
  throw new Error(`Invalid Paradex environment: ${environment}`);
20
21
  }
21
22
  }
22
23
  function getParadexApiUrl(environment) {
23
24
  return `https://api.${environment}.paradex.trade/v1`;
24
25
  }
25
- export function buildConfig(rawConfig) {
26
+ export function buildConfig(rawConfig, paradexApiUrl) {
26
27
  const bridgedTokens = Object.fromEntries(rawConfig.bridged_tokens.map((token) => [
27
28
  token.symbol,
28
29
  {
@@ -45,6 +46,7 @@ export function buildConfig(rawConfig) {
45
46
  paraclearAddress: rawConfig.paraclear_address,
46
47
  paraclearDecimals: rawConfig.paraclear_decimals,
47
48
  bridgedTokens,
49
+ ...(paradexApiUrl != null ? { paradexApiUrl } : {}),
48
50
  };
49
51
  }
50
52
  function getStarknetChainId(rawConfig) {
@@ -0,0 +1,102 @@
1
+ import type { Hex } from './types.js';
2
+ /** A code lookup that answers no faster than this counts as no code. */
3
+ export declare const DEFAULT_CONTRACT_CODE_TIMEOUT_MS = 3000;
4
+ /**
5
+ * Anything that can read an address's bytecode, such as an ethers
6
+ * `Provider`. Pass one per chain the wallet might be a contract on.
7
+ */
8
+ export interface EthCodeProvider {
9
+ readonly getCode: (address: string) => Promise<string>;
10
+ }
11
+ /**
12
+ * Options for the determinism guard on `deriveFromEthSigner`.
13
+ * @experimental
14
+ */
15
+ export interface DeterminismGuardOptions {
16
+ /**
17
+ * The wallet address that signs. Defaults to `signer.getAddress()`; when
18
+ * both are known they must match.
19
+ */
20
+ readonly walletAddress?: string;
21
+ /**
22
+ * Providers to look the wallet's bytecode up on, one per chain. Defaults to
23
+ * the signer's own provider (`signer.getCode`). The guard refuses a wallet
24
+ * with contract code on any of them; an EIP-7702 delegation counts as an
25
+ * EOA.
26
+ */
27
+ readonly codeProviders?: readonly EthCodeProvider[];
28
+ /**
29
+ * Set to false to skip the contract code check, for example for a local
30
+ * private-key wallet with no provider. Defaults to true.
31
+ */
32
+ readonly contractCodeCheck?: boolean;
33
+ /**
34
+ * How long to wait for each code lookup. A lookup that fails or times out
35
+ * counts as no code, so a provider outage never locks out an EOA. Defaults
36
+ * to 3000 ms.
37
+ */
38
+ readonly contractCodeTimeoutMs?: number;
39
+ /**
40
+ * Called with the outcome once the key is accepted. A caller that keeps
41
+ * its own record of wallets that passed the two-signature test can store
42
+ * it from here; the SDK keeps no state between calls. A returned promise
43
+ * is awaited, and a rejection fails the derivation.
44
+ */
45
+ readonly onResult?: (result: DeterminismGuardResult) => unknown;
46
+ }
47
+ /**
48
+ * How the guard accepted the derived key.
49
+ * @experimental
50
+ */
51
+ export interface DeterminismGuardResult {
52
+ /**
53
+ * `existing`: an account already holds the derived key, which proves the
54
+ * wallet reproduced the signature the account was created from.
55
+ * `new`: no account holds the key and none is known for the wallet; the
56
+ * wallet signed twice and both signatures matched.
57
+ */
58
+ readonly kind: 'existing' | 'new';
59
+ /** Number of signatures requested from the wallet. */
60
+ readonly signatures: 1 | 2;
61
+ /** The wallet that signed, lowercased. */
62
+ readonly walletAddress: string;
63
+ /** The Paradex account address, as reported by the Paradex API. */
64
+ readonly address: Hex;
65
+ /** The derived Stark public key. */
66
+ readonly publicKey: Hex;
67
+ }
68
+ export type DeterminismGuardErrorCode =
69
+ /** The wallet address has contract code, so it cannot derive a key. */
70
+ 'contract_wallet'
71
+ /** The wallet already owns an account under a different key. */
72
+ | 'key_mismatch'
73
+ /** The wallet owns an EVM-owned account, which uses sessions, not a key. */
74
+ | 'evm_owned_account'
75
+ /** The wallet returned different signatures for the same message. */
76
+ | 'non_deterministic'
77
+ /** A Paradex API lookup failed; nothing was derived. */
78
+ | 'lookup_failed'
79
+ /** The guard is missing an input it needs (wallet address, API URL). */
80
+ | 'invalid_options';
81
+ /**
82
+ * Raised when the determinism guard refuses to derive a key. A refusal
83
+ * means the caller must not onboard an account with this wallet.
84
+ * @experimental
85
+ */
86
+ export declare class DeterminismGuardError extends Error {
87
+ readonly code: DeterminismGuardErrorCode;
88
+ constructor(code: DeterminismGuardErrorCode, message: string);
89
+ }
90
+ /** Whether `code` is a contract's bytecode, not an EOA or an EIP-7702 one. */
91
+ export declare function isContractCode(code: string | null | undefined): boolean;
92
+ /**
93
+ * Whether `address` holds contract code on any of `providers`. A provider
94
+ * that errors or does not answer within `timeoutMs` counts as no code.
95
+ */
96
+ export declare function hasContractCode(address: string, providers: readonly EthCodeProvider[], timeoutMs?: number): Promise<boolean>;
97
+ /**
98
+ * The key as most clients write it (unpadded), then zero-padded to 32 bytes
99
+ * if different. The API matches keys case-insensitively but as written, so
100
+ * an account stored with the padded form must not read as missing.
101
+ */
102
+ export declare function publicKeyForms(publicKey: Hex): Hex[];
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Bytecode prefix of an EIP-7702 delegation. An EOA that delegated still
3
+ * signs with its own key, so it derives a Stark key like any other EOA.
4
+ */
5
+ const EIP_7702_DELEGATION_PREFIX = '0xef0100';
6
+ /** A code lookup that answers no faster than this counts as no code. */
7
+ export const DEFAULT_CONTRACT_CODE_TIMEOUT_MS = 3000;
8
+ /**
9
+ * Raised when the determinism guard refuses to derive a key. A refusal
10
+ * means the caller must not onboard an account with this wallet.
11
+ * @experimental
12
+ */
13
+ export class DeterminismGuardError extends Error {
14
+ constructor(code, message) {
15
+ super(message);
16
+ this.name = 'DeterminismGuardError';
17
+ this.code = code;
18
+ }
19
+ }
20
+ /** Whether `code` is a contract's bytecode, not an EOA or an EIP-7702 one. */
21
+ export function isContractCode(code) {
22
+ if (code == null)
23
+ return false;
24
+ const normalized = code.toLowerCase();
25
+ if (normalized === '' || normalized === '0x')
26
+ return false;
27
+ return !normalized.startsWith(EIP_7702_DELEGATION_PREFIX);
28
+ }
29
+ /**
30
+ * Whether `address` holds contract code on any of `providers`. A provider
31
+ * that errors or does not answer within `timeoutMs` counts as no code.
32
+ */
33
+ export async function hasContractCode(address, providers, timeoutMs = DEFAULT_CONTRACT_CODE_TIMEOUT_MS) {
34
+ const results = await Promise.allSettled(providers.map(async (provider) => {
35
+ let timer;
36
+ try {
37
+ return await Promise.race([
38
+ provider.getCode(address),
39
+ new Promise((resolve) => {
40
+ timer = setTimeout(() => {
41
+ resolve(undefined);
42
+ }, timeoutMs);
43
+ }),
44
+ ]);
45
+ }
46
+ finally {
47
+ clearTimeout(timer);
48
+ }
49
+ }));
50
+ return results.some((result) => result.status === 'fulfilled' && isContractCode(result.value));
51
+ }
52
+ /**
53
+ * The key as most clients write it (unpadded), then zero-padded to 32 bytes
54
+ * if different. The API matches keys case-insensitively but as written, so
55
+ * an account stored with the padded form must not read as missing.
56
+ */
57
+ export function publicKeyForms(publicKey) {
58
+ const hex = publicKey.replace(/^0x/iu, '').replace(/^0+(?=.)/u, '');
59
+ const unpadded = `0x${hex}`;
60
+ const padded = `0x${hex.padStart(64, '0')}`;
61
+ return padded === unpadded ? [unpadded] : [unpadded, padded];
62
+ }