From 68a5335b02539dce47fa20dfd94019806501a03f Mon Sep 17 00:00:00 2001 From: Ben Kremer Date: Mon, 14 Feb 2022 11:49:15 +0100 Subject: [PATCH] wip --- dapps/react-dapp-v2-with-ethers/src/App.tsx | 32 ++-- .../src/components/Blockchain.tsx | 3 - .../src/constants/default.ts | 3 - .../src/contexts/ClientContext.tsx | 177 +++++++++--------- .../src/contexts/Web3ProviderContext.tsx | 113 ----------- 5 files changed, 99 insertions(+), 229 deletions(-) delete mode 100644 dapps/react-dapp-v2-with-ethers/src/contexts/Web3ProviderContext.tsx diff --git a/dapps/react-dapp-v2-with-ethers/src/App.tsx b/dapps/react-dapp-v2-with-ethers/src/App.tsx index c679758..316cb8b 100644 --- a/dapps/react-dapp-v2-with-ethers/src/App.tsx +++ b/dapps/react-dapp-v2-with-ethers/src/App.tsx @@ -58,12 +58,12 @@ export default function App() { client, session, disconnect, - chains, + chain, + setChain, accounts, balances, isFetchingBalances, isInitializing, - setChains, onEnable, web3Provider, } = useWalletConnectClient(); @@ -160,14 +160,6 @@ export default function App() { setLocaleStorageTestnetFlag(nextIsTestnetState); }; - const handleChainSelectionClick = (chainId: string) => { - if (chains.includes(chainId)) { - setChains(chains.filter(chain => chain !== chainId)); - } else { - setChains([...chains, chainId]); - } - }; - // Renders the appropriate model for the given request that is currently in-flight. const renderModal = () => { switch (modal) { @@ -175,7 +167,8 @@ export default function App() { if (typeof client === "undefined") { throw new Error("WalletConnect is not initialized"); } - return ; + // return ; + return null; case "request": return ; case "ping": @@ -194,7 +187,7 @@ export default function App() { {`Using v${version || "2.0.0-beta"}`} -
Select chains:
+
Select an Ethereum chain:

Testnets Only?

@@ -204,13 +197,13 @@ export default function App() { key={chainId} chainId={chainId} chainData={chainData} - onClick={handleChainSelectionClick} - active={chains.includes(chainId)} + onClick={onEnable} + // active={chains.includes(chainId)} /> ))} - + {/* {"Connect"} - + */}
) : ( @@ -218,9 +211,6 @@ export default function App() {

Accounts

{accounts.map(account => { - // const [namespace, reference, address] = account.split(":"); - // const chainId = `${namespace}:${reference}`; - const chainId = "eip155:42"; return ( ); })} diff --git a/dapps/react-dapp-v2-with-ethers/src/components/Blockchain.tsx b/dapps/react-dapp-v2-with-ethers/src/components/Blockchain.tsx index 50a6230..23545c9 100644 --- a/dapps/react-dapp-v2-with-ethers/src/components/Blockchain.tsx +++ b/dapps/react-dapp-v2-with-ethers/src/components/Blockchain.tsx @@ -16,7 +16,6 @@ import { ChainNamespaces, } from "../helpers"; import { fonts } from "../styles"; -import { useWalletConnectClient } from "../contexts/ClientContext"; interface AccountStyleProps { rgb: string; @@ -123,8 +122,6 @@ const Blockchain: FC> = ( const chain = getBlockchainDisplayData(chainId, chainData); if (typeof chain === "undefined") { - console.warn("CHAIN UNDEFINED"); - return null; } const name = chain.meta.name || chain.data.name; diff --git a/dapps/react-dapp-v2-with-ethers/src/constants/default.ts b/dapps/react-dapp-v2-with-ethers/src/constants/default.ts index 18ff4f8..078c280 100644 --- a/dapps/react-dapp-v2-with-ethers/src/constants/default.ts +++ b/dapps/react-dapp-v2-with-ethers/src/constants/default.ts @@ -6,7 +6,6 @@ export const DEFAULT_MAIN_CHAINS = [ "eip155:137", "eip155:42161", "eip155:42220", - "cosmos:cosmoshub-4", ]; export const DEFAULT_TEST_CHAINS = [ @@ -26,8 +25,6 @@ export const DEFAULT_RELAY_URL = process.env.REACT_APP_RELAY_URL; export const DEFAULT_EIP155_METHODS = ["eth_sendTransaction", "personal_sign", "eth_signTypedData"]; -export const DEFAULT_COSMOS_METHODS = ["cosmos_signDirect", "cosmos_signAmino"]; - export const DEFAULT_LOGGER = "debug"; export const DEFAULT_APP_METADATA = { diff --git a/dapps/react-dapp-v2-with-ethers/src/contexts/ClientContext.tsx b/dapps/react-dapp-v2-with-ethers/src/contexts/ClientContext.tsx index 3cde166..046f9b5 100644 --- a/dapps/react-dapp-v2-with-ethers/src/contexts/ClientContext.tsx +++ b/dapps/react-dapp-v2-with-ethers/src/contexts/ClientContext.tsx @@ -12,7 +12,6 @@ import { } from "react"; import { DEFAULT_APP_METADATA, - DEFAULT_COSMOS_METHODS, DEFAULT_EIP155_METHODS, DEFAULT_LOGGER, DEFAULT_PROJECT_ID, @@ -30,13 +29,13 @@ interface IContext { session: SessionTypes.Created | undefined; disconnect: () => Promise; isInitializing: boolean; - chains: string[]; + chain: string; pairings: string[]; accounts: string[]; balances: { symbol: string; balance: string }[]; isFetchingBalances: boolean; - setChains: any; - onEnable: () => Promise; + setChain: (chainId: string) => void; + onEnable: (chainId: string) => Promise; web3Provider?: providers.Web3Provider; } @@ -61,43 +60,14 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac const [balances, setBalances] = useState<{ symbol: string; balance: string }[]>([]); const [accounts, setAccounts] = useState([]); - const [chains, setChains] = useState([]); + const [chain, setChain] = useState(""); const resetApp = () => { setPairings([]); setSession(undefined); setBalances([]); setAccounts([]); - setChains([]); - }; - - const getSupportedNamespaces = useCallback(() => { - const supportedNamespaces: string[] = []; - chains.forEach(chainId => { - const [namespace] = chainId.split(":"); - if (!supportedNamespaces.includes(namespace)) { - supportedNamespaces.push(namespace); - } - }); - - return supportedNamespaces; - }, [chains]); - - const getSupportedMethods = (namespaces: string[]) => { - const supportedMethods: string[] = namespaces - .map(namespace => { - switch (namespace) { - case "eip155": - return DEFAULT_EIP155_METHODS; - case "cosmos": - return DEFAULT_COSMOS_METHODS; - default: - throw new Error(`No default methods for namespace: ${namespace}`); - } - }) - .flat(); - - return supportedMethods; + setChain(""); }; const disconnect = useCallback(async () => { @@ -133,7 +103,6 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac }); _client.on(CLIENT_EVENTS.pairing.created, async () => { - debugger; setPairings(_client.pairing.topics); }); @@ -173,6 +142,7 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac setClient(_client); await _subscribeToEvents(_client); + // TODO: // await _checkPersistedState(_client); } catch (err) { throw err; @@ -187,13 +157,64 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac } }, [client, createClient]); - useEffect(() => { - const init = async () => { - if (!client) return; + // useEffect(() => { + // const init = async () => { + // if (!client) return; + + // // Create WalletConnect Provider + // const ethereumProvider = new EthereumProvider({ + // chainId: 42, + // rpc: { + // infuraId: "5dc0df7abe4645dfb06a9a8c39ede422", + // }, + // // FIXME: `signer-connection` sub-dep is already specifying beta.23 -> typings mismatch. + // // @ts-ignore + // client, + // }); + // const web3Provider = new providers.Web3Provider(ethereumProvider); + + // setEthereumProvider(ethereumProvider); + // setWeb3Provider(web3Provider); + + // // Enable session (triggers QR Code modal if we bound the listener on `client` for it). + // // const accounts = await ethereumProvider.enable(); + // // console.log("accounts:", accounts); + + // // const provider = new providers.Web3Provider(ethereumProvider); + + // // console.log(provider); + // // console.log(await provider.listAccounts()); + // // console.log(await provider.getNetwork()); + // // console.log(provider.getSigner()); + // // console.log(await provider.getBalance(accounts[0])); + + // // const TEST_ETH_TRANSFER = { + // // from: accounts[0], + // // to: accounts[0], + // // value: utils.parseEther("1").toHexString(), + // // data: "0x", + // // }; + + // // const signer = provider.getSigner(); + // // const transferTx = await signer.sendTransaction(TEST_ETH_TRANSFER); + // }; + + // init(); + // }, [client]); + + const onEnable = useCallback( + async (caipChainId: string) => { + if (!client) { + throw new ReferenceError("WalletConnect Client is not initialized."); + } + + const chainId = caipChainId.split(":").pop(); + + console.log("Enabling EthereumProvider for chainId: ", chainId); // Create WalletConnect Provider const ethereumProvider = new EthereumProvider({ - chainId: 42, + chainId: Number(chainId), rpc: { infuraId: "5dc0df7abe4645dfb06a9a8c39ede422", }, @@ -203,58 +224,36 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac }); const web3Provider = new providers.Web3Provider(ethereumProvider); + console.log(ethereumProvider); + setEthereumProvider(ethereumProvider); setWeb3Provider(web3Provider); - // Enable session (triggers QR Code modal if we bound the listener on `client` for it). - // const accounts = await ethereumProvider.enable(); - // console.log("accounts:", accounts); + const accounts = await ethereumProvider.enable(); + setAccounts(accounts); - // const provider = new providers.Web3Provider(ethereumProvider); + setChain(caipChainId); - // console.log(provider); - // console.log(await provider.listAccounts()); - // console.log(await provider.getNetwork()); - // console.log(provider.getSigner()); - // console.log(await provider.getBalance(accounts[0])); + try { + setIsFetchingBalances(true); + const balances = await Promise.all( + accounts.map(async account => { + const balance = await web3Provider.getBalance(account); + return { symbol: "ETH", balance: utils.formatEther(balance) }; + }), + ); - // const TEST_ETH_TRANSFER = { - // from: accounts[0], - // to: accounts[0], - // value: utils.parseEther("1").toHexString(), - // data: "0x", - // }; + setBalances(balances); + } catch (error: any) { + throw new Error(error); + } finally { + setIsFetchingBalances(false); + } - // const signer = provider.getSigner(); - // const transferTx = await signer.sendTransaction(TEST_ETH_TRANSFER); - }; - - init(); - }, [client]); - - const onEnable = useCallback(async () => { - if (!ethereumProvider) { - throw new ReferenceError("ethereumProvider is not defined."); - } - if (!web3Provider) { - throw new ReferenceError("web3Provider is not defined."); - } - const accounts = await ethereumProvider.enable(); - setAccounts(accounts); - - setChains(["eip155:42"]); - - const balances = await Promise.all( - accounts.map(async account => { - const balance = await web3Provider.getBalance(account); - return { symbol: "ETH", balance: utils.formatEther(balance) }; - }), - ); - - setBalances(balances); - - QRCodeModal.close(); - }, [ethereumProvider, web3Provider]); + QRCodeModal.close(); + }, + [client], + ); console.log(balances); @@ -265,11 +264,11 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac balances, isFetchingBalances, accounts, - chains, + chain, client, session, disconnect, - setChains, + setChain, onEnable, web3Provider, }), @@ -279,11 +278,11 @@ export function ClientContextProvider({ children }: { children: ReactNode | Reac balances, isFetchingBalances, accounts, - chains, + chain, client, session, disconnect, - setChains, + setChain, onEnable, web3Provider, ], diff --git a/dapps/react-dapp-v2-with-ethers/src/contexts/Web3ProviderContext.tsx b/dapps/react-dapp-v2-with-ethers/src/contexts/Web3ProviderContext.tsx deleted file mode 100644 index 1e9350e..0000000 --- a/dapps/react-dapp-v2-with-ethers/src/contexts/Web3ProviderContext.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import Client, { CLIENT_EVENTS } from "@walletconnect/client"; -import { PairingTypes, SessionTypes } from "@walletconnect/types"; -import QRCodeModal from "@walletconnect/legacy-modal"; -import { - createContext, - ReactNode, - useCallback, - useContext, - useEffect, - useMemo, - useState, -} from "react"; -import { - DEFAULT_APP_METADATA, - DEFAULT_COSMOS_METHODS, - DEFAULT_EIP155_METHODS, - DEFAULT_LOGGER, - DEFAULT_PROJECT_ID, - DEFAULT_RELAY_URL, -} from "../constants"; -import { AccountBalances, apiGetAccountAssets } from "../helpers"; -import { ERROR, getAppMetadata } from "@walletconnect/utils"; -import EthereumProvider from "@walletconnect/ethereum-provider"; -import { providers } from "ethers"; -import { useWalletConnectClient } from "./ClientContext"; - -/** - * Types - */ -type IContext = any; - -/** - * Context - */ -export const Web3ProviderContext = createContext({} as IContext); - -/** - * Provider - */ -export function Web3ContextProvider({ children }: { children: ReactNode | ReactNode[] }) { - const [ethereumProvider, setEthereumProvider] = useState(); - const [web3Provider, setWeb3Provider] = useState(); - - const { client } = useWalletConnectClient(); - - useEffect(() => { - const init = async () => { - if (!client) return; - - // Create WalletConnect Provider - const ethereumProvider = new EthereumProvider({ - chainId: 42, - rpc: { - infuraId: "5dc0df7abe4645dfb06a9a8c39ede422", - }, - // FIXME: `signer-connection` sub-dep is already specifying beta.23 -> typings mismatch. - // @ts-ignore - client, - }); - const web3Provider = new providers.Web3Provider(ethereumProvider); - - setEthereumProvider(ethereumProvider); - setWeb3Provider(web3Provider); - - // Enable session (triggers QR Code modal if we bound the listener on `client` for it). - // const accounts = await ethereumProvider.enable(); - // console.log("accounts:", accounts); - - // const provider = new providers.Web3Provider(ethereumProvider); - - // console.log(provider); - // console.log(await provider.listAccounts()); - // console.log(await provider.getNetwork()); - // console.log(provider.getSigner()); - // console.log(await provider.getBalance(accounts[0])); - - // const TEST_ETH_TRANSFER = { - // from: accounts[0], - // to: accounts[0], - // value: utils.parseEther("1").toHexString(), - // data: "0x", - // }; - - // const signer = provider.getSigner(); - // const transferTx = await signer.sendTransaction(TEST_ETH_TRANSFER); - - // console.log(transferTx); - - // const signer = provider.getSigner(); - // const msg = "Hello world"; - // const signature = await signer.signMessage(msg); - // console.log("signature:", signature); - }; - - init(); - }, [client]); - - const onEnable = async () => { - await ethereumProvider?.enable(); - }; - - return ( - {children} - ); -} - -export function useWeb3Provider() { - const context = useContext(Web3ProviderContext); - if (context === undefined) { - throw new Error("useWeb3Provider must be used within a Web3ContextProvider"); - } - return context; -}