🧰 A simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps

Last update: Jun 23, 2022

web3-react 🧰

A simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps

lerna code style: prettier

Actions Status

Packages @latest Version Size Description
🏠 Core
@web3-react/core npm version minzip React Interface
🔌 Connectors
Browser Extension/dApp Browser
@web3-react/injected-connector npm version minzip Injected Connector
Remote API
@web3-react/network-connector npm version minzip RPC Connector
QR Code
@web3-react/walletconnect-connector npm version minzip WalletConnect Connector
@web3-react/walletlink-connector npm version minzip WalletLink Connector
Hardware
@web3-react/ledger-connector npm version minzip Ledger Connector
@web3-react/trezor-connector npm version minzip Trezor Connector
@web3-react/lattice-connector npm version minzip Lattice Connector
Native
@web3-react/frame-connector npm version minzip Frame Connector
Hosted
@web3-react/authereum-connector npm version minzip Authereum Connector
@web3-react/fortmatic-connector npm version minzip Fortmatic Connector
@web3-react/portis-connector npm version minzip Portis Connector
@web3-react/squarelink-connector npm version minzip Squarelink Connector
@web3-react/torus-connector npm version minzip Torus Connector
🐉 Low-Level
@web3-react/abstract-connector npm version minzip Shared Connector Class
@web3-react/types npm version minzip Shared TypeScript Types

Quickstart

Edit web3-react-example

Documentation

Projects using web3-react

Open a PR to add your project to the list!

Related Efforts

Local Development

  • Clone repo
    git clone https://github.com/NoahZinsmeister/web3-react.git

  • Install top-level dependencies
    yarn

  • Install sub-dependencies
    yarn bootstrap

  • Build and watch for changes
    yarn start

GitHub

https://github.com/NoahZinsmeister/web3-react
Comments
  • 1. Error: Cannot find module `use-sync-external-store/shim/with-selector`

    Hello, thanks for such a great package!

    I have some troubles with connecting web3-react to my application. I'm having the following error:

    Error: Cannot find module '/Users/dmytro/Work/learn/web3-react/packages/example/node_modules/use-sync-external-store/shim/with-selector' imported from /Users/dmytro/Work/learn/web3-react/packages/example/node_modules/@web3-react/core/node_modules/zustand/esm/index.mjs
    Did you mean to import use-sync-external-store/shim/with-selector.js?
    

    Tried launching the official example under packages/example, but also got the same issue.

    EDIT: I've detected, that it occurs when I'm destructuring from connector hooks (so the problem lies in initializeConnector function):

    import { hooks } from "../connectors/metaMask";
    
    const { useProvider } = hooks;
    
    Reviewed by sinnrrr at 2022-01-22 22:49
  • 2. New Version: v6!

    Hi web3-react peeps! I want to give everyone a status update on the future development of the project.

    While I'm open to being proved wrong, I consider the overall design of web3-react to be sound (using React context to pass down relevant web3-related manager functions and descriptive variables with a generic connector format for specifying requirements specific to different providers). However, I think the current codebase leaves something to be desired in terms of thoughtfulness around function memoization, provider initialization, error messages, multiple simultaneous provider support, etc.

    I have a basic framework in my head for how I'd like to structure the next version of the library to address some of these issues, but unfortunately not too much time to work on it.

    I'm going to note down some of these ideas here, and set a tentative deadline of 1/1/2020 to get a beta version of the new architecture published.

    1. Migration to lerna monorepo (publish core and individual connectors separately)
    2. Use tsdx to manage development environment (bundling, testing, etc.)
    3. CI/CD via Github Actions and GitHub Package Registry
    4. Native multi-provider support (via multiple contexts? keys within a single context?)
    5. Suspense/Concurrent mode integration (if it ends up being relevant to the new architecture and in a stable release by then)
    6. Rip out ethers dependency in core
    7. Other stuff that I'm sure I'm not remembering at the moment.

    Feel free to use this thread as a sounding board for questions/suggestions/comments/ etc. Thanks for your interest in the library, and I hope you'll continue to follow along as it continues to evolve!

    Reviewed by NoahZinsmeister at 2019-11-01 21:22
  • 3. InjectedConnector activation opening MetaMask and Coinbase Wallet pop-ups when the user has both extensions

    Bug Description Activation of the InjectedConnector results in displaying pop-ups from both wallets at the same time when the user has both extensions installed. When we use WalletLinkConnector only the Coinbase Wallet is activated.

    Reproduction CodeSandbox reproduction

    Steps to reproduce:

    1. Install MetaMask and Coinbase Wallet chrome extensions.
    2. Open the CodeSandbox example and then run the code in a new tab (when we try it within the CodeSandbox editor it seems to work properly) - direct link.
    3. Click the "Connect Wallet" button.

    Expected Behavior Only the MetaMask wallet popup should be displayed when we use InjectedConnector.

    Additional Context Using Google Chrome 94.0.4606.81 on Mac

    Reviewed by tomaszbakula at 2021-10-21 14:33
  • 4. We wrote some docs for web3react , hoping someone will check them out

    Description

    Hi! We really like your library, and ended up writing some internal docs to help us use it better, which we are in the process of turning into an article. Seeing as a lot of Web3React isn't documented, we thought this might be useful for you. We'd like to invite any of the Web3React team to take a look, give feedback, and use whatever might be useful for you.

    Additional Context

    We've been writing using a HackMD here, and would be happy to respond to any feedback here in the thread.

    Reviewed by wschwab at 2021-07-09 12:01
  • 5. How does injected.isAuthorized() work?

    Hi,

    I assume injected.isAuthorized() is returning a promise if (e.g. MetaMask has already allowed the connection) if the user is already authorised.

    If the user is isAuthorized do I have to activate the connector again? If I do so I'll get a

    Warning: Suppressed stale connector activation [object Object]
    

    Warning.

    Thanks for your help

    Sebastian

    Reviewed by sebastiandeutsch at 2020-02-09 20:10
  • 6. walletconnect-connector doesn't work in 6.2.8

    Bug Description Package: @web3-react/walletconnect-connector The @walletconnect/ethereum-provider was updated to 1.6 in #255. For some reason now WalletConnect modal closes and opens again after approving connection. Connection does not get established. Also when modal is closed the error is thrown.

    Environment:

    "@web3-react/core": "^6.1.9",
    "@web3-react/walletconnect-connector": "^6.2.8",
    

    Reproduction Unfortunately I don't have time to make contrived example, but here's the problem I'm describing: https://github.com/pancakeswap/pancake-frontend/compare/develop...Chef-Cheems:feature/update-walletconnect?expand=1

    Screencapture of connection attempt

    https://user-images.githubusercontent.com/81824236/139859804-c70e7fc7-672c-4059-8066-6529baec8f9e.mp4

    Expected Behavior Being able to connect via WalletConnect

    Additional Context Latest @walletconnect/ethereum-provider is 1.6.6, maybe its worth updating to that at the same time.

    Reviewed by Chef-Cheems at 2021-11-02 13:53
  • 7. Connect to Wallet Connection with @web3-react/walletconnect-connector shows errors "Cannot read properties of undefined (reading 'connected')"

    Hi, I made connection with Wallet Connection with code bellow but I get error is Cannot read properties of undefined (reading 'connected'). Anyone can help me this issues. Thank you

    `import { UserRejectedRequestError as UserRejectedRequestErrorWalletConnect, WalletConnectConnector, } from '@web3-react/walletconnect-connector'

    import { UnsupportedChainIdError, useWeb3React } from '@web3-react/core'

    const connection = async () => { const { activate } = useWeb3React(); const connector = new WalletConnectConnector({ rpc: { 56: 'https://bsc-dataseed.binance.org/' }, bridge: 'https://bridge.walletconnect.org', qrcode: true, pollingInterval: 10000 }) await activate(connector, async (error) => { if (error instanceof UnsupportedChainIdError) { console.log(error) const network = config.unsupportedChainSetup[config.chainId]; const hasSetup = await switchChain(network ?? { chainId: 0x${parseInt(config.chainId.toString()).toString(16)} }) if (hasSetup) { setError(null) await activate(connector, async () => { setError(${error.message}) }) } else { setError(Unable to connect to required network ${config.chainId}) } } else { if (error instanceof NoEthereumProviderError || error instanceof NoBscProviderError) { setError('No wallet provider was found') } else if ( error instanceof UserRejectedRequestErrorInjected || error instanceof UserRejectedRequestErrorWalletConnect ) { if (connector instanceof WalletConnectConnector) { connector.walletConnectProvider = null } setError('Please authorize to access your account') } else if ((error as any).code === -32002) { setError(Already processing wallet connect requuest, please click on wallet to unlock it!) } else { setError(${error.message}) } } }) } else { setError(Cannot find connector in the connector config) }

    }

    `

    Reviewed by evansben87 at 2022-01-26 09:28
  • 8. Disconnect wallet, but reconnects on refresh.

    Hi,

    I have implemented (using the example) a connection to metamask and it works great. I refresh and after a second then it reconnects! Exactly what I need.

    Now I decided to implement the disconnect. I did, and when I disconnect then it does disconnect and the UI updates but as soon as I refresh then it reconnects the wallet.

    Am I doing something wrong ?

    I notice the demo app also does the same. ( https://codesandbox.io/s/p5b66?file=/pages/index.tsx )

    I was hoping for a method to disconnect permantenly or at least some state so that it knows not to reconnect.

    I am basically using the following from the example app

      // handle logic to eagerly connect to the injected ethereum provider, if it exists and has granted access already
      const triedEager = useEagerConnect()
    
    
      // handle logic to connect in reaction to certain events on the injected ethereum provider, if it exists
      useInactiveListener(!triedEager || !!activatingConnector)
    

    and I have

      const onDisconnect = () => {
        deactivate()
      }
    
    
      return (
        <div>
          <div>ChainId: {chainId}</div>
          <div>Account: {account}</div>
          {active ? (
            <div>✅ </div>
          ) : (
            <div>
            <button type="button" onClick={onClick}>
              Connect
            </button>
    
    
            </div>
          )}
          <button type="button" onClick={onDisconnect}>
            Disconnect
          </button>
        </div>
      )
    
    

    As I say, if I disconnect then the UI updates and it seems I am disconnected - but a refresh then causes it to reconnect.

    Of course, it is the following code that performs that - inside of useEagerConnect

      injected.isAuthorized().then((isAuthorized: boolean) => {
          if (isAuthorized) {
            activate(injected, undefined, true).catch(() => {
              setTried(true)
            })
          } else {
            setTried(true)
          }
        })
    

    So it seems the disconnect doesn't unauthorized ?

    Are there any ways around this ?

    Thanks in advance

    Reviewed by iangregsondev at 2021-07-12 20:22
  • 9. WalletConnect-Connector support more than one chain

    Description Currently there is a restriction than walletconnnect-connector can only have 1 chain invariant(Object.keys(rpc).length === 1, '@walletconnect/web3-provider is broken with >1 chainId, please use 1') https://github.com/NoahZinsmeister/web3-react/blob/v6/packages/walletconnect-connector/src/index.ts#L31

    But this is no longer true, it can support multiple chains easily https://docs.walletconnect.org/quick-start/dapps/web3-provider#rpc-url-mapping

    Additional Context Removing this restriction would alow dapps to use mainnet and testnet as well as other networks

    Reviewed by pmprete at 2021-01-07 19:36
  • 10. Reopening WalletConnect modal doesn't work

    Bug Description

    If a user closes the Walletconnect modal by mistake they can't reopen it unless they reload the page

    Reproduction

    The flow is below

    • A user visits the website
    • Chooses Walletconnect option
    • closes the modal by mistake
    • Chooses the Walletconnect option again (the Walletconnect modal doesn't reopen the user has to reload the page)

    An example can be found using the example directory in the repo. Closing the modal and trying to reopen it doesn't work

    CodeSandbox reproduction

    Steps to reproduce:

    1. Launch the example app
    2. Select the Walletconnect option
    3. Close the modal
    4. Try selecting the Walletconnec option again, doesn't work

    Expected Behavior

    The Walletconnect Modal should relaunch

    Additional Context

    Reviewed by samparsky at 2020-09-09 10:58
  • 11. Consider releasing connectors as separate packages

    Right now, web3-react weighs more than my whole web app. It looks like most of this weight comes from Portis and WalletConnect SDKs. I guess that not everyone will need these and if they do, they can always load them asynchronically to improve app performance.

    What do you think?

    Reviewed by macbem at 2019-04-18 15:16
  • 12. V8 node 18 compatibility

    I am currently on node 18.4.0 but this prevents yarn from executing as the package.jsonspecifics node engine version 14 or 16.

    Will it be compatible with v18 if I add || ^18 or is this not recommended?

    Should I roll back to 16.5.1?

    Thanks in advance!

    Reviewed by JasonT1407 at 2022-06-17 16:53
  • 13. Getting: Error: underlying network changed

    Hi, I'm using web3-react v8 in my app but getting the following error on network change using a select network or directly from metamask:

    index.js?4a96:219 Uncaught (in promise) Error: underlying network changed (event="changed", network={"name":"matic","chainId":137,"ensAddress":null}, detectedNetwork={"name":"homestead","chainId":1,"ensAddress":"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"}, code=NETWORK_ERROR, version=providers/5.6.8)
    

    I'm calling a getBalances() function in order to fetch the user's balances of multi tokens and need to pass the web3-react provider to a multicall function. Bellow my hooks called from my components:

    export const useGetUserAssetsBalances = (assets: any): TokenWithBalance[] => {
      const { account, provider } = useWeb3React();
      const [balances, setBalances] = useState<TokenWithBalance[]>([]);
      const fetchBalances = useCallback(async () => {
        const tokens: Token[] = Object.values(assets);
        let data: TokenWithBalance[] = [];
        if (account && provider) {
          data = (await getMultipleTokenBalancesByMultiCall(
            tokens,
            account,
            provider,
          )) as TokenWithBalance[];
        }
        setBalances(data);
      }, [account, provider, assets]);
    
      useEffect(() => {
        if (account && assets && provider && chainId) {
          fetchBalances();
        }
      }, [account, provider, assets, setBalances, fetchBalances]);
      return balances;
    };
    

    The getMultipleTokenBalancesByMultiCall() is defined as below :

    export const getMultipleTokenBalancesByMultiCall = async (
      tokens: Token[],
      userAddress: string,
      provider: ethers.providers.Provider
    ): Promise<TokenWithBalance[]> => {
      const ethCallProvider = new Provider(provider);
      await ethCallProvider.init();
      const balanceCalls = tokens.map((token) => {
        if (NATIVE[chainId].equals(token)) {
          return ethCallProvider.getEthBalance(userAddress);
        }
        return getERC20Contract_MultiCall(token.address).balanceOf(userAddress);
      });
      const balances = await ethCallProvider?.all(balanceCalls);
      return tokens.map(
        (token, index) =>
          ({
            ...token,
            balance: FixBigNumber.fromWei(
              balances[index].toString(),
              token.decimals
            ),
          } as TokenWithBalance)
      );
    };
    

    I tried to remove the getMultipleTokenBalancesByMultiCall() and just make a await provider?.getNetwork();, but getting the same error.

    I'm using import { useWeb3React } from '@web3-react/core';

    My web3react dependencies are:

        "@coinbase/wallet-sdk": "^3.1.0",
        "@walletconnect/ethereum-provider": "^1.7.8",
        "@web3-react/coinbase-wallet": "8.0.31-beta.0",
        "@web3-react/core": "8.0.30-beta.0",
        "@web3-react/frame": "8.0.17-beta.0",
        "@web3-react/metamask": "8.0.24-beta.0",
        "@web3-react/network": "8.0.23-beta.0",
        "@web3-react/types": "8.0.17-beta.0",
        "@web3-react/walletconnect": "8.0.31-beta.0",
    

    and using the import { Web3ReactProvider } from '@web3-react/core'; that wrap every components in my _app.tsx file

    I don't have any idea on why my provider coming from useWeb3React is not sync with the current network. Do someone has an idea?

    Reviewed by FabienCoutant at 2022-06-17 09:59
  • 14. Linking additional docs in the readme

    I was really struggling to understand this library, and found this article to be an incredible explanation, so if you guys think its applicable to link in the README, feel free to merge

    Reviewed by elenamik at 2022-06-16 20:41
  • 15. How does provider integration with web3 library work now?

    In v6 web3 used to be part of the hook useWeb3React as Library

    Then something like:

    {library} = useWeb3React

    Allowed us to (for example) sign a message: library.eth.personal.sign(...)

    Now when using the web3 library somewhat detached from the react-web3/core, the library does not have a provider.

    signature error Error: Provider not set or invalid
        at Object.InvalidProvider (errors.js:39:1)
        at RequestManager.push.Fm6o.RequestManager.send (index.js:147:1)
        at sendRequest (index.js:624:1)
        at Personal.send [as sign] (index.js:656:1)
        at _callee$ (web3Adapter.ts:8:1)
        at tryCatch (runtime.js:63:1)
        at Generator.invoke [as _invoke] (runtime.js:294:1)
        at Generator.next (runtime.js:119:1)
        at bn.js:3547:1
        at new Promise (<anonymous>)
        at push.vL4m.__awaiter (bn.js:3547:1)
        at Object.web3Sign (web3Adapter.ts:3:1)
        at _callee$ (authService.ts:83:1)
        at tryCatch (runtime.js:63:1)
        at Generator.invoke [as _invoke] (runtime.js:294:1)
        at Generator.next (runtime.js:119:1)
        at fulfilled (batch.js:72:1)
    

    I tried using my library instance:

    import web3 from 'web3'
    
    new web3().setProvider(connector.provider)
    

    But the types are incompatible.

    TS2345: Argument of type 'Provider | undefined' is not assignable to parameter of type 'provider'.   Type 'undefined' is not assignable to type 'provider'.
    

    What is the v8 way to integrate the provider into other functions of the web3 lib?

    Reviewed by fmontserrat at 2022-06-14 16:45
  • 16. Provider in not defined after activating connector

    hello!

    I have metamask connector:

    export const [metaMask, hooks] = initializeConnector((actions) => ( new MetaMask({ actions })));

    and I use in in my component like this:

    const provider = metaMaskHooks.useProvider(); const accounts = metaMaskHooks.useAccounts();

    I want to create login functionality on button click, but provider and accounts are not defined there:

    const onMetaMaskLogin = async () => { await metaMask.activate(); dispatch(loginWithMetamask(provider, accounts)); };

    can I get them inside of this function somehow?

    thank you!

    P.S. I don't want to activate metaMask connector on component mount, just by clicking on button

    Reviewed by YVeselovskyi at 2022-06-14 16:26
  • 17. Add feature: Binance wallet

    Please add Binance wallet support to web3-react as a plugin. @NoahZinsmeister OR If there is any other existing solution to integrate with Binance wallet in web3-react? Please leave comment below

    Reviewed by msghadiri at 2022-06-14 08:05
A simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps

A simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps

Nov 1, 2021
A data-driven, functional, and reactive framework for building Modern Web Apps in JavaScript.
A data-driven, functional, and reactive framework for building Modern Web Apps in JavaScript.

A data-driven, functional, and reactive framework for building Modern Web Apps in JavaScript. It leverages React, inspired by re-frame.

Mar 2, 2022
A frontend Framework for building B2B applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Material Design
A frontend Framework for building B2B applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Material Design

react-admin A frontend Framework for building data-driven applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Materi

Jun 26, 2022
A web framework for building virtual reality experiences (VR Web)
A web framework for building virtual reality experiences (VR Web)

Virtual Reality Made Simple: A-Frame handles the 3D and WebVR boilerplate required to get running across platforms including mobile, desktop, Vive, and Rift

Mar 18, 2022
Hydrogen is a React-based framework for building dynamic, Shopify-powered custom storefronts.
Hydrogen is a React-based framework for building dynamic, Shopify-powered custom storefronts.

Hydrogen is a React-based framework for building dynamic, Shopify-powered custom storefronts.

Jun 19, 2022
A high-performance framework with fine-grained observable-based reactivity for building rich applications

A high-performance framework with fine-grained observable-based reactivity for building rich applications

Jun 17, 2022
🛡️ ⚛️ A simple, scalable, and powerful architecture for building production ready React applications.

??️ ⚛️ A simple, scalable, and powerful architecture for building production ready React applications.

Jun 21, 2022
Build blazing fast, modern apps and websites with React

Gatsby v2 ⚛️ ?? ?? Fast in every way that matters Gatsby is a free and open source framework based on React that helps developers build blazing fast w

Jun 19, 2022
A declarative, efficient, and flexible JavaScript library for building user interfaces.

React · React is a JavaScript library for building user interfaces. Declarative: React makes it painless to create interactive UIs. Design simple view

Jun 20, 2022
The React Framework

Next.js Getting Started Visit https://nextjs.org/learn to get started with Next.js. Documentation Visit https://nextjs.org/docs to view the full docum

Jun 19, 2022
The Full-stack Framework for React and other in Deno.

The Full-stack Framework for React and other in Deno.

Jun 17, 2022
⚡️The Fullstack React Framework — built on Next.js
⚡️The Fullstack React Framework — built on Next.js

⚡️The Fullstack React Framework — built on Next.js

Jun 16, 2022
A most advanced ssr framework support React/Vue2/Vue3 on Earth that implemented serverless-side render specification.
A most advanced ssr framework support React/Vue2/Vue3 on Earth that implemented serverless-side render specification.

A most advanced ssr framework support React/Vue2/Vue3 on Earth that implemented serverless-side render specification.

Jun 18, 2022
⚡️The Fullstack React Framework — built on Next.js — Inspired by Ruby on Rails
⚡️The Fullstack React Framework — built on Next.js — Inspired by Ruby on Rails

⚡️The Fullstack React Framework — built on Next.js — Inspired by Ruby on Rails

Oct 12, 2021
🌟 DataFormsJS 🌟 A minimal JavaScript Framework, standalone React and Web Components, and JSX Compiler for rapid development of high quality websites and single page applications.
🌟 DataFormsJS 🌟 A minimal JavaScript Framework, standalone React and Web Components, and JSX Compiler for rapid development of high quality websites and single page applications.

?? DataFormsJS ?? A minimal JavaScript Framework, standalone React and Web Components, and JSX Compiler for rapid development of high quality websites and single page applications.

Jun 13, 2022
Web App using react framework

waldo.vision This is the website for waldo-anticheat :D Libraries used: React React-router React-router-hash-link React-helmet TODO: improve this list

Nov 12, 2021
Create a SPA project using Mithril JS framework and design layout by JSX syntax and use Typescript and Vite for build system.
Create a SPA project using Mithril JS framework and design layout by JSX syntax and use Typescript and Vite for build system.

Mithril TS(Type script) JSX Create a SPA project using Mithril JS framework and design layout by JSX syntax and use Typescript and Vite for build syst

Feb 22, 2022
Declarative data-fetching and caching framework for REST APIs with React
Declarative data-fetching and caching framework for REST APIs with React

Declarative data-fetching and caching framework for REST APIs with React

Jun 12, 2022