Skip to content

Commit

Permalink
[hooks] Add cacheProvider prop to <Provider /> (#340)
Browse files Browse the repository at this point in the history
Co-authored-by: Dhaiwat Pandya <dhaiwatpandya@gmail.com>
  • Loading branch information
j-5-s and Dhaiwat10 authored May 3, 2022
1 parent e51c657 commit 16ac4cc
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 14 deletions.
5 changes: 5 additions & 0 deletions .changeset/strange-carrots-wonder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@web3-ui/hooks': minor
---

[hooks] `<Provider />` now exposes a `cacheProvider` prop to allow persistence with Web3Modal.
42 changes: 29 additions & 13 deletions packages/hooks/src/Provider.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useEffect, useRef } from 'react';
import { JsonRpcSigner } from '@ethersproject/providers';
import WalletConnectProvider from '@walletconnect/web3-provider';
import { ethers } from 'ethers';
Expand Down Expand Up @@ -53,6 +54,11 @@ export interface ProviderProps {
* @type string
*/
rpcUrl?: string;
/**
* @dev To persist the cacheProvider functionality from web3modal
* @type boolean
*/
cacheProvider?: boolean;
}

/**
Expand All @@ -61,15 +67,17 @@ export interface ProviderProps {
* @param network The network you want to connect to.
* @param infuraId Your Infura project ID. This is required if you want to support WalletConnect.
* @param extraWalletProviders An array of extra Wallet Providers you want to support.
* @param cacheProvider boolean flag to persist provider
*/
export const Provider: React.FC<ProviderProps> = ({
children,
network,
infuraId,
extraWalletProviders = [],
rpcUrl = '',
cacheProvider = false,
}) => {
const [web3Modal, setWeb3Modal] = useState<Web3Modal>();
const web3Modal = useRef<Web3Modal>();
const [signer, setSigner] = useState<null | JsonRpcSigner>();
const [error, setError] = useState<string>();
const [provider, setProvider] =
Expand Down Expand Up @@ -97,15 +105,9 @@ export const Provider: React.FC<ProviderProps> = ({
};

const connectWallet = useCallback(async () => {
if (!web3Modal.current) return;
try {
const web3Modal = new Web3Modal({
providerOptions: Object.assign(
defaulProviderOptions,
...extraWalletProviders
),
});
setWeb3Modal(web3Modal);
const connection = await web3Modal.connect();
const connection = await web3Modal.current.connect();
const provider = new ethers.providers.Web3Provider(connection);
setProvider(provider);
const chainId = await provider
Expand Down Expand Up @@ -133,7 +135,7 @@ export const Provider: React.FC<ProviderProps> = ({
connection.on('accountsChanged', async (accounts: string[]) => {
if (accounts.length === 0) {
// The user has disconnected their account from Metamask
web3Modal?.clearCachedProvider();
web3Modal.current?.clearCachedProvider();
disconnectWallet();
return;
}
Expand All @@ -151,16 +153,16 @@ export const Provider: React.FC<ProviderProps> = ({
});

connection.on('disconnect', async () => {
web3Modal?.clearCachedProvider();
web3Modal.current?.clearCachedProvider();
disconnectWallet();
});
} catch (err: any) {
setError(err?.message || err.toString());
setError(err?.message || err?.toString() || 'An error occurred');
}
}, [network, correctNetwork, infuraId, extraWalletProviders]);

const disconnectWallet = useCallback(() => {
web3Modal?.clearCachedProvider();
web3Modal.current?.clearCachedProvider();
setSigner(null);
setUserAddress(null);
setConnected(false);
Expand Down Expand Up @@ -195,6 +197,20 @@ export const Provider: React.FC<ProviderProps> = ({
]
);

useEffect(() => {
web3Modal.current = new Web3Modal({
cacheProvider,
providerOptions: Object.assign(
defaulProviderOptions,
...extraWalletProviders
),
});

if (web3Modal.current.cachedProvider) {
connectWallet();
}
}, []);

return (
<Web3Context.Provider value={{ ...value }}>{children}</Web3Context.Provider>
);
Expand Down
2 changes: 1 addition & 1 deletion packages/hooks/src/stories/UseContract.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ const Default = () => {
};

storiesOf('Hooks/useWriteContract', module).add('Default', () => (
<Provider network={NETWORKS.rinkeby}>
<Provider network={NETWORKS.rinkeby} cacheProvider>
<Default />
</Provider>
));
Expand Down

2 comments on commit 16ac4cc

@vercel
Copy link

@vercel vercel bot commented on 16ac4cc May 3, 2022

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

web3ui – ./

web3-ui.vercel.app
web3ui-git-main-developdao.vercel.app
web3ui-developdao.vercel.app

@vercel
Copy link

@vercel vercel bot commented on 16ac4cc May 3, 2022

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

web3-ui-docs – ./

web3-ui-docs-git-main-developdao.vercel.app
web3-ui-docs.vercel.app
web3-ui-docs-developdao.vercel.app

Please sign in to comment.