@paradex/sdk 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1035 @@
1
+ import { hexToBytes } from '@noble/hashes/utils';
2
+ import BigNumber from 'bignumber.js';
3
+ import * as Starknet from 'starknet';
4
+ import { hashTypedData as hashEip712TypedData, } from './eip712.js';
5
+ /*
6
+ * Typed data for session grants: `SessionGrant`, `PasskeyGrant` and
7
+ * `SessionMint`, in EIP-712 (EVM owners) and SNIP-12 revision 1 (Stark
8
+ * owners) encodings with the same field names and order.
9
+ *
10
+ * @experimental The server side of sessions is not released yet. Field
11
+ * shapes may still change.
12
+ */
13
+ export const SESSION_DOMAIN_NAME = 'Paradex Session';
14
+ export const SESSION_DOMAIN_VERSION = '1';
15
+ /** The "none" builder / first-party passkey sentinel. */
16
+ export const NO_BUILDER = '0x0';
17
+ const ENVIRONMENT_RE = /^[a-z][a-z0-9-]{0,30}$/;
18
+ export const GRANTABLE_SCOPES = [
19
+ 'trade',
20
+ 'trade:rfq',
21
+ 'trade:block',
22
+ 'account:settings',
23
+ ];
24
+ /** Scopes that exist in the format but are refused. */
25
+ export const RESERVED_SCOPES = [
26
+ 'withdraw:owner',
27
+ 'trade:isolated',
28
+ ];
29
+ const DAY = 24 * 60 * 60;
30
+ /** Server caps on session lifetime, in seconds. */
31
+ export const SESSION_TTL = {
32
+ browserDefault: 7 * DAY,
33
+ browserMax: 30 * DAY,
34
+ /**
35
+ * Cap for IP-pinned API sessions. `POST /v2/sessions` applies
36
+ * `browserMax` to every grant, so `SessionConnector` never uses this.
37
+ */
38
+ apiMax: 180 * DAY,
39
+ /** Cap for grants that include `trade:block` or `account:settings`. */
40
+ sensitiveScopeMax: 7 * DAY,
41
+ passkeyMax: 180 * DAY,
42
+ passkeySessionMax: 7 * DAY,
43
+ };
44
+ const SENSITIVE_SCOPES = [
45
+ 'trade:block',
46
+ 'account:settings',
47
+ ];
48
+ export const MAX_PASSKEY_CONCURRENT_SESSIONS = 5;
49
+ /** `issuedAt` may be at most this far ahead of the server clock. */
50
+ const MAX_ISSUED_AT_SKEW = 5 * 60;
51
+ /** Labels are printable ASCII of at most this many characters. */
52
+ const MAX_LABEL_LENGTH = 64;
53
+ const LABEL_RE = /^[\x20-\x7e]*$/;
54
+ /** Scopes the ceiling of a first-party (Paradex app) passkey may carry. */
55
+ const FIRST_PARTY_PASSKEY_CEILING_SCOPES = [
56
+ 'trade',
57
+ 'trade:rfq',
58
+ 'account:settings',
59
+ ];
60
+ /** The only scope the ceiling of a builder passkey may carry. */
61
+ const BUILDER_PASSKEY_CEILING_SCOPES = ['trade'];
62
+ /** A grant, mint or passkey ceiling lists at most this many subaccounts. */
63
+ export const MAX_GRANT_SUBACCOUNTS = 32;
64
+ export class SessionGrantError extends Error {
65
+ constructor(code, message) {
66
+ super(message);
67
+ this.name = 'SessionGrantError';
68
+ this.code = code;
69
+ }
70
+ }
71
+ /** A limit value meaning "not capped by this grant". */
72
+ export const NO_CAP = 'none';
73
+ /** `markets` value meaning every permitted market. */
74
+ export const ALL_MARKETS = ['*'];
75
+ const LIMIT_AMOUNTS = [
76
+ 'maxOrderNotional',
77
+ 'maxOpenNotional',
78
+ 'dailyNotional',
79
+ 'maxLoss',
80
+ 'maxLeverage',
81
+ ];
82
+ /** No client-side caps by default; the server applies its own. */
83
+ export const DEFAULT_LIMIT_CAPS = {};
84
+ /**
85
+ * Limits the server enforces. Defaults to none: until the server enforces a
86
+ * limit, a grant may not set it, because nothing would hold orders to it.
87
+ */
88
+ export const DEFAULT_ENFORCED_LIMITS = [];
89
+ /** Every limit set, for limits a client knows the server enforces. */
90
+ export const ALL_LIMITS = [...LIMIT_AMOUNTS, 'markets'];
91
+ /** Every limit uncapped: what a grant must state while none is enforced. */
92
+ export const UNCAPPED_LIMITS = {
93
+ maxOrderNotional: NO_CAP,
94
+ maxOpenNotional: NO_CAP,
95
+ dailyNotional: NO_CAP,
96
+ maxLoss: NO_CAP,
97
+ maxLeverage: NO_CAP,
98
+ markets: ALL_MARKETS,
99
+ };
100
+ /** The account a `SessionMint`'s SNIP-12 message hash is taken for: a mint names no account. */
101
+ export const MINT_HASH_ACCOUNT = '0x0';
102
+ /** A `SessionMint` `expiresAt` asking for the longest session the passkey allows. */
103
+ export const LONGEST_SESSION = 0;
104
+ /**
105
+ * The limits a `SessionMint` states to take its passkey's ceiling: every
106
+ * amount empty and no markets.
107
+ */
108
+ export const CEILING_LIMITS = {
109
+ maxOrderNotional: '',
110
+ maxOpenNotional: '',
111
+ dailyNotional: '',
112
+ maxLoss: '',
113
+ maxLeverage: '',
114
+ markets: [],
115
+ };
116
+ /** Whether `limits` are {@link CEILING_LIMITS}: no limit stated at all. */
117
+ export function isCeilingLimits(limits) {
118
+ return (limits != null &&
119
+ typeof limits === 'object' &&
120
+ LIMIT_AMOUNTS.every((key) => limits[key] === '') &&
121
+ Array.isArray(limits.markets) &&
122
+ limits.markets.length === 0);
123
+ }
124
+ // ---------------------------------------------------------------------------
125
+ // Type definitions
126
+ // ---------------------------------------------------------------------------
127
+ const EIP712_LIMITS = [
128
+ { name: 'maxOrderNotional', type: 'string' },
129
+ { name: 'maxOpenNotional', type: 'string' },
130
+ { name: 'dailyNotional', type: 'string' },
131
+ { name: 'maxLoss', type: 'string' },
132
+ { name: 'maxLeverage', type: 'string' },
133
+ { name: 'markets', type: 'string[]' },
134
+ ];
135
+ export const SESSION_GRANT_EIP712_TYPES = {
136
+ SessionGrant: [
137
+ { name: 'paradexChain', type: 'string' },
138
+ { name: 'environment', type: 'string' },
139
+ { name: 'account', type: 'string' },
140
+ { name: 'sessionKey', type: 'string' },
141
+ { name: 'label', type: 'string' },
142
+ { name: 'scopes', type: 'string[]' },
143
+ { name: 'limits', type: 'Limits' },
144
+ { name: 'builder', type: 'Builder' },
145
+ { name: 'subaccounts', type: 'string[]' },
146
+ { name: 'nonce', type: 'string' },
147
+ { name: 'issuedAt', type: 'uint64' },
148
+ { name: 'expiresAt', type: 'uint64' },
149
+ ],
150
+ Limits: EIP712_LIMITS,
151
+ Builder: [
152
+ { name: 'account', type: 'string' },
153
+ { name: 'maxFeeRate', type: 'string' },
154
+ { name: 'expiresAt', type: 'uint64' },
155
+ ],
156
+ };
157
+ export const PASSKEY_GRANT_EIP712_TYPES = {
158
+ PasskeyGrant: [
159
+ { name: 'paradexChain', type: 'string' },
160
+ { name: 'environment', type: 'string' },
161
+ { name: 'account', type: 'string' },
162
+ { name: 'passkey', type: 'Passkey' },
163
+ { name: 'ceiling', type: 'Ceiling' },
164
+ { name: 'builderAccount', type: 'string' },
165
+ { name: 'nonce', type: 'string' },
166
+ { name: 'issuedAt', type: 'uint64' },
167
+ { name: 'expiresAt', type: 'uint64' },
168
+ ],
169
+ Passkey: [
170
+ { name: 'credentialId', type: 'string' },
171
+ { name: 'pubkeyX', type: 'string' },
172
+ { name: 'pubkeyY', type: 'string' },
173
+ { name: 'rpId', type: 'string' },
174
+ { name: 'label', type: 'string' },
175
+ ],
176
+ Ceiling: [
177
+ { name: 'scopes', type: 'string[]' },
178
+ { name: 'limits', type: 'Limits' },
179
+ { name: 'subaccounts', type: 'string[]' },
180
+ { name: 'includeFutureSubaccounts', type: 'bool' },
181
+ { name: 'maxSessionTtl', type: 'uint64' },
182
+ { name: 'maxConcurrentSessions', type: 'uint64' },
183
+ ],
184
+ Limits: EIP712_LIMITS,
185
+ };
186
+ export const SESSION_MINT_EIP712_TYPES = {
187
+ SessionMint: [
188
+ { name: 'paradexChain', type: 'string' },
189
+ { name: 'environment', type: 'string' },
190
+ { name: 'sessionKey', type: 'string' },
191
+ { name: 'scopes', type: 'string[]' },
192
+ { name: 'limits', type: 'Limits' },
193
+ { name: 'subaccounts', type: 'string[]' },
194
+ { name: 'nonce', type: 'string' },
195
+ { name: 'expiresAt', type: 'uint64' },
196
+ ],
197
+ Limits: EIP712_LIMITS,
198
+ };
199
+ const SNIP12_DOMAIN = [
200
+ { name: 'name', type: 'shortstring' },
201
+ { name: 'version', type: 'shortstring' },
202
+ { name: 'chainId', type: 'shortstring' },
203
+ { name: 'revision', type: 'shortstring' },
204
+ ];
205
+ const SNIP12_LIMITS = [
206
+ { name: 'maxOrderNotional', type: 'string' },
207
+ { name: 'maxOpenNotional', type: 'string' },
208
+ { name: 'dailyNotional', type: 'string' },
209
+ { name: 'maxLoss', type: 'string' },
210
+ { name: 'maxLeverage', type: 'string' },
211
+ { name: 'markets', type: 'shortstring*' },
212
+ ];
213
+ export const SESSION_GRANT_SNIP12_TYPES = {
214
+ StarknetDomain: SNIP12_DOMAIN,
215
+ SessionGrant: [
216
+ { name: 'paradexChain', type: 'shortstring' },
217
+ { name: 'environment', type: 'shortstring' },
218
+ { name: 'account', type: 'ContractAddress' },
219
+ { name: 'sessionKey', type: 'felt' },
220
+ { name: 'label', type: 'string' },
221
+ { name: 'scopes', type: 'shortstring*' },
222
+ { name: 'limits', type: 'Limits' },
223
+ { name: 'builder', type: 'Builder' },
224
+ { name: 'subaccounts', type: 'ContractAddress*' },
225
+ { name: 'nonce', type: 'felt' },
226
+ { name: 'issuedAt', type: 'timestamp' },
227
+ { name: 'expiresAt', type: 'timestamp' },
228
+ ],
229
+ Limits: SNIP12_LIMITS,
230
+ Builder: [
231
+ { name: 'account', type: 'ContractAddress' },
232
+ { name: 'maxFeeRate', type: 'string' },
233
+ { name: 'expiresAt', type: 'timestamp' },
234
+ ],
235
+ };
236
+ export const PASSKEY_GRANT_SNIP12_TYPES = {
237
+ StarknetDomain: SNIP12_DOMAIN,
238
+ PasskeyGrant: [
239
+ { name: 'paradexChain', type: 'shortstring' },
240
+ { name: 'environment', type: 'shortstring' },
241
+ { name: 'account', type: 'ContractAddress' },
242
+ { name: 'passkey', type: 'Passkey' },
243
+ { name: 'ceiling', type: 'Ceiling' },
244
+ { name: 'builderAccount', type: 'ContractAddress' },
245
+ { name: 'nonce', type: 'felt' },
246
+ { name: 'issuedAt', type: 'timestamp' },
247
+ { name: 'expiresAt', type: 'timestamp' },
248
+ ],
249
+ Passkey: [
250
+ { name: 'credentialId', type: 'string' },
251
+ { name: 'pubkeyX', type: 'string' },
252
+ { name: 'pubkeyY', type: 'string' },
253
+ { name: 'rpId', type: 'string' },
254
+ { name: 'label', type: 'string' },
255
+ ],
256
+ Ceiling: [
257
+ { name: 'scopes', type: 'shortstring*' },
258
+ { name: 'limits', type: 'Limits' },
259
+ { name: 'subaccounts', type: 'ContractAddress*' },
260
+ { name: 'includeFutureSubaccounts', type: 'bool' },
261
+ { name: 'maxSessionTtl', type: 'u128' },
262
+ { name: 'maxConcurrentSessions', type: 'u128' },
263
+ ],
264
+ Limits: SNIP12_LIMITS,
265
+ };
266
+ export const SESSION_MINT_SNIP12_TYPES = {
267
+ StarknetDomain: SNIP12_DOMAIN,
268
+ SessionMint: [
269
+ { name: 'paradexChain', type: 'shortstring' },
270
+ { name: 'environment', type: 'shortstring' },
271
+ { name: 'sessionKey', type: 'felt' },
272
+ { name: 'scopes', type: 'shortstring*' },
273
+ { name: 'limits', type: 'Limits' },
274
+ { name: 'subaccounts', type: 'ContractAddress*' },
275
+ { name: 'nonce', type: 'felt' },
276
+ { name: 'expiresAt', type: 'timestamp' },
277
+ ],
278
+ Limits: SNIP12_LIMITS,
279
+ };
280
+ // ---------------------------------------------------------------------------
281
+ // Canonical field forms
282
+ // ---------------------------------------------------------------------------
283
+ /** Starknet field prime. */
284
+ const FELT_PRIME = 2n ** 251n + 17n * 2n ** 192n + 1n;
285
+ /** Upper bound (exclusive) of a Starknet contract address. */
286
+ const ADDRESS_BOUND = 2n ** 251n - 256n;
287
+ const NONCE_BOUND = 2n ** 128n;
288
+ const UINT64_BOUND = 2n ** 64n;
289
+ const DECIMAL_RE = /^(0|[1-9][0-9]*)(\.[0-9]*[1-9])?$/;
290
+ const MARKET_CHARS_RE = /^[A-Za-z0-9_*-]+$/;
291
+ /**
292
+ * Market symbols and patterns, e.g. `BTC-USD-PERP`, `kPEPE-USD-PERP`,
293
+ * `NEAR-USD-27NOV26-5_4-C`, `*-USD-PERP`. `"*"` alone (every market) is
294
+ * handled by the caller.
295
+ */
296
+ function isMarket(value) {
297
+ if (!MARKET_CHARS_RE.test(value))
298
+ return false;
299
+ // Needs a letter, "*" or "-": a bare number is not a market.
300
+ if (!/[A-Za-z*-]/.test(value))
301
+ return false;
302
+ if (value.startsWith('-'))
303
+ return false;
304
+ // `0x…`, `0b…` and `0o…` parse as numbers in SNIP-12 encoders, so two
305
+ // different markets could share a hash.
306
+ if (/^0[xbo]/i.test(value))
307
+ return false;
308
+ if (value.includes('*')) {
309
+ // A pattern needs something to match on, and "**" adds nothing.
310
+ if (!/[A-Za-z0-9]/.test(value) || value.includes('**'))
311
+ return false;
312
+ }
313
+ return true;
314
+ }
315
+ /** Whether a ceiling market entry covers a mint's market entry. */
316
+ export function marketCovers(pattern, market) {
317
+ if (pattern === '*')
318
+ return true;
319
+ // A pattern is covered only by the same pattern (or `["*"]`), as the
320
+ // server checks it.
321
+ if (!pattern.includes('*') || market.includes('*')) {
322
+ return pattern === market;
323
+ }
324
+ const source = pattern
325
+ .split('*')
326
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
327
+ .join('.*');
328
+ return new RegExp(`^${source}$`).test(market);
329
+ }
330
+ const P256_COORD_RE = /^0x[0-9a-f]{64}$/;
331
+ const BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
332
+ const SHORT_STRING_MAX = 31;
333
+ function invalid(field, reason) {
334
+ return new SessionGrantError('INVALID_FIELD', `${field}: ${reason}`);
335
+ }
336
+ function parseHexFelt(field, value, bound) {
337
+ if (typeof value !== 'string' || !/^0x[0-9a-fA-F]+$/.test(value)) {
338
+ throw invalid(field, 'must be 0x-prefixed hex');
339
+ }
340
+ const n = BigInt(value);
341
+ if (n >= bound)
342
+ throw invalid(field, 'out of range');
343
+ return n;
344
+ }
345
+ /**
346
+ * Canonical hex for felts and addresses: lowercase, `0x`-prefixed, no leading
347
+ * zeros (`0x0` for zero). EIP-712 hashes these as strings, so the form is part
348
+ * of the signed bytes; every builder normalizes to it and validation rejects
349
+ * anything else.
350
+ */
351
+ export function canonicalFelt(value) {
352
+ const n = typeof value === 'bigint' ? value : BigInt(value);
353
+ if (n < 0n || n >= FELT_PRIME)
354
+ throw invalid('felt', 'out of range');
355
+ return `0x${n.toString(16)}`;
356
+ }
357
+ function requireCanonicalHex(field, value, bound) {
358
+ const n = parseHexFelt(field, value, bound);
359
+ if (value !== `0x${n.toString(16)}`) {
360
+ throw invalid(field, 'must be lowercase hex without leading zeros');
361
+ }
362
+ }
363
+ function requireAddress(field, value, nonZero = true) {
364
+ requireCanonicalHex(field, value, ADDRESS_BOUND);
365
+ if (nonZero && value === '0x0')
366
+ throw invalid(field, 'must not be zero');
367
+ }
368
+ function requireTimestamp(field, value) {
369
+ if (typeof value !== 'number' ||
370
+ !Number.isSafeInteger(value) ||
371
+ value < 0 ||
372
+ BigInt(value) >= UINT64_BOUND) {
373
+ throw invalid(field, 'must be a non-negative integer of seconds');
374
+ }
375
+ }
376
+ function requireShortString(field, value) {
377
+ if (typeof value !== 'string' ||
378
+ value.length === 0 ||
379
+ value.length > SHORT_STRING_MAX ||
380
+ !/^[\x20-\x7e]+$/.test(value)) {
381
+ throw invalid(field, `must be 1-${SHORT_STRING_MAX} printable ASCII chars`);
382
+ }
383
+ }
384
+ function requireDecimal(field, value, allowEmpty) {
385
+ if (typeof value !== 'string')
386
+ throw invalid(field, 'must be a string');
387
+ if (value === '' && allowEmpty)
388
+ return;
389
+ if (!DECIMAL_RE.test(value)) {
390
+ throw invalid(field, 'must be a canonical decimal string like "25000"');
391
+ }
392
+ }
393
+ function requireEnvironment(value) {
394
+ if (value === 'prod') {
395
+ // `Config.fetch` names it "prod"; sessions sign the environment name.
396
+ throw invalid('environment', 'use "mainnet", not "prod"');
397
+ }
398
+ if (typeof value !== 'string' || !ENVIRONMENT_RE.test(value)) {
399
+ throw invalid('environment', 'must be an environment name like "mainnet"');
400
+ }
401
+ }
402
+ function requireNonce(field, value) {
403
+ requireCanonicalHex(field, value, NONCE_BOUND);
404
+ if (value === '0x0')
405
+ throw invalid(field, 'must not be zero');
406
+ }
407
+ function requireUniqueAddresses(field, values, anchor) {
408
+ if (!Array.isArray(values))
409
+ throw invalid(field, 'must be an array');
410
+ if (values.length > MAX_GRANT_SUBACCOUNTS) {
411
+ throw invalid(field, `lists more than ${MAX_GRANT_SUBACCOUNTS} accounts`);
412
+ }
413
+ const seen = new Set();
414
+ values.forEach((v, i) => {
415
+ requireAddress(`${field}[${i}]`, v);
416
+ if (anchor != null && v === anchor) {
417
+ throw invalid(field, 'must not include the account');
418
+ }
419
+ if (seen.has(v))
420
+ throw invalid(field, 'has duplicates');
421
+ seen.add(v);
422
+ });
423
+ }
424
+ /** Rejects unknown and reserved scopes, duplicates and an empty list. */
425
+ export function validateScopes(scopes, field = 'scopes') {
426
+ if (!Array.isArray(scopes) || scopes.length === 0) {
427
+ throw invalid(field, 'must list at least one scope');
428
+ }
429
+ const seen = new Set();
430
+ for (const scope of scopes) {
431
+ if (typeof scope !== 'string')
432
+ throw invalid(field, 'must be strings');
433
+ if (RESERVED_SCOPES.includes(scope)) {
434
+ throw new SessionGrantError('RESERVED_SCOPE', `${field}: "${scope}" is reserved and cannot be granted`);
435
+ }
436
+ if (!GRANTABLE_SCOPES.includes(scope)) {
437
+ throw new SessionGrantError('UNKNOWN_SCOPE', `${field}: unknown scope "${scope}"`);
438
+ }
439
+ if (seen.has(scope))
440
+ throw invalid(field, `duplicate scope "${scope}"`);
441
+ seen.add(scope);
442
+ }
443
+ }
444
+ function isNoCap(value) {
445
+ return value === NO_CAP;
446
+ }
447
+ /**
448
+ * Every amount must be a positive decimal or `"none"`; `markets` must be a
449
+ * non-empty list, or `["*"]` alone. A limit the server does not enforce
450
+ * must be `"none"` (`markets`: `["*"]`).
451
+ *
452
+ * @param builderGrant builder grants must cap `maxLoss` with a number, so
453
+ * they are refused while the server does not enforce `maxLoss`.
454
+ */
455
+ export function validateLimits(limits, builderGrant, field = 'limits', options = {}) {
456
+ const caps = options.limitCaps ?? DEFAULT_LIMIT_CAPS;
457
+ const enforced = options.enforcedLimits ?? DEFAULT_ENFORCED_LIMITS;
458
+ if (limits == null || typeof limits !== 'object') {
459
+ throw invalid(field, 'is required');
460
+ }
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
+ for (const key of LIMIT_AMOUNTS) {
465
+ const value = limits[key];
466
+ if (value === '' || value == null) {
467
+ throw invalid(`${field}.${key}`, `must be stated: a positive decimal or "${NO_CAP}"`);
468
+ }
469
+ if (typeof value !== 'string')
470
+ 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 {
477
+ requireDecimal(`${field}.${key}`, value, false);
478
+ if (new BigNumber(value).isZero()) {
479
+ throw invalid(`${field}.${key}`, 'must be positive');
480
+ }
481
+ }
482
+ if (!enforced.includes(key) && !isNoCap(value)) {
483
+ throw new SessionGrantError('LIMIT_INVALID', `${field}.${key}: not enforced by the server yet, so it must be "${NO_CAP}"`);
484
+ }
485
+ const cap = caps[key];
486
+ if (cap != null && !enforced.includes(key)) {
487
+ throw new SessionGrantError('LIMIT_INVALID', `${field}.${key}: has a ${cap} cap, but the server does not enforce this limit, so no value can meet it`);
488
+ }
489
+ if (cap != null &&
490
+ (isNoCap(value) || new BigNumber(value).isGreaterThan(cap))) {
491
+ throw new SessionGrantError('LIMIT_INVALID', `${field}.${key}: ${value} is above the ${cap} cap`);
492
+ }
493
+ }
494
+ if (!Array.isArray(limits.markets) || limits.markets.length === 0) {
495
+ throw invalid(`${field}.markets`, 'must list markets, or ["*"] for every permitted market');
496
+ }
497
+ if (limits.markets.includes('*') && limits.markets.length > 1) {
498
+ throw invalid(`${field}.markets`, '"*" must be the only entry');
499
+ }
500
+ if (!enforced.includes('markets') && limits.markets[0] !== '*') {
501
+ throw new SessionGrantError('LIMIT_INVALID', `${field}.markets: not enforced by the server yet, so it must be ["*"]`);
502
+ }
503
+ const seen = new Set();
504
+ limits.markets.forEach((market, i) => {
505
+ if (typeof market !== 'string' || (market !== '*' && !isMarket(market))) {
506
+ throw invalid(`${field}.markets[${i}]`, 'is not a market symbol');
507
+ }
508
+ requireShortString(`${field}.markets[${i}]`, market);
509
+ if (seen.has(market))
510
+ throw invalid(`${field}.markets`, 'has duplicates');
511
+ seen.add(market);
512
+ });
513
+ }
514
+ function validateBinding(value) {
515
+ requireShortString('paradexChain', value.paradexChain);
516
+ requireEnvironment(value.environment);
517
+ requireNonce('nonce', value.nonce);
518
+ }
519
+ function validateAccountBinding(value) {
520
+ validateBinding(value);
521
+ requireAddress('account', value.account);
522
+ }
523
+ function requireLabel(field, value) {
524
+ if (typeof value !== 'string')
525
+ throw invalid(field, 'is required');
526
+ if (value.length > MAX_LABEL_LENGTH || !LABEL_RE.test(value)) {
527
+ throw invalid(field, `must be printable ASCII of at most ${MAX_LABEL_LENGTH} characters`);
528
+ }
529
+ }
530
+ /**
531
+ * Longest lifetime a grant with these scopes can request. The server measures
532
+ * the lifetime from the earlier of `issuedAt` and its own clock, and accepts
533
+ * an `issuedAt` up to 5 minutes ahead of it, so this is the server's cap less
534
+ * that allowance: a grant at this length still passes when the client's clock
535
+ * runs ahead.
536
+ */
537
+ export function maxSessionTtl(scopes, sessionType = 'browser', clockSkewSeconds = MAX_ISSUED_AT_SKEW) {
538
+ let cap;
539
+ if (scopes.some((s) => SENSITIVE_SCOPES.includes(s))) {
540
+ cap = SESSION_TTL.sensitiveScopeMax;
541
+ }
542
+ else {
543
+ cap = sessionType === 'api' ? SESSION_TTL.apiMax : SESSION_TTL.browserMax;
544
+ }
545
+ return cap - clockSkewSeconds;
546
+ }
547
+ /**
548
+ * Checks a grant against the format rules and server caps. Throws a
549
+ * {@link SessionGrantError}. The server repeats every check; this one fails
550
+ * before the owner is asked to sign.
551
+ */
552
+ export function validateSessionGrant(grant, options = {}) {
553
+ validateAccountBinding(grant);
554
+ requireCanonicalHex('sessionKey', grant.sessionKey, FELT_PRIME);
555
+ if (grant.sessionKey === '0x0')
556
+ throw invalid('sessionKey', 'is zero');
557
+ requireLabel('label', grant.label);
558
+ validateScopes(grant.scopes);
559
+ requireUniqueAddresses('subaccounts', grant.subaccounts, grant.account);
560
+ requireTimestamp('issuedAt', grant.issuedAt);
561
+ requireTimestamp('expiresAt', grant.expiresAt);
562
+ if (grant.expiresAt <= grant.issuedAt) {
563
+ throw invalid('expiresAt', 'must be after issuedAt');
564
+ }
565
+ const ttl = grant.expiresAt - grant.issuedAt;
566
+ const cap = maxSessionTtl(grant.scopes, options.sessionType, options.clockSkewSeconds);
567
+ if (ttl > cap) {
568
+ throw new SessionGrantError('TTL_EXCEEDED', `expiresAt: lifetime ${ttl}s exceeds the ${cap}s limit for these scopes (the server cap less the clock-skew allowance)`);
569
+ }
570
+ const builder = grant.builder;
571
+ if (builder == null || typeof builder !== 'object') {
572
+ throw invalid('builder', 'is required');
573
+ }
574
+ requireAddress('builder.account', builder.account, false);
575
+ requireDecimal('builder.maxFeeRate', builder.maxFeeRate, false);
576
+ requireTimestamp('builder.expiresAt', builder.expiresAt);
577
+ const hasBuilder = builder.account !== NO_BUILDER;
578
+ if (hasBuilder) {
579
+ const firstPartyOnly = grant.scopes.find((s) => SENSITIVE_SCOPES.includes(s));
580
+ if (firstPartyOnly != null) {
581
+ throw new SessionGrantError('SCOPE_NOT_ALLOWED', `scopes: "${firstPartyOnly}" cannot be granted to a builder`);
582
+ }
583
+ }
584
+ if (!hasBuilder && (builder.maxFeeRate !== '0' || builder.expiresAt !== 0)) {
585
+ throw invalid('builder', 'no builder must have maxFeeRate "0" and 0');
586
+ }
587
+ if (hasBuilder && builder.account === grant.account) {
588
+ throw invalid('builder.account', 'must not be the granting account');
589
+ }
590
+ if (builder.expiresAt > grant.expiresAt) {
591
+ throw invalid('builder.expiresAt', 'must not outlive the session');
592
+ }
593
+ validateLimits(grant.limits, hasBuilder, 'limits', options);
594
+ }
595
+ export function validatePasskeyGrant(grant, options = {}) {
596
+ validateAccountBinding(grant);
597
+ requireAddress('builderAccount', grant.builderAccount, false);
598
+ requireTimestamp('issuedAt', grant.issuedAt);
599
+ requireTimestamp('expiresAt', grant.expiresAt);
600
+ if (grant.expiresAt <= grant.issuedAt) {
601
+ throw invalid('expiresAt', 'must be after issuedAt');
602
+ }
603
+ if (grant.expiresAt - grant.issuedAt > SESSION_TTL.passkeyMax) {
604
+ throw new SessionGrantError('TTL_EXCEEDED', `expiresAt: passkey grants last at most ${SESSION_TTL.passkeyMax}s`);
605
+ }
606
+ const passkey = grant.passkey;
607
+ if (passkey == null || typeof passkey !== 'object') {
608
+ throw invalid('passkey', 'is required');
609
+ }
610
+ if (!BASE64URL_RE.test(passkey.credentialId)) {
611
+ throw invalid('passkey.credentialId', 'must be base64url');
612
+ }
613
+ if (!P256_COORD_RE.test(passkey.pubkeyX)) {
614
+ throw invalid('passkey.pubkeyX', 'must be 0x + 64 lowercase hex');
615
+ }
616
+ if (!P256_COORD_RE.test(passkey.pubkeyY)) {
617
+ throw invalid('passkey.pubkeyY', 'must be 0x + 64 lowercase hex');
618
+ }
619
+ if (typeof passkey.rpId !== 'string' || passkey.rpId === '') {
620
+ throw invalid('passkey.rpId', 'is required');
621
+ }
622
+ requireLabel('passkey.label', passkey.label);
623
+ const ceiling = grant.ceiling;
624
+ if (ceiling == null || typeof ceiling !== 'object') {
625
+ throw invalid('ceiling', 'is required');
626
+ }
627
+ validateScopes(ceiling.scopes, 'ceiling.scopes');
628
+ const ceilingScopes = grant.builderAccount === NO_BUILDER
629
+ ? FIRST_PARTY_PASSKEY_CEILING_SCOPES
630
+ : BUILDER_PASSKEY_CEILING_SCOPES;
631
+ const notCeilingScope = ceiling.scopes.find((s) => !ceilingScopes.includes(s));
632
+ if (notCeilingScope != null) {
633
+ throw new SessionGrantError('SCOPE_NOT_ALLOWED', `ceiling.scopes: "${notCeilingScope}" cannot be in a passkey ceiling`);
634
+ }
635
+ validateLimits(ceiling.limits, grant.builderAccount !== NO_BUILDER, 'ceiling.limits', options);
636
+ requireUniqueAddresses('ceiling.subaccounts', ceiling.subaccounts, grant.account);
637
+ if (typeof ceiling.includeFutureSubaccounts !== 'boolean') {
638
+ throw invalid('ceiling.includeFutureSubaccounts', 'must be a boolean');
639
+ }
640
+ if (options.passkeySubaccounts !== true &&
641
+ (ceiling.subaccounts.length > 0 || ceiling.includeFutureSubaccounts)) {
642
+ throw invalid('ceiling.subaccounts', 'passkey subaccounts are not enabled on the server');
643
+ }
644
+ if (ceiling.includeFutureSubaccounts && grant.builderAccount !== NO_BUILDER) {
645
+ throw invalid('ceiling.includeFutureSubaccounts', 'is allowed only for first-party passkeys');
646
+ }
647
+ requireTimestamp('ceiling.maxSessionTtl', ceiling.maxSessionTtl);
648
+ const skew = options.clockSkewSeconds ?? MAX_ISSUED_AT_SKEW;
649
+ if (ceiling.maxSessionTtl <= skew ||
650
+ ceiling.maxSessionTtl > SESSION_TTL.passkeySessionMax) {
651
+ throw new SessionGrantError('TTL_EXCEEDED', `ceiling.maxSessionTtl: must be ${skew + 1}-${SESSION_TTL.passkeySessionMax}s`);
652
+ }
653
+ if (!Number.isSafeInteger(ceiling.maxConcurrentSessions) ||
654
+ ceiling.maxConcurrentSessions < 1 ||
655
+ ceiling.maxConcurrentSessions > MAX_PASSKEY_CONCURRENT_SESSIONS) {
656
+ throw invalid('ceiling.maxConcurrentSessions', `must be 1-${MAX_PASSKEY_CONCURRENT_SESSIONS}`);
657
+ }
658
+ }
659
+ /**
660
+ * Checks a `SessionMint`'s format. Its limits are either all stated (as for
661
+ * a grant) or {@link CEILING_LIMITS}; `expiresAt` may be
662
+ * {@link LONGEST_SESSION}. A mint names no account, so whether its
663
+ * subaccounts leave out the passkey's account is checked by
664
+ * {@link assertMintWithinCeiling}.
665
+ */
666
+ export function validateSessionMint(mint, options = {}) {
667
+ validateBinding(mint);
668
+ requireUniqueAddresses('subaccounts', mint.subaccounts);
669
+ requireCanonicalHex('sessionKey', mint.sessionKey, FELT_PRIME);
670
+ if (mint.sessionKey === '0x0')
671
+ throw invalid('sessionKey', 'is zero');
672
+ validateScopes(mint.scopes);
673
+ if (!isCeilingLimits(mint.limits)) {
674
+ validateLimits(mint.limits, false, 'limits', options);
675
+ }
676
+ requireTimestamp('expiresAt', mint.expiresAt);
677
+ }
678
+ function exceeds(message) {
679
+ return new SessionGrantError('EXCEEDS_CEILING', message);
680
+ }
681
+ /**
682
+ * Checks a `SessionMint` against the `PasskeyGrant` of the passkey that signs
683
+ * it, as the server does: same chain and environment, and scopes within the
684
+ * ceiling. A mint names no account or passkey; the server finds the grant by
685
+ * the assertion's credential id. Only limits the server enforces are
686
+ * compared: each must be numeric and at or below a numeric ceiling (anything
687
+ * goes under a `"none"` ceiling), and markets must be within the ceiling's
688
+ * unless it allows `["*"]`. Unenforced limits are `"none"` on the mint and
689
+ * skipped, so passkeys registered with numeric limits keep working. A mint
690
+ * stating {@link CEILING_LIMITS} takes the ceiling's and fits by definition.
691
+ * A builder passkey's mints are checked like any other: the server checks
692
+ * `maxLoss` when the passkey registers, not on its mints. Subaccounts must
693
+ * not list the passkey's account.
694
+ *
695
+ * The check holds only when `grant`'s passkey signs. With an empty
696
+ * `allowCredentials` the user may pick another passkey, on another account
697
+ * or with another ceiling, and the server checks the mint against that one.
698
+ * Pin `allowCredentials` to `grant.passkey.credentialId`, or compare the
699
+ * account in the server's response with `grant.account` and revoke the
700
+ * session if they differ.
701
+ *
702
+ * Expiry: the passkey must not have expired. `expiresAt`
703
+ * {@link LONGEST_SESSION} always fits. Otherwise it must be in the future
704
+ * and at most the ceiling's `maxSessionTtl` from `now` (less the clock-skew
705
+ * allowance). It may be later than the passkey's expiry: the server then
706
+ * ends the session when the passkey expires.
707
+ *
708
+ * @experimental
709
+ */
710
+ export function assertMintWithinCeiling(mint, grant, now = nowSeconds(), options = {}) {
711
+ validateSessionMint(mint, options);
712
+ // The passkey was registered earlier, possibly with limits the server now
713
+ // leaves unenforced; check its format only.
714
+ validatePasskeyGrant(grant, {
715
+ limitCaps: {},
716
+ enforcedLimits: ALL_LIMITS,
717
+ passkeySubaccounts: true,
718
+ clockSkewSeconds: 0,
719
+ });
720
+ if (mint.paradexChain !== grant.paradexChain ||
721
+ mint.environment !== grant.environment) {
722
+ throw new SessionGrantError('ENVIRONMENT_MISMATCH', 'mint and passkey grant are for different environments');
723
+ }
724
+ const { ceiling } = grant;
725
+ for (const scope of mint.scopes) {
726
+ if (!ceiling.scopes.includes(scope)) {
727
+ throw exceeds(`scopes: "${scope}" is not in the ceiling`);
728
+ }
729
+ }
730
+ const enforced = options.enforcedLimits ?? DEFAULT_ENFORCED_LIMITS;
731
+ // The ceiling's own limits fit by definition. Limits the server does not
732
+ // enforce are "none" on the mint and are not compared, so passkeys
733
+ // registered with numbers keep working.
734
+ if (!isCeilingLimits(mint.limits)) {
735
+ for (const key of LIMIT_AMOUNTS) {
736
+ const cap = ceiling.limits[key];
737
+ const value = mint.limits[key];
738
+ if (!enforced.includes(key) || isNoCap(cap))
739
+ continue;
740
+ if (isNoCap(value)) {
741
+ throw exceeds(`limits.${key}: the ceiling caps it at ${cap}`);
742
+ }
743
+ if (new BigNumber(value).isGreaterThan(cap)) {
744
+ throw exceeds(`limits.${key}: ${value} is above the ceiling ${cap}`);
745
+ }
746
+ }
747
+ const allowedMarkets = enforced.includes('markets')
748
+ ? ceiling.limits.markets
749
+ : ALL_MARKETS;
750
+ for (const market of mint.limits.markets) {
751
+ if (!allowedMarkets.some((pattern) => marketCovers(pattern, market))) {
752
+ throw exceeds(`limits.markets: "${market}" is not in the ceiling`);
753
+ }
754
+ }
755
+ }
756
+ if (mint.subaccounts.includes(grant.account)) {
757
+ throw invalid('subaccounts', "must not include the passkey's account");
758
+ }
759
+ if (!ceiling.includeFutureSubaccounts) {
760
+ for (const account of mint.subaccounts) {
761
+ if (!ceiling.subaccounts.includes(account)) {
762
+ throw exceeds(`subaccounts: ${account} is not in the ceiling`);
763
+ }
764
+ }
765
+ }
766
+ if (grant.expiresAt <= now) {
767
+ throw new SessionGrantError('GRANT_EXPIRED', `passkey grant expired at ${grant.expiresAt}`);
768
+ }
769
+ // The server picks the expiry: the ceiling's maxSessionTtl from its own
770
+ // clock, or the passkey's expiry if that is sooner.
771
+ if (mint.expiresAt === LONGEST_SESSION)
772
+ return;
773
+ if (mint.expiresAt <= now) {
774
+ throw new SessionGrantError('GRANT_EXPIRED', `mint expired at ${mint.expiresAt}`);
775
+ }
776
+ const skew = options.clockSkewSeconds ?? MAX_ISSUED_AT_SKEW;
777
+ if (ceiling.maxSessionTtl <= skew) {
778
+ throw new SessionGrantError('TTL_EXCEEDED', `ceiling.maxSessionTtl: ${ceiling.maxSessionTtl}s leaves no time after ${skew}s of clock skew`);
779
+ }
780
+ // A mint may outlive its passkey: the server ends the session when the
781
+ // passkey expires.
782
+ const latest = now + ceiling.maxSessionTtl - skew;
783
+ if (mint.expiresAt > latest) {
784
+ throw exceeds(`expiresAt: must be at or before ${latest}`);
785
+ }
786
+ }
787
+ // ---------------------------------------------------------------------------
788
+ // Builders
789
+ // ---------------------------------------------------------------------------
790
+ /** A fresh 128-bit random nonce in canonical hex. */
791
+ export function generateSessionNonce() {
792
+ const bytes = new Uint8Array(16);
793
+ globalThis.crypto.getRandomValues(bytes);
794
+ let n = 0n;
795
+ for (const b of bytes)
796
+ n = (n << 8n) | BigInt(b);
797
+ // A zero nonce is refused; the chance is 2^-128 but stay correct.
798
+ return n === 0n ? '0x1' : canonicalFelt(n);
799
+ }
800
+ export function nowSeconds() {
801
+ return Math.floor(Date.now() / 1000);
802
+ }
803
+ /**
804
+ * Builds a canonical, validated `SessionGrant`. Addresses and keys are
805
+ * normalized to canonical hex; everything else is checked as given.
806
+ *
807
+ * @experimental
808
+ */
809
+ export function createSessionGrant(params) {
810
+ const issuedAt = params.issuedAt ?? nowSeconds();
811
+ const scopes = params.scopes ?? ['trade'];
812
+ const expiresAt = params.expiresAt ??
813
+ issuedAt +
814
+ (params.ttlSeconds ??
815
+ Math.min(SESSION_TTL.browserDefault, maxSessionTtl(scopes, params.sessionType, params.clockSkewSeconds)));
816
+ const grant = {
817
+ paradexChain: params.paradexChain,
818
+ environment: params.environment,
819
+ account: canonicalFelt(params.account),
820
+ sessionKey: canonicalFelt(params.sessionKey),
821
+ label: params.label ?? '',
822
+ scopes: [...scopes],
823
+ limits: {
824
+ ...(params.limits ?? UNCAPPED_LIMITS),
825
+ markets: [...(params.limits ?? UNCAPPED_LIMITS).markets],
826
+ },
827
+ builder: params.builder == null
828
+ ? { account: NO_BUILDER, maxFeeRate: '0', expiresAt: 0 }
829
+ : {
830
+ account: canonicalFelt(params.builder.account),
831
+ maxFeeRate: params.builder.maxFeeRate,
832
+ expiresAt: params.builder.expiresAt ?? 0,
833
+ },
834
+ subaccounts: (params.subaccounts ?? []).map((a) => canonicalFelt(a)),
835
+ nonce: params.nonce != null
836
+ ? canonicalFelt(params.nonce)
837
+ : generateSessionNonce(),
838
+ issuedAt,
839
+ expiresAt,
840
+ };
841
+ validateSessionGrant(grant, {
842
+ sessionType: params.sessionType,
843
+ clockSkewSeconds: params.clockSkewSeconds,
844
+ limitCaps: params.limitCaps,
845
+ enforcedLimits: params.enforcedLimits,
846
+ });
847
+ return grant;
848
+ }
849
+ /** Every account a grant reaches: the anchor first, then its sub-accounts. */
850
+ export function grantAccounts(grant) {
851
+ return [grant.account, ...grant.subaccounts];
852
+ }
853
+ /**
854
+ * Throws `GRANT_EXPIRED` once the grant (or a time just ahead of `now`) has
855
+ * passed its expiry, and `INVALID_FIELD` if `issuedAt` is too far ahead.
856
+ */
857
+ export function assertGrantActive(grant, now = nowSeconds()) {
858
+ if (now >= grant.expiresAt) {
859
+ throw new SessionGrantError('GRANT_EXPIRED', `grant expired at ${grant.expiresAt}`);
860
+ }
861
+ if (grant.issuedAt > now + MAX_ISSUED_AT_SKEW) {
862
+ throw invalid('issuedAt', 'is in the future');
863
+ }
864
+ }
865
+ // ---------------------------------------------------------------------------
866
+ // Encodings and hashes
867
+ // ---------------------------------------------------------------------------
868
+ function toChainId(signatureChainId) {
869
+ let n = Number.NaN;
870
+ try {
871
+ n =
872
+ typeof signatureChainId === 'number'
873
+ ? signatureChainId
874
+ : Number(BigInt(signatureChainId));
875
+ }
876
+ catch {
877
+ // Not an integer; rejected below.
878
+ }
879
+ if (!Number.isSafeInteger(n) || n <= 0) {
880
+ throw invalid('signatureChainId', 'must be a positive EVM chain id');
881
+ }
882
+ return n;
883
+ }
884
+ function eip712(primaryType, types, message, signatureChainId) {
885
+ return {
886
+ domain: {
887
+ name: SESSION_DOMAIN_NAME,
888
+ version: SESSION_DOMAIN_VERSION,
889
+ chainId: toChainId(signatureChainId),
890
+ },
891
+ primaryType,
892
+ types,
893
+ message: structuredClone(message),
894
+ };
895
+ }
896
+ /**
897
+ * SNIP-12 `string` is a Cairo ByteArray. Keep every string ASCII so the
898
+ * byte encoding cannot differ between implementations.
899
+ */
900
+ function requireAsciiStrings(value, path) {
901
+ if (typeof value === 'string') {
902
+ if (!/^[\x20-\x7e]*$/.test(value)) {
903
+ throw invalid(path, 'must be printable ASCII in SNIP-12 typed data');
904
+ }
905
+ }
906
+ else if (Array.isArray(value)) {
907
+ value.forEach((v, i) => {
908
+ requireAsciiStrings(v, `${path}[${i}]`);
909
+ });
910
+ }
911
+ else if (value != null && typeof value === 'object') {
912
+ for (const [k, v] of Object.entries(value)) {
913
+ requireAsciiStrings(v, path === '' ? k : `${path}.${k}`);
914
+ }
915
+ }
916
+ }
917
+ function snip12(primaryType, types, message, paradexChain) {
918
+ requireAsciiStrings(message, '');
919
+ return {
920
+ domain: {
921
+ name: SESSION_DOMAIN_NAME,
922
+ version: SESSION_DOMAIN_VERSION,
923
+ chainId: paradexChain,
924
+ revision: '1',
925
+ },
926
+ primaryType,
927
+ types,
928
+ message: structuredClone(message),
929
+ };
930
+ }
931
+ /**
932
+ * EIP-712 `SessionGrant`. `signatureChainId` is the wallet's *current* EVM
933
+ * chain, so no network switch is needed; send it along with the signature.
934
+ *
935
+ * @experimental
936
+ */
937
+ export function buildSessionGrantEip712(grant, signatureChainId, options = {}) {
938
+ validateSessionGrant(grant, options);
939
+ return eip712('SessionGrant', SESSION_GRANT_EIP712_TYPES, grant, signatureChainId);
940
+ }
941
+ /**
942
+ * SNIP-12 revision 1 `SessionGrant`, signed by a Stark owner key. Builder
943
+ * grants are EIP-712 only, so a grant naming a builder is refused here.
944
+ *
945
+ * @experimental
946
+ */
947
+ export function buildSessionGrantSnip12(grant, options = {}) {
948
+ validateSessionGrant(grant, options);
949
+ if (grant.builder.account !== NO_BUILDER) {
950
+ throw new SessionGrantError('BUILDER_REQUIRES_EIP712', 'builder grants are accepted only from EIP-191 accounts (EIP-712)');
951
+ }
952
+ return snip12('SessionGrant', SESSION_GRANT_SNIP12_TYPES, grant, grant.paradexChain);
953
+ }
954
+ /** @experimental */
955
+ export function buildPasskeyGrantEip712(grant, signatureChainId, options = {}) {
956
+ validatePasskeyGrant(grant, options);
957
+ return eip712('PasskeyGrant', PASSKEY_GRANT_EIP712_TYPES, grant, signatureChainId);
958
+ }
959
+ /** @experimental */
960
+ export function buildPasskeyGrantSnip12(grant, options = {}) {
961
+ validatePasskeyGrant(grant, options);
962
+ return snip12('PasskeyGrant', PASSKEY_GRANT_SNIP12_TYPES, grant, grant.paradexChain);
963
+ }
964
+ /** @experimental */
965
+ export function buildSessionMintEip712(mint, signatureChainId, options = {}) {
966
+ validateSessionMint(mint, options);
967
+ return eip712('SessionMint', SESSION_MINT_EIP712_TYPES, mint, signatureChainId);
968
+ }
969
+ /** @experimental */
970
+ export function buildSessionMintSnip12(mint, options = {}) {
971
+ validateSessionMint(mint, options);
972
+ return snip12('SessionMint', SESSION_MINT_SNIP12_TYPES, mint, mint.paradexChain);
973
+ }
974
+ /** EIP-712 digest (`0x1901 ‖ domain ‖ struct`) as 0x-prefixed 32-byte hex. */
975
+ export function hashEip712(typedData) {
976
+ return hashEip712TypedData(typedData);
977
+ }
978
+ /**
979
+ * SNIP-12 message hash for `account` (the signer's address), as 0x-prefixed
980
+ * 32-byte hex.
981
+ */
982
+ export function hashSnip12(typedData, account) {
983
+ const hash = Starknet.typedData.getMessageHash(typedData, account);
984
+ return `0x${BigInt(hash).toString(16).padStart(64, '0')}`;
985
+ }
986
+ /**
987
+ * The WebAuthn challenge for a `SessionMint`: the 32-byte SNIP-12 message
988
+ * hash, taken for {@link MINT_HASH_ACCOUNT} (`0x0`) since a mint names no
989
+ * account, base64url-encoded without padding.
990
+ */
991
+ export function sessionMintChallenge(mint, options = {}) {
992
+ const hash = hashSnip12(buildSessionMintSnip12(mint, options), MINT_HASH_ACCOUNT);
993
+ const bytes = hexToBytes(hash.slice(2));
994
+ let binary = '';
995
+ for (const b of bytes)
996
+ binary += String.fromCharCode(b);
997
+ return btoa(binary)
998
+ .replace(/\+/g, '-')
999
+ .replace(/\//g, '_')
1000
+ .replace(/=+$/, '');
1001
+ }
1002
+ /** The wording shown to owners about what a session can lose. */
1003
+ export function lossSummary(limits) {
1004
+ return isNoCap(limits.maxLoss)
1005
+ ? 'Cannot withdraw; trading losses are not capped by this session'
1006
+ : `Cannot withdraw; can lose up to ${limits.maxLoss} USD by trading`;
1007
+ }
1008
+ /**
1009
+ * A readable summary of a grant for the approval screen, one line each.
1010
+ * Show the builder by its registered name, not the grant's free-text label.
1011
+ *
1012
+ * @experimental
1013
+ */
1014
+ export function summarizeGrant(grant) {
1015
+ const lines = [
1016
+ lossSummary(grant.limits),
1017
+ `Scopes: ${grant.scopes.join(', ')}`,
1018
+ `Accounts: ${grantAccounts(grant).join(', ')}`,
1019
+ `Expires: ${new Date(grant.expiresAt * 1000).toISOString()}`,
1020
+ ];
1021
+ const stated = [
1022
+ ['Max order', grant.limits.maxOrderNotional, ' USD'],
1023
+ ['Max open', grant.limits.maxOpenNotional, ' USD'],
1024
+ ['Daily volume', grant.limits.dailyNotional, ' USD'],
1025
+ ['Max leverage', grant.limits.maxLeverage, 'x'],
1026
+ ].map(([name, value, unit]) => isNoCap(value) ? `${name}: no cap` : `${name}: ${value}${unit}`);
1027
+ lines.push(...stated);
1028
+ lines.push(grant.limits.markets.includes('*')
1029
+ ? 'Markets: all permitted'
1030
+ : `Markets: ${grant.limits.markets.join(', ')}`);
1031
+ if (grant.builder.account !== NO_BUILDER) {
1032
+ lines.push(`Builder ${grant.builder.account} may charge up to ${grant.builder.maxFeeRate} per trade`);
1033
+ }
1034
+ return lines;
1035
+ }