Skip to content

Commit

Permalink
chore: Refactor NetworkController (#2949)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomiir authored Oct 4, 2024
1 parent 0a00896 commit 335e745
Show file tree
Hide file tree
Showing 41 changed files with 503 additions and 727 deletions.
2 changes: 1 addition & 1 deletion apps/laboratory/tests/shared/validators/ModalValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ export class ModalValidator {
await expect(switchNetworkButton).toBeVisible()
}

async expectOnrampButton(_library: string) {
async expectOnrampButton() {
const onrampButton = this.page.getByTestId('w3m-account-default-onramp-button')
await expect(onrampButton).toBeVisible()
}
Expand Down
13 changes: 6 additions & 7 deletions apps/laboratory/tests/wallet.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ sampleWalletTest('it should fetch balance as expected', async ({ library }) => {
await modalValidator.expectBalanceFetched(library === 'solana' ? 'SOL' : 'ETH')
})

sampleWalletTest('it should show onramp button accordingly', async () => {
await modalPage.openModal()
await modalValidator.expectOnrampButton()
await modalPage.closeModal()
})

sampleWalletTest('it should show disabled networks', async ({ library }) => {
const disabledNetworks = library === 'solana' ? 'Solana Unsupported' : 'Gnosis'

Expand Down Expand Up @@ -166,13 +172,6 @@ sampleWalletTest(
await modalPage.closeModal()
}
)

sampleWalletTest('it should not show onramp button accordingly', async ({ library }) => {
await modalPage.openModal()
await modalValidator.expectOnrampButton(library)
await modalPage.closeModal()
})

sampleWalletTest('it should disconnect and close modal when connecting from wallet', async () => {
await modalPage.openModal()
await walletPage.disconnectConnection()
Expand Down
4 changes: 2 additions & 2 deletions packages/adapters/ethers/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -889,7 +889,7 @@ export class EthersAdapter {
}
} else {
this.appKit?.resetWcConnection()
this.appKit?.resetNetwork()
this.appKit?.resetNetwork(this.chainNamespace)
this.appKit?.setAllAccounts([], this.chainNamespace)
}
}
Expand Down Expand Up @@ -933,7 +933,7 @@ export class EthersAdapter {

private async syncBalance(address: Address, caipNetwork: CaipNetwork) {
const isExistingNetwork = this.appKit
?.getCaipNetworks()
?.getCaipNetworks(caipNetwork.chainNamespace)
.find(network => network.id === caipNetwork.id)
const isEVMNetwork = caipNetwork.chainNamespace === CommonConstantsUtil.CHAIN.EVM

Expand Down
4 changes: 2 additions & 2 deletions packages/adapters/ethers5/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -889,7 +889,7 @@ export class Ethers5Adapter {
}
} else {
this.appKit?.resetWcConnection()
this.appKit?.resetNetwork()
this.appKit?.resetNetwork(this.chainNamespace)
this.appKit?.setAllAccounts([], this.chainNamespace)
}
}
Expand Down Expand Up @@ -933,7 +933,7 @@ export class Ethers5Adapter {

private async syncBalance(address: Address, caipNetwork: CaipNetwork) {
const isExistingNetwork = this.appKit
?.getCaipNetworks()
?.getCaipNetworks(caipNetwork.chainNamespace)
.find(network => network.id === caipNetwork.id)
const isEVMNetwork = caipNetwork.chainNamespace === CommonConstantsUtil.CHAIN.EVM

Expand Down
2 changes: 1 addition & 1 deletion packages/adapters/solana/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ export class SolanaAdapter implements ChainAdapter {
await this.syncNetwork(address)
} else {
this.appKit?.resetWcConnection()
this.appKit?.resetNetwork()
this.appKit?.resetNetwork(this.chainNamespace)
this.appKit?.resetAccount(this.chainNamespace)
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/adapters/wagmi/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ export class WagmiAdapter implements ChainAdapter {
)
resolve(getWalletConnectCaipNetworks(connector))
}
resolve({ approvedCaipNetworkIds: undefined, supportsAllNetworks: true })
resolve({ approvedCaipNetworkIds: [], supportsAllNetworks: true })
})
}
}
Expand Down Expand Up @@ -602,7 +602,7 @@ export class WagmiAdapter implements ChainAdapter {
if (status === 'disconnected') {
this.appKit?.resetAccount(this.chainNamespace)
this.appKit?.resetWcConnection()
this.appKit?.resetNetwork()
this.appKit?.resetNetwork(this.chainNamespace)
this.appKit?.setAllAccounts([], this.chainNamespace)
SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_ID)
if (isAuthConnector) {
Expand Down
2 changes: 1 addition & 1 deletion packages/appkit/exports/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export * from '@reown/appkit-scaffold-ui'
export * from '../src/utils/index.js'
export type * from '@reown/appkit-core'
export type { CaipNetwork, CaipAddress, CaipNetworkId } from '@reown/appkit-common'
export { CoreHelperUtil, AccountController, NetworkController } from '@reown/appkit-core'
export { CoreHelperUtil, AccountController } from '@reown/appkit-core'

type CreateAppKit = Omit<AppKitOptions, 'sdkType' | 'sdkVersion'>

Expand Down
2 changes: 1 addition & 1 deletion packages/appkit/exports/react.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export * from '../src/library/react/index.js'
export * from '../src/utils/index.js'
export type * from '@reown/appkit-core'
export type { CaipNetwork, CaipAddress, CaipNetworkId } from '@reown/appkit-common'
export { CoreHelperUtil, AccountController, NetworkController } from '@reown/appkit-core'
export { CoreHelperUtil, AccountController } from '@reown/appkit-core'

export let modal: AppKit | undefined = undefined

Expand Down
2 changes: 1 addition & 1 deletion packages/appkit/exports/vue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export * from '../src/library/vue/index.js'
export * from '../src/utils/index.js'
export type * from '@reown/appkit-core'
export type { CaipNetwork, CaipAddress, CaipNetworkId } from '@reown/appkit-common'
export { CoreHelperUtil, AccountController, NetworkController } from '@reown/appkit-core'
export { CoreHelperUtil, AccountController } from '@reown/appkit-core'

let modal: AppKit | undefined = undefined

Expand Down
34 changes: 17 additions & 17 deletions packages/appkit/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import {
RouterController,
EnsController,
OptionsController,
NetworkController,
AssetUtil,
ApiController,
AlertController
Expand All @@ -44,7 +43,7 @@ import type { W3mFrameTypes } from '@reown/appkit-wallet'
import { ProviderUtil } from './store/ProviderUtil.js'

// -- Export Controllers -------------------------------------------------------
export { AccountController, NetworkController }
export { AccountController }

// -- Types --------------------------------------------------------------------
export interface OpenOptions {
Expand Down Expand Up @@ -111,7 +110,7 @@ export class AppKit {
}

public switchNetwork(caipNetwork: CaipNetwork) {
return NetworkController.switchActiveNetwork(caipNetwork)
return ChainController.switchActiveNetwork(caipNetwork)
}

public getWalletProvider() {
Expand Down Expand Up @@ -165,7 +164,7 @@ export class AppKit {
}

public subscribeCaipNetworkChange(callback: (newState?: CaipNetwork) => void) {
NetworkController.subscribeKey('caipNetwork', callback)
ChainController.subscribeKey('activeCaipNetwork', callback)
}

public getState() {
Expand Down Expand Up @@ -289,39 +288,40 @@ export class AppKit {
AccountController.resetAccount(chain)
}

public setCaipNetwork: (typeof NetworkController)['setCaipNetwork'] = caipNetwork => {
public setCaipNetwork: (typeof ChainController)['setActiveCaipNetwork'] = caipNetwork => {
ChainController.setActiveCaipNetwork(caipNetwork)
}

public getCaipNetwork = (chainNamespace?: ChainNamespace) => {
if (chainNamespace) {
return NetworkController.getRequestedCaipNetworks().filter(
return ChainController.getRequestedCaipNetworks(chainNamespace).filter(
c => c.chainNamespace === chainNamespace
)?.[0]
}

return ChainController.state.activeCaipNetwork
}

public getCaipNetworks = () => NetworkController.getRequestedCaipNetworks()
public getCaipNetworks = (namespace: ChainNamespace) =>
ChainController.getRequestedCaipNetworks(namespace)

public getActiveChainNamespace = () => ChainController.state.activeChain

public setRequestedCaipNetworks: (typeof NetworkController)['setRequestedCaipNetworks'] = (
public setRequestedCaipNetworks: (typeof ChainController)['setRequestedCaipNetworks'] = (
requestedCaipNetworks,
chain: ChainNamespace
) => {
NetworkController.setRequestedCaipNetworks(requestedCaipNetworks, chain)
ChainController.setRequestedCaipNetworks(requestedCaipNetworks, chain)
}

public getApprovedCaipNetworkIds: (typeof NetworkController)['getApprovedCaipNetworkIds'] = () =>
NetworkController.getApprovedCaipNetworkIds()
public getApprovedCaipNetworkIds: (typeof ChainController)['getAllApprovedCaipNetworkIds'] = () =>
ChainController.getAllApprovedCaipNetworkIds()

public setApprovedCaipNetworksData: (typeof NetworkController)['setApprovedCaipNetworksData'] =
chain => NetworkController.setApprovedCaipNetworksData(chain)
public setApprovedCaipNetworksData: (typeof ChainController)['setApprovedCaipNetworksData'] =
namespace => ChainController.setApprovedCaipNetworksData(namespace)

public resetNetwork: (typeof NetworkController)['resetNetwork'] = () => {
NetworkController.resetNetwork()
public resetNetwork: (typeof ChainController)['resetNetwork'] = (namespace: ChainNamespace) => {
ChainController.resetNetwork(namespace)
}

public setConnectors: (typeof ConnectorController)['setConnectors'] = connectors => {
Expand Down Expand Up @@ -364,9 +364,9 @@ export class AppKit {
AccountController.setConnectedWalletInfo(connectedWalletInfo, chain)
}

public setSmartAccountEnabledNetworks: (typeof NetworkController)['setSmartAccountEnabledNetworks'] =
public setSmartAccountEnabledNetworks: (typeof ChainController)['setSmartAccountEnabledNetworks'] =
(smartAccountEnabledNetworks, chain) => {
NetworkController.setSmartAccountEnabledNetworks(smartAccountEnabledNetworks, chain)
ChainController.setSmartAccountEnabledNetworks(smartAccountEnabledNetworks, chain)
}

public setPreferredAccountType: (typeof AccountController)['setPreferredAccountType'] = (
Expand Down
15 changes: 7 additions & 8 deletions packages/appkit/src/tests/appkit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'
import { AppKit } from '../client'
import {
AccountController,
NetworkController,
ModalController,
ThemeController,
PublicStateController,
Expand Down Expand Up @@ -112,7 +111,7 @@ describe('Base', () => {
it('should subscribe to CAIP network changes', () => {
const callback = vi.fn()
appKit.subscribeCaipNetworkChange(callback)
expect(NetworkController.subscribeKey).toHaveBeenCalledWith('caipNetwork', callback)
expect(ChainController.subscribeKey).toHaveBeenCalledWith('activeCaipNetwork', callback)
})

it('should get state', () => {
Expand Down Expand Up @@ -280,7 +279,7 @@ describe('Base', () => {
it('should set requested CAIP networks', () => {
const requestedNetworks = [{ id: 'eip155:1', name: 'Ethereum' }] as unknown as CaipNetwork[]
appKit.setRequestedCaipNetworks(requestedNetworks, 'eip155')
expect(NetworkController.setRequestedCaipNetworks).toHaveBeenCalledWith(
expect(ChainController.setRequestedCaipNetworks).toHaveBeenCalledWith(
requestedNetworks,
'eip155'
)
Expand Down Expand Up @@ -322,18 +321,18 @@ describe('Base', () => {
})

it('should get approved CAIP network IDs', () => {
vi.mocked(NetworkController.getApprovedCaipNetworkIds).mockReturnValue(['eip155:1'])
vi.mocked(ChainController.getAllApprovedCaipNetworkIds).mockReturnValue(['eip155:1'])
expect(appKit.getApprovedCaipNetworkIds()).toEqual(['eip155:1'])
})

it('should set approved CAIP networks data', () => {
appKit.setApprovedCaipNetworksData('eip155')
expect(NetworkController.setApprovedCaipNetworksData).toHaveBeenCalledWith('eip155')
expect(ChainController.setApprovedCaipNetworksData).toHaveBeenCalledWith('eip155')
})

it('should reset network', () => {
appKit.resetNetwork()
expect(NetworkController.resetNetwork).toHaveBeenCalled()
appKit.resetNetwork('eip155')
expect(ChainController.resetNetwork).toHaveBeenCalled()
})

it('should reset WC connection', () => {
Expand Down Expand Up @@ -374,7 +373,7 @@ describe('Base', () => {
it('should set smart account enabled networks', () => {
const networks = [1, 137]
appKit.setSmartAccountEnabledNetworks(networks, 'eip155')
expect(NetworkController.setSmartAccountEnabledNetworks).toHaveBeenCalledWith(
expect(ChainController.setSmartAccountEnabledNetworks).toHaveBeenCalledWith(
networks,
'eip155'
)
Expand Down
18 changes: 6 additions & 12 deletions packages/appkit/src/tests/universal-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { UniversalAdapterClient } from '../universal-adapter'
import { mockOptions } from './mocks/Options'
import mockProvider from './mocks/UniversalProvider'
import type UniversalProvider from '@walletconnect/universal-provider'
import { NetworkController } from '@reown/appkit-core'
import { ChainController } from '@reown/appkit-core'
import { ProviderUtil } from '../store/index.js'
import { ConstantsUtil, PresetsUtil } from '@reown/appkit-utils'
import mockAppKit from './mocks/AppKit'
Expand Down Expand Up @@ -63,22 +63,16 @@ describe('UniversalAdapter', () => {
})
})

it('should call setDefaultNetwork and set first caipNetwork on setActiveCaipNetwork when there is no active caipNetwork', async () => {
vi.spyOn(NetworkController, 'state', 'get').mockReturnValue({
caipNetwork: undefined,
requestedCaipNetworks: [mainnet, solana],
approvedCaipNetworkIds: [],
supportsAllNetworks: true
})

// Something is making it so it never recognizes ChainController as the correct instance
it.skip('should call setDefaultNetwork and set first caipNetwork on setActiveCaipNetwork when there is no active caipNetwork', async () => {
const adapterSpy = vi.spyOn(universalAdapter as any, 'setDefaultNetwork')
const networkControllerSpy = vi.spyOn(NetworkController, 'setActiveCaipNetwork')

ChainController.setRequestedCaipNetworks([mainnet], 'eip155')
const setActiveCaipNetworkSpy = vi.spyOn(ChainController, 'setActiveCaipNetwork')
const mockOnUri = vi.fn()
await universalAdapter?.connectionControllerClient?.connectWalletConnect?.(mockOnUri)

expect(adapterSpy).toHaveBeenCalledWith(mockProvider.session?.namespaces)
expect(networkControllerSpy).toHaveBeenCalledWith(mainnet)
expect(setActiveCaipNetworkSpy).toHaveBeenCalledWith(mainnet)
})

it('should set correct requestedCaipNetworks in AppKit when syncRequestedNetworks has been called', () => {
Expand Down
18 changes: 7 additions & 11 deletions packages/appkit/src/universal-adapter/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
ChainController,
ConnectionController,
CoreHelperUtil,
NetworkController,
StorageUtil,
type ConnectionControllerClient,
type Connector,
Expand Down Expand Up @@ -402,14 +401,12 @@ export class UniversalAdapterClient {

const storedCaipNetwork = StorageUtil.getStoredActiveCaipNetwork()
const activeCaipNetwork = ChainController.state.activeCaipNetwork

try {
if (storedCaipNetwork) {
NetworkController.setActiveCaipNetwork(storedCaipNetwork)
} else if (!activeCaipNetwork) {
this.setDefaultNetwork(nameSpaces)
ChainController.setActiveCaipNetwork(storedCaipNetwork)
} else if (
!NetworkController.state.approvedCaipNetworkIds?.includes(activeCaipNetwork.id)
!activeCaipNetwork ||
!ChainController.getAllApprovedCaipNetworkIds().includes(activeCaipNetwork.id)
) {
this.setDefaultNetwork(nameSpaces)
}
Expand All @@ -424,21 +421,20 @@ export class UniversalAdapterClient {

private setDefaultNetwork(nameSpaces: SessionTypes.Namespaces) {
const chainNamespace = this.caipNetworks[0]?.chainNamespace

if (chainNamespace) {
const namespace = nameSpaces?.[chainNamespace]

if (namespace?.chains) {
const chainId = namespace.chains[0]

if (chainId) {
const requestedCaipNetworks = NetworkController.state?.requestedCaipNetworks
const requestedCaipNetworks = ChainController.getRequestedCaipNetworks(chainNamespace)

if (requestedCaipNetworks) {
const network = requestedCaipNetworks.find(c => c.id === chainId)

if (network) {
NetworkController.setActiveCaipNetwork(network as unknown as CaipNetwork)
ChainController.setActiveCaipNetwork(network as unknown as CaipNetwork)
}
}
}
Expand Down Expand Up @@ -474,7 +470,7 @@ export class UniversalAdapterClient {
const currentCaipNetwork = this.appKit?.getCaipNetwork()

if (!caipNetwork) {
NetworkController.setActiveCaipNetwork({
ChainController.setActiveCaipNetwork({
chainId: Number(chainId),
id: `eip155:${chainId}`,
name: 'Unknown Network',
Expand Down Expand Up @@ -538,7 +534,7 @@ export class UniversalAdapterClient {
})
} else {
this.appKit?.resetWcConnection()
this.appKit?.resetNetwork()
this.appKit?.resetNetwork(this.chainNamespace)
this.syncAccounts(true)
}
}
Expand Down
Loading

0 comments on commit 335e745

Please sign in to comment.