Onchain data on open standards
Read chain state, query indexed data, and stream blocks with GraphOps
- #22,984,172
- #22,984,173
- #22,984,174
- #22,984,175
- #22,984,176
JSON-RPC Subgraphs GraphQL Substreams gRPC - harborlabs.eth
- 0427.eth
- lumen-studio.eth
- cobaltvault.eth
- northwind.eth
- 7720.eth
- quietmesa.eth
- atlas-node.eth
Your app needs live chain state, its own onchain state in a schema you define, and often every block in its own database. Starting today, GraphOps serves all three, self-serve, each over its open standard:
- GraphOps RPC for balances, contract state and transactions straight from the chain, with no nodes to run, over JSON-RPC. Explore RPC
- GraphOps Subgraphs for your app's onchain state in your own schema, over Subgraph GraphQL, or one of 16,000+ Subgraphs on The Graph Network. Explore Subgraphs
- GraphOps Substreams for every block in your own database, starting from a published package, over Substreams gRPC. Explore Substreams
This is also the launch of The Graph Network's first independent gateway. GraphOps Subgraphs gives every team that queries The Graph another way in, run by one of the network's top Indexers. Since 2022 we've contributed to open data frameworks and standards, with a longstanding history as a core contributor to The Graph and its indexing software. The same team that contributes to that software runs these services.
Because each service speaks an open standard, you start with the tools you already use: the viem or ethers client in your app, any Subgraph published on The Graph Network, standard Substreams packages, and the Substreams CLI.
{ swaps(first: 3) }ethereum-common.spkgcursor #21,804,JSON-RPCRequest · responseGraphQLQuery · indexed entitiesgRPCStream · every blockanswers each callindexed #21,804,sends blocks in orderGraphOps RPC gives your application live chain state without running your own nodes: read balances and contract state, submit signed transactions, and react to each new block. Teams use it to power wallets and Web3 products, track treasury balances and movements, and read asset supply at an exact block.
Send standard JSON-RPC to https://rpc.graphops.xyz/v1/evm/<chainId>, with
your API key as a Bearer token:
Example Make your first RPC request
Read the latest Ethereum block number with curl or a TypeScript, Go, Rust, or Python client.
Read the guide(opens in a new tab)
Prerequisites
Set GRAPHOPS_API_KEY to your GraphOps API key.
CLI · curl
curl --fail-with-body --silent --show-error "https://rpc.graphops.xyz/v1/evm/1" \
-H "Authorization: Bearer ${GRAPHOPS_API_KEY}" \
-H "Content-Type: application/json" \
--data '{
"jsonrpc": "2.0",
"id": 1,
"method": "eth_blockNumber",
"params": []
}'
Output
{ "jsonrpc": "2.0",JSON-RPC version "id": 1,Matches the id you sent "result": "0x1934014"Latest block in decimal: 26,427,412}import os
from web3 import Web3
w3 = Web3(
Web3.HTTPProvider(
"https://rpc.graphops.xyz/v1/evm/1",
request_kwargs={
"headers": {
"Authorization": f"Bearer {os.environ['GRAPHOPS_API_KEY']}",
},
},
)
)
print(w3.eth.block_number)
import { createPublicClient, http } from "viem";
import { mainnet } from "viem/chains";
const client = createPublicClient({
chain: mainnet,
transport: http("https://rpc.graphops.xyz/v1/evm/1", {
fetchOptions: {
headers: {
Authorization: `Bearer ${process.env.GRAPHOPS_API_KEY}`,
},
},
}),
});
const blockNumber = await client.getBlockNumber();
console.log(blockNumber.toString());
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
)
func main() {
ctx := context.Background()
rpcClient, err := rpc.DialOptions(ctx, "https://rpc.graphops.xyz/v1/evm/1",
rpc.WithHeader("Authorization", "Bearer "+os.Getenv("GRAPHOPS_API_KEY")))
if err != nil {
log.Fatal(err)
}
client := ethclient.NewClient(rpcClient)
defer client.Close()
blockNumber, err := client.BlockNumber(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(blockNumber)
}
use alloy::providers::{Provider, ProviderBuilder};
use alloy::rpc::client::RpcClient;
use alloy::transports::http::Http;
use reqwest::header::{HeaderMap, AUTHORIZATION};
use std::{env, error::Error};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let mut headers = HeaderMap::new();
headers.insert(
AUTHORIZATION,
format!("Bearer {}", env::var("GRAPHOPS_API_KEY")?).parse()?,
);
let http = reqwest::Client::builder()
.default_headers(headers)
.build()?;
let provider = ProviderBuilder::new().connect_client(RpcClient::new(
Http::with_client(http, "https://rpc.graphops.xyz/v1/evm/1".parse()?),
false,
));
let block_number = provider.get_block_number().await?;
println!("{block_number}");
Ok(())
}
EVM networks are served over HTTPS and WebSocket, including subscriptions for new heads and logs, and Bitcoin over HTTPS. GraphOps RPC is served from the same archive infrastructure we run as an Indexer on The Graph Network, and archive and tracing access are listed per network on the networks pages.
Example Read contract state
Use eth_call to read USDC balanceOf at an explicit Ethereum mainnet block.
Read the guide(opens in a new tab)
Prerequisites
Set GRAPHOPS_API_KEY to your GraphOps API key.
CLI · curl
# data is the balanceOf(address) selector 0x70a08231 followed by the holder address
# left-padded to 32 bytes. 0x112a880 is block 18,000,000.
curl --fail-with-body --silent --show-error "https://rpc.graphops.xyz/v1/evm/1" \
-H "Authorization: Bearer ${GRAPHOPS_API_KEY}" \
-H "Content-Type: application/json" \
--data '{
"jsonrpc": "2.0",
"id": 1,
"method": "eth_call",
"params": [
{
"to": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
"data": "0x70a08231000000000000000000000000b4e16d0168e52d35cacd2c6185b44281ec28c9dc"
},
"0x112a880"
]
}'
Output
{ "jsonrpc": "2.0", "id": 1,Matches the id you sent "result": "0x0000000000000000000000000000000000000000000000000000197016bc99ff"Token amount: 27,969,208,490,495 base units, 27,969,208.490495 USDC}import { createPublicClient, erc20Abi, http } from "viem";
import { mainnet } from "viem/chains";
const client = createPublicClient({
chain: mainnet,
transport: http("https://rpc.graphops.xyz/v1/evm/1", {
fetchOptions: {
headers: {
Authorization: `Bearer ${process.env.GRAPHOPS_API_KEY}`,
},
},
}),
});
const balance = await client.readContract({
address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
abi: erc20Abi,
functionName: "balanceOf",
args: ["0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc"],
blockNumber: 18_000_000n,
});
console.log(balance.toString());
import os
from web3 import Web3
w3 = Web3(
Web3.HTTPProvider(
"https://rpc.graphops.xyz/v1/evm/1",
request_kwargs={
"headers": {
"Authorization": f"Bearer {os.environ['GRAPHOPS_API_KEY']}",
},
},
)
)
usdc = w3.eth.contract(
address="0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
abi=[
{
"name": "balanceOf",
"type": "function",
"stateMutability": "view",
"inputs": [{"name": "owner", "type": "address"}],
"outputs": [{"name": "", "type": "uint256"}],
}
],
)
balance = usdc.functions.balanceOf(
"0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc"
).call(block_identifier=18_000_000)
print(balance)
package main
import (
"context"
"fmt"
"log"
"math/big"
"os"
"strings"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
)
const balanceOfABI = `[{
"name": "balanceOf",
"type": "function",
"stateMutability": "view",
"inputs": [{"name": "owner", "type": "address"}],
"outputs": [{"name": "", "type": "uint256"}]
}]`
func main() {
ctx := context.Background()
rpcClient, err := rpc.DialOptions(ctx, "https://rpc.graphops.xyz/v1/evm/1",
rpc.WithHeader("Authorization", "Bearer "+os.Getenv("GRAPHOPS_API_KEY")))
if err != nil {
log.Fatal(err)
}
client := ethclient.NewClient(rpcClient)
defer client.Close()
usdcABI, err := abi.JSON(strings.NewReader(balanceOfABI))
if err != nil {
log.Fatal(err)
}
data, err := usdcABI.Pack("balanceOf", common.HexToAddress("0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc"))
if err != nil {
log.Fatal(err)
}
usdc := common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")
output, err := client.CallContract(ctx, ethereum.CallMsg{To: &usdc, Data: data}, big.NewInt(18_000_000))
if err != nil {
log.Fatal(err)
}
var balance *big.Int
if err := usdcABI.UnpackIntoInterface(&balance, "balanceOf", output); err != nil {
log.Fatal(err)
}
fmt.Println(balance)
}
use alloy::primitives::address;
use alloy::providers::ProviderBuilder;
use alloy::rpc::client::RpcClient;
use alloy::sol;
use alloy::transports::http::Http;
use reqwest::header::{HeaderMap, AUTHORIZATION};
use std::{env, error::Error};
sol! {
#[sol(rpc)]
interface IERC20 {
function balanceOf(address owner) external view returns (uint256);
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let mut headers = HeaderMap::new();
headers.insert(
AUTHORIZATION,
format!("Bearer {}", env::var("GRAPHOPS_API_KEY")?).parse()?,
);
let http = reqwest::Client::builder()
.default_headers(headers)
.build()?;
let provider = ProviderBuilder::new().connect_client(RpcClient::new(
Http::with_client(http, "https://rpc.graphops.xyz/v1/evm/1".parse()?),
false,
));
let usdc = IERC20::new(
address!("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
&provider,
);
let balance = usdc
.balanceOf(address!("0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc"))
.block(18_000_000.into())
.call()
.await?;
println!("{balance}");
Ok(())
}
Because the same key queries Subgraphs, you can read contract state at the exact block a Subgraph answered from, so indexed entities and live state describe one block. See Match RPC reads to Subgraph data(opens in a new tab).
A Subgraph turns contract events into your application's state, in a schema you define: positions, transfers, pools, and holders, indexed and related to each other and queried with GraphQL, with no indexing backend of your own to build. Use it for application feeds and APIs, protocol dashboards and analytics, and holder views of an asset.
16,000+ Subgraphs on The Graph Network already index the protocols your app reads, with data you can query right away over GraphQL, by Deployment CID or Graph Network Subgraph ID.
Example Paginate results
Page through large Subgraph entity sets with stable ordering and bounded requests.
Read the guide(opens in a new tab)
Prerequisites
Set GRAPHOPS_API_KEY to your GraphOps API key.
Replace
<ALIAS>with your Endpoint Alias.
CLI · curl
# Start below every id. For the next page, set lastId to the last id in this response.
curl --fail-with-body --silent --show-error "https://subgraphs.graphops.xyz/v1/alias/<ALIAS>" \
-H "Authorization: Bearer ${GRAPHOPS_API_KEY}" \
-H "Content-Type: application/json" \
--data '{
"query": "query PoolsPage($first: Int!, $lastId: ID!) { pools(first: $first, where: { id_gt: $lastId }, orderBy: id, orderDirection: asc) { id token0 { symbol } token1 { symbol } } _meta { block { number hash } } }",
"variables": { "first": 10, "lastId": "0x0000000000000000000000000000000000000000" },
"operationName": "PoolsPage"
}'
Output
{ "data": { "pools": [Up to $first rows, ordered by id { "id": "0x000024feb293b6c6c3a80a95f1f830a8746400b9", "token0": { "symbol": "TRUMP" }, "token1": { "symbol": "WETH" } }, { "id": "0x0000d36ab86d213c14d93cd5ae78615a20596505",Last id: your next $lastId "token0": { "symbol": "RALPH" }, "token1": { "symbol": "WETH" } }, { "id": "0x00013bffe4c38c1372a450fac78b01cb4f554781", "token0": { "symbol": "Pectra" }, "token1": { "symbol": "WETH" } }, { "id": "0x0001fcbba8eb491c3ccfeddc5a5caba1a98c4c28", "token0": { "symbol": "BCZ" }, "token1": { "symbol": "WETH" } }, { "id": "0x00024b66a38a676c0eae59126c1367ad141afa79", "token0": { "symbol": "WETH" }, "token1": { "symbol": "TI" } }, { "id": "0x0002e63328169d7feea121f1e32e4f620abf0352", "token0": { "symbol": "wNXM" }, "token1": { "symbol": "ICHI" } }, { "id": "0x0003c9d75e102b8a9fe77280ca410e9135beb150", "token0": { "symbol": "TRANCHE-bWBTC-A" }, "token1": { "symbol": "USDT" } }, { "id": "0x0003e7d8d22d0e8e53d56885069fc8a254f0431f", "token0": { "symbol": "RLP" }, "token1": { "symbol": "USDC" } }, { "id": "0x0004cd8474e882278e32e584699090be496f410e", "token0": { "symbol": "ZERO" }, "token1": { "symbol": "USDC" } }, { "id": "0x0005079292756443f2e711570f8ab4e1951d4f97", "token0": { "symbol": "EDG" }, "token1": { "symbol": "WETH" } } ], "_meta": { "block": { "number": 26427422,Log with each page "hash": "0x2b2e7dba584f940514fb8d7744402f46a2af1c1154458932c771b1eb7df2d718" } } }}export {};
// Start below every id. For the next page, pass the last id this page returns.
const lastId = "0x0000000000000000000000000000000000000000";
const response = await fetch(
"https://subgraphs.graphops.xyz/v1/alias/<ALIAS>",
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.GRAPHOPS_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
query: `
query PoolsPage($first: Int!, $lastId: ID!) {
pools(
first: $first
where: { id_gt: $lastId }
orderBy: id
orderDirection: asc
) {
id
token0 { symbol }
token1 { symbol }
}
_meta { block { number hash } }
}
`,
variables: { first: 10, lastId },
operationName: "PoolsPage",
}),
},
);
if (!response.ok) throw new Error(await response.text());
const result = await response.json();
// The last id is the cursor for the next page; null means there are no more rows.
console.log(JSON.stringify(result.data.pools.at(-1)?.id ?? null));
import json
import os
import requests
# Start below every id. For the next page, pass the last id this page returns.
last_id = "0x0000000000000000000000000000000000000000"
response = requests.post(
"https://subgraphs.graphops.xyz/v1/alias/<ALIAS>",
headers={
"Authorization": f"Bearer {os.environ['GRAPHOPS_API_KEY']}",
},
json={
"query": """
query PoolsPage($first: Int!, $lastId: ID!) {
pools(
first: $first
where: { id_gt: $lastId }
orderBy: id
orderDirection: asc
) {
id
token0 { symbol }
token1 { symbol }
}
_meta { block { number hash } }
}
""",
"variables": {"first": 10, "lastId": last_id},
"operationName": "PoolsPage",
},
timeout=30,
)
response.raise_for_status()
pools = response.json()["data"]["pools"]
# The last id is the cursor for the next page; None means there are no more rows.
print(json.dumps(pools[-1]["id"] if pools else None))
use serde_json::{json, Value};
use std::{env, error::Error, time::Duration};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Start below every id. For the next page, pass the last id this page returns.
let last_id = "0x0000000000000000000000000000000000000000";
let response = reqwest::Client::new()
.post("https://subgraphs.graphops.xyz/v1/alias/<ALIAS>")
.bearer_auth(env::var("GRAPHOPS_API_KEY")?)
.timeout(Duration::from_secs(30))
.json(&json!({
"query": r#"
query PoolsPage($first: Int!, $lastId: ID!) {
pools(
first: $first
where: { id_gt: $lastId }
orderBy: id
orderDirection: asc
) {
id
token0 { symbol }
token1 { symbol }
}
_meta { block { number hash } }
}
"#,
"variables": { "first": 10, "lastId": last_id },
"operationName": "PoolsPage",
}))
.send()
.await?
.error_for_status()?;
let result: Value = response.json().await?;
let pools = result["data"]["pools"].as_array().ok_or("missing pools")?;
// The last id is the cursor for the next page; null means there are no more rows.
println!(
"{}",
pools.last().map_or(Value::Null, |pool| pool["id"].clone())
);
Ok(())
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
)
func main() {
// Start below every id. For the next page, pass the last id this page returns.
lastID := "0x0000000000000000000000000000000000000000"
payload, err := json.Marshal(struct {
Query string `json:"query"`
Variables map[string]any `json:"variables"`
OperationName string `json:"operationName"`
}{
Query: `
query PoolsPage($first: Int!, $lastId: ID!) {
pools(
first: $first
where: { id_gt: $lastId }
orderBy: id
orderDirection: asc
) {
id
token0 { symbol }
token1 { symbol }
}
_meta { block { number hash } }
}
`,
Variables: map[string]any{"first": 10, "lastId": lastID},
OperationName: "PoolsPage",
})
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest(http.MethodPost,
"https://subgraphs.graphops.xyz/v1/alias/<ALIAS>", bytes.NewReader(payload))
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("GRAPHOPS_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
log.Fatalf("HTTP %d: %s", resp.StatusCode, body)
}
var result struct {
Data struct {
Pools []struct {
ID string `json:"id"`
} `json:"pools"`
} `json:"data"`
Errors json.RawMessage `json:"errors"`
}
if err := json.Unmarshal(body, &result); err != nil {
log.Fatal(err)
}
// GraphQL errors can arrive with HTTP 200; a missing page must not read as the last one.
if result.Errors != nil || result.Data.Pools == nil {
log.Fatalf("GraphQL errors: %s", body)
}
// The last id is the cursor for the next page; null means there are no more rows.
var cursor *string
if pools := result.Data.Pools; len(pools) > 0 {
cursor = &pools[len(pools)-1].ID
}
next, err := json.Marshal(cursor)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(next))
}
The hard parts are capacity and upgrades. A Subgraph on The Graph Network waits for Indexers to pick it up, with no capacity reserved for your app. And every new version gets a new Deployment CID and starts with no data, so an app pinned to a CID needs a release to move, and an app that follows the newest version can query it before it has indexed. GraphOps adds two things the standard does not give you.
Endpoint Aliases give your app one URL, and you choose when it moves. Pin a Deployment CID, or follow a Graph Network Subgraph ID with Latest available version, which moves to a new version only once network Indexers serve it and keeps serving the previous one until then. Aliases carry no charge of their own. A policy that moves on its own can deliver the owner's breaking schema changes, so pin when your queries need a fixed schema.
/v1/alias/dex-poolsLatest available versionServing CIDQm…a1f4Qm…7c2e5zvR…Kq2Qm…a1f4Served by IndexersQm…7c2ePublishedServed by IndexersIndexersA Managed Subgraph begins indexing immediately and has elastic query capacity backed by Indexers on The Graph Network. GraphOps runs both a gateway to The Graph Network and an Indexer on it, so your deployment never waits on another Indexer while queries stay backed by the full network. A Managed Subgraph can also follow another team's Subgraph ID, and each version they publish reaches your app once it's ready.
Your own queries are free. Queries your organization sends to its own Managed Subgraphs cost no credits within your rate limits, on a monthly plan (other organizations' queries are billed as usual). See what GraphOps guarantees(opens in a new tab) for exact scope.
Upgrades wait until they're ready. On a Managed Subgraph, a new version indexes alongside the one your app uses, breaking schema changes are flagged, and it goes live when you choose, once it's ready. Point your app at an Endpoint Alias and it keeps one URL, pointing to a Managed Subgraph's live version, a pinned deployment, or the latest version The Graph Network's Indexers serve. Managed indexing runs on a monthly plan and draws on its credits, for both versions during an upgrade, and a small Managed Subgraph fits within the smallest plan.
/v1/alias/positionsServes Current version/v1/alias/positions-stagingServes Next versionCurrent versionQm…a1f4Qm…7c2eAvailableSynced to #21,480,512#21,480,513#21,480,514#21,480,515#21,480,516#21,480,517#21,480,518#21,480,519#21,480,520#21,480,521Qm…7c2eNot stagedSyncingReady to promoteThe Subgraph setup guide(opens in a new tab) compares every option, with what each one waits for and costs.
GraphOps Substreams puts onchain data in your own database, beside the rest of your data: every block, or only the events you select, in order, from a historical backfill straight into the live chain. Use it to load a warehouse for analytics, keep a traceable record for compliance review, or reconcile onchain movements with your books.
Start from a package that already exists. Substreams Discover in the console lists popular packages for your network, ranked by downloads, and its explorer shows each package's modules and output types before you run it. See Discover packages(opens in a new tab).
Point the Substreams CLI or your own gRPC client at
https://<CHAIN_ID>.evm.substreams.graphops.xyz, where the hostname starts
with the network's chain ID, and run a standard package: a historical backfill that
continues as a live stream into your own database. The protocol sends a cursor with every
block of output and an undo signal when a reorg drops blocks. Your consumer commits each
cursor with its data and rewinds on an undo signal, keeping your consumer portable across
compliant providers. The
cursor guide(opens in a new tab)
shows the commit order.
- #1,201
0x4e1a… - #1,202
0x7b3c… - #1,203
0x9c07…#1,2030x31d5… - #1,204
0xa86f…
ethereum-common@v0.4.0sf.ethereum.type.v2.Blocksourceindex_eventsindexfiltered_eventsmapevt_addr:0xa0b8…eb48evt_sig:0xddf2…b3ef
0x4e1a…140x7b3c…90x9c07…210x31d5…180xa86f…11a7Hq…3kQ#1,202a7Hq…9vR#1,203a7Hq…Xc2#1,203a7Hq…mP4#1,204a7Hq…Lw8 Example Resume with cursors
Persist cursors and resume Substreams consumers after disconnects.
Read the guide(opens in a new tab)
Prerequisites
Install the Substreams CLI.
Set GRAPHOPS_API_KEY to your GraphOps API key.
Replace
<LAST_COMMITTED_CURSOR>with the cursor of the last block you committed.
CLI · Substreams CLI
# The CLI sends SUBSTREAMS_API_KEY to GraphOps in the x-api-key header.
export SUBSTREAMS_API_KEY="${GRAPHOPS_API_KEY}"
# --cursor resumes right after the block where that cursor was committed.
substreams run \
-e "https://1.evm.substreams.graphops.xyz" \
"https://spkg.io/v1/packages/ethereum-common/v0.4.0" \
"filtered_events" \
--params "filtered_events=evt_addr:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 && evt_sig:0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" \
--start-block 18000002 \
--stop-block 18000008 \
--cursor "<LAST_COMMITTED_CURSOR>" \
-o jsonl
Output
{ "@module": "filtered_events", "@block": 18000003,Historical block: 18,000,003 "@type": "sf.substreams.ethereum.v1.Events", "@data": { "clock": { "id": "90c06a9fad66de217ce5862a92a2d45a8f42f9abf8ec17d5bfb85ffdc7836ca4", "number": "18000003", "timestamp": "2023-08-26T16:22:11Z" }, "events": [ { "log": { "address": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",Ethereum mainnet USDC contract; hexadecimal in CLI output, base64 in Protobuf JSON "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",ERC-20 Transfer signature "0x000000000000000000000000180cd4303582d348a54fcb0436d5665f082a23d1",Sender address, left-padded to 32 bytes "0x000000000000000000000000a9d1e08c7793af67e9d92fe308d5697fb81d3e43"Recipient address, left-padded to 32 bytes ], "data": "0x00000000000000000000000000000000000000000000000000000000aad0a340",Transfer amount: 2,865,800,000 base units, 2,865.8 USDC "blockIndex": 222, "ordinal": "4219" }, "txHash": "05c9c59145387faa91370e56d717d42856bd20f8f19306814d5b7afbe837efe3"Transaction containing this log }, { "log": { "address": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x0000000000000000000000001c727a55ea3c11b0ab7d3a361fe0f3c47ce6de5d", "0x000000000000000000000000c3dcc088aef4373e665b00fc8be45a4b6a4b24a6" ], "data": "0x000000000000000000000000000000000000000000000000000000000686bcda", "blockIndex": 230, "ordinal": "4543" }, "txHash": "eb8505dd3dc2964c1b43ed40371fb9c907b751ccb9294b99db032270889edc42" } ] }}{ "@module": "filtered_events", "@block": 18000004, "@type": "sf.substreams.ethereum.v1.Events", "@data": { "clock": { "id": "7f7889c3686d7f560dd690aeb2a10b49e3a76844543cf78cc0dfe4687e2985d2", "number": "18000004", "timestamp": "2023-08-26T16:22:23Z" }, "events": [ { "log": { "address": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x00000000000000000000000043954785980c50768373dc1dafd7ba3a2052036f" ], "data": "0x000000000000000000000000000000000000000000000000000000e8d433aa6e", "index": 1, "blockIndex": 191, "ordinal": "3060" }, "txHash": "b2c1d8c8e7989adab51dafdc9be24fd05243342b8d08828c4325662de629c690" } ] }}{ "@module": "filtered_events", "@block": 18000005, "@type": "sf.substreams.ethereum.v1.Events", "@data": { "clock": { "id": "127c6b9794874d7011770b3aa2a0a640e1db201c2d677d01b2b3b19e7ad427c7", "number": "18000005", "timestamp": "2023-08-26T16:22:35Z" }, "events": [ { "log": { "address": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x000000000000000000000000c880d8be4e94f644f1daa7d3558b50ff5a1c2db7", "0x000000000000000000000000ae2d4617c862309a3d75a0ffb358c7a5009c673f" ], "data": "0x0000000000000000000000000000000000000000000000000000002e90edd000", "blockIndex": 64, "ordinal": "1110" }, "txHash": "1691b8e89e13f483c549d9b61efbc54ecc54015b8186726911c8458f0993e13d" }, { "log": { "address": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x000000000000000000000000b86fc5e985facdcae6034beefc6cbdcd8bbd8cb4", "0x00000000000000000000000027f713adefc708469d826ab8f5b1e4672f1a070e" ], "data": "0x0000000000000000000000000000000000000000000000000000000059682f00", "blockIndex": 203, "ordinal": "3669" }, "txHash": "440106b494b7eb657d19e5f82a164ce4cc62e5252058fab5fb4ee6b92600543c" } ] }}{ "@module": "filtered_events", "@block": 18000006, "@type": "sf.substreams.ethereum.v1.Events", "@data": { "clock": { "id": "ed05b59286d4f2db801e78a23ce4584d869d857b70b2758822844427caa55a85", "number": "18000006", "timestamp": "2023-08-26T16:22:47Z" } }}{ "@module": "filtered_events", "@block": 18000007, "@type": "sf.substreams.ethereum.v1.Events", "@data": { "clock": { "id": "db63e26b655ad31d60b2173c02127180ed46b28506f785a2682e058ca61afdc1", "number": "18000007", "timestamp": "2023-08-26T16:22:59Z" }, "events": [ { "log": { "address": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x000000000000000000000000b4eae88d1643e172518dde0ef213c20628798c65", "0x00000000000000000000000038c5a4f22e2e290ba9bbb9e3d9aaf8582f79f4d1" ], "data": "0x0000000000000000000000000000000000000000000000000000000006b78840", "blockIndex": 94, "ordinal": "1448" }, "txHash": "21d8e836f79606db39fcd51f7e563ea9c12cfb7a2bb3e36f23f4eb89b93045ea" }, { "log": { "address": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x000000000000000000000000579752cff8fee7af09446b2133ee2f9ff10c4fbf", "0x0000000000000000000000001715a3e4a142d8b698131108995174f37aeba10d" ], "data": "0x000000000000000000000000000000000000000000000000000000001d0221cd", "blockIndex": 179, "ordinal": "3398" }, "txHash": "d78a180e669534a650d842f13d032610e29bf4a7731fb90a6dff73d752ac049c" } ] }}import { createHash } from "node:crypto";
import { createGrpcTransport, Http2SessionManager } from "@connectrpc/connect-node";
import {
applyParams,
createRegistry,
createRequest,
createSubstream,
streamBlocks,
unpackMapOutput,
} from "@substreams/core";
const endpoint = "https://1.evm.substreams.graphops.xyz";
const apiKey = process.env.GRAPHOPS_API_KEY;
if (!apiKey) throw new Error("Set GRAPHOPS_API_KEY");
// Check the package's SHA-256, so the program only runs the exact module code you reviewed.
const download = await fetch("https://spkg.io/v1/packages/ethereum-common/v0.4.0");
if (!download.ok) throw new Error(`Package download failed: ${download.status}`);
const bytes = new Uint8Array(await download.arrayBuffer());
const checksum = createHash("sha256").update(bytes).digest("hex");
if (checksum !== "beda75cef8a655941816a7c2be222ed590f618fe389e7c08c3ac5f0826161345") {
throw new Error("Package checksum mismatch");
}
const pkg = createSubstream(bytes);
if (!pkg.modules) throw new Error("Package has no modules");
// Keep Transfer events (evt_sig) emitted by the USDC contract (evt_addr).
applyParams(
[
"filtered_events=evt_addr:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 && evt_sig:0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
],
pkg.modules.modules,
);
// The package embeds its protobuf schemas, so the output decodes without generated code.
const registry = createRegistry(pkg);
const request = createRequest({
substreamPackage: pkg,
outputModule: "filtered_events",
startBlockNum: 18000002,
stopBlockNum: 18000008, // exclusive
// Unset starts at startBlockNum; a committed cursor resumes right after its block.
startCursor: process.env.GRAPHOPS_CURSOR || undefined,
// Production mode processes the range in parallel and sends only the output module.
productionMode: true,
// Only irreversible blocks, so the server never sends a blockUndoSignal (reorg rewind).
finalBlocksOnly: true,
});
const sessionManager = new Http2SessionManager(endpoint);
const transport = createGrpcTransport({ baseUrl: endpoint, httpVersion: "2", sessionManager });
// GraphOps authenticates every gRPC call with the x-api-key metadata header.
const headers = { "x-api-key": apiKey };
try {
for await (const response of streamBlocks(transport, request, { headers })) {
// Skip session, progress and other non-data messages.
if (response.message.case !== "blockScopedData") continue;
const { clock, cursor } = response.message.value;
const output = unpackMapOutput(response, registry);
const data = output?.toJson() as { events?: unknown[] } | undefined;
if (!data?.events) continue; // no matching transfers in this block
// Store the events and this cursor together; after a restart, pass the last stored
// cursor as startCursor to continue from the next block without gaps or duplicates.
console.log(JSON.stringify({ block: String(clock?.number), cursor, data }));
}
} finally {
sessionManager.abort(); // Close the HTTP/2 connection so the process can exit.
}
import hashlib
import json
import os
import grpc
import requests
from google.protobuf import descriptor_pool, json_format, message_factory
# Generated Substreams protocol bindings, included in the example project.
from sf.substreams.rpc.v2 import service_pb2, service_pb2_grpc
from sf.substreams.v1 import package_pb2
ENDPOINT = "https://1.evm.substreams.graphops.xyz"
PACKAGE_URL = "https://spkg.io/v1/packages/ethereum-common/v0.4.0"
PACKAGE_SHA256 = "beda75cef8a655941816a7c2be222ed590f618fe389e7c08c3ac5f0826161345"
MODULE = "filtered_events"
OUTPUT_TYPE = "sf.substreams.ethereum.v1.Events"
# Keep Transfer events (evt_sig) emitted by the USDC contract (evt_addr).
PARAMS = "evt_addr:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 && evt_sig:0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
api_key = os.environ["GRAPHOPS_API_KEY"]
# Check the package's SHA-256, so the program only runs the exact module code you reviewed.
download = requests.get(PACKAGE_URL, timeout=30)
download.raise_for_status()
if hashlib.sha256(download.content).hexdigest() != PACKAGE_SHA256:
raise RuntimeError("Package checksum mismatch")
package = package_pb2.Package.FromString(download.content)
# Set the module's params input, like `substreams run --params`.
for module in package.modules.modules:
if module.name == MODULE:
for module_input in module.inputs:
if module_input.HasField("params"):
module_input.params.value = PARAMS
# The package embeds its protobuf schemas, so the output decodes without generated code.
pool = descriptor_pool.DescriptorPool()
for proto_file in package.proto_files:
pool.Add(proto_file)
Events = message_factory.GetMessageClass(pool.FindMessageTypeByName(OUTPUT_TYPE))
# Trust gRPC's default roots, or the CA bundle in SSL_CERT_FILE when set.
roots = None
if os.environ.get("SSL_CERT_FILE"):
with open(os.environ["SSL_CERT_FILE"], "rb") as bundle:
roots = bundle.read()
credentials = grpc.ssl_channel_credentials(root_certificates=roots)
with grpc.secure_channel(ENDPOINT.removeprefix("https://"), credentials) as channel:
request = service_pb2.Request(
modules=package.modules,
output_module=MODULE,
start_block_num=18000002,
stop_block_num=18000008, # exclusive
# Empty starts at start_block_num; a committed cursor resumes right after its block.
start_cursor=os.environ.get("GRAPHOPS_CURSOR", ""),
# Production mode processes the range in parallel and sends only the output module.
production_mode=True,
# Only irreversible blocks, so the server never sends a BlockUndoSignal (reorg rewind).
final_blocks_only=True,
)
# GraphOps authenticates every gRPC call with the x-api-key metadata header.
stream = service_pb2_grpc.StreamStub(channel).Blocks(
request, metadata=[("x-api-key", api_key)]
)
for response in stream:
# Skip session, progress and other non-data messages.
if not response.HasField("block_scoped_data"):
continue
data = response.block_scoped_data
events = json_format.MessageToDict(
Events.FromString(data.output.map_output.value)
)
if "events" not in events:
continue # no matching transfers in this block
# Store the events and this cursor together; after a restart, pass the last stored
# cursor as start_cursor to continue from the next block without gaps or duplicates.
record = {"block": str(data.clock.number), "cursor": data.cursor, "data": events}
print(json.dumps(record))
package main
import (
"context"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
rpc "github.com/streamingfast/substreams/pb/sf/substreams/rpc/v2"
pb "github.com/streamingfast/substreams/pb/sf/substreams/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protodesc"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/dynamicpb"
)
const (
endpoint = "https://1.evm.substreams.graphops.xyz"
packageURL = "https://spkg.io/v1/packages/ethereum-common/v0.4.0"
packageSHA256 = "beda75cef8a655941816a7c2be222ed590f618fe389e7c08c3ac5f0826161345"
module = "filtered_events"
outputType = "sf.substreams.ethereum.v1.Events"
// Keep Transfer events (evt_sig) emitted by the USDC contract (evt_addr).
params = "evt_addr:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 && evt_sig:0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
apiKey := os.Getenv("GRAPHOPS_API_KEY")
if apiKey == "" {
return errors.New("set GRAPHOPS_API_KEY")
}
pkg, err := downloadPackage()
if err != nil {
return err
}
// Set the module's params input, like `substreams run --params`.
for _, m := range pkg.Modules.Modules {
if m.Name != module {
continue
}
for _, input := range m.Inputs {
if p := input.GetParams(); p != nil {
p.Value = params
}
}
}
// The package embeds its protobuf schemas, so the output decodes without generated code.
files, err := protodesc.NewFiles(&descriptorpb.FileDescriptorSet{File: pkg.ProtoFiles})
if err != nil {
return err
}
descriptor, err := files.FindDescriptorByName(outputType)
if err != nil {
return err
}
eventsType := descriptor.(protoreflect.MessageDescriptor)
// Trust the system roots, or the CA bundle in SSL_CERT_FILE when set (Go ignores it on macOS).
creds := credentials.NewTLS(&tls.Config{})
if caFile := os.Getenv("SSL_CERT_FILE"); caFile != "" {
if creds, err = credentials.NewClientTLSFromFile(caFile, ""); err != nil {
return err
}
}
conn, err := grpc.NewClient(strings.TrimPrefix(endpoint, "https://"), grpc.WithTransportCredentials(creds))
if err != nil {
return err
}
defer conn.Close()
// GraphOps authenticates every gRPC call with the x-api-key metadata header.
ctx := metadata.AppendToOutgoingContext(context.Background(), "x-api-key", apiKey)
stream, err := rpc.NewStreamClient(conn).Blocks(ctx, &rpc.Request{
Modules: pkg.Modules,
OutputModule: module,
StartBlockNum: 18000002,
StopBlockNum: 18000008, // exclusive
// Empty starts at StartBlockNum; a committed cursor resumes right after its block.
StartCursor: os.Getenv("GRAPHOPS_CURSOR"),
// Production mode processes the range in parallel and sends only the output module.
ProductionMode: true,
// Only irreversible blocks, so the server never sends a BlockUndoSignal (reorg rewind).
FinalBlocksOnly: true,
})
if err != nil {
return err
}
for {
response, err := stream.Recv()
if errors.Is(err, io.EOF) {
return nil // reached StopBlockNum
}
if err != nil {
return err
}
data := response.GetBlockScopedData()
if data == nil {
continue // session, progress and other non-data messages
}
output := dynamicpb.NewMessage(eventsType)
if err := proto.Unmarshal(data.GetOutput().GetMapOutput().GetValue(), output); err != nil {
return err
}
outputJSON, err := protojson.Marshal(output)
if err != nil {
return err
}
var payload map[string]any
if err := json.Unmarshal(outputJSON, &payload); err != nil {
return err
}
if payload["events"] == nil {
continue // no matching transfers in this block
}
// Store the events and this cursor together; after a restart, pass the last stored
// cursor as StartCursor to continue from the next block without gaps or duplicates.
record := map[string]any{"block": fmt.Sprint(data.Clock.Number), "cursor": data.Cursor, "data": payload}
if err := json.NewEncoder(os.Stdout).Encode(record); err != nil {
return err
}
}
}
// downloadPackage fetches the Substreams package and checks its SHA-256, so the program only
// ever runs the exact module code that was reviewed.
func downloadPackage() (*pb.Package, error) {
response, err := http.Get(packageURL)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("package download: %s", response.Status)
}
content, err := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
if sum := sha256.Sum256(content); hex.EncodeToString(sum[:]) != packageSHA256 {
return nil, errors.New("package checksum mismatch")
}
pkg := &pb.Package{}
return pkg, proto.Unmarshal(content, pkg)
}
// build.rs generates the Substreams protocol types and client with Buffa and connectrpc.
mod pb {
connectrpc::include_generated!();
}
use buffa::Message;
use buffa_descriptor::{generated::descriptor::FileDescriptorSet, DescriptorPool, DynamicMessage};
use connectrpc::client::{ClientConfig, HttpClient};
use connectrpc::{rustls, Protocol};
use pb::sf::substreams::rpc::v2::{response, Request, StreamClient};
use pb::sf::substreams::v1::{module::input::Input, Package};
use ring::digest::{digest, SHA256};
use serde_json::json;
use std::{env, error::Error, sync::Arc};
const ENDPOINT: &str = "https://1.evm.substreams.graphops.xyz";
const PACKAGE_URL: &str = "https://spkg.io/v1/packages/ethereum-common/v0.4.0";
const PACKAGE_SHA256: &str = "beda75cef8a655941816a7c2be222ed590f618fe389e7c08c3ac5f0826161345";
const MODULE: &str = "filtered_events";
const OUTPUT_TYPE: &str = "sf.substreams.ethereum.v1.Events";
// Keep Transfer events (evt_sig) emitted by the USDC contract (evt_addr).
const PARAMS: &str = "evt_addr:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 && evt_sig:0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let api_key = env::var("GRAPHOPS_API_KEY")?;
// Check the package's SHA-256, so the program only runs the exact module code you reviewed.
let bytes = reqwest::get(PACKAGE_URL)
.await?
.error_for_status()?
.bytes()
.await?;
let checksum: String = digest(&SHA256, &bytes)
.as_ref()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
if checksum != PACKAGE_SHA256 {
return Err("package checksum mismatch".into());
}
let mut package = Package::decode_from_slice(&bytes)?;
// Set the module's params input, like `substreams run --params`.
let module = package
.modules
.as_option_mut()
.ok_or("package has no modules")?
.modules
.iter_mut()
.find(|module| module.name == MODULE)
.ok_or("module not found")?;
for input in &mut module.inputs {
if let Some(Input::Params(params)) = &mut input.input {
params.value = PARAMS.into();
}
}
// The package embeds its protobuf schemas, so the output decodes without generated code.
let pool = Arc::new(DescriptorPool::new(FileDescriptorSet {
file: std::mem::take(&mut package.proto_files),
..Default::default()
})?);
let events_type = pool
.message_index(OUTPUT_TYPE)
.ok_or("output type not found")?;
// Trust the system roots, or the CA bundle in SSL_CERT_FILE when set.
let mut roots = rustls::RootCertStore::empty();
roots.add_parsable_certificates(rustls_native_certs::load_native_certs().certs);
let tls = rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
// GraphOps authenticates every gRPC call with the x-api-key metadata header.
let config = ClientConfig::new(ENDPOINT.parse()?)
.with_protocol(Protocol::Grpc)
.with_default_header("x-api-key", api_key);
let client = StreamClient::new(HttpClient::with_tls(Arc::new(tls)), config);
let mut stream = client
.blocks(Request {
modules: package.modules,
output_module: MODULE.into(),
start_block_num: 18000002,
stop_block_num: 18000008, // exclusive
// Empty starts at start_block_num; a committed cursor resumes right after its block.
start_cursor: env::var("GRAPHOPS_CURSOR").unwrap_or_default(),
// Production mode processes the range in parallel and sends only the output module.
production_mode: true,
// Only irreversible blocks, so the server never sends a BlockUndoSignal (reorg rewind).
final_blocks_only: true,
..Default::default()
})
.await?;
while let Some(message) = stream.message().await? {
// Skip session, progress and other non-data messages.
let Some(response::Message::BlockScopedData(data)) = message.to_owned_message().message
else {
continue;
};
let output = &data.output.map_output;
let events = DynamicMessage::decode(pool.clone(), events_type, &output.value)?;
let events = serde_json::to_value(&events)?;
if events.get("events").is_none() {
continue; // no matching transfers in this block
}
// Store the events and this cursor together; after a restart, pass the last stored
// cursor as start_cursor to continue from the next block without gaps or duplicates.
let record = json!({
"block": data.clock.number.to_string(),
"cursor": data.cursor,
"data": events,
});
println!("{record}");
}
Ok(())
}
What it costs
There is one monthly plan, sized in steps of credits, and the price per credit falls with each step you add. Every service and every API key in your organization draws on the same balance. No plan is required: you can top up credits and pay as you go instead, and the estimator sizes a plan from the usage you expect.
Where to start
Every service has a quickstart, and runnable examples in the docs come as projects you can download as an archive. For coding agents, start with Use GraphOps with AI agents(opens in a new tab); every page is also available as Markdown.
If you start from a problem rather than a service, each solution page works through one case step by step and shows which read each step makes.
Data for asset issuers
Explain a 40,000 USDC supply gap
Data for compliance workflows
Keep a flagged transfer’s evidence exact
Treasury and onchain operations
Close the day with one receipt left to explain
Onchain analytics and reporting
Trace a daily total back to its transfers
Web3 application development
Show a repayment the same way across your app
Onchain data for European institutions
Trace a month-end balance report to its sources
Questions about annual terms, invoiced payment, or larger volumes go through Discuss your project. Service status is at status.graphops.xyz(opens in a new tab), and support is a chat inside the platform.
Onchain data in the shape your app needs.