Options
All
  • Public
  • Public/Protected
  • All
Menu

@truffle/db

Introduction

@truffle/db tracks information about smart contracts and their development histories. It organizes this information almost entirely in the form of content-addressed, immutable resources and seeks to serve as a complete system of record, suitable to perfectly reproduce prior builds and to act as a single source of truth.

This system of record covers the full gamut of concepts related to smart contract development, from source code to deployment. Among other features, it includes mechanisms for tracking the continuity of a smart contract as it is implemented and even as the network to which it's deployed experiences a hard-fork. Blockchain data is not forgotten — neither should blockchain metadata.

At a high-level, this package provides a GraphQL interface and stores data via one of several persistence backends thanks to PouchDB. Use of this package directly is intended mostly for other tools – end users can find interfaces to @truffle/db by way of Truffle itself, e.g. with the truffle db serve command that starts a GraphQL Playground HTTP server.

This documentation serves to organize the modules and namespaces included in the package, both for tool developer reference and for continued work on @truffle/db itself. (Disclaimer: as a result, this API documentation may serve neither of these purposes well. Please reach out with questions and/or to suggest helpful clarifications!)

Continue reading below for an overview and full index of this package's exports.


Example query
Figure: Example query for a project's MagicSquare contract

Contents

For quick reference, this documentation summary contains the following headings:

Core library interface

Instantiating @truffle/db

This package defines the primary connect() function, which returns an object adhering to the Db interface for given ConnectOptions. This Db interface defines the async db.execute() method that accepts a GraphQL request and returns a GraphQL response.

GraphQL schema

@truffle/db makes its GraphQL schema available as the exported Graph.schema variable, or view the SDL details in the Graph namespace description.

Data model

Structure

Data is organized as collections of representations of key concepts related to smart contract development. Each collection specifies:

  • A collection name
  • A complete resource type (exported as Resources.Resource<"<collectionName>">; for retrieved records)
  • An input type (exported as Resources.Input<"<collectionName>">; for new records)
  • A subset list of fields from its input type whose values strictly compose to form a resource's content-addressable ID.
  • Whether its resources are mutable (note: currently, only "projectNames" resources are mutable)
  • Whether its resources are named (meaning that resources of the same and collection will be tracked by name, for continuity and easy lookup)

List of collections

@truffle/db defines the following collections:

This list is not intended to be static; since @truffle/db is in early release, it may make sense to add new collections / change relationships between existing collections. Backwards compatibility is planned but not yet guaranteed.

Other interfaces

JavaScript / TypeScript interface

This package exposes programmatic interfaces for working with the resources listed above:

  • Process.resources, a set of four generator functions that encode logic for storing and retrieving resources for a given collectionName.

  • [[Process.Run.forDb()]], to construct an async helper that facilitates requests/responses from/to the above generator functions against a given Db instance.

  • generateId(), to predict the ID for a given resource input. This can be useful for determining how to query for additional information about entities with known properties.

In addition, please see the Resources module for handy helper types for dealing with @truffle/db entities.

Network abstraction

Keeping track of blockchain networks is nontrivial if you want to handle network forks/re-orgs. To accommodate this, @truffle/db models blockchain networks as individual point-in-time slices at various historic blocks. As a result, a single blockchain network (e.g., "mainnet") can and will comprise many disparate DataModel.Network resources, one for each block previously added.

This approach preserves immutability but requires additional record-keeping in order to provide the commonly-understood continuous view of a blockchain. To maintain this continuity, @truffle/db defines the DataModel.NetworkGenealogy resource, each of which links two DataModel.Network resources, stating that a given network is ancestor to another. This collection of genealogy pairs is then used to compute a sparse list of past historic blocks for a given latest network.

The process to populate @truffle/db with correct network data involves alternately querying GraphQL and the underlying blockchain JSON-RPC.

This package provides the Network abstraction to simplify this process.

Example usage
import type { Provider } from "web3/providers";
declare const provider: Provider;

import { connect, Network } from "@truffle/db";

const db = connect({
  // ...
});

const network = await Network.initialize({
  provider,
  db: connect({
    // ...
  }),
  network: { name: "mainnet" }
});

await network.includeBlocks([
  { height: 10000000, hash: "0x..." },
  // ...
]);

const { historicBlock } = network.knownLatest;

Truffle project abstraction

This package also provides an abstraction to interface with other Truffle data formats, namely WorkflowCompileResult, returned by @truffle/workflow-compile, and the Truffle contract artifacts format, defined by @truffle/contract-schema. This abstraction covers two classes:

HTTP interface

This package exposes the serve() function, which returns an Apollo Server instance, adherent to the Node.js http.Server interface. This server runs GraphQL Playground for the browser and also accepts plain GraphQL requests.

(This is a handy way to explore @truffle/db, since it offers schema-aware auto-completion and the ability to explore relationships between entities.)

Additional materials

This package listing contains other namespaces not mentioned above. These are for internal use and not to be considered part of @truffle/db's public interface.

For those curious about these internals, of particular note is the Meta namespace, which houses underlying collections-agnostic logic for integrating GraphQL and PouchDB.

Index

Other

ConnectOptions

ConnectOptions: ConnectOptions<Collections>

Options for connecting to @truffle/db

type ConnectOptions = {
  workingDirectory: string;
  adapter?:
    | {
        name: "couch";
        settings?: Meta.Pouch.Adapters.Couch.DatabasesSettings;
      }
    | {
        name: "fs";
        settings?: Meta.Pouch.Adapters.Fs.DatabasesSettings;
      }
    | {
        name: "memory";
        settings?: Meta.Pouch.Adapters.Memory.DatabasesSettings;
      }
    | {
        name: "sqlite";
        settings?: Meta.Pouch.Adapters.Sqlite.DatabasesSettings;
      }
};

See individual settings interfaces:

Default adapter: { name: "sqlite" }

We recommend using only "sqlite" and "couch" at this time.

Db

An instance of @truffle/db

Defines the db.execute() method, which accepts GraphQL requests and returns GraphQL responses.

See connect() for how to instantiate this interface.

example
import gql from "graphql-tag";
import { connect, Db } from "@truffle/db";

const db: Db = connect({
  // ...
});

const {
  project: {
    contract: {
      id,
      abi,
      processedSource,
      callBytecode
    }
  }
} = await db.execute(gql`
  query {
    project(id: "0x...") {
      contract(name: "MagicSquare") {
        id
        abi { json }
        processedSource {
          source { contents }
          ast { json }
        }
        callBytecode {
          bytes
          linkReferences { name length offsets }
          instructions { opcode programCounter pushData }
        }
      }
    }
  }
`);

Const connect

Const generateId

Const serve

Generated using TypeDoc