sphere-connect 1.0.1

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,553 @@
1
+ import { Cedra, Account } from '@cedra-labs/ts-sdk';
2
+ export { Account, Cedra, CedraConfig, Network as CedraNetwork, Ed25519PrivateKey, PrivateKey, PrivateKeyVariants } from '@cedra-labs/ts-sdk';
3
+ import React, { ReactNode } from 'react';
4
+
5
+ /**
6
+ * Simple, browser-compatible EventEmitter implementation
7
+ * Removes dependency on Node.js 'events' module
8
+ */
9
+ declare class EventEmitter {
10
+ private listeners;
11
+ on(event: string, listener: Function): this;
12
+ off(event: string, listener: Function): this;
13
+ emit(event: string, ...args: any[]): boolean;
14
+ removeAllListeners(event?: string): this;
15
+ }
16
+
17
+ /**
18
+ * Type definitions for Sphere Account Abstraction SDK
19
+ */
20
+ type Network = 'mainnet' | 'testnet' | 'devnet';
21
+ interface SDKConfig {
22
+ /** Sphere network to connect to */
23
+ network?: Network;
24
+ /** Google OAuth Client ID */
25
+ googleClientId?: string;
26
+ /** Custom RPC endpoint */
27
+ rpcEndpoint?: string;
28
+ /** GraphQL indexer endpoint for querying blockchain data */
29
+ indexerUrl?: string;
30
+ /** Redirect URI for OAuth flows (optional) */
31
+ redirectUri?: string;
32
+ }
33
+ interface GoogleAuthResponse {
34
+ /** Google ID token (JWT) */
35
+ idToken: string;
36
+ /** User's email address */
37
+ email: string;
38
+ /** User's display name */
39
+ name?: string;
40
+ /** User's profile picture URL */
41
+ picture?: string;
42
+ /** Google user ID */
43
+ sub: string;
44
+ }
45
+ interface WalletInfo {
46
+ /** Cedra wallet address (32 bytes hex) */
47
+ address: string;
48
+ /** Public key (hex) */
49
+ publicKey: string;
50
+ /** Whether the account exists on-chain */
51
+ existsOnChain: boolean;
52
+ /** Current sequence number (nonce) */
53
+ sequenceNumber: string;
54
+ /** Authentication key */
55
+ authKey: string;
56
+ }
57
+ interface TransactionOptions {
58
+ /** Recipient address */
59
+ to: string;
60
+ /** Amount to send (in smallest unit, e.g., 100000000 = 1 CED) */
61
+ amount: number;
62
+ /** Optional coin type (defaults to CedraCoin) */
63
+ coinType?: string;
64
+ /** Optional max gas amount */
65
+ maxGasAmount?: number;
66
+ /** Optional gas unit price */
67
+ gasUnitPrice?: number;
68
+ }
69
+ interface TransactionResult {
70
+ /** Transaction hash */
71
+ hash: string;
72
+ /** Whether transaction was successful (Executed) */
73
+ success: boolean;
74
+ /** If aborted, this contains the VM status/error */
75
+ vmStatus?: string;
76
+ /** Gas used */
77
+ gasUsed: string;
78
+ /** Block height */
79
+ version: string;
80
+ }
81
+ interface TransactionHistoryItem {
82
+ hash: string;
83
+ success: boolean;
84
+ type: string;
85
+ sender: string;
86
+ receiver?: string;
87
+ amount?: string;
88
+ timestamp: number;
89
+ version: string;
90
+ }
91
+ interface FungibleAssetMetadata {
92
+ asset_type: string;
93
+ creator_address: string;
94
+ decimals: number;
95
+ icon_uri?: string;
96
+ name: string;
97
+ project_uri?: string;
98
+ symbol: string;
99
+ token_standard: string;
100
+ }
101
+ interface BalanceInfo {
102
+ /** Coin type identifier */
103
+ coinType: string;
104
+ /** Balance amount (in smallest unit) */
105
+ amount: string;
106
+ /** Decimals for this coin */
107
+ decimals: number;
108
+ /** Human-readable balance */
109
+ formatted: string;
110
+ /** Token metadata (if available) */
111
+ metadata?: FungibleAssetMetadata;
112
+ }
113
+ interface KeylessConfig {
114
+ /** Google ID token (JWT) used for keyless proof */
115
+ idToken: string;
116
+ /** Ephemeral Key Pair (Ed25519) - Runtime only */
117
+ ephemeralKeyPair?: any;
118
+ /** Ephemeral Private Key Hex - Storage only */
119
+ ephemeralPrivateKey?: string;
120
+ /** Nonce blinding factor used during login */
121
+ nonceBlinding: string;
122
+ /** Expiry of the ephemeral session */
123
+ expiresAt: number;
124
+ }
125
+ interface SessionData {
126
+ /** Encrypted wallet data (deterministic private key) */
127
+ encryptedWallet: string;
128
+ /** Session expiration timestamp */
129
+ expiresAt: number;
130
+ /** Google refresh token (encrypted) */
131
+ refreshToken?: string;
132
+ /** Keyless session data (Petra way) */
133
+ keyless?: KeylessConfig;
134
+ /** User info */
135
+ userInfo: {
136
+ email: string;
137
+ name?: string;
138
+ picture?: string;
139
+ };
140
+ }
141
+ interface StorageProvider {
142
+ /** Get item from storage */
143
+ getItem(key: string): Promise<string | null>;
144
+ /** Set item in storage */
145
+ setItem(key: string, value: string): Promise<void>;
146
+ /** Remove item from storage */
147
+ removeItem(key: string): Promise<void>;
148
+ /** Clear all storage */
149
+ clear(): Promise<void>;
150
+ }
151
+ interface KeyDerivationOptions {
152
+ /** User identifier (e.g., Google sub) */
153
+ userId: string;
154
+ /** Application-specific salt */
155
+ salt: string;
156
+ /** Number of iterations for key derivation */
157
+ iterations?: number;
158
+ }
159
+ interface SphereWalletMethods {
160
+ /** Get wallet address */
161
+ getAddress(): string;
162
+ /** Get public key */
163
+ getPublicKey(): string;
164
+ /** Check if account exists on-chain */
165
+ existsOnChain(): Promise<boolean>;
166
+ /** Get account balance */
167
+ getBalance(coinType?: string): Promise<BalanceInfo>;
168
+ /** Get all token balances */
169
+ getAllBalances(): Promise<BalanceInfo[]>;
170
+ /** Send transaction */
171
+ sendTransaction(options: TransactionOptions, simulate?: boolean): Promise<TransactionResult>;
172
+ /** Update network and RPC endpoint */
173
+ updateNetwork(network: Network, rpcEndpoint: string): void;
174
+ /** Simulate transaction without submitting */
175
+ simulateTransaction(options: TransactionOptions): Promise<{
176
+ success: boolean;
177
+ gasUsed: string;
178
+ gasUnitPrice: string;
179
+ totalGasCost: number;
180
+ vmStatus: string;
181
+ }>;
182
+ /** Sign message */
183
+ signMessage(message: string): Promise<string>;
184
+ /** Get account info */
185
+ getAccountInfo(): Promise<WalletInfo>;
186
+ /** Wait for a transaction to be confirmed */
187
+ waitForTransaction(hash: string): Promise<TransactionResult>;
188
+ /** Get current network gas price */
189
+ getGasPrice(): Promise<number>;
190
+ /** Get transaction history */
191
+ getTransactionHistory(): Promise<TransactionHistoryItem[]>;
192
+ /** Disconnect wallet */
193
+ disconnect(): Promise<void>;
194
+ }
195
+ interface AccountAbstractionSDK {
196
+ /** Initialize SDK */
197
+ initialize(): Promise<void>;
198
+ /** Login with Google OAuth */
199
+ loginWithGoogle(): Promise<SphereWalletMethods>;
200
+ /** Handle Google OAuth response (for redirects) */
201
+ handleGoogleResponse(credential: string): Promise<SphereWalletMethods>;
202
+ /** Restore session if available */
203
+ restoreSession(): Promise<SphereWalletMethods | null>;
204
+ /** Logout and clear session */
205
+ logout(): Promise<void>;
206
+ /** Check if user is authenticated */
207
+ isAuthenticated(): boolean;
208
+ /** Get current wallet (if authenticated) */
209
+ getCurrentWallet(): SphereWalletMethods | null;
210
+ /** Get current user email (if authenticated) */
211
+ getUserEmail(): string | null;
212
+ /** Get the ephemeral public key for the current session */
213
+ getEphemeralPublicKey(): string | null;
214
+ /** Update network and RPC endpoint */
215
+ updateNetwork(network: Network, rpcEndpoint: string): Promise<void>;
216
+ getIndexerUrl(): string | undefined;
217
+ /** Subscribe to SDK events */
218
+ on(event: string, callback: (data: any) => void): void;
219
+ /** Unsubscribe from SDK events */
220
+ off(event: string, callback: (data: any) => void): void;
221
+ }
222
+ interface ErrorResponse {
223
+ /** Error code */
224
+ code: string;
225
+ /** Error message */
226
+ message: string;
227
+ /** Additional error details */
228
+ details?: unknown;
229
+ }
230
+ declare enum ErrorCode {
231
+ AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED",
232
+ WALLET_CREATION_FAILED = "WALLET_CREATION_FAILED",
233
+ TRANSACTION_FAILED = "TRANSACTION_FAILED",
234
+ INSUFFICIENT_BALANCE = "INSUFFICIENT_BALANCE",
235
+ NETWORK_ERROR = "NETWORK_ERROR",
236
+ INVALID_ADDRESS = "INVALID_ADDRESS",
237
+ SESSION_EXPIRED = "SESSION_EXPIRED",
238
+ STORAGE_ERROR = "STORAGE_ERROR",
239
+ KEY_DERIVATION_FAILED = "KEY_DERIVATION_FAILED",
240
+ TRANSACTION_ABORTED = "TRANSACTION_ABORTED",
241
+ DISCARDED_TRANSACTION = "DISCARDED_TRANSACTION",
242
+ INVALID_CONFIG = "INVALID_CONFIG"
243
+ }
244
+ declare class SphereSDKError extends Error {
245
+ code: ErrorCode;
246
+ details?: unknown | undefined;
247
+ constructor(code: ErrorCode, message: string, details?: unknown | undefined);
248
+ }
249
+
250
+ /**
251
+ * Main SDK class for Sphere Account Abstraction
252
+ */
253
+ declare class SphereAccountAbstraction extends EventEmitter implements AccountAbstractionSDK {
254
+ private cedra;
255
+ private config;
256
+ private authProvider;
257
+ private storage;
258
+ private sessionManager;
259
+ private currentWallet;
260
+ private initialized;
261
+ private readonly appName;
262
+ private readonly storageKey;
263
+ constructor(config: SDKConfig);
264
+ initialize(): Promise<void>;
265
+ loginWithGoogle(): Promise<SphereWalletMethods>;
266
+ restoreSession(): Promise<SphereWalletMethods | null>;
267
+ handleGoogleResponse(credential: string): Promise<SphereWalletMethods>;
268
+ logout(): Promise<void>;
269
+ isAuthenticated(): boolean;
270
+ getCurrentWallet(): SphereWalletMethods | null;
271
+ getUserEmail(): string | null;
272
+ getEphemeralPublicKey(): string | null;
273
+ updateNetwork(network: Network, rpcEndpoint: string): Promise<void>;
274
+ getIndexerUrl(): string | undefined;
275
+ private encryptWalletData;
276
+ private decryptWalletData;
277
+ on(event: string, listener: (...args: any[]) => void): this;
278
+ off(event: string, listener: (...args: any[]) => void): this;
279
+ }
280
+
281
+ /**
282
+ * Sphere Wallet Implementation
283
+ */
284
+
285
+ /**
286
+ * Sphere Wallet class
287
+ * Manages wallet operations and blockchain interactions
288
+ */
289
+ declare class SphereWallet implements SphereWalletMethods {
290
+ private account;
291
+ private client;
292
+ private network;
293
+ private privateKeyHex;
294
+ private keylessConfig;
295
+ private _indexerUrl;
296
+ constructor(clientOrKey: Cedra | string, privateKeyOrNetwork?: string | Network, networkOrEndpoint?: Network | string, rpcEndpoint?: string, indexerUrl?: string);
297
+ getAddress(): string;
298
+ getPublicKey(): string;
299
+ getIndexerUrl(): string | null;
300
+ existsOnChain(): Promise<boolean>;
301
+ getBalance(coinType?: string): Promise<BalanceInfo>;
302
+ getAllBalances(): Promise<BalanceInfo[]>;
303
+ sendTransaction(options: TransactionOptions, simulate?: boolean): Promise<TransactionResult>;
304
+ waitForTransaction(hash: string): Promise<TransactionResult>;
305
+ getGasPrice(): Promise<number>;
306
+ getTransactionHistory(): Promise<TransactionHistoryItem[]>;
307
+ simulateTransaction(options: TransactionOptions): Promise<{
308
+ success: boolean;
309
+ gasUsed: string;
310
+ gasUnitPrice: string;
311
+ totalGasCost: number;
312
+ vmStatus: string;
313
+ }>;
314
+ signMessage(message: string): Promise<string>;
315
+ getAccountInfo(): Promise<WalletInfo>;
316
+ disconnect(): Promise<void>;
317
+ updateNetwork(network: Network, rpcEndpoint: string): void;
318
+ private mapNetwork;
319
+ getAccount(): Account;
320
+ getClient(): Cedra;
321
+ getPrivateKeyHex(): string;
322
+ setKeylessConfig(config: KeylessConfig): void;
323
+ isKeyless(): boolean;
324
+ }
325
+
326
+ /**
327
+ * Google OAuth Authentication Provider
328
+ * Handles Google Sign-In flow and token validation
329
+ */
330
+
331
+ interface GoogleAuthConfig {
332
+ clientId: string;
333
+ redirectUri?: string;
334
+ }
335
+ /**
336
+ * Google OAuth Provider for authentication
337
+ */
338
+ declare class GoogleAuthProvider {
339
+ private clientId;
340
+ private redirectUri?;
341
+ constructor(config: GoogleAuthConfig);
342
+ /**
343
+ * Initiate Google OAuth login flow
344
+ * Opens Google Sign-In popup
345
+ * @param nonce Optional OIDC nonce for keyless binding
346
+ */
347
+ login(nonce?: string): Promise<GoogleAuthResponse>;
348
+ /**
349
+ * Initialize Google Identity Services
350
+ * @param callback Credential handler
351
+ * @param nonce Optional OIDC nonce for binding
352
+ */
353
+ initialize(callback: (response: {
354
+ credential: string;
355
+ }) => void, nonce?: string): Promise<void>;
356
+ /**
357
+ * Handle the credential response from Google
358
+ */
359
+ handleCredentialResponse(credential: string): Promise<GoogleAuthResponse>;
360
+ /**
361
+ * Verify Google ID token (optional, for enhanced security)
362
+ * This should ideally be done server-side
363
+ */
364
+ verifyToken(idToken: string): Promise<boolean>;
365
+ /**
366
+ * Load Google Identity Services script
367
+ */
368
+ private loadGoogleIdentityScript;
369
+ /**
370
+ * Sign out from Google
371
+ */
372
+ logout(): Promise<void>;
373
+ /**
374
+ * Render Google Sign-In button
375
+ * @param elementId ID of the container element
376
+ * @param options Button customization options
377
+ * @param options Button customization options
378
+ */
379
+ renderButton(elementId: string, options?: {
380
+ theme?: 'outline' | 'filled_blue' | 'filled_black';
381
+ size?: 'large' | 'medium' | 'small';
382
+ text?: 'signin_with' | 'signup_with' | 'continue_with';
383
+ shape?: 'rectangular' | 'pill' | 'circle' | 'square';
384
+ width?: string | number;
385
+ nonce?: string;
386
+ callback?: (response: {
387
+ credential: string;
388
+ }) => void;
389
+ }): Promise<void>;
390
+ }
391
+
392
+ /**
393
+ * Key Derivation Module
394
+ * Implements secure, deterministic key derivation from Google OAuth credentials
395
+ */
396
+
397
+ /**
398
+ * Derives a deterministic private key from user credentials
399
+ * Uses HKDF (HMAC-based Key Derivation Function) for security
400
+ */
401
+ declare class KeyDerivation {
402
+ private static readonly DEFAULT_ITERATIONS;
403
+ private static readonly KEY_LENGTH;
404
+ /**
405
+ * Derive a private key from user ID and salt
406
+ * @param options Key derivation options
407
+ * @returns Hex-encoded private key (64 characters)
408
+ */
409
+ static derivePrivateKey(options: KeyDerivationOptions): string;
410
+ /**
411
+ * Generate a deterministic salt from app name and user email
412
+ * This ensures the same user gets the same wallet across devices
413
+ * @param appName Application name
414
+ * @param userEmail User's email address
415
+ * @returns Deterministic salt string
416
+ */
417
+ static generateDeterministicSalt(appName: string, userEmail: string): string;
418
+ /**
419
+ * Validate a private key format
420
+ * @param privateKey Hex-encoded private key
421
+ * @returns True if valid
422
+ */
423
+ static isValidPrivateKey(privateKey: string): boolean;
424
+ /**
425
+ * Securely clear sensitive data from memory
426
+ * @param data Sensitive string to clear
427
+ */
428
+ static clearSensitiveData(data: string): void;
429
+ /**
430
+ * Generates a temporary ephemeral key pair for the session
431
+ * @returns A fresh Ed25519 account/keypair
432
+ */
433
+ static generateEphemeralKeyPair(): Account;
434
+ /**
435
+ * Computes an OIDC-compliant nonce hash to bind the session key
436
+ * @param publicKey Ephemeral Public Key (hex or string)
437
+ * @param blinding A random blinding factor (hex)
438
+ * @param expiry Expiration timestamp (optional)
439
+ * @returns SHA256 hash of the nonce commitment
440
+ */
441
+ static computeNonce(publicKey: string, blinding: string, expiry?: number): string;
442
+ }
443
+
444
+ /**
445
+ * Secure Storage Module
446
+ * Handles encrypted storage of sensitive wallet data
447
+ */
448
+
449
+ /**
450
+ * Browser-based secure storage implementation
451
+ */
452
+ declare class SecureStorage implements StorageProvider {
453
+ private encryptionKey;
454
+ private storagePrefix;
455
+ constructor(encryptionKey?: string, storagePrefix?: string);
456
+ /**
457
+ * Get item from storage and decrypt
458
+ */
459
+ getItem(key: string): Promise<string | null>;
460
+ /**
461
+ * Encrypt and store item
462
+ */
463
+ setItem(key: string, value: string): Promise<void>;
464
+ /**
465
+ * Remove item from storage
466
+ */
467
+ removeItem(key: string): Promise<void>;
468
+ /**
469
+ * Clear all SDK storage
470
+ */
471
+ clear(): Promise<void>;
472
+ /**
473
+ * Generate encryption key from browser fingerprint
474
+ * This provides basic encryption without requiring user input
475
+ * Note: Not cryptographically secure, but better than plaintext
476
+ */
477
+ private generateEncryptionKey;
478
+ /**
479
+ * Check if storage is available
480
+ */
481
+ static isAvailable(): boolean;
482
+ }
483
+ /**
484
+ * Session Manager
485
+ * Manages user sessions with automatic expiration
486
+ */
487
+ declare class SessionManager {
488
+ private storage;
489
+ private sessionKey;
490
+ private sessionDuration;
491
+ private cachedSession;
492
+ constructor(storage: StorageProvider, sessionDurationHours?: number);
493
+ /**
494
+ * Get cached session data (synchronous)
495
+ */
496
+ getCachedSession(): SessionData | null;
497
+ /**
498
+ * Save session data
499
+ */
500
+ saveSession(data: Omit<SessionData, 'expiresAt'>): Promise<void>;
501
+ /**
502
+ * Get current session
503
+ * Returns null if session doesn't exist or is expired
504
+ */
505
+ getSession(): Promise<SessionData | null>;
506
+ /**
507
+ * Clear current session
508
+ */
509
+ clearSession(): Promise<void>;
510
+ /**
511
+ * Check if session is valid
512
+ */
513
+ isSessionValid(): Promise<boolean>;
514
+ /**
515
+ * Refresh session expiration
516
+ */
517
+ refreshSession(): Promise<void>;
518
+ /**
519
+ * Get time until session expires (in milliseconds)
520
+ */
521
+ getTimeUntilExpiration(): Promise<number | null>;
522
+ }
523
+
524
+ interface SphereContextType {
525
+ sdk: SphereAccountAbstraction;
526
+ wallet: SphereWalletMethods | null;
527
+ walletInfo: WalletInfo | null;
528
+ balance: BalanceInfo | null;
529
+ email: string | null;
530
+ indexerUrl: string | undefined;
531
+ isAuthenticated: boolean;
532
+ isLoading: boolean;
533
+ error: string | null;
534
+ login: () => Promise<void>;
535
+ logout: () => Promise<void>;
536
+ setIsLoading: (loading: boolean) => void;
537
+ refreshData: () => Promise<void>;
538
+ handleAuthSuccess: (wallet: SphereWalletMethods) => Promise<void>;
539
+ }
540
+ interface SphereProviderProps {
541
+ children: ReactNode;
542
+ config: SDKConfig;
543
+ }
544
+ declare const SphereProvider: React.FC<SphereProviderProps>;
545
+ declare const useSphere: () => SphereContextType;
546
+
547
+ interface SphereModalProps {
548
+ isOpen: boolean;
549
+ onClose: () => void;
550
+ }
551
+ declare const SphereModal: React.FC<SphereModalProps>;
552
+
553
+ export { type AccountAbstractionSDK, type BalanceInfo, ErrorCode, type ErrorResponse, type FungibleAssetMetadata, GoogleAuthProvider, type GoogleAuthResponse, KeyDerivation, type KeyDerivationOptions, type KeylessConfig, type Network, type SDKConfig, SecureStorage, type SessionData, SessionManager, SphereAccountAbstraction, SphereModal, SphereProvider, SphereSDKError, SphereWallet, type SphereWalletMethods, type StorageProvider, type TransactionHistoryItem, type TransactionOptions, type TransactionResult, type WalletInfo, useSphere };