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: ethers/ethers5 infinite requests #3086

Merged
merged 3 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
23 changes: 23 additions & 0 deletions .changeset/lazy-windows-behave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
'@reown/appkit-adapter-ethers5': patch
'@reown/appkit-adapter-ethers': patch
'@apps/demo': patch
'@apps/gallery': patch
'@apps/laboratory': patch
'@reown/appkit-adapter-polkadot': patch
'@reown/appkit-adapter-solana': patch
'@reown/appkit-adapter-wagmi': patch
'@reown/appkit': patch
'@reown/appkit-utils': patch
'@reown/appkit-cdn': patch
'@reown/appkit-common': patch
'@reown/appkit-core': patch
'@reown/appkit-experimental': patch
'@reown/appkit-polyfills': patch
'@reown/appkit-scaffold-ui': patch
'@reown/appkit-siwe': patch
'@reown/appkit-ui': patch
'@reown/appkit-wallet': patch
---

Fixes an issue where ethers and ethers5 adapters were causing infinite network requests
7 changes: 5 additions & 2 deletions packages/adapters/ethers/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -631,9 +631,12 @@ export class EthersAdapter {
if (provider) {
const { addresses, chainId } = await EthersHelpersUtil.getUserInfo(provider)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why source the infor from here ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's because during the construct of the adapter we'd need to get the address and chain id directly from the provider so users are still connected even if they refresh the page. The logic happens here.

const firstAddress = addresses?.[0]
const caipAddress = `${this.chainNamespace}:${chainId}:${firstAddress}` as CaipAddress
const caipNetwork = this.caipNetworks.find(c => c.id === chainId) ?? this.caipNetworks[0]
const caipAddress =
`${this.chainNamespace}:${caipNetwork?.id}:${firstAddress}` as CaipAddress
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not use the caipNetwork id directly?

Copy link
Contributor Author

@magiziz magiziz Oct 15, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Like adding chainId directly into caipAddress ? I tried doing that, but when switching to a unsupported network it'd throw an error, instead i checked if the network is supported.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I meant ${caipNetwork.namespace}:${caipNetwork?.id}:${firstAddress} or ${caipNetwork.caipNetworkId}:${firstAddress}

(unsure about proper names but you get what I mean)


if (firstAddress && chainId) {
if (firstAddress && caipNetwork) {
this.appKit?.setCaipNetwork(caipNetwork)
this.appKit?.setCaipAddress(caipAddress, this.chainNamespace)
ProviderUtil.setProviderId('eip155', providerId)
ProviderUtil.setProvider<Provider>('eip155', provider)
Expand Down
68 changes: 64 additions & 4 deletions packages/adapters/ethers/src/tests/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
mainnet as AppkitMainnet,
polygon as AppkitPolygon,
optimism as AppkitOptimism,
bsc as AppkitBsc
bsc as AppkitBsc,
harmonyOne as AppkitHarmonyOne
} from '@reown/appkit/networks'
import { ProviderUtil, type ProviderIdType } from '@reown/appkit/store'
import { SafeLocalStorage, SafeLocalStorageKeys } from '@reown/appkit-common'
Expand Down Expand Up @@ -107,17 +108,40 @@ vi.mock('ethers', async () => {
}
})

vi.mock('@reown/appkit-common', async importOriginal => {
const actual = await importOriginal()
return {
// @ts-expect-error - actual is not typed
...actual,
SafeLocalStorage: {
getItem: vi.fn(key => {
const values = {
'@appkit/wallet_id': 'injected'
}
return values[key as keyof typeof values]
}),
setItem: vi.fn(),
removeItem: vi.fn()
}
}
})

describe('EthersAdapter', () => {
let client: EthersAdapter

beforeEach(() => {
vi.clearAllMocks()
const ethersConfig = mockCreateEthersConfig()
client = new EthersAdapter()
vi.spyOn(client as any, 'createEthersConfig').mockImplementation(() => ({
metadata: ethersConfig.metadata,
injected: ethersConfig.injected
}))
const optionsWithEthersConfig = {
...mockOptions,
networks: caipNetworks,
defaultNetwork: undefined,
ethersConfig: mockCreateEthersConfig()
ethersConfig
}
client.construct(mockAppKit, optionsWithEthersConfig)
})
Expand Down Expand Up @@ -650,17 +674,23 @@ describe('EthersAdapter', () => {
describe('EthersClient - syncAccount', () => {
beforeEach(() => {
vi.spyOn(client as any, 'syncConnectedWalletInfo').mockImplementation(() => {})
vi.spyOn(client as any, 'setupProviderListeners').mockImplementation(() => {})
vi.spyOn(client as any, 'setProvider').mockImplementation(() => Promise.resolve())
vi.spyOn(client as any, 'syncProfile').mockImplementation(() => Promise.resolve())
vi.spyOn(client as any, 'syncBalance').mockImplementation(() => Promise.resolve())
vi.spyOn(mockAppKit, 'getIsConnectedState').mockReturnValue(true)
vi.spyOn(mockAppKit, 'getPreferredAccountType').mockReturnValue('eoa')
})

it('should sync account when connected and address is provided', async () => {
const mockAddress = '0x1234567890123456789012345678901234567890'
const mockCaipNetwork = mainnet

vi.spyOn(mockAppKit, 'getIsConnectedState').mockReturnValue(true)
vi.spyOn(mockAppKit, 'getCaipNetwork').mockReturnValue(mockCaipNetwork)
vi.spyOn(mockAppKit, 'getPreferredAccountType').mockReturnValue('eoa')
vi.spyOn(EthersHelpersUtil, 'getUserInfo').mockResolvedValue({
addresses: ['0x1234567890123456789012345678901234567890'],
chainId: 1
})

await client['syncAccount']({ address: mockAddress })

Expand All @@ -671,9 +701,39 @@ describe('EthersAdapter', () => {
)
expect(client['syncConnectedWalletInfo']).toHaveBeenCalled()
expect(client['syncProfile']).toHaveBeenCalledWith(mockAddress)
expect(client['setupProviderListeners']).toHaveBeenCalledOnce()
expect(client['setProvider']).toHaveBeenCalledOnce()
expect(mockAppKit.setCaipAddress).toHaveBeenCalledTimes(2)
expect(mockAppKit.setCaipAddress).toHaveBeenCalledWith(
`eip155:${mainnet.id}:${mockAddress}`,
'eip155'
)
expect(mockAppKit.setCaipNetwork).toHaveBeenCalledOnce()
expect(mockAppKit.setCaipNetwork).toHaveBeenCalledWith(mainnet)
expect(mockAppKit.setApprovedCaipNetworksData).toHaveBeenCalledWith('eip155')
})

it('it should fallback to first available chain if current chain is unsupported', async () => {
const mockAddress = '0x1234567890123456789012345678901234567890'

vi.spyOn(EthersHelpersUtil, 'getUserInfo').mockResolvedValue({
addresses: [mockAddress],
chainId: AppkitHarmonyOne.id as number
})

await client['syncAccount']({ address: mockAddress })

expect(client['setupProviderListeners']).toHaveBeenCalledOnce()
expect(client['setProvider']).toHaveBeenCalledOnce()
expect(mockAppKit.setCaipAddress).toHaveBeenCalledTimes(2)
expect(mockAppKit.setCaipAddress).toHaveBeenCalledWith(
`eip155:${mainnet.id}:${mockAddress}`,
'eip155'
)
expect(mockAppKit.setCaipNetwork).toHaveBeenCalledOnce()
expect(mockAppKit.setCaipNetwork).toHaveBeenCalledWith(mainnet)
})

it('should reset connection when not connected', async () => {
vi.spyOn(mockAppKit, 'getIsConnectedState').mockReturnValue(false)

Expand Down
7 changes: 5 additions & 2 deletions packages/adapters/ethers5/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,9 +607,12 @@ export class Ethers5Adapter {
if (provider) {
const { addresses, chainId } = await EthersHelpersUtil.getUserInfo(provider)
const firstAddress = addresses?.[0]
const caipAddress = `${this.chainNamespace}:${chainId}:${firstAddress}` as CaipAddress
const caipNetwork = this.caipNetworks.find(c => c.id === chainId) ?? this.caipNetworks[0]
const caipAddress =
`${this.chainNamespace}:${caipNetwork?.id}:${firstAddress}` as CaipAddress

if (firstAddress && chainId) {
if (firstAddress && caipNetwork) {
this.appKit?.setCaipNetwork(caipNetwork)
this.appKit?.setCaipAddress(caipAddress, this.chainNamespace)
ProviderUtil.setProviderId('eip155', providerId)
ProviderUtil.setProvider<Provider>('eip155', provider)
Expand Down
68 changes: 64 additions & 4 deletions packages/adapters/ethers5/src/tests/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
mainnet as AppkitMainnet,
polygon as AppkitPolygon,
optimism as AppkitOptimism,
bsc as AppkitBsc
bsc as AppkitBsc,
harmonyOne as AppkitHarmonyOne
} from '@reown/appkit/networks'
import { ProviderUtil, type ProviderIdType } from '@reown/appkit/store'
import { SafeLocalStorage, SafeLocalStorageKeys } from '@reown/appkit-common'
Expand Down Expand Up @@ -113,17 +114,40 @@ vi.mock('ethers', async () => {
}
})

vi.mock('@reown/appkit-common', async importOriginal => {
const actual = await importOriginal()
return {
// @ts-expect-error - actual is not typed
...actual,
SafeLocalStorage: {
getItem: vi.fn(key => {
const values = {
'@appkit/wallet_id': 'injected'
}
return values[key as keyof typeof values]
}),
setItem: vi.fn(),
removeItem: vi.fn()
}
}
})

describe('EthersAdapter', () => {
let client: Ethers5Adapter

beforeEach(() => {
vi.clearAllMocks()
const ethersConfig = mockCreateEthersConfig()
client = new Ethers5Adapter()
vi.spyOn(client as any, 'createEthersConfig').mockImplementation(() => ({
metadata: ethersConfig.metadata,
injected: ethersConfig.injected
}))
const optionsWithEthersConfig = {
...mockOptions,
networks: caipNetworks,
defaultNetwork: undefined,
ethersConfig: mockCreateEthersConfig()
ethersConfig
}
client.construct(mockAppKit, optionsWithEthersConfig)
})
Expand Down Expand Up @@ -656,17 +680,23 @@ describe('EthersAdapter', () => {
describe('EthersClient - syncAccount', () => {
beforeEach(() => {
vi.spyOn(client as any, 'syncConnectedWalletInfo').mockImplementation(() => {})
vi.spyOn(client as any, 'setupProviderListeners').mockImplementation(() => {})
vi.spyOn(client as any, 'setProvider').mockImplementation(() => Promise.resolve())
vi.spyOn(client as any, 'syncProfile').mockImplementation(() => Promise.resolve())
vi.spyOn(client as any, 'syncBalance').mockImplementation(() => Promise.resolve())
vi.spyOn(mockAppKit, 'getIsConnectedState').mockReturnValue(true)
vi.spyOn(mockAppKit, 'getPreferredAccountType').mockReturnValue('eoa')
})

it('should sync account when connected and address is provided', async () => {
const mockAddress = '0x1234567890123456789012345678901234567890'
const mockCaipNetwork = mainnet

vi.spyOn(mockAppKit, 'getIsConnectedState').mockReturnValue(true)
vi.spyOn(mockAppKit, 'getCaipNetwork').mockReturnValue(mockCaipNetwork)
vi.spyOn(mockAppKit, 'getPreferredAccountType').mockReturnValue('eoa')
vi.spyOn(EthersHelpersUtil, 'getUserInfo').mockResolvedValue({
addresses: ['0x1234567890123456789012345678901234567890'],
chainId: 1
})

await client['syncAccount']({ address: mockAddress })

Expand All @@ -677,9 +707,39 @@ describe('EthersAdapter', () => {
)
expect(client['syncConnectedWalletInfo']).toHaveBeenCalled()
expect(client['syncProfile']).toHaveBeenCalledWith(mockAddress)
expect(client['setupProviderListeners']).toHaveBeenCalledOnce()
expect(client['setProvider']).toHaveBeenCalledOnce()
expect(mockAppKit.setCaipAddress).toHaveBeenCalledTimes(2)
expect(mockAppKit.setCaipAddress).toHaveBeenCalledWith(
`eip155:${mainnet.id}:${mockAddress}`,
'eip155'
)
expect(mockAppKit.setCaipNetwork).toHaveBeenCalledOnce()
expect(mockAppKit.setCaipNetwork).toHaveBeenCalledWith(mainnet)
expect(mockAppKit.setApprovedCaipNetworksData).toHaveBeenCalledWith('eip155')
})

it('it should fallback to first available chain if current chain is unsupported', async () => {
const mockAddress = '0x1234567890123456789012345678901234567890'

vi.spyOn(EthersHelpersUtil, 'getUserInfo').mockResolvedValue({
addresses: [mockAddress],
chainId: AppkitHarmonyOne.id as number
})

await client['syncAccount']({ address: mockAddress })

expect(client['setupProviderListeners']).toHaveBeenCalledOnce()
expect(client['setProvider']).toHaveBeenCalledOnce()
expect(mockAppKit.setCaipAddress).toHaveBeenCalledTimes(2)
expect(mockAppKit.setCaipAddress).toHaveBeenCalledWith(
`eip155:${mainnet.id}:${mockAddress}`,
'eip155'
)
expect(mockAppKit.setCaipNetwork).toHaveBeenCalledOnce()
expect(mockAppKit.setCaipNetwork).toHaveBeenCalledWith(mainnet)
})

it('should reset connection when not connected', async () => {
vi.spyOn(mockAppKit, 'getIsConnectedState').mockReturnValue(false)

Expand Down
Loading