@tuwaio/quasar-sdk 1.0.0-fix-docs-alpha.7.481db45 → 1.0.0-fix-docs-alpha.9.40e8658

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 @@
1
+ 'use strict';var zustand=require('zustand'),middleware=require('zustand/middleware');var d=(a=>(a.EVM="EVM",a.SOLANA="SOLANA",a))(d||{});var S=300*1e3,f=60*1e3;function m(e){return `Mini-Session Login: ${e}`}async function y(e){let t=new Date().toISOString(),a=m(t);if(e.chainType==="EVM"){let n=e.signer;try{return {signature:await n.signMessage({account:e.walletAddress,message:a}),timestamp:t}}catch(s){throw new Error(`[SDK] EVM signing failed: ${s.message}`,{cause:s})}}if(e.chainType==="SOLANA"){let n=e.signer,s;try{s=await import('gill');}catch(r){throw new Error('[SDK] Peer dependency "gill" is required for Solana signing.',{cause:r})}try{let i=s.getUtf8Encoder().encode(a),g;if(n.modifyAndSignMessages){let o=s.createSignableMessage(i),[l]=await n.modifyAndSignMessages([o]),u=l.signatures[n.address];if(!u)throw new Error(`[SDK] Signature missing for address: ${n.address}`);g=u;}else if(n.signMessages){let[o]=await n.signMessages([i]);if(!o?.signature)throw new Error("[SDK] Wallet returned invalid signMessages output.");g=o.signature;}else if(n.signMessage)g=await n.signMessage(i);else throw new Error("[SDK] Signer lacks message signing capabilities.");return {signature:s.getSignatureFromBytes(g),timestamp:t}}catch(r){throw new Error(`[SDK] Solana signing failed: ${r.message}`,{cause:r})}}throw new Error(`[SDK] Unsupported chain type: ${e.chainType}`)}async function P(e){let t=new Date(e.timestamp).getTime(),a=Date.now();if(isNaN(t))throw new Error("[SDK] Invalid timestamp format. Use ISO string.");let n=e.maxAge??S;if(a-t>n)throw new Error("[SDK] Signature expired. Please sign a fresh message.");if(t>a+f)throw new Error("[SDK] Timestamp is in the future. Check your system clock.");let s=m(e.timestamp);if(e.chainType==="EVM"){let r;try{r=await import('viem');}catch(i){throw new Error('[SDK] Peer dependency "viem" is required for EVM verification.',{cause:i})}return await r.verifyMessage({address:e.walletAddress,message:s,signature:e.signature})}if(e.chainType==="SOLANA"){let r;try{r=await import('gill');}catch(i){throw new Error('[SDK] Peer dependency "gill" is required for Solana verification.',{cause:i})}try{let i=r.address(e.walletAddress);return await r.verifySignatureForAddress(i,e.signature,s)}catch{return false}}return false}function k(e="mini-session-storage"){return zustand.create()(middleware.persist(t=>({miniSession:null,setMiniSession:a=>t({miniSession:a}),clearSession:()=>t({miniSession:null})}),{name:e}))}async function C(e,t){let{isConnected:a,address:n,chainType:s,signer:r}=e;if(!a||!n)throw new Error("[SDK] Wallet not connected. Please connect your wallet first.");let i=t.miniSession;if(i&&i.walletAddress===n&&i.chainType===s){let o=Date.now(),l=new Date(i.timestamp).getTime();if(o-l<S)return i}let c={...await y({signer:r,walletAddress:n,chainType:s}),chainType:s,walletAddress:n};return t.setMiniSession(c),c}exports.a=d;exports.b=S;exports.c=m;exports.d=y;exports.e=P;exports.f=k;exports.g=C;
@@ -0,0 +1 @@
1
+ import {create}from'zustand';import {persist}from'zustand/middleware';var d=(a=>(a.EVM="EVM",a.SOLANA="SOLANA",a))(d||{});var S=300*1e3,f=60*1e3;function m(e){return `Mini-Session Login: ${e}`}async function y(e){let t=new Date().toISOString(),a=m(t);if(e.chainType==="EVM"){let n=e.signer;try{return {signature:await n.signMessage({account:e.walletAddress,message:a}),timestamp:t}}catch(s){throw new Error(`[SDK] EVM signing failed: ${s.message}`,{cause:s})}}if(e.chainType==="SOLANA"){let n=e.signer,s;try{s=await import('gill');}catch(r){throw new Error('[SDK] Peer dependency "gill" is required for Solana signing.',{cause:r})}try{let i=s.getUtf8Encoder().encode(a),g;if(n.modifyAndSignMessages){let o=s.createSignableMessage(i),[l]=await n.modifyAndSignMessages([o]),u=l.signatures[n.address];if(!u)throw new Error(`[SDK] Signature missing for address: ${n.address}`);g=u;}else if(n.signMessages){let[o]=await n.signMessages([i]);if(!o?.signature)throw new Error("[SDK] Wallet returned invalid signMessages output.");g=o.signature;}else if(n.signMessage)g=await n.signMessage(i);else throw new Error("[SDK] Signer lacks message signing capabilities.");return {signature:s.getSignatureFromBytes(g),timestamp:t}}catch(r){throw new Error(`[SDK] Solana signing failed: ${r.message}`,{cause:r})}}throw new Error(`[SDK] Unsupported chain type: ${e.chainType}`)}async function P(e){let t=new Date(e.timestamp).getTime(),a=Date.now();if(isNaN(t))throw new Error("[SDK] Invalid timestamp format. Use ISO string.");let n=e.maxAge??S;if(a-t>n)throw new Error("[SDK] Signature expired. Please sign a fresh message.");if(t>a+f)throw new Error("[SDK] Timestamp is in the future. Check your system clock.");let s=m(e.timestamp);if(e.chainType==="EVM"){let r;try{r=await import('viem');}catch(i){throw new Error('[SDK] Peer dependency "viem" is required for EVM verification.',{cause:i})}return await r.verifyMessage({address:e.walletAddress,message:s,signature:e.signature})}if(e.chainType==="SOLANA"){let r;try{r=await import('gill');}catch(i){throw new Error('[SDK] Peer dependency "gill" is required for Solana verification.',{cause:i})}try{let i=r.address(e.walletAddress);return await r.verifySignatureForAddress(i,e.signature,s)}catch{return false}}return false}function k(e="mini-session-storage"){return create()(persist(t=>({miniSession:null,setMiniSession:a=>t({miniSession:a}),clearSession:()=>t({miniSession:null})}),{name:e}))}async function C(e,t){let{isConnected:a,address:n,chainType:s,signer:r}=e;if(!a||!n)throw new Error("[SDK] Wallet not connected. Please connect your wallet first.");let i=t.miniSession;if(i&&i.walletAddress===n&&i.chainType===s){let o=Date.now(),l=new Date(i.timestamp).getTime();if(o-l<S)return i}let c={...await y({signer:r,walletAddress:n,chainType:s}),chainType:s,walletAddress:n};return t.setMiniSession(c),c}export{d as a,S as b,m as c,y as d,P as e,k as f,C as g};
package/dist/index.d.mts CHANGED
@@ -1,219 +1,11 @@
1
1
  import { FetchOptions } from 'ofetch';
2
+ import { Q as QuasarConfig, H as HistoryQuery, P as PaginatedResult, V as VerifySessionParams, S as SignSessionParams, a as SignSessionResult, M as MiniSessionStore, C as ConnectionData, b as MiniSessionAuth } from './types-Ctaain6g.mjs';
3
+ export { c as ChainType, E as EvmSigner, d as SolanaSignedMessage, e as SolanaSigner } from './types-Ctaain6g.mjs';
2
4
  import { Transaction } from '@tuwaio/pulsar-core';
3
5
  export { Transaction, UpdatableTransactionFields } from '@tuwaio/pulsar-core';
4
6
  import * as zustand_middleware from 'zustand/middleware';
5
7
  import * as zustand from 'zustand';
6
8
 
7
- /**
8
- * @module types
9
- * @description Shared type definitions for the Quasar SDK.
10
- * Contains configuration interfaces, query parameters, paginated result structure,
11
- * and re-exports from `@tuwaio/pulsar-core`.
12
- */
13
-
14
- /**
15
- * Configuration options for initializing the {@link Quasar} SDK client.
16
- *
17
- * @public
18
- * @example
19
- * ```typescript
20
- * const config: QuasarConfig = {
21
- * secretKey: 'sk_live_abc123...',
22
- * baseUrl: 'https://api.tuwa.io',
23
- * timeout: 15000,
24
- * };
25
- * ```
26
- */
27
- interface QuasarConfig {
28
- /**
29
- * Your secret API key starting with `sk_live_`.
30
- *
31
- * @remarks
32
- * This key authenticates every request through the Iron Dome security perimeter.
33
- * It **MUST** be kept secure on the server side — never expose it in client-side bundles
34
- * as it grants full access to your organization's Quasar data.
35
- */
36
- secretKey: string;
37
- /**
38
- * Optional internal secret sent as `x-internal-secret` header on every request.
39
- *
40
- * @remarks
41
- * This is used for system-to-system communication between TUWA internal services.
42
- * Most third-party developers do not need to provide this.
43
- */
44
- internalSecret?: string;
45
- /**
46
- * The base URL of the Quasar Cloud API.
47
- *
48
- * @defaultValue `'https://api.tuwa.io'`
49
- */
50
- baseUrl?: string;
51
- /**
52
- * Request timeout in milliseconds for all API calls.
53
- *
54
- * @defaultValue `10000` (10 seconds)
55
- */
56
- timeout?: number;
57
- }
58
- /**
59
- * Query parameters for filtering and paginating transaction history.
60
- *
61
- * All fields are optional. When omitted, no filtering is applied to that field.
62
- *
63
- * @public
64
- * @example
65
- * ```typescript
66
- * const query: HistoryQuery = {
67
- * page: 1,
68
- * limit: 10,
69
- * chainId: 1, // Ethereum Mainnet
70
- * status: 'Success', // Only successful transactions
71
- * appName: 'Tuwa App', // Filter by application
72
- * };
73
- * ```
74
- */
75
- interface HistoryQuery {
76
- /**
77
- * Page number for pagination (1-indexed).
78
- *
79
- * @defaultValue `1`
80
- */
81
- page?: number;
82
- /**
83
- * Maximum number of results to return per page.
84
- *
85
- * @defaultValue `10`
86
- */
87
- limit?: number;
88
- /**
89
- * Filter by blockchain chain ID.
90
- *
91
- * @example `1` (Ethereum), `'solana'`, `'SN_MAIN'` (Starknet)
92
- */
93
- chainId?: string | number;
94
- /**
95
- * Filter by transaction status.
96
- *
97
- * @example `'pending'`, `'Success'`, `'Failed'`, `'Replaced'`
98
- */
99
- status?: string;
100
- /**
101
- * Filter by a specific unique transaction key assigned by Quasar.
102
- */
103
- txKey?: string;
104
- /**
105
- * Filter by the application name that synced the transaction.
106
- */
107
- appName?: string;
108
- /**
109
- * Filter by the sender's wallet address.
110
- */
111
- walletAddress?: string;
112
- }
113
- /**
114
- * Generic wrapper for paginated API responses.
115
- *
116
- * @typeParam T - The type of the documents contained in the result set.
117
- *
118
- * @public
119
- * @example
120
- * ```typescript
121
- * const result: PaginatedResult<Transaction> = await quasar.pulsar.getHistory();
122
- *
123
- * console.log(`Showing page ${result.page} of ${result.totalPages}`);
124
- * console.log(`Total transactions found: ${result.totalDocs}`);
125
- * ```
126
- */
127
- interface PaginatedResult<T> {
128
- /** Array of documents for the current page. */
129
- docs: T[];
130
- /** Total number of documents matching the query across all pages. */
131
- totalDocs: number;
132
- /** Total number of available pages based on the limit. */
133
- totalPages: number;
134
- /** The current page number (1-indexed). */
135
- page: number;
136
- /** Indicates if a subsequent page of results is available. */
137
- hasNextPage: boolean;
138
- /** Indicates if a preceding page of results is available. */
139
- hasPrevPage: boolean;
140
- }
141
-
142
- /**
143
- * Supported blockchain ecosystems for authentication.
144
- * @public
145
- */
146
- declare enum ChainType {
147
- EVM = "EVM",
148
- SOLANA = "SOLANA"
149
- }
150
- /**
151
- * Result of the Mini-Session signing process.
152
- * Used for both frontend-side caching and backend-side verification.
153
- * @public
154
- */
155
- interface MiniSessionAuth {
156
- /** The cryptographic signature (hex for EVM, base58 for Solana). */
157
- signature: string;
158
- /** ISO string timestamp used in the signed message. */
159
- timestamp: string;
160
- /** The blockchain ecosystem type. */
161
- chainType: ChainType;
162
- /** The wallet address that signed the message. */
163
- walletAddress: string;
164
- }
165
- /**
166
- * Parameters for verifying a mini-session signature.
167
- * @public
168
- */
169
- interface VerifySessionParams extends Omit<MiniSessionAuth, 'walletAddress'> {
170
- /** The wallet address that allegedly signed the message. */
171
- walletAddress: string;
172
- /**
173
- * Maximum allowed age for the signature in milliseconds.
174
- * Default: 5 minutes (300,000ms).
175
- */
176
- maxAge?: number;
177
- }
178
- /**
179
- * Parameters for signing a mini-session message.
180
- * @public
181
- */
182
- interface SignSessionParams {
183
- /** The signer object. For EVM, a `WalletClient`. For Solana, a `KeyPairSigner` or `TransactionSendingSigner`. */
184
- signer: any;
185
- /** The wallet address to sign with (required for EVM). */
186
- walletAddress?: string;
187
- /** The blockchain ecosystem type. */
188
- chainType: ChainType;
189
- }
190
- /**
191
- * Zustand store interface for managing Mini-Sessions.
192
- * @public
193
- */
194
- interface MiniSessionStore {
195
- /** Current active session or null. */
196
- miniSession: MiniSessionAuth | null;
197
- /** Sets the active session. */
198
- setMiniSession: (session: MiniSessionAuth | null) => void;
199
- /** Clears the current session. */
200
- clearSession: () => void;
201
- }
202
- /**
203
- * Minimum connection data required for Mini-Session signing.
204
- * @public
205
- */
206
- interface ConnectionData {
207
- /** Whether a wallet is currently connected. */
208
- isConnected: boolean;
209
- /** The active wallet address. */
210
- address: string;
211
- /** The blockchain ecosystem type. */
212
- chainType: ChainType;
213
- /** The wallet signer object (WalletClient for EVM, TransactionSendingSigner for Solana). */
214
- signer: any;
215
- }
216
-
217
9
  /**
218
10
  * @module core/client
219
11
  * @description Core HTTP client for the Quasar SDK.
@@ -406,12 +198,19 @@ declare class PulsarModule {
406
198
 
407
199
  /**
408
200
  * @module utils/auth
409
- * @description Security utilities for Mini-Session signature verification.
201
+ * @description Security utilities for Mini-Session signature creation and verification.
202
+ * Supports dual-ecosystem (EVM & Solana) authentication flows with strict type safety.
410
203
  */
411
204
 
412
205
  /**
413
- * Standardizes the message format for Mini-Session login.
414
- * Both frontend and backend must use this exact template.
206
+ * Default maximum allowed age for a signature (5 minutes).
207
+ * Prevents replay attacks using stale signatures.
208
+ * @internal
209
+ */
210
+ declare const DEFAULT_MAX_AGE: number;
211
+ /**
212
+ * Standardizes the message format for Mini-Session authentication.
213
+ * Both frontend and backend MUST use this exact template for verification to pass.
415
214
  *
416
215
  * @param timestamp - ISO string timestamp (e.g., `new Date().toISOString()`).
417
216
  * @returns The formatted message string to be signed.
@@ -423,50 +222,40 @@ declare class PulsarModule {
423
222
  * ```
424
223
  */
425
224
  declare function createMiniSessionMessage(timestamp: string): string;
426
- /**
427
- * Result of a mini-session signing operation.
428
- */
429
- interface SignSessionResult {
430
- /** The cryptographic signature. */
431
- signature: string;
432
- /** The ISO timestamp used to generate the message. */
433
- timestamp: string;
434
- }
435
225
  /**
436
226
  * Triggers a signature request in the connected wallet to create a Mini-Session.
437
227
  *
438
- * This is a frontend-friendly helper that:
439
- * 1. Generates a fresh ISO timestamp.
440
- * 2. Formats the standard login message.
441
- * 3. Triggers the wallet's signMessage method.
442
- * 4. Returns the signature and timestamp for verification on the backend.
228
+ * This function detects the signer's capabilities and uses the most appropriate
229
+ * signing method available (e.g., Web3 v2, Standard, or Legacy).
443
230
  *
444
- * @param params - The signing parameters including the signer and ecosystem type.
445
- * @returns A promise that resolves to the signature and timestamp.
446
- * @throws {Error} If the required peer dependencies are missing or signing fails.
231
+ * @param params - Parameters containing the signer and target ecosystem.
232
+ * @returns A promise resolving to the signature and timestamp.
233
+ * @throws {Error} If signing fails or the signer lacks required methods.
234
+ *
235
+ * @public
447
236
  */
448
237
  declare function signMiniSession(params: SignSessionParams): Promise<SignSessionResult>;
449
238
  /**
450
- * Verifies a Mini-Session signature to protect API quota from unauthorized access.
239
+ * Verifies a Mini-Session signature for authenticity and freshness.
240
+ *
241
+ * Performs cryptographic verification against the provided wallet address and
242
+ * ensures the signature hasn't expired according to the `maxAge` parameter.
451
243
  *
452
- * This utility performs three checks:
453
- * 1. Timestamp freshness (rejects if older than 5 minutes or in the future).
454
- * 2. Cryptographic validity (checks if the signature matches the wallet address and message).
455
- * 3. Ecosystem-specific logic (EVM via `viem`, Solana via `gill`).
244
+ * @param params - Verification data including signature and timestamp.
245
+ * @returns A promise resolving to true if the session is valid.
456
246
  *
457
- * @param params - The verification parameters including address, signature, and timestamp.
458
- * @returns A promise that resolves to `true` if the signature is valid and fresh.
459
- * @throws {Error} If the required peer dependencies (`viem` or `gill`) are missing.
460
- * @throws {Error} If the timestamp is invalid or expired.
247
+ * @public
461
248
  */
462
249
  declare function verifyMiniSession(params: VerifySessionParams): Promise<boolean>;
463
250
 
464
251
  /**
465
252
  * Creates a persistent Zustand store to cache Mini-Session signatures.
466
- * Requires `zustand` to be installed as a peer dependency.
253
+ * This is the recommended way to manage sessions in React applications.
254
+ *
255
+ * @param storageName - The localStorage key for persistence. Defaults to 'mini-session-storage'.
256
+ * @returns A Zustand store instance initialized with MiniSessionStore interface.
467
257
  *
468
- * @param storageName - Key name for localStorage persistence.
469
- * @returns A Zustand store instance.
258
+ * @public
470
259
  */
471
260
  declare function createMiniSessionStore(storageName?: string): zustand.UseBoundStore<Omit<zustand.StoreApi<MiniSessionStore>, "setState" | "persist"> & {
472
261
  setState(partial: MiniSessionStore | Partial<MiniSessionStore> | ((state: MiniSessionStore) => MiniSessionStore | Partial<MiniSessionStore>), replace?: false | undefined): unknown;
@@ -482,19 +271,22 @@ declare function createMiniSessionStore(storageName?: string): zustand.UseBoundS
482
271
  };
483
272
  }>;
484
273
  /**
485
- * Generic helper to manage Mini-Session signing and caching.
274
+ * High-level orchestrator to retrieve an existing Mini-Session or trigger a new signature.
486
275
  *
487
- * Checks the provided store for an existing session matching the current connection.
488
- * If no session is found, it triggers a signature request using the provided signer.
276
+ * This function checks the provided store for a valid, non-expired session matching
277
+ * the current wallet connection. If no session is found or it has expired, it
278
+ * triggers a signature request through the wallet.
489
279
  *
490
- * @param connection - Current active connection state.
491
- * @param store - An object compatible with MiniSessionStore to read/write the session.
492
- * @returns A promise resolving to the authenticated session.
493
- * @throws {Error} If no wallet is connected or signing fails.
280
+ * @param connection - The current active wallet connection data (address, signer, etc).
281
+ * @param store - A store implementation (Zustand or compatible) for session persistence.
282
+ * @returns A promise resolving to a valid MiniSessionAuth object.
283
+ * @throws {Error} If the wallet is disconnected or signing fails.
284
+ *
285
+ * @public
494
286
  */
495
287
  declare function getMiniSessionAuth(connection: ConnectionData, store: {
496
288
  miniSession: MiniSessionAuth | null;
497
- setMiniSession: (s: MiniSessionAuth) => void;
289
+ setMiniSession: (session: MiniSessionAuth | null) => void;
498
290
  }): Promise<MiniSessionAuth>;
499
291
 
500
292
  declare const BASE_API_URL = "https://api.tuwa.io";
@@ -639,4 +431,4 @@ declare class Quasar {
639
431
  constructor(config: QuasarConfig);
640
432
  }
641
433
 
642
- export { BASE_API_URL, ChainType, type ConnectionData, type HistoryQuery, type MiniSessionAuth, type MiniSessionStore, PULSAR_HISTORY_ENDPOINT, PULSAR_SYNC_ENDPOINT, type PaginatedResult, PulsarModule, Quasar, type QuasarConfig, QuasarSDKError, type SignSessionParams, type SignSessionResult, type VerifySessionParams, createMiniSessionMessage, createMiniSessionStore, getMiniSessionAuth, signMiniSession, utils, verifyMiniSession };
434
+ export { BASE_API_URL, ConnectionData, DEFAULT_MAX_AGE, HistoryQuery, MiniSessionAuth, MiniSessionStore, PULSAR_HISTORY_ENDPOINT, PULSAR_SYNC_ENDPOINT, PaginatedResult, PulsarModule, Quasar, QuasarConfig, QuasarSDKError, SignSessionParams, SignSessionResult, VerifySessionParams, createMiniSessionMessage, createMiniSessionStore, getMiniSessionAuth, signMiniSession, utils, verifyMiniSession };