{"id":18781582,"url":"https://github.com/aboutlo/ether-swr","last_synced_at":"2025-05-07T08:03:45.565Z","repository":{"id":39533216,"uuid":"266866882","full_name":"aboutlo/ether-swr","owner":"aboutlo","description":"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","archived":false,"fork":false,"pushed_at":"2021-11-24T17:04:23.000Z","size":240,"stargazers_count":138,"open_issues_count":2,"forks_count":11,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-05-07T08:03:38.379Z","etag":null,"topics":["blockchain","ethereum","javascript","smart-contracts","typescript","web3"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/aboutlo.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null}},"created_at":"2020-05-25T19:47:13.000Z","updated_at":"2025-03-10T15:48:36.000Z","dependencies_parsed_at":"2022-08-21T08:00:25.241Z","dependency_job_id":null,"html_url":"https://github.com/aboutlo/ether-swr","commit_stats":null,"previous_names":["aboutlo/swr-eth"],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aboutlo%2Fether-swr","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aboutlo%2Fether-swr/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aboutlo%2Fether-swr/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aboutlo%2Fether-swr/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/aboutlo","download_url":"https://codeload.github.com/aboutlo/ether-swr/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252839287,"owners_count":21812086,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["blockchain","ethereum","javascript","smart-contracts","typescript","web3"],"created_at":"2024-11-07T20:32:42.228Z","updated_at":"2025-05-07T08:03:45.539Z","avatar_url":"https://github.com/aboutlo.png","language":"TypeScript","readme":"# Ether-SWR\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"logo.png\" width=\"450\" height=\"auto\"/\u003e\n\u003c/div\u003e\n\nEther-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.\nIt does so with a declarative approach via an opinionated wrapper of [SWR](https://swr.vercel.app/).\n\nEther-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.\n\nIn case the same request is defined multiple times on the same rendered component tree only one request is made because SWR deduping process.\n\n[![view on npm](https://img.shields.io/npm/v/ether-swr.svg)](https://www.npmjs.org/package/ether-swr)\n[![](https://github.com/aboutlo/ether-swr/workflows/ci/badge.svg)](https://github.com/aboutlo/ether-swr/actions?query=workflow%3Aci)\n\n## Installation\n\n    yarn add ether-swr\n\nor\n\n    npm install --save ether-swr\n\n## API\n\n### Interact with Ethereum methods (e.g. getBalance, blockNumber)\n\n```typescript\nconst { data: balance } = useEtherSWR(['getBalance', 'latest'])\n```\n\nYou can use all the methods provided by a Web3Provider from [Ether.js]()\n\n### Interact with a smart contract (e.g ERC20 )\n\n```typescript\nconst { data: balance } = useEtherSWR([\n  '0x6b175474e89094c44da98b954eedeac495271d0f', // DAI contract\n  'balanceOf', // Method\n  '0x5d3a536e4d6dbd6114cc1ead35777bab948e3643' // holder\n])\n```\n\n### Make multiple requests at once with a smart contract (e.g ERC20 )\n\n```typescript\nconst { data: balances } = useEtherSWR([\n  [\n    '0x6b175474e89094c44da98b954eedeac495271d0f', // DAI contract\n    'balanceOf', // Method\n    '0x5d3a536e4d6dbd6114cc1ead35777bab948e3643' // holder 1\n  ],\n  [\n    '0x6b175474e89094c44da98b954eedeac495271d0f', // DAI contract\n    'balanceOf', // Method\n    '0x5d3a536e4d6dbd6114cc1ead35777bab948e3643' // holder 2\n  ]\n])\n```\n\nYou can use all the methods provided by a contract as long as you have provided the ABI associated to the smart contract\n\n### Subscribe to a topic\n\nSubscribe to a topic refresh automatically the underline data once it's dispatched\n\n```typescript\nconst { data: balance, mutate } = useEtherSWR([address, 'balanceOf', account], {\n  subscribe: [\n    // A filter from anyone to me\n    {\n      name: 'Transfer',\n      topics: [null, account]\n    },\n    // A filter from me to anyone\n    {\n      name: 'Transfer',\n      topics: [account, null]\n    }\n  ]\n})\n\nreturn (\n  \u003cdiv\u003e\n    {parseFloat(formatUnits(balance, decimals)).toPrecision(4)} {symbol}\n  \u003c/div\u003e\n)\n```\n\nSubscribe to a topic providing a callback allows to use an optimistic update\n\n```typescript\nconst { data: balance, mutate } = useEtherSWR([address, 'balanceOf', account], {\n  subscribe: [\n    // A filter from anyone to me\n    {\n      name: 'Transfer',\n      topics: [null, account],\n      on: (\n        data: BigNumber,\n        fromAddress: string,\n        toAddress: string,\n        amount: BigNumber,\n        event: any\n      ) =\u003e {\n        console.log('receive', { event })\n        const update = data.add(amount)\n        mutate(update, false) // optimistic update skip re-fetch\n      }\n    },\n    // A filter from me to anyone\n    {\n      name: 'Transfer',\n      topics: [account, null],\n      on: (\n        data: BigNumber,\n        fromAddress: string,\n        toAddress: string,\n        amount: BigNumber,\n        event: any\n      ) =\u003e {\n        console.log('send', { event })\n        const update = data.sub(amount)\n        mutate(update, false) // optimistic update skip re-fetch\n      }\n    }\n  ]\n})\n\nreturn (\n  \u003cdiv\u003e\n    {parseFloat(formatUnits(balance, decimals)).toPrecision(4)} {symbol}\n  \u003c/div\u003e\n)\n```\n\n## Getting Started\n\nYou can use `EthSWRConfig` to have a global fetcher capable of retrieving basic Ethereum information (e.g. block, getBalance)\nor directly interact with a smart contract mapped to its ABI.\nTo 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.\n\n```js\nimport React from 'react'\nimport { Web3ReactProvider, useWeb3React } from '@web3-react/core'\nimport { Web3Provider } from '@ethersproject/providers'\nimport { InjectedConnector } from '@web3-react/injected-connector'\nimport { BigNumber } from 'ethers'\nimport { formatEther, formatUnits } from '@ethersproject/units'\nimport useEtherSWR, { EthSWRConfig } from 'ether-swr'\nimport ERC20ABI from './ERC20.abi.json'\n\nconst ABIs = [\n  ['0x6b175474e89094c44da98b954eedeac495271d0f', ERC20ABI]\n]\n\nconst EthBalance = () =\u003e {\n  const { account } = useWeb3React\u003cWeb3Provider\u003e()\n  const { data: balance } = useEtherSWR(['getBalance', account, 'latest'])\n\n  if (!balance) {\n    return \u003cdiv\u003e...\u003c/div\u003e\n  }\n  return \u003cdiv\u003e{parseFloat(formatEther(balance)).toPrecision(4)} Ξ\u003c/div\u003e\n}\n\nconst TokenBalance = ({ symbol, address, decimals }: {\n  symbol: string\n  address: string\n  decimals: number\n}) =\u003e {\n  const { account } = useWeb3React\u003cWeb3Provider\u003e()\n\n  const { data: balance } = useEtherSWR([address, 'balanceOf', account])\n\n  if (!balance) {\n    return \u003cdiv\u003e...\u003c/div\u003e\n  }\n\n  return (\n    \u003cdiv\u003e\n      {parseFloat(formatUnits(balance, decimals)).toPrecision(4)} {symbol}\n    \u003c/div\u003e\n  )\n}\n\nexport const TokenList = ({ chainId }: { chainId: number }) =\u003e {\n  return (\n    \u003c\u003e\n      {['0x6b175474e89094c44da98b954eedeac495271d0f'].map(token =\u003e (\n        \u003cTokenBalance key={token.address} {...token} /\u003e\n      ))}\n    \u003c/\u003e\n  )\n}\n\nexport const Wallet = () =\u003e {\n  const { chainId, account, library, activate, active } = useWeb3React\u003cWeb3Provider\u003e()\n\n  const onClick = () =\u003e {\n    activate(injectedConnector)\n  }\n\n  return (\n    \u003cdiv\u003e\n      \u003cdiv\u003eChainId: {chainId}\u003c/div\u003e\n      \u003cdiv\u003eAccount: {shorter(account)}\u003c/div\u003e\n      {active ? (\n        \u003cspan role=\"img\" aria-label=\"active\"\u003e\n          ✅{' '}\n        \u003c/span\u003e\n      ) : (\n        \u003cbutton type=\"button\" onClick={onClick}\u003e\n          Connect\n        \u003c/button\u003e\n      )}\n      {active \u0026\u0026 chainId \u0026\u0026 (\n        \u003cEthSWRConfig\n          value={{ web3Provider: library, ABIs: new Map(ABIs), refreshInterval: 30000 }}\n        \u003e\n          \u003cEthBalance /\u003e\n          \u003cTokenList chainId={chainId} /\u003e\n        \u003c/EthSWRConfig\u003e\n      )}\n    \u003c/div\u003e\n  )\n}\n```\n\n## Example\n\nA minimal example with an event is available [here](./examples)\n\n## Utilities\n\n### useBalanceOf\n\nIt retrieves balances for an ERC20 token.\nYou can either pass one or multiple contracts and one or multiple owners\n\n```typescript\nimport { useBalanceOf } from 'ether-swr'\n\nconst { account } = useWeb3React\u003cWeb3Provider\u003e()\nconst { data: balances } = useBalanceOf\u003cBigNumber[]\u003e(\n  [\n    '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n    '0x6B175474E89094C44Da98b954EedeAC495271d0F'\n  ],\n  account\n)\n```\n\n### useBalance\n\nIt retrieves Ether balance.\nYou can either pass one or multiple owners\n\n```typescript\nimport { useBalance } from 'ether-swr'\n\nconst { account } = useWeb3React\u003cWeb3Provider\u003e()\nconst { data: balances } = useBalance\u003cBigNumber\u003e(\n  [\n    '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n    '0x6B175474E89094C44Da98b954EedeAC495271d0F'\n  ],\n  account\n)\n```\n\n## Related projects\n\n- [SWR](https://swr.now.sh)\n- [Ether.js](https://github.com/ethers-io/ethers.js)\n- [web3-react](https://github.com/NoahZinsmeister/web3-react)\n- [Ethereum JSON-RPC Spec](https://eth.wiki/json-rpc/API)\n\n## Licence\n\nLicensed under [MIT](./LICENSE).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faboutlo%2Fether-swr","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faboutlo%2Fether-swr","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faboutlo%2Fether-swr/lists"}