question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Enhancement] Add additional Web3 Providers

See original GitHub issue

Background I like this Dapp and have a build running with multiple customizations, such as dynamic price displays, randomized Mint orders, NFT Gallery of owned NFTs, ability to merge two NFT’s to create a brand new minted NFT etc. One thing I’m having trouble with is adding on additional Web3 providers such as this example: https://github.com/web3modal/web3modal

The way this is configured on the BlockchainActions.js to use Web3EthContract.setProvider(ethereum); let web3 = new Web3(ethereum); is difficult for me to swap. If I try using web3Modal above or WalletConnect as a provider, it seems to break everything.

Request Make this more modern with multiple provider options across HD and Mobile so it can be used in a variety of platforms and applications, such as Trust Wallet Mobile etc

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:4
  • Comments:56

github_iconTop GitHub Comments

6reactions
flappyscommented, Feb 18, 2022

Here you go, replace the whole file blockchainActions.js with the below code

// constants
import Web3EthContract from "web3-eth-contract";
import Web3 from "web3";
import Web3Modal from "web3modal";
import WalletConnectProvider from "@walletconnect/web3-provider";
import WalletLink from "walletlink";

// log
import { fetchData } from "../data/dataActions";

const INFURA_ID = "";

const providerOptions = {
  walletconnect: {
    package: WalletConnectProvider, // required
    options: {
      infuraId: INFURA_ID, // required
      rpc: {
        43114: "https://api.avax.network/ext/bc/C/rpc", // AVAX C-Chain
      },
    },
  },
  walletlink: {
    package: WalletLink, // Required
    options: {
      appName: "Ava Sharks", // Required
      infuraId: "", // Required unless you provide a JSON RPC url; see `rpc` below
      rpc: "https://api.avax.network/ext/bc/C/rpc", // Optional if `infuraId` is provided; otherwise it's required
      chainId: 43114, // Optional. It defaults to 1 if not provided
      appLogoUrl: null, // Optional. Application logo image URL. favicon is used if unspecified
      darkMode: false, // Optional. Use dark theme, defaults to false
    },
  },
};

const connectRequest = () => {
  return {
    type: "CONNECTION_REQUEST",
  };
};

const connectSuccess = (payload) => {
  return {
    type: "CONNECTION_SUCCESS",
    payload: payload,
  };
};

const connectFailed = (payload) => {
  return {
    type: "CONNECTION_FAILED",
    payload: payload,
  };
};

const updateAccountRequest = (payload) => {
  return {
    type: "UPDATE_ACCOUNT",
    payload: payload,
  };
};

export const connect = () => {
  return async (dispatch) => {
    dispatch(connectRequest());
    try {
      const abiResponse = await fetch("/config/abi.json", {
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
      });
      const abi = await abiResponse.json();
      const configResponse = await fetch("/config/config.json", {
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
      });
      const CONFIG = await configResponse.json();
      localStorage.removeItem("walletconnect");
      localStorage.removeItem("WALLETCONNECT_DEEPLINK_CHOICE");
      const web3Modal = new Web3Modal({
        network: "mainnet", // optional
        cacheProvider: false, // optional
        providerOptions, // required
      });
      const provider = await web3Modal.connect();
      const web3 = new Web3(provider);
      console.log("web", web3);

      Web3EthContract.setProvider(provider);
      const accounts = await web3.eth.getAccounts();
      const networkId = await provider.request({
        method: "net_version",
      });
      console.log("networkId", networkId);
      if (networkId == CONFIG.NETWORK.ID) {
        const SmartContractObj = new Web3EthContract(
          abi,
          CONFIG.CONTRACT_ADDRESS
        );
        dispatch(
          connectSuccess({
            account: accounts[0],
            smartContract: SmartContractObj,
            web3: web3,
          })
        );
        // Add listeners start
        provider.on("accountsChanged", (accounts) => {
          dispatch(updateAccount(accounts[0]));
        });
        provider.on("chainChanged", () => {
          window.location.reload();
        });
        // Add listeners end
      } else {
        dispatch(connectFailed(`Change network to ${CONFIG.NETWORK.NAME}.`));
      }
    } catch (err) {
      console.log("error", err, " message", err.message);
      if (
        typeof err !== "undefined" &&
        typeof err.message !== "undefined" &&
        err.message.includes("User Rejected")
      ) {
        dispatch(connectFailed("User rejected the request"));
      } else if (
        (typeof err === "string" || err instanceof String) &&
        err.includes("Modal closed by user")
      ) {
        dispatch(connectFailed("Modal closed by user"));
      } else {
        dispatch(connectFailed("Something went wrong."));
      }
    }
  };
};

export const updateAccount = (account) => {
  return async (dispatch) => {
    dispatch(updateAccountRequest({ account: account }));
    dispatch(fetchData(account));
  };
};

1reaction
austin2080commented, Mar 10, 2022

@Karmeleons That’s good to know because I never would have thought of that. We are really trying to push towards the Cronos network so that’s next on my list too lol

Read more comments on GitHub >

github_iconTop Results From Across the Web

Best practices for Web3 providers - LogRocket Blog
Best practices for Web3 providers · Reduced internet censorship · Few to no middlemen · High security · Room for collaboration and opportunity....
Read more >
How to Create More Efficient Web3 Dapps with Web3 Onboard
1. Implement A Module System · 2. Exclude External Dependencies · 3. Utilize Code Splitting and Dynamic Imports.
Read more >
The 12 Best Blockchain Node Providers in Web3 (2022)
Explore the best blockchain node providers across Ethereum, Solana, Polygon and more including details on pricing, NFT APIs, reliability, ...
Read more >
web3-providers-http | Yarn - Package Manager
Changelog · 1]. Added. transactionPollingInterval added to web3, contract and method constructor options. defaults to 1 second. (#4584) · 2]. Changed. Remove ...
Read more >
Front-End Development In Web3: This Is What You Need to ...
Web3 providers are websites that run nodes for you. You can use Infura, Alchemy, or QuickNode as Web3 providers for Ethereum ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found