Sidebar

Table of content

Install @fewcha/web3-react

In your repository

With npm

npm install @fewcha/web3 @fewcha/web3-react

With yarn

yarn add @fewcha/web3 @fewcha/web3-react

Example repository

https://github.com/fewcha-wallet/aptos-web3/tree/main/packages/example

Use React Provider

import React from "react";
import Web3Provider from "@fewcha/web3-react";

const App: React.FC = () => {
  return (
    <Web3Provider>
      {/* your website */}
    </Web3Provider>
  );
};

export default App;

Web3 Hook

import { useWeb3 } from "@fewcha/web3-react";

const aptos = useWeb3();
const { init, account, isConnected, connect, disconnect, sdk, token } = aptos;

/*
init: boolean - for check web3 is ready yet
account: string - wallet address
isConnected: boolean - check the website is connected yet (realtime)
connect: function - trigger connect popup
disconnect: function - trigger disconnect action

sdk: Aptos SDK functions
token: Aptos TokenClient functions
*/

Connect & Disconnect

const aptos = useWeb3();
const { init, account, isConnected, connect, disconnect, web3 } = aptos;

if (!isConnected) {
  return (
    <Button
      onClick={() => {
        connect();
      }}
    >
      Connect
    </Button>
  );
} else {
  return (
    <Button
      onClick={() => {
        disconnect();
      }}
    >
      Disconnect
    </Button>
  );
}

Use Aptos SDK

const aptos = useWeb3();
const { init, account, isConnected, connect, disconnect, web3 } = aptos;

web3.

Example of use Aptos SDK

Get Balance

useEffect(() => {
  if (isConnected && account) {
    web3.getAccountResources(account).then((data) => {
      const accountResource = data.find((r) => r.type === "0x1::Coin::CoinStore<0x1::TestCoin::TestCoin>");
      const balance = (accountResource!.data as { coin: { value: string } }).coin.value;

      setBalance(balance);
    });
  }
}, [isConnected, account, web3]);

Source code

https://github.com/fewcha-wallet/aptos-web3