@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,31 @@
1
+ import * as Starknet from 'starknet';
2
+ /** Session JWTs live at most 15 minutes, and never past the session. */
3
+ export declare const SESSION_AUTH_MAX_TTL: number;
4
+ /** The path the `/auth` request signs, whichever key signs in. */
5
+ export declare const AUTH_PATH = "/v1/auth";
6
+ /**
7
+ * Where a session key signs in: `POST /v1/auth/{public_key}`. Plain
8
+ * `/v1/auth` verifies the signature against the account's main key, so a
9
+ * session key is refused there. The signed path stays {@link AUTH_PATH}.
10
+ */
11
+ export declare function sessionAuthPath(sessionPublicKey: string): string;
12
+ export declare function buildAuthTypedData(paradexChain: string, timestamp: number, expiration: number): Starknet.TypedData;
13
+ export type OrderSide = 'BUY' | 'SELL';
14
+ export type OrderType = 'LIMIT' | 'MARKET';
15
+ export interface SessionOrder {
16
+ readonly market: string;
17
+ readonly side: OrderSide;
18
+ readonly type: OrderType;
19
+ /** Decimal string in base asset units. */
20
+ readonly size: string;
21
+ /** Decimal string; required for LIMIT, ignored for MARKET. */
22
+ readonly price?: string;
23
+ readonly instruction?: 'GTC' | 'IOC' | 'POST_ONLY' | 'RPI';
24
+ readonly clientId?: string;
25
+ readonly reduceOnly?: boolean;
26
+ }
27
+ /** Decimal string → 8-decimal quantum integer string, as the chain signs it. */
28
+ export declare function toChainQuantums(value: string, field: string): string;
29
+ export declare function buildOrderTypedData(paradexChain: string, order: SessionOrder, signatureTimestampMs: number): Starknet.TypedData;
30
+ /** Reads `exp` (seconds) from a JWT without verifying it. */
31
+ export declare function jwtExpiry(token: string): number | undefined;
@@ -0,0 +1,115 @@
1
+ import BigNumber from 'bignumber.js';
2
+ import * as Starknet from 'starknet';
3
+ /**
4
+ * Typed data a session key signs: the `/auth` request that mints a JWT and
5
+ * the orders it places. Both are today's SNIP-12 (revision 0) "Paradex"
6
+ * domain messages, signed for the account in `PARADEX-STARKNET-ACCOUNT`.
7
+ *
8
+ * @experimental
9
+ */
10
+ const REQUEST_DOMAIN_TYPES = [
11
+ { name: 'name', type: 'felt' },
12
+ { name: 'chainId', type: 'felt' },
13
+ { name: 'version', type: 'felt' },
14
+ ];
15
+ function paradexDomain(paradexChain) {
16
+ return {
17
+ name: 'Paradex',
18
+ chainId: Starknet.shortString.encodeShortString(paradexChain),
19
+ version: '1',
20
+ };
21
+ }
22
+ /** Session JWTs live at most 15 minutes, and never past the session. */
23
+ export const SESSION_AUTH_MAX_TTL = 15 * 60;
24
+ /** The path the `/auth` request signs, whichever key signs in. */
25
+ export const AUTH_PATH = '/v1/auth';
26
+ /**
27
+ * Where a session key signs in: `POST /v1/auth/{public_key}`. Plain
28
+ * `/v1/auth` verifies the signature against the account's main key, so a
29
+ * session key is refused there. The signed path stays {@link AUTH_PATH}.
30
+ */
31
+ export function sessionAuthPath(sessionPublicKey) {
32
+ if (!/^0x[0-9a-fA-F]{1,64}$/.test(sessionPublicKey)) {
33
+ throw new Error('session public key must be 0x-prefixed hex');
34
+ }
35
+ return `${AUTH_PATH}/${sessionPublicKey}`;
36
+ }
37
+ export function buildAuthTypedData(paradexChain, timestamp, expiration) {
38
+ return {
39
+ domain: paradexDomain(paradexChain),
40
+ primaryType: 'Request',
41
+ types: {
42
+ StarkNetDomain: REQUEST_DOMAIN_TYPES,
43
+ Request: [
44
+ { name: 'method', type: 'felt' },
45
+ { name: 'path', type: 'felt' },
46
+ { name: 'body', type: 'felt' },
47
+ { name: 'timestamp', type: 'felt' },
48
+ { name: 'expiration', type: 'felt' },
49
+ ],
50
+ },
51
+ message: {
52
+ method: 'POST',
53
+ path: AUTH_PATH,
54
+ body: '',
55
+ timestamp,
56
+ expiration,
57
+ },
58
+ };
59
+ }
60
+ /** Decimal string → 8-decimal quantum integer string, as the chain signs it. */
61
+ export function toChainQuantums(value, field) {
62
+ const n = new BigNumber(value);
63
+ if (!n.isFinite() || n.isNegative() || !/^\d+(\.\d+)?$/.test(value)) {
64
+ throw new Error(`${field} must be a non-negative decimal string`);
65
+ }
66
+ const scaled = n.shiftedBy(8);
67
+ if (!scaled.isInteger()) {
68
+ throw new Error(`${field} has more than 8 decimal places`);
69
+ }
70
+ return scaled.toFixed(0);
71
+ }
72
+ export function buildOrderTypedData(paradexChain, order, signatureTimestampMs) {
73
+ if (order.type === 'LIMIT' && order.price == null) {
74
+ throw new Error('LIMIT orders need a price');
75
+ }
76
+ return {
77
+ domain: paradexDomain(paradexChain),
78
+ primaryType: 'Order',
79
+ types: {
80
+ StarkNetDomain: REQUEST_DOMAIN_TYPES,
81
+ Order: [
82
+ { name: 'timestamp', type: 'felt' },
83
+ { name: 'market', type: 'felt' },
84
+ { name: 'side', type: 'felt' },
85
+ { name: 'orderType', type: 'felt' },
86
+ { name: 'size', type: 'felt' },
87
+ { name: 'price', type: 'felt' },
88
+ ],
89
+ },
90
+ message: {
91
+ timestamp: String(signatureTimestampMs),
92
+ market: Starknet.shortString.encodeShortString(order.market),
93
+ side: order.side === 'BUY' ? '1' : '2',
94
+ orderType: Starknet.shortString.encodeShortString(order.type),
95
+ size: toChainQuantums(order.size, 'size'),
96
+ price: order.type === 'MARKET'
97
+ ? '0'
98
+ : toChainQuantums(order.price ?? '', 'price'),
99
+ },
100
+ };
101
+ }
102
+ /** Reads `exp` (seconds) from a JWT without verifying it. */
103
+ export function jwtExpiry(token) {
104
+ const payload = token.split('.')[1];
105
+ if (payload == null)
106
+ return undefined;
107
+ try {
108
+ const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
109
+ const json = JSON.parse(atob(base64));
110
+ return typeof json.exp === 'number' ? json.exp : undefined;
111
+ }
112
+ catch {
113
+ return undefined;
114
+ }
115
+ }
@@ -0,0 +1,132 @@
1
+ import { SessionKey, type SessionStorage } from './session-key.js';
2
+ import { type SessionOwnerSigner } from './session-owner-signer.js';
3
+ import { type HttpTransport } from './session-transport.js';
4
+ import { type CreateSessionGrantParams, type LimitCaps, type LimitName, type SessionEnvironment, type SessionGrant } from './session-typed-data.js';
5
+ import type { Hex } from './types.js';
6
+ export declare const SESSIONS_PATH = "/v2/sessions";
7
+ export declare const EVM_SUBACCOUNTS_PATH = "/v2/onboarding/subaccounts";
8
+ /** A registered session: the grant and the key that may act under it. */
9
+ export interface Session {
10
+ /** The server's id for the grant (its hash). */
11
+ readonly grantId: string;
12
+ readonly grant: SessionGrant;
13
+ readonly key: SessionKey;
14
+ readonly ownerSignature: Hex;
15
+ readonly signatureChainId: number;
16
+ }
17
+ export interface SessionConnectorParams {
18
+ readonly environment: SessionEnvironment;
19
+ /** Paradex chain id (`ParadexConfig.paradexChainId`). */
20
+ readonly paradexChain: string;
21
+ readonly owner: SessionOwnerSigner;
22
+ /** Defaults to memory; use `indexedDbSessionStorage()` to survive reloads. */
23
+ readonly storage?: SessionStorage;
24
+ readonly transport?: HttpTransport;
25
+ readonly apiUrl?: string;
26
+ readonly now?: () => number;
27
+ /**
28
+ * Optional caps checked before the owner signs (none by default).
29
+ * `open()` may override them per call.
30
+ */
31
+ readonly limitCaps?: LimitCaps;
32
+ /**
33
+ * Limits the server enforces (none by default, so every limit must be
34
+ * `"none"`). `open()` may override them per call.
35
+ */
36
+ readonly enforcedLimits?: readonly LimitName[];
37
+ }
38
+ /** UTM tracking parameters, as `POST /v2/onboarding` takes them. */
39
+ export interface SessionUtm {
40
+ readonly source: string;
41
+ readonly campaign: string;
42
+ readonly type?: string;
43
+ }
44
+ /**
45
+ * Sent with the grant and read only when it opens a new account (a wallet
46
+ * with no Paradex account yet). None of it is signed, so the server ignores
47
+ * it for a grant that names a builder.
48
+ */
49
+ export interface SessionOnboardingParams {
50
+ readonly referralCode?: string;
51
+ /** `campaign:code`. */
52
+ readonly marketingCode?: string;
53
+ readonly utm?: SessionUtm;
54
+ /**
55
+ * A Privy access token for the signing wallet, sent as
56
+ * `PARADEX-PRIVY-ACCESS-TOKEN`. It lets a verified Privy user's wallet skip
57
+ * the minimum-balance check when the grant opens a new account.
58
+ */
59
+ readonly privyAccessToken?: string;
60
+ }
61
+ export type OpenSessionParams = Omit<CreateSessionGrantParams, 'paradexChain' | 'environment' | 'sessionKey' | 'sessionType'> & {
62
+ /** Used only when the grant opens a new account. */
63
+ readonly onboarding?: SessionOnboardingParams;
64
+ };
65
+ /** An EVM-owned account's sub-account, as `GET /v2/onboarding/subaccounts` lists it. */
66
+ export interface EvmSubaccount {
67
+ readonly address: string;
68
+ /** Index under the owner the address derives from. */
69
+ readonly index: number;
70
+ }
71
+ /**
72
+ * Opens trading sessions for a wallet-owned account: generates the session
73
+ * key in the page, asks the owner to sign one grant, and registers it.
74
+ *
75
+ * @experimental The request and response shapes of `/v2/sessions` may
76
+ * change.
77
+ */
78
+ export declare class SessionConnector {
79
+ readonly environment: SessionEnvironment;
80
+ readonly paradexChain: string;
81
+ private readonly owner;
82
+ private readonly storage;
83
+ private readonly transport;
84
+ private readonly apiUrl;
85
+ private readonly now;
86
+ private readonly limitCaps;
87
+ private readonly enforcedLimits;
88
+ constructor(params: SessionConnectorParams);
89
+ /**
90
+ * Lists the sub-accounts of the EVM-owned account a wallet owns, lowest
91
+ * index first, so a grant can list them before the wallet has signed in.
92
+ * A wallet with no EVM-owned account has none.
93
+ */
94
+ listSubaccounts(ethAddress: string): Promise<EvmSubaccount[]>;
95
+ /**
96
+ * Generates a session key, has the owner sign the grant (one wallet
97
+ * prompt), and registers the session. On any failure the new key is
98
+ * deleted.
99
+ *
100
+ * A grant from a wallet with no Paradex account opens the account too; it
101
+ * may list no subaccounts. Pass `onboarding` for that case.
102
+ *
103
+ * When the owner signer knows its address and the grant lists
104
+ * subaccounts, each is checked against {@link listSubaccounts} before the
105
+ * owner is asked to sign. The grant always takes the browser lifetime cap,
106
+ * the one `POST /v2/sessions` applies.
107
+ */
108
+ open(params: OpenSessionParams): Promise<Session>;
109
+ /**
110
+ * Restores registered sessions from storage for this environment. Expired
111
+ * sessions and sessions that never registered are deleted; records that
112
+ * cannot be read are skipped.
113
+ */
114
+ restore(): Promise<Session[]>;
115
+ /** Restores one session by its public key. */
116
+ restoreByKey(publicKey: string): Promise<Session | undefined>;
117
+ /**
118
+ * Forgets a session locally. This does not revoke it on the server; use
119
+ * `SessionAccounts.revoke()` for that.
120
+ */
121
+ forget(session: Pick<Session, 'key'>): Promise<void>;
122
+ /**
123
+ * Refuses, before the owner signs, a grant listing an account that
124
+ * {@link listSubaccounts} does not return for the owner wallet. The listing
125
+ * leaves out archived children, which `POST /v2/sessions` may still accept,
126
+ * so this check can be stricter than the server. It is advisory: skipped
127
+ * when the signer cannot name its address or the listing fails for any
128
+ * reason, leaving `POST /v2/sessions` to decide.
129
+ */
130
+ private assertSubaccountsOwned;
131
+ private fromRecord;
132
+ }
@@ -0,0 +1,304 @@
1
+ import { hashTypedData } from './eip712.js';
2
+ import { assertRecordVersion, memorySessionStorage, SessionKey, } from './session-key.js';
3
+ import { assertEoaSignature, } from './session-owner-signer.js';
4
+ import { defaultApiUrl, fetchTransport, SessionApiError, } from './session-transport.js';
5
+ import { assertGrantActive, buildSessionGrantEip712, canonicalFelt, createSessionGrant, grantAccounts, nowSeconds, SessionGrantError, } from './session-typed-data.js';
6
+ export const SESSIONS_PATH = '/v2/sessions';
7
+ export const EVM_SUBACCOUNTS_PATH = '/v2/onboarding/subaccounts';
8
+ /** Whether `open()` finished registering this record. */
9
+ function isRegistered(record) {
10
+ return (record.grant != null &&
11
+ record.grantId != null &&
12
+ record.ownerSignature != null &&
13
+ record.signatureChainId != null);
14
+ }
15
+ function onboardingBody(onboarding) {
16
+ if (onboarding == null)
17
+ return {};
18
+ const body = {};
19
+ if (onboarding.referralCode != null && onboarding.referralCode !== '') {
20
+ body.referral_code = onboarding.referralCode;
21
+ }
22
+ if (onboarding.marketingCode != null && onboarding.marketingCode !== '') {
23
+ body.marketing_code = onboarding.marketingCode;
24
+ }
25
+ if (onboarding.utm != null) {
26
+ body.utm = {
27
+ source: onboarding.utm.source,
28
+ campaign: onboarding.utm.campaign,
29
+ ...(onboarding.utm.type != null ? { type: onboarding.utm.type } : {}),
30
+ };
31
+ }
32
+ return body;
33
+ }
34
+ function sameAccounts(listed, grant) {
35
+ if (!Array.isArray(listed))
36
+ return false;
37
+ const expected = new Set(grantAccounts(grant));
38
+ const got = new Set();
39
+ for (const account of listed) {
40
+ if (typeof account !== 'string')
41
+ return false;
42
+ try {
43
+ got.add(canonicalFelt(account));
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
49
+ return got.size === expected.size && [...got].every((a) => expected.has(a));
50
+ }
51
+ /**
52
+ * Opens trading sessions for a wallet-owned account: generates the session
53
+ * key in the page, asks the owner to sign one grant, and registers it.
54
+ *
55
+ * @experimental The request and response shapes of `/v2/sessions` may
56
+ * change.
57
+ */
58
+ export class SessionConnector {
59
+ constructor(params) {
60
+ this.environment = params.environment;
61
+ this.paradexChain = params.paradexChain;
62
+ this.owner = params.owner;
63
+ this.storage = params.storage ?? memorySessionStorage();
64
+ this.transport = params.transport ?? fetchTransport;
65
+ this.apiUrl = params.apiUrl ?? defaultApiUrl(params.environment);
66
+ this.now = params.now ?? nowSeconds;
67
+ this.limitCaps = params.limitCaps;
68
+ this.enforcedLimits = params.enforcedLimits;
69
+ }
70
+ /**
71
+ * Lists the sub-accounts of the EVM-owned account a wallet owns, lowest
72
+ * index first, so a grant can list them before the wallet has signed in.
73
+ * A wallet with no EVM-owned account has none.
74
+ */
75
+ async listSubaccounts(ethAddress) {
76
+ if (!/^0x[0-9a-fA-F]{40}$/.test(ethAddress)) {
77
+ throw new Error('ethAddress must be a 0x-prefixed 20-byte address');
78
+ }
79
+ const response = await this.transport({
80
+ method: 'GET',
81
+ url: `${this.apiUrl}${EVM_SUBACCOUNTS_PATH}?eth_address=${ethAddress}`,
82
+ headers: {},
83
+ });
84
+ if (response.status < 200 || response.status >= 300) {
85
+ throw new SessionApiError(response.status, response.body);
86
+ }
87
+ const results = response.body?.results;
88
+ if (!Array.isArray(results)) {
89
+ throw new SessionApiError(response.status, {
90
+ error: 'INVALID_RESPONSE',
91
+ message: `GET ${EVM_SUBACCOUNTS_PATH} returned no results`,
92
+ });
93
+ }
94
+ return results.map((entry) => {
95
+ const { address, index } = (entry ?? {});
96
+ if (typeof address !== 'string' ||
97
+ typeof index !== 'number' ||
98
+ !Number.isSafeInteger(index) ||
99
+ index < 0) {
100
+ throw new SessionApiError(response.status, {
101
+ error: 'INVALID_RESPONSE',
102
+ message: `GET ${EVM_SUBACCOUNTS_PATH} returned a malformed entry`,
103
+ });
104
+ }
105
+ return { address: canonicalFelt(address), index };
106
+ });
107
+ }
108
+ /**
109
+ * Generates a session key, has the owner sign the grant (one wallet
110
+ * prompt), and registers the session. On any failure the new key is
111
+ * deleted.
112
+ *
113
+ * A grant from a wallet with no Paradex account opens the account too; it
114
+ * may list no subaccounts. Pass `onboarding` for that case.
115
+ *
116
+ * When the owner signer knows its address and the grant lists
117
+ * subaccounts, each is checked against {@link listSubaccounts} before the
118
+ * owner is asked to sign. The grant always takes the browser lifetime cap,
119
+ * the one `POST /v2/sessions` applies.
120
+ */
121
+ async open(params) {
122
+ const { onboarding, ...grantParams } = params;
123
+ const limitOptions = {
124
+ limitCaps: grantParams.limitCaps ?? this.limitCaps,
125
+ enforcedLimits: grantParams.enforcedLimits ?? this.enforcedLimits,
126
+ };
127
+ let key = await SessionKey.generate();
128
+ const grant = createSessionGrant({
129
+ ...grantParams,
130
+ ...limitOptions,
131
+ // POST /v2/sessions caps every grant at the browser lifetime.
132
+ sessionType: 'browser',
133
+ issuedAt: grantParams.issuedAt ?? this.now(),
134
+ paradexChain: this.paradexChain,
135
+ environment: this.environment,
136
+ sessionKey: key.publicKey,
137
+ });
138
+ await this.assertSubaccountsOwned(grant);
139
+ await this.storage.put(key.record);
140
+ try {
141
+ const signatureChainId = await this.owner.getChainId();
142
+ const typedData = buildSessionGrantEip712(grant, signatureChainId, limitOptions);
143
+ const ownerSignature = assertEoaSignature(await this.owner.signTypedData({
144
+ typedData,
145
+ digest: hashTypedData(typedData),
146
+ }));
147
+ const response = await this.transport({
148
+ method: 'POST',
149
+ url: `${this.apiUrl}${SESSIONS_PATH}`,
150
+ headers: {
151
+ 'Content-Type': 'application/json',
152
+ ...(onboarding?.privyAccessToken != null &&
153
+ onboarding.privyAccessToken !== ''
154
+ ? { 'PARADEX-PRIVY-ACCESS-TOKEN': onboarding.privyAccessToken }
155
+ : {}),
156
+ },
157
+ body: JSON.stringify({
158
+ grant,
159
+ signature: ownerSignature,
160
+ signature_chain_id: signatureChainId,
161
+ signature_type: 'eip712',
162
+ ...onboardingBody(onboarding),
163
+ }),
164
+ });
165
+ if (response.status < 200 || response.status >= 300) {
166
+ throw new SessionApiError(response.status, response.body);
167
+ }
168
+ const body = response.body;
169
+ const grantId = body?.grant_id;
170
+ if (typeof grantId !== 'string' || grantId === '') {
171
+ throw new SessionApiError(response.status, {
172
+ error: 'INVALID_RESPONSE',
173
+ message: 'POST /v2/sessions returned no grant_id',
174
+ });
175
+ }
176
+ if (!sameAccounts(body?.accounts, grant)) {
177
+ throw new SessionApiError(response.status, {
178
+ error: 'INVALID_RESPONSE',
179
+ message: 'POST /v2/sessions registered different accounts',
180
+ });
181
+ }
182
+ // The API reports times in milliseconds; the signed grant uses seconds.
183
+ // A different expiry means the server did not register this grant.
184
+ if (body?.expires_at !== grant.expiresAt * 1000) {
185
+ throw new SessionApiError(response.status, {
186
+ error: 'INVALID_RESPONSE',
187
+ message: 'POST /v2/sessions registered a different expiry',
188
+ });
189
+ }
190
+ key = key.withMetadata({
191
+ grant,
192
+ ownerSignature,
193
+ signatureChainId,
194
+ grantId,
195
+ });
196
+ await this.storage.put(key.record);
197
+ return { grantId, grant, key, ownerSignature, signatureChainId };
198
+ }
199
+ catch (error) {
200
+ await this.storage.delete(key.publicKey);
201
+ throw error;
202
+ }
203
+ }
204
+ /**
205
+ * Restores registered sessions from storage for this environment. Expired
206
+ * sessions and sessions that never registered are deleted; records that
207
+ * cannot be read are skipped.
208
+ */
209
+ async restore() {
210
+ const sessions = [];
211
+ for (const record of await this.storage.list()) {
212
+ try {
213
+ const session = await this.fromRecord(record);
214
+ if (session != null)
215
+ sessions.push(session);
216
+ }
217
+ catch {
218
+ // Unreadable record (e.g. from a newer SDK); leave it in place.
219
+ }
220
+ }
221
+ return sessions;
222
+ }
223
+ /** Restores one session by its public key. */
224
+ async restoreByKey(publicKey) {
225
+ const record = await this.storage.get(publicKey);
226
+ return record == null ? undefined : await this.fromRecord(record);
227
+ }
228
+ /**
229
+ * Forgets a session locally. This does not revoke it on the server; use
230
+ * `SessionAccounts.revoke()` for that.
231
+ */
232
+ async forget(session) {
233
+ await this.storage.delete(session.key.publicKey);
234
+ }
235
+ /**
236
+ * Refuses, before the owner signs, a grant listing an account that
237
+ * {@link listSubaccounts} does not return for the owner wallet. The listing
238
+ * leaves out archived children, which `POST /v2/sessions` may still accept,
239
+ * so this check can be stricter than the server. It is advisory: skipped
240
+ * when the signer cannot name its address or the listing fails for any
241
+ * reason, leaving `POST /v2/sessions` to decide.
242
+ */
243
+ async assertSubaccountsOwned(grant) {
244
+ if (grant.subaccounts.length === 0 || this.owner.getAddress == null) {
245
+ return;
246
+ }
247
+ let listed;
248
+ try {
249
+ listed = await this.listSubaccounts(await this.owner.getAddress());
250
+ }
251
+ catch {
252
+ // POST /v2/sessions refuses an ineligible account itself.
253
+ return;
254
+ }
255
+ const owned = new Set(listed.map((s) => s.address));
256
+ const foreign = grant.subaccounts.find((a) => !owned.has(a));
257
+ if (foreign != null) {
258
+ throw new SessionGrantError('ACCOUNT_NOT_ELIGIBLE', `subaccounts: ${foreign} is not a sub-account of the owner wallet`);
259
+ }
260
+ }
261
+ async fromRecord(record) {
262
+ // A record from a newer SDK is unreadable here; leave it in place.
263
+ assertRecordVersion(record);
264
+ const publicKey = record.publicKey;
265
+ if (!isRegistered(record)) {
266
+ // `open()` in another tab may have registered it since it was listed.
267
+ // Only a complete record is read again, so this cannot loop.
268
+ const latest = await this.storage.get(publicKey);
269
+ if (latest != null && isRegistered(latest)) {
270
+ return await this.fromRecord(latest);
271
+ }
272
+ await this.storage.delete(publicKey);
273
+ return undefined;
274
+ }
275
+ const { grant, grantId, ownerSignature, signatureChainId } = record;
276
+ if (grant.environment !== this.environment ||
277
+ grant.paradexChain !== this.paradexChain) {
278
+ // Another environment's session: leave it for that connector.
279
+ return undefined;
280
+ }
281
+ try {
282
+ assertGrantActive(grant, this.now());
283
+ }
284
+ catch (error) {
285
+ if (error instanceof SessionGrantError &&
286
+ error.code === 'GRANT_EXPIRED') {
287
+ await this.storage.delete(publicKey);
288
+ return undefined;
289
+ }
290
+ throw error;
291
+ }
292
+ if (grant.sessionKey !== publicKey) {
293
+ await this.storage.delete(publicKey);
294
+ return undefined;
295
+ }
296
+ return {
297
+ grantId,
298
+ grant,
299
+ key: SessionKey.fromRecord(record),
300
+ ownerSignature,
301
+ signatureChainId,
302
+ };
303
+ }
304
+ }
@@ -0,0 +1,68 @@
1
+ import * as Starknet from 'starknet';
2
+ import type { SessionGrant } from './session-typed-data.js';
3
+ import type { Hex } from './types.js';
4
+ /** Throws for a record written in a format this SDK cannot read. */
5
+ export declare function assertRecordVersion(record: Pick<StoredSession, 'version'>): void;
6
+ export interface StoredSession {
7
+ readonly version: 1;
8
+ /** The session public key; also the storage id. */
9
+ readonly publicKey: Hex;
10
+ readonly wrappingKey: CryptoKey;
11
+ readonly iv: Uint8Array;
12
+ readonly ciphertext: Uint8Array;
13
+ readonly createdAt: number;
14
+ /** Set once the owner has signed the grant. */
15
+ readonly grant?: SessionGrant;
16
+ readonly ownerSignature?: Hex;
17
+ readonly signatureChainId?: number;
18
+ /** Set once the server has registered the grant. */
19
+ readonly grantId?: string;
20
+ }
21
+ /**
22
+ * Where encrypted sessions live. Records must be stored by structured clone
23
+ * (IndexedDB does this) so the `CryptoKey` stays non-extractable.
24
+ */
25
+ export interface SessionStorage {
26
+ get: (publicKey: string) => Promise<StoredSession | undefined>;
27
+ put: (record: StoredSession) => Promise<void>;
28
+ delete: (publicKey: string) => Promise<void>;
29
+ list: () => Promise<StoredSession[]>;
30
+ }
31
+ /** In-memory storage: nothing survives a reload. Useful for bots and tests. */
32
+ export declare function memorySessionStorage(): SessionStorage;
33
+ export interface IndexedDbSessionStorageOptions {
34
+ readonly dbName?: string;
35
+ readonly storeName?: string;
36
+ readonly indexedDB?: IDBFactory;
37
+ }
38
+ /** Browser storage backed by IndexedDB. */
39
+ export declare function indexedDbSessionStorage(options?: IndexedDbSessionStorageOptions): SessionStorage;
40
+ /**
41
+ * A session's Stark key, generated in the page and kept encrypted at rest.
42
+ *
43
+ * The private key is encrypted with AES-GCM under a non-extractable WebCrypto
44
+ * key. Storage holds the `CryptoKey` handle and the ciphertext; script can use
45
+ * the handle but cannot read the AES key out of it. The private key is
46
+ * decrypted only for the duration of a signature and the plaintext buffer is
47
+ * zeroed afterwards.
48
+ *
49
+ * @experimental
50
+ */
51
+ export declare class SessionKey {
52
+ #private;
53
+ readonly publicKey: Hex;
54
+ private constructor();
55
+ /** The encrypted record, for storage. */
56
+ get record(): StoredSession;
57
+ /** Generates a key pair and encrypts the private key. Nothing is stored. */
58
+ static generate(): Promise<SessionKey>;
59
+ /** Wraps a stored record. The key is checked on first use. */
60
+ static fromRecord(record: StoredSession): SessionKey;
61
+ /** Returns a copy of this key carrying updated metadata. */
62
+ withMetadata(metadata: Pick<StoredSession, 'grant' | 'ownerSignature' | 'signatureChainId' | 'grantId'>): SessionKey;
63
+ private withPrivateKey;
64
+ /** Signs a felt hash. Returns `[r, s]` as decimal strings. */
65
+ signHash(hash: string): Promise<[string, string]>;
66
+ /** Signs SNIP-12 typed data on behalf of `account`. */
67
+ signTypedData(typedData: Starknet.TypedData, account: string): Promise<[string, string]>;
68
+ }