From cd54e39b3b4cb316de7cb1c74bafce0178223a6b Mon Sep 17 00:00:00 2001 From: byterose <77129089+byterose@users.noreply.github.com> Date: Mon, 26 Jul 2021 16:37:00 +0200 Subject: [PATCH] Unsubscribe all events __networkChanged__ will emit the network ID as a decimal string __chainChanged__ will emit the chain ID as a hexadecimal string I commented out the __chainChanged__ listener since only one chain / network listener is needed. --- src/web3-store.js | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/src/web3-store.js b/src/web3-store.js index 94c5770..02047ef 100644 --- a/src/web3-store.js +++ b/src/web3-store.js @@ -41,28 +41,31 @@ export const createStore = () => { if (getWindowEthereum()) getWindowEthereum().autoRefreshOnNetworkChange = false } - const setProvider = async provider => { + const setProvider = async (provider, callback?) => { init() const instance = new Web3(provider) const chainId = await instance.eth.getChainId() // no account with ganache const accounts = /127/.test(provider) ? [] : await instance.eth.getAccounts() - if (instance._provider && instance._provider.on) { - instance._provider.on('accountsChanged', () => setProvider(provider)) - instance._provider.on('chainChanged', () => setProvider(provider)) - instance._provider.on('networkChanged', () => setProvider(provider)) - } - update(previous => { - // TODO if (previous.instance) unsubcribe all events - return { - provider, - providerType: 'String', - connected: true, - chainId, - accounts, - instance, + if (callback) { + instance._provider.removeListener('accountsChanged', () => setProvider(provider, true)) + // instance._provider.removeListener('chainChanged', () => setProvider(provider, true)) + instance._provider.removeListener('networkChanged', () => setProvider(provider, true)) + } else { + if (instance._provider && instance._provider.on) { + instance._provider.on('accountsChanged', () => setProvider(provider, true)) + // instance._provider.on('chainChanged', () => setProvider(provider, true)) + instance._provider.on('networkChanged', () => setProvider(provider, true)) } - }) + } + update(() => ({ + provider, + providerType: 'String', + connected: true, + chainId, + accounts, + instance + })) } const setBrowserProvider = async () => {