Giter VIP home page Giter VIP logo

squid-substrate-template's Introduction

Squid template project

A starter Squid project to demonstrate its structure and conventions. It accumulates kusama account transfers and serves them via GraphQL API.

Summary

Prerequisites

  • node 16.x
  • docker
  • npm -- note that yarn package manager is not supported

Quickly running the sample

Example commands below use sqd. Please install it before proceeding.

# 1. Install dependencies
npm ci

# 2. Start target Postgres database and detach
sqd up

# 3. Build the project
sqd build

# 4. Start both the squid processor and the GraphQL server
sqd run .

A GraphiQL playground will be available at localhost:4350/graphql.

Public archives for Parachains

Subsquid provides archive data sources for most parachains. Use lookupArchive(<network name>, <lookup filters>) from @subsquid/archive-registry to look up the archive endpoint by the network name, e.g.

processor.setDataSource({
  archive: lookupArchive("kusama", { release: "ArrowSquid" })
  //...
});

To make sure you're indexing the right chain one can additionally filter by the genesis block hash:

processor.setDataSource({
  archive: lookupArchive("kusama", { 
    release: "ArrowSquid",
    genesis: "0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe" 
  }),
  //...
});

If the chain is not yet supported, you can still index it using RPC ingestion. If you take this route, use metadata exporer with Substrate typegen for help with decoding.

You can also fill out this form to submit a request for an Archive/Subsquid Network dataset.

Self-hosted archive

Self-hosted Archives are deprecated by the ArrowSquid release. Keep an eye on updates on Subsquid Network and use it instead once it is released.

Dev flow

1. Define database schema

Start development by defining the schema of the target database via schema.graphql. Schema definition consists of regular graphql type declarations annotated with custom directives. Full description of schema.graphql dialect is available here.

2. Generate TypeORM classes

Mapping developers use TypeORM entities to interact with the target database during data processing. All necessary entity classes are generated by the squid framework from schema.graphql. This is done by running npx squid-typeorm-codegen or (equivalently) sqd codegen command.

3. Generate database migration

All database changes are applied through migration files located at db/migrations. squid-typeorm-migration(1) tool provides several commands to drive the process. It is all TypeORM under the hood.

# Connect to database, analyze its state and generate migration to match the target schema.
# The target schema is derived from entity classes generated earlier.
# Don't forget to compile your entity classes beforehand!
npx squid-typeorm-migration generate

# Create template file for custom database changes
npx squid-typeorm-migration create

# Apply database migrations from `db/migrations`
npx squid-typeorm-migration apply

# Revert the last performed migration
npx squid-typeorm-migration revert         

Available sqd shortcuts:

# Build the project, remove any old migrations, then run `npx squid-typeorm-migration generate`
sqd migration:generate

# Run npx squid-typeorm-migration apply
sqd migration:apply

4. Generate TypeScript definitions for substrate events, calls and storage

This is an optional part, but it is very advisable.

Event, call and runtime storage data come to mapping handlers as raw untyped json. While it is possible to work with raw untyped json data, it's extremely error-prone and the json structure may change over time due to runtime upgrades.

Squid framework provides a tool for generating type-safe wrappers around events, calls and runtime storage items for each historical change in the spec version. See the Substrate typegen documentation page.

Deploy the Squid

After a local run, obtain a deployment key by signing into Subsquid Cloud and run

npx sqd auth -k YOUR_DEPLOYMENT_KEY

Next, inspect the Squid CLI help to deploy and manage your squid:

npx sqd squid --help

For more information, consult the Deployment Guide.

Project conventions

Squid tools assume a certain project layout.

  • All compiled js files must reside in lib and all TypeScript sources in src. The layout of lib must reflect src.
  • All TypeORM classes must be exported by src/model/index.ts (lib/model module).
  • Database schema must be defined in schema.graphql.
  • Database migrations must reside in db/migrations and must be plain js files.
  • squid-*(1) executables consult .env file for a number of environment variables.

See the full desription in the documentation.

Types bundle

Substrate chains that have blocks with metadata versions below 14 don't provide enough information to decode their data. For those chains, external type definitions are required.

Subsquid tools include definitions for many chains, however sometimes external definitions are still required.

You can pass them as a special json file (types bundle) of the following structure:

{
  "types": {
    "AccountId": "[u8; 32]"
  },
  "typesAlias": {
    "assets": {
      "Balance": "u64"
    }
  },
  "versions": [
    {
      "minmax": [0, 1000], // spec version range with inclusive boundaries
      "types": {
        "AccountId": "[u8; 16]"
      },
      "typesAlias": {
        "assets": {
          "Balance": "u32"
        }
      }
    }
  ]
}

All fields in the type bundle are optional and applied on top of a fixed set of well-known frame types.

Note, that although the structure of subsquid types bundle is very similar to the one from polkadot.js, those two are not fully compatible.

Differences from polkadot.js

Polkadot.js provides lots of specialized classes for various types of data. Even primitives like u32 are exposed through special classes. In contrast, the squid framework works only with plain js primitives and objects. For instance, account data is passed to the handler context as a plain byte array. To convert it into a standard human-readable format one should explicitly use a utility lib @subsquid/ss58:

    // ...
    from: ss58.codec('kusama').encode(rec.from),
    to: ss58.codec('kusama').encode(rec.to),

Graphql server extensions

It is possible to extend squid-graphql-server(1) with custom type-graphql resolvers and to add request validation. For more details, consult docs.

squid-substrate-template's People

Contributors

abernatskiy avatar belopash avatar dzhelezov avatar eldargab avatar ma-shulgin avatar mo4islona avatar raekwoniii avatar renovate[bot] avatar rikonorus avatar tmcgroul avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

squid-substrate-template's Issues

License missing

Please add a License file, otherwise it's not legal to use/fork this repo

Ingest service stuck at block 0

I am running a Macbook air with M1 chip but have replicated it with a macbook pro machine with intel chip.

After running the docker compose -f archive/docker-compose.yml up command, the archive-ingest-1 service gets stuck at the first block. I've attached an image of the output below.

Screenshot 2022-08-30 at 3 58 17 PM

I am running a substrate node locally and have changed the command of the ingest service to "ws://host.docker.internal:9944".

I can see my chain produce many blocks however even querying the gateway service with the below query gives blockHeight 0.

query {
   metadata {
      blockHeight
      blockHash
  } 
}

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: File contents are invalid JSON but parse using JSON5. Support for this will be removed in a future release so please change to a support .json5 file name or ensure correct JSON syntax.

This repository currently has no open or pending branches.

Detected dependencies

docker-compose
docker-compose.yml
npm
package.json
  • @subsquid/graphql-server ^4.5.1
  • @subsquid/ss58 ^2.0.2
  • @subsquid/substrate-processor ^8.3.0
  • @subsquid/typeorm-migration ^1.3.0
  • @subsquid/typeorm-store ^1.4.0
  • @subsquid/substrate-metadata-explorer ^3.1.2
  • @subsquid/substrate-typegen ^8.1.0
  • @subsquid/typeorm-codegen ^2.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Location: renovate.json
Error type: Invalid JSON (parsing failed)
Message: Syntax error: expecting String near ], // "a

Crustio Tutorial Error when running $npx squid-substrate-typegen typegen.json

Hi there,

Going through your docs, and testing the Crustio tutorial. When I try to execute

npx squid-substrate-typegen typegen.json

I get the following error.

Error: Type MerchantLedger is not defined at OldTypeRegistry.buildNamedType (/home/ksm-node/Github/mu-squid/node_modules/@subsquid/substrate-metadata/lib/old/typeRegistry.js:284:15) at OldTypeRegistry.buildScaleType (/home/ksm-node/Github/mu-squid/node_modules/@subsquid/substrate-metadata/lib/old/typeRegistry.js:208:29) at OldTypeRegistry.use (/home/ksm-node/Github/mu-squid/node_modules/@subsquid/substrate-metadata/lib/old/typeRegistry.js:78:35) at /home/ksm-node/Github/mu-squid/node_modules/@subsquid/substrate-metadata/lib/chainDescription.js:529:42 at Array.forEach (<anonymous>) at /home/ksm-node/Github/mu-squid/node_modules/@subsquid/substrate-metadata/lib/chainDescription.js:496:31 at /home/ksm-node/Github/mu-squid/node_modules/@subsquid/substrate-metadata/lib/chainDescription.js:596:21 at Array.forEach (<anonymous>) at FromOld.forEachPallet (/home/ksm-node/Github/mu-squid/node_modules/@subsquid/substrate-metadata/lib/chainDescription.js:593:45) at FromOld.storage (/home/ksm-node/Github/mu-squid/node_modules/@subsquid/substrate-metadata/lib/chainDescription.js:492:14)

at BalancesTransferEvent.get asV269 ?

AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:

  (0, assert_1.default)(this.isV269)

    at BalancesTransferEvent.get asV269 [as asV269] (/Users/polkadot/Desktop/project/squid-template/lib/types/events.js:24:30)
    at BalancesTransferEvent.get asLatest [as asLatest] (/Users/polkadot/Desktop/project/squid-template/lib/types/events.js:33:21)
    at getTransferEvent (/Users/polkadot/Desktop/project/squid-template/lib/processor.js:71:18)
    at Array.<anonymous> (/Users/polkadot/Desktop/project/squid-template/lib/processor.js:34:22)
    at /Users/polkadot/Desktop/project/squid-template/node_modules/@subsquid/substrate-processor/lib/processor.js:189:51
    at /Users/polkadot/Desktop/project/squid-template/node_modules/@subsquid/substrate-processor/lib/db.js:62:19
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  generatedMessage: true,
  code: 'ERR_ASSERTION',
  actual: false,
  expected: true,
  operator: '=='

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.