Skip to content

Commit

Permalink
feat: validate internal state for persisted chainId
Browse files Browse the repository at this point in the history
  • Loading branch information
tmm committed Aug 6, 2024
1 parent b791610 commit 871dbdb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/thin-fireants-turn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@wagmi/core": patch
---

Added validation to internal state for persisted `chainId`.
31 changes: 23 additions & 8 deletions packages/core/src/createConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,14 +224,10 @@ export function createConfig<
if (version === currentVersion) return persistedState as State

const initialState = getInitialState()
const chainId =
persistedState &&
typeof persistedState === 'object' &&
'chainId' in persistedState &&
typeof persistedState.chainId === 'number' &&
chains.getState().some((x) => x.id === persistedState.chainId)
? persistedState.chainId
: initialState.chainId
const chainId = validatePersistedChainId(
persistedState,
initialState.chainId,
)
return { ...initialState, chainId }
},
name: 'store',
Expand Down Expand Up @@ -260,9 +256,15 @@ export function createConfig<
'status' in persistedState
)
delete persistedState.status
// Make sure persisted `chainId` is valid
const chainId = validatePersistedChainId(
persistedState,
currentState.chainId,
)
return {
...currentState,
...(persistedState as object),
chainId,
}
},
skipHydration: ssr,
Expand All @@ -273,6 +275,19 @@ export function createConfig<
),
)

function validatePersistedChainId(
persistedState: unknown,
defaultChainId: number,
) {
return persistedState &&
typeof persistedState === 'object' &&
'chainId' in persistedState &&
typeof persistedState.chainId === 'number' &&
chains.getState().some((x) => x.id === persistedState.chainId)
? persistedState.chainId
: defaultChainId
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// Subscribe to changes
/////////////////////////////////////////////////////////////////////////////////////////////////
Expand Down

0 comments on commit 871dbdb

Please sign in to comment.