//------------------------------------------------------------------------------------------------------------ //---------- VARIABLES ------------------------------------------- //------------------------------------------------------------------------------------------------------------ // Unpkg imports. Setting up the constants I'll use in the script const Web3Modal = window.Web3Modal.default; const WalletConnectProvider = window.WalletConnectProvider.default; const EvmChains = window.EvmChains; const Fortmatic = window.Fortmatic; // Web3modal instance + provider + selected account (set up as nil first) let web3Modal, provider, selectedAccount; let accounts = []; //Get address, used for most functions let address = getSavedAddress() if(address) { $("#address-textfield").val(address) } //------------------------------------------------------------------------------------------------------------ //---------- ADDRESS MANAGEMENT FUNCTIONS ------------------------------------------- //------------------------------------------------------------------------------------------------------------ //called from connect function or form filling. Will also reload data //(fetch all data from blockchain) function setAddress(a) { console.log("address set") console.log(address) address = a saveAddress(a) SCOPE.address = a } function checkIfWasConnected(){ if (getSavedAddress()) { onConnect() } } function getSavedAddress() { return window.localStorage != null ? window.localStorage.getItem("address") : null } function saveAddress(address) { if(!window.localStorage) { return; } if(!address || !address.startsWith("0x")) { return; } window.localStorage.setItem("address", address) } //------------------------------------------------------------------------------------------------------------ //---------- WALLET CONNECT FUNCTIONS ------------------------------------------- //------------------------------------------------------------------------------------------------------------ //Init function for the wallet-connect function init() { //need provider for walletconnect and Formatic (unused at the moment) const providerOptions = { walletconnect: { package: WalletConnectProvider, options: { // InfuraID. required to make this work infuraId: "8c4beffc4b7041c889224772fbd23e2b", } }, fortmatic: { package: Fortmatic, options: { // EtherscanAPIKey? unsure about this. Not even sure it's //used unless you use formatic key: "pk_test_A3045BC3289C81DB" } } }; //create an instance of the web3modal web3Modal = new Web3Modal({ //debug cacheProvider: true, // optional //cacheProvider: false, // optional providerOptions, // required }); } /** * Kick in the UI action after Web3modal dialog has chosen a provider */ async function fetchAccountData() { console.log("fetch account data") accounts = await provider.listAccounts() // Get connected chain id from Ethereum node //const chainId = await web3.eth.getChainId(); // Get list of accounts of the connected wallet //accounts = await web3.eth.getAccounts(); // MetaMask does not give you all accounts, only the selected account selectedAccount = accounts[0]; var cutAcc = selectedAccount.replace(selectedAccount.substring(4,selectedAccount.length - 4), "..."); $("#address-textfield").val(selectedAccount) updateState("connected") setAddress(selectedAccount) // Display fully loaded UI for wallet data $("#connect-text").text(cutAcc); showNavButtons(true) } /** * Fetch account data for UI when * - User switches accounts in wallet * - User switches networks in wallet * - User connects wallet initially */ async function refreshAccountData() { // If any current data is displayed when // the user is switching acounts in the wallet // immediate hide this data // Disable button while UI is loading. // fetchAccountData() will take a while as it communicates // with Ethereum node via JSON-RPC and loads chain data // over an API call. await fetchAccountData(provider); } //------------------------------------------------------------------------------------------------------------ //---------- UI FUNCTIONS ------------------------------------------- //------------------------------------------------------------------------------------------------------------ function showNavButtons(isConnected) { if (isConnected) { $("#btn-connect").hide() $("#connect-text").show() $("#btn-disconnect").show() } else { $("#btn-connect").show() $("#btn-disconnect").hide() $("#connect-text").hide() } } /** * Connect wallet button pressed. */ async function onConnect() { let instance if(window.ethereum) { instance = window.ethereum await instance.request({ method: "eth_requestAccounts" }) } else { instance = new WalletConnectProvider({ infuraId: "8c4beffc4b7041c889224772fbd23e2b" }) await instance.enable() } provider = new ethers.providers.Web3Provider(instance) SCOPE.provider = provider /* //updateState("connecting") console.log("Opening a dialog", web3Modal); try { provider = await web3Modal.connect(); } catch(e) { console.log("Could not get a wallet connection", e); return; }*/ // Subscribe to accounts change provider.on("accountsChanged", (accounts) => { fetchAccountData(); }); // Subscribe to chainId change provider.on("chainChanged", (chainId) => { fetchAccountData(); }); // Subscribe to networkId change provider.on("networkChanged", (networkId) => { fetchAccountData(); }); await refreshAccountData(); } /*Disconnect button pressed*/ async function onDisconnect(dontClear) { showNavButtons(false) updateState("disconnected") localStorage.removeItem("WEB3_CONNECT_CACHED_PROVIDER") // TODO: Which providers have close method? if(provider.close) { await provider.close(); // If the cached provider is not cleared, // WalletConnect will default to the existing session // and does not allow to re-scan the QR code with a new wallet. // Depending on your use case you may want or want not his behavir. await web3Modal.clearCachedProvider(); provider = null; SCOPE.provider = null; } selectedAccount = null; // Set the UI back to the initial state //$('.address').text("0x00000"); //$('.balance').text("0.000"); if(!dontClear) { $("#address-textfield").val("") } setAddress(undefined) } //------------------------------------------------------------------------------------------------------------ //---------- UI LISTENERS ------------------------------------------- //------------------------------------------------------------------------------------------------------------ /** * Listener on load. will basically launch //the initialization function for wallet connect */ window.addEventListener('load', async () => { init(); if(localStorage.getItem("WEB3_CONNECT_CACHED_PROVIDER")) { onConnect() } else { } $("#btn-connect").on("click", () => {onConnect() }); $("#btn-disconnect").on("click", ()=> {onDisconnect() }); }); //Adding listener to the address-form $("#address-form").submit(function(e) { e.preventDefault() const value = $("#address-textfield").val() if(value.length !== 42) { return false } onDisconnect(true) try { setAddress(value) } catch(e) { return false } return false }) showNavButtons(false) checkIfWasConnected() //------------------------------------------------------------------------------------------------------------ //---------- STATE MANAGER ------------------------------------------- //------------------------------------------------------------------------------------------------------------ function updateState(state) { SCOPE.state = state }