@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 +358 -12
- package/dist/account.d.ts +34 -0
- package/dist/account.js +47 -7
- package/dist/client.d.ts +80 -0
- package/dist/client.js +119 -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 +42 -19
- package/dist/starknet-account-support.js +45 -14
- package/dist/starknet-signer.js +5 -1
- package/package.json +24 -16
- package/dist/_example.d.ts +0 -6
- package/dist/_example.js +0 -68
- package/dist/utils.d.ts +0 -5
- package/dist/utils.js +0 -7
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
|
|
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
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { BigNumber } from 'bignumber.js';
|
|
2
2
|
import * as Starknet from 'starknet';
|
|
3
|
-
const MAX_FEE = BigNumber('5e17'); // 5e17 WEI = 0.5 ETH
|
|
4
3
|
/**
|
|
5
4
|
* Get the Paraclear balance of the given token for the given account.
|
|
6
5
|
*/
|
|
@@ -9,14 +8,11 @@ export async function getTokenBalance(params) {
|
|
|
9
8
|
if (token == null) {
|
|
10
9
|
throw new Error(`Token ${params.token} is not supported`);
|
|
11
10
|
}
|
|
12
|
-
const
|
|
11
|
+
const result = await params.provider.callContract({
|
|
13
12
|
contractAddress: params.config.paraclearAddress,
|
|
14
13
|
entrypoint: 'getTokenAssetBalance',
|
|
15
|
-
calldata:
|
|
16
|
-
|
|
17
|
-
token.l2TokenAddress,
|
|
18
|
-
]),
|
|
19
|
-
}, 'latest');
|
|
14
|
+
calldata: [params.account.address, token.l2TokenAddress],
|
|
15
|
+
}, Starknet.BlockTag.LATEST);
|
|
20
16
|
const value = result?.[0];
|
|
21
17
|
if (value == null) {
|
|
22
18
|
throw new Error('Failed to get token balance');
|
|
@@ -29,6 +25,36 @@ export async function getTokenBalance(params) {
|
|
|
29
25
|
const sizeBn = fromChainSize(chainSizeBn, params.config.paraclearDecimals);
|
|
30
26
|
return { size: sizeBn.toString() };
|
|
31
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
|
+
}
|
|
32
58
|
/**
|
|
33
59
|
* Socialized losses happen when Paradex Insurance Fund is bankrupt
|
|
34
60
|
* due to large amounts of unprofitable liquidations. When socialized
|
|
@@ -37,7 +63,7 @@ export async function getTokenBalance(params) {
|
|
|
37
63
|
* requested amount.
|
|
38
64
|
*/
|
|
39
65
|
export async function getSocializedLossFactor(params) {
|
|
40
|
-
const
|
|
66
|
+
const result = await params.provider.callContract({
|
|
41
67
|
contractAddress: params.config.paraclearAddress,
|
|
42
68
|
entrypoint: 'getSocializedLossFactor',
|
|
43
69
|
});
|
|
@@ -100,9 +126,7 @@ export async function withdraw(params) {
|
|
|
100
126
|
throw new Error(`Token ${params.token} is not supported`);
|
|
101
127
|
}
|
|
102
128
|
const chainAmountBn = toChainSize(params.amount, params.config.paraclearDecimals);
|
|
103
|
-
|
|
104
|
-
const maxFee = MAX_FEE.plus(intNoise(10000));
|
|
105
|
-
const result = await params.account.execute([
|
|
129
|
+
const txnInvocation = [
|
|
106
130
|
{
|
|
107
131
|
contractAddress: params.config.paraclearAddress,
|
|
108
132
|
entrypoint: 'withdraw',
|
|
@@ -111,7 +135,13 @@ export async function withdraw(params) {
|
|
|
111
135
|
...(Array.isArray(params.bridgeCall)
|
|
112
136
|
? params.bridgeCall
|
|
113
137
|
: [params.bridgeCall]),
|
|
114
|
-
]
|
|
138
|
+
];
|
|
139
|
+
// Estimate fees to get proper resource bounds
|
|
140
|
+
const fees = await params.account.estimateInvokeFee(txnInvocation);
|
|
141
|
+
// Use the resource bounds from fee estimation
|
|
142
|
+
const result = await params.account.execute(txnInvocation, {
|
|
143
|
+
resourceBounds: fees.resourceBounds,
|
|
144
|
+
});
|
|
115
145
|
return { hash: result.transaction_hash };
|
|
116
146
|
}
|
|
117
147
|
function fromChainSize(size, decimals) {
|
|
@@ -122,10 +152,3 @@ function toChainSize(size, decimals) {
|
|
|
122
152
|
.times(10 ** decimals)
|
|
123
153
|
.integerValue(BigNumber.ROUND_FLOOR);
|
|
124
154
|
}
|
|
125
|
-
/**
|
|
126
|
-
* Generates a pseudorandom integer between 0 and `max`.
|
|
127
|
-
* @param max Maximum value for the noise.
|
|
128
|
-
*/
|
|
129
|
-
function intNoise(max) {
|
|
130
|
-
return Math.round(Math.random() * max);
|
|
131
|
-
}
|