npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ether-swr

v2.0.1

Published

Ether-SWR is a React hook that fetches blockchain data, streamlines the chores to keep the internal state of Decentralized App (DApp) and optimize the RPC calls to an Ethereum node.

Downloads

146

Readme

Ether-SWR

Ether-SWR is a React hook that fetches Ethereum data, streamlines the chores to keep the internal state of Decentralized App (DApp) and optimize the RPC calls to an Ethereum node. It does so with a declarative approach via an opinionated wrapper of SWR.

Ether-SWR follows the stale-while-revalidate (HTTP RFC 5861) concept: first it returns the data from cache (stale), then send the fetch request on chain, and finally come with the up-to-date data.

In case the same request is defined multiple times on the same rendered component tree only one request is made because SWR deduping process.

view on npm

Installation

yarn add ether-swr

or

npm install --save ether-swr

API

Interact with Ethereum methods (e.g. getBalance, blockNumber)

const { data: balance } = useEtherSWR(['getBalance', 'latest'])

You can use all the methods provided by a Web3Provider from Ether.js

Interact with a smart contract (e.g ERC20 )

const { data: balance } = useEtherSWR([
  '0x6b175474e89094c44da98b954eedeac495271d0f', // DAI contract
  'balanceOf', // Method
  '0x5d3a536e4d6dbd6114cc1ead35777bab948e3643' // holder
])

Make multiple requests at once with a smart contract (e.g ERC20 )

const { data: balances } = useEtherSWR([
  [
    '0x6b175474e89094c44da98b954eedeac495271d0f', // DAI contract
    'balanceOf', // Method
    '0x5d3a536e4d6dbd6114cc1ead35777bab948e3643' // holder 1
  ],
  [
    '0x6b175474e89094c44da98b954eedeac495271d0f', // DAI contract
    'balanceOf', // Method
    '0x5d3a536e4d6dbd6114cc1ead35777bab948e3643' // holder 2
  ]
])

You can use all the methods provided by a contract as long as you have provided the ABI associated to the smart contract

Subscribe to a topic

Subscribe to a topic refresh automatically the underline data once it's dispatched

const { data: balance, mutate } = useEtherSWR([address, 'balanceOf', account], {
  subscribe: [
    // A filter from anyone to me
    {
      name: 'Transfer',
      topics: [null, account]
    },
    // A filter from me to anyone
    {
      name: 'Transfer',
      topics: [account, null]
    }
  ]
})

return (
  <div>
    {parseFloat(formatUnits(balance, decimals)).toPrecision(4)} {symbol}
  </div>
)

Subscribe to a topic providing a callback allows to use an optimistic update

const { data: balance, mutate } = useEtherSWR([address, 'balanceOf', account], {
  subscribe: [
    // A filter from anyone to me
    {
      name: 'Transfer',
      topics: [null, account],
      on: (
        data: BigNumber,
        fromAddress: string,
        toAddress: string,
        amount: BigNumber,
        event: any
      ) => {
        console.log('receive', { event })
        const update = data.add(amount)
        mutate(update, false) // optimistic update skip re-fetch
      }
    },
    // A filter from me to anyone
    {
      name: 'Transfer',
      topics: [account, null],
      on: (
        data: BigNumber,
        fromAddress: string,
        toAddress: string,
        amount: BigNumber,
        event: any
      ) => {
        console.log('send', { event })
        const update = data.sub(amount)
        mutate(update, false) // optimistic update skip re-fetch
      }
    }
  ]
})

return (
  <div>
    {parseFloat(formatUnits(balance, decimals)).toPrecision(4)} {symbol}
  </div>
)

Getting Started

You can use EthSWRConfig to have a global fetcher capable of retrieving basic Ethereum information (e.g. block, getBalance) or directly interact with a smart contract mapped to its ABI. To keep the state fresh you can pass refreshInterval: 30000 to the value object so that behind the scene Ether-SWR will refresh every 30 seconds the data of all the keys mounted in the tree components.

import React from 'react'
import { Web3ReactProvider, useWeb3React } from '@web3-react/core'
import { Web3Provider } from '@ethersproject/providers'
import { InjectedConnector } from '@web3-react/injected-connector'
import { BigNumber } from 'ethers'
import { formatEther, formatUnits } from '@ethersproject/units'
import useEtherSWR, { EthSWRConfig } from 'ether-swr'
import ERC20ABI from './ERC20.abi.json'

const ABIs = [
  ['0x6b175474e89094c44da98b954eedeac495271d0f', ERC20ABI]
]

const EthBalance = () => {
  const { account } = useWeb3React<Web3Provider>()
  const { data: balance } = useEtherSWR(['getBalance', account, 'latest'])

  if (!balance) {
    return <div>...</div>
  }
  return <div>{parseFloat(formatEther(balance)).toPrecision(4)} Ξ</div>
}

const TokenBalance = ({ symbol, address, decimals }: {
  symbol: string
  address: string
  decimals: number
}) => {
  const { account } = useWeb3React<Web3Provider>()

  const { data: balance } = useEtherSWR([address, 'balanceOf', account])

  if (!balance) {
    return <div>...</div>
  }

  return (
    <div>
      {parseFloat(formatUnits(balance, decimals)).toPrecision(4)} {symbol}
    </div>
  )
}

export const TokenList = ({ chainId }: { chainId: number }) => {
  return (
    <>
      {['0x6b175474e89094c44da98b954eedeac495271d0f'].map(token => (
        <TokenBalance key={token.address} {...token} />
      ))}
    </>
  )
}

export const Wallet = () => {
  const { chainId, account, library, activate, active } = useWeb3React<Web3Provider>()

  const onClick = () => {
    activate(injectedConnector)
  }

  return (
    <div>
      <div>ChainId: {chainId}</div>
      <div>Account: {shorter(account)}</div>
      {active ? (
        <span role="img" aria-label="active">
          ✅{' '}
        </span>
      ) : (
        <button type="button" onClick={onClick}>
          Connect
        </button>
      )}
      {active && chainId && (
        <EthSWRConfig
          value={{ web3Provider: library, ABIs: new Map(ABIs), refreshInterval: 30000 }}
        >
          <EthBalance />
          <TokenList chainId={chainId} />
        </EthSWRConfig>
      )}
    </div>
  )
}

Example

A minimal example with an event is available here

Utilities

useBalanceOf

It retrieves balances for an ERC20 token. You can either pass one or multiple contracts and one or multiple owners

import { useBalanceOf } from 'ether-swr'

const { account } = useWeb3React<Web3Provider>()
const { data: balances } = useBalanceOf<BigNumber[]>(
  [
    '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
    '0x6B175474E89094C44Da98b954EedeAC495271d0F'
  ],
  account
)

useBalance

It retrieves Ether balance. You can either pass one or multiple owners

import { useBalance } from 'ether-swr'

const { account } = useWeb3React<Web3Provider>()
const { data: balances } = useBalance<BigNumber>(
  [
    '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
    '0x6B175474E89094C44Da98b954EedeAC495271d0F'
  ],
  account
)

Related projects

Licence

Licensed under MIT.