Class BrowserWallet
Hierarchy
- BaseWallet
- BrowserWallet (View Summary)
Index
Constructors
Properties
Accessors
Methods
Constructors
constructor
Create a new BrowserWallet instance
Parameters
- provider: IProvider
Provider instance for blockchain communication
Optionalconfig: WalletConfigOptional wallet configuration
privateKey
Private key for private key mode (hex string)
pemContent
PEM file content for PEM mode
pemPassword
Optional password for encrypted PEM files
Returns BrowserWallet
- provider: IProvider
Properties
Protected_address
Protected_connected
Protected_events
Protected_provider
Protected_publicKey
Accessors
address
- get address(): string
Wallet address (bech32 format)
Returns string
provider
Provider instance for blockchain queries
Returns IProvider
publicKey
- get publicKey(): string
Public key (hex format)
Returns string
Methods
broadcastTransaction
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)
Parameters
- tx: Transaction
Returns Promise<TransactionHash>
broadcastTransactions
Broadcast multiple signed transactions to the network in a single batch In extension mode: Uses KleverWeb extension In private key mode: Uses provider.sendRawTransactions
Parameters
- signedTxs: Transaction[]
Array of signed transactions
Returns Promise<TransactionHash[]>
Array of transaction hashes
- signedTxs: Transaction[]
buildTransaction
- buildTransaction(
contracts: ContractRequestData[],
txData?: string[],
options?: { kdaFee?: string; nonce?: number },
): Promise<Transaction>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
Parameters
- contracts: ContractRequestData[]
Array of contract requests to include in the transaction
OptionaltxData: string[]Optional transaction data (for smart contracts or metadata)
Optionaloptions: { kdaFee?: string; nonce?: number }Optional transaction options
OptionalkdaFee?: stringAsset ID to pay fees with (defaults to KLV)
Optionalnonce?: numberManual nonce override (auto-fetched if not provided)
Returns Promise<Transaction>
Unsigned transaction ready to be signed
Example
// 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)
buildTransfer
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
Parameters
- to: string
Recipient address (bech32 format)
- amount: string | number
Amount to transfer in smallest units (KLV has 6 decimals)
Optionaltoken: stringOptional token ID (defaults to 'KLV')
Returns Promise<Transaction>
Signed transaction ready to broadcast
connect
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
Returns Promise<void>
createAccount
Create a new account using the extension Extension mode only
Returns Promise<{ address: string; privateKey: string }>
PEM response with private key and address
disconnect
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)
Parameters
- clearPrivateKey: boolean = false
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)
Returns Promise<void>
Protectedemit
Parameters
- event: WalletEvent
Optionaldata: unknown
Returns void
encrypt
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
Parameters
- password: string
The password to encrypt the keystore
Optionaloptions: EncryptOptionsOptional scrypt parameters for encryption strength
scryptN
Work factor (default: 262144, min: 4096)
Returns Promise<Keystore>
A promise that resolves to the encrypted keystore object
Example
// 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))
getAccount
- getAccount(
address?: string,
): Promise<
{
address: string;
allowance?: number;
balance?: number;
nonce?: number;
permissions?: string[];
rootHash?: string;
txCount?: number;
},
>Get account information In extension mode: Uses KleverWeb extension In private key mode: Uses provider
Parameters
Optionaladdress: stringOptional address to query (defaults to current wallet address)
Returns Promise<
{
address: string;
allowance?: number;
balance?: number;
nonce?: number;
permissions?: string[];
rootHash?: string;
txCount?: number;
},
>Account information
getBalance
Get wallet balance
Returns Promise<bigint>
Balance in smallest units (KLV has 6 decimals)
getExtensionProvider
Get the extension's current provider configuration
Returns NetworkURI
Network URI configuration from the extension
getNonce
Get current nonce for the wallet Used for transaction ordering
Returns Promise<number>
Current nonce value
isConnected
Check if wallet is connected
Returns boolean
true if connected, false otherwise
off
Unregister an event handler
Parameters
- event: WalletEvent
Event name
- handler: WalletEventHandler
Event handler function to remove
Returns void
- event: WalletEvent
on
Register an event handler
Parameters
- event: WalletEvent
Event name ('connect', 'disconnect', 'accountChanged')
- handler: WalletEventHandler
Event handler function
Returns void
- event: WalletEvent
parsePemFileData
Parse PEM file data using the extension Extension mode only
Parameters
- pemData: string
PEM file content
Returns Promise<{ address: string; privateKey: string }>
Private key and address from PEM
- pemData: string
removeAllListeners
Remove all event listeners for a specific event or all events
Parameters
Optionalevent: WalletEventOptional event name. If not provided, removes all listeners for all events
Returns void
sendTransaction
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)
Parameters
- contract: ContractRequestData
Returns Promise<TransactionSubmitResult>
setPrivateKey
Set a private key in the extension Extension mode only
Parameters
- privateKey: string
Private key to set
Returns Promise<void>
- privateKey: string
setWalletAddress
Set the wallet address in the extension Extension mode only
Parameters
- address: string
Address to set
Returns Promise<void>
- address: string
signMessage
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
Parameters
- message: string | Uint8Array<ArrayBufferLike>
Message to sign (string or bytes)
Returns Promise<Signature>
Signature object with .toHex() and .toBase64() methods
signTransaction
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
Parameters
- unsignedTx: Transaction
Unsigned transaction to sign
Returns Promise<Transaction>
Signed transaction ready for broadcast
Example
// 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)
transfer
Transfer tokens to another address In extension mode: Uses KleverWeb extension In private key mode: Uses base implementation
Parameters
- params: TransferRequest
Returns Promise<TransactionSubmitResult>
updateProvider
Parameters
- provider: NetworkURI | IProvider
Returns void
validateSignature
- validateSignature(
message: string,
signature: string,
address: string,
): Promise<{ isValid: boolean; signer?: string }>Validate a signature using the extension Extension mode only
Parameters
- message: string
The original message that was signed
- signature: string
The signature to validate
- address: string
The address of the expected signer
Returns Promise<{ isValid: boolean; signer?: string }>
Validation result with signer information
- message: string
verifyMessage
- verifyMessage(
message: string | Uint8Array<ArrayBufferLike>,
signature: string | Signature,
): Promise<boolean>Verify a message signature
Parameters
- message: string | Uint8Array<ArrayBufferLike>
The message that was signed (string or bytes)
- signature: string | Signature
The signature to verify (Signature object, hex string, or base64 string)
Returns Promise<boolean>
true if signature is valid, false otherwise
Example
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) - message: string | Uint8Array<ArrayBufferLike>
Wallet implementation for browser environments
BrowserWallet supports two modes of operation:
1. Extension Mode (Default):
2. Private Key Mode:
Security Considerations:
Event Handling:
Example
Example
Example