This article is the second part of a 3-piece series:
- The Graph and Its Contribution to dApps and Blockchain Development
- Demonstrate Subgraph Structure on 2key Subgraph “The Graph”
- One Referral Map to Rule Them (Blockchains) All — Using 2 Subgraphs on 2key dApp to generate the referral map
First, let’s jump into the — 2key Subgraphs project on Github, and clone it to a local workspace.
There are 4 important files needed for the Subgraph:
- Schema.graphql, GraphQL entities definition, such as User, Campaign, and attributes types
- The ABI of the contract, which will trigger indexing handlers
- Exported handler functions and indexing logic.
- Subgraph.yaml, basic config of the Subgraph, contract address that will emit the events, ABI, handlers, event names and entities
Schema.graphql
Collection of entities. Think of an entity as a relation in a DB.
type Rate @entity {
id: ID!
_from:String!
_to:String!
_rate: BigInt!
_maintainer: Bytes!
_timeStamp: BigInt!
_event: PriceUpdated!
}(schema.graphql at Subgraphs repo)
mapping.ts
In the subgraph.yaml, we define an event and a handler. The mapping.ts will be the place where we keep these handlers:
Each is invoked as a response for an emitted event. For the “UserRegistered” event, the following handler will be emitted:
export function handleUserRegistered(event: UserRegisteredEvent): void{
let newUser = User.load(event.params._address.toHex());
if (newUser == null){
newUser = new User(event.params._address.toHex());
newUser._timeStamp = event.block.timestamp;
}
newUser._name = event.params._name;
newUser._fullName = event.params._fullName;
newUser._walletName = event.params._username_walletName;
newUser._email = event.params._email;
newUser._updatedTimeStamp = event.block.timestamp;
newUser.save();
}(mapping.ts at Subgraphs repo)
subgraph.yaml
#it's an edited version - only with the most relevant config.
schema:
file: ./schema.graphql
dataSources:
network: ropsten
source:
address: "0x0e05fd4224e7e9b5abaaa9cfd56de91cdc95b1cc"
abi: TwoKeyEventSource
mapping:
entities:
- Campaign
- User
abis:
- name: TwoKeyEventSource
file: ./abis/TwoKeyEventSource.json
eventHandlers:
- event: UserRegistered(string,address,string,string,string)
handler: handleUserRegistered
- event: Joined(address,address,address)
handler: handleJoined
file: ./src/mapping.ts(subgraph.yaml at Subgraphs repo)
- source: what address to listen for defined events + ABI.
- entities: what are the created entities we could query upon.
- eventHandlers: name of an event and the related handler.
Follow the steps to deploy a Subgraph (TheGraph site).
After it is finished, your graph is ready to play with. Use the playground to query and explore your contracts state according to your indexing logic.
Let’s explore our schema according to our schema.graphql
The next step is to take the Query URL and fetch it from your app/dApp,
Have fun!