Skip to content

Commit

Permalink
refactor: clean up solana network syncing logic (#2867)
Browse files Browse the repository at this point in the history
Co-authored-by: tomiir <[email protected]>
  • Loading branch information
zoruka and tomiir authored Sep 19, 2024
1 parent a181a19 commit 48ad644
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 75 deletions.
38 changes: 38 additions & 0 deletions .changeset/sharp-wombats-fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
'@reown/appkit-adapter-ethers5': patch
'@reown/appkit-adapter-ethers': patch
'@reown/appkit-adapter-solana': patch
'@reown/appkit-adapter-wagmi': patch
'@reown/appkit': patch
'@reown/appkit-wallet': patch
'@reown/appkit-core': patch
'@apps/demo': patch
'@apps/gallery': patch
'@apps/laboratory': patch
'@examples/html-ethers': patch
'@examples/html-ethers5': patch
'@examples/html-wagmi': patch
'@examples/next-ethers': patch
'@examples/next-wagmi': patch
'@examples/react-ethers': patch
'@examples/react-ethers5': patch
'@examples/react-solana': patch
'@examples/react-wagmi': patch
'@examples/vue-ethers5': patch
'@examples/vue-solana': patch
'@examples/vue-wagmi': patch
'@reown/appkit-adapter-polkadot': patch
'@reown/appkit-utils': patch
'@reown/appkit-cdn': patch
'@reown/appkit-common': patch
'@reown/appkit-ethers': patch
'@reown/appkit-ethers5': patch
'@reown/appkit-polyfills': patch
'@reown/appkit-scaffold-ui': patch
'@reown/appkit-siwe': patch
'@reown/appkit-solana': patch
'@reown/appkit-ui': patch
'@reown/appkit-wagmi': patch
---

Refactors solana network and account syncing logic to clean up the code and fix missing project id for solana connection
87 changes: 30 additions & 57 deletions packages/adapters/solana/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ import { CoinbaseWalletProvider } from './providers/CoinbaseWalletProvider.js'

export interface AdapterOptions {
connectionSettings?: Commitment | ConnectionConfig
defaultCaipNetwork?: CaipNetwork
wallets?: BaseWalletAdapter[]
}

Expand All @@ -70,7 +69,7 @@ export class SolanaAdapter implements ChainAdapter {

public caipNetworks: CaipNetwork[] = []

public chainNamespace: ChainNamespace = CommonConstantsUtil.CHAIN.SOLANA
public readonly chainNamespace: ChainNamespace = CommonConstantsUtil.CHAIN.SOLANA

public networkControllerClient?: NetworkControllerClient

Expand All @@ -86,32 +85,27 @@ export class SolanaAdapter implements ChainAdapter {

public defaultCaipNetwork: CaipNetwork | undefined = undefined

public adapterType: AdapterType = 'solana'
public readonly adapterType: AdapterType = 'solana'

public constructor(options: AdapterOptions) {
const { wallets, connectionSettings = 'confirmed' } = options

this.wallets = wallets
this.connectionSettings = connectionSettings

ChainController.subscribeKey('activeCaipNetwork', val => {
const caipAddress = this.appKit?.getCaipAddress(this.chainNamespace)
const isSolanaAddress = caipAddress?.startsWith('solana:')
const isSolanaNetwork = val?.chainNamespace === this.chainNamespace

if (isSolanaAddress && isSolanaNetwork && caipAddress) {
this.syncAccount({ address: CoreHelperUtil.getPlainAddress(caipAddress), caipNetwork: val })
ChainController.subscribeKey('activeCaipNetwork', caipNetwork => {
if (caipNetwork?.chainNamespace === 'solana') {
this.syncAccount()
}
})

AccountController.subscribeKey(
'caipAddress',
val => {
const isSolanaAddress = val?.startsWith('solana:')
const caipNetwork = ChainController.state.activeCaipNetwork
const isSolanaNetwork = caipNetwork?.chainNamespace === this.chainNamespace
caipAddress => {
const isSolanaAddress = caipAddress?.startsWith('solana:')

if (isSolanaAddress && isSolanaNetwork) {
this.syncAccount({ address: CoreHelperUtil.getPlainAddress(val) })
if (isSolanaAddress) {
this.syncAccount()
}
},
this.chainNamespace
Expand All @@ -128,11 +122,10 @@ export class SolanaAdapter implements ChainAdapter {
this.appKit = appKit
this.options = options
this.caipNetworks = options.networks
const defaultCaipNetwork = SolHelpersUtil.getChainFromCaip(
this.defaultCaipNetwork = SolHelpersUtil.getChainFromCaip(
options.networks,
SafeLocalStorage.getItem(SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID)
)
this.defaultCaipNetwork = defaultCaipNetwork

if (!projectId) {
throw new Error('Solana:construct - projectId is undefined')
Expand Down Expand Up @@ -319,8 +312,7 @@ export class SolanaAdapter implements ChainAdapter {
this.syncRequestedNetworks(this.caipNetworks)

AssetController.subscribeNetworkImages(() => {
const address = this.appKit?.getAddress(this.chainNamespace) as string
this.syncNetwork({ address })
this.syncNetwork()
})

ChainController.subscribeKey('activeCaipNetwork', (newCaipNetwork: CaipNetwork | undefined) => {
Expand Down Expand Up @@ -365,37 +357,21 @@ export class SolanaAdapter implements ChainAdapter {
}

// -- Private -----------------------------------------------------------------
private async syncAccount({
address,
caipNetwork
}: {
address: string | undefined
caipNetwork?: CaipNetwork | undefined
}) {
const currentCaipNetwork = caipNetwork || this.appKit?.getCaipNetwork()
const solanaNetwork =
currentCaipNetwork?.chainNamespace === CommonConstantsUtil.CHAIN.SOLANA
? currentCaipNetwork
: this.appKit?.getCaipNetwork(this.chainNamespace)

if (!currentCaipNetwork && solanaNetwork) {
this.appKit?.setCaipNetwork(solanaNetwork)
}
private async syncAccount(address = this.appKit?.getAddress(this.chainNamespace)) {
const caipNetwork = this.appKit?.getCaipNetwork(this.chainNamespace)

if (address) {
if (solanaNetwork) {
SolStoreUtil.setConnection(new Connection(solanaNetwork.rpcUrl, this.connectionSettings))
this.appKit?.setAllAccounts([{ address, type: 'eoa' }], this.chainNamespace)
}
await this.syncNetwork({ address })
if (address && caipNetwork) {
SolStoreUtil.setConnection(new Connection(caipNetwork.rpcUrl, this.connectionSettings))
this.appKit?.setAllAccounts([{ address, type: 'eoa' }], this.chainNamespace)
await this.syncNetwork(address)
} else {
this.appKit?.resetWcConnection()
this.appKit?.resetNetwork()
this.appKit?.resetAccount(this.chainNamespace)
}
}

private async syncBalance(address: string) {
private async syncBalance(address = this.appKit?.getAddress(this.chainNamespace)) {
if (!address) {
return
}
Expand Down Expand Up @@ -451,32 +427,29 @@ export class SolanaAdapter implements ChainAdapter {
ProviderUtil.setProvider(this.chainNamespace, this.authProvider)
ProviderUtil.setProviderId(this.chainNamespace, 'walletConnect')
this.appKit?.setCaipAddress(caipAddress, this.chainNamespace)
this.syncAccount({ address: user.address })
this.syncAccount(user.address)
}
} else {
this.appKit?.setCaipNetwork(caipNetwork)

const address = this.appKit?.getAddress(this.chainNamespace) as string
await this.syncAccount({ address })
await this.syncAccount(address)
}
}

private async syncNetwork({ address }: { address: string | undefined }) {
if (!address) {
return
}
private async syncNetwork(address = this.appKit?.getAddress(this.chainNamespace)) {
const caipNetwork = this.appKit?.getCaipNetwork(this.chainNamespace)
const connection = SolStoreUtil.state.connection

if (caipNetwork && connection) {
if (caipNetwork.explorerUrl) {
const url = `${caipNetwork.explorerUrl}/account/${address}`
this.appKit?.setAddressExplorerUrl(url, this.chainNamespace)
} else {
this.appKit?.setAddressExplorerUrl(undefined, this.chainNamespace)
}
await this.syncBalance(address)
if (!address || !caipNetwork || !connection) {
return
}

this.appKit?.setAddressExplorerUrl(
caipNetwork.explorerUrl ? `${caipNetwork.explorerUrl}/account/${address}` : undefined,
this.chainNamespace
)
await this.syncBalance(address)
}

private async setProvider(provider: Provider) {
Expand Down
4 changes: 2 additions & 2 deletions packages/adapters/solana/src/tests/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ describe('SolanaAdapter', () => {
vi.spyOn(mockAppKit, 'getAddress').mockReturnValue(mockAddress)
vi.spyOn(client as any, 'syncBalance')

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

expect(mockAppKit.setAddressExplorerUrl).toHaveBeenCalledWith(
`${solana.explorerUrl}/account/${mockAddress}`,
Expand All @@ -122,7 +122,7 @@ describe('SolanaAdapter', () => {
vi.spyOn(mockAppKit, 'getIsConnectedState').mockReturnValue(true)
vi.spyOn(client as any, 'syncBalance').mockResolvedValue(undefined)

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

expect(SolStoreUtil.setConnection).toHaveBeenCalled()
expect(client['syncBalance']).toHaveBeenCalledWith(mockAddress)
Expand Down
24 changes: 8 additions & 16 deletions packages/appkit/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,12 @@ export class AppKit {
]
}

options.networks = this.prepareCaipNetworks(
options.networks,
options.chainImages,
options.projectId
)

this.initializeUniversalAdapter(options)
this.initializeAdapters(options)

Expand Down Expand Up @@ -493,15 +499,7 @@ export class AppKit {
}

private initializeUniversalAdapter(options: AppKitOptions) {
const caipNetworks = this.extendCaipNetworksWithImages(
options.networks,
options.chainImages,
options.projectId
)
this.universalAdapter = new UniversalAdapterClient({
...options,
networks: caipNetworks
})
this.universalAdapter = new UniversalAdapterClient(options)

ChainController.initializeUniversalAdapter(this.universalAdapter, options.adapters || [])

Expand All @@ -513,12 +511,6 @@ export class AppKit {
private initializeAdapters(options: AppKitOptions) {
ChainController.initialize(options.adapters || [])
options.adapters?.forEach(adapter => {
const caipNetworks = this.extendCaipNetworksWithImages(
options.networks,
options.chainImages,
options.projectId
)
options.networks = caipNetworks
// @ts-expect-error will introduce construct later
adapter.construct?.(this, options)

Expand All @@ -545,7 +537,7 @@ export class AppKit {
return this.initPromise
}

private extendCaipNetworksWithImages(
private prepareCaipNetworks(
caipNetworks: CaipNetwork[],
caipNetworkImages: Record<number | string, string> | undefined,
projectId: string
Expand Down

0 comments on commit 48ad644

Please sign in to comment.