import { TXTypeValue, TransactionHash } from '@klever/connect-core'; import { NetworkURI, IBroadcastResponse, IProvider, TransferRequest, TransactionSubmitResult, ContractRequestData, Network } from '@klever/connect-provider'; export { TransferRequest } from '@klever/connect-provider'; import { Transaction } from '@klever/connect-transactions'; import { Signature, EncryptOptions, Keystore, MnemonicToKeyOptions } from '@klever/connect-crypto'; interface IPemResponse { privateKey: string; address: string; } interface IAccount { address: string; balance?: number; nonce?: number; allowance?: number; permissions?: string[]; rootHash?: string; txCount?: number; } interface IVerifyResponse { isValid: boolean; signer?: string; } interface IContractRequest { type: TXTypeValue; payload?: unknown; } interface ITxOptionsRequest { nonce?: number; kdaFee?: string; kAppFee?: number; bandwidthFee?: number; message?: string; } interface KleverWeb { address: string; provider: NetworkURI; createAccount(): Promise; getAccount(address?: string): Promise; parsePemFileData(pemData: string): Promise; broadcastTransactions(payload: Transaction[]): Promise; signTransaction(payload: Transaction | { [k: string]: unknown; }): Promise; setWalletAddress(payload: string): Promise; setPrivateKey(payload: string): Promise; getWalletAddress(): string; getProvider(): NetworkURI; signMessage(payload: string): Promise; validateSignature(message: string, signature: string, address: string): Promise; buildTransaction(contracts: IContractRequest[], txData?: string[], options?: ITxOptionsRequest): Promise; } interface KleverHub { initialize: () => Promise; onAccountChanged: (callback: (event: { chain: string | number; address: string; }) => void) => void; disconnect: () => Promise; } declare global { interface Window { kleverWeb?: KleverWeb; kleverHub?: KleverHub; } } interface WalletConfig { privateKey?: string; pemContent?: string; pemPassword?: string; network?: Network; provider?: IProvider; } interface Wallet { readonly address: string; readonly publicKey?: string; readonly provider?: IProvider; connect(): Promise; disconnect(clearPrivateKey?: boolean): Promise; isConnected(): boolean; signMessage(message: string | Uint8Array): Promise; signTransaction(tx: Transaction): Promise; transfer(params: TransferRequest): Promise; /** * Send any transaction type with properly typed parameters * @param contract - Complete contract request with contractType and parameters * @example * ```typescript * await wallet.sendTransaction({ * contractType: 0, // Transfer * receiver: 'klv1...', * amount: 1000000 * }) * ``` */ sendTransaction?(contract: ContractRequestData): Promise; broadcastTransaction?(tx: Transaction): Promise; broadcastTransactions?(txs: Transaction[]): Promise; getBalance(): Promise; getNonce(): Promise; /** * Encrypts the wallet's private key to a keystore format * @param password - The password to encrypt the keystore * @param options - Optional scrypt parameters for encryption strength * @returns A promise that resolves to the encrypted keystore object */ encrypt?(password: string, options?: EncryptOptions): Promise; on(event: WalletEvent, handler: WalletEventHandler): void; off(event: WalletEvent, handler: WalletEventHandler): void; removeAllListeners(event?: WalletEvent): void; } type WalletEvent = 'connect' | 'disconnect' | 'accountChanged'; type WalletEventHandler = (data: unknown) => void; interface WalletFactory$1 { createWallet(config?: WalletConfig): Promise; } /** * Abstract base wallet implementation providing common functionality * * BaseWallet implements the core wallet interface and provides shared functionality * for all wallet types. It handles: * - Provider management * - Event system (connect, disconnect, accountChanged) * - Balance and nonce queries * - Transaction broadcasting * - Message verification * * **Design Pattern:** * This class follows the Template Method pattern, where concrete implementations * (NodeWallet, BrowserWallet) provide specific implementations for: * - connect() - How to establish wallet connection * - disconnect() - How to clean up connection * - signMessage() - How to sign arbitrary messages * - signTransaction() - How to sign blockchain transactions * * **Common Functionality:** * All wallets inherit these capabilities: * - getBalance() - Query wallet balance * - getNonce() - Get transaction nonce * - verifyMessage() - Verify message signatures * - broadcastTransaction() - Send signed transactions to blockchain * - Event handling (on/off/emit) * * **Do Not Instantiate Directly:** * This is an abstract class. Use concrete implementations: * - NodeWallet for server-side Node.js applications * - BrowserWallet for browser/dApp applications * * @example * ```typescript * // Don't do this (abstract class): * // const wallet = new BaseWallet(provider) // ❌ Error * * // Do this instead: * import { NodeWallet } from '@klever/connect-wallet' * const wallet = new NodeWallet(provider, privateKey) // ✅ Correct * ``` */ declare abstract class BaseWallet implements Wallet { protected _provider: IProvider; protected _address: string; protected _publicKey: string; protected _connected: boolean; protected _events: Map>; constructor(provider: IProvider); /** Wallet address (bech32 format) */ get address(): string; /** Public key (hex format) */ get publicKey(): string; /** Provider instance for blockchain queries */ get provider(): IProvider; /** Connect to the wallet */ abstract connect(): Promise; /** Disconnect from the wallet */ abstract disconnect(clearPrivateKey?: boolean): Promise; /** Sign a message with the wallet's private key */ abstract signMessage(message: string | Uint8Array): Promise; /** Sign a transaction with the wallet's private key */ abstract signTransaction(unsignedTx: Transaction): Promise; /** * Verify a message signature * @param message - The message that was signed (string or bytes) * @param signature - The signature to verify (Signature object, hex string, or base64 string) * @returns true if signature is valid, false otherwise * * @example * ```typescript * const message = "Hello, Klever!" * const signature = await wallet.signMessage(message) * * // Verify with Signature object * const isValid = await wallet.verifyMessage(message, signature) * * // Or verify with hex string * const isValidHex = await wallet.verifyMessage(message, signature.toHex()) * * // Or verify with base64 string * const isValidBase64 = await wallet.verifyMessage(message, signature.toBase64()) * console.log('Signature valid:', isValid) * ``` */ verifyMessage(message: string | Uint8Array, signature: Signature | string): Promise; /** * Check if wallet is connected * @returns true if connected, false otherwise */ isConnected(): boolean; /** * Get wallet balance * @returns Balance in smallest units (KLV has 6 decimals) */ getBalance(): Promise; /** * Get current nonce for the wallet * Used for transaction ordering * @returns Current nonce value */ getNonce(): Promise; /** * Broadcast a single signed transaction to the network * Default implementation uses the provider's sendRawTransaction method * Can be overridden by child classes for custom behavior (e.g., extension broadcasting) */ broadcastTransaction(tx: Transaction): Promise; /** * Broadcast multiple signed transactions to the network in a single batch * Default implementation uses the provider's sendRawTransactions method * Can be overridden by child classes for custom behavior (e.g., extension broadcasting) */ broadcastTransactions(txs: Transaction[]): Promise; /** * Send a transaction with any contract type * Builds, signs, and broadcasts the transaction * Can be overridden by child classes (e.g., BrowserWallet uses extension) */ sendTransaction(contract: ContractRequestData): Promise; /** * Transfer tokens to another address * Convenience method that uses sendTransaction internally */ transfer(params: TransferRequest): Promise; /** * Register an event handler * @param event - Event name ('connect', 'disconnect', 'accountChanged') * @param handler - Event handler function */ on(event: WalletEvent, handler: WalletEventHandler): void; /** * Unregister an event handler * @param event - Event name * @param handler - Event handler function to remove */ off(event: WalletEvent, handler: WalletEventHandler): void; /** * Remove all event listeners for a specific event or all events * @param event - Optional event name. If not provided, removes all listeners for all events */ removeAllListeners(event?: WalletEvent): void; protected emit(event: WalletEvent, data?: unknown): void; } /** * Wallet implementation for browser environments * * BrowserWallet supports two modes of operation: * * **1. Extension Mode (Default):** * - Integrates with the Klever Browser Extension * - Users sign transactions through the extension UI * - Most secure for dApps - private keys never leave the extension * - Supports account switching and network changes * - Requires Klever Extension to be installed * * **2. Private Key Mode:** * - Direct signing using a private key (like NodeWallet) * - Useful for testing or non-extension wallets * - Can also use PEM files with optional password protection * - Less secure - private keys are in browser memory * * **Security Considerations:** * - Extension mode is recommended for production dApps * - Private key mode should only be used for testing or trusted environments * - Never expose private keys in production code * - Always validate transaction details before signing * * **Event Handling:** * - Emits 'accountChanged' when user switches accounts in extension * - Emits 'disconnect' when user switches to a different blockchain * - Events are debounced to prevent rapid firing * * @example * ```typescript * // Extension mode (recommended for dApps) * import { BrowserWallet } from '@klever/connect-wallet' * import { KleverProvider } from '@klever/connect-provider' * * const provider = new KleverProvider({ network: 'mainnet' }) * const wallet = new BrowserWallet(provider) * * try { * await wallet.connect() * console.log('Connected:', wallet.address) * * // Listen for account changes * wallet.on('accountChanged', ({ address }) => { * console.log('Account changed to:', address) * }) * * // Send a transaction (extension will prompt user) * const result = await wallet.transfer({ * receiver: 'klv1...', * amount: 1000000, * }) * console.log('Transaction hash:', result.hash) * } catch (error) { * if (error.message.includes('Extension not found')) { * console.log('Please install Klever Extension') * } * } * ``` * * @example * ```typescript * // Private key mode (testing only) * const wallet = new BrowserWallet(provider, { * privateKey: '0x123...', * }) * await wallet.connect() // No extension needed * ``` * * @example * ```typescript * // PEM file mode with password * const pemContent = '-----BEGIN PRIVATE KEY-----...' * const wallet = new BrowserWallet(provider, { * pemContent, * pemPassword: 'my-secure-password', * }) * await wallet.connect() * ``` */ declare class BrowserWallet extends BaseWallet { private _kleverWeb?; private _kleverHub?; private _privateKey?; private _mode; private _useExtensionBroadcast; private _lastEmittedAddress?; private _accountChangeDebounceTimer?; /** * Create a new BrowserWallet instance * * @param provider - Provider instance for blockchain communication * @param config - Optional wallet configuration * @param config.privateKey - Private key for private key mode (hex string) * @param config.pemContent - PEM file content for PEM mode * @param config.pemPassword - Optional password for encrypted PEM files * * @throws {WalletError} If used in non-browser environment * * @example * ```typescript * // Extension mode (default) * const wallet = new BrowserWallet(provider) * * // Private key mode * const wallet = new BrowserWallet(provider, { * privateKey: '0x123...', * }) * * // PEM mode * const wallet = new BrowserWallet(provider, { * pemContent: pemFileContent, * pemPassword: 'optional-password', * }) * ``` */ constructor(provider: IProvider, config?: WalletConfig); private _pendingPemLoad?; /** * Connect to the wallet * * **Extension Mode:** * - Checks for Klever Extension installation * - Retrieves the current wallet address from extension * - Sets up event listeners for account changes * - Prompts user if no wallet is connected in extension * * **Private Key Mode:** * - Derives address from the provided private key or PEM file * - No user interaction required * * @throws {WalletError} In extension mode: If extension is not installed or no wallet is connected * @throws {WalletError} In private key mode: If key is invalid or PEM decryption fails * * @fires connect - Emits when successfully connected with { address: string } * * @example * ```typescript * // Extension mode - user must have extension installed * const wallet = new BrowserWallet(provider) * try { * await wallet.connect() * console.log('Connected to:', wallet.address) * } catch (error) { * console.error('Extension not found or no wallet connected') * } * ``` * * @example * ```typescript * // Private key mode - instant connection * const wallet = new BrowserWallet(provider, { privateKey: '0x123...' }) * await wallet.connect() // No extension needed * ``` */ connect(): Promise; /** * Disconnect from the wallet * * **Extension Mode:** * - Disconnects from KleverHub * - Removes event listeners * - Clears connection state * * **Private Key Mode:** * - Clears connection state * - Optionally removes private key from memory (clearPrivateKey=true) * * @param clearPrivateKey - In private key mode, whether to clear the private key from memory (default: false) * - false: Keep key in memory for quick reconnection * - true: Remove key from memory (recommended for security) * * @fires disconnect - Emits when disconnected * * @example * ```typescript * // Extension mode * await wallet.disconnect() * * // Private key mode - clear key for security * await wallet.disconnect(true) * ``` */ disconnect(clearPrivateKey?: boolean): Promise; /** * Sign a message with the wallet's private key * * **SECURITY WARNING:** * - Only sign messages from trusted sources * - Verify message content before signing * - Extension mode will show a confirmation dialog to the user * - Malicious messages could trick users into authorizing unintended actions * * **Extension Mode:** * - Prompts user to confirm signing in extension UI * - User can review message before approving * - More secure as private key never leaves extension * * **Private Key Mode:** * - Signs immediately without user confirmation * - Use only in trusted environments * * @param message - Message to sign (string or bytes) * @returns Signature object with .toHex() and .toBase64() methods * * @throws {WalletError} If wallet is not connected * @throws {WalletError} If user rejects signing in extension mode * * @example * ```typescript * // Extension mode - user will see confirmation dialog * const message = "Sign in to My dApp" * const signature = await wallet.signMessage(message) * console.log('Signature:', signature.toHex()) * ``` * * @example * ```typescript * // Private key mode - immediate signing * const signature = await wallet.signMessage("Hello, Klever!") * const isValid = await wallet.verifyMessage("Hello, Klever!", signature) * ``` */ signMessage(message: string | Uint8Array): Promise; /** * Sign a transaction with the wallet's private key * * **SECURITY WARNING:** * - Always verify transaction details before signing * - Check recipient address, amount, and contract type * - Extension mode shows transaction details to user for review * - Signed transactions authorize blockchain state changes * * **Extension Mode:** * - Displays transaction in extension UI for user approval * - User can review all details before signing * - Most secure - private key never exposed * * **Private Key Mode:** * - Signs immediately without user confirmation * - Validate transaction parameters before calling * * @param unsignedTx - Unsigned transaction to sign * @returns Signed transaction ready for broadcast * * @throws {WalletError} If wallet is not connected * @throws {WalletError} If user rejects signing in extension mode * * @example * ```typescript * // Build a transaction * const unsignedTx = await wallet.buildTransaction([ * { * contractType: TXType.Transfer, * receiver: 'klv1...', * amount: '1000000', * } * ]) * * // Sign it (extension will prompt user) * const signedTx = await wallet.signTransaction(unsignedTx) * * // Broadcast * const hash = await wallet.broadcastTransaction(signedTx) * ``` */ signTransaction(unsignedTx: Transaction): Promise; /** * Build an unsigned transaction * * Creates a transaction with the specified contracts and parameters. * The transaction is built but not signed. * * **Extension Mode:** * - Uses KleverWeb extension's transaction builder * - Automatically fetches nonce and other parameters * * **Private Key Mode:** * - Uses TransactionBuilder with provider * - Fetches account data for proper transaction construction * * @param contracts - Array of contract requests to include in the transaction * @param txData - Optional transaction data (for smart contracts or metadata) * @param options - Optional transaction options * @param options.nonce - Manual nonce override (auto-fetched if not provided) * @param options.kdaFee - Asset ID to pay fees with (defaults to KLV) * * @returns Unsigned transaction ready to be signed * * @throws {WalletError} If wallet is not connected * @throws {WalletError} If transaction building fails * * @example * ```typescript * // Build a simple transfer * const tx = await wallet.buildTransaction([ * { * contractType: TXType.Transfer, * receiver: 'klv1...', * amount: '1000000', * } * ]) * * // Sign and broadcast * const signedTx = await wallet.signTransaction(tx) * const hash = await wallet.broadcastTransaction(signedTx) * ``` * * @example * ```typescript * // Build multi-contract transaction * const tx = await wallet.buildTransaction([ * { contractType: TXType.Transfer, receiver: 'klv1...', amount: '1000000' }, * { contractType: TXType.Claim, claimType: 0 }, * ]) * ``` * * @example * ```typescript * // Build with custom nonce and KDA fee * const tx = await wallet.buildTransaction( * [{ contractType: TXType.Transfer, receiver: 'klv1...', amount: '1000000' }], * undefined, * { nonce: 42, kdaFee: 'KFI' } * ) * ``` */ buildTransaction(contracts: ContractRequestData[], txData?: string[], options?: { nonce?: number; kdaFee?: string; }): Promise; /** * Broadcast multiple signed transactions to the network in a single batch * In extension mode: Uses KleverWeb extension * In private key mode: Uses provider.sendRawTransactions * @param signedTxs Array of signed transactions * @returns Array of transaction hashes */ broadcastTransactions(signedTxs: Transaction[]): Promise; /** * Build and sign a transfer transaction * * Convenience method that combines building and signing a transfer in one call. * * **Extension Mode:** * - Uses KleverWeb extension * - User confirms the transfer in extension UI * * **Private Key Mode:** * - Uses TransactionBuilder + local signing * - Signs immediately without confirmation * * @param to - Recipient address (bech32 format) * @param amount - Amount to transfer in smallest units (KLV has 6 decimals) * @param token - Optional token ID (defaults to 'KLV') * * @returns Signed transaction ready to broadcast * * @throws {WalletError} If wallet is not connected * @throws {WalletError} If user rejects in extension mode * * @example * ```typescript * // Transfer 1 KLV (1000000 smallest units) * const signedTx = await wallet.buildTransfer( * 'klv1...', * 1000000 * ) * const hash = await wallet.broadcastTransaction(signedTx) * ``` * * @example * ```typescript * // Transfer custom token * const signedTx = await wallet.buildTransfer( * 'klv1...', * 5000000, * 'KFI-ABC' // Custom token ID * ) * ``` */ buildTransfer(to: string, amount: string | number, token?: string): Promise; /** * Get the extension's current provider configuration * @returns Network URI configuration from the extension */ getExtensionProvider(): NetworkURI; /** * Update the provider for network switching * * This method updates both the extension's provider configuration (NetworkURI) * and the wallet's internal provider (IProvider) to ensure consistency during * network switches. * * @param provider - Can be either: * - NetworkURI: Updates only the extension's provider configuration * - IProvider: Updates the wallet's internal provider for blockchain operations * * @remarks * When switching networks, call this method twice: * 1. First with NetworkURI (network config) to update the extension * 2. Then with IProvider to update the wallet's internal provider * * @example * ```typescript * // Switch to mainnet * const networkConfig = getNetworkConfig('mainnet') * const newProvider = new KleverProvider({ network: 'mainnet' }) * * // Update both extension config and internal provider * wallet.updateProvider(networkConfig) // Extension config * wallet.updateProvider(newProvider) // Internal provider * ``` */ /** * Type guard to check if provider is an IProvider interface */ private isIProvider; /** * Type guard to check if provider is a NetworkURI */ private isNetworkURI; updateProvider(provider: NetworkURI | IProvider): void; /** * Create a new account using the extension * Extension mode only * @returns PEM response with private key and address */ createAccount(): Promise<{ privateKey: string; address: string; }>; /** * Get account information * In extension mode: Uses KleverWeb extension * In private key mode: Uses provider * @param address - Optional address to query (defaults to current wallet address) * @returns Account information */ getAccount(address?: string): Promise<{ address: string; balance?: number; nonce?: number; allowance?: number; permissions?: string[]; rootHash?: string; txCount?: number; }>; /** * Parse PEM file data using the extension * Extension mode only * @param pemData - PEM file content * @returns Private key and address from PEM */ parsePemFileData(pemData: string): Promise<{ privateKey: string; address: string; }>; /** * Set the wallet address in the extension * Extension mode only * @param address - Address to set */ setWalletAddress(address: string): Promise; /** * Set a private key in the extension * Extension mode only * @param privateKey - Private key to set */ setPrivateKey(privateKey: string): Promise; /** * Validate a signature using the extension * Extension mode only * @param message - The original message that was signed * @param signature - The signature to validate * @param address - The address of the expected signer * @returns Validation result with signer information */ validateSignature(message: string, signature: string, address: string): Promise<{ isValid: boolean; signer?: string; }>; /** * Extract transaction data from contract payload * Handles smart contract calls and regular transaction data */ private extractTxData; /** * Build standard payload from contract data * Filters out non-standard fields like function/args/data */ private buildStandardPayload; /** * Send a generic transaction * In extension mode: Uses KleverWeb extension for building and broadcasting * In private key mode: Uses base implementation (local signing + provider broadcast) */ sendTransaction(contract: ContractRequestData): Promise; /** * Transfer tokens to another address * In extension mode: Uses KleverWeb extension * In private key mode: Uses base implementation */ transfer(params: TransferRequest): Promise; /** * Encrypts the wallet's private key to a keystore format * * **Only available in private key mode** - extension mode wallets cannot be encrypted * as the private key is stored in the browser extension. * * Creates an encrypted keystore (Web3 Secret Storage format) that can be * saved and later decrypted using `WalletFactory.fromEncryptedJson()`. * * **Security Notes:** * - Use a strong password with mixed characters, numbers, and symbols * - The scryptN parameter controls encryption strength vs speed * - Higher scryptN = more secure but slower (default: 262144) * - Never store the password with the keystore * * @param password - The password to encrypt the keystore * @param options - Optional scrypt parameters for encryption strength * @param options.scryptN - Work factor (default: 262144, min: 4096) * @returns A promise that resolves to the encrypted keystore object * * @throws {WalletError} If wallet is not connected or in extension mode * * @example * ```typescript * // Private key mode only * const wallet = new BrowserWallet(provider, { privateKey: '0x123...' }) * await wallet.connect() * * // Encrypt with default parameters * const keystore = await wallet.encrypt('my-secure-password') * * // Save to localStorage or download as file * localStorage.setItem('wallet', JSON.stringify(keystore)) * ``` * * @example * ```typescript * // Encrypt with custom parameters (faster, for testing) * const testKeystore = await wallet.encrypt('password', { * scryptN: 4096 // Faster but less secure * }) * ``` */ encrypt(password: string, options?: EncryptOptions): Promise; } /** * Wallet implementation for Node.js environments * * NodeWallet provides secure wallet operations in server-side Node.js applications. * It uses private key-based signing and is designed for backend services, CLI tools, * and automated systems. * * **Security Considerations:** * - Private keys are stored in memory and should be handled with care * - Use environment variables or secure key management systems for production * - Never expose private keys in logs, error messages, or client-side code * - Consider using the `disconnect(true)` option to clear keys from memory when done * * **Environment:** * - Node.js only - will throw error if used in browser environments * - Use BrowserWallet for browser/dApp applications * * @example * ```typescript * import { KleverProvider } from '@klever/connect-provider' * import { NodeWallet } from '@klever/connect-wallet' * * // Create wallet with private key * const provider = new KleverProvider({ network: 'mainnet' }) * const wallet = new NodeWallet(provider, process.env.PRIVATE_KEY) * * // Connect and use * await wallet.connect() * console.log('Address:', wallet.address) * * // Send a transaction * const result = await wallet.transfer({ * receiver: 'klv1...', * amount: 1000000, // 1 KLV (6 decimals) * }) * console.log('Transaction hash:', result.hash) * * // Disconnect and clear private key from memory (recommended for security) * await wallet.disconnect(true) * ``` * * @example * ```typescript * // Generate a new random wallet * const newWallet = await NodeWallet.generate(provider) * await newWallet.connect() * console.log('New address:', newWallet.address) * ``` */ declare class NodeWallet extends BaseWallet { private _privateKey?; /** * Create a new NodeWallet instance * * @param provider - Provider instance for blockchain communication * @param privateKey - Optional private key as hex string. Can be set later with setPrivateKey() * * @throws {WalletError} If used in non-Node.js environment * @throws {WalletError} If private key format is invalid */ constructor(provider: IProvider, privateKey?: string); private importPrivateKey; /** * Connect the wallet * * Derives the public key and address from the private key and marks the wallet as connected. * This operation is performed locally without any network calls. * * @throws {WalletError} If no private key was provided during construction or via setPrivateKey() * @throws {WalletError} If the generated address is invalid * * @fires connect - Emits when successfully connected with { address: string } * * @example * ```typescript * const wallet = new NodeWallet(provider, privateKey) * await wallet.connect() * console.log('Connected:', wallet.address) * ``` */ connect(): Promise; /** * Disconnect from the wallet * * Clears the connection state and optionally removes the private key from memory. * * **Security Note:** * - By default (clearPrivateKey=false), the private key remains in memory for quick reconnection * - For enhanced security, set clearPrivateKey=true to completely remove the key from memory * - After clearing the private key, you must create a new wallet instance to reconnect * * @param clearPrivateKey - Whether to clear the private key from memory (default: false) * - false: Keep key in memory, can reconnect with connect() * - true: Remove key from memory, requires new wallet instance * * @fires disconnect - Emits when disconnected * * @example * ```typescript * // Disconnect but keep key for reconnection * await wallet.disconnect() * await wallet.connect() // Works - key still in memory * * // Disconnect and clear key (recommended for security) * await wallet.disconnect(true) * await wallet.connect() // Throws error - key cleared * ``` */ disconnect(clearPrivateKey?: boolean): Promise; /** * Sign a message with the wallet's private key * * **SECURITY WARNING:** * - Only sign messages from trusted sources * - Signing malicious messages can lead to phishing attacks * - Never sign messages that look like transactions or authorization requests * - Verify the message content before signing * * The message is signed using the Ed25519 signature scheme. The resulting signature * can be verified using the wallet's public key. * * @param message - Message to sign (string or raw bytes) * @returns Signature object with .toHex() and .toBase64() methods * * @throws {WalletError} If wallet is not connected or private key not available * * @example * ```typescript * const message = "Hello, Klever!" * const signature = await wallet.signMessage(message) * * // Get signature in different formats * console.log('Hex:', signature.toHex()) * console.log('Base64:', signature.toBase64()) * * // Verify the signature * const isValid = await wallet.verifyMessage(message, signature) * console.log('Valid:', isValid) // true * ``` * * @example * ```typescript * // Sign raw bytes * const data = new Uint8Array([1, 2, 3, 4]) * const signature = await wallet.signMessage(data) * ``` */ signMessage(message: string | Uint8Array): Promise; /** * Sign a transaction with the wallet's private key * * **SECURITY WARNING:** * - Always verify transaction details before signing * - Check recipient address, amount, and contract type * - Signing a transaction authorizes it to be broadcasted to the blockchain * - Signed transactions cannot be reversed once broadcasted * * The transaction is signed in-place, modifying the original transaction object * with the signature. The same transaction object is returned for convenience. * * @param tx - Unsigned transaction to sign * @returns The same transaction object, now signed * * @throws {WalletError} If wallet is not connected or private key not available * * @example * ```typescript * import { TransactionBuilder } from '@klever/connect-transactions' * * // Build a transaction * const builder = new TransactionBuilder(provider) * const unsignedTx = await builder * .transfer({ receiver: 'klv1...', amount: 1000000 }) * .sender(wallet.address) * .build() * * // Sign it * const signedTx = await wallet.signTransaction(unsignedTx) * * // Broadcast * const hash = await wallet.broadcastTransaction(signedTx) * console.log('Transaction hash:', hash) * ``` */ signTransaction(tx: Transaction): Promise; /** * Get the private key for internal use by child classes * * @returns The private key instance or undefined if not set * @internal */ protected getPrivateKey(): Uint8Array | undefined; /** * Set or change the private key * * **Security Note:** * Can only be called when wallet is disconnected to prevent accidental key changes * during active operations. * * @param privateKey - Private key as hex string * * @throws {WalletError} If wallet is currently connected * @throws {WalletError} If private key format is invalid * * @example * ```typescript * const wallet = new NodeWallet(provider) // No key yet * wallet.setPrivateKey(process.env.PRIVATE_KEY) * await wallet.connect() * ``` */ setPrivateKey(privateKey: string): void; /** * Generate a new wallet with a random private key * * Creates a new wallet instance with a cryptographically secure random private key. * The wallet is ready to connect and use immediately. * * **Important:** * - Save the private key securely - it cannot be recovered if lost * - Never share the private key with anyone * - Use environment variables or secure key management in production * * @param provider - Provider instance for blockchain communication * @returns New NodeWallet instance with generated key pair * * @example * ```typescript * import { KleverProvider } from '@klever/connect-provider' * import { NodeWallet } from '@klever/connect-wallet' * * const provider = new KleverProvider({ network: 'testnet' }) * const wallet = await NodeWallet.generate(provider) * * await wallet.connect() * console.log('New wallet address:', wallet.address) * * // IMPORTANT: Save the private key securely! * // You can extract it before connecting if needed for backup * ``` * * @example * ```typescript * // Generate multiple wallets for testing * const wallets = await Promise.all([ * NodeWallet.generate(provider), * NodeWallet.generate(provider), * NodeWallet.generate(provider), * ]) * * for (const wallet of wallets) { * await wallet.connect() * console.log('Generated address:', wallet.address) * } * ``` */ static generate(provider: IProvider): Promise; /** * Encrypts the wallet's private key to a keystore format * * Creates an encrypted keystore (Web3 Secret Storage format) that can be * saved to disk and later decrypted using `WalletFactory.fromEncryptedJson()`. * * **Security Notes:** * - Use a strong password with mixed characters, numbers, and symbols * - The scryptN parameter controls encryption strength vs speed * - Higher scryptN = more secure but slower (default: 262144) * - Never store the password with the keystore file * * @param password - The password to encrypt the keystore * @param options - Optional scrypt parameters for encryption strength * @param options.scryptN - Work factor (default: 262144, min: 4096) * @returns A promise that resolves to the encrypted keystore object * * @throws {WalletError} If wallet is not connected * * @example * ```typescript * const wallet = await NodeWallet.generate(provider) * await wallet.connect() * * // Encrypt with default parameters (most secure) * const keystore = await wallet.encrypt('my-secure-password') * * // Save to file * await fs.writeFile('keystore.json', JSON.stringify(keystore, null, 2)) * ``` * * @example * ```typescript * // Encrypt with custom parameters (faster, for testing) * const testKeystore = await wallet.encrypt('password', { * scryptN: 4096 // Faster but less secure * }) * ``` */ encrypt(password: string, options?: EncryptOptions): Promise; } /** * Factory for creating environment-appropriate wallet instances * * WalletFactory automatically detects the runtime environment (Node.js, Browser, React Native) * and creates the appropriate wallet implementation. This provides a unified API for * wallet creation across different platforms. * * **Automatic Environment Detection:** * - Node.js → Creates NodeWallet * - Browser → Creates BrowserWallet * - React Native → (Future support) * * **Benefits:** * - Write once, run anywhere - same code works in Node.js and browser * - Simplifies multi-platform dApp development * - Handles environment-specific wallet initialization * - Type-safe configuration * * @example * ```typescript * import { WalletFactory } from '@klever/connect-wallet' * import { KleverProvider } from '@klever/connect-provider' * * const provider = new KleverProvider({ network: 'mainnet' }) * const factory = new WalletFactory(provider) * * // In Node.js, this creates a NodeWallet * // In Browser, this creates a BrowserWallet * const wallet = await factory.createWallet({ * privateKey: process.env.PRIVATE_KEY, // Optional in browser (uses extension) * network: 'mainnet', * }) * * await wallet.connect() * console.log('Wallet address:', wallet.address) * ``` * * @example * ```typescript * // Browser-specific configuration * const wallet = await factory.createWallet({ * // No privateKey = uses extension in browser * // With privateKey = uses private key mode * privateKey: '0x123...', // Optional * }) * ``` * * @example * ```typescript * // Use the convenience function for simpler code * import { createWallet } from '@klever/connect-wallet' * * const wallet = await createWallet({ * network: 'testnet', * privateKey: process.env.PRIVATE_KEY, * }) * ``` */ declare class WalletFactory implements WalletFactory$1 { private provider; /** * Create a new WalletFactory instance * * @param provider - Optional provider instance. If not provided, creates a default KleverProvider */ constructor(provider?: IProvider); /** * Create a wallet instance appropriate for the current environment * * Detects the runtime environment and creates: * - NodeWallet in Node.js (requires privateKey) * - BrowserWallet in browsers (optional privateKey, defaults to extension mode) * - Throws error for React Native (not yet implemented) * * @param config - Optional wallet configuration * @param config.privateKey - Private key for wallet initialization (required for Node.js) * @param config.pemContent - PEM file content (alternative to privateKey) * @param config.pemPassword - Password for encrypted PEM files * @param config.network - Network to connect to ('mainnet', 'testnet', etc.) * @param config.provider - Override the factory's provider * * @returns Wallet instance ready to connect * * @throws {Error} If environment is React Native (not yet supported) * @throws {Error} If privateKey is not provided in Node.js environment * * @example * ```typescript * // Node.js environment * const wallet = await factory.createWallet({ * privateKey: process.env.PRIVATE_KEY, // Required * network: 'mainnet', * }) * ``` * * @example * ```typescript * // Browser environment - Extension mode * const wallet = await factory.createWallet({ * // No privateKey = uses Klever Extension * }) * ``` * * @example * ```typescript * // Browser environment - Private key mode * const wallet = await factory.createWallet({ * privateKey: '0x123...', // Uses private key instead of extension * }) * ``` */ createWallet(config?: WalletConfig): Promise; private createBrowserWallet; private createNodeWallet; /** * Create a new wallet with a randomly generated private key * * Creates a wallet appropriate for the current environment: * - Node.js → NodeWallet with random key * - Browser → BrowserWallet in private key mode with random key * * **Important:** * - Save the private key securely - it cannot be recovered if lost * - Never share the private key with anyone * - Use environment variables or secure key management in production * * @param provider - Optional custom provider (defaults to factory's provider) * @returns A promise that resolves to a new Wallet instance * * @example * ```typescript * const factory = new WalletFactory() * const wallet = await factory.createRandom() * await wallet.connect() * console.log('New address:', wallet.address) * ``` * * @example * ```typescript * // With custom provider * const testProvider = new KleverProvider({ network: 'testnet' }) * const wallet = await factory.createRandom(testProvider) * ``` */ createRandom(provider?: IProvider): Promise; /** * Converts a BIP39 mnemonic phrase to a private key (hex string) * * This is a utility method that derives a private key from a mnemonic without * creating a wallet instance. Useful when you only need the private key. * * @param mnemonic - The BIP39 mnemonic phrase (12-24 words) * @param options - Optional derivation path and passphrase * @returns The private key as a hexadecimal string * * @example * ```typescript * const factory = new WalletFactory() * const privateKey = factory.mnemonicToPrivateKey('abandon abandon abandon...') * console.log('Private key:', privateKey) * ``` * * @example * ```typescript * // With custom derivation path * const privateKey = factory.mnemonicToPrivateKey('abandon abandon abandon...', { * path: "m/44'/690'/0'/0'/1'" * }) * ``` */ mnemonicToPrivateKey(mnemonic: string, options?: MnemonicToKeyOptions): string; /** * Create a wallet from a BIP39 mnemonic phrase * * Creates a wallet appropriate for the current environment: * - Node.js → NodeWallet with derived key * - Browser → BrowserWallet in private key mode with derived key * * @param mnemonic - The BIP39 mnemonic phrase (12-24 words) * @param provider - Optional custom provider (defaults to factory's provider) * @param options - Optional derivation path and passphrase * @returns A promise that resolves to a new Wallet instance * * @example * ```typescript * const factory = new WalletFactory() * const wallet = await factory.fromMnemonic('abandon abandon abandon...') * await wallet.connect() * console.log('Address:', wallet.address) * ``` * * @example * ```typescript * // With custom derivation path * const wallet = await factory.fromMnemonic('abandon abandon abandon...', undefined, { * path: "m/44'/690'/0'/0'/1'" * }) * ``` * * @example * ```typescript * // With passphrase * const wallet = await factory.fromMnemonic('abandon abandon abandon...', undefined, { * passphrase: 'my-secret-passphrase' * }) * ``` */ fromMnemonic(mnemonic: string, provider?: IProvider, options?: MnemonicToKeyOptions): Promise; /** * Create a wallet from an encrypted keystore (Web3 Secret Storage) * * Creates a wallet appropriate for the current environment: * - Node.js → NodeWallet with decrypted key * - Browser → BrowserWallet in private key mode with decrypted key * * @param json - The keystore object or JSON string * @param password - The password to decrypt the keystore * @param provider - Optional custom provider (defaults to factory's provider) * @returns A promise that resolves to a new Wallet instance * * @throws Error if password is incorrect or keystore is invalid * * @example * ```typescript * const factory = new WalletFactory() * const wallet = await factory.fromEncryptedJson(keystore, 'my-password') * await wallet.connect() * console.log('Loaded wallet address:', wallet.address) * ``` * * @example * ```typescript * // From JSON string * const keystoreJson = await fs.readFile('keystore.json', 'utf-8') * const wallet = await factory.fromEncryptedJson(keystoreJson, 'my-password') * ``` */ fromEncryptedJson(json: Keystore | string, password: string, provider?: IProvider): Promise; } /** * Convenience function for creating environment-appropriate wallets * * This is a simplified wrapper around WalletFactory for quick wallet creation. * It automatically detects the environment and creates the appropriate wallet type. * * **When to use:** * - Quick prototyping and testing * - Simple applications with one wallet instance * - Default provider configuration is acceptable * * **When to use WalletFactory instead:** * - Need to reuse the same provider for multiple wallets * - Custom provider configuration required * - Creating multiple wallet instances * * @param config - Optional wallet configuration * @param config.privateKey - Private key (required in Node.js, optional in browser) * @param config.pemContent - PEM file content (alternative to privateKey) * @param config.pemPassword - Password for encrypted PEM files * @param config.network - Network to connect to * @param config.provider - Custom provider instance * * @returns Wallet instance appropriate for the current environment * * @example * ```typescript * // Simple usage with defaults * const wallet = await createWallet({ * privateKey: process.env.PRIVATE_KEY, * }) * await wallet.connect() * ``` * * @example * ```typescript * // Browser extension mode * const wallet = await createWallet() // No config needed * await wallet.connect() // Uses Klever Extension * ``` * * @example * ```typescript * // Custom network * const wallet = await createWallet({ * network: 'testnet', * privateKey: process.env.TEST_PRIVATE_KEY, * }) * ``` */ declare function createWallet(config?: WalletConfig): Promise; export { BaseWallet, BrowserWallet, type IAccount, type IContractRequest, type IPemResponse, type ITxOptionsRequest, type IVerifyResponse, type KleverHub, type KleverWeb, NodeWallet, type Wallet, type WalletConfig, type WalletEvent, type WalletEventHandler, WalletFactory, createWallet };