@paradex/sdk 0.10.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 +177 -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 +109 -0
- package/dist/builder-codes.js +103 -0
- 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 +56 -4
- package/dist/index.js +45 -2
- 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 +158 -40
- package/dist/session-auth.d.ts +30 -0
- package/dist/session-auth.js +70 -18
- package/dist/session-connector.d.ts +35 -1
- package/dist/session-connector.js +72 -1
- package/dist/session-transport.d.ts +8 -1
- package/dist/session-transport.js +4 -0
- package/dist/session-typed-data.d.ts +81 -7
- package/dist/session-typed-data.js +128 -18
- 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
|
@@ -2,9 +2,11 @@ import { hashTypedData } from './eip712.js';
|
|
|
2
2
|
import { assertRecordVersion, memorySessionStorage, SessionKey, } from './session-key.js';
|
|
3
3
|
import { assertEoaSignature, } from './session-owner-signer.js';
|
|
4
4
|
import { defaultApiUrl, fetchTransport, SessionApiError, } from './session-transport.js';
|
|
5
|
-
import { assertGrantActive, buildSessionGrantEip712, canonicalFelt, createSessionGrant, grantAccounts, nowSeconds, SessionGrantError, } from './session-typed-data.js';
|
|
5
|
+
import { assertGrantActive, buildBuilderApprovalEip712, buildSessionGrantEip712, canonicalFelt, createBuilderApproval, createSessionGrant, grantAccounts, nowSeconds, SessionGrantError, } from './session-typed-data.js';
|
|
6
6
|
export const SESSIONS_PATH = '/v2/sessions';
|
|
7
7
|
export const EVM_SUBACCOUNTS_PATH = '/v2/onboarding/subaccounts';
|
|
8
|
+
export const BUILDER_APPROVALS_PATH = '/v2/builders/approvals';
|
|
9
|
+
export const SYSTEM_TIME_PATH = '/v1/system/time';
|
|
8
10
|
/** Whether `open()` finished registering this record. */
|
|
9
11
|
function isRegistered(record) {
|
|
10
12
|
return (record.grant != null &&
|
|
@@ -201,6 +203,75 @@ export class SessionConnector {
|
|
|
201
203
|
throw error;
|
|
202
204
|
}
|
|
203
205
|
}
|
|
206
|
+
/**
|
|
207
|
+
* Has the owner approve a builder's fee without opening a session (one
|
|
208
|
+
* wallet prompt) and registers the approval with
|
|
209
|
+
* `POST /v2/builders/approvals`, which needs no JWT. The approval covers
|
|
210
|
+
* the account and any `subaccounts` it lists until `builder.expiresAt`.
|
|
211
|
+
* The owner revokes it with `DELETE /v2/builders/approvals/{builder_account}`.
|
|
212
|
+
*
|
|
213
|
+
* `issuedAt` is the server's time in whole seconds, and the server refuses
|
|
214
|
+
* an approval issued in the same second as the builder's last revoke or
|
|
215
|
+
* approval (including one a session grant made) with
|
|
216
|
+
* `BUILDER_APPROVAL_STALE`. So after either, wait for the next server
|
|
217
|
+
* second, or the owner signs an approval that is refused.
|
|
218
|
+
*
|
|
219
|
+
* @experimental
|
|
220
|
+
*/
|
|
221
|
+
async approveBuilder(params) {
|
|
222
|
+
const approval = createBuilderApproval({
|
|
223
|
+
...params,
|
|
224
|
+
paradexChain: this.paradexChain,
|
|
225
|
+
environment: this.environment,
|
|
226
|
+
issuedAt: await this.serverTime(),
|
|
227
|
+
});
|
|
228
|
+
await this.assertSubaccountsOwned(approval);
|
|
229
|
+
const signatureChainId = await this.owner.getChainId();
|
|
230
|
+
const typedData = buildBuilderApprovalEip712(approval, signatureChainId);
|
|
231
|
+
const ownerSignature = assertEoaSignature(await this.owner.signTypedData({
|
|
232
|
+
typedData,
|
|
233
|
+
digest: hashTypedData(typedData),
|
|
234
|
+
}));
|
|
235
|
+
const response = await this.transport({
|
|
236
|
+
method: 'POST',
|
|
237
|
+
url: `${this.apiUrl}${BUILDER_APPROVALS_PATH}`,
|
|
238
|
+
headers: { 'Content-Type': 'application/json' },
|
|
239
|
+
body: JSON.stringify({
|
|
240
|
+
approval,
|
|
241
|
+
signature: ownerSignature,
|
|
242
|
+
signature_type: 'eip712',
|
|
243
|
+
signature_chain_id: signatureChainId,
|
|
244
|
+
}),
|
|
245
|
+
});
|
|
246
|
+
if (response.status < 200 || response.status >= 300) {
|
|
247
|
+
throw new SessionApiError(response.status, response.body);
|
|
248
|
+
}
|
|
249
|
+
return {
|
|
250
|
+
approval,
|
|
251
|
+
ownerSignature,
|
|
252
|
+
signatureChainId,
|
|
253
|
+
response: response.body,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
/** The server's clock in whole seconds, from `GET /v1/system/time`. */
|
|
257
|
+
async serverTime() {
|
|
258
|
+
const response = await this.transport({
|
|
259
|
+
method: 'GET',
|
|
260
|
+
url: `${this.apiUrl}${SYSTEM_TIME_PATH}`,
|
|
261
|
+
headers: {},
|
|
262
|
+
});
|
|
263
|
+
if (response.status < 200 || response.status >= 300) {
|
|
264
|
+
throw new SessionApiError(response.status, response.body);
|
|
265
|
+
}
|
|
266
|
+
const ms = Number(response.body?.server_time);
|
|
267
|
+
if (!Number.isSafeInteger(ms) || ms <= 0) {
|
|
268
|
+
throw new SessionApiError(response.status, {
|
|
269
|
+
error: 'INVALID_RESPONSE',
|
|
270
|
+
message: `GET ${SYSTEM_TIME_PATH} returned no server_time`,
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
return Math.floor(ms / 1000);
|
|
274
|
+
}
|
|
204
275
|
/**
|
|
205
276
|
* Restores registered sessions from storage for this environment. Expired
|
|
206
277
|
* sessions and sessions that never registered are deleted; records that
|
|
@@ -21,6 +21,8 @@ export declare const fetchTransport: HttpTransport;
|
|
|
21
21
|
/** The subset of the WHATWG `WebSocket` used here. */
|
|
22
22
|
export interface WebSocketLike {
|
|
23
23
|
readonly readyState: number;
|
|
24
|
+
/** Set to `arraybuffer`: the server's data messages are binary. */
|
|
25
|
+
binaryType?: string;
|
|
24
26
|
send: (data: string) => void;
|
|
25
27
|
close: (code?: number, reason?: string) => void;
|
|
26
28
|
onopen: ((event: unknown) => void) | null;
|
|
@@ -38,11 +40,16 @@ export declare function defaultWsUrl(environment: SessionEnvironment): string;
|
|
|
38
40
|
* Error codes the session endpoints are known to return. Servers may add
|
|
39
41
|
* codes, so `SessionApiError.code` can hold any string.
|
|
40
42
|
*/
|
|
41
|
-
export type KnownSessionApiErrorCode = 'INVALID_SIGNATURE' | 'GRANT_EXPIRED' | 'INVALID_ENVIRONMENT' | 'INVALID_CHAIN' | 'SCOPE_NOT_ALLOWED' | 'LIMIT_INVALID' | 'NONCE_REUSED' | 'ACCOUNT_NOT_ELIGIBLE' | 'INVALID_GRANT' | 'SESSION_KEY_IN_USE' | 'SESSION_LIMIT_REACHED' | 'BUILDER_APPROVAL_LIMIT_REACHED' | 'BUILDER_APPROVAL_STALE' | 'SESSIONS_DISABLED' | 'INVALID_MARKETING_CODE' | 'INVALID_REQUEST_PARAMETER' | 'INSUFFICIENT_MIN_CHAIN_BALANCE' | 'ETHEREUM_ADDRESS_BLOCKED' | 'PARENT_ADDRESS_ALREADY_ONBOARDED' | 'ONBOARDING_RATE_LIMITED' | 'SESSION_REVOKED' | 'SESSION_EXPIRED' | 'NOT_ONBOARDED' | 'INVALID_TOKEN' | 'INVALID_SUBKEY' | 'STARKNET_SIGNATURE_VERIFICATION_FAILED' | 'INVALID_TOKEN_SCOPE' | 'REQUEST_NOT_ALLOWED' | 'IP_NOT_ALLOWED' | 'NOT_FOUND' | 'INVALID_RESPONSE';
|
|
43
|
+
export type KnownSessionApiErrorCode = 'INVALID_SIGNATURE' | 'GRANT_EXPIRED' | 'INVALID_ENVIRONMENT' | 'INVALID_CHAIN' | 'SCOPE_NOT_ALLOWED' | 'LIMIT_INVALID' | 'NONCE_REUSED' | 'ACCOUNT_NOT_ELIGIBLE' | 'INVALID_GRANT' | 'SESSION_KEY_IN_USE' | 'SESSION_LIMIT_REACHED' | 'BUILDER_APPROVAL_LIMIT_REACHED' | 'BUILDER_APPROVAL_STALE' | 'SESSIONS_DISABLED' | 'INVALID_MARKETING_CODE' | 'INVALID_REQUEST_PARAMETER' | 'INSUFFICIENT_MIN_CHAIN_BALANCE' | 'ETHEREUM_ADDRESS_BLOCKED' | 'PARENT_ADDRESS_ALREADY_ONBOARDED' | 'ONBOARDING_RATE_LIMITED' | 'SESSION_REVOKED' | 'SESSION_EXPIRED' | 'NOT_ONBOARDED' | 'INVALID_TOKEN' | 'INVALID_SUBKEY' | 'STARKNET_SIGNATURE_VERIFICATION_FAILED' | 'INVALID_TOKEN_SCOPE' | 'REQUEST_NOT_ALLOWED' | 'IP_NOT_ALLOWED' | 'NOT_FOUND' | 'EVM_SIGNATURE_VERIFICATION_FAILED' | 'INVALID_EVM_SIGNATURE' | 'ETHEREUM_SIGNER_MISMATCH' | 'INVALID_STARKNET_ADDRESS' | 'PUBLIC_KEY_INVALID' | 'UNAUTHORIZED_ERROR' | 'BUILDER_CODES_NOT_ENABLED' | 'BUILDER_NOT_APPROVED' | 'BUILDER_FEE_RATE_OVER_APPROVAL' | 'BUILDER_NOT_ONBOARDED' | 'RFQ_NOT_ENABLED' | 'TOKEN_LIMIT_REACHED' | 'SUBKEY_REVOKED' | 'VALIDATION_ERROR' | 'ORDER_ID_NOT_FOUND' | 'ORDER_IS_CLOSED' | 'CLIENT_ORDER_ID_NOT_FOUND' | 'DUPLICATED_CLIENT_ID' | 'INVALID_ORDER_SIZE' | 'MARKET_NOT_FOUND' | 'MARKET_NOT_OPEN' | 'NO_ACCESS_TO_MARKET' | 'SYSTEM_STATUS_POST_ONLY' | 'SYSTEM_STATUS_CANCEL_ONLY' | 'GEO_IP_BLOCK' | 'SERVICE_UNAVAILABLE' | 'INTERNAL_ERROR' | 'INVALID_RESPONSE';
|
|
42
44
|
export type SessionApiErrorCode = KnownSessionApiErrorCode | (string & {});
|
|
43
45
|
export declare class SessionApiError extends Error {
|
|
44
46
|
readonly status: number;
|
|
45
47
|
readonly code: SessionApiErrorCode | undefined;
|
|
46
48
|
readonly body: unknown;
|
|
49
|
+
/**
|
|
50
|
+
* Per-field detail the server adds to some errors, such as
|
|
51
|
+
* `INVALID_REQUEST_PARAMETER`'s `{ builder_fee_rate: "…" }`.
|
|
52
|
+
*/
|
|
53
|
+
readonly data: Readonly<Record<string, unknown>> | undefined;
|
|
47
54
|
constructor(status: number, body: unknown);
|
|
48
55
|
}
|
|
@@ -33,7 +33,9 @@ export declare const SESSION_TTL: {
|
|
|
33
33
|
export declare const MAX_PASSKEY_CONCURRENT_SESSIONS = 5;
|
|
34
34
|
/** A grant, mint or passkey ceiling lists at most this many subaccounts. */
|
|
35
35
|
export declare const MAX_GRANT_SUBACCOUNTS = 32;
|
|
36
|
-
export type SessionGrantErrorCode = 'INVALID_FIELD' | 'UNKNOWN_SCOPE' | 'RESERVED_SCOPE' | 'TTL_EXCEEDED'
|
|
36
|
+
export type SessionGrantErrorCode = 'INVALID_FIELD' | 'UNKNOWN_SCOPE' | 'RESERVED_SCOPE' | 'TTL_EXCEEDED'
|
|
37
|
+
/** @deprecated No longer thrown: builder grants follow the normal limit rules. */
|
|
38
|
+
| 'BUILDER_LIMITS_REQUIRED' | 'BUILDER_REQUIRES_EIP712' | 'GRANT_EXPIRED' | 'GRANT_REVOKED' | 'ENVIRONMENT_MISMATCH' | 'ACCOUNT_NOT_IN_GRANT' | 'ACCOUNT_NOT_ELIGIBLE' | 'EXCEEDS_CEILING' | 'SCOPE_NOT_ALLOWED' | 'LIMIT_INVALID';
|
|
37
39
|
export declare class SessionGrantError extends Error {
|
|
38
40
|
readonly code: SessionGrantErrorCode;
|
|
39
41
|
constructor(code: SessionGrantErrorCode, message: string);
|
|
@@ -141,6 +143,24 @@ export interface PasskeyGrant {
|
|
|
141
143
|
readonly issuedAt: number;
|
|
142
144
|
readonly expiresAt: number;
|
|
143
145
|
}
|
|
146
|
+
/**
|
|
147
|
+
* An EVM owner's approval of a builder's fee, outside any session grant.
|
|
148
|
+
* Signed with EIP-712 only and registered with
|
|
149
|
+
* `POST /v2/builders/approvals`.
|
|
150
|
+
*
|
|
151
|
+
* @experimental
|
|
152
|
+
*/
|
|
153
|
+
export interface BuilderApproval {
|
|
154
|
+
readonly paradexChain: string;
|
|
155
|
+
readonly environment: SessionEnvironment;
|
|
156
|
+
readonly account: string;
|
|
157
|
+
/** `expiresAt` is required here: there is no session to follow. */
|
|
158
|
+
readonly builder: Builder;
|
|
159
|
+
readonly subaccounts: readonly string[];
|
|
160
|
+
readonly nonce: string;
|
|
161
|
+
/** Seconds, by the server's clock: the server refuses one in its future. */
|
|
162
|
+
readonly issuedAt: number;
|
|
163
|
+
}
|
|
144
164
|
/**
|
|
145
165
|
* What a passkey signs to open one session; its SNIP-12 hash is the WebAuthn
|
|
146
166
|
* challenge ({@link sessionMintChallenge}).
|
|
@@ -184,11 +204,19 @@ export declare const CEILING_LIMITS: Limits;
|
|
|
184
204
|
/** Whether `limits` are {@link CEILING_LIMITS}: no limit stated at all. */
|
|
185
205
|
export declare function isCeilingLimits(limits: Limits): boolean;
|
|
186
206
|
export declare const SESSION_GRANT_EIP712_TYPES: Eip712Types;
|
|
207
|
+
export declare const BUILDER_APPROVAL_EIP712_TYPES: Eip712Types;
|
|
187
208
|
export declare const PASSKEY_GRANT_EIP712_TYPES: Eip712Types;
|
|
188
209
|
export declare const SESSION_MINT_EIP712_TYPES: Eip712Types;
|
|
189
210
|
export declare const SESSION_GRANT_SNIP12_TYPES: Starknet.TypedData['types'];
|
|
190
211
|
export declare const PASSKEY_GRANT_SNIP12_TYPES: Starknet.TypedData['types'];
|
|
191
212
|
export declare const SESSION_MINT_SNIP12_TYPES: Starknet.TypedData['types'];
|
|
213
|
+
/**
|
|
214
|
+
* A builder account in canonical `0x` form, refusing anything but a
|
|
215
|
+
* non-zero felt address. Orders and the Builder Codes calls share it.
|
|
216
|
+
*
|
|
217
|
+
* @internal
|
|
218
|
+
*/
|
|
219
|
+
export declare function builderAddress(value: string, name?: string): string;
|
|
192
220
|
/** Whether a ceiling market entry covers a mint's market entry. */
|
|
193
221
|
export declare function marketCovers(pattern: string, market: string): boolean;
|
|
194
222
|
/**
|
|
@@ -205,10 +233,11 @@ export declare function validateScopes(scopes: readonly string[], field?: string
|
|
|
205
233
|
* non-empty list, or `["*"]` alone. A limit the server does not enforce
|
|
206
234
|
* must be `"none"` (`markets`: `["*"]`).
|
|
207
235
|
*
|
|
208
|
-
*
|
|
209
|
-
*
|
|
236
|
+
* Builder grants and builder passkeys follow the same rules as any other grant.
|
|
237
|
+
*
|
|
238
|
+
* @param _builderGrant ignored; kept so existing callers still compile.
|
|
210
239
|
*/
|
|
211
|
-
export declare function validateLimits(limits: Limits,
|
|
240
|
+
export declare function validateLimits(limits: Limits, _builderGrant: boolean, field?: string, options?: LimitOptions): void;
|
|
212
241
|
export type SessionType = 'browser' | 'api';
|
|
213
242
|
/**
|
|
214
243
|
* Longest lifetime a grant with these scopes can request. The server measures
|
|
@@ -240,6 +269,18 @@ export interface ValidateSessionGrantOptions extends LimitOptions {
|
|
|
240
269
|
* before the owner is asked to sign.
|
|
241
270
|
*/
|
|
242
271
|
export declare function validateSessionGrant(grant: SessionGrant, options?: ValidateSessionGrantOptions): void;
|
|
272
|
+
/** Longest a builder approval may live after its `issuedAt`. */
|
|
273
|
+
export declare const BUILDER_APPROVAL_TTL_MAX: number;
|
|
274
|
+
/**
|
|
275
|
+
* Checks a builder approval against the server's rules: a builder other than
|
|
276
|
+
* the account, a `maxFeeRate` above 0 with at most 8 decimal places, and a
|
|
277
|
+
* required `expiresAt` at most
|
|
278
|
+
* {@link BUILDER_APPROVAL_TTL_MAX} after `issuedAt`. Throws a
|
|
279
|
+
* {@link SessionGrantError}.
|
|
280
|
+
*
|
|
281
|
+
* @experimental
|
|
282
|
+
*/
|
|
283
|
+
export declare function validateBuilderApproval(approval: BuilderApproval): void;
|
|
243
284
|
export interface ValidatePasskeyGrantOptions extends LimitOptions {
|
|
244
285
|
/**
|
|
245
286
|
* Whether the server accepts subaccounts in a passkey ceiling. Defaults to
|
|
@@ -282,9 +323,8 @@ export interface AssertMintOptions extends LimitOptions {
|
|
|
282
323
|
* unless it allows `["*"]`. Unenforced limits are `"none"` on the mint and
|
|
283
324
|
* skipped, so passkeys registered with numeric limits keep working. A mint
|
|
284
325
|
* stating {@link CEILING_LIMITS} takes the ceiling's and fits by definition.
|
|
285
|
-
* A builder passkey's mints are checked like any other
|
|
286
|
-
*
|
|
287
|
-
* not list the passkey's account.
|
|
326
|
+
* A builder passkey's mints are checked like any other. Subaccounts must not
|
|
327
|
+
* list the passkey's account.
|
|
288
328
|
*
|
|
289
329
|
* The check holds only when `grant`'s passkey signs. With an empty
|
|
290
330
|
* `allowCredentials` the user may pick another passkey, on another account
|
|
@@ -347,6 +387,32 @@ export declare function nowSeconds(): number;
|
|
|
347
387
|
* @experimental
|
|
348
388
|
*/
|
|
349
389
|
export declare function createSessionGrant(params: CreateSessionGrantParams): SessionGrant;
|
|
390
|
+
export interface CreateBuilderApprovalParams {
|
|
391
|
+
readonly paradexChain: string;
|
|
392
|
+
readonly environment: SessionEnvironment;
|
|
393
|
+
readonly account: string;
|
|
394
|
+
/**
|
|
395
|
+
* The builder and its fee cap. `expiresAt` (seconds) defaults to
|
|
396
|
+
* `issuedAt + ttlSeconds`, as on a grant's builder.
|
|
397
|
+
*/
|
|
398
|
+
readonly builder: {
|
|
399
|
+
readonly account: string;
|
|
400
|
+
readonly maxFeeRate: string;
|
|
401
|
+
readonly expiresAt?: number;
|
|
402
|
+
};
|
|
403
|
+
/** Seconds, from the server's clock (`GET /v1/system/time`). */
|
|
404
|
+
readonly issuedAt: number;
|
|
405
|
+
/** Defaults to {@link BUILDER_APPROVAL_TTL_MAX}. */
|
|
406
|
+
readonly ttlSeconds?: number;
|
|
407
|
+
readonly subaccounts?: readonly string[];
|
|
408
|
+
readonly nonce?: string;
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Builds a canonical, validated {@link BuilderApproval}.
|
|
412
|
+
*
|
|
413
|
+
* @experimental
|
|
414
|
+
*/
|
|
415
|
+
export declare function createBuilderApproval(params: CreateBuilderApprovalParams): BuilderApproval;
|
|
350
416
|
/** Every account a grant reaches: the anchor first, then its sub-accounts. */
|
|
351
417
|
export declare function grantAccounts(grant: Pick<SessionGrant, 'account' | 'subaccounts'>): readonly string[];
|
|
352
418
|
/**
|
|
@@ -376,6 +442,14 @@ export declare function buildPasskeyGrantSnip12(grant: PasskeyGrant, options?: V
|
|
|
376
442
|
export declare function buildSessionMintEip712(mint: SessionMint, signatureChainId: number | string | bigint, options?: LimitOptions): Eip712TypedData;
|
|
377
443
|
/** @experimental */
|
|
378
444
|
export declare function buildSessionMintSnip12(mint: SessionMint, options?: LimitOptions): Starknet.TypedData;
|
|
445
|
+
/**
|
|
446
|
+
* EIP-712 `BuilderApproval`, signed by the account's EVM owner on the
|
|
447
|
+
* wallet's current chain. There is no SNIP-12 form: the server accepts
|
|
448
|
+
* builder approvals from EVM owners only.
|
|
449
|
+
*
|
|
450
|
+
* @experimental
|
|
451
|
+
*/
|
|
452
|
+
export declare function buildBuilderApprovalEip712(approval: BuilderApproval, signatureChainId: number | string | bigint): Eip712TypedData;
|
|
379
453
|
/** EIP-712 digest (`0x1901 ‖ domain ‖ struct`) as 0x-prefixed 32-byte hex. */
|
|
380
454
|
export declare function hashEip712(typedData: Eip712TypedData): Hex;
|
|
381
455
|
/**
|
|
@@ -132,6 +132,11 @@ const EIP712_LIMITS = [
|
|
|
132
132
|
{ name: 'maxLeverage', type: 'string' },
|
|
133
133
|
{ name: 'markets', type: 'string[]' },
|
|
134
134
|
];
|
|
135
|
+
const EIP712_BUILDER = [
|
|
136
|
+
{ name: 'account', type: 'string' },
|
|
137
|
+
{ name: 'maxFeeRate', type: 'string' },
|
|
138
|
+
{ name: 'expiresAt', type: 'uint64' },
|
|
139
|
+
];
|
|
135
140
|
export const SESSION_GRANT_EIP712_TYPES = {
|
|
136
141
|
SessionGrant: [
|
|
137
142
|
{ name: 'paradexChain', type: 'string' },
|
|
@@ -148,11 +153,19 @@ export const SESSION_GRANT_EIP712_TYPES = {
|
|
|
148
153
|
{ name: 'expiresAt', type: 'uint64' },
|
|
149
154
|
],
|
|
150
155
|
Limits: EIP712_LIMITS,
|
|
151
|
-
Builder:
|
|
156
|
+
Builder: EIP712_BUILDER,
|
|
157
|
+
};
|
|
158
|
+
export const BUILDER_APPROVAL_EIP712_TYPES = {
|
|
159
|
+
BuilderApproval: [
|
|
160
|
+
{ name: 'paradexChain', type: 'string' },
|
|
161
|
+
{ name: 'environment', type: 'string' },
|
|
152
162
|
{ name: 'account', type: 'string' },
|
|
153
|
-
{ name: '
|
|
154
|
-
{ name: '
|
|
163
|
+
{ name: 'builder', type: 'Builder' },
|
|
164
|
+
{ name: 'subaccounts', type: 'string[]' },
|
|
165
|
+
{ name: 'nonce', type: 'string' },
|
|
166
|
+
{ name: 'issuedAt', type: 'uint64' },
|
|
155
167
|
],
|
|
168
|
+
Builder: EIP712_BUILDER,
|
|
156
169
|
};
|
|
157
170
|
export const PASSKEY_GRANT_EIP712_TYPES = {
|
|
158
171
|
PasskeyGrant: [
|
|
@@ -282,6 +295,21 @@ export const SESSION_MINT_SNIP12_TYPES = {
|
|
|
282
295
|
// ---------------------------------------------------------------------------
|
|
283
296
|
/** Starknet field prime. */
|
|
284
297
|
const FELT_PRIME = 2n ** 251n + 17n * 2n ** 192n + 1n;
|
|
298
|
+
/**
|
|
299
|
+
* A builder account in canonical `0x` form, refusing anything but a
|
|
300
|
+
* non-zero felt address. Orders and the Builder Codes calls share it.
|
|
301
|
+
*
|
|
302
|
+
* @internal
|
|
303
|
+
*/
|
|
304
|
+
export function builderAddress(value, name = 'builder') {
|
|
305
|
+
if (typeof value !== 'string' ||
|
|
306
|
+
!/^0x[0-9a-fA-F]{1,64}$/.test(value) ||
|
|
307
|
+
BigInt(value) === 0n ||
|
|
308
|
+
BigInt(value) >= FELT_PRIME) {
|
|
309
|
+
throw new Error(`${name} must be a non-zero 0x-prefixed hex address`);
|
|
310
|
+
}
|
|
311
|
+
return `0x${BigInt(value).toString(16)}`;
|
|
312
|
+
}
|
|
285
313
|
/** Upper bound (exclusive) of a Starknet contract address. */
|
|
286
314
|
const ADDRESS_BOUND = 2n ** 251n - 256n;
|
|
287
315
|
const NONCE_BOUND = 2n ** 128n;
|
|
@@ -449,18 +477,16 @@ function isNoCap(value) {
|
|
|
449
477
|
* non-empty list, or `["*"]` alone. A limit the server does not enforce
|
|
450
478
|
* must be `"none"` (`markets`: `["*"]`).
|
|
451
479
|
*
|
|
452
|
-
*
|
|
453
|
-
*
|
|
480
|
+
* Builder grants and builder passkeys follow the same rules as any other grant.
|
|
481
|
+
*
|
|
482
|
+
* @param _builderGrant ignored; kept so existing callers still compile.
|
|
454
483
|
*/
|
|
455
|
-
export function validateLimits(limits,
|
|
484
|
+
export function validateLimits(limits, _builderGrant, field = 'limits', options = {}) {
|
|
456
485
|
const caps = options.limitCaps ?? DEFAULT_LIMIT_CAPS;
|
|
457
486
|
const enforced = options.enforcedLimits ?? DEFAULT_ENFORCED_LIMITS;
|
|
458
487
|
if (limits == null || typeof limits !== 'object') {
|
|
459
488
|
throw invalid(field, 'is required');
|
|
460
489
|
}
|
|
461
|
-
if (builderGrant && !enforced.includes('maxLoss')) {
|
|
462
|
-
throw new SessionGrantError('BUILDER_LIMITS_REQUIRED', `${field}.maxLoss: builder grants need a loss cap, which the server does not enforce yet`);
|
|
463
|
-
}
|
|
464
490
|
for (const key of LIMIT_AMOUNTS) {
|
|
465
491
|
const value = limits[key];
|
|
466
492
|
if (value === '' || value == null) {
|
|
@@ -468,12 +494,7 @@ export function validateLimits(limits, builderGrant, field = 'limits', options =
|
|
|
468
494
|
}
|
|
469
495
|
if (typeof value !== 'string')
|
|
470
496
|
throw invalid(`${field}.${key}`, 'must be a string');
|
|
471
|
-
if (isNoCap(value)) {
|
|
472
|
-
if (key === 'maxLoss' && builderGrant) {
|
|
473
|
-
throw new SessionGrantError('BUILDER_LIMITS_REQUIRED', `${field}.maxLoss: builder grants must cap losses with a number`);
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
else {
|
|
497
|
+
if (!isNoCap(value)) {
|
|
477
498
|
requireDecimal(`${field}.${key}`, value, false);
|
|
478
499
|
if (new BigNumber(value).isZero()) {
|
|
479
500
|
throw invalid(`${field}.${key}`, 'must be positive');
|
|
@@ -587,11 +608,65 @@ export function validateSessionGrant(grant, options = {}) {
|
|
|
587
608
|
if (hasBuilder && builder.account === grant.account) {
|
|
588
609
|
throw invalid('builder.account', 'must not be the granting account');
|
|
589
610
|
}
|
|
611
|
+
if (hasBuilder)
|
|
612
|
+
requireBuilderFeeRate(builder.maxFeeRate);
|
|
590
613
|
if (builder.expiresAt > grant.expiresAt) {
|
|
591
614
|
throw invalid('builder.expiresAt', 'must not outlive the session');
|
|
592
615
|
}
|
|
616
|
+
if (builder.expiresAt !== 0 && builder.expiresAt <= grant.issuedAt) {
|
|
617
|
+
throw invalid('builder.expiresAt', 'must be after issuedAt');
|
|
618
|
+
}
|
|
593
619
|
validateLimits(grant.limits, hasBuilder, 'limits', options);
|
|
594
620
|
}
|
|
621
|
+
/** Longest a builder approval may live after its `issuedAt`. */
|
|
622
|
+
export const BUILDER_APPROVAL_TTL_MAX = 180 * DAY;
|
|
623
|
+
/** Most decimal places a builder's `maxFeeRate` may have. The server sets the highest rate it accepts. */
|
|
624
|
+
const BUILDER_FEE_RATE_PLACES = 8;
|
|
625
|
+
/**
|
|
626
|
+
* A builder's fee ceiling, as the server checks it on grants and approvals:
|
|
627
|
+
* above 0 and at most 8 decimal places. The server refuses a rate above its
|
|
628
|
+
* configured cap.
|
|
629
|
+
*/
|
|
630
|
+
function requireBuilderFeeRate(maxFeeRate) {
|
|
631
|
+
requireDecimal('builder.maxFeeRate', maxFeeRate, false);
|
|
632
|
+
const rate = new BigNumber(maxFeeRate);
|
|
633
|
+
if (rate.isZero()) {
|
|
634
|
+
throw invalid('builder.maxFeeRate', 'must be above 0');
|
|
635
|
+
}
|
|
636
|
+
if ((rate.decimalPlaces() ?? 0) > BUILDER_FEE_RATE_PLACES) {
|
|
637
|
+
throw invalid('builder.maxFeeRate', `must have at most ${BUILDER_FEE_RATE_PLACES} decimal places`);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Checks a builder approval against the server's rules: a builder other than
|
|
642
|
+
* the account, a `maxFeeRate` above 0 with at most 8 decimal places, and a
|
|
643
|
+
* required `expiresAt` at most
|
|
644
|
+
* {@link BUILDER_APPROVAL_TTL_MAX} after `issuedAt`. Throws a
|
|
645
|
+
* {@link SessionGrantError}.
|
|
646
|
+
*
|
|
647
|
+
* @experimental
|
|
648
|
+
*/
|
|
649
|
+
export function validateBuilderApproval(approval) {
|
|
650
|
+
validateAccountBinding(approval);
|
|
651
|
+
requireUniqueAddresses('subaccounts', approval.subaccounts, approval.account);
|
|
652
|
+
requireTimestamp('issuedAt', approval.issuedAt);
|
|
653
|
+
const builder = approval.builder;
|
|
654
|
+
if (builder == null || typeof builder !== 'object') {
|
|
655
|
+
throw invalid('builder', 'is required');
|
|
656
|
+
}
|
|
657
|
+
requireAddress('builder.account', builder.account);
|
|
658
|
+
if (builder.account === approval.account) {
|
|
659
|
+
throw invalid('builder.account', 'must not be the approving account');
|
|
660
|
+
}
|
|
661
|
+
requireBuilderFeeRate(builder.maxFeeRate);
|
|
662
|
+
requireTimestamp('builder.expiresAt', builder.expiresAt);
|
|
663
|
+
if (builder.expiresAt <= approval.issuedAt) {
|
|
664
|
+
throw invalid('builder.expiresAt', 'must be after issuedAt');
|
|
665
|
+
}
|
|
666
|
+
if (builder.expiresAt - approval.issuedAt > BUILDER_APPROVAL_TTL_MAX) {
|
|
667
|
+
throw new SessionGrantError('TTL_EXCEEDED', `builder.expiresAt: an approval lives at most ${BUILDER_APPROVAL_TTL_MAX}s after issuedAt`);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
595
670
|
export function validatePasskeyGrant(grant, options = {}) {
|
|
596
671
|
validateAccountBinding(grant);
|
|
597
672
|
requireAddress('builderAccount', grant.builderAccount, false);
|
|
@@ -688,9 +763,8 @@ function exceeds(message) {
|
|
|
688
763
|
* unless it allows `["*"]`. Unenforced limits are `"none"` on the mint and
|
|
689
764
|
* skipped, so passkeys registered with numeric limits keep working. A mint
|
|
690
765
|
* stating {@link CEILING_LIMITS} takes the ceiling's and fits by definition.
|
|
691
|
-
* A builder passkey's mints are checked like any other
|
|
692
|
-
*
|
|
693
|
-
* not list the passkey's account.
|
|
766
|
+
* A builder passkey's mints are checked like any other. Subaccounts must not
|
|
767
|
+
* list the passkey's account.
|
|
694
768
|
*
|
|
695
769
|
* The check holds only when `grant`'s passkey signs. With an empty
|
|
696
770
|
* `allowCredentials` the user may pick another passkey, on another account
|
|
@@ -846,6 +920,31 @@ export function createSessionGrant(params) {
|
|
|
846
920
|
});
|
|
847
921
|
return grant;
|
|
848
922
|
}
|
|
923
|
+
/**
|
|
924
|
+
* Builds a canonical, validated {@link BuilderApproval}.
|
|
925
|
+
*
|
|
926
|
+
* @experimental
|
|
927
|
+
*/
|
|
928
|
+
export function createBuilderApproval(params) {
|
|
929
|
+
const approval = {
|
|
930
|
+
paradexChain: params.paradexChain,
|
|
931
|
+
environment: params.environment,
|
|
932
|
+
account: canonicalFelt(params.account),
|
|
933
|
+
builder: {
|
|
934
|
+
account: canonicalFelt(params.builder.account),
|
|
935
|
+
maxFeeRate: params.builder.maxFeeRate,
|
|
936
|
+
expiresAt: params.builder.expiresAt ??
|
|
937
|
+
params.issuedAt + (params.ttlSeconds ?? BUILDER_APPROVAL_TTL_MAX),
|
|
938
|
+
},
|
|
939
|
+
subaccounts: (params.subaccounts ?? []).map((a) => canonicalFelt(a)),
|
|
940
|
+
nonce: params.nonce != null
|
|
941
|
+
? canonicalFelt(params.nonce)
|
|
942
|
+
: generateSessionNonce(),
|
|
943
|
+
issuedAt: params.issuedAt,
|
|
944
|
+
};
|
|
945
|
+
validateBuilderApproval(approval);
|
|
946
|
+
return approval;
|
|
947
|
+
}
|
|
849
948
|
/** Every account a grant reaches: the anchor first, then its sub-accounts. */
|
|
850
949
|
export function grantAccounts(grant) {
|
|
851
950
|
return [grant.account, ...grant.subaccounts];
|
|
@@ -971,6 +1070,17 @@ export function buildSessionMintSnip12(mint, options = {}) {
|
|
|
971
1070
|
validateSessionMint(mint, options);
|
|
972
1071
|
return snip12('SessionMint', SESSION_MINT_SNIP12_TYPES, mint, mint.paradexChain);
|
|
973
1072
|
}
|
|
1073
|
+
/**
|
|
1074
|
+
* EIP-712 `BuilderApproval`, signed by the account's EVM owner on the
|
|
1075
|
+
* wallet's current chain. There is no SNIP-12 form: the server accepts
|
|
1076
|
+
* builder approvals from EVM owners only.
|
|
1077
|
+
*
|
|
1078
|
+
* @experimental
|
|
1079
|
+
*/
|
|
1080
|
+
export function buildBuilderApprovalEip712(approval, signatureChainId) {
|
|
1081
|
+
validateBuilderApproval(approval);
|
|
1082
|
+
return eip712('BuilderApproval', BUILDER_APPROVAL_EIP712_TYPES, approval, signatureChainId);
|
|
1083
|
+
}
|
|
974
1084
|
/** EIP-712 digest (`0x1901 ‖ domain ‖ struct`) as 0x-prefixed 32-byte hex. */
|
|
975
1085
|
export function hashEip712(typedData) {
|
|
976
1086
|
return hashEip712TypedData(typedData);
|
package/dist/siwe.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Hex } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Sign-In with Ethereum (ERC-4361) messages, as Paradex's EVM owner login
|
|
4
|
+
* (`POST /v2/auth`) and onboarding (`POST /v2/onboarding`) take them.
|
|
5
|
+
*/
|
|
6
|
+
export declare const SIWE_AUTH_STATEMENT = "Paradex Auth";
|
|
7
|
+
export declare const SIWE_ONBOARDING_STATEMENT = "Paradex Onboarding";
|
|
8
|
+
/** The server refuses an auth message valid for longer than this. */
|
|
9
|
+
export declare const SIWE_AUTH_MAX_TTL = 300;
|
|
10
|
+
export interface SiweMessageParams {
|
|
11
|
+
/** The Paradex app host the server accepts, e.g. `app.paradex.trade`. */
|
|
12
|
+
readonly domain: string;
|
|
13
|
+
readonly address: string;
|
|
14
|
+
readonly statement: string;
|
|
15
|
+
readonly chainId: number;
|
|
16
|
+
readonly nonce: string;
|
|
17
|
+
/** Seconds since the epoch. */
|
|
18
|
+
readonly issuedAt: number;
|
|
19
|
+
/** Seconds since the epoch. */
|
|
20
|
+
readonly expirationTime?: number;
|
|
21
|
+
}
|
|
22
|
+
/** EIP-55 mixed-case checksum spelling of an address. */
|
|
23
|
+
export declare function checksumAddress(address: string): string;
|
|
24
|
+
/** A 32-hex-character nonce (the server needs at least 16 characters). */
|
|
25
|
+
export declare function siweNonce(): string;
|
|
26
|
+
/** Formats an ERC-4361 message. */
|
|
27
|
+
export declare function buildSiweMessage(params: SiweMessageParams): string;
|
|
28
|
+
/** Standard base64 of an ASCII message, as the SIWE headers carry it. */
|
|
29
|
+
export declare function base64Ascii(message: string): string;
|
|
30
|
+
/**
|
|
31
|
+
* The uncompressed public key (`0x04…`) that made `signature`, an EIP-191
|
|
32
|
+
* `personal_sign` over the UTF-8 text `message`. Throws unless it belongs to
|
|
33
|
+
* `address`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function recoverPersonalSignPublicKey(message: string, signature: string, address: string): Hex;
|
package/dist/siwe.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { secp256k1 } from '@noble/curves/secp256k1';
|
|
2
|
+
import { keccak_256 } from '@noble/hashes/sha3';
|
|
3
|
+
import { bytesToHex } from './wallet.js';
|
|
4
|
+
/**
|
|
5
|
+
* Sign-In with Ethereum (ERC-4361) messages, as Paradex's EVM owner login
|
|
6
|
+
* (`POST /v2/auth`) and onboarding (`POST /v2/onboarding`) take them.
|
|
7
|
+
*/
|
|
8
|
+
export const SIWE_AUTH_STATEMENT = 'Paradex Auth';
|
|
9
|
+
export const SIWE_ONBOARDING_STATEMENT = 'Paradex Onboarding';
|
|
10
|
+
/** The server refuses an auth message valid for longer than this. */
|
|
11
|
+
export const SIWE_AUTH_MAX_TTL = 300;
|
|
12
|
+
/** EIP-55 mixed-case checksum spelling of an address. */
|
|
13
|
+
export function checksumAddress(address) {
|
|
14
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
|
|
15
|
+
throw new Error('address must be a 0x-prefixed 20-byte address');
|
|
16
|
+
}
|
|
17
|
+
const lower = address.slice(2).toLowerCase();
|
|
18
|
+
const hash = bytesToHex(keccak_256(new TextEncoder().encode(lower))).slice(2);
|
|
19
|
+
let out = '0x';
|
|
20
|
+
for (let i = 0; i < lower.length; i++) {
|
|
21
|
+
const c = lower.charAt(i);
|
|
22
|
+
out += parseInt(hash.charAt(i), 16) >= 8 ? c.toUpperCase() : c;
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
/** A 32-hex-character nonce (the server needs at least 16 characters). */
|
|
27
|
+
export function siweNonce() {
|
|
28
|
+
const bytes = new Uint8Array(16);
|
|
29
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
30
|
+
return bytesToHex(bytes).slice(2);
|
|
31
|
+
}
|
|
32
|
+
function isoSeconds(seconds) {
|
|
33
|
+
return new Date(seconds * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
34
|
+
}
|
|
35
|
+
/** Formats an ERC-4361 message. */
|
|
36
|
+
export function buildSiweMessage(params) {
|
|
37
|
+
if (!/^[A-Za-z0-9.-]+(:\d+)?$/.test(params.domain)) {
|
|
38
|
+
throw new Error('domain must be a host name');
|
|
39
|
+
}
|
|
40
|
+
if (!/^[A-Za-z0-9]{8,}$/.test(params.nonce)) {
|
|
41
|
+
throw new Error('nonce must be at least 8 alphanumeric characters');
|
|
42
|
+
}
|
|
43
|
+
const lines = [
|
|
44
|
+
`${params.domain} wants you to sign in with your Ethereum account:`,
|
|
45
|
+
checksumAddress(params.address),
|
|
46
|
+
'',
|
|
47
|
+
params.statement,
|
|
48
|
+
'',
|
|
49
|
+
`URI: https://${params.domain}`,
|
|
50
|
+
'Version: 1',
|
|
51
|
+
`Chain ID: ${params.chainId}`,
|
|
52
|
+
`Nonce: ${params.nonce}`,
|
|
53
|
+
`Issued At: ${isoSeconds(params.issuedAt)}`,
|
|
54
|
+
];
|
|
55
|
+
if (params.expirationTime != null) {
|
|
56
|
+
lines.push(`Expiration Time: ${isoSeconds(params.expirationTime)}`);
|
|
57
|
+
}
|
|
58
|
+
return lines.join('\n');
|
|
59
|
+
}
|
|
60
|
+
/** Standard base64 of an ASCII message, as the SIWE headers carry it. */
|
|
61
|
+
export function base64Ascii(message) {
|
|
62
|
+
if (!/^[\x20-\x7e\n]*$/.test(message)) {
|
|
63
|
+
throw new Error('SIWE message must be printable ASCII');
|
|
64
|
+
}
|
|
65
|
+
return btoa(message);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The uncompressed public key (`0x04…`) that made `signature`, an EIP-191
|
|
69
|
+
* `personal_sign` over the UTF-8 text `message`. Throws unless it belongs to
|
|
70
|
+
* `address`.
|
|
71
|
+
*/
|
|
72
|
+
export function recoverPersonalSignPublicKey(message, signature, address) {
|
|
73
|
+
const sig = signature.replace(/^0x/, '');
|
|
74
|
+
if (!/^[0-9a-fA-F]{130}$/.test(sig)) {
|
|
75
|
+
throw new Error('Wallet signature must be a 65-byte EOA signature; contract wallets are not supported');
|
|
76
|
+
}
|
|
77
|
+
const v = parseInt(sig.slice(128, 130), 16);
|
|
78
|
+
const recovery = v >= 27 ? v - 27 : v;
|
|
79
|
+
if (recovery !== 0 && recovery !== 1) {
|
|
80
|
+
throw new Error(`Wallet signature has an invalid v: ${v}`);
|
|
81
|
+
}
|
|
82
|
+
const bytes = new TextEncoder().encode(message);
|
|
83
|
+
const prefix = new TextEncoder().encode(`\x19Ethereum Signed Message:\n${bytes.length}`);
|
|
84
|
+
const digest = keccak_256(new Uint8Array([...prefix, ...bytes]));
|
|
85
|
+
const publicKey = new secp256k1.Signature(BigInt(`0x${sig.slice(0, 64)}`), BigInt(`0x${sig.slice(64, 128)}`))
|
|
86
|
+
.addRecoveryBit(recovery)
|
|
87
|
+
.recoverPublicKey(digest)
|
|
88
|
+
.toRawBytes(false);
|
|
89
|
+
const recovered = bytesToHex(keccak_256(publicKey.slice(1)).slice(-20));
|
|
90
|
+
if (recovered.toLowerCase() !== address.toLowerCase()) {
|
|
91
|
+
throw new Error(`Wallet signature recovers to ${recovered}, not the wallet ${address}`);
|
|
92
|
+
}
|
|
93
|
+
return bytesToHex(publicKey);
|
|
94
|
+
}
|