Code Monkey home page Code Monkey logo

web3-react's Introduction

web3-react (beta)

CI

Looking for the prior version of this library? It's available on the v6 branch.

This is a hosted version of example.

Packages

Package Version Size Link
@web3-react/types npm minzip
@web3-react/store npm minzip
@web3-react/core npm minzip
Connectors
@web3-react/eip1193 npm minzip EIP-1193
@web3-react/empty npm minzip
@web3-react/gnosis-safe npm minzip Gnosis Safe
@web3-react/metamask npm minzip MetaMask
@web3-react/network npm minzip
@web3-react/url npm minzip
@web3-react/walletconnect-v2 npm minzip WalletConnect
@web3-react/coinbase-wallet npm minzip Coinbase Wallet
@web3-react-trust-wallet npm minzip Trust Wallet
@avalabs/web3-react-core-connector npm minzip Core Wallet
@venly/web3-react-venly npm minzip Venly

Get Started

  • yarn
  • yarn start

In addition to compiling each package in watch mode, this will also spin up /example on localhost:3000.

Run Tests

  • yarn build
  • yarn test --watch

Publish

  • yarn lerna publish [--dist-tag]

Documentation

This version of web3-react is still in beta, so unfortunately documentation is pretty sparse at the moment. /example, TSDoc comments, and the source code itself are the best ways to get an idea of what's going on. More thorough documentation is a priority as development continues!

Upgrading Connector Dependencies

Some connectors have one or more dependencies that are specific to the connection method in question. For example, the walletconnect connector relies on @walletconnect/ethereum-provider package to handle a lot of the connection logic. Often, you may wish to upgrade to the latest version of a client package, to take advantage of the latest features. web3-react makes the process of upgrading client packages fairly painless by specifying them as peerDependencies. This means that you have to explicitly install client packages, and therefore may transparently switch between any version that agrees with the semver specified in the connector (usually any matching major).

Third-Party Connectors

The decision to publish a connector under the @web3-react namespace is fully up to the discretion of the team. However, third-party connectors are always welcome! This library was designed to be highly modular, and you should be able to draw inspiration from the existing connectors to write your own. That connector can live inside your codebase, or even be published as a standalone package. A selection of third-party connectors that have widespread usage may be featured below, PRs modifying this list are welcome.

Upgrading from v6

While the internals of web3-react have changed fairly dramatically between v6 and v8, the hope is that usage don't have to change too much when upgrading. Once you've migrated to the new connectors and state management patterns, you should be able to use the hooks defined in @web3-react/core, in particular useWeb3React (or usePriorityWeb3React), as more or less drop-in replacements for the v6 hooks. The big benefit in v8 is that hooks are now per-connector, as opposed to global, so no more juggling between connectors/multiple roots!

web3-react's People

Contributors

adrianleb avatar albertbinance avatar alex-miller-0 avatar bpierre avatar brendanww avatar chaitanyapotti avatar cwhinfrey avatar dependabot[bot] avatar grabbou avatar jfrankfurt avatar karllevine avatar kimpers avatar makbari avatar makoto avatar miguelmota avatar mmv08 avatar moodysalem avatar noahzinsmeister avatar pedrouid avatar petejkim avatar pseudomata avatar pwnslinger avatar samajammin avatar sammdec avatar skylarbarrera avatar tarrencev avatar vercy avatar vishnumad avatar vm avatar zzmp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

web3-react's Issues

updating MetaMask state

Hi @NoahZinsmeister!

Sorry for opening another issue here but I cannot still understand well the structure of web3-react and the context which could be fetched from useWebContext(). Here,

import React, { Component, Fragment, useEffect } from "react";
import Web3Provider, { Connectors, useWeb3Context } from "web3-react";

const { InjectedConnector } = Connectors;
const MetaMask = new InjectedConnector();
const connectors = { MetaMask };

function 
function MetaMaskComponent() {
  const context = useWeb3Context();

  useEffect(() => {
    context.setConnector("MetaMask")
  }, []);

  return ({ context.active ? <MyComponent /> : "None" });
}

class App extends Component {
  render() {
    return (
      <Web3Provider connectors={connectors} libraryName="ethers.js">
        <div className="App">
          <MetaMaskComponent />
        </div>
      </Web3Provider>
    );
  }
}

export default App;

Once context.setConnector("MetaMask") called and it sets the context.active as true, and if I logout MetaMask, I wonder what happens in context? Currenty I'm using the unstable version of web3-react (v 3.1.3) and it seems it doesn't update any of context properly, so it keeps still the active as true and connector as MetaMask. Is there any way to render components according to the MetaMask's login status without external reload of the page? In other words, can I know the MetaMask's login status from the connector or context?

web3-react does not always update to current chainID

Bug Description
When switching networks, web3React does not always resolve with the current correct NetworkID/ChainID. I found this in our own custom code but noticed the behavior also in the demo code-sandbox. (Screenshot attached). I am unsure what is causing the problem.

Reproduction
CodeSandbox reproduction

Steps to reproduce:
1.
2.

Expected Behavior
Web3React should return proper ChainId/NetworkId information but sometimes it fails to do so.

Additional Context
Screen Shot 2020-01-29 at 11 17 26 PM

Pending Transactions

Thank you for this awesome library. I was wondering, how would you go about getting a list of an account's pending transactions (submitted transactions waiting to be mined)?

TypeError: library.BatchRequest is not a constructor

I'm trying to load 10 blocks from the chain in a batch: https://ethereum.stackexchange.com/questions/1587/how-can-i-get-the-data-of-the-latest-10-blocks-via-web3-js

const latest = await web3.eth.getBlockNumber()
const blockNumbers = _range(latest - n, latest + 1, 1)
const batch = new web3.eth.BatchRequest()

blockNumbers.forEach((blockNumber) => {
  batch.add(
    web3.eth.getBlock.request(blockNumber, storeLocalCopy)
  )
})

batch.execute()

Loading the first block works with:

/**
   * Loads the latest block number
   */
  const [latestBlockNumber, setLatestBlockNumber] = useState(0);

  useEffect(() => {
    if (active) {
      library
        .getBlockNumber()
        .then(value => {
          setLatestBlockNumber(value);
        })
        .catch(err => {
          console.log(err);
        });
    }
  }, [active]);

However when issuing a const batch = new library.BatchRequest() I'm getting the following error: TypeError: library.BatchRequest is not a constructor

Thank you!

Cannot connect to opera injected crypto wallet

Bug Description
I try to connect to opera crypto wallet (desktop browser) with InjectedConnector, but the only thing I see is an error - TypeError: Cannot read property 'hasOwnProperty' of undefined
The same logic for metamask works great, no problems detected. But connection to opera crypto wallet doesn't work.
Current error was detected with an update of web3-react library update. Previous version connected perfectly with Opera injected crypto wallet, so I think there is some kind of bug

Reproduction
https://codesandbox.io/s/web3-react-v6-8rg3h?fontsize=14&hidenavigation=1&theme=dark

Steps to reproduce:
You can open codesandbox link above in Opera Browser with crypto wallet and push the button "Injected" and then you can see an error in the console

Expected Behavior
It should return a valid connector provider, not an error

Additional Context
Opera browser version: 65.0.3467.78
OS: MacOS Catalina 10.15.1

Detecting unsupported network

What is the pattern for detecting that the user is connected to a network that is not one of the ids passed in supportedNetworks to InjectedConnector?

context.error has Error: Unable to set any valid connector., that seems like a catch-all error.

Thanks!

Guidance on NetworkOnlyConnector

The docs are pretty straightforward, with the exception of NetworkOnlyConnector.

This is my context for InjectedConnector (MetaMask):

InjectedConnector

And NetworkOnlyConnector:

NetworkOnlyConnector

So I receive no account, but that's what I was expecting anyway.

It'd be nice to add more info in the docs about the most practical applications of NetworkOnlyConnector. I reckon that it works best in development, or when you just want to read data from the blockchain. But I'm not sure, since I see it's used in production at Uniswap.

yarn build error

Bug Description

Hi, I wan't to try and use the library, and of course the last version.

I'm under Windows here are the command i used :

git clone https://github.com/NoahZinsmeister/web3-react.git
yarn
yarn bootstrap
yarn build

yarn run v1.19.1
$ lerna run build
lerna notice cli v3.18.4
lerna info Executing command in 15 packages: "yarn run build"
lerna info run Ran npm script 'build' in '@web3-react/types' in 8.2s:
$ tsdx build
✓ Creating entry file 4.2 secs
✓ Building modules 1.5 secs
lerna ERR! yarn run build exited 1 in '@web3-react/abstract-connector'
lerna ERR! yarn run build stdout:
$ tsdx build
✓ Creating entry file 4.9 secs
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

lerna ERR! yarn run build stderr:
(typescript) Error: C:/_CODE/react/web3-react/packages/abstract-connector/src/index.ts(7,8): semantic error TS2307: Cannot find module '@web3-react/types'.
Error: C:/_CODE/react/web3-react/packages/abstract-connector/src/index.ts(7,8): semantic error TS2307: Cannot find module '@web3-react/types'.
    at error (C:\_CODE\react\web3-react\node_modules\rollup\dist\rollup.js:5351:30)
    at throwPluginError (C:\_CODE\react\web3-react\node_modules\rollup\dist\rollup.js:11668:12)
    at Object.error (C:\_CODE\react\web3-react\node_modules\rollup\dist\rollup.js:12637:24)
    at Object.error (C:\_CODE\react\web3-react\node_modules\rollup\dist\rollup.js:11867:38)
    at RollupContext.error (C:\_CODE\react\web3-react\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:17194:30)
    at lodash_3 (C:\_CODE\react\web3-react\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:24958:23)
    at arrayEach (C:\_CODE\react\web3-react\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:534:11)
    at forEach (C:\_CODE\react\web3-react\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:9360:14)
    at printDiagnostics (C:\_CODE\react\web3-react\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:24931:5)
    at Object.transform (C:\_CODE\react\web3-react\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:27373:17)
error Command failed with exit code 1.**

I also have another react beginner question, i've already have started a project how will i integrate the lib? should i just use the directory with and import? of is there a better practice?

Thanks in advance for helping !

Yann

Testing help needed!

I'm not incredibly up to speed on the latest React/JS testing frameworks, and testing this package is particularly challenging due to its reliance on the injected web3 object.

If anyone has an ideas, suggestions, or wants to open PRs around testing, I would be grateful!

doesn't work with latest MetaMask

MetaMask has been updated to 6.4.1 a few days ago, and they something changed the events so that web3-react 5.0.4 doesn't work well any more. It cannot detect the MetaMask login/logout, for example.

Switching to Localhost throws Error

Bug Description
When switching MetaMask to local host, while using an injected connector created thus:

export const injectedConnector = new InjectedConnector({ supportedChainIds: [ 1, 3, 4, 5, 10, 42, 77, 99, 100 ] })

Web3React throws the error. This happens in our own code as well as on the code-sandbox.
Screen Shot 2020-02-01 at 11 24 55 AM

Unhandled Rejection (Error): Invariant failed: chainId loading is not an integer
invariant
node_modules/tiny-invariant/dist/tiny-invariant.esm.js:10
normalizeChainId
src/normalizers.ts:13
  10 |   chainId = chainId.replace(/^Ox/, '0x')
  11 | 
  12 |   const parsedChainId = Number.parseInt(chainId, chainId.trim().substring(0, 2) === '0x' ? 16 : 10)
> 13 |   invariant(!Number.isNaN(parsedChainId), `chainId ${chainId} is not an integer`)
     | ^  14 |   return parsedChainId
  15 | } else {
  16 |   invariant(Number.isInteger(chainId), `chainId ${chainId} is not an integer`)
View compiled
(anonymous function)
src/manager.ts:181
  178 | 
  179 | // updates are handled differently depending on whether the connector is active vs in an error state
  180 | if (!error) {
> 181 |   const chainId = update.chainId === undefined ? undefined : normalizeChainId(update.chainId)
      | ^  182 |   if (chainId !== undefined && !!connector.supportedChainIds && !connector.supportedChainIds.includes(chainId)) {
  183 |     const error = new UnsupportedChainIdError(chainId, connector.supportedChainIds)
  184 |     onError ? onError(error) : dispatch({ type: ActionType.ERROR, payload: { error } })
View compiled
▶ 2 stack frames were collapsed.
InjectedConnector.emitUpdate
src/index.ts:27
  24 |   sortProperties,
  25 |   getAttributeMode,
  26 |   getElementDataset,
> 27 |   getIdElementProperties,
  28 |   getDataElementProperties,
  29 |   createAttributeSelector,
  30 | } from '~/lib/utils';
View compiled
InjectedConnector.handleNetworkChanged
src/index.ts:66
  63 | 
  64 | const feature = element.getAttribute(DATA_FEATURE);
  65 | 
> 66 | if (!feature) {
     | ^  67 |   return console.error(`Feature attribute was not added to the element`);
  68 | }
  69 | 
View compiled
▶ 27 stack frames were collapsed.

Reproduction
CodeSandbox reproduction

Steps to reproduce:
1.
2.

Expected Behavior
Expected to handle the case of using a local network.

Additional Context

Why are HOCs not recommended?

Any solid reasons? My projects are highly based on HOCs and I'm very happy with that. These days many projects offer both hooks, render props and HOCs as interfaces but this is the first time I see someone talk about HOCs -which are the oldest and most established one of those- as being "not recommended".

I'm asking this question not to start something like a flame war or defending functional programming or anything like that. My current app's architecture encourages the use of HOCs as much as possible and I want to know any possible downsides of interacting with this library using HOCs.

Please clarify.

https://github.com/NoahZinsmeister/web3-react#not-recommended---hocs

Missing ethers instance in `library`

From the docs, if we pass the string ethers.js to the libraryName prop of <Web3Provider>, we should then get an instance of ethers in the library prop of the context object returned by useWeb3Context.

But if we look the code sandbox example, this is what is actually returned:

blockNumber: (...)
connection: {url: "http://localhost:8545"}
network: (...)
polling: (...)
pollingInterval: (...)
ready: Promise {<resolved>: {…}}
_balances: {}
_emitted: {block: -2}
_events: [{…}]
_fastQueryDate: 0
_lastBlockNumber: -1
_network: {name: "kovan", chainId: 42, ensAddress: null, _defaultProvider: ƒ}
_poller: 150
_pollingInterval: 4000
_sendAsync: ƒ ()
_web3Provider: Proxy {selectedAddress: "0x7cfa255496a7631f5750f6bd94223e6b1759f23e", networkVersion: "42", _events: {…}, _eventsCount: 3, _maxListeners: 100, …}
_ethersType: "Provider"
__proto__: S

it looks like the low level provider object.

I expected it to be an ethers instance, where I could access methods like getBalance and estimateGas.

Is it supposed to be like this or am I missing something?

Require syntax error when used with Webpack | Connector: Torus

Bug Description
When importing the Torus connector, my webpack is throwing an error to do with internal node modules of Torus.

I'm using react with typescript 3.7+ via webpack

client.js?f33d:189 ./node_modules/random-id/index.js 36:14-21Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

Expected Behavior

Additional Context
All other connectors work except for Authereum for a different reason

Detect noWeb3 and networkId on passive mode

Hi Noah,

I have two questions:

  1. When using the useWeb3Context hook with the provider in passive mode, is it possible for the context to have the networkId?
    (If I use web3.js, I can always get the networkId with
    window.web3.currentProvider.networkVersion)

  2. When using the useWeb3Context hook with the provider in passive mode, is it possible to detect that my user does not have any web3 object in their window?
    (If I use web3.js, I can check window.web3 == null

Edit: Oh wait. Did you remove the passive option?

The error from useWeb3Context is of type Error, which doesn't have a code property - leads to TypeScript warning

When using useWeb3Context from web3-react in a TypeScript-flavored create-react-app app, this error is shown: Property 'code' does not exist on type 'Error'. ts(2339)

Here's a snippet to reproduce it:

import { useWeb3Context, Connectors } from "web3-react";
const { Connector } = Connectors;

const { error } = useWeb3Context();

const blockRender =
    error &&
    error.code &&
    error.code === Connector.errorCodes.UNSUPPORTED_NETWORK;

[v6] Should connectors export a standard name?

Multiple connectors export UserRejectedRequestError under the same name, but the name of the connector itself depends on the package.

I was wondering if it would make sense to export the connector under a standard name, or using the default export? It would make it possible to import a new connector without guessing or checking the code / documentation.

error when using web3.js instead of ethers.js

Hi, @NoahZinsmeister!

When I changed libraryName to web3.js, console shows an uncaught type error as:

Uncaught TypeError: Web3 is not a constructor
    at provider.js:106
    at Web3Provider (provider.js:111)
    at renderWithHooks (react-dom.development.js:13450)
    at updateFunctionComponent (react-dom.development.js:15200)
    at beginWork (react-dom.development.js:16255)
    at performUnitOfWork (react-dom.development.js:20285)
    at workLoop (react-dom.development.js:20326)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
    at invokeGuardedCallback (react-dom.development.js:250)
    at replayUnitOfWork (react-dom.development.js:19509)
    at renderRoot (react-dom.development.js:20439)
    at performWorkOnRoot (react-dom.development.js:21363)
    at performWork (react-dom.development.js:21273)
    at performSyncWork (react-dom.development.js:21247)
    at requestWork (react-dom.development.js:21102)
    at scheduleWork (react-dom.development.js:20915)
    at dispatchAction (react-dom.development.js:14119)
    at manager.js:399

I'm using web-react v5.0.2 and web3.js v1.0.0-beta.52.
Thanks!

Cannot install: "eS11y" not found

I'm in a React project bootstrapped with CRA, but my error is not the same with #27.

warning web3-react > @0x/subproviders > ganache-core > merkle-patricia-tree > level-ws > xtend > [email protected]:
error An unexpected error occurred: "https://registry.yarnpkg.com/eS11y: Not found"

I tried deleting yarn.lock and node_modules, nothing worked. Using yarn 1.17.3 and node 10.15.3

Is this an outage or a known issue?

"Could not find block" thrown from network-provider

Bug Description
Occasionally, the network-provider's web3-provider-engine will throw an error with the message "Could not find block". This is due to a block number being returned from Infura for eth_blockNumber but null being returned for eth_getBlockByNumber for the same number.

Screen Shot 2020-01-21 at 12 00 54 PM
eth_blockNumber request
Screen Shot 2020-01-21 at 12 27 16 PM
eth_blockNumber response
Screen Shot 2020-01-21 at 12 27 23 PM
eth_getBlockByNumber request
Screen Shot 2020-01-21 at 12 27 06 PM
eth_getBlockByNumber response
Screen Shot 2020-01-21 at 12 27 30 PM

Reproduction
This is very hard to reproduce as the error is rare. By running the uniswap frontend locally and refreshing every ~15 secs, you may get the error to appear.

Steps to reproduce:

  1. run the uniswap frontend locally
  2. refresh every ~15 sec

Expected Behavior
The error should be caught and logged.

Additional Context

Managing multiple web3 instances.

Interesting project!

But in my case we have 2 web3 instances connected to different networks (Ethereum and a sidechain). Can I manage multiple connections with web3-react?

conflict with web3 library in Opera Browser with InjectedConnector

Bug Description
Detected bug related to that issue: #57
Now the previous error disappeared, but I can see a new one: OperaWeb3Provider.sendAsync(request, callback) got 1 arguments

Reproduction
The bug happens when you import web3 library somewhere to you application (doesn't matter if you use it or not as a part of getLibrary method of Web3ReactProvider).
here is the example: https://codesandbox.io/s/web3-react-v6-ocmxc
(pay attention to the file src/hooks.js, line 3 where I just imported web3 library previously added to package.json as dependency)

Steps to reproduce:

  1. Install [email protected] to your application
  2. Import it somewhere in your application (you can just import it, even not use somewhere)
  3. Open application in Opera Desktop Browser (65.0.3467.78 for instance)
  4. Try to activate Injected connector

Expected Behavior
Expected Behavior is to activate Injected Connector and to avoid error with web3 library installed and used in application

Additional Context
Opera Desktop Browser (65.0.3467.78)
MacOS Catalina (10.15.1)

walletlink-connector doesn't export `UserRejectedRequestError`

Bug Description

The walletlink-connector package doesn't export a UserRejectedRequestError error like the rest of the walletconnect-connector and injected-connector packages do.

Reproduction
CodeSandbox reproduction

Try importing import { UserRejectedRequestError } from "@web3-react/walletlink-connector" fails.

Steps to reproduce:

  1. import { UserRejectedRequestError } from "@web3-react/walletlink-connector"

Expected Behavior

Package should export this.

Additional Context

InjectedConnector and EIP-1102

InjectedConnector doesn't seem to respect EIP-1102. In other words, it seems like it uses window.web3 as the provider instead of window.ethereum. Is this correct?

I can provide more details if necessary.

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!

Where is the name of a connector set?

Where is the name of a connector set such that it shows up in the context as connectorName?

I have this question both for the connectors that are exported by default from this library and for custom connectors. Thanks!

How to use in Trust Wallet

In the Readme it mentions Trust but I'm unclear on exactly what the connector would be, whether its just the Metamask one or what I should be doing...

Uncaught TypeError: (0 , _react.useReducer) is not a function

Hello, I am experiencing the following issue when attempting to use the package with render-props

Usage

Import React, { Component } from "react"

import { ThemeProvider } from "rimble-ui"
import { Header, NavBar, Footer } from "./Layouts/Utils"
import { MainBody } from "./Components/MainBody"
import Web3Provider from "web3-react"

export default class App extends Component {
 render() {
    return (
      <ThemeProvider>
          <Web3Provider>
          <NavBar />
          <Header />
          <MainBody />
          <Footer />
          </Web3Provider>
     </ThemeProvider>
    )
  }
}

Traceback

index.js:299 Uncaught TypeError: (0 , _react.useReducer) is not a function
    at useWeb3Manager (index.js:299)
    at Web3Provider (index.js:447)
    at mountIndeterminateComponent (react-dom.development.js:15425)
    at beginWork (react-dom.development.js:15956)
    at performUnitOfWork (react-dom.development.js:19102)
    at workLoop (react-dom.development.js:19143)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
    at invokeGuardedCallback (react-dom.development.js:250)
    at replayUnitOfWork (react-dom.development.js:18350)
    at renderRoot (react-dom.development.js:19261)
    at performWorkOnRoot (react-dom.development.js:20165)
    at performWork (react-dom.development.js:20075)
    at performSyncWork (react-dom.development.js:20049)
    at requestWork (react-dom.development.js:19904)
    at scheduleWork (react-dom.development.js:19711)
    at scheduleRootUpdate (react-dom.development.js:20415)
    at updateContainerAtExpirationTime (react-dom.development.js:20441)
    at updateContainer (react-dom.development.js:20509)
    at ReactRoot.push../node_modules/react-dom/cjs/react-dom.development.js.ReactRoot.render (react-dom.development.js:20820)
    at react-dom.development.js:20974
    at unbatchedUpdates (react-dom.development.js:20292)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:20970)
    at Object.render (react-dom.development.js:21037)
    at Module../src/index.js (index.js:6)
    at __webpack_require__ (bootstrap:787)
    at fn (bootstrap:150)
    at Object.0 (serviceWorker.js:135)
    at __webpack_require__ (bootstrap:787)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1

System Information

  • web3-react 1.1.2
  • react 16.7.0

npm complains vulnerabilities

Hi @NoahZinsmeister! Do you have any idea for these vulnerabilities?

$ npm audit
                                                                                
                       === npm audit security report ===                        
                                                                                
┌──────────────────────────────────────────────────────────────────────────────┐
│                                Manual Review                                 │
│            Some vulnerabilities require your attention to resolve            │
│                                                                              │
│         Visit https://go.npm.me/audit-guide for additional guidance          │
└──────────────────────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Moderate      │ Prototype Pollution                                          │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ lodash                                                       │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=4.17.11                                                    │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ web3-react                                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ web3-react > @0x/subproviders > eth-lightwallet >            │
│               │ bitcore-lib > lodash                                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://npmjs.com/advisories/782                             │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low           │ Prototype Pollution                                          │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ lodash                                                       │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=4.17.5                                                     │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ web3-react                                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ web3-react > @0x/subproviders > eth-lightwallet >            │
│               │ bitcore-lib > lodash                                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://npmjs.com/advisories/577                             │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High          │ Arbitrary File Overwrite                                     │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ tar                                                          │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=4.4.2                                                      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ web3-react                                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ web3-react > @0x/subproviders > ganache-core > web3 >        │
│               │ web3-bzz > swarm-js > tar.gz > tar                           │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://npmjs.com/advisories/803                             │
└───────────────┴──────────────────────────────────────────────────────────────┘
found 3 vulnerabilities (1 low, 1 moderate, 1 high) in 1015485 scanned packages
  3 vulnerabilities require manual review. See the full report for details.

I guess they are not from the web3-react itself, but one of them shows "High" vulnerability, so wonder if it can be fixed easily or not.

Thank you!

Internal package not resolving in Authereum connector

Bug Description
When compiling through Webpack for a react + typescript project, I receive the following error

[HMR] bundle has 1 warnings
client.js?f33d:189 ./node_modules/moment/src/lib/locale/locales.jsModule not found: Error: Can't resolve './locale' in '/home/ryann/Documents/Repos/ChainSafe/imploy-connext-poc/WebApp/node_modules/moment/src/lib/locale'

Understanding error bubbling

Description

I'm trying to understand the way errors are handled in web3-react.

In the README:

suppressAndThrowErrors (false by default) controls whether errors, instead of bubbling up to context.error, are instead thrown by this function

But that's not how things work in my app. I get this warning:

Silently handling error from 'Injected': Error: Unsupported Network: 100.

I use a useEffect Hook similar to this one from uniswap-frontend.

I know that you set suppressAndThrowErrors to true and handle errors manually, but I purposefully reverted to the default to see what happens (and use the global context state to handle my wallet modal).

While inspecting the source code, I saw the following in manager.ts:

if (refId.current !== callingTimeRefId + 1) {
  // eslint-disable-next-line no-console
  console.warn(`Silently handling error from '${connectorName}': ${error.toString()}`)
  return
}

Pardon my noobness, but why do you need to do this in the first place? And then, is there any workaround or do I also have to suppress and throw the errors?

Environment

Consider making provider packages independent

Description
Right now, if torus-embed gets a patch release, it requires you to release a new version of web3-react. The better way is for the dapp installing the package to include the corresponding provider package so that updates can be handled better.
What do you think?

Yarn install sub-dependencies issue

Bug Description
Cannot install sub-dependencies

Reproduction
When installing sub-dependencies, I see these errors:

MacBook-Pro:web3-react dai$ yarn bootstrap
yarn run v1.19.2
$ lerna bootstrap
lerna notice cli v3.19.0
lerna info Bootstrapping 15 packages
lerna info Installing external dependencies
lerna ERR! yarn install --mutex network:42424 --non-interactive exited 1 in '@web3-react/ledger-connector'
lerna ERR! yarn install --mutex network:42424 --non-interactive stdout:
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

lerna ERR! yarn install --mutex network:42424 --non-interactive stderr:
warning Waiting for the other yarn instance to finish (92382)
warning Waiting for the other yarn instance to finish (92374)
error /dai/web3-react/packages/ledger-connector/node_modules/sha3: Command failed.
Exit code: 1
Command: node-gyp rebuild
Arguments: 
Directory: /dai/web3-react/packages/ledger-connector/node_modules/sha3
Output:
gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | darwin | x64
gyp info find Python using Python version 2.7.10 found at "/usr/bin/python"
gyp info spawn /usr/bin/python
gyp info spawn args [
gyp info spawn args   '/usr/local/Cellar/node/13.2.0/libexec/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/dai/web3-react/packages/ledger-connector/node_modules/sha3/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/usr/local/Cellar/node/13.2.0/libexec/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/dai/Library/Caches/node-gyp/13.2.0/include/node/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/dai/Library/Caches/node-gyp/13.2.0',
gyp info spawn args   '-Dnode_gyp_dir=/usr/local/Cellar/node/13.2.0/libexec/lib/node_modules/npm/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=/dai/Library/Caches/node-gyp/13.2.0/<(target_arch)/node.lib',
gyp info spawn args   '-Dmodule_root_dir=/dai/web3-react/packages/ledger-connector/node_modules/sha3',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.'
gyp info spawn args ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
  CXX(target) Release/obj.target/sha3/src/addon.o
In file included from ../src/addon.cpp:9:
In file included from ../src/KeccakNISTInterface.h:17:
../src/KeccakSponge.h:23:9: warning: 'ALIGN' macro redefined [-Wmacro-redefined]
#define ALIGN __attribute__ ((aligned(32)))
        ^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/i386/param.h:83:9: note: previous definition is here
#define ALIGN(p)        __DARWIN_ALIGN(p)
        ^
../src/addon.cpp:83:11: error: no matching member function for call to 'Set'
                target->Set(className, f);
                ~~~~~~~~^~~
/dai/Library/Caches/node-gyp/13.2.0/include/node/v8.h:3547:37: note: candidate function not viable: requires 3 arguments, but 2 were provided
  V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
                                    ^
/dai/Library/Caches/node-gyp/13.2.0/include/node/v8.h:3550:37: note: candidate function not viable: requires 3 arguments, but 2 were provided
  V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
                                    ^
1 warning and 1 error generated.
make: *** [Release/obj.target/sha3/src/addon.o] Error 1
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/Cellar/node/13.2.0/libexec/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:194:23)
gyp ERR! stack     at ChildProcess.emit (events.js:210:5)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:270:12)
gyp ERR! System Darwin 18.7.0
gyp ERR! command "/usr/local/Cellar/node/13.2.0/bin/node" "/usr/local/Cellar/node/13.2.0/libexec/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /dai/web3-react/packages/ledger-connector/node_modules/sha3
gyp ERR! node -v v13.2.0
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok
Process stalled
Active handles:
  - Socket
  - Socket
  - Socket
  - Socket
  - Socket
  - ChildProcess
  - Socket
  - Socket
  - ChildProcess
  - Socket
  - Socket
  - ChildProcess
  - Socket
  - Socket
  - ChildProcess

lerna ERR! yarn install --mutex network:42424 --non-interactive exited 1 in '@web3-react/ledger-connector'
lerna WARN complete Waiting for 7 child processes to exit. CTRL-C to exit immediately.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

yarn version: 1.19.2
node version: v13.2.0
macOS : 10.14.6

Steps to reproduce:
git clone https://github.com/NoahZinsmeister/web3-react.git
yarn
yarn bootstrap

Expected Behavior
Sub-dependencies install without error

Additional Context

Using WalletConnectConnector

I set up web3-react with WalletConnector but I'm not getting the modal with the QR. I guess I can do it using context.connector.walletConnector and then following the instructions in WalletConnect docs, but I thought that the web3-react connector would handle that for me. Am I missing something here?

Thanks!

What happened to web3Hooks?

Projects using older versions of this library make use of several hooks that were found in src/web3Hooks.js at one point, including useTransactionManager and useSignPersonalManager. These functionalities seem pretty core to any real web3 frontend, so I was curios about the decision to remove them or if it was replaced somehow.

Cannot install in clean CRA project

Tried to install it into a clean create-react-app, but it fails.

Steps to repro
Install/update create-react-app
Create new project: npx create-react-app web3 --typescript
npm install web3-react
npm run build

Expect that that should be enough to run the solution.

Result
`npm ERR! path /Users/wslyvh/Documents/Code/Test/web3/node_modules/ganache-core/node_modules/web3-providers-ws/node_modules/websocket
npm ERR! code EISGIT
npm ERR! git /Users/wslyvh/Documents/Code/Test/web3/node_modules/ganache-core/node_modules/web3-providers-ws/node_modules/websocket: Appears to be a git repo or submodule.
npm ERR! git /Users/wslyvh/Documents/Code/Test/web3/node_modules/ganache-core/node_modules/web3-providers-ws/node_modules/websocket
npm ERR! git Refusing to remove it. Update manually,
npm ERR! git or move it out of the way first.

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/wslyvh/.npm/_logs/2019-08-08T14_34_50_685Z-debug.log`

Workaround
Delete & clean node_modules (specifically node_modules/ganache-core/node_modules/web3-providers-ws/node_modules/websocket).

How can I make connection automatically?

Hi, @NoahZinsmeister again!

I made my first react-app successfully connected when I login MetaMask. now my app has the codes:
App.js:

import React, { Component } from "react";
import Web3Provider, { Connectors, useWeb3Context } from "web3-react";

import './App.css';
import { Web3Unavailable, AccountUnavailable } from "./Error";

const { MetaMaskConnector } = Connectors;
const MetaMask = new MetaMaskConnector();
const connectors = { MetaMask };

function MyComponent() {
  const context = useWeb3Context();
  const ether = context.library;

  React.useEffect(() => {
    context.setConnector("MetaMask")
  }, []);
  console.log(context);

  return (
    <React.Fragment>
      {context.active ? (
        <React.Fragment>
          <p>Active Connector: {context.connectorName || "None"}</p>
          <p>Account: {context.account || "None"}</p>
          <p>Network ID: {context.networkId || "None"}</p>
          <p>test: {ether.s} </p>
        </React.Fragment>
      ) : (
        <React.Fragment>
          <Web3Unavailable />
        </React.Fragment>
      )}
      {context.error && <p>{context.error.toString()}</p>}
    </React.Fragment>
  );
}

class App extends Component {
  render() {
    return (
      <Web3Provider connectors={connectors} libraryName="ethers.js">
        <div className="App">
          <MyComponent />
        </div>
      </Web3Provider>
    );
  }
}

export default App;

So I plan to use only MetaMaskConnector and handle all connection using it. If the MetaMask is not installed or not logged in, it shows some Error page.
Most of the components are working as I expected, but on the error page, it doesn't connect automatically when I logged in MetaMask using its plugin window.
Can you advise me how to do so?

One more thing is, how can I access the ether's current provider? I want to make some button to make transfer or something. But I'm not so familiar with the latest javascript and to deal with the context as well.

Thank you!

Can I see any simple example react app?

I'm a newbie of react and web3. As trying to make my first react app using this package but it shows a vacant page, so it will be great help to see any kind of example I can refer to. Could you provide any simple example from the scratch?

Why does Uniswap use custom NetworkOnlyConnector and InjectedConnector rather than the ones from this lib?

Why does Uniswap (a high-profile example use case for this library) use custom NetworkOnlyConnector and InjectedConnector connectors rather than the ones from this lib?

exported connectors from web3-react including "network only" and "injected"

network only (e.g. accountless Infura/Etherscan API)

network only in web3-react
network only in uniswap-frontend

injected (e.g. MetaMask)

injected in web3-react
injected in uniswap-frontend

It seems that Uniswap ought to be able to pass in minimal config if any to the ones from this lib without too much boilerplate.

Thanks!

Why the components are called twice?

Hi @NoahZinsmeister!

This is very basic questions to understand how your library and the React operate; when I run the components, the subcomponents wrapped with Web3Provider called twice:

import React, { Fragment, useState, useEffect } from "react";
import Web3Provider, { Connectors, useWeb3Context } from "web3-react";

import './App.css';
import { Web3Unavailable, AccountUnavailable } from "./Error";
import NetworkInfo from "./NetworkInfo";
import AccountInfo from "./AccountInfo";

const { InjectedConnector } = Connectors;
const MetaMask = new InjectedConnector();
const connectors = { MetaMask };

function MyComponent() {
  const context = useWeb3Context();

  const checkSigner = () => {
    return context.library.getSigner(context.account);
  }
  const [signer, setSigner] = useState(checkSigner());

  useEffect(() => {
    setSigner(checkSigner());
  }, [context]);

  const myContext = {
    ...context,
    signer: signer
  }
  console.log(myContext);

  return (
    context.account ? (
      <Fragment>
        {/*
        <NetworkInfo context={myContext}/>
        <br />
        <AccountInfo context={myContext} />
        */}
      </Fragment>
    ) : <AccountUnavailable />
  );
}

function MetaMaskComponent() {
  const context = useWeb3Context();

  useEffect(() => {
    context.active || context.setConnector("MetaMask");
    console.log("MetaMaskComponent");
  }, [context]);

  return (context.active ? <MyComponent /> : <Web3Unavailable />);
}

export default function App() {
  return (
    <Web3Provider connectors={connectors} libraryName="ethers.js">
      <div className="App">
        <MetaMaskComponent />
      </div>
    </Web3Provider>
  );
}

image

As you can see, the console msg MetaMaskComponent called twice even though there is no change of context. I don't know well about the React's rendering and the hooks when useEffect() is executed. Could you help me to understand it?

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.