---
# System prepended metadata

title: The Graph -> NEAR Integration Testnet

---

# The Graph -> NEAR Integration Testnet 

## Overview 

We'll be going over how to set up an indexer on NEAR's testnet using the tools provided by [The Graph](https://thegraph.com/en/). The Graph will enable developers to build subgraphs on the NEAR network allowing developers and users to query information about transactions, contract method calls and more without having to develop and maintain their own custom indexing infrastructure, which takes a huge burden off of the developer. 

The Graph just released their testnet version of their indexer! Let's use this to learn how to set up your own subgraph

## Working Demo 

head on over to [gm-near.surge.sh](https://gm-near.surge.sh/), and you will see a live demo of this integration. 

It let's you say "good morning" and lets you see who was the last person who said "good morning". The application is simple but will give you a good idea of what the process is in order to set this up. 

Here the utility behind this application is to see how many users have previously said "good morning" by indexing this information from the NEAR blockchain itself. 

In the source code of this example you will find 3 files of importance. 

* subgraph.yaml 
* schema.graphql
* mapping.ts

We won't be recreating this full applicaion, but rather we will be using it as a reference to show you how to index your own smart contract. 

## The Smart Contract Code 

The smart contract we'll be working with is quite simple and you can find the repo here
https://github.com/doriancrutcher/near-subgraph-demo-contract.git
```typescript=
/*
 * This is an example of an AssemblyScript smart contract with two simple,
 * symmetric functions:
 *
 * 1. sayGm: say "gm"
 * 2. getGreeter: find out the last account to say "gm"
 *
 * Learn more about writing NEAR smart contracts with AssemblyScript:
 * https://docs.near.org/docs/roles/developer/contracts/assemblyscript
 *
 */

import { Context, logging, storage } from "near-sdk-as";

export function // Exported functions will be part of the public interface for your smart contract.

getGreeter(): string | null {
  // This uses raw `storage.get`, a low-level way to interact with on-chain
  // storage for simple contracts.
  // If you have something more complex, check out persistent collections:
  // https://docs.near.org/docs/roles/developer/contracts/assemblyscript#imports
  return storage.getString("Greeter");
}

export function sayGm(): void {
  const account_id = Context.sender;

  logging.log('{"greeter": "' + account_id + '"}');

  storage.set("Greeter", account_id);
}

```

The contract simply takes the signer's name and puts it in storage under the key "Greeter"

If you have not done so already go to wallet.testnet.near.org to create your NEAR Account Name. 

Afterwards install [NEAR CLI](https://docs.near.org/docs/tools/near-cli#installation), login, and create a new subaccount using the following commands

### Install NEAR CLI 

```
npm install -g near-cli 
```
> Note: You may have to run `sudo` in front of this command to install it globally 


### Login
This will store a key pair to your near account locally onto your machine in the `.near-credentials`  folder, allowing you to use NEAR CLI to interact with your account and the NEAR blockchain
```
near login
```

### Create a SubAccount 
```bash
near create-account sub-acct.example-acct.testnet --masterAccount example-acct.testnet
```


After your sub account is created set this variable to your sub account name 

```bash=
ID=<YOUR SUB ACCOUNT NAME>
```

After you have this setup go ahead and clone the repo and from the root directory run the following in the root directory

```bash=
yarn && yarn build
```

This will install your dependencies and build your contract. All that's left is to deploy your newly compiled smart contract to your sub account.

After you've built your smart contract, navigate into 
```bash
build/release/near-to-subgraph.wasm
```

and run

```bash=
near deploy --accountId $ID --wasmFile near-to-subgraph.wasm
```
You can test your deployment by running 


```bash=
near call $ID sayGm "{}" --account-id <Any of your NEAR Accounts>
```

The output should look like this 

```bash
Receipt: 5PyYRohH9fZzZwzRE7rdZK1C2YsUo4cAkTbCub8uwdFp
        Log [subaccount.youraccount.near]: {"greeter": "youraccount.testnet"}
Transaction Id A4rxwCRdFnAZG121k5UxBiCkgdwUAKsVYJjvoRivp4va
To see the transaction in the transaction explorer, please open this url in your browser
https://explorer.mainnet.near.org/transactions/A4rxwCRdFnAZG121k5UxBiCkgdwUAKsVYJjvoRivp4va
''
```

## Creating a SubGraph!

Ok now here comes the fun part haha.

Now that you have your contract setup and deployed, it's time to create a subgraph! 

Luckily The Graph does a lot of the work for you. 

Craete an empty repo on github with the name of your choosing. then go to [The Graph Dashboard](https://thegraph.com/hosted-service/dashboard) and sign in with your github to create your own subgraph. 

![](https://i.imgur.com/lcbTIY8.png)

After that there are four easy steps to follow to create your subgraph nicely displayed for you here:

![](https://i.imgur.com/w3DoKOQ.png)

Simply fill out the form as you see here below using the github repo that you created earlier

![](https://i.imgur.com/9HoetWW.png)

Af†erwards simply hit the `create subgraph` button 

![](https://i.imgur.com/7Dojn6q.png)

Afterwards follow the remainign steps you see here on screen 

![](https://i.imgur.com/1u1iBbn.png)

> Be aware that when installing these packages you may have to use the keyword `sudo` to install these packages globally if you're running on mac or linux. 

You may get an error otherwise

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

or 

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

### Initializing a SubGraph 

In your terminal type in 

```bash 
graph init
```

![](https://i.imgur.com/lotcCb7.png)

and enter your user name and subgraph name as said in the cli. 

then select `near` as your protocol.

![](https://i.imgur.com/sq0xFZl.png)

Here you can see that the **NEAR Network** is set to `near-mainnet`. This is ok for now, The Graph is working on adding a testnet option to this but keep following along and you'll see how to configure your subgraph for `testnet`

run 
```bash
graph auth --product hosted-service <ACCESS_TOKEN>
```


You can find the access token on the dashboard just above where the "install init deploy" steps are. 

After that `cd` into your subgraph repo as shown in step two and run `yarn deploy`

## Subgraph Code 

Open up your current directory in a code editor like VS code or run `code .` from inside the subgraph file you just created. 

You will notice the `subgraph.yaml mapping.ts and schema.graphql` files. These three files are going to be your core setup for configuring your subgraph


We will go through each one of these. It's important to note that whenever you modify the `schema.ts` and `subgraph.yaml` file be sure to run `graph codegen` in your terminal to generate a `schema.ts` file which will generate type classes identified from the manifest (`subgraph.yaml` file)

## Configuring the subgraph to Work on Testnet

To get configure your subgraph to work on testnet, set the network property from `near-mainnet` to `near-testnet`


## subgraph.yaml

```yaml=
specVersion: 0.0.4
description: Good Morning NEAR
repository: https://github.com/graphprotocol/example-subgraph/tree/near-receipts-example
schema:
  file: ./schema.graphql
dataSources:
  - kind: near
    name: receipts
    network: near-testnet
    source:
      account: "sub-account.youraccount.testnet"
      startBlock: 50736511
    mapping:
      apiVersion: 0.0.5
      language: wasm/assemblyscript
      file: ./src/mapping.ts
      entities:
        - Greeter
        - Greeting
      receiptHandlers:
        - handler: handleReceipt
```

Lines 1-3: Just consists of some metadata

Lines 4-5: Reference a schema file which we'll discuss a bit later

Lines 6-21: We have our datasources

Line 7: Blockchain for theGraph to index

Line 9: Network  on the blockchain we ware indexing in this case it will be the near-mainnet

Line 10-12: In this source section you'll be detailing the contract account, and the starting block you want to index

Line 20-21: 
The receiptHandlers essentially states that everytime the indexer reads a new receipt run this handler, "handleReceipt"

The **startingBlock** here is important. You can retreive that by going to the [NEAR Explorer](https://explorer.near.org/stats) searching the name of the sub account and getting the block number from the first transaction you created when testing your contrat deployment 

>NOTE: search name -> select transaction -> click on block hash 

![](https://i.imgur.com/vTz2PFt.png)

(that number 78042607 is what you will enter as your starting block)



## schema.graphql

```graphql=

type Greeter @entity {
  id: ID!
  name: String!
  greetings: [Greeting!] @derivedFrom(field: "greeter")
}

type Greeting @entity {
  id: ID!
  greeter: Greeter!
  timestamp: BigInt!
}
```


The `Greeter` type will keep track of who said goodmorning and how many times they have said it

The `Greeting` type essentially will record the id, and timestamp  of the person out of every single greeting that happens 

## mapping.ts

In the `src` file you will find a mapping.ts file. 

```typescript=
import { near, BigInt, log } from "@graphprotocol/graph-ts";
import { Greeter, Greeting } from "../generated/schema";

export function handleReceipt(receipt: near.ReceiptWithOutcome): void {
  const actions = receipt.receipt.actions;
  for (let i = 0; i < actions.length; i++) {
    handleAction(actions[i], receipt.receipt, receipt.block.header);
  }
}

function handleAction(
  action: near.ActionValue,
  receipt: near.ActionReceipt,
  blockHeader: near.BlockHeader
): void {
  if (action.kind != near.ActionKind.FUNCTION_CALL) {
    log.info("Early return: {}", ["Not a function call"]);
    return;
  }

  const functionCall = action.toFunctionCall();
  if (functionCall.methodName == "sayGm") {
    let greeter = Greeter.load(receipt.signerId);
    if (greeter == null) {
      greeter = new Greeter(receipt.signerId);
      greeter.name = receipt.signerId;
      greeter.save();
    }

    const greeting = new Greeting(receipt.id.toBase58());
    greeting.greeter = greeter.id;
    greeting.timestamp = BigInt.fromU64(blockHeader.timestampNanosec);
    greeting.save();
  } else {
    log.info("Not processed - FunctionCall is: {}", [functionCall.methodName]);
  }
}

```

Lines 4-9: Here is the handleReceipt functon that was mentioned earlier. 

Essentially it will collect an array of actions, maps through them and for each action the handle action function gets called. 

Line 21-28: ifthe methodName matches "sayGM" 

then they will check if the greeter has said a greeting before and if they haven't then they'll be added to the application's register. 

lines: 30-36 will then save the greetings


## Deploy Your Subgraph! 

 Once you have these three files filled out. 

Run the following in side of your local subgraph repository 

```bash 
yarn build && yarn deploy
```

You will receive your subgraph endpoints..

![](https://i.imgur.com/6IBhQ39.png)


Go back to your subgraph dashboard and you can see some demo queries laid out for you. 

Hit the "Play Button" to run these qureies and your output should display in the center output column. 

In this screenshot you can see the number of times I called this contract.
![](https://i.imgur.com/c1Nrk27.png)


And there you go! 

If you have any questions you can go to theGraph [discord](https://discord.gg/vtvv7FP), or find me (Dorian ) on the [NEAR Discord](http://near.chat/)
