@bkc-network-lib/web-wallet-connect
v0.1.1
Published
dApp SDK for the BKC web wallet (email sign-in, ML-DSA-65 keys): an EIP-1193 provider with EIP-6963 discovery and a Keplr-like offline signer that talk to the wallet in a popup.
Maintainers
Readme
@bkc-network-lib/web-wallet-connect
Connect a dApp to the BKC web wallet: the BKC wallet people sign in to with email, with
nothing to install, also in mobile browsers. The SDK gives you an EIP-1193 provider (with EIP-6963
discovery) for EVM dApps and a Keplr-like offline signer for Cosmos dApps. The wallet opens in a
popup window (a new tab on phones) at its own origin; the SDK talks to it with postMessage.
BKC keys are ML-DSA-65 (FIPS 204, post-quantum), so there is no ECDSA: ecrecover and
eth_sendRawTransaction do not apply. Message signatures come back as
{ signature, publicKey, address } and are checked with verifyMessageSignature.
Install
npm install @bkc-network-lib/web-wallet-connectShips ESM and CommonJS, built for ES2022, with type declarations. Use a bundler (Vite, webpack,
Next.js…) or native import in a dApp; a Node backend can import or require it. TypeScript works
with "moduleResolution" bundler, node16, nodenext or node. Entry points:
@bkc-network-lib/web-wallet-connect, @bkc-network-lib/web-wallet-connect/protocol (wire types)
and @bkc-network-lib/web-wallet-connect/verify (what a backend needs to check a signature, no
DOM). Runtime dependencies:
@bkc-network-lib/crypto and @bkc-network-lib/encoding. The declarations use DOM types, so include the DOM lib
(or keep skipLibCheck) in your tsconfig.json.
Configure the wallet origin
Every provider needs the origin of the BKC web wallet you integrate with. Put it in your own configuration, for example an environment variable:
const WALLET_ORIGIN = import.meta.env.VITE_BKC_WEB_WALLET_ORIGIN; // e.g. https://wallet.example.comNever take it from a URL parameter or a message, or a phishing link could send your users to
a fake wallet. The SDK accepts only an https: origin (http: on localhost for development).
Testnet: the BKC web wallet at https://wallet.bkc.network serves the testnet, so use it as your
walletOrigin while you build. Cosmos chain id bkc-testnet, EVM chain id 262144 (0x40000).
It is a test deployment and sign-in codes are not emailed to everyone yet, so ask the BKC team for
access before you plan a demo on it.
Quick start: EVM (EIP-1193)
import {
announceProvider,
createBkcEthereumProvider,
type MessageSignature,
verifyMessageSignature,
} from '@bkc-network-lib/web-wallet-connect';
const ethereum = createBkcEthereumProvider({ walletOrigin: WALLET_ORIGIN, chainId: 262144 });
announceProvider(ethereum); // EIP-6963: wallet pickers list "BKC Wallet (email)"
// Call interactive methods from a click handler: they open the wallet popup.
connectButton.onclick = async () => {
const [account] = (await ethereum.request({ method: 'eth_requestAccounts' })) as string[];
const message = `Sign in to example.com\nNonce: ${nonce}`;
const signed = (await ethereum.request({ method: 'personal_sign', params: [message, account] })) as MessageSignature;
verifyMessageSignature(message, signed, { expectedAddress: account }); // true (check it again on your server)
const txHash = (await ethereum.request({
method: 'eth_sendTransaction',
params: [{ from: account, to: '0x…', value: '0x2386f26fc10000' }], // 0.01 BKC
})) as string;
showTransaction(txHash);
};It works as the EIP1193Provider of viem/wagmi or ethers' BrowserProvider for the account;
send reads (eth_call, eth_getBalance…) to your own RPC transport.
Message signatures and Cosmos signatures are verified by the SDK, but an EVM address has no
public key to check against, so eth_requestAccounts results and eth_sendTransaction hashes are
taken from the wallet as they come: confirm a transaction on chain before acting on it.
Quick start: Cosmos (Keplr-like)
import { createBkcCosmosProvider } from '@bkc-network-lib/web-wallet-connect';
import { SigningStargateClient } from '@bkc-network-lib/stargate';
const bkc = createBkcCosmosProvider({ walletOrigin: WALLET_ORIGIN });
connectButton.onclick = async () => {
bkc.transport.open(); // open the popup inside the click: the client awaits the network first
const { address } = await bkc.enable('bkc-testnet');
const signer = bkc.getOfflineSigner('bkc-testnet'); // OfflineDirectSigner, algo 'mldsa65'
const client = await SigningStargateClient.connectWithSigner(RPC_URL, signer);
const result = await client.signAndBroadcast(address, messages, 'auto'); // your EncodeObject[]
};Use the @bkc-network-lib clients (@bkc-network-lib/stargate, @bkc-network-lib/proto-signing):
upstream @cosmjs types reject algo: 'mldsa65' and its SigningStargateClient encodes the
public key as secp256k1.
Extension or email
Let the user choose. If the BKC extension is injected (window.bkc), offer it; the email wallet is
always available.
import { getBkcWalletChoices } from '@bkc-network-lib/web-wallet-connect';
const choices = getBkcWalletChoices({ walletOrigin: WALLET_ORIGIN, evmChainId: 262144 });
// [{ kind: 'extension', label, extension }, { kind: 'email', label, connect() }]: render a button per choice.
button.onclick = () => {
const choice = choices.find((c) => c.kind === picked)!;
const ethereum = choice.kind === 'extension' ? choice.extension.ethereum : choice.connect().ethereum;
void ethereum.request({ method: 'eth_requestAccounts' });
};walletOrigin must come from your own configuration, never from a URL parameter or a message.
EVM provider
Supported: eth_requestAccounts, eth_accounts, eth_chainId, eth_sendTransaction,
personal_sign, wallet_disconnect; events connect, accountsChanged, chainChanged,
disconnect. Read methods (eth_call, eth_getBalance…) return 4200: use your own RPC transport
for reads (e.g. viem/wagmi http()), and this provider for the account.
Cosmos provider
signDirect returns the same shape as the extension: signature.pub_key.type is
cosmos/PubKeyMlDsa65, values in standard base64. The wallet signs the SignDoc unchanged or
refuses; it never edits fees or memo. The SDK checks the returned signature over the SignDoc
bytes and that the key is the signer's before resolving.
The wallet signs only a SignDoc for the network it is on, whose AuthInfo names exactly one signer: the connected account's ML-DSA-65 key (or no key). Anything else is refused with -32602.
To share one popup between both providers, pass transport: ethereum.transport to the second.
Account changes
While its popup is open, the wallet tells the dApp when what the site may see changes: the user
switched account, removed the site in Manage Dapps, or signed out (accountsChanged, [] when
the site is no longer connected), or switched network (chainChanged). A closed popup cannot
tell anything: the next request reopens it, the wallet sends the current state first, and a
site that is no longer connected gets 4100, which also clears the providers' cached account.
ethereum.on('accountsChanged', (accounts) => (accounts.length ? showAccount(accounts[0]) : showConnectButton()));
const stop = bkc.onAccountsChanged((addresses) => (addresses.length ? reconnect() : showConnectButton()));If the dApp window closes, the popup drops what it asked and closes itself.
Like the BKC extension's request window, the popup closes itself about a second after the user
answered the last interactive request (approved or rejected). A request sent within that second
reuses the window; a later one reopens it (from a click, see below). Closing this way rejects
nothing, but non-interactive methods sent after it fail with 4900 not_ready (eth_accounts
returns the cached accounts; wallet_disconnect then only forgets the site in the dApp).
Popups and user gestures
Browsers allow window.open only shortly after a click. Interactive requests open the popup
synchronously inside request(), so call them from the click handler. If your handler awaits
network calls first (e.g. cosmjs fetching the account number before signDirect), call
provider.transport.open() at the start of the handler. A blocked popup rejects with
{ code: 4900, reason: 'popup_blocked' }; closing it rejects pending interactive requests
with 4001 (others with 4900).
The popup is 375 x 640 (the BKC extension's request window), centred over the dApp's browser
window with left/top on Windows, macOS and Linux X11. On Linux Wayland the compositor decides
where the window goes (Chrome ignores left/top there). Touch devices get a new tab instead.
Open the wallet
The request popup closes itself after each answer, so give users a way back to their wallet (balances, history, send, settings), like the BKC extension's toolbar icon. Put your own button somewhere natural, e.g. on the connected account chip; the SDK injects no UI.
accountChip.onclick = () => {
try {
// or bkc.transport.openWallet(), or choice.connect().openWallet()
if (ethereum.transport.openWallet() === 'focused') showHint('Finish the request in the wallet window');
} catch (error) {
showError(error); // { code: 4900, reason: 'popup_blocked' }
}
};- Call it synchronously inside the click (it calls
window.open). It returns'opened'or'focused'and throws aBkcProviderError4900popup_blockedwhen the browser blocks the window. - It opens
<walletOrigin>/#bkc-dapp-view=<your page's origin, URI-encoded>, the configured origin only, in a popup of the request popup's size and position (a new tab on touch devices), named<windowName>-view(bkc-web-wallet-view). A page with an opaque origin (sandboxed iframe,file:) sends the bare#bkc-dapp-view. - When your site is connected to the wallet's current account, the wallet home shows it in a bar
at the bottom (like the extension's bar for the active tab): your origin and its default site
picture (the wallet never fetches your favicon). The user can open Manage Dapps from it or
disconnect your site; after that, your next request gets
accountsChanged([])and has to connect again. The origin in the marker is a claim any page can make, so the wallet only uses it to pick which connected site to show, and only if it is an exacthttps:origin (http:on loopback in development builds). - While the request popup is waiting for the user (an interactive request is pending), it focuses
that window instead and returns
'focused': the request has to be answered first. Browsers may ignore that focus, so tell the user where the request is. - The wallet page gets no
window.openerand the SDK keeps no reference to the window; the wallet home's COOPsame-origin(a hosting requirement of the wallet) severs the two windows in both directions. - The wallet keeps a single such window. That COOP clears the window's name, so the browser cannot
find it again; instead the wallet reads the
#bkc-dapp-viewmarker (removed from the URL at once) and its windows coordinate over a same-originBroadcastChannel: a new wallet window replaces an older one, unless the older one is busy (a signer prompt is open or a text field holds text). Then the older one stays and asks for the focus (browsers may ignore that), and the new one closes. Two windows opened together (a double click) settle on one. Tabs the user opened and the request popup are never closed. WithoutBroadcastChannel, each click opens another window.
Verifying a message signature
import { type MessageSignature, personalSignMessageBytes, verifyMessageSignature } from '@bkc-network-lib/web-wallet-connect';
const result = (await ethereum.request({ method: 'personal_sign', params: [message, account] })) as MessageSignature;
// Ideally on your server, with the account you expect:
const ok = verifyMessageSignature(message, result, { expectedAddress: account });
// For a 0x-hex personal_sign message: verifyMessageSignature(personalSignMessageBytes(hex), result, …)The providers already run this check before resolving, but verify again wherever the signature
is trusted (your server). Always pass expectedAddress: without it the check proves only that
some key signed. The prefix separates messages from transactions but carries no site, chain or
time, so put your domain, a server nonce and an expiry in the message itself to stop replays.
It checks that the public key derives the address as the chain does (sha256(pubkey)[:20], bech32
bkc) and that the ML-DSA-65 signature covers "\x19BKC Signed Message:\n" + length + "\n" +
message, so a signed message can never double as a transaction.
Wallet error messages are plain text from the wallet; never render them as HTML.
Verify a signature on your server
@bkc-network-lib/web-wallet-connect/verify is the part a backend needs: no popup, no DOM, and it
loads from CommonJS and from ESM.
// CommonJS (NestJS, Express…)
const { verifyMessageSignature } = require('@bkc-network-lib/web-wallet-connect/verify');// ESM
import { verifyMessageSignature } from '@bkc-network-lib/web-wallet-connect/verify';Send the wallet's answer to your server as it came: { signature, publicKey, address }, with the
key and signature in base64url and the address in bech32 (bkc1…). Verify with the address you
expect, never the one the request claims:
const ok = verifyMessageSignature(message, signed, { expectedAddress });verify also exports personalSignMessageBytes, encodeSignedMessage, MESSAGE_SIGNING_PREFIX,
addressFromPublicKey, toBase64Url and fromBase64Url. If an API of yours (or another BKC
service) takes standard base64 for the key and signature, convert the answer first with
toStandardBase64Signature(signed), which keeps the field names and the address.
Sign in with a wallet (your own backend)
The wallet proves control of a key, so it can be your login. Four rules keep it safe:
Server issues the text.
POST /auth/noncecreates a random nonce (at least 128 bits), stores it with a short expiry (a few minutes) and returns the text to sign. Put your domain, the nonce and the expiry in the text, so a signature cannot be replayed on another site or later:Sign in to example.com\nAddress: bkc1…\nNonce: 7f3c…\nExpires: 2026-11-16T10:05:00Z.Wallet signs it from a click:
bkc.signArbitrary(chainId, address, text)(Cosmos) orpersonal_sign(EVM). The popup shows the text.Server verifies with the address it expects, against the text it stored for that nonce (never a text the client sends back):
const text = await takeNonce(nonce); // fetch and delete in one step: single use if (!text || isExpired(text)) throw new Error('expired'); if (!verifyMessageSignature(text, signed, { expectedAddress: address })) throw new Error('bad signature');Single use. Delete the nonce when you fetch it, so two requests cannot both succeed, and only then start the session.
Errors
Every failure is a BkcProviderError (an EIP-1193 ProviderRpcError): an Error with a numeric
code and, when the SDK itself failed the request, a reason.
| Code | Meaning |
|---|---|
| 4001 | The user rejected the request or closed the wallet window (reason: 'popup_closed'). |
| 4100 | The site is not connected to the wallet's current account; connect again. |
| 4200 | Method not supported (chain reads: use your own RPC). |
| 4900 | No usable wallet window: popup_blocked, popup_closed, not_ready, wallet_reloaded. |
| -32602 | Invalid params (checked before the popup opens where possible). |
| -32603 | Internal error: timeout, or invalid_response when the wallet's answer failed the SDK's checks. |
import { BkcProviderError } from '@bkc-network-lib/web-wallet-connect';
try {
await ethereum.request({ method: 'eth_requestAccounts' });
} catch (error) {
if (error instanceof BkcProviderError && error.reason === 'popup_blocked') showAllowPopupsHint();
}Hosting requirements
- The dApp page must not send
Cross-Origin-Opener-Policy: same-origin(usesame-origin-allow-popups), or the SDK loses the popup reference. - The wallet's
/connectpage must keepwindow.opener(nonoopener, COOPunsafe-none).
Development
Node.js 18 or later (CI runs Node 22).
npm ci
npm run typecheck
npm test
npm run build # dist/: ESM, CommonJS, declarations and source maps
npm run test:dist # build, then load dist/ from a CommonJS and an ESM consumer