@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,527 @@
|
|
|
1
|
+
import BigNumber from 'bignumber.js';
|
|
2
|
+
import { BuilderAppError } from './api-errors.js';
|
|
3
|
+
import { BuilderCodesClient, } from './builder-codes.js';
|
|
4
|
+
import { fetchConfig } from './config.js';
|
|
5
|
+
import { EvmOwnerClient, starkgateWithdrawCall } from './evm-owner-client.js';
|
|
6
|
+
import { OwnerAuth } from './owner-auth.js';
|
|
7
|
+
import { RfqClient } from './rfq.js';
|
|
8
|
+
import { fetchGrantState, SessionAccounts, } from './session-accounts.js';
|
|
9
|
+
import { toChainQuantums } from './session-auth.js';
|
|
10
|
+
import { SessionConnector } from './session-connector.js';
|
|
11
|
+
import { indexedDbSessionStorage, memorySessionStorage, } from './session-key.js';
|
|
12
|
+
import { defaultApiUrl, fetchTransport, SessionApiError, } from './session-transport.js';
|
|
13
|
+
import { builderAddress, canonicalFelt, nowSeconds, SessionGrantError, } from './session-typed-data.js';
|
|
14
|
+
import { fillsQueryParams, queryString, toPage, } from './trading.js';
|
|
15
|
+
import { walletEvmOwnerSigner, walletOwnerSigner, } from './wallet.js';
|
|
16
|
+
/** The Paradex app host each environment's SIWE messages must name. */
|
|
17
|
+
export const SIWE_DOMAINS = {
|
|
18
|
+
prod: 'app.paradex.trade',
|
|
19
|
+
testnet: 'app.testnet.paradex.trade',
|
|
20
|
+
nightly: 'app.nightly.paradex.trade',
|
|
21
|
+
};
|
|
22
|
+
const APPROVALS_LOGIN = 'approvals';
|
|
23
|
+
const RFQ_LOGIN = 'rfq';
|
|
24
|
+
/**
|
|
25
|
+
* The builder fee a fill of `size` at `price` pays, in USDC, as a decimal
|
|
26
|
+
* string: `size × price × feeRate`. It is what the fill's `builder_fee` will
|
|
27
|
+
* read for a perpetual filled at that price. For display before an order is
|
|
28
|
+
* placed; the fill itself is the record.
|
|
29
|
+
*/
|
|
30
|
+
export function estimateBuilderFee({ size, price, feeRate, }) {
|
|
31
|
+
const values = [size, price, feeRate].map((v) => new BigNumber(v));
|
|
32
|
+
if (values.some((v) => !v.isFinite() || v.isNegative())) {
|
|
33
|
+
throw new Error('size, price and feeRate must be non-negative decimals');
|
|
34
|
+
}
|
|
35
|
+
const [s, p, r] = values;
|
|
36
|
+
return s.times(p).times(r).decimalPlaces(8, BigNumber.ROUND_UP).toFixed();
|
|
37
|
+
}
|
|
38
|
+
function sessionEnvironment(env) {
|
|
39
|
+
return env === 'prod' ? 'mainnet' : env;
|
|
40
|
+
}
|
|
41
|
+
function defaultStorage() {
|
|
42
|
+
return typeof globalThis.indexedDB !== 'undefined'
|
|
43
|
+
? indexedDbSessionStorage()
|
|
44
|
+
: memorySessionStorage();
|
|
45
|
+
}
|
|
46
|
+
function sameFelt(a, b) {
|
|
47
|
+
return canonicalFelt(a) === canonicalFelt(b);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Everything a builder's web app does with Paradex, behind one object:
|
|
51
|
+
* open the user's account and a trading session that approves the builder,
|
|
52
|
+
* trade with the builder fee, read fills, manage approvals, withdraw, and
|
|
53
|
+
* read builder stats. Builders never use subkeys.
|
|
54
|
+
*
|
|
55
|
+
* @experimental
|
|
56
|
+
*/
|
|
57
|
+
export class BuilderApp {
|
|
58
|
+
constructor(params, config, ownerAddress, account) {
|
|
59
|
+
this.params = params;
|
|
60
|
+
this.environment = params.environment;
|
|
61
|
+
this.wallet = params.wallet;
|
|
62
|
+
this.builder = {
|
|
63
|
+
account: builderAddress(params.builder.account, 'builder.account'),
|
|
64
|
+
feeRate: params.builder.feeRate,
|
|
65
|
+
maxFeeRate: params.builder.maxFeeRate ?? params.builder.feeRate,
|
|
66
|
+
};
|
|
67
|
+
this.config = config;
|
|
68
|
+
this.ownerAddress = ownerAddress;
|
|
69
|
+
this.accountState = account;
|
|
70
|
+
this.apiUrl = (params.apiUrl ?? defaultApiUrl(sessionEnvironment(params.environment))).replace(/\/+$/, '');
|
|
71
|
+
this.transport = params.transport ?? fetchTransport;
|
|
72
|
+
this.connector = new SessionConnector({
|
|
73
|
+
environment: sessionEnvironment(params.environment),
|
|
74
|
+
paradexChain: config.paradexChainId,
|
|
75
|
+
owner: walletOwnerSigner(params.wallet),
|
|
76
|
+
storage: params.storage ?? defaultStorage(),
|
|
77
|
+
transport: this.transport,
|
|
78
|
+
apiUrl: this.apiUrl,
|
|
79
|
+
...(params.now != null ? { now: params.now } : {}),
|
|
80
|
+
});
|
|
81
|
+
this.ownerAuth = new OwnerAuth({
|
|
82
|
+
wallet: params.wallet,
|
|
83
|
+
apiUrl: this.apiUrl,
|
|
84
|
+
siweDomain: params.siweDomain ?? SIWE_DOMAINS[params.environment],
|
|
85
|
+
ethereumChainId: Number(config.ethereumChainId),
|
|
86
|
+
transport: this.transport,
|
|
87
|
+
...(params.now != null ? { now: params.now } : {}),
|
|
88
|
+
});
|
|
89
|
+
this.codes = new BuilderCodesClient({
|
|
90
|
+
environment: sessionEnvironment(params.environment),
|
|
91
|
+
apiUrl: this.apiUrl,
|
|
92
|
+
transport: this.transport,
|
|
93
|
+
});
|
|
94
|
+
this.rfq = new RfqClient({
|
|
95
|
+
environment: sessionEnvironment(params.environment),
|
|
96
|
+
apiUrl: this.apiUrl,
|
|
97
|
+
transport: this.transport,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Reads the config and the wallet's account. Prompts the wallet only to
|
|
102
|
+
* connect (`eth_requestAccounts`) when it has no address yet.
|
|
103
|
+
*/
|
|
104
|
+
static async connect(params) {
|
|
105
|
+
const { feeRate } = params.builder;
|
|
106
|
+
const maxFeeRate = params.builder.maxFeeRate ?? feeRate;
|
|
107
|
+
builderAddress(params.builder.account, 'builder.account');
|
|
108
|
+
if (toChainQuantums(feeRate, 'builder.feeRate') === '0') {
|
|
109
|
+
throw new Error('builder.feeRate must be above 0');
|
|
110
|
+
}
|
|
111
|
+
toChainQuantums(maxFeeRate, 'builder.maxFeeRate');
|
|
112
|
+
if (new BigNumber(maxFeeRate).isLessThan(feeRate)) {
|
|
113
|
+
throw new Error('builder.maxFeeRate must be at least builder.feeRate');
|
|
114
|
+
}
|
|
115
|
+
const config = params.config ?? (await fetchConfig(params.environment));
|
|
116
|
+
const ownerAddress = await params.wallet.getAddress();
|
|
117
|
+
const apiUrl = (params.apiUrl ?? defaultApiUrl(sessionEnvironment(params.environment))).replace(/\/+$/, '');
|
|
118
|
+
const account = await lookupAccount(params.transport ?? fetchTransport, apiUrl, ownerAddress);
|
|
119
|
+
return new BuilderApp(params, config, ownerAddress, account);
|
|
120
|
+
}
|
|
121
|
+
/** The wallet's account as last read. */
|
|
122
|
+
get account() {
|
|
123
|
+
return this.accountState;
|
|
124
|
+
}
|
|
125
|
+
/** Re-reads whether the wallet's account exists. */
|
|
126
|
+
async refreshAccount() {
|
|
127
|
+
this.accountState = await lookupAccount(this.transport, this.apiUrl, this.ownerAddress);
|
|
128
|
+
return this.accountState;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Opens the account without a session (one `personal_sign` prompt). Only
|
|
132
|
+
* for an app that needs the account, or a referral code, before trading:
|
|
133
|
+
* {@link openSession} opens a new account itself, and a grant naming a
|
|
134
|
+
* builder carries no referral.
|
|
135
|
+
*/
|
|
136
|
+
async onboard(options = {}) {
|
|
137
|
+
await this.ownerAuth.onboard(this.accountState.address, options);
|
|
138
|
+
return await this.refreshAccount();
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Opens a trading session that approves the app's builder (one EIP-712
|
|
142
|
+
* prompt). For a wallet with no account, the same grant opens it: the
|
|
143
|
+
* account exists at once and deploys shortly after, and a Privy wallet's
|
|
144
|
+
* access token lets a verified user skip the minimum-balance check.
|
|
145
|
+
*/
|
|
146
|
+
async openSession(options = {}) {
|
|
147
|
+
if (options.scopes != null && !options.scopes.includes('trade')) {
|
|
148
|
+
throw new SessionGrantError('INVALID_FIELD', 'scopes: a builder session must include "trade"');
|
|
149
|
+
}
|
|
150
|
+
const privyAccessToken = this.accountState.exists
|
|
151
|
+
? undefined
|
|
152
|
+
: await this.wallet.getPrivyAccessToken?.();
|
|
153
|
+
const session = await this.connector.open({
|
|
154
|
+
account: this.accountState.address,
|
|
155
|
+
builder: {
|
|
156
|
+
account: this.builder.account,
|
|
157
|
+
maxFeeRate: this.builder.maxFeeRate,
|
|
158
|
+
expiresAt: 0,
|
|
159
|
+
},
|
|
160
|
+
...(options.scopes != null ? { scopes: options.scopes } : {}),
|
|
161
|
+
...(options.subaccounts != null
|
|
162
|
+
? { subaccounts: options.subaccounts }
|
|
163
|
+
: {}),
|
|
164
|
+
...(options.ttlSeconds != null ? { ttlSeconds: options.ttlSeconds } : {}),
|
|
165
|
+
...(options.label != null ? { label: options.label } : {}),
|
|
166
|
+
...(privyAccessToken != null ? { onboarding: { privyAccessToken } } : {}),
|
|
167
|
+
});
|
|
168
|
+
this.accountState = { ...this.accountState, exists: true };
|
|
169
|
+
return this.sessionFor(session, options.onDropped);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* The newest stored session of this wallet's account that can still place
|
|
173
|
+
* the app's orders, or `undefined`: its grant approves the app's builder
|
|
174
|
+
* at a ceiling of at least `feeRate`, and the server reports it active.
|
|
175
|
+
* Its grant lists `trade` and, with `scopes`, every one of those too.
|
|
176
|
+
* Sessions the server reports revoked or expired are deleted from
|
|
177
|
+
* storage. When the status cannot be read (offline), the session is kept
|
|
178
|
+
* and returned; its first call re-checks it.
|
|
179
|
+
*/
|
|
180
|
+
async restoreSession(options = {}) {
|
|
181
|
+
const now = this.now();
|
|
182
|
+
// A session without `trade` cannot place the app's orders.
|
|
183
|
+
const scopes = [
|
|
184
|
+
'trade',
|
|
185
|
+
...(options.scopes ?? []),
|
|
186
|
+
];
|
|
187
|
+
const sessions = (await this.connector.restore()).filter((s) => sameFelt(s.grant.account, this.accountState.address) &&
|
|
188
|
+
scopes.every((scope) => s.grant.scopes.includes(scope)) &&
|
|
189
|
+
sameFelt(s.grant.builder.account, this.builder.account) &&
|
|
190
|
+
new BigNumber(s.grant.builder.maxFeeRate).gte(this.builder.feeRate) &&
|
|
191
|
+
(s.grant.builder.expiresAt === 0 || s.grant.builder.expiresAt > now));
|
|
192
|
+
sessions.sort((a, b) => b.grant.issuedAt - a.grant.issuedAt);
|
|
193
|
+
for (const session of sessions) {
|
|
194
|
+
const state = await fetchGrantState(this.transport, this.apiUrl, session.grantId);
|
|
195
|
+
if (state === 'revoked' || state === 'expired') {
|
|
196
|
+
await this.connector.forget(session);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
return this.sessionFor(session, options.onDropped);
|
|
200
|
+
}
|
|
201
|
+
return undefined;
|
|
202
|
+
}
|
|
203
|
+
now() {
|
|
204
|
+
return (this.params.now ?? nowSeconds)();
|
|
205
|
+
}
|
|
206
|
+
/** Deletes a session's key from storage (after it ends). */
|
|
207
|
+
async forgetSession(session) {
|
|
208
|
+
await this.connector.forget(session.session);
|
|
209
|
+
}
|
|
210
|
+
sessionFor(session, onDropped) {
|
|
211
|
+
const accounts = new SessionAccounts({
|
|
212
|
+
session,
|
|
213
|
+
environment: sessionEnvironment(this.environment),
|
|
214
|
+
paradexChain: this.config.paradexChainId,
|
|
215
|
+
transport: this.transport,
|
|
216
|
+
apiUrl: this.apiUrl,
|
|
217
|
+
...(this.params.wsUrl != null ? { wsUrl: this.params.wsUrl } : {}),
|
|
218
|
+
...(this.params.webSocketFactory != null
|
|
219
|
+
? { webSocketFactory: this.params.webSocketFactory }
|
|
220
|
+
: {}),
|
|
221
|
+
...(this.params.onMessageError != null
|
|
222
|
+
? { onMessageError: this.params.onMessageError }
|
|
223
|
+
: {}),
|
|
224
|
+
...(this.params.now != null ? { now: this.params.now } : {}),
|
|
225
|
+
// A session that ended is never usable again: delete its key so
|
|
226
|
+
// restoreSession() does not offer it.
|
|
227
|
+
onDropped: (reason) => {
|
|
228
|
+
void this.connector.forget(session).catch(() => undefined);
|
|
229
|
+
onDropped?.(reason);
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
return new BuilderSession(session, accounts, this.builder);
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Approves the app's builder without a session (one EIP-712 prompt), for
|
|
236
|
+
* orders the user signs with their own key. A session already approves
|
|
237
|
+
* the builder through its grant.
|
|
238
|
+
*/
|
|
239
|
+
async approveBuilder(options = {}) {
|
|
240
|
+
const { response } = await this.connector.approveBuilder({
|
|
241
|
+
account: this.accountState.address,
|
|
242
|
+
builder: {
|
|
243
|
+
account: this.builder.account,
|
|
244
|
+
maxFeeRate: options.maxFeeRate ?? this.builder.maxFeeRate,
|
|
245
|
+
},
|
|
246
|
+
...(options.ttlSeconds != null ? { ttlSeconds: options.ttlSeconds } : {}),
|
|
247
|
+
...(options.subaccounts != null
|
|
248
|
+
? { subaccounts: options.subaccounts }
|
|
249
|
+
: {}),
|
|
250
|
+
});
|
|
251
|
+
const approval = response?.approval;
|
|
252
|
+
if (approval == null || typeof approval !== 'object') {
|
|
253
|
+
throw new SessionApiError(200, {
|
|
254
|
+
error: 'INVALID_RESPONSE',
|
|
255
|
+
message: 'POST /v2/builders/approvals returned no approval',
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
return approval;
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* The account's builder approvals, standalone and in-grant. Needs the
|
|
262
|
+
* owner's login: one `personal_sign` of a Sign-In with Ethereum message
|
|
263
|
+
* naming the Paradex app, reused for 5 minutes.
|
|
264
|
+
*/
|
|
265
|
+
async listApprovals(options = {}) {
|
|
266
|
+
return await this.codes.listApprovals(await this.ownerLogin(APPROVALS_LOGIN), options);
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Revokes the account's approval of a builder (the app's by default).
|
|
270
|
+
* New orders naming it are refused at once and resting ones are
|
|
271
|
+
* cancelled. It also revokes every session of the account that names the
|
|
272
|
+
* builder, on every device, including this page's own: its
|
|
273
|
+
* {@link BuilderSession} keeps its key until its next request is refused,
|
|
274
|
+
* then the SDK drops it and calls `onDropped`. Needs the owner's
|
|
275
|
+
* login, as {@link listApprovals}.
|
|
276
|
+
*/
|
|
277
|
+
async revokeApproval(builderAccount) {
|
|
278
|
+
await this.codes.revokeApproval(await this.ownerLogin(APPROVALS_LOGIN), builderAccount ?? this.builder.account);
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* The Paradex app's Builder approvals settings page for this
|
|
282
|
+
* environment, where the user lists and revokes approvals with no
|
|
283
|
+
* cross-site warning.
|
|
284
|
+
*/
|
|
285
|
+
get approvalsSettingsUrl() {
|
|
286
|
+
return `https://${SIWE_DOMAINS[this.params.environment]}/settings/builder-approvals`;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Turns on RFQ trading for the user's account: until then its RFQ calls
|
|
290
|
+
* are refused with `RFQ_NOT_ENABLED`. A session's RFQ calls also need
|
|
291
|
+
* `trade:rfq` in its grant and Paradex allowing RFQ for the builder's
|
|
292
|
+
* sessions; this call does neither. It
|
|
293
|
+
* provisions the account on Paradigm, the RFQ venue, and registers a
|
|
294
|
+
* Paradigm delegation subkey on the account, which counts against its
|
|
295
|
+
* subkey limit. Needs the owner's login, as {@link listApprovals}; a
|
|
296
|
+
* session cannot enable RFQ. RFQ is enabled per account: pass
|
|
297
|
+
* `account` to enable one of the user's EVM sub-accounts, which takes
|
|
298
|
+
* its own owner login. Safe to call again: an enabled account gets the
|
|
299
|
+
* same state back. It can take up to 30 s; a slow call ends as a
|
|
300
|
+
* retryable 503 `SERVICE_UNAVAILABLE`, and calling again resumes it.
|
|
301
|
+
*/
|
|
302
|
+
async enableRfq(options = {}) {
|
|
303
|
+
const account = options.account != null
|
|
304
|
+
? canonicalFelt(options.account)
|
|
305
|
+
: this.accountState.address;
|
|
306
|
+
return await this.rfq.enable(await this.ownerLogin(RFQ_LOGIN, account));
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Whether {@link listApprovals}, {@link revokeApproval} and
|
|
310
|
+
* {@link enableRfq} work here without sending the user to the Paradex
|
|
311
|
+
* app: false for an injected wallet unless `allowCrossSiteOwnerLogin` is
|
|
312
|
+
* set.
|
|
313
|
+
*/
|
|
314
|
+
get canManageApprovals() {
|
|
315
|
+
return (this.params.wallet.kind !== 'injected' ||
|
|
316
|
+
this.params.allowCrossSiteOwnerLogin === true);
|
|
317
|
+
}
|
|
318
|
+
async ownerLogin(purpose, account = this.accountState.address) {
|
|
319
|
+
if (!this.canManageApprovals) {
|
|
320
|
+
throw new BuilderAppError('OWNER_LOGIN_NEEDS_PARADEX_APP', purpose === APPROVALS_LOGIN
|
|
321
|
+
? `Listing and revoking approvals with an injected wallet signs in to the Paradex app, which the wallet flags as another site. Link the user to ${this.approvalsSettingsUrl}, or set allowCrossSiteOwnerLogin.`
|
|
322
|
+
: `Enabling RFQ with an injected wallet signs in to the Paradex app, which the wallet flags as another site. Have the user enable RFQ in the Paradex app (${SIWE_DOMAINS[this.params.environment]}), or set allowCrossSiteOwnerLogin.`);
|
|
323
|
+
}
|
|
324
|
+
return await this.ownerAuth.login(account);
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Withdraws to Ethereum, signed by the owner wallet with EIP-191 (one
|
|
328
|
+
* `personal_sign` prompt). By default the funds go through StarkGate to
|
|
329
|
+
* the owner's own address and are claimable on L1 once the block is
|
|
330
|
+
* proven there.
|
|
331
|
+
*/
|
|
332
|
+
async withdraw(params) {
|
|
333
|
+
const token = params.token ?? 'USDC';
|
|
334
|
+
const client = await this.evmOwnerClient();
|
|
335
|
+
let bridgeCall = params.bridgeCall;
|
|
336
|
+
if (bridgeCall == null) {
|
|
337
|
+
const { receivableAmountChain } = await client.getReceivableAmount(token, params.amount);
|
|
338
|
+
bridgeCall = starkgateWithdrawCall({
|
|
339
|
+
config: this.config,
|
|
340
|
+
token,
|
|
341
|
+
l1Recipient: this.ownerAddress,
|
|
342
|
+
amountChain: receivableAmountChain,
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
return await client.withdraw(token, params.amount, bridgeCall);
|
|
346
|
+
}
|
|
347
|
+
async waitForTransaction(hash, options) {
|
|
348
|
+
return await (await this.evmOwnerClient()).waitForTransaction(hash, options);
|
|
349
|
+
}
|
|
350
|
+
async evmOwnerClient() {
|
|
351
|
+
this.withdrawClient ?? (this.withdrawClient = EvmOwnerClient.create({
|
|
352
|
+
config: this.config,
|
|
353
|
+
signer: walletEvmOwnerSigner(this.wallet),
|
|
354
|
+
accountAddress: this.accountState.address,
|
|
355
|
+
}).catch((error) => {
|
|
356
|
+
this.withdrawClient = undefined;
|
|
357
|
+
throw error;
|
|
358
|
+
}));
|
|
359
|
+
return await this.withdrawClient;
|
|
360
|
+
}
|
|
361
|
+
/** The app's builder fee for an order of `size` at `price`, in USDC. */
|
|
362
|
+
estimateFee(size, price, feeRate) {
|
|
363
|
+
return estimateBuilderFee({
|
|
364
|
+
size,
|
|
365
|
+
price,
|
|
366
|
+
feeRate: feeRate ?? this.builder.feeRate,
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
/** A builder's stats, one row per window (the app's builder by default). */
|
|
370
|
+
async builderStats(builderAccount) {
|
|
371
|
+
return await this.codes.fetchStats(builderAccount ?? this.builder.account);
|
|
372
|
+
}
|
|
373
|
+
async leaderboard(window) {
|
|
374
|
+
return await this.codes.fetchLeaderboard(window);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* A trading session that approves the app's builder. Calls act on the
|
|
379
|
+
* grant's main account unless `account` names one of its sub-accounts.
|
|
380
|
+
*
|
|
381
|
+
* @experimental
|
|
382
|
+
*/
|
|
383
|
+
export class BuilderSession {
|
|
384
|
+
/** @internal */
|
|
385
|
+
constructor(session, accounts, builder) {
|
|
386
|
+
this.session = session;
|
|
387
|
+
this.accounts = accounts;
|
|
388
|
+
this.builder = builder;
|
|
389
|
+
}
|
|
390
|
+
/** The main account the session trades. */
|
|
391
|
+
get account() {
|
|
392
|
+
return this.session.grant.account;
|
|
393
|
+
}
|
|
394
|
+
get expiresAt() {
|
|
395
|
+
return this.session.grant.expiresAt;
|
|
396
|
+
}
|
|
397
|
+
/** Signs and places an order carrying the app's builder fee. */
|
|
398
|
+
async placeOrder(order, account) {
|
|
399
|
+
const builderFeeRate = order.builderFeeRate ?? this.builder.feeRate;
|
|
400
|
+
// The grant's ceiling, not the app's current one: a restored session
|
|
401
|
+
// may have been opened with a lower maxFeeRate.
|
|
402
|
+
if (new BigNumber(builderFeeRate).isGreaterThan(this.session.grant.builder.maxFeeRate)) {
|
|
403
|
+
throw new BuilderAppError('BUILDER_FEE_RATE_OVER_APPROVAL', `builderFeeRate ${builderFeeRate} is above the session's approved ${this.session.grant.builder.maxFeeRate}`);
|
|
404
|
+
}
|
|
405
|
+
return (await this.accounts.placeOrder(account ?? this.account, {
|
|
406
|
+
...order,
|
|
407
|
+
builder: this.builder.account,
|
|
408
|
+
builderFeeRate,
|
|
409
|
+
}));
|
|
410
|
+
}
|
|
411
|
+
async cancelOrder(orderId, account) {
|
|
412
|
+
await this.accounts.cancelOrder(account ?? this.account, orderId);
|
|
413
|
+
}
|
|
414
|
+
async cancelOrderByClientId(clientId, account) {
|
|
415
|
+
await this.accounts.request(account ?? this.account, {
|
|
416
|
+
method: 'DELETE',
|
|
417
|
+
path: `/v1/orders/by_client_id/${encodeURIComponent(clientId)}`,
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
/** Cancels every open order, or those in one market. */
|
|
421
|
+
async cancelAllOrders(options = {}, account) {
|
|
422
|
+
await this.accounts.request(account ?? this.account, {
|
|
423
|
+
method: 'DELETE',
|
|
424
|
+
path: `/v1/orders${queryString({ market: options.market })}`,
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
async listOpenOrders(options = {}, account) {
|
|
428
|
+
const body = await this.accounts.request(account ?? this.account, {
|
|
429
|
+
method: 'GET',
|
|
430
|
+
path: `/v1/orders${queryString({ market: options.market })}`,
|
|
431
|
+
});
|
|
432
|
+
return toPage(body, 'GET /v1/orders').results;
|
|
433
|
+
}
|
|
434
|
+
async listOrdersHistory(query = {}, account) {
|
|
435
|
+
const body = await this.accounts.request(account ?? this.account, {
|
|
436
|
+
method: 'GET',
|
|
437
|
+
path: `/v1/orders-history${queryString({
|
|
438
|
+
...fillsQueryParams(query),
|
|
439
|
+
side: query.side,
|
|
440
|
+
status: query.status,
|
|
441
|
+
type: query.type,
|
|
442
|
+
client_id: query.clientId,
|
|
443
|
+
})}`,
|
|
444
|
+
});
|
|
445
|
+
return toPage(body, 'GET /v1/orders-history');
|
|
446
|
+
}
|
|
447
|
+
/** Fills, newest first, with the builder fee each paid. */
|
|
448
|
+
async listFills(query = {}, account) {
|
|
449
|
+
const body = await this.accounts.request(account ?? this.account, {
|
|
450
|
+
method: 'GET',
|
|
451
|
+
path: `/v1/fills${queryString(fillsQueryParams(query))}`,
|
|
452
|
+
});
|
|
453
|
+
return toPage(body, 'GET /v1/fills');
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* The account's onboarding state. A new account reads `ONBOARDING` and
|
|
457
|
+
* `is_deployed: false` until it deploys.
|
|
458
|
+
*/
|
|
459
|
+
async accountInfo(account) {
|
|
460
|
+
return (await this.accounts.request(account ?? this.account, {
|
|
461
|
+
method: 'GET',
|
|
462
|
+
path: '/v1/account/info',
|
|
463
|
+
}));
|
|
464
|
+
}
|
|
465
|
+
async status() {
|
|
466
|
+
return await this.accounts.status();
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Subscribes to a websocket channel, such as `orders.ALL`, `fills.ALL`,
|
|
470
|
+
* `positions`, `account` or `bbo.BTC-USD-PERP`; returns the unsubscribe
|
|
471
|
+
* function. Fills come without the builder fee: read it with
|
|
472
|
+
* {@link listFills}. See {@link SessionAccounts.subscribe}.
|
|
473
|
+
*/
|
|
474
|
+
async subscribe(channel, handler, account) {
|
|
475
|
+
return await this.accounts.subscribe(account ?? this.account, channel, handler);
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Ends the session on the server and deletes its key from storage. Its
|
|
479
|
+
* resting orders, TWAPs and untriggered stops are cancelled. With
|
|
480
|
+
* `cancelOrders: false` only resting orders are kept: a grant that names
|
|
481
|
+
* a builder still has its TWAPs and untriggered stops cancelled, and its
|
|
482
|
+
* kept orders last until the approval ends, by revoke or expiry.
|
|
483
|
+
*
|
|
484
|
+
* The builder approval the grant carried stays active until it expires
|
|
485
|
+
* (by default, when the last of the sessions that carried it would have
|
|
486
|
+
* expired, unless {@link BuilderApp.approveBuilder} gave it its own
|
|
487
|
+
* expiry). To end it too, call
|
|
488
|
+
* {@link BuilderApp.revokeApproval}, which also revokes the account's
|
|
489
|
+
* sessions naming the builder and cancels resting orders naming it. With
|
|
490
|
+
* an injected wallet, link to {@link BuilderApp.approvalsSettingsUrl}
|
|
491
|
+
* instead.
|
|
492
|
+
*/
|
|
493
|
+
async revoke(options = {}) {
|
|
494
|
+
await this.accounts.revoke(options);
|
|
495
|
+
}
|
|
496
|
+
/** Closes sockets and timers; the session stays valid. */
|
|
497
|
+
close() {
|
|
498
|
+
this.accounts.close();
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
async function lookupAccount(transport, apiUrl, ethAddress) {
|
|
502
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(ethAddress)) {
|
|
503
|
+
throw new Error('Wallet address must be a 0x-prefixed 20-byte address');
|
|
504
|
+
}
|
|
505
|
+
const response = await transport({
|
|
506
|
+
method: 'GET',
|
|
507
|
+
url: `${apiUrl}/v1/onboarding${queryString({
|
|
508
|
+
eth_address: ethAddress,
|
|
509
|
+
account_signer_type: 'eip191',
|
|
510
|
+
})}`,
|
|
511
|
+
headers: {},
|
|
512
|
+
});
|
|
513
|
+
if (response.status < 200 || response.status >= 300) {
|
|
514
|
+
throw new SessionApiError(response.status, response.body);
|
|
515
|
+
}
|
|
516
|
+
const body = (response.body ?? {});
|
|
517
|
+
if (typeof body.address !== 'string' || typeof body.exists !== 'boolean') {
|
|
518
|
+
throw new SessionApiError(response.status, {
|
|
519
|
+
error: 'INVALID_RESPONSE',
|
|
520
|
+
message: 'GET /v1/onboarding returned no address',
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
if (body.account_signer_type !== 'eip191') {
|
|
524
|
+
throw new BuilderAppError('STARK_OWNED_ACCOUNT', "The wallet's Paradex account is Stark-owned; builder apps need an EVM-owned account");
|
|
525
|
+
}
|
|
526
|
+
return { address: canonicalFelt(body.address), exists: body.exists };
|
|
527
|
+
}
|
package/dist/builder-codes.d.ts
CHANGED
|
@@ -85,7 +85,8 @@ export declare class BuilderCodesClient {
|
|
|
85
85
|
/**
|
|
86
86
|
* `DELETE /v2/builders/approvals/{builder_account}`: new orders naming the
|
|
87
87
|
* builder are refused at once, on the account and its sub-accounts, and
|
|
88
|
-
* the resting orders naming it there are cancelled.
|
|
88
|
+
* the resting orders naming it there are cancelled. Every session of the
|
|
89
|
+
* account that names the builder is revoked too, on every device. A
|
|
89
90
|
* builder with no live approval is a 404 `SessionApiError`.
|
|
90
91
|
*/
|
|
91
92
|
revokeApproval(token: string, builderAccount: string): Promise<void>;
|
|
@@ -104,3 +105,5 @@ export declare class BuilderCodesClient {
|
|
|
104
105
|
private send;
|
|
105
106
|
private results;
|
|
106
107
|
}
|
|
108
|
+
/** The `Authorization` header for an account owner's JWT. */
|
|
109
|
+
export declare function bearer(token: string): Record<string, string>;
|
package/dist/builder-codes.js
CHANGED
|
@@ -39,7 +39,8 @@ export class BuilderCodesClient {
|
|
|
39
39
|
/**
|
|
40
40
|
* `DELETE /v2/builders/approvals/{builder_account}`: new orders naming the
|
|
41
41
|
* builder are refused at once, on the account and its sub-accounts, and
|
|
42
|
-
* the resting orders naming it there are cancelled.
|
|
42
|
+
* the resting orders naming it there are cancelled. Every session of the
|
|
43
|
+
* account that names the builder is revoked too, on every device. A
|
|
43
44
|
* builder with no live approval is a 404 `SessionApiError`.
|
|
44
45
|
*/
|
|
45
46
|
async revokeApproval(token, builderAccount) {
|
|
@@ -93,7 +94,8 @@ export class BuilderCodesClient {
|
|
|
93
94
|
return results;
|
|
94
95
|
}
|
|
95
96
|
}
|
|
96
|
-
|
|
97
|
+
/** The `Authorization` header for an account owner's JWT. */
|
|
98
|
+
export function bearer(token) {
|
|
97
99
|
if (typeof token !== 'string' || token === '') {
|
|
98
100
|
throw new Error("token must be the account owner's JWT");
|
|
99
101
|
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import * as Starknet from 'starknet';
|
|
2
|
+
import type { ReceivableAmount, SocializedLossFactor, WithdrawResult } from './client.js';
|
|
3
|
+
import type { ParadexConfig } from './config.js';
|
|
4
|
+
import { type EvmOwnerSigner } from './evm-owner-signer.js';
|
|
5
|
+
import { DefaultProvider } from './paraclear-provider.js';
|
|
6
|
+
/**
|
|
7
|
+
* L2 gas reserved for `__validate__` on an EIP-191 account. Validation runs
|
|
8
|
+
* keccak256 and a secp256k1 ecrecover in Cairo, a fixed cost of about 17.3M
|
|
9
|
+
* L2 gas whatever the call does; this leaves headroom over it.
|
|
10
|
+
*/
|
|
11
|
+
export declare const EVM_VALIDATE_L2_GAS = 25000000n;
|
|
12
|
+
/**
|
|
13
|
+
* The fee is estimated with `SKIP_VALIDATE`, so the wallet is asked to sign
|
|
14
|
+
* once, not twice. The estimate then leaves out `__validate__`, whose cost
|
|
15
|
+
* is fixed, so it is added rather than scaled: a multiplier on a cheap
|
|
16
|
+
* call's estimate falls short of it and the transaction runs out of gas.
|
|
17
|
+
* Execution gets 50% headroom because the estimate runs at `pre_confirmed`
|
|
18
|
+
* and execution at inclusion can cost more.
|
|
19
|
+
*/
|
|
20
|
+
export declare function withEvmValidationGas(bounds: Starknet.ResourceBoundsBN): Starknet.ResourceBoundsBN;
|
|
21
|
+
export interface CreateClientFromEvmOwnerParams {
|
|
22
|
+
readonly config: ParadexConfig;
|
|
23
|
+
/** The EVM wallet that owns the account. See `EvmOwnerSigner`. */
|
|
24
|
+
readonly signer: EvmOwnerSigner;
|
|
25
|
+
/**
|
|
26
|
+
* The EVM-owned account to act on. Defaults to the wallet's main account,
|
|
27
|
+
* looked up with `GET /onboarding?eth_address=…&account_signer_type=eip191`.
|
|
28
|
+
* Pass it for an EVM sub-account the same wallet owns.
|
|
29
|
+
*/
|
|
30
|
+
readonly accountAddress?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Paradex REST API base URL for the account lookup.
|
|
33
|
+
* Defaults to `config.paradexApiUrl`.
|
|
34
|
+
*/
|
|
35
|
+
readonly apiUrl?: string;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Client for an EVM-owned (EIP-191) Paradex account, whose on-chain owner is
|
|
39
|
+
* an EVM wallet rather than a Stark key. Every transaction is signed by the
|
|
40
|
+
* owner wallet with `personal_sign` over the Starknet transaction hash.
|
|
41
|
+
*
|
|
42
|
+
* No Stark key is derived: `Client.fromEthSigner` derives a key for a
|
|
43
|
+
* different (Stark-owned) account and must not be used for these accounts.
|
|
44
|
+
*
|
|
45
|
+
* Balance reads (`getTokenBalance`, `getMaxWithdraw`) are not offered: the
|
|
46
|
+
* Paradex full node returns account data only to authenticated callers. Use
|
|
47
|
+
* the REST API (`GET /v1/balance`) with the account's JWT instead.
|
|
48
|
+
*/
|
|
49
|
+
export declare class EvmOwnerClient {
|
|
50
|
+
private readonly config;
|
|
51
|
+
private readonly provider;
|
|
52
|
+
private readonly account;
|
|
53
|
+
private readonly ownerAddress;
|
|
54
|
+
private constructor();
|
|
55
|
+
static create({ config, signer, accountAddress, apiUrl, }: CreateClientFromEvmOwnerParams): Promise<EvmOwnerClient>;
|
|
56
|
+
/** The Paradex (Starknet) account address. */
|
|
57
|
+
getAddress(): string;
|
|
58
|
+
/** The EVM wallet that owns the account and signs its transactions. */
|
|
59
|
+
getOwnerAddress(): string;
|
|
60
|
+
getSocializedLossFactor(): Promise<SocializedLossFactor>;
|
|
61
|
+
/** The amount a withdrawal of `amount` delivers after socialized loss. */
|
|
62
|
+
getReceivableAmount(token: string, amount: string): Promise<ReceivableAmount>;
|
|
63
|
+
/**
|
|
64
|
+
* Withdraws `amount` of `token` from Paraclear and runs `bridgeCall` in the
|
|
65
|
+
* same atomic transaction, signed by the owner wallet (one signature
|
|
66
|
+
* prompt).
|
|
67
|
+
*
|
|
68
|
+
* `paraclear.withdraw` moves the funds to the account contract's own
|
|
69
|
+
* Starknet token balance; the bridge call must then move them out (for
|
|
70
|
+
* example `starkgateWithdrawCall`). Build it for the receivable amount
|
|
71
|
+
* from `getReceivableAmount`. Do not use `paraclear.transfer` as a bridge
|
|
72
|
+
* call: it credits another Paradex account's Paraclear balance, not the
|
|
73
|
+
* bridge.
|
|
74
|
+
*/
|
|
75
|
+
withdraw(token: string, amount: string, bridgeCall: Starknet.Call | readonly Starknet.Call[]): Promise<WithdrawResult>;
|
|
76
|
+
/**
|
|
77
|
+
* Signs and sends any invoke from the account with the owner wallet.
|
|
78
|
+
* @advanced Prefer `withdraw`.
|
|
79
|
+
*/
|
|
80
|
+
execute(calls: Starknet.Call | readonly Starknet.Call[]): Promise<WithdrawResult>;
|
|
81
|
+
waitForTransaction(txHash: string, options?: Starknet.waitForTransactionOptions): Promise<Starknet.GetTransactionReceiptResponse>;
|
|
82
|
+
/** The underlying provider (unauthenticated full-node RPC). */
|
|
83
|
+
getProvider(): DefaultProvider;
|
|
84
|
+
}
|
|
85
|
+
export interface StarkgateWithdrawCallParams {
|
|
86
|
+
readonly config: ParadexConfig;
|
|
87
|
+
/** Token symbol, e.g. `'USDC'`. */
|
|
88
|
+
readonly token: string;
|
|
89
|
+
/** Ethereum (L1) address that receives the funds. */
|
|
90
|
+
readonly l1Recipient: string;
|
|
91
|
+
/**
|
|
92
|
+
* Amount in the token's own decimals, normally `receivableAmountChain`
|
|
93
|
+
* from `getReceivableAmount`.
|
|
94
|
+
*/
|
|
95
|
+
readonly amountChain: string;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The StarkGate bridge call that sends a withdrawn amount to Ethereum: the
|
|
99
|
+
* funds are claimable on L1 once the Starknet block is proven there.
|
|
100
|
+
*/
|
|
101
|
+
export declare function starkgateWithdrawCall({ config, token, l1Recipient, amountChain, }: StarkgateWithdrawCallParams): Starknet.Call;
|