Repository navigation
fix(wallet): preserve explicit URL chain across refresh on reconnect - #7910
tenderdeve wants to merge 6 commits into
Conversation
On refresh the first chain reported by the reconnecting wallet was applied unconditionally (in useAccountState) and written back to the URL (in WalletChainUrlSyncUpdater), overriding the network the user had selected before the refresh and causing an unexpected chain switch. Treat an explicit chain in the URL as the user's selection: skip the initial reconnect override when it differs, while still applying later chain switches and the no-explicit-URL 'follow the wallet' case as before. Fixes cowprotocol#7863
|
@tenderdeve is attempting to deploy a commit to the cow-dev Team on Vercel. A member of the Team first needs to authorize it. |
WalkthroughThe wallet account hook, trade setup hook, and URL synchronizer capture an explicit URL chain at load time. During reconnect, conflicting wallet chains are ignored and restored sessions do not trigger a wallet switch. Supported chain changes continue updating state and the URL. ChangesChain selection synchronization
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant URL
participant useAccountState
participant useSetupTradeState
participant WalletChainUrlSyncUpdater
participant Wallet
URL->>useAccountState: provide explicit chain
Wallet->>useAccountState: report reconnecting chain
useAccountState->>useAccountState: suppress conflicting chain
useSetupTradeState->>Wallet: avoid switch for restored session
WalletChainUrlSyncUpdater->>URL: preserve explicit chain
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
libs/wallet/src/wagmi/hooks/useAccountState.ts (1)
28-64: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winReset the initial-emission guard after disconnect.
initialStateAppliedRefis never reset. On a later disconnect/reconnect, this hook applies the wallet’s stored chain, whileWalletChainUrlSyncUpdaterre-arms its corresponding guard and preserves the explicit URL chain. That desynchronizes app state from the URL and reintroduces the reconnect behavior this PR intends to prevent. Reset both guards at the same wallet-session disconnect boundary.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@libs/wallet/src/wagmi/hooks/useAccountState.ts` around lines 28 - 64, Reset initialStateAppliedRef at the wallet-session disconnect boundary, alongside WalletChainUrlSyncUpdater’s corresponding guard reset. Ensure the next reconnect treats its first reported chain as the wallet’s stored chain and preserves an explicit URL chain, while subsequent user-driven chain changes continue updating normally.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@libs/wallet/src/wagmi/hooks/useAccountState.ts`:
- Around line 28-64: Reset initialStateAppliedRef at the wallet-session
disconnect boundary, alongside WalletChainUrlSyncUpdater’s corresponding guard
reset. Ensure the next reconnect treats its first reported chain as the wallet’s
stored chain and preserves an explicit URL chain, while subsequent user-driven
chain changes continue updating normally.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 935d3503-e4be-425d-86ff-6f54940beaa9
📒 Files selected for processing (2)
apps/cowswap-frontend/src/common/updaters/WalletChainUrlSyncUpdater.tslibs/wallet/src/wagmi/hooks/useAccountState.ts
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
elena-zh
left a comment
There was a problem hiding this comment.
Hey @tenderdeve , thank you, but not fixed:
- 1st app open: I connect to a wallet on Base, but the app is on Ethereum -->the app is connected to Ethreum
- Mobile (+WC): I connect to Arbitrum, switch to Avalanche, refresh the page --> I'm connected back to arbitrum.
- Besides, the app keeps showing this modal on page refresh on a mobile device
…h connect The previous guard keyed on whether a chain was present in the URL, but the cowswap URL always carries a chain in the path (e.g. /1/swap), so a fresh connect on a different wallet chain was wrongly suppressed and the app stayed on the default chain. Gate the URL-chain preservation on the wallet actually restoring a session (status === 'reconnecting') instead: on a fresh connect the wallet's chain is applied, on refresh the explicit URL chain is kept, and user-initiated switches after restore continue to sync.
|
@elena-zh thanks for testing on device — case 1 exposed the real flaw. cowswap always carries the chain in the URL path (e.g. Reworked in d230777: I now gate URL-chain preservation on the wallet actually restoring a session (
Could you re-test 1 and 2 on mobile+WC when you get a chance? I don't have a device to reproduce the WC restore timing, so I'd like to confirm case 2 holds there. For case 3 (the modal on every mobile refresh) — that looks separate from the chain-sync logic (it's the reconnect UI, not touched by this PR). Want me to look into it here, or track it as its own issue? |
|
Hey @tenderdeve ,
Thank you, but it sounds weird, because everyone has a mobile device nowadays. I'd like to remind you one of my requests to ship a code to review that is already properly tested.
Again, weird. Why does this happen in your PR while it does not on develop? |
|
You're right on both counts, and I was wrong to call case 3 separate — apologies. I traced it: this branch adds a That's the core problem: preserving the URL chain without a network-switch prompt only works if the WC session itself comes back on that chain, which the app can't force. I can't verify any variant of this without a mobile + WalletConnect setup, and you're right that I shouldn't have taken it on without one. I'd rather not keep pushing changes I can't test against your setup. I'm happy to close this so it's not sitting in your queue, and leave #7863 for someone who can reproduce it on device — unless you'd prefer a specific direction. Sorry for the back-and-forth. |
…resh The first-load handler forced the wallet to switch to the URL chain whenever a chain was present in the URL. Because the URL always carries a chain, this (1) overrode the wallet's chain on a fresh connect (app stayed on the URL default instead of following the wallet) and (2) re-fired switchNetwork on every refresh when the restored session reported a different chain, popping a network-switch modal each time. Distinguish a restored session (page refresh) from a fresh user connect via the wagmi connection status: on refresh keep the user's URL chain and don't prompt a switch; on a fresh connect follow the wallet's chain.
|
I found the actual driver — it's in The first-load handler called
Fixed in 18466b5 by telling a refresh apart from a fresh connect via the wagmi connection status (
One honest caveat I can't verify without a device: on refresh the wallet keeps whatever chain its WalletConnect session restored on. The app now shows your pre-refresh chain and won't pop the switch modal; if the wallet itself restored on a different chain, you'd only be asked to switch when you actually place a trade (the normal wrong-network prompt), not on every refresh. Could you give it another go on mobile + WC when you have a moment? Understand if you'd rather hand it off — just wanted to land the real cause first. |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@apps/cowswap-frontend/src/modules/trade/hooks/setupTradeState/useSetupTradeState.ts`:
- Around line 57-60: Update the useEffect tracking connectionStatus and reset
wasConnectionRestoredRef.current to false when connectionStatus becomes
'disconnected', while preserving the existing latch behavior for 'reconnecting'.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7afafa96-eb44-4aba-8540-e86238f1f8e6
📒 Files selected for processing (1)
apps/cowswap-frontend/src/modules/trade/hooks/setupTradeState/useSetupTradeState.ts
| const wasConnectionRestoredRef = useRef(false) | ||
| useEffect(() => { | ||
| if (connectionStatus === 'reconnecting') wasConnectionRestoredRef.current = true | ||
| }, [connectionStatus]) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate file =="
fd -a 'useSetupTradeState\.ts$' . || true
echo "== target file outline =="
ast-grep outline apps/cowswap-frontend/src/modules/trade/hooks/setupTradeState/useSetupTradeState.ts --view expanded || true
echo "== target file relevant sections =="
cat -n apps/cowswap-frontend/src/modules/trade/hooks/setupTradeState/useSetupTradeState.ts | sed -n '1,180p'
echo "== connectionStatus references in repo =="
rg -n "connectionStatus|wasConnectionRestoredRef|useConnection" apps/cowswap-frontend/src/modules/trade src -S || trueRepository: cowprotocol/cowswap
Length of output: 11166
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate dependency versions =="
fd -a '(^package\.json$|^yarn\.lock$|^package-lock\.json$|^pnpm-lock\.yaml$)' . | sed 's#^\./##' | head -100
echo "== wagmi versions =="
rg -n '"wagmi"|"`@wagmi/core`"|"`@wagmi/connectors`"' apps/cowswap-frontend/package.json package.json yarn.lock pnpm-lock.yaml package-lock.json 2>/dev/null || true
echo "== package files =="
for f in apps/cowswap-frontend/package.json package.json; do
if [ -f "$f" ]; then
echo "--- $f ---"
cat "$f" | jq '.dependencies.wagmi, .dependencies["`@wagmi/core`"], .dependencies["`@wagmi/connectors`"], .devDependencies.wagmi, .devDependencies["`@wagmi/core`"], .devDependencies["`@wagmi/connectors`"]' 2>/dev/null || cat "$f"
fi
done
echo "== deterministic state machine based on source behavior =="
python3 - <<'PY'
from pathlib import Path
p = Path("apps/cowswap-frontend/src/modules/trade/hooks/setupTradeState/useSetupTradeState.ts")
text = p.read_text()
checks = {
"latch_declared": "useRef(false)" in text and "wasConnectionRestoredRef" in text,
"latch_set_reconnecting": "connectionStatus === 'reconnecting'" in text and "wasConnectionRestoredRef.current = true" in text,
"latch_never_reset_in_setter": "wasConnectionRestoredRef.current = false" not in text,
"latch_used_in_chain_decision": "wasConnectionRestoredRef.current" in text,
"latch_effect_deps_connectionStatus": "[connectionStatus]" in text,
}
for k, v in checks.items():
print(f"{k}: {v}")
PYRepository: cowprotocol/cowswap
Length of output: 2388
🌐 Web query:
wagmi 3.6.9 useConnection status disconnected reconnecting failed connect
💡 Result:
In Wagmi v3.6.9, the useConnection hook provides the current connection state of your application [1][2]. The status property of this hook returns one of four string values representing the connection lifecycle [1]: 'connecting': The application is currently attempting to establish a connection. 'reconnecting': The application is attempting to re-establish a connection to one or more previously connected connectors (often triggered automatically on page load). 'connected': At least one connector is currently active and connected [1]. 'disconnected': There is no active connection to any connector [1]. If you are observing a state that transitions between these, it is typical behavior for Wagmi to manage its connection state automatically [3]. For example, if the status shows as 'reconnecting', Wagmi is likely performing an auto-connection process; if it ends in 'disconnected', the attempt to restore the previous session has failed [1]. To manage these states in your UI, you can use the boolean flags derived from the status, such as isConnecting, isReconnecting, isConnected, and isDisconnected [1]. You can also use the useConnectionEffect hook if you need to trigger specific actions (like logging or UI alerts) specifically when a connection is established or lost [4]. If you are facing persistent issues where the status remains 'disconnected' after an attempted connection, ensure that your Wagmi Config is correctly initialized and that your connectors are configured to support auto-connection if desired [3].
Citations:
- 1: https://wagmi.sh/react/api/hooks/useConnection
- 2: https://cdn.jsdelivr.net/npm/[email protected]/dist/types/hooks/useConnection.d.ts
- 3: https://wagmi.sh/react/guides/faq
- 4: https://app.unpkg.com/[email protected]/files/src/hooks/useConnectionEffect.ts
🌐 Web query:
site:wagmi.sh/reference/hooks/useConnection status disconnected reconnecting wagmi 3
💡 Result:
The URL appears invalid: https://wagmi.sh/reference/hooks/useConnection returns 404. In current Wagmi docs, connection state is exposed through useAccount, whose status can be:
'connecting' | 'reconnecting' | 'connected' | 'disconnected'Example:
const { status, isConnected } = useAccount()
if (status === 'reconnecting') {
// Restoring a previously persisted wallet connection
}
if (status === 'disconnected') {
// No wallet is connected
}Wagmi’s current documentation site lists React hooks but does not appear to provide a useConnection hook reference. [1][2]
🌐 Web query:
github wagmi isAutoReconnecting reconnecting status source
💡 Result:
In Wagmi, the isReconnecting flag and the reconnecting status are used to track whether a wallet is in the process of automatically reconnecting to a previously used connector, typically upon application load [1][2][3]. Core Details: - Status: The account status is a state that can be 'connecting', 'reconnecting', 'connected', or 'disconnected' [1][4]. - isReconnecting: This boolean flag is true when the application is attempting to restore a previous session (e.g., via auto-connect) [1][2][3]. - isConnected vs. Reconnecting: A known point of discussion is that while status is 'reconnecting', isConnected may return false or a boolean depending on the version and specific internal state, as the connection is not yet fully established [4]. - Reconnect Action: In modern versions of Wagmi (e.g., v2+), there is an explicit reconnect action provided by @wagmi/core that can be used to manually trigger reconnection to specific connectors [5]. The behavior of these flags is managed by the Wagmi config [6][7]. In older versions, an autoConnect property was used in the configuration [7], whereas newer versions may handle this through different lifecycle mechanisms or the reconnect action [5]. If you encounter an application getting stuck in a 'reconnecting' state, it is often related to component re-renders or hydration issues where the connection effect is not being triggered or cleaned up correctly [8].
Citations:
- 1: https://1.x.wagmi.sh/react/hooks/useAccount
- 2: https://0.9.x.wagmi.sh/react/hooks/useAccount
- 3: https://0.10.x.wagmi.sh/react/hooks/useAccount
- 4: [BUG]: isConnected is incorrect wevm/wagmi#4050
- 5: https://wagmi.sh/core/api/actions/reconnect
- 6: https://1.x.wagmi.sh/core/config
- 7: https://0.9.x.wagmi.sh/react/config
- 8: wagmi stays in the
reconnecting: truestate during the hot-reload wevm/wagmi#3490
🌐 Web query:
github wagmi v3 useConnection implementation useAccount isReconnecting
💡 Result:
In Wagmi v3, the hook previously known as useAccount has been renamed to useConnection [1]. This change reflects a more accurate representation of how Wagmi manages connections between applications and Ethereum providers [1]. When using useConnection to check for reconnection status, you can access the isReconnecting boolean property, which is derived from the current connection status [2]. The status property returned by useConnection can be one of four values [2]: - 'connecting': Attempting to establish a connection. - 'reconnecting': Attempting to re-establish a connection to one or more connectors. - 'connected': At least one connector is connected. - 'disconnected': No connection to any connector. The isReconnecting flag is a boolean that provides a direct way to check if the application is currently in the 'reconnecting' state [2]. This is typically used to handle UI states while the application attempts to re-establish a session, such as after a page refresh or when auto-connect is active [2]. Example usage: import { useConnection } from 'wagmi' function ConnectionStatus { const { isReconnecting, status } = useConnection if (isReconnecting) { return
Citations:
- 1: https://wagmi.sh/react/guides/migrate-from-v2-to-v3
- 2: https://wagmi.sh/react/api/hooks/useConnection
🌐 Web query:
github wevm wagmi v3 useConnection hook source isAutoReconnecting connecting reconnecting
💡 Result:
In Wagmi v3, the useAccount hook from previous versions has been renamed to useConnection to better reflect the library's connection model [1][2]. The useConnection hook returns an object that includes several boolean flags and a status property, which are derived from the current connection state [3]. Key properties returned by useConnection: - status: This property can be one of four values: 'connecting', 'reconnecting', 'connected', or 'disconnected' [3]. - 'connecting': The application is attempting to establish a connection. - 'reconnecting': The application is attempting to re-establish a connection to one or more connectors. - 'connected': At least one connector is active. - 'disconnected': No connections are active. - Derived booleans: Based on the status, the hook also provides boolean properties such as isConnecting, isReconnecting, isConnected, and isDisconnected [3]. Regarding isAutoReconnecting: It is important to note that the useConnection hook does not explicitly provide an isAutoReconnecting property [3]. The reconnection process is internally handled by Wagmi, and when the system is in the process of re-establishing previous connections (often triggered by auto-connect logic), the status will be 'reconnecting', and the isReconnecting boolean will be true [3]. Source Implementation: The useConnection hook is implemented using useSyncExternalStoreWithTracked to ensure it stays in sync with the underlying Wagmi configuration [4]. It utilizes the watchConnection function from @wagmi/core to monitor connection changes and retrieve the current state via getConnection [4]. Technical Context: Wagmi v3 simplifies the API to better align with TanStack Query patterns, and developers are encouraged to use the returned status to narrow the return type [3][2]. For instance, when the status is 'connected', properties like address are guaranteed to be defined [3]. If you are encountering issues where the application appears to hang in a specific state (like isReconnecting), this may be related to hydration or mount cycles, which have been topics of discussion in the project's issue tracker [5][6].
Citations:
- 1: https://wagmi.sh/react/guides/migrate-from-v2-to-v3
- 2: https://www.ignaciopastorsanchez.com/blog/how-to-read-from-a-smart-contract-using-wagmi-v3
- 3: https://wagmi.sh/react/api/hooks/useConnection
- 4: https://app.unpkg.com/[email protected]/files/src/hooks/useConnection.ts
- 5: wagmi stays in the
reconnecting: truestate during the hot-reload wevm/wagmi#3490 - 6: fix: allow excessive hydration to fix hanging
isReconnectingstate wevm/wagmi#3492
🌐 Web query:
github wevm wagmi src hooks useConnection
💡 Result:
In the current version of the Wagmi library (wagmi), the useConnection hook is a provided React hook used to retrieve the current connection status and details [1]. It allows you to access information about the connected account and chain within your React components [1]. Key details about useConnection: - Import: It is imported directly from the wagmi package: import { useConnection } from 'wagmi' [1]. - Functionality: It provides the connected address, addresses, chain, connector, and status (e.g., connecting, connected, disconnected) [1]. - Derived State: It also provides boolean flags like isConnecting, isReconnecting, isConnected, and isDisconnected, which are derived from the connection status [1]. Related hooks: - useConnect: Used specifically for initiating a connection to a wallet/connector [2][3]. - useConnectionEffect: A hook for performing side effects (like callbacks) when connection status changes (e.g., onConnect, onDisconnect) [4]. You can find the official documentation and API reference for this hook on the Wagmi website [1].
Citations:
- 1: https://wagmi.sh/react/api/hooks/useConnection
- 2: https://wagmi.sh/react/api/hooks/useConnect
- 3: https://1.x.wagmi.sh/react/hooks/useConnect
- 4: https://app.unpkg.com/[email protected]/files/src/hooks/useConnectionEffect.ts
🌐 Web query:
"hasAnyConnector" "isAutoReconnecting" useConnection wagmi
💡 Result:
In the context of Wagmi, the terms you mentioned relate to account connection and auto-reconnection state, though their availability depends on the specific version of the library you are using [1][2]. 1. isReconnecting: This is a standard property available in the useAccount hook (in Wagmi v1.x and earlier) that indicates whether the application is currently attempting to automatically reconnect to the last used connector [1]. It is part of the account status object [1]. 2. useConnection: This is a hook introduced in newer versions of Wagmi (e.g., v3+) as a replacement for useAccount [2]. It provides access to account information, such as the connected address, connection status, and chain ID [2]. 3. hasAnyConnector / isAutoReconnecting: There are no standard, public-facing hooks or properties by these exact names in the official Wagmi documentation [3][1][4][5]. For auto-reconnection behavior: - In older versions (v0.x/v1.x), auto-reconnection was configured via the autoConnect property in createConfig [3][6]. - If you are experiencing issues with reconnection, ensure your connectors are correctly registered within the createConfig function, as this allows Wagmi to properly manage their storage for session persistence [7]. If you are transitioning to Wagmi v3, note that the API has changed significantly, such as using useConnection for account state and using separate hooks like useConnectors for managing connector lists [2]. Always refer to the specific documentation for your installed version [2].
Citations:
- 1: https://1.x.wagmi.sh/react/hooks/useAccount
- 2: https://docs.metamask.io/metamask-connect/evm/quickstart/wagmi/
- 3: https://1.x.wagmi.sh/core/config
- 4: https://1.x.wagmi.sh/react/hooks/useConnect
- 5: https://1.x.wagmi.sh/examples/connect-wallet
- 6: https://0.9.x.wagmi.sh/react/config
- 7: bug: autoConnect fails to reconnect wevm/wagmi#2511
🌐 Web query:
"github.com/wevm/wagmi" "src/hooks" "useConnection.ts" "isAutoReconnecting"
💡 Result:
In modern versions of wagmi (v2+), there is no property named isAutoReconnecting on the useConnection hook or related connection state [1][2]. The wagmi library manages reconnection state via the status property, which can be one of 'connecting', 'reconnecting', 'connected', or 'disconnected' [1]. The useConnection hook (and similar hooks like useAccount) provide boolean flags derived from this status, specifically isReconnecting (for when the library is attempting to re-establish a connection) [1][3]. Key technical details regarding connection state: - The isReconnecting flag is used to indicate that the library is currently attempting to re-establish a connection to one or more previously used connectors [1]. - In earlier versions of wagmi (v1.x), the autoConnect configuration was used to enable automatic reconnection [4]. In current versions, this is handled automatically by the wagmi configuration on mount [5]. - Issues related to the "hanging" of the isReconnecting state during development (e.g., during hot-module replacement) have been documented in the wagmi repository, where the state may fail to transition correctly if the component lifecycle behavior during re-renders is not handled as expected [5][6]. If you are looking for a boolean to check if the library is in the process of reconnecting, you should use the isReconnecting flag provided by useConnection or useAccount [1][3].
Citations:
- 1: https://wagmi.sh/react/api/hooks/useConnection
- 2: https://cdn.jsdelivr.net/npm/[email protected]/dist/types/hooks/useConnection.d.ts
- 3: https://1.x.wagmi.sh/react/hooks/useAccount
- 4: https://1.x.wagmi.sh/core/config
- 5: wagmi stays in the
reconnecting: truestate during the hot-reload wevm/wagmi#3490 - 6: fix: allow excessive hydration to fix hanging
isReconnectingstate wevm/wagmi#3492
Reset the restoration latch when auto-connect fails.
wasConnectionRestoredRef.current stays true after connectionStatus === 'reconnecting'. If the restore flow fails and connectionStatus later becomes disconnected, a subsequent user-initiated connection is still treated as a refreshed session and can take the URL chain instead of the wallet chain. Clear the latch when connectionStatus is disconnected.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@apps/cowswap-frontend/src/modules/trade/hooks/setupTradeState/useSetupTradeState.ts`
around lines 57 - 60, Update the useEffect tracking connectionStatus and reset
wasConnectionRestoredRef.current to false when connectionStatus becomes
'disconnected', while preserving the existing latch behavior for 'reconnecting'.
|
@tenderdeve , sorry, if you don't have a possibility to verify your proposed fix first, it is better to close the PR. |
Summary
Fixes #7863.
After connecting a wallet, selecting a network (e.g. Avalanche) and refreshing the page, the app switched to a different network instead of staying on the one that was selected.
Root cause
An explicit chain in the URL (
#/43114/…) is the user's selection and should survive a refresh, but on reconnect it was clobbered in two places:useAccountState— the first chain reported bysubscribeState(the wallet's stored chain) was applied unconditionally, overriding the URL-seeded chain.WalletChainUrlSyncUpdater— that wallet chain was then written back into the URL, so the whole app followed the wallet's chain.Fix
Capture the explicit URL chain at load and, on the first reconnect emission only, skip applying the wallet's chain when it differs. Chains the user switches to after reconnect still sync normally, and when the URL has no explicit chain the existing 'follow the wallet' behaviour is unchanged. This also lines up with the intent of #7853 (the app should honour the user's selected network).
Testing
I don't have a WalletConnect/Rabby setup to reproduce on-device, so this is scoped narrowly to the initial-reconnect-with-explicit-URL case to avoid touching the normal connect/switch flows. On-device confirmation from someone with the repro would be appreciated — happy to adjust the precedence if you intended the wallet's chain to win here.
Summary by CodeRabbit