diff --git a/src/web3-store.js b/src/web3-store.js index 94c5770..cb96449 100644 --- a/src/web3-store.js +++ b/src/web3-store.js @@ -41,28 +41,29 @@ 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)) + } else { + if (instance._provider && instance._provider.on) { + instance._provider.on('accountsChanged', () => setProvider(provider, true)) + instance._provider.on('chainChanged', () => setProvider(provider, true)) } - }) + } + update(() => ({ + provider, + providerType: 'String', + connected: true, + chainId, + accounts, + instance + })) } const setBrowserProvider = async () => { @@ -82,8 +83,8 @@ export const createStore = () => { } const close = async (provider) => { - if(provider && provider.close) { - await provider.close() + if(provider && provider.disconnect) { + await provider.disconnect() } update(() => ({ connected: false,