Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added disconnect button #17

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 37 additions & 13 deletions src/components/Connect/Connect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,16 @@ export const Connect: React.FC<{
}
}, []);

const refreshProvider = (eth: Eip1193Provider) => {
const p = new BrowserProvider(eth);
setProvider(p);
return p;
};
const initializeProvider = useCallback(() => {
const eth = window.ethereum;
if (eth) {
const p = new BrowserProvider(eth);
setProvider(p);
return p;
}
setError('No wallet has been found');
return null;
}, []);

useEffect(() => {
const eth = window.ethereum;
Expand All @@ -56,25 +61,33 @@ export const Connect: React.FC<{
return;
}

const p = refreshProvider(eth);
const p = initializeProvider();

p.send('eth_accounts', [])
p
?.send('eth_accounts', [])
.then(async (accounts: string[]) => {
refreshAccounts(accounts);
await refreshNetwork();
})
.catch(() => {
// Do nothing
});

eth.on('accountsChanged', refreshAccounts);
eth.on('chainChanged', refreshNetwork);
}, []);

return () => {
eth.removeListener('accountsChanged', refreshAccounts);
eth.removeListener('chainChanged', refreshNetwork);
};
}, [initializeProvider, refreshNetwork]);

const connect = async () => {
if (!provider) {
const p = provider || initializeProvider(); // Reinitialize provider if null
if (!p) {
return;
}
const accounts: string[] = await provider.send('eth_requestAccounts', []);
const accounts: string[] = await p.send('eth_requestAccounts', []);

if (accounts.length > 0) {
setAccount(accounts[0]);
Expand All @@ -85,6 +98,13 @@ export const Connect: React.FC<{
}
};

const disconnect = () => {
setAccount('');
setConnected(false);
setValidNetwork(false);
setProvider(null); // Reset provider
};

const switchNetwork = useCallback(async () => {
try {
await window.ethereum.request({
Expand Down Expand Up @@ -125,9 +145,13 @@ export const Connect: React.FC<{

const connectInfos = (
<div className="Connect__info">
{!connected && <button onClick={connect}>Connect your wallet</button>}
{connected && (
<div className="Connect__account">Connected with {account}</div>
{!connected ? (
<button onClick={connect}>Connect your wallet</button>
) : (
<div className="Connect__account">
<span>Connected with {account}</span>
<button onClick={disconnect}>Disconnect</button>
</div>
)}
</div>
);
Expand Down