Indexing Data on Somnia using Graph Services
The blockchain is an ever-growing database of transactions and Smart Contract events. Developers use subgraphs, an indexing solution provided by the Graph protocol, to retrieve and analyze this data efficiently.
A graph in this context represents the structure of blockchain data, including token transfers, contract events, and user interactions. A subgraph is a customized indexing service that listens to blockchain transactions and structures them in a way that can be easily queried using GraphQL.
Prerequisites
This guide is not an introduction to Solidity Programming; you are expected to understand Basic Solidity Programming.
GraphQL is installed and set up on your local machine.
npm install -g @graphprotocol/graph-cli
Deploy a Simple ERC20 Token on Somnia
We will deploy a basic ERC20 token on the Somnia network using Hardhat. Ensure you have Hardhat, OpenZeppelin, and dotenv installed:
npm install --save-dev hardhat @nomicfoundation/hardhat-ignition-ethers @openzeppelin/contracts dotenv ethers
Create an ERC20 Token Contract
Create a new Solidity file: contracts/MyToken.sol
and update it
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MyToken is ERC20 {
constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {
_mint(msg.sender, initialSupply * 10**decimals());
}
function mint(address to, uint256 amount) external {
_mint(to, amount);
}
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
}
Create a Deployment Script
Create a new file in ignition/modules/MyTokenModule.ts
import { buildModule } from "@nomicfoundation/hardhat-ignition/modules";
export default buildModule("MyTokenModule", (m) => {
const initialSupply = m.getParameter("initialSupply", 1000000n * 10n ** 18n);
const myToken = m.contract("MyToken", [initialSupply]);
return { myToken };
});
Deploy the Smart Contract
Open the hardhat.config.js file and update the network information by adding Somnia Network to the list of networks. Copy your Wallet Address Private Key from MetaMask, and add it to the accounts section. Ensure there are enough STT Token in the Wallet Address to pay for Gas. You can get some from the Somnia Faucet.
module.exports = {
// ...
networks: {
somniaTestnet: {
url: "https://dream-rpc.somnia.network",
accounts: ["0xPRIVATE_KEY"], // put dev menomonic or PK here,
},
},
// ...
};
Open a new terminal and deploy the smart contract to the Somnia Network. Run the command:
npx hardhat ignition deploy ./ignition/modules/MyTokenModule.ts --network somniaTestnet
This will deploy the ERC20 contract to the Somnia network and return the deployed contract address.
Simulate On-Chain Activity
Once deployed, we will create a script to generate multiple transactions on the blockchain.
Create a new file scripts/interact.js
Create an .env
file to hold sensitive informations such as the private keys
SOMNIA_RPC_URL=https://dream-rpc.somnia.network
PRIVATE_KEY_1=0x...
PRIVATE_KEY_2=0x...
PRIVATE_KEY_3=0x...
PRIVATE_KEY_4=0x...
PRIVATE_KEY_5=0x...
Run the Script
node scripts/interact.js
This will generate several on-chain transactions for our subgraph to index.
Deploy a Subgraph on Somnia
Go to https://somnia.chain.love/ and connect your Wallet.
First, you need to create a private key for deploying subgraphs. To do so, please go to Somnia Protofire Service and create an Account.
You are now able to create subgraphs. Click the create button and enter the required details.
After initialising the subgraph on https://somnia.chain.love/ the next step is to create and deploy the subgraph via the terminal.
Initialize the Subgraph
graph init --contract-name MyToken --from-contract 0xYourTokenAddress --network somnia-testnet mytoken
Then, update networks.json to use Somnia’s RPC
{
"somnia-testnet": {
"network": "Somnia Testnet",
"rpc": "https://dream-rpc.somnia.network",
"startBlock": 12345678
}
}
Define the Subgraph Schema
📁 Edit schema.graphql
type Transfer @entity(immutable: true) {
id: Bytes!
from: Bytes!
to: Bytes!
value: BigInt!
blockNumber: BigInt!
blockTimestamp: BigInt!
transactionHash: Bytes!
}
Build the Subgraph
graph codegen
graph build
Deploy the Subgraph
graph deploy --node https://proxy.somnia.chain.love/graph/somnia-testnet --version-label 0.0.1 somnia-testnet/test-mytoken
--access-token=your_token_from_somnia_chain_love
Query the Subgraph
Once your subgraph is deployed and indexing blockchain data on Somnia, you can retrieve information using GraphQL queries. These queries allow you to efficiently access structured data such as token transfers, approvals, and contract interactions without having to scan the blockchain manually.
Developers can query indexed blockchain data in real time using the Graph Explorer or a GraphQL client. This enables DApps, analytics dashboards, and automated systems to interact more efficiently with blockchain events.
This section demonstrates how to write and execute GraphQL queries to fetch blockchain data indexed by the subgraph. Go to https://somnia.chain.love/graph/17
Fetch Latest Transfers
{
transfers(first: 10, orderBy: blockTimestamp, orderDirection: desc) {
id
from
to
value
blockTimestamp
transactionHash
}
}
Get Transfers by Address
{
transfers(where: { from: "0xUserWalletAddress" }) {
id
from
to
value
}
}
Get Transfers in a Time Range
{
transfers(where: { blockTimestamp_gte: "1700000000", blockTimestamp_lte: "1710000000" }) {
id
from
to
value
}
}
Conclusion
This tutorial provides a complete pipeline for indexing blockchain data on Somnia using The Graph! 🔥
Last updated