Giter Club home page Giter Club logo

covalent's Introduction

Covalent Integration

This example shows you how to fetch indexed NFT information about a wallet using Covalent.

It loads all of a user's owned tokens by making an API request to the Get token balances for address endpoint. Using thirdweb's React SDK, we fetch the metadata about each ERC-721 NFT and display it in a list using the ThirdwebNftMedia component.

Tools:

  • Covalent: Fetch tokens owned by the connected wallet.

  • React SDK: enable users to connect and disconnect their wallets to our website.

  • TypeScript SDK: Load contract and NFT metadata for the owned NFTs.

Using This Repo

  • Create a project using this example by running:
npx thirdweb create --template covalent

Get a free API key from Covalent and add your API key in an environment variable called COVALENT_API_KEY in the .env.local file.

COVALENT_API_KEY=ckey_xxx

Guide

Learn how this repo works below!

Connecting to user's wallet

Our application is wrapped in the ThirdwebProvider component. Allowing us to use all of the React SDK's functionality such as connect and disconnect wallets.

import { ChainId, ThirdwebProvider } from "@thirdweb-dev/react";
import Head from "next/head";
import ThirdwebGuideFooter from "../components/guide/ThirdwebGuideFooter";
import Header from "../components/Header";
import "../styles/globals.css";

// This is the chainId your dApp will work on.
const activeChainId = ChainId.Mumbai;

function MyApp({ Component, pageProps }) {
  return (
    <ThirdwebProvider desiredChainId={activeChainId}>
      <Component {...pageProps} />
    </ThirdwebProvider>
  );
}

export default MyApp;

Then we can use the hooks to connect to and access the connected wallet address on index.js.

// Wallet connection hooks from React SDK
const address = useAddress();
const connectWithMetamask = useMetamask();

Loading Token Balances

Once the user has connected their wallet, we load their token balances by requesting data from the Covalent API.

Firstly, we make a fetch request to our Next.js API route:

const req = await fetch("/api/get-wallet-data", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },

  body: JSON.stringify({
    address: address,
  }),
});

On the API route, we make a request for data about the address from the Covalent API, passing in our API Key as the authentication header.

const apikey = process.env.COVALENT_API_KEY;

let headers = new Headers();
let authString = `${apikey}:`;
headers.set("Authorization", "Basic " + btoa(authString));

const URL = `https://api.covalenthq.com/v1/${chainId}/address/${address}/balances_v2/?nft=true&no-nft-fetch=true`;

fetch(URL, { method: "GET", headers: headers })
  .then((res) => res.json())

  .then((response) => {
    console.log(response);
    res.status(200).json({
      tokens: response.data.items,
    });
  })

  .catch((error) => {
    console.log(error);
    res.status(500).json({
      error: error,
    });
  });

As you can see we return that data as json back to the client once the data has been loaded, and store that in state on the client:

// De-structure tokens out of the response JSON
const { tokens } = await req.json();
// Set the tokens in state.
setTokenData(tokens.filter((t) => t.type === "nft"));

Now we have the token balances of the connected wallet, we're ready to display them.

Displaying NFTs

Firstly, we map over the different kinds of tokens returned from the API endpoint, filtering to ERC-721 NFTs.

{
  tokenData
    ?.filter((t) => t.type === "nft")
    ?.filter((t) => t.supports_erc?.includes("erc721"))
    ?.map((nft, i) => <NftCardContainer nft={nft} key={i} />);
}

The NftCardContainer component uses the React SDK's MediaRenderer component to resolve the NFT's image from IPFS and display it:

<MediaRenderer
  style={{ width: 128, height: 128, borderRadius: 16, padding: 4 }}
  src={nft.external_data.image}
  alt="A mp4 video"
/>

Join our Discord!

For any questions, suggestions, join our discord at https://discord.gg/thirdweb.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.