
In traditional Web2 architecture, login is a simple, closed, nearly linear HTTP exchange: users submit credentials, and the server verifies them and issues a Session Cookie or JWT.
In modern Web3 systems using Sign-In with Ethereum (SIWE / EIP-4361), login becomes an asynchronous distributed state machine spanning the browser DOM, injected extensions such as MetaMask and Rabby, hardware wallets, on-chain RPC nodes, and backend authentication servers.
Most open-source tutorials and scaffolds demonstrate only the Happy Path, which represents less than 10% of wallet-connection behavior:
// Textbook happy-path antipattern: fails as soon as an exception occurs
const { data: signature } = await signMessageAsync({ message: siweMessage });
await api.post('/auth/verify', { signature });
Ignoring the uncontrollable, heterogeneous nature of external wallet extensions leaves more than 90% of DApps with fragile real-world experiences:
- While the signing prompt is open, a user switches MetaMask from Account 1 to Account 2. The private key now belongs to Account 2, but the message still hardcodes Account 1’s address. Server verification fails, and the frontend stays on a loading spinner forever;
- A user selects Reject on a mobile or hardware wallet. The frontend mishandles MetaMask’s
4001/ACTION_REJECTEDcode, deadlocking the UI until a forced refresh; - A user starts login in tab A, then logs out in tab B while waiting to sign. Seconds later, A’s callback writes an expired authentication Token, creating conflicting ghost identities across tabs;
- The signature message’s
nonceexpires, for example after 5 minutes. The server returns a context-free401 Unauthorized, and the frontend has no recovery path to fetch a fresh Nonce automatically.
In our early infrastructure article Wallet login: design the failure states first, we established a core rule: design wallet interactions by defining their Failure States first. Drawing on production work in NOVA Membership, this article examines 7 unhappy paths and provides a production solution using TypeScript, wagmi/viem, an authAttemptId generation counter, and a finite state machine (FSM).
Wallet Authentication: Seven Unhappy Paths
A robust SIWE login flow must handle these 7 common production exceptions:
+-----------------------------------------------------------------------------------+
| Seven Web3 Wallet Login Unhappy Paths |
+-----------------------------------------------------------------------------------+
| [State 1: IDLE / Initially disconnected] |
| | |
| +--> [Path 1: Extension missing / Provider lost] -> Offer another wallet or WalletConnect |
| | |
| [State 2: ACQUIRING_NONCE / Fetching server Nonce] |
| | |
| +--> [Path 2: Server RPC instability / gateway timeout] -> Exponential backoff, 3 retries maximum |
| | |
| [State 3: AWAITING_SIGNATURE / Wallet prompt open] |
| | |
| +--> [Path 3: User cancels / rejects (Error 4001)] -> Clean reset and restore retry |
| +--> [Path 4: Account changes (accountsChanged race)] -> Abort, invalidate generation |
| +--> [Path 5: Chain changes (chainChanged race)] -> Abort and request target chain |
| +--> [Path 6: Nonce expires while prompt remains open] -> Refresh Nonce and request signature again |
| | |
| [State 4: VERIFYING / Server cryptographic verification] |
| | |
| +--> [Path 7: Concurrent tab login / cross-tab logout conflict] -> BroadcastChannel logout sync |
| | |
| [State 5: AUTHENTICATED / Final authenticated state] |
+-----------------------------------------------------------------------------------+
Comparing Three Wallet Authentication Architectures

| Dimension | Basic useSignMessage Scaffold |
Common Default RainbowKit/ConnectKit Integration | Fone Failure-State Machine (NOVA) |
|---|---|---|---|
| Account/chain switch defense | 0% (signature/address mismatch) | Weak (may disconnect but cannot neutralize in-flight work) | 100% immunity (authAttemptId generation lock + two physical-state checks) |
| Rejection/cancellation | Can stick at isConnecting: true |
Toast appears, but internal state may lag | Precisely catches ACTION_REJECTED, returns to IDLE with 0 delay |
| Stale-prompt replacement | Multiple overlapping signing prompts | Relies on browser replacement; unexpected errors possible | Make-Before-Break actively cancels pending Promises |
| Cross-tab sessions | Unsupported (A logged in, B still guest) | LocalStorage polling introduces delay | Bidirectional BroadcastChannel sync in milliseconds |
| Clock-skew tolerance | Unclear boundaries; frequent Expired errors | Server-only configuration | Shared 300-second tolerance band and automatic renewal |
Implementation: A Wallet State Machine with Generation Locks
The following excerpts are sanitized from our production membership and permission system (nova-membership/src/hooks/useWalletAuth.ts).
1. Neutralizing Async Races with authAttemptId
After a user clicks “connect and sign,” fetching the Nonce and opening the wallet occur at different times. Rapid double-clicks or an account change while the prompt is open can create two concurrent asynchronous contexts.
The production solution is a monotonically increasing Generation Counter:
// Excerpt from nova-membership/src/hooks/useWalletAuth.ts
import { useRef, useState, useCallback, useEffect } from 'react';
import { useWalletClient, usePublicClient } from 'wagmi';
import { SiweMessage } from 'siwe';
export type AuthState =
| 'IDLE'
| 'PREPARING_NONCE'
| 'AWAITING_SIGNATURE'
| 'VERIFYING'
| 'AUTHENTICATED'
| 'REJECTED'
| 'SESSION_CONFLICT'
| 'ERROR';
export function useGuardedWalletAuth() {
const [state, setState] = useState<AuthState>('IDLE');
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const { data: walletClient } = useWalletClient();
const publicClient = usePublicClient();
// Core defense: a monotonically increasing generation counter
const authAttemptId = useRef(0);
const activeAbortController = useRef<AbortController | null>(null);
// Destroy in-flight tasks on component unmount or reset
useEffect(() => {
return () => {
authAttemptId.current++;
activeAbortController.current?.abort();
};
}, []);
2. Preflight Checks and Wallet-State Snapshots
Before sending personal_sign to the wallet, capture the current address, chain ID, and Genesis Hash, and start a new generation context:
// Excerpt from nova-membership/src/hooks/useWalletAuth.ts
const login = useCallback(async () => {
// 1. Invalidate old in-flight work and create a new generation ID
authAttemptId.current++;
const currentGeneration = authAttemptId.current;
// 2. Abort previous HTTP requests
activeAbortController.current?.abort();
activeAbortController.current = new AbortController();
const signal = activeAbortController.current.signal;
if (!walletClient || !publicClient) {
setState('ERROR');
setErrorMessage('WALLET_NOT_CONNECTED');
return;
}
try {
setState('PREPARING_NONCE');
setErrorMessage(null);
// 3. Capture the initial physical wallet state
const [initialAddress] = await walletClient.getAddresses();
const initialChainId = await walletClient.getChainId();
// Fetch a high-entropy server Nonce, protected by AbortSignal
const nonceRes = await fetch('/api/auth/nonce', { signal });
if (!nonceRes.ok) throw new Error('NONCE_ACQUISITION_FAILED');
const { nonce } = await nonceRes.json();
// Checkpoint 1: after the network response, check whether this generation was abandoned
if (currentGeneration !== authAttemptId.current) return;
// Build the standard EIP-4361 SIWE payload
const domain = window.location.host;
const origin = window.location.origin;
const siwe = new SiweMessage({
domain,
address: initialAddress,
statement: 'Sign in to access Web3 Membership & Portal features.',
uri: origin,
version: '1',
chainId: initialChainId,
nonce,
issuedAt: new Date().toISOString(),
expirationTime: new Date(Date.now() + 5 * 60 * 1000).toISOString(), // Hard 5-minute timeout
});
const preparedMessage = siwe.prepareMessage();
// Enter the awaiting-signature state
setState('AWAITING_SIGNATURE');
// Checkpoint 2: before opening the prompt, recheck for account or chain changes
const [currentAddress] = await walletClient.getAddresses();
const currentChainId = await walletClient.getChainId();
if (
currentAddress.toLowerCase() !== initialAddress.toLowerCase() ||
currentChainId !== initialChainId
) {
throw new Error('ACCOUNT_OR_CHAIN_CHANGED');
}
// Open the external wallet signing prompt
const signature = await walletClient.signMessage({
account: initialAddress,
message: preparedMessage,
});
// Checkpoint 3: after signing, recheck the generation and active address
if (currentGeneration !== authAttemptId.current) return;
const [postSignAddress] = await walletClient.getAddresses();
if (postSignAddress.toLowerCase() !== initialAddress.toLowerCase()) {
throw new Error('ACCOUNT_SWITCHED_DURING_SIGNATURE');
}
// Enter server-side credential verification
setState('VERIFYING');
const verifyRes = await fetch('/api/auth/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: preparedMessage, signature }),
signal,
});
if (!verifyRes.ok) {
throw new Error('SIGNATURE_VERIFICATION_FAILED');
}
// Authentication succeeded; broadcast session state across tabs
syncChannel.postMessage({ type: 'LOGIN_SUCCESS', address: initialAddress });
setState('AUTHENTICATED');
} catch (err: any) {
// Prevent stale generations from overwriting current UI state
if (currentGeneration !== authAttemptId.current) return;
// Identify explicit rejection errors from the wallet prompt
if (
err?.code === 4001 ||
err?.code === 'ACTION_REJECTED' ||
err?.name === 'UserRejectedRequestError'
) {
setState('REJECTED');
setErrorMessage('User rejected the signature request.');
return;
}
if (err.message === 'ACCOUNT_SWITCHED_DURING_SIGNATURE' || err.message === 'ACCOUNT_OR_CHAIN_CHANGED') {
setState('SESSION_CONFLICT');
setErrorMessage('Wallet account or chain changed during login. Please retry.');
return;
}
setState('ERROR');
setErrorMessage(err.message || 'AUTHENTICATION_FAILED');
}
}, [walletClient, publicClient]);
For a more detailed examination of stale-prompt cancellation during asynchronous generation, see Cancel Stale Wallet Prompts with Async Generation Checks.
3. Real-Time Cross-Tab Session Synchronization (BroadcastChannel)
If login in tab 1 leaves tab 2 showing a guest view, or disconnecting in tab 2 leaves tab 1 authenticated, business state becomes seriously inconsistent.
The browser-native BroadcastChannel enables cross-tab broadcasts within seconds, without server polling:
// Excerpt from nova-membership/src/domain/wallet-state-machine.ts
const syncChannel = new BroadcastChannel('nova_wallet_auth_channel');
export function initMultiTabSessionSync(
onLogin: (address: string) => void,
onLogout: () => void
) {
syncChannel.onmessage = (event) => {
switch (event.data?.type) {
case 'LOGIN_SUCCESS':
onLogin(event.data.address);
break;
case 'LOGOUT_SUCCESS':
onLogout();
break;
case 'ACCOUNT_CHANGED':
// Another tab changed accounts; trigger global revalidation
onLogout();
break;
default:
break;
}
};
}
export function broadcastLogout() {
syncChannel.postMessage({ type: 'LOGOUT_SUCCESS' });
}
Four Production Rules for Wallet Authentication
Before releasing a login flow for a Web3 business application, membership system, or DApp, verify these requirements:
- Never request a wallet signature without locking the generation: Record the interaction with
authAttemptIdand check its validity at everyawaitboundary so old requests cannot overwrite new state; - Check physical account and network state before and after signing: At prompt invocation and after the signature returns, compare
walletClient.getAddresses()against the message address to prevent account substitution; - Treat rejection properly (Error 4001 / ACTION_REJECTED): A normal cancellation is not a system-wide network failure. Reset to
REJECTEDorIDLEwithin 0 milliseconds and preserve one-click retry; - Use BroadcastChannel for consistent site-wide login state: Broadcast credential changes to all open tabs within milliseconds to prevent conflicts.
Enterprise Web3 Architecture Consulting and Full-Stack Delivery
Fone specializes in Web3 frontends, ERC-4337 smart accounts, high-concurrency membership points, and decentralized business platforms. Alongside code-level security, we use a thoroughly tested production standard for handling interaction failures:
- Explore our full-stack membership, referral, and entitlement platform: NOVA Membership
- Read the original failure-state design approach: Wallet login: design the failure states first
- Review the production-readiness audit: From AI and Web3 Prototype to Production: 12 Engineering and Financial-Security Checks
- Book a system availability and code assessment with a senior Web3 architect: Discuss Custom Requirements with Fone