# Follow transfers of a Fan Token

Tracking Fan Token movements on Chiliz Chain is a great way to monitor the activity of your favourite tokens. By using it as a building block for a potential dashboard, you can streamline data to provide insights into what's popular and what's not.

When tracking Fan Token™movements, you quickly run into a challenge: reading data directly from the blockchain is efficient for current status ("*What is the balance of wallet X?*"), but inefficient for historical data ("*Show me every transfer involving wallet X over the last year*").

To solve this, we can use subgraphs.

## About subgraphs

A Subgraph is a custom API that extracts data from a blockchain, processes it, and stores it so it can be easily queried. \
Instead of asking the blockchain to scan millions of blocks every time you need data, a subgraph indexes specific events as they happen and stores them in a database.

Chiliz Chain supports industry-standard indexing protocols. You can choose the provider that best fits your project's needs:

* [The Graph](https://thegraph.com/): The industry standard for decentralized indexing. It allows you to deploy your subgraph to a decentralized network of indexers.
* [Goldsky](https://goldsky.com/): A high-performance, hosted indexing service. It is fully compatible with The Graph's code (you can often use the exact same code) but offers faster indexing speeds and real-time data streaming features.

Both tools use the same development framework, so most of the steps on this page can apply to both.

Let's see for instance how we could follow transfers of the PSG Fan Token...

## 0. Choose a tool

You can deploy a subgraph on Chiliz Chain using **The Graph** (decentralized network) or **Goldsky** (hosted indexer). The code structure is identical; only the deployment commands differ.

Of course, you can rely on their own docs:

{% embed url="<https://thegraph.com/docs/en/subgraphs/quick-start/>" %}

{% embed url="<https://docs.goldsky.com/subgraphs/deploying-subgraphs>" %}

## 1. Initialize a subgraph project

Both The Graph and Goldsky offer CLI-based methods to create your graph.

{% hint style="info" %}
The Graph has [Subgraph Studio](https://thegraph.com/studio/), which you can connect to using your Web3, then create a subgraph through the interface.&#x20;

Goldsky gives you a [dashboard](https://app.goldsky.com/) when you create an account, from which you can create a subgraph.
{% endhint %}

### Install the Graph CLI⁠

On your local machine, run the following:

```bash
npm install -g @graphprotocol/graph-cli
```

{% hint style="info" %}
You can create a subgraph using the CLI tool from The Graph for either The Graph-decentralized subgraphs, or Goldsky-hosted subgraphs.

Goldsky has its own CLI tool, which you will need if you want to deploy on Goldsky (see below).
{% endhint %}

### Initialize your subgraph⁠

You can copy this directly from your subgraph page to include your specific subgraph slug:

```bash
graph init --studio <SUBGRAPH_SLUG>
```

The `--studio` tag is optional.&#x20;

In our PSG Fan Token example, we can use:

```bash
graph init chiliz-psg-fantoken-followup
```

You’ll be prompted to provide some info on your subgraph, like this:

<figure><img src="https://3400301555-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4L7rBH2rmyoBTn93MSdx%2Fuploads%2FGMGt5GCqFm90iJs9sCSP%2Fimage.png?alt=media&#x26;token=15139a74-acfe-43ab-99f4-a5ed09fb9101" alt=""><figcaption></figcaption></figure>

You need to have your contract verified on the block explorer, and the CLI will automatically obtain the ABI and set up your subgraph. The default settings will generate an entity for each event.

{% hint style="warning" %}
Note:

* If the contract uses a proxy, like the PSG Fan Token does, then use the implementation contract's address instead. You'll see it in the "Read/write contract" tab on the block explorer page of the contract. For instance, [see here for the PSG Fan token contract on Chiliz Block Explorer](https://scan.chiliz.com/token/0xc2661815C69c2B3924D3dd0c2C1358A1E38A3105?tab=read_write_contract).
  * If you had to enter a proxy's implementation contract address, then once the project is set up, go to the manifest file (`subgraph.yaml`) and change the contract address to the proxy's address.
* If the Start Block isn't automatically obtained, you can manually enter the block number where the contract was created. You can obtain this from the block explorer.
  {% endhint %}

{% hint style="info" %}
When making changes to your subgraph, you will mostly work with three files:

* The Manifest (`subgraph.yaml`): Defines what data sources your subgraph will index.
* The Schema (`schema.graphql`): Defines what data you wish to retrieve from the subgraph.
* AssemblyScript Mappings (`mapping.ts`): Translates data from your data sources to the entities defined in the schema.
  {% endhint %}

Open `subgraph.yaml` and make sur your manifest file points to the correct network:

```yaml
dataSources:
  - kind: ethereum
    name: FanToken
    network: chiliz  # Use 'chiliz' for Mainnet, chiliz-testnet for Spicy
    source:
      address: "0x..." 
      abi: FanToken
```

### Compile your subgraph

Finally, compile your subgraph to ensure that there are no errors:

```bash
graph codegen && graph build
```

## 2. Deploy & Publish

Once your subgraph is built, choose your provider to deploy it.

{% columns %}
{% column %}
**The Graph**

1. Connect to [Subgraph Studio](https://thegraph.com/studio/), create a subgraph, and copy your deploy key.
2. Authenticate through the CLI:\
   `graph auth --studio <DEPLOY_KEY>`&#x20;
3. Deploy your subgraph to Subgraph Studio:\
   `graph deploy --studio <SUBGRAPH_SLUG>`&#x20;
4. Go to Studio, open your subgraph and click "Publish" to mint your subgraph to the decentralized network. \
   It'll trigger a transaction through your wallet to publish your subgraph as an NFT on the Arbitrum One network.
   {% endcolumn %}

{% column %}
**Goldsky**

1. Go to [Goldsky](https://app.goldsky.com/), create an API key in "Project Settings", and log in via CLI.
2. Install the `goldsky` command: \
   `curl https://goldsky.com | sh` \
   Then authenticate through the CLI:\
   `goldsky login`
3. Upload your subgraph to Goldsky:\
   `goldsky subgraph deploy / --path`

Goldsky subgraphs are live immediately after deployment. No extra publishing step is required.
{% endcolumn %}
{% endcolumns %}

{% hint style="info" %}
You will be asked for a version label. You can enter something like `v0.0.1`, but you’re free to choose the format. Once that's done, you'll see the subgraph start to sync in the Studio page.
{% endhint %}

{% hint style="info" %}
The Graph's smart contracts are all on [Arbitrum One](https://arbitrum.io/arbitrum-101), even though your subgraph is indexing data from Chiliz Chain.
{% endhint %}

## 3. Query your Subgraph

Congratulations! You can now start querying it by passing a GraphQL query into the subgraph’s query URL which can be found in the dashboard of your chosen service.

Example:

{% columns %}
{% column %}
**The Graph**

`https://gateway-arbitrum.network.thegraph.com/api/[APIKEY]/subgraphs/id/[ID]`
{% endcolumn %}

{% column %}
**Goldsky**

`https://api.goldsky.com/api/public/project_[KEY]/subgraphs/[SLUG]/1.0.0/gn`
{% endcolumn %}
{% endcolumns %}

Now, you simply need to  fill in your details to start sending GraphQL queries to this endpoint.

## Appendices

### Sample Query

This query shows all transactions of the PSG Fan Token.

```typescript
const axios = require('axios');

// The GraphQL query (Identical for both providers)
const graphqlQuery = `{
  transfers {
    from
    to
    value
    transactionHash
  }
}`;

// Choose the right URL format depending on the provider:
// const queryUrl = 'https://gateway-arbitrum.network.thegraph.com/api/[api-key]/subgraphs/id/[id]'
// const queryUrl = 'https://api.goldsky.com/api/public/project_[key]/subgraphs/[slug]/1.0.0/gn';

const graphQLRequest = {
  method: 'post',
  url: queryUrl,
  data: {
    query: graphqlQuery,
  },
};

// Send the GraphQL query
axios(graphQLRequest)
  .then((response) => {
    // Handle the response here
    const data = response.data.data
    console.log(data)

  })
  .catch((error) => {
    // Handle any errors
    console.error(error);
  });
```

### Sample code

```json
{
  "data": {
    "transfers": [
      {
        "from": "0x26a3e78fa4d2cbebf6b59b2f84b8fb7c61b52d28",
        "to": "0xdca23d02923d01779fb22959bd2575d64eab4535",
        "value": "1500",
        "transactionHash": "0x000309e9cd3f550e8965381bbd83a35c5cee18f26c33a357f9dbb57450d594ea"
      },
//      ...
  }
}
```

Passing this into the query URL returns this result:

```json
{
  transfers {
    from
    to
    value
    transactionHash
  }
}
```

## Additional resources

For more information about querying data from your subgraph with GraphQL:

{% embed url="<https://thegraph.com/docs/en/subgraphs/querying/best-practices/>" %}
