@paradex/sdk 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_example.d.ts +6 -0
- package/dist/_example.js +68 -0
- package/dist/account.d.ts +4 -3
- package/dist/account.js +7 -7
- package/dist/config.d.ts +28 -11
- package/dist/config.js +25 -5
- package/dist/index.d.ts +11 -0
- package/dist/index.js +11 -0
- package/dist/paraclear-provider.d.ts +6 -0
- package/dist/paraclear-provider.js +9 -0
- package/dist/paraclear.d.ts +137 -0
- package/dist/paraclear.js +129 -0
- package/dist/types.d.ts +1 -0
- package/dist/types.js +1 -0
- package/dist/utils.d.ts +5 -0
- package/dist/utils.js +7 -0
- package/package.json +3 -2
package/dist/_example.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { ethers } from 'ethers';
|
|
2
|
+
import * as Paradex from './index.js';
|
|
3
|
+
// Flow summary:
|
|
4
|
+
// 1. Fetch Paradex config
|
|
5
|
+
// 2. Derive Paradex account from Ethereum signer
|
|
6
|
+
// 3. Create Paraclear provider
|
|
7
|
+
// 4. Get user's USDC balance
|
|
8
|
+
// 5. Withdraw USDC
|
|
9
|
+
// 1. Fetch Paradex config for the relevant environment
|
|
10
|
+
const config = await Paradex.Config.fetchConfig('testnet'); // "testnet" | "mainnet"
|
|
11
|
+
// 2. Create Paraclear provider
|
|
12
|
+
const paraclearProvider = new Paradex.ParaclearProvider.DefaultProvider(config);
|
|
13
|
+
// 3. Derive Paradex account from Ethereum signer
|
|
14
|
+
// 3.1. Get ethers signer (example with injected provider)
|
|
15
|
+
if (window.ethereum == null)
|
|
16
|
+
throw new Error('Ethereum provider not found');
|
|
17
|
+
const ethersProvider = new ethers.BrowserProvider(window.ethereum);
|
|
18
|
+
const ethersSigner = await ethersProvider.getSigner();
|
|
19
|
+
// 3.2. Create Ethereum signer based on ethers signer
|
|
20
|
+
const signer = Paradex.Signer.ethersSignerAdapter(ethersSigner);
|
|
21
|
+
// 3.3. Initialize the account with config and Ethereum signer
|
|
22
|
+
const account = await Paradex.Account.fromEthSigner({
|
|
23
|
+
provider: paraclearProvider,
|
|
24
|
+
config,
|
|
25
|
+
signer,
|
|
26
|
+
});
|
|
27
|
+
// 4. Get user's USDC balance
|
|
28
|
+
const getBalanceResult = await Paradex.Paraclear.getTokenBalance({
|
|
29
|
+
provider: paraclearProvider, // account can be passed as the provider
|
|
30
|
+
config,
|
|
31
|
+
account,
|
|
32
|
+
token: 'USDC',
|
|
33
|
+
});
|
|
34
|
+
console.log(getBalanceResult); // { size: '100.45' }
|
|
35
|
+
// 5. Withdrawal
|
|
36
|
+
// 5.1. Get receivable amount and socialized loss factor
|
|
37
|
+
const receivableAmountResult = await Paradex.Paraclear.getReceivableAmount({
|
|
38
|
+
provider: paraclearProvider, // account can be passed as the provider
|
|
39
|
+
config,
|
|
40
|
+
amount: '50.4',
|
|
41
|
+
});
|
|
42
|
+
// 5.2. Check if socialized loss factor is not 0
|
|
43
|
+
if (Number(receivableAmountResult.socializedLossFactor) !== 0) {
|
|
44
|
+
// Display a warning to the user, suggesting to withdraw a smaller
|
|
45
|
+
// amount or to wait for the socialized loss factor to decrease.
|
|
46
|
+
console.log(`Socialized loss is active. You will receive` +
|
|
47
|
+
` ${receivableAmountResult.receivableAmount} USDC.`);
|
|
48
|
+
}
|
|
49
|
+
// 5.3. Request withdrawal (batches 1. withdraw from Paraclear contract
|
|
50
|
+
// and 2. deposit to the bridge in `bridgeCall`) for atomic transaction.
|
|
51
|
+
// Note that the requested withdraw amount can be different from the amount
|
|
52
|
+
// that will be received if socialized loss is active. Use the receivable
|
|
53
|
+
// amount to make the bridge call.
|
|
54
|
+
const withdrawResult = await Paradex.Paraclear.withdraw({
|
|
55
|
+
config,
|
|
56
|
+
account,
|
|
57
|
+
token: 'USDC',
|
|
58
|
+
amount: '50.4',
|
|
59
|
+
bridgeCall: {
|
|
60
|
+
contractAddress: '0x...',
|
|
61
|
+
entrypoint: 'deposit',
|
|
62
|
+
calldata: ['...', receivableAmountResult.receivableAmountChain],
|
|
63
|
+
},
|
|
64
|
+
});
|
|
65
|
+
console.log(withdrawResult); // { hash: '0x...' }
|
|
66
|
+
// 5.4. Monitor batch withdrawal transaction to completion
|
|
67
|
+
// https://www.starknetjs.com/docs/api/classes/providerinterface/#waitfortransaction
|
|
68
|
+
await paraclearProvider.waitForTransaction(withdrawResult.hash);
|
package/dist/account.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import * as Starknet from 'starknet';
|
|
1
2
|
import type { ParadexConfig } from './config.js';
|
|
2
3
|
import type { EthereumSigner } from './ethereum-signer.js';
|
|
3
|
-
interface Account {
|
|
4
|
-
readonly address: string;
|
|
4
|
+
export interface Account extends Starknet.Account {
|
|
5
5
|
}
|
|
6
6
|
interface FromEthSignerParams {
|
|
7
|
+
readonly provider: Starknet.ProviderOptions | Starknet.ProviderInterface;
|
|
7
8
|
readonly config: ParadexConfig;
|
|
8
9
|
readonly signer: EthereumSigner;
|
|
9
10
|
}
|
|
@@ -11,5 +12,5 @@ interface FromEthSignerParams {
|
|
|
11
12
|
* Generates a Paradex account from an Ethereum wallet.
|
|
12
13
|
* @returns The generated Paradex account.
|
|
13
14
|
*/
|
|
14
|
-
export declare function fromEthSigner({ config, signer, }: FromEthSignerParams): Promise<Account>;
|
|
15
|
+
export declare function fromEthSigner({ provider, config, signer, }: FromEthSignerParams): Promise<Account>;
|
|
15
16
|
export {};
|
package/dist/account.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { keyDerivation } from '@starkware-industries/starkware-crypto-utils';
|
|
2
|
-
import
|
|
2
|
+
import * as Starknet from 'starknet';
|
|
3
3
|
/**
|
|
4
4
|
* Generates a Paradex account from an Ethereum wallet.
|
|
5
5
|
* @returns The generated Paradex account.
|
|
6
6
|
*/
|
|
7
|
-
export async function fromEthSigner({ config, signer, }) {
|
|
7
|
+
export async function fromEthSigner({ provider, config, signer, }) {
|
|
8
8
|
const starkKeyTypedData = buildStarkKeyTypedData(config.l1ChainId);
|
|
9
9
|
const signature = await signer.signTypedData(starkKeyTypedData);
|
|
10
10
|
const privateKey = keyDerivation.getPrivateKeyFromEthSignature(signature);
|
|
@@ -14,7 +14,7 @@ export async function fromEthSigner({ config, signer, }) {
|
|
|
14
14
|
accountClassHash: config.paraclearAccountHash,
|
|
15
15
|
accountProxyClassHash: config.paraclearAccountProxyHash,
|
|
16
16
|
});
|
|
17
|
-
return
|
|
17
|
+
return new Starknet.Account(provider, address, `0x${privateKey}`);
|
|
18
18
|
}
|
|
19
19
|
/**
|
|
20
20
|
* Returns the typed data that needs to be signed by an Ethereum
|
|
@@ -41,14 +41,14 @@ function buildStarkKeyTypedData(l1ChainId) {
|
|
|
41
41
|
* Generates an account address based on the account contract and public key.
|
|
42
42
|
*/
|
|
43
43
|
function generateAccountAddress({ accountClassHash, accountProxyClassHash, publicKey, }) {
|
|
44
|
-
const callData = CallData.compile({
|
|
44
|
+
const callData = Starknet.CallData.compile({
|
|
45
45
|
implementation: accountClassHash,
|
|
46
|
-
selector: hash.getSelectorFromName('initialize'),
|
|
47
|
-
calldata: CallData.compile({
|
|
46
|
+
selector: Starknet.hash.getSelectorFromName('initialize'),
|
|
47
|
+
calldata: Starknet.CallData.compile({
|
|
48
48
|
signer: publicKey,
|
|
49
49
|
guardian: '0',
|
|
50
50
|
}),
|
|
51
51
|
});
|
|
52
|
-
const address = hash.calculateContractAddressFromHash(publicKey, accountProxyClassHash, callData, 0);
|
|
52
|
+
const address = Starknet.hash.calculateContractAddressFromHash(publicKey, accountProxyClassHash, callData, 0);
|
|
53
53
|
return address;
|
|
54
54
|
}
|
package/dist/config.d.ts
CHANGED
|
@@ -1,29 +1,45 @@
|
|
|
1
|
+
import type { Hex } from './types.js';
|
|
1
2
|
interface RawBridgedTokenConfig {
|
|
2
3
|
readonly name: string;
|
|
3
4
|
readonly symbol: string;
|
|
4
5
|
readonly decimals: number;
|
|
5
|
-
readonly l1_token_address:
|
|
6
|
-
readonly l1_bridge_address:
|
|
7
|
-
readonly l2_token_address:
|
|
8
|
-
readonly l2_bridge_address:
|
|
6
|
+
readonly l1_token_address: Hex;
|
|
7
|
+
readonly l1_bridge_address: Hex;
|
|
8
|
+
readonly l2_token_address: Hex;
|
|
9
|
+
readonly l2_bridge_address: Hex;
|
|
9
10
|
}
|
|
10
11
|
export interface RawParadexConfig {
|
|
11
12
|
readonly starknet_gateway_url: string;
|
|
13
|
+
readonly starknet_fullnode_rpc_url: string;
|
|
12
14
|
readonly starknet_chain_id: string;
|
|
13
15
|
readonly block_explorer_url: string;
|
|
14
|
-
readonly paraclear_address:
|
|
16
|
+
readonly paraclear_address: Hex;
|
|
15
17
|
readonly paraclear_decimals: number;
|
|
16
|
-
readonly paraclear_account_proxy_hash:
|
|
17
|
-
readonly paraclear_account_hash:
|
|
18
|
+
readonly paraclear_account_proxy_hash: Hex;
|
|
19
|
+
readonly paraclear_account_hash: Hex;
|
|
18
20
|
readonly bridged_tokens: readonly RawBridgedTokenConfig[];
|
|
19
|
-
readonly l1_core_contract_address:
|
|
20
|
-
readonly l1_operator_address:
|
|
21
|
+
readonly l1_core_contract_address: Hex;
|
|
22
|
+
readonly l1_operator_address: Hex;
|
|
21
23
|
readonly l1_chain_id: string;
|
|
22
24
|
}
|
|
25
|
+
interface BridgedTokenConfig {
|
|
26
|
+
readonly name: string;
|
|
27
|
+
readonly symbol: string;
|
|
28
|
+
readonly decimals: number;
|
|
29
|
+
readonly l1TokenAddress: Hex;
|
|
30
|
+
readonly l1BridgeAddress: Hex;
|
|
31
|
+
readonly l2TokenAddress: Hex;
|
|
32
|
+
readonly l2BridgeAddress: Hex;
|
|
33
|
+
}
|
|
23
34
|
export interface ParadexConfig {
|
|
35
|
+
readonly starknetFullNodeRpcUrl: string;
|
|
36
|
+
readonly starknetChainId: string;
|
|
24
37
|
readonly l1ChainId: string;
|
|
25
|
-
readonly paraclearAccountHash:
|
|
26
|
-
readonly paraclearAccountProxyHash:
|
|
38
|
+
readonly paraclearAccountHash: Hex;
|
|
39
|
+
readonly paraclearAccountProxyHash: Hex;
|
|
40
|
+
readonly paraclearAddress: Hex;
|
|
41
|
+
readonly paraclearDecimals: number;
|
|
42
|
+
readonly bridgedTokens: Record<string, BridgedTokenConfig>;
|
|
27
43
|
}
|
|
28
44
|
type ParadexEnvironment = 'testnet' | 'prod';
|
|
29
45
|
/**
|
|
@@ -31,4 +47,5 @@ type ParadexEnvironment = 'testnet' | 'prod';
|
|
|
31
47
|
* This is required for account derivation.
|
|
32
48
|
*/
|
|
33
49
|
export declare function fetchConfig(environment: ParadexEnvironment): Promise<ParadexConfig>;
|
|
50
|
+
export declare function buildConfig(rawConfig: RawParadexConfig): ParadexConfig;
|
|
34
51
|
export {};
|
package/dist/config.js
CHANGED
|
@@ -11,11 +11,7 @@ export async function fetchConfig(environment) {
|
|
|
11
11
|
}
|
|
12
12
|
const jsonResp = await resp.json();
|
|
13
13
|
const config = jsonResp;
|
|
14
|
-
return
|
|
15
|
-
l1ChainId: config.l1_chain_id,
|
|
16
|
-
paraclearAccountHash: config.paraclear_account_hash,
|
|
17
|
-
paraclearAccountProxyHash: config.paraclear_account_proxy_hash,
|
|
18
|
-
};
|
|
14
|
+
return buildConfig(config);
|
|
19
15
|
}
|
|
20
16
|
function assertParadexEnvironment(environment) {
|
|
21
17
|
if (environment !== 'testnet' && environment !== 'prod') {
|
|
@@ -25,3 +21,27 @@ function assertParadexEnvironment(environment) {
|
|
|
25
21
|
function getParadexApiUrl(environment) {
|
|
26
22
|
return `https://api.${environment}.paradex.trade/v1`;
|
|
27
23
|
}
|
|
24
|
+
export function buildConfig(rawConfig) {
|
|
25
|
+
const bridgedTokens = Object.fromEntries(rawConfig.bridged_tokens.map((token) => [
|
|
26
|
+
token.symbol,
|
|
27
|
+
{
|
|
28
|
+
name: token.name,
|
|
29
|
+
symbol: token.symbol,
|
|
30
|
+
decimals: token.decimals,
|
|
31
|
+
l1TokenAddress: token.l1_token_address,
|
|
32
|
+
l1BridgeAddress: token.l1_bridge_address,
|
|
33
|
+
l2TokenAddress: token.l2_token_address,
|
|
34
|
+
l2BridgeAddress: token.l2_bridge_address,
|
|
35
|
+
},
|
|
36
|
+
]));
|
|
37
|
+
return {
|
|
38
|
+
starknetFullNodeRpcUrl: rawConfig.starknet_fullnode_rpc_url,
|
|
39
|
+
starknetChainId: rawConfig.starknet_chain_id,
|
|
40
|
+
l1ChainId: rawConfig.l1_chain_id,
|
|
41
|
+
paraclearAccountHash: rawConfig.paraclear_account_hash,
|
|
42
|
+
paraclearAccountProxyHash: rawConfig.paraclear_account_proxy_hash,
|
|
43
|
+
paraclearAddress: rawConfig.paraclear_address,
|
|
44
|
+
paraclearDecimals: rawConfig.paraclear_decimals,
|
|
45
|
+
bridgedTokens,
|
|
46
|
+
};
|
|
47
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import * as _Account from './account.js';
|
|
2
2
|
import * as _Config from './config.js';
|
|
3
3
|
import * as _Signer from './ethereum-signer.js';
|
|
4
|
+
import * as _ParaclearProvider from './paraclear-provider.js';
|
|
5
|
+
import * as _Paraclear from './paraclear.js';
|
|
4
6
|
export declare const Config: {
|
|
5
7
|
fetchConfig: typeof _Config.fetchConfig;
|
|
6
8
|
};
|
|
@@ -10,3 +12,12 @@ export declare const Account: {
|
|
|
10
12
|
export declare const Signer: {
|
|
11
13
|
ethersSignerAdapter: typeof _Signer.ethersSignerAdapter;
|
|
12
14
|
};
|
|
15
|
+
export declare const ParaclearProvider: {
|
|
16
|
+
DefaultProvider: typeof _ParaclearProvider.DefaultProvider;
|
|
17
|
+
};
|
|
18
|
+
export declare const Paraclear: {
|
|
19
|
+
getTokenBalance: typeof _Paraclear.getTokenBalance;
|
|
20
|
+
getSocializedLossFactor: typeof _Paraclear.getSocializedLossFactor;
|
|
21
|
+
getReceivableAmount: typeof _Paraclear.getReceivableAmount;
|
|
22
|
+
withdraw: typeof _Paraclear.withdraw;
|
|
23
|
+
};
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import * as _Account from './account.js';
|
|
2
2
|
import * as _Config from './config.js';
|
|
3
3
|
import * as _Signer from './ethereum-signer.js';
|
|
4
|
+
import * as _ParaclearProvider from './paraclear-provider.js';
|
|
5
|
+
import * as _Paraclear from './paraclear.js';
|
|
4
6
|
export const Config = { fetchConfig: _Config.fetchConfig };
|
|
5
7
|
export const Account = { fromEthSigner: _Account.fromEthSigner };
|
|
6
8
|
export const Signer = { ethersSignerAdapter: _Signer.ethersSignerAdapter };
|
|
9
|
+
export const ParaclearProvider = {
|
|
10
|
+
DefaultProvider: _ParaclearProvider.DefaultProvider,
|
|
11
|
+
};
|
|
12
|
+
export const Paraclear = {
|
|
13
|
+
getTokenBalance: _Paraclear.getTokenBalance,
|
|
14
|
+
getSocializedLossFactor: _Paraclear.getSocializedLossFactor,
|
|
15
|
+
getReceivableAmount: _Paraclear.getReceivableAmount,
|
|
16
|
+
withdraw: _Paraclear.withdraw,
|
|
17
|
+
};
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import * as Starknet from 'starknet';
|
|
2
|
+
import type { Account } from './account.js';
|
|
3
|
+
import type { ParadexConfig } from './config.js';
|
|
4
|
+
import type { ParaclearProvider } from './paraclear-provider.js';
|
|
5
|
+
import type { Hex } from './types.js';
|
|
6
|
+
interface GetBalanceParams {
|
|
7
|
+
readonly config: ParadexConfig;
|
|
8
|
+
readonly provider: Pick<ParaclearProvider, 'callContract'>;
|
|
9
|
+
/**
|
|
10
|
+
* Account to get the balance for.
|
|
11
|
+
*/
|
|
12
|
+
readonly account: Pick<Account, 'address'>;
|
|
13
|
+
/**
|
|
14
|
+
* Token symbol.
|
|
15
|
+
* @example 'USDC'
|
|
16
|
+
*/
|
|
17
|
+
readonly token: string;
|
|
18
|
+
}
|
|
19
|
+
interface GetBalanceResult {
|
|
20
|
+
/**
|
|
21
|
+
* Token balance as a decimal string.
|
|
22
|
+
* @example '100.45'
|
|
23
|
+
* @example '45.2'
|
|
24
|
+
*/
|
|
25
|
+
readonly size: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Get the Paraclear balance of the given token for the given account.
|
|
29
|
+
*/
|
|
30
|
+
export declare function getTokenBalance(params: GetBalanceParams): Promise<GetBalanceResult>;
|
|
31
|
+
interface GetSocializedLossFactorParams {
|
|
32
|
+
readonly config: ParadexConfig;
|
|
33
|
+
readonly provider: Pick<ParaclearProvider, 'callContract'>;
|
|
34
|
+
}
|
|
35
|
+
interface GetSocializedLossFactorResult {
|
|
36
|
+
readonly socializedLossFactor: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Socialized losses happen when Paradex Insurance Fund is bankrupt
|
|
40
|
+
* due to large amounts of unprofitable liquidations. When socialized
|
|
41
|
+
* losses are active, (socialized loss factor > 0), the amount that
|
|
42
|
+
* the user will receive when withdrawing will be smaller than the
|
|
43
|
+
* requested amount.
|
|
44
|
+
*/
|
|
45
|
+
export declare function getSocializedLossFactor(params: GetSocializedLossFactorParams): Promise<GetSocializedLossFactorResult>;
|
|
46
|
+
interface GetReceivableAmountParams {
|
|
47
|
+
readonly config: ParadexConfig;
|
|
48
|
+
readonly provider: Pick<ParaclearProvider, 'callContract'>;
|
|
49
|
+
/**
|
|
50
|
+
* Token symbol.
|
|
51
|
+
* @example 'USDC'
|
|
52
|
+
*/
|
|
53
|
+
readonly token: string;
|
|
54
|
+
/**
|
|
55
|
+
* Amount of to withdraw from Paradex, as a decimal string.
|
|
56
|
+
* The receivable amount will be calculated based on this amount and
|
|
57
|
+
* can be less than the requested amount if socialized loss is active.
|
|
58
|
+
*/
|
|
59
|
+
readonly amount: string;
|
|
60
|
+
}
|
|
61
|
+
interface GetReceivableAmountResult {
|
|
62
|
+
/**
|
|
63
|
+
* Amount that will be received from Paradex, after socialized loss,
|
|
64
|
+
* if applicable, after a withdrawal of the given amount parameter.
|
|
65
|
+
* Decimal string.
|
|
66
|
+
* @example '99.45'
|
|
67
|
+
*/
|
|
68
|
+
readonly receivableAmount: string;
|
|
69
|
+
/**
|
|
70
|
+
* The receivable amount, converted to be used in chain calls,
|
|
71
|
+
* using the Paraclear decimals.
|
|
72
|
+
* @example '9945000000'
|
|
73
|
+
*/
|
|
74
|
+
readonly receivableAmountChain: string;
|
|
75
|
+
/**
|
|
76
|
+
* Socialized loss factor used to calculate the receivable amount.
|
|
77
|
+
* Decimal string.
|
|
78
|
+
* @example '0.05'
|
|
79
|
+
*/
|
|
80
|
+
readonly socializedLossFactor: string;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The receivable amount is calculated based on the current
|
|
84
|
+
* socialized loss factor: amount * (1 - socializedLossFactor)
|
|
85
|
+
*
|
|
86
|
+
* If the socialized loss factor is 0, the receivable amount
|
|
87
|
+
* will be equal to the requested amount.
|
|
88
|
+
*/
|
|
89
|
+
export declare function getReceivableAmount(params: GetReceivableAmountParams): Promise<GetReceivableAmountResult>;
|
|
90
|
+
interface WithdrawParams {
|
|
91
|
+
readonly config: ParadexConfig;
|
|
92
|
+
/**
|
|
93
|
+
* Account to withdraw from.
|
|
94
|
+
*/
|
|
95
|
+
readonly account: Account;
|
|
96
|
+
/**
|
|
97
|
+
* Token symbol.
|
|
98
|
+
* @example 'USDC'
|
|
99
|
+
*/
|
|
100
|
+
readonly token: string;
|
|
101
|
+
/**
|
|
102
|
+
* Amount to withdraw from Paradex.
|
|
103
|
+
* Note that this amount can be less than the amount that will be
|
|
104
|
+
* received if socialized loss is active. Use {@link getReceivableAmount}
|
|
105
|
+
* to calculate the amount that will be received.
|
|
106
|
+
* Decimal string.
|
|
107
|
+
* @example '100.45'
|
|
108
|
+
* @example '45.2'
|
|
109
|
+
*/
|
|
110
|
+
readonly amount: string;
|
|
111
|
+
/**
|
|
112
|
+
* Call to transfer funds to the bridge. This transaction will be called
|
|
113
|
+
* as the second transaction of the withdrawal transactions batch.
|
|
114
|
+
*
|
|
115
|
+
* The bridge call must be made with the receivable amount calculated
|
|
116
|
+
* using {@link getReceivableAmount}.
|
|
117
|
+
*/
|
|
118
|
+
readonly bridgeCall: Starknet.Call;
|
|
119
|
+
}
|
|
120
|
+
interface TransactionResult {
|
|
121
|
+
readonly hash: Hex;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Withdraw funds from Paraclear for the given account.
|
|
125
|
+
*
|
|
126
|
+
* Automatically make a batch transaction with `initiate_withdrawal`
|
|
127
|
+
* call to the Paraclear contract along with the transaction passed
|
|
128
|
+
* as `params.bridgeCall` The batch call is atomic. If either of
|
|
129
|
+
* the transactions fail, the entire batch gets reverted.
|
|
130
|
+
*
|
|
131
|
+
* If socialized loss is active, the bridge call must be constructed
|
|
132
|
+
* with an amount that accounts for the loss. To calculate that amount,
|
|
133
|
+
* use {@link getReceivableAmount}. Failing to do so can result in a
|
|
134
|
+
* failed withdrawal.
|
|
135
|
+
*/
|
|
136
|
+
export declare function withdraw(params: WithdrawParams): Promise<TransactionResult>;
|
|
137
|
+
export {};
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { BigNumber } from 'bignumber.js';
|
|
2
|
+
import * as Starknet from 'starknet';
|
|
3
|
+
const MAX_FEE = BigNumber('5e17'); // 5e17 WEI = 0.5 ETH
|
|
4
|
+
/**
|
|
5
|
+
* Get the Paraclear balance of the given token for the given account.
|
|
6
|
+
*/
|
|
7
|
+
export async function getTokenBalance(params) {
|
|
8
|
+
const token = params.config.bridgedTokens[params.token];
|
|
9
|
+
if (token == null) {
|
|
10
|
+
throw new Error(`Token ${params.token} is not supported`);
|
|
11
|
+
}
|
|
12
|
+
const { result } = await params.provider.callContract({
|
|
13
|
+
contractAddress: params.config.paraclearAddress,
|
|
14
|
+
entrypoint: 'getTokenAssetBalance',
|
|
15
|
+
calldata: Starknet.CallData.compile([
|
|
16
|
+
params.account.address,
|
|
17
|
+
token.l2TokenAddress,
|
|
18
|
+
]),
|
|
19
|
+
}, 'latest');
|
|
20
|
+
const value = result?.[0];
|
|
21
|
+
if (value == null) {
|
|
22
|
+
throw new Error('Failed to get token balance');
|
|
23
|
+
}
|
|
24
|
+
const valueBn = new BigNumber(value);
|
|
25
|
+
if (valueBn.isNaN()) {
|
|
26
|
+
throw new Error('Failed to parse token balance');
|
|
27
|
+
}
|
|
28
|
+
const chainSizeBn = valueBn;
|
|
29
|
+
const sizeBn = fromChainSize(chainSizeBn, params.config.paraclearDecimals);
|
|
30
|
+
return { size: sizeBn.toString() };
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Socialized losses happen when Paradex Insurance Fund is bankrupt
|
|
34
|
+
* due to large amounts of unprofitable liquidations. When socialized
|
|
35
|
+
* losses are active, (socialized loss factor > 0), the amount that
|
|
36
|
+
* the user will receive when withdrawing will be smaller than the
|
|
37
|
+
* requested amount.
|
|
38
|
+
*/
|
|
39
|
+
export async function getSocializedLossFactor(params) {
|
|
40
|
+
const { result } = await params.provider.callContract({
|
|
41
|
+
contractAddress: params.config.paraclearAddress,
|
|
42
|
+
entrypoint: 'getSocializedLossFactor',
|
|
43
|
+
});
|
|
44
|
+
const value = result?.[0];
|
|
45
|
+
if (value == null) {
|
|
46
|
+
throw new Error('Failed to get socialized loss factor');
|
|
47
|
+
}
|
|
48
|
+
const valueBn = new BigNumber(value);
|
|
49
|
+
if (valueBn.isNaN()) {
|
|
50
|
+
throw new Error('Failed to parse socialized loss factor');
|
|
51
|
+
}
|
|
52
|
+
const chainFactorBn = valueBn;
|
|
53
|
+
const factorBn = fromChainSize(chainFactorBn, params.config.paraclearDecimals);
|
|
54
|
+
return { socializedLossFactor: factorBn.toString() };
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The receivable amount is calculated based on the current
|
|
58
|
+
* socialized loss factor: amount * (1 - socializedLossFactor)
|
|
59
|
+
*
|
|
60
|
+
* If the socialized loss factor is 0, the receivable amount
|
|
61
|
+
* will be equal to the requested amount.
|
|
62
|
+
*/
|
|
63
|
+
export async function getReceivableAmount(params) {
|
|
64
|
+
const amountBn = new BigNumber(params.amount);
|
|
65
|
+
if (amountBn.isNaN()) {
|
|
66
|
+
throw new Error('Invalid amount');
|
|
67
|
+
}
|
|
68
|
+
const token = params.config.bridgedTokens[params.token];
|
|
69
|
+
if (token == null) {
|
|
70
|
+
throw new Error(`Token ${params.token} is not supported`);
|
|
71
|
+
}
|
|
72
|
+
const { socializedLossFactor } = await getSocializedLossFactor({
|
|
73
|
+
config: params.config,
|
|
74
|
+
provider: params.provider,
|
|
75
|
+
});
|
|
76
|
+
const receivableAmount = amountBn.times(BigNumber(1).minus(socializedLossFactor));
|
|
77
|
+
const receivableAmountChainBn = toChainSize(receivableAmount.toString(), token.decimals);
|
|
78
|
+
return {
|
|
79
|
+
receivableAmount: receivableAmount.toString(),
|
|
80
|
+
receivableAmountChain: receivableAmountChainBn.toString(),
|
|
81
|
+
socializedLossFactor,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Withdraw funds from Paraclear for the given account.
|
|
86
|
+
*
|
|
87
|
+
* Automatically make a batch transaction with `initiate_withdrawal`
|
|
88
|
+
* call to the Paraclear contract along with the transaction passed
|
|
89
|
+
* as `params.bridgeCall` The batch call is atomic. If either of
|
|
90
|
+
* the transactions fail, the entire batch gets reverted.
|
|
91
|
+
*
|
|
92
|
+
* If socialized loss is active, the bridge call must be constructed
|
|
93
|
+
* with an amount that accounts for the loss. To calculate that amount,
|
|
94
|
+
* use {@link getReceivableAmount}. Failing to do so can result in a
|
|
95
|
+
* failed withdrawal.
|
|
96
|
+
*/
|
|
97
|
+
export async function withdraw(params) {
|
|
98
|
+
const token = params.config.bridgedTokens[params.token];
|
|
99
|
+
if (token == null) {
|
|
100
|
+
throw new Error(`Token ${params.token} is not supported`);
|
|
101
|
+
}
|
|
102
|
+
const chainAmountBn = toChainSize(params.amount, params.config.paraclearDecimals);
|
|
103
|
+
// ensure unique txn hash on subsequent calls via `intNoise`
|
|
104
|
+
const maxFee = MAX_FEE.plus(intNoise(10000));
|
|
105
|
+
const result = await params.account.execute([
|
|
106
|
+
{
|
|
107
|
+
contractAddress: params.config.paraclearAddress,
|
|
108
|
+
entrypoint: 'withdraw',
|
|
109
|
+
calldata: [token.l2TokenAddress, chainAmountBn.toString()],
|
|
110
|
+
},
|
|
111
|
+
params.bridgeCall,
|
|
112
|
+
], undefined, { maxFee: maxFee.toString() });
|
|
113
|
+
return { hash: result.transaction_hash };
|
|
114
|
+
}
|
|
115
|
+
function fromChainSize(size, decimals) {
|
|
116
|
+
return new BigNumber(size).div(10 ** decimals);
|
|
117
|
+
}
|
|
118
|
+
function toChainSize(size, decimals) {
|
|
119
|
+
return new BigNumber(size)
|
|
120
|
+
.times(10 ** decimals)
|
|
121
|
+
.integerValue(BigNumber.ROUND_FLOOR);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Generates a pseudorandom integer between 0 and `max`.
|
|
125
|
+
* @param max Maximum value for the noise.
|
|
126
|
+
*/
|
|
127
|
+
function intNoise(max) {
|
|
128
|
+
return Math.round(Math.random() * max);
|
|
129
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type Hex = `0x${string}`;
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/utils.d.ts
ADDED
package/dist/utils.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@paradex/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "JavaScript SDK for Paradex",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"files": [
|
|
@@ -28,7 +28,8 @@
|
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
30
|
"@starkware-industries/starkware-crypto-utils": "^0.2.1",
|
|
31
|
-
"
|
|
31
|
+
"bignumber.js": "^9.1.2",
|
|
32
|
+
"starknet": "^5.24.3"
|
|
32
33
|
},
|
|
33
34
|
"devDependencies": {
|
|
34
35
|
"@ianvs/prettier-plugin-sort-imports": "^4.2.1",
|