---
title: Subgraph Manifest
---

## Overview

The Subgraph manifest, `subgraph.yaml`, defines the smart contracts & network your Subgraph will index, the events from these contracts to pay attention to, and how to map event data to entities that Graph Node stores and allows to query.

The **Subgraph definition** consists of the following files:

- `subgraph.yaml`: Contains the Subgraph manifest

- `schema.graphql`: A GraphQL schema defining the data stored for your Subgraph and how to query it via GraphQL

- `mapping.ts`: [AssemblyScript Mappings](https://github.com/AssemblyScript/assemblyscript) code that translates event data into entities defined in your schema (e.g. `mapping.ts` in this guide)

### Subgraph Capabilities

A single Subgraph can:

- Index data from multiple smart contracts (but not multiple networks).

- Index data from IPFS files using File Data Sources.

- Add an entry for each contract that requires indexing to the `dataSources` array.

The full specification for Subgraph manifests can be found [here](https://github.com/graphprotocol/graph-node/blob/master/docs/subgraph-manifest.md).

For the example Subgraph listed above, `subgraph.yaml` is:

```yaml
specVersion: 1.3.0
description: Gravatar for Ethereum
repository: https://github.com/graphprotocol/graph-tooling
schema:
  file: ./schema.graphql
indexerHints:
  prune: auto
dataSources:
  - kind: ethereum/contract
    name: Gravity
    network: mainnet
    source:
      address: '0x2E645469f354BB4F5c8a05B3b30A929361cf77eC'
      abi: Gravity
      startBlock: 6175244
      endBlock: 7175245
    context:
      foo:
        type: Bool
        data: true
      bar:
        type: String
        data: 'bar'
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.9
      language: wasm/assemblyscript
      entities:
        - Gravatar
      abis:
        - name: Gravity
          file: ./abis/Gravity.json
      eventHandlers:
        - event: NewGravatar(uint256,address,string,string)
          handler: handleNewGravatar
        - event: UpdatedGravatar(uint256,address,string,string)
          handler: handleUpdatedGravatar
      callHandlers:
        - function: createGravatar(string,string)
          handler: handleCreateGravatar
      blockHandlers:
        - handler: handleBlock
        - handler: handleBlockWithCall
          filter:
            kind: call
      file: ./src/mapping.ts
```

## Subgraph Entries

> Important Note: Be sure you populate your Subgraph manifest with all handlers and [entities](/subgraphs/developing/creating/ql-schema/).

The important entries to update for the manifest are:

- `specVersion`: a semver version that identifies the supported manifest structure and functionality for the Subgraph. The latest version is `1.3.0`. See [specVersion releases](#specversion-releases) section to see more details on features & releases.

- `description`: a human-readable description of what the Subgraph is. This description is displayed in Graph Explorer when the Subgraph is deployed to Subgraph Studio.

- `repository`: the URL of the repository where the Subgraph manifest can be found. This is also displayed in Graph Explorer.

- `features`: a list of all used [feature](#experimental-features) names.

- `indexerHints.prune`: Defines the retention of historical block data for a Subgraph. See [prune](#prune) in [indexerHints](#indexer-hints) section.

- `dataSources.source`: the address of the smart contract the Subgraph sources, and the ABI of the smart contract to use. The address is optional; omitting it allows you to index matching events from all contracts.

- `dataSources.source.startBlock`: the optional number of the block that the data source starts indexing from. In most cases, we suggest using the block in which the contract was created.

- `dataSources.source.endBlock`: The optional number of the block that the data source stops indexing at, including that block. Minimum spec version required: `0.0.9`.

- `dataSources.context`: key-value pairs that can be used within Subgraph mappings. Supports various data types like `Bool`, `String`, `Int`, `Int8`, `BigDecimal`, `Bytes`, `List`, and `BigInt`. Each variable needs to specify its `type` and `data`. These context variables are then accessible in the mapping files, offering more configurable options for Subgraph development.

- `dataSources.mapping.entities`: the entities that the data source writes to the store. The schema for each entity is defined in the schema.graphql file.

- `dataSources.mapping.abis`: one or more named ABI files for the source contract as well as any other smart contracts that you interact with from within the mappings.

- `dataSources.mapping.eventHandlers`: lists the smart contract events this Subgraph reacts to and the handlers in the mapping—./src/mapping.ts in the example—that transform these events into entities in the store.

- `dataSources.mapping.callHandlers`: lists the smart contract functions this Subgraph reacts to and handlers in the mapping that transform the inputs and outputs to function calls into entities in the store.

- `dataSources.mapping.blockHandlers`: lists the blocks this Subgraph reacts to and handlers in the mapping to run when a block is appended to the chain. Without a filter, the block handler will be run on every block. An optional call-filter can be provided by adding a `filter` field with `kind: call` to the handler. This will only run the handler if the block contains at least one call to the data source contract.

A single Subgraph can index data from multiple smart contracts. Add an entry for each contract from which data needs to be indexed to the `dataSources` array.

## Event Handlers

Event handlers in a Subgraph react to specific events emitted by smart contracts on the blockchain and trigger handlers defined in the Subgraph's manifest. This enables Subgraphs to process and store event data according to defined logic.

### Defining an Event Handler

An event handler is declared within a data source in the Subgraph's YAML configuration. It specifies which events to listen for and the corresponding function to execute when those events are detected.

```yaml
dataSources:
  - kind: ethereum/contract
    name: Gravity
    network: dev
    source:
      address: '0x731a10897d267e19b34503ad902d0a29173ba4b1'
      abi: Gravity
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.9
      language: wasm/assemblyscript
      entities:
        - Gravatar
        - Transaction
      abis:
        - name: Gravity
          file: ./abis/Gravity.json
      eventHandlers:
        - event: Approval(address,address,uint256)
          handler: handleApproval
        - event: Transfer(address,address,uint256)
          handler: handleTransfer
          topic1: ['0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', '0xc8dA6BF26964aF9D7eEd9e03E53415D37aA96325'] # Optional topic filter which filters only events with the specified topic.
```

## Call Handlers

While events provide an effective way to collect relevant changes to the state of a contract, many contracts avoid generating logs to optimize gas costs. In these cases, a Subgraph can subscribe to calls made to the data source contract. This is achieved by defining call handlers referencing the function signature and the mapping handler that will process calls to this function. To process these calls, the mapping handler will receive an `ethereum.Call` as an argument with the typed inputs to and outputs from the call. Calls made at any depth in a transaction's call chain will trigger the mapping, allowing activity with the data source contract through proxy contracts to be captured.

Call handlers will only trigger in one of two cases: when the function specified is called by an account other than the contract itself or when it is marked as external in Solidity and called as part of another function in the same contract.

> **Note:** Call handlers currently depend on the Parity tracing API. Certain networks, such as BNB chain and Arbitrum, do not support this API. If a Subgraph indexing one of these networks contains one or more call handlers, it will not start syncing. Subgraph developers should instead use event handlers. These are far more performant than call handlers, and are supported on every evm network.

### Defining a Call Handler

To define a call handler in your manifest, simply add a `callHandlers` array under the data source you would like to subscribe to.

```yaml
dataSources:
  - kind: ethereum/contract
    name: Gravity
    network: mainnet
    source:
      address: '0x731a10897d267e19b34503ad902d0a29173ba4b1'
      abi: Gravity
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.9
      language: wasm/assemblyscript
      entities:
        - Gravatar
        - Transaction
      abis:
        - name: Gravity
          file: ./abis/Gravity.json
      callHandlers:
        - function: createGravatar(string,string)
          handler: handleCreateGravatar
```

The `function` is the normalized function signature to filter calls by. The `handler` property is the name of the function in your mapping you would like to execute when the target function is called in the data source contract.

### Mapping Function

Each call handler takes a single parameter that has a type corresponding to the name of the called function. In the example Subgraph above, the mapping contains a handler for when the `createGravatar` function is called and receives a `CreateGravatarCall` parameter as an argument:

```typescript
import { CreateGravatarCall } from '../generated/Gravity/Gravity'
import { Transaction } from '../generated/schema'

export function handleCreateGravatar(call: CreateGravatarCall): void {
  let id = call.transaction.hash
  let transaction = new Transaction(id)
  transaction.displayName = call.inputs._displayName
  transaction.imageUrl = call.inputs._imageUrl
  transaction.save()
}
```

The `handleCreateGravatar` function takes a new `CreateGravatarCall` which is a subclass of `ethereum.Call`, provided by `@graphprotocol/graph-ts`, that includes the typed inputs and outputs of the call. The `CreateGravatarCall` type is generated for you when you run `graph codegen`.

## Block Handlers

In addition to subscribing to contract events or function calls, a Subgraph may want to update its data as new blocks are appended to the chain. To achieve this a Subgraph can run a function after every block or after blocks that match a pre-defined filter.

### Supported Filters

#### Call Filter

```yaml
filter:
  kind: call
```

_The defined handler will be called once for every block which contains a call to the contract (data source) the handler is defined under._

> **Note:** The `call` filter currently depends on the Parity tracing API. Certain networks, such as BNB chain, Arbitrum, Polygon, and Optimism do not support this API. If a Subgraph indexing one of these networks contains one or more block handlers with a `call` filter, it will not start syncing.

The absence of a filter for a block handler will ensure that the handler is called every block. A data source can only contain one block handler for each filter type.

```yaml
dataSources:
  - kind: ethereum/contract
    name: Gravity
    network: dev
    source:
      address: '0x731a10897d267e19b34503ad902d0a29173ba4b1'
      abi: Gravity
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.9
      language: wasm/assemblyscript
      entities:
        - Gravatar
        - Transaction
      abis:
        - name: Gravity
          file: ./abis/Gravity.json
      blockHandlers:
        - handler: handleBlock
        - handler: handleBlockWithCallToContract
          filter:
            kind: call
```

#### Polling Filter

> **Requires `specVersion` >= 0.0.8**

> **Note:** Polling filters are only available on dataSources of `kind: ethereum`.

```yaml
blockHandlers:
  - handler: handleBlock
    filter:
      kind: polling
      every: 10
```

The defined handler will be called once for every `n` blocks, where `n` is the value provided in the `every` field. This configuration allows the Subgraph to perform specific operations at regular block intervals.

#### Once Filter

> **Requires `specVersion` >= 0.0.8**

> **Note:** Once filters are only available on dataSources of `kind: ethereum`.

```yaml
blockHandlers:
  - handler: handleOnce
    filter:
      kind: once
```

The defined handler with the once filter will be called only once before all other handlers run. This configuration allows the Subgraph to use the handler as an initialization handler, performing specific tasks at the start of indexing.

```ts
export function handleOnce(block: ethereum.Block): void {
  let data = new InitialData(Bytes.fromUTF8('initial'))
  data.data = 'Setup data here'
  data.save()
}
```

### Mapping Function

The mapping function will receive an `ethereum.Block` as its only argument. Like mapping functions for events, this function can access existing Subgraph entities in the store, call smart contracts and create or update entities.

```typescript
import { ethereum } from '@graphprotocol/graph-ts'

export function handleBlock(block: ethereum.Block): void {
  let id = block.hash
  let entity = new Block(id)
  entity.save()
}
```

## Anonymous Events

If you need to process anonymous events in Solidity, that can be achieved by providing the topic 0 of the event, as in the example:

```yaml
eventHandlers:
  - event: LogNote(bytes4,address,bytes32,bytes32,uint256,bytes)
    topic0: '0x644843f351d3fba4abcd60109eaff9f54bac8fb8ccf0bab941009c21df21cf31'
    handler: handleGive
```

An event will only be triggered when both the signature and topic 0 match. By default, `topic0` is equal to the hash of the event signature.

## Transaction Receipts in Event Handlers

Starting from `specVersion` `0.0.5` and `apiVersion` `0.0.7`, event handlers can have access to the receipt for the transaction which emitted them.

To do so, event handlers must be declared in the Subgraph manifest with the new `receipt: true` key, which is optional and defaults to false.

```yaml
eventHandlers:
  - event: NewGravatar(uint256,address,string,string)
    handler: handleNewGravatar
    receipt: true
```

Inside the handler function, the receipt can be accessed in the `Event.receipt` field. When the `receipt` key is set to `false` or omitted in the manifest, a `null` value will be returned instead.

## Order of Triggering Handlers

The triggers for a data source within a block are ordered using the following process:

1.  Event and call triggers are first ordered by transaction index within the block.
2.  Event and call triggers within the same transaction are ordered using a convention: event triggers first then call triggers, each type respecting the order they are defined in the manifest.
3.  Block triggers are run after event and call triggers, in the order they are defined in the manifest.

These ordering rules are subject to change.

> **Note:** When new [dynamic data source](#data-source-templates-for-dynamically-created-contracts) are created, the handlers defined for dynamic data sources will only start processing after all existing data source handlers are processed, and will repeat in the same sequence whenever triggered.

## Data Source Templates

A common pattern in EVM-compatible smart contracts is the use of registry or factory contracts, where one contract creates, manages, or references an arbitrary number of other contracts that each have their own state and events.

The addresses of these sub-contracts may or may not be known upfront and many of these contracts may be created and/or added over time. This is why, in such cases, defining a single data source or a fixed number of data sources is impossible and a more dynamic approach is needed: _data source templates_.

### Data Source for the Main Contract

First, you define a regular data source for the main contract. The snippet below shows a simplified example data source for the [Uniswap](https://uniswap.org) exchange factory contract. Note the `NewExchange(address,address)` event handler. This is emitted when a new exchange contract is created onchain by the factory contract.

```yaml
dataSources:
  - kind: ethereum/contract
    name: Factory
    network: mainnet
    source:
      address: '0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95'
      abi: Factory
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.9
      language: wasm/assemblyscript
      file: ./src/mappings/factory.ts
      entities:
        - Directory
      abis:
        - name: Factory
          file: ./abis/factory.json
      eventHandlers:
        - event: NewExchange(address,address)
          handler: handleNewExchange
```

### Data Source Templates for Dynamically Created Contracts

Then, you add _data source templates_ to the manifest. These are identical to regular data sources, except that they lack a pre-defined contract address under `source`. Typically, you would define one template for each type of sub-contract managed or referenced by the parent contract.

```yaml
dataSources:
  - kind: ethereum/contract
    name: Factory
    # ... other source fields for the main contract ...
templates:
  - name: Exchange
    kind: ethereum/contract
    network: mainnet
    source:
      abi: Exchange
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.9
      language: wasm/assemblyscript
      file: ./src/mappings/exchange.ts
      entities:
        - Exchange
      abis:
        - name: Exchange
          file: ./abis/exchange.json
      eventHandlers:
        - event: TokenPurchase(address,uint256,uint256)
          handler: handleTokenPurchase
        - event: EthPurchase(address,uint256,uint256)
          handler: handleEthPurchase
        - event: AddLiquidity(address,uint256,uint256)
          handler: handleAddLiquidity
        - event: RemoveLiquidity(address,uint256,uint256)
          handler: handleRemoveLiquidity
```

### Instantiating a Data Source Template

In the final step, you update your main contract mapping to create a dynamic data source instance from one of the templates. In this example, you would change the main contract mapping to import the `Exchange` template and call the `Exchange.create(address)` method on it to start indexing the new exchange contract.

```typescript
import { Exchange } from '../generated/templates'

export function handleNewExchange(event: NewExchange): void {
  // Start indexing the exchange; `event.params.exchange` is the
  // address of the new exchange contract
  Exchange.create(event.params.exchange)
}
```

> **Note:** A new data source will only process the calls and events for the block in which it was created and all following blocks, but will not process historical data, i.e., data that is contained in prior blocks.
>
> If prior blocks contain data relevant to the new data source, it is best to index that data by reading the current state of the contract and creating entities representing that state at the time the new data source is created.

### Data Source Context

Data source contexts allow passing extra configuration when instantiating a template. In our example, let's say exchanges are associated with a particular trading pair, which is included in the `NewExchange` event. That information can be passed into the instantiated data source, like so:

```typescript
import { Exchange } from '../generated/templates'

export function handleNewExchange(event: NewExchange): void {
  let context = new DataSourceContext()
  context.setString('tradingPair', event.params.tradingPair)
  Exchange.createWithContext(event.params.exchange, context)
}
```

Inside a mapping of the `Exchange` template, the context can then be accessed:

```typescript
import { dataSource } from '@graphprotocol/graph-ts'

let context = dataSource.context()
let tradingPair = context.getString('tradingPair')
```

There are setters and getters like `setString` and `getString` for all value types.

> Referencing an entity is done via ID in GraphQL. That ID can be passed into the instantiated data source by setting it in the context and then accessed within the mapping of the template. An example can be found in the [documentation of `graph-ts`](https://github.com/graphprotocol/graph-tooling/tree/main/packages/ts#api).

## Start Blocks

The `startBlock` is an optional setting that allows you to define from which block in the chain the data source will start indexing. Setting the start block allows the data source to skip potentially millions of blocks that are irrelevant. Typically, a Subgraph developer will set `startBlock` to the block in which the smart contract of the data source was created.

```yaml
dataSources:
  - kind: ethereum/contract
    name: ExampleSource
    network: mainnet
    source:
      address: '0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95'
      abi: ExampleContract
      startBlock: 6627917
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.9
      language: wasm/assemblyscript
      file: ./src/mappings/factory.ts
      entities:
        - User
      abis:
        - name: ExampleContract
          file: ./abis/ExampleContract.json
      eventHandlers:
        - event: NewEvent(address,address)
          handler: handleNewEvent
```

> **Note:** The contract creation block can be quickly looked up on Etherscan:
>
> 1.  Search for the contract by entering its address in the search bar.
> 2.  Click on the creation transaction hash in the `Contract Creator` section.
> 3.  Load the transaction details page where you'll find the start block for that contract.

## Indexer Hints

The `indexerHints` setting in a Subgraph's manifest provides directives for indexers on processing and managing a Subgraph. It influences operational decisions across data handling, indexing strategies, and optimizations. Presently, it features the `prune` option for managing historical data retention or pruning.

> This feature is available from `specVersion: 1.0.0`

### Prune

`indexerHints.prune`: Defines the retention of historical block data for a Subgraph. Options include:

1.  `"never"`: No pruning of historical data; retains the entire history.
2.  `"auto"`: Retains the minimum necessary history as set by the indexer, optimizing query performance.
3.  A specific number: Sets a custom limit on the number of historical blocks to retain.

```
 indexerHints:
  prune: auto
```

> The term "history" in this context of Subgraphs is about storing data that reflects the old states of mutable entities.

History as of a given block is required for:

- [Time travel queries](/subgraphs/querying/graphql-api/#time-travel-queries), which enable querying the past states of these entities at specific blocks throughout the Subgraph's history
- Using the Subgraph as a [graft base](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) in another Subgraph, at that block
- Rewinding the Subgraph back to that block

If historical data as of the block has been pruned, the above capabilities will not be available.

> Using `"auto"` is generally recommended as it maximizes query performance and is sufficient for most users who do not require access to extensive historical data.

For Subgraphs leveraging [time travel queries](/subgraphs/querying/graphql-api/#time-travel-queries), it's advisable to either set a specific number of blocks for historical data retention or use `prune: never` to keep all historical entity states. Below are examples of how to configure both options in your Subgraph's settings:

To retain a specific amount of historical data:

```
 indexerHints:
  prune: 1000 # Replace 1000 with the desired number of blocks to retain
```

To preserve the complete history of entity states:

```
indexerHints:
  prune: never
```

## SpecVersion Releases

| Version | Release notes |
| :-: | --- |
| 1.3.0 | Added support for [Subgraph Composition](/cookbook/subgraph-composition-three-sources) |
| 1.2.0 | Added support for [Indexed Argument Filtering](/developing/creating/advanced/#indexed-argument-filters--topic-filters) & declared `eth_call` |
| 1.1.0 | Supports [Timeseries & Aggregations](/developing/creating/advanced/#timeseries-and-aggregations). Added support for type `Int8` for `id`. |
| 1.0.0 | Supports [`indexerHints`](/developing/creating/subgraph-manifest/#indexer-hints) feature to prune Subgraphs |
| 0.0.9 | Supports `endBlock` feature |
| 0.0.8 | Added support for polling [Block Handlers](/developing/creating/subgraph-manifest/#polling-filter) and [Initialisation Handlers](/developing/creating/subgraph-manifest/#once-filter). |
| 0.0.7 | Added support for [File Data Sources](/developing/creating/advanced/#ipfsarweave-file-data-sources). |
| 0.0.6 | Supports fast [Proof of Indexing](/indexing/overview/#what-is-a-proof-of-indexing-poi) calculation variant. |
| 0.0.5 | Added support for event handlers having access to transaction receipts. |
| 0.0.4 | Added support for managing subgraph features. |
