Graph


GRAPH 


1. WHY THE GRAPH EXISTS (Root Problem)

Ethereum RPC nodes allow only low-level reads:

  • eth_getBalance

  • eth_call

  • eth_getLogs

  • getBlockByNumber

But if you want something like:

“Give me a list of all swaps where user=0xA”

Your only option is to:

❌ scan all blocks
❌ fetch all events
❌ filter in your backend
❌ store in your database
❌ query manually

If you need:

  • token history

  • all NFT transfers

  • Uniswap swaps

  • All LP positions

You’d need to scan millions of blocks, slow and expensive.

So The Graph solves this.


⭐ 2. HOW THE GRAPH WORKS INTERNALLY

The Graph has three big components:

✔ Graph Node

Scans blockchain → extracts events → writes to your database.

✔ Subgraph Manifest

Tells Graph Node what to index.

✔ Mappings

Code (AssemblyScript) that transforms raw blockchain data → structured entities.


⭐ 3. WHAT EXACTLY IS A SUBGRAPH?

A subgraph is:

A definition file that tells Graph Node which smart contracts to watch,
which events to index,
and how to store the extracted data.

Your subgraph contains:

FilePurpose
subgraph.yamlWhat to index (contracts, events, start block)
schema.graphqlDatabase schema (entities you store)
mapping.tsCode that processes events and stores them

These three pieces create an indexer, like a custom database.


⭐ 4. LIFE OF A SUBGRAPH (ACTUAL INTERNAL FLOW)

Let’s say you have a UniswapPool subgraph.

Step 1: You write subgraph.yaml

Example:

dataSources: - kind: ethereum name: UniswapPool network: mainnet source: address: "0x8ad599c..." abi: UniswapV3Pool startBlock: 12345678 mapping: kind: ethereum/events apiVersion: 0.0.7 language: wasm/assemblyscript entities: - Swap abis: - name: UniswapV3Pool file: ./abis/UniswapV3Pool.json eventHandlers: - event: Swap(address,address,uint256,uint256,int24) handler: handleSwap

This tells Graph Node:

“Watch this contract starting from block 12,345,678
and call handleSwap() for every Swap event.”


Step 2: You define your schema in schema.graphql

type Swap @entity { id: ID! sender: Bytes! recipient: Bytes! amount0: BigInt! amount1: BigInt! tick: Int! timestamp: BigInt! }

This creates your database table.


Step 3: You write your mapping in AssemblyScript (WASM)

mapping.ts:

export function handleSwap(event: SwapEvent): void { let entity = new Swap(event.transaction.hash.toHex() + "-" + event.logIndex.toString()); entity.sender = event.params.sender; entity.recipient = event.params.recipient; entity.amount0 = event.params.amount0; entity.amount1 = event.params.amount1; entity.tick = event.params.tick; entity.timestamp = event.block.timestamp; entity.save(); }

Graph Node compiles this into WebAssembly, not JS.


Step 4: Graph Node begins indexing

Graph Node does this:

Sync block 11000 Scan for events Match events to your subgraph definition Call mapping.ts handlers Store entities in database (PostgreSQL) Repeat for all blocks

This takes hours for big subgraphs (Uniswap, Aave).

Once indexing is done →
your subgraph is instantly queryable.


Step 5: You query using GraphQL

Example:

{ swaps(first: 5, orderBy: timestamp, orderDirection: desc) { sender recipient amount0 amount1 tick } }

Graph Node responds instantly — because it's reading from PostgreSQL, not blockchain.


⭐ 5. WHAT IS HAPPENING BEHIND THE SCENES?

This is the deep part.

✔ The Graph runs a full Ethereum node

Gets every block, tx, log, receipt.

✔ Graph Node decodes logs using ABI

Smart contract events emit logs: topics + data.

Graph Node uses ABI to decode:

topic[0] → event signature topic[1],topic[2] → indexed params data → non-indexed params

✔ Mapping handlers run inside WASM sandbox

Every event is passed into your code.

✔ Entities stored in Graph Database

Uses PostgreSQL with strong indexing.

✔ GraphQL layer sits on top of the database

Optimized for fast searchable queries.


⭐ 6. WHY SUBGRAPHS MAKE DATA FAST?

Instead of scanning chain every time:

❌ RPC nodes re-scan millions of blocks → slow
❌ Logs must be decoded repeatedly → slow
❌ You must process in backend → slow

With subgraphs:

✔ events are indexed once — forever
✔ stored in organized DB tables
✔ GraphQL queries are extremely fast
✔ filtering and pagination built-in
✔ historical data instantly accessible

This is why Uniswap, Aave, Balancer all rely on subgraphs.


⭐ 7. HOW MULTIPLE CONTRACTS ARE INDEXED TOGETHER?

You can add multiple dataSources in the subgraph:

dataSources: - UniswapPool - ERC20Token - StakingContract

Mappings can reference each other.

This allows:

✔ LP positions
✔ Reward calculations
✔ User portfolio
✔ Token prices
✔ Swap history


⭐ 8. IMPORTANT CONCEPT: ENTITY RELATIONSHIPS

GraphQL schema allows relations:

type User @entity { id: ID! swaps: [Swap!]! @derivedFrom(field: "sender") } type Swap @entity { id: ID! sender: User! amount0: BigInt! }

This creates SQL-like joins but decentralized.


⭐ 9. START BLOCK IS IMPORTANT

If you set:

startBlock: 1

Graph Node will index the entire chain → slow.

If your contract was deployed at:

block 12,345,678

Always set this:

startBlock: 12345678

Saves DAYS.


⭐ 10. FULL INTERNAL ARCHITECTURE OVERVIEW

User TxEthereum NodeLogs emitted → → Graph NodeABI decodemapping.ts (WASM)Entity saved in PostgreSQLGraphQL API

⭐ 11. Why This Replaces Querying Ethereum

Network query becomes:

GraphQL → PostgreSQL (indexed data) → instant

Instead of:

RPC → scan blocks → fetch logs → filter → slow

⭐ 12. Real Example: How Uniswap v3 Uses The Graph

You can query:

  • top pools

  • top tokens

  • swaps

  • LP fees

  • TVL

  • user positions

all within milliseconds — subgraph precomputed everything.


⭐ FINAL SUMMARY (SUPER SIMPLE)

“Subgraph = Custom blockchain database

built by converting contract events into structured entities
indexed by Graph Node, queryable with GraphQL.”  




๐Ÿ—️ Who Created The Graph?

Entity

Role

The Graph Foundation

Manages ecosystem, governance, and grants.

The Graph Council

Similar to Ethereum’s community governance — it approves changes.

Edge & Node (originally The Graph’s core development company)

Founded by Yaniv Tal, Brandon Ramirez, Jannis Pohlmann — they built the initial protocol. Now one of multiple core dev teams.

StreamingFast, Figment, Semiotic Labs, The Guild

Other core dev teams contributing now.

So:

Initially built by a company (Edge & Node).
Now an open-source, decentralized protocol governed by token holders (GRT).


✅ Step 1: What The Graph Is — Simple Summary

The Graph = Google Search Index + API Layer for Blockchain Data.

Blockchains store all data, but not optimized for searching/querying.

Example: Uniswap wants to show all swaps where WETH was traded → Ethereum can't query like that directly — you'd have to scan millions of blocks manually.

The Graph solves this:

Without The Graph

With The Graph

You write code to listen to events, parse logs, store them manually

You write a Subgraph definition once, and Graph Network auto-indexes

Your backend constantly syncs blockchain

Indexers sync for you

You serve API manually

The Graph exposes GraphQL endpoint



๐Ÿ Summary: Manual vs The Graph

Task

Manual (ethers.js)

The Graph

Fetch Live Events

✅ Easy

✅ Easy

Fetch Historical Events

❌ Hard

✅ Auto

Store Data

❌ Need your own DB

✅ Built in

Aggregate/Filter

❌ Manual code

✅ GraphQL

Decentralized Indexing

❌ Centralized

✅ Multiple Indexers




๐Ÿงฑ Layered Stack of a dApp (Example: Uniswap)

Layer

Purpose

Example Providers

Layer 1 Blockchain

Stores raw state & transactions

Ethereum

Node Providers (RPC / Execution Layer Access)

Let apps read/write raw blockchain data

Alchemy, Infura, QuickNode

Indexing / Query Layer (Structured Data Access)

Turns raw logs into filtered, queryable datasets

The Graph (Subgraphs)

Application Backend / Frontend

UI + Logic

Uniswap Frontend


๐Ÿ”„ Real Flow: How Uniswap Uses Alchemy & The Graph Together

๐Ÿ“Œ Scenario: User opens Uniswap and selects a token pair

Task

Done By

Why?

Fetch token balances, prices, pool state (real-time)

Alchemy RPC

Frontend needs live blockchain state (via eth_call, getLogs, etc.)

Show historical swaps, volume, price charts

The Graph Subgraph

These require indexed & aggregated data over time


✅ So How Does Uniswap Actually Use Both?

[ User Interface ]

        |

        | ① Live state (e.g. reserves, prices, balances)

        ↓

[ Alchemy RPC Node ]    <-- (eth_call, getReserves, block number, etc.)

        |

        | ② Historical / aggregated data (e.g. past swaps, volume history)

        ↓

[ The Graph Subgraph ]  <-- pre-indexed swap events turned into GraphQL API



๐Ÿง  Key Insight:

Alchemy gives you RAW ACCESS.
The Graph gives you ORGANIZED ACCESS.

You could get swap events directly from Alchemy using getLogs,
but you'd still need to decode, store, and format everything yourself.

The Graph does that work for you automatically.


๐Ÿงช Real Example — Uniswap Swap Page

Let’s say you visit info.uniswap.org/pair/WETH-USDC

Data Type

Source

Why

Current price

Alchemy RPC

Get live reserve ratio

24h volume, last 100 swaps

The Graph

Indexed from many blocks

Your wallet balance

Alchemy RPC

Fast direct request

Chart history

The Graph

Querying stored events

Comments

Popular posts from this blog

Frontend-to-Blockchain Flow