Skip to content

Commit

Permalink
small changes
Browse files Browse the repository at this point in the history
  • Loading branch information
ricardocr987 committed Mar 21, 2024
1 parent 9c5d8c8 commit 7d18adc
Show file tree
Hide file tree
Showing 2 changed files with 151 additions and 146 deletions.
40 changes: 18 additions & 22 deletions src/hooks/common/useConnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,7 @@ export function useConnect(): UseConnectReturn {
if (providerType === ProviderEnum.WalletConnect) {
provider = await walletConnect.connect(chain)
}

return await updateState(chain, provider);
return await updateState(chain, provider)
} catch (err) {
const e = err as Error
onNoti(e.message, 'error') // we assume because the user denied the connection
Expand All @@ -114,9 +113,10 @@ export function useConnect(): UseConnectReturn {
if (currentProvider === ProviderEnum.WalletConnect) {
await walletConnect.disconnect()
}

setCurrentProvider(ProviderEnum.Disconnected)
dispatch({ type: AccountActionType.ACCOUNT_DISCONNECT, payload: null })
}, [dispatch, setCurrentProvider])
}, [dispatch, currentProvider, walletConnect.disconnect])

const switchNetwork = useCallback(
async (chain?: Chain, providerType: ProviderEnum = ProviderEnum.Metamask) => {
Expand All @@ -128,19 +128,13 @@ export function useConnect(): UseConnectReturn {
provider = await walletConnect.connect(chain)
}

return await updateState(chain, provider);
return await updateState(chain, provider)
} catch (err) {
const e = err as Error
onNoti(e.message, 'error')
}
},
[
updateState,
currentProvider,
setSelectedNetwork,
setCurrentProvider,
onNoti,
],
[updateState, onNoti],
)

const { account } = state
Expand All @@ -154,37 +148,39 @@ export function useConnect(): UseConnectReturn {
switch (currentProvider) {
case ProviderEnum.Metamask:
provider = metamaskProvider()
break;
break

case ProviderEnum.WalletConnect:
provider = await walletConnect.createClient();
provider = await walletConnect.connect(selectedNetwork)
if (!provider || !provider.session) return
break;
break

default:
console.log("No provider selected or provider not supported.");
console.log("No provider selected or provider not supported.")
}

await updateState(selectedNetwork, provider);
}, [currentProvider, selectedNetwork, metamaskProvider, walletConnect]);
await updateState(selectedNetwork, provider)
}, [currentProvider, selectedNetwork, metamaskProvider, walletConnect.connect])


useEffect(() => {
autoLogin()

// fix this clean-up function
return () => {
switch (currentProvider) {
case ProviderEnum.Metamask:
;(window.ethereum as any)?.removeListener('accountsChanged', () => {
disconnect()
})
break
case ProviderEnum.WalletConnect:
/*case ProviderEnum.WalletConnect:
walletConnect.removeListeners()
break
default:
console.log("No provider selected or provider not supported.");
}
console.log("No provider selected or provider not supported.")*/
}
}
}, [currentProvider])
}, [])

return {
connect,
Expand Down
257 changes: 133 additions & 124 deletions src/hooks/common/useWalletConnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,142 +9,151 @@ import { Chain } from 'aleph-sdk-ts/dist/messages/types'
import Provider from '@walletconnect/universal-provider'

export type WalletConnectReturn = {
createClient: () => Promise<UniversalProvider | undefined>
createClient: () => Promise<UniversalProvider>
connect: (chain: Chain) => Promise<UniversalProvider>
switchNetwork: (chain: Chain) => Promise<void>
disconnect: () => Promise<void>
removeListeners: () => void
}

export function useWalletConnect(): WalletConnectReturn {
const [universalProvider, setUniversalProvider] = useState<UniversalProvider>()
const [web3Modal, setWeb3Modal] = useState<WalletConnectModal>()

const createClient = useCallback(async () => {
try {
if (!process.env.NEXT_PUBLIC_WALLET_CONNECT_ID) return
const provider = await UniversalProvider.init({
projectId: process.env.NEXT_PUBLIC_WALLET_CONNECT_ID!,
metadata: {
name: 'Aleph.im',
description: 'Aleph.im: Web3 cloud solution',
url: 'https://aleph.im/',
icons: [],
},
})

const web3Modal = new WalletConnectModal({
projectId: process.env.NEXT_PUBLIC_WALLET_CONNECT_ID!,
//mobileWallets: []
})

await subscribeToEvents(provider)
setUniversalProvider(provider)
setWeb3Modal(web3Modal)
const [universalProvider, setUniversalProvider] = useState<UniversalProvider>()
const [web3Modal, setWeb3Modal] = useState<WalletConnectModal>()

return provider
} catch (err) {
throw err
}
}, [])

const switchNetwork = useCallback(
async (chain: Chain) => {
if (!universalProvider) throw new Error('ethereumProvider is not initialized')
if (!universalProvider.session) throw new Error('session is not initialized')

await universalProvider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: `0x${chainToId(chain).toString(16)}` }],
})
},
[universalProvider],
)

const disconnect = useCallback(async () => {
const disconnect = useCallback(async () => {
const provider = universalProvider || await createClient()

await provider.disconnect()
}, [universalProvider])

const displayUriListener = useCallback(
async (uri: string) => {
web3Modal?.openModal({ uri })
},
[web3Modal],
)

const sessionDeleteListener = useCallback(async () => {
await disconnect()
}, [disconnect])

/*const sessionEventListener = useCallback(async (event: any) => {
console.log("EVENT", "session_update", event)
if (!ethereumProvider?.session) return
if (event.params?.event?.name === 'chainChanged') {
await onSessionConnect(idToChain(event.params?.event?.data), ethereumProvider)
}
}, [onSessionConnect, ethereumProvider])*/

const subscribeToEvents = useCallback(
(provider: Provider) => {
provider.on('display_uri', displayUriListener)
//provider.on("session_update", sessionEventListener)
provider.on('session_delete', sessionDeleteListener)
},
[displayUriListener, sessionDeleteListener],
)

const removeListeners = useCallback(() => {
if (!universalProvider) throw new Error('wallet connect is not initialized')

universalProvider.off('display_uri', displayUriListener)
//universalProvider.off('session_update', sessionEventListener)
universalProvider.off('session_delete', sessionDeleteListener)
},
[displayUriListener, sessionDeleteListener])

const createModal = useCallback(() => {
try {
const web3Modal = new WalletConnectModal({
projectId: process.env.NEXT_PUBLIC_WALLET_CONNECT_ID!,
//mobileWallets: []
})

setWeb3Modal(web3Modal)
} catch (err) {
throw err
}
}, [setWeb3Modal])

const createClient = useCallback(async () => {
try {
const provider = await UniversalProvider.init({
projectId: process.env.NEXT_PUBLIC_WALLET_CONNECT_ID!,
metadata: {
name: 'Aleph.im',
description: 'Aleph.im: Web3 cloud solution',
url: 'https://aleph.im/',
icons: [],
},
})

createModal()
subscribeToEvents(provider)
setUniversalProvider(provider)

return provider
} catch (err) {
throw err
}
}, [createModal, subscribeToEvents, setUniversalProvider])

const switchNetwork = useCallback(
async (chain: Chain) => {
if (!universalProvider) throw new Error('ethereumProvider is not initialized')
if (!universalProvider.session) throw new Error('session is not initialized')

await universalProvider.disconnect()
}, [universalProvider])

const connect = useCallback(
async (chain: Chain): Promise<UniversalProvider> => {
const provider = await createClient()
if (!provider) throw new Error('wallet connect is not initialized')

const methods = [
'eth_sendTransaction',
'eth_signTransaction',
'eth_sign',
'personal_sign',
'eth_signTypedData',
'wallet_addEthereumChain',
'wallet_switchEthereumChain',
]
const events = ['chainChanged', 'accountsChanged']
await provider.connect({
namespaces: {
eip155: {
methods,
chains: [`eip155:${chainToId(chain)}`],
events,
},
},
})

web3Modal?.closeModal()
await universalProvider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: `0x${chainToId(chain).toString(16)}` }],
})
},
[universalProvider],
)

const connect = useCallback(
async (chain: Chain): Promise<UniversalProvider> => {
const provider = await createClient()

// auto-login
if (provider.session && provider.session.expiry > Math.floor(Date.now() / 1000)) {
return provider
},
[universalProvider, createClient]
)

const displayUriListener = useCallback(
async (uri: string) => {
web3Modal?.openModal({ uri })
},
[web3Modal],
)

const sessionDeleteListener = useCallback(async () => {
await disconnect()
}, [disconnect])

/*const sessionEventListener = useCallback(async (event: any) => {
console.log("EVENT", "session_update", event)
if (!ethereumProvider?.session) return
if (event.params?.event?.name === 'chainChanged') {
await onSessionConnect(idToChain(event.params?.event?.data), ethereumProvider)
}
}, [onSessionConnect, ethereumProvider])*/

const subscribeToEvents = useCallback(
async (provider: Provider) => {
if (typeof provider === 'undefined') {
throw new Error('WalletConnect is not initialized')
}
provider.on('display_uri', displayUriListener)
//provider.on("session_update", sessionEventListener)
provider.on('session_delete', sessionDeleteListener)
},
[displayUriListener, sessionDeleteListener],
)

const removeListeners = useCallback(() => {
if (!universalProvider) throw new Error('wallet connect is not initialized')

universalProvider.off('display_uri', displayUriListener)
universalProvider.off('session_update', displayUriListener)
universalProvider.off('session_delete', sessionDeleteListener)

const methods = [
'eth_sendTransaction',
'eth_signTransaction',
'eth_sign',
'personal_sign',
'eth_signTypedData',
'wallet_addEthereumChain',
'wallet_switchEthereumChain',
]
const events = ['chainChanged', 'accountsChanged']

await provider.connect({
namespaces: {
eip155: {
methods,
chains: [`eip155:${chainToId(chain)}`],
events,
},
},
})

web3Modal?.closeModal()

return provider
},
[displayUriListener, sessionDeleteListener])

return {
createClient,
connect,
switchNetwork,
disconnect,
removeListeners
}
[universalProvider, web3Modal, ]
)

return {
createClient,
connect,
switchNetwork,
disconnect,
removeListeners
}
}

0 comments on commit 7d18adc

Please sign in to comment.