@paradex/sdk 0.7.0 → 0.8.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
@@ -1,31 +1,377 @@
1
1
  # Paradex SDK
2
2
 
3
- ## Install
3
+ Official JavaScript/TypeScript SDK for [Paradex](https://paradex.trade) - a decentralized perpetuals exchange built on Starknet.
4
4
 
5
- ```sh
6
- npm install --save @paradex/sdk
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @paradex/sdk
7
9
  ```
8
10
 
9
- ```sh
11
+ ```bash
10
12
  yarn add @paradex/sdk
11
13
  ```
12
14
 
15
+ ```bash
16
+ pnpm add @paradex/sdk
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ### Browser (MetaMask/Web3 Wallet)
22
+
23
+ ```typescript
24
+ import * as Paradex from '@paradex/sdk';
25
+ import { ethers } from 'ethers';
26
+
27
+ // 1. Fetch configuration for your environment
28
+ const config = await Paradex.Config.fetch('testnet'); // or 'mainnet'
29
+
30
+ // 2. Connect to user's wallet
31
+ const provider = new ethers.BrowserProvider(window.ethereum);
32
+ const ethersSigner = await provider.getSigner();
33
+ const signer = Paradex.Signer.fromEthers(ethersSigner);
34
+
35
+ // 3. Create Paradex client
36
+ const client = await Paradex.Client.fromEthSigner({ config, signer });
37
+
38
+ // 4. Use the client
39
+ console.log('Your Paradex address:', client.getAddress());
40
+ const balance = await client.getTokenBalance('USDC');
41
+ console.log('USDC Balance:', balance.size);
42
+ ```
43
+
44
+ ### Node.js (Private Key)
45
+
46
+ ```typescript
47
+ import * as Paradex from '@paradex/sdk';
48
+ import { ethers } from 'ethers';
49
+
50
+ // 1. Fetch configuration
51
+ const config = await Paradex.Config.fetch('testnet');
52
+
53
+ // 2. Create wallet from private key
54
+ const wallet = new ethers.Wallet(process.env.PRIVATE_KEY);
55
+ const signer = Paradex.Signer.fromEthers(wallet);
56
+
57
+ // 3. Create Paradex client
58
+ const client = await Paradex.Client.fromEthSigner({ config, signer });
59
+
60
+ // 4. Use the client
61
+ const balance = await client.getTokenBalance('USDC');
62
+ console.log('Balance:', balance.size);
63
+ ```
64
+
65
+ ## Core Concepts
66
+
67
+ ### Client
68
+
69
+ The `ParadexClient` is the main interface for interacting with Paradex. It handles authentication and provides a clean API for common operations.
70
+
71
+ ```typescript
72
+ // Create from Ethereum wallet
73
+ const client = await Paradex.Client.fromEthSigner({ config, signer });
74
+
75
+ // Create from Starknet account
76
+ const client = await Paradex.Client.fromStarknetAccount({
77
+ config,
78
+ account: starknetAccount,
79
+ starknetProvider: optionalProvider,
80
+ });
81
+ ```
82
+
83
+ ### Configuration
84
+
85
+ Fetch environment-specific configuration:
86
+
87
+ ```typescript
88
+ const config = await Paradex.Config.fetch('testnet'); // testnet, mainnet, or custom URL
89
+ ```
90
+
91
+ ## Common Operations
92
+
93
+ ### Get Token Balance
94
+
95
+ ```typescript
96
+ const balance = await client.getTokenBalance('USDC');
97
+ console.log(`Balance: ${balance.size} USDC`);
98
+ ```
99
+
100
+ ### Get Maximum Withdrawable Amount
101
+
102
+ ```typescript
103
+ const maxWithdraw = await client.getMaxWithdraw('USDC');
104
+ console.log(`Max withdrawable: ${maxWithdraw.amount} USDC`);
105
+ console.log(`Chain amount: ${maxWithdraw.amountChain}`);
106
+ ```
107
+
108
+ ### Check Socialized Loss Factor
109
+
110
+ ```typescript
111
+ const { socializedLossFactor } = await client.getSocializedLossFactor();
112
+ if (Number(socializedLossFactor) > 0) {
113
+ console.warn('Socialized loss is active');
114
+ }
115
+ ```
116
+
117
+ ### Calculate Receivable Amount
118
+
119
+ ```typescript
120
+ const receivable = await client.getReceivableAmount('USDC', '100');
121
+ console.log(`Requesting: 100 USDC`);
122
+ console.log(`Will receive: ${receivable.receivableAmount} USDC`);
123
+ console.log(`Loss factor: ${receivable.socializedLossFactor}`);
124
+ ```
125
+
126
+ ### Withdraw Tokens
127
+
128
+ ```typescript
129
+ // Simple withdrawal (no bridge call)
130
+ const result = await client.withdraw('USDC', '50', []);
131
+ console.log('Transaction hash:', result.hash);
132
+
133
+ // Wait for confirmation
134
+ await client.waitForTransaction(result.hash);
135
+ console.log('Withdrawal complete!');
136
+ ```
137
+
138
+ ### Withdraw with Bridge Call
139
+
140
+ ```typescript
141
+ // Calculate receivable amount first
142
+ const receivable = await client.getReceivableAmount('USDC', '100');
143
+
144
+ // Prepare bridge call with receivable amount
145
+ const bridgeCall = {
146
+ contractAddress: '0x...',
147
+ entrypoint: 'deposit',
148
+ calldata: ['...', receivable.receivableAmountChain],
149
+ };
150
+
151
+ // Execute withdrawal with bridge call
152
+ const result = await client.withdraw('USDC', '100', bridgeCall);
153
+ await client.waitForTransaction(result.hash);
154
+ ```
155
+
156
+ ## TypeScript Support
157
+
158
+ The SDK is written in TypeScript and provides full type definitions out of the box.
159
+
160
+ ```typescript
161
+ import type {
162
+ MaxWithdraw,
163
+ ParadexClient,
164
+ ParadexConfig,
165
+ ReceivableAmount,
166
+ TokenBalance,
167
+ WithdrawResult,
168
+ } from '@paradex/sdk';
169
+
170
+ // All types are fully typed and autocomplete-friendly
171
+ const balance: TokenBalance = await client.getTokenBalance('USDC');
172
+ ```
173
+
174
+ ## Error Handling
175
+
176
+ ```typescript
177
+ try {
178
+ const balance = await client.getTokenBalance('USDC');
179
+ console.log('Balance:', balance.size);
180
+ } catch (error) {
181
+ if (error instanceof Error) {
182
+ console.error('Failed to get balance:', error.message);
183
+ }
184
+ }
185
+ ```
186
+
187
+ ## Advanced Usage
188
+
189
+ ### Access Underlying Provider
190
+
191
+ ```typescript
192
+ const provider = client.getProvider();
193
+ // Access the authenticated RPC provider for advanced operations
194
+ ```
195
+
196
+ ### Get Account Address
197
+
198
+ ```typescript
199
+ const address = client.getAddress();
200
+ console.log('Your Paradex address:', address);
201
+ ```
202
+
203
+ ### Custom RPC Calls
204
+
205
+ ```typescript
206
+ const provider = client.getProvider();
207
+ const result = await provider.callContract({
208
+ contractAddress: '0x...',
209
+ entrypoint: 'get_balance',
210
+ calldata: ['0x123'],
211
+ });
212
+ ```
213
+
214
+ ## Best Practices
215
+
216
+ ### 1. Environment Variables
217
+
218
+ Store sensitive data in environment variables:
219
+
220
+ ```typescript
221
+ const privateKey = process.env.PRIVATE_KEY;
222
+ if (!privateKey) {
223
+ throw new Error('PRIVATE_KEY environment variable is required');
224
+ }
225
+ ```
226
+
227
+ ### 2. Error Handling
228
+
229
+ Always wrap SDK calls in try-catch blocks:
230
+
231
+ ```typescript
232
+ try {
233
+ const client = await Paradex.Client.fromEthSigner({ config, signer });
234
+ const balance = await client.getTokenBalance('USDC');
235
+ } catch (error) {
236
+ // Handle errors appropriately
237
+ console.error('SDK Error:', error);
238
+ }
239
+ ```
240
+
241
+ ### 3. Socialized Loss Checks
242
+
243
+ Always check for socialized loss before withdrawals:
244
+
245
+ ```typescript
246
+ const receivable = await client.getReceivableAmount('USDC', amount);
247
+ if (Number(receivable.socializedLossFactor) !== 0) {
248
+ // Warn user they will receive less than requested
249
+ console.warn(
250
+ `Due to socialized loss, you will receive ${receivable.receivableAmount} instead of ${amount}`,
251
+ );
252
+ }
253
+ ```
254
+
255
+ ### 4. Transaction Confirmations
256
+
257
+ Wait for transaction confirmations:
258
+
259
+ ```typescript
260
+ const result = await client.withdraw('USDC', '100', []);
261
+ console.log('Transaction submitted:', result.hash);
262
+
263
+ // Wait for confirmation
264
+ await client.waitForTransaction(result.hash);
265
+ console.log('Transaction confirmed!');
266
+ ```
267
+
268
+ ### 5. Type Safety
269
+
270
+ Leverage TypeScript for type safety:
271
+
272
+ ```typescript
273
+ import type { ParadexClient } from '@paradex/sdk';
274
+
275
+ function processBalance(client: ParadexClient, token: string): Promise<void> {
276
+ // TypeScript will ensure correct usage
277
+ return client.getTokenBalance(token).then((balance) => {
278
+ console.log(`${token} Balance:`, balance.size);
279
+ });
280
+ }
281
+ ```
282
+
283
+ ## Browser Usage Notes
284
+
285
+ To use the Paradex SDK in the browser, you'll need to configure your bundler to polyfill Node.js modules:
286
+
287
+ ### Webpack 5
288
+
289
+ ```javascript
290
+ // webpack.config.js
291
+ module.exports = {
292
+ resolve: {
293
+ fallback: {
294
+ buffer: require.resolve('buffer/'),
295
+ crypto: require.resolve('crypto-browserify'),
296
+ stream: require.resolve('stream-browserify'),
297
+ },
298
+ },
299
+ plugins: [
300
+ new webpack.ProvidePlugin({
301
+ Buffer: ['buffer', 'Buffer'],
302
+ process: 'process/browser',
303
+ }),
304
+ ],
305
+ };
306
+ ```
307
+
308
+ ### Vite
309
+
310
+ ```javascript
311
+ // vite.config.js
312
+ import { defineConfig } from 'vite';
313
+ import { nodePolyfills } from 'vite-plugin-node-polyfills';
314
+
315
+ export default defineConfig({
316
+ plugins: [nodePolyfills()],
317
+ define: {
318
+ 'process.env.NODE_DEBUG': JSON.stringify(''),
319
+ },
320
+ });
321
+ ```
322
+
13
323
  ## Examples
14
324
 
15
- - [React app](https://github.com/tradeparadex/paradex-react-example)
325
+ See the [examples](./examples) directory for complete working examples:
326
+
327
+ - **[account-ethereum.ts](./examples/account-ethereum.ts)** - Create client from Ethereum wallet
328
+ - **[account-starknet.ts](./examples/account-starknet.ts)** - Create client from Starknet account
329
+ - **[withdrawal-node.ts](./examples/withdrawal-node.ts)** - Complete withdrawal flow (Node.js)
330
+ - **[withdrawal.ts](./examples/withdrawal.ts)** - Complete withdrawal flow (Browser)
331
+
332
+ For a full React application example, see: [paradex-react-example](https://github.com/tradeparadex/paradex-react-example)
333
+
334
+ ## API Reference
16
335
 
17
- ## Notes on browser usage
336
+ ### Client Methods
18
337
 
19
- To use the Paradex SDK in the browser you will need to polyfill `Buffer` from node and define `process.env.NODE_DEBUG` to satisfy `@starkware-industries/starkware-crypto-utils`.
338
+ | Method | Description | Returns |
339
+ | ------------------------------------- | -------------------------------------- | ---------------------- |
340
+ | `getTokenBalance(token)` | Get token balance | `TokenBalance` |
341
+ | `getMaxWithdraw(token)` | Get maximum withdrawable amount | `MaxWithdraw` |
342
+ | `getSocializedLossFactor()` | Get current socialized loss factor | `SocializedLossFactor` |
343
+ | `getReceivableAmount(token, amount)` | Calculate amount after socialized loss | `ReceivableAmount` |
344
+ | `withdraw(token, amount, bridgeCall)` | Initiate withdrawal | `WithdrawResult` |
345
+ | `waitForTransaction(hash, options?)` | Wait for transaction confirmation | `TransactionReceipt` |
346
+ | `getAddress()` | Get account address | `string` |
347
+ | `getProvider()` | Get underlying provider | `DefaultProvider` |
20
348
 
21
- ## Get in touch
349
+ ### Configuration
22
350
 
23
- Have a feature to request or a bug to report?
351
+ | Method | Description | Returns |
352
+ | ------------------- | ----------------------------------- | --------------- |
353
+ | `Config.fetch(env)` | Fetch configuration for environment | `ParadexConfig` |
24
354
 
25
- Drop us a message on [Discord].
355
+ ### Signer
26
356
 
27
- [Discord]: https://discord.gg/paradex
357
+ | Method | Description | Returns |
358
+ | --------------------------- | ---------------------------- | ---------------- |
359
+ | `Signer.fromEthers(signer)` | Create signer from ethers.js | `EthereumSigner` |
360
+
361
+ ## Support
362
+
363
+ - **Discord:** [Join our Discord](https://discord.gg/paradex)
364
+ - **Documentation:** [docs.paradex.trade](https://docs.paradex.trade)
365
+ - **Issues:** [GitHub Issues](https://github.com/tradeparadex/paradex.js/issues)
366
+
367
+ ## License
368
+
369
+ MIT
28
370
 
29
371
  ## Warning
30
372
 
31
- ⚠️ `@paradex/sdk` is experimental and APIs are subject to change
373
+ ⚠️ **This SDK is in active development.** APIs may change between versions. Please check the changelog before upgrading.
374
+
375
+ ## Contributing
376
+
377
+ Contributions are welcome! Please read our contributing guidelines before submitting pull requests.
package/dist/account.d.ts CHANGED
@@ -1,8 +1,28 @@
1
1
  import * as Starknet from 'starknet';
2
2
  import type { ParadexConfig } from './config.js';
3
3
  import * as ethereumSigner from './ethereum-signer.js';
4
+ import type { Hex } from './types.js';
4
5
  export interface Account extends Starknet.Account {
5
6
  }
7
+ /**
8
+ * Account credentials (internal use only)
9
+ * @internal
10
+ */
11
+ export interface AccountCredentials {
12
+ readonly address: Hex;
13
+ readonly privateKey: Hex;
14
+ }
15
+ interface DeriveFromEthSignerParams {
16
+ readonly config: ParadexConfig;
17
+ readonly signer: ethereumSigner.EthereumSigner;
18
+ }
19
+ /**
20
+ * Derives Paradex account credentials from an Ethereum wallet.
21
+ * Internal use only - use ParadexClient.createFromEthSigner() instead.
22
+ * @internal
23
+ * @returns The account address and private key.
24
+ */
25
+ export declare function deriveFromEthSigner({ config, signer, }: DeriveFromEthSignerParams): Promise<AccountCredentials>;
6
26
  interface FromEthSignerParams {
7
27
  readonly provider: Starknet.ProviderOptions | Starknet.ProviderInterface;
8
28
  readonly config: ParadexConfig;
@@ -10,9 +30,22 @@ interface FromEthSignerParams {
10
30
  }
11
31
  /**
12
32
  * Generates a Paradex account from an Ethereum wallet.
33
+ * @deprecated Use deriveFromEthSigner() and pass credentials to DefaultProvider constructor
13
34
  * @returns The generated Paradex account.
14
35
  */
15
36
  export declare function fromEthSigner({ provider, config, signer, }: FromEthSignerParams): Promise<Account>;
37
+ interface DeriveFromStarknetAccountParams {
38
+ readonly config: ParadexConfig;
39
+ readonly account: Starknet.AccountInterface;
40
+ readonly starknetProvider?: Starknet.ProviderInterface;
41
+ }
42
+ /**
43
+ * Derives Paradex account credentials from a Starknet account.
44
+ * Internal use only - use ParadexClient.createFromStarknetAccount() instead.
45
+ * @internal
46
+ * @returns The account address and private key.
47
+ */
48
+ export declare function deriveFromStarknetAccount({ config, account, starknetProvider, }: DeriveFromStarknetAccountParams): Promise<AccountCredentials>;
16
49
  interface FromStarknetAccountParams {
17
50
  /** Paradex chain provider */
18
51
  readonly provider: Starknet.ProviderOptions | Starknet.ProviderInterface;
@@ -22,6 +55,7 @@ interface FromStarknetAccountParams {
22
55
  }
23
56
  /**
24
57
  * Generates a Paradex account from a Starknet signer.
58
+ * @deprecated Use deriveFromStarknetAccount() and pass credentials to DefaultProvider constructor
25
59
  * @returns The generated Paradex account.
26
60
  */
27
61
  export declare function fromStarknetAccount({ provider, config, account, starknetProvider, }: FromStarknetAccountParams): Promise<Account>;
package/dist/account.js CHANGED
@@ -3,10 +3,12 @@ import * as Starknet from 'starknet';
3
3
  import * as ethereumSigner from './ethereum-signer.js';
4
4
  import * as starknetSigner from './starknet-signer.js';
5
5
  /**
6
- * Generates a Paradex account from an Ethereum wallet.
7
- * @returns The generated Paradex account.
6
+ * Derives Paradex account credentials from an Ethereum wallet.
7
+ * Internal use only - use ParadexClient.createFromEthSigner() instead.
8
+ * @internal
9
+ * @returns The account address and private key.
8
10
  */
9
- export async function fromEthSigner({ provider, config, signer, }) {
11
+ export async function deriveFromEthSigner({ config, signer, }) {
10
12
  const starkKeyTypedData = ethereumSigner.buildEthereumStarkKeyTypedData(config.ethereumChainId);
11
13
  const seed = await signer.signTypedData(starkKeyTypedData);
12
14
  const additionalSeed = await signer.signTypedData(starkKeyTypedData);
@@ -19,13 +21,31 @@ export async function fromEthSigner({ provider, config, signer, }) {
19
21
  accountClassHash: config.paraclearAccountHash,
20
22
  accountProxyClassHash: config.paraclearAccountProxyHash,
21
23
  });
22
- return new Starknet.Account({ provider, address, signer: `0x${privateKey}` });
24
+ return {
25
+ address,
26
+ privateKey: `0x${privateKey}`,
27
+ };
23
28
  }
24
29
  /**
25
- * Generates a Paradex account from a Starknet signer.
30
+ * Generates a Paradex account from an Ethereum wallet.
31
+ * @deprecated Use deriveFromEthSigner() and pass credentials to DefaultProvider constructor
26
32
  * @returns The generated Paradex account.
27
33
  */
28
- export async function fromStarknetAccount({ provider, config, account, starknetProvider, }) {
34
+ export async function fromEthSigner({ provider, config, signer, }) {
35
+ const credentials = await deriveFromEthSigner({ config, signer });
36
+ return new Starknet.Account({
37
+ provider,
38
+ address: credentials.address,
39
+ signer: credentials.privateKey,
40
+ });
41
+ }
42
+ /**
43
+ * Derives Paradex account credentials from a Starknet account.
44
+ * Internal use only - use ParadexClient.createFromStarknetAccount() instead.
45
+ * @internal
46
+ * @returns The account address and private key.
47
+ */
48
+ export async function deriveFromStarknetAccount({ config, account, starknetProvider, }) {
29
49
  const starkKeyTypedData = starknetSigner.buildStarknetStarkKeyTypedData(config.starknetChainId);
30
50
  const accountSupport = await starknetSigner.getAccountSupport(account, starknetProvider ??
31
51
  starknetSigner.getPublicProvider(config.starknetChainId));
@@ -40,7 +60,27 @@ export async function fromStarknetAccount({ provider, config, account, starknetP
40
60
  accountClassHash: config.paraclearAccountHash,
41
61
  accountProxyClassHash: config.paraclearAccountProxyHash,
42
62
  });
43
- return new Starknet.Account({ provider, address, signer: `0x${privateKey}` });
63
+ return {
64
+ address,
65
+ privateKey: `0x${privateKey}`,
66
+ };
67
+ }
68
+ /**
69
+ * Generates a Paradex account from a Starknet signer.
70
+ * @deprecated Use deriveFromStarknetAccount() and pass credentials to DefaultProvider constructor
71
+ * @returns The generated Paradex account.
72
+ */
73
+ export async function fromStarknetAccount({ provider, config, account, starknetProvider, }) {
74
+ const credentials = await deriveFromStarknetAccount({
75
+ config,
76
+ account,
77
+ starknetProvider,
78
+ });
79
+ return new Starknet.Account({
80
+ provider,
81
+ address: credentials.address,
82
+ signer: credentials.privateKey,
83
+ });
44
84
  }
45
85
  /**
46
86
  * Generates an account address based on the account contract and public key.
@@ -0,0 +1,80 @@
1
+ import type * as Starknet from 'starknet';
2
+ import type { ParadexConfig } from './config.js';
3
+ import type { EthereumSigner } from './ethereum-signer.js';
4
+ import { DefaultProvider } from './paraclear-provider.js';
5
+ export interface CreateClientFromEthSignerParams {
6
+ readonly config: ParadexConfig;
7
+ readonly signer: EthereumSigner;
8
+ }
9
+ export interface CreateClientFromStarknetAccountParams {
10
+ readonly config: ParadexConfig;
11
+ readonly account: Starknet.AccountInterface;
12
+ readonly starknetProvider?: Starknet.ProviderInterface;
13
+ }
14
+ export interface TokenBalance {
15
+ readonly size: string;
16
+ }
17
+ export interface SocializedLossFactor {
18
+ readonly socializedLossFactor: string;
19
+ }
20
+ export interface ReceivableAmount {
21
+ readonly receivableAmount: string;
22
+ readonly receivableAmountChain: string;
23
+ readonly socializedLossFactor: string;
24
+ }
25
+ export interface MaxWithdraw {
26
+ readonly amount: string;
27
+ readonly amountChain: string;
28
+ }
29
+ export interface WithdrawResult {
30
+ readonly hash: string;
31
+ }
32
+ /**
33
+ * High-level Paradex client with clean interface
34
+ */
35
+ export declare class ParadexClient {
36
+ private readonly provider;
37
+ private readonly config;
38
+ private readonly account;
39
+ private constructor();
40
+ /**
41
+ * Create a Paradex client from an Ethereum signer
42
+ */
43
+ static createFromEthSigner({ config, signer, }: CreateClientFromEthSignerParams): Promise<ParadexClient>;
44
+ /**
45
+ * Create a Paradex client from a Starknet account
46
+ */
47
+ static createFromStarknetAccount({ config, account, starknetProvider, }: CreateClientFromStarknetAccountParams): Promise<ParadexClient>;
48
+ /**
49
+ * Get maximum withdrawable amount (includes balance and accounts for socialized loss)
50
+ */
51
+ getMaxWithdraw(token: string): Promise<MaxWithdraw>;
52
+ /**
53
+ * Get token balance
54
+ */
55
+ getTokenBalance(token: string): Promise<TokenBalance>;
56
+ /**
57
+ * Get socialized loss factor
58
+ */
59
+ getSocializedLossFactor(): Promise<SocializedLossFactor>;
60
+ /**
61
+ * Get receivable amount after applying socialized loss
62
+ */
63
+ getReceivableAmount(token: string, amount: string): Promise<ReceivableAmount>;
64
+ /**
65
+ * Withdraw tokens
66
+ */
67
+ withdraw(token: string, amount: string, bridgeCall: Starknet.Call | readonly Starknet.Call[]): Promise<WithdrawResult>;
68
+ /**
69
+ * Wait for transaction to complete
70
+ */
71
+ waitForTransaction(txHash: string, options?: Starknet.waitForTransactionOptions): Promise<Starknet.GetTransactionReceiptResponse>;
72
+ /**
73
+ * Get the account address (public key, safe to expose)
74
+ */
75
+ getAddress(): string;
76
+ /**
77
+ * Get the underlying provider (for advanced use cases)
78
+ */
79
+ getProvider(): DefaultProvider;
80
+ }
package/dist/client.js ADDED
@@ -0,0 +1,119 @@
1
+ import { deriveFromEthSigner, deriveFromStarknetAccount, } from './account.js';
2
+ import { DefaultProvider } from './paraclear-provider.js';
3
+ import * as Paraclear from './paraclear.js';
4
+ /**
5
+ * High-level Paradex client with clean interface
6
+ */
7
+ export class ParadexClient {
8
+ constructor(config, provider, account) {
9
+ this.config = config;
10
+ this.provider = provider;
11
+ this.account = account;
12
+ }
13
+ /**
14
+ * Create a Paradex client from an Ethereum signer
15
+ */
16
+ static async createFromEthSigner({ config, signer, }) {
17
+ // Derive credentials internally (privateKey never exposed)
18
+ const credentials = await deriveFromEthSigner({ config, signer });
19
+ // Create authenticated provider
20
+ const provider = new DefaultProvider(config, credentials);
21
+ // Get the account from provider
22
+ const account = provider.getAccount();
23
+ if (account == null) {
24
+ throw new Error('Failed to create authenticated provider');
25
+ }
26
+ return new ParadexClient(config, provider, account);
27
+ }
28
+ /**
29
+ * Create a Paradex client from a Starknet account
30
+ */
31
+ static async createFromStarknetAccount({ config, account, starknetProvider, }) {
32
+ // Derive credentials internally (privateKey never exposed)
33
+ const credentials = await deriveFromStarknetAccount({
34
+ config,
35
+ account,
36
+ starknetProvider,
37
+ });
38
+ // Create authenticated provider
39
+ const provider = new DefaultProvider(config, credentials);
40
+ // Get the account from provider
41
+ const paradexAccount = provider.getAccount();
42
+ if (paradexAccount == null) {
43
+ throw new Error('Failed to create authenticated provider');
44
+ }
45
+ return new ParadexClient(config, provider, paradexAccount);
46
+ }
47
+ /**
48
+ * Get maximum withdrawable amount (includes balance and accounts for socialized loss)
49
+ */
50
+ async getMaxWithdraw(token) {
51
+ return await Paraclear.getMaxWithdraw({
52
+ provider: this.provider,
53
+ config: this.config,
54
+ account: this.account,
55
+ token,
56
+ });
57
+ }
58
+ /**
59
+ * Get token balance
60
+ */
61
+ async getTokenBalance(token) {
62
+ return await Paraclear.getTokenBalance({
63
+ provider: this.provider,
64
+ config: this.config,
65
+ account: this.account,
66
+ token,
67
+ });
68
+ }
69
+ /**
70
+ * Get socialized loss factor
71
+ */
72
+ async getSocializedLossFactor() {
73
+ return await Paraclear.getSocializedLossFactor({
74
+ provider: this.provider,
75
+ config: this.config,
76
+ });
77
+ }
78
+ /**
79
+ * Get receivable amount after applying socialized loss
80
+ */
81
+ async getReceivableAmount(token, amount) {
82
+ return await Paraclear.getReceivableAmount({
83
+ provider: this.provider,
84
+ config: this.config,
85
+ token,
86
+ amount,
87
+ });
88
+ }
89
+ /**
90
+ * Withdraw tokens
91
+ */
92
+ async withdraw(token, amount, bridgeCall) {
93
+ return await Paraclear.withdraw({
94
+ config: this.config,
95
+ account: this.account,
96
+ token,
97
+ amount,
98
+ bridgeCall,
99
+ });
100
+ }
101
+ /**
102
+ * Wait for transaction to complete
103
+ */
104
+ async waitForTransaction(txHash, options) {
105
+ return await this.provider.waitForTransaction(txHash, options);
106
+ }
107
+ /**
108
+ * Get the account address (public key, safe to expose)
109
+ */
110
+ getAddress() {
111
+ return this.account.address;
112
+ }
113
+ /**
114
+ * Get the underlying provider (for advanced use cases)
115
+ */
116
+ getProvider() {
117
+ return this.provider;
118
+ }
119
+ }
@@ -0,0 +1,8 @@
1
+ import type { Account } from './account.js';
2
+ import type { AuthSignature } from './paraclear-provider.js';
3
+ export declare const FULLNODE_SIGNATURE_VERSION = "1.0.0";
4
+ /**
5
+ * Generate authentication signature for RPC calls
6
+ * Adopted from the authentication approach in the Paradex frontend
7
+ */
8
+ export declare function generateAuthSignature(account: Account, chainId: string, method: string, params: unknown): Promise<AuthSignature>;
@@ -0,0 +1,100 @@
1
+ import * as Starknet from 'starknet';
2
+ export const FULLNODE_SIGNATURE_VERSION = '1.0.0';
3
+ /**
4
+ * Hashes JSON payload using Poseidon hashing algorithm
5
+ * Uses official StarkNet.js ByteArray utilities for consistency
6
+ */
7
+ function hashPayloadWithPoseidon(jsonPayload) {
8
+ // Parse and re-stringify to ensure consistent formatting
9
+ const payloadString = JSON.stringify(JSON.parse(jsonPayload));
10
+ // Convert string to Cairo ByteArray using official StarkNet.js utility
11
+ const byteArray = Starknet.byteArray.byteArrayFromString(payloadString);
12
+ // Prepare data for Poseidon hashing
13
+ const felts = [];
14
+ // Add the number of full chunks
15
+ felts.push(BigInt(byteArray.data.length));
16
+ // Add each data chunk
17
+ for (const chunk of byteArray.data) {
18
+ felts.push(BigInt(chunk));
19
+ }
20
+ // Add pending word if it exists
21
+ if (byteArray.pending_word !== 0 && byteArray.pending_word_len !== 0) {
22
+ felts.push(BigInt(byteArray.pending_word), BigInt(byteArray.pending_word_len));
23
+ }
24
+ // Use official StarkNet.js Poseidon hash
25
+ return Starknet.hash.computePoseidonHashOnElements(felts);
26
+ }
27
+ /**
28
+ * Generate authentication signature for RPC calls
29
+ * Adopted from the authentication approach in the Paradex frontend
30
+ */
31
+ export async function generateAuthSignature(account, chainId, method, params) {
32
+ // Generate timestamp and ID
33
+ const timestamp = Math.floor(Date.now() / 1000);
34
+ const id = Math.floor(Date.now() / 1000); // Use timestamp-based ID for uniqueness
35
+ // Create the RPC payload
36
+ const payload = {
37
+ jsonrpc: '2.0',
38
+ method,
39
+ params,
40
+ id,
41
+ };
42
+ const jsonPayload = JSON.stringify(payload, (_, value) => typeof value === 'bigint' ? value.toString() : value);
43
+ // Hash payload using Poseidon
44
+ const payloadHash = hashPayloadWithPoseidon(jsonPayload);
45
+ // Convert hex string to bigint for the payload field
46
+ const payloadValue = typeof payloadHash === 'string' && payloadHash.startsWith('0x')
47
+ ? BigInt(payloadHash)
48
+ : BigInt(payloadHash);
49
+ const accountHex = Starknet.num.toHex(account.address);
50
+ const chainIdHex = Starknet.shortString.encodeShortString(chainId);
51
+ const typedData = {
52
+ message: {
53
+ account: accountHex,
54
+ payload: payloadValue.toString(), // Convert to decimal string
55
+ timestamp: timestamp.toString(),
56
+ version: FULLNODE_SIGNATURE_VERSION,
57
+ },
58
+ domain: {
59
+ name: 'Paradex',
60
+ chainId: chainIdHex,
61
+ version: '1',
62
+ },
63
+ primaryType: 'Request',
64
+ types: {
65
+ StarkNetDomain: [
66
+ { name: 'name', type: 'felt' },
67
+ { name: 'chainId', type: 'felt' },
68
+ { name: 'version', type: 'felt' },
69
+ ],
70
+ Request: [
71
+ { name: 'account', type: 'felt' },
72
+ { name: 'payload', type: 'felt' },
73
+ { name: 'timestamp', type: 'felt' },
74
+ { name: 'version', type: 'felt' },
75
+ ],
76
+ },
77
+ };
78
+ // Sign the typed data
79
+ const signature = await account.signMessage(typedData);
80
+ // Format signature as decimal strings
81
+ let signatureArray;
82
+ if (Array.isArray(signature)) {
83
+ signatureArray = [
84
+ signature[0]?.toString() ?? '',
85
+ signature[1]?.toString() ?? '',
86
+ ];
87
+ }
88
+ else {
89
+ signatureArray = [
90
+ signature.r?.toString() ?? '',
91
+ signature.s?.toString() ?? '',
92
+ ];
93
+ }
94
+ return {
95
+ account: accountHex,
96
+ signature: signatureArray,
97
+ timestamp: timestamp.toString(),
98
+ id,
99
+ };
100
+ }
package/dist/index.d.ts CHANGED
@@ -1,24 +1,17 @@
1
- import * as _Account from './account.js';
1
+ import * as _Client from './client.js';
2
2
  import * as _Config from './config.js';
3
3
  import * as _Signer from './ethereum-signer.js';
4
- import * as _ParaclearProvider from './paraclear-provider.js';
5
- import * as _Paraclear from './paraclear.js';
6
- export declare const Config: {
7
- fetchConfig: typeof _Config.fetchConfig;
4
+ export declare const Client: {
5
+ fromEthSigner: (params: _Client.CreateClientFromEthSignerParams) => Promise<_Client.ParadexClient>;
6
+ fromStarknetAccount: (params: _Client.CreateClientFromStarknetAccountParams) => Promise<_Client.ParadexClient>;
8
7
  };
9
- export declare const Account: {
10
- fromEthSigner: typeof _Account.fromEthSigner;
11
- fromStarknetAccount: typeof _Account.fromStarknetAccount;
8
+ export declare const Config: {
9
+ fetch: typeof _Config.fetchConfig;
12
10
  };
13
11
  export declare const Signer: {
14
- ethersSignerAdapter: typeof _Signer.ethersSignerAdapter;
15
- };
16
- export declare const ParaclearProvider: {
17
- DefaultProvider: typeof _ParaclearProvider.DefaultProvider;
18
- };
19
- export declare const Paraclear: {
20
- getTokenBalance: typeof _Paraclear.getTokenBalance;
21
- getSocializedLossFactor: typeof _Paraclear.getSocializedLossFactor;
22
- getReceivableAmount: typeof _Paraclear.getReceivableAmount;
23
- withdraw: typeof _Paraclear.withdraw;
12
+ fromEthers: typeof _Signer.ethersSignerAdapter;
24
13
  };
14
+ export type { ParadexClient, CreateClientFromEthSignerParams, CreateClientFromStarknetAccountParams, TokenBalance, SocializedLossFactor, ReceivableAmount, MaxWithdraw, WithdrawResult, } from './client.js';
15
+ export type { ParadexConfig } from './config.js';
16
+ export type { EthereumSigner } from './ethereum-signer.js';
17
+ export type { Hex } from './types.js';
package/dist/index.js CHANGED
@@ -1,20 +1,14 @@
1
- import * as _Account from './account.js';
1
+ import * as _Client from './client.js';
2
2
  import * as _Config from './config.js';
3
3
  import * as _Signer from './ethereum-signer.js';
4
- import * as _ParaclearProvider from './paraclear-provider.js';
5
- import * as _Paraclear from './paraclear.js';
6
- export const Config = { fetchConfig: _Config.fetchConfig };
7
- export const Account = {
8
- fromEthSigner: _Account.fromEthSigner,
9
- fromStarknetAccount: _Account.fromStarknetAccount,
4
+ // Recommended: High-level client interface
5
+ export const Client = {
6
+ fromEthSigner: async (params) => await _Client.ParadexClient.createFromEthSigner(params),
7
+ fromStarknetAccount: async (params) => await _Client.ParadexClient.createFromStarknetAccount(params),
10
8
  };
11
- export const Signer = { ethersSignerAdapter: _Signer.ethersSignerAdapter };
12
- export const ParaclearProvider = {
13
- DefaultProvider: _ParaclearProvider.DefaultProvider,
9
+ export const Config = {
10
+ fetch: _Config.fetchConfig,
14
11
  };
15
- export const Paraclear = {
16
- getTokenBalance: _Paraclear.getTokenBalance,
17
- getSocializedLossFactor: _Paraclear.getSocializedLossFactor,
18
- getReceivableAmount: _Paraclear.getReceivableAmount,
19
- withdraw: _Paraclear.withdraw,
12
+ export const Signer = {
13
+ fromEthers: _Signer.ethersSignerAdapter,
20
14
  };
@@ -1,6 +1,37 @@
1
1
  import * as Starknet from 'starknet';
2
+ import type { Account, AccountCredentials } from './account.js';
2
3
  import type { ParadexConfig } from './config.js';
3
- export declare class DefaultProvider extends Starknet.RpcProvider {
4
- constructor(config: ParadexConfig);
4
+ export interface AuthSignature {
5
+ account: string;
6
+ signature: [string, string];
7
+ timestamp: string;
8
+ id: number;
9
+ }
10
+ /**
11
+ * Stateless RPC provider that supports Paradex authentication
12
+ * Extends Starknet.RpcProvider with automatic EIP-712 signature authentication
13
+ * All RPC calls automatically include authentication headers when account is present
14
+ */
15
+ export declare class AuthenticatedRpcProvider extends Starknet.RpcProvider {
16
+ protected chainId: string;
17
+ constructor(nodeUrl: string, chainId: string);
18
+ /**
19
+ * Get the chain ID string (not encoded)
20
+ */
21
+ getChainIdString(): string;
22
+ }
23
+ export declare class DefaultProvider extends AuthenticatedRpcProvider {
24
+ private readonly account?;
25
+ private readonly nodeUrl;
26
+ constructor(config: ParadexConfig, credentials?: AccountCredentials | Account);
27
+ /**
28
+ * Get the account (internal use only)
29
+ * @internal
30
+ */
31
+ getAccount(): Account | undefined;
32
+ /**
33
+ * Override callContract to add authentication headers
34
+ */
35
+ callContract(call: Starknet.Call, blockIdentifier?: Starknet.BlockIdentifier): Promise<Starknet.CallContractResponse>;
5
36
  }
6
37
  export type ParaclearProvider = DefaultProvider;
@@ -1,9 +1,101 @@
1
1
  import * as Starknet from 'starknet';
2
- export class DefaultProvider extends Starknet.RpcProvider {
3
- constructor(config) {
2
+ /**
3
+ * Stateless RPC provider that supports Paradex authentication
4
+ * Extends Starknet.RpcProvider with automatic EIP-712 signature authentication
5
+ * All RPC calls automatically include authentication headers when account is present
6
+ */
7
+ export class AuthenticatedRpcProvider extends Starknet.RpcProvider {
8
+ constructor(nodeUrl, chainId) {
4
9
  super({
5
- nodeUrl: config.paradexFullNodeRpcUrl,
6
- chainId: Starknet.shortString.encodeShortString(config.paradexChainId),
10
+ nodeUrl,
11
+ chainId: Starknet.shortString.encodeShortString(chainId),
7
12
  });
13
+ this.chainId = chainId;
14
+ }
15
+ /**
16
+ * Get the chain ID string (not encoded)
17
+ */
18
+ getChainIdString() {
19
+ return this.chainId;
20
+ }
21
+ }
22
+ export class DefaultProvider extends AuthenticatedRpcProvider {
23
+ constructor(config, credentials) {
24
+ super(config.paradexFullNodeRpcUrl, config.paradexChainId);
25
+ this.nodeUrl = config.paradexFullNodeRpcUrl;
26
+ if (credentials != null) {
27
+ // If it's already an Account, use it directly
28
+ if ('address' in credentials && 'signer' in credentials) {
29
+ this.account = credentials;
30
+ }
31
+ else {
32
+ this.account = new Starknet.Account({
33
+ provider: this,
34
+ address: credentials.address,
35
+ signer: credentials.privateKey,
36
+ });
37
+ }
38
+ }
39
+ }
40
+ /**
41
+ * Get the account (internal use only)
42
+ * @internal
43
+ */
44
+ getAccount() {
45
+ return this.account;
46
+ }
47
+ /**
48
+ * Override callContract to add authentication headers
49
+ */
50
+ async callContract(call, blockIdentifier = Starknet.BlockTag.PRE_CONFIRMED) {
51
+ // If no account, use standard callContract
52
+ if (this.account == null) {
53
+ return await super.callContract(call, blockIdentifier);
54
+ }
55
+ // Build the RPC params
56
+ const request = {
57
+ contract_address: call.contractAddress,
58
+ entry_point_selector: Starknet.hash.getSelectorFromName(call.entrypoint),
59
+ calldata: call.calldata ?? [],
60
+ };
61
+ const params = {
62
+ request,
63
+ block_id: blockIdentifier,
64
+ };
65
+ const method = 'starknet_call';
66
+ // Generate auth signature
67
+ const { generateAuthSignature } = await import('./fullnode-auth.js');
68
+ const signature = await generateAuthSignature(this.account, this.chainId, method, params);
69
+ // Build the JSON-RPC payload with the same ID used in signature
70
+ const payload = {
71
+ jsonrpc: '2.0',
72
+ method,
73
+ params,
74
+ id: signature.id,
75
+ };
76
+ const jsonPayload = JSON.stringify(payload, (_, value) => typeof value === 'bigint' ? value.toString() : value);
77
+ // Add auth headers
78
+ const authHeaders = {
79
+ 'Content-Type': 'application/json',
80
+ 'PARADEX-STARKNET-ACCOUNT': signature.account,
81
+ 'PARADEX-STARKNET-SIGNATURE': JSON.stringify(signature.signature),
82
+ 'PARADEX-STARKNET-SIGNATURE-TIMESTAMP': signature.timestamp,
83
+ 'PARADEX-STARKNET-SIGNATURE-VERSION': '1.0.0',
84
+ };
85
+ // Make authenticated request directly
86
+ const response = await fetch(this.nodeUrl, {
87
+ method: 'POST',
88
+ headers: authHeaders,
89
+ body: jsonPayload,
90
+ });
91
+ if (!response.ok) {
92
+ throw new Error(`HTTP error! status: ${response.status}`);
93
+ }
94
+ const result = (await response.json());
95
+ // Handle RPC errors
96
+ if (result.error !== undefined) {
97
+ throw new Error(`RPC error: ${result.error.message}`);
98
+ }
99
+ return result.result;
8
100
  }
9
101
  }
@@ -28,6 +28,39 @@ interface GetBalanceResult {
28
28
  * Get the Paraclear balance of the given token for the given account.
29
29
  */
30
30
  export declare function getTokenBalance(params: GetBalanceParams): Promise<GetBalanceResult>;
31
+ interface GetMaxWithdrawParams {
32
+ readonly config: ParadexConfig;
33
+ readonly provider: Pick<ParaclearProvider, 'callContract'>;
34
+ /**
35
+ * Account to check.
36
+ */
37
+ readonly account: Account;
38
+ /**
39
+ * Token symbol.
40
+ * @example 'USDC'
41
+ */
42
+ readonly token: string;
43
+ }
44
+ interface GetMaxWithdrawResult {
45
+ /**
46
+ * The maximum amount the user can withdraw (accounting for socialized loss).
47
+ * If socialized loss factor is 0, this equals the balance.
48
+ * Decimal string.
49
+ * @example '950.475'
50
+ */
51
+ readonly amount: string;
52
+ /**
53
+ * The maxWithdrawable amount, converted to be used in chain calls,
54
+ * using the Paraclear decimals.
55
+ * @example '950475000000'
56
+ */
57
+ readonly amountChain: string;
58
+ }
59
+ /**
60
+ * Get the maximum withdrawable amount for a token, accounting for socialized loss.
61
+ * This calls the `max_withdraw` contract method which returns the actual withdrawable amount.
62
+ */
63
+ export declare function getMaxWithdraw(params: GetMaxWithdrawParams): Promise<GetMaxWithdrawResult>;
31
64
  interface GetSocializedLossFactorParams {
32
65
  readonly config: ParadexConfig;
33
66
  readonly provider: Pick<ParaclearProvider, 'callContract'>;
package/dist/paraclear.js CHANGED
@@ -11,11 +11,8 @@ export async function getTokenBalance(params) {
11
11
  const result = await params.provider.callContract({
12
12
  contractAddress: params.config.paraclearAddress,
13
13
  entrypoint: 'getTokenAssetBalance',
14
- calldata: Starknet.CallData.compile([
15
- params.account.address,
16
- token.l2TokenAddress,
17
- ]),
18
- }, 'latest');
14
+ calldata: [params.account.address, token.l2TokenAddress],
15
+ }, Starknet.BlockTag.LATEST);
19
16
  const value = result?.[0];
20
17
  if (value == null) {
21
18
  throw new Error('Failed to get token balance');
@@ -28,6 +25,36 @@ export async function getTokenBalance(params) {
28
25
  const sizeBn = fromChainSize(chainSizeBn, params.config.paraclearDecimals);
29
26
  return { size: sizeBn.toString() };
30
27
  }
28
+ /**
29
+ * Get the maximum withdrawable amount for a token, accounting for socialized loss.
30
+ * This calls the `max_withdraw` contract method which returns the actual withdrawable amount.
31
+ */
32
+ export async function getMaxWithdraw(params) {
33
+ const token = params.config.bridgedTokens[params.token];
34
+ if (token == null) {
35
+ throw new Error(`Token ${params.token} is not supported`);
36
+ }
37
+ // Call max_withdraw contract method (returns max withdrawable amount accounting for socialized loss)
38
+ const result = await params.provider.callContract({
39
+ contractAddress: params.config.paraclearAddress,
40
+ entrypoint: 'max_withdraw',
41
+ calldata: [params.account.address, token.l2TokenAddress],
42
+ }, Starknet.BlockTag.PRE_CONFIRMED);
43
+ const value = result?.[0];
44
+ if (value == null) {
45
+ throw new Error('Failed to get max withdraw amount');
46
+ }
47
+ const valueBn = new BigNumber(value);
48
+ if (valueBn.isNaN()) {
49
+ throw new Error('Failed to parse max withdraw amount');
50
+ }
51
+ const chainMaxWithdrawBn = valueBn;
52
+ const maxWithdrawable = fromChainSize(chainMaxWithdrawBn, params.config.paraclearDecimals);
53
+ return {
54
+ amount: maxWithdrawable.toString(),
55
+ amountChain: chainMaxWithdrawBn.toString(),
56
+ };
57
+ }
31
58
  /**
32
59
  * Socialized losses happen when Paradex Insurance Fund is bankrupt
33
60
  * due to large amounts of unprofitable liquidations. When socialized
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@paradex/sdk",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "JavaScript SDK for Paradex",
5
5
  "main": "dist/index.js",
6
6
  "files": [