@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.
@@ -0,0 +1,98 @@
1
+ export type OrderStatus = 'NEW' | 'UNTRIGGERED' | 'OPEN' | 'CLOSED';
2
+ /** @experimental */
3
+ export interface Order {
4
+ readonly id: string;
5
+ readonly account: string;
6
+ readonly market: string;
7
+ readonly side: 'BUY' | 'SELL';
8
+ readonly type: string;
9
+ readonly size: string;
10
+ readonly remaining_size: string;
11
+ readonly price: string;
12
+ readonly status: OrderStatus | (string & Record<never, never>);
13
+ readonly instruction?: string;
14
+ readonly client_id?: string;
15
+ readonly avg_fill_price?: string;
16
+ readonly flags?: readonly string[];
17
+ /**
18
+ * Why the order closed without filling in full, e.g. `USER_CANCELED` or a
19
+ * builder reason (`BuilderCancelReason`).
20
+ */
21
+ readonly cancel_reason?: string;
22
+ readonly created_at: number;
23
+ readonly last_updated_at?: number;
24
+ /** The builder the order is attributed to; absent for none. */
25
+ readonly builder?: string;
26
+ /** The builder fee rate, a decimal fraction (`"0.0005"` = 5 bps). */
27
+ readonly builder_fee_rate?: string;
28
+ }
29
+ /** @experimental */
30
+ export interface Fill {
31
+ readonly id: string;
32
+ readonly account: string;
33
+ readonly market: string;
34
+ readonly order_id: string;
35
+ readonly client_id?: string;
36
+ readonly side: 'BUY' | 'SELL';
37
+ readonly liquidity: 'TAKER' | 'MAKER' | (string & Record<never, never>);
38
+ readonly fill_type?: string;
39
+ readonly price: string;
40
+ readonly size: string;
41
+ readonly remaining_size?: string;
42
+ /** The exchange fee, in `fee_currency`. */
43
+ readonly fee: string;
44
+ readonly fee_currency: string;
45
+ readonly realized_pnl?: string;
46
+ readonly realized_funding?: string;
47
+ readonly created_at: number;
48
+ /** The builder paid on this fill; absent for none. */
49
+ readonly builder?: string;
50
+ /** The builder fee rate, a decimal fraction. */
51
+ readonly builder_fee_rate?: string;
52
+ /** The builder fee in USDC, charged on top of `fee`. */
53
+ readonly builder_fee?: string;
54
+ }
55
+ /** A page of results and the cursors around it. */
56
+ export interface Page<T> {
57
+ readonly results: readonly T[];
58
+ /** Pass as `cursor` for the next page; `null` on the last one. */
59
+ readonly next: string | null;
60
+ readonly prev: string | null;
61
+ }
62
+ export interface FillsQuery {
63
+ readonly market?: string;
64
+ /** Milliseconds. */
65
+ readonly startAt?: number;
66
+ /** Milliseconds. */
67
+ readonly endAt?: number;
68
+ readonly cursor?: string;
69
+ /** Defaults to 100 on the server; at most 5000. */
70
+ readonly pageSize?: number;
71
+ }
72
+ export interface OrdersHistoryQuery extends FillsQuery {
73
+ readonly side?: 'BUY' | 'SELL';
74
+ readonly status?: 'OPEN' | 'CLOSED' | 'NEW';
75
+ readonly type?: string;
76
+ readonly clientId?: string;
77
+ }
78
+ export type OnboardingStatus = 'ONBOARDING' | 'ONBOARDED' | 'ONBOARDING_FAILED' | 'BLOCKED' | 'UNKNOWN';
79
+ /**
80
+ * `GET /v1/account/info`. `onboarding_status` and `is_deployed` are absent
81
+ * on servers that predate them.
82
+ */
83
+ export interface AccountInfo {
84
+ readonly account: string;
85
+ /**
86
+ * `ONBOARDING` while a new account waits to be deployed (deferred deploy);
87
+ * it trades once `ONBOARDED`.
88
+ */
89
+ readonly onboarding_status?: OnboardingStatus;
90
+ readonly is_deployed?: boolean;
91
+ readonly kind?: string;
92
+ readonly parent_account?: string;
93
+ readonly created_at?: number;
94
+ }
95
+ /** Builds a query string from defined values; empty when there are none. */
96
+ export declare function queryString(params: Record<string, string | number | undefined>): string;
97
+ export declare function fillsQueryParams(q: FillsQuery): Record<string, string | number | undefined>;
98
+ export declare function toPage<T>(body: unknown, what: string): Page<T>;
@@ -0,0 +1,39 @@
1
+ import { SessionApiError } from './session-transport.js';
2
+ /** Builds a query string from defined values; empty when there are none. */
3
+ export function queryString(params) {
4
+ const query = new URLSearchParams();
5
+ for (const [key, value] of Object.entries(params)) {
6
+ if (value != null && value !== '')
7
+ query.set(key, String(value));
8
+ }
9
+ const text = query.toString();
10
+ return text === '' ? '' : `?${text}`;
11
+ }
12
+ export function fillsQueryParams(q) {
13
+ if (q.pageSize != null &&
14
+ (!Number.isSafeInteger(q.pageSize) || q.pageSize < 1)) {
15
+ throw new Error('pageSize must be a positive integer');
16
+ }
17
+ return {
18
+ market: q.market,
19
+ start_at: q.startAt,
20
+ end_at: q.endAt,
21
+ cursor: q.cursor,
22
+ page_size: q.pageSize,
23
+ };
24
+ }
25
+ export function toPage(body, what) {
26
+ const record = (body ?? {});
27
+ if (!Array.isArray(record.results)) {
28
+ throw new SessionApiError(200, {
29
+ error: 'INVALID_RESPONSE',
30
+ message: `${what} returned no results`,
31
+ });
32
+ }
33
+ const cursor = (v) => typeof v === 'string' && v !== '' ? v : null;
34
+ return {
35
+ results: record.results,
36
+ next: cursor(record.next),
37
+ prev: cursor(record.prev),
38
+ };
39
+ }
@@ -0,0 +1,78 @@
1
+ import type { ethers } from 'ethers';
2
+ import { type Eip712TypedData } from './eip712.js';
3
+ import type { EvmOwnerSigner } from './evm-owner-signer.js';
4
+ import type { Eip1193Provider, SessionOwnerSigner } from './session-owner-signer.js';
5
+ import type { Hex } from './types.js';
6
+ /**
7
+ * The user's EVM wallet, as a builder app holds it: an injected wallet
8
+ * (MetaMask, Rabby, …), a Privy embedded wallet, or a key in Node.
9
+ *
10
+ * One wallet signs everything the builder flow needs: the session grant and
11
+ * builder approvals (EIP-712), the owner login and onboarding messages (SIWE,
12
+ * EIP-191 text) and withdrawals (EIP-191 over a transaction hash's bytes).
13
+ * Only EOAs are supported: every signature must be 65 bytes.
14
+ *
15
+ * @experimental
16
+ */
17
+ export interface ParadexWallet {
18
+ readonly kind: 'injected' | 'privy' | 'local';
19
+ /** The wallet's address. */
20
+ getAddress: () => Promise<string>;
21
+ /** The chain the wallet is on; it becomes `signature_chain_id`. */
22
+ getChainId: () => Promise<number>;
23
+ /** `eth_signTypedData_v4`. Returns a 65-byte `r‖s‖v` hex signature. */
24
+ signTypedData: (typedData: Eip712TypedData) => Promise<string>;
25
+ /**
26
+ * EIP-191 `personal_sign`. A string is signed as UTF-8 text, a
27
+ * `Uint8Array` as raw bytes.
28
+ */
29
+ signMessage: (message: string | Uint8Array) => Promise<string>;
30
+ /**
31
+ * A Privy access token for this wallet's user, sent as
32
+ * `PARADEX-PRIVY-ACCESS-TOKEN` when a new account is opened, so a verified
33
+ * Privy user skips the minimum-balance check. Only Privy wallets have it.
34
+ */
35
+ getPrivyAccessToken?: () => Promise<string | undefined>;
36
+ }
37
+ /** Error a wallet raises when the user rejects a prompt (EIP-1193 `4001`). */
38
+ export declare class WalletRejectedError extends Error {
39
+ readonly walletError: unknown;
40
+ constructor(cause: unknown);
41
+ }
42
+ export declare function parseChainId(value: unknown): number;
43
+ export declare function bytesToHex(bytes: Uint8Array): Hex;
44
+ export interface WalletFromEip1193Params {
45
+ readonly provider: Eip1193Provider;
46
+ /** Defaults to the wallet's first account (`eth_requestAccounts`). */
47
+ readonly address?: string;
48
+ }
49
+ /** An injected wallet (`window.ethereum`) or any EIP-1193 provider. */
50
+ export declare function walletFromEip1193(params: WalletFromEip1193Params): ParadexWallet;
51
+ export interface WalletFromPrivyParams {
52
+ /** `await privyWallet.getEthereumProvider()`. */
53
+ readonly provider: Eip1193Provider;
54
+ /** `privyWallet.address`. */
55
+ readonly address: string;
56
+ /** `getAccessToken` from `usePrivy()`. */
57
+ readonly getAccessToken: () => Promise<string | null | undefined>;
58
+ }
59
+ /**
60
+ * A Privy embedded wallet. Signing goes through its EIP-1193 provider; its
61
+ * access token lets a new account skip the minimum-balance check.
62
+ */
63
+ export declare function walletFromPrivy({ provider, address, getAccessToken, }: WalletFromPrivyParams): ParadexWallet;
64
+ export interface WalletFromEthersParams {
65
+ /** An ethers v6 signer, e.g. `new ethers.Wallet(key)`. */
66
+ readonly signer: ethers.Signer;
67
+ /**
68
+ * The chain to sign for. Defaults to the signer's provider network; a
69
+ * signer without a provider needs it.
70
+ */
71
+ readonly chainId?: number;
72
+ }
73
+ /** An ethers v6 signer: a key in Node scripts, tests and bots. */
74
+ export declare function walletFromEthers({ signer, chainId, }: WalletFromEthersParams): ParadexWallet;
75
+ /** The wallet as the session connector's owner signer. */
76
+ export declare function walletOwnerSigner(wallet: ParadexWallet): SessionOwnerSigner;
77
+ /** The wallet as an EVM-owned account's transaction signer. */
78
+ export declare function walletEvmOwnerSigner(wallet: ParadexWallet): EvmOwnerSigner;
package/dist/wallet.js ADDED
@@ -0,0 +1,157 @@
1
+ import { toEthSignTypedDataV4 } from './eip712.js';
2
+ /** Error a wallet raises when the user rejects a prompt (EIP-1193 `4001`). */
3
+ export class WalletRejectedError extends Error {
4
+ constructor(cause) {
5
+ super('The user rejected the wallet request');
6
+ this.name = 'WalletRejectedError';
7
+ this.walletError = cause;
8
+ }
9
+ }
10
+ function isUserRejection(error) {
11
+ const code = error?.code;
12
+ return code === 4001 || code === 'ACTION_REJECTED';
13
+ }
14
+ async function walletCall(call) {
15
+ try {
16
+ return await call();
17
+ }
18
+ catch (error) {
19
+ if (isUserRejection(error))
20
+ throw new WalletRejectedError(error);
21
+ throw error;
22
+ }
23
+ }
24
+ export function parseChainId(value) {
25
+ let n = Number.NaN;
26
+ if (typeof value === 'number')
27
+ n = value;
28
+ else if (typeof value === 'bigint')
29
+ n = Number(value);
30
+ else if (typeof value === 'string' && /^(0x[0-9a-fA-F]+|[0-9]+)$/.test(value))
31
+ n = Number(BigInt(value));
32
+ if (!Number.isSafeInteger(n) || n <= 0) {
33
+ throw new Error(`Wallet returned an invalid chain id: ${String(value)}`);
34
+ }
35
+ return n;
36
+ }
37
+ function assertAddress(address) {
38
+ if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
39
+ throw new Error('Wallet address must be a 0x-prefixed 20-byte address');
40
+ }
41
+ return address;
42
+ }
43
+ function asSignature(value) {
44
+ if (typeof value !== 'string') {
45
+ throw new Error('Wallet returned a non-string signature');
46
+ }
47
+ return value;
48
+ }
49
+ export function bytesToHex(bytes) {
50
+ return `0x${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}`;
51
+ }
52
+ function messageHex(message) {
53
+ return bytesToHex(typeof message === 'string' ? new TextEncoder().encode(message) : message);
54
+ }
55
+ function eip1193Wallet(kind, { provider, address }) {
56
+ let resolved = address != null ? assertAddress(address) : undefined;
57
+ const getAddress = async () => {
58
+ if (resolved != null)
59
+ return resolved;
60
+ const accounts = await walletCall(async () => await provider.request({ method: 'eth_requestAccounts' }));
61
+ const first = Array.isArray(accounts) ? accounts[0] : undefined;
62
+ if (typeof first !== 'string')
63
+ throw new Error('Wallet returned no accounts');
64
+ resolved = assertAddress(first);
65
+ return resolved;
66
+ };
67
+ // A wallet the user switched to another account would sign for that
68
+ // account (or refuse `from`): fail with a clear error instead.
69
+ const signer = async () => {
70
+ const from = await getAddress();
71
+ // A provider that cannot answer leaves the check to the wallet itself.
72
+ const accounts = await provider
73
+ .request({ method: 'eth_accounts' })
74
+ .catch(() => undefined);
75
+ if (!Array.isArray(accounts) || accounts.length === 0)
76
+ return from;
77
+ const allowed = accounts.filter((a) => typeof a === 'string');
78
+ // Without a chosen address the wallet follows its selected account, so
79
+ // it must still be selected. A chosen address only has to stay allowed.
80
+ const ok = address == null
81
+ ? allowed[0]?.toLowerCase() === from.toLowerCase()
82
+ : allowed.some((a) => a.toLowerCase() === from.toLowerCase());
83
+ if (!ok) {
84
+ throw new Error(`The wallet switched away from ${from} (now ${allowed[0] ?? 'none'}); connect again`);
85
+ }
86
+ return from;
87
+ };
88
+ return {
89
+ kind,
90
+ getAddress,
91
+ getChainId: async () => parseChainId(await provider.request({ method: 'eth_chainId' })),
92
+ signTypedData: async (typedData) => {
93
+ const from = await signer();
94
+ return asSignature(await walletCall(async () => await provider.request({
95
+ method: 'eth_signTypedData_v4',
96
+ params: [from, toEthSignTypedDataV4(typedData)],
97
+ })));
98
+ },
99
+ signMessage: async (message) => {
100
+ const from = await signer();
101
+ return asSignature(await walletCall(async () => await provider.request({
102
+ method: 'personal_sign',
103
+ params: [messageHex(message), from],
104
+ })));
105
+ },
106
+ };
107
+ }
108
+ /** An injected wallet (`window.ethereum`) or any EIP-1193 provider. */
109
+ export function walletFromEip1193(params) {
110
+ return eip1193Wallet('injected', params);
111
+ }
112
+ /**
113
+ * A Privy embedded wallet. Signing goes through its EIP-1193 provider; its
114
+ * access token lets a new account skip the minimum-balance check.
115
+ */
116
+ export function walletFromPrivy({ provider, address, getAccessToken, }) {
117
+ return {
118
+ ...eip1193Wallet('privy', { provider, address }),
119
+ getPrivyAccessToken: async () => {
120
+ const token = await getAccessToken();
121
+ return token != null && token !== '' ? token : undefined;
122
+ },
123
+ };
124
+ }
125
+ /** An ethers v6 signer: a key in Node scripts, tests and bots. */
126
+ export function walletFromEthers({ signer, chainId, }) {
127
+ return {
128
+ kind: 'local',
129
+ getAddress: async () => assertAddress(await signer.getAddress()),
130
+ getChainId: async () => {
131
+ if (chainId != null)
132
+ return parseChainId(chainId);
133
+ const network = await signer.provider?.getNetwork();
134
+ if (network == null) {
135
+ throw new Error('Pass chainId for a signer without a provider');
136
+ }
137
+ return parseChainId(network.chainId);
138
+ },
139
+ signTypedData: async ({ domain, types, message }) => await signer.signTypedData(domain, types, message),
140
+ signMessage: async (message) => await signer.signMessage(message),
141
+ };
142
+ }
143
+ /** The wallet as the session connector's owner signer. */
144
+ export function walletOwnerSigner(wallet) {
145
+ return {
146
+ getChainId: wallet.getChainId,
147
+ getAddress: wallet.getAddress,
148
+ signTypedData: async ({ typedData }) => await wallet.signTypedData(typedData),
149
+ };
150
+ }
151
+ /** The wallet as an EVM-owned account's transaction signer. */
152
+ export function walletEvmOwnerSigner(wallet) {
153
+ return {
154
+ getAddress: wallet.getAddress,
155
+ signMessage: async (message) => await wallet.signMessage(message),
156
+ };
157
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@paradex/sdk",
3
- "version": "0.11.0",
3
+ "version": "0.12.1",
4
4
  "description": "JavaScript SDK for Paradex",
5
5
  "main": "dist/index.js",
6
6
  "files": [
@@ -12,7 +12,8 @@
12
12
  "lint": "prettier --check . && eslint .",
13
13
  "format": "prettier --write .",
14
14
  "test": "jest",
15
- "example:withdrawal": "tsx examples/withdrawal-node.ts"
15
+ "example:withdrawal": "tsx examples/withdrawal-node.ts",
16
+ "example:builder": "tsx examples/builder-app/node.ts"
16
17
  },
17
18
  "lint-staged": {
18
19
  "**/*": "prettier --write --ignore-unknown"
@@ -28,6 +29,7 @@
28
29
  "url": "git+https://github.com/tradeparadex/paradex.js.git"
29
30
  },
30
31
  "dependencies": {
32
+ "@noble/curves": "~1.7.0",
31
33
  "@noble/hashes": "~1.6.0",
32
34
  "bignumber.js": "^9.3.1",
33
35
  "starknet": "^8.6.0"