0.1.2 ā€¢ Published 4 years ago

swr-eth v0.1.2

Weekly downloads
15
License
MIT
Repository
github
Last release
4 years ago

SWR-eth

An util to use SWR with Ethereum

view on npm

export const EthBalance = ({ symbol, address, decimals }) => {
  const { account, library } = useWeb3React<Web3Provider>()
  const { data: balance } = useSWR(['getBalance', 'latest'])

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

Configure in your project

You can use SWRConfig to have a global fetcher capable of retrieving basic Ethereum information (e.g. block, getBalance) or directly interact with a smart contract

import {ethFetcher } from "swr-eth";
import {SWRConfig} from "swr";
import ERC20ABI from "../abi/ERC20.abi.json";
import {EthBalance} from "./EthBalance";

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

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 ? (
            <div>āœ… </div>
        ) : (
            <button type="button" onClick={onClick}>
              Connect
            </button>
        )}
        {active && (
            <SWRConfig value={{ fetcher: ethFetcher(library, new Map(ABIs)) }}>
              <EthBalance />
              <TokenList chainId={chainId} />
            </SWRConfig>
        )}
      </div>
  )
}

Interact with basic method

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

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

Interact with a smart contract

const { data: balance } = useSWR(['0x6b175474e89094c44da98b954eedeac495271d0f','balanceOf', 'latest'])

You can use all the methods provided by a contract as long as you have provided the ABI associated to the smat contract address when you configured the ethFetcher

Example

A minimal example is availablehere

Related projects

Licence

Licensed under MIT.