Skip to main content

DApp discovery and connections in the built-in browser

Scope and authorization boundaries​

This guide covers injected EVM providers in InvisiPay's built-in browser. Provider discovery, permission to read accounts, application sign-in, wallet unlock and signing authorization are separate capabilities. See Accounts and signing boundaries. A connection does not authorize arbitrary signatures or automatic payments, or establish private-protocol deployment on a chain.

This page does not promise external desktop WalletConnect, browser extensions, simultaneous multi-account authorization, cross-device session synchronization or arbitrary signing methods. The example discovers and connects providers; it is not a method-support matrix and performs no signing or transactions. Verify capabilities against the actual release and account type.

Discover providers: listen before requesting​

Use the EIP-6963 handshake: listen for eip6963:announceProvider before dispatching eip6963:requestProvider. Wallets may announce proactively or respond later. Do not read window.ethereum just once or assume the first announcement is the desired wallet. Repeated announcements must not create duplicate entries for the same candidate.

Announced name, icon, rdns and uuid values do not authenticate wallet identity. Do not select, trust or request accounts automatically based on a name, reverse-domain identifier or isMetaMask. Let the user select explicitly and review the origin in the wallet's own interface. Render labels as text rather than executable content. The example omits icons; if needed, validate them separately and never insert SVG markup into the DOM or use it as an executable object. A standards-compliant UUID distinguishes discovery sessions, not brands; do not hardcode an old sample value or treat it as identity evidence.

window.ethereum can be an explicitly labeled compatibility candidate, but must not silently replace the user's selected provider. Its presence proves neither identity nor authorization. If discovery finds nothing, ask the user to open a supported built-in browser or request discovery again instead of switching automatically to an unverified connection channel.

Account authorization and session ownership​

  1. Call the selected provider's eth_requestAccounts only after an explicit user selection. Prevent duplicate prompts while pending; discovery, timers and rerenders must not trigger authorization.
  2. The user may choose an account in the wallet or reject the request. eth_accounts reads the accounts currently exposed to this site. Without site authorization, handle an empty list rather than reusing another site's account or a cached address.
  3. After approval, read eth_accounts and eth_chainId, validate the results and check the selected deployment. An address does not prove the wallet is unlocked, capable of signing or signed into your backend.
  4. The built-in browser manages sessions by origin, with one authorized account per site in this scope. Revisiting may restore existing permission, but reread the current account and chain. Do not force a new prompt on every refresh or promise cross-device recovery.
  5. Use the site's session account rather than inferring it from the account selected on Home. Read the browser network from the provider, not Home's All networks filter or a historically stored session chain ID.

Do not share a pending authorization across tabs or navigations without source binding. Invalidate old queries and confirmations when the site, account or network changes or the component is destroyed. A late Promise must not write old state into a new page. Connection exposes authorized information only; later actions still require separate permission checks.

Minimal discovery and connection example​

Create these elements before running the JavaScript. Wallet names are untrusted display labels, not an InvisiPay filter. The candidate limit prevents unbounded announcements; it is not a product-support limit.

<div id="wallets" aria-label="Discovered wallets"></div>
<button id="cancel" type="button">Stop locally</button>
<pre id="status" role="status"></pre>
const list = document.querySelector("#wallets");
const status = document.querySelector("#status");
const cancel = document.querySelector("#cancel");
const seen = new WeakSet();
let count = 0, generation = 0, revision = 0;
let active = null, busy = false, disposed = false;
let unbind = () => {};
const address = (x) => typeof x === "string" && /^0x[0-9a-f]{40}$/i.test(x);
const chain = (x) => typeof x === "string" && /^0x[0-9a-f]+$/i.test(x);
const show = (text) => { status.textContent = text; };

function invalidated() {
revision++;
// Clear account-dependent state, balances and unsigned previews here too.
show("Context changed. Recheck the account and network before continuing.");
}

async function connect(provider) {
if (disposed || busy) return; // One outstanding wallet prompt at a time.
unbind();
active = provider;
const owner = ++generation;
const current = () => !disposed && generation === owner && active === provider;
const changed = () => { if (current()) invalidated(); };
provider.on("accountsChanged", changed);
provider.on("chainChanged", changed);
provider.on("disconnect", changed);
unbind = () => {
provider.removeListener("accountsChanged", changed);
provider.removeListener("chainChanged", changed);
provider.removeListener("disconnect", changed);
};
busy = true;
show("Check the request in your wallet.");
try {
await provider.request({ method: "eth_requestAccounts" });
if (!current()) return;
// Read again after approval: the wallet may have emitted change events.
const snapshot = revision;
const [accounts, chainId] = await Promise.all([
provider.request({ method: "eth_accounts" }),
provider.request({ method: "eth_chainId" }),
]);
if (!current() || revision !== snapshot) return;
if (!Array.isArray(accounts) || !accounts.every(address) || !chain(chainId)) {
throw new Error("Invalid provider response");
}
if (accounts.length === 0) {
show("No authorized account. Connect again only when you choose to.");
return;
}
// No signing, transfers, backend login or chain-support inference here.
show(JSON.stringify({ accounts, chainId }, null, 2));
} catch (error) {
if (!current()) return;
const messages = {
4001: "Request rejected or cancelled. No automatic retry.",
4100: "Not authorized. Check the wallet before trying again.",
4200: "Method unsupported. Check this wallet version.",
4900: "Provider disconnected. Check connectivity.",
4901: "Requested network unavailable. Check the browser network.",
};
show(messages[error?.code] ?? "Connection result unavailable. Check the wallet.");
} finally {
busy = false;
}
}

function announced(event) {
if (disposed || count >= 32) return; // Bound untrusted announcement volume.
const detail = event.detail;
const provider = detail?.provider;
if (!provider || typeof provider !== "object" || seen.has(provider) ||
typeof provider.request !== "function" || typeof provider.on !== "function" ||
typeof provider.removeListener !== "function") return;
seen.add(provider);
count++;
const label = typeof detail.info?.name === "string"
? detail.info.name.slice(0, 80) : "Injected wallet";
const button = document.createElement("button");
button.type = "button";
button.textContent = `${label} (unverified provider)`;
button.addEventListener("click", () => { void connect(provider); });
list.append(button); // Do not render the announced icon or HTML.
}

cancel.addEventListener("click", () => {
generation++;
active = null;
unbind();
unbind = () => {};
show("Stopped locally. Dismiss any wallet prompt; no new request until it settles.");
// Keep busy while request() is pending. This does not cancel the wallet RPC.
});
window.addEventListener("eip6963:announceProvider", announced);
window.dispatchEvent(new Event("eip6963:requestProvider"));
window.addEventListener("pagehide", () => {
disposed = true;
generation++;
active = null;
unbind();
window.removeEventListener("eip6963:announceProvider", announced);
}, { once: true });

The example displays a connection snapshot after basic format checks. A production integration must also validate allowed chains and deployments and bind balances, forms and previews to the same account/network revision. Events invalidate the old snapshot without automatically prompting again or executing financial actions. Production pages may reread non-prompting state after invalidation while retaining the same stale-result protections.

Events and invalidation​

Handle provider events using EIP-1193, removing old listeners when replacing the provider or unmounting:

EventPage behavior
accountsChangedThe exposed account list changed; an empty array means no authorized account. Clear old balances, receiving targets and unsigned previews, then check current state
chainChangedInvalidate estimates, requests and confirmations for the old chain. Verify support for the new chain instead of executing an old transaction draft
disconnectClear actionable state and ask the user to check connectivity; this is not an on-chain refund or cancellation
connect, if receivedProvider chain connectivity returned; still read account authorization rather than treating this as user sign-in or signing approval

Account events do not permit selecting arbitrary accounts, and network events do not guarantee support for website-driven network switching or addition. In multiple tabs, update only the associated provider/page context rather than delivering another tab's confirmation to the current one.

Rejection, cancellation and failures​

ResultHandling
4001Common rejection/cancellation result; allow another attempt only after a fresh user choice, without automatically reopening the prompt
4100Account/request unauthorized; check site permission and wallet state without bypassing verification
4200Unsupported method; stop instead of silently substituting a different signing method
4900 / 4901Provider or requested network unavailable; check connectivity and the current browser network
Empty accounts, unexpected results or unknown errorsDo not display connection success or manufacture authorization from cache; ask the user to check the wallet before proceeding

These are standard error meanings. A particular cancellation path may return another error, and error codes alone do not establish whether funds changed. Rejecting a new connection attempt also does not prove that a previously granted session was revoked; check current account access separately. A local Stop action only invalidates results; it does not guarantee dismissal of a wallet prompt or cancellation of its RPC. A timeout is also not proof of wallet cancellation. Do not automatically retry financial requests with unknown results.

Disconnecting a site removes that connection capability, not on-chain token allowances. If a separate financial flow has already broadcast, closing the page or cancelling its interface does not reverse it. Reconcile the original operation using Transaction state and recovery.

Integration checks​

Verify repeated discovery, explicit selection, unauthorized empty accounts, rejection/cancellation, account and chain changes, late results, same-origin revisits and cross-origin isolation. A successful connection demo does not establish support for eth_sign, typed signing, automatic chain switching, external-account signing or all transaction methods. Verify each method's capability and authorization separately. Keep private keys, seed phrases, full private credentials and unlock material out of webpage logs.