From 3a7f226cacc994aea51e2dd60bffea72db0432d4 Mon Sep 17 00:00:00 2001 From: phipsae Date: Sat, 13 Apr 2024 08:23:55 -0500 Subject: [PATCH 1/5] preparation to integrate more pages with dom router --- packages/react-app/src/App.jsx | 1568 +---------------- packages/react-app/src/App.test.js | 2 +- packages/react-app/src/MainWallet.jsx | 1431 +++++++++++++++ packages/react-app/src/components/Account.jsx | 111 +- packages/react-app/src/components/Header.jsx | 136 +- .../react-app/src/contexts/AppContext.jsx | 28 + packages/react-app/src/index.jsx | 8 +- packages/react-app/src/pages/SwapPage.jsx | 22 + packages/react-app/src/pages/WalletPage.jsx | 30 + 9 files changed, 1780 insertions(+), 1556 deletions(-) create mode 100644 packages/react-app/src/MainWallet.jsx create mode 100644 packages/react-app/src/contexts/AppContext.jsx create mode 100644 packages/react-app/src/pages/SwapPage.jsx create mode 100644 packages/react-app/src/pages/WalletPage.jsx diff --git a/packages/react-app/src/App.jsx b/packages/react-app/src/App.jsx index abcac18bd..149982007 100644 --- a/packages/react-app/src/App.jsx +++ b/packages/react-app/src/App.jsx @@ -1,153 +1,27 @@ -import { CaretUpOutlined, ScanOutlined, SendOutlined, HistoryOutlined } from "@ant-design/icons"; -import { StaticJsonRpcProvider, Web3Provider } from "@ethersproject/providers"; -import { formatEther, parseEther } from "@ethersproject/units"; +// Import necessary parts from react-router-dom +import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; +import React, { useEffect, useState } from "react"; +import Web3Modal from "web3modal"; import WalletConnectProvider from "@walletconnect/web3-provider"; -import { Alert, Button, Checkbox, Col, Row, Select, Spin, Input, Modal, notification } from "antd"; -import "antd/dist/antd.css"; +import { useAppContext } from "./contexts/AppContext"; +import { INFURA_ID, NETWORKS } from "./constants"; +import WalletPage from "./pages/WalletPage"; +import SwapPage from "./pages/SwapPage"; +import Header from "./components/Header"; import { useUserAddress } from "eth-hooks"; -import React, { useCallback, useEffect, useState, useMemo } from "react"; -import Web3Modal from "web3modal"; -import "./App.css"; -import { - Account, - Address, - AddressInput, - Balance, - ERC20Balance, - ERC20Input, - SelectorWithSettings, - EtherInput, - Faucet, - GasGauge, - Header, - IFrame, - Monerium, - MoneriumCrossChainAddressSelector, - MoneriumOnChainCrossChainRadio, - NetworkDisplay, - NetworkDetailedDisplay, - SettingsModal, - QRPunkBlockie, - Ramp, - Reload, - TokenDetailedDisplay, - TokenDisplay, - TokenImportDisplay, - TransactionResponses, - Wallet, - WalletConnectTransactionPopUp, - WalletConnectV2ConnectionError, -} from "./components"; -import { INFURA_ID, NETWORK, NETWORKS } from "./constants"; -import { Transactor } from "./helpers"; -import { useBalance, useExchangePrice, useGasPrice, useLocalStorage, usePoller, useUserProvider } from "./hooks"; - -import WalletConnect from "@walletconnect/client"; +import { StaticJsonRpcProvider } from "@ethersproject/providers"; -import { - isWalletConnectV2Connected, - disconnectWallectConnectV2Sessions, - connectWalletConnectV2, - updateWalletConnectSession, - createWeb3wallet, - onSessionProposal, -} from "./helpers/WalletConnectV2Helper"; - -import { - ON_CHAIN_IBAN_VALUE, - getAvailableTargetChainNames, - isCrossChain, - getMemo, - getNewMoneriumClient, - getFilteredOrders, - getShortAddress, - isValidIban, - placeCrossChainOrder, - placeIbanOrder, - isIbanAddressObjectValid, -} from "./helpers/MoneriumHelper"; +import { NETWORK_SETTINGS_STORAGE_KEY, getNetworkWithSettings } from "./helpers/NetworkSettingsHelper"; import { SettingsHelper } from "./helpers/SettingsHelper"; -import { monitorBalance } from "./helpers/ERC20Helper"; - -import { - NETWORK_SETTINGS_STORAGE_KEY, - migrateSelectedNetworkStorageSetting, - getNetworkWithSettings, -} from "./helpers/NetworkSettingsHelper"; - -import { - TOKEN_SETTINGS_STORAGE_KEY, - getSelectedErc20Token, - getTokens, - migrateSelectedTokenStorageSetting, -} from "./helpers/TokenSettingsHelper"; - -import { getChain } from "./helpers/ChainHelper"; - -const { confirm } = Modal; - -const { ethers } = require("ethers"); - -const { OrderState } = require("@monerium/sdk"); - -/* - Welcome to πŸ— scaffold-eth ! - - Code: - https://github.com/austintgriffith/scaffold-eth - - Support: - https://t.me/joinchat/KByvmRe5wkR-8F_zz6AjpA - or DM @austingriffith on twitter or telegram - - You should get your own Infura.io ID and put it in `constants.js` - (this is your connection to the main Ethereum network for ENS etc.) - - - 🌏 EXTERNAL CONTRACTS: - You can also bring in contract artifacts in `constants.js` - (and then use the `useExternalContractLoader()` hook!) -*/ - -let scanner; +import { useLocalStorage, useUserProvider } from "./hooks"; -/* - Web3 modal helps us "connect" external wallets: -*/ -const web3Modal = new Web3Modal({ - // network: "mainnet", // optional - cacheProvider: true, // optional - providerOptions: { - walletconnect: { - package: WalletConnectProvider, // required - options: { - infuraId: INFURA_ID, - rpc: { - 10: "https://mainnet.optimism.io", // xDai - 100: "https://rpc.gnosischain.com", // xDai - 137: "https://polygon-rpc.com", - 280: "https://zksync2-testnet.zksync.dev", // zksync alpha tesnet - 31337: "http://localhost:8545", - 42161: "https://arb1.arbitrum.io/rpc", - 80001: "https://rpc-mumbai.maticvigil.com", - 80216: "https://chain.buidlguidl.com:8545", - }, - }, - }, - }, -}); - -// 😬 Sorry for all the console logging -const DEBUG = false; +function App({ subgraphUri }) { + const networks = Object.values(NETWORKS); -const networks = Object.values(NETWORKS); + const { setWeb3Modal, blockExplorer, priceContext, injectedProvider } = useAppContext(); -function App(props) { - const [dollarMode, setDollarMode] = useLocalStorage("dollarMode", true); - - const [networkSettingsModalOpen, setNetworkSettingsModalOpen] = useState(false); const [networkSettings, setNetworkSettings] = useLocalStorage(NETWORK_SETTINGS_STORAGE_KEY, {}); const networkSettingsHelper = new SettingsHelper( NETWORK_SETTINGS_STORAGE_KEY, @@ -168,1382 +42,82 @@ function App(props) { ); }, [targetNetwork]); - // πŸ”­ block explorer URL - const blockExplorer = targetNetwork.blockExplorer; - - const networkName = targetNetwork.name; - const erc20Tokens = targetNetwork?.erc20Tokens; - - const tokenSettingsStorageKey = networkName + TOKEN_SETTINGS_STORAGE_KEY; - const tokens = getTokens(targetNetwork?.nativeToken, erc20Tokens); - const [tokenSettingsModalOpen, setTokenSettingsModalOpen] = useState(false); - const [tokenSettings, setTokenSettings] = useLocalStorage(tokenSettingsStorageKey, {}); - - const tokenSettingsHelper = tokens - ? new SettingsHelper(tokenSettingsStorageKey, tokens, tokenSettings, setTokenSettings) - : undefined; - - useEffect(() => { - migrateSelectedTokenStorageSetting(networkName, tokenSettingsHelper); - migrateSelectedNetworkStorageSetting(networkSettingsHelper); - }, []); - - const selectedErc20Token = tokenSettingsHelper - ? getSelectedErc20Token( - tokenSettingsHelper.getSelectedItem(), - erc20Tokens.concat(tokenSettingsHelper.getCustomItems()), - ) - : undefined; - - if (selectedErc20Token) { - const switchToEth = localStorage.getItem("switchToEth"); - if (switchToEth) { - localStorage.removeItem("switchToEth"); - - if (targetNetwork?.nativeToken?.name) { - tokenSettingsHelper.updateSelectedName(targetNetwork.nativeToken.name); - console.log("Switched to native token"); - } - } - } - - const mainnetProvider = new StaticJsonRpcProvider(NETWORKS.ethereum.rpcUrl); - - const [injectedProvider, setInjectedProvider] = useState(); - - const logoutOfWeb3Modal = async () => { - await web3Modal.clearCachedProvider(); - if (injectedProvider && injectedProvider.provider && injectedProvider.provider.disconnect) { - await injectedProvider.provider.disconnect(); - } - setTimeout(() => { - window.location.reload(); - }, 1); - }; - - /* πŸ’΅ This hook will get the price of ETH from πŸ¦„ Uniswap: */ - const price = useExchangePrice(targetNetwork, mainnetProvider); - - /* πŸ”₯ This hook will get the price of Gas from ⛽️ EtherGasStation */ - const gasPrice = useGasPrice(targetNetwork, "fast", localProvider); // Use your injected provider from 🦊 Metamask or if you don't have it then instantly generate a πŸ”₯ burner wallet. const userProvider = useUserProvider(injectedProvider, localProvider); - const address = useUserAddress(userProvider); - - // You can warn the user if you would like them to be on a specific network - // I think the naming is misleading a little bit - // localChainId is what we can select with the chainId selector on the UI - // selectedChainId is different in case we connect with MetaMask (or Wallet Connect) and we're on a different chain - const localChainId = localProvider && localProvider._network && localProvider._network.chainId; - const selectedChainId = userProvider && userProvider._network && userProvider._network.chainId; - - // For more hooks, check out πŸ”—eth-hooks at: https://www.npmjs.com/package/eth-hooks - - // The transactor wraps transactions and provides notificiations - const tx = Transactor(userProvider, gasPrice, undefined, injectedProvider); - - // Faucet Tx can be used to send funds from the faucet - const faucetTx = Transactor(localProvider, gasPrice); - - // πŸ— scaffold-eth is full of handy hooks like this one to get your balance: - const yourLocalBalance = useBalance(localProvider, address); - - const balance = yourLocalBalance && formatEther(yourLocalBalance); - - const [showHistory, setShowHistory] = useLocalStorage("showHistory", true); - - const [moneriumClient, setMoneriumClient] = useState(getNewMoneriumClient()); - const [moneriumConnected, setMoneriumConnected] = useState(false); - const [moneriumClientData, setMoneriumClientData] = useState(null); - const [punkConnectedToMonerium, setPunkConnectedToMonerium] = useState(false); - const [moneriumOrders, setMoneriumOrders] = useState(null); - const [moneriumRadio, setMoneriumRadio] = useLocalStorage("moneriumRadio", ON_CHAIN_IBAN_VALUE); - const [moneriumTargetChain, setMoneriumTargetChain] = useLocalStorage( - networkName + "MoneriumTargetChain", - getAvailableTargetChainNames(networkName)[0], - ); - const [moneriumTargetAddress, setMoneriumTargetAddress] = useState(address); - useEffect(() => { - setMoneriumTargetAddress(prevAddress => (prevAddress == address ? prevAddress : address)); - }, [address]); - - const memoizedMonerium = useMemo( - () => ( - - ), - [moneriumClient, moneriumConnected, moneriumClientData, punkConnectedToMonerium, address], - ); - - const initMoneriumOrders = async sleepMs => { - if (sleepMs) { - await new Promise(r => setTimeout(r, sleepMs)); - } - - const filterObject = { - address: address, - }; - - try { - const moneriumOrders = await getFilteredOrders(moneriumClient, filterObject); - setMoneriumOrders(moneriumOrders); - } catch (error) { - console.log("Something went wrong", error); - } - }; - - useEffect(() => { - if (!moneriumConnected || !punkConnectedToMonerium || !address) { - return; - } - - initMoneriumOrders(); - }, [moneriumClient, moneriumConnected, punkConnectedToMonerium, address]); - - useEffect(() => { - if (!moneriumOrders) { - return; - } - - let pendingOrder = false; - - for (const order of moneriumOrders) { - const state = order?.meta?.state; - if ((state && state == OrderState.placed) || state == OrderState.pending) { - console.log("There is a pending order", order); - pendingOrder = true; - break; - } - } - - if (pendingOrder) { - initMoneriumOrders(3000); - } - }, [moneriumOrders]); - - const [ibanAddressObject, setIbanAddressObject] = useState({}); - - const isMoneriumDataLoading = - moneriumConnected && !moneriumClientData && selectedErc20Token && selectedErc20Token.name == "EURe"; - const isMoneriumTransferReady = - moneriumConnected && punkConnectedToMonerium && selectedErc20Token && selectedErc20Token.name == "EURe"; - - const connectWallet = sessionDetails => { - console.log(" πŸ“‘ Connecting to Wallet Connect....", sessionDetails); - - let connector; - try { - connector = new WalletConnect(sessionDetails); - const { peerMeta } = connector; - if (peerMeta) { - setWalletConnectPeerMeta(peerMeta); - } - } catch (error) { - console.error("Coudn't connect to", sessionDetails, error); - localStorage.removeItem("walletConnectUrl"); - return; - } - setWallectConnectConnector(connector); - - // Subscribe to session requests - connector.on("session_request", (error, payload) => { - if (error) { - throw error; - } - - console.log("SESSION REQUEST"); - // Handle Session Request - - connector.approveSession({ - accounts: [ - // required - address, - ], - chainId: targetNetwork.chainId, // required - }); - - setWalletConnectConnected(true); - setWallectConnectConnectorSession(connector.session); - const { peerMeta } = payload.params[0]; - if (peerMeta) { - setWalletConnectPeerMeta(peerMeta); - } - - /* payload: - { - id: 1, - jsonrpc: '2.0'. - method: 'session_request', - params: [{ - peerId: '15d8b6a3-15bd-493e-9358-111e3a4e6ee4', - peerMeta: { - name: "WalletConnect Example", - description: "Try out WalletConnect v1.0", - icons: ["https://example.walletconnect.org/favicon.ico"], - url: "https://example.walletconnect.org" - } - }] - } - */ - }); - - // Subscribe to call requests - connector.on("call_request", async (error, payload) => { - if (error) { - throw error; - } - - console.log("call_request payload", payload); - - WalletConnectTransactionPopUp(payload, userProvider, connector, undefined, targetNetwork.chainId); - }); - - connector.on("disconnect", (error, payload) => { - if (error) { - throw error; - } - console.log("disconnect"); - - disconnectFromWalletConnect(); - }); - }; - - const disconnectFromWalletConnect = async (wallectConnectConnector, web3wallet) => { - try { - if (wallectConnectConnector) { - console.log("Disconnect from Wallet Connect V1"); - await wallectConnectConnector.killSession(); - } - } catch (error) { - console.error("Coudn't disconnect from Wallet Connect V1", error); - } - - try { - if (web3wallet && isWalletConnectV2Connected(web3wallet)) { - console.log("Disconnect from Wallet Connect V2"); - await disconnectWallectConnectV2Sessions(web3wallet); - } - } catch (error) { - console.error("Coudn't disconnect from Wallet Connect V2", error); - - // This is a hack to remove the session manually - // Otherwise if an old session is stuck, we cannot delete it - localStorage.removeItem("wc@2:client:0.3//session"); - } - - setWalletConnectUrl(""); - setWalletConnectPeerMeta(); - setWallectConnectConnector(); - setWallectConnectConnectorSession(""); - - // This has to be the last, so we don't try to reconnect in "Wallet Connect Hook" too early - setWalletConnectConnected(false); - }; - - const [walletConnectUrl, setWalletConnectUrl] = useLocalStorage("walletConnectUrl"); - const [walletConnectConnected, setWalletConnectConnected] = useState(); - const [walletConnectPeerMeta, setWalletConnectPeerMeta] = useState(); - - const [wallectConnectConnector, setWallectConnectConnector] = useState(); - //store the connector session in local storage so sessions persist through page loads ( thanks Pedro <3 ) - const [wallectConnectConnectorSession, setWallectConnectConnectorSession] = useLocalStorage( - "wallectConnectConnectorSession", - ); - - const [web3wallet, setWeb3wallet] = useState(); - // Wallet Connect V2 initialization and listeners - useEffect(() => { - if (!address) { - return; - } - - async function initWeb3wallet() { - const web3wallet = await createWeb3wallet(); - - web3wallet.on("session_proposal", proposal => { - onSessionProposal( - web3wallet, - address, - proposal, - disconnectFromWalletConnect, - setWalletConnectUrl, - setWalletConnectConnected, - setWalletConnectPeerMeta, - ); - }); - - web3wallet.on("session_request", async requestEvent => { - console.log("session_request requestEvent", requestEvent); - - WalletConnectTransactionPopUp(requestEvent, userProvider, undefined, web3wallet, targetNetwork.chainId); - }); - - web3wallet.on("session_update", async event => { - console.log("session_update event", event); - }); - - web3wallet.on("session_delete", async event => { - console.log("session_delete event", event); - - await disconnectFromWalletConnect(undefined, web3wallet); - }); - - web3wallet.on("session_event", async event => { - console.log("session_event", event); - }); - - web3wallet.on("session_ping", async event => { - console.log("session_ping", event); - }); - - web3wallet.on("session_expire", async event => { - console.log("session_expire", event); - }); - - web3wallet.on("session_extend", async event => { - console.log("session_extend", event); - }); - - web3wallet.on("proposal_expire", async event => { - console.log("proposal_expire", event); - }); - - setWeb3wallet(web3wallet); - } - - initWeb3wallet(); - }, [address]); - - useEffect(() => { - if (!web3wallet) { - return; - } - - connectWalletConnectV2(web3wallet, setWalletConnectConnected, setWalletConnectPeerMeta); - }, [web3wallet]); - - // Add an event listener to kill Wallet Connect V1 session when V2 Dapp reconnects - // and there was an existing V1 session - useEffect(() => { - if (!web3wallet || !wallectConnectConnector) { - return; - } - - const listener = () => { - if (wallectConnectConnector) { - console.log("Kill Wallet Connect V1 session"); - wallectConnectConnector.killSession(); - } - }; - - web3wallet.on("session_proposal", listener); - - return () => { - web3wallet.off("session_proposal", listener); - }; - }, [web3wallet, wallectConnectConnector]); - - useEffect(() => { - if (wallectConnectConnector && wallectConnectConnector.connected && address && localChainId) { - const connectedAccounts = wallectConnectConnector?.accounts; - let connectedAddress; - - if (connectedAccounts) { - connectedAddress = connectedAccounts[0]; - } - - // Use Checksummed addresses - if (connectedAddress && ethers.utils.getAddress(connectedAddress) != ethers.utils.getAddress(address)) { - console.log("Updating wallet connect session with the new address"); - console.log("Connected address", ethers.utils.getAddress(connectedAddress)); - console.log("New address ", ethers.utils.getAddress(address)); - - updateWalletConnectSession(wallectConnectConnector, address, localChainId); - } - - const connectedChainId = wallectConnectConnector?.chainId; - - if (connectedChainId && connectedChainId != localChainId) { - console.log("Updating wallet connect session with the new chainId"); - console.log("Connected chainId", connectedChainId); - console.log("New chainId ", localChainId); - - updateWalletConnectSession(wallectConnectConnector, address, localChainId); - } - } - }, [address, localChainId, wallectConnectConnector]); - - // "Wallet Connect Hook" - useEffect(() => { - if (!walletConnectConnected && address) { - if (wallectConnectConnectorSession) { - console.log("NOT CONNECTED AND wallectConnectConnectorSession", wallectConnectConnectorSession); - connectWallet(wallectConnectConnectorSession); - setWalletConnectConnected(true); - } else if (walletConnectUrl) { - // Version 2 is handled separately - if (walletConnectUrl.includes("@2")) { - return; - } - - //CLEAR LOCAL STORAGE?!? - console.log("clear local storage and connect..."); - localStorage.removeItem("walletconnect"); // lololol - connectWallet( - { - // Required - uri: walletConnectUrl, - // Required - clientMeta: { - description: "Forkable web wallet for small/quick transactions.", - url: "https://punkwallet.io", - icons: ["https://punkwallet.io/punk.png"], - name: "πŸ§‘β€πŸŽ€ PunkWallet.io", - }, - } /*, - { - // Optional - url: "", - type: "fcm", - token: token, - peerMeta: true, - language: language, - }*/, - ); - } - } - }, [walletConnectUrl, address, walletConnectConnected, wallectConnectConnectorSession]); - - useEffect(() => { - async function pairWalletConnectV2() { - if ( - walletConnectUrl && - walletConnectUrl.includes("@2") && - web3wallet && - !isWalletConnectV2Connected(web3wallet) - ) { - console.log(" πŸ“‘ Connecting to Wallet Connect V2....", walletConnectUrl); - try { - await web3wallet.core.pairing.pair({ uri: walletConnectUrl }); - } catch (error) { - console.log("Cannot create pairing", error); - WalletConnectV2ConnectionError(error, undefined); - setWalletConnectUrl(""); - } - } - } - - pairWalletConnectV2(); - }, [walletConnectUrl, web3wallet]); - - useMemo(() => { - if (address && window.location.pathname) { - if (window.location.pathname.indexOf("/wc") >= 0) { - // ToDo - console.log("WALLET CONNECT!!!!!", window.location.search); - let uri = window.location.search.replace("?uri=", ""); - console.log("WC URI:", uri); - setWalletConnectUrl(decodeURIComponent(uri)); - } - } - }, [injectedProvider, localProvider, address]); + const mainnetProvider = new StaticJsonRpcProvider(NETWORKS.ethereum.rpcUrl); - // Just plug in different πŸ›° providers to get your balance on different chains: - const yourMainnetBalance = useBalance(mainnetProvider, address); + const address = useUserAddress(userProvider); - // - // 🧫 DEBUG πŸ‘¨πŸ»β€πŸ”¬ - // /* - useEffect(()=>{ - if(DEBUG && mainnetProvider && address && selectedChainId && yourLocalBalance && yourMainnetBalance && readContracts && writeContracts && mainnetDAIContract){ - console.log("_____________________________________ πŸ— scaffold-eth _____________________________________") - console.log("🌎 mainnetProvider",mainnetProvider) - console.log("🏠 localChainId",localChainId) - console.log("πŸ‘©β€πŸ’Ό selected address:",address) - console.log("πŸ•΅πŸ»β€β™‚οΈ selectedChainId:",selectedChainId) - console.log("πŸ’΅ yourLocalBalance",yourLocalBalance?formatEther(yourLocalBalance):"...") - console.log("πŸ’΅ yourMainnetBalance",yourMainnetBalance?formatEther(yourMainnetBalance):"...") - console.log("πŸ“ readContracts",readContracts) - console.log("🌍 DAI contract on mainnet:",mainnetDAIContract) - console.log("πŸ” writeContracts",writeContracts) - } - }, [mainnetProvider, address, selectedChainId, yourLocalBalance, yourMainnetBalance, readContracts, writeContracts, mainnetDAIContract]) - */ - - let networkDisplay = ""; - if (localChainId && selectedChainId && localChainId !== selectedChainId) { - const networkSelected = NETWORK(selectedChainId); - const networkLocal = NETWORK(localChainId); - if (selectedChainId === 1337 && localChainId === 31337) { - networkDisplay = ( -
- - You have chain id 1337 for localhost and you need to change it to 31337 to work with - HardHat. -
(MetaMask -> Settings -> Networks -> Chain ID -> 31337)
-
- } - type="error" - closable={false} - /> - - ); - } else { - networkDisplay = ( -
- - You have {networkSelected && networkSelected.name} selected and you need to be on{" "} - {networkLocal && networkLocal.name}. - -
- } - type="error" - closable={false} - /> - - ); - } - } else { - networkDisplay = ( -
- {networkName} -
- ); - } - - const loadWeb3Modal = useCallback(async () => { - const provider = await web3Modal.connect(); - provider.on("disconnect", () => { - console.log("LOGOUT!"); - logoutOfWeb3Modal(); - }); - setInjectedProvider(new Web3Provider(provider)); - }, [setInjectedProvider]); + Web3 modal helps us "connect" external wallets: +*/ + const web3ModalInstance = new Web3Modal({ + // network: "mainnet", // optional + cacheProvider: true, // optional + providerOptions: { + walletconnect: { + package: WalletConnectProvider, // required + options: { + infuraId: INFURA_ID, + rpc: { + 10: "https://mainnet.optimism.io", // xDai + 100: "https://rpc.gnosischain.com", // xDai + 137: "https://polygon-rpc.com", + 280: "https://zksync2-testnet.zksync.dev", // zksync alpha tesnet + 31337: "http://localhost:8545", + 42161: "https://arb1.arbitrum.io/rpc", + 80001: "https://rpc-mumbai.maticvigil.com", + 80216: "https://chain.buidlguidl.com:8545", + }, + }, + }, + }, + }); useEffect(() => { - if (web3Modal.cachedProvider) { - loadWeb3Modal(); - } - }, [loadWeb3Modal]); - - let faucetHint = ""; - const faucetAvailable = localProvider && localProvider.connection && networkName == "localhost"; - - const [faucetClicked, setFaucetClicked] = useState(false); - if ( - !faucetClicked && - localProvider && - localProvider._network && - localProvider._network.chainId == 31337 && - yourLocalBalance && - formatEther(yourLocalBalance) <= 0 - ) { - faucetHint = ( -
- -
- ); - } - - const [toAddress, setToAddress] = useLocalStorage("punkWalletToAddress", "", 120000); - - const [amount, setAmount] = useState(); - - const [amountEthMode, setAmountEthMode] = useState(false); - - if (window.location.pathname) { - try { - const incoming = window.location.pathname.replace("/", ""); - - if (incoming) { - const incomingParts = incoming.split(":"); - - let index = 0; - let pushState = false; - - const incomingNetworkName = incomingParts[index]; - let incomingNetwork; - - if (incomingNetworkName) { - incomingNetwork = Object.values(NETWORKS).find(network => network.name.startsWith(incomingNetworkName)); - - if (incomingNetwork) { - console.log("incoming network:", incomingNetwork); - - networkSettingsHelper.updateSelectedName(incomingNetwork.name); - setTargetNetwork(networkSettingsHelper.getSelectedItem(true)); - - let pushStateURL = "/"; - - if (incomingParts.length > 1 && incomingParts[1] == "pk") { - pushStateURL = "pk" + window.location.hash; - } - - window.history.pushState({}, "", pushStateURL); - pushState = true; - - index++; - } - } - - let validAddress = false; - - if (incomingParts.length > index) { - const incomingAddress = incomingParts[index]; - - if (incomingAddress && ethers.utils.isAddress(incomingAddress)) { - console.log("incoming address:", incomingAddress); - - validAddress = true; - - setToAddress(incomingAddress); - - if (!pushState) { - window.history.pushState({}, "", "/"); - pushState = true; - } - } - - index++; - } - - if (validAddress && incomingParts.length > index) { - const incomingAmount = parseFloat(incomingParts[index]); - - if (incomingAmount > 0) { - console.log("incoming amount:", incomingAmount); - setAmount(incomingAmount); - setAmountEthMode(true); - - if (!incomingNetwork) { - if (targetNetwork?.nativeToken?.name) { - tokenSettingsHelper.updateSelectedName(targetNetwork.nativeToken.name); - console.log("Switched to native token"); - } - } - - if (incomingNetwork?.nativeToken) { - localStorage.setItem("switchToEth", true); - } - } - - if (!pushState) { - window.history.pushState({}, "", "/"); - } - } - } - } catch (error) { - console.error("Coudn't parse incoming address/amount/network", error); - } - } - - const [data, setData] = useState(); - - const [walletConnectTx, setWalletConnectTx] = useState(); - - const [loading, setLoading] = useState(false); - - const [depositing, setDepositing] = useState(); - const [depositAmount, setDepositAmount] = useState(); - - // ERC20 Token balance to use in ERC20Balance and in ERC20Input - const [balanceERC20, setBalanceERC20] = useState(null); - - const [priceERC20, setPriceERC20] = useState(); - - const walletDisplay = - web3Modal && web3Modal.cachedProvider ? ( - "" - ) : ( - - ); + setWeb3Modal(web3ModalInstance); + }, []); return ( -
- {networkSettingsHelper && ( - } - itemDetailedDisplay={( + +
+
( - - )} - modalOpen={networkSettingsModalOpen} - setModalOpen={setNetworkSettingsModalOpen} - title={"Network Settings"} - setTargetNetwork={setTargetNetwork} - /> - )} - - {tokenSettingsHelper && ( - ( - - )} - itemDetailedDisplay={(tokenSettingsHelper, tokenDetailed, tokenCoreDisplay, network, setItemDetailed) => ( - - )} - itemImportDisplay={(tokenSettingsHelper, tokenCoreDisplay, tokenDetailedDisplay, network, setImportView) => ( - - )} - modalOpen={tokenSettingsModalOpen} - setModalOpen={setTokenSettingsModalOpen} - title={"Token Settings"} // ToDo: Reuse TOKEN_SETTINGS_STORAGE_KEY and colored network name - network={targetNetwork} + priceContext, + web3ModalInstance, + }} /> - )} - -
-
, - /* - - { - window.open("https://zapper.fi/transactions?address="+address) - }}/> - - , */ - walletDisplay, - - + + ( + , - , - ]} - /> -
- - {/* ✏️ Edit the header and change the title to your project name */} - -
-
- {selectedErc20Token ? ( - - ) : ( - - )} -
- - -
-
- } - onChange={value => { - setTargetNetwork(networkSettingsHelper.getSelectedItem(true)); - }} - optionStyle={{ lineHeight: 1.1 }} - /> -
-
- {" "} - {tokenSettingsHelper && ( - } - /> - )} -
-
- {faucetHint} -
-
- - {address && ( -
- -
- )} - -
-
- {isMoneriumDataLoading && ( -
- {"Monerium - -
- )} - {isMoneriumTransferReady && ( - - )} - {isMoneriumTransferReady && isCrossChain(moneriumRadio) ? ( - - ) : ( - { - scanner = toggle; - }} - isMoneriumTransferReady={isMoneriumTransferReady} - ibanAddressObject={ibanAddressObject} - setIbanAddressObject={setIbanAddressObject} - walletConnect={async wcLink => { - if (walletConnectConnected) { - await disconnectFromWalletConnect(wallectConnectConnector, web3wallet); - } - - setWalletConnectUrl(wcLink); - }} - /> - )} -
- -
- {walletConnectTx ? ( - - ) : selectedErc20Token ? ( - - ) : ( - { - setAmount(value); - }} + mainnetProvider={mainnetProvider} /> )} -
- -
{networkDisplay}
- -
- { - - } -
-
- -
- { - - } -
- -
- - - -
- -
- {wallectConnectConnector && !wallectConnectConnector.connected && ( -
- -
Connecting to the Dapp...
-
- )} -
- {walletConnectConnected ? ( - <> - {walletConnectPeerMeta?.icons[0] ? ( - - {walletConnectPeerMeta?.icons[0] && ( - {walletConnectPeerMeta.name - )} - - ) : ( - βœ… - )} - - ) : ( - "" - )} - )"} - value={walletConnectPeerMeta?.name ? walletConnectPeerMeta.name : walletConnectUrl} - disabled={walletConnectConnected} - onChange={e => { - setWalletConnectUrl(e.target.value); - }} - /> - {walletConnectConnected ? ( - { - disconnectFromWalletConnect(wallectConnectConnector, web3wallet); - }} - > - πŸ—‘ - - ) : ( - "" - )} -
-