Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: state and local storage sync and persistent when use multiple adapters #3419

Merged
Show file tree
Hide file tree
Changes from 25 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
296dff4
refactor: multiple adapter state sync and persisting
enesozturk Dec 10, 2024
f9d86b7
chore: linter issues
enesozturk Dec 10, 2024
2b0ef58
chore: changeset file
enesozturk Dec 10, 2024
334d0ad
chore: revert lock file
enesozturk Dec 10, 2024
3fb35db
Merge branch 'main' into enes/apkt-1689-connecting-to-multiple-adapte…
enesozturk Dec 10, 2024
2b4bdfe
fix: type import dependency
enesozturk Dec 10, 2024
0602994
chore: ignore clone packages
enesozturk Dec 10, 2024
ec5d0c8
chore: ignore lab new
enesozturk Dec 10, 2024
b2604c2
chore: ignore gallery and lab new
enesozturk Dec 10, 2024
5c7fb26
chore: remove scaffold-ui new vitest config
enesozturk Dec 10, 2024
6a5be28
Merge branch 'main' into enes/apkt-1689-connecting-to-multiple-adapte…
enesozturk Dec 10, 2024
3dfc7ae
chore: lock file
enesozturk Dec 10, 2024
1ff0a16
refactor: use active namespace storage value
enesozturk Dec 10, 2024
d1dfa8a
refactor: use active namespace storage value to sync account and balance
enesozturk Dec 10, 2024
f852c89
refactor: add caipNetworks to chain controller initialize function
enesozturk Dec 10, 2024
ee0eedd
chore: fix tests
enesozturk Dec 10, 2024
194b3d7
chore: missing initialize param
enesozturk Dec 10, 2024
52f1ca9
Merge branch 'main' into enes/apkt-1689-connecting-to-multiple-adapte…
enesozturk Dec 10, 2024
b6a8dc5
chore: import solana network
enesozturk Dec 10, 2024
5173f98
chore: save changes
enesozturk Dec 10, 2024
8b7b972
refactor: solana request get active chain logic
enesozturk Dec 10, 2024
018e7c0
Merge branch 'main' into enes/apkt-1689-connecting-to-multiple-adapte…
enesozturk Dec 10, 2024
d79a51a
chore: lock file
enesozturk Dec 10, 2024
278d4c9
chore: linter issues
enesozturk Dec 10, 2024
7833dca
chore: linter issues
enesozturk Dec 10, 2024
3482663
fix: finding network with local storage id value
enesozturk Dec 10, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/few-chicken-enjoy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@reown/appkit-adapter-solana': patch
'@reown/appkit-adapter-wagmi': patch
'@reown/appkit': patch
'@reown/appkit-common': patch
'@reown/appkit-core': patch
'@reown/appkit-adapter-ethers': patch
'@reown/appkit-adapter-ethers5': patch
'@reown/appkit-utils': patch
'@reown/appkit-cdn': patch
'appkit-cli': patch
'@reown/appkit-experimental': patch
'@reown/appkit-polyfills': patch
'@reown/appkit-scaffold-ui': patch
'@reown/appkit-siwe': patch
'@reown/appkit-siwx': patch
'@reown/appkit-ui': patch
'@reown/appkit-wallet': patch
---

Fixes state and storage syncronization and persisting on multiple adapter instances
8 changes: 6 additions & 2 deletions packages/adapters/solana/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import {
} from '@reown/appkit-common'
import {
AlertController,
ChainController,
CoreHelperUtil,
EventsController,
StorageUtil,
type ConnectorType,
type Provider
} from '@reown/appkit-core'
Expand All @@ -33,6 +35,7 @@ import { handleMobileWalletRedirection } from './utils/handleMobileWalletRedirec
import { SolStoreUtil } from './utils/SolanaStoreUtil.js'
import { watchStandard } from './utils/watchStandard.js'
import { withSolanaNamespace } from './utils/withSolanaNamespace.js'
import { solana } from '@reown/appkit/networks'

export interface AdapterOptions {
connectionSettings?: Commitment | ConnectionConfig
Expand Down Expand Up @@ -454,7 +457,8 @@ export class SolanaAdapter extends AdapterBlueprint {

// For standard Solana wallets
const address = await selectedProvider.connect()
const chainId = this.caipNetworks?.[0]?.id || 1
const { chainId: activeChainId } = StorageUtil.getActiveNetworkProps()
const chainId = activeChainId || solana.id

this.listenProviderEvents(selectedProvider as unknown as WalletStandardProvider)

Expand All @@ -475,7 +479,7 @@ export class SolanaAdapter extends AdapterBlueprint {
const walletConnectProvider = new WalletConnectProvider({
provider: params.provider as UniversalProvider,
chains: params.caipNetworks,
getActiveChain: () => params.activeCaipNetwork
getActiveChain: () => ChainController.state.activeCaipNetwork
})

return walletConnectProvider as unknown as UniversalProvider
Expand Down
15 changes: 9 additions & 6 deletions packages/adapters/wagmi/src/connectors/UniversalConnector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { StorageUtil } from '@reown/appkit-core'
import type { AppKitOptions } from '@reown/appkit'
import type { AppKit } from '@reown/appkit'
import { ConstantsUtil } from '@reown/appkit-common'
import type { CaipNetwork } from '@reown/appkit-common'
import type { CaipNetwork, ChainNamespace } from '@reown/appkit-common'

type UniversalConnector = Connector & {
onDisplayUri(uri: string): void
Expand Down Expand Up @@ -201,7 +201,7 @@ export function walletConnect(
return []
}

const accountsList = provider?.session?.namespaces['eip155']?.accounts
const accountsList = provider?.session?.namespaces[ConstantsUtil.CHAIN.EVM]?.accounts

const accounts = accountsList?.map(account => account.split(':')[2]) ?? []

Expand All @@ -213,10 +213,13 @@ export function walletConnect(
provider_?.events.setMaxListeners(Number.POSITIVE_INFINITY)
}

const activeNamespace = StorageUtil.getActiveNamespace()
const currentChainId = appKit.getCaipNetwork()?.id

if (chainId && currentChainId !== chainId) {
const storedCaipNetwork = StorageUtil.getStoredActiveCaipNetwork()
if (chainId && currentChainId !== chainId && activeNamespace) {
const storedCaipNetworkId = StorageUtil.getStoredActiveCaipNetworkId()
const appKitCaipNetworks = appKit?.getCaipNetworks(activeNamespace as ChainNamespace)
const storedCaipNetwork = appKitCaipNetworks?.find(n => n.id === storedCaipNetworkId)

if (storedCaipNetwork && storedCaipNetwork.chainNamespace === ConstantsUtil.CHAIN.EVM) {
await this.switchChain?.({ chainId: Number(storedCaipNetwork.id) })
Expand All @@ -234,7 +237,7 @@ export function walletConnect(
}

const provider = await this.getProvider()
const chain = provider.session?.namespaces['eip155']?.chains?.[0]
const chain = provider.session?.namespaces[ConstantsUtil.CHAIN.EVM]?.chains?.[0]

const network = caipNetworks.find(c => c.id === chain)

Expand Down Expand Up @@ -388,7 +391,7 @@ export function walletConnect(
return []
}

const accounts = provider_?.session?.namespaces['eip155']?.accounts
const accounts = provider_?.session?.namespaces[ConstantsUtil.CHAIN.EVM]?.accounts

// eslint-disable-next-line radix
const chainIds = accounts?.map(account => Number.parseInt(account.split(':')[1] ?? '')) ?? []
Expand Down
170 changes: 170 additions & 0 deletions packages/adapters/wagmi/src/tests/UniversalConnector.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { walletConnect } from '../connectors/UniversalConnector'
import { mainnet } from '@reown/appkit/networks'
import { getAddress } from 'viem'
import {
mockAppKit,
mockProvider,
mockSession,
mockAddress,
mockCaipNetworks,
mockCaipAddress
} from './mocks/AppKit'

vi.mock('@reown/appkit-core', async importOriginal => {
const actual = await importOriginal<typeof import('@reown/appkit-core')>()
return {
...actual,
StorageUtil: {
getActiveNamespace: vi.fn(),
getStoredActiveCaipNetworkId: vi.fn()
}
}
})

const mockStorage = {
getItem: vi.fn(),
setItem: vi.fn()
}

const mockEmitter = {
emit: vi.fn(),
on: vi.fn(),
removeListener: vi.fn()
}

describe('UniversalConnector', () => {
let connectorInstance: any

beforeEach(() => {
const createConnector = walletConnect(
{
isNewChainsStale: false
} as any,
mockAppKit,
mockCaipNetworks as any
)

connectorInstance = createConnector({
chains: mockCaipNetworks,
options: {},
// @ts-expect-error - mocking Wagmi's storage
storage: mockStorage,
// @ts-expect-error - mocking Wagmi's emitter
emitter: mockEmitter
})
})

afterEach(() => {
vi.clearAllMocks()
})

describe('connect', () => {
it('should connect successfully', async () => {
const expectedChainId = mainnet.id

mockProvider.enable.mockResolvedValue([mockAddress])

const result = await connectorInstance.connect()

expect(result).toEqual({
accounts: [getAddress(mockAddress)],
chainId: expectedChainId
})
expect(mockProvider.on).toHaveBeenCalled()
expect(mockProvider.session.namespaces.eip155.accounts).toEqual([mockCaipAddress])
})

it('should handle user rejection', async () => {
mockProvider.enable.mockRejectedValue(new Error('user rejected'))

await expect(connectorInstance.connect()).rejects.toThrow('User rejected the request.')
})
})

describe('getAccounts', () => {
it('should return accounts from provider session', async () => {
mockProvider.enable.mockResolvedValue([mockAddress])
await connectorInstance.connect()
const accounts = await connectorInstance.getAccounts()

expect(accounts).toEqual([mockAddress])
})

it('should return empty array when no session exists', async () => {
// @ts-expect-error - override mockProvider only for session to test getAccounts
mockProvider.session = undefined
const accounts = await connectorInstance.getAccounts()

expect(accounts).toEqual([])
})
})

describe('disconnect', () => {
it('should disconnect successfully', async () => {
mockProvider.session = mockSession

await connectorInstance.connect()
await connectorInstance.disconnect()

expect(mockProvider.disconnect).toHaveBeenCalled()
expect(mockProvider.removeListener).toHaveBeenCalled()
})
})

describe('switchChain', () => {
it('should switch chain successfully', async () => {
mockProvider.request.mockResolvedValue(null)

const result = await connectorInstance.switchChain({ chainId: 1 })

expect(result).toEqual(
expect.objectContaining({
id: 1,
name: 'Ethereum'
})
)
expect(mockProvider.request).toHaveBeenCalledWith({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0x1' }]
})
})

it('should handle adding a new chain', async () => {
// First request fails, triggering add chain flow
mockProvider.request.mockRejectedValueOnce(new Error('chain not found'))
mockProvider.request.mockResolvedValueOnce(null)

const result = await connectorInstance.switchChain({ chainId: 1 })

expect(result).toEqual(
expect.objectContaining({
id: 1,
name: 'Ethereum'
})
)
expect(mockProvider.request).toHaveBeenCalledWith({
method: 'wallet_addEthereumChain',
params: [
expect.objectContaining({
chainId: '0x1',
chainName: 'Ethereum'
})
]
})
})
})

describe.skip('isAuthorized', () => {
it('should return true when authorized', async () => {
const result = await connectorInstance.isAuthorized()
expect(result).toBe(true)
})

it('should return false when no accounts exist', async () => {
mockProvider.session.namespaces.eip155.accounts = []
const result = await connectorInstance.isAuthorized()
expect(result).toBe(false)
})
})
})
Loading
Loading