@unicitylabs/sphere-sdk 0.1.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,2548 @@
1
+ import { Token as Token$1 } from '@unicitylabs/state-transition-sdk/lib/token/Token';
2
+ import elliptic from 'elliptic';
3
+
4
+ /**
5
+ * Cryptographic utilities for SDK2
6
+ *
7
+ * Provides BIP39 mnemonic and BIP32 key derivation functions.
8
+ * Platform-independent - no browser-specific APIs.
9
+ */
10
+
11
+ declare const ec: elliptic.ec;
12
+ /** Default derivation path for Unicity (BIP44) */
13
+ declare const DEFAULT_DERIVATION_PATH = "m/44'/0'/0'";
14
+ interface MasterKey {
15
+ privateKey: string;
16
+ chainCode: string;
17
+ }
18
+ interface DerivedKey {
19
+ privateKey: string;
20
+ chainCode: string;
21
+ }
22
+ interface KeyPair {
23
+ privateKey: string;
24
+ publicKey: string;
25
+ }
26
+ interface AddressInfo extends KeyPair {
27
+ address: string;
28
+ path: string;
29
+ index: number;
30
+ }
31
+ /**
32
+ * Generate a new BIP39 mnemonic phrase
33
+ * @param strength - Entropy bits (128 = 12 words, 256 = 24 words)
34
+ */
35
+ declare function generateMnemonic(strength?: 128 | 256): string;
36
+ /**
37
+ * Validate a BIP39 mnemonic phrase
38
+ */
39
+ declare function validateMnemonic(mnemonic: string): boolean;
40
+ /**
41
+ * Convert mnemonic to seed (64-byte hex string)
42
+ * @param mnemonic - BIP39 mnemonic phrase
43
+ * @param passphrase - Optional passphrase for additional security
44
+ */
45
+ declare function mnemonicToSeed(mnemonic: string, passphrase?: string): Promise<string>;
46
+ /**
47
+ * Synchronous version of mnemonicToSeed
48
+ */
49
+ declare function mnemonicToSeedSync(mnemonic: string, passphrase?: string): string;
50
+ /**
51
+ * Convert mnemonic to entropy (for recovery purposes)
52
+ */
53
+ declare function mnemonicToEntropy(mnemonic: string): string;
54
+ /**
55
+ * Convert entropy to mnemonic
56
+ */
57
+ declare function entropyToMnemonic(entropy: string): string;
58
+ /**
59
+ * Generate master key from seed (BIP32 standard)
60
+ * Uses HMAC-SHA512 with key "Bitcoin seed"
61
+ */
62
+ declare function generateMasterKey(seedHex: string): MasterKey;
63
+ /**
64
+ * Derive child key using BIP32 standard
65
+ * @param parentPrivKey - Parent private key (64 hex chars)
66
+ * @param parentChainCode - Parent chain code (64 hex chars)
67
+ * @param index - Child index (>= 0x80000000 for hardened)
68
+ */
69
+ declare function deriveChildKey(parentPrivKey: string, parentChainCode: string, index: number): DerivedKey;
70
+ /**
71
+ * Derive key at a full BIP32/BIP44 path
72
+ * @param masterPrivKey - Master private key
73
+ * @param masterChainCode - Master chain code
74
+ * @param path - BIP44 path like "m/44'/0'/0'/0/0"
75
+ */
76
+ declare function deriveKeyAtPath(masterPrivKey: string, masterChainCode: string, path: string): DerivedKey;
77
+ /**
78
+ * Get public key from private key
79
+ * @param privateKey - Private key as hex string
80
+ * @param compressed - Return compressed public key (default: true)
81
+ */
82
+ declare function getPublicKey(privateKey: string, compressed?: boolean): string;
83
+ /**
84
+ * Create key pair from private key
85
+ */
86
+ declare function createKeyPair(privateKey: string): KeyPair;
87
+ /**
88
+ * Compute SHA256 hash
89
+ */
90
+ declare function sha256(data: string, inputEncoding?: 'hex' | 'utf8'): string;
91
+ /**
92
+ * Compute RIPEMD160 hash
93
+ */
94
+ declare function ripemd160(data: string, inputEncoding?: 'hex' | 'utf8'): string;
95
+ /**
96
+ * Compute HASH160 (SHA256 -> RIPEMD160)
97
+ */
98
+ declare function hash160(data: string): string;
99
+ /**
100
+ * Compute double SHA256
101
+ */
102
+ declare function doubleSha256(data: string, inputEncoding?: 'hex' | 'utf8'): string;
103
+ /**
104
+ * Alias for hash160 (L1 SDK compatibility)
105
+ */
106
+ declare const computeHash160: typeof hash160;
107
+ /**
108
+ * Convert hex string to Uint8Array for witness program
109
+ */
110
+ declare function hash160ToBytes(hash160Hex: string): Uint8Array;
111
+ /**
112
+ * Generate bech32 address from public key
113
+ * @param publicKey - Compressed public key as hex string
114
+ * @param prefix - Address prefix (default: "alpha")
115
+ * @param witnessVersion - Witness version (default: 0 for P2WPKH)
116
+ * @returns Bech32 encoded address
117
+ */
118
+ declare function publicKeyToAddress(publicKey: string, prefix?: string, witnessVersion?: number): string;
119
+ /**
120
+ * Get address info from private key
121
+ */
122
+ declare function privateKeyToAddressInfo(privateKey: string, prefix?: string): {
123
+ address: string;
124
+ publicKey: string;
125
+ };
126
+ /**
127
+ * Convert hex string to Uint8Array
128
+ */
129
+ declare function hexToBytes(hex: string): Uint8Array;
130
+ /**
131
+ * Convert Uint8Array to hex string
132
+ */
133
+ declare function bytesToHex(bytes: Uint8Array): string;
134
+ /**
135
+ * Generate random bytes as hex string
136
+ */
137
+ declare function randomBytes(length: number): string;
138
+ /**
139
+ * Generate identity from mnemonic
140
+ * Returns master key derived from mnemonic seed
141
+ */
142
+ declare function identityFromMnemonic(mnemonic: string, passphrase?: string): Promise<MasterKey>;
143
+ /**
144
+ * Synchronous version of identityFromMnemonic
145
+ */
146
+ declare function identityFromMnemonicSync(mnemonic: string, passphrase?: string): MasterKey;
147
+ /**
148
+ * Derive address info at a specific path
149
+ * @param masterKey - Master key with privateKey and chainCode
150
+ * @param basePath - Base derivation path (e.g., "m/44'/0'/0'")
151
+ * @param index - Address index
152
+ * @param isChange - Whether this is a change address (chain 1 vs 0)
153
+ * @param prefix - Address prefix (default: "alpha")
154
+ */
155
+ declare function deriveAddressInfo(masterKey: MasterKey, basePath: string, index: number, isChange?: boolean, prefix?: string): AddressInfo;
156
+ /**
157
+ * Generate full address info from private key with index and path
158
+ * (L1 SDK compatibility)
159
+ */
160
+ declare function generateAddressInfo(privateKey: string, index: number, path: string, prefix?: string): AddressInfo;
161
+
162
+ /**
163
+ * TXF (Token eXchange Format) Type Definitions
164
+ * Based on TXF Format Specification v2.0
165
+ *
166
+ * These types define the serialization format for tokens,
167
+ * independent of any UI or storage implementation.
168
+ */
169
+ /**
170
+ * Complete token object in TXF format
171
+ */
172
+ interface TxfToken {
173
+ version: '2.0';
174
+ genesis: TxfGenesis;
175
+ state: TxfState;
176
+ transactions: TxfTransaction[];
177
+ nametags?: string[];
178
+ _integrity?: TxfIntegrity;
179
+ }
180
+ /**
181
+ * Genesis transaction (initial minting)
182
+ */
183
+ interface TxfGenesis {
184
+ data: TxfGenesisData;
185
+ inclusionProof: TxfInclusionProof;
186
+ }
187
+ /**
188
+ * Genesis data payload
189
+ */
190
+ interface TxfGenesisData {
191
+ tokenId: string;
192
+ tokenType: string;
193
+ coinData: [string, string][];
194
+ tokenData: string;
195
+ salt: string;
196
+ recipient: string;
197
+ recipientDataHash: string | null;
198
+ reason: string | null;
199
+ }
200
+ /**
201
+ * Current token state
202
+ */
203
+ interface TxfState {
204
+ data: string;
205
+ predicate: string;
206
+ }
207
+ /**
208
+ * State transition transaction
209
+ */
210
+ interface TxfTransaction {
211
+ previousStateHash: string;
212
+ newStateHash?: string;
213
+ predicate: string;
214
+ inclusionProof: TxfInclusionProof | null;
215
+ data?: Record<string, unknown>;
216
+ }
217
+ /**
218
+ * Sparse Merkle Tree inclusion proof
219
+ */
220
+ interface TxfInclusionProof {
221
+ authenticator: TxfAuthenticator;
222
+ merkleTreePath: TxfMerkleTreePath;
223
+ transactionHash: string;
224
+ unicityCertificate: string;
225
+ }
226
+ /**
227
+ * Proof authenticator
228
+ */
229
+ interface TxfAuthenticator {
230
+ algorithm: string;
231
+ publicKey: string;
232
+ signature: string;
233
+ stateHash: string;
234
+ }
235
+ /**
236
+ * Merkle tree path for proof verification
237
+ */
238
+ interface TxfMerkleTreePath {
239
+ root: string;
240
+ steps: TxfMerkleStep[];
241
+ }
242
+ /**
243
+ * Single step in merkle path
244
+ */
245
+ interface TxfMerkleStep {
246
+ data: string;
247
+ path: string;
248
+ }
249
+ /**
250
+ * Token integrity metadata
251
+ */
252
+ interface TxfIntegrity {
253
+ genesisDataJSONHash: string;
254
+ currentStateHash?: string;
255
+ }
256
+ /**
257
+ * Nametag data (one per identity)
258
+ */
259
+ interface NametagData {
260
+ name: string;
261
+ token: object;
262
+ timestamp: number;
263
+ format: string;
264
+ version: string;
265
+ }
266
+ /**
267
+ * Tombstone entry for tracking spent token states
268
+ */
269
+ interface TombstoneEntry {
270
+ tokenId: string;
271
+ stateHash: string;
272
+ timestamp: number;
273
+ }
274
+
275
+ /**
276
+ * SDK2 Core Types
277
+ * Platform-independent type definitions
278
+ */
279
+ type ProviderStatus = 'disconnected' | 'connecting' | 'connected' | 'error';
280
+ interface ProviderMetadata {
281
+ readonly id: string;
282
+ readonly name: string;
283
+ readonly type: 'local' | 'cloud' | 'p2p' | 'network';
284
+ readonly description?: string;
285
+ }
286
+ interface BaseProvider extends ProviderMetadata {
287
+ connect(config?: unknown): Promise<void>;
288
+ disconnect(): Promise<void>;
289
+ isConnected(): boolean;
290
+ getStatus(): ProviderStatus;
291
+ }
292
+ interface Identity {
293
+ readonly publicKey: string;
294
+ /** L1 address (alpha1...) */
295
+ readonly address: string;
296
+ /** L3 predicate address (DIRECT://...) */
297
+ readonly predicateAddress?: string;
298
+ readonly ipnsName?: string;
299
+ readonly nametag?: string;
300
+ }
301
+ interface FullIdentity extends Identity {
302
+ readonly privateKey: string;
303
+ }
304
+ type TokenStatus = 'pending' | 'confirmed' | 'transferring' | 'spent' | 'invalid';
305
+ interface Token {
306
+ readonly id: string;
307
+ readonly coinId: string;
308
+ readonly symbol: string;
309
+ readonly name: string;
310
+ readonly amount: string;
311
+ status: TokenStatus;
312
+ readonly createdAt: number;
313
+ updatedAt: number;
314
+ readonly sdkData?: string;
315
+ }
316
+ interface TokenBalance {
317
+ readonly coinId: string;
318
+ readonly symbol: string;
319
+ readonly name: string;
320
+ readonly totalAmount: string;
321
+ readonly tokenCount: number;
322
+ readonly decimals: number;
323
+ }
324
+ type TransferStatus = 'pending' | 'submitted' | 'confirmed' | 'delivered' | 'completed' | 'failed';
325
+ interface TransferRequest {
326
+ readonly coinId: string;
327
+ readonly amount: string;
328
+ readonly recipient: string;
329
+ readonly memo?: string;
330
+ }
331
+ interface TransferResult {
332
+ readonly id: string;
333
+ status: TransferStatus;
334
+ readonly tokens: Token[];
335
+ txHash?: string;
336
+ error?: string;
337
+ }
338
+ interface IncomingTransfer {
339
+ readonly id: string;
340
+ readonly senderPubkey: string;
341
+ readonly senderNametag?: string;
342
+ readonly tokens: Token[];
343
+ readonly memo?: string;
344
+ readonly receivedAt: number;
345
+ }
346
+ type PaymentRequestStatus = 'pending' | 'accepted' | 'rejected' | 'paid' | 'expired';
347
+ /**
348
+ * Outgoing payment request (requesting payment from someone)
349
+ */
350
+ interface PaymentRequest {
351
+ /** Unique request ID */
352
+ readonly id: string;
353
+ /** Amount requested (in smallest units) */
354
+ readonly amount: string;
355
+ /** Coin/token type */
356
+ readonly coinId: string;
357
+ /** Optional message/memo */
358
+ readonly message?: string;
359
+ /** Recipient nametag (who should pay) */
360
+ readonly recipientNametag?: string;
361
+ /** Custom metadata */
362
+ readonly metadata?: Record<string, unknown>;
363
+ /** Expiration timestamp (ms) */
364
+ readonly expiresAt?: number;
365
+ /** Created timestamp */
366
+ readonly createdAt: number;
367
+ }
368
+ /**
369
+ * Incoming payment request (someone requesting payment from us)
370
+ */
371
+ interface IncomingPaymentRequest$1 {
372
+ /** Event ID from Nostr */
373
+ readonly id: string;
374
+ /** Sender's public key */
375
+ readonly senderPubkey: string;
376
+ /** Sender's nametag (if known) */
377
+ readonly senderNametag?: string;
378
+ /** Amount requested */
379
+ readonly amount: string;
380
+ /** Coin/token type */
381
+ readonly coinId: string;
382
+ /** Symbol for display */
383
+ readonly symbol: string;
384
+ /** Message from sender */
385
+ readonly message?: string;
386
+ /** Who this request is for (our nametag) */
387
+ readonly recipientNametag?: string;
388
+ /** Original request ID from sender */
389
+ readonly requestId: string;
390
+ /** Timestamp */
391
+ readonly timestamp: number;
392
+ /** Current status */
393
+ status: PaymentRequestStatus;
394
+ /** Custom metadata */
395
+ readonly metadata?: Record<string, unknown>;
396
+ }
397
+ /**
398
+ * Result of sending a payment request
399
+ */
400
+ interface PaymentRequestResult {
401
+ readonly success: boolean;
402
+ readonly requestId?: string;
403
+ readonly eventId?: string;
404
+ readonly error?: string;
405
+ }
406
+ /**
407
+ * Handler for incoming payment requests
408
+ */
409
+ type PaymentRequestHandler$1 = (request: IncomingPaymentRequest$1) => void;
410
+ /**
411
+ * Response type for payment requests
412
+ */
413
+ type PaymentRequestResponseType$1 = 'accepted' | 'rejected' | 'paid';
414
+ /**
415
+ * Outgoing payment request (we sent to someone)
416
+ */
417
+ interface OutgoingPaymentRequest {
418
+ /** Unique request ID */
419
+ readonly id: string;
420
+ /** Nostr event ID */
421
+ readonly eventId: string;
422
+ /** Recipient's public key */
423
+ readonly recipientPubkey: string;
424
+ /** Recipient's nametag (if known) */
425
+ readonly recipientNametag?: string;
426
+ /** Amount requested */
427
+ readonly amount: string;
428
+ /** Coin/token type */
429
+ readonly coinId: string;
430
+ /** Message sent with request */
431
+ readonly message?: string;
432
+ /** Created timestamp */
433
+ readonly createdAt: number;
434
+ /** Current status */
435
+ status: PaymentRequestStatus;
436
+ /** Response data (if received) */
437
+ response?: PaymentRequestResponse;
438
+ }
439
+ /**
440
+ * Response to a payment request
441
+ */
442
+ interface PaymentRequestResponse {
443
+ /** Response event ID */
444
+ readonly id: string;
445
+ /** Responder's public key */
446
+ readonly responderPubkey: string;
447
+ /** Responder's nametag (if known) */
448
+ readonly responderNametag?: string;
449
+ /** Original request ID */
450
+ readonly requestId: string;
451
+ /** Response type */
452
+ readonly responseType: PaymentRequestResponseType$1;
453
+ /** Optional message */
454
+ readonly message?: string;
455
+ /** Transfer ID (if paid) */
456
+ readonly transferId?: string;
457
+ /** Timestamp */
458
+ readonly timestamp: number;
459
+ }
460
+ /**
461
+ * Handler for payment request responses
462
+ */
463
+ type PaymentRequestResponseHandler$1 = (response: PaymentRequestResponse) => void;
464
+ interface DirectMessage {
465
+ readonly id: string;
466
+ readonly senderPubkey: string;
467
+ readonly senderNametag?: string;
468
+ readonly recipientPubkey: string;
469
+ readonly recipientNametag?: string;
470
+ readonly content: string;
471
+ readonly timestamp: number;
472
+ isRead: boolean;
473
+ }
474
+ interface BroadcastMessage {
475
+ readonly id: string;
476
+ readonly authorPubkey: string;
477
+ readonly authorNametag?: string;
478
+ readonly content: string;
479
+ readonly timestamp: number;
480
+ readonly tags?: string[];
481
+ }
482
+ type SphereEventType = 'transfer:incoming' | 'transfer:confirmed' | 'transfer:failed' | 'payment_request:incoming' | 'payment_request:accepted' | 'payment_request:rejected' | 'payment_request:paid' | 'payment_request:response' | 'message:dm' | 'message:broadcast' | 'sync:started' | 'sync:completed' | 'sync:provider' | 'sync:error' | 'connection:changed' | 'nametag:registered' | 'identity:changed';
483
+ interface SphereEventMap {
484
+ 'transfer:incoming': IncomingTransfer;
485
+ 'transfer:confirmed': TransferResult;
486
+ 'transfer:failed': TransferResult;
487
+ 'payment_request:incoming': IncomingPaymentRequest$1;
488
+ 'payment_request:accepted': IncomingPaymentRequest$1;
489
+ 'payment_request:rejected': IncomingPaymentRequest$1;
490
+ 'payment_request:paid': IncomingPaymentRequest$1;
491
+ 'payment_request:response': PaymentRequestResponse;
492
+ 'message:dm': DirectMessage;
493
+ 'message:broadcast': BroadcastMessage;
494
+ 'sync:started': {
495
+ source: string;
496
+ };
497
+ 'sync:completed': {
498
+ source: string;
499
+ count: number;
500
+ };
501
+ 'sync:provider': {
502
+ providerId: string;
503
+ success: boolean;
504
+ added?: number;
505
+ removed?: number;
506
+ error?: string;
507
+ };
508
+ 'sync:error': {
509
+ source: string;
510
+ error: string;
511
+ };
512
+ 'connection:changed': {
513
+ provider: string;
514
+ connected: boolean;
515
+ };
516
+ 'nametag:registered': {
517
+ nametag: string;
518
+ addressIndex: number;
519
+ };
520
+ 'identity:changed': {
521
+ address: string;
522
+ predicateAddress?: string;
523
+ publicKey: string;
524
+ nametag?: string;
525
+ addressIndex: number;
526
+ };
527
+ }
528
+ type SphereEventHandler<T extends SphereEventType> = (data: SphereEventMap[T]) => void;
529
+ /**
530
+ * Derivation mode determines how child keys are derived:
531
+ * - "bip32": Standard BIP32 with chain code (IL + parentKey) mod n
532
+ * - "legacy_hmac": Legacy Sphere HMAC derivation with chain code
533
+ * - "wif_hmac": Simple HMAC derivation without chain code (webwallet compatibility)
534
+ */
535
+ type DerivationMode = 'bip32' | 'legacy_hmac' | 'wif_hmac';
536
+ /**
537
+ * Source of wallet creation
538
+ */
539
+ type WalletSource = 'mnemonic' | 'file' | 'unknown';
540
+ /**
541
+ * Wallet information for backup/export purposes
542
+ */
543
+ interface WalletInfo {
544
+ readonly source: WalletSource;
545
+ readonly hasMnemonic: boolean;
546
+ readonly hasChainCode: boolean;
547
+ readonly derivationMode: DerivationMode;
548
+ readonly basePath: string;
549
+ readonly address0: string | null;
550
+ }
551
+ /**
552
+ * JSON export format for wallet backup (v1.0)
553
+ */
554
+ interface WalletJSON {
555
+ readonly version: '1.0';
556
+ readonly type: 'sphere-wallet';
557
+ readonly createdAt: string;
558
+ readonly wallet: {
559
+ readonly masterPrivateKey?: string;
560
+ readonly chainCode?: string;
561
+ readonly addresses: ReadonlyArray<{
562
+ readonly address: string;
563
+ readonly publicKey: string;
564
+ readonly path: string;
565
+ readonly index: number;
566
+ }>;
567
+ readonly isBIP32: boolean;
568
+ readonly descriptorPath?: string;
569
+ };
570
+ readonly mnemonic?: string;
571
+ readonly encrypted?: boolean;
572
+ readonly source?: WalletSource;
573
+ readonly derivationMode?: DerivationMode;
574
+ }
575
+ /**
576
+ * Options for exporting wallet to JSON
577
+ */
578
+ interface WalletJSONExportOptions {
579
+ /** Include mnemonic in export (default: true if available) */
580
+ includeMnemonic?: boolean;
581
+ /** Encrypt sensitive data with password */
582
+ password?: string;
583
+ /** Number of addresses to include (default: 1) */
584
+ addressCount?: number;
585
+ }
586
+
587
+ /**
588
+ * L1 Payments Sub-Module
589
+ *
590
+ * Handles Layer 1 (ALPHA blockchain) transactions including:
591
+ * - Balance queries
592
+ * - UTXO management
593
+ * - Transaction sending
594
+ * - Vesting classification
595
+ * - Transaction history
596
+ */
597
+
598
+ interface L1SendRequest {
599
+ /** Recipient address */
600
+ to: string;
601
+ /** Amount in satoshis */
602
+ amount: string;
603
+ /** Fee rate in sat/byte */
604
+ feeRate?: number;
605
+ /** Use vested coins only */
606
+ useVested?: boolean;
607
+ /** Memo/OP_RETURN data */
608
+ memo?: string;
609
+ }
610
+ interface L1SendResult {
611
+ success: boolean;
612
+ txHash?: string;
613
+ fee?: string;
614
+ error?: string;
615
+ }
616
+ interface L1Balance {
617
+ confirmed: string;
618
+ unconfirmed: string;
619
+ vested: string;
620
+ unvested: string;
621
+ total: string;
622
+ }
623
+ interface L1Utxo {
624
+ txid: string;
625
+ vout: number;
626
+ amount: string;
627
+ address: string;
628
+ isVested: boolean;
629
+ confirmations: number;
630
+ coinbaseHeight?: number;
631
+ }
632
+ interface L1Transaction {
633
+ txid: string;
634
+ type: 'send' | 'receive';
635
+ amount: string;
636
+ fee?: string;
637
+ address: string;
638
+ confirmations: number;
639
+ timestamp: number;
640
+ blockHeight?: number;
641
+ }
642
+ interface L1PaymentsModuleConfig {
643
+ /** Fulcrum server URL */
644
+ electrumUrl?: string;
645
+ /** Network: mainnet or testnet */
646
+ network?: 'mainnet' | 'testnet';
647
+ /** Default fee rate */
648
+ defaultFeeRate?: number;
649
+ /** Enable vesting classification */
650
+ enableVesting?: boolean;
651
+ }
652
+ interface L1PaymentsModuleDependencies {
653
+ identity: FullIdentity;
654
+ chainCode?: string;
655
+ addresses?: string[];
656
+ }
657
+ /**
658
+ * L1 Payments Module - Full Implementation
659
+ *
660
+ * Handles all L1 (ALPHA blockchain) operations including balance queries,
661
+ * transaction sending, UTXO management, and vesting classification.
662
+ */
663
+ declare class L1PaymentsModule {
664
+ private _initialized;
665
+ private _config;
666
+ private _identity?;
667
+ private _chainCode?;
668
+ private _addresses;
669
+ private _wallet?;
670
+ constructor(config?: L1PaymentsModuleConfig);
671
+ initialize(deps: L1PaymentsModuleDependencies): Promise<void>;
672
+ destroy(): void;
673
+ send(request: L1SendRequest): Promise<L1SendResult>;
674
+ getBalance(): Promise<L1Balance>;
675
+ getUtxos(): Promise<L1Utxo[]>;
676
+ getHistory(limit?: number): Promise<L1Transaction[]>;
677
+ getTransaction(txid: string): Promise<L1Transaction | null>;
678
+ estimateFee(to: string, amount: string): Promise<{
679
+ fee: string;
680
+ feeRate: number;
681
+ }>;
682
+ getAddresses(): string[];
683
+ addAddress(address: string): void;
684
+ getVestingThreshold(): number;
685
+ isConnected(): boolean;
686
+ private ensureInitialized;
687
+ private _getWatchedAddresses;
688
+ private _getAllUtxos;
689
+ }
690
+
691
+ /**
692
+ * Nametag Minter
693
+ * Mints nametag tokens on-chain for PROXY address support
694
+ *
695
+ * Flow (same as Sphere wallet and lottery):
696
+ * 1. Generate salt
697
+ * 2. Create MintTransactionData from nametag
698
+ * 3. Create MintCommitment
699
+ * 4. Submit to aggregator
700
+ * 5. Wait for inclusion proof
701
+ * 6. Create Token with proof
702
+ * 7. Return token for storage
703
+ */
704
+
705
+ interface MintNametagResult {
706
+ success: boolean;
707
+ token?: Token$1<any>;
708
+ nametagData?: NametagData;
709
+ error?: string;
710
+ }
711
+
712
+ /**
713
+ * Storage Provider Interface
714
+ * Platform-independent storage abstraction
715
+ */
716
+
717
+ /**
718
+ * Basic key-value storage provider
719
+ * All operations are async for platform flexibility
720
+ */
721
+ interface StorageProvider extends BaseProvider {
722
+ /**
723
+ * Set identity for scoped storage
724
+ */
725
+ setIdentity(identity: FullIdentity): void;
726
+ /**
727
+ * Get value by key
728
+ */
729
+ get(key: string): Promise<string | null>;
730
+ /**
731
+ * Set value by key
732
+ */
733
+ set(key: string, value: string): Promise<void>;
734
+ /**
735
+ * Remove key
736
+ */
737
+ remove(key: string): Promise<void>;
738
+ /**
739
+ * Check if key exists
740
+ */
741
+ has(key: string): Promise<boolean>;
742
+ /**
743
+ * Get all keys with optional prefix filter
744
+ */
745
+ keys(prefix?: string): Promise<string[]>;
746
+ /**
747
+ * Clear all keys with optional prefix filter
748
+ */
749
+ clear(prefix?: string): Promise<void>;
750
+ }
751
+ /**
752
+ * Storage result types
753
+ */
754
+ interface SaveResult {
755
+ success: boolean;
756
+ cid?: string;
757
+ error?: string;
758
+ timestamp: number;
759
+ }
760
+ interface LoadResult<T = unknown> {
761
+ success: boolean;
762
+ data?: T;
763
+ error?: string;
764
+ source: 'local' | 'remote' | 'cache';
765
+ timestamp: number;
766
+ }
767
+ interface SyncResult<T = unknown> {
768
+ success: boolean;
769
+ merged?: T;
770
+ added: number;
771
+ removed: number;
772
+ conflicts: number;
773
+ error?: string;
774
+ }
775
+ /**
776
+ * Token-specific storage provider
777
+ * Handles token persistence with sync capabilities
778
+ */
779
+ interface TokenStorageProvider<TData = unknown> extends BaseProvider {
780
+ /**
781
+ * Set identity for storage scope
782
+ */
783
+ setIdentity(identity: FullIdentity): void;
784
+ /**
785
+ * Initialize provider (called once after identity is set)
786
+ */
787
+ initialize(): Promise<boolean>;
788
+ /**
789
+ * Shutdown provider
790
+ */
791
+ shutdown(): Promise<void>;
792
+ /**
793
+ * Save token data
794
+ */
795
+ save(data: TData): Promise<SaveResult>;
796
+ /**
797
+ * Load token data
798
+ */
799
+ load(identifier?: string): Promise<LoadResult<TData>>;
800
+ /**
801
+ * Sync local data with remote
802
+ */
803
+ sync(localData: TData): Promise<SyncResult<TData>>;
804
+ /**
805
+ * Check if data exists
806
+ */
807
+ exists?(identifier?: string): Promise<boolean>;
808
+ /**
809
+ * Clear all data
810
+ */
811
+ clear?(): Promise<boolean>;
812
+ /**
813
+ * Subscribe to storage events
814
+ */
815
+ onEvent?(callback: StorageEventCallback): () => void;
816
+ /**
817
+ * Save individual token (for file-based storage like lottery pattern)
818
+ */
819
+ saveToken?(tokenId: string, tokenData: unknown): Promise<void>;
820
+ /**
821
+ * Get individual token
822
+ */
823
+ getToken?(tokenId: string): Promise<unknown | null>;
824
+ /**
825
+ * List all token IDs
826
+ */
827
+ listTokenIds?(): Promise<string[]>;
828
+ /**
829
+ * Delete individual token
830
+ */
831
+ deleteToken?(tokenId: string): Promise<void>;
832
+ }
833
+ type StorageEventType = 'storage:saving' | 'storage:saved' | 'storage:loading' | 'storage:loaded' | 'storage:error' | 'sync:started' | 'sync:completed' | 'sync:conflict' | 'sync:error';
834
+ interface StorageEvent {
835
+ type: StorageEventType;
836
+ timestamp: number;
837
+ data?: unknown;
838
+ error?: string;
839
+ }
840
+ type StorageEventCallback = (event: StorageEvent) => void;
841
+ interface TxfStorageDataBase {
842
+ _meta: TxfMeta;
843
+ _tombstones?: TxfTombstone[];
844
+ _outbox?: TxfOutboxEntry[];
845
+ _sent?: TxfSentEntry[];
846
+ _invalid?: TxfInvalidEntry[];
847
+ [key: `_${string}`]: unknown;
848
+ }
849
+ interface TxfMeta {
850
+ version: number;
851
+ address: string;
852
+ ipnsName?: string;
853
+ formatVersion: string;
854
+ updatedAt: number;
855
+ }
856
+ interface TxfTombstone {
857
+ tokenId: string;
858
+ stateHash: string;
859
+ timestamp: number;
860
+ }
861
+ interface TxfOutboxEntry {
862
+ id: string;
863
+ status: string;
864
+ tokenId: string;
865
+ recipient: string;
866
+ createdAt: number;
867
+ data: unknown;
868
+ }
869
+ interface TxfSentEntry {
870
+ tokenId: string;
871
+ recipient: string;
872
+ txHash: string;
873
+ sentAt: number;
874
+ }
875
+ interface TxfInvalidEntry {
876
+ tokenId: string;
877
+ reason: string;
878
+ detectedAt: number;
879
+ }
880
+
881
+ /**
882
+ * Transport Provider Interface
883
+ * Platform-independent P2P messaging abstraction
884
+ */
885
+
886
+ /**
887
+ * P2P messaging transport provider
888
+ */
889
+ interface TransportProvider extends BaseProvider {
890
+ /**
891
+ * Set identity for signing/encryption
892
+ */
893
+ setIdentity(identity: FullIdentity): void;
894
+ /**
895
+ * Send encrypted direct message
896
+ * @returns Event ID
897
+ */
898
+ sendMessage(recipientPubkey: string, content: string): Promise<string>;
899
+ /**
900
+ * Subscribe to incoming direct messages
901
+ * @returns Unsubscribe function
902
+ */
903
+ onMessage(handler: MessageHandler): () => void;
904
+ /**
905
+ * Send token transfer payload
906
+ * @returns Event ID
907
+ */
908
+ sendTokenTransfer(recipientPubkey: string, payload: TokenTransferPayload): Promise<string>;
909
+ /**
910
+ * Subscribe to incoming token transfers
911
+ * @returns Unsubscribe function
912
+ */
913
+ onTokenTransfer(handler: TokenTransferHandler): () => void;
914
+ /**
915
+ * Resolve nametag to public key
916
+ */
917
+ resolveNametag?(nametag: string): Promise<string | null>;
918
+ /**
919
+ * Register a nametag for this identity
920
+ * @returns true if successful, false if already taken
921
+ */
922
+ registerNametag?(nametag: string, publicKey: string): Promise<boolean>;
923
+ /**
924
+ * Publish nametag binding
925
+ */
926
+ publishNametag?(nametag: string, address: string): Promise<void>;
927
+ /**
928
+ * Subscribe to broadcast messages (global/channel)
929
+ */
930
+ subscribeToBroadcast?(tags: string[], handler: BroadcastHandler): () => void;
931
+ /**
932
+ * Publish broadcast message
933
+ */
934
+ publishBroadcast?(content: string, tags?: string[]): Promise<string>;
935
+ /**
936
+ * Send payment request to a recipient
937
+ * @returns Event ID
938
+ */
939
+ sendPaymentRequest?(recipientPubkey: string, request: PaymentRequestPayload): Promise<string>;
940
+ /**
941
+ * Subscribe to incoming payment requests
942
+ * @returns Unsubscribe function
943
+ */
944
+ onPaymentRequest?(handler: PaymentRequestHandler): () => void;
945
+ /**
946
+ * Send response to a payment request
947
+ * @returns Event ID
948
+ */
949
+ sendPaymentRequestResponse?(recipientPubkey: string, response: PaymentRequestResponsePayload): Promise<string>;
950
+ /**
951
+ * Subscribe to incoming payment request responses
952
+ * @returns Unsubscribe function
953
+ */
954
+ onPaymentRequestResponse?(handler: PaymentRequestResponseHandler): () => void;
955
+ /**
956
+ * Get list of configured relay URLs
957
+ */
958
+ getRelays?(): string[];
959
+ /**
960
+ * Get list of currently connected relay URLs
961
+ */
962
+ getConnectedRelays?(): string[];
963
+ /**
964
+ * Add a relay dynamically
965
+ * @returns true if added successfully
966
+ */
967
+ addRelay?(relayUrl: string): Promise<boolean>;
968
+ /**
969
+ * Remove a relay dynamically
970
+ * @returns true if removed successfully
971
+ */
972
+ removeRelay?(relayUrl: string): Promise<boolean>;
973
+ /**
974
+ * Check if a relay is configured
975
+ */
976
+ hasRelay?(relayUrl: string): boolean;
977
+ /**
978
+ * Check if a relay is currently connected
979
+ */
980
+ isRelayConnected?(relayUrl: string): boolean;
981
+ }
982
+ interface IncomingMessage {
983
+ id: string;
984
+ senderPubkey: string;
985
+ content: string;
986
+ timestamp: number;
987
+ encrypted: boolean;
988
+ }
989
+ type MessageHandler = (message: IncomingMessage) => void;
990
+ interface TokenTransferPayload {
991
+ /** Serialized token data */
992
+ token: string;
993
+ /** Inclusion proof */
994
+ proof: unknown;
995
+ /** Optional memo */
996
+ memo?: string;
997
+ /** Sender info */
998
+ sender?: {
999
+ pubkey: string;
1000
+ nametag?: string;
1001
+ };
1002
+ }
1003
+ interface IncomingTokenTransfer {
1004
+ id: string;
1005
+ senderPubkey: string;
1006
+ payload: TokenTransferPayload;
1007
+ timestamp: number;
1008
+ }
1009
+ type TokenTransferHandler = (transfer: IncomingTokenTransfer) => void;
1010
+ interface PaymentRequestPayload {
1011
+ /** Amount requested (in smallest units) */
1012
+ amount: string | bigint;
1013
+ /** Coin/token type ID */
1014
+ coinId: string;
1015
+ /** Message/memo for recipient */
1016
+ message?: string;
1017
+ /** Recipient's nametag (who should pay) */
1018
+ recipientNametag?: string;
1019
+ /** Custom metadata */
1020
+ metadata?: Record<string, unknown>;
1021
+ }
1022
+ interface IncomingPaymentRequest {
1023
+ /** Event ID */
1024
+ id: string;
1025
+ /** Sender's public key */
1026
+ senderPubkey: string;
1027
+ /** Parsed request data */
1028
+ request: {
1029
+ requestId: string;
1030
+ amount: string;
1031
+ coinId: string;
1032
+ message?: string;
1033
+ recipientNametag?: string;
1034
+ metadata?: Record<string, unknown>;
1035
+ };
1036
+ /** Timestamp */
1037
+ timestamp: number;
1038
+ }
1039
+ type PaymentRequestHandler = (request: IncomingPaymentRequest) => void;
1040
+ type PaymentRequestResponseType = 'accepted' | 'rejected' | 'paid';
1041
+ interface PaymentRequestResponsePayload {
1042
+ /** Original request ID */
1043
+ requestId: string;
1044
+ /** Response type */
1045
+ responseType: PaymentRequestResponseType;
1046
+ /** Optional message */
1047
+ message?: string;
1048
+ /** Transfer ID (if paid) */
1049
+ transferId?: string;
1050
+ }
1051
+ interface IncomingPaymentRequestResponse {
1052
+ /** Event ID */
1053
+ id: string;
1054
+ /** Responder's public key */
1055
+ responderPubkey: string;
1056
+ /** Parsed response data */
1057
+ response: {
1058
+ requestId: string;
1059
+ responseType: PaymentRequestResponseType;
1060
+ message?: string;
1061
+ transferId?: string;
1062
+ };
1063
+ /** Timestamp */
1064
+ timestamp: number;
1065
+ }
1066
+ type PaymentRequestResponseHandler = (response: IncomingPaymentRequestResponse) => void;
1067
+ interface IncomingBroadcast {
1068
+ id: string;
1069
+ authorPubkey: string;
1070
+ content: string;
1071
+ tags: string[];
1072
+ timestamp: number;
1073
+ }
1074
+ type BroadcastHandler = (broadcast: IncomingBroadcast) => void;
1075
+
1076
+ /**
1077
+ * Oracle Provider Interface
1078
+ * Platform-independent Unicity oracle abstraction
1079
+ *
1080
+ * The oracle is a trusted third-party service that provides verifiable truth
1081
+ * about the state of tokens in the Unicity network. It aggregates state
1082
+ * transitions into rounds and provides inclusion proofs that cryptographically
1083
+ * verify token ownership and transfers.
1084
+ */
1085
+
1086
+ /**
1087
+ * Unicity state transition oracle provider
1088
+ *
1089
+ * The oracle serves as the source of truth for:
1090
+ * - Token state validation (spent/unspent)
1091
+ * - State transition inclusion proofs
1092
+ * - Round-based commitment aggregation
1093
+ */
1094
+ interface OracleProvider extends BaseProvider {
1095
+ /**
1096
+ * Initialize with trust base
1097
+ */
1098
+ initialize(trustBase?: unknown): Promise<void>;
1099
+ /**
1100
+ * Submit transfer commitment
1101
+ */
1102
+ submitCommitment(commitment: TransferCommitment): Promise<SubmitResult>;
1103
+ /**
1104
+ * Get inclusion proof for a request
1105
+ */
1106
+ getProof(requestId: string): Promise<InclusionProof | null>;
1107
+ /**
1108
+ * Wait for inclusion proof with polling
1109
+ */
1110
+ waitForProof(requestId: string, options?: WaitOptions): Promise<InclusionProof>;
1111
+ /**
1112
+ * Validate token against aggregator
1113
+ */
1114
+ validateToken(tokenData: unknown): Promise<ValidationResult>;
1115
+ /**
1116
+ * Check if token state is spent
1117
+ */
1118
+ isSpent(stateHash: string): Promise<boolean>;
1119
+ /**
1120
+ * Get token state
1121
+ */
1122
+ getTokenState(tokenId: string): Promise<TokenState | null>;
1123
+ /**
1124
+ * Get current round number
1125
+ */
1126
+ getCurrentRound(): Promise<number>;
1127
+ /**
1128
+ * Mint new tokens (for faucet/testing)
1129
+ */
1130
+ mint?(params: MintParams): Promise<MintResult>;
1131
+ /**
1132
+ * Get underlying StateTransitionClient (if available)
1133
+ * Used for advanced SDK operations like commitment creation
1134
+ */
1135
+ getStateTransitionClient?(): unknown;
1136
+ /**
1137
+ * Get underlying AggregatorClient (if available)
1138
+ * Used for direct aggregator API access
1139
+ */
1140
+ getAggregatorClient?(): unknown;
1141
+ /**
1142
+ * Wait for inclusion proof using SDK commitment (if available)
1143
+ * Used for transfer flows with SDK TransferCommitment
1144
+ */
1145
+ waitForProofSdk?(commitment: unknown, signal?: AbortSignal): Promise<unknown>;
1146
+ }
1147
+ interface TransferCommitment {
1148
+ /** Source token (SDK format) */
1149
+ sourceToken: unknown;
1150
+ /** Recipient address/predicate */
1151
+ recipient: string;
1152
+ /** Random salt (non-reproducible) */
1153
+ salt: Uint8Array;
1154
+ /** Optional additional data */
1155
+ data?: unknown;
1156
+ }
1157
+ interface SubmitResult {
1158
+ success: boolean;
1159
+ requestId?: string;
1160
+ error?: string;
1161
+ timestamp: number;
1162
+ }
1163
+ interface InclusionProof {
1164
+ requestId: string;
1165
+ roundNumber: number;
1166
+ proof: unknown;
1167
+ timestamp: number;
1168
+ }
1169
+ interface WaitOptions {
1170
+ /** Timeout in ms (default: 30000) */
1171
+ timeout?: number;
1172
+ /** Poll interval in ms (default: 1000) */
1173
+ pollInterval?: number;
1174
+ /** Callback on each poll attempt */
1175
+ onPoll?: (attempt: number) => void;
1176
+ }
1177
+ interface ValidationResult {
1178
+ valid: boolean;
1179
+ spent: boolean;
1180
+ error?: string;
1181
+ stateHash?: string;
1182
+ }
1183
+ interface TokenState {
1184
+ tokenId: string;
1185
+ stateHash: string;
1186
+ spent: boolean;
1187
+ roundNumber?: number;
1188
+ lastUpdated: number;
1189
+ }
1190
+ interface MintParams {
1191
+ coinId: string;
1192
+ amount: string;
1193
+ recipientAddress: string;
1194
+ recipientPubkey?: string;
1195
+ }
1196
+ interface MintResult {
1197
+ success: boolean;
1198
+ requestId?: string;
1199
+ tokenId?: string;
1200
+ error?: string;
1201
+ }
1202
+
1203
+ /**
1204
+ * Payments Module
1205
+ * Platform-independent token operations with full wallet repository functionality
1206
+ *
1207
+ * Includes:
1208
+ * - Token CRUD operations
1209
+ * - Tombstones for sync
1210
+ * - Archived tokens (spent history)
1211
+ * - Forked tokens (alternative histories)
1212
+ * - Transaction history
1213
+ * - Nametag storage
1214
+ */
1215
+
1216
+ interface TransactionHistoryEntry {
1217
+ id: string;
1218
+ type: 'SENT' | 'RECEIVED' | 'SPLIT' | 'MINT';
1219
+ amount: string;
1220
+ coinId: string;
1221
+ symbol: string;
1222
+ timestamp: number;
1223
+ recipientNametag?: string;
1224
+ senderPubkey?: string;
1225
+ txHash?: string;
1226
+ }
1227
+ interface PaymentsModuleConfig {
1228
+ /** Auto-sync after operations */
1229
+ autoSync?: boolean;
1230
+ /** Auto-validate with aggregator */
1231
+ autoValidate?: boolean;
1232
+ /** Retry failed transfers */
1233
+ retryFailed?: boolean;
1234
+ /** Max retry attempts */
1235
+ maxRetries?: number;
1236
+ /** Enable debug logging */
1237
+ debug?: boolean;
1238
+ /** L1 (ALPHA blockchain) configuration */
1239
+ l1?: L1PaymentsModuleConfig;
1240
+ }
1241
+ interface PaymentsModuleDependencies {
1242
+ identity: FullIdentity;
1243
+ storage: StorageProvider;
1244
+ /** @deprecated Use tokenStorageProviders instead */
1245
+ tokenStorage?: TokenStorageProvider<TxfStorageDataBase>;
1246
+ /** Multiple token storage providers (e.g., IPFS, MongoDB, file) */
1247
+ tokenStorageProviders?: Map<string, TokenStorageProvider<TxfStorageDataBase>>;
1248
+ transport: TransportProvider;
1249
+ oracle: OracleProvider;
1250
+ emitEvent: <T extends SphereEventType>(type: T, data: SphereEventMap[T]) => void;
1251
+ /** Chain code for BIP32 HD derivation (for L1 multi-address support) */
1252
+ chainCode?: string;
1253
+ /** Additional L1 addresses to watch */
1254
+ l1Addresses?: string[];
1255
+ }
1256
+ declare class PaymentsModule {
1257
+ private readonly moduleConfig;
1258
+ private deps;
1259
+ /** L1 (ALPHA blockchain) payments sub-module (null if disabled) */
1260
+ readonly l1: L1PaymentsModule | null;
1261
+ private tokens;
1262
+ private pendingTransfers;
1263
+ private tombstones;
1264
+ private archivedTokens;
1265
+ private forkedTokens;
1266
+ private transactionHistory;
1267
+ private nametag;
1268
+ private paymentRequests;
1269
+ private paymentRequestHandlers;
1270
+ private outgoingPaymentRequests;
1271
+ private paymentRequestResponseHandlers;
1272
+ private pendingResponseResolvers;
1273
+ private unsubscribeTransfers;
1274
+ private unsubscribePaymentRequests;
1275
+ private unsubscribePaymentRequestResponses;
1276
+ constructor(config?: PaymentsModuleConfig);
1277
+ /** Get module configuration */
1278
+ getConfig(): Omit<Required<PaymentsModuleConfig>, 'l1'>;
1279
+ private log;
1280
+ /**
1281
+ * Initialize module with dependencies
1282
+ */
1283
+ initialize(deps: PaymentsModuleDependencies): void;
1284
+ /**
1285
+ * Load tokens from storage
1286
+ */
1287
+ load(): Promise<void>;
1288
+ /**
1289
+ * Cleanup resources
1290
+ */
1291
+ destroy(): void;
1292
+ /**
1293
+ * Send tokens to recipient
1294
+ * Supports automatic token splitting when exact amount is needed
1295
+ */
1296
+ send(request: TransferRequest): Promise<TransferResult>;
1297
+ /**
1298
+ * Get coin symbol from coinId
1299
+ */
1300
+ private getCoinSymbol;
1301
+ /**
1302
+ * Get coin name from coinId
1303
+ */
1304
+ private getCoinName;
1305
+ /**
1306
+ * Send a payment request to someone
1307
+ * @param recipientPubkeyOrNametag - Recipient's pubkey or @nametag
1308
+ * @param request - Payment request details
1309
+ * @returns Result with event ID
1310
+ */
1311
+ sendPaymentRequest(recipientPubkeyOrNametag: string, request: Omit<PaymentRequest, 'id' | 'createdAt'>): Promise<PaymentRequestResult>;
1312
+ /**
1313
+ * Subscribe to incoming payment requests
1314
+ * @param handler - Handler function for incoming requests
1315
+ * @returns Unsubscribe function
1316
+ */
1317
+ onPaymentRequest(handler: PaymentRequestHandler$1): () => void;
1318
+ /**
1319
+ * Get all payment requests
1320
+ * @param filter - Optional status filter
1321
+ */
1322
+ getPaymentRequests(filter?: {
1323
+ status?: PaymentRequestStatus;
1324
+ }): IncomingPaymentRequest$1[];
1325
+ /**
1326
+ * Get pending payment requests count
1327
+ */
1328
+ getPendingPaymentRequestsCount(): number;
1329
+ /**
1330
+ * Accept a payment request (marks it as accepted, user should then call send())
1331
+ */
1332
+ acceptPaymentRequest(requestId: string): Promise<void>;
1333
+ /**
1334
+ * Reject a payment request
1335
+ */
1336
+ rejectPaymentRequest(requestId: string): Promise<void>;
1337
+ /**
1338
+ * Mark a payment request as paid (after successful transfer)
1339
+ */
1340
+ markPaymentRequestPaid(requestId: string): void;
1341
+ /**
1342
+ * Clear processed (non-pending) payment requests
1343
+ */
1344
+ clearProcessedPaymentRequests(): void;
1345
+ /**
1346
+ * Remove a specific payment request
1347
+ */
1348
+ removePaymentRequest(requestId: string): void;
1349
+ /**
1350
+ * Pay a payment request directly
1351
+ * Convenience method that accepts, sends, and marks as paid
1352
+ */
1353
+ payPaymentRequest(requestId: string, memo?: string): Promise<TransferResult>;
1354
+ private updatePaymentRequestStatus;
1355
+ private handleIncomingPaymentRequest;
1356
+ /**
1357
+ * Get outgoing payment requests
1358
+ * @param filter - Optional status filter
1359
+ */
1360
+ getOutgoingPaymentRequests(filter?: {
1361
+ status?: PaymentRequestStatus;
1362
+ }): OutgoingPaymentRequest[];
1363
+ /**
1364
+ * Subscribe to payment request responses (for outgoing requests)
1365
+ * @param handler - Handler function for incoming responses
1366
+ * @returns Unsubscribe function
1367
+ */
1368
+ onPaymentRequestResponse(handler: PaymentRequestResponseHandler$1): () => void;
1369
+ /**
1370
+ * Wait for a response to a payment request
1371
+ * @param requestId - The outgoing request ID to wait for
1372
+ * @param timeoutMs - Timeout in milliseconds (default: 60000)
1373
+ * @returns Promise that resolves with the response or rejects on timeout
1374
+ */
1375
+ waitForPaymentResponse(requestId: string, timeoutMs?: number): Promise<PaymentRequestResponse>;
1376
+ /**
1377
+ * Cancel waiting for a payment response
1378
+ */
1379
+ cancelWaitForPaymentResponse(requestId: string): void;
1380
+ /**
1381
+ * Remove an outgoing payment request
1382
+ */
1383
+ removeOutgoingPaymentRequest(requestId: string): void;
1384
+ /**
1385
+ * Clear completed/expired outgoing payment requests
1386
+ */
1387
+ clearCompletedOutgoingPaymentRequests(): void;
1388
+ private handlePaymentRequestResponse;
1389
+ /**
1390
+ * Send a response to a payment request (used internally by accept/reject/pay methods)
1391
+ */
1392
+ private sendPaymentRequestResponse;
1393
+ /**
1394
+ * Get balance for coin type
1395
+ */
1396
+ getBalance(coinId?: string): TokenBalance[];
1397
+ /**
1398
+ * Get all tokens
1399
+ */
1400
+ getTokens(filter?: {
1401
+ coinId?: string;
1402
+ status?: TokenStatus;
1403
+ }): Token[];
1404
+ /**
1405
+ * Get single token
1406
+ */
1407
+ getToken(id: string): Token | undefined;
1408
+ /**
1409
+ * Add a token
1410
+ * @returns false if duplicate
1411
+ */
1412
+ addToken(token: Token, skipHistory?: boolean): Promise<boolean>;
1413
+ /**
1414
+ * Save token as individual file to token storage providers
1415
+ * Similar to lottery's saveReceivedToken() pattern
1416
+ */
1417
+ private saveTokenToFileStorage;
1418
+ /**
1419
+ * Load tokens from file storage providers (lottery compatibility)
1420
+ * This loads tokens from file-based storage that may have been saved
1421
+ * by other applications using the same storage directory.
1422
+ */
1423
+ private loadTokensFromFileStorage;
1424
+ /**
1425
+ * Update an existing token
1426
+ */
1427
+ updateToken(token: Token): Promise<void>;
1428
+ /**
1429
+ * Remove a token by ID
1430
+ */
1431
+ removeToken(tokenId: string, recipientNametag?: string, skipHistory?: boolean): Promise<void>;
1432
+ /**
1433
+ * Get all tombstones
1434
+ */
1435
+ getTombstones(): TombstoneEntry[];
1436
+ /**
1437
+ * Check if token state is tombstoned
1438
+ */
1439
+ isStateTombstoned(tokenId: string, stateHash: string): boolean;
1440
+ /**
1441
+ * Merge remote tombstones
1442
+ * @returns number of local tokens removed
1443
+ */
1444
+ mergeTombstones(remoteTombstones: TombstoneEntry[]): Promise<number>;
1445
+ /**
1446
+ * Prune old tombstones
1447
+ */
1448
+ pruneTombstones(maxAge?: number): Promise<void>;
1449
+ /**
1450
+ * Get archived tokens
1451
+ */
1452
+ getArchivedTokens(): Map<string, TxfToken>;
1453
+ /**
1454
+ * Get best archived version of a token
1455
+ */
1456
+ getBestArchivedVersion(tokenId: string): TxfToken | null;
1457
+ /**
1458
+ * Merge remote archived tokens
1459
+ * @returns number of tokens updated/added
1460
+ */
1461
+ mergeArchivedTokens(remoteArchived: Map<string, TxfToken>): Promise<number>;
1462
+ /**
1463
+ * Prune archived tokens
1464
+ */
1465
+ pruneArchivedTokens(maxCount?: number): Promise<void>;
1466
+ /**
1467
+ * Get forked tokens
1468
+ */
1469
+ getForkedTokens(): Map<string, TxfToken>;
1470
+ /**
1471
+ * Store a forked token
1472
+ */
1473
+ storeForkedToken(tokenId: string, stateHash: string, txfToken: TxfToken): Promise<void>;
1474
+ /**
1475
+ * Merge remote forked tokens
1476
+ * @returns number of tokens added
1477
+ */
1478
+ mergeForkedTokens(remoteForked: Map<string, TxfToken>): Promise<number>;
1479
+ /**
1480
+ * Prune forked tokens
1481
+ */
1482
+ pruneForkedTokens(maxCount?: number): Promise<void>;
1483
+ /**
1484
+ * Get transaction history
1485
+ */
1486
+ getHistory(): TransactionHistoryEntry[];
1487
+ /**
1488
+ * Add to transaction history
1489
+ */
1490
+ addToHistory(entry: Omit<TransactionHistoryEntry, 'id'>): Promise<void>;
1491
+ /**
1492
+ * Set nametag for current identity
1493
+ */
1494
+ setNametag(nametag: NametagData): Promise<void>;
1495
+ /**
1496
+ * Get nametag
1497
+ */
1498
+ getNametag(): NametagData | null;
1499
+ /**
1500
+ * Check if has nametag
1501
+ */
1502
+ hasNametag(): boolean;
1503
+ /**
1504
+ * Clear nametag
1505
+ */
1506
+ clearNametag(): Promise<void>;
1507
+ /**
1508
+ * Save nametag to file storage for lottery compatibility
1509
+ * Creates file: nametag-{name}.json
1510
+ */
1511
+ private saveNametagToFileStorage;
1512
+ /**
1513
+ * Load nametag from file storage (lottery compatibility)
1514
+ * Looks for file: nametag-{name}.json
1515
+ */
1516
+ private loadNametagFromFileStorage;
1517
+ /**
1518
+ * Mint a nametag token on-chain (like Sphere wallet and lottery)
1519
+ * This creates the nametag token required for receiving tokens via PROXY addresses
1520
+ *
1521
+ * @param nametag - The nametag to mint (e.g., "alice" or "@alice")
1522
+ * @returns MintNametagResult with success status and token if successful
1523
+ */
1524
+ mintNametag(nametag: string): Promise<MintNametagResult>;
1525
+ /**
1526
+ * Check if a nametag is available for minting
1527
+ * @param nametag - The nametag to check (e.g., "alice" or "@alice")
1528
+ */
1529
+ isNametagAvailable(nametag: string): Promise<boolean>;
1530
+ /**
1531
+ * Sync with all token storage providers (IPFS, MongoDB, etc.)
1532
+ * Syncs with each provider and merges results
1533
+ */
1534
+ sync(): Promise<{
1535
+ added: number;
1536
+ removed: number;
1537
+ }>;
1538
+ /**
1539
+ * Get all active token storage providers
1540
+ */
1541
+ private getTokenStorageProviders;
1542
+ /**
1543
+ * Update token storage providers (called when providers are added/removed dynamically)
1544
+ */
1545
+ updateTokenStorageProviders(providers: Map<string, TokenStorageProvider<TxfStorageDataBase>>): void;
1546
+ /**
1547
+ * Validate tokens with aggregator
1548
+ */
1549
+ validate(): Promise<{
1550
+ valid: Token[];
1551
+ invalid: Token[];
1552
+ }>;
1553
+ /**
1554
+ * Get pending transfers
1555
+ */
1556
+ getPendingTransfers(): TransferResult[];
1557
+ private resolveRecipient;
1558
+ /**
1559
+ * Create SDK TransferCommitment for a token transfer
1560
+ */
1561
+ private createSdkCommitment;
1562
+ /**
1563
+ * Create SigningService from identity private key
1564
+ */
1565
+ private createSigningService;
1566
+ /**
1567
+ * Resolve recipient to IAddress
1568
+ */
1569
+ private resolveRecipientAddress;
1570
+ private handleIncomingTransfer;
1571
+ private archiveToken;
1572
+ private save;
1573
+ private saveToOutbox;
1574
+ private removeFromOutbox;
1575
+ private loadOutbox;
1576
+ private createStorageData;
1577
+ private loadFromStorageData;
1578
+ private ensureInitialized;
1579
+ }
1580
+
1581
+ /**
1582
+ * Communications Module
1583
+ * Platform-independent messaging operations
1584
+ */
1585
+
1586
+ interface CommunicationsModuleConfig {
1587
+ /** Auto-save messages */
1588
+ autoSave?: boolean;
1589
+ /** Max messages in memory */
1590
+ maxMessages?: number;
1591
+ /** Enable read receipts */
1592
+ readReceipts?: boolean;
1593
+ }
1594
+ interface CommunicationsModuleDependencies {
1595
+ identity: FullIdentity;
1596
+ storage: StorageProvider;
1597
+ transport: TransportProvider;
1598
+ emitEvent: <T extends SphereEventType>(type: T, data: SphereEventMap[T]) => void;
1599
+ }
1600
+ declare class CommunicationsModule {
1601
+ private config;
1602
+ private deps;
1603
+ private messages;
1604
+ private broadcasts;
1605
+ private unsubscribeMessages;
1606
+ private broadcastSubscriptions;
1607
+ private dmHandlers;
1608
+ private broadcastHandlers;
1609
+ constructor(config?: CommunicationsModuleConfig);
1610
+ /**
1611
+ * Initialize module with dependencies
1612
+ */
1613
+ initialize(deps: CommunicationsModuleDependencies): void;
1614
+ /**
1615
+ * Load messages from storage
1616
+ */
1617
+ load(): Promise<void>;
1618
+ /**
1619
+ * Cleanup resources
1620
+ */
1621
+ destroy(): void;
1622
+ /**
1623
+ * Send direct message
1624
+ */
1625
+ sendDM(recipient: string, content: string): Promise<DirectMessage>;
1626
+ /**
1627
+ * Get conversation with peer
1628
+ */
1629
+ getConversation(peerPubkey: string): DirectMessage[];
1630
+ /**
1631
+ * Get all conversations grouped by peer
1632
+ */
1633
+ getConversations(): Map<string, DirectMessage[]>;
1634
+ /**
1635
+ * Mark messages as read
1636
+ */
1637
+ markAsRead(messageIds: string[]): Promise<void>;
1638
+ /**
1639
+ * Get unread count
1640
+ */
1641
+ getUnreadCount(peerPubkey?: string): number;
1642
+ /**
1643
+ * Subscribe to incoming DMs
1644
+ */
1645
+ onDirectMessage(handler: (message: DirectMessage) => void): () => void;
1646
+ /**
1647
+ * Publish broadcast message
1648
+ */
1649
+ broadcast(content: string, tags?: string[]): Promise<BroadcastMessage>;
1650
+ /**
1651
+ * Subscribe to broadcasts with tags
1652
+ */
1653
+ subscribeToBroadcasts(tags: string[]): () => void;
1654
+ /**
1655
+ * Get broadcasts
1656
+ */
1657
+ getBroadcasts(limit?: number): BroadcastMessage[];
1658
+ /**
1659
+ * Subscribe to incoming broadcasts
1660
+ */
1661
+ onBroadcast(handler: (message: BroadcastMessage) => void): () => void;
1662
+ private handleIncomingMessage;
1663
+ private handleIncomingBroadcast;
1664
+ private save;
1665
+ private pruneIfNeeded;
1666
+ private resolveRecipient;
1667
+ private ensureInitialized;
1668
+ }
1669
+
1670
+ /** Network configurations */
1671
+ declare const NETWORKS: {
1672
+ readonly mainnet: {
1673
+ readonly name: "Mainnet";
1674
+ readonly aggregatorUrl: "https://aggregator.unicity.network/rpc";
1675
+ readonly nostrRelays: readonly ["wss://relay.unicity.network", "wss://relay.damus.io", "wss://nos.lol", "wss://relay.nostr.band"];
1676
+ readonly ipfsGateways: readonly ["https://ipfs.unicity.network", "https://dweb.link", "https://ipfs.io"];
1677
+ readonly electrumUrl: "wss://fulcrum.alpha.unicity.network:50004";
1678
+ };
1679
+ readonly testnet: {
1680
+ readonly name: "Testnet";
1681
+ readonly aggregatorUrl: "https://goggregator-test.unicity.network";
1682
+ readonly nostrRelays: readonly ["wss://nostr-relay.testnet.unicity.network"];
1683
+ readonly ipfsGateways: readonly ["https://ipfs.unicity.network", "https://dweb.link", "https://ipfs.io"];
1684
+ readonly electrumUrl: "wss://fulcrum.alpha.testnet.unicity.network:50004";
1685
+ };
1686
+ readonly dev: {
1687
+ readonly name: "Development";
1688
+ readonly aggregatorUrl: "https://dev-aggregator.dyndns.org/rpc";
1689
+ readonly nostrRelays: readonly ["wss://nostr-relay.testnet.unicity.network"];
1690
+ readonly ipfsGateways: readonly ["https://ipfs.unicity.network", "https://dweb.link", "https://ipfs.io"];
1691
+ readonly electrumUrl: "wss://fulcrum.alpha.testnet.unicity.network:50004";
1692
+ };
1693
+ };
1694
+ type NetworkType = keyof typeof NETWORKS;
1695
+
1696
+ /**
1697
+ * Legacy File Serialization Types
1698
+ */
1699
+
1700
+ type LegacyFileType = 'dat' | 'txt' | 'json' | 'mnemonic' | 'unknown';
1701
+ /**
1702
+ * Progress callback for decryption operations
1703
+ */
1704
+ type DecryptionProgressCallback = (iteration: number, total: number) => Promise<void> | void;
1705
+
1706
+ /** Options for creating a new wallet */
1707
+ interface SphereCreateOptions {
1708
+ /** BIP39 mnemonic (12 or 24 words) */
1709
+ mnemonic: string;
1710
+ /** Custom derivation path (default: m/44'/0'/0') */
1711
+ derivationPath?: string;
1712
+ /** Optional nametag to register for this wallet (e.g., 'alice' for @alice). Token is auto-minted. */
1713
+ nametag?: string;
1714
+ /** Storage provider instance */
1715
+ storage: StorageProvider;
1716
+ /** Optional token storage provider (for IPFS sync) */
1717
+ tokenStorage?: TokenStorageProvider<TxfStorageDataBase>;
1718
+ /** Transport provider instance */
1719
+ transport: TransportProvider;
1720
+ /** Oracle provider instance */
1721
+ oracle: OracleProvider;
1722
+ /** L1 (ALPHA blockchain) configuration */
1723
+ l1?: L1Config;
1724
+ /**
1725
+ * Network type (mainnet, testnet, dev) - informational only.
1726
+ * Actual network configuration comes from provider URLs.
1727
+ * Use createBrowserProviders({ network: 'testnet' }) to set up testnet providers.
1728
+ */
1729
+ network?: NetworkType;
1730
+ }
1731
+ /** Options for loading existing wallet */
1732
+ interface SphereLoadOptions {
1733
+ /** Storage provider instance */
1734
+ storage: StorageProvider;
1735
+ /** Optional token storage provider (for IPFS sync) */
1736
+ tokenStorage?: TokenStorageProvider<TxfStorageDataBase>;
1737
+ /** Transport provider instance */
1738
+ transport: TransportProvider;
1739
+ /** Oracle provider instance */
1740
+ oracle: OracleProvider;
1741
+ /** L1 (ALPHA blockchain) configuration */
1742
+ l1?: L1Config;
1743
+ /**
1744
+ * Network type (mainnet, testnet, dev) - informational only.
1745
+ * Actual network configuration comes from provider URLs.
1746
+ * Use createBrowserProviders({ network: 'testnet' }) to set up testnet providers.
1747
+ */
1748
+ network?: NetworkType;
1749
+ }
1750
+ /** Options for importing a wallet */
1751
+ interface SphereImportOptions {
1752
+ /** BIP39 mnemonic to import */
1753
+ mnemonic?: string;
1754
+ /** Or master private key (hex) */
1755
+ masterKey?: string;
1756
+ /** Chain code for BIP32 (optional) */
1757
+ chainCode?: string;
1758
+ /** Custom derivation path */
1759
+ derivationPath?: string;
1760
+ /** Base path for BIP32 derivation (e.g., "m/84'/1'/0'" from wallet.dat) */
1761
+ basePath?: string;
1762
+ /** Derivation mode: bip32, wif_hmac, legacy_hmac */
1763
+ derivationMode?: DerivationMode;
1764
+ /** Optional nametag to register for this wallet (e.g., 'alice' for @alice). Token is auto-minted. */
1765
+ nametag?: string;
1766
+ /** Storage provider instance */
1767
+ storage: StorageProvider;
1768
+ /** Optional token storage provider */
1769
+ tokenStorage?: TokenStorageProvider<TxfStorageDataBase>;
1770
+ /** Transport provider instance */
1771
+ transport: TransportProvider;
1772
+ /** Oracle provider instance */
1773
+ oracle: OracleProvider;
1774
+ /** L1 (ALPHA blockchain) configuration */
1775
+ l1?: L1Config;
1776
+ }
1777
+ /** L1 (ALPHA blockchain) configuration */
1778
+ interface L1Config {
1779
+ /** Fulcrum WebSocket URL (default: wss://fulcrum.alpha.unicity.network:50004) */
1780
+ electrumUrl?: string;
1781
+ /** Default fee rate in sat/byte (default: 10) */
1782
+ defaultFeeRate?: number;
1783
+ /** Enable vesting classification (default: true) */
1784
+ enableVesting?: boolean;
1785
+ }
1786
+ /** Options for unified init (auto-create or load) */
1787
+ interface SphereInitOptions {
1788
+ /** Storage provider instance */
1789
+ storage: StorageProvider;
1790
+ /** Transport provider instance */
1791
+ transport: TransportProvider;
1792
+ /** Oracle provider instance */
1793
+ oracle: OracleProvider;
1794
+ /** Optional token storage provider (for IPFS sync) */
1795
+ tokenStorage?: TokenStorageProvider<TxfStorageDataBase>;
1796
+ /** BIP39 mnemonic - if wallet doesn't exist, use this to create */
1797
+ mnemonic?: string;
1798
+ /** Auto-generate mnemonic if wallet doesn't exist and no mnemonic provided */
1799
+ autoGenerate?: boolean;
1800
+ /** Custom derivation path (default: m/44'/0'/0') */
1801
+ derivationPath?: string;
1802
+ /** Optional nametag to register (only on create). Token is auto-minted. */
1803
+ nametag?: string;
1804
+ /** L1 (ALPHA blockchain) configuration */
1805
+ l1?: L1Config;
1806
+ /**
1807
+ * Network type (mainnet, testnet, dev) - informational only.
1808
+ * Actual network configuration comes from provider URLs.
1809
+ * Use createBrowserProviders({ network: 'testnet' }) to set up testnet providers.
1810
+ */
1811
+ network?: NetworkType;
1812
+ }
1813
+ /** Result of init operation */
1814
+ interface SphereInitResult {
1815
+ /** The initialized Sphere instance */
1816
+ sphere: Sphere;
1817
+ /** Whether wallet was newly created */
1818
+ created: boolean;
1819
+ /** Generated mnemonic (only if autoGenerate was used) */
1820
+ generatedMnemonic?: string;
1821
+ }
1822
+ declare class Sphere {
1823
+ private static instance;
1824
+ private _initialized;
1825
+ private _identity;
1826
+ private _masterKey;
1827
+ private _mnemonic;
1828
+ private _source;
1829
+ private _derivationMode;
1830
+ private _basePath;
1831
+ private _currentAddressIndex;
1832
+ private _addressNametags;
1833
+ private _storage;
1834
+ private _tokenStorageProviders;
1835
+ private _transport;
1836
+ private _oracle;
1837
+ private _payments;
1838
+ private _communications;
1839
+ private eventHandlers;
1840
+ private constructor();
1841
+ /**
1842
+ * Check if wallet exists in storage
1843
+ */
1844
+ static exists(storage: StorageProvider): Promise<boolean>;
1845
+ /**
1846
+ * Initialize wallet - auto-loads existing or creates new
1847
+ *
1848
+ * @example
1849
+ * ```ts
1850
+ * // Load existing or create with provided mnemonic
1851
+ * const { sphere, created } = await Sphere.init({
1852
+ * storage,
1853
+ * transport,
1854
+ * oracle,
1855
+ * mnemonic: 'your twelve words...',
1856
+ * });
1857
+ *
1858
+ * // Load existing or auto-generate new mnemonic
1859
+ * const { sphere, created, generatedMnemonic } = await Sphere.init({
1860
+ * storage,
1861
+ * transport,
1862
+ * oracle,
1863
+ * autoGenerate: true,
1864
+ * });
1865
+ * if (generatedMnemonic) {
1866
+ * console.log('Save this mnemonic:', generatedMnemonic);
1867
+ * }
1868
+ * ```
1869
+ */
1870
+ static init(options: SphereInitOptions): Promise<SphereInitResult>;
1871
+ /**
1872
+ * Create new wallet with mnemonic
1873
+ */
1874
+ static create(options: SphereCreateOptions): Promise<Sphere>;
1875
+ /**
1876
+ * Load existing wallet from storage
1877
+ */
1878
+ static load(options: SphereLoadOptions): Promise<Sphere>;
1879
+ /**
1880
+ * Import wallet from mnemonic or master key
1881
+ */
1882
+ static import(options: SphereImportOptions): Promise<Sphere>;
1883
+ /**
1884
+ * Clear wallet data from storage
1885
+ */
1886
+ static clear(storage: StorageProvider): Promise<void>;
1887
+ /**
1888
+ * Get current instance
1889
+ */
1890
+ static getInstance(): Sphere | null;
1891
+ /**
1892
+ * Check if initialized
1893
+ */
1894
+ static isInitialized(): boolean;
1895
+ /**
1896
+ * Validate mnemonic using BIP39
1897
+ */
1898
+ static validateMnemonic(mnemonic: string): boolean;
1899
+ /**
1900
+ * Generate new BIP39 mnemonic
1901
+ * @param strength - 128 for 12 words, 256 for 24 words
1902
+ */
1903
+ static generateMnemonic(strength?: 128 | 256): string;
1904
+ /** Payments module (L3 + L1) */
1905
+ get payments(): PaymentsModule;
1906
+ /** Communications module */
1907
+ get communications(): CommunicationsModule;
1908
+ /** Current identity (public info only) */
1909
+ get identity(): Identity | null;
1910
+ /** Is ready */
1911
+ get isReady(): boolean;
1912
+ getStorage(): StorageProvider;
1913
+ /**
1914
+ * Get first token storage provider (for backward compatibility)
1915
+ * @deprecated Use getTokenStorageProviders() for multiple providers
1916
+ */
1917
+ getTokenStorage(): TokenStorageProvider<TxfStorageDataBase> | undefined;
1918
+ /**
1919
+ * Get all token storage providers
1920
+ */
1921
+ getTokenStorageProviders(): Map<string, TokenStorageProvider<TxfStorageDataBase>>;
1922
+ /**
1923
+ * Add a token storage provider dynamically (e.g., from UI)
1924
+ * Provider will be initialized and connected automatically
1925
+ */
1926
+ addTokenStorageProvider(provider: TokenStorageProvider<TxfStorageDataBase>): Promise<void>;
1927
+ /**
1928
+ * Remove a token storage provider dynamically
1929
+ */
1930
+ removeTokenStorageProvider(providerId: string): Promise<boolean>;
1931
+ /**
1932
+ * Check if a token storage provider is registered
1933
+ */
1934
+ hasTokenStorageProvider(providerId: string): boolean;
1935
+ getTransport(): TransportProvider;
1936
+ getAggregator(): OracleProvider;
1937
+ /**
1938
+ * Check if wallet has BIP32 master key for HD derivation
1939
+ */
1940
+ hasMasterKey(): boolean;
1941
+ /**
1942
+ * Get the base derivation path used by this wallet (e.g., "m/44'/0'/0'")
1943
+ */
1944
+ getBasePath(): string;
1945
+ /**
1946
+ * Get the default address path (first external address)
1947
+ * Returns path like "m/44'/0'/0'/0/0"
1948
+ */
1949
+ getDefaultAddressPath(): string;
1950
+ /**
1951
+ * Get current derivation mode
1952
+ */
1953
+ getDerivationMode(): DerivationMode;
1954
+ /**
1955
+ * Get the mnemonic phrase (for backup purposes)
1956
+ * Returns null if wallet was imported from file (masterKey only)
1957
+ */
1958
+ getMnemonic(): string | null;
1959
+ /**
1960
+ * Get wallet info for backup/export purposes
1961
+ */
1962
+ getWalletInfo(): WalletInfo;
1963
+ /**
1964
+ * Export wallet to JSON format for backup
1965
+ *
1966
+ * @example
1967
+ * ```ts
1968
+ * // Export with mnemonic (if available)
1969
+ * const json = sphere.exportToJSON();
1970
+ *
1971
+ * // Export with encryption
1972
+ * const encrypted = sphere.exportToJSON({ password: 'secret' });
1973
+ *
1974
+ * // Export multiple addresses
1975
+ * const multi = sphere.exportToJSON({ addressCount: 5 });
1976
+ * ```
1977
+ */
1978
+ exportToJSON(options?: WalletJSONExportOptions): WalletJSON;
1979
+ /**
1980
+ * Export wallet to text format for backup
1981
+ *
1982
+ * @example
1983
+ * ```ts
1984
+ * // Export unencrypted
1985
+ * const text = sphere.exportToTxt();
1986
+ *
1987
+ * // Export with encryption
1988
+ * const encrypted = sphere.exportToTxt({ password: 'secret' });
1989
+ *
1990
+ * // Export multiple addresses
1991
+ * const multi = sphere.exportToTxt({ addressCount: 5 });
1992
+ * ```
1993
+ */
1994
+ exportToTxt(options?: {
1995
+ password?: string;
1996
+ addressCount?: number;
1997
+ }): string;
1998
+ /**
1999
+ * Import wallet from JSON backup
2000
+ *
2001
+ * @returns Object with success status and optionally recovered mnemonic
2002
+ *
2003
+ * @example
2004
+ * ```ts
2005
+ * const json = '{"version":"1.0",...}';
2006
+ * const { success, mnemonic } = await Sphere.importFromJSON({
2007
+ * jsonContent: json,
2008
+ * password: 'secret', // if encrypted
2009
+ * storage, transport, oracle,
2010
+ * });
2011
+ * ```
2012
+ */
2013
+ static importFromJSON(options: {
2014
+ jsonContent: string;
2015
+ password?: string;
2016
+ storage: StorageProvider;
2017
+ transport: TransportProvider;
2018
+ oracle: OracleProvider;
2019
+ tokenStorage?: TokenStorageProvider<TxfStorageDataBase>;
2020
+ }): Promise<{
2021
+ success: boolean;
2022
+ mnemonic?: string;
2023
+ error?: string;
2024
+ }>;
2025
+ /**
2026
+ * Import wallet from legacy file (.dat, .txt, or mnemonic text)
2027
+ *
2028
+ * Supports:
2029
+ * - Bitcoin Core wallet.dat files (SQLite format, encrypted or unencrypted)
2030
+ * - Text backup files (UNICITY WALLET DETAILS format)
2031
+ * - Plain mnemonic text (12 or 24 words)
2032
+ *
2033
+ * @returns Object with success status, created Sphere instance, and optionally recovered mnemonic
2034
+ *
2035
+ * @example
2036
+ * ```ts
2037
+ * // Import from .dat file
2038
+ * const fileBuffer = await file.arrayBuffer();
2039
+ * const result = await Sphere.importFromLegacyFile({
2040
+ * fileContent: new Uint8Array(fileBuffer),
2041
+ * fileName: 'wallet.dat',
2042
+ * password: 'wallet-password', // if encrypted
2043
+ * storage, transport, oracle,
2044
+ * });
2045
+ *
2046
+ * // Import from .txt file
2047
+ * const textContent = await file.text();
2048
+ * const result = await Sphere.importFromLegacyFile({
2049
+ * fileContent: textContent,
2050
+ * fileName: 'backup.txt',
2051
+ * storage, transport, oracle,
2052
+ * });
2053
+ * ```
2054
+ */
2055
+ static importFromLegacyFile(options: {
2056
+ /** File content - Uint8Array for .dat, string for .txt */
2057
+ fileContent: string | Uint8Array;
2058
+ /** File name (used for type detection) */
2059
+ fileName: string;
2060
+ /** Password for encrypted files */
2061
+ password?: string;
2062
+ /** Progress callback for long decryption operations */
2063
+ onDecryptProgress?: DecryptionProgressCallback;
2064
+ /** Storage provider instance */
2065
+ storage: StorageProvider;
2066
+ /** Transport provider instance */
2067
+ transport: TransportProvider;
2068
+ /** Oracle provider instance */
2069
+ oracle: OracleProvider;
2070
+ /** Optional token storage provider */
2071
+ tokenStorage?: TokenStorageProvider<TxfStorageDataBase>;
2072
+ /** Optional nametag to register */
2073
+ nametag?: string;
2074
+ }): Promise<{
2075
+ success: boolean;
2076
+ sphere?: Sphere;
2077
+ mnemonic?: string;
2078
+ needsPassword?: boolean;
2079
+ error?: string;
2080
+ }>;
2081
+ /**
2082
+ * Detect legacy file type from filename and content
2083
+ */
2084
+ static detectLegacyFileType(fileName: string, content: string | Uint8Array): LegacyFileType;
2085
+ /**
2086
+ * Check if a legacy file is encrypted
2087
+ */
2088
+ static isLegacyFileEncrypted(fileName: string, content: string | Uint8Array): boolean;
2089
+ /**
2090
+ * Get the current active address index
2091
+ *
2092
+ * @example
2093
+ * ```ts
2094
+ * const currentIndex = sphere.getCurrentAddressIndex();
2095
+ * console.log(currentIndex); // 0
2096
+ *
2097
+ * await sphere.switchToAddress(2);
2098
+ * console.log(sphere.getCurrentAddressIndex()); // 2
2099
+ * ```
2100
+ */
2101
+ getCurrentAddressIndex(): number;
2102
+ /**
2103
+ * Get nametag for a specific address index
2104
+ *
2105
+ * @param index - Address index (default: current address)
2106
+ * @returns Nametag or undefined if not registered
2107
+ */
2108
+ getNametagForAddress(index?: number): string | undefined;
2109
+ /**
2110
+ * Get all registered address nametags
2111
+ *
2112
+ * @returns Map of address index to nametag
2113
+ */
2114
+ getAllAddressNametags(): Map<number, string>;
2115
+ /**
2116
+ * Switch to a different address by index
2117
+ * This changes the active identity to the derived address at the specified index.
2118
+ *
2119
+ * @param index - Address index to switch to (0, 1, 2, ...)
2120
+ *
2121
+ * @example
2122
+ * ```ts
2123
+ * // Switch to second address
2124
+ * await sphere.switchToAddress(1);
2125
+ * console.log(sphere.identity?.address); // alpha1... (address at index 1)
2126
+ *
2127
+ * // Register nametag for this address
2128
+ * await sphere.registerNametag('bob');
2129
+ *
2130
+ * // Switch back to first address
2131
+ * await sphere.switchToAddress(0);
2132
+ * ```
2133
+ */
2134
+ switchToAddress(index: number): Promise<void>;
2135
+ /**
2136
+ * Re-initialize modules after address switch
2137
+ */
2138
+ private reinitializeModulesForNewAddress;
2139
+ /**
2140
+ * Derive address at a specific index
2141
+ *
2142
+ * @param index - Address index (0, 1, 2, ...)
2143
+ * @param isChange - Whether this is a change address (default: false)
2144
+ * @returns Address info with privateKey, publicKey, address, path, index
2145
+ *
2146
+ * @example
2147
+ * ```ts
2148
+ * // Derive first receiving address
2149
+ * const addr0 = sphere.deriveAddress(0);
2150
+ * console.log(addr0.address); // alpha1...
2151
+ *
2152
+ * // Derive second receiving address
2153
+ * const addr1 = sphere.deriveAddress(1);
2154
+ *
2155
+ * // Derive change address
2156
+ * const change = sphere.deriveAddress(0, true);
2157
+ * ```
2158
+ */
2159
+ deriveAddress(index: number, isChange?: boolean): AddressInfo;
2160
+ /**
2161
+ * Derive address at a full BIP32 path
2162
+ *
2163
+ * @param path - Full BIP32 path like "m/44'/0'/0'/0/5"
2164
+ * @returns Address info
2165
+ *
2166
+ * @example
2167
+ * ```ts
2168
+ * const addr = sphere.deriveAddressAtPath("m/44'/0'/0'/0/5");
2169
+ * ```
2170
+ */
2171
+ deriveAddressAtPath(path: string): AddressInfo;
2172
+ /**
2173
+ * Derive multiple addresses starting from index 0
2174
+ *
2175
+ * @param count - Number of addresses to derive
2176
+ * @param includeChange - Include change addresses (default: false)
2177
+ * @returns Array of address info
2178
+ *
2179
+ * @example
2180
+ * ```ts
2181
+ * // Get first 5 receiving addresses
2182
+ * const addresses = sphere.deriveAddresses(5);
2183
+ *
2184
+ * // Get 5 receiving + 5 change addresses
2185
+ * const allAddresses = sphere.deriveAddresses(5, true);
2186
+ * ```
2187
+ */
2188
+ deriveAddresses(count: number, includeChange?: boolean): AddressInfo[];
2189
+ getStatus(): {
2190
+ storage: {
2191
+ connected: boolean;
2192
+ };
2193
+ transport: {
2194
+ connected: boolean;
2195
+ };
2196
+ oracle: {
2197
+ connected: boolean;
2198
+ };
2199
+ };
2200
+ reconnect(): Promise<void>;
2201
+ on<T extends SphereEventType>(type: T, handler: SphereEventHandler<T>): () => void;
2202
+ off<T extends SphereEventType>(type: T, handler: SphereEventHandler<T>): void;
2203
+ sync(): Promise<void>;
2204
+ /**
2205
+ * Get current nametag (if registered)
2206
+ */
2207
+ getNametag(): string | undefined;
2208
+ /**
2209
+ * Check if nametag is registered
2210
+ */
2211
+ hasNametag(): boolean;
2212
+ /**
2213
+ * Register a nametag for the current active address
2214
+ * Each address can have its own independent nametag
2215
+ *
2216
+ * @example
2217
+ * ```ts
2218
+ * // Register nametag for first address (index 0)
2219
+ * await sphere.registerNametag('alice');
2220
+ *
2221
+ * // Switch to second address and register different nametag
2222
+ * await sphere.switchToAddress(1);
2223
+ * await sphere.registerNametag('bob');
2224
+ *
2225
+ * // Now:
2226
+ * // - Address 0 has nametag @alice
2227
+ * // - Address 1 has nametag @bob
2228
+ * ```
2229
+ */
2230
+ registerNametag(nametag: string): Promise<void>;
2231
+ /**
2232
+ * Persist address nametags to storage
2233
+ */
2234
+ private persistAddressNametags;
2235
+ /**
2236
+ * Mint a nametag token on-chain (like Sphere wallet and lottery)
2237
+ * This creates the nametag token required for receiving tokens via PROXY addresses (@nametag)
2238
+ *
2239
+ * @param nametag - The nametag to mint (e.g., "alice" or "@alice")
2240
+ * @returns MintNametagResult with success status and token if successful
2241
+ *
2242
+ * @example
2243
+ * ```typescript
2244
+ * // Mint nametag token for receiving via @alice
2245
+ * const result = await sphere.mintNametag('alice');
2246
+ * if (result.success) {
2247
+ * console.log('Nametag minted:', result.nametagData?.name);
2248
+ * } else {
2249
+ * console.error('Mint failed:', result.error);
2250
+ * }
2251
+ * ```
2252
+ */
2253
+ mintNametag(nametag: string): Promise<MintNametagResult>;
2254
+ /**
2255
+ * Check if a nametag is available for minting
2256
+ * @param nametag - The nametag to check (e.g., "alice" or "@alice")
2257
+ * @returns true if available, false if taken or error
2258
+ */
2259
+ isNametagAvailable(nametag: string): Promise<boolean>;
2260
+ /**
2261
+ * Load address nametags from storage
2262
+ */
2263
+ private loadAddressNametags;
2264
+ /**
2265
+ * Sync nametag with Nostr on wallet load
2266
+ * If local nametag exists but not registered on Nostr, re-register it
2267
+ */
2268
+ private syncNametagWithNostr;
2269
+ /**
2270
+ * Validate nametag format
2271
+ */
2272
+ private validateNametag;
2273
+ destroy(): Promise<void>;
2274
+ private storeMnemonic;
2275
+ private storeMasterKey;
2276
+ /**
2277
+ * Mark wallet as fully created (after successful initialization)
2278
+ * This is called at the end of create()/import() to ensure wallet is only
2279
+ * marked as existing after all initialization steps succeed.
2280
+ */
2281
+ private finalizeWalletCreation;
2282
+ private loadIdentityFromStorage;
2283
+ private initializeIdentityFromMnemonic;
2284
+ private initializeIdentityFromMasterKey;
2285
+ private initializeProviders;
2286
+ private initializeModules;
2287
+ private ensureReady;
2288
+ private emitEvent;
2289
+ private encrypt;
2290
+ private decrypt;
2291
+ }
2292
+ declare const createSphere: typeof Sphere.create;
2293
+ declare const loadSphere: typeof Sphere.load;
2294
+ declare const importSphere: typeof Sphere.import;
2295
+ declare const initSphere: typeof Sphere.init;
2296
+ declare const getSphere: typeof Sphere.getInstance;
2297
+ declare const sphereExists: typeof Sphere.exists;
2298
+
2299
+ /**
2300
+ * Encryption utilities for SDK2
2301
+ *
2302
+ * Provides AES-256 encryption for sensitive wallet data.
2303
+ * Uses crypto-js for cross-platform compatibility.
2304
+ */
2305
+ interface EncryptedData {
2306
+ /** Encrypted ciphertext (base64) */
2307
+ ciphertext: string;
2308
+ /** Initialization vector (hex) */
2309
+ iv: string;
2310
+ /** Salt used for key derivation (hex) */
2311
+ salt: string;
2312
+ /** Algorithm identifier */
2313
+ algorithm: 'aes-256-cbc';
2314
+ /** Key derivation function */
2315
+ kdf: 'pbkdf2';
2316
+ /** Number of PBKDF2 iterations */
2317
+ iterations: number;
2318
+ }
2319
+ interface EncryptionOptions {
2320
+ /** Number of PBKDF2 iterations (default: 100000) */
2321
+ iterations?: number;
2322
+ }
2323
+ /**
2324
+ * Encrypt data with AES-256-CBC
2325
+ * @param plaintext - Data to encrypt (string or object)
2326
+ * @param password - Encryption password
2327
+ * @param options - Encryption options
2328
+ */
2329
+ declare function encrypt(plaintext: string | object, password: string, options?: EncryptionOptions): EncryptedData;
2330
+ /**
2331
+ * Decrypt AES-256-CBC encrypted data
2332
+ * @param encryptedData - Encrypted data object
2333
+ * @param password - Decryption password
2334
+ */
2335
+ declare function decrypt(encryptedData: EncryptedData, password: string): string;
2336
+ /**
2337
+ * Decrypt and parse JSON data
2338
+ * @param encryptedData - Encrypted data object
2339
+ * @param password - Decryption password
2340
+ */
2341
+ declare function decryptJson<T = unknown>(encryptedData: EncryptedData, password: string): T;
2342
+ /**
2343
+ * Simple encryption using CryptoJS built-in password-based encryption
2344
+ * Suitable for localStorage where we don't need full EncryptedData metadata
2345
+ * @param plaintext - Data to encrypt
2346
+ * @param password - Encryption password
2347
+ */
2348
+ declare function encryptSimple(plaintext: string, password: string): string;
2349
+ /**
2350
+ * Simple decryption
2351
+ * @param ciphertext - Encrypted string
2352
+ * @param password - Decryption password
2353
+ */
2354
+ declare function decryptSimple(ciphertext: string, password: string): string;
2355
+ /**
2356
+ * Encrypt mnemonic phrase for storage
2357
+ * Uses simple AES encryption compatible with existing wallet format
2358
+ * @param mnemonic - BIP39 mnemonic phrase
2359
+ * @param password - Encryption password
2360
+ */
2361
+ declare function encryptMnemonic(mnemonic: string, password: string): string;
2362
+ /**
2363
+ * Decrypt mnemonic phrase from storage
2364
+ * @param encryptedMnemonic - Encrypted mnemonic string
2365
+ * @param password - Decryption password
2366
+ */
2367
+ declare function decryptMnemonic(encryptedMnemonic: string, password: string): string;
2368
+ /**
2369
+ * Check if data looks like an EncryptedData object
2370
+ */
2371
+ declare function isEncryptedData(data: unknown): data is EncryptedData;
2372
+ /**
2373
+ * Serialize EncryptedData to string for storage
2374
+ */
2375
+ declare function serializeEncrypted(data: EncryptedData): string;
2376
+ /**
2377
+ * Deserialize EncryptedData from string
2378
+ */
2379
+ declare function deserializeEncrypted(serialized: string): EncryptedData;
2380
+ /**
2381
+ * Generate a random password/key as hex string
2382
+ * @param bytes - Number of random bytes (default: 32)
2383
+ */
2384
+ declare function generateRandomKey(bytes?: number): string;
2385
+
2386
+ /**
2387
+ * Currency Utilities
2388
+ * Conversion between human-readable amounts and smallest units (bigint)
2389
+ */
2390
+ /** Default token decimals (18 for most tokens) */
2391
+ declare const DEFAULT_TOKEN_DECIMALS = 18;
2392
+ /**
2393
+ * Convert human-readable amount to smallest unit (bigint)
2394
+ *
2395
+ * @example
2396
+ * ```ts
2397
+ * toSmallestUnit('1.5', 18) // 1500000000000000000n
2398
+ * toSmallestUnit('100', 6) // 100000000n
2399
+ * ```
2400
+ */
2401
+ declare function toSmallestUnit(amount: number | string, decimals?: number): bigint;
2402
+ /**
2403
+ * Convert smallest unit (bigint) to human-readable string
2404
+ *
2405
+ * @example
2406
+ * ```ts
2407
+ * toHumanReadable(1500000000000000000n, 18) // '1.5'
2408
+ * toHumanReadable(100000000n, 6) // '100'
2409
+ * ```
2410
+ */
2411
+ declare function toHumanReadable(amount: bigint | string, decimals?: number): string;
2412
+ /**
2413
+ * Format amount for display with optional symbol
2414
+ *
2415
+ * @example
2416
+ * ```ts
2417
+ * formatAmount(1500000000000000000n, { decimals: 18, symbol: 'ALPHA' })
2418
+ * // '1.5 ALPHA'
2419
+ * ```
2420
+ */
2421
+ declare function formatAmount(amount: bigint | string, options?: {
2422
+ decimals?: number;
2423
+ symbol?: string;
2424
+ maxFractionDigits?: number;
2425
+ }): string;
2426
+ declare const CurrencyUtils: {
2427
+ toSmallestUnit: typeof toSmallestUnit;
2428
+ toHumanReadable: typeof toHumanReadable;
2429
+ format: typeof formatAmount;
2430
+ };
2431
+
2432
+ /**
2433
+ * Bech32 Encoding/Decoding
2434
+ * BIP-173 implementation for address encoding
2435
+ */
2436
+ /** Bech32 character set from BIP-173 */
2437
+ declare const CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
2438
+ /**
2439
+ * Convert between bit arrays (8→5 or 5→8)
2440
+ */
2441
+ declare function convertBits(data: number[], fromBits: number, toBits: number, pad: boolean): number[] | null;
2442
+ /**
2443
+ * Encode data to bech32 address
2444
+ *
2445
+ * @example
2446
+ * ```ts
2447
+ * const address = encodeBech32('alpha', 1, pubkeyHash);
2448
+ * // 'alpha1qw...'
2449
+ * ```
2450
+ */
2451
+ declare function encodeBech32(hrp: string, version: number, program: Uint8Array): string;
2452
+ /**
2453
+ * Decode bech32 address
2454
+ *
2455
+ * @example
2456
+ * ```ts
2457
+ * const result = decodeBech32('alpha1qw...');
2458
+ * // { hrp: 'alpha', witnessVersion: 1, data: Uint8Array }
2459
+ * ```
2460
+ */
2461
+ declare function decodeBech32(addr: string): {
2462
+ hrp: string;
2463
+ witnessVersion: number;
2464
+ data: Uint8Array;
2465
+ } | null;
2466
+ /**
2467
+ * Create address from public key hash
2468
+ *
2469
+ * @example
2470
+ * ```ts
2471
+ * const address = createAddress('alpha', pubkeyHash);
2472
+ * // 'alpha1...'
2473
+ * ```
2474
+ */
2475
+ declare function createAddress(hrp: string, pubkeyHash: Uint8Array | string): string;
2476
+ /**
2477
+ * Validate bech32 address
2478
+ */
2479
+ declare function isValidBech32(addr: string): boolean;
2480
+ /**
2481
+ * Get HRP from address
2482
+ */
2483
+ declare function getAddressHrp(addr: string): string | null;
2484
+ /**
2485
+ * Alias for encodeBech32 (L1 SDK compatibility)
2486
+ */
2487
+ declare const createBech32: typeof encodeBech32;
2488
+
2489
+ /**
2490
+ * SDK Utility Functions
2491
+ * Pure utility functions for the wallet SDK
2492
+ */
2493
+ /**
2494
+ * Validate if a hex string is a valid secp256k1 private key
2495
+ * Must be 0 < key < n (curve order)
2496
+ */
2497
+ declare function isValidPrivateKey(hex: string): boolean;
2498
+ /**
2499
+ * Base58 encode hex string
2500
+ *
2501
+ * @example
2502
+ * ```ts
2503
+ * base58Encode('00f54a5851e9372b87810a8e60cdd2e7cfd80b6e31')
2504
+ * // '1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs'
2505
+ * ```
2506
+ */
2507
+ declare function base58Encode(hex: string): string;
2508
+ /**
2509
+ * Base58 decode string to Uint8Array
2510
+ *
2511
+ * @example
2512
+ * ```ts
2513
+ * base58Decode('1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs')
2514
+ * // Uint8Array [0, 245, 74, ...]
2515
+ * ```
2516
+ */
2517
+ declare function base58Decode(str: string): Uint8Array;
2518
+ /**
2519
+ * Find pattern in Uint8Array
2520
+ *
2521
+ * @param data - Data to search in
2522
+ * @param pattern - Pattern to find
2523
+ * @param startIndex - Start index for search
2524
+ * @returns Index of pattern or -1 if not found
2525
+ */
2526
+ declare function findPattern(data: Uint8Array, pattern: Uint8Array, startIndex?: number): number;
2527
+ /**
2528
+ * Extract value from text using regex pattern
2529
+ *
2530
+ * @param text - Text to search
2531
+ * @param pattern - Regex pattern with capture group
2532
+ * @returns Captured value or null
2533
+ */
2534
+ declare function extractFromText(text: string, pattern: RegExp): string | null;
2535
+ /**
2536
+ * Sleep for specified milliseconds
2537
+ */
2538
+ declare function sleep(ms: number): Promise<void>;
2539
+ /**
2540
+ * Generate random hex string of specified byte length
2541
+ */
2542
+ declare function randomHex(byteLength: number): string;
2543
+ /**
2544
+ * Generate random UUID v4
2545
+ */
2546
+ declare function randomUUID(): string;
2547
+
2548
+ export { type AddressInfo, CHARSET, CurrencyUtils, DEFAULT_DERIVATION_PATH, DEFAULT_TOKEN_DECIMALS, type DerivedKey, type EncryptedData, type EncryptionOptions, type KeyPair, type L1Config, type MasterKey, Sphere, type SphereCreateOptions, type SphereImportOptions, type SphereInitOptions, type SphereInitResult, type SphereLoadOptions, base58Decode, base58Encode, bytesToHex, computeHash160, convertBits, createAddress, createBech32, createKeyPair, createSphere, decodeBech32, decrypt, decryptJson, decryptMnemonic, decryptSimple, deriveAddressInfo, deriveChildKey, deriveKeyAtPath, deserializeEncrypted, doubleSha256, ec, encodeBech32, encrypt, encryptMnemonic, encryptSimple, entropyToMnemonic, extractFromText, findPattern, formatAmount, generateAddressInfo, generateMasterKey, generateMnemonic, generateRandomKey, getAddressHrp, getPublicKey, getSphere, hash160, hash160ToBytes, hexToBytes, identityFromMnemonic, identityFromMnemonicSync, importSphere, initSphere, isEncryptedData, isValidBech32, isValidPrivateKey, loadSphere, mnemonicToEntropy, mnemonicToSeed, mnemonicToSeedSync, privateKeyToAddressInfo, publicKeyToAddress, randomBytes, randomHex, randomUUID, ripemd160, serializeEncrypted, sha256, sleep, sphereExists, toHumanReadable, toSmallestUnit, validateMnemonic };