Untitled
unknown
typescript
a year ago
2.3 kB
5
Indexable
Never
import { useSDK } from '@metamask/sdk-react'; import { useState, useEffect } from 'react'; import Web3 from "web3"; import "./index.css"; export const App = () => { const [account, setAccount] = useState<string>(""); const [balance, setBalance] = useState<number | string | undefined>(); const [loginStatus, setLoginStatus] = useState<boolean>(false); const { sdk, connected, connecting, chainId } = useSDK(); const [accTest, setAccTest] = useState(""); const provider: string = "http://127.0.0.1:8545"; useEffect(() => { const test = async () => { const accountsTest: any = await window.ethereum?.request({ method: 'eth_requestAccounts' }); setAccTest(accountsTest); }; test(); }, []) useEffect(() => { if (provider) { const web3 = new Web3("http://127.0.0.1:8545"); web3.eth.getAccounts().then((accounts: string[]) => { if (accounts.length > 0) { console.log(accounts); setAccount(accounts[0]); setLoginStatus(true); } }); } }, [provider]); console.log(accTest); const connect = async () => { try { await sdk?.connect(); } catch (err) { console.warn("failed to connect..", err); } }; const disconnect = async () => { try { sdk?.disconnect(); setAccount(""); setLoginStatus(false); } catch (err) { console.warn("failed disconnect", err); } }; return ( <div className="App"> {!loginStatus ? ( <button onClick={connect}>Connect</button> ) : null} {connected && ( <div> <> {chainId && `Connected chain: ${chainId}`} <p></p> {account && `Connected account: ${account}`} </> </div> )} {loginStatus ? ( <button onClick={disconnect}> Disconnect </button> ) : null} </div> ); };
Leave a Comment