@paradex/sdk 0.11.0 → 0.12.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 +132 -2
- package/dist/api-errors.d.ts +76 -0
- package/dist/api-errors.js +249 -0
- package/dist/builder-app.d.ts +329 -0
- package/dist/builder-app.js +527 -0
- package/dist/builder-codes.d.ts +4 -1
- package/dist/builder-codes.js +4 -2
- package/dist/evm-owner-client.d.ts +101 -0
- package/dist/evm-owner-client.js +191 -0
- package/dist/evm-owner-signer.d.ts +81 -0
- package/dist/evm-owner-signer.js +165 -0
- package/dist/index.d.ts +48 -1
- package/dist/index.js +40 -1
- package/dist/owner-auth.d.ts +68 -0
- package/dist/owner-auth.js +184 -0
- package/dist/paraclear.d.ts +6 -1
- package/dist/paraclear.js +15 -8
- package/dist/rfq.d.ts +54 -0
- package/dist/rfq.js +64 -0
- package/dist/sbe.d.ts +47 -0
- package/dist/sbe.js +744 -0
- package/dist/session-accounts.d.ts +33 -1
- package/dist/session-accounts.js +148 -40
- package/dist/session-auth.d.ts +3 -0
- package/dist/session-auth.js +12 -0
- package/dist/session-transport.d.ts +8 -1
- package/dist/session-transport.js +4 -0
- package/dist/siwe.d.ts +35 -0
- package/dist/siwe.js +94 -0
- package/dist/trading.d.ts +98 -0
- package/dist/trading.js +39 -0
- package/dist/wallet.d.ts +78 -0
- package/dist/wallet.js +157 -0
- package/package.json +4 -2
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { BigNumber } from 'bignumber.js';
|
|
2
|
+
import * as Starknet from 'starknet';
|
|
3
|
+
import { fetchOnboarding } from './account.js';
|
|
4
|
+
import { createEip191StarknetSigner, } from './evm-owner-signer.js';
|
|
5
|
+
import { DefaultProvider } from './paraclear-provider.js';
|
|
6
|
+
import * as Paraclear from './paraclear.js';
|
|
7
|
+
/**
|
|
8
|
+
* L2 gas reserved for `__validate__` on an EIP-191 account. Validation runs
|
|
9
|
+
* keccak256 and a secp256k1 ecrecover in Cairo, a fixed cost of about 17.3M
|
|
10
|
+
* L2 gas whatever the call does; this leaves headroom over it.
|
|
11
|
+
*/
|
|
12
|
+
export const EVM_VALIDATE_L2_GAS = 25000000n;
|
|
13
|
+
/**
|
|
14
|
+
* The fee is estimated with `SKIP_VALIDATE`, so the wallet is asked to sign
|
|
15
|
+
* once, not twice. The estimate then leaves out `__validate__`, whose cost
|
|
16
|
+
* is fixed, so it is added rather than scaled: a multiplier on a cheap
|
|
17
|
+
* call's estimate falls short of it and the transaction runs out of gas.
|
|
18
|
+
* Execution gets 50% headroom because the estimate runs at `pre_confirmed`
|
|
19
|
+
* and execution at inclusion can cost more.
|
|
20
|
+
*/
|
|
21
|
+
export function withEvmValidationGas(bounds) {
|
|
22
|
+
const estimated = BigInt(bounds.l2_gas.max_amount);
|
|
23
|
+
return {
|
|
24
|
+
...bounds,
|
|
25
|
+
l2_gas: {
|
|
26
|
+
...bounds.l2_gas,
|
|
27
|
+
max_amount: (estimated * 3n) / 2n + EVM_VALIDATE_L2_GAS,
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Client for an EVM-owned (EIP-191) Paradex account, whose on-chain owner is
|
|
33
|
+
* an EVM wallet rather than a Stark key. Every transaction is signed by the
|
|
34
|
+
* owner wallet with `personal_sign` over the Starknet transaction hash.
|
|
35
|
+
*
|
|
36
|
+
* No Stark key is derived: `Client.fromEthSigner` derives a key for a
|
|
37
|
+
* different (Stark-owned) account and must not be used for these accounts.
|
|
38
|
+
*
|
|
39
|
+
* Balance reads (`getTokenBalance`, `getMaxWithdraw`) are not offered: the
|
|
40
|
+
* Paradex full node returns account data only to authenticated callers. Use
|
|
41
|
+
* the REST API (`GET /v1/balance`) with the account's JWT instead.
|
|
42
|
+
*/
|
|
43
|
+
export class EvmOwnerClient {
|
|
44
|
+
constructor(config, provider, account, ownerAddress) {
|
|
45
|
+
this.config = config;
|
|
46
|
+
this.provider = provider;
|
|
47
|
+
this.account = account;
|
|
48
|
+
this.ownerAddress = ownerAddress;
|
|
49
|
+
}
|
|
50
|
+
static async create({ config, signer, accountAddress, apiUrl, }) {
|
|
51
|
+
const ownerAddress = await signer.getAddress();
|
|
52
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(ownerAddress)) {
|
|
53
|
+
throw new Error('EVM owner signer returned an invalid address; expected a 0x-prefixed 20-byte address');
|
|
54
|
+
}
|
|
55
|
+
const address = accountAddress ?? (await lookupAccount());
|
|
56
|
+
if (!/^0x[0-9a-fA-F]{1,64}$/.test(address)) {
|
|
57
|
+
throw new Error('accountAddress must be a 0x-prefixed Starknet address');
|
|
58
|
+
}
|
|
59
|
+
// No credentials: the provider never signs full-node auth headers, which
|
|
60
|
+
// need a Stark key this account does not have.
|
|
61
|
+
const provider = new DefaultProvider(config);
|
|
62
|
+
const account = new Starknet.Account({
|
|
63
|
+
provider,
|
|
64
|
+
address,
|
|
65
|
+
signer: createEip191StarknetSigner(signer, ownerAddress),
|
|
66
|
+
});
|
|
67
|
+
return new EvmOwnerClient(config, provider, account, ownerAddress);
|
|
68
|
+
async function lookupAccount() {
|
|
69
|
+
const resolvedApiUrl = apiUrl ?? config.paradexApiUrl;
|
|
70
|
+
if (resolvedApiUrl == null || resolvedApiUrl === '') {
|
|
71
|
+
throw new Error('Looking up the account needs an API URL: pass apiUrl or accountAddress, or use a config from Config.fetch()');
|
|
72
|
+
}
|
|
73
|
+
const info = await fetchOnboarding({
|
|
74
|
+
apiUrl: resolvedApiUrl,
|
|
75
|
+
ethAddress: ownerAddress,
|
|
76
|
+
});
|
|
77
|
+
if (info.accountSignerType !== 'eip191') {
|
|
78
|
+
throw new Error(`The wallet's Paradex account is not EVM-owned (signer type ${info.accountSignerType}); use Client.fromEthSigner`);
|
|
79
|
+
}
|
|
80
|
+
if (!info.exists) {
|
|
81
|
+
throw new Error('This wallet has no EVM-owned Paradex account yet; onboard it in the Paradex app first');
|
|
82
|
+
}
|
|
83
|
+
return info.address;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** The Paradex (Starknet) account address. */
|
|
87
|
+
getAddress() {
|
|
88
|
+
return this.account.address;
|
|
89
|
+
}
|
|
90
|
+
/** The EVM wallet that owns the account and signs its transactions. */
|
|
91
|
+
getOwnerAddress() {
|
|
92
|
+
return this.ownerAddress;
|
|
93
|
+
}
|
|
94
|
+
async getSocializedLossFactor() {
|
|
95
|
+
return await Paraclear.getSocializedLossFactor({
|
|
96
|
+
provider: this.provider,
|
|
97
|
+
config: this.config,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/** The amount a withdrawal of `amount` delivers after socialized loss. */
|
|
101
|
+
async getReceivableAmount(token, amount) {
|
|
102
|
+
return await Paraclear.getReceivableAmount({
|
|
103
|
+
provider: this.provider,
|
|
104
|
+
config: this.config,
|
|
105
|
+
token,
|
|
106
|
+
amount,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Withdraws `amount` of `token` from Paraclear and runs `bridgeCall` in the
|
|
111
|
+
* same atomic transaction, signed by the owner wallet (one signature
|
|
112
|
+
* prompt).
|
|
113
|
+
*
|
|
114
|
+
* `paraclear.withdraw` moves the funds to the account contract's own
|
|
115
|
+
* Starknet token balance; the bridge call must then move them out (for
|
|
116
|
+
* example `starkgateWithdrawCall`). Build it for the receivable amount
|
|
117
|
+
* from `getReceivableAmount`. Do not use `paraclear.transfer` as a bridge
|
|
118
|
+
* call: it credits another Paradex account's Paraclear balance, not the
|
|
119
|
+
* bridge.
|
|
120
|
+
*/
|
|
121
|
+
async withdraw(token, amount, bridgeCall) {
|
|
122
|
+
const amountBn = new BigNumber(amount);
|
|
123
|
+
if (amountBn.isNaN() || !amountBn.isGreaterThan(0)) {
|
|
124
|
+
throw new Error('Invalid amount');
|
|
125
|
+
}
|
|
126
|
+
const calls = Paraclear.buildWithdrawCalls({
|
|
127
|
+
config: this.config,
|
|
128
|
+
token,
|
|
129
|
+
amount,
|
|
130
|
+
bridgeCall,
|
|
131
|
+
});
|
|
132
|
+
return await this.execute(calls);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Signs and sends any invoke from the account with the owner wallet.
|
|
136
|
+
* @advanced Prefer `withdraw`.
|
|
137
|
+
*/
|
|
138
|
+
async execute(calls) {
|
|
139
|
+
const batch = Array.isArray(calls)
|
|
140
|
+
? [...calls]
|
|
141
|
+
: [calls];
|
|
142
|
+
const blockIdentifier = Starknet.BlockTag.PRE_CONFIRMED;
|
|
143
|
+
const nonce = await this.account.getNonce(blockIdentifier);
|
|
144
|
+
const fees = await this.account.estimateInvokeFee(batch, {
|
|
145
|
+
blockIdentifier,
|
|
146
|
+
nonce,
|
|
147
|
+
tip: 0n,
|
|
148
|
+
skipValidate: true,
|
|
149
|
+
});
|
|
150
|
+
const result = await this.account.execute(batch, {
|
|
151
|
+
nonce,
|
|
152
|
+
tip: 0n,
|
|
153
|
+
resourceBounds: withEvmValidationGas(fees.resourceBounds),
|
|
154
|
+
});
|
|
155
|
+
return { hash: result.transaction_hash };
|
|
156
|
+
}
|
|
157
|
+
async waitForTransaction(txHash, options) {
|
|
158
|
+
return await this.provider.waitForTransaction(txHash, options);
|
|
159
|
+
}
|
|
160
|
+
/** The underlying provider (unauthenticated full-node RPC). */
|
|
161
|
+
getProvider() {
|
|
162
|
+
return this.provider;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* The StarkGate bridge call that sends a withdrawn amount to Ethereum: the
|
|
167
|
+
* funds are claimable on L1 once the Starknet block is proven there.
|
|
168
|
+
*/
|
|
169
|
+
export function starkgateWithdrawCall({ config, token, l1Recipient, amountChain, }) {
|
|
170
|
+
const tokenConfig = config.bridgedTokens[token];
|
|
171
|
+
if (tokenConfig == null) {
|
|
172
|
+
throw new Error(`Token ${token} is not supported`);
|
|
173
|
+
}
|
|
174
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(l1Recipient)) {
|
|
175
|
+
throw new Error('l1Recipient must be a 0x-prefixed 20-byte address');
|
|
176
|
+
}
|
|
177
|
+
if (!/^[0-9]+$/.test(amountChain) || BigInt(amountChain) === 0n) {
|
|
178
|
+
throw new Error('amountChain must be a positive integer string');
|
|
179
|
+
}
|
|
180
|
+
const amount = Starknet.uint256.bnToUint256(amountChain);
|
|
181
|
+
return {
|
|
182
|
+
contractAddress: tokenConfig.l2BridgeAddress,
|
|
183
|
+
entrypoint: 'initiate_token_withdraw',
|
|
184
|
+
calldata: [
|
|
185
|
+
tokenConfig.l1TokenAddress,
|
|
186
|
+
l1Recipient,
|
|
187
|
+
Starknet.num.toHex(amount.low),
|
|
188
|
+
Starknet.num.toHex(amount.high),
|
|
189
|
+
],
|
|
190
|
+
};
|
|
191
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { ethers } from 'ethers';
|
|
2
|
+
import * as Starknet from 'starknet';
|
|
3
|
+
import type { Eip1193Provider } from './session-owner-signer.js';
|
|
4
|
+
import type { Hex } from './types.js';
|
|
5
|
+
/**
|
|
6
|
+
* The EVM wallet that owns an EVM-owned (EIP-191) Paradex account.
|
|
7
|
+
*
|
|
8
|
+
* The account contract (Argent v0.5, `Eip191` owner) accepts a transaction
|
|
9
|
+
* when the owner wallet `personal_sign`s its 32-byte Starknet transaction
|
|
10
|
+
* hash, so this is all the SDK needs from the wallet. No Stark key is
|
|
11
|
+
* derived or used.
|
|
12
|
+
*
|
|
13
|
+
* Adapters: {@link evmOwnerSignerFromEthers}, {@link evmOwnerSignerFromViem},
|
|
14
|
+
* {@link evmOwnerSignerFromEip1193}. A custom signer (an MPC or embedded
|
|
15
|
+
* wallet API) must sign the 32 bytes as bytes, not their hex spelling as
|
|
16
|
+
* text.
|
|
17
|
+
*/
|
|
18
|
+
export interface EvmOwnerSigner {
|
|
19
|
+
/** The owner wallet's address. */
|
|
20
|
+
readonly getAddress: () => Promise<string>;
|
|
21
|
+
/**
|
|
22
|
+
* EIP-191 `personal_sign` over `message`, the 32 raw bytes of the
|
|
23
|
+
* transaction hash: the wallet signs
|
|
24
|
+
* `keccak256("\x19Ethereum Signed Message:\n32" ‖ message)`.
|
|
25
|
+
* Must return a 65-byte `r‖s‖v` hex signature.
|
|
26
|
+
*/
|
|
27
|
+
readonly signMessage: (message: Uint8Array) => Promise<string>;
|
|
28
|
+
}
|
|
29
|
+
/** Uses an ethers v6 `Signer` (e.g. `Wallet`, `BrowserProvider.getSigner()`). */
|
|
30
|
+
export declare function evmOwnerSignerFromEthers(signer: ethers.Signer): EvmOwnerSigner;
|
|
31
|
+
/** The subset of a viem `WalletClient` (or `LocalAccount`) used here. */
|
|
32
|
+
export interface ViemMessageSigner {
|
|
33
|
+
readonly signMessage: (args: {
|
|
34
|
+
readonly account?: any;
|
|
35
|
+
readonly message: {
|
|
36
|
+
readonly raw: Hex;
|
|
37
|
+
};
|
|
38
|
+
}) => Promise<string>;
|
|
39
|
+
}
|
|
40
|
+
export interface EvmOwnerSignerFromViemParams {
|
|
41
|
+
/** A viem `WalletClient`, or a `LocalAccount` such as `privateKeyToAccount`. */
|
|
42
|
+
readonly client: ViemMessageSigner;
|
|
43
|
+
/** The owner wallet address, or the viem `Account` to sign with. */
|
|
44
|
+
readonly account: string | {
|
|
45
|
+
readonly address: string;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** Uses a viem `WalletClient` or `LocalAccount`. */
|
|
49
|
+
export declare function evmOwnerSignerFromViem({ client, account, }: EvmOwnerSignerFromViemParams): EvmOwnerSigner;
|
|
50
|
+
export interface EvmOwnerSignerFromEip1193Params {
|
|
51
|
+
readonly provider: Eip1193Provider;
|
|
52
|
+
/** The owner wallet address. Defaults to the wallet's first account. */
|
|
53
|
+
readonly address?: string;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Uses an injected wallet (`window.ethereum`), a Privy embedded wallet's
|
|
57
|
+
* EIP-1193 provider, or any other EIP-1193 provider, via `personal_sign`.
|
|
58
|
+
*/
|
|
59
|
+
export declare function evmOwnerSignerFromEip1193({ provider, address, }: EvmOwnerSignerFromEip1193Params): EvmOwnerSigner;
|
|
60
|
+
/**
|
|
61
|
+
* A Starknet `SignerInterface` for an Argent v0.5 account whose owner is an
|
|
62
|
+
* `Eip191` signer. Signs invoke transactions only.
|
|
63
|
+
*
|
|
64
|
+
* Each signature is checked to recover to `ownerAddress` before it is
|
|
65
|
+
* returned, so a wallet that signs the wrong bytes fails here with a clear
|
|
66
|
+
* error instead of as an on-chain validation failure.
|
|
67
|
+
*
|
|
68
|
+
* @internal Use `Client.fromEvmOwner()`.
|
|
69
|
+
*/
|
|
70
|
+
export declare function createEip191StarknetSigner(owner: EvmOwnerSigner, ownerAddress: string): Starknet.SignerInterface;
|
|
71
|
+
/** The transaction hash as 32 big-endian bytes, the message the contract checks. */
|
|
72
|
+
export declare function txHashBytes(txHash: Starknet.BigNumberish): Uint8Array;
|
|
73
|
+
/**
|
|
74
|
+
* Encodes a 65-byte EVM signature as the Argent v0.5 account signature:
|
|
75
|
+
* `[1, Eip191 = 3, eth_address, r.low, r.high, s.low, s.high, y_parity]`
|
|
76
|
+
* (one owner signature, no guardian).
|
|
77
|
+
*
|
|
78
|
+
* A high-s signature is converted to its low-s form. Throws unless the
|
|
79
|
+
* signature recovers to `ownerAddress` over the EIP-191 hash of `txHash`.
|
|
80
|
+
*/
|
|
81
|
+
export declare function formatEip191Signature(ownerAddress: string, txHash: Starknet.BigNumberish, signatureHex: string): string[];
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { secp256k1 } from '@noble/curves/secp256k1';
|
|
2
|
+
import { keccak_256 } from '@noble/hashes/sha3';
|
|
3
|
+
import * as Starknet from 'starknet';
|
|
4
|
+
/** Uses an ethers v6 `Signer` (e.g. `Wallet`, `BrowserProvider.getSigner()`). */
|
|
5
|
+
export function evmOwnerSignerFromEthers(signer) {
|
|
6
|
+
return {
|
|
7
|
+
getAddress: async () => await signer.getAddress(),
|
|
8
|
+
// A Uint8Array is signed as bytes; a string would be signed as UTF-8.
|
|
9
|
+
signMessage: async (message) => await signer.signMessage(message),
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
/** Uses a viem `WalletClient` or `LocalAccount`. */
|
|
13
|
+
export function evmOwnerSignerFromViem({ client, account, }) {
|
|
14
|
+
const address = typeof account === 'string' ? account : account.address;
|
|
15
|
+
return {
|
|
16
|
+
getAddress: async () => address,
|
|
17
|
+
signMessage: async (message) => await client.signMessage({
|
|
18
|
+
account,
|
|
19
|
+
message: { raw: bytesToHex(message) },
|
|
20
|
+
}),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Uses an injected wallet (`window.ethereum`), a Privy embedded wallet's
|
|
25
|
+
* EIP-1193 provider, or any other EIP-1193 provider, via `personal_sign`.
|
|
26
|
+
*/
|
|
27
|
+
export function evmOwnerSignerFromEip1193({ provider, address, }) {
|
|
28
|
+
const getAddress = async () => {
|
|
29
|
+
if (address != null)
|
|
30
|
+
return address;
|
|
31
|
+
const accounts = await provider.request({ method: 'eth_requestAccounts' });
|
|
32
|
+
const first = Array.isArray(accounts) ? accounts[0] : undefined;
|
|
33
|
+
if (typeof first !== 'string') {
|
|
34
|
+
throw new Error('Wallet returned no accounts');
|
|
35
|
+
}
|
|
36
|
+
return first;
|
|
37
|
+
};
|
|
38
|
+
return {
|
|
39
|
+
getAddress,
|
|
40
|
+
signMessage: async (message) => {
|
|
41
|
+
const signature = await provider.request({
|
|
42
|
+
method: 'personal_sign',
|
|
43
|
+
params: [bytesToHex(message), await getAddress()],
|
|
44
|
+
});
|
|
45
|
+
if (typeof signature !== 'string') {
|
|
46
|
+
throw new Error('Wallet returned a non-string signature');
|
|
47
|
+
}
|
|
48
|
+
return signature;
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* A Starknet `SignerInterface` for an Argent v0.5 account whose owner is an
|
|
54
|
+
* `Eip191` signer. Signs invoke transactions only.
|
|
55
|
+
*
|
|
56
|
+
* Each signature is checked to recover to `ownerAddress` before it is
|
|
57
|
+
* returned, so a wallet that signs the wrong bytes fails here with a clear
|
|
58
|
+
* error instead of as an on-chain validation failure.
|
|
59
|
+
*
|
|
60
|
+
* @internal Use `Client.fromEvmOwner()`.
|
|
61
|
+
*/
|
|
62
|
+
export function createEip191StarknetSigner(owner, ownerAddress) {
|
|
63
|
+
const unsupported = (what) => async () => {
|
|
64
|
+
throw new Error(`EVM owner signer cannot sign ${what}`);
|
|
65
|
+
};
|
|
66
|
+
return {
|
|
67
|
+
getPubKey: async () => '0x0',
|
|
68
|
+
signMessage: unsupported('Starknet typed data'),
|
|
69
|
+
signDeployAccountTransaction: unsupported('deploy account transactions'),
|
|
70
|
+
signDeclareTransaction: unsupported('declare transactions'),
|
|
71
|
+
async signTransaction(transactions, details) {
|
|
72
|
+
if (!('resourceBounds' in details)) {
|
|
73
|
+
throw new Error('EVM owner signer signs V3 transactions only');
|
|
74
|
+
}
|
|
75
|
+
const compiledCalldata = Starknet.transaction.getExecuteCalldata(transactions, details.cairoVersion);
|
|
76
|
+
const txHash = Starknet.hash.calculateInvokeTransactionHash({
|
|
77
|
+
senderAddress: details.walletAddress,
|
|
78
|
+
version: details.version,
|
|
79
|
+
compiledCalldata,
|
|
80
|
+
chainId: details.chainId,
|
|
81
|
+
nonce: details.nonce,
|
|
82
|
+
accountDeploymentData: details.accountDeploymentData,
|
|
83
|
+
nonceDataAvailabilityMode: Starknet.stark.intDAM(details.nonceDataAvailabilityMode),
|
|
84
|
+
feeDataAvailabilityMode: Starknet.stark.intDAM(details.feeDataAvailabilityMode),
|
|
85
|
+
resourceBounds: details.resourceBounds,
|
|
86
|
+
tip: details.tip,
|
|
87
|
+
paymasterData: details.paymasterData,
|
|
88
|
+
});
|
|
89
|
+
const signature = await owner.signMessage(txHashBytes(txHash));
|
|
90
|
+
return formatEip191Signature(ownerAddress, txHash, signature);
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/** The transaction hash as 32 big-endian bytes, the message the contract checks. */
|
|
95
|
+
export function txHashBytes(txHash) {
|
|
96
|
+
const hex = BigInt(txHash).toString(16).padStart(64, '0');
|
|
97
|
+
if (hex.length !== 64)
|
|
98
|
+
throw new Error('Transaction hash exceeds 32 bytes');
|
|
99
|
+
return hexToBytes(hex);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Encodes a 65-byte EVM signature as the Argent v0.5 account signature:
|
|
103
|
+
* `[1, Eip191 = 3, eth_address, r.low, r.high, s.low, s.high, y_parity]`
|
|
104
|
+
* (one owner signature, no guardian).
|
|
105
|
+
*
|
|
106
|
+
* A high-s signature is converted to its low-s form. Throws unless the
|
|
107
|
+
* signature recovers to `ownerAddress` over the EIP-191 hash of `txHash`.
|
|
108
|
+
*/
|
|
109
|
+
export function formatEip191Signature(ownerAddress, txHash, signatureHex) {
|
|
110
|
+
const sig = signatureHex.replace(/^0x/, '');
|
|
111
|
+
if (!/^[0-9a-fA-F]{130}$/.test(sig)) {
|
|
112
|
+
throw new Error('Owner signature must be a 65-byte EOA signature; contract wallets are not supported');
|
|
113
|
+
}
|
|
114
|
+
const r = BigInt(`0x${sig.slice(0, 64)}`);
|
|
115
|
+
let s = BigInt(`0x${sig.slice(64, 128)}`);
|
|
116
|
+
const v = parseInt(sig.slice(128, 130), 16);
|
|
117
|
+
let yParity = v >= 27 ? v - 27 : v;
|
|
118
|
+
if (yParity !== 0 && yParity !== 1) {
|
|
119
|
+
throw new Error(`Owner signature has an invalid v: ${v}`);
|
|
120
|
+
}
|
|
121
|
+
// The account accepts only low-s. A high-s signature is the same signature
|
|
122
|
+
// as (n - s) with the other parity, so convert it rather than fail on chain.
|
|
123
|
+
const n = secp256k1.CURVE.n;
|
|
124
|
+
if (s > n / 2n) {
|
|
125
|
+
s = n - s;
|
|
126
|
+
yParity ^= 1;
|
|
127
|
+
}
|
|
128
|
+
const recovered = recoverEip191Address(txHashBytes(txHash), r, s, yParity);
|
|
129
|
+
if (recovered.toLowerCase() !== ownerAddress.toLowerCase()) {
|
|
130
|
+
throw new Error(`Owner signature recovers to ${recovered}, not the account owner ${ownerAddress}. ` +
|
|
131
|
+
'The wallet must personal_sign the 32 hash bytes, not their hex text.');
|
|
132
|
+
}
|
|
133
|
+
const rU = Starknet.uint256.bnToUint256(r);
|
|
134
|
+
const sU = Starknet.uint256.bnToUint256(s);
|
|
135
|
+
return [
|
|
136
|
+
'0x1',
|
|
137
|
+
'0x3',
|
|
138
|
+
Starknet.num.toHex(ownerAddress),
|
|
139
|
+
Starknet.num.toHex(rU.low),
|
|
140
|
+
Starknet.num.toHex(rU.high),
|
|
141
|
+
Starknet.num.toHex(sU.low),
|
|
142
|
+
Starknet.num.toHex(sU.high),
|
|
143
|
+
Starknet.num.toHex(yParity),
|
|
144
|
+
];
|
|
145
|
+
}
|
|
146
|
+
function recoverEip191Address(message, r, s, recovery) {
|
|
147
|
+
const prefix = new TextEncoder().encode(`\x19Ethereum Signed Message:\n${message.length}`);
|
|
148
|
+
const digest = keccak_256(new Uint8Array([...prefix, ...message]));
|
|
149
|
+
const publicKey = new secp256k1.Signature(r, s)
|
|
150
|
+
.addRecoveryBit(recovery)
|
|
151
|
+
.recoverPublicKey(digest)
|
|
152
|
+
.toRawBytes(false);
|
|
153
|
+
const address = keccak_256(publicKey.slice(1)).slice(-20);
|
|
154
|
+
return bytesToHex(address);
|
|
155
|
+
}
|
|
156
|
+
function bytesToHex(bytes) {
|
|
157
|
+
return `0x${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}`;
|
|
158
|
+
}
|
|
159
|
+
function hexToBytes(hex) {
|
|
160
|
+
const out = new Uint8Array(hex.length / 2);
|
|
161
|
+
for (let i = 0; i < out.length; i++) {
|
|
162
|
+
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
163
|
+
}
|
|
164
|
+
return out;
|
|
165
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,22 @@
|
|
|
1
1
|
import * as _Account from './account.js';
|
|
2
|
+
import * as _ApiErrors from './api-errors.js';
|
|
2
3
|
import * as _Client from './client.js';
|
|
3
4
|
import * as _Config from './config.js';
|
|
4
5
|
import * as _Signer from './ethereum-signer.js';
|
|
6
|
+
import * as _EvmOwnerClient from './evm-owner-client.js';
|
|
7
|
+
import * as _EvmOwnerSigner from './evm-owner-signer.js';
|
|
5
8
|
import * as _SessionKey from './session-key.js';
|
|
6
9
|
import * as _SessionOwnerSigner from './session-owner-signer.js';
|
|
7
10
|
import * as _SessionTypedData from './session-typed-data.js';
|
|
11
|
+
import * as _Wallet from './wallet.js';
|
|
8
12
|
export declare const Client: {
|
|
9
13
|
fromEthSigner: (params: _Client.CreateClientFromEthSignerParams) => Promise<_Client.ParadexClient>;
|
|
10
14
|
fromStarknetAccount: (params: _Client.CreateClientFromStarknetAccountParams) => Promise<_Client.ParadexClient>;
|
|
15
|
+
/**
|
|
16
|
+
* Client for an EVM-owned (EIP-191) account: every transaction is signed
|
|
17
|
+
* by the owner wallet. No Stark key is derived.
|
|
18
|
+
*/
|
|
19
|
+
fromEvmOwner: (params: _EvmOwnerClient.CreateClientFromEvmOwnerParams) => Promise<_EvmOwnerClient.EvmOwnerClient>;
|
|
11
20
|
};
|
|
12
21
|
export declare const Config: {
|
|
13
22
|
fetch: typeof _Config.fetchConfig;
|
|
@@ -18,6 +27,30 @@ export declare const Onboarding: {
|
|
|
18
27
|
export declare const Signer: {
|
|
19
28
|
fromEthers: typeof _Signer.ethersSignerAdapter;
|
|
20
29
|
};
|
|
30
|
+
/** Owner signers for EVM-owned (EIP-191) accounts, for `Client.fromEvmOwner`. */
|
|
31
|
+
export declare const EvmOwnerSigner: {
|
|
32
|
+
fromEthers: typeof _EvmOwnerSigner.evmOwnerSignerFromEthers;
|
|
33
|
+
fromViem: typeof _EvmOwnerSigner.evmOwnerSignerFromViem;
|
|
34
|
+
fromEip1193: typeof _EvmOwnerSigner.evmOwnerSignerFromEip1193;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* The user's EVM wallet for `BuilderApp`: an injected wallet, a Privy
|
|
38
|
+
* embedded wallet, or an ethers signer.
|
|
39
|
+
* @experimental
|
|
40
|
+
*/
|
|
41
|
+
export declare const Wallet: {
|
|
42
|
+
fromEip1193: typeof _Wallet.walletFromEip1193;
|
|
43
|
+
fromPrivy: typeof _Wallet.walletFromPrivy;
|
|
44
|
+
fromEthers: typeof _Wallet.walletFromEthers;
|
|
45
|
+
};
|
|
46
|
+
/** Help for Paradex API errors. @experimental */
|
|
47
|
+
export declare const Errors: {
|
|
48
|
+
isCode: typeof _ApiErrors.isApiErrorCode;
|
|
49
|
+
describe: typeof _ApiErrors.describeApiError;
|
|
50
|
+
};
|
|
51
|
+
export declare const Bridge: {
|
|
52
|
+
starkgateWithdrawCall: typeof _EvmOwnerClient.starkgateWithdrawCall;
|
|
53
|
+
};
|
|
21
54
|
/**
|
|
22
55
|
* Session grant typed data and hashing.
|
|
23
56
|
* @experimental The server side of sessions is not released yet.
|
|
@@ -61,15 +94,29 @@ export declare const Session: {
|
|
|
61
94
|
};
|
|
62
95
|
export { ALL_LIMITS, BUILDER_APPROVAL_TTL_MAX, CEILING_LIMITS, DEFAULT_ENFORCED_LIMITS, DEFAULT_LIMIT_CAPS, LONGEST_SESSION, MAX_GRANT_SUBACCOUNTS, MINT_HASH_ACCOUNT, SessionGrantError, UNCAPPED_LIMITS, } from './session-typed-data.js';
|
|
63
96
|
export { SessionConnector } from './session-connector.js';
|
|
97
|
+
export { BuilderApp, BuilderSession, estimateBuilderFee, SIWE_DOMAINS, } from './builder-app.js';
|
|
98
|
+
export type { ApproveBuilderOptions, BuilderAppAccount, BuilderAppBuilder, BuilderAppEnvironment, BuilderAppParams, BuilderOrder, BuilderSessionScope, BuilderWithdrawParams, EstimateBuilderFeeParams, EnableRfqOptions, OpenBuilderSessionOptions, } from './builder-app.js';
|
|
99
|
+
export type { OnboardOptions } from './owner-auth.js';
|
|
100
|
+
export { WalletRejectedError } from './wallet.js';
|
|
101
|
+
export type { ParadexWallet, WalletFromEip1193Params, WalletFromEthersParams, WalletFromPrivyParams, } from './wallet.js';
|
|
102
|
+
export { BuilderAppError } from './api-errors.js';
|
|
103
|
+
export type { ApiErrorDescription, ApiErrorWithCode, DerivedApiErrorCode, BuilderAppErrorCode, BuilderCancelReason, } from './api-errors.js';
|
|
104
|
+
export type { AccountInfo, Fill, FillsQuery, OnboardingStatus, Order, OrderStatus, OrdersHistoryQuery, Page, } from './trading.js';
|
|
64
105
|
export { BuilderCodesClient } from './builder-codes.js';
|
|
65
106
|
export type { BuilderApprovalRecord, BuilderApprovalStatus, BuilderCodesClientParams, BuilderLeaderboardRow, BuilderRef, BuilderStats, BuilderStatsWindow, ListBuilderApprovalsOptions, } from './builder-codes.js';
|
|
107
|
+
export { RfqClient } from './rfq.js';
|
|
108
|
+
export type { RfqClientParams, RfqEnableResult } from './rfq.js';
|
|
66
109
|
export { DeterminismGuardError, isContractCode } from './determinism-guard.js';
|
|
67
110
|
export { SessionAccounts } from './session-accounts.js';
|
|
68
|
-
export { SessionApiError
|
|
111
|
+
export { SessionApiError,
|
|
112
|
+
/** The error every Paradex REST call throws; the same class as `SessionApiError`. */
|
|
113
|
+
SessionApiError as ParadexApiError, } from './session-transport.js';
|
|
69
114
|
export { SessionKey } from './session-key.js';
|
|
70
115
|
export type { AddressDerivationOptions, OnboardingInfo, OnboardingDerivationInfo, } from './account.js';
|
|
71
116
|
export type { ParadexClient, CreateClientFromEthSignerParams, CreateClientFromStarknetAccountParams, TokenBalance, SocializedLossFactor, ReceivableAmount, MaxWithdraw, WithdrawResult, } from './client.js';
|
|
72
117
|
export type { ParadexConfig } from './config.js';
|
|
118
|
+
export type { CreateClientFromEvmOwnerParams, EvmOwnerClient, StarkgateWithdrawCallParams, } from './evm-owner-client.js';
|
|
119
|
+
export type { EvmOwnerSigner as EvmOwnerSignerInterface, EvmOwnerSignerFromEip1193Params, EvmOwnerSignerFromViemParams, ViemMessageSigner, } from './evm-owner-signer.js';
|
|
73
120
|
export type { EthereumSigner } from './ethereum-signer.js';
|
|
74
121
|
export type { DeterminismGuardErrorCode, DeterminismGuardOptions, DeterminismGuardResult, EthCodeProvider, } from './determinism-guard.js';
|
|
75
122
|
export type { Hex } from './types.js';
|
package/dist/index.js
CHANGED
|
@@ -1,14 +1,23 @@
|
|
|
1
1
|
import * as _Account from './account.js';
|
|
2
|
+
import * as _ApiErrors from './api-errors.js';
|
|
2
3
|
import * as _Client from './client.js';
|
|
3
4
|
import * as _Config from './config.js';
|
|
4
5
|
import * as _Signer from './ethereum-signer.js';
|
|
6
|
+
import * as _EvmOwnerClient from './evm-owner-client.js';
|
|
7
|
+
import * as _EvmOwnerSigner from './evm-owner-signer.js';
|
|
5
8
|
import * as _SessionKey from './session-key.js';
|
|
6
9
|
import * as _SessionOwnerSigner from './session-owner-signer.js';
|
|
7
10
|
import * as _SessionTypedData from './session-typed-data.js';
|
|
11
|
+
import * as _Wallet from './wallet.js';
|
|
8
12
|
// Recommended: High-level client interface
|
|
9
13
|
export const Client = {
|
|
10
14
|
fromEthSigner: async (params) => await _Client.ParadexClient.createFromEthSigner(params),
|
|
11
15
|
fromStarknetAccount: async (params) => await _Client.ParadexClient.createFromStarknetAccount(params),
|
|
16
|
+
/**
|
|
17
|
+
* Client for an EVM-owned (EIP-191) account: every transaction is signed
|
|
18
|
+
* by the owner wallet. No Stark key is derived.
|
|
19
|
+
*/
|
|
20
|
+
fromEvmOwner: async (params) => await _EvmOwnerClient.EvmOwnerClient.create(params),
|
|
12
21
|
};
|
|
13
22
|
export const Config = {
|
|
14
23
|
fetch: _Config.fetchConfig,
|
|
@@ -19,6 +28,30 @@ export const Onboarding = {
|
|
|
19
28
|
export const Signer = {
|
|
20
29
|
fromEthers: _Signer.ethersSignerAdapter,
|
|
21
30
|
};
|
|
31
|
+
/** Owner signers for EVM-owned (EIP-191) accounts, for `Client.fromEvmOwner`. */
|
|
32
|
+
export const EvmOwnerSigner = {
|
|
33
|
+
fromEthers: _EvmOwnerSigner.evmOwnerSignerFromEthers,
|
|
34
|
+
fromViem: _EvmOwnerSigner.evmOwnerSignerFromViem,
|
|
35
|
+
fromEip1193: _EvmOwnerSigner.evmOwnerSignerFromEip1193,
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* The user's EVM wallet for `BuilderApp`: an injected wallet, a Privy
|
|
39
|
+
* embedded wallet, or an ethers signer.
|
|
40
|
+
* @experimental
|
|
41
|
+
*/
|
|
42
|
+
export const Wallet = {
|
|
43
|
+
fromEip1193: _Wallet.walletFromEip1193,
|
|
44
|
+
fromPrivy: _Wallet.walletFromPrivy,
|
|
45
|
+
fromEthers: _Wallet.walletFromEthers,
|
|
46
|
+
};
|
|
47
|
+
/** Help for Paradex API errors. @experimental */
|
|
48
|
+
export const Errors = {
|
|
49
|
+
isCode: _ApiErrors.isApiErrorCode,
|
|
50
|
+
describe: _ApiErrors.describeApiError,
|
|
51
|
+
};
|
|
52
|
+
export const Bridge = {
|
|
53
|
+
starkgateWithdrawCall: _EvmOwnerClient.starkgateWithdrawCall,
|
|
54
|
+
};
|
|
22
55
|
/**
|
|
23
56
|
* Session grant typed data and hashing.
|
|
24
57
|
* @experimental The server side of sessions is not released yet.
|
|
@@ -62,8 +95,14 @@ export const Session = {
|
|
|
62
95
|
};
|
|
63
96
|
export { ALL_LIMITS, BUILDER_APPROVAL_TTL_MAX, CEILING_LIMITS, DEFAULT_ENFORCED_LIMITS, DEFAULT_LIMIT_CAPS, LONGEST_SESSION, MAX_GRANT_SUBACCOUNTS, MINT_HASH_ACCOUNT, SessionGrantError, UNCAPPED_LIMITS, } from './session-typed-data.js';
|
|
64
97
|
export { SessionConnector } from './session-connector.js';
|
|
98
|
+
export { BuilderApp, BuilderSession, estimateBuilderFee, SIWE_DOMAINS, } from './builder-app.js';
|
|
99
|
+
export { WalletRejectedError } from './wallet.js';
|
|
100
|
+
export { BuilderAppError } from './api-errors.js';
|
|
65
101
|
export { BuilderCodesClient } from './builder-codes.js';
|
|
102
|
+
export { RfqClient } from './rfq.js';
|
|
66
103
|
export { DeterminismGuardError, isContractCode } from './determinism-guard.js';
|
|
67
104
|
export { SessionAccounts } from './session-accounts.js';
|
|
68
|
-
export { SessionApiError
|
|
105
|
+
export { SessionApiError,
|
|
106
|
+
/** The error every Paradex REST call throws; the same class as `SessionApiError`. */
|
|
107
|
+
SessionApiError as ParadexApiError, } from './session-transport.js';
|
|
69
108
|
export { SessionKey } from './session-key.js';
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { type SessionUtm } from './session-connector.js';
|
|
2
|
+
import { type HttpTransport } from './session-transport.js';
|
|
3
|
+
import type { ParadexWallet } from './wallet.js';
|
|
4
|
+
export declare const EVM_AUTH_PATH = "/v2/auth";
|
|
5
|
+
export declare const EVM_ONBOARDING_PATH = "/v2/onboarding";
|
|
6
|
+
export interface OwnerAuthParams {
|
|
7
|
+
readonly wallet: ParadexWallet;
|
|
8
|
+
/** API host root, e.g. `https://api.testnet.paradex.trade`. */
|
|
9
|
+
readonly apiUrl: string;
|
|
10
|
+
/** The Paradex app host the server accepts in SIWE messages. */
|
|
11
|
+
readonly siweDomain: string;
|
|
12
|
+
/** The Ethereum chain id the server expects (`ParadexConfig.ethereumChainId`). */
|
|
13
|
+
readonly ethereumChainId: number;
|
|
14
|
+
readonly transport?: HttpTransport;
|
|
15
|
+
/** Seconds since the epoch. */
|
|
16
|
+
readonly now?: () => number;
|
|
17
|
+
}
|
|
18
|
+
export interface OnboardOptions {
|
|
19
|
+
readonly referralCode?: string;
|
|
20
|
+
/** `campaign:code`. */
|
|
21
|
+
readonly marketingCode?: string;
|
|
22
|
+
readonly utm?: SessionUtm;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The account owner's own sign-in, with the EVM wallet: SIWE login for a
|
|
26
|
+
* main-key JWT (`POST /v2/auth`), and onboarding without a session
|
|
27
|
+
* (`POST /v2/onboarding`).
|
|
28
|
+
*
|
|
29
|
+
* The SIWE message names the Paradex app's host, the only domain the server
|
|
30
|
+
* accepts. Embedded wallets (Privy) sign it without comment; injected
|
|
31
|
+
* wallets such as MetaMask warn that the domain differs from the page's.
|
|
32
|
+
*
|
|
33
|
+
* Not exported from the package: `BuilderApp` is the public way in.
|
|
34
|
+
*
|
|
35
|
+
* @internal
|
|
36
|
+
*/
|
|
37
|
+
export declare class OwnerAuth {
|
|
38
|
+
private readonly params;
|
|
39
|
+
private readonly transport;
|
|
40
|
+
private readonly now;
|
|
41
|
+
private readonly tokens;
|
|
42
|
+
private readonly inflight;
|
|
43
|
+
/** Bumped by `logout()`, so a login in flight then is not cached. */
|
|
44
|
+
private generation;
|
|
45
|
+
constructor(params: OwnerAuthParams);
|
|
46
|
+
/**
|
|
47
|
+
* The owner's main-key JWT for `account` (5 minutes), minted with one
|
|
48
|
+
* `personal_sign` prompt and reused until 30 s before it expires. It is
|
|
49
|
+
* what listing and revoking builder approvals need.
|
|
50
|
+
*/
|
|
51
|
+
login(account: string): Promise<string>;
|
|
52
|
+
/** Drops the cached owner tokens. */
|
|
53
|
+
logout(): void;
|
|
54
|
+
private mint;
|
|
55
|
+
/** The server's clock in whole seconds, from `GET /v1/system/time`. */
|
|
56
|
+
private serverTime;
|
|
57
|
+
/**
|
|
58
|
+
* Opens the wallet's account without a session (one `personal_sign`
|
|
59
|
+
* prompt). A new main account is created at once and deployed later
|
|
60
|
+
* ("deferred deploy"); it trades once it is deployed. Calling it for an
|
|
61
|
+
* account that exists is a no-op on the server.
|
|
62
|
+
*
|
|
63
|
+
* A Privy wallet sends its access token, so a verified Privy user skips
|
|
64
|
+
* the minimum-balance check. Otherwise the server may refuse with
|
|
65
|
+
* `INSUFFICIENT_MIN_CHAIN_BALANCE` or `ONBOARDING_RATE_LIMITED`.
|
|
66
|
+
*/
|
|
67
|
+
onboard(account: string, options?: OnboardOptions): Promise<void>;
|
|
68
|
+
}
|