Dorian Crutcher
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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/)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully