@paradex/sdk 0.8.0 → 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 +81 -8
- package/dist/account.js +304 -14
- package/dist/client.d.ts +13 -4
- package/dist/client.js +12 -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-account-support.js +23 -1
- package/dist/starknet-signer.d.ts +3 -4
- package/dist/starknet-signer.js +10 -14
- package/package.json +6 -6
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
2
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
4
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
5
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
6
|
+
};
|
|
7
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
8
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
9
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
|
+
};
|
|
12
|
+
var _SessionKey_record;
|
|
13
|
+
import * as Starknet from 'starknet';
|
|
14
|
+
/** Throws for a record written in a format this SDK cannot read. */
|
|
15
|
+
export function assertRecordVersion(record) {
|
|
16
|
+
if (record.version !== 1) {
|
|
17
|
+
throw new Error(`Unsupported session record version ${String(record.version)}`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** In-memory storage: nothing survives a reload. Useful for bots and tests. */
|
|
21
|
+
export function memorySessionStorage() {
|
|
22
|
+
const records = new Map();
|
|
23
|
+
return {
|
|
24
|
+
get: async (publicKey) => records.get(publicKey),
|
|
25
|
+
put: async (record) => {
|
|
26
|
+
records.set(record.publicKey, record);
|
|
27
|
+
},
|
|
28
|
+
delete: async (publicKey) => {
|
|
29
|
+
records.delete(publicKey);
|
|
30
|
+
},
|
|
31
|
+
list: async () => [...records.values()],
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
async function promisify(request) {
|
|
35
|
+
return await new Promise((resolve, reject) => {
|
|
36
|
+
request.onsuccess = () => {
|
|
37
|
+
resolve(request.result);
|
|
38
|
+
};
|
|
39
|
+
request.onerror = () => {
|
|
40
|
+
reject(request.error ?? new Error('IndexedDB request failed'));
|
|
41
|
+
};
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/** Browser storage backed by IndexedDB. */
|
|
45
|
+
export function indexedDbSessionStorage(options = {}) {
|
|
46
|
+
const dbName = options.dbName ?? 'paradex-sessions';
|
|
47
|
+
const storeName = options.storeName ?? 'sessions';
|
|
48
|
+
const factory = options.indexedDB ?? globalThis.indexedDB;
|
|
49
|
+
if (factory == null) {
|
|
50
|
+
throw new Error('IndexedDB is not available; pass a SessionStorage');
|
|
51
|
+
}
|
|
52
|
+
let db;
|
|
53
|
+
const open = async () => {
|
|
54
|
+
db ?? (db = new Promise((resolve, reject) => {
|
|
55
|
+
const request = factory.open(dbName, 1);
|
|
56
|
+
request.onupgradeneeded = () => {
|
|
57
|
+
request.result.createObjectStore(storeName, { keyPath: 'publicKey' });
|
|
58
|
+
};
|
|
59
|
+
request.onsuccess = () => {
|
|
60
|
+
const opened = request.result;
|
|
61
|
+
// Another tab upgrading or the browser closing the connection: reopen
|
|
62
|
+
// on next use instead of failing every later transaction.
|
|
63
|
+
const reset = () => {
|
|
64
|
+
opened.close();
|
|
65
|
+
db = undefined;
|
|
66
|
+
};
|
|
67
|
+
opened.onversionchange = reset;
|
|
68
|
+
opened.onclose = reset;
|
|
69
|
+
resolve(opened);
|
|
70
|
+
};
|
|
71
|
+
request.onerror = () => {
|
|
72
|
+
db = undefined;
|
|
73
|
+
reject(request.error ?? new Error('Failed to open IndexedDB'));
|
|
74
|
+
};
|
|
75
|
+
}));
|
|
76
|
+
return await db;
|
|
77
|
+
};
|
|
78
|
+
const store = async (mode) => (await open()).transaction(storeName, mode).objectStore(storeName);
|
|
79
|
+
return {
|
|
80
|
+
get: async (publicKey) => (await promisify((await store('readonly')).get(publicKey))),
|
|
81
|
+
put: async (record) => {
|
|
82
|
+
await promisify((await store('readwrite')).put(record));
|
|
83
|
+
},
|
|
84
|
+
delete: async (publicKey) => {
|
|
85
|
+
await promisify((await store('readwrite')).delete(publicKey));
|
|
86
|
+
},
|
|
87
|
+
list: async () => (await promisify((await store('readonly')).getAll())),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
function subtle() {
|
|
91
|
+
const s = globalThis.crypto?.subtle;
|
|
92
|
+
if (s == null) {
|
|
93
|
+
throw new Error('WebCrypto is not available (needs a secure context)');
|
|
94
|
+
}
|
|
95
|
+
return s;
|
|
96
|
+
}
|
|
97
|
+
const textEncoder = new TextEncoder();
|
|
98
|
+
function toBufferSource(bytes) {
|
|
99
|
+
return new Uint8Array(bytes);
|
|
100
|
+
}
|
|
101
|
+
/** `plaintext` is passed to WebCrypto as is, so no unzeroed copy is made. */
|
|
102
|
+
async function encrypt(key, iv, publicKey, plaintext) {
|
|
103
|
+
return new Uint8Array(await subtle().encrypt({
|
|
104
|
+
name: 'AES-GCM',
|
|
105
|
+
iv: toBufferSource(iv),
|
|
106
|
+
additionalData: textEncoder.encode(publicKey),
|
|
107
|
+
}, key, plaintext));
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* A session's Stark key, generated in the page and kept encrypted at rest.
|
|
111
|
+
*
|
|
112
|
+
* The private key is encrypted with AES-GCM under a non-extractable WebCrypto
|
|
113
|
+
* key. Storage holds the `CryptoKey` handle and the ciphertext; script can use
|
|
114
|
+
* the handle but cannot read the AES key out of it. The private key is
|
|
115
|
+
* decrypted only for the duration of a signature and the plaintext buffer is
|
|
116
|
+
* zeroed afterwards.
|
|
117
|
+
*
|
|
118
|
+
* @experimental
|
|
119
|
+
*/
|
|
120
|
+
export class SessionKey {
|
|
121
|
+
constructor(record) {
|
|
122
|
+
_SessionKey_record.set(this, void 0);
|
|
123
|
+
this.publicKey = record.publicKey;
|
|
124
|
+
__classPrivateFieldSet(this, _SessionKey_record, record, "f");
|
|
125
|
+
}
|
|
126
|
+
/** The encrypted record, for storage. */
|
|
127
|
+
get record() {
|
|
128
|
+
return __classPrivateFieldGet(this, _SessionKey_record, "f");
|
|
129
|
+
}
|
|
130
|
+
/** Generates a key pair and encrypts the private key. Nothing is stored. */
|
|
131
|
+
static async generate() {
|
|
132
|
+
const privateKey = Starknet.ec.starkCurve.utils.randomPrivateKey();
|
|
133
|
+
try {
|
|
134
|
+
const publicKey = Starknet.num.toHex(Starknet.ec.starkCurve.getStarkKey(privateKey));
|
|
135
|
+
const wrappingKey = await subtle().generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
136
|
+
const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
|
|
137
|
+
const ciphertext = await encrypt(wrappingKey, iv, publicKey, privateKey);
|
|
138
|
+
return new SessionKey({
|
|
139
|
+
version: 1,
|
|
140
|
+
publicKey,
|
|
141
|
+
wrappingKey,
|
|
142
|
+
iv,
|
|
143
|
+
ciphertext,
|
|
144
|
+
createdAt: Date.now(),
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
privateKey.fill(0);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** Wraps a stored record. The key is checked on first use. */
|
|
152
|
+
static fromRecord(record) {
|
|
153
|
+
assertRecordVersion(record);
|
|
154
|
+
if (record.wrappingKey.extractable) {
|
|
155
|
+
throw new Error('Session wrapping key must be non-extractable');
|
|
156
|
+
}
|
|
157
|
+
return new SessionKey(record);
|
|
158
|
+
}
|
|
159
|
+
/** Returns a copy of this key carrying updated metadata. */
|
|
160
|
+
withMetadata(metadata) {
|
|
161
|
+
return new SessionKey({ ...__classPrivateFieldGet(this, _SessionKey_record, "f"), ...metadata });
|
|
162
|
+
}
|
|
163
|
+
async withPrivateKey(fn) {
|
|
164
|
+
const { wrappingKey, iv, ciphertext } = __classPrivateFieldGet(this, _SessionKey_record, "f");
|
|
165
|
+
const plaintext = new Uint8Array(await subtle().decrypt({
|
|
166
|
+
name: 'AES-GCM',
|
|
167
|
+
iv: toBufferSource(iv),
|
|
168
|
+
additionalData: textEncoder.encode(this.publicKey),
|
|
169
|
+
}, wrappingKey, toBufferSource(ciphertext)));
|
|
170
|
+
try {
|
|
171
|
+
return fn(plaintext);
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
plaintext.fill(0);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/** Signs a felt hash. Returns `[r, s]` as decimal strings. */
|
|
178
|
+
async signHash(hash) {
|
|
179
|
+
const signature = await this.withPrivateKey((key) => Starknet.ec.starkCurve.sign(Starknet.num.toHex(hash), key));
|
|
180
|
+
return [signature.r.toString(), signature.s.toString()];
|
|
181
|
+
}
|
|
182
|
+
/** Signs SNIP-12 typed data on behalf of `account`. */
|
|
183
|
+
async signTypedData(typedData, account) {
|
|
184
|
+
return await this.signHash(Starknet.typedData.getMessageHash(typedData, account));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
_SessionKey_record = new WeakMap();
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { type Eip712TypedData } from './eip712.js';
|
|
2
|
+
import type { Hex } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Who signs the session grant: the account owner's EVM wallet.
|
|
5
|
+
*
|
|
6
|
+
* Two implementations ship: {@link eip1193OwnerSigner} for browser wallets,
|
|
7
|
+
* and {@link externalOwnerSigner} for signers that live elsewhere, such as an
|
|
8
|
+
* MPC provider signing with its own infrastructure.
|
|
9
|
+
*
|
|
10
|
+
* @experimental
|
|
11
|
+
*/
|
|
12
|
+
export interface SessionOwnerSigner {
|
|
13
|
+
/**
|
|
14
|
+
* The EVM chain the signature is bound to: the wallet's *current* chain.
|
|
15
|
+
* It becomes the EIP-712 domain `chainId` and is sent to the server as
|
|
16
|
+
* `signature_chain_id`, so the user never has to switch networks.
|
|
17
|
+
*/
|
|
18
|
+
getChainId: () => Promise<number>;
|
|
19
|
+
/**
|
|
20
|
+
* Signs the grant. `digest` is the EIP-712 hash of `typedData`, for
|
|
21
|
+
* signers that sign raw hashes. Must return a 65-byte `r‖s‖v` signature.
|
|
22
|
+
*/
|
|
23
|
+
signTypedData: (request: OwnerSignRequest) => Promise<string>;
|
|
24
|
+
/**
|
|
25
|
+
* The owner wallet's address. Optional: when present, `SessionConnector`
|
|
26
|
+
* checks a grant's subaccounts against the wallet's before it signs.
|
|
27
|
+
*/
|
|
28
|
+
getAddress?: () => Promise<string>;
|
|
29
|
+
}
|
|
30
|
+
export interface OwnerSignRequest {
|
|
31
|
+
readonly typedData: Eip712TypedData;
|
|
32
|
+
readonly digest: Hex;
|
|
33
|
+
}
|
|
34
|
+
/** The subset of an EIP-1193 provider used here. */
|
|
35
|
+
export interface Eip1193Provider {
|
|
36
|
+
request: (args: {
|
|
37
|
+
readonly method: string;
|
|
38
|
+
readonly params?: readonly unknown[];
|
|
39
|
+
}) => Promise<unknown>;
|
|
40
|
+
}
|
|
41
|
+
export interface Eip1193OwnerSignerParams {
|
|
42
|
+
readonly provider: Eip1193Provider;
|
|
43
|
+
/** The owner wallet address. Defaults to the wallet's first account. */
|
|
44
|
+
readonly address?: string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Default owner signer: an injected wallet (`window.ethereum`) or any
|
|
48
|
+
* EIP-1193 provider, signing with `eth_signTypedData_v4`.
|
|
49
|
+
*/
|
|
50
|
+
export declare function eip1193OwnerSigner({ provider, address, }: Eip1193OwnerSignerParams): SessionOwnerSigner;
|
|
51
|
+
export interface ExternalOwnerSignerParams {
|
|
52
|
+
/** The EVM chain id the external signer binds signatures to. */
|
|
53
|
+
readonly chainId: number | (() => Promise<number>);
|
|
54
|
+
/** Signs the typed data (or its digest) with the partner's infrastructure. */
|
|
55
|
+
readonly sign: (request: OwnerSignRequest) => Promise<string>;
|
|
56
|
+
/** The owner wallet's address, if known. */
|
|
57
|
+
readonly address?: string;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Hook for signers outside the page, e.g. an MPC partner. The SDK hands over
|
|
61
|
+
* the EIP-712 typed data and its digest; the partner returns the signature.
|
|
62
|
+
*/
|
|
63
|
+
export declare function externalOwnerSigner({ chainId, sign, address, }: ExternalOwnerSignerParams): SessionOwnerSigner;
|
|
64
|
+
/**
|
|
65
|
+
* Accepts only 65-byte EOA signatures. ERC-1271 and ERC-6492 contract
|
|
66
|
+
* signatures are longer; the server refuses them, so fail before submitting.
|
|
67
|
+
*/
|
|
68
|
+
export declare function assertEoaSignature(signature: string): Hex;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { toEthSignTypedDataV4 } from './eip712.js';
|
|
2
|
+
function parseChainId(value) {
|
|
3
|
+
let n = Number.NaN;
|
|
4
|
+
if (typeof value === 'number')
|
|
5
|
+
n = value;
|
|
6
|
+
else if (typeof value === 'string' && /^(0x[0-9a-fA-F]+|[0-9]+)$/.test(value))
|
|
7
|
+
n = Number(BigInt(value));
|
|
8
|
+
if (!Number.isSafeInteger(n) || n <= 0) {
|
|
9
|
+
throw new Error(`Wallet returned an invalid chain id: ${String(value)}`);
|
|
10
|
+
}
|
|
11
|
+
return n;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Default owner signer: an injected wallet (`window.ethereum`) or any
|
|
15
|
+
* EIP-1193 provider, signing with `eth_signTypedData_v4`.
|
|
16
|
+
*/
|
|
17
|
+
export function eip1193OwnerSigner({ provider, address, }) {
|
|
18
|
+
const resolveAddress = async () => {
|
|
19
|
+
if (address != null)
|
|
20
|
+
return address;
|
|
21
|
+
const accounts = await provider.request({ method: 'eth_requestAccounts' });
|
|
22
|
+
const first = Array.isArray(accounts) ? accounts[0] : undefined;
|
|
23
|
+
if (typeof first !== 'string') {
|
|
24
|
+
throw new Error('Wallet returned no accounts');
|
|
25
|
+
}
|
|
26
|
+
return first;
|
|
27
|
+
};
|
|
28
|
+
return {
|
|
29
|
+
getChainId: async () => parseChainId(await provider.request({ method: 'eth_chainId' })),
|
|
30
|
+
getAddress: resolveAddress,
|
|
31
|
+
signTypedData: async ({ typedData }) => {
|
|
32
|
+
const from = await resolveAddress();
|
|
33
|
+
const signature = await provider.request({
|
|
34
|
+
method: 'eth_signTypedData_v4',
|
|
35
|
+
params: [from, toEthSignTypedDataV4(typedData)],
|
|
36
|
+
});
|
|
37
|
+
if (typeof signature !== 'string') {
|
|
38
|
+
throw new Error('Wallet returned a non-string signature');
|
|
39
|
+
}
|
|
40
|
+
return signature;
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Hook for signers outside the page, e.g. an MPC partner. The SDK hands over
|
|
46
|
+
* the EIP-712 typed data and its digest; the partner returns the signature.
|
|
47
|
+
*/
|
|
48
|
+
export function externalOwnerSigner({ chainId, sign, address, }) {
|
|
49
|
+
return {
|
|
50
|
+
getChainId: async () => parseChainId(typeof chainId === 'function' ? await chainId() : chainId),
|
|
51
|
+
signTypedData: sign,
|
|
52
|
+
...(address != null ? { getAddress: async () => address } : {}),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Accepts only 65-byte EOA signatures. ERC-1271 and ERC-6492 contract
|
|
57
|
+
* signatures are longer; the server refuses them, so fail before submitting.
|
|
58
|
+
*/
|
|
59
|
+
export function assertEoaSignature(signature) {
|
|
60
|
+
if (!/^0x[0-9a-fA-F]{130}$/.test(signature)) {
|
|
61
|
+
throw new Error('Owner signature must be a 65-byte EOA signature; contract wallets are not supported');
|
|
62
|
+
}
|
|
63
|
+
return signature.toLowerCase();
|
|
64
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { SessionEnvironment } from './session-typed-data.js';
|
|
2
|
+
/**
|
|
3
|
+
* HTTP and WebSocket plumbing for sessions, injectable so tests (and
|
|
4
|
+
* non-browser runtimes) can supply their own.
|
|
5
|
+
*
|
|
6
|
+
* @experimental
|
|
7
|
+
*/
|
|
8
|
+
export interface HttpRequest {
|
|
9
|
+
readonly method: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
10
|
+
readonly url: string;
|
|
11
|
+
readonly headers: Record<string, string>;
|
|
12
|
+
readonly body?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface HttpResponse {
|
|
15
|
+
readonly status: number;
|
|
16
|
+
readonly body: unknown;
|
|
17
|
+
}
|
|
18
|
+
export type HttpTransport = (request: HttpRequest) => Promise<HttpResponse>;
|
|
19
|
+
/** Default transport on top of global `fetch`. */
|
|
20
|
+
export declare const fetchTransport: HttpTransport;
|
|
21
|
+
/** The subset of the WHATWG `WebSocket` used here. */
|
|
22
|
+
export interface WebSocketLike {
|
|
23
|
+
readonly readyState: number;
|
|
24
|
+
send: (data: string) => void;
|
|
25
|
+
close: (code?: number, reason?: string) => void;
|
|
26
|
+
onopen: ((event: unknown) => void) | null;
|
|
27
|
+
onmessage: ((event: {
|
|
28
|
+
readonly data: unknown;
|
|
29
|
+
}) => void) | null;
|
|
30
|
+
onclose: ((event: unknown) => void) | null;
|
|
31
|
+
onerror: ((event: unknown) => void) | null;
|
|
32
|
+
}
|
|
33
|
+
export type WebSocketFactory = (url: string) => WebSocketLike;
|
|
34
|
+
export declare const defaultWebSocketFactory: WebSocketFactory;
|
|
35
|
+
export declare function defaultApiUrl(environment: SessionEnvironment): string;
|
|
36
|
+
export declare function defaultWsUrl(environment: SessionEnvironment): string;
|
|
37
|
+
/**
|
|
38
|
+
* Error codes the session endpoints are known to return. Servers may add
|
|
39
|
+
* codes, so `SessionApiError.code` can hold any string.
|
|
40
|
+
*/
|
|
41
|
+
export type KnownSessionApiErrorCode = 'INVALID_SIGNATURE' | 'GRANT_EXPIRED' | 'INVALID_ENVIRONMENT' | 'INVALID_CHAIN' | 'SCOPE_NOT_ALLOWED' | 'LIMIT_INVALID' | 'NONCE_REUSED' | 'ACCOUNT_NOT_ELIGIBLE' | 'INVALID_GRANT' | 'SESSION_KEY_IN_USE' | 'SESSION_LIMIT_REACHED' | 'BUILDER_APPROVAL_LIMIT_REACHED' | 'BUILDER_APPROVAL_STALE' | 'SESSIONS_DISABLED' | 'INVALID_MARKETING_CODE' | 'INVALID_REQUEST_PARAMETER' | 'INSUFFICIENT_MIN_CHAIN_BALANCE' | 'ETHEREUM_ADDRESS_BLOCKED' | 'PARENT_ADDRESS_ALREADY_ONBOARDED' | 'ONBOARDING_RATE_LIMITED' | 'SESSION_REVOKED' | 'SESSION_EXPIRED' | 'NOT_ONBOARDED' | 'INVALID_TOKEN' | 'INVALID_SUBKEY' | 'STARKNET_SIGNATURE_VERIFICATION_FAILED' | 'INVALID_TOKEN_SCOPE' | 'REQUEST_NOT_ALLOWED' | 'IP_NOT_ALLOWED' | 'NOT_FOUND' | 'INVALID_RESPONSE';
|
|
42
|
+
export type SessionApiErrorCode = KnownSessionApiErrorCode | (string & {});
|
|
43
|
+
export declare class SessionApiError extends Error {
|
|
44
|
+
readonly status: number;
|
|
45
|
+
readonly code: SessionApiErrorCode | undefined;
|
|
46
|
+
readonly body: unknown;
|
|
47
|
+
constructor(status: number, body: unknown);
|
|
48
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Default transport on top of global `fetch`. */
|
|
2
|
+
export const fetchTransport = async (request) => {
|
|
3
|
+
const response = await fetch(request.url, {
|
|
4
|
+
method: request.method,
|
|
5
|
+
headers: request.headers,
|
|
6
|
+
body: request.body,
|
|
7
|
+
});
|
|
8
|
+
const text = await response.text();
|
|
9
|
+
let body = text;
|
|
10
|
+
if (text !== '') {
|
|
11
|
+
try {
|
|
12
|
+
body = JSON.parse(text);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
// Leave non-JSON bodies as text.
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return { status: response.status, body };
|
|
19
|
+
};
|
|
20
|
+
export const defaultWebSocketFactory = (url) => {
|
|
21
|
+
if (typeof globalThis.WebSocket !== 'function') {
|
|
22
|
+
throw new Error('WebSocket is not available; pass a webSocketFactory');
|
|
23
|
+
}
|
|
24
|
+
return new globalThis.WebSocket(url);
|
|
25
|
+
};
|
|
26
|
+
/** The API host label: `prod` for mainnet, otherwise the environment name. */
|
|
27
|
+
function hostLabel(environment) {
|
|
28
|
+
if (!/^[a-z][a-z0-9-]*$/.test(environment)) {
|
|
29
|
+
throw new Error(`Invalid environment: ${environment}`);
|
|
30
|
+
}
|
|
31
|
+
return environment === 'mainnet' ? 'prod' : environment;
|
|
32
|
+
}
|
|
33
|
+
export function defaultApiUrl(environment) {
|
|
34
|
+
return `https://api.${hostLabel(environment)}.paradex.trade`;
|
|
35
|
+
}
|
|
36
|
+
export function defaultWsUrl(environment) {
|
|
37
|
+
return `wss://ws.api.${hostLabel(environment)}.paradex.trade/v1`;
|
|
38
|
+
}
|
|
39
|
+
export class SessionApiError extends Error {
|
|
40
|
+
constructor(status, body) {
|
|
41
|
+
const record = body != null && typeof body === 'object'
|
|
42
|
+
? body
|
|
43
|
+
: {};
|
|
44
|
+
const code = typeof record.error === 'string' ? record.error : undefined;
|
|
45
|
+
const message = typeof record.message === 'string'
|
|
46
|
+
? record.message
|
|
47
|
+
: typeof body === 'string' && body !== ''
|
|
48
|
+
? body
|
|
49
|
+
: `HTTP ${status}`;
|
|
50
|
+
super(code != null ? `${code}: ${message}` : message);
|
|
51
|
+
this.name = 'SessionApiError';
|
|
52
|
+
this.status = status;
|
|
53
|
+
this.code = code;
|
|
54
|
+
this.body = body;
|
|
55
|
+
}
|
|
56
|
+
}
|