@web3-react/core#useWeb3React JavaScript Examples

The following examples show how to use @web3-react/core#useWeb3React. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.js    From dshop with MIT License 7 votes vote down vote up
export function useWeb3Manager() {
  const injectedWeb3React = useWeb3React()
  const networkWeb3React = useWeb3React('network')
  const tried = useEagerConnect()
  const { active, chainId } = injectedWeb3React

  useEffect(() => {
    if (!tried) return
    if (!active || chainId !== defaultChainId) {
      networkWeb3React.activate(networkConnector)
    }
  }, [tried, active, chainId])

  const ret = pick(injectedWeb3React, allFields)
  ret.activate = () => injectedWeb3React.activate(injectedConnector)
  // ret.activate = () => injectedWeb3React.activate(walletConnectConnector)

  if (!active || chainId !== defaultChainId) {
    assign(ret, pick(networkWeb3React, activeFields))
    ret.isNetwork = true
    if (chainId !== defaultChainId) {
      ret.desiredNetwork =
        defaultChainId === 1
          ? 'Mainnet'
          : defaultChainId === 4
          ? 'Rinkeby'
          : `Chain ID ${defaultChainId}`
    }
  }

  return ret
}
Example #2
Source File: index.js    From pine-interface with GNU General Public License v3.0 7 votes vote down vote up
export default function WalletModal({ toggleWalletModal, isOpen, ENSName }) {
  // important that these are destructed from the account-specific web3-react context
  const { active, account, connector, activate, error } = useWeb3React()

  const [walletView, setWalletView] = useState(WALLET_VIEWS.ACCOUNT)

  const [pendingWallet, setPendingWallet] = useState()

  const [pendingError, setPendingError] = useState()

  // always reset to account view
  useEffect(() => {
    if (isOpen) {
      setPendingError(false)
      setWalletView(WALLET_VIEWS.ACCOUNT)
    }
  }, [isOpen])

  // close modal when a connection is successful
  const activePrevious = usePrevious(active)
  const connectorPrevious = usePrevious(connector)
  useEffect(() => {
    if (isOpen && ((active && !activePrevious) || (connector && connector !== connectorPrevious && !error))) {
      setWalletView(WALLET_VIEWS.ACCOUNT)
    }
  }, [setWalletView, active, error, connector, isOpen, activePrevious, connectorPrevious])

  const tryActivation = async connector => {
    let name = ''
    Object.keys(SUPPORTED_WALLETS).map(key => {
      if (connector === SUPPORTED_WALLETS[key].connector) {
        return (name = SUPPORTED_WALLETS[key].name)
      }
      return true
    })
    // log selected wallet
    ReactGA.event({
      category: 'Wallet',
      action: 'Change Wallet',
      label: name
    })
    setPendingWallet(connector) // set wallet for pending view
    setWalletView(WALLET_VIEWS.PENDING)

    // if the connector is walletconnect and the user has already tried to connect, manually reset the connector
    if (
      connector instanceof WalletConnectConnector &&
      connector.walletConnectProvider &&
      connector.walletConnectProvider.wc.uri
    ) {
      connector.walletConnectProvider = undefined
    }

    activate(connector, undefined, true).catch(error => {
      if (error instanceof UnsupportedChainIdError) {
        activate(connector) // a little janky...can't use setError because the connector isn't set
      } else {
        setPendingError(true)
      }
    })
  }

  // close wallet modal if fortmatic modal is active
  useEffect(() => {
    fortmatic.on(OVERLAY_READY, () => {
      toggleWalletModal()
    })
  }, [toggleWalletModal])

  // get wallets user can switch too, depending on device/browser
  function getOptions() {
    const isMetamask = window.ethereum && window.ethereum.isMetaMask
    return Object.keys(SUPPORTED_WALLETS).map(key => {
      const option = SUPPORTED_WALLETS[key]
      // check for mobile options
      if (isMobile) {
        //disable portis on mobile for now
        if (option.connector === portis) {
          return null
        }

        if (!window.web3 && !window.ethereum && option.mobile) {
          return (
            <Option
              onClick={() => {
                option.connector !== connector && !option.href && tryActivation(option.connector)
              }}
              id={`connect-${key}`}
              key={key}
              active={option.connector && option.connector === connector}
              color={option.color}
              link={option.href}
              header={option.name}
              subheader={null}
              icon={require('../../assets/images/' + option.iconName)}
            />
          )
        }
        return null
      }

      // overwrite injected when needed
      if (option.connector === injected) {
        // don't show injected if there's no injected provider
        if (!(window.web3 || window.ethereum)) {
          if (option.name === 'MetaMask') {
            return (
              <Option
                id={`connect-${key}`}
                key={key}
                color={'#E8831D'}
                header={'Install Metamask'}
                subheader={null}
                link={'https://metamask.io/'}
                icon={MetamaskIcon}
              />
            )
          } else {
            return null //dont want to return install twice
          }
        }
        // don't return metamask if injected provider isn't metamask
        else if (option.name === 'MetaMask' && !isMetamask) {
          return null
        }
        // likewise for generic
        else if (option.name === 'Injected' && isMetamask) {
          return null
        }
      }

      // return rest of options
      return (
        !isMobile &&
        !option.mobileOnly && (
          <Option
            id={`connect-${key}`}
            onClick={() => {
              option.connector === connector
                ? setWalletView(WALLET_VIEWS.ACCOUNT)
                : !option.href && tryActivation(option.connector)
            }}
            key={key}
            active={option.connector === connector}
            color={option.color}
            link={option.href}
            header={option.name}
            subheader={null} //use option.descriptio to bring back multi-line
            icon={require('../../assets/images/' + option.iconName)}
          />
        )
      )
    })
  }

  function getModalContent() {
    if (error) {
      return (
        <UpperSection>
          <CloseIcon onClick={toggleWalletModal}>
            <CloseColor />
          </CloseIcon>
          <HeaderRow>{error instanceof UnsupportedChainIdError ? 'Wrong Network' : 'Error connecting'}</HeaderRow>
          <ContentWrapper>
            {error instanceof UnsupportedChainIdError ? (
              <h5>Please connect to the appropriate Ethereum network.</h5>
            ) : (
              'Error connecting. Try refreshing the page.'
            )}
          </ContentWrapper>
        </UpperSection>
      )
    }
    if (account && walletView === WALLET_VIEWS.ACCOUNT) {
      return (
        <AccountDetails
          toggleWalletModal={toggleWalletModal}
          ENSName={ENSName}
          openOptions={() => setWalletView(WALLET_VIEWS.OPTIONS)}
        />
      )
    }
    return (
      <UpperSection>
        <CloseIcon onClick={toggleWalletModal}>
          <CloseColor />
        </CloseIcon>
        {walletView !== WALLET_VIEWS.ACCOUNT ? (
          <HeaderRow color="blue">
            <HoverText
              onClick={() => {
                setPendingError(false)
                setWalletView(WALLET_VIEWS.ACCOUNT)
              }}
            >
              Back
            </HoverText>
          </HeaderRow>
        ) : (
          <HeaderRow>
            <HoverText>Connect to a wallet</HoverText>
          </HeaderRow>
        )}
        <ContentWrapper>
          {walletView === WALLET_VIEWS.PENDING ? (
            <PendingView
              connector={pendingWallet}
              error={pendingError}
              setPendingError={setPendingError}
              tryActivation={tryActivation}
            />
          ) : (
            <OptionGrid>{getOptions()}</OptionGrid>
          )}
          {walletView !== WALLET_VIEWS.PENDING && (
            <Blurb>
              <span>New to Ethereum? &nbsp;</span>{' '}
              <Link href="https://ethereum.org/use/#3-what-is-a-wallet-and-which-one-should-i-use">
                Learn more about wallets
              </Link>
            </Blurb>
          )}
        </ContentWrapper>
      </UpperSection>
    )
  }

  return (
    <Modal isOpen={isOpen} onDismiss={toggleWalletModal} minHeight={null} maxHeight={90}>
      <Wrapper>{getModalContent()}</Wrapper>
    </Modal>
  )
}
Example #3
Source File: Authenticate.jsx    From locked.fyi with MIT License 7 votes vote down vote up
Authenticate = () => {
  const { activate } = useWeb3React()
  const injectedConnector = new InjectedConnector({
    supportedChainIds: [1, 3, 4, 5, 42],
  })

  const walletConnectConnector = new WalletConnectConnector({
    rpc: {
      1: "https://eth-mainnet.alchemyapi.io/v2/GUEohLZ1A5Sv0e5mnfOu0lvF6kwfgkyc",
    },
    bridge: "https://bridge.walletconnect.org",
    qrcode: true,
    pollingInterval: 12000,
  })

  return (
    <Buttons>
      <AuthenticateButton onClick={() => activate(injectedConnector)}>
        Log-in
      </AuthenticateButton>
      <WalletConnectButton onClick={() => activate(walletConnectConnector)}>
        <Qr height={20} width={20} />
      </WalletConnectButton>
    </Buttons>
  )
}
Example #4
Source File: _Helpers.js    From acy-dex-interface with MIT License 6 votes vote down vote up
export function useChainId() {
  let { chainId } = useWeb3React();

  if (!chainId) {
    const chainIdFromLocalStorage = localStorage.getItem(
      SELECTED_NETWORK_LOCAL_STORAGE_KEY
    );
    if (chainIdFromLocalStorage) {
      chainId = parseInt(chainIdFromLocalStorage);
      if (!chainId) {
        // localstorage value is invalid
        localStorage.removeItem(SELECTED_NETWORK_LOCAL_STORAGE_KEY);
      }
    }
  }

  if (!chainId || !supportedChainIds.includes(chainId)) {
    chainId = DEFAULT_CHAIN_ID;
  }
  return { chainId };
}
Example #5
Source File: hooks.js    From semaphore_auth with MIT License 6 votes vote down vote up
useProofOfBurn = () => {
  const { library, active } = useWeb3React()

  if (active) {
    return new ethers.Contract(
      proofOfBurnAddress,
      ProofOfBurnABI,
      library.getSigner()
    )
  } else {
    return null
  }
}
Example #6
Source File: index.js    From Artion-Client with GNU General Public License v3.0 6 votes vote down vote up
TxButton = ({ onClick, children, ...rest }) => {
  const dispatch = useDispatch();
  const { chainId } = useWeb3React();

  const handleClick = e => {
    if (chainId) {
      onClick(e);
    } else {
      dispatch(ModalActions.showConnectWalletModal());
    }
  };

  return (
    <div {...rest} onClick={handleClick}>
      {children}
    </div>
  );
}
Example #7
Source File: utils.js    From dshop with MIT License 6 votes vote down vote up
// const walletConnectConnector = new WalletConnectConnector({
//   rpc: { 1: atob(mainnet) },
//   bridge: 'https://bridge.walletconnect.org',
//   qrcode: true,
//   pollingInterval: 12
// })

export function useEagerConnect() {
  const { activate, active, chainId, connector } = useWeb3React()
  const networkWeb3React = useWeb3React('network')
  const [tried, setTried] = useState(false)
  useEffect(() => {
    let stale
    injectedConnector.isAuthorized().then((isAuthorized) => {
      if (stale) return
      if (isAuthorized) {
        activate(injectedConnector, undefined, true).catch(() => {
          setTried(true)
          networkWeb3React.activate(networkConnector)
        })
      } else {
        setTried(true)
        networkWeb3React.activate(networkConnector)
      }
    })
    return () => (stale = true)
  }, [])

  useEffect(() => {
    if (tried && connector !== injectedConnector && !networkWeb3React.active) {
      networkWeb3React.activate(networkConnector)
    }
  }, [active, connector, chainId, tried])

  useEffect(() => {
    if (!tried && active) {
      setTried(true)
    }
  }, [tried, active])

  return tried
}
Example #8
Source File: hooks.jsx    From crv.finance with MIT License 6 votes vote down vote up
export function useEagerConnect() {
  const { activate, active } = useWeb3React();

  const [tried, setTried] = useState(false);

  useEffect(() => {
    injected.isAuthorized().then(isAuthorized => {
      if (isAuthorized) {

        activate(injected, undefined, true).catch(() => {
          setTried(true);
        });
      } else {
        setTried(true);
      }
    });
  }, [activate]); // intentionally only running on mount (make sure it's only mounted once :))

  // if the connection worked, wait until we get confirmation of that to flip the flag
  useEffect(() => {
    if (!tried && active) {
      setTried(true);
    }
  }, [tried, active]);

  return tried;
}
Example #9
Source File: index.js    From sorbet-finance with GNU General Public License v3.0 6 votes vote down vote up
export function OrdersHistory() {
  const { account, chainId } = useWeb3React()
  const orders = usePastOrders(account, chainId)
  return orders.length > 0 ? (
    <>
      <p style={{ marginTop: '40px', fontSize: '24px' }}>History</p>
      {orders.map((order) => (
        <PastOrderCard key={order.id} data={order} />
      ))}
    </>
  ) : null
}
Example #10
Source File: index.js    From pine-interface with GNU General Public License v3.0 6 votes vote down vote up
export function OrdersHistory() {
  const { account, chainId } = useWeb3React()
  const orders = usePastOrders(account, chainId)
  return orders.length > 0 ? (
    <>
      <p style={{ marginTop: '40px', fontSize: '24px' }}>History</p>
      {orders.map(order => (
        <PastOrderCard key={order.id} data={order} />
      ))}
    </>
  ) : null
}
Example #11
Source File: Pure.js    From pure.finance with MIT License 6 votes vote down vote up
PureContextProvider = function ({ children }) {
  const { active, library, account } = useWeb3React()
  const [merkle, setMerkle] = useState({})
  const [sablier, setSablier] = useState({})
  const [tokenApprovals, setTokenApprovals] = useState(null)
  const [erc20, setErc20] = useState()

  useEffect(
    function () {
      if (active) {
        setMerkle(createMerkle(library, { from: account }))
        setSablier(createSablier(library, { from: account }))
        setTokenApprovals(createTokenApprovals(library, { from: account }))
        setErc20(
          () => address => createErc20(library, address, { from: account })
        )
      }
    },
    [active, library, account]
  )

  return (
    <PureContext.Provider value={{ erc20, merkle, sablier, tokenApprovals }}>
      {children}
    </PureContext.Provider>
  )
}
Example #12
Source File: Layout.jsx    From locked.fyi with MIT License 6 votes vote down vote up
Layout = ({ children }) => {
  const { account } = useWeb3React()
  const { loading } = useBox(account)

  return (
    <Page>
      <Header>
        <h1>
          <Link to="/">Locked.fyi</Link>
        </h1>
        <Nav right>
          {loading && <Loading />}
          {!loading && !account && <Authenticate />}
          {!loading && account && <ConnectedUser address={account} />}
        </Nav>
        <Nav>
          <StyledLink to={writePath()}>
            <WriteButton>Write</WriteButton>
          </StyledLink>
        </Nav>
      </Header>

      <Body>{children}</Body>
    </Page>
  )
}
Example #13
Source File: ContractManager.js    From lrc-staking-dapp with MIT License 6 votes vote down vote up
ContractManager = () => {
  const language = useSelector((state) => state.settings.language);
  const stakingContract = useSelector((state) => state.staking.contract);
  const feeContract = useSelector((state) => state.fee.contract);
  const tokenContract = useSelector((state) => state.token.contract);
  const walletAddress = useSelector((state) => state.settings.walletAddress);
  const { library } = useWeb3React();

  const messages = languageProvider[language];

  if (!walletAddress.value || !library) return (<Redirect exact from="/" to="/login" />);

  if (!stakingContract || !feeContract
    || !tokenContract) return (<SuspenseLoading messages={messages} />);

  return (
    <Card className="card-box mb-4">
      <span className="ribbon-angle ribbon-angle--top-left ribbon-primary">
        <small><a href="https://twitter.com/NolanVanmoortel" target="_blank" rel="noopener noreferrer" style={{ color: 'white' }}>twitter</a></small>
      </span>
      <Grid container spacing={4}>
        <Grid item xs={12} lg={5}>
          <div className="p-4 text-center">
            <ProfileContainer />
          </div>
        </Grid>
        <Grid item xs={12} lg={7}>
          <div className="hero-wrapper bg-composed-wrapper h-100 rounded-right bg-secondary">
            <div className="flex-grow-1 w-100 d-flex align-items-center justify-content-center px-4">
              <Action />
            </div>
          </div>
        </Grid>
      </Grid>
    </Card>
  );
}
Example #14
Source File: index.js    From uniswap-v1-frontend with GNU General Public License v3.0 5 votes vote down vote up
export default function Web3ReactManager({ children }) {
  const { t } = useTranslation()
  const { active } = useWeb3React()
  const { active: networkActive, error: networkError, activate: activateNetwork } = useWeb3React(NetworkContextName)

  // try to eagerly connect to an injected provider, if it exists and has granted access already
  const triedEager = useEagerConnect()

  // after eagerly trying injected, if the network connect ever isn't active or in an error state, activate itd
  // TODO think about not doing this at all
  useEffect(() => {
    if (triedEager && !networkActive && !networkError && !active) {
      activateNetwork(network)
    }
  }, [triedEager, networkActive, networkError, activateNetwork, active])

  // 'pause' the network connector if we're ever connected to an account and it's active
  useEffect(() => {
    if (active && networkActive) {
      network.pause()
    }
  }, [active, networkActive])

  // 'resume' the network connector if we're ever not connected to an account and it's active
  useEffect(() => {
    if (!active && networkActive) {
      network.resume()
    }
  }, [active, networkActive])

  // when there's no account connected, react to logins (broadly speaking) on the injected provider, if it exists
  useInactiveListener(!triedEager)

  // handle delayed loader state
  const [showLoader, setShowLoader] = useState(false)
  useEffect(() => {
    const timeout = setTimeout(() => {
      setShowLoader(true)
    }, 600)

    return () => {
      clearTimeout(timeout)
    }
  }, [])

  // on page load, do nothing until we've tried to connect to the injected connector
  if (!triedEager) {
    return null
  }

  // if the account context isn't active, and there's an error on the network context, it's an irrecoverable error
  if (!active && networkError) {
    return (
      <MessageWrapper>
        <Message>{t('unknownError')}</Message>
      </MessageWrapper>
    )
  }

  // if neither context is active, spin
  if (!active && !networkActive) {
    return showLoader ? (
      <MessageWrapper>
        <SpinnerWrapper src={Circle} />
      </MessageWrapper>
    ) : null
  }

  return children
}
Example #15
Source File: _Helpers.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useEagerConnect(setActivatingConnector) {
  const { activate, active } = useWeb3React();

  const [tried, setTried] = useState(false);

  useEffect(() => {
    (async function() {
      let shouldTryWalletConnect = false;
      try {
        // naive validation to not trigger Wallet Connect if data is corrupted
        const rawData = localStorage.getItem(WALLET_CONNECT_LOCALSTORAGE_KEY);
        if (rawData) {
          const data = JSON.parse(rawData);
          if (data && data.connected) {
            shouldTryWalletConnect = true;
          }
        }
      } catch (ex) {
        if (ex instanceof SyntaxError) {
          // rawData is not a valid json
          clearWalletConnectData();
        }
      }

      if (shouldTryWalletConnect) {
        try {
          const connector = getWalletConnectConnector();
          setActivatingConnector(connector);
          await activate(connector, undefined, true);
          // in case Wallet Connect is activated no need to check injected wallet
          return;
        } catch (ex) {
          // assume data in localstorage is corrupted and delete it to not retry on next page load
          clearWalletConnectData();
        }
      }

      try {
        const connector = getInjectedConnector();
        const authorized = await connector.isAuthorized();
        if (authorized) {
          setActivatingConnector(connector);
          await activate(connector, undefined, true);
        }
      } catch (ex) {}

      setTried(true);
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // intentionally only running on mount (make sure it's only mounted once :))

  // if the connection worked, wait until we get confirmation of that to flip the flag
  useEffect(() => {
    if (!tried && active) {
      setTried(true);
    }
  }, [tried, active]);

  return tried;
}
Example #16
Source File: index.js    From semaphore_auth with MIT License 5 votes vote down vote up
Activation = () => {
  const { activate, active, account } = useWeb3React()
  const [error, setError] = useState(null)

  const connectMetaMask = async () => {
    try {
      await activate(MetaMask, undefined, true)
    } catch (err) {
      setError(err)
    }
  }

  if (!active && !error) {
    return (
      <>
        <p>
          Supported Network: <strong>{supportedNetworkName}</strong>{' '}
        </p>
        <p>
          Please connect to MetaMask, we are about to read/write some
          information on the contract.
        </p>
        <button className='button is-primary' onClick={connectMetaMask}>
          Connect MetaMask
        </button>
      </>
    )
  } else if (error) {
    //error
    return <p className='has-text-danger'>{getErrorMessage(error)}</p>
  } else {
    // success
    return (
      <>
        <h1>Loading sucess</h1>
        <p>{account}</p>
      </>
    )
  }
}
Example #17
Source File: index.js    From Artion-Client with GNU General Public License v3.0 5 votes vote down vote up
export default function Web3ReactManager({ children }) {
  const { active } = useWeb3React();
  const {
    active: networkActive,
    error: networkError,
    activate: activateNetwork,
  } = useWeb3React(NetworkContextName);

  // try to eagerly connect to an injected provider, if it exists and has granted access already
  const triedEager = useEagerConnect();

  // after eagerly trying injected, if the network connect ever isn't active or in an error state, activate itd
  useEffect(() => {
    if (triedEager && !networkActive && !networkError && !active) {
      activateNetwork(network);
    }
  }, [triedEager, networkActive, networkError, activateNetwork, active]);

  // when there's no account connected, react to logins (broadly speaking) on the injected provider, if it exists
  useInactiveListener(!triedEager);

  // handle delayed loader state
  const [showLoader, setShowLoader] = useState(false);
  useEffect(() => {
    const timeout = setTimeout(() => {
      setShowLoader(true);
    }, 600);

    return () => {
      clearTimeout(timeout);
    };
  }, []);
  console.log(showLoader);

  // on page load, do nothing until we've tried to connect to the injected connector
  if (!triedEager) {
    return null;
  }

  // if the account context isn't active, and there's an error on the network context, it's an irrecoverable error
  // if (!active && networkError) {
  //   return (
  //     <div className="flex items-center justify-center h-80">
  //       <div className="text-secondary">
  //         {`Oops! An unknown error occurred. Please refresh the page, or visit from another browser or device`}
  //       </div>
  //     </div>
  //   );
  // }

  // if neither context is active, spin
  // if (!active && !networkActive) {
  //   return showLoader ? (
  //     <div className="flex items-center justify-center h-80">
  //       <Loader />
  //     </div>
  //   ) : null;
  // }

  return children;
}
Example #18
Source File: history.js    From origin-dollar with MIT License 5 votes vote down vote up
export default function History({ locale, onLocale }) {
  const { active } = useWeb3React()

  return (
    <>
      <Layout locale={locale} onLocale={onLocale} dapp>
        <Nav dapp page={'history'} locale={locale} onLocale={onLocale} />
        <div className="home d-flex flex-column">
          <BalanceHeader />
          {active && <TransactionHistory />}
          {!active && (
            <div className="empty-placeholder d-flex flex-column align-items-center justify-content-start">
              <img src={assetRootPath('/images/wallet-icons.svg')} />
              <div className="header-text">
                {fbt('No wallet connected', 'Disconnected dapp message')}
              </div>
              <div className="subtext">
                {fbt(
                  'Please connect an Ethereum wallet',
                  'Disconnected dapp subtext'
                )}
              </div>
              <GetOUSD primary connect trackSource="Dapp widget body" />
            </div>
          )}
        </div>
      </Layout>
      <style jsx>{`
        .empty-placeholder {
          min-height: 470px;
          height: 100%;
          padding: 70px;
          border-radius: 10px;
          border-top: solid 1px #cdd7e0;
          background-color: #fafbfc;
        }

        .header-text {
          font-size: 22px;
          line-height: 0.86;
          text-align: center;
          color: black;
          margin-top: 23px;
          margin-bottom: 10px;
        }

        .subtext {
          font-size: 14px;
          line-height: 1.36;
          text-align: center;
          color: #8293a4;
          margin-bottom: 50px;
        }

        @media (min-width: 799px) {
          .home {
            padding-top: 20px;
          }
        }
      `}</style>
    </>
  )
}
Example #19
Source File: App.js    From gnosis-safe-delegate-dapp with MIT License 5 votes vote down vote up
function withUseWeb3React(Component) {
    return function WrappedComponent(props) {
        const values = useWeb3React();
        return <Component {...props} web3ReactHookValue={values} />;
    }
}
Example #20
Source File: index.jsx    From sorbet-finance with GNU General Public License v3.0 5 votes vote down vote up
export default function Orders() {
  const { t } = useTranslation()
  const { account, chainId } = useWeb3React()
  const uniswapEXContract = useUniswapExContract()
  const multicallContract = useMulticallContract()
  const [orders, setOrders] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    setLoading(!account)
  }, [account])

  const pendingOrders = useAllPendingOrders()
  const pendingCancelOrders = useAllPendingCancelOrders()

  // Get locally saved orders and the graph orders
  const local = useSavedOrders(account, chainId, uniswapEXContract, multicallContract, [
    pendingOrders.length,
    pendingCancelOrders.length,
  ])
  const graph = useGraphOrders(account, chainId)

  // Define orders to show as openOrders + pending orders
  useEffect(() => {
    // Aggregate graph and local orders, local orders have priority
    const allOrders = local.allOrders.concat(
      graph.allOrders.filter((o) => !local.allOrders.find((c) => c.secret === o.secret))
    )
    const openOrders = local.openOrders.concat(
      graph.openOrders.filter((o) => !local.allOrders.find((c) => c.secret === o.secret))
    )

    setOrders(openOrders.concat(allOrders.filter((o) => pendingOrders.find((p) => p.secret === o.secret))))

    // eslint-disable-next-line
  }, [
    local.allOrders.length,
    local.openOrders.length,
    graph.allOrders.length,
    graph.openOrders.length,
    pendingOrders.length,
  ])

  return (
    <>
      {account && (
        <>
          <>
            <p className="orders-title">{`${t('Orders')} ${orders.length > 0 ? `(${orders.length})` : ''}`}</p>
            {loading && (
              <>
                <SpinnerWrapper src={Circle} alt="loader" /> Loading ...
                <br />
                <br />
              </>
            )}
            {orders.length === 0 && !loading && <p>{t('noOpenOrders')}</p>}
            {
              <div>
                {orders.map((order) => (
                  <OrderCard key={order.witness} data={order} />
                ))}
              </div>
            }
          </>
          <OrdersHistory />
        </>
      )}
    </>
  )
}
Example #21
Source File: index.jsx    From pine-interface with GNU General Public License v3.0 5 votes vote down vote up
export default function Orders() {
  const { t } = useTranslation()
  const { account, chainId } = useWeb3React()
  const uniswapEXContract = useUniswapExContract()
  const multicallContract = useMulticallContract()
  const [orders, setOrders] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    setLoading(!account)
  }, [account])

  const pendingOrders = useAllPendingOrders()
  const pendingCancelOrders = useAllPendingCancelOrders()

  // Get locally saved orders and the graph orders
  const local = useSavedOrders(account, chainId, uniswapEXContract, multicallContract, [
    pendingOrders.length,
    pendingCancelOrders.length
  ])
  const graph = useGraphOrders(account, chainId)

  // Define orders to show as openOrders + pending orders
  useEffect(() => {
    // Aggregate graph and local orders, local orders have priority
    const allOrders = local.allOrders.concat(
      graph.allOrders.filter(o => !local.allOrders.find(c => c.secret === o.secret))
    )
    const openOrders = local.openOrders.concat(
      graph.openOrders.filter(o => !local.allOrders.find(c => c.secret === o.secret))
    )

    setOrders(openOrders.concat(allOrders.filter(o => pendingOrders.find(p => p.secret === o.secret))))

    // eslint-disable-next-line
  }, [local.allOrders.length, local.openOrders.length, graph.allOrders.length, graph.openOrders.length, pendingOrders.length])

  return (
    <>
      {account && (
        <>
          <>
            <p className="orders-title">{`${t('Orders')} ${orders.length > 0 ? `(${orders.length})` : ''}`}</p>
            {loading && (
              <>
                <SpinnerWrapper src={Circle} alt="loader" /> Loading ...
                <br />
                <br />
              </>
            )}
            {orders.length === 0 && !loading && <p>{t('noOpenOrders')}</p>}
            {
              <div>
                {orders.map(order => (
                  <OrderCard key={order.witness} data={order} />
                ))}
              </div>
            }
          </>
          <OrdersHistory />
        </>
      )}
    </>
  )
}
Example #22
Source File: token-approvals.js    From pure.finance with MIT License 5 votes vote down vote up
useAllowanceInput = function (
  token,
  spender,
  allowance,
  setAllowance,
  setFeedback
) {
  const { account, active, chainId } = useWeb3React()
  const { tokenApprovals } = useContext(PureContext)

  const disabled = !token || !spender || !active || !tokenApprovals

  useEffect(
    function () {
      setAllowance('')
    },
    [active, token, spender]
  )

  useEffect(
    function () {
      if (disabled) {
        return
      }

      tokenApprovals
        .allowance(token.address, account, spender.address)
        .then(function (currentAllowance) {
          setAllowance(fromUnit(currentAllowance, token.decimals))
        })
        .catch(function (err) {
          setFeedback('error', err.message)
        })
    },
    [token, spender, account, chainId]
  )

  const handleChange = function (e) {
    const re = /^(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$/ // Decimal number
    if (e.target.value === '' || re.test(e.target.value)) {
      setAllowance(e.target.value)
    }
  }

  return {
    disabled,
    onChange: handleChange,
    suffix: token && token.symbol,
    value: allowance
  }
}
Example #23
Source File: Note.jsx    From locked.fyi with MIT License 5 votes vote down vote up
Note = ({ address, note: index, thread: page }) => {
  const { account } = useWeb3React()
  const { note, error, loading } = useNote(address, page, index)

  if (error) {
    return <p>{error}</p>
  }
  if (loading) {
    return <Loading />
  }

  const viewedByAuthor = account === note.attributes.author

  if (note.attributes.draft && !viewedByAuthor) {
    return <p>Note not found!</p>
  }
  const locks =
    note.attributes.locks && note.attributes.locks.length
      ? note.attributes.locks
      : [defaultLock]

  return (
    <>
      {note.attributes.draft && (
        <Warning>
          This story is a draft and has not been published yet!{" "}
          <Link to={writePath(page, index)}>Edit</Link>
        </Warning>
      )}
      <Author address={note.attributes.author} />
      <Locked locks={locks} skip={viewedByAuthor}>
        <Markdown
          dangerouslySetInnerHTML
          markup={note.body}
          options={showdownOptions()}
        />
      </Locked>
      {!note.attributes.draft && (
        <footer>
          <nav>
            Back to <Link to={threadPath(address)}>Thread</Link>
          </nav>
          {viewedByAuthor && (
            <nav>
              <Link to={writePath(page, index)}>Edit</Link>
            </nav>
          )}
        </footer>
      )}
    </>
  )
}
Example #24
Source File: Dashboard.js    From lrc-staking-dapp with MIT License 5 votes vote down vote up
Dashboard = ({ classes, children }) => {
  const { library } = useWeb3React();
  const stakingContract = useSelector((state) => state.staking.contract);
  const feeContract = useSelector((state) => state.fee.contract);
  const tokenContract = useSelector((state) => state.token.contract);
  const dispatch = useDispatch();
  const setLanguage = (_language) => dispatch(settingsSetLanguage(_language));
  const setContractStaking = (_contract) => dispatch(stakingSetContract(_contract));
  const setContractFee = (_contract) => dispatch(feeSetContract(_contract));
  const setContractToken = (_contract) => dispatch(tokenSetContract(_contract));


  useEffect(() => {
    makeAllSmartContract(library, stakingContract, feeContract, tokenContract,
      setContractStaking, setContractFee, setContractToken);
  }, [library, stakingContract, feeContract, tokenContract,
    setContractStaking, setContractFee, setContractToken]);

  return (
    <div className="app-wrapper min-vh-100 bg-neutral-primary">
      <div className="app-main flex-column">
        <div className={classes.btnTranslate}>
          <TranslationButton
            languageList={[{ flag: (<FlagIcon code="US" size={45} />), name: LANGUAGES.english },
              { flag: (<FlagIcon code="FR" size={45} />), name: LANGUAGES.french }]}
            onSetLanguage={setLanguage}
          />
        </div>
        <div className="app-content p-0">
          <div className={`app-content--inner d-flex align-items-center ${classes.noPaddingMobile}`}>
            <div className="flex-grow-1 w-100 d-flex align-items-center">
              <div className={`bg-composed-wrapper--content py-5 ${classes.noPaddingMobile}`}>
                <Container maxWidth="lg">
                  { children }
                </Container>
              </div>
            </div>
          </div>
        </div>
      </div>
      <DisplayError />
    </div>
  );
}
Example #25
Source File: index.js    From uniswap-v1-frontend with GNU General Public License v3.0 4 votes vote down vote up
export default function WalletModal({ pendingTransactions, confirmedTransactions, ENSName }) {
  const { active, account, connector, activate, error } = useWeb3React()

  const [walletView, setWalletView] = useState(WALLET_VIEWS.ACCOUNT)

  const [pendingWallet, setPendingWallet] = useState()

  const [pendingError, setPendingError] = useState()

  const walletModalOpen = useWalletModalOpen()
  const toggleWalletModal = useWalletModalToggle()

  const { t } = useTranslation()

  // always reset to account view
  useEffect(() => {
    if (walletModalOpen) {
      setPendingError(false)
      setWalletView(WALLET_VIEWS.ACCOUNT)
    }
  }, [walletModalOpen])

  // set up uri listener for walletconnect
  const [uri, setUri] = useState()
  useEffect(() => {
    const activateWC = uri => {
      setUri(uri)
      // setWalletView(WALLET_VIEWS.PENDING)
    }
    walletconnect.on(URI_AVAILABLE, activateWC)
    return () => {
      walletconnect.off(URI_AVAILABLE, activateWC)
    }
  }, [])

  // close modal when a connection is successful
  const activePrevious = usePrevious(active)
  const connectorPrevious = usePrevious(connector)
  useEffect(() => {
    if (walletModalOpen && ((active && !activePrevious) || (connector && connector !== connectorPrevious && !error))) {
      setWalletView(WALLET_VIEWS.ACCOUNT)
    }
  }, [setWalletView, active, error, connector, walletModalOpen, activePrevious, connectorPrevious])

  const tryActivation = async connector => {
    let name = ''
    Object.keys(SUPPORTED_WALLETS).map(key => {
      if (connector === SUPPORTED_WALLETS[key].connector) {
        return (name = SUPPORTED_WALLETS[key].name)
      }
      return true
    })
    // log selected wallet
    ReactGA.event({
      category: 'Wallet',
      action: 'Change Wallet',
      label: name
    })
    setPendingWallet(connector) // set wallet for pending view
    setWalletView(WALLET_VIEWS.PENDING)
    activate(connector, undefined, true).catch(error => {
      if (error instanceof UnsupportedChainIdError) {
        activate(connector) // a little janky...can't use setError because the connector isn't set
      } else {
        setPendingError(true)
      }
    })
  }

  // close wallet modal if fortmatic modal is active
  useEffect(() => {
    fortmatic.on(OVERLAY_READY, () => {
      toggleWalletModal()
    })
  }, [toggleWalletModal])

  // get wallets user can switch too, depending on device/browser
  function getOptions() {
    const isMetamask = window.ethereum && window.ethereum.isMetaMask
    return Object.keys(SUPPORTED_WALLETS).map(key => {
      const option = SUPPORTED_WALLETS[key]
      // check for mobile options
      if (isMobile) {
        // disable portis on mobile for now
        if (option.connector === portis) {
          return null
        }

        if (!window.web3 && !window.ethereum && option.mobile) {
          return (
            <Option
              onClick={() => {
                option.connector !== connector && !option.href && tryActivation(option.connector)
              }}
              key={key}
              active={option.connector && option.connector === connector}
              color={option.color}
              link={option.href}
              header={option.name}
              subheader={null}
              icon={require('../../assets/images/' + option.iconName)}
            />
          )
        }
        return null
      }

      // overwrite injected when needed
      if (option.connector === injected) {
        // don't show injected if there's no injected provider
        if (!(window.web3 || window.ethereum)) {
          if (option.name === 'MetaMask') {
            return (
              <Option
                key={key}
                color={'#E8831D'}
                header={'Install Metamask'}
                subheader={null}
                link={'https://metamask.io/'}
                icon={MetamaskIcon}
              />
            )
          } else {
            return null // dont want to return install twice
          }
        }
        // don't return metamask if injected provider isn't metamask
        else if (option.name === 'MetaMask' && !isMetamask) {
          return null
        }
        // likewise for generic
        else if (option.name === 'Injected' && isMetamask) {
          return null
        }
      }

      // return rest of options
      return (
        !isMobile &&
        !option.mobileOnly && (
          <Option
            onClick={() => {
              option.connector === connector
                ? setWalletView(WALLET_VIEWS.ACCOUNT)
                : !option.href && tryActivation(option.connector)
            }}
            key={key}
            active={option.connector === connector}
            color={option.color}
            link={option.href}
            header={option.name}
            subheader={null} // use option.descriptio to bring back multi-line
            icon={require('../../assets/images/' + option.iconName)}
          />
        )
      )
    })
  }

  function getModalContent() {
    if (error) {
      return (
        <UpperSection>
          <CloseIcon onClick={toggleWalletModal}>
            <CloseColor alt={'close icon'} />
          </CloseIcon>
          <HeaderRow>{error instanceof UnsupportedChainIdError ? 'Wrong Network' : 'Error connecting'}</HeaderRow>
          <ContentWrapper>
            {error instanceof UnsupportedChainIdError ? (
              <h5>Please connect to the main Ethereum network.</h5>
            ) : (
              'Error connecting. Try refreshing the page.'
            )}
          </ContentWrapper>
        </UpperSection>
      )
    }
    if (account && walletView === WALLET_VIEWS.ACCOUNT) {
      return (
        <AccountDetails
          toggleWalletModal={toggleWalletModal}
          pendingTransactions={pendingTransactions}
          confirmedTransactions={confirmedTransactions}
          ENSName={ENSName}
          openOptions={() => setWalletView(WALLET_VIEWS.OPTIONS)}
        />
      )
    }
    return (
      <UpperSection>
        <CloseIcon onClick={toggleWalletModal}>
          <CloseColor alt={'close icon'} />
        </CloseIcon>
        {walletView !== WALLET_VIEWS.ACCOUNT ? (
          <HeaderRow color="blue">
            <HoverText
              onClick={() => {
                setPendingError(false)
                setWalletView(WALLET_VIEWS.ACCOUNT)
              }}
            >
              Back
            </HoverText>
          </HeaderRow>
        ) : (
          <HeaderRow>
            <HoverText>{t('connectToWallet')}</HoverText>
          </HeaderRow>
        )}
        <ContentWrapper>
          {walletView === WALLET_VIEWS.PENDING ? (
            <PendingView
              uri={uri}
              size={220}
              connector={pendingWallet}
              error={pendingError}
              setPendingError={setPendingError}
              tryActivation={tryActivation}
            />
          ) : (
            <OptionGrid>{getOptions()}</OptionGrid>
          )}
          {walletView !== WALLET_VIEWS.PENDING && (
            <Blurb>
              <span>New to Ethereum? &nbsp;</span>{' '}
              <Link href="https://ethereum.org/use/#3-what-is-a-wallet-and-which-one-should-i-use">
                Learn more about wallets
              </Link>
            </Blurb>
          )}
        </ContentWrapper>
      </UpperSection>
    )
  }

  return (
    <Modal
      style={{ userSelect: 'none' }}
      isOpen={walletModalOpen}
      onDismiss={toggleWalletModal}
      minHeight={null}
      maxHeight={90}
    >
      <Wrapper>{getModalContent()}</Wrapper>
    </Modal>
  )
}
Example #26
Source File: _Helpers.js    From acy-dex-interface with MIT License 4 votes vote down vote up
export function useAccountOrders(flagOrdersEnabled, overrideAccount) {
  const { active, library, account: connectedAccount } = useWeb3React();
  const account = overrideAccount || connectedAccount;

  const { chainId } = useChainId();
  const shouldRequest = active && account && flagOrdersEnabled;

  const orderBookAddress = getContract(chainId, "OrderBook");
  const orderBookReaderAddress = getContract(chainId, "OrderBookReader");
  const key = shouldRequest
    ? [active, chainId, orderBookAddress, account]
    : false;
  const { data: orders = [], mutate: updateOrders } = useSWR(key, {
    dedupingInterval: 5000,
    fetcher: async (active, chainId, orderBookAddress, account) => {
      const provider = getProvider(library, chainId);
      const orderBookContract = new ethers.Contract(
        orderBookAddress,
        OrderBook.abi,
        provider
      );
      const orderBookReaderContract = new ethers.Contract(
        orderBookReaderAddress,
        OrderBookReader.abi,
        provider
      );

      const fetchLastIndex = async type => {
        const method = type.toLowerCase() + "OrdersIndex";
        return await orderBookContract[method](account).then(res =>
          bigNumberify(res._hex).toNumber()
        );
      };

      const fetchLastIndexes = async () => {
        const [swap, increase, decrease] = await Promise.all([
          fetchLastIndex("swap"),
          fetchLastIndex("increase"),
          fetchLastIndex("decrease")
        ]);

        return { swap, increase, decrease };
      };

      const getRange = (to, from) => {
        const LIMIT = 10;
        const _indexes = [];
        from = from || Math.max(to - LIMIT, 0);
        for (let i = to - 1; i >= from; i--) {
          _indexes.push(i);
        }
        return _indexes;
      };

      const getIndexes = (knownIndexes, lastIndex) => {
        if (knownIndexes.length === 0) {
          return getRange(lastIndex);
        }
        return [
          ...knownIndexes,
          ...getRange(
            lastIndex,
            knownIndexes[knownIndexes.length - 1] + 1
          ).sort((a, b) => b - a)
        ];
      };

      const getOrders = async (method, lastIndex, parseFunc) => {
        const indexes = getRange(lastIndex);
        const ordersData = await orderBookReaderContract[method](
          orderBookAddress,
          account,
          indexes
        );
        const orders = parseFunc(chainId, ordersData, account, indexes);

        return orders;
      };

      try {
        const lastIndexes = await Promise.all(fetchLastIndexes());
        const [
          swapOrders = [],
          increaseOrders = [],
          decreaseOrders = []
        ] = await Promise.all([
          getOrders(
            "getSwapOrders",
            lastIndexes.swap,
            parseSwapOrdersData
          ),
          getOrders(
            "getIncreaseOrders",
            lastIndexes.increase,
            parseIncreaseOrdersData
          ),
          getOrders(
            "getDecreaseOrders",
            lastIndexes.decrease,
            parseDecreaseOrdersData
          )
        ]);
        return [...swapOrders, ...increaseOrders, ...decreaseOrders];
      } catch (ex) {
        console.error(ex);
      }
    }
  });

  return [orders, updateOrders];
}