@paradex/sdk 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +358 -12
- package/dist/account.d.ts +37 -1
- package/dist/account.js +53 -9
- package/dist/client.d.ts +81 -0
- package/dist/client.js +120 -0
- package/dist/fullnode-auth.d.ts +8 -0
- package/dist/fullnode-auth.js +100 -0
- package/dist/index.d.ts +11 -18
- package/dist/index.js +9 -15
- package/dist/paraclear-provider.d.ts +33 -2
- package/dist/paraclear-provider.js +96 -4
- package/dist/paraclear.d.ts +33 -0
- package/dist/paraclear.js +32 -5
- package/dist/starknet-account-support.js +23 -1
- package/dist/starknet-signer.js +5 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,31 +1,377 @@
|
|
|
1
1
|
# Paradex SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Official JavaScript/TypeScript SDK for [Paradex](https://paradex.trade) - a decentralized perpetuals exchange built on Starknet.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @paradex/sdk
|
|
7
9
|
```
|
|
8
10
|
|
|
9
|
-
```
|
|
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
|
-
|
|
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
|
-
|
|
336
|
+
### Client Methods
|
|
18
337
|
|
|
19
|
-
|
|
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
|
-
|
|
349
|
+
### Configuration
|
|
22
350
|
|
|
23
|
-
|
|
351
|
+
| Method | Description | Returns |
|
|
352
|
+
| ------------------- | ----------------------------------- | --------------- |
|
|
353
|
+
| `Config.fetch(env)` | Fetch configuration for environment | `ParadexConfig` |
|
|
24
354
|
|
|
25
|
-
|
|
355
|
+
### Signer
|
|
26
356
|
|
|
27
|
-
|
|
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
|
-
⚠️
|
|
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,21 +30,37 @@ 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
|
+
readonly rpcUrl?: string;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Derives Paradex account credentials from a Starknet account.
|
|
45
|
+
* Internal use only - use ParadexClient.createFromStarknetAccount() instead.
|
|
46
|
+
* @internal
|
|
47
|
+
* @returns The account address and private key.
|
|
48
|
+
*/
|
|
49
|
+
export declare function deriveFromStarknetAccount({ config, account, starknetProvider, rpcUrl, }: DeriveFromStarknetAccountParams): Promise<AccountCredentials>;
|
|
16
50
|
interface FromStarknetAccountParams {
|
|
17
51
|
/** Paradex chain provider */
|
|
18
52
|
readonly provider: Starknet.ProviderOptions | Starknet.ProviderInterface;
|
|
19
53
|
readonly config: ParadexConfig;
|
|
20
54
|
readonly account: Starknet.AccountInterface;
|
|
21
55
|
readonly starknetProvider?: Starknet.ProviderInterface;
|
|
56
|
+
readonly rpcUrl?: string;
|
|
22
57
|
}
|
|
23
58
|
/**
|
|
24
59
|
* Generates a Paradex account from a Starknet signer.
|
|
60
|
+
* @deprecated Use deriveFromStarknetAccount() and pass credentials to DefaultProvider constructor
|
|
25
61
|
* @returns The generated Paradex account.
|
|
26
62
|
*/
|
|
27
|
-
export declare function fromStarknetAccount({ provider, config, account, starknetProvider, }: FromStarknetAccountParams): Promise<Account>;
|
|
63
|
+
export declare function fromStarknetAccount({ provider, config, account, starknetProvider, rpcUrl, }: FromStarknetAccountParams): Promise<Account>;
|
|
28
64
|
/**
|
|
29
65
|
* Checks if starknet signatures are equal.
|
|
30
66
|
*/
|
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
|
-
*
|
|
7
|
-
*
|
|
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
|
|
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,16 +21,37 @@ export async function fromEthSigner({ provider, config, signer, }) {
|
|
|
19
21
|
accountClassHash: config.paraclearAccountHash,
|
|
20
22
|
accountProxyClassHash: config.paraclearAccountProxyHash,
|
|
21
23
|
});
|
|
22
|
-
return
|
|
24
|
+
return {
|
|
25
|
+
address,
|
|
26
|
+
privateKey: `0x${privateKey}`,
|
|
27
|
+
};
|
|
23
28
|
}
|
|
24
29
|
/**
|
|
25
|
-
* Generates a Paradex account from
|
|
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
|
|
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, rpcUrl, }) {
|
|
29
49
|
const starkKeyTypedData = starknetSigner.buildStarknetStarkKeyTypedData(config.starknetChainId);
|
|
30
|
-
const
|
|
31
|
-
|
|
50
|
+
const provider = starknetProvider ??
|
|
51
|
+
(rpcUrl != null
|
|
52
|
+
? new Starknet.RpcProvider({ nodeUrl: rpcUrl })
|
|
53
|
+
: starknetSigner.getPublicProvider(config.starknetChainId));
|
|
54
|
+
const accountSupport = await starknetSigner.getAccountSupport(account, provider);
|
|
32
55
|
const signature = await account.signMessage(starkKeyTypedData);
|
|
33
56
|
const additionalSignature = await account.signMessage(starkKeyTypedData);
|
|
34
57
|
if (!isStarknetSignatureEqual(signature, additionalSignature))
|
|
@@ -40,7 +63,28 @@ export async function fromStarknetAccount({ provider, config, account, starknetP
|
|
|
40
63
|
accountClassHash: config.paraclearAccountHash,
|
|
41
64
|
accountProxyClassHash: config.paraclearAccountProxyHash,
|
|
42
65
|
});
|
|
43
|
-
return
|
|
66
|
+
return {
|
|
67
|
+
address,
|
|
68
|
+
privateKey: `0x${privateKey}`,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Generates a Paradex account from a Starknet signer.
|
|
73
|
+
* @deprecated Use deriveFromStarknetAccount() and pass credentials to DefaultProvider constructor
|
|
74
|
+
* @returns The generated Paradex account.
|
|
75
|
+
*/
|
|
76
|
+
export async function fromStarknetAccount({ provider, config, account, starknetProvider, rpcUrl, }) {
|
|
77
|
+
const credentials = await deriveFromStarknetAccount({
|
|
78
|
+
config,
|
|
79
|
+
account,
|
|
80
|
+
starknetProvider,
|
|
81
|
+
rpcUrl,
|
|
82
|
+
});
|
|
83
|
+
return new Starknet.Account({
|
|
84
|
+
provider,
|
|
85
|
+
address: credentials.address,
|
|
86
|
+
signer: credentials.privateKey,
|
|
87
|
+
});
|
|
44
88
|
}
|
|
45
89
|
/**
|
|
46
90
|
* Generates an account address based on the account contract and public key.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
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
|
+
readonly rpcUrl?: string;
|
|
14
|
+
}
|
|
15
|
+
export interface TokenBalance {
|
|
16
|
+
readonly size: string;
|
|
17
|
+
}
|
|
18
|
+
export interface SocializedLossFactor {
|
|
19
|
+
readonly socializedLossFactor: string;
|
|
20
|
+
}
|
|
21
|
+
export interface ReceivableAmount {
|
|
22
|
+
readonly receivableAmount: string;
|
|
23
|
+
readonly receivableAmountChain: string;
|
|
24
|
+
readonly socializedLossFactor: string;
|
|
25
|
+
}
|
|
26
|
+
export interface MaxWithdraw {
|
|
27
|
+
readonly amount: string;
|
|
28
|
+
readonly amountChain: string;
|
|
29
|
+
}
|
|
30
|
+
export interface WithdrawResult {
|
|
31
|
+
readonly hash: string;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* High-level Paradex client with clean interface
|
|
35
|
+
*/
|
|
36
|
+
export declare class ParadexClient {
|
|
37
|
+
private readonly provider;
|
|
38
|
+
private readonly config;
|
|
39
|
+
private readonly account;
|
|
40
|
+
private constructor();
|
|
41
|
+
/**
|
|
42
|
+
* Create a Paradex client from an Ethereum signer
|
|
43
|
+
*/
|
|
44
|
+
static createFromEthSigner({ config, signer, }: CreateClientFromEthSignerParams): Promise<ParadexClient>;
|
|
45
|
+
/**
|
|
46
|
+
* Create a Paradex client from a Starknet account
|
|
47
|
+
*/
|
|
48
|
+
static createFromStarknetAccount({ config, account, starknetProvider, rpcUrl, }: CreateClientFromStarknetAccountParams): Promise<ParadexClient>;
|
|
49
|
+
/**
|
|
50
|
+
* Get maximum withdrawable amount (includes balance and accounts for socialized loss)
|
|
51
|
+
*/
|
|
52
|
+
getMaxWithdraw(token: string): Promise<MaxWithdraw>;
|
|
53
|
+
/**
|
|
54
|
+
* Get token balance
|
|
55
|
+
*/
|
|
56
|
+
getTokenBalance(token: string): Promise<TokenBalance>;
|
|
57
|
+
/**
|
|
58
|
+
* Get socialized loss factor
|
|
59
|
+
*/
|
|
60
|
+
getSocializedLossFactor(): Promise<SocializedLossFactor>;
|
|
61
|
+
/**
|
|
62
|
+
* Get receivable amount after applying socialized loss
|
|
63
|
+
*/
|
|
64
|
+
getReceivableAmount(token: string, amount: string): Promise<ReceivableAmount>;
|
|
65
|
+
/**
|
|
66
|
+
* Withdraw tokens
|
|
67
|
+
*/
|
|
68
|
+
withdraw(token: string, amount: string, bridgeCall: Starknet.Call | readonly Starknet.Call[]): Promise<WithdrawResult>;
|
|
69
|
+
/**
|
|
70
|
+
* Wait for transaction to complete
|
|
71
|
+
*/
|
|
72
|
+
waitForTransaction(txHash: string, options?: Starknet.waitForTransactionOptions): Promise<Starknet.GetTransactionReceiptResponse>;
|
|
73
|
+
/**
|
|
74
|
+
* Get the account address (public key, safe to expose)
|
|
75
|
+
*/
|
|
76
|
+
getAddress(): string;
|
|
77
|
+
/**
|
|
78
|
+
* Get the underlying provider (for advanced use cases)
|
|
79
|
+
*/
|
|
80
|
+
getProvider(): DefaultProvider;
|
|
81
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
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, rpcUrl, }) {
|
|
32
|
+
// Derive credentials internally (privateKey never exposed)
|
|
33
|
+
const credentials = await deriveFromStarknetAccount({
|
|
34
|
+
config,
|
|
35
|
+
account,
|
|
36
|
+
starknetProvider,
|
|
37
|
+
rpcUrl,
|
|
38
|
+
});
|
|
39
|
+
// Create authenticated provider
|
|
40
|
+
const provider = new DefaultProvider(config, credentials);
|
|
41
|
+
// Get the account from provider
|
|
42
|
+
const paradexAccount = provider.getAccount();
|
|
43
|
+
if (paradexAccount == null) {
|
|
44
|
+
throw new Error('Failed to create authenticated provider');
|
|
45
|
+
}
|
|
46
|
+
return new ParadexClient(config, provider, paradexAccount);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Get maximum withdrawable amount (includes balance and accounts for socialized loss)
|
|
50
|
+
*/
|
|
51
|
+
async getMaxWithdraw(token) {
|
|
52
|
+
return await Paraclear.getMaxWithdraw({
|
|
53
|
+
provider: this.provider,
|
|
54
|
+
config: this.config,
|
|
55
|
+
account: this.account,
|
|
56
|
+
token,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Get token balance
|
|
61
|
+
*/
|
|
62
|
+
async getTokenBalance(token) {
|
|
63
|
+
return await Paraclear.getTokenBalance({
|
|
64
|
+
provider: this.provider,
|
|
65
|
+
config: this.config,
|
|
66
|
+
account: this.account,
|
|
67
|
+
token,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Get socialized loss factor
|
|
72
|
+
*/
|
|
73
|
+
async getSocializedLossFactor() {
|
|
74
|
+
return await Paraclear.getSocializedLossFactor({
|
|
75
|
+
provider: this.provider,
|
|
76
|
+
config: this.config,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Get receivable amount after applying socialized loss
|
|
81
|
+
*/
|
|
82
|
+
async getReceivableAmount(token, amount) {
|
|
83
|
+
return await Paraclear.getReceivableAmount({
|
|
84
|
+
provider: this.provider,
|
|
85
|
+
config: this.config,
|
|
86
|
+
token,
|
|
87
|
+
amount,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Withdraw tokens
|
|
92
|
+
*/
|
|
93
|
+
async withdraw(token, amount, bridgeCall) {
|
|
94
|
+
return await Paraclear.withdraw({
|
|
95
|
+
config: this.config,
|
|
96
|
+
account: this.account,
|
|
97
|
+
token,
|
|
98
|
+
amount,
|
|
99
|
+
bridgeCall,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Wait for transaction to complete
|
|
104
|
+
*/
|
|
105
|
+
async waitForTransaction(txHash, options) {
|
|
106
|
+
return await this.provider.waitForTransaction(txHash, options);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Get the account address (public key, safe to expose)
|
|
110
|
+
*/
|
|
111
|
+
getAddress() {
|
|
112
|
+
return this.account.address;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Get the underlying provider (for advanced use cases)
|
|
116
|
+
*/
|
|
117
|
+
getProvider() {
|
|
118
|
+
return this.provider;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -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
|
|
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
|
-
|
|
5
|
-
|
|
6
|
-
|
|
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
|
|
10
|
-
|
|
11
|
-
fromStarknetAccount: typeof _Account.fromStarknetAccount;
|
|
8
|
+
export declare const Config: {
|
|
9
|
+
fetch: typeof _Config.fetchConfig;
|
|
12
10
|
};
|
|
13
11
|
export declare const Signer: {
|
|
14
|
-
|
|
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
|
|
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
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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
|
|
12
|
-
|
|
13
|
-
DefaultProvider: _ParaclearProvider.DefaultProvider,
|
|
9
|
+
export const Config = {
|
|
10
|
+
fetch: _Config.fetchConfig,
|
|
14
11
|
};
|
|
15
|
-
export const
|
|
16
|
-
|
|
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
|
|
4
|
-
|
|
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
|
-
|
|
3
|
-
|
|
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
|
|
6
|
-
chainId: Starknet.shortString.encodeShortString(
|
|
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
|
}
|
package/dist/paraclear.d.ts
CHANGED
|
@@ -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:
|
|
15
|
-
|
|
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
|
|
@@ -11,6 +11,8 @@ const BRAAVOS_MULTI_OWNER_V1_0_0_CLASS_HASH = '0x041bf1e71792aecb9df3e9d04e15400
|
|
|
11
11
|
const BRAAVOS_V1_0_0_CLASS_HASH = '0x00816dd0297efc55dc1e7559020a3a825e81ef734b558f03c83325d4da7e6253';
|
|
12
12
|
const BRAAVOS_V1_1_0_CLASS_HASH = '0x02c8c7e6fbcfb3e8e15a46648e8914c6aa1fc506fc1e7fb3d1e19630716174bc';
|
|
13
13
|
const BRAAVOS_V1_2_0_CLASS_HASH = '0x03957f9f5a1cbfe918cedc2015c85200ca51a5f7506ecb6de98a5207b759bf8a';
|
|
14
|
+
const KEPLR_OZ_V0_17_0_CLASS_HASH = '0x06cc43e9a4a0036cd09d8a997c61df18d7e4fa9459c907a4664b4e56b679d187';
|
|
15
|
+
const XVERSE_ARGENT_V0_4_0_CLASS_HASH = '0x0663fc01a0dbe1bacc4cd2a4c856eb9784b255a20988aa33d4d52b6fc20bd024';
|
|
14
16
|
export class AccountSupport {
|
|
15
17
|
constructor(
|
|
16
18
|
/** The contract instance of the account. */
|
|
@@ -32,7 +34,8 @@ export class AccountSupport {
|
|
|
32
34
|
if (this.testClassHash(ARGENT_V0_3_1_CLASS_HASH)) {
|
|
33
35
|
return 'argent-v0.3.1';
|
|
34
36
|
}
|
|
35
|
-
if (this.testClassHash(ARGENT_V0_4_0_CLASS_HASH)
|
|
37
|
+
if (this.testClassHash(ARGENT_V0_4_0_CLASS_HASH) ||
|
|
38
|
+
this.testClassHash(XVERSE_ARGENT_V0_4_0_CLASS_HASH)) {
|
|
36
39
|
const ownerTypeResp = (await this.contract.call('get_owner_type'));
|
|
37
40
|
const ownerType = ownerTypeResp.activeVariant();
|
|
38
41
|
switch (ownerType) {
|
|
@@ -111,6 +114,9 @@ export class AccountSupport {
|
|
|
111
114
|
return 'braavos-v1.2.0-stark-signer';
|
|
112
115
|
return 'unknown';
|
|
113
116
|
}
|
|
117
|
+
if (this.testClassHash(KEPLR_OZ_V0_17_0_CLASS_HASH)) {
|
|
118
|
+
return 'keplr-oz-v0.17.0';
|
|
119
|
+
}
|
|
114
120
|
return 'unknown';
|
|
115
121
|
}
|
|
116
122
|
async check() {
|
|
@@ -122,6 +128,7 @@ export class AccountSupport {
|
|
|
122
128
|
case 'braavos-v1.0.0-stark-signer':
|
|
123
129
|
case 'braavos-v1.1.0-stark-signer':
|
|
124
130
|
case 'braavos-v1.2.0-stark-signer':
|
|
131
|
+
case 'keplr-oz-v0.17.0':
|
|
125
132
|
return { ok: true };
|
|
126
133
|
case 'argent-v0.4.0-secp256k1-signer':
|
|
127
134
|
return {
|
|
@@ -227,6 +234,21 @@ export class AccountSupport {
|
|
|
227
234
|
}
|
|
228
235
|
throw new Error('Unsupported Braavos signature');
|
|
229
236
|
}
|
|
237
|
+
case 'keplr-oz-v0.17.0': {
|
|
238
|
+
if (segments.length !== 5) {
|
|
239
|
+
throw new Error('Keplr signature must have 5 segments');
|
|
240
|
+
}
|
|
241
|
+
const [rl, rh, _sl, _sh, _v] = segments;
|
|
242
|
+
if (rl == null || rh == null) {
|
|
243
|
+
throw new Error('Keplr signature is missing R segments');
|
|
244
|
+
}
|
|
245
|
+
// Combine r.low and r.high into a single hex value
|
|
246
|
+
// Uint256 = high * 2^128 + low
|
|
247
|
+
const lowBig = BigInt(rl);
|
|
248
|
+
const highBig = BigInt(rh);
|
|
249
|
+
const r = highBig * 2n ** 128n + lowBig;
|
|
250
|
+
return Starknet.num.toHex(r);
|
|
251
|
+
}
|
|
230
252
|
case 'argent-v0.4.0-secp256k1-signer':
|
|
231
253
|
case 'argent-v0.4.0-secp256r1-signer':
|
|
232
254
|
case 'argent-v0.4.0-eip191-signer':
|
package/dist/starknet-signer.js
CHANGED
|
@@ -58,12 +58,13 @@ export async function getAccountSupport(account, starknetProvider) {
|
|
|
58
58
|
return accountSupport;
|
|
59
59
|
}
|
|
60
60
|
const RPC_NODES_MAINNET = [
|
|
61
|
-
'https://starknet
|
|
62
|
-
'https://
|
|
61
|
+
'https://rpc.starknet.lava.build/rpc/v0_9',
|
|
62
|
+
'https://api-starknet-mainnet.n.dwellir.com/79e509c1-b94b-4146-ac66-efdc56786415/rpc/v0_9',
|
|
63
63
|
];
|
|
64
64
|
const RPC_NODES_TESTNET = [
|
|
65
|
-
'https://starknet-
|
|
66
|
-
'https://
|
|
65
|
+
'https://rpc.starknet-testnet.lava.build/rpc/v0_9',
|
|
66
|
+
'https://api-starknet-sepolia.n.dwellir.com/79e509c1-b94b-4146-ac66-efdc56786415/rpc/v0_9',
|
|
67
|
+
'https://starknet.api.onfinality.io/public',
|
|
67
68
|
];
|
|
68
69
|
export function getPublicProvider(chainId) {
|
|
69
70
|
const nodes = chainId === STARKNET_MAINNET_CHAIN_ID
|