@paradex/sdk 0.6.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, `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, `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
+ }