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:
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:
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.
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! 🔥