Class: BrowserSDK
Defined in: BrowserSDK.ts:48
High-level browser SDK for KEA Wallet integration.
Wraps EmbeddedProvider with a ThruClient for direct blockchain RPC
queries and automatic dApp metadata resolution (appName, appUrl, appId are
derived from window.location when not explicitly provided).
Remarks
The typical lifecycle is:
- Create an instance with optional BrowserSDKConfig
- Call initialize (or let connect do it automatically)
- Call connect to open the wallet consent modal
- Use getAccounts, getSelectedAccount, and the thru signer
- Listen for events via on
- Call destroy when the SDK is no longer needed
Example
import { BrowserSDK } from '@kea-wallet/browser-sdk';
const sdk = new BrowserSDK({ rpcUrl: 'https://grpc-web.alphanet.thruput.org' });
await sdk.initialize();
const { accounts } = await sdk.connect();
console.log('Connected:', accounts[0].address);
sdk.on('accountChanged', (account) => {
console.log('Switched to:', account.address);
});
// When done:
sdk.destroy();
See
- BrowserSDKConfig for configuration options
- SDKEvent for available events
- SDKEventPayloads for event payload types
Constructors
Constructor
new BrowserSDK(config?: BrowserSDKConfig): BrowserSDK;
Defined in: BrowserSDK.ts:68
Create a new BrowserSDK instance.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | BrowserSDKConfig | SDK configuration including iframe URL, RPC URL, and address types |
Returns
BrowserSDK
Lifecycle
destroy()
destroy(): void;
Defined in: BrowserSDK.ts:522
Tear down the SDK — destroys the iframe, clears all event listeners, and resets internal state.
Returns
void
Remarks
After calling destroy(), the instance cannot be reused. Create a
new BrowserSDK instance if you need to reconnect.
Example
// Cleanup on component unmount or page unload
sdk.destroy();
See
initialize to set up a new instance
initialize()
initialize(): Promise<void>;
Defined in: BrowserSDK.ts:105
Initialize the SDK by creating the wallet iframe. Automatically called by connect if not already initialized. Calling it explicitly allows pre-loading the iframe for faster first connection.
Returns
Promise<void>
Remarks
This method is idempotent — calling it multiple times has no effect after the first successful initialization.
Example
// Pre-load for faster UX
const sdk = new BrowserSDK();
await sdk.initialize(); // iframe created, ready for connect()
// Later, when user clicks "Connect":
const result = await sdk.connect(); // instant, no iframe delay
mountInline()
mountInline(container: HTMLElement): Promise<void>;
Defined in: BrowserSDK.ts:209
Mount the wallet iframe inline inside a DOM container instead of as a modal.
Parameters
| Parameter | Type | Description |
|---|---|---|
container | HTMLElement | The DOM element to embed the wallet into |
Returns
Promise<void>
Remarks
Use this for embedded wallet experiences where the wallet UI is always visible within your app layout rather than appearing as a popup.
Example
const container = document.getElementById('wallet-container')!;
await sdk.mountInline(container);
Connection
connect()
connect(options?: ConnectOptions): Promise<ConnectResult>;
Defined in: BrowserSDK.ts:146
Connect to the KEA Wallet. Opens the wallet modal for user authorization.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | ConnectOptions | Optional connection settings including dApp metadata |
Returns
Promise<ConnectResult>
The connection result containing authorized wallet accounts
Remarks
- Auto-initializes the SDK if initialize was not called.
- Concurrent calls are deduplicated — only the first in-flight request runs.
- If already connected, returns the cached result immediately.
- dApp metadata (appName, appUrl) is automatically resolved from
window.locationunless explicitly provided inoptions.metadata.
Throws
Error with ErrorCode.USER_REJECTED if the user declines
Example
// Basic connection
const { accounts } = await sdk.connect();
// With custom metadata for the consent screen
const { accounts } = await sdk.connect({
metadata: { appName: 'My dApp', imageUrl: 'https://mydapp.com/logo.png' },
});
See
- ConnectOptions for available options
- disconnect to end the session
- isConnected to check connection state
disconnect()
disconnect(): Promise<void>;
Defined in: BrowserSDK.ts:232
Disconnect from the wallet and clear session state.
Returns
Promise<void>
Remarks
Emits a 'disconnect' event on success and an 'error' event if the
underlying message fails. The error is also re-thrown.
Throws
Error if the disconnect message fails
Example
await sdk.disconnect();
console.log(sdk.isConnected()); // false
See
connect to re-establish the session
isConnected()
isConnected(): boolean;
Defined in: BrowserSDK.ts:261
Check whether the wallet is currently connected.
Returns
boolean
true if a wallet session is active
Example
if (sdk.isConnected()) {
const accounts = sdk.getAccounts();
}
See
isReconnecting()
isReconnecting(): boolean;
Defined in: BrowserSDK.ts:278
Whether the SDK is currently attempting a silent auto-reconnect.
Returns
boolean
true while a silent session check is in progress
Remarks
Use this to show a loading skeleton or "Reconnecting…" state instead of briefly flashing the "Connect Wallet" button on page reload.
See
Accounts
getAccounts()
getAccounts(): WalletAccount[];
Defined in: BrowserSDK.ts:301
Get all accounts from the current wallet session.
Returns
WalletAccount[]
Array of connected wallet accounts (each with address, label,
and accountType fields)
Example
const accounts = sdk.getAccounts();
accounts.forEach((acc) => {
console.log(`${acc.label}: ${acc.address}`);
});
See
- getSelectedAccount to get only the active account
- selectAccount to switch accounts
getSelectedAccount()
getSelectedAccount(): any;
Defined in: BrowserSDK.ts:325
Get the currently selected (active) account.
Returns
any
The selected account, or null if none is selected
Example
const account = sdk.getSelectedAccount();
if (account) {
console.log('Active:', account.address);
}
See
- selectAccount to switch the active account
- getAccounts to list all accounts
selectAccount()
selectAccount(publicKey: string): Promise<WalletAccount>;
Defined in: BrowserSDK.ts:353
Switch the active account by public key.
Parameters
| Parameter | Type | Description |
|---|---|---|
publicKey | string | The public key of the account to select |
Returns
Promise<WalletAccount>
The newly selected account
Remarks
Emits an 'accountChanged' event after the switch completes.
Example
const accounts = sdk.getAccounts();
const newAccount = await sdk.selectAccount(accounts[1].address);
console.log('Now active:', newAccount.label);
Throws
Error with ErrorCode.ACCOUNT_NOT_FOUND if the public key does not match any connected account
See
Chain
thru
Get Signature
get thru(): IThruChain;
Defined in: BrowserSDK.ts:382
Access the Thru chain adapter for signing transactions and messages.
Remarks
The signer delegates signing to the wallet iframe — private keys never leave the wallet. Use getThru for read-only RPC queries that do not require signing.
Example
const signingCtx = await sdk.thru.getSigningContext();
console.log('Fee payer:', signingCtx.feePayerPublicKey);
const signed = await sdk.thru.signTransaction(serializedTx);
See
getThru for the read-only RPC client
Returns
IThruChain
The iframe-backed Thru chain signer
getThru()
getThru(): Thru;
Defined in: BrowserSDK.ts:408
Get the ThruClient instance for direct blockchain RPC queries (balance lookups, transaction submission, block queries).
Returns
Thru
The configured ThruClient (uses the rpcUrl from BrowserSDKConfig)
Remarks
This client communicates with the Thru blockchain via gRPC-web. It does not require a connected wallet — you can query the blockchain before calling connect.
Example
const thru = sdk.getThru();
// Query account balance, submit transactions, etc.
See
- thru for the signing adapter (requires connection)
- BrowserSDKConfig.rpcUrl for configuring the endpoint
Events
off()
off<T>(event: T, callback: EventCallback<T>): void;
Defined in: BrowserSDK.ts:469
Unsubscribe from an SDK event.
Type Parameters
| Type Parameter | Description |
|---|---|
T extends keyof SDKEventPayloads | The event name |
Parameters
| Parameter | Type | Description |
|---|---|---|
event | T | The event name |
callback | EventCallback<T> | The exact listener reference passed to on |
Returns
void
Example
const handler: EventCallback<'accountChanged'> = (account) => {
console.log(account.address);
};
sdk.on('accountChanged', handler);
// Later:
sdk.off('accountChanged', handler);
See
on()
on<T>(event: T, callback: EventCallback<T>): void;
Defined in: BrowserSDK.ts:441
Subscribe to an SDK event.
Type Parameters
| Type Parameter | Description |
|---|---|
T extends keyof SDKEventPayloads | The event name, used to narrow the callback payload type |
Parameters
| Parameter | Type | Description |
|---|---|---|
event | T | The event name |
callback | EventCallback<T> | The listener function, called with the event payload |
Returns
void
Example
// Type-safe: `account` is narrowed to WalletAccount
sdk.on('accountChanged', (account) => {
console.log('Switched to:', account.address);
});
sdk.on('error', (err) => {
console.error('SDK error:', err);
});
sdk.on('disconnect', (data) => {
console.log('Disconnected:', data.reason);
});
See
- SDKEventPayloads for per-event payload types
- off to unsubscribe
- once for single-fire listeners
once()
once<T>(event: T, callback: EventCallback<T>): void;
Defined in: BrowserSDK.ts:496
Subscribe to an SDK event for a single invocation. The listener is automatically removed after the first call.
Type Parameters
| Type Parameter | Description |
|---|---|
T extends keyof SDKEventPayloads | The event name |
Parameters
| Parameter | Type | Description |
|---|---|---|
event | T | The event name |
callback | EventCallback<T> | The listener function |
Returns
void
Example
// Wait for the first connect event, then stop listening
sdk.once('connect', (result) => {
if ('accounts' in result) {
console.log('Connected with', result.accounts.length, 'accounts');
}
});