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/wagmi solana auth #2876

Closed
wants to merge 7 commits into from
Closed
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
5 changes: 4 additions & 1 deletion packages/adapters/solana/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,10 @@ export class SolanaAdapter implements ChainAdapter {
const isSolanaNetwork = val?.chainNamespace === this.chainNamespace

if (isSolanaAddress && isSolanaNetwork && caipAddress) {
this.syncAccount({ address: CoreHelperUtil.getPlainAddress(caipAddress), caipNetwork: val })
this.syncAccount({
address: CoreHelperUtil.getPlainAddress(caipAddress),
caipNetwork: val
})
}
})
AccountController.subscribeKey(
Expand Down
32 changes: 17 additions & 15 deletions packages/adapters/solana/src/providers/AuthProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ import {
import { withSolanaNamespace } from '../utils/withSolanaNamespace.js'
import base58 from 'bs58'
import { isVersionedTransaction } from '@solana/wallet-adapter-base'
import type { CaipNetwork, ChainNamespace } from '@reown/appkit-common'
import {
SafeLocalStorage,
SafeLocalStorageKeys,
type CaipNetwork,
type ChainNamespace
} from '@reown/appkit-common'

export type AuthProviderConfig = {
getProvider: () => W3mFrameProvider
Expand All @@ -31,24 +36,15 @@ export class AuthProvider extends ProviderEventEmitter implements Provider, Prov

private readonly getProvider: AuthProviderConfig['getProvider']
private readonly getActiveChain: AuthProviderConfig['getActiveChain']
private readonly getActiveNamespace: AuthProviderConfig['getActiveNamespace']
private readonly requestedChains: CaipNetwork[]
private readonly getSession: AuthProviderConfig['getSession']
private readonly setSession: AuthProviderConfig['setSession']

constructor({
getProvider,
getActiveChain,
getActiveNamespace,
getSession,
setSession,
chains
}: AuthProviderConfig) {
constructor({ getProvider, getActiveChain, getSession, setSession, chains }: AuthProviderConfig) {
super()

this.getProvider = getProvider
this.getActiveChain = getActiveChain
this.getActiveNamespace = getActiveNamespace
this.requestedChains = chains
this.getSession = getSession
this.setSession = setSession
Expand Down Expand Up @@ -213,7 +209,9 @@ export class AuthProvider extends ProviderEventEmitter implements Provider, Prov
}

private serializeTransaction(transaction: AnyTransaction) {
return base58.encode(transaction.serialize({ verifySignatures: false }))
const serializedTransaction = transaction.serialize({ verifySignatures: false })

return base58.encode(Buffer.from(serializedTransaction))
}

private bindEvents() {
Expand All @@ -231,10 +229,14 @@ export class AuthProvider extends ProviderEventEmitter implements Provider, Prov

this.getProvider().onIsConnected(response => {
this.setSession(response)
const activeNamespace = this.getActiveNamespace()

if (activeNamespace === 'solana') {
this.emit('connect', this.getPublicKey(true))
const storedCaipNetwork = SafeLocalStorage.getItem(SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK)
if (storedCaipNetwork) {
const parsedCaipNetwork = JSON.parse(storedCaipNetwork) as CaipNetwork

if (parsedCaipNetwork.chainNamespace === 'solana') {
this.emit('connect', this.getPublicKey(true))
}
}
})

Expand Down
19 changes: 18 additions & 1 deletion packages/adapters/wagmi/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,14 @@ export class WagmiAdapter implements ChainAdapter {
)
const chainId = Number(NetworkUtil.caipNetworkIdToNumber(caipNetwork?.id))

if (chainId && this.wagmiConfig) {
if (chainId && this.wagmiConfig && caipNetwork) {
const connectedConnector = SafeLocalStorage.getItem(
SafeLocalStorageKeys.CONNECTED_CONNECTOR
)
const isConnectedWithAuth = connectedConnector === 'AUTH'
if (isConnectedWithAuth) {
this.handleSwitchNetworkAuthConnector(caipNetwork)
}
await switchChain(this.wagmiConfig, { chainId })
}
},
Expand Down Expand Up @@ -787,6 +794,16 @@ export class WagmiAdapter implements ChainAdapter {
this.appKit?.setBalance(undefined, undefined, this.chainNamespace)
}

private async handleSwitchNetworkAuthConnector(caipNetwork: CaipNetwork) {
const connector = this.wagmiConfig.connectors.find(
c => c.id === ConstantsUtil.AUTH_CONNECTOR_ID
) as unknown as AdapterOptions<Config>['wagmiConfig']['connectors'][0]
const provider = (await connector?.getProvider()) as W3mFrameProvider
if (caipNetwork?.id) {
await provider.switchNetwork(caipNetwork?.id)
}
}

private async syncConnectedWalletInfo(connector: GetAccountReturnType['connector']) {
if (!connector) {
throw Error('syncConnectedWalletInfo - connector is undefined')
Expand Down
10 changes: 9 additions & 1 deletion packages/core/src/controllers/ChainController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ export const ChainController = {
if (!state.noAdapters) {
state.activeChain = adapterToActivate?.chainNamespace
PublicStateController.set({ activeChain: adapterToActivate?.chainNamespace })
this.setActiveCaipNetwork(adapterToActivate?.defaultNetwork)
this.setActiveCaipNetwork(
adapterToActivate?.defaultNetwork || adapterToActivate?.caipNetworks?.[0]
)

adapters.forEach((adapter: ChainsInitializerAdapter) => {
state.chains.set(adapter.chainNamespace, {
Expand Down Expand Up @@ -262,6 +264,12 @@ export const ChainController = {

if (caipNetwork.chainNamespace !== state.activeChain) {
this.setActiveChain(caipNetwork.chainNamespace, caipNetwork)
state.activeCaipNetwork = caipNetwork
SafeLocalStorage.setItem(
SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK,
JSON.stringify(caipNetwork)
)
SafeLocalStorage.setItem(SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID, caipNetwork.id)

return
}
Expand Down
13 changes: 5 additions & 8 deletions packages/core/src/controllers/ConnectorController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,18 +146,15 @@ export const ConnectorController = {
},

getAuthConnector(): AuthConnector | undefined {
const activeNamespace = ChainController.state.activeChain
const authConnector = state.connectors.find(c => c.id === 'w3mAuth')
const activeNamespace = ChainController.state.activeCaipNetwork?.chainNamespace

const authConnector = state.connectors.find(
c => c.id === 'w3mAuth' && c.chain === activeNamespace
)
if (!authConnector) {
return undefined
}

if (authConnector.type === 'MULTI_CHAIN' && authConnector?.connectors?.length) {
return authConnector.connectors.find(c => c.chain === activeNamespace) as
| AuthConnector
| undefined
}

return authConnector as AuthConnector
},

Expand Down
66 changes: 18 additions & 48 deletions packages/core/tests/controllers/ConnectorController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,21 @@ import {
import { ConstantsUtil, getW3mThemeVariables } from '@reown/appkit-common'

// -- Setup --------------------------------------------------------------------
const authProvider = {
const evmAuthProvider = {
syncDappData: (_args: { metadata: Metadata; sdkVersion: SdkVersion; projectId: string }) =>
Promise.resolve(),
syncTheme: (_args: { themeMode: ThemeMode; themeVariables: ThemeVariables }) => Promise.resolve()
}
} as const

const caipNetwork = {
id: 'eip155:1',
name: 'Ethereum',
chainNamespace: ConstantsUtil.CHAIN.EVM,
chainId: 1,
currency: 'ETH',
explorerUrl: 'https://etherscan.io',
rpcUrl: 'https://rpc.infura.com/v1/'
} as const

const walletConnectConnector = {
id: 'walletConnect',
Expand All @@ -33,17 +43,10 @@ const externalConnector = {
const evmAuthConnector = {
id: 'w3mAuth',
type: 'AUTH',
provider: authProvider,
provider: evmAuthProvider,
chain: ConstantsUtil.CHAIN.EVM,
name: 'Auth'
} as const
const solanaAuthConnector = {
id: 'w3mAuth',
type: 'AUTH',
provider: authProvider,
chain: ConstantsUtil.CHAIN.SOLANA,
name: 'Auth'
} as const

const announcedConnector = {
id: 'announced',
Expand All @@ -53,8 +56,8 @@ const announcedConnector = {
name: 'Announced'
} as const

const syncDappDataSpy = vi.spyOn(authProvider, 'syncDappData')
const syncThemeSpy = vi.spyOn(authProvider, 'syncTheme')
const syncDappDataSpy = vi.spyOn(evmAuthProvider, 'syncDappData')
const syncThemeSpy = vi.spyOn(evmAuthProvider, 'syncTheme')

const mockDappData = {
metadata: {
Expand Down Expand Up @@ -85,6 +88,7 @@ const zerionConnector = {
describe('ConnectorController', () => {
beforeAll(() => {
ChainController.state.activeChain = ConstantsUtil.CHAIN.EVM
ChainController.state.activeCaipNetwork = caipNetwork
})
it('should have valid default state', () => {
expect(ConnectorController.state.connectors).toEqual([])
Expand Down Expand Up @@ -152,12 +156,6 @@ describe('ConnectorController', () => {
expect(connector).toEqual(evmAuthConnector)
})

it('getAuthConnector() should return merged connector when already added on different network', () => {
ConnectorController.addConnector(solanaAuthConnector)
const connector = ConnectorController.getAuthConnector()
expect(connector).toEqual(evmAuthConnector)
})

Comment on lines -155 to -160
Copy link
Collaborator

Choose a reason for hiding this comment

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

why remove this? aren't the connectors being merged?

it('getAnnouncedConnectorRdns() should not throw when no announced connector is not set', () => {
expect(ConnectorController.getAnnouncedConnectorRdns()).toEqual([])
})
Expand All @@ -173,37 +171,9 @@ describe('ConnectorController', () => {
externalConnector,
metamaskConnector,
zerionConnector,
evmAuthConnector,
// Need to define inline to reference the spies
{
id: 'w3mAuth',
imageId: undefined,
imageUrl: undefined,
name: 'Auth',
type: 'MULTI_CHAIN',
chain: 'eip155',
connectors: [
{
chain: 'eip155',
id: 'w3mAuth',
name: 'Auth',
provider: {
syncDappData: syncDappDataSpy,
syncTheme: syncThemeSpy
},
type: 'AUTH'
},
{
chain: 'solana',
id: 'w3mAuth',
name: 'Auth',
provider: {
syncDappData: syncDappDataSpy,
syncTheme: syncThemeSpy
},
type: 'AUTH'
}
]
},

announcedConnector
])
})
Expand Down
Loading