Skip to main content

NEAR Ref Finance. Quickstart Guide

SubQuery TeamAbout 2 min

NEAR Ref Finance. Quickstart Guide

The objective of this project is to catalog the swap actions performed by the v2.ref-finance.near contract on the NEAR mainnet. It serves as an excellent opportunity to gain practical experience in understanding SubQuery's functionality through a real-world example.

In the earlier Quickstart section , you should have taken note of three crucial files. To initiate the setup of a project from scratch, you can proceed to follow the steps outlined in the initialisation description.

Please initialise a NEAR Network project. Now, let's move forward and update these configurations.

Note

The final code of this project can be found hereopen in new window.

Update Your GraphQL Schema File

The schema.graphql file determines the shape of your data from SubQuery due to the mechanism of the GraphQL query language. Hence, updating the GraphQL Schema file is the perfect place to start. It allows you to define your end goal right at the start.

schema.graphql
type Swap @entity {
  id: ID!
  pool: Pool!
  firstToken: Token!
  secondToken: Token!
}

type Token @entity {
  id: ID!
}

type Pool @entity {
  id: ID!
}

The schema include Swap entity with a unique identifier, associated with a specific Pool and involve two tokens (firstToken and secondToken). The Token type represents a generic token with a unique identifier, and the Pool type represents a pool with a unique identifier.

Note

Importantly, these relationships can not only establish one-to-many connections but also extend to include many-to-many associations. To delve deeper into entity relationships, you can refer to this section. If you prefer a more example-based approach, our dedicated Hero Course Module can provide further insights.

SubQuery simplifies and ensures type-safety when working with GraphQL entities, actions, and transactions.

yarn
yarn codegen

This action will generate a new directory (or update the existing one) named src/types. Inside this directory, you will find automatically generated entity classes corresponding to each type defined in your schema.graphql. These classes facilitate type-safe operations for loading, reading, and writing entity fields. You can learn more about this process in the GraphQL Schema section.

Now that you have made essential changes to the GraphQL Schema file, let’s move forward to the next file.

Your Project Manifest File

The Project Manifest file is an entry point to your project. It defines most of the details on how SubQuery will index and transform the chain data.

For NEAR, there are three types of mapping handlers (and you can have more than one in each project):

  • BlockHandler: On each and every block, run a mapping function
  • TransactionHandlers: On each and every transaction that matches optional filter criteria, run a mapping function
  • ActionHandlers: On each and every transaction action that matches optional filter criteria, run a mapping function

We are indexing all actions with a method name equal to swap and the v2.ref-finance.near contract as the recipient.

project.ts
{
  dataSources: [
    {
      kind: NearDatasourceKind.Runtime, // We use ethereum runtime since NEAR Aurora is a layer-2 that is compatible
      startBlock: 105757726, // You can set any start block you want here. This block was when the sweat_welcome.near address was created
      mapping: {
        file: "./dist/index.js",
        handlers: [
          {
            handler: "handleAction",
            kind: NearHandlerKind.Action,
            filter: {
              type: "FunctionCall",
              methodName: "swap",
              receiver: "v2.ref-finance.near",
            },
          },
        ],
      },
    },
  ];
}

In the provided configuration, when the specified action is indexed, it will be forwarded to a handler known as handleAction.

Check out our Manifest File documentation to get more information about the Project Manifest (project.ts) file.

Next, let’s proceed ahead with the Mapping Function’s configuration.

The handleAction function receives event data whenever an event matches the filters, which you specified previously in the project.ts. Let’s make changes to it, process the relevant transaction action, and save them to the GraphQL entities created earlier.

Update the handleAction function as follows:

src/mappingHandlers.ts
import { Swap, Token, Pool } from "../types";
import { NearAction } from "@subql/types-near";

export async function handleAction(action: NearAction): Promise<void> {
  logger.info(`Swap found at block ${action.transaction.block_height}`);
  // An Action can belong to either a transaction or a receipt
  // To check which one, we can check if action.transaction is null
  // If it is null, then it belongs to a receipt
  if (!action.transaction) {
    return;
  }
  let actions = action.action.args.toJson()["actions"];

  for (let i = 0; i < actions.length; i++) {
    Swap.create({
      id: `${action.transaction.block_height}-${action.transaction.result.id}-${action.id}-${i}`,
      poolId: (await getOrCreatePool(JSON.stringify(actions[i]["pool_id"]))).id,
      firstTokenId: (
        await getOrCreateToken(JSON.stringify(actions[i]["token_in"]))
      ).id,
      secondTokenId: (
        await getOrCreateToken(JSON.stringify(actions[i]["token_out"]))
      ).id,
    }).save();
    logger.info("Swap is saved");
  }
}

async function getOrCreateToken(tokenid: string): Promise<Token> {
  let token = await Token.get(tokenid);
  if (token === undefined) {
    token = Token.create({ id: tokenid });
    await token.save();
  }
  return token;
}

async function getOrCreatePool(poolid: string): Promise<Pool> {
  let pool = await Token.get(poolid);
  if (pool === undefined) {
    pool = Token.create({ id: poolid });
    await pool.save();
  }
  return pool;
}

This code snippet demonstrates how swap within Ref Finance are processed and indexed. First, the code imports specific types.

The handleAction function processes a Near Protocol action, specifically related to a swap. It, first, checks whether the action belongs to a transaction or a receipt. If it's part of a transaction, it extracts a list of actions and iterates through them. For each action, it creates a Swap entity and saves it to the database.

The getOrCreateToken and getOrCreatePool functions are used to retrieve existing tokens/pools or create new ones if they don't exist. These functions are utility functions used by handleAction.

Note

For more information on mapping functions, please refer to our Mappings documentation.

Build Your Project

Next, build your work to run your new SubQuery project. Run the build command from the project's root directory as given here:

yarn
yarn build

Important

Whenever you make changes to your mapping functions, you must rebuild your project.

Now, you are ready to run your first SubQuery project. Let’s check out the process of running your project in detail.

Whenever you create a new SubQuery Project, first, you must run it locally on your computer and test it and using Docker is the easiest and quickiest way to do this.

Run Your Project Locally with Docker

The docker-compose.yml file defines all the configurations that control how a SubQuery node runs. For a new project, which you have just initialised, you won't need to change anything.

However, visit the Running SubQuery Locally to get more information on the file and the settings.

Run the following command under the project directory:

yarn
yarn start:docker

Note

It may take a few minutes to download the required images and start the various nodes and Postgres databases.

Query your Project

Next, let's query our project. Follow these three simple steps to query your SubQuery project:

  1. Open your browser and head to http://localhost:3000.

  2. You will see a GraphQL playground in the browser and the schemas which are ready to query.

  3. Find the Docs tab on the right side of the playground which should open a documentation drawer. This documentation is automatically generated and it helps you find what entities and methods you can query.

Try the following queries to understand how it works for your new SubQuery starter project. Don’t forget to learn more about the GraphQL Query language.

{
  query {
    swaps {
      nodes {
        id
        firstToken {
          id
        }
        secondToken {
          id
        }
        pool {
          id
        }
      }
    }
  }
}

You will see the result similar to below:

{
  "data": {
    "query": {
      "swaps": {
        "nodes": [
          {
            "id": "107215746-6n73gva1H7X2ctEQiQ2kdnVCkvfJpDN9M3zAUzDQmugL-0-2",
            "firstToken": {
              "id": "\"f5cfbc74057c610c8ef151a439252680ac68c6dc.factory.bridge.near\""
            },
            "secondToken": {
              "id": "\"wrap.near\""
            },
            "pool": null
          },
          {
            "id": "107215746-6n73gva1H7X2ctEQiQ2kdnVCkvfJpDN9M3zAUzDQmugL-0-1",
            "firstToken": {
              "id": "\"meta-pool.near\""
            },
            "secondToken": {
              "id": "\"f5cfbc74057c610c8ef151a439252680ac68c6dc.factory.bridge.near\""
            },
            "pool": null
          }
        ]
      }
    }
  }
}

Note

The final code of this project can be found hereopen in new window.

What's next?

Congratulations! You have now a locally running SubQuery project that accepts GraphQL API requests for transferring data.

Tip

Find out how to build a performant SubQuery project and avoid common mistakes in Project Optimisation.

Click here to learn what should be your next step in your SubQuery journey.