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