All Projects → aboutlo → ether-swr

aboutlo / ether-swr

Licence: MIT license
Ether-SWR is a React hook that fetches Ethereum data. It streamlines the chores to keep the internal state of the Decentralized App (DApp), batches the RPC calls to an Ethereum node and cache the responses

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to ether-swr

uniswap-arbitrage-flash-swap
Uniswap flash swap arbitrage solidity contracts
Stars: ✭ 341 (+172.8%)
Mutual labels:  smart-contracts, web3
Web3swift
Elegant Web3js functionality in Swift. Native ABI parsing and smart contract interactions.
Stars: ✭ 237 (+89.6%)
Mutual labels:  smart-contracts, web3
Web3.php
A php interface for interacting with the Ethereum blockchain and ecosystem. Native ABI parsing and smart contract interactions.
Stars: ✭ 507 (+305.6%)
Mutual labels:  smart-contracts, web3
React Ethereum Dapp Example
A starter boilerplate for an Ethereum dapp using web3.js v1.0, truffle, react, and parity
Stars: ✭ 384 (+207.2%)
Mutual labels:  smart-contracts, web3
trufflepig
🍄🐷Truffle contract artifact loading tool for local development
Stars: ✭ 45 (-64%)
Mutual labels:  smart-contracts, web3
Eth Crypto
Cryptographic javascript-functions for ethereum and tutorials to use them with web3js and solidity
Stars: ✭ 420 (+236%)
Mutual labels:  smart-contracts, web3
Blockchainbooks.github.io
Blockchain Books
Stars: ✭ 139 (+11.2%)
Mutual labels:  smart-contracts, web3
Solidity Idiosyncrasies
Solidity gotchas, pitfalls, limitations, and idiosyncrasies.
Stars: ✭ 267 (+113.6%)
Mutual labels:  smart-contracts, web3
eth-decoder
Simple library to decode ethereum transaction and logs
Stars: ✭ 32 (-74.4%)
Mutual labels:  smart-contracts, web3
docs
Unleash Bitcoin's full potential with decentralized apps and smart contracts. The documentation covers key aspects of the Stacks network and technology and provides tutorials and other helpful content for developers.
Stars: ✭ 134 (+7.2%)
Mutual labels:  smart-contracts, web3
Ethereum Php
PHP interface to Ethereum JSON-RPC API. Fully typed Web3 for PHP 7.X
Stars: ✭ 343 (+174.4%)
Mutual labels:  smart-contracts, web3
framework
Lightweight, open source and magic-free framework for testing solidity smart contracts.
Stars: ✭ 36 (-71.2%)
Mutual labels:  smart-contracts, web3
Alpha
Follow the white rabbit 🐇
Stars: ✭ 304 (+143.2%)
Mutual labels:  smart-contracts, web3
Web3swift
Elegant Web3js functionality in Swift. Native ABI parsing and smart contract interactions on Ethereum network.
Stars: ✭ 462 (+269.6%)
Mutual labels:  smart-contracts, web3
Web3.swift
A pure swift Ethereum Web3 library
Stars: ✭ 295 (+136%)
Mutual labels:  smart-contracts, web3
Eth.social
An Ethereum dApp for posting social events.
Stars: ✭ 17 (-86.4%)
Mutual labels:  smart-contracts, web3
awesome-waves
Curated list of awesome things for development on Waves blockchain.
Stars: ✭ 60 (-52%)
Mutual labels:  smart-contracts, web3
full-blockchain-solidity-course-py
Ultimate Solidity, Blockchain, and Smart Contract - Beginner to Expert Full Course | Python Edition
Stars: ✭ 5,349 (+4179.2%)
Mutual labels:  smart-contracts, web3
useWeb3
useWeb3 provides a curated overview of the best and latest resources on Ethereum, blockchain and Web3 development.
Stars: ✭ 325 (+160%)
Mutual labels:  smart-contracts, web3
starter-kit-gsn
An OpenZeppelin starter kit focused on GSN.
Stars: ✭ 39 (-68.8%)
Mutual labels:  smart-contracts, web3

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].