@etherplay/connect
Main connection library for Etherplay Accounts - provides seamless wallet and social authentication with session account management. This package combines Web3 wallet support with social login capabilities to create a unified authentication experience.
Installation
npm install @etherplay/connect
# or
pnpm add @etherplay/connect
# or
yarn add @etherplay/connect
Features
- Web3 Wallet Support: Connect via MetaMask, Coinbase Wallet, and other EIP-6963 compliant wallets
- Social Login: Authenticate via email OTP, Google, Facebook, or Auth0 through a popup flow
- Mnemonic Login: Direct authentication using BIP-39 mnemonic phrases
- Session Accounts: Generate origin-specific session accounts for enhanced security
- Backend-Free Mode: Sign in and derive a session signer with an injected wallet alone, no host and no server (see Supported connection shapes)
- Auto-Connect: Automatically reconnect returning users
- Chain Management: Built-in chain switching and validation
- Svelte Integration: Reactive state management via Svelte stores
- Type-Safe: Full TypeScript support with comprehensive type definitions
Quick Start
Basic Wallet Connection
import {createConnection} from '@etherplay/connect';
// Create a connection targeting wallet connection only
const connection = createConnection({
targetStep: 'WalletConnected',
chainInfo: {
id: 1,
name: 'Ethereum',
rpcUrls: {default: {http: ['https://eth.llamarpc.com']}},
nativeCurrency: {name: 'Ether', symbol: 'ETH', decimals: 18},
},
});
// Subscribe to connection state changes
connection.subscribe((state) => {
if (state.step === 'WalletConnected') {
console.log('Connected:', state.account.address);
}
});
// Initiate wallet connection
await connection.connect({type: 'wallet'});
Full SignedIn Flow with Social Login
import {createConnection} from '@etherplay/connect';
const connection = createConnection({
walletHost: 'https://wallet.etherplay.io', // Required for popup-based auth
chainInfo: {
id: 1,
name: 'Ethereum',
rpcUrls: {default: {http: ['https://eth.llamarpc.com']}},
nativeCurrency: {name: 'Ether', symbol: 'ETH', decimals: 18},
},
autoConnect: true, // Auto-reconnect returning users
});
// Connect via email
await connection.connect({type: 'email', mode: 'otp', email: 'user@example.com'});
// Or via OAuth
await connection.connect({type: 'oauth', provider: {id: 'google'}, usePopup: true});
Using ensureConnected
The ensureConnected method provides a promise-based API that resolves when the target connection state is reached:
// Wait for wallet connection
const state = await connection.ensureConnected('WalletConnected');
console.log('Wallet connected:', state.account.address);
// Wait for full sign-in
const signedInState = await connection.ensureConnected('SignedIn');
console.log('Session account:', signedInState.account.signer.address);
What the target is
ensureConnected promises a target, not a step comparison, and does whatever reaching it takes. The target is reached when the connection is:
- at or beyond
step. The steps are ordered (SignedIn implies WalletConnected implies WalletChosen), so a signed-in connection satisfies ensureConnected('WalletConnected') and resolves as itself.
- on the wallet you named, if you named one.
- able to act as the address you named, if you named one: connected, not locked, and actually holding that account. A connection already at the requested step but on a different account initiates an attempt rather than resolving with somebody else.
- on the right chain — but only for a
WalletConnected target, and unless you pass {skipChainCheck: true}. A SignedIn target does not check the chain (a session signer is chain-independent), so skipChainCheck does nothing there; read wallet.invalidChainId and offer switchWalletChain() if your signed-in app also sends through the wallet.
Anything you did not name is not part of the target, so a bare ensureConnected() behaves exactly as before.
An address or a wallet name you pass is a requirement. An address the library replays from the connection's own state (its locked-wallet reconnect does this) stays a preference and degrades to an ordinary connect, because nobody asked for it.
It always answers
There is no timeout, deliberately: a human is in the loop, so any timer is either long enough to be useless or short enough to cut a user off mid-decision, and it would report "timed out" about a wallet dialog that is open and healthy. The rule is narrower instead: waiting is only legitimate while something is actually in progress. It stays pending only while one of these is true, and every one of them is published on the connection so your app can render it and the user can answer it:
| Still pending because |
What the state says |
What ends it |
| an attempt is running |
step is WaitingForWalletConnection / PopupLaunched |
the wallet or the host answers |
| the wallet is holding a signature prompt |
step: 'WaitingForSignature' |
the user answers it |
| the user is choosing |
step is MechanismToChoose / WalletToChoose |
they pick, or cancel() |
| the user is picking an account |
step: 'ChooseWalletAccount' |
connectToAddress(...), or cancel() |
| the wallet is on another account |
connection.addressUnavailable (see below) |
they switch in the wallet, or acknowledge it |
the wallet is on another chain (WalletConnected target only) |
wallet.invalidChainId |
switchWalletChain(), or they switch themselves |
| the signature has not been asked for |
step: 'WalletConnected' with a SignedIn target |
requestSignature(), or see the note below |
If the target is not satisfied, nothing is in progress and nothing can be initiated, that is an answer and it is delivered immediately rather than awaited. "In progress" includes an attempt this call has started that has not come back yet, even before that attempt has published anything. Every resting entry state is enumerated against this, crossed with every target and every kind of mechanism, in test/ensure-connected-settles.test.ts.
The last row is the one worth knowing about: with the default requestSignatureAutomaticallyIfPossible: false, a SignedIn target rests at WalletConnected waiting for your "sign in" button, because prompting over the top of it would ask for a signature you deliberately deferred. Pass {requestSignatureRightAway: true} (or set the store option) and ensureConnected asks for it itself.
How it initiates
- It initiates from
Idle, from WalletChosen (the wallet is chosen; upgrading it is what you asked for), and from any resting state that does not satisfy the target, including one holding the wrong account.
- It initiates from a picker step (
MechanismToChoose, WalletToChoose) that still carries the error of a previous failed attempt, so retrying after a rejected wallet prompt prompts again.
- It does not initiate from a picker step without an
error: that means the user is making a choice right now and connecting would hijack it. It waits for the user to pick (or cancel) and settles then. Pass {forceConnect: true} to connect anyway.
- It rejects with a
ConnectionFailure when the attempt fails. cause and the convenience code carry the underlying wallet error, so a user rejection is code === 4001.
- It rejects with
ConnectionFailure('Connection cancelled') when the user backs out, including by acknowledging an addressUnavailable.
Why it failed: reason
Read reason, not message, and not "is there a cause". Every ConnectionFailure carries a reason from a closed set of string literals, and the connection's own resting error carries the same field, with the same value for the same event: the thrown failure copies it, so the banner your app renders and the error your await caught cannot disagree.
This replaces the older advice to tell a cancellation from a failure by whether an underlying error is present. That test was all there was, and it was not enough: several outcomes carry no cause and mean completely different things, so "no cause" collapsed "the user closed the dialog" (say nothing) together with "the connection came to rest and cannot get there" (report it) and "your own app asked for a different account" (retry it).
reason |
What happened |
What to do |
cancelled |
The user closed or dismissed the connect flow (cancel(), back(), closed the popup). |
Nothing. Do not show an error: they decided. |
address-unavailable-acknowledged |
The user read addressUnavailable and chose not to switch account. |
Nothing, or re-offer the action. Also a decision, also not an error. |
superseded |
A newer ensureConnected naming a different address took the account slot. |
Retry, if you still want it. The user decided nothing; your app asked for two things at once. |
unreachable |
Came to rest, nothing in progress, nothing can be initiated from here. |
Report it. "Could not connect, try again." This is an outcome, not a silent no-op. |
wallet-rejected |
The wallet prompt was declined (EIP-1193 4001). |
Offer a retry; the same prompt can succeed next time. |
wallet-unavailable |
The wallet cannot authorise accounts (EIP-1193 4100): read-only, locked, unconfigured. |
Retrying will not help. Tell the user to unlock or configure their wallet. |
no-accounts |
The wallet answered with an empty account list. |
Report it. It looks like a refusal and is not one. |
cross-origin-blocked |
The wallet host refused a cross-origin request. |
Offer the onchain delegate path, not another popup. See "Cross-origin requests" below. |
host-refused |
The wallet host refused for a reason of its own. |
Show message; read (err.cause as {type?: string})?.type if you need to tell refusals apart. |
failed |
Anything else. The underlying error is on cause. |
Show message, offer a retry. |
import {ConnectionFailure} from '@etherplay/connect';
try {
const state = await connection.ensureConnected('WalletConnected');
} catch (err) {
if (!(err instanceof ConnectionFailure)) throw err;
switch (err.reason) {
case 'cancelled':
case 'address-unavailable-acknowledged':
break; // the user decided: say nothing
case 'wallet-rejected':
toast('Connection declined. Try again when you are ready.');
break;
case 'superseded':
break; // your own app asked for another account; retry if you still want this one
default:
toast(err.message); // unreachable, no-accounts, host refusals, anything new
}
}
Host refusals are deliberately not modelled further. The wallet host is deployed separately and chooses its own vocabulary, so this library pins only the refusal types it can verify: cross-origin-blocked, minted by @etherplay/connect-core, and its own popup's cancelation, which is not a refusal at all and surfaces as cancelled. Anything else passes through as host-refused with the host's type intact on cause. A member per host word would be a claim this package cannot check, and would go stale the day the host shipped a new one.
A dismissed addressUnavailable keeps the shape of a cancellation. Its message is still 'Connection cancelled', exactly as cancel() produces, so every path you already wrote that maps a refusal to "the user chose not to" keeps working and nobody paints a red banner over a decision. reason is what tells the two apart, and it is the only thing that does.
New members may appear in a MINOR version, so keep a default branch. A union the type system can exhaust is worth having, and it comes with that cost: an exhaustive switch with no default is the one shape a new member breaks. The trade was taken deliberately (see ADR-0004). failed is the catch-all, so most future causes will need no new member at all, and anything that does get one was indistinguishable from a generic failure before it existed.
reason is additive: message, cause and code are unchanged on every path, so code that ignores it behaves exactly as it did.
Asking for a specific account
Some sends only mean anything for one account. Replacing or cancelling a stuck transaction reuses its original nonce, so it has to be signed by the same key, and a signature from any other account is not a lesser answer, it is a wrong one. Name the account, and the wallet if you recorded it:
await connection.ensureConnected(
'WalletConnected',
{type: 'wallet', name: 'Rabby', address: payerOfTheStuckTransaction},
{doNotStoreLocally: true},
);
Call it unconditionally. Do not put an "are we already there" check in front of it: connection.account.address is the address the connection agreed on, not the one that can sign right now, and it is deliberately left untouched when the wallet locks, is revoked, or the user switches account behind the connection's back (wallet.status and wallet.accountChanged record those). A hand-written check on it passes for a locked wallet, skips the call that would have prompted the unlock, and the send then comes back {code: 4001} from the always-on provider, which is easy to report as "rejected by user" about a prompt nobody was shown.
To render readiness without initiating anything, ask canActAs:
import {canActAs} from '@etherplay/connect';
// in an event handler, against the store's current state
const ready = connection.canActAs(address);
// in markup or a reactive block, against a state you already hold: it takes `$connection`, so it
// re-evaluates when the wallet locks. The method form would not, since a method call gives a
// reactive block nothing to depend on.
const readyToo = canActAs($connection, address);
It is false for a locked wallet, for a revoked one, and for a connection on another account, and it starts no flow. It reads wallet.status and the accounts the wallet is offering, so it is right about a wallet that has never been asked for accounts (a WalletChosen connection) as well as one that has been. Chain is not part of the answer: signing as an address is chain-independent, and wallet.invalidChainId is the separate question.
When the wallet is not on that account: connection.addressUnavailable